text
stringlengths
128
100k
source
stringlengths
31
152
Computer programming or coding is the composition of sequences of instructions, called programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of procedures, by writing code in one or more programming languages. Programmers typically use high-level programming languages that are more easily intelligible to humans than machine code, which is directly executed by the central processing unit. Proficient programming usually requires expertise in several different subjects, including knowledge of the application domain, details of programming languages and generic code libraries, specialized algorithms, and formal logic. Auxiliary tasks accompanying and related to programming include analyzing requirements, testing, debugging (investigating and fixing problems), implementation of build systems, and management of derived artifacts, such as programs' machine code. While these are sometimes considered programming, often the term software development is used for this larger overall process – with the terms programming, implementation, and coding reserved for the writing and editing of code per se. Sometimes software development is known as software engineering, especially when it employs formal methods or follows an engineering design process. == History == Programmable devices have existed for centuries. As early as the 9th century, a programmable music sequencer was invented by the Persian Banu Musa brothers, who described an automated mechanical flute player in the Book of Ingenious Devices. In 1206, the Arab engineer Al-Jazari invented a programmable drum machine where a musical mechanical automaton could be made to play different rhythms and drum patterns, via pegs and cams. In 1801, the Jacquard loom could produce entirely different weaves by changing the "program" – a series of pasteboard cards with holes punched in them. Code-breaking algorithms have also existed for centuries. In the 9th century, the Arab mathematician Al-Kindi described a cryptographic algorithm for deciphering encrypted code, in A Manuscript on Deciphering Cryptographic Messages. He gave the first description of cryptanalysis by frequency analysis, the earliest code-breaking algorithm. The first computer program is generally dated to 1843 when mathematician Ada Lovelace published an algorithm to calculate a sequence of Bernoulli numbers, intended to be carried out by Charles Babbage's Analytical Engine. The algorithm, which was conveyed through notes on a translation of Luigi Federico Menabrea's paper on the analytical engine was mainly conceived by Lovelace as can be discerned through her correspondence with Babbage. However, Charles Babbage himself had written a program for the AE in 1837. Lovelace was also the first to see a broader application for the analytical engine beyond mathematical calculations. In the 1880s, Herman Hollerith invented the concept of storing data in machine-readable form. Later a control panel (plug board) added to his 1906 Type I Tabulator allowed it to be programmed for different jobs, and by the late 1940s, unit record equipment such as the IBM 602 and IBM 604, were programmed by control panels in a similar way, as were the first electronic computers. However, with the concept of the stored-program computer introduced in 1949, both programs and data were stored and manipulated in the same way in computer memory. === Machine language === Machine code was the language of early programs, written in the instruction set of the particular machine, often in binary notation. Assembly languages were soon developed that let the programmer specify instructions in a text format (e.g., ADD X, TOTAL), with abbreviations for each operation code and meaningful names for specifying addresses. However, because an assembly language is little more than a different notation for a machine language, two machines with different instruction sets also have different assembly languages. === Compiler languages === High-level languages made the process of developing a program simpler and more understandable, and less bound to the underlying hardware. The first compiler related tool, the A-0 System, was developed in 1952 by Grace Hopper, who also coined the term 'compiler'. FORTRAN, the first widely used high-level language to have a functional implementation, came out in 1957, and many other languages were soon developed—in particular, COBOL aimed at commercial data processing, and Lisp for computer research. These compiled languages allow the programmer to write programs in terms that are syntactically richer, and more capable of abstracting the code, making it easy to target varying machine instruction sets via compilation declarations and heuristics. Compilers harnessed the power of computers to make programming easier by allowing programmers to specify calculations by entering a formula using infix notation. === Source code entry === Programs were mostly entered using punched cards or paper tape. By the late 1960s, data storage devices and computer terminals became inexpensive enough that programs could be created by typing directly into the computers. Text editors were also developed that allowed changes and corrections to be made much more easily than with punched cards. == Modern programming == === Quality requirements === Whatever the approach to development may be, the final program must satisfy some fundamental properties. The following properties are among the most important: Reliability: how often the results of a program are correct. This depends on conceptual correctness of algorithms and minimization of programming mistakes, such as mistakes in resource management (e.g., buffer overflows and race conditions) and logic errors (such as division by zero or off-by-one errors). Robustness: how well a program anticipates problems due to errors (not bugs). This includes situations such as incorrect, inappropriate or corrupt data, unavailability of needed resources such as memory, operating system services, and network connections, user error, and unexpected power outages. Usability: the ergonomics of a program: the ease with which a person can use the program for its intended purpose or in some cases even unanticipated purposes. Such issues can make or break its success even regardless of other issues. This involves a wide range of textual, graphical, and sometimes hardware elements that improve the clarity, intuitiveness, cohesiveness, and completeness of a program's user interface. Portability: the range of computer hardware and operating system platforms on which the source code of a program can be compiled/interpreted and run. This depends on differences in the programming facilities provided by the different platforms, including hardware and operating system resources, expected behavior of the hardware and operating system, and availability of platform-specific compilers (and sometimes libraries) for the language of the source code. Maintainability: the ease with which a program can be modified by its present or future developers in order to make improvements or to customize, fix bugs and security holes, or adapt it to new environments. Good practices during initial development make the difference in this regard. This quality may not be directly apparent to the end user but it can significantly affect the fate of a program over the long term. Efficiency/performance: Measure of system resources a program consumes (processor time, memory space, slow devices such as disks, network bandwidth and to some extent even user interaction): the less, the better. This also includes careful management of resources, for example cleaning up temporary files and eliminating memory leaks. This is often discussed under the shadow of a chosen programming language. Although the language certainly affects performance, even slower languages, such as Python, can execute programs instantly from a human perspective. Speed, resource usage, and performance are important for programs that bottleneck the system, but efficient use of programmer time is also important and is related to cost: more hardware may be cheaper. Using automated tests and fitness functions can help to maintain some of the aforementioned attributes. === Readability of source code === In computer programming, readability refers to the ease with which a human reader can comprehend the purpose, control flow, and operation of source code. It affects the aspects of quality above, including portability, usability and most importantly maintainability. Readability is important because programmers spend the majority of their time reading, trying to understand, reusing, and modifying existing source code, rather than writing new source code. Unreadable code often leads to bugs, inefficiencies, and duplicated code. A study found that a few simple readability transformations made code shorter and drastically reduced the time to understand it. Following a consistent programming style often helps readability. However, readability is more than just programming style. Many factors, having little or nothing to do with the ability of the computer to efficiently compile and execute the code, contribute to readability. Some of these factors include: Different indent styles (whitespace) Comments Decomposition Naming conventions for objects (such as variables, classes, functions, procedures, etc.) The presentation aspects of this (such as indents, line breaks, color highlighting, and so on) are often handled by the source code editor, but the content aspects reflect the programmer's talent and skills. Various visual programming languages have also been developed with the intent to resolve readability concerns by adopting non-traditional approaches to code structure and display. Integrated development environments (IDEs) aim to integrate all such help. Techniques like Code refactoring can enhance readability. === Algorithmic complexity === The academic field and the engineering practice of computer programming are concerned with discovering and implementing the most efficient algorithms for a given class of problems. For this purpose, algorithms are classified into orders using Big O notation, which expresses resource use—such as execution time or memory consumption—in terms of the size of an input. Expert programmers are familiar with a variety of well-established algorithms and their respective complexities and use this knowledge to choose algorithms that are best suited to the circumstances. === Methodologies === The first step in most formal software development processes is requirements analysis, followed by testing to determine value modeling, implementation, and failure elimination (debugging). There exist a lot of different approaches for each of those tasks. One approach popular for requirements analysis is Use Case analysis. Many programmers use forms of Agile software development where the various stages of formal software development are more integrated together into short cycles that take a few weeks rather than years. There are many approaches to the Software development process. Popular modeling techniques include Object-Oriented Analysis and Design (OOAD) and Model-Driven Architecture (MDA). The Unified Modeling Language (UML) is a notation used for both the OOAD and MDA. A similar technique used for database design is Entity-Relationship Modeling (ER Modeling). Implementation techniques include imperative languages (object-oriented or procedural), functional languages, and logic programming languages. === Measuring language usage === It is very difficult to determine what are the most popular modern programming languages. Methods of measuring programming language popularity include: counting the number of job advertisements that mention the language, the number of books sold and courses teaching the language (this overestimates the importance of newer languages), and estimates of the number of existing lines of code written in the language (this underestimates the number of users of business languages such as COBOL). Some languages are very popular for particular kinds of applications, while some languages are regularly used to write many different kinds of applications. For example, COBOL is still strong in corporate data centers often on large mainframe computers, Fortran in engineering applications, scripting languages in Web development, and C in embedded software. Many applications use a mix of several languages in their construction and use. New languages are generally designed around the syntax of a prior language with new functionality added, (for example C++ adds object-orientation to C, and Java adds memory management and bytecode to C++, but as a result, loses efficiency and the ability for low-level manipulation). === Debugging === Debugging is a very important task in the software development process since having defects in a program can have significant consequences for its users. Some languages are more prone to some kinds of faults because their specification does not require compilers to perform as much checking as other languages. Use of a static code analysis tool can help detect some possible problems. Normally the first step in debugging is to attempt to reproduce the problem. This can be a non-trivial task, for example as with parallel processes or some unusual software bugs. Also, specific user environment and usage history can make it difficult to reproduce the problem. After the bug is reproduced, the input of the program may need to be simplified to make it easier to debug. For example, when a bug in a compiler can make it crash when parsing some large source file, a simplification of the test case that results in only few lines from the original source file can be sufficient to reproduce the same crash. Trial-and-error/divide-and-conquer is needed: the programmer will try to remove some parts of the original test case and check if the problem still exists. When debugging the problem in a GUI, the programmer can try to skip some user interaction from the original problem description and check if the remaining actions are sufficient for bugs to appear. Scripting and breakpointing are also part of this process. Debugging is often done with IDEs. Standalone debuggers like GDB are also used, and these often provide less of a visual environment, usually using a command line. Some text editors such as Emacs allow GDB to be invoked through them, to provide a visual environment. == Programming languages == Different programming languages support different styles of programming (called programming paradigms). The choice of language used is subject to many considerations, such as company policy, suitability to task, availability of third-party packages, or individual preference. Ideally, the programming language best suited for the task at hand will be selected. Trade-offs from this ideal involve finding enough programmers who know the language to build a team, the availability of compilers for that language, and the efficiency with which programs written in a given language execute. Languages form an approximate spectrum from "low-level" to "high-level"; "low-level" languages are typically more machine-oriented and faster to execute, whereas "high-level" languages are more abstract and easier to use but execute less quickly. It is usually easier to code in "high-level" languages than in "low-level" ones. Programming languages are essential for software development. They are the building blocks for all software, from the simplest applications to the most sophisticated ones. Allen Downey, in his book How To Think Like A Computer Scientist, writes: The details look different in different languages, but a few basic instructions appear in just about every language: Input: Gather data from the keyboard, a file, or some other device. Output: Display data on the screen or send data to a file or other device. Arithmetic: Perform basic arithmetical operations like addition and multiplication. Conditional Execution: Check for certain conditions and execute the appropriate sequence of statements. Repetition: Perform some action repeatedly, usually with some variation. Many computer languages provide a mechanism to call functions provided by shared libraries. Provided the functions in a library follow the appropriate run-time conventions (e.g., method of passing arguments), then these functions may be written in any other language. == Learning to program == Learning to program has a long history related to professional standards and practices, academic initiatives and curriculum, and commercial books and materials for students, self-taught learners, hobbyists, and others who desire to create or customize software for personal use. Since the 1960s, learning to program has taken on the characteristics of a popular movement, with the rise of academic disciplines, inspirational leaders, collective identities, and strategies to grow the movement and make institutionalize change. Through these social ideals and educational agendas, learning to code has become important not just for scientists and engineers, but for millions of citizens who have come to believe that creating software is beneficial to society and its members. === Context === In 1957, there were approximately 15,000 computer programmers employed in the U.S., a figure that accounts for 80% of the world's active developers. In 2014, there were approximately 18.5 million professional programmers in the world, of which 11 million can be considered professional and 7.5 million student or hobbyists. Before the rise of the commercial Internet in the mid-1990s, most programmers learned about software construction through books, magazines, user groups, and informal instruction methods, with academic coursework and corporate training playing important roles for professional workers. The first book containing specific instructions about how to program a computer may have been Maurice Wilkes, David Wheeler, and Stanley Gill's Preparation of Programs for an Electronic Digital Computer (1951). The book offered a selection of common subroutines for handling basic operations on the EDSAC, one of the world's first stored-program computers. When high-level languages arrived, they were introduced by numerous books and materials that explained language keywords, managing program flow, working with data, and other concepts. These languages included FLOW-MATIC, COBOL, FORTRAN, ALGOL, Pascal, BASIC, and C. An example of an early programming primer from these years is Marshal H. Wrubel's A Primer of Programming for Digital Computers (1959), which included step-by-step instructions for filling out coding sheets, creating punched cards, and using the keywords in IBM's early FORTRAN system. Daniel McCracken's A Guide to FORTRAN Programming (1961) presented FORTRAN to a larger audience, including students and office workers. In 1961, Alan Perlis suggested that all university freshmen at Carnegie Technical Institute take a course in computer programming. His advice was published in the popular technical journal Computers and Automation, which became a regular source of information for professional programmers. Programmers soon had a range of learning texts at their disposal. Programmer's references listed keywords and functions related to a language, often in alphabetical order, as well as technical information about compilers and related systems. An early example was IBM's Programmers' Reference Manual: the FORTRAN Automatic Coding System for the IBM 704 EDPM (1956). Over time, the genre of programmer's guides emerged, which presented the features of a language in tutorial or step by step format. Many early primers started with a program known as “Hello, World”, which presented the shortest program a developer could create in a given system. Programmer's guides then went on to discuss core topics like declaring variables, data types, formulas, flow control, user-defined functions, manipulating data, and other topics. Early and influential programmer's guides included John G. Kemeny and Thomas E. Kurtz's BASIC Programming (1967), Kathleen Jensen and Niklaus Wirth's The Pascal User Manual and Report (1971), and Brian W. Kernighan and Dennis Ritchie's The C Programming Language (1978). Similar books for popular audiences (but with a much lighter tone) included Bob Albrecht's My Computer Loves Me When I Speak BASIC (1972), Al Kelley and Ira Pohl's A Book on C (1984), and Dan Gookin's C for Dummies (1994). Beyond language-specific primers, there were numerous books and academic journals that introduced professional programming practices. Many were designed for university courses in computer science, software engineering, or related disciplines. Donald Knuth's The Art of Computer Programming (1968 and later), presented hundreds of computational algorithms and their analysis. The Elements of Programming Style (1974), by Brian W. Kernighan and P. J. Plauger, concerned itself with programming style, the idea that programs should be written not only to satisfy the compiler but human readers. Jon Bentley's Programming Pearls (1986) offered practical advice about the art and craft of programming in professional and academic contexts. Texts specifically designed for students included Doug Cooper and Michael Clancy's Oh Pascal! (1982), Alfred Aho's Data Structures and Algorithms (1983), and Daniel Watt's Learning with Logo (1983). === Technical publishers === As personal computers became mass-market products, thousands of trade books and magazines sought to teach professional, hobbyist, and casual users to write computer programs. A sample of these learning resources includes BASIC Computer Games, Microcomputer Edition (1978), by David Ahl; Programming the Z80 (1979), by Rodnay Zaks; Programmer's CP/M Handbook (1983), by Andy Johnson-Laird; C Primer Plus (1984), by Mitchell Waite and The Waite Group; The Peter Norton Programmer's Guide to the IBM PC (1985), by Peter Norton; Advanced MS-DOS (1986), by Ray Duncan; Learn BASIC Now (1989), by Michael Halvorson and David Rygymr; Programming Windows (1992 and later), by Charles Petzold; Code Complete: A Practical Handbook for Software Construction (1993), by Steve McConnell; and Tricks of the Game-Programming Gurus (1994), by André LaMothe. The PC software industry spurred the creation of numerous book publishers that offered programming primers and tutorials, as well as books for advanced software developers. These publishers included Addison-Wesley, IDG, Macmillan Inc., McGraw-Hill, Microsoft Press, O'Reilly Media, Prentice Hall, Sybex, Ventana Press, Waite Group Press, Wiley, Wrox Press, and Ziff-Davis. Computer magazines and journals also provided learning content for professional and hobbyist programmers. A partial list of these resources includes Amiga World, Byte (magazine), Communications of the ACM, Computer (magazine), Compute!, Computer Language (magazine), Computers and Electronics, Dr. Dobb's Journal, IEEE Software, Macworld, PC Magazine, PC/Computing, and UnixWorld. === Digital learning / online resources === Between 2000 and 2010, computer book and magazine publishers declined significantly as providers of programming instruction, as programmers moved to Internet resources to expand their access to information. This shift brought forward new digital products and mechanisms to learn programming skills. During the transition, digital books from publishers transferred information that had traditionally been delivered in print to new and expanding audiences. Important Internet resources for learning to code included blogs, wikis, videos, online databases, subscription sites, and custom websites focused on coding skills. New commercial resources included YouTube videos, Lynda.com tutorials (later LinkedIn Learning), Khan Academy, Codecademy, GitHub, W3Schools, and numerous coding bootcamps. Most software development systems and game engines included rich online help resources, including integrated development environments (IDEs), context-sensitive help, APIs, and other digital resources. Commercial software development kits (SDKs) also provided a collection of software development tools and documentation in one installable package. Commercial and non-profit organizations published learning websites for developers, created blogs, and established newsfeeds and social media resources about programming. Corporations like Apple, Microsoft, Oracle, Google, and Amazon built corporate websites providing support for programmers, including resources like the Microsoft Developer Network (MSDN). Contemporary movements like Hour of Code (Code.org) show how learning to program has become associated with digital learning strategies, education agendas, and corporate philanthropy. == Programmers == Computer programmers are those who write computer software. Their jobs usually involve: Although programming has been presented in the media as a somewhat mathematical subject, some research shows that good programmers have strong skills in natural human languages, and that learning to code is similar to learning a foreign language. == See also == Code smell Computer networking Competitive programming Programming best practices Systems programming == References == === Sources === Ceruzzi, Paul E. (1998). History of Computing. Cambridge, Massachusetts: MIT Press. ISBN 9780262032551 – via EBSCOhost. Evans, Claire L. (2018). Broad Band: The Untold Story of the Women Who Made the Internet. New York: Portfolio/Penguin. ISBN 9780735211759. Gürer, Denise (1995). "Pioneering Women in Computer Science" (PDF). Communications of the ACM. 38 (1): 45–54. doi:10.1145/204865.204875. S2CID 6626310. Archived (PDF) from the original on October 9, 2022. Smith, Erika E. (2013). "Recognizing a Collective Inheritance through the History of Women in Computing". CLCWeb: Comparative Literature & Culture. 15 (1): 1–9. doi:10.7771/1481-4374.1972. Essinger, J., & EBSCO Publishing (Firm). (2014). Ada's algorithm: How lord byron's daughter ada lovelace launched the digital age. Melville House. == Further reading == A.K. Hartmann, Practical Guide to Computer Simulations, Singapore: World Scientific (2009) A. Hunt, D. Thomas, and W. Cunningham, The Pragmatic Programmer. From Journeyman to Master, Amsterdam: Addison-Wesley Longman (1999) Brian W. Kernighan, The Practice of Programming, Pearson (1999) Weinberg, Gerald M., The Psychology of Computer Programming, New York: Van Nostrand Reinhold (1971) Edsger W. Dijkstra, A Discipline of Programming, Prentice-Hall (1976) O.-J. Dahl, E.W.Dijkstra, C.A.R. Hoare, Structured Programming, Academic Press (1972) David Gries, The Science of Programming, Springer-Verlag (1981) == External links == Media related to Computer programming at Wikimedia Commons Quotations related to Programming at Wikiquote
https://en.wikipedia.org/wiki/Computer_programming
A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their syntax (form) and semantics (meaning), usually defined by a formal language. Languages usually provide features such as a type system, variables, and mechanisms for error handling. An implementation of a programming language is required in order to execute programs, namely an interpreter or a compiler. An interpreter directly executes the source code, while a compiler produces an executable program. Computer architecture has strongly influenced the design of programming languages, with the most common type (imperative languages—which implement operations in a specified order) developed to perform well on the popular von Neumann architecture. While early programming languages were closely tied to the hardware, over time they have developed more abstraction to hide implementation details for greater simplicity. Thousands of programming languages—often classified as imperative, functional, logic, or object-oriented—have been developed for a wide variety of uses. Many aspects of programming language design involve tradeoffs—for example, exception handling simplifies error handling, but at a performance cost. Programming language theory is the subfield of computer science that studies the design, implementation, analysis, characterization, and classification of programming languages. == Definitions == Programming languages differ from natural languages in that natural languages are used for interaction between people, while programming languages are designed to allow humans to communicate instructions to machines. The term computer language is sometimes used interchangeably with "programming language". However, usage of these terms varies among authors. In one usage, programming languages are described as a subset of computer languages. Similarly, the term "computer language" may be used in contrast to the term "programming language" to describe languages used in computing but not considered programming languages. Most practical programming languages are Turing complete, and as such are equivalent in what programs they can compute. Another usage regards programming languages as theoretical constructs for programming abstract machines and computer languages as the subset thereof that runs on physical computers, which have finite hardware resources. John C. Reynolds emphasizes that formal specification languages are just as much programming languages as are the languages intended for execution. He also argues that textual and even graphical input formats that affect the behavior of a computer are programming languages, despite the fact they are commonly not Turing-complete, and remarks that ignorance of programming language concepts is the reason for many flaws in input formats. == History == === Early developments === The first programmable computers were invented at the end of the 1940s, and with them, the first programming languages. The earliest computers were programmed in first-generation programming languages (1GLs), machine language (simple instructions that could be directly executed by the processor). This code was very difficult to debug and was not portable between different computer systems. In order to improve the ease of programming, assembly languages (or second-generation programming languages—2GLs) were invented, diverging from the machine language to make programs easier to understand for humans, although they did not increase portability. Initially, hardware resources were scarce and expensive, while human resources were cheaper. Therefore, cumbersome languages that were time-consuming to use, but were closer to the hardware for higher efficiency were favored. The introduction of high-level programming languages (third-generation programming languages—3GLs)—revolutionized programming. These languages abstracted away the details of the hardware, instead being designed to express algorithms that could be understood more easily by humans. For example, arithmetic expressions could now be written in symbolic notation and later translated into machine code that the hardware could execute. In 1957, Fortran (FORmula TRANslation) was invented. Often considered the first compiled high-level programming language, Fortran has remained in use into the twenty-first century. === 1960s and 1970s === Around 1960, the first mainframes—general purpose computers—were developed, although they could only be operated by professionals and the cost was extreme. The data and instructions were input by punch cards, meaning that no input could be added while the program was running. The languages developed at this time therefore are designed for minimal interaction. After the invention of the microprocessor, computers in the 1970s became dramatically cheaper. New computers also allowed more user interaction, which was supported by newer programming languages. Lisp, implemented in 1958, was the first functional programming language. Unlike Fortran, it supported recursion and conditional expressions, and it also introduced dynamic memory management on a heap and automatic garbage collection. For the next decades, Lisp dominated artificial intelligence applications. In 1978, another functional language, ML, introduced inferred types and polymorphic parameters. After ALGOL (ALGOrithmic Language) was released in 1958 and 1960, it became the standard in computing literature for describing algorithms. Although its commercial success was limited, most popular imperative languages—including C, Pascal, Ada, C++, Java, and C#—are directly or indirectly descended from ALGOL 60. Among its innovations adopted by later programming languages included greater portability and the first use of context-free, BNF grammar. Simula, the first language to support object-oriented programming (including subtypes, dynamic dispatch, and inheritance), also descends from ALGOL and achieved commercial success. C, another ALGOL descendant, has sustained popularity into the twenty-first century. C allows access to lower-level machine operations more than other contemporary languages. Its power and efficiency, generated in part with flexible pointer operations, comes at the cost of making it more difficult to write correct code. Prolog, designed in 1972, was the first logic programming language, communicating with a computer using formal logic notation. With logic programming, the programmer specifies a desired result and allows the interpreter to decide how to achieve it. === 1980s to 2000s === During the 1980s, the invention of the personal computer transformed the roles for which programming languages were used. New languages introduced in the 1980s included C++, a superset of C that can compile C programs but also supports classes and inheritance. Ada and other new languages introduced support for concurrency. The Japanese government invested heavily into the so-called fifth-generation languages that added support for concurrency to logic programming constructs, but these languages were outperformed by other concurrency-supporting languages. Due to the rapid growth of the Internet and the World Wide Web in the 1990s, new programming languages were introduced to support Web pages and networking. Java, based on C++ and designed for increased portability across systems and security, enjoyed large-scale success because these features are essential for many Internet applications. Another development was that of dynamically typed scripting languages—Python, JavaScript, PHP, and Ruby—designed to quickly produce small programs that coordinate existing applications. Due to their integration with HTML, they have also been used for building web pages hosted on servers. === 2000s to present === During the 2000s, there was a slowdown in the development of new programming languages that achieved widespread popularity. One innovation was service-oriented programming, designed to exploit distributed systems whose components are connected by a network. Services are similar to objects in object-oriented programming, but run on a separate process. C# and F# cross-pollinated ideas between imperative and functional programming. After 2010, several new languages—Rust, Go, Swift, Zig and Carbon —competed for the performance-critical software for which C had historically been used. Most of the new programming languages use static typing while a few numbers of new languages use dynamic typing like Ring and Julia. Some of the new programming languages are classified as visual programming languages like Scratch, LabVIEW and PWCT. Also, some of these languages mix between textual and visual programming usage like Ballerina. Also, this trend lead to developing projects that help in developing new VPLs like Blockly by Google. Many game engines like Unreal and Unity added support for visual scripting too. == Elements == Every programming language includes fundamental elements for describing data and the operations or transformations applied to them, such as adding two numbers or selecting an item from a collection. These elements are governed by syntactic and semantic rules that define their structure and meaning, respectively. === Syntax === A programming language's surface form is known as its syntax. Most programming languages are purely textual; they use sequences of text including words, numbers, and punctuation, much like written natural languages. On the other hand, some programming languages are graphical, using visual relationships between symbols to specify a program. The syntax of a language describes the possible combinations of symbols that form a syntactically correct program. The meaning given to a combination of symbols is handled by semantics (either formal or hard-coded in a reference implementation). Since most languages are textual, this article discusses textual syntax. The programming language syntax is usually defined using a combination of regular expressions (for lexical structure) and Backus–Naur form (for grammatical structure). Below is a simple grammar, based on Lisp: This grammar specifies the following: an expression is either an atom or a list; an atom is either a number or a symbol; a number is an unbroken sequence of one or more decimal digits, optionally preceded by a plus or minus sign; a symbol is a letter followed by zero or more of any alphabetical characters (excluding whitespace); and a list is a matched pair of parentheses, with zero or more expressions inside it. The following are examples of well-formed token sequences in this grammar: 12345, () and (a b c232 (1)). Not all syntactically correct programs are semantically correct. Many syntactically correct programs are nonetheless ill-formed, per the language's rules; and may (depending on the language specification and the soundness of the implementation) result in an error on translation or execution. In some cases, such programs may exhibit undefined behavior. Even when a program is well-defined within a language, it may still have a meaning that is not intended by the person who wrote it. Using natural language as an example, it may not be possible to assign a meaning to a grammatically correct sentence or the sentence may be false: "Colorless green ideas sleep furiously." is grammatically well-formed but has no generally accepted meaning. "John is a married bachelor." is grammatically well-formed but expresses a meaning that cannot be true. The following C language fragment is syntactically correct, but performs operations that are not semantically defined (the operation *p >> 4 has no meaning for a value having a complex type and p->im is not defined because the value of p is the null pointer): If the type declaration on the first line were omitted, the program would trigger an error on the undefined variable p during compilation. However, the program would still be syntactically correct since type declarations provide only semantic information. The grammar needed to specify a programming language can be classified by its position in the Chomsky hierarchy. The syntax of most programming languages can be specified using a Type-2 grammar, i.e., they are context-free grammars. Some languages, including Perl and Lisp, contain constructs that allow execution during the parsing phase. Languages that have constructs that allow the programmer to alter the behavior of the parser make syntax analysis an undecidable problem, and generally blur the distinction between parsing and execution. In contrast to Lisp's macro system and Perl's BEGIN blocks, which may contain general computations, C macros are merely string replacements and do not require code execution. === Semantics === The term semantics refers to the meaning of languages, as opposed to their form (syntax). ==== Static semantics ==== Static semantics defines restrictions on the structure of valid texts that are hard or impossible to express in standard syntactic formalisms. For compiled languages, static semantics essentially include those semantic rules that can be checked at compile time. Examples include checking that every identifier is declared before it is used (in languages that require such declarations) or that the labels on the arms of a case statement are distinct. Many important restrictions of this type, like checking that identifiers are used in the appropriate context (e.g. not adding an integer to a function name), or that subroutine calls have the appropriate number and type of arguments, can be enforced by defining them as rules in a logic called a type system. Other forms of static analyses like data flow analysis may also be part of static semantics. Programming languages such as Java and C# have definite assignment analysis, a form of data flow analysis, as part of their respective static semantics. ==== Dynamic semantics ==== Once data has been specified, the machine must be instructed to perform operations on the data. For example, the semantics may define the strategy by which expressions are evaluated to values, or the manner in which control structures conditionally execute statements. The dynamic semantics (also known as execution semantics) of a language defines how and when the various constructs of a language should produce a program behavior. There are many ways of defining execution semantics. Natural language is often used to specify the execution semantics of languages commonly used in practice. A significant amount of academic research goes into formal semantics of programming languages, which allows execution semantics to be specified in a formal manner. Results from this field of research have seen limited application to programming language design and implementation outside academia. === Type system === A data type is a set of allowable values and operations that can be performed on these values. Each programming language's type system defines which data types exist, the type of an expression, and how type equivalence and type compatibility function in the language. According to type theory, a language is fully typed if the specification of every operation defines types of data to which the operation is applicable. In contrast, an untyped language, such as most assembly languages, allows any operation to be performed on any data, generally sequences of bits of various lengths. In practice, while few languages are fully typed, most offer a degree of typing. Because different types (such as integers and floats) represent values differently, unexpected results will occur if one type is used when another is expected. Type checking will flag this error, usually at compile time (runtime type checking is more costly). With strong typing, type errors can always be detected unless variables are explicitly cast to a different type. Weak typing occurs when languages allow implicit casting—for example, to enable operations between variables of different types without the programmer making an explicit type conversion. The more cases in which this type coercion is allowed, the fewer type errors can be detected. ==== Commonly supported types ==== Early programming languages often supported only built-in, numeric types such as the integer (signed and unsigned) and floating point (to support operations on real numbers that are not integers). Most programming languages support multiple sizes of floats (often called float and double) and integers depending on the size and precision required by the programmer. Storing an integer in a type that is too small to represent it leads to integer overflow. The most common way of representing negative numbers with signed types is twos complement, although ones complement is also used. Other common types include Boolean—which is either true or false—and character—traditionally one byte, sufficient to represent all ASCII characters. Arrays are a data type whose elements, in many languages, must consist of a single type of fixed length. Other languages define arrays as references to data stored elsewhere and support elements of varying types. Depending on the programming language, sequences of multiple characters, called strings, may be supported as arrays of characters or their own primitive type. Strings may be of fixed or variable length, which enables greater flexibility at the cost of increased storage space and more complexity. Other data types that may be supported include lists, associative (unordered) arrays accessed via keys, records in which data is mapped to names in an ordered structure, and tuples—similar to records but without names for data fields. Pointers store memory addresses, typically referencing locations on the heap where other data is stored. The simplest user-defined type is an ordinal type, often called an enumeration, whose values can be mapped onto the set of positive integers. Since the mid-1980s, most programming languages also support abstract data types, in which the representation of the data and operations are hidden from the user, who can only access an interface. The benefits of data abstraction can include increased reliability, reduced complexity, less potential for name collision, and allowing the underlying data structure to be changed without the client needing to alter its code. ==== Static and dynamic typing ==== In static typing, all expressions have their types determined before a program executes, typically at compile-time. Most widely used, statically typed programming languages require the types of variables to be specified explicitly. In some languages, types are implicit; one form of this is when the compiler can infer types based on context. The downside of implicit typing is the potential for errors to go undetected. Complete type inference has traditionally been associated with functional languages such as Haskell and ML. With dynamic typing, the type is not attached to the variable but only the value encoded in it. A single variable can be reused for a value of a different type. Although this provides more flexibility to the programmer, it is at the cost of lower reliability and less ability for the programming language to check for errors. Some languages allow variables of a union type to which any type of value can be assigned, in an exception to their usual static typing rules. === Concurrency === In computing, multiple instructions can be executed simultaneously. Many programming languages support instruction-level and subprogram-level concurrency. By the twenty-first century, additional processing power on computers was increasingly coming from the use of additional processors, which requires programmers to design software that makes use of multiple processors simultaneously to achieve improved performance. Interpreted languages such as Python and Ruby do not support the concurrent use of multiple processors. Other programming languages do support managing data shared between different threads by controlling the order of execution of key instructions via the use of semaphores, controlling access to shared data via monitor, or enabling message passing between threads. === Exception handling === Many programming languages include exception handlers, a section of code triggered by runtime errors that can deal with them in two main ways: Termination: shutting down and handing over control to the operating system. This option is considered the simplest. Resumption: resuming the program near where the exception occurred. This can trigger a repeat of the exception, unless the exception handler is able to modify values to prevent the exception from reoccurring. Some programming languages support dedicating a block of code to run regardless of whether an exception occurs before the code is reached; this is called finalization. There is a tradeoff between increased ability to handle exceptions and reduced performance. For example, even though array index errors are common C does not check them for performance reasons. Although programmers can write code to catch user-defined exceptions, this can clutter a program. Standard libraries in some languages, such as C, use their return values to indicate an exception. Some languages and their compilers have the option of turning on and off error handling capability, either temporarily or permanently. == Design and implementation == One of the most important influences on programming language design has been computer architecture. Imperative languages, the most commonly used type, were designed to perform well on von Neumann architecture, the most common computer architecture. In von Neumann architecture, the memory stores both data and instructions, while the CPU that performs instructions on data is separate, and data must be piped back and forth to the CPU. The central elements in these languages are variables, assignment, and iteration, which is more efficient than recursion on these machines. Many programming languages have been designed from scratch, altered to meet new needs, and combined with other languages. Many have eventually fallen into disuse. The birth of programming languages in the 1950s was stimulated by the desire to make a universal programming language suitable for all machines and uses, avoiding the need to write code for different computers. By the early 1960s, the idea of a universal language was rejected due to the differing requirements of the variety of purposes for which code was written. === Tradeoffs === Desirable qualities of programming languages include readability, writability, and reliability. These features can reduce the cost of training programmers in a language, the amount of time needed to write and maintain programs in the language, the cost of compiling the code, and increase runtime performance. Although early programming languages often prioritized efficiency over readability, the latter has grown in importance since the 1970s. Having multiple operations to achieve the same result can be detrimental to readability, as is overloading operators, so that the same operator can have multiple meanings. Another feature important to readability is orthogonality, limiting the number of constructs that a programmer has to learn. A syntax structure that is easily understood and special words that are immediately obvious also supports readability. Writability is the ease of use for writing code to solve the desired problem. Along with the same features essential for readability, abstraction—interfaces that enable hiding details from the client—and expressivity—enabling more concise programs—additionally help the programmer write code. The earliest programming languages were tied very closely to the underlying hardware of the computer, but over time support for abstraction has increased, allowing programmers express ideas that are more remote from simple translation into underlying hardware instructions. Because programmers are less tied to the complexity of the computer, their programs can do more computing with less effort from the programmer. Most programming languages come with a standard library of commonly used functions. Reliability means that a program performs as specified in a wide range of circumstances. Type checking, exception handling, and restricted aliasing (multiple variable names accessing the same region of memory) all can improve a program's reliability. Programming language design often involves tradeoffs. For example, features to improve reliability typically come at the cost of performance. Increased expressivity due to a large number of operators makes writing code easier but comes at the cost of readability. Natural-language programming has been proposed as a way to eliminate the need for a specialized language for programming. However, this goal remains distant and its benefits are open to debate. Edsger W. Dijkstra took the position that the use of a formal language is essential to prevent the introduction of meaningless constructs. Alan Perlis was similarly dismissive of the idea. === Specification === The specification of a programming language is an artifact that the language users and the implementors can use to agree upon whether a piece of source code is a valid program in that language, and if so what its behavior shall be. A programming language specification can take several forms, including the following: An explicit definition of the syntax, static semantics, and execution semantics of the language. While syntax is commonly specified using a formal grammar, semantic definitions may be written in natural language (e.g., as in the C language), or a formal semantics (e.g., as in Standard ML and Scheme specifications). A description of the behavior of a translator for the language (e.g., the C++ and Fortran specifications). The syntax and semantics of the language have to be inferred from this description, which may be written in natural or formal language. A reference or model implementation, sometimes written in the language being specified (e.g., Prolog or ANSI REXX). The syntax and semantics of the language are explicit in the behavior of the reference implementation. === Implementation === An implementation of a programming language is the conversion of a program into machine code that can be executed by the hardware. The machine code then can be executed with the help of the operating system. The most common form of interpretation in production code is by a compiler, which translates the source code via an intermediate-level language into machine code, known as an executable. Once the program is compiled, it will run more quickly than with other implementation methods. Some compilers are able to provide further optimization to reduce memory or computation usage when the executable runs, but increasing compilation time. Another implementation method is to run the program with an interpreter, which translates each line of software into machine code just before it executes. Although it can make debugging easier, the downside of interpretation is that it runs 10 to 100 times slower than a compiled executable. Hybrid interpretation methods provide some of the benefits of compilation and some of the benefits of interpretation via partial compilation. One form this takes is just-in-time compilation, in which the software is compiled ahead of time into an intermediate language, and then into machine code immediately before execution. == Proprietary languages == Although most of the most commonly used programming languages have fully open specifications and implementations, many programming languages exist only as proprietary programming languages with the implementation available only from a single vendor, which may claim that such a proprietary language is their intellectual property. Proprietary programming languages are commonly domain-specific languages or internal scripting languages for a single product; some proprietary languages are used only internally within a vendor, while others are available to external users. Some programming languages exist on the border between proprietary and open; for example, Oracle Corporation asserts proprietary rights to some aspects of the Java programming language, and Microsoft's C# programming language, which has open implementations of most parts of the system, also has Common Language Runtime (CLR) as a closed environment. Many proprietary languages are widely used, in spite of their proprietary nature; examples include MATLAB, VBScript, and Wolfram Language. Some languages may make the transition from closed to open; for example, Erlang was originally Ericsson's internal programming language. Open source programming languages are particularly helpful for open science applications, enhancing the capacity for replication and code sharing. == Use == Thousands of different programming languages have been created, mainly in the computing field. Individual software projects commonly use five programming languages or more. Programming languages differ from most other forms of human expression in that they require a greater degree of precision and completeness. When using a natural language to communicate with other people, human authors and speakers can be ambiguous and make small errors, and still expect their intent to be understood. However, figuratively speaking, computers "do exactly what they are told to do", and cannot "understand" what code the programmer intended to write. The combination of the language definition, a program, and the program's inputs must fully specify the external behavior that occurs when the program is executed, within the domain of control of that program. On the other hand, ideas about an algorithm can be communicated to humans without the precision required for execution by using pseudocode, which interleaves natural language with code written in a programming language. A programming language provides a structured mechanism for defining pieces of data, and the operations or transformations that may be carried out automatically on that data. A programmer uses the abstractions present in the language to represent the concepts involved in a computation. These concepts are represented as a collection of the simplest elements available (called primitives). Programming is the process by which programmers combine these primitives to compose new programs, or adapt existing ones to new uses or a changing environment. Programs for a computer might be executed in a batch process without any human interaction, or a user might type commands in an interactive session of an interpreter. In this case the "commands" are simply programs, whose execution is chained together. When a language can run its commands through an interpreter (such as a Unix shell or other command-line interface), without compiling, it is called a scripting language. === Measuring language usage === Determining which is the most widely used programming language is difficult since the definition of usage varies by context. One language may occupy the greater number of programmer hours, a different one has more lines of code, and a third may consume the most CPU time. Some languages are very popular for particular kinds of applications. For example, COBOL is still strong in the corporate data center, often on large mainframes; Fortran in scientific and engineering applications; Ada in aerospace, transportation, military, real-time, and embedded applications; and C in embedded applications and operating systems. Other languages are regularly used to write many different kinds of applications. Various methods of measuring language popularity, each subject to a different bias over what is measured, have been proposed: counting the number of job advertisements that mention the language the number of books sold that teach or describe the language estimates of the number of existing lines of code written in the language – which may underestimate languages not often found in public searches counts of language references (i.e., to the name of the language) found using a web search engine. Combining and averaging information from various internet sites, stackify.com reported the ten most popular programming languages (in descending order by overall popularity): Java, C, C++, Python, C#, JavaScript, VB .NET, R, PHP, and MATLAB. As of June 2024, the top five programming languages as measured by TIOBE index are Python, C++, C, Java and C#. TIOBE provides a list of top 100 programming languages according to popularity and update this list every month. == Dialects, flavors and implementations == A dialect of a programming language or a data exchange language is a (relatively small) variation or extension of the language that does not change its intrinsic nature. With languages such as Scheme and Forth, standards may be considered insufficient, inadequate, or illegitimate by implementors, so often they will deviate from the standard, making a new dialect. In other cases, a dialect is created for use in a domain-specific language, often a subset. In the Lisp world, most languages that use basic S-expression syntax and Lisp-like semantics are considered Lisp dialects, although they vary wildly as do, say, Racket and Clojure. As it is common for one language to have several dialects, it can become quite difficult for an inexperienced programmer to find the right documentation. The BASIC language has many dialects. == Classifications == Programming languages are often placed into four main categories: imperative, functional, logic, and object oriented. Imperative languages are designed to implement an algorithm in a specified order; they include visual programming languages such as .NET for generating graphical user interfaces. Scripting languages, which are partly or fully interpreted rather than compiled, are sometimes considered a separate category but meet the definition of imperative languages. Functional programming languages work by successively applying functions to the given parameters. Although appreciated by many researchers for their simplicity and elegance, problems with efficiency have prevented them from being widely adopted. Logic languages are designed so that the software, rather than the programmer, decides what order in which the instructions are executed. Object-oriented programming—whose characteristic features are data abstraction, inheritance, and dynamic dispatch—is supported by most popular imperative languages and some functional languages. Although markup languages are not programming languages, some have extensions that support limited programming. Additionally, there are special-purpose languages that are not easily compared to other programming languages. == See also == == References == == Further reading ==
https://en.wikipedia.org/wiki/Programming_language
C (pronounced – like the letter c) is a general-purpose programming language. It was created in the 1970s by Dennis Ritchie and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of the targeted CPUs. It has found lasting use in operating systems code (especially in kernels), device drivers, and protocol stacks, but its use in application software has been decreasing. C is commonly used on computer architectures that range from the largest supercomputers to the smallest microcontrollers and embedded systems. A successor to the programming language B, C was originally developed at Bell Labs by Ritchie between 1972 and 1973 to construct utilities running on Unix. It was applied to re-implementing the kernel of the Unix operating system. During the 1980s, C gradually gained popularity. It has become one of the most widely used programming languages, with C compilers available for practically all modern computer architectures and operating systems. The book The C Programming Language, co-authored by the original language designer, served for many years as the de facto standard for the language. C has been standardized since 1989 by the American National Standards Institute (ANSI) and, subsequently, jointly by the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC). C is an imperative procedural language, supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support. Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant C program written with portability in mind can be compiled for a wide variety of computer platforms and operating systems with few changes to its source code. Since 2000, C has consistently ranked among the top four languages in the TIOBE index, a measure of the popularity of programming languages. == Overview == C is an imperative, procedural language in the ALGOL tradition. It has a static type system. In C, all executable code is contained within subroutines (also called "functions", though not in the sense of functional programming). Function parameters are passed by value, although arrays are passed as pointers, i.e. the address of the first item in the array. Pass-by-reference is simulated in C by explicitly passing pointers to the thing being referenced. C program source text is free-form code. Semicolons terminate statements, while curly braces are used to group statements into blocks. The C language also exhibits the following characteristics: The language has a small, fixed number of keywords, including a full set of control flow primitives: if/else, for, do/while, while, and switch. User-defined names are not distinguished from keywords by any kind of sigil. It has a large number of arithmetic, bitwise, and logic operators: +,+=,++,&,||, etc. More than one assignment may be performed in a single statement. Functions: Function return values can be ignored, when not needed. Function and data pointers permit ad hoc run-time polymorphism. Functions may not be defined within the lexical scope of other functions. Variables may be defined within a function, with scope. A function may call itself, so recursion is supported. Data typing is static, but weakly enforced; all data has a type, but implicit conversions are possible. User-defined (typedef) and compound types are possible. Heterogeneous aggregate data types (struct) allow related data elements to be accessed and assigned as a unit. The contents of whole structs cannot be compared using a single built-in operator (the elements must be compared individually). Union is a structure with overlapping members; it allows multiple data types to share the same memory location. Array indexing is a secondary notation, defined in terms of pointer arithmetic. Whole arrays cannot be assigned or compared using a single built-in operator. There is no "array" keyword in use or definition; instead, square brackets indicate arrays syntactically, for example month[11]. Enumerated types are possible with the enum keyword. They are freely interconvertible with integers. Strings are not a distinct data type, but are conventionally implemented as null-terminated character arrays. Low-level access to computer memory is possible by converting machine addresses to pointers. Procedures (subroutines not returning values) are a special case of function, with an empty return type void. Memory can be allocated to a program with calls to library routines. A preprocessor performs macro definition, source code file inclusion, and conditional compilation. There is a basic form of modularity: files can be compiled separately and linked together, with control over which functions and data objects are visible to other files via static and extern attributes. Complex functionality such as I/O, string manipulation, and mathematical functions are consistently delegated to library routines. The generated code after compilation has relatively straightforward needs on the underlying platform, which makes it suitable for creating operating systems and for use in embedded systems. While C does not include certain features found in other languages (such as object orientation and garbage collection), these can be implemented or emulated, often through the use of external libraries (e.g., the GLib Object System or the Boehm garbage collector). === Relations to other languages === Many later languages have borrowed directly or indirectly from C, including C++, C#, Unix's C shell, D, Go, Java, JavaScript (including transpilers), Julia, Limbo, LPC, Objective-C, Perl, PHP, Python, Ruby, Rust, Swift, Verilog and SystemVerilog (hardware description languages). These languages have drawn many of their control structures and other basic features from C. Most of them also express highly similar syntax to C, and they tend to combine the recognizable expression and statement syntax of C with underlying type systems, data models, and semantics that can be radically different. == History == === Early developments === The origin of C is closely tied to the development of the Unix operating system, originally implemented in assembly language on a PDP-7 by Dennis Ritchie and Ken Thompson, incorporating several ideas from colleagues. Eventually, they decided to port the operating system to a PDP-11. The original PDP-11 version of Unix was also developed in assembly language. ==== B ==== Thompson wanted a programming language for developing utilities for the new platform. He first tried writing a Fortran compiler, but he soon gave up the idea and instead created a cut-down version of the recently developed systems programming language called BCPL. The official description of BCPL was not available at the time, and Thompson modified the syntax to be less 'wordy' and similar to a simplified ALGOL known as SMALGOL. He called the result B, describing it as "BCPL semantics with a lot of SMALGOL syntax". Like BCPL, B had a bootstrapping compiler to facilitate porting to new machines. Ultimately, few utilities were written in B because it was too slow and could not take advantage of PDP-11 features such as byte addressability. ==== New B and first C release ==== In 1971 Ritchie started to improve B, to use the features of the more-powerful PDP-11. A significant addition was a character data type. He called this New B (NB). Thompson started to use NB to write the Unix kernel, and his requirements shaped the direction of the language development. Through to 1972, richer types were added to the NB language: NB had arrays of int and char. Pointers, the ability to generate pointers to other types, arrays of all types, and types to be returned from functions were all also added. Arrays within expressions became pointers. A new compiler was written, and the language was renamed C. The C compiler and some utilities made with it were included in Version 2 Unix, which is also known as Research Unix. ==== Structures and Unix kernel re-write ==== At Version 4 Unix, released in November 1973, the Unix kernel was extensively re-implemented in C. By this time, the C language had acquired some powerful features such as struct types. The preprocessor was introduced around 1973 at the urging of Alan Snyder and also in recognition of the usefulness of the file-inclusion mechanisms available in BCPL and PL/I. Its original version provided only included files and simple string replacements: #include and #define of parameterless macros. Soon after that, it was extended, mostly by Mike Lesk and then by John Reiser, to incorporate macros with arguments and conditional compilation. Unix was one of the first operating system kernels implemented in a language other than assembly. Earlier instances include the Multics system (which was written in PL/I) and Master Control Program (MCP) for the Burroughs B5000 (which was written in ALGOL) in 1961. In around 1977, Ritchie and Stephen C. Johnson made further changes to the language to facilitate portability of the Unix operating system. Johnson's Portable C Compiler served as the basis for several implementations of C on new platforms. === K&R C === In 1978 Brian Kernighan and Dennis Ritchie published the first edition of The C Programming Language. Known as K&R from the initials of its authors, the book served for many years as an informal specification of the language. The version of C that it describes is commonly referred to as "K&R C". As this was released in 1978, it is now also referred to as C78. The second edition of the book covers the later ANSI C standard, described below. K&R introduced several language features: Standard I/O library long int data type unsigned int data type Compound assignment operators of the form =op (such as =-) were changed to the form op= (that is, -=) to remove the semantic ambiguity created by constructs such as i=-10, which had been interpreted as i =- 10 (decrement i by 10) instead of the possibly intended i = -10 (let i be −10). Even after the publication of the 1989 ANSI standard, for many years K&R C was still considered the "lowest common denominator" to which C programmers restricted themselves when maximum portability was desired, since many older compilers were still in use, and because carefully written K&R C code can be legal Standard C as well. In early versions of C, only functions that return types other than int must be declared if used before the function definition; functions used without prior declaration were presumed to return type int. For example: The int type specifiers which are commented out could be omitted in K&R C, but are required in later standards. Since K&R function declarations did not include any information about function arguments, function parameter type checks were not performed, although some compilers would issue a warning message if a local function was called with the wrong number of arguments, or if different calls to an external function used different numbers or types of arguments. Separate tools such as Unix's lint utility were developed that (among other things) could check for consistency of function use across multiple source files. In the years following the publication of K&R C, several features were added to the language, supported by compilers from AT&T (in particular PCC) and some other vendors. These included: void functions (i.e., functions with no return value) functions returning struct or union types (previously only a single pointer, integer or float could be returned) assignment for struct data types enumerated types (previously, preprocessor definitions for integer fixed values were used, e.g. #define GREEN 3) The large number of extensions and lack of agreement on a standard library, together with the language popularity and the fact that not even the Unix compilers precisely implemented the K&R specification, led to the necessity of standardization. === ANSI C and ISO C === During the late 1970s and 1980s, versions of C were implemented for a wide variety of mainframe computers, minicomputers, and microcomputers, including the IBM PC, as its popularity began to increase significantly. In 1983 the American National Standards Institute (ANSI) formed a committee, X3J11, to establish a standard specification of C. X3J11 based the C standard on the Unix implementation; however, the non-portable portion of the Unix C library was handed off to the IEEE working group 1003 to become the basis for the 1988 POSIX standard. In 1989, the C standard was ratified as ANSI X3.159-1989 "Programming Language C". This version of the language is often referred to as ANSI C, Standard C, or sometimes C89. In 1990 the ANSI C standard (with formatting changes) was adopted by the International Organization for Standardization (ISO) as ISO/IEC 9899:1990, which is sometimes called C90. Therefore, the terms "C89" and "C90" refer to the same programming language. ANSI, like other national standards bodies, no longer develops the C standard independently, but defers to the international C standard, maintained by the working group ISO/IEC JTC1/SC22/WG14. National adoption of an update to the international standard typically occurs within a year of ISO publication. One of the aims of the C standardization process was to produce a superset of K&R C, incorporating many of the subsequently introduced unofficial features. The standards committee also included several additional features such as function prototypes (borrowed from C++), void pointers, support for international character sets and locales, and preprocessor enhancements. Although the syntax for parameter declarations was augmented to include the style used in C++, the K&R interface continued to be permitted, for compatibility with existing source code. C89 is supported by current C compilers, and most modern C code is based on it. Any program written only in Standard C and without any hardware-dependent assumptions will run correctly on any platform with a conforming C implementation, within its resource limits. Without such precautions, programs may compile only on a certain platform or with a particular compiler, due, for example, to the use of non-standard libraries, such as GUI libraries, or to a reliance on compiler- or platform-specific attributes such as the exact size of data types and byte endianness. In cases where code must be compilable by either standard-conforming or K&R C-based compilers, the __STDC__ macro can be used to split the code into Standard and K&R sections to prevent the use on a K&R C-based compiler of features available only in Standard C. After the ANSI/ISO standardization process, the C language specification remained relatively static for several years. In 1995, Normative Amendment 1 to the 1990 C standard (ISO/IEC 9899/AMD1:1995, known informally as C95) was published, to correct some details and to add more extensive support for international character sets. === C99 === The C standard was further revised in the late 1990s, leading to the publication of ISO/IEC 9899:1999 in 1999, which is commonly referred to as "C99". It has since been amended three times by Technical Corrigenda. C99 introduced several new features, including inline functions, several new data types (including long long int and a complex type to represent complex numbers), variable-length arrays and flexible array members, improved support for IEEE 754 floating point, support for variadic macros (macros of variable arity), and support for one-line comments beginning with //, as in BCPL or C++. Many of these had already been implemented as extensions in several C compilers. C99 is for the most part backward compatible with C90, but is stricter in some ways; in particular, a declaration that lacks a type specifier no longer has int implicitly assumed. A standard macro __STDC_VERSION__ is defined with value 199901L to indicate that C99 support is available. GCC, Solaris Studio, and other C compilers now support many or all of the new features of C99. The C compiler in Microsoft Visual C++, however, implements the C89 standard and those parts of C99 that are required for compatibility with C++11. In addition, the C99 standard requires support for identifiers using Unicode in the form of escaped characters (e.g. \u0040 or \U0001f431) and suggests support for raw Unicode names. === C11 === Work began in 2007 on another revision of the C standard, informally called "C1X" until its official publication of ISO/IEC 9899:2011 on December 8, 2011. The C standards committee adopted guidelines to limit the adoption of new features that had not been tested by existing implementations. The C11 standard adds numerous new features to C and the library, including type generic macros, anonymous structures, improved Unicode support, atomic operations, multi-threading, and bounds-checked functions. It also makes some portions of the existing C99 library optional, and improves compatibility with C++. The standard macro __STDC_VERSION__ is defined as 201112L to indicate that C11 support is available. === C17 === C17 is an informal name for ISO/IEC 9899:2018, a standard for the C programming language published in June 2018. It introduces no new language features, only technical corrections, and clarifications to defects in C11. The standard macro __STDC_VERSION__ is defined as 201710L to indicate that C17 support is available. === C23 === C23 is an informal name for the current major C language standard revision. It was informally known as "C2X" through most of its development. C23 was published in October 2024 as ISO/IEC 9899:2024. The standard macro __STDC_VERSION__ is defined as 202311L to indicate that C23 support is available. === C2Y === C2Y is an informal name for the next major C language standard revision, after C23 (C2X), that is hoped to be released later in the 2020s, hence the '2' in "C2Y". An early working draft of C2Y was released in February 2024 as N3220 by the working group ISO/IEC JTC1/SC22/WG14. === Embedded C === Historically, embedded C programming requires non-standard extensions to the C language to support exotic features such as fixed-point arithmetic, multiple distinct memory banks, and basic I/O operations. In 2008, the C Standards Committee published a technical report extending the C language to address these issues by providing a common standard for all implementations to adhere to. It includes a number of features not available in normal C, such as fixed-point arithmetic, named address spaces, and basic I/O hardware addressing. == Syntax == C has a formal grammar specified by the C standard. Line endings are generally not significant in C; however, line boundaries do have significance during the preprocessing phase. Comments may appear either between the delimiters /* and */, or (since C99) following // until the end of the line. Comments delimited by /* and */ do not nest, and these sequences of characters are not interpreted as comment delimiters if they appear inside string or character literals. C source files contain declarations and function definitions. Function definitions, in turn, contain declarations and statements. Declarations either define new types using keywords such as struct, union, and enum, or assign types to and perhaps reserve storage for new variables, usually by writing the type followed by the variable name. Keywords such as char and int specify built-in types. Sections of code are enclosed in braces ({ and }, sometimes called "curly brackets") to limit the scope of declarations and to act as a single statement for control structures. As an imperative language, C uses statements to specify actions. The most common statement is an expression statement, consisting of an expression to be evaluated, followed by a semicolon; as a side effect of the evaluation, functions may be called and variables assigned new values. To modify the normal sequential execution of statements, C provides several control-flow statements identified by reserved keywords. Structured programming is supported by if ... [else] conditional execution and by do ... while, while, and for iterative execution (looping). The for statement has separate initialization, testing, and reinitialization expressions, any or all of which can be omitted. break and continue can be used within the loop. Break is used to leave the innermost enclosing loop statement and continue is used to skip to its reinitialisation. There is also a non-structured goto statement which branches directly to the designated label within the function. switch selects a case to be executed based on the value of an integer expression. Different from many other languages, control-flow will fall through to the next case unless terminated by a break. Expressions can use a variety of built-in operators and may contain function calls. The order in which arguments to functions and operands to most operators are evaluated is unspecified. The evaluations may even be interleaved. However, all side effects (including storage to variables) will occur before the next "sequence point"; sequence points include the end of each expression statement, and the entry to and return from each function call. Sequence points also occur during evaluation of expressions containing certain operators (&&, ||, ?: and the comma operator). This permits a high degree of object code optimization by the compiler, but requires C programmers to take more care to obtain reliable results than is needed for other programming languages. Kernighan and Ritchie say in the Introduction of The C Programming Language: "C, like any other language, has its blemishes. Some of the operators have the wrong precedence; some parts of the syntax could be better." The C standard did not attempt to correct many of these blemishes, because of the impact of such changes on already existing software. === Character set === The basic C source character set includes the following characters: Lowercase and uppercase letters of the ISO basic Latin alphabet: a–z, A–Z Decimal digits: 0–9 Graphic characters: ! " # % & ' ( ) * + , - . / : ; < = > ? [ \ ] ^ _ { | } ~ Whitespace characters: space, horizontal tab, vertical tab, form feed, newline The newline character indicates the end of a text line; it need not correspond to an actual single character, although for convenience C treats it as such. Additional multi-byte encoded characters may be used in string literals, but they are not entirely portable. Since C99 multi-national Unicode characters can be embedded portably within C source text by using \uXXXX or \UXXXXXXXX encoding (where X denotes a hexadecimal character). The basic C execution character set contains the same characters, along with representations for alert, backspace, and carriage return. Run-time support for extended character sets has increased with each revision of the C standard. === Reserved words === The following reserved words are case sensitive. C89 has 32 reserved words, also known as 'keywords', which cannot be used for any purposes other than those for which they are predefined: C99 added five more reserved words: (‡ indicates an alternative spelling alias for a C23 keyword) C11 added seven more reserved words: (‡ indicates an alternative spelling alias for a C23 keyword) C23 reserved fifteen more words: Most of the recently reserved words begin with an underscore followed by a capital letter, because identifiers of that form were previously reserved by the C standard for use only by implementations. Since existing program source code should not have been using these identifiers, it would not be affected when C implementations started supporting these extensions to the programming language. Some standard headers do define more convenient synonyms for underscored identifiers. Some of those words were added as keywords with their conventional spelling in C23 and the corresponding macros were removed. Prior to C89, entry was reserved as a keyword. In the second edition of their book The C Programming Language, which describes what became known as C89, Kernighan and Ritchie wrote, "The ... [keyword] entry, formerly reserved but never used, is no longer reserved." and "The stillborn entry keyword is withdrawn." === Operators === C supports a rich set of operators, which are symbols used within an expression to specify the manipulations to be performed while evaluating that expression. C has operators for: arithmetic: +, -, *, /, % assignment: = augmented assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= bitwise logic: ~, &, |, ^ bitwise shifts: <<, >> Boolean logic: !, &&, || conditional evaluation: ? : equality testing: ==, != calling functions: ( ) increment and decrement: ++, -- member selection: ., -> object size: sizeof type: typeof, typeof_unqual since C23 order relations: <, <=, >, >= reference and dereference: &, *, [ ] sequencing: , subexpression grouping: ( ) type conversion: (typename) C uses the operator = (used in mathematics to express equality) to indicate assignment, following the precedent of Fortran and PL/I, but unlike ALGOL and its derivatives. C uses the operator == to test for equality. The similarity between the operators for assignment and equality may result in the accidental use of one in place of the other, and in many cases the mistake does not produce an error message (although some compilers produce warnings). For example, the conditional expression if (a == b + 1) might mistakenly be written as if (a = b + 1), which will be evaluated as true unless the value of a is 0 after the assignment. The C operator precedence is not always intuitive. For example, the operator == binds more tightly than (is executed prior to) the operators & (bitwise AND) and | (bitwise OR) in expressions such as x & 1 == 0, which must be written as (x & 1) == 0 if that is the coder's intent. == "Hello, world" example == The "hello, world" example that appeared in the first edition of K&R has become the model for an introductory program in most programming textbooks. The program prints "hello, world" to the standard output, which is usually a terminal or screen display. The original version was: A standard-conforming "hello, world" program is: The first line of the program contains a preprocessing directive, indicated by #include. This causes the compiler to replace that line of code with the entire text of the stdio.h header file, which contains declarations for standard input and output functions such as printf and scanf. The angle brackets surrounding stdio.h indicate that the header file can be located using a search strategy that prefers headers provided with the compiler to other headers having the same name (as opposed to double quotes which typically include local or project-specific header files). The second line indicates that a function named main is being defined. The main function serves a special purpose in C programs; the run-time environment calls the main function to begin program execution. The type specifier int indicates that the value returned to the invoker (in this case the run-time environment) as a result of evaluating the main function, is an integer. The keyword void as a parameter list indicates that the main function takes no arguments. The opening curly brace indicates the beginning of the code that defines the main function. The next line of the program is a statement that calls (i.e. diverts execution to) a function named printf, which in this case is supplied from a system library. In this call, the printf function is passed (i.e. provided with) a single argument, which is the address of the first character in the string literal "hello, world\n". The string literal is an unnamed array set up automatically by the compiler, with elements of type char and a final NULL character (ASCII value 0) marking the end of the array (to allow printf to determine the length of the string). The NULL character can also be written as the escape sequence \0. The \n is a standard escape sequence that C translates to a newline character, which, on output, signifies the end of the current line. The return value of the printf function is of type int, but it is silently discarded since it is not used. (A more careful program might test the return value to check that the printf function succeeded.) The semicolon ; terminates the statement. The closing curly brace indicates the end of the code for the main function. According to the C99 specification and newer, the main function (unlike any other function) will implicitly return a value of 0 upon reaching the } that terminates the function. The return value of 0 is interpreted by the run-time system as an exit code indicating successful execution of the function. == Data types == The type system in C is static and weakly typed, which makes it similar to the type system of ALGOL descendants such as Pascal. There are built-in types for integers of various sizes, both signed and unsigned, floating-point numbers, and enumerated types (enum). Integer type char is often used for single-byte characters. C99 added a Boolean data type. There are also derived types including arrays, pointers, records (struct), and unions (union). C is often used in low-level systems programming where escapes from the type system may be necessary. The compiler attempts to ensure type correctness of most expressions, but the programmer can override the checks in various ways, either by using a type cast to explicitly convert a value from one type to another, or by using pointers or unions to reinterpret the underlying bits of a data object in some other way. Some find C's declaration syntax unintuitive, particularly for function pointers. (Ritchie's idea was to declare identifiers in contexts resembling their use: "declaration reflects use".) C's usual arithmetic conversions allow for efficient code to be generated, but can sometimes produce unexpected results. For example, a comparison of signed and unsigned integers of equal width requires a conversion of the signed value to unsigned. This can generate unexpected results if the signed value is negative. === Pointers === C supports the use of pointers, a type of reference that records the address or location of an object or function in memory. Pointers can be dereferenced to access data stored at the address pointed to, or to invoke a pointed-to function. Pointers can be manipulated using assignment or pointer arithmetic. The run-time representation of a pointer value is typically a raw memory address (perhaps augmented by an offset-within-word field), but since a pointer's type includes the type of the thing pointed to, expressions including pointers can be type-checked at compile time. Pointer arithmetic is automatically scaled by the size of the pointed-to data type. Pointers are used for many purposes in C. Text strings are commonly manipulated using pointers into arrays of characters. Dynamic memory allocation is performed using pointers; the result of a malloc is usually cast to the data type of the data to be stored. Many data types, such as trees, are commonly implemented as dynamically allocated struct objects linked together using pointers. Pointers to other pointers are often used in multi-dimensional arrays and arrays of struct objects. Pointers to functions (function pointers) are useful for passing functions as arguments to higher-order functions (such as qsort or bsearch), in dispatch tables, or as callbacks to event handlers. A null pointer value explicitly points to no valid location. Dereferencing a null pointer value is undefined, often resulting in a segmentation fault. Null pointer values are useful for indicating special cases such as no "next" pointer in the final node of a linked list, or as an error indication from functions returning pointers. In appropriate contexts in source code, such as for assigning to a pointer variable, a null pointer constant can be written as 0, with or without explicit casting to a pointer type, as the NULL macro defined by several standard headers or, since C23 with the constant nullptr. In conditional contexts, null pointer values evaluate to false, while all other pointer values evaluate to true. Void pointers (void *) point to objects of unspecified type, and can therefore be used as "generic" data pointers. Since the size and type of the pointed-to object is not known, void pointers cannot be dereferenced, nor is pointer arithmetic on them allowed, although they can easily be (and in many contexts implicitly are) converted to and from any other object pointer type. Careless use of pointers is potentially dangerous. Because they are typically unchecked, a pointer variable can be made to point to any arbitrary location, which can cause undesirable effects. Although properly used pointers point to safe places, they can be made to point to unsafe places by using invalid pointer arithmetic; the objects they point to may continue to be used after deallocation (dangling pointers); they may be used without having been initialized (wild pointers); or they may be directly assigned an unsafe value using a cast, union, or through another corrupt pointer. In general, C is permissive in allowing manipulation of and conversion between pointer types, although compilers typically provide options for various levels of checking. Some other programming languages address these problems by using more restrictive reference types. === Arrays === Array types in C are traditionally of a fixed, static size specified at compile time. The more recent C99 standard also allows a form of variable-length arrays. However, it is also possible to allocate a block of memory (of arbitrary size) at run-time, using the standard library's malloc function, and treat it as an array. Since arrays are always accessed (in effect) via pointers, array accesses are typically not checked against the underlying array size, although some compilers may provide bounds checking as an option. Array bounds violations are therefore possible and can lead to various repercussions, including illegal memory accesses, corruption of data, buffer overruns, and run-time exceptions. C does not have a special provision for declaring multi-dimensional arrays, but rather relies on recursion within the type system to declare arrays of arrays, which effectively accomplishes the same thing. The index values of the resulting "multi-dimensional array" can be thought of as increasing in row-major order. Multi-dimensional arrays are commonly used in numerical algorithms (mainly from applied linear algebra) to store matrices. The structure of the C array is well suited to this particular task. However, in early versions of C the bounds of the array must be known fixed values or else explicitly passed to any subroutine that requires them, and dynamically sized arrays of arrays cannot be accessed using double indexing. (A workaround for this was to allocate the array with an additional "row vector" of pointers to the columns.) C99 introduced "variable-length arrays" which address this issue. The following example using modern C (C99 or later) shows allocation of a two-dimensional array on the heap and the use of multi-dimensional array indexing for accesses (which can use bounds-checking on many C compilers): And here is a similar implementation using C99's Auto VLA feature: === Array–pointer interchangeability === The subscript notation x[i] (where x designates a pointer) is syntactic sugar for *(x+i). Taking advantage of the compiler's knowledge of the pointer type, the address that x + i points to is not the base address (pointed to by x) incremented by i bytes, but rather is defined to be the base address incremented by i multiplied by the size of an element that x points to. Thus, x[i] designates the i+1th element of the array. Furthermore, in most expression contexts (a notable exception is as operand of sizeof), an expression of array type is automatically converted to a pointer to the array's first element. This implies that an array is never copied as a whole when named as an argument to a function, but rather only the address of its first element is passed. Therefore, although function calls in C use pass-by-value semantics, arrays are in effect passed by reference. The total size of an array x can be determined by applying sizeof to an expression of array type. The size of an element can be determined by applying the operator sizeof to any dereferenced element of an array A, as in n = sizeof A[0]. Thus, the number of elements in a declared array A can be determined as sizeof A / sizeof A[0]. Note, that if only a pointer to the first element is available as it is often the case in C code because of the automatic conversion described above, the information about the full type of the array and its length are lost. == Memory management == One of the most important functions of a programming language is to provide facilities for managing memory and the objects that are stored in memory. C provides three principal ways to allocate memory for objects: Static memory allocation: space for the object is provided in the binary at compile-time; these objects have an extent (or lifetime) as long as the binary which contains them is loaded into memory. Automatic memory allocation: temporary objects can be stored on the stack, and this space is automatically freed and reusable after the block in which they are declared is exited. Dynamic memory allocation: blocks of memory of arbitrary size can be requested at run-time using library functions such as malloc from a region of memory called the heap; these blocks persist until subsequently freed for reuse by calling the library function realloc or free. These three approaches are appropriate in different situations and have various trade-offs. For example, static memory allocation has little allocation overhead, automatic allocation may involve slightly more overhead, and dynamic memory allocation can potentially have a great deal of overhead for both allocation and deallocation. The persistent nature of static objects is useful for maintaining state information across function calls, automatic allocation is easy to use but stack space is typically much more limited and transient than either static memory or heap space, and dynamic memory allocation allows convenient allocation of objects whose size is known only at run-time. Most C programs make extensive use of all three. Where possible, automatic or static allocation is usually simplest because the storage is managed by the compiler, freeing the programmer of the potentially error-prone chore of manually allocating and releasing storage. However, many data structures can change in size at runtime, and since static allocations (and automatic allocations before C99) must have a fixed size at compile-time, there are many situations in which dynamic allocation is necessary. Prior to the C99 standard, variable-sized arrays were a common example of this. (See the article on C dynamic memory allocation for an example of dynamically allocated arrays.) Unlike automatic allocation, which can fail at run time with uncontrolled consequences, the dynamic allocation functions return an indication (in the form of a null pointer value) when the required storage cannot be allocated. (Static allocation that is too large is usually detected by the linker or loader, before the program can even begin execution.) Unless otherwise specified, static objects contain zero or null pointer values upon program startup. Automatically and dynamically allocated objects are initialized only if an initial value is explicitly specified; otherwise they initially have indeterminate values (typically, whatever bit pattern happens to be present in the storage, which might not even represent a valid value for that type). If the program attempts to access an uninitialized value, the results are undefined. Many modern compilers try to detect and warn about this problem, but both false positives and false negatives can occur. Heap memory allocation has to be synchronized with its actual usage in any program to be reused as much as possible. For example, if the only pointer to a heap memory allocation goes out of scope or has its value overwritten before it is deallocated explicitly, then that memory cannot be recovered for later reuse and is essentially lost to the program, a phenomenon known as a memory leak. Conversely, it is possible for memory to be freed, but is referenced subsequently, leading to unpredictable results. Typically, the failure symptoms appear in a portion of the program unrelated to the code that causes the error, making it difficult to diagnose the failure. Such issues are ameliorated in languages with automatic garbage collection. == Libraries == The C programming language uses libraries as its primary method of extension. In C, a library is a set of functions contained within a single "archive" file. Each library typically has a header file, which contains the prototypes of the functions contained within the library that may be used by a program, and declarations of special data types and macro symbols used with these functions. For a program to use a library, it must include the library's header file, and the library must be linked with the program, which in many cases requires compiler flags (e.g., -lm, shorthand for "link the math library"). The most common C library is the C standard library, which is specified by the ISO and ANSI C standards and comes with every C implementation (implementations which target limited environments such as embedded systems may provide only a subset of the standard library). This library supports stream input and output, memory allocation, mathematics, character strings, and time values. Several separate standard headers (for example, stdio.h) specify the interfaces for these and other standard library facilities. Another common set of C library functions are those used by applications specifically targeted for Unix and Unix-like systems, especially functions which provide an interface to the kernel. These functions are detailed in various standards such as POSIX and the Single UNIX Specification. Since many programs have been written in C, there are a wide variety of other libraries available. Libraries are often written in C because C compilers generate efficient object code; programmers then create interfaces to the library so that the routines can be used from higher-level languages like Java, Perl, and Python. === File handling and streams === File input and output (I/O) is not part of the C language itself but instead is handled by libraries (such as the C standard library) and their associated header files (e.g. stdio.h). File handling is generally implemented through high-level I/O which works through streams. A stream is from this perspective a data flow that is independent of devices, while a file is a concrete device. The high-level I/O is done through the association of a stream to a file. In the C standard library, a buffer (a memory area or queue) is temporarily used to store data before it is sent to the final destination. This reduces the time spent waiting for slower devices, for example a hard drive or solid-state drive. Low-level I/O functions are not part of the standard C library but are generally part of "bare metal" programming (programming that is independent of any operating system such as most embedded programming). With few exceptions, implementations include low-level I/O. == Language tools == A number of tools have been developed to help C programmers find and fix statements with undefined behavior or possibly erroneous expressions, with greater rigor than that provided by the compiler. Automated source code checking and auditing tools exist, such as Lint. A common practice is to use Lint to detect questionable code when a program is first written. Once a program passes Lint, it is then compiled using the C compiler. Also, many compilers can optionally warn about syntactically valid constructs that are likely to actually be errors. MISRA C is a proprietary set of guidelines to avoid such questionable code, developed for embedded systems. There are also compilers, libraries, and operating system level mechanisms for performing actions that are not a standard part of C, such as bounds checking for arrays, detection of buffer overflow, serialization, dynamic memory tracking, and automatic garbage collection. Memory management checking tools like Purify or Valgrind and linking with libraries containing special versions of the memory allocation functions can help uncover runtime errors in memory usage. == Uses == === Rationale for use in systems programming === C is widely used for systems programming in implementing operating systems and embedded system applications. This is for several reasons: The C language permits platform hardware and memory to be accessed with pointers and type punning, so system-specific features (e.g. Control/Status Registers, I/O registers) can be configured and used with code written in C – it allows fullest control of the platform it is running on. The code generated after compilation does not demand many system features, and can be invoked from some boot code in a straightforward manner – it is simple to execute. The C language statements and expressions typically map well on to sequences of instructions for the target processor, and consequently there is a low run-time demand on system resources – it is fast to execute. With its rich set of operators, the C language can use many of the features of target CPUs. Where a particular CPU has more esoteric instructions, a language variant can be constructed with perhaps intrinsic functions to exploit those instructions – it can use practically all the target CPU's features. The language makes it easy to overlay structures onto blocks of binary data, allowing the data to be comprehended, navigated and modified – it can write data structures, even file systems. The language supports a rich set of operators, including bit manipulation, for integer arithmetic and logic, and perhaps different sizes of floating point numbers – it can process appropriately-structured data effectively. C is a fairly small language, with only a handful of statements, and without too many features that generate extensive target code – it is comprehensible. C has direct control over memory allocation and deallocation, which gives reasonable efficiency and predictable timing to memory-handling operations, without any concerns for sporadic stop-the-world garbage collection events – it has predictable performance. C permits the use and implementation of different memory allocation schemes, including a typical malloc and free; a more sophisticated mechanism with arenas; or a version for an OS kernel that may suit DMA, use within interrupt handlers, or integrated with the virtual memory system. Depending on the linker and environment, C code can also call libraries written in assembly language, and may be called from assembly language – it interoperates well with other lower-level code. C and its calling conventions and linker structures are commonly used in conjunction with other high-level languages, with calls both to C and from C supported – it interoperates well with other high-level code. C has a very mature and broad ecosystem, including libraries, frameworks, open source compilers, debuggers and utilities, and is the de facto standard. It is likely the drivers already exist in C, or that there is a similar CPU architecture as a back-end of a C compiler, so there is reduced incentive to choose another language. === Used for computationally-intensive libraries === C enables programmers to create efficient implementations of algorithms and data structures, because the layer of abstraction from hardware is thin, and its overhead is low, an important criterion for computationally intensive programs. For example, the GNU Multiple Precision Arithmetic Library, the GNU Scientific Library, Mathematica, and MATLAB are completely or partially written in C. Many languages support calling library functions in C, for example, the Python-based framework NumPy uses C for the high-performance and hardware-interacting aspects. === Games === Computer games are often built from a combination of languages. C has featured significantly, especially for those games attempting to obtain best performance from computer platforms. Examples include Doom from 1993. === C as an intermediate language === C is sometimes used as an intermediate language by implementations of other languages. This approach may be used for portability or convenience; by using C as an intermediate language, additional machine-specific code generators are not necessary. C has some features, such as line-number preprocessor directives and optional superfluous commas at the end of initializer lists, that support compilation of generated code. However, some of C's shortcomings have prompted the development of other C-based languages specifically designed for use as intermediate languages, such as C--. Also, contemporary major compilers GCC and LLVM both feature an intermediate representation that is not C, and those compilers support front ends for many languages including C. === Other languages written in C === A consequence of C's wide availability and efficiency is that compilers, libraries and interpreters of other programming languages are often implemented in C. For example, the reference implementations of Python, Perl, Ruby, and PHP are written in C. === Once used for web development === Historically, C was sometimes used for web development using the Common Gateway Interface (CGI) as a "gateway" for information between the web application, the server, and the browser. C may have been chosen over interpreted languages because of its speed, stability, and near-universal availability. It is no longer common practice for web development to be done in C, and many other web development languages are popular. Applications where C-based web development continues include the HTTP configuration pages on routers, IoT devices and similar, although even here some projects have parts in higher-level languages e.g. the use of Lua within OpenWRT. === Web servers === The two most popular web servers, Apache HTTP Server and Nginx, are both written in C. These web servers interact with the operating system, listen on TCP ports for HTTP requests, and then serve up static web content, or cause the execution of other languages handling to 'render' content such as PHP, which is itself primarily written in C. C's close-to-the-metal approach allows for the construction of these high-performance software systems. === End-user applications === C has also been widely used to implement end-user applications. However, such applications can also be written in newer, higher-level languages. == Limitations == the power of assembly language and the convenience of ... assembly language While C has been popular, influential and hugely successful, it has drawbacks, including: The standard dynamic memory handling with malloc and free is error prone. Improper use can lead to memory leaks and dangling pointers. The use of pointers and the direct manipulation of memory means corruption of memory is possible, perhaps due to programmer error, or insufficient checking of bad data. There is some type checking, but it does not apply to areas like variadic functions, and the type checking can be trivially or inadvertently circumvented. It is weakly typed. Since the code generated by the compiler contains few checks itself, there is a burden on the programmer to consider all possible outcomes, to protect against buffer overruns, array bounds checking, stack overflows, memory exhaustion, and consider race conditions, thread isolation, etc. The use of pointers and the run-time manipulation of these means there may be two ways to access the same data (aliasing), which is not determinable at compile time. This means that some optimisations that may be available to other languages are not possible in C. FORTRAN is considered faster. Some of the standard library functions, e.g. scanf or strncat, can lead to buffer overruns. There is limited standardisation in support for low-level variants in generated code, for example: different function calling conventions and ABI; different structure packing conventions; different byte ordering within larger integers (including endianness). In many language implementations, some of these options may be handled with the preprocessor directive #pragma, and some with additional keywords e.g. use __cdecl calling convention. The directive and options are not consistently supported. String handling using the standard library is code-intensive, with explicit memory management required. The language does not directly support object orientation, introspection, run-time expression evaluation, generics, etc. There are few guards against inappropriate use of language features, which may lead to unmaintainable code. In particular, the C preprocessor can hide troubling effects such as double evaluation and worse. This facility for tricky code has been celebrated with competitions such as the International Obfuscated C Code Contest and the Underhanded C Contest. C lacks standard support for exception handling and only offers return codes for error checking. The setjmp and longjmp standard library functions have been used to implement a try-catch mechanism via macros. For some purposes, restricted styles of C have been adopted, e.g. MISRA C or CERT C, in an attempt to reduce the opportunity for bugs. Databases such as CWE attempt to count the ways C etc. has vulnerabilities, along with recommendations for mitigation. There are tools that can mitigate against some of the drawbacks. Contemporary C compilers include checks which may generate warnings to help identify many potential bugs. == Related languages == C has both directly and indirectly influenced many later languages such as C++ and Java. The most pervasive influence has been syntactical; all of the languages mentioned combine the statement and (more or less recognizably) expression syntax of C with type systems, data models or large-scale program structures that differ from those of C, sometimes radically. Several C or near-C interpreters exist, including Ch and CINT, which can also be used for scripting. When object-oriented programming languages became popular, C++ and Objective-C were two different extensions of C that provided object-oriented capabilities. Both languages were originally implemented as source-to-source compilers; source code was translated into C, and then compiled with a C compiler. The C++ programming language (originally named "C with Classes") was devised by Bjarne Stroustrup as an approach to providing object-oriented functionality with a C-like syntax. C++ adds greater typing strength, scoping, and other tools useful in object-oriented programming, and permits generic programming via templates. Nearly a superset of C, C++ now supports most of C, with a few exceptions. Objective-C was originally a very "thin" layer on top of C, and remains a strict superset of C that permits object-oriented programming using a hybrid dynamic/static typing paradigm. Objective-C derives its syntax from both C and Smalltalk: syntax that involves preprocessing, expressions, function declarations, and function calls is inherited from C, while the syntax for object-oriented features was originally taken from Smalltalk. In addition to C++ and Objective-C, Ch, Cilk, and Unified Parallel C are nearly supersets of C. == See also == Compatibility of C and C++ Comparison of Pascal and C Comparison of programming languages International Obfuscated C Code Contest List of C-family programming languages List of C compilers == Notes == == References == == Sources == Ritchie, Dennis M. (March 1993). "The Development of the C Language". ACM SIGPLAN Notices. 28 (3). ACM: 201–208. doi:10.1145/155360.155580. By courtesy of the author, also at Ritchie, Dennis M. "Chistory". www.bell-labs.com. Retrieved March 29, 2022. Ritchie, Dennis M. (1993). "The Development of the C Language". The Second ACM SIGPLAN Conference on History of Programming Languages (HOPL-II). ACM. pp. 201–208. doi:10.1145/154766.155580. ISBN 0-89791-570-4. Archived from the original on April 11, 2019. Retrieved November 4, 2014. Kernighan, Brian W.; Ritchie, Dennis M. (1988). The C Programming Language (2nd ed.). Prentice Hall. ISBN 0-13-110362-8. == Further reading == Plauger, P.J. (1992). The Standard C Library (1 ed.). Prentice Hall. ISBN 978-0131315099. (source) Banahan, M.; Brady, D.; Doran, M. (1991). The C Book: Featuring the ANSI C Standard (2 ed.). Addison-Wesley. ISBN 978-0201544336. (free) Feuer, Alan R. (1985). The C Puzzle Book (1 ed.). Prentice Hall. ISBN 0131099345. Harbison, Samuel; Steele, Guy Jr. (2002). C: A Reference Manual (5 ed.). Pearson. ISBN 978-0130895929. (archive) King, K.N. (2008). C Programming: A Modern Approach (2 ed.). W. W. Norton. ISBN 978-0393979503. (archive) Griffiths, David; Griffiths, Dawn (2012). Head First C (1 ed.). O'Reilly. ISBN 978-1449399917. Perry, Greg; Miller, Dean (2013). C Programming: Absolute Beginner's Guide (3 ed.). Que. ISBN 978-0789751980. Deitel, Paul; Deitel, Harvey (2015). C: How to Program (8 ed.). Pearson. ISBN 978-0133976892. Gustedt, Jens (2019). Modern C (2 ed.). Manning. ISBN 978-1617295812. (free) == External links == ISO C Working Group official website ISO/IEC 9899, publicly available official C documents, including the C99 Rationale "C99 with Technical corrigenda TC1, TC2, and TC3 included" (PDF). Archived (PDF) from the original on October 25, 2007. (3.61 MB) comp.lang.c Frequently Asked Questions A History of C, by Dennis Ritchie C Library Reference and Examples
https://en.wikipedia.org/wiki/C_(programming_language)
In computer programming, a programming idiom, code idiom or simply idiom is a code fragment having a semantic role which recurs frequently across software projects. It often expresses a special feature of a recurring construct in one or more programming languages, frameworks or libraries. This definition is rooted in the linguistic definition of "idiom". The idiom can be seen by developers as an action on a programming concept underlying a pattern in code, which is represented in implementation by contiguous or scattered code snippets. Generally speaking, a programming idiom's semantic role is a natural language expression of a simple task, algorithm, or data structure that is not a built-in feature in the programming language being used, or, conversely, the use of an unusual or notable feature that is built into a programming language. Knowing the idioms associated with a programming language and how to use them is an important part of gaining fluency in that language. It also helps to transfer knowledge in the form of analogies from one language or framework to another. Such idiomatic knowledge is widely used in crowdsourced repositories to help developers overcome programming barriers. Mapping code idioms to idiosyncrasies can be a helpful way to navigate the tradeoffs between generalization and specificity. By identifying common patterns and idioms, developers can create mental models and schemata that help them quickly understand and navigate new code. Furthermore, by mapping these idioms to idiosyncrasies and specific use cases, developers can ensure that they are applying the correct approach and not overgeneralizing it. One way to do this is by creating a reference or documentation that maps common idioms to specific use cases, highlighting where they may need to be adapted or modified to fit a particular project or development team. This can help ensure that developers are working with a shared understanding of best practices and can make informed decisions about when to use established idioms and when to adapt them to fit their specific needs. A common misconception is to use the adverbial or adjectival form of the term as "using a programming language in a typical way", which really refers to a idiosyncrasy. An idiom implies the semantics of some code in a programming language has similarities to other languages or frameworks. For example, an idiosyncratic way to manage dynamic memory in C would be to use the C standard library functions malloc and free, whereas idiomatic refers to manual memory management as recurring semantic role that can be achieved with code fragments malloc in C, or pointer = new type [number_of_elements] in C++. In both cases, the semantics of the code are intelligible to developers familiar with C or C++, once the idiomatic or idiosyncratic rationale is exposed to them. However, while idiomatic rationale is often general to the programming domain, idiosyncratic rationale is frequently tied to specific API terminology. == Examples == === Printing Hello World === One of the most common starting points to learn to program or notice the syntax differences between a known language and a new one. It has several implementations, among them the code fragments for C++: For Java: === Inserting an element in an array === This idiom helps developers understand how to manipulate collections in a given language, particularly inserting an element x at a position i in a list s and moving the elements to its right. Code fragments: For Python: For JavaScript: For Perl: == See also == Algorithmic skeleton Embedded SQL Idiom == References == == External links == programming-idioms.org shows short idioms implementations in most mainstream languages. C++ programming idioms from Wikibooks.
https://en.wikipedia.org/wiki/Programming_idiom
In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior. == Historical background == The earliest computers were programmed in their native assembly languages, which were inherently reflective, as these original architectures could be programmed by defining instructions as data and using self-modifying code. As the bulk of programming moved to higher-level compiled languages such as ALGOL, COBOL, Fortran, Pascal, and C, this reflective ability largely disappeared until new programming languages with reflection built into their type systems appeared. Brian Cantwell Smith's 1982 doctoral dissertation introduced the notion of computational reflection in procedural programming languages and the notion of the meta-circular interpreter as a component of 3-Lisp. == Uses == Reflection helps programmers make generic software libraries to display data, process different formats of data, perform serialization and deserialization of data for communication, or do bundling and unbundling of data for containers or bursts of communication. Effective use of reflection almost always requires a plan: A design framework, encoding description, object library, a map of a database or entity relations. Reflection makes a language more suited to network-oriented code. For example, it assists languages such as Java to operate well in networks by enabling libraries for serialization, bundling and varying data formats. Languages without reflection such as C are required to use auxiliary compilers for tasks like Abstract Syntax Notation to produce code for serialization and bundling. Reflection can be used for observing and modifying program execution at runtime. A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal of that enclosure. This is typically accomplished by dynamically assigning program code at runtime. In object-oriented programming languages such as Java, reflection allows inspection of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at compile time. It also allows instantiation of new objects and invocation of methods. Reflection is often used as part of software testing, such as for the runtime creation/instantiation of mock objects. Reflection is also a key strategy for metaprogramming. In some object-oriented programming languages such as C# and Java, reflection can be used to bypass member accessibility rules. For C#-properties this can be achieved by writing directly onto the (usually invisible) backing field of a non-public property. It is also possible to find non-public methods of classes and types and manually invoke them. This works for project-internal files as well as external libraries such as .NET's assemblies and Java's archives. == Implementation == A language that supports reflection provides a number of features available at runtime that would otherwise be difficult to accomplish in a lower-level language. Some of these features are the abilities to: Discover and modify source-code constructions (such as code blocks, classes, methods, protocols, etc.) as first-class objects at runtime. Convert a string matching the symbolic name of a class or function into a reference to or invocation of that class or function. Evaluate a string as if it were a source-code statement at runtime. Create a new interpreter for the language's bytecode to give a new meaning or purpose for a programming construct. These features can be implemented in different ways. In MOO, reflection forms a natural part of everyday programming idiom. When verbs (methods) are called, various variables such as verb (the name of the verb being called) and this (the object on which the verb is called) are populated to give the context of the call. Security is typically managed by accessing the caller stack programmatically: Since callers() is a list of the methods by which the current verb was eventually called, performing tests on callers()[0] (the command invoked by the original user) allows the verb to protect itself against unauthorised use. Compiled languages rely on their runtime system to provide information about the source code. A compiled Objective-C executable, for example, records the names of all methods in a block of the executable, providing a table to correspond these with the underlying methods (or selectors for these methods) compiled into the program. In a compiled language that supports runtime creation of functions, such as Common Lisp, the runtime environment must include a compiler or an interpreter. Reflection can be implemented for languages without built-in reflection by using a program transformation system to define automated source-code changes. == Security considerations == Reflection may allow a user to create unexpected control flow paths through an application, potentially bypassing security measures. This may be exploited by attackers. Historical vulnerabilities in Java caused by unsafe reflection allowed code retrieved from potentially untrusted remote machines to break out of the Java sandbox security mechanism. A large scale study of 120 Java vulnerabilities in 2013 concluded that unsafe reflection is the most common vulnerability in Java, though not the most exploited. == Examples == The following code snippets create an instance foo of class Foo and invoke its method PrintHello. For each programming language, normal and reflection-based call sequences are shown. === Common Lisp === The following is an example in Common Lisp using the Common Lisp Object System: === C# === The following is an example in C#: === Delphi, Object Pascal === This Delphi and Object Pascal example assumes that a TFoo class has been declared in a unit called Unit1: === eC === The following is an example in eC: === Go === The following is an example in Go: === Java === The following is an example in Java: === JavaScript === The following is an example in JavaScript: === Julia === The following is an example in Julia: === Objective-C === The following is an example in Objective-C, implying either the OpenStep or Foundation Kit framework is used: === Perl === The following is an example in Perl: === PHP === The following is an example in PHP: === Python === The following is an example in Python: === R === The following is an example in R: === Ruby === The following is an example in Ruby: === Xojo === The following is an example using Xojo: == See also == List of reflective programming languages and platforms Mirror (programming) Programming paradigms Self-hosting (compilers) Self-modifying code Type introspection typeof == References == === Citations === === Sources === == Further reading == Ira R. Forman and Nate Forman, Java Reflection in Action (2005), ISBN 1-932394-18-4 Ira R. Forman and Scott Danforth, Putting Metaclasses to Work (1999), ISBN 0-201-43305-2 == External links == Reflection in logic, functional and object-oriented programming: a short comparative study An Introduction to Reflection-Oriented Programming Brian Foote's pages on Reflection in Smalltalk Java Reflection API Tutorial from Oracle
https://en.wikipedia.org/wiki/Reflective_programming
In computer science, extensible programming is a style of computer programming that focuses on mechanisms to extend the programming language, compiler, and runtime system (environment). Extensible programming languages, supporting this style of programming, were an active area of work in the 1960s, but the movement was marginalized in the 1970s. Extensible programming has become a topic of renewed interest in the 21st century. == Historical movement == The first paper usually associated with the extensible programming language movement is M. Douglas McIlroy's 1960 paper on macros for high-level programming languages. Another early description of the principle of extensibility occurs in Brooker and Morris's 1960 paper on the compiler-compiler. The peak of the movement was marked by two academic symposia, in 1969 and 1971. By 1975, a survey article on the movement by Thomas A. Standish was essentially a post mortem. The Forth was an exception, but it went essentially unnoticed. === Character of the historical movement === As typically envisioned, an extensible language consisted of a base language providing elementary computing facilities, and a metalanguage able to modify the base language. A program then consisted of metalanguage modifications and code in the modified base language. The most prominent language-extension technique used in the movement was macro definition. Grammar modification was also closely associated with the movement, resulting in the eventual development of adaptive grammar formalisms. The Lisp language community remained separate from the extensible language community, apparently because, as one researcher observed, any programming language in which programs and data are essentially interchangeable can be regarded as an extendible [sic] language. ... this can be seen very easily from the fact that Lisp has been used as an extendible language for years. At the 1969 conference, Simula was presented as an extensible language. Standish described three classes of language extension, which he named paraphrase, orthophrase, and metaphrase (otherwise paraphrase and metaphrase being translation terms). Paraphrase defines a facility by showing how to exchange it for something formerly defined (or to be defined). As examples, he mentions macro definitions, ordinary procedure definitions, grammatical extensions, data definitions, operator definitions, and control structure extensions. Orthophrase adds features to a language that could not be achieved using the base language, such as adding an input/output (I/O) system to a base language formerly with no I/O primitives. Extensions must be understood as orthophrase relative to some given base language, since a feature not defined in terms of the base language must be defined in terms of some other language. This corresponds to the modern notion of plug-ins. Metaphrase modifies the interpretation rules used for pre-existing expressions. This corresponds to the modern notion of reflective programming (reflection). === Death of the historical movement === Standish attributed the failure of the extensibility movement to the difficulty of programming successive extensions. A programmer might build a first shell of macros around a base language. Then, if a second shell of macros is built around that, any subsequent programmer must be intimately familiar with both the base language, and the first shell. A third shell would require familiarity with the base and both the first and second shells, and so on. Shielding a programmer from lower-level details is the intent of the abstraction movement that supplanted the extensibility movement. Despite the earlier presentation of Simula as extensible, by 1975, Standish's survey does not seem in practice to have included the newer abstraction-based technologies (though he used a very general definition of extensibility that technically could have included them). A 1978 history of programming abstraction from the invention of the computer until then, made no mention of macros, and gave no hint that the extensible languages movement had ever occurred. Macros were tentatively admitted into the abstraction movement by the late 1980s (perhaps due to the advent of hygienic macros), by being granted the pseudonym syntactic abstractions. == Modern movement == In the modern sense, a system that supports extensible programming will provide all of the features described below. === Extensible syntax === This simply means that the source language(s) to be compiled must not be closed, fixed, or static. It must be possible to add new keywords, concepts, and structures to the source language(s). Languages which allow the addition of constructs with user defined syntax include Coq, Racket, Camlp4, OpenC++, Seed7, Red, Rebol, and Felix. While it is acceptable for some fundamental and intrinsic language features to be immutable, the system must not rely solely on those language features. It must be possible to add new ones. === Extensible compiler === In extensible programming, a compiler is not a monolithic program that converts source code input into binary executable output. The compiler itself must be extensible to the point that it is really a collection of plugins that assist with the translation of source language input into anything. For example, an extensible compiler will support the generation of object code, code documentation, re-formatted source code, or any other desired output. The architecture of the compiler must permit its users to "get inside" the compilation process and provide alternative processing tasks at every reasonable step in the compilation process. For just the task of translating source code into something that can be executed on a computer, an extensible compiler should: use a plug-in or component architecture for nearly every aspect of its function determine which language or language variant is being compiled and locate the appropriate plug-in to recognize and validate that language use formal language specifications to syntactically and structurally validate arbitrary source languages assist with the semantic validation of arbitrary source languages by invoking an appropriate validation plug-in allow users to select from different kinds of code generators so that the resulting executable can be targeted for different processors, operating systems, virtual machines, or other execution environment. provide facilities for error generation and extensions to it allow new kinds of nodes in the abstract syntax tree (AST), allow new values in nodes of the AST, allow new kinds of edges between nodes, support the transformation of the input AST, or portions thereof, by some external "pass" support the translation of the input AST, or portions thereof, into another form by some external "pass" assist with the flow of information between internal and external passes as they both transform and translate the AST into new ASTs or other representations === Extensible runtime === At runtime, extensible programming systems must permit languages to extend the set of operations that it permits. For example, if the system uses a byte-code interpreter, it must allow new byte-code values to be defined. As with extensible syntax, it is acceptable for there to be some (smallish) set of fundamental or intrinsic operations that are immutable. However, it must be possible to overload or augment those intrinsic operations so that new or additional behavior can be supported. === Content separated from form === Extensible programming systems should regard programs as data to be processed. Those programs should be completely devoid of any kind of formatting information. The visual display and editing of programs to users should be a translation function, supported by the extensible compiler, that translates the program data into forms more suitable for viewing or editing. Naturally, this should be a two-way translation. This is important because it must be possible to easily process extensible programs in a variety of ways. It is unacceptable for the only uses of source language input to be editing, viewing and translation to machine code. The arbitrary processing of programs is facilitated by de-coupling the source input from specifications of how it should be processed (formatted, stored, displayed, edited, etc.). === Source language debugging support === Extensible programming systems must support the debugging of programs using the constructs of the original source language regardless of the extensions or transformation the program has undergone in order to make it executable. Most notably, it cannot be assumed that the only way to display runtime data is in structures or arrays. The debugger, or more correctly 'program inspector', must permit the display of runtime data in forms suitable to the source language. For example, if the language supports a data structure for a business process or work flow, it must be possible for the debugger to display that data structure as a fishbone chart or other form provided by a plugin. == Examples == Camlp4 Felix Nemerle Seed7 Rebol Red Ruby (metaprogramming) IMP OpenC++ XL XML Forth Lisp Racket Scheme Lua PL/I Smalltalk == See also == Adaptive grammar Concept programming Dialecting Grammar-oriented programming Language-oriented programming Homoiconicity == References == == External links == === General === Greg Wilson's Article in ACM Queue Slashdot Discussion Modern Extensible Languages Archived 2011-06-12 at the Wayback Machine – A paper from Daniel Zingaro === Tools === MetaL – an extensible programming compiler engine implementation XPS – eXtensible Programming System (in development) MPS – JetBrains Metaprogramming system === Languages with extensible syntax === OpenZz xtc – eXTensible C English-script Nemerle Macros Boo Syntactic Macros Stanford University Intermediate Format compiler Seed7 – The extensible programming language Katahdin – a language with syntax and semantics that are mutable at runtime π – a language with extensible syntax, implemented using an Earley parser
https://en.wikipedia.org/wiki/Extensible_programming
In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that map values to other values, rather than a sequence of imperative statements which update the running state of the program. In functional programming, functions are treated as first-class citizens, meaning that they can be bound to names (including local identifiers), passed as arguments, and returned from other functions, just as any other data type can. This allows programs to be written in a declarative and composable style, where small functions are combined in a modular manner. Functional programming is sometimes treated as synonymous with purely functional programming, a subset of functional programming that treats all functions as deterministic mathematical functions, or pure functions. When a pure function is called with some given arguments, it will always return the same result, and cannot be affected by any mutable state or other side effects. This is in contrast with impure procedures, common in imperative programming, which can have side effects (such as modifying the program's state or taking input from a user). Proponents of purely functional programming claim that by restricting side effects, programs can have fewer bugs, be easier to debug and test, and be more suited to formal verification. Functional programming has its roots in academia, evolving from the lambda calculus, a formal system of computation based only on functions. Functional programming has historically been less popular than imperative programming, but many functional languages are seeing use today in industry and education, including Common Lisp, Scheme, Clojure, Wolfram Language, Racket, Erlang, Elixir, OCaml, Haskell, and F#. Lean is a functional programming language commonly used for verifying mathematical theorems. Functional programming is also key to some languages that have found success in specific domains, like JavaScript in the Web, R in statistics, J, K and Q in financial analysis, and XQuery/XSLT for XML. Domain-specific declarative languages like SQL and Lex/Yacc use some elements of functional programming, such as not allowing mutable values. In addition, many other programming languages support programming in a functional style or have implemented features from functional programming, such as C++11, C#, Kotlin, Perl, PHP, Python, Go, Rust, Raku, Scala, and Java (since Java 8). == History == The lambda calculus, developed in the 1930s by Alonzo Church, is a formal system of computation built from function application. In 1937 Alan Turing proved that the lambda calculus and Turing machines are equivalent models of computation, showing that the lambda calculus is Turing complete. Lambda calculus forms the basis of all functional programming languages. An equivalent theoretical formulation, combinatory logic, was developed by Moses Schönfinkel and Haskell Curry in the 1920s and 1930s. Church later developed a weaker system, the simply typed lambda calculus, which extended the lambda calculus by assigning a data type to all terms. This forms the basis for statically typed functional programming. The first high-level functional programming language, Lisp, was developed in the late 1950s for the IBM 700/7000 series of scientific computers by John McCarthy while at Massachusetts Institute of Technology (MIT). Lisp functions were defined using Church's lambda notation, extended with a label construct to allow recursive functions. Lisp first introduced many paradigmatic features of functional programming, though early Lisps were multi-paradigm languages, and incorporated support for numerous programming styles as new paradigms evolved. Later dialects, such as Scheme and Clojure, and offshoots such as Dylan and Julia, sought to simplify and rationalise Lisp around a cleanly functional core, while Common Lisp was designed to preserve and update the paradigmatic features of the numerous older dialects it replaced. Information Processing Language (IPL), 1956, is sometimes cited as the first computer-based functional programming language. It is an assembly-style language for manipulating lists of symbols. It does have a notion of generator, which amounts to a function that accepts a function as an argument, and, since it is an assembly-level language, code can be data, so IPL can be regarded as having higher-order functions. However, it relies heavily on the mutating list structure and similar imperative features. Kenneth E. Iverson developed APL in the early 1960s, described in his 1962 book A Programming Language (ISBN 9780471430148). APL was the primary influence on John Backus's FP. In the early 1990s, Iverson and Roger Hui created J. In the mid-1990s, Arthur Whitney, who had previously worked with Iverson, created K, which is used commercially in financial industries along with its descendant Q. In the mid-1960s, Peter Landin invented SECD machine, the first abstract machine for a functional programming language, described a correspondence between ALGOL 60 and the lambda calculus, and proposed the ISWIM programming language. John Backus presented FP in his 1977 Turing Award lecture "Can Programming Be Liberated From the von Neumann Style? A Functional Style and its Algebra of Programs". He defines functional programs as being built up in a hierarchical way by means of "combining forms" that allow an "algebra of programs"; in modern language, this means that functional programs follow the principle of compositionality. Backus's paper popularized research into functional programming, though it emphasized function-level programming rather than the lambda-calculus style now associated with functional programming. The 1973 language ML was created by Robin Milner at the University of Edinburgh, and David Turner developed the language SASL at the University of St Andrews. Also in Edinburgh in the 1970s, Burstall and Darlington developed the functional language NPL. NPL was based on Kleene Recursion Equations and was first introduced in their work on program transformation. Burstall, MacQueen and Sannella then incorporated the polymorphic type checking from ML to produce the language Hope. ML eventually developed into several dialects, the most common of which are now OCaml and Standard ML. In the 1970s, Guy L. Steele and Gerald Jay Sussman developed Scheme, as described in the Lambda Papers and the 1985 textbook Structure and Interpretation of Computer Programs. Scheme was the first dialect of lisp to use lexical scoping and to require tail-call optimization, features that encourage functional programming. In the 1980s, Per Martin-Löf developed intuitionistic type theory (also called constructive type theory), which associated functional programs with constructive proofs expressed as dependent types. This led to new approaches to interactive theorem proving and has influenced the development of subsequent functional programming languages. The lazy functional language, Miranda, developed by David Turner, initially appeared in 1985 and had a strong influence on Haskell. With Miranda being proprietary, Haskell began with a consensus in 1987 to form an open standard for functional programming research; implementation releases have been ongoing as of 1990. More recently it has found use in niches such as parametric CAD in the OpenSCAD language built on the CGAL framework, although its restriction on reassigning values (all values are treated as constants) has led to confusion among users who are unfamiliar with functional programming as a concept. Functional programming continues to be used in commercial settings. == Concepts == A number of concepts and paradigms are specific to functional programming, and generally foreign to imperative programming (including object-oriented programming). However, programming languages often cater to several programming paradigms, so programmers using "mostly imperative" languages may have utilized some of these concepts. === First-class and higher-order functions === Higher-order functions are functions that can either take other functions as arguments or return them as results. In calculus, an example of a higher-order function is the differential operator d / d x {\displaystyle d/dx} , which returns the derivative of a function f {\displaystyle f} . Higher-order functions are closely related to first-class functions in that higher-order functions and first-class functions both allow functions as arguments and results of other functions. The distinction between the two is subtle: "higher-order" describes a mathematical concept of functions that operate on other functions, while "first-class" is a computer science term for programming language entities that have no restriction on their use (thus first-class functions can appear anywhere in the program that other first-class entities like numbers can, including as arguments to other functions and as their return values). Higher-order functions enable partial application or currying, a technique that applies a function to its arguments one at a time, with each application returning a new function that accepts the next argument. This lets a programmer succinctly express, for example, the successor function as the addition operator partially applied to the natural number one. === Pure functions === Pure functions (or expressions) have no side effects (memory or I/O). This means that pure functions have several useful properties, many of which can be used to optimize the code: If the result of a pure expression is not used, it can be removed without affecting other expressions. If a pure function is called with arguments that cause no side-effects, the result is constant with respect to that argument list (sometimes called referential transparency or idempotence), i.e., calling the pure function again with the same arguments returns the same result. (This can enable caching optimizations such as memoization.) If there is no data dependency between two pure expressions, their order can be reversed, or they can be performed in parallel and they cannot interfere with one another (in other terms, the evaluation of any pure expression is thread-safe). If the entire language does not allow side-effects, then any evaluation strategy can be used; this gives the compiler freedom to reorder or combine the evaluation of expressions in a program (for example, using deforestation). While most compilers for imperative programming languages detect pure functions and perform common-subexpression elimination for pure function calls, they cannot always do this for pre-compiled libraries, which generally do not expose this information, thus preventing optimizations that involve those external functions. Some compilers, such as gcc, add extra keywords for a programmer to explicitly mark external functions as pure, to enable such optimizations. Fortran 95 also lets functions be designated pure. C++11 added constexpr keyword with similar semantics. === Recursion === Iteration (looping) in functional languages is usually accomplished via recursion. Recursive functions invoke themselves, letting an operation be repeated until it reaches the base case. In general, recursion requires maintaining a stack, which consumes space in a linear amount to the depth of recursion. This could make recursion prohibitively expensive to use instead of imperative loops. However, a special form of recursion known as tail recursion can be recognized and optimized by a compiler into the same code used to implement iteration in imperative languages. Tail recursion optimization can be implemented by transforming the program into continuation passing style during compiling, among other approaches. The Scheme language standard requires implementations to support proper tail recursion, meaning they must allow an unbounded number of active tail calls. Proper tail recursion is not simply an optimization; it is a language feature that assures users that they can use recursion to express a loop and doing so would be safe-for-space. Moreover, contrary to its name, it accounts for all tail calls, not just tail recursion. While proper tail recursion is usually implemented by turning code into imperative loops, implementations might implement it in other ways. For example, Chicken intentionally maintains a stack and lets the stack overflow. However, when this happens, its garbage collector will claim space back, allowing an unbounded number of active tail calls even though it does not turn tail recursion into a loop. Common patterns of recursion can be abstracted away using higher-order functions, with catamorphisms and anamorphisms (or "folds" and "unfolds") being the most obvious examples. Such recursion schemes play a role analogous to built-in control structures such as loops in imperative languages. Most general purpose functional programming languages allow unrestricted recursion and are Turing complete, which makes the halting problem undecidable, can cause unsoundness of equational reasoning, and generally requires the introduction of inconsistency into the logic expressed by the language's type system. Some special purpose languages such as Coq allow only well-founded recursion and are strongly normalizing (nonterminating computations can be expressed only with infinite streams of values called codata). As a consequence, these languages fail to be Turing complete and expressing certain functions in them is impossible, but they can still express a wide class of interesting computations while avoiding the problems introduced by unrestricted recursion. Functional programming limited to well-founded recursion with a few other constraints is called total functional programming. === Strict versus non-strict evaluation === Functional languages can be categorized by whether they use strict (eager) or non-strict (lazy) evaluation, concepts that refer to how function arguments are processed when an expression is being evaluated. The technical difference is in the denotational semantics of expressions containing failing or divergent computations. Under strict evaluation, the evaluation of any term containing a failing subterm fails. For example, the expression: print length([2+1, 3*2, 1/0, 5-4]) fails under strict evaluation because of the division by zero in the third element of the list. Under lazy evaluation, the length function returns the value 4 (i.e., the number of items in the list), since evaluating it does not attempt to evaluate the terms making up the list. In brief, strict evaluation always fully evaluates function arguments before invoking the function. Lazy evaluation does not evaluate function arguments unless their values are required to evaluate the function call itself. The usual implementation strategy for lazy evaluation in functional languages is graph reduction. Lazy evaluation is used by default in several pure functional languages, including Miranda, Clean, and Haskell. Hughes 1984 argues for lazy evaluation as a mechanism for improving program modularity through separation of concerns, by easing independent implementation of producers and consumers of data streams. Launchbury 1993 describes some difficulties that lazy evaluation introduces, particularly in analyzing a program's storage requirements, and proposes an operational semantics to aid in such analysis. Harper 2009 proposes including both strict and lazy evaluation in the same language, using the language's type system to distinguish them. === Type systems === Especially since the development of Hindley–Milner type inference in the 1970s, functional programming languages have tended to use typed lambda calculus, rejecting all invalid programs at compilation time and risking false positive errors, as opposed to the untyped lambda calculus, that accepts all valid programs at compilation time and risks false negative errors, used in Lisp and its variants (such as Scheme), as they reject all invalid programs at runtime when the information is enough to not reject valid programs. The use of algebraic data types makes manipulation of complex data structures convenient; the presence of strong compile-time type checking makes programs more reliable in absence of other reliability techniques like test-driven development, while type inference frees the programmer from the need to manually declare types to the compiler in most cases. Some research-oriented functional languages such as Coq, Agda, Cayenne, and Epigram are based on intuitionistic type theory, which lets types depend on terms. Such types are called dependent types. These type systems do not have decidable type inference and are difficult to understand and program with. But dependent types can express arbitrary propositions in higher-order logic. Through the Curry–Howard isomorphism, then, well-typed programs in these languages become a means of writing formal mathematical proofs from which a compiler can generate certified code. While these languages are mainly of interest in academic research (including in formalized mathematics), they have begun to be used in engineering as well. Compcert is a compiler for a subset of the language C that is written in Coq and formally verified. A limited form of dependent types called generalized algebraic data types (GADT's) can be implemented in a way that provides some of the benefits of dependently typed programming while avoiding most of its inconvenience. GADT's are available in the Glasgow Haskell Compiler, in OCaml and in Scala, and have been proposed as additions to other languages including Java and C#. === Referential transparency === Functional programs do not have assignment statements, that is, the value of a variable in a functional program never changes once defined. This eliminates any chances of side effects because any variable can be replaced with its actual value at any point of execution. So, functional programs are referentially transparent. Consider C assignment statement x=x*10, this changes the value assigned to the variable x. Let us say that the initial value of x was 1, then two consecutive evaluations of the variable x yields 10 and 100 respectively. Clearly, replacing x=x*10 with either 10 or 100 gives a program a different meaning, and so the expression is not referentially transparent. In fact, assignment statements are never referentially transparent. Now, consider another function such as int plusone(int x) {return x+1;} is transparent, as it does not implicitly change the input x and thus has no such side effects. Functional programs exclusively use this type of function and are therefore referentially transparent. === Data structures === Purely functional data structures are often represented in a different way to their imperative counterparts. For example, the array with constant access and update times is a basic component of most imperative languages, and many imperative data-structures, such as the hash table and binary heap, are based on arrays. Arrays can be replaced by maps or random access lists, which admit purely functional implementation, but have logarithmic access and update times. Purely functional data structures have persistence, a property of keeping previous versions of the data structure unmodified. In Clojure, persistent data structures are used as functional alternatives to their imperative counterparts. Persistent vectors, for example, use trees for partial updating. Calling the insert method will result in some but not all nodes being created. == Comparison to imperative programming == Functional programming is very different from imperative programming. The most significant differences stem from the fact that functional programming avoids side effects, which are used in imperative programming to implement state and I/O. Pure functional programming completely prevents side-effects and provides referential transparency. Higher-order functions are rarely used in older imperative programming. A traditional imperative program might use a loop to traverse and modify a list. A functional program, on the other hand, would probably use a higher-order "map" function that takes a function and a list, generating and returning a new list by applying the function to each list item. === Imperative vs. functional programming === The following two examples (written in JavaScript) achieve the same effect: they multiply all even numbers in an array by 10 and add them all, storing the final sum in the variable result. Traditional imperative loop: Functional programming with higher-order functions: Sometimes the abstractions offered by functional programming might lead to development of more robust code that avoids certain issues that might arise when building upon large amount of complex, imperative code, such as off-by-one errors (see Greenspun's tenth rule). === Simulating state === There are tasks (for example, maintaining a bank account balance) that often seem most naturally implemented with state. Pure functional programming performs these tasks, and I/O tasks such as accepting user input and printing to the screen, in a different way. The pure functional programming language Haskell implements them using monads, derived from category theory. Monads offer a way to abstract certain types of computational patterns, including (but not limited to) modeling of computations with mutable state (and other side effects such as I/O) in an imperative manner without losing purity. While existing monads may be easy to apply in a program, given appropriate templates and examples, many students find them difficult to understand conceptually, e.g., when asked to define new monads (which is sometimes needed for certain types of libraries). Functional languages also simulate states by passing around immutable states. This can be done by making a function accept the state as one of its parameters, and return a new state together with the result, leaving the old state unchanged. Impure functional languages usually include a more direct method of managing mutable state. Clojure, for example, uses managed references that can be updated by applying pure functions to the current state. This kind of approach enables mutability while still promoting the use of pure functions as the preferred way to express computations. Alternative methods such as Hoare logic and uniqueness have been developed to track side effects in programs. Some modern research languages use effect systems to make the presence of side effects explicit. === Efficiency issues === Functional programming languages are typically less efficient in their use of CPU and memory than imperative languages such as C and Pascal. This is related to the fact that some mutable data structures like arrays have a very straightforward implementation using present hardware. Flat arrays may be accessed very efficiently with deeply pipelined CPUs, prefetched efficiently through caches (with no complex pointer chasing), or handled with SIMD instructions. It is also not easy to create their equally efficient general-purpose immutable counterparts. For purely functional languages, the worst-case slowdown is logarithmic in the number of memory cells used, because mutable memory can be represented by a purely functional data structure with logarithmic access time (such as a balanced tree). However, such slowdowns are not universal. For programs that perform intensive numerical computations, functional languages such as OCaml and Clean are only slightly slower than C according to The Computer Language Benchmarks Game. For programs that handle large matrices and multidimensional databases, array functional languages (such as J and K) were designed with speed optimizations. Immutability of data can in many cases lead to execution efficiency by allowing the compiler to make assumptions that are unsafe in an imperative language, thus increasing opportunities for inline expansion. Even if the involved copying that may seem implicit when dealing with persistent immutable data structures might seem computationally costly, some functional programming languages, like Clojure solve this issue by implementing mechanisms for safe memory sharing between formally immutable data. Rust distinguishes itself by its approach to data immutability which involves immutable references and a concept called lifetimes. Immutable data with separation of identity and state and shared-nothing schemes can also potentially be more well-suited for concurrent and parallel programming by the virtue of reducing or eliminating the risk of certain concurrency hazards, since concurrent operations are usually atomic and this allows eliminating the need for locks. This is how for example java.util.concurrent classes are implemented, where some of them are immutable variants of the corresponding classes that are not suitable for concurrent use. Functional programming languages often have a concurrency model that instead of shared state and synchronization, leverages message passing mechanisms (such as the actor model, where each actor is a container for state, behavior, child actors and a message queue). This approach is common in Erlang/Elixir or Akka. Lazy evaluation may also speed up the program, even asymptotically, whereas it may slow it down at most by a constant factor (however, it may introduce memory leaks if used improperly). Launchbury 1993 discusses theoretical issues related to memory leaks from lazy evaluation, and O'Sullivan et al. 2008 give some practical advice for analyzing and fixing them. However, the most general implementations of lazy evaluation making extensive use of dereferenced code and data perform poorly on modern processors with deep pipelines and multi-level caches (where a cache miss may cost hundreds of cycles) . ==== Abstraction cost ==== Some functional programming languages might not optimize abstractions such as higher order functions like "map" or "filter" as efficiently as the underlying imperative operations. Consider, as an example, the following two ways to check if 5 is an even number in Clojure: When benchmarked using the Criterium tool on a Ryzen 7900X GNU/Linux PC in a Leiningen REPL 2.11.2, running on Java VM version 22 and Clojure version 1.11.1, the first implementation, which is implemented as: has the mean execution time of 4.76 ms, while the second one, in which .equals is a direct invocation of the underlying Java method, has a mean execution time of 2.8 μs – roughly 1700 times faster. Part of that can be attributed to the type checking and exception handling involved in the implementation of even?. For instance the lo library for Go, which implements various higher-order functions common in functional programming languages using generics. In a benchmark provided by the library's author, calling map is 4% slower than an equivalent for loop and has the same allocation profile, which can be attributed to various compiler optimizations, such as inlining. One distinguishing feature of Rust are zero-cost abstractions. This means that using them imposes no additional runtime overhead. This is achieved thanks to the compiler using loop unrolling, where each iteration of a loop, be it imperative or using iterators, is converted into a standalone Assembly instruction, without the overhead of the loop controlling code. If an iterative operation writes to an array, the resulting array's elements will be stored in specific CPU registers, allowing for constant-time access at runtime. === Functional programming in non-functional languages === It is possible to use a functional style of programming in languages that are not traditionally considered functional languages. For example, both D and Fortran 95 explicitly support pure functions. JavaScript, Lua, Python and Go had first class functions from their inception. Python had support for "lambda", "map", "reduce", and "filter" in 1994, as well as closures in Python 2.2, though Python 3 relegated "reduce" to the functools standard library module. First-class functions have been introduced into other mainstream languages such as Perl 5.0 in 1994, PHP 5.3, Visual Basic 9, C# 3.0, C++11, and Kotlin. In Perl, lambda, map, reduce, filter, and closures are fully supported and frequently used. The book Higher-Order Perl, released in 2005, was written to provide an expansive guide on using Perl for functional programming. In PHP, anonymous classes, closures and lambdas are fully supported. Libraries and language extensions for immutable data structures are being developed to aid programming in the functional style. In Java, anonymous classes can sometimes be used to simulate closures; however, anonymous classes are not always proper replacements to closures because they have more limited capabilities. Java 8 supports lambda expressions as a replacement for some anonymous classes. In C#, anonymous classes are not necessary, because closures and lambdas are fully supported. Libraries and language extensions for immutable data structures are being developed to aid programming in the functional style in C#. Many object-oriented design patterns are expressible in functional programming terms: for example, the strategy pattern simply dictates use of a higher-order function, and the visitor pattern roughly corresponds to a catamorphism, or fold. Similarly, the idea of immutable data from functional programming is often included in imperative programming languages, for example the tuple in Python, which is an immutable array, and Object.freeze() in JavaScript. == Comparison to logic programming == Logic programming can be viewed as a generalisation of functional programming, in which functions are a special case of relations. For example, the function, mother(X) = Y, (every X has only one mother Y) can be represented by the relation mother(X, Y). Whereas functions have a strict input-output pattern of arguments, relations can be queried with any pattern of inputs and outputs. Consider the following logic program: The program can be queried, like a functional program, to generate mothers from children: But it can also be queried backwards, to generate children: It can even be used to generate all instances of the mother relation: Compared with relational syntax, functional syntax is a more compact notation for nested functions. For example, the definition of maternal grandmother in functional syntax can be written in the nested form: The same definition in relational notation needs to be written in the unnested form: Here :- means if and , means and. However, the difference between the two representations is simply syntactic. In Ciao Prolog, relations can be nested, like functions in functional programming: Ciao transforms the function-like notation into relational form and executes the resulting logic program using the standard Prolog execution strategy. == Applications == === Text editors === Emacs, a highly extensible text editor family uses its own Lisp dialect for writing plugins. The original author of the most popular Emacs implementation, GNU Emacs and Emacs Lisp, Richard Stallman considers Lisp one of his favorite programming languages. Helix, since version 24.03 supports previewing AST as S-expressions, which are also the core feature of the Lisp programming language family. === Spreadsheets === Spreadsheets can be considered a form of pure, zeroth-order, strict-evaluation functional programming system. However, spreadsheets generally lack higher-order functions as well as code reuse, and in some implementations, also lack recursion. Several extensions have been developed for spreadsheet programs to enable higher-order and reusable functions, but so far remain primarily academic in nature. === Microservices === Due to their composability, functional programming paradigms can be suitable for microservices-based architectures. === Academia === Functional programming is an active area of research in the field of programming language theory. There are several peer-reviewed publication venues focusing on functional programming, including the International Conference on Functional Programming, the Journal of Functional Programming, and the Symposium on Trends in Functional Programming. === Industry === Functional programming has been employed in a wide range of industrial applications. For example, Erlang, which was developed by the Swedish company Ericsson in the late 1980s, was originally used to implement fault-tolerant telecommunications systems, but has since become popular for building a range of applications at companies such as Nortel, Facebook, Électricité de France and WhatsApp. Scheme, a dialect of Lisp, was used as the basis for several applications on early Apple Macintosh computers and has been applied to problems such as training-simulation software and telescope control. OCaml, which was introduced in the mid-1990s, has seen commercial use in areas such as financial analysis, driver verification, industrial robot programming and static analysis of embedded software. Haskell, though initially intended as a research language, has also been applied in areas such as aerospace systems, hardware design and web programming. Other functional programming languages that have seen use in industry include Scala, F#, Wolfram Language, Lisp, Standard ML and Clojure. Scala has been widely used in Data science, while ClojureScript, Elm or PureScript are some of the functional frontend programming languages used in production. Elixir's Phoenix framework is also used by some relatively popular commercial projects, such as Font Awesome or Allegro (one of the biggest e-commerce platforms in Poland)'s classified ads platform Allegro Lokalnie. Functional "platforms" have been popular in finance for risk analytics (particularly with large investment banks). Risk factors are coded as functions that form interdependent graphs (categories) to measure correlations in market shifts, similar in manner to Gröbner basis optimizations but also for regulatory frameworks such as Comprehensive Capital Analysis and Review. Given the use of OCaml and Caml variations in finance, these systems are sometimes considered related to a categorical abstract machine. Functional programming is heavily influenced by category theory. === Education === Many universities teach functional programming. Some treat it as an introductory programming concept while others first teach imperative programming methods. Outside of computer science, functional programming is used to teach problem-solving, algebraic and geometric concepts. It has also been used to teach classical mechanics, as in the book Structure and Interpretation of Classical Mechanics. In particular, Scheme has been a relatively popular choice for teaching programming for years. == See also == Eager evaluation Functional reactive programming Inductive functional programming List of functional programming languages List of functional programming topics Nested function Purely functional programming == Notes and references == == Further reading == Abelson, Hal; Sussman, Gerald Jay (1985). Structure and Interpretation of Computer Programs. MIT Press. Bibcode:1985sicp.book.....A. Cousineau, Guy and Michel Mauny. The Functional Approach to Programming. Cambridge, UK: Cambridge University Press, 1998. Curry, Haskell Brooks and Feys, Robert and Craig, William. Combinatory Logic. Volume I. North-Holland Publishing Company, Amsterdam, 1958. Curry, Haskell B.; Hindley, J. Roger; Seldin, Jonathan P. (1972). Combinatory Logic. Vol. II. Amsterdam: North Holland. ISBN 978-0-7204-2208-5. Dominus, Mark Jason. Higher-Order Perl. Morgan Kaufmann. 2005. Felleisen, Matthias; Findler, Robert; Flatt, Matthew; Krishnamurthi, Shriram (2018). How to Design Programs. MIT Press. Graham, Paul. ANSI Common LISP. Englewood Cliffs, New Jersey: Prentice Hall, 1996. MacLennan, Bruce J. Functional Programming: Practice and Theory. Addison-Wesley, 1990. Michaelson, Greg (10 April 2013). An Introduction to Functional Programming Through Lambda Calculus. Courier Corporation. ISBN 978-0-486-28029-5. O'Sullivan, Brian; Stewart, Don; Goerzen, John (2008). Real World Haskell. O'Reilly. Pratt, Terrence W. and Marvin Victor Zelkowitz. Programming Languages: Design and Implementation. 3rd ed. Englewood Cliffs, New Jersey: Prentice Hall, 1996. Salus, Peter H. Functional and Logic Programming Languages. Vol. 4 of Handbook of Programming Languages. Indianapolis, Indiana: Macmillan Technical Publishing, 1998. Thompson, Simon. Haskell: The Craft of Functional Programming. Harlow, England: Addison-Wesley Longman Limited, 1996. == External links == Ford, Neal. "Functional thinking". Retrieved 2021-11-10. Akhmechet, Slava (2006-06-19). "defmacro – Functional Programming For The Rest of Us". Retrieved 2013-02-24. An introduction Functional programming in Python (by David Mertz): part 1, part 2, part 3
https://en.wikipedia.org/wiki/Functional_programming
Inductive programming (IP) is a special area of automatic programming, covering research from artificial intelligence and programming, which addresses learning of typically declarative (logic or functional) and often recursive programs from incomplete specifications, such as input/output examples or constraints. Depending on the programming language used, there are several kinds of inductive programming. Inductive functional programming, which uses functional programming languages such as Lisp or Haskell, and most especially inductive logic programming, which uses logic programming languages such as Prolog and other logical representations such as description logics, have been more prominent, but other (programming) language paradigms have also been used, such as constraint programming or probabilistic programming. == Definition == Inductive programming incorporates all approaches which are concerned with learning programs or algorithms from incomplete (formal) specifications. Possible inputs in an IP system are a set of training inputs and corresponding outputs or an output evaluation function, describing the desired behavior of the intended program, traces or action sequences which describe the process of calculating specific outputs, constraints for the program to be induced concerning its time efficiency or its complexity, various kinds of background knowledge such as standard data types, predefined functions to be used, program schemes or templates describing the data flow of the intended program, heuristics for guiding the search for a solution or other biases. Output of an IP system is a program in some arbitrary programming language containing conditionals and loop or recursive control structures, or any other kind of Turing-complete representation language. In many applications the output program must be correct with respect to the examples and partial specification, and this leads to the consideration of inductive programming as a special area inside automatic programming or program synthesis, usually opposed to 'deductive' program synthesis, where the specification is usually complete. In other cases, inductive programming is seen as a more general area where any declarative programming or representation language can be used and we may even have some degree of error in the examples, as in general machine learning, the more specific area of structure mining or the area of symbolic artificial intelligence. A distinctive feature is the number of examples or partial specification needed. Typically, inductive programming techniques can learn from just a few examples. The diversity of inductive programming usually comes from the applications and the languages that are used: apart from logic programming and functional programming, other programming paradigms and representation languages have been used or suggested in inductive programming, such as functional logic programming, constraint programming, probabilistic programming, abductive logic programming, modal logic, action languages, agent languages and many types of imperative languages. == History == Research on the inductive synthesis of recursive functional programs started in the early 1970s and was brought onto firm theoretical foundations with the seminal THESIS system of Summers and work of Biermann. These approaches were split into two phases: first, input-output examples are transformed into non-recursive programs (traces) using a small set of basic operators; second, regularities in the traces are searched for and used to fold them into a recursive program. The main results until the mid-1980s are surveyed by Smith. Due to limited progress with respect to the range of programs that could be synthesized, research activities decreased significantly in the next decade. The advent of logic programming brought a new elan but also a new direction in the early 1980s, especially due to the MIS system of Shapiro eventually spawning the new field of inductive logic programming (ILP). The early works of Plotkin, and his "relative least general generalization (rlgg)", had an enormous impact in inductive logic programming. Most of ILP work addresses a wider class of problems, as the focus is not only on recursive logic programs but on machine learning of symbolic hypotheses from logical representations. However, there were some encouraging results on learning recursive Prolog programs such as quicksort from examples together with suitable background knowledge, for example with GOLEM. But again, after initial success, the community got disappointed by limited progress about the induction of recursive programs with ILP less and less focusing on recursive programs and leaning more and more towards a machine learning setting with applications in relational data mining and knowledge discovery. In parallel to work in ILP, Koza proposed genetic programming in the early 1990s as a generate-and-test based approach to learning programs. The idea of genetic programming was further developed into the inductive programming system ADATE and the systematic-search-based system MagicHaskeller. Here again, functional programs are learned from sets of positive examples together with an output evaluation (fitness) function which specifies the desired input/output behavior of the program to be learned. The early work in grammar induction (also known as grammatical inference) is related to inductive programming, as rewriting systems or logic programs can be used to represent production rules. In fact, early works in inductive inference considered grammar induction and Lisp program inference as basically the same problem. The results in terms of learnability were related to classical concepts, such as identification-in-the-limit, as introduced in the seminal work of Gold. More recently, the language learning problem was addressed by the inductive programming community. In the recent years, the classical approaches have been resumed and advanced with great success. Therefore, the synthesis problem has been reformulated on the background of constructor-based term rewriting systems taking into account modern techniques of functional programming, as well as moderate use of search-based strategies and usage of background knowledge as well as automatic invention of subprograms. Many new and successful applications have recently appeared beyond program synthesis, most especially in the area of data manipulation, programming by example and cognitive modelling (see below). Other ideas have also been explored with the common characteristic of using declarative languages for the representation of hypotheses. For instance, the use of higher-order features, schemes or structured distances have been advocated for a better handling of recursive data types and structures; abstraction has also been explored as a more powerful approach to cumulative learning and function invention. One powerful paradigm that has been recently used for the representation of hypotheses in inductive programming (generally in the form of generative models) is probabilistic programming (and related paradigms, such as stochastic logic programs and Bayesian logic programming). == Application areas == The first workshop on Approaches and Applications of Inductive Programming (AAIP) held in conjunction with ICML 2005 identified all applications where "learning of programs or recursive rules are called for, [...] first in the domain of software engineering where structural learning, software assistants and software agents can help to relieve programmers from routine tasks, give programming support for end users, or support of novice programmers and programming tutor systems. Further areas of application are language learning, learning recursive control rules for AI-planning, learning recursive concepts in web-mining or for data-format transformations". Since then, these and many other areas have shown to be successful application niches for inductive programming, such as end-user programming, the related areas of programming by example and programming by demonstration, and intelligent tutoring systems. Other areas where inductive inference has been recently applied are knowledge acquisition, artificial general intelligence, reinforcement learning and theory evaluation, and cognitive science in general. There may also be prospective applications in intelligent agents, games, robotics, personalisation, ambient intelligence and human interfaces. == See also == Evolutionary programming Inductive reasoning Test-driven development == References == == Further reading == == External links == Inductive Programming community page, hosted by the University of Bamberg.
https://en.wikipedia.org/wiki/Inductive_programming
Extreme programming (XP) is a software development methodology intended to improve software quality and responsiveness to changing customer requirements. As a type of agile software development, it advocates frequent releases in short development cycles, intended to improve productivity and introduce checkpoints at which new customer requirements can be adopted. Other elements of extreme programming include programming in pairs or doing extensive code review, unit testing of all code, not programming features until they are actually needed, a flat management structure, code simplicity and clarity, expecting changes in the customer's requirements as time passes and the problem is better understood, and frequent communication with the customer and among programmers. The methodology takes its name from the idea that the beneficial elements of traditional software engineering practices are taken to "extreme" levels. As an example, code reviews are considered a beneficial practice; taken to the extreme, code can be reviewed continuously (i.e. the practice of pair programming). == History == Kent Beck developed extreme programming during his work on the Chrysler Comprehensive Compensation System (C3) payroll project. Beck became the C3 project leader in March 1996. He began to refine the development methodology used in the project and wrote a book on the methodology (Extreme Programming Explained, published in October 1999). Chrysler cancelled the C3 project in February 2000, after seven years, when Daimler-Benz acquired the company. Ward Cunningham was another major influence on XP. Many extreme-programming practices have been around for some time; the methodology takes "best practices" to extreme levels. For example, the "practice of test-first development, planning and writing tests before each micro-increment" was used as early as NASA's Project Mercury, in the early 1960s. To shorten the total development time, some formal test documents (such as for acceptance testing) have been developed in parallel with (or shortly before) the software being ready for testing. A NASA independent test group can write the test procedures, based on formal requirements and logical limits, before programmers write the software and integrate it with the hardware. XP takes this concept to the extreme level, writing automated tests (sometimes inside software modules) which validate the operation of even small sections of software coding, rather than only testing the larger features. === Origins === Two major influences shaped software development in the 1990s: Internally, object-oriented programming replaced procedural programming as the programming paradigm favored by some developers. Externally, the rise of the Internet and the dot-com boom emphasized speed-to-market and company growth as competitive business factors. Rapidly changing requirements demanded shorter product life-cycles, and often clashed with traditional methods of software development. The Chrysler Comprehensive Compensation System (C3) started in order to determine the best way to use object technologies, using the payroll systems at Chrysler as the object of research, with Smalltalk as the language and GemStone as the data access layer. Chrysler brought in Kent Beck, a prominent Smalltalk practitioner, to do performance tuning on the system, but his role expanded as he noted several problems with the development process. He took this opportunity to propose and implement some changes in development practices - based on his work with his frequent collaborator, Ward Cunningham. Beck describes the early conception of the methods: The first time I was asked to lead a team, I asked them to do a little bit of the things I thought were sensible, like testing and reviews. The second time there was a lot more on the line. I thought, "Damn the torpedoes, at least this will make a good article," [and] asked the team to crank up all the knobs to 10 on the things I thought were essential and leave out everything else. Beck invited Ron Jeffries to the project to help develop and refine these methods. Jeffries thereafter acted as a coach to instill the practices as habits in the C3 team. Information about the principles and practices behind XP disseminated to the wider world through discussions on the original wiki, Cunningham's WikiWikiWeb. Various contributors discussed and expanded upon the ideas, and some spin-off methodologies resulted (see agile software development). Also, XP concepts have been explained, for several years, using a hypertext system map on the XP website at http://www.extremeprogramming.org c. 1999. Beck edited a series of books on XP, beginning with his own Extreme Programming Explained (1999, ISBN 0-201-61641-6), spreading his ideas to a much larger audience. Authors in the series went through various aspects attending XP and its practices. The series included a book critical of the practices. === Current state === XP generated significant interest among software communities in the late 1990s and early 2000s, seeing adoption in a number of environments radically different from its origins. The high discipline required by the original practices often went by the wayside, causing some of these practices, such as those thought too rigid, to be deprecated or reduced, or even left unfinished, on individual sites. For example, the practice of end-of-day integration tests for a particular project could be changed to an end-of-week schedule, or simply reduced to testing on mutually agreed dates. Such a more relaxed schedule could avoid people feeling rushed to generate artificial stubs just to pass the end-of-day testing. A less-rigid schedule allows, instead, the development of complex features over a period of several days. Meanwhile, other agile-development practices have not stood still, and as of 2019 XP continues to evolve, assimilating more lessons from experiences in the field, to use other practices. In the second edition of Extreme Programming Explained (November 2004), five years after the first edition, Beck added more values and practices and differentiated between primary and corollary practices. == Concept == === Goals === Extreme Programming Explained describes extreme programming as a software-development discipline that organizes people to produce higher-quality software more productively. XP attempts to reduce the cost of changes in requirements by having multiple short development cycles, rather than a long one. In this doctrine, changes are a natural, inescapable and desirable aspect of software-development projects, and should be planned for, instead of attempting to define a stable set of requirements. Extreme programming also introduces a number of basic values, principles and practices on top of the agile methodology. === Activities === XP describes four basic activities that are performed within the software development process: coding, testing, listening, and designing. Each of those activities is described below. ==== Coding ==== The advocates of XP argue that the only truly important product of the system development process is code – software instructions that a computer can interpret. Without code, there is no working product. Coding can be used to figure out the most suitable solution. Coding can also help to communicate thoughts about programming problems. A programmer dealing with a complex programming problem, or finding it hard to explain the solution to fellow programmers, might code it in a simplified manner and use the code to demonstrate what they mean. Code, say the proponents of this position, is always clear and concise and cannot be interpreted in more than one way. Other programmers can give feedback on this code by also coding their thoughts. ==== Testing ==== Testing is central to extreme programming. Extreme programming's approach is that if a little testing can eliminate a few flaws, a lot of testing can eliminate many more flaws. Unit tests determine whether a given feature works as intended. Programmers write as many automated tests as they can think of that might "break" the code; if all tests run successfully, then the coding is complete. Every piece of code that is written is tested before moving on to the next feature. Acceptance tests verify that the requirements as understood by the programmers satisfy the customer's actual requirements. System-wide integration testing was encouraged, initially, as a daily end-of-day activity, for early detection of incompatible interfaces, to reconnect before the separate sections diverged widely from coherent functionality. However, system-wide integration testing has been reduced, to weekly, or less often, depending on the stability of the overall interfaces in the system. ==== Listening ==== Programmers must listen to what the customers need the system to do, what "business logic" is needed. They must understand these needs well enough to give the customer feedback about the technical aspects of how the problem might be solved, or cannot be solved. Communication between the customer and programmer is further addressed in the planning game. ==== Designing ==== From the point of view of simplicity, of course one could say that system development doesn't need more than coding, testing and listening. If those activities are performed well, the result should always be a system that works. In practice, this will not work. One can come a long way without designing but at a given time one will get stuck. The system becomes too complex and the dependencies within the system cease to be clear. One can avoid this by creating a design structure that organizes the logic in the system. Good design will avoid many dependencies within a system; this means that changing one part of the system will not affect other parts of the system. === Values === Extreme programming initially recognized four values in 1999: communication, simplicity, feedback, and courage. A new value, respect, was added in the second edition of Extreme Programming Explained. Those five values are described below. ==== Communication ==== Building software systems requires communicating system requirements to the developers of the system. In formal software development methodologies, this task is accomplished through documentation. Extreme programming techniques can be viewed as methods for rapidly building and disseminating institutional knowledge among members of a development team. The goal is to give all developers a shared view of the system which matches the view held by the users of the system. To this end, extreme programming favors simple designs, common metaphors, collaboration of users and programmers, frequent verbal communication, and feedback. ==== Simplicity ==== Extreme programming encourages starting with the simplest solution. Extra functionality can then be added later. The difference between this approach and more conventional system development methods is the focus on designing and coding for the needs of today instead of those of tomorrow, next week, or next month. This is sometimes summed up as the "You aren't gonna need it" (YAGNI) approach. Proponents of XP acknowledge the disadvantage that this can sometimes entail more effort tomorrow to change the system; their claim is that this is more than compensated for by the advantage of not investing in possible future requirements that might change before they become relevant. Coding and designing for uncertain future requirements implies the risk of spending resources on something that might not be needed, while perhaps delaying crucial features. Related to the "communication" value, simplicity in design and coding should improve the quality of communication. A simple design with very simple code could be easily understood by most programmers in the team. ==== Feedback ==== Within extreme programming, feedback relates to different dimensions of the system development: Feedback from the system: by writing unit tests, or running periodic integration tests, the programmers have direct feedback from the state of the system after implementing changes. Feedback from the customer: The functional tests (aka acceptance tests) are written by the customer and the testers. They will get concrete feedback about the current state of their system. This review is planned once in every two or three weeks so the customer can easily steer the development. Feedback from the team: When customers come up with new requirements in the planning game the team directly gives an estimation of the time that it will take to implement. Feedback is closely related to communication and simplicity. Flaws in the system are easily communicated by writing a unit test that proves a certain piece of code will break. The direct feedback from the system tells programmers to recode this part. A customer is able to test the system periodically according to the functional requirements, known as user stories. To quote Kent Beck, "Optimism is an occupational hazard of programming. Feedback is the treatment." ==== Courage ==== Several practices embody courage. One is the commandment to always design and code for today and not for tomorrow. This is an effort to avoid getting bogged down in design and requiring a lot of effort to implement anything else. Courage enables developers to feel comfortable with refactoring their code when necessary. This means reviewing the existing system and modifying it so that future changes can be implemented more easily. Another example of courage is knowing when to throw code away: courage to remove source code that is obsolete, no matter how much effort was used to create that source code. Also, courage means persistence: a programmer might be stuck on a complex problem for an entire day, then solve the problem quickly the next day, but only if they are persistent. ==== Respect ==== The respect value includes respect for others as well as self-respect. Programmers should never commit changes that break compilation, that make existing unit-tests fail, or that otherwise delay the work of their peers. Members respect their own work by always striving for high quality and seeking for the best design for the solution at hand through refactoring. Adopting the four earlier values leads to respect gained from others in the team. Nobody on the team should feel unappreciated or ignored. This ensures a high level of motivation and encourages loyalty toward the team and toward the goal of the project. This value is dependent upon the other values, and is oriented toward teamwork. === Rules === The first version of rules for XP was published in 1999 by Don Wells at the XP website. 29 rules are given in the categories of planning, managing, designing, coding, and testing. Planning, managing and designing are called out explicitly to counter claims that XP doesn't support those activities. Another version of XP rules was proposed by Ken Auer in XP/Agile Universe 2003. He felt XP was defined by its rules, not its practices (which are subject to more variation and ambiguity). He defined two categories: "Rules of Engagement" which dictate the environment in which software development can take place effectively, and "Rules of Play" which define the minute-by-minute activities and rules within the framework of the Rules of Engagement. Here are some of the rules (incomplete): Coding The customer is always available Code the unit test first Only one pair integrates code at a time Leave optimization until last No overtime Testing All code must have unit tests All code must pass all unit tests before it can be released. When a bug is found, tests are created before the bug is addressed (a bug is not an error in logic; it is a test that was not written) Acceptance tests are run often and the results are published === Principles === The principles that form the basis of XP are based on the values just described and are intended to foster decisions in a system development project. The principles are intended to be more concrete than the values and more easily translated to guidance in a practical situation. ==== Feedback ==== Extreme programming sees feedback as most useful if it is done frequently and promptly. It stresses that minimal delay between an action and its feedback is critical to learning and making changes. Unlike traditional system development methods, contact with the customer occurs in more frequent iterations. The customer has clear insight into the system that is being developed, and can give feedback and steer the development as needed. With frequent feedback from the customer, a mistaken design decision made by the developer will be noticed and corrected quickly, before the developer spends much time implementing it. Unit tests contribute to the rapid feedback principle. When writing code, running the unit test provides direct feedback as to how the system reacts to the changes made. This includes running not only the unit tests that test the developer's code, but running in addition all unit tests against all the software, using an automated process that can be initiated by a single command. That way, if the developer's changes cause a failure in some other portion of the system that the developer knows little or nothing about, the automated all-unit-test suite will reveal the failure immediately, alerting the developer of the incompatibility of their change with other parts of the system, and the necessity of removing or modifying their change. Under traditional development practices, the absence of an automated, comprehensive unit-test suite meant that such a code change, assumed harmless by the developer, would have been left in place, appearing only during integration testing – or worse, only in production; and determining which code change caused the problem, among all the changes made by all the developers during the weeks or even months previous to integration testing, was a formidable task. ==== Assuming simplicity ==== This is about treating every problem as if its solution were "extremely simple". Traditional system development methods say to plan for the future and to code for reusability. Extreme programming rejects these ideas. The advocates of extreme programming say that making big changes all at once does not work. Extreme programming applies incremental changes: for example, a system might have small releases every three weeks. When many little steps are made, the customer has more control over the development process and the system that is being developed. ==== Embracing change ==== The principle of embracing change is about not working against changes but embracing them. For instance, if at one of the iterative meetings it appears that the customer's requirements have changed dramatically, programmers are to embrace this and plan the new requirements for the next iteration. == Practices == Extreme programming has been described as having 12 practices, grouped into four areas: === Fine-scale feedback === Pair programming Planning game Test-driven development Whole team === Continuous process === Continuous integration Refactoring or design improvement Small releases === Shared understanding === Coding standards Collective code ownership Simple design System metaphor === Programmer welfare === Sustainable pace == Controversial aspects == The practices in XP have been heavily debated. Proponents of extreme programming claim that by having the on-site customer request changes informally, the process becomes flexible, and saves the cost of formal overhead. Critics of XP claim this can lead to costly rework and project scope creep beyond what was previously agreed or funded. Change-control boards are a sign that there are potential conflicts in project objectives and constraints between multiple users. XP's expedited methods are somewhat dependent on programmers being able to assume a unified client viewpoint so the programmer can concentrate on coding, rather than documentation of compromise objectives and constraints. This also applies when multiple programming organizations are involved, particularly organizations which compete for shares of projects. Other potentially controversial aspects of extreme programming include: Requirements are expressed as automated acceptance tests rather than specification documents. Requirements are defined incrementally, rather than trying to get them all in advance. Software developers are usually required to work in pairs. There is no big design up front. Most of the design activity takes place on the fly and incrementally, starting with "the simplest thing that could possibly work" and adding complexity only when it's required by failing tests. Critics characterize this as "debugging a system into appearance" and fear this will result in more re-design effort than only re-designing when requirements change. A customer representative is attached to the project. This role can become a single-point-of-failure for the project, and some people have found it to be a source of stress. Also, there is the danger of micro-management by a non-technical representative trying to dictate the use of technical software features and architecture. Critics have noted several potential drawbacks, including problems with unstable requirements, no documented compromises of user conflicts, and a lack of an overall design specification or document. === Scalability === Thoughtworks has claimed reasonable success on distributed XP projects with up to sixty people. In 2004, industrial extreme programming (IXP) was introduced as an evolution of XP. It is intended to bring the ability to work in large and distributed teams. It now has 23 practices and flexible values. === Severability and responses === In 2003, Matt Stephens and Doug Rosenberg published Extreme Programming Refactored: The Case Against XP, which questioned the value of the XP process and suggested ways in which it could be improved. This triggered a lengthy debate in articles, Internet newsgroups, and web-site chat areas. The core argument of the book is that XP's practices are interdependent but that few practical organizations are willing/able to adopt all the practices; therefore the entire process fails. The book also makes other criticisms, and it draws a likeness of XP's "collective ownership" model to socialism in a negative manner. Certain aspects of XP have changed since the publication of Extreme Programming Refactored; in particular, XP now accommodates modifications to the practices as long as the required objectives are still met. XP also uses increasingly generic terms for processes. Some argue that these changes invalidate previous criticisms; others claim that this is simply watering the process down. Other authors have tried to reconcile XP with the older methodologies in order to form a unified methodology. Some of these XP sought to replace, such as the waterfall methodology; example Project Lifecycles: Waterfall, Rapid Application Development (RAD), etc. JPMorgan Chase & Co. tried combining XP with the computer programming methods of capability maturity model integration (CMMI), and Six Sigma. They found that the three systems reinforced each other well, leading to better development, and did not mutually contradict. == Criticism == Extreme programming's initial buzz and controversial tenets, such as pair programming and continuous design, have attracted particular criticisms, such as the ones coming from McBreen, Boehm and Turner, Matt Stephens and Doug Rosenberg. Many of the criticisms, however, are believed by Agile practitioners to be misunderstandings of agile development. In particular, extreme programming has been reviewed and critiqued by Matt Stephens's and Doug Rosenberg's Extreme Programming Refactored. == See also == Agile software development Continuous obsolescence EXtreme Manufacturing Extreme project management Extreme programming practices Kaizen List of software development philosophies Pair programming Scrum (development) Software craftsmanship Stand-up meeting Timeboxing == References == == Further reading == Ken Auer and Roy Miller. Extreme Programming Applied: Playing To Win, Addison–Wesley. Ken Auer; Ron Jeffries; Jeff Canna; Glen B. Alleman; Lisa Crispin; Janet Gregory (2002). "Are Testers eXtinct? How Can Testers Contribute to XP Teams?". Extreme Programming and Agile Methods — XP/Agile Universe 2002. Lecture Notes in Computer Science. Vol. 2418. Springer-Verlag. p. 287. doi:10.1007/3-540-45672-4_50. ISBN 978-3-540-44024-6. Kent Beck: Extreme Programming Explained: Embrace Change, Addison–Wesley. First edition, 1999. Second edition, with Cynthia Andres, 2004. Kent Beck and Martin Fowler: Planning Extreme Programming, Addison–Wesley. Alistair Cockburn: Agile Software Development, Addison–Wesley. Martin Fowler: Refactoring: Improving the Design of Existing Code.With Kent Beck, John Brant, William Opdyke, and Don Roberts (1999). Addison-Wesley. Harvey Herela (2005). Case Study: The Chrysler Comprehensive Compensation System. Galen Lab, U.C. Irvine. Jim Highsmith. Agile Software Development Ecosystems, Addison–Wesley. Ron Jeffries, Ann Anderson and Chet Hendrickson (2000), Extreme Programming Installed, Addison–Wesley. Larman, C.; Basili, V.R. (June 2003). "Iterative and incremental developments. a brief history" (PDF). Computer. 36 (6): 47–56. doi:10.1109/MC.2003.1204375. Matt Stephens and Doug Rosenberg (2003). Extreme Programming Refactored: The Case Against XP, Apress. Waldner, JB. (2008). "Nanocomputers and Swarm Intelligence". In: ISTE, 225–256. == External links == A gentle introduction Industrial eXtreme Programming Problems and Solutions to XP implementation Using an Agile Software Process with Offshore Development – ThoughtWorks' experiences with implementing XP in large distributed projects
https://en.wikipedia.org/wiki/Extreme_programming
Ajax (also AJAX ; short for "asynchronous JavaScript and XML") is a set of web development techniques that uses various web technologies on the client-side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously (in the background) without interfering with the display and behaviour of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows web pages and, by extension, web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly utilize JSON instead of XML. Ajax is not a technology, but rather a programming pattern. HTML and CSS can be used in combination to mark up and style information. The webpage can be modified by JavaScript to dynamically display (and allow the user to interact with) the new information. The built-in XMLHttpRequest object is used to execute Ajax on webpages, allowing websites to load content onto the screen without refreshing the page. Ajax is not a new technology, nor is it a new language. Instead, it is existing technologies used in a new way. == History == In the early-to-mid 1990s, most Websites were based on complete HTML pages. Each user action required a complete new page to be loaded from the server. This process was inefficient, as reflected by the user experience: all page content disappeared, then the new page appeared. Each time the browser reloaded a page because of a partial change, all the content had to be re-sent, even though only some of the information had changed. This placed additional load on the server and made bandwidth a limiting factor in performance. In 1996, the iframe tag was introduced by Internet Explorer; like the object element, it can load a part of the web page asynchronously. In 1998, the Microsoft Outlook Web Access team developed the concept behind the XMLHttpRequest scripting object. It appeared as XMLHTTP in the second version of the MSXML library, which shipped with Internet Explorer 5.0 in March 1999. The functionality of the Windows XMLHTTP ActiveX control in IE 5 was later implemented by Mozilla Firefox, Safari, Opera, Google Chrome, and other browsers as the XMLHttpRequest JavaScript object. Microsoft adopted the native XMLHttpRequest model as of Internet Explorer 7. The ActiveX version is still supported in Internet Explorer and on "Internet Explorer mode" in Microsoft Edge. The utility of these background HTTP requests and asynchronous Web technologies remained fairly obscure until it started appearing in large scale online applications such as Outlook Web Access (2000) and Oddpost (2002). Google made a wide deployment of standards-compliant, cross browser Ajax with Gmail (2004) and Google Maps (2005). In October 2004 Kayak.com's public beta release was among the first large-scale e-commerce uses of what their developers at that time called "the xml http thing". This increased interest in Ajax among web program developers. The term AJAX was publicly used on 18 February 2005 by Jesse James Garrett in an article titled Ajax: A New Approach to Web Applications, based on techniques used on Google pages. On 5 April 2006, the World Wide Web Consortium (W3C) released the first draft specification for the XMLHttpRequest object in an attempt to create an official Web standard. The latest draft of the XMLHttpRequest object was published on 6 October 2016, and the XMLHttpRequest specification is now a living standard. == Technologies == The term Ajax has come to represent a broad group of Web technologies that can be used to implement a Web application that communicates with a server in the background, without interfering with the current state of the page. In the article that coined the term Ajax, Jesse James Garrett explained that the following technologies are incorporated: HTML (or XHTML) and CSS for presentation The Document Object Model (DOM) for dynamic display of and interaction with data JSON or XML for the interchange of data, and XSLT for XML manipulation The XMLHttpRequest object for asynchronous communication JavaScript to bring these technologies together Since then, however, there have been a number of developments in the technologies used in an Ajax application, and in the definition of the term Ajax itself. XML is no longer required for data interchange and, therefore, XSLT is no longer required for the manipulation of data. JavaScript Object Notation (JSON) is often used as an alternative format for data interchange, although other formats such as preformatted HTML or plain text can also be used. A variety of popular JavaScript libraries, including jQuery, include abstractions to assist in executing Ajax requests. == Examples == === JavaScript example === An example of a simple Ajax request using the GET method, written in JavaScript. get-ajax-data.js: send-ajax-data.php: === Fetch example === Fetch is a native JavaScript API. According to Google Developers Documentation, "Fetch makes it easier to make web requests and handle responses than with the older XMLHttpRequest." ==== ES7 async/await example ==== Fetch relies on JavaScript promises. The fetch specification differs from Ajax in the following significant ways: The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the Promise will resolve normally (with the ok property of the response set to false if the response isn't in the range 200–299), and it will only reject on network failure or if anything prevented the request from completing. fetch() won't send cross-origin cookies unless you set the credentials init option. (Since April 2018. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.) == Benefits == Ajax offers several benefits that can significantly enhance web application performance and user experience. By reducing server traffic and improving speed, Ajax plays a crucial role in modern web development. One key advantage of Ajax is its capacity to render web applications without requiring data retrieval, resulting in reduced server traffic. This optimization minimizes response times on both the server and client sides, eliminating the need for users to endure loading screens. Furthermore, Ajax facilitates asynchronous processing by simplifying the utilization of XmlHttpRequest, which enables efficient handling of requests for asynchronous data retrieval. Additionally, the dynamic loading of content enhances the application's performance significantly. Besides, Ajax enjoys broad support across all major web browsers, including Microsoft Internet Explorer versions 5 and above, Mozilla Firefox versions 1.0 and beyond, Opera versions 7.6 and above, and Apple Safari versions 1.2 and higher. == See also == == References == == External links == [1] Ajax: A New Approach to Web applications - Article that coined the Ajax term and Q&A Ajax Tutorial with GET, POST, text and XML examples.
https://en.wikipedia.org/wiki/Ajax_(programming)
In computer science, imperative programming is a programming paradigm of software that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program consists of commands for the computer to perform. Imperative programming focuses on describing how a program operates step by step (generally order of the steps being determined in source code by the placement of statements one below the other), rather than on high-level descriptions of its expected results. The term is often used in contrast to declarative programming, which focuses on what the program should accomplish without specifying all the details of how the program should achieve the result. == Procedural programming == Procedural programming is a type of imperative programming in which the program is built from one or more procedures (also termed subroutines or functions). The terms are often used as synonyms, but the use of procedures has a dramatic effect on how imperative programs appear and how they are constructed. Heavy procedural programming, in which state changes are localized to procedures or restricted to explicit arguments and returns from procedures, is a form of structured programming. Since the 1960s, structured programming and modular programming in general have been promoted as techniques to improve the maintainability and overall quality of imperative programs. The concepts behind object-oriented programming attempt to extend this approach. Procedural programming could be considered a step toward declarative programming. A programmer can often tell, simply by looking at the names, arguments, and return types of procedures (and related comments), what a particular procedure is supposed to do, without necessarily looking at the details of how it achieves its result. At the same time, a complete program is still imperative since it fixes the statements to be executed and their order of execution to a large extent. == Rationale and foundations of imperative programming == The programming paradigm used to build programs for almost all computers typically follows an imperative model. Digital computer hardware is designed to execute machine code, which is native to the computer and is usually written in the imperative style, although low-level compilers and interpreters using other paradigms exist for some architectures such as lisp machines. From this low-level perspective, the program state is defined by the contents of memory, and the statements are instructions in the native machine language of the computer. Higher-level imperative languages use variables and more complex statements, but still follow the same paradigm. Recipes and process checklists, while not computer programs, are also familiar concepts that are similar in style to imperative programming; each step is an instruction, and the physical world holds the state. Since the basic ideas of imperative programming are both conceptually familiar and directly embodied in the hardware, most computer languages are in the imperative style. Assignment statements, in imperative paradigm, perform an operation on information located in memory and store the results in memory for later use. High-level imperative languages, in addition, permit the evaluation of complex expressions, which may consist of a combination of arithmetic operations and function evaluations, and the assignment of the resulting value to memory. Looping statements (as in while loops, do while loops, and for loops) allow a sequence of statements to be executed multiple times. Loops can either execute the statements they contain a predefined number of times, or they can execute them repeatedly until some condition is met. Conditional branching statements allow a sequence of statements to be executed only if some condition is met. Otherwise, the statements are skipped and the execution sequence continues from the statement following them. Unconditional branching statements allow an execution sequence to be transferred to another part of a program. These include the jump (called goto in many languages), switch, and the subprogram, subroutine, or procedure call (which usually returns to the next statement after the call). Early in the development of high-level programming languages, the introduction of the block enabled the construction of programs in which a group of statements and declarations could be treated as if they were one statement. This, alongside the introduction of subroutines, enabled complex structures to be expressed by hierarchical decomposition into simpler procedural structures. Many imperative programming languages (such as Fortran, BASIC, and C) are abstractions of assembly language. == History of imperative and object-oriented languages == The earliest imperative languages were the machine languages of the original computers. In these languages, instructions were very simple, which made hardware implementation easier but hindered the creation of complex programs. FORTRAN, developed by John Backus at International Business Machines (IBM) starting in 1954, was the first major programming language to remove the obstacles presented by machine code in the creation of complex programs. FORTRAN was a compiled language that allowed named variables, complex expressions, subprograms, and many other features now common in imperative languages. The next two decades saw the development of many other major high-level imperative programming languages. In the late 1950s and 1960s, ALGOL was developed in order to allow mathematical algorithms to be more easily expressed and even served as the operating system's target language for some computers. MUMPS (1966) carried the imperative paradigm to a logical extreme, by not having any statements at all, relying purely on commands, even to the extent of making the IF and ELSE commands independent of each other, connected only by an intrinsic variable named $TEST. COBOL (1960) and BASIC (1964) were both attempts to make programming syntax look more like English. In the 1970s, Pascal was developed by Niklaus Wirth, and C was created by Dennis Ritchie while he was working at Bell Laboratories. Wirth went on to design Modula-2 and Oberon. For the needs of the United States Department of Defense, Jean Ichbiah and a team at Honeywell began designing Ada in 1978, after a 4-year project to define the requirements for the language. The specification was first published in 1983, with revisions in 1995, 2005, and 2012. The 1980s saw a rapid growth in interest in object-oriented programming. These languages were imperative in style, but added features to support objects. The last two decades of the 20th century saw the development of many such languages. Smalltalk-80, originally conceived by Alan Kay in 1969, was released in 1980, by the Xerox Palo Alto Research Center (PARC). Drawing from concepts in another object-oriented language—Simula (which is considered the world's first object-oriented programming language, developed in the 1960s)—Bjarne Stroustrup designed C++, an object-oriented language based on C. Design of C++ began in 1979 and the first implementation was completed in 1983. In the late 1980s and 1990s, the notable imperative languages drawing on object-oriented concepts were Perl, released by Larry Wall in 1987; Python, released by Guido van Rossum in 1990; Visual Basic and Visual C++ (which included Microsoft Foundation Class Library (MFC) 2.0), released by Microsoft in 1991 and 1993 respectively; PHP, released by Rasmus Lerdorf in 1994; Java, by James Gosling (Sun Microsystems) in 1995, JavaScript, by Brendan Eich (Netscape), and Ruby, by Yukihiro "Matz" Matsumoto, both released in 1995. Microsoft's .NET Framework (2002) is imperative at its core, as are its main target languages, VB.NET and C# that run on it; however Microsoft's F#, a functional language, also runs on it. == Examples == === Fortran === FORTRAN (1958) was unveiled as "The IBM Mathematical FORmula TRANslating system." It was designed for scientific calculations, without string handling facilities. Along with declarations, expressions, and statements, it supported: arrays subroutines "do" loops It succeeded because: programming and debugging costs were below computer running costs it was supported by IBM applications at the time were scientific. However, non IBM vendors also wrote Fortran compilers, but with a syntax that would likely fail IBM's compiler. The American National Standards Institute (ANSI) developed the first Fortran standard in 1966. In 1978, Fortran 77 became the standard until 1991. Fortran 90 supports: records pointers to arrays === COBOL === COBOL (1959) stands for "COmmon Business Oriented Language." Fortran manipulated symbols. It was soon realized that symbols did not need to be numbers, so strings were introduced. The US Department of Defense influenced COBOL's development, with Grace Hopper being a major contributor. The statements were English-like and verbose. The goal was to design a language so managers could read the programs. However, the lack of structured statements hindered this goal. COBOL's development was tightly controlled, so dialects did not emerge to require ANSI standards. As a consequence, it was not changed for 15 years until 1974. The 1990s version did make consequential changes, like object-oriented programming. === Algol === ALGOL (1960) stands for "ALGOrithmic Language." It had a profound influence on programming language design. Emerging from a committee of European and American programming language experts, it used standard mathematical notation and had a readable structured design. Algol was first to define its syntax using the Backus–Naur form. This led to syntax-directed compilers. It added features like: block structure, where variables were local to their block arrays with variable bounds "for" loops functions recursion Algol's direct descendants include Pascal, Modula-2, Ada, Delphi and Oberon on one branch. On another branch there's C, C++ and Java. === Basic === BASIC (1964) stands for "Beginner's All Purpose Symbolic Instruction Code." It was developed at Dartmouth College for all of their students to learn. If a student did not go on to a more powerful language, the student would still remember Basic. A Basic interpreter was installed in the microcomputers manufactured in the late 1970s. As the microcomputer industry grew, so did the language. Basic pioneered the interactive session. It offered operating system commands within its environment: The 'new' command created an empty slate Statements evaluated immediately Statements could be programmed by preceding them with a line number The 'list' command displayed the program The 'run' command executed the program However, the Basic syntax was too simple for large programs. Recent dialects added structure and object-oriented extensions. Microsoft's Visual Basic is still widely used and produces a graphical user interface. === C === C programming language (1973) got its name because the language BCPL was replaced with B, and AT&T Bell Labs called the next version "C." Its purpose was to write the UNIX operating system. C is a relatively small language -- making it easy to write compilers. Its growth mirrored the hardware growth in the 1980s. Its growth also was because it has the facilities of assembly language, but uses a high-level syntax. It added advanced features like: inline assembler arithmetic on pointers pointers to functions bit operations freely combining complex operators C allows the programmer to control in which region of memory data is to be stored. Global variables and static variables require the fewest clock cycles to store. The stack is automatically used for the standard variable declarations. Heap memory is returned to a pointer variable from the malloc() function. The global and static data region is located just above the program region. (The program region is technically called the text region. It's where machine instructions are stored.) The global and static data region is technically two regions. One region is called the initialized data segment, where variables declared with default values are stored. The other region is called the block started by segment, where variables declared without default values are stored. Variables stored in the global and static data region have their addresses set at compile-time. They retain their values throughout the life of the process. The global and static region stores the global variables that are declared on top of (outside) the main() function. Global variables are visible to main() and every other function in the source code. On the other hand, variable declarations inside of main(), other functions, or within { } block delimiters are local variables. Local variables also include formal parameter variables. Parameter variables are enclosed within the parenthesis of function definitions. They provide an interface to the function. Local variables declared using the static prefix are also stored in the global and static data region. Unlike global variables, static variables are only visible within the function or block. Static variables always retain their value. An example usage would be the function int increment_counter(){ static int counter = 0; counter++; return counter;} The stack region is a contiguous block of memory located near the top memory address. Variables placed in the stack are populated from top to bottom. A stack pointer is a special-purpose register that keeps track of the last memory address populated. Variables are placed into the stack via the assembly language PUSH instruction. Therefore, the addresses of these variables are set during runtime. The method for stack variables to lose their scope is via the POP instruction. Local variables declared without the static prefix, including formal parameter variables, are called automatic variables and are stored in the stack. They are visible inside the function or block and lose their scope upon exiting the function or block. The heap region is located below the stack. It is populated from the bottom to the top. The operating system manages the heap using a heap pointer and a list of allocated memory blocks. Like the stack, the addresses of heap variables are set during runtime. An out of memory error occurs when the heap pointer and the stack pointer meet. C provides the malloc() library function to allocate heap memory. Populating the heap with data is an additional copy function. Variables stored in the heap are economically passed to functions using pointers. Without pointers, the entire block of data would have to be passed to the function via the stack. === C++ === In the 1970s, software engineers needed language support to break large projects down into modules. One obvious feature was to decompose large projects physically into separate files. A less obvious feature was to decompose large projects logically into abstract datatypes. At the time, languages supported concrete (scalar) datatypes like integer numbers, floating-point numbers, and strings of characters. Concrete datatypes have their representation as part of their name. Abstract datatypes are structures of concrete datatypes — with a new name assigned. For example, a list of integers could be called integer_list. In object-oriented jargon, abstract datatypes are called classes. However, a class is only a definition; no memory is allocated. When memory is allocated to a class, it's called an object. Object-oriented imperative languages developed by combining the need for classes and the need for safe functional programming. A function, in an object-oriented language, is assigned to a class. An assigned function is then referred to as a method, member function, or operation. Object-oriented programming is executing operations on objects. Object-oriented languages support a syntax to model subset/superset relationships. In set theory, an element of a subset inherits all the attributes contained in the superset. For example, a student is a person. Therefore, the set of students is a subset of the set of persons. As a result, students inherit all the attributes common to all persons. Additionally, students have unique attributes that other persons don't have. Object-oriented languages model subset/superset relationships using inheritance. Object-oriented programming became the dominant language paradigm by the late 1990s. C++ (1985) was originally called "C with Classes." It was designed to expand C's capabilities by adding the object-oriented facilities of the language Simula. An object-oriented module is composed of two files. The definitions file is called the header file. Here is a C++ header file for the GRADE class in a simple school application: A constructor operation is a function with the same name as the class name. It is executed when the calling operation executes the new statement. A module's other file is the source file. Here is a C++ source file for the GRADE class in a simple school application: Here is a C++ header file for the PERSON class in a simple school application: Here is a C++ source file for the PERSON class in a simple school application: Here is a C++ header file for the STUDENT class in a simple school application: Here is a C++ source file for the STUDENT class in a simple school application: Here is a driver program for demonstration: Here is a makefile to compile everything: == See also == Functional programming Reactive programming History of programming languages List of imperative programming languages == Notes == == References == Pratt, Terrence W. and Marvin V. Zelkowitz. Programming Languages: Design and Implementation, 3rd ed. Englewood Cliffs, N.J.: Prentice Hall, 1996. Sebesta, Robert W. Concepts of Programming Languages, 3rd ed. Reading, Mass.: Addison-Wesley Publishing Company, 1996. Originally based on the article 'Imperative programming' by Stan Seibert, from Nupedia, licensed under the GNU Free Documentation License.
https://en.wikipedia.org/wiki/Imperative_programming
Java is a high-level, general-purpose, memory-safe, object-oriented programming language. It is intended to let programmers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need to recompile. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of the underlying computer architecture. The syntax of Java is similar to C and C++, but has fewer low-level facilities than either of them. The Java runtime provides dynamic capabilities (such as reflection and runtime code modification) that are typically not available in traditional compiled languages. Java gained popularity shortly after its release, and has been a popular programming language since then. Java was the third most popular programming language in 2022 according to GitHub. Although still widely popular, there has been a gradual decline in use of Java in recent years with other languages using JVM gaining popularity. Java was designed by James Gosling at Sun Microsystems. It was released in May 1995 as a core component of Sun's Java platform. The original and reference implementation Java compilers, virtual machines, and class libraries were released by Sun under proprietary licenses. As of May 2007, in compliance with the specifications of the Java Community Process, Sun had relicensed most of its Java technologies under the GPL-2.0-only license. Oracle, which bought Sun in 2010, offers its own HotSpot Java Virtual Machine. However, the official reference implementation is the OpenJDK JVM, which is open-source software used by most developers and is the default JVM for almost all Linux distributions. Java 24 is the version current as of March 2025. Java 8, 11, 17, and 21 are long-term support versions still under maintenance. == History == James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. Java was originally designed for interactive television, but it was too advanced for the digital cable television industry at the time. The language was initially called Oak after an oak tree that stood outside Gosling's office. Later the project went by the name Green and was finally renamed Java, from Java coffee, a type of coffee from Indonesia. Gosling designed Java with a C/C++-style syntax that system and application programmers would find familiar. Sun Microsystems released the first public implementation as Java 1.0 in 1996. It promised write once, run anywhere (WORA) functionality, providing no-cost run-times on popular platforms. Fairly secure and featuring configurable security, it allowed network- and file-access restrictions. Major web browsers soon incorporated the ability to run Java applets within web pages, and Java quickly became popular. The Java 1.0 compiler was re-written in Java by Arthur van Hoff to comply strictly with the Java 1.0 language specification. With the advent of Java 2 (released initially as J2SE 1.2 in December 1998 – 1999), new versions had multiple configurations built for different types of platforms. J2EE included technologies and APIs for enterprise applications typically run in server environments, while J2ME featured APIs optimized for mobile applications. The desktop version was renamed J2SE. In 2006, for marketing purposes, Sun renamed new J2 versions as Java EE, Java ME, and Java SE, respectively. In 1997, Sun Microsystems approached the ISO/IEC JTC 1 standards body and later the Ecma International to formalize Java, but it soon withdrew from the process. Java remains a de facto standard, controlled through the Java Community Process. At one time, Sun made most of its Java implementations available without charge, despite their proprietary software status. Sun generated revenue from Java through the selling of licenses for specialized products such as the Java Enterprise System. On November 13, 2006, Sun released much of its Java virtual machine (JVM) as free and open-source software (FOSS), under the terms of the GPL-2.0-only license. On May 8, 2007, Sun finished the process, making all of its JVM's core code available under free software/open-source distribution terms, aside from a small portion of code to which Sun did not hold the copyright. Sun's vice-president Rich Green said that Sun's ideal role with regard to Java was as an evangelist. Following Oracle Corporation's acquisition of Sun Microsystems in 2009–10, Oracle has described itself as the steward of Java technology with a relentless commitment to fostering a community of participation and transparency. This did not prevent Oracle from filing a lawsuit against Google shortly after that for using Java inside the Android SDK (see the Android section). On April 2, 2010, James Gosling resigned from Oracle. In January 2016, Oracle announced that Java run-time environments based on JDK 9 will discontinue the browser plugin. Java software runs on most devices from laptops to data centers, game consoles to scientific supercomputers. Oracle (and others) highly recommend uninstalling outdated and unsupported versions of Java, due to unresolved security issues in older versions. === Principles === There were five primary goals in creating the Java language: It must be simple, object-oriented, and familiar. It must be robust and secure. It must be architecture-neutral and portable. It must execute with high performance. It must be interpreted, threaded, and dynamic. === Versions === As of November 2024, Java 8, 11, 17, and 21 are supported as long-term support (LTS) versions, with Java 25, releasing in September 2025, as the next scheduled LTS version. Oracle released the last zero-cost public update for the legacy version Java 8 LTS in January 2019 for commercial use, although it will otherwise still support Java 8 with public updates for personal use indefinitely. Other vendors such as Adoptium continue to offer free builds of OpenJDK's long-term support (LTS) versions. These builds may include additional security patches and bug fixes. Major release versions of Java, along with their release dates: == Editions == Sun has defined and supports four editions of Java targeting different application environments and segmented many of its APIs so that they belong to one of the platforms. The platforms are: Java Card for smart-cards. Java Platform, Micro Edition (Java ME) – targeting environments with limited resources. Java Platform, Standard Edition (Java SE) – targeting workstation environments. Java Platform, Enterprise Edition (Java EE) – targeting large distributed enterprise or Internet environments. The classes in the Java APIs are organized into separate groups called packages. Each package contains a set of related interfaces, classes, subpackages and exceptions. Sun also provided an edition called Personal Java that has been superseded by later, standards-based Java ME configuration-profile pairings. == Execution system == === Java JVM and bytecode === One design goal of Java is portability, which means that programs written for the Java platform must run similarly on any combination of hardware and operating system with adequate run time support. This is achieved by compiling the Java language code to an intermediate representation called Java bytecode, instead of directly to architecture-specific machine code. Java bytecode instructions are analogous to machine code, but they are intended to be executed by a virtual machine (VM) written specifically for the host hardware. End-users commonly use a Java Runtime Environment (JRE) installed on their device for standalone Java applications or a web browser for Java applets. Standard libraries provide a generic way to access host-specific features such as graphics, threading, and networking. The use of universal bytecode makes porting simple. However, the overhead of interpreting bytecode into machine instructions made interpreted programs almost always run more slowly than native executables. Just-in-time (JIT) compilers that compile byte-codes to machine code during runtime were introduced from an early stage. Java's Hotspot compiler is actually two compilers in one; and with GraalVM (included in e.g. Java 11, but removed as of Java 16) allowing tiered compilation. Java itself is platform-independent and is adapted to the particular platform it is to run on by a Java virtual machine (JVM), which translates the Java bytecode into the platform's machine language. ==== Performance ==== Programs written in Java have a reputation for being slower and requiring more memory than those written in C++. However, Java programs' execution speed improved significantly with the introduction of just-in-time compilation in 1997/1998 for Java 1.1, the addition of language features supporting better code analysis (such as inner classes, the StringBuilder class, optional assertions, etc.), and optimizations in the Java virtual machine, such as HotSpot becoming Sun's default JVM in 2000. With Java 1.5, the performance was improved with the addition of the java.util.concurrent package, including lock-free implementations of the ConcurrentMaps and other multi-core collections, and it was improved further with Java 1.6. === Non-JVM === Some platforms offer direct hardware support for Java; there are micro controllers that can run Java bytecode in hardware instead of a software Java virtual machine, and some ARM-based processors could have hardware support for executing Java bytecode through their Jazelle option, though support has mostly been dropped in current implementations of ARM. === Automatic memory management === Java uses an automatic garbage collector to manage memory in the object lifecycle. The programmer determines when objects are created, and the Java runtime is responsible for recovering the memory once objects are no longer in use. Once no references to an object remain, the unreachable memory becomes eligible to be freed automatically by the garbage collector. Something similar to a memory leak may still occur if a programmer's code holds a reference to an object that is no longer needed, typically when objects that are no longer needed are stored in containers that are still in use. If methods for a non-existent object are called, a null pointer exception is thrown. One of the ideas behind Java's automatic memory management model is that programmers can be spared the burden of having to perform manual memory management. In some languages, memory for the creation of objects is implicitly allocated on the stack or explicitly allocated and deallocated from the heap. In the latter case, the responsibility of managing memory resides with the programmer. If the program does not deallocate an object, a memory leak occurs. If the program attempts to access or deallocate memory that has already been deallocated, the result is undefined and difficult to predict, and the program is likely to become unstable or crash. This can be partially remedied by the use of smart pointers, but these add overhead and complexity. Garbage collection does not prevent logical memory leaks, i.e. those where the memory is still referenced but never used. Garbage collection may happen at any time. Ideally, it will occur when a program is idle. It is guaranteed to be triggered if there is insufficient free memory on the heap to allocate a new object; this can cause a program to stall momentarily. Explicit memory management is not possible in Java. Java does not support C/C++ style pointer arithmetic, where object addresses can be arithmetically manipulated (e.g. by adding or subtracting an offset). This allows the garbage collector to relocate referenced objects and ensures type safety and security. As in C++ and some other object-oriented languages, variables of Java's primitive data types are either stored directly in fields (for objects) or on the stack (for methods) rather than on the heap, as is commonly true for non-primitive data types (but see escape analysis). This was a conscious decision by Java's designers for performance reasons. Java contains multiple types of garbage collectors. Since Java 9, HotSpot uses the Garbage First Garbage Collector (G1GC) as the default. However, there are also several other garbage collectors that can be used to manage the heap, such as the Z Garbage Collector (ZGC) introduced in Java 11, and Shenandoah GC, introduced in Java 12 but unavailable in Oracle-produced OpenJDK builds. Shenandoah is instead available in third-party builds of OpenJDK, such as Eclipse Temurin. For most applications in Java, G1GC is sufficient. In prior versions of Java, such as Java 8, the Parallel Garbage Collector was used as the default garbage collector. Having solved the memory management problem does not relieve the programmer of the burden of handling properly other kinds of resources, like network or database connections, file handles, etc., especially in the presence of exceptions. == Syntax == The syntax of Java is largely influenced by C++ and C. Unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built almost exclusively as an object-oriented language. All code is written inside classes, and every data item is an object, with the exception of the primitive data types, (i.e. integers, floating-point numbers, boolean values, and characters), which are not objects for performance reasons. Java reuses some popular aspects of C++ (such as the printf method). Unlike C++, Java does not support operator overloading or multiple inheritance for classes, though multiple inheritance is supported for interfaces. Java uses comments similar to those of C++. There are three different styles of comments: a single line style marked with two slashes (//), a multiple line style opened with /* and closed with */, and the Javadoc commenting style opened with /** and closed with */. The Javadoc style of commenting allows the user to run the Javadoc executable to create documentation for the program and can be read by some integrated development environments (IDEs) such as Eclipse to allow developers to access documentation within the IDE. === Hello world === The following is a simple example of a "Hello, World!" program that writes a message to the standard output: == Special classes == === Applet === Java applets were programs embedded in other applications, mainly in web pages displayed in web browsers. The Java applet API was deprecated with the release of Java 9 in 2017. === Servlet === Java servlet technology provides Web developers with a simple, consistent mechanism for extending the functionality of a Web server and for accessing existing business systems. Servlets are server-side Java EE components that generate responses to requests from clients. Most of the time, this means generating HTML pages in response to HTTP requests, although there are a number of other standard servlet classes available, for example for WebSocket communication. The Java servlet API has to some extent been superseded (but still used under the hood) by two standard Java technologies for web services: the Java API for RESTful Web Services (JAX-RS 2.0) useful for AJAX, JSON and REST services, and the Java API for XML Web Services (JAX-WS) useful for SOAP Web Services. Typical implementations of these APIs on Application Servers or Servlet Containers use a standard servlet for handling all interactions with the HTTP requests and responses that delegate to the web service methods for the actual business logic. === JavaServer Pages === JavaServer Pages (JSP) are server-side Java EE components that generate responses, typically HTML pages, to HTTP requests from clients. JSPs embed Java code in an HTML page by using the special delimiters <% and %>. A JSP is compiled to a Java servlet, a Java application in its own right, the first time it is accessed. After that, the generated servlet creates the response. === Swing application === Swing is a graphical user interface library for the Java SE platform. It is possible to specify a different look and feel through the pluggable look and feel system of Swing. Clones of Windows, GTK+, and Motif are supplied by Sun. Apple also provides an Aqua look and feel for macOS. Where prior implementations of these looks and feels may have been considered lacking, Swing in Java SE 6 addresses this problem by using more native GUI widget drawing routines of the underlying platforms. === JavaFX application === JavaFX is a software platform for creating and delivering desktop applications, as well as rich web applications that can run across a wide variety of devices. JavaFX is intended to replace Swing as the standard graphical user interface (GUI) library for Java SE, but since JDK 11 JavaFX has not been in the core JDK and instead in a separate module. JavaFX has support for desktop computers and web browsers on Microsoft Windows, Linux, and macOS. JavaFX does not have support for native OS look and feels. === Generics === In 2004, generics were added to the Java language, as part of J2SE 5.0. Prior to the introduction of generics, each variable declaration had to be of a specific type. For container classes, for example, this is a problem because there is no easy way to create a container that accepts only specific types of objects. Either the container operates on all subtypes of a class or interface, usually Object, or a different container class has to be created for each contained class. Generics allow compile-time type checking without having to create many container classes, each containing almost identical code. In addition to enabling more efficient code, certain runtime exceptions are prevented from occurring, by issuing compile-time errors. If Java prevented all runtime type errors (ClassCastExceptions) from occurring, it would be type safe. In 2016, the type system of Java was proven unsound in that it is possible to use generics to construct classes and methods that allow assignment of an instance of one class to a variable of another unrelated class. Such code is accepted by the compiler, but fails at run time with a class cast exception. == Criticism == Criticisms directed at Java include the implementation of generics, speed, the handling of unsigned numbers, the implementation of floating-point arithmetic, and a history of security vulnerabilities in the primary Java VM implementation HotSpot. Developers have criticized the complexity and verbosity of the Java Persistence API (JPA), a standard part of Java EE. This has led to increased adoption of higher-level abstractions like Spring Data JPA, which aims to simplify database operations and reduce boilerplate code. The growing popularity of such frameworks suggests limitations in the standard JPA implementation's ease-of-use for modern Java development. == Class libraries == The Java Class Library is the standard library, developed to support application development in Java. It is controlled by Oracle in cooperation with others through the Java Community Process program. Companies or individuals participating in this process can influence the design and development of the APIs. This process has been a subject of controversy during the 2010s. The class library contains features such as: The core libraries, which include: Input/output (I/O or IO) and non-blocking I/O (NIO), or IO/NIO Networking (new user agent (HTTP client) since Java 11) Reflective programming (reflection) Concurrent computing (concurrency) Generics Scripting, Compiler Functional programming (Lambda, streaming) Collection libraries that implement data structures such as lists, dictionaries, trees, sets, queues and double-ended queue, or stacks XML Processing (Parsing, Transforming, Validating) libraries Security Internationalization and localization libraries The integration libraries, which allow the application writer to communicate with external systems. These libraries include: The Java Database Connectivity (JDBC) API for database access Java Naming and Directory Interface (JNDI) for lookup and discovery Java remote method invocation (RMI) and Common Object Request Broker Architecture (CORBA) for distributed application development Java Management Extensions (JMX) for managing and monitoring applications User interface libraries, which include: The (heavyweight, or native) Abstract Window Toolkit (AWT), which provides GUI components, the means for laying out those components and the means for handling events from those components The (lightweight) Swing libraries, which are built on AWT but provide (non-native) implementations of the AWT widgetry APIs for audio capture, processing, and playback JavaFX A platform dependent implementation of the Java virtual machine that is the means by which the bytecodes of the Java libraries and third-party applications are executed Plugins, which enable applets to be run in web browsers Java Web Start, which allows Java applications to be efficiently distributed to end users across the Internet Licensing and documentation == Documentation == Javadoc is a comprehensive documentation system, created by Sun Microsystems. It provides developers with an organized system for documenting their code. Javadoc comments have an extra asterisk at the beginning, i.e. the delimiters are /** and */, whereas the normal multi-line comments in Java are delimited by /* and */, and single-line comments start with //. == Implementations == Oracle Corporation owns the official implementation of the Java SE platform, due to its acquisition of Sun Microsystems on January 27, 2010. This implementation is based on the original implementation of Java by Sun. The Oracle implementation is available for Windows, macOS, Linux, and Solaris. Because Java lacks any formal standardization recognized by Ecma International, ISO/IEC, ANSI, or other third-party standards organizations, the Oracle implementation is the de facto standard. The Oracle implementation is packaged into two different distributions: The Java Runtime Environment (JRE) which contains the parts of the Java SE platform required to run Java programs and is intended for end users, and the Java Development Kit (JDK), which is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger. Oracle has also released GraalVM, a high performance Java dynamic compiler and interpreter. OpenJDK is another Java SE implementation that is licensed under the GNU GPL. The implementation started when Sun began releasing the Java source code under the GPL. As of Java SE 7, OpenJDK is the official Java reference implementation. The goal of Java is to make all implementations of Java compatible. Historically, Sun's trademark license for usage of the Java brand insists that all implementations be compatible. This resulted in a legal dispute with Microsoft after Sun claimed that the Microsoft implementation did not support Java remote method invocation (RMI) or Java Native Interface (JNI) and had added platform-specific features of their own. Sun sued in 1997, and, in 2001, won a settlement of US$20 million, as well as a court order enforcing the terms of the license from Sun. As a result, Microsoft no longer ships Java with Windows. Platform-independent Java is essential to Java EE, and an even more rigorous validation is required to certify an implementation. This environment enables portable server-side applications. == Use outside the Java platform == The Java programming language requires the presence of a software platform in order for compiled programs to be executed. Oracle supplies the Java platform for use with Java. The Android SDK is an alternative software platform, used primarily for developing Android applications with its own GUI system. === Android === The Java language is a key pillar in Android, an open source mobile operating system. Although Android, built on the Linux kernel, is written largely in C, the Android SDK uses the Java language as the basis for Android applications but does not use any of its standard GUI, SE, ME or other established Java standards. The bytecode language supported by the Android SDK is incompatible with Java bytecode and runs on its own virtual machine, optimized for low-memory devices such as smartphones and tablet computers. Depending on the Android version, the bytecode is either interpreted by the Dalvik virtual machine or compiled into native code by the Android Runtime. Android does not provide the full Java SE standard library, although the Android SDK does include an independent implementation of a large subset of it. It supports Java 6 and some Java 7 features, offering an implementation compatible with the standard library (Apache Harmony). ==== Controversy ==== The use of Java-related technology in Android led to a legal dispute between Oracle and Google. On May 7, 2012, a San Francisco jury found that if APIs could be copyrighted, then Google had infringed Oracle's copyrights by the use of Java in Android devices. District Judge William Alsup ruled on May 31, 2012, that APIs cannot be copyrighted, but this was reversed by the United States Court of Appeals for the Federal Circuit in May 2014. On May 26, 2016, the district court decided in favor of Google, ruling the copyright infringement of the Java API in Android constitutes fair use. In March 2018, this ruling was overturned by the Appeals Court, which sent down the case of determining the damages to federal court in San Francisco. Google filed a petition for writ of certiorari with the Supreme Court of the United States in January 2019 to challenge the two rulings that were made by the Appeals Court in Oracle's favor. On April 5, 2021, the Court ruled 6–2 in Google's favor, that its use of Java APIs should be considered fair use. However, the court refused to rule on the copyrightability of APIs, choosing instead to determine their ruling by considering Java's API copyrightable "purely for argument's sake." == See also == C# C++ Dalvik, used in old Android versions, replaced by non-JIT Android Runtime Java Heterogeneous Distributed Computing List of Java APIs List of Java frameworks List of JVM languages List of Java virtual machines Comparison of C# and Java Comparison of Java and C++ Comparison of programming languages == References == == Bibliography == == External links == Official website, OpenJDK, Oracle JDK builds, Adoptium
https://en.wikipedia.org/wiki/Java_(programming_language)
Dynamic programming is both a mathematical optimization method and an algorithmic paradigm. The method was developed by Richard Bellman in the 1950s and has found applications in numerous fields, from aerospace engineering to economics. In both contexts it refers to simplifying a complicated problem by breaking it down into simpler sub-problems in a recursive manner. While some decision problems cannot be taken apart this way, decisions that span several points in time do often break apart recursively. Likewise, in computer science, if a problem can be solved optimally by breaking it into sub-problems and then recursively finding the optimal solutions to the sub-problems, then it is said to have optimal substructure. If sub-problems can be nested recursively inside larger problems, so that dynamic programming methods are applicable, then there is a relation between the value of the larger problem and the values of the sub-problems. In the optimization literature this relationship is called the Bellman equation. == Overview == === Mathematical optimization === In terms of mathematical optimization, dynamic programming usually refers to simplifying a decision by breaking it down into a sequence of decision steps over time. This is done by defining a sequence of value functions V1, V2, ..., Vn taking y as an argument representing the state of the system at times i from 1 to n. The definition of Vn(y) is the value obtained in state y at the last time n. The values Vi at earlier times i = n −1, n − 2, ..., 2, 1 can be found by working backwards, using a recursive relationship called the Bellman equation. For i = 2, ..., n, Vi−1 at any state y is calculated from Vi by maximizing a simple function (usually the sum) of the gain from a decision at time i − 1 and the function Vi at the new state of the system if this decision is made. Since Vi has already been calculated for the needed states, the above operation yields Vi−1 for those states. Finally, V1 at the initial state of the system is the value of the optimal solution. The optimal values of the decision variables can be recovered, one by one, by tracking back the calculations already performed. === Control theory === In control theory, a typical problem is to find an admissible control u ∗ {\displaystyle \mathbf {u} ^{\ast }} which causes the system x ˙ ( t ) = g ( x ( t ) , u ( t ) , t ) {\displaystyle {\dot {\mathbf {x} }}(t)=\mathbf {g} \left(\mathbf {x} (t),\mathbf {u} (t),t\right)} to follow an admissible trajectory x ∗ {\displaystyle \mathbf {x} ^{\ast }} on a continuous time interval t 0 ≤ t ≤ t 1 {\displaystyle t_{0}\leq t\leq t_{1}} that minimizes a cost function J = b ( x ( t 1 ) , t 1 ) + ∫ t 0 t 1 f ( x ( t ) , u ( t ) , t ) d t {\displaystyle J=b\left(\mathbf {x} (t_{1}),t_{1}\right)+\int _{t_{0}}^{t_{1}}f\left(\mathbf {x} (t),\mathbf {u} (t),t\right)\mathrm {d} t} The solution to this problem is an optimal control law or policy u ∗ = h ( x ( t ) , t ) {\displaystyle \mathbf {u} ^{\ast }=h(\mathbf {x} (t),t)} , which produces an optimal trajectory x ∗ {\displaystyle \mathbf {x} ^{\ast }} and a cost-to-go function J ∗ {\displaystyle J^{\ast }} . The latter obeys the fundamental equation of dynamic programming: − J t ∗ = min u { f ( x ( t ) , u ( t ) , t ) + J x ∗ T g ( x ( t ) , u ( t ) , t ) } {\displaystyle -J_{t}^{\ast }=\min _{\mathbf {u} }\left\{f\left(\mathbf {x} (t),\mathbf {u} (t),t\right)+J_{x}^{\ast {\mathsf {T}}}\mathbf {g} \left(\mathbf {x} (t),\mathbf {u} (t),t\right)\right\}} a partial differential equation known as the Hamilton–Jacobi–Bellman equation, in which J x ∗ = ∂ J ∗ ∂ x = [ ∂ J ∗ ∂ x 1 ∂ J ∗ ∂ x 2 … ∂ J ∗ ∂ x n ] T {\displaystyle J_{x}^{\ast }={\frac {\partial J^{\ast }}{\partial \mathbf {x} }}=\left[{\frac {\partial J^{\ast }}{\partial x_{1}}}~~~~{\frac {\partial J^{\ast }}{\partial x_{2}}}~~~~\dots ~~~~{\frac {\partial J^{\ast }}{\partial x_{n}}}\right]^{\mathsf {T}}} and J t ∗ = ∂ J ∗ ∂ t {\displaystyle J_{t}^{\ast }={\frac {\partial J^{\ast }}{\partial t}}} . One finds that minimizing u {\displaystyle \mathbf {u} } in terms of t {\displaystyle t} , x {\displaystyle \mathbf {x} } , and the unknown function J x ∗ {\displaystyle J_{x}^{\ast }} and then substitutes the result into the Hamilton–Jacobi–Bellman equation to get the partial differential equation to be solved with boundary condition J ( t 1 ) = b ( x ( t 1 ) , t 1 ) {\displaystyle J\left(t_{1}\right)=b\left(\mathbf {x} (t_{1}),t_{1}\right)} . In practice, this generally requires numerical techniques for some discrete approximation to the exact optimization relationship. Alternatively, the continuous process can be approximated by a discrete system, which leads to a following recurrence relation analog to the Hamilton–Jacobi–Bellman equation: J k ∗ ( x n − k ) = min u n − k { f ^ ( x n − k , u n − k ) + J k − 1 ∗ ( g ^ ( x n − k , u n − k ) ) } {\displaystyle J_{k}^{\ast }\left(\mathbf {x} _{n-k}\right)=\min _{\mathbf {u} _{n-k}}\left\{{\hat {f}}\left(\mathbf {x} _{n-k},\mathbf {u} _{n-k}\right)+J_{k-1}^{\ast }\left({\hat {\mathbf {g} }}\left(\mathbf {x} _{n-k},\mathbf {u} _{n-k}\right)\right)\right\}} at the k {\displaystyle k} -th stage of n {\displaystyle n} equally spaced discrete time intervals, and where f ^ {\displaystyle {\hat {f}}} and g ^ {\displaystyle {\hat {\mathbf {g} }}} denote discrete approximations to f {\displaystyle f} and g {\displaystyle \mathbf {g} } . This functional equation is known as the Bellman equation, which can be solved for an exact solution of the discrete approximation of the optimization equation. ==== Example from economics: Ramsey's problem of optimal saving ==== In economics, the objective is generally to maximize (rather than minimize) some dynamic social welfare function. In Ramsey's problem, this function relates amounts of consumption to levels of utility. Loosely speaking, the planner faces the trade-off between contemporaneous consumption and future consumption (via investment in capital stock that is used in production), known as intertemporal choice. Future consumption is discounted at a constant rate β ∈ ( 0 , 1 ) {\displaystyle \beta \in (0,1)} . A discrete approximation to the transition equation of capital is given by k t + 1 = g ^ ( k t , c t ) = f ( k t ) − c t {\displaystyle k_{t+1}={\hat {g}}\left(k_{t},c_{t}\right)=f(k_{t})-c_{t}} where c {\displaystyle c} is consumption, k {\displaystyle k} is capital, and f {\displaystyle f} is a production function satisfying the Inada conditions. An initial capital stock k 0 > 0 {\displaystyle k_{0}>0} is assumed. Let c t {\displaystyle c_{t}} be consumption in period t, and assume consumption yields utility u ( c t ) = ln ⁡ ( c t ) {\displaystyle u(c_{t})=\ln(c_{t})} as long as the consumer lives. Assume the consumer is impatient, so that he discounts future utility by a factor b each period, where 0 < b < 1 {\displaystyle 0<b<1} . Let k t {\displaystyle k_{t}} be capital in period t. Assume initial capital is a given amount k 0 > 0 {\displaystyle k_{0}>0} , and suppose that this period's capital and consumption determine next period's capital as k t + 1 = A k t a − c t {\displaystyle k_{t+1}=Ak_{t}^{a}-c_{t}} , where A is a positive constant and 0 < a < 1 {\displaystyle 0<a<1} . Assume capital cannot be negative. Then the consumer's decision problem can be written as follows: max ∑ t = 0 T b t ln ⁡ ( c t ) {\displaystyle \max \sum _{t=0}^{T}b^{t}\ln(c_{t})} subject to k t + 1 = A k t a − c t ≥ 0 {\displaystyle k_{t+1}=Ak_{t}^{a}-c_{t}\geq 0} for all t = 0 , 1 , 2 , … , T {\displaystyle t=0,1,2,\ldots ,T} Written this way, the problem looks complicated, because it involves solving for all the choice variables c 0 , c 1 , c 2 , … , c T {\displaystyle c_{0},c_{1},c_{2},\ldots ,c_{T}} . (The capital k 0 {\displaystyle k_{0}} is not a choice variable—the consumer's initial capital is taken as given.) The dynamic programming approach to solve this problem involves breaking it apart into a sequence of smaller decisions. To do so, we define a sequence of value functions V t ( k ) {\displaystyle V_{t}(k)} , for t = 0 , 1 , 2 , … , T , T + 1 {\displaystyle t=0,1,2,\ldots ,T,T+1} which represent the value of having any amount of capital k at each time t. There is (by assumption) no utility from having capital after death, V T + 1 ( k ) = 0 {\displaystyle V_{T+1}(k)=0} . The value of any quantity of capital at any previous time can be calculated by backward induction using the Bellman equation. In this problem, for each t = 0 , 1 , 2 , … , T {\displaystyle t=0,1,2,\ldots ,T} , the Bellman equation is V t ( k t ) = max ( ln ⁡ ( c t ) + b V t + 1 ( k t + 1 ) ) {\displaystyle V_{t}(k_{t})\,=\,\max \left(\ln(c_{t})+bV_{t+1}(k_{t+1})\right)} subject to k t + 1 = A k t a − c t ≥ 0 {\displaystyle k_{t+1}=Ak_{t}^{a}-c_{t}\geq 0} This problem is much simpler than the one we wrote down before, because it involves only two decision variables, c t {\displaystyle c_{t}} and k t + 1 {\displaystyle k_{t+1}} . Intuitively, instead of choosing his whole lifetime plan at birth, the consumer can take things one step at a time. At time t, his current capital k t {\displaystyle k_{t}} is given, and he only needs to choose current consumption c t {\displaystyle c_{t}} and saving k t + 1 {\displaystyle k_{t+1}} . To actually solve this problem, we work backwards. For simplicity, the current level of capital is denoted as k. V T + 1 ( k ) {\displaystyle V_{T+1}(k)} is already known, so using the Bellman equation once we can calculate V T ( k ) {\displaystyle V_{T}(k)} , and so on until we get to V 0 ( k ) {\displaystyle V_{0}(k)} , which is the value of the initial decision problem for the whole lifetime. In other words, once we know V T − j + 1 ( k ) {\displaystyle V_{T-j+1}(k)} , we can calculate V T − j ( k ) {\displaystyle V_{T-j}(k)} , which is the maximum of ln ⁡ ( c T − j ) + b V T − j + 1 ( A k a − c T − j ) {\displaystyle \ln(c_{T-j})+bV_{T-j+1}(Ak^{a}-c_{T-j})} , where c T − j {\displaystyle c_{T-j}} is the choice variable and A k a − c T − j ≥ 0 {\displaystyle Ak^{a}-c_{T-j}\geq 0} . Working backwards, it can be shown that the value function at time t = T − j {\displaystyle t=T-j} is V T − j ( k ) = a ∑ i = 0 j a i b i ln ⁡ k + v T − j {\displaystyle V_{T-j}(k)\,=\,a\sum _{i=0}^{j}a^{i}b^{i}\ln k+v_{T-j}} where each v T − j {\displaystyle v_{T-j}} is a constant, and the optimal amount to consume at time t = T − j {\displaystyle t=T-j} is c T − j ( k ) = 1 ∑ i = 0 j a i b i A k a {\displaystyle c_{T-j}(k)\,=\,{\frac {1}{\sum _{i=0}^{j}a^{i}b^{i}}}Ak^{a}} which can be simplified to c T ( k ) = A k a c T − 1 ( k ) = A k a 1 + a b c T − 2 ( k ) = A k a 1 + a b + a 2 b 2 … c 2 ( k ) = A k a 1 + a b + a 2 b 2 + … + a T − 2 b T − 2 c 1 ( k ) = A k a 1 + a b + a 2 b 2 + … + a T − 2 b T − 2 + a T − 1 b T − 1 c 0 ( k ) = A k a 1 + a b + a 2 b 2 + … + a T − 2 b T − 2 + a T − 1 b T − 1 + a T b T {\displaystyle {\begin{aligned}c_{T}(k)&=Ak^{a}\\c_{T-1}(k)&={\frac {Ak^{a}}{1+ab}}\\c_{T-2}(k)&={\frac {Ak^{a}}{1+ab+a^{2}b^{2}}}\\&\dots \\c_{2}(k)&={\frac {Ak^{a}}{1+ab+a^{2}b^{2}+\ldots +a^{T-2}b^{T-2}}}\\c_{1}(k)&={\frac {Ak^{a}}{1+ab+a^{2}b^{2}+\ldots +a^{T-2}b^{T-2}+a^{T-1}b^{T-1}}}\\c_{0}(k)&={\frac {Ak^{a}}{1+ab+a^{2}b^{2}+\ldots +a^{T-2}b^{T-2}+a^{T-1}b^{T-1}+a^{T}b^{T}}}\end{aligned}}} We see that it is optimal to consume a larger fraction of current wealth as one gets older, finally consuming all remaining wealth in period T, the last period of life. === Computer science === There are two key attributes that a problem must have in order for dynamic programming to be applicable: optimal substructure and overlapping sub-problems. If a problem can be solved by combining optimal solutions to non-overlapping sub-problems, the strategy is called "divide and conquer" instead. This is why merge sort and quick sort are not classified as dynamic programming problems. Optimal substructure means that the solution to a given optimization problem can be obtained by the combination of optimal solutions to its sub-problems. Such optimal substructures are usually described by means of recursion. For example, given a graph G=(V,E), the shortest path p from a vertex u to a vertex v exhibits optimal substructure: take any intermediate vertex w on this shortest path p. If p is truly the shortest path, then it can be split into sub-paths p1 from u to w and p2 from w to v such that these, in turn, are indeed the shortest paths between the corresponding vertices (by the simple cut-and-paste argument described in Introduction to Algorithms). Hence, one can easily formulate the solution for finding shortest paths in a recursive manner, which is what the Bellman–Ford algorithm or the Floyd–Warshall algorithm does. Overlapping sub-problems means that the space of sub-problems must be small, that is, any recursive algorithm solving the problem should solve the same sub-problems over and over, rather than generating new sub-problems. For example, consider the recursive formulation for generating the Fibonacci sequence: Fi = Fi−1 + Fi−2, with base case F1 = F2 = 1. Then F43 = F42 + F41, and F42 = F41 + F40. Now F41 is being solved in the recursive sub-trees of both F43 as well as F42. Even though the total number of sub-problems is actually small (only 43 of them), we end up solving the same problems over and over if we adopt a naive recursive solution such as this. Dynamic programming takes account of this fact and solves each sub-problem only once. This can be achieved in either of two ways: Top-down approach: This is the direct fall-out of the recursive formulation of any problem. If the solution to any problem can be formulated recursively using the solution to its sub-problems, and if its sub-problems are overlapping, then one can easily memoize or store the solutions to the sub-problems in a table (often an array or hashtable in practice). Whenever we attempt to solve a new sub-problem, we first check the table to see if it is already solved. If a solution has been recorded, we can use it directly, otherwise we solve the sub-problem and add its solution to the table. Bottom-up approach: Once we formulate the solution to a problem recursively as in terms of its sub-problems, we can try reformulating the problem in a bottom-up fashion: try solving the sub-problems first and use their solutions to build-on and arrive at solutions to bigger sub-problems. This is also usually done in a tabular form by iteratively generating solutions to bigger and bigger sub-problems by using the solutions to small sub-problems. For example, if we already know the values of F41 and F40, we can directly calculate the value of F42. Some programming languages can automatically memoize the result of a function call with a particular set of arguments, in order to speed up call-by-name evaluation (this mechanism is referred to as call-by-need). Some languages make it possible portably (e.g. Scheme, Common Lisp, Perl or D). Some languages have automatic memoization built in, such as tabled Prolog and J, which supports memoization with the M. adverb. In any case, this is only possible for a referentially transparent function. Memoization is also encountered as an easily accessible design pattern within term-rewrite based languages such as Wolfram Language. === Bioinformatics === Dynamic programming is widely used in bioinformatics for tasks such as sequence alignment, protein folding, RNA structure prediction and protein-DNA binding. The first dynamic programming algorithms for protein-DNA binding were developed in the 1970s independently by Charles DeLisi in the US and by Georgii Gurskii and Alexander Zasedatelev in the Soviet Union. Recently these algorithms have become very popular in bioinformatics and computational biology, particularly in the studies of nucleosome positioning and transcription factor binding. == Examples: computer algorithms == === Dijkstra's algorithm for the shortest path problem === From a dynamic programming point of view, Dijkstra's algorithm for the shortest path problem is a successive approximation scheme that solves the dynamic programming functional equation for the shortest path problem by the Reaching method. In fact, Dijkstra's explanation of the logic behind the algorithm, namely Problem 2. Find the path of minimum total length between two given nodes P {\displaystyle P} and Q {\displaystyle Q} . We use the fact that, if R {\displaystyle R} is a node on the minimal path from P {\displaystyle P} to Q {\displaystyle Q} , knowledge of the latter implies the knowledge of the minimal path from P {\displaystyle P} to R {\displaystyle R} . is a paraphrasing of Bellman's famous Principle of Optimality in the context of the shortest path problem. === Fibonacci sequence === Using dynamic programming in the calculation of the nth member of the Fibonacci sequence improves its performance greatly. Here is a naïve implementation, based directly on the mathematical definition: function fib(n) if n <= 1 return n return fib(n − 1) + fib(n − 2) Notice that if we call, say, fib(5), we produce a call tree that calls the function on the same value many different times: fib(5) fib(4) + fib(3) (fib(3) + fib(2)) + (fib(2) + fib(1)) ((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1)) (((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1)) In particular, fib(2) was calculated three times from scratch. In larger examples, many more values of fib, or subproblems, are recalculated, leading to an exponential time algorithm. Now, suppose we have a simple map object, m, which maps each value of fib that has already been calculated to its result, and we modify our function to use it and update it. The resulting function requires only O(n) time instead of exponential time (but requires O(n) space): var m := map(0 → 0, 1 → 1) function fib(n) if key n is not in map m m[n] := fib(n − 1) + fib(n − 2) return m[n] This technique of saving values that have already been calculated is called memoization; this is the top-down approach, since we first break the problem into subproblems and then calculate and store values. In the bottom-up approach, we calculate the smaller values of fib first, then build larger values from them. This method also uses O(n) time since it contains a loop that repeats n − 1 times, but it only takes constant (O(1)) space, in contrast to the top-down approach which requires O(n) space to store the map. function fib(n) if n = 0 return 0 else var previousFib := 0, currentFib := 1 repeat n − 1 times // loop is skipped if n = 1 var newFib := previousFib + currentFib previousFib := currentFib currentFib := newFib return currentFib In both examples, we only calculate fib(2) one time, and then use it to calculate both fib(4) and fib(3), instead of computing it every time either of them is evaluated. === A type of balanced 0–1 matrix === Consider the problem of assigning values, either zero or one, to the positions of an n × n matrix, with n even, so that each row and each column contains exactly n / 2 zeros and n / 2 ones. We ask how many different assignments there are for a given n {\displaystyle n} . For example, when n = 4, five possible solutions are [ 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 ] and [ 0 0 1 1 0 0 1 1 1 1 0 0 1 1 0 0 ] and [ 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 ] and [ 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 ] and [ 1 1 0 0 1 1 0 0 0 0 1 1 0 0 1 1 ] . {\displaystyle {\begin{bmatrix}0&1&0&1\\1&0&1&0\\0&1&0&1\\1&0&1&0\end{bmatrix}}{\text{ and }}{\begin{bmatrix}0&0&1&1\\0&0&1&1\\1&1&0&0\\1&1&0&0\end{bmatrix}}{\text{ and }}{\begin{bmatrix}1&1&0&0\\0&0&1&1\\1&1&0&0\\0&0&1&1\end{bmatrix}}{\text{ and }}{\begin{bmatrix}1&0&0&1\\0&1&1&0\\0&1&1&0\\1&0&0&1\end{bmatrix}}{\text{ and }}{\begin{bmatrix}1&1&0&0\\1&1&0&0\\0&0&1&1\\0&0&1&1\end{bmatrix}}.} There are at least three possible approaches: brute force, backtracking, and dynamic programming. Brute force consists of checking all assignments of zeros and ones and counting those that have balanced rows and columns (n / 2 zeros and n / 2 ones). As there are 2 n 2 {\displaystyle 2^{n^{2}}} possible assignments and ( n n / 2 ) n {\displaystyle {\tbinom {n}{n/2}}^{n}} sensible assignments, this strategy is not practical except maybe up to n = 6 {\displaystyle n=6} . Backtracking for this problem consists of choosing some order of the matrix elements and recursively placing ones or zeros, while checking that in every row and column the number of elements that have not been assigned plus the number of ones or zeros are both at least n / 2. While more sophisticated than brute force, this approach will visit every solution once, making it impractical for n larger than six, since the number of solutions is already 116,963,796,250 for n = 8, as we shall see. Dynamic programming makes it possible to count the number of solutions without visiting them all. Imagine backtracking values for the first row – what information would we require about the remaining rows, in order to be able to accurately count the solutions obtained for each first row value? We consider k × n boards, where 1 ≤ k ≤ n, whose k {\displaystyle k} rows contain n / 2 {\displaystyle n/2} zeros and n / 2 {\displaystyle n/2} ones. The function f to which memoization is applied maps vectors of n pairs of integers to the number of admissible boards (solutions). There is one pair for each column, and its two components indicate respectively the number of zeros and ones that have yet to be placed in that column. We seek the value of f ( ( n / 2 , n / 2 ) , ( n / 2 , n / 2 ) , … ( n / 2 , n / 2 ) ) {\displaystyle f((n/2,n/2),(n/2,n/2),\ldots (n/2,n/2))} ( n {\displaystyle n} arguments or one vector of n {\displaystyle n} elements). The process of subproblem creation involves iterating over every one of ( n n / 2 ) {\displaystyle {\tbinom {n}{n/2}}} possible assignments for the top row of the board, and going through every column, subtracting one from the appropriate element of the pair for that column, depending on whether the assignment for the top row contained a zero or a one at that position. If any one of the results is negative, then the assignment is invalid and does not contribute to the set of solutions (recursion stops). Otherwise, we have an assignment for the top row of the k × n board and recursively compute the number of solutions to the remaining (k − 1) × n board, adding the numbers of solutions for every admissible assignment of the top row and returning the sum, which is being memoized. The base case is the trivial subproblem, which occurs for a 1 × n board. The number of solutions for this board is either zero or one, depending on whether the vector is a permutation of n / 2 ( 0 , 1 ) {\displaystyle (0,1)} and n / 2 ( 1 , 0 ) {\displaystyle (1,0)} pairs or not. For example, in the first two boards shown above the sequences of vectors would be ((2, 2) (2, 2) (2, 2) (2, 2)) ((2, 2) (2, 2) (2, 2) (2, 2)) k = 4 0 1 0 1 0 0 1 1 ((1, 2) (2, 1) (1, 2) (2, 1)) ((1, 2) (1, 2) (2, 1) (2, 1)) k = 3 1 0 1 0 0 0 1 1 ((1, 1) (1, 1) (1, 1) (1, 1)) ((0, 2) (0, 2) (2, 0) (2, 0)) k = 2 0 1 0 1 1 1 0 0 ((0, 1) (1, 0) (0, 1) (1, 0)) ((0, 1) (0, 1) (1, 0) (1, 0)) k = 1 1 0 1 0 1 1 0 0 ((0, 0) (0, 0) (0, 0) (0, 0)) ((0, 0) (0, 0), (0, 0) (0, 0)) The number of solutions (sequence A058527 in the OEIS) is 1 , 2 , 90 , 297200 , 116963796250 , 6736218287430460752 , … {\displaystyle 1,\,2,\,90,\,297200,\,116963796250,\,6736218287430460752,\ldots } Links to the MAPLE implementation of the dynamic programming approach may be found among the external links. === Checkerboard === Consider a checkerboard with n × n squares and a cost function c(i, j) which returns a cost associated with square (i,j) (i being the row, j being the column). For instance (on a 5 × 5 checkerboard), Thus c(1, 3) = 5 Let us say there was a checker that could start at any square on the first rank (i.e., row) and you wanted to know the shortest path (the sum of the minimum costs at each visited rank) to get to the last rank; assuming the checker could move only diagonally left forward, diagonally right forward, or straight forward. That is, a checker on (1,3) can move to (2,2), (2,3) or (2,4). This problem exhibits optimal substructure. That is, the solution to the entire problem relies on solutions to subproblems. Let us define a function q(i, j) as q(i, j) = the minimum cost to reach square (i, j). Starting at rank n and descending to rank 1, we compute the value of this function for all the squares at each successive rank. Picking the square that holds the minimum value at each rank gives us the shortest path between rank n and rank 1. The function q(i, j) is equal to the minimum cost to get to any of the three squares below it (since those are the only squares that can reach it) plus c(i, j). For instance: q ( A ) = min ( q ( B ) , q ( C ) , q ( D ) ) + c ( A ) {\displaystyle q(A)=\min(q(B),q(C),q(D))+c(A)\,} Now, let us define q(i, j) in somewhat more general terms: q ( i , j ) = { ∞ j < 1 or j > n c ( i , j ) i = 1 min ( q ( i − 1 , j − 1 ) , q ( i − 1 , j ) , q ( i − 1 , j + 1 ) ) + c ( i , j ) otherwise. {\displaystyle q(i,j)={\begin{cases}\infty &j<1{\text{ or }}j>n\\c(i,j)&i=1\\\min(q(i-1,j-1),q(i-1,j),q(i-1,j+1))+c(i,j)&{\text{otherwise.}}\end{cases}}} The first line of this equation deals with a board modeled as squares indexed on 1 at the lowest bound and n at the highest bound. The second line specifies what happens at the first rank; providing a base case. The third line, the recursion, is the important part. It represents the A,B,C,D terms in the example. From this definition we can derive straightforward recursive code for q(i, j). In the following pseudocode, n is the size of the board, c(i, j) is the cost function, and min() returns the minimum of a number of values: function minCost(i, j) if j < 1 or j > n return infinity else if i = 1 return c(i, j) else return min( minCost(i-1, j-1), minCost(i-1, j), minCost(i-1, j+1) ) + c(i, j) This function only computes the path cost, not the actual path. We discuss the actual path below. This, like the Fibonacci-numbers example, is horribly slow because it too exhibits the overlapping sub-problems attribute. That is, it recomputes the same path costs over and over. However, we can compute it much faster in a bottom-up fashion if we store path costs in a two-dimensional array q[i, j] rather than using a function. This avoids recomputation; all the values needed for array q[i, j] are computed ahead of time only once. Precomputed values for (i,j) are simply looked up whenever needed. We also need to know what the actual shortest path is. To do this, we use another array p[i, j]; a predecessor array. This array records the path to any square s. The predecessor of s is modeled as an offset relative to the index (in q[i, j]) of the precomputed path cost of s. To reconstruct the complete path, we lookup the predecessor of s, then the predecessor of that square, then the predecessor of that square, and so on recursively, until we reach the starting square. Consider the following pseudocode: function computeShortestPathArrays() for x from 1 to n q[1, x] := c(1, x) for y from 1 to n q[y, 0] := infinity q[y, n + 1] := infinity for y from 2 to n for x from 1 to n m := min(q[y-1, x-1], q[y-1, x], q[y-1, x+1]) q[y, x] := m + c(y, x) if m = q[y-1, x-1] p[y, x] := -1 else if m = q[y-1, x] p[y, x] := 0 else p[y, x] := 1 Now the rest is a simple matter of finding the minimum and printing it. function computeShortestPath() computeShortestPathArrays() minIndex := 1 min := q[n, 1] for i from 2 to n if q[n, i] < min minIndex := i min := q[n, i] printPath(n, minIndex) function printPath(y, x) print(x) print("<-") if y = 2 print(x + p[y, x]) else printPath(y-1, x + p[y, x]) === Sequence alignment === In genetics, sequence alignment is an important application where dynamic programming is essential. Typically, the problem consists of transforming one sequence into another using edit operations that replace, insert, or remove an element. Each operation has an associated cost, and the goal is to find the sequence of edits with the lowest total cost. The problem can be stated naturally as a recursion, a sequence A is optimally edited into a sequence B by either: inserting the first character of B, and performing an optimal alignment of A and the tail of B deleting the first character of A, and performing the optimal alignment of the tail of A and B replacing the first character of A with the first character of B, and performing optimal alignments of the tails of A and B. The partial alignments can be tabulated in a matrix, where cell (i,j) contains the cost of the optimal alignment of A[1..i] to B[1..j]. The cost in cell (i,j) can be calculated by adding the cost of the relevant operations to the cost of its neighboring cells, and selecting the optimum. Different variants exist, see Smith–Waterman algorithm and Needleman–Wunsch algorithm. === Tower of Hanoi puzzle === The Tower of Hanoi or Towers of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules: Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk. The dynamic programming solution consists of solving the functional equation S(n,h,t) = S(n-1,h, not(h,t)) ; S(1,h,t) ; S(n-1,not(h,t),t) where n denotes the number of disks to be moved, h denotes the home rod, t denotes the target rod, not(h,t) denotes the third rod (neither h nor t), ";" denotes concatenation, and S(n, h, t) := solution to a problem consisting of n disks that are to be moved from rod h to rod t. For n=1 the problem is trivial, namely S(1,h,t) = "move a disk from rod h to rod t" (there is only one disk left). The number of moves required by this solution is 2n − 1. If the objective is to maximize the number of moves (without cycling) then the dynamic programming functional equation is slightly more complicated and 3n − 1 moves are required. === Egg dropping puzzle === The following is a description of the instance of this famous puzzle involving N=2 eggs and a building with H=36 floors: Suppose that we wish to know which stories in a 36-story building are safe to drop eggs from, and which will cause the eggs to break on landing (using U.S. English terminology, in which the first floor is at ground level). We make a few assumptions: An egg that survives a fall can be used again. A broken egg must be discarded. The effect of a fall is the same for all eggs. If an egg breaks when dropped, then it would break if dropped from a higher window. If an egg survives a fall, then it would survive a shorter fall. It is not ruled out that the first-floor windows break eggs, nor is it ruled out that eggs can survive the 36th-floor windows. If only one egg is available and we wish to be sure of obtaining the right result, the experiment can be carried out in only one way. Drop the egg from the first-floor window; if it survives, drop it from the second-floor window. Continue upward until it breaks. In the worst case, this method may require 36 droppings. Suppose 2 eggs are available. What is the lowest number of egg-droppings that is guaranteed to work in all cases? To derive a dynamic programming functional equation for this puzzle, let the state of the dynamic programming model be a pair s = (n,k), where n = number of test eggs available, n = 0, 1, 2, 3, ..., N − 1. k = number of (consecutive) floors yet to be tested, k = 0, 1, 2, ..., H − 1. For instance, s = (2,6) indicates that two test eggs are available and 6 (consecutive) floors are yet to be tested. The initial state of the process is s = (N,H) where N denotes the number of test eggs available at the commencement of the experiment. The process terminates either when there are no more test eggs (n = 0) or when k = 0, whichever occurs first. If termination occurs at state s = (0,k) and k > 0, then the test failed. Now, let W(n,k) = minimum number of trials required to identify the value of the critical floor under the worst-case scenario given that the process is in state s = (n,k). Then it can be shown that W(n,k) = 1 + min{max(W(n − 1, x − 1), W(n,k − x)): x = 1, 2, ..., k } with W(n,0) = 0 for all n > 0 and W(1,k) = k for all k. It is easy to solve this equation iteratively by systematically increasing the values of n and k. ==== Faster DP solution using a different parametrization ==== Notice that the above solution takes O ( n k 2 ) {\displaystyle O(nk^{2})} time with a DP solution. This can be improved to O ( n k log ⁡ k ) {\displaystyle O(nk\log k)} time by binary searching on the optimal x {\displaystyle x} in the above recurrence, since W ( n − 1 , x − 1 ) {\displaystyle W(n-1,x-1)} is increasing in x {\displaystyle x} while W ( n , k − x ) {\displaystyle W(n,k-x)} is decreasing in x {\displaystyle x} , thus a local minimum of max ( W ( n − 1 , x − 1 ) , W ( n , k − x ) ) {\displaystyle \max(W(n-1,x-1),W(n,k-x))} is a global minimum. Also, by storing the optimal x {\displaystyle x} for each cell in the DP table and referring to its value for the previous cell, the optimal x {\displaystyle x} for each cell can be found in constant time, improving it to O ( n k ) {\displaystyle O(nk)} time. However, there is an even faster solution that involves a different parametrization of the problem: Let k {\displaystyle k} be the total number of floors such that the eggs break when dropped from the k {\displaystyle k} th floor (The example above is equivalent to taking k = 37 {\displaystyle k=37} ). Let m {\displaystyle m} be the minimum floor from which the egg must be dropped to be broken. Let f ( t , n ) {\displaystyle f(t,n)} be the maximum number of values of m {\displaystyle m} that are distinguishable using t {\displaystyle t} tries and n {\displaystyle n} eggs. Then f ( t , 0 ) = f ( 0 , n ) = 1 {\displaystyle f(t,0)=f(0,n)=1} for all t , n ≥ 0 {\displaystyle t,n\geq 0} . Let a {\displaystyle a} be the floor from which the first egg is dropped in the optimal strategy. If the first egg broke, m {\displaystyle m} is from 1 {\displaystyle 1} to a {\displaystyle a} and distinguishable using at most t − 1 {\displaystyle t-1} tries and n − 1 {\displaystyle n-1} eggs. If the first egg did not break, m {\displaystyle m} is from a + 1 {\displaystyle a+1} to k {\displaystyle k} and distinguishable using t − 1 {\displaystyle t-1} tries and n {\displaystyle n} eggs. Therefore, f ( t , n ) = f ( t − 1 , n − 1 ) + f ( t − 1 , n ) {\displaystyle f(t,n)=f(t-1,n-1)+f(t-1,n)} . Then the problem is equivalent to finding the minimum x {\displaystyle x} such that f ( x , n ) ≥ k {\displaystyle f(x,n)\geq k} . To do so, we could compute { f ( t , i ) : 0 ≤ i ≤ n } {\displaystyle \{f(t,i):0\leq i\leq n\}} in order of increasing t {\displaystyle t} , which would take O ( n x ) {\displaystyle O(nx)} time. Thus, if we separately handle the case of n = 1 {\displaystyle n=1} , the algorithm would take O ( n k ) {\displaystyle O(n{\sqrt {k}})} time. But the recurrence relation can in fact be solved, giving f ( t , n ) = ∑ i = 0 n ( t i ) {\displaystyle f(t,n)=\sum _{i=0}^{n}{\binom {t}{i}}} , which can be computed in O ( n ) {\displaystyle O(n)} time using the identity ( t i + 1 ) = ( t i ) t − i i + 1 {\displaystyle {\binom {t}{i+1}}={\binom {t}{i}}{\frac {t-i}{i+1}}} for all i ≥ 0 {\displaystyle i\geq 0} . Since f ( t , n ) ≤ f ( t + 1 , n ) {\displaystyle f(t,n)\leq f(t+1,n)} for all t ≥ 0 {\displaystyle t\geq 0} , we can binary search on t {\displaystyle t} to find x {\displaystyle x} , giving an O ( n log ⁡ k ) {\displaystyle O(n\log k)} algorithm. === Matrix chain multiplication === Matrix chain multiplication is a well-known example that demonstrates utility of dynamic programming. For example, engineering applications often have to multiply a chain of matrices. It is not surprising to find matrices of large dimensions, for example 100×100. Therefore, our task is to multiply matrices ⁠ A 1 , A 2 , . . . . A n {\displaystyle A_{1},A_{2},....A_{n}} ⁠. Matrix multiplication is not commutative, but is associative; and we can multiply only two matrices at a time. So, we can multiply this chain of matrices in many different ways, for example: ((A1 × A2) × A3) × ... An A1×(((A2×A3)× ... ) × An) (A1 × A2) × (A3 × ... An) and so on. There are numerous ways to multiply this chain of matrices. They will all produce the same final result, however they will take more or less time to compute, based on which particular matrices are multiplied. If matrix A has dimensions m×n and matrix B has dimensions n×q, then matrix C=A×B will have dimensions m×q, and will require m*n*q scalar multiplications (using a simplistic matrix multiplication algorithm for purposes of illustration). For example, let us multiply matrices A, B and C. Let us assume that their dimensions are m×n, n×p, and p×s, respectively. Matrix A×B×C will be of size m×s and can be calculated in two ways shown below: Ax(B×C) This order of matrix multiplication will require nps + mns scalar multiplications. (A×B)×C This order of matrix multiplication will require mnp + mps scalar calculations. Let us assume that m = 10, n = 100, p = 10 and s = 1000. So, the first way to multiply the chain will require 1,000,000 + 1,000,000 calculations. The second way will require only 10,000+100,000 calculations. Obviously, the second way is faster, and we should multiply the matrices using that arrangement of parenthesis. Therefore, our conclusion is that the order of parenthesis matters, and that our task is to find the optimal order of parenthesis. At this point, we have several choices, one of which is to design a dynamic programming algorithm that will split the problem into overlapping problems and calculate the optimal arrangement of parenthesis. The dynamic programming solution is presented below. Let's call m[i,j] the minimum number of scalar multiplications needed to multiply a chain of matrices from matrix i to matrix j (i.e. Ai × .... × Aj, i.e. i<=j). We split the chain at some matrix k, such that i <= k < j, and try to find out which combination produces minimum m[i,j]. The formula is: if i = j, m[i,j]= 0 if i < j, m[i,j]= min over all possible values of k (m[i,k]+m[k+1,j] + p i − 1 ∗ p k ∗ p j {\displaystyle p_{i-1}*p_{k}*p_{j}} ) where k ranges from i to j − 1. ⁠ p i − 1 {\displaystyle p_{i-1}} ⁠ is the row dimension of matrix i, ⁠ p k {\displaystyle p_{k}} ⁠ is the column dimension of matrix k, ⁠ p j {\displaystyle p_{j}} ⁠ is the column dimension of matrix j. This formula can be coded as shown below, where input parameter "chain" is the chain of matrices, i.e. ⁠ A 1 , A 2 , . . . A n {\displaystyle A_{1},A_{2},...A_{n}} ⁠: function OptimalMatrixChainParenthesis(chain) n = length(chain) for i = 1, n m[i,i] = 0 // Since it takes no calculations to multiply one matrix for len = 2, n for i = 1, n - len + 1 j = i + len -1 m[i,j] = infinity // So that the first calculation updates for k = i, j-1 q = m[i, k] + m[k+1, j] + p i − 1 ∗ p k ∗ p j {\displaystyle p_{i-1}*p_{k}*p_{j}} if q < m[i, j] // The new order of parentheses is better than what we had m[i, j] = q // Update s[i, j] = k // Record which k to split on, i.e. where to place the parenthesis So far, we have calculated values for all possible m[i, j], the minimum number of calculations to multiply a chain from matrix i to matrix j, and we have recorded the corresponding "split point"s[i, j]. For example, if we are multiplying chain A1×A2×A3×A4, and it turns out that m[1, 3] = 100 and s[1, 3] = 2, that means that the optimal placement of parenthesis for matrices 1 to 3 is ⁠ ( A 1 × A 2 ) × A 3 {\displaystyle (A_{1}\times A_{2})\times A_{3}} ⁠ and to multiply those matrices will require 100 scalar calculations. This algorithm will produce "tables" m[, ] and s[, ] that will have entries for all possible values of i and j. The final solution for the entire chain is m[1, n], with corresponding split at s[1, n]. Unraveling the solution will be recursive, starting from the top and continuing until we reach the base case, i.e. multiplication of single matrices. Therefore, the next step is to actually split the chain, i.e. to place the parenthesis where they (optimally) belong. For this purpose we could use the following algorithm: function PrintOptimalParenthesis(s, i, j) if i = j print "A"i else print "(" PrintOptimalParenthesis(s, i, s[i, j]) PrintOptimalParenthesis(s, s[i, j] + 1, j) print ")" Of course, this algorithm is not useful for actual multiplication. This algorithm is just a user-friendly way to see what the result looks like. To actually multiply the matrices using the proper splits, we need the following algorithm: == History of the name == The term dynamic programming was originally used in the 1940s by Richard Bellman to describe the process of solving problems where one needs to find the best decisions one after another. By 1953, he refined this to the modern meaning, referring specifically to nesting smaller decision problems inside larger decisions, and the field was thereafter recognized by the IEEE as a systems analysis and engineering topic. Bellman's contribution is remembered in the name of the Bellman equation, a central result of dynamic programming which restates an optimization problem in recursive form. Bellman explains the reasoning behind the term dynamic programming in his autobiography, Eye of the Hurricane: An Autobiography: I spent the Fall quarter (of 1950) at RAND. My first task was to find a name for multistage decision processes. An interesting question is, "Where did the name, dynamic programming, come from?" The 1950s were not good years for mathematical research. We had a very interesting gentleman in Washington named Wilson. He was Secretary of Defense, and he actually had a pathological fear and hatred of the word "research". I'm not using the term lightly; I'm using it precisely. His face would suffuse, he would turn red, and he would get violent if people used the term research in his presence. You can imagine how he felt, then, about the term mathematical. The RAND Corporation was employed by the Air Force, and the Air Force had Wilson as its boss, essentially. Hence, I felt I had to do something to shield Wilson and the Air Force from the fact that I was really doing mathematics inside the RAND Corporation. What title, what name, could I choose? In the first place I was interested in planning, in decision making, in thinking. But planning, is not a good word for various reasons. I decided therefore to use the word "programming". I wanted to get across the idea that this was dynamic, this was multistage, this was time-varying. I thought, let's kill two birds with one stone. Let's take a word that has an absolutely precise meaning, namely dynamic, in the classical physical sense. It also has a very interesting property as an adjective, and that is it's impossible to use the word dynamic in a pejorative sense. Try thinking of some combination that will possibly give it a pejorative meaning. It's impossible. Thus, I thought dynamic programming was a good name. It was something not even a Congressman could object to. So I used it as an umbrella for my activities. The word dynamic was chosen by Bellman to capture the time-varying aspect of the problems, and because it sounded impressive. The word programming referred to the use of the method to find an optimal program, in the sense of a military schedule for training or logistics. This usage is the same as that in the phrases linear programming and mathematical programming, a synonym for mathematical optimization. The above explanation of the origin of the term may be inaccurate: According to Russell and Norvig, the above story "cannot be strictly true, because his first paper using the term (Bellman, 1952) appeared before Wilson became Secretary of Defense in 1953." Also, Harold J. Kushner stated in a speech that, "On the other hand, when I asked [Bellman] the same question, he replied that he was trying to upstage Dantzig's linear programming by adding dynamic. Perhaps both motivations were true." == See also == == References == == Further reading == Adda, Jerome; Cooper, Russell (2003), Dynamic Economics, MIT Press, ISBN 9780262012010. An accessible introduction to dynamic programming in economics. MATLAB code for the book Archived 2020-10-09 at the Wayback Machine. Bellman, Richard (1954), "The theory of dynamic programming", Bulletin of the American Mathematical Society, 60 (6): 503–516, doi:10.1090/S0002-9904-1954-09848-8, MR 0067459. Includes an extensive bibliography of the literature in the area, up to the year 1954. Bellman, Richard (1957), Dynamic Programming, Princeton University Press. Dover paperback edition (2003), ISBN 0-486-42809-5. Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001), Introduction to Algorithms (2nd ed.), MIT Press & McGraw–Hill, ISBN 978-0-262-03293-3. Especially pp. 323–69. Dreyfus, Stuart E.; Law, Averill M. (1977), The Art and Theory of Dynamic Programming, Academic Press, ISBN 978-0-12-221860-6. Giegerich, R.; Meyer, C.; Steffen, P. (2004), "A Discipline of Dynamic Programming over Sequence Data" (PDF), Science of Computer Programming, 51 (3): 215–263, doi:10.1016/j.scico.2003.12.005. Meyn, Sean (2007), Control Techniques for Complex Networks, Cambridge University Press, ISBN 978-0-521-88441-9, archived from the original on 2010-06-19. Sritharan, S. S. (1991). "Dynamic Programming of the Navier-Stokes Equations". Systems and Control Letters. 16 (4): 299–307. doi:10.1016/0167-6911(91)90020-f. Stokey, Nancy; Lucas, Robert E.; Prescott, Edward (1989), Recursive Methods in Economic Dynamics, Harvard Univ. Press, ISBN 978-0-674-75096-8. == External links == A Tutorial on Dynamic programming MIT course on algorithms - Includes 4 video lectures on DP, lectures 15–18 Applied Mathematical Programming by Bradley, Hax, and Magnanti, Chapter 11 More DP Notes King, Ian, 2002 (1987), "A Simple Introduction to Dynamic Programming in Macroeconomic Models." An introduction to dynamic programming as an important tool in economic theory. Dynamic Programming: from novice to advanced A TopCoder.com article by Dumitru on Dynamic Programming Algebraic Dynamic Programming – a formalized framework for dynamic programming, including an entry-level course to DP, University of Bielefeld Dreyfus, Stuart, "Richard Bellman on the birth of Dynamic Programming. Archived 2020-10-13 at the Wayback Machine" Dynamic programming tutorial A Gentle Introduction to Dynamic Programming and the Viterbi Algorithm Tabled Prolog BProlog, XSB, SWI-Prolog IFORS online interactive dynamic programming modules including, shortest path, traveling salesman, knapsack, false coin, egg dropping, bridge and torch, replacement, chained matrix products, and critical path problem.
https://en.wikipedia.org/wiki/Dynamic_programming
Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically type-checked and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library. Guido van Rossum began working on Python in the late 1980s as a successor to the ABC programming language, and he first released it in 1991 as Python 0.9.0. Python 2.0 was released in 2000. Python 3.0, released in 2008, was a major revision not completely backward-compatible with earlier versions. Python 2.7.18, released in 2020, was the last release of Python 2. Python consistently ranks as one of the most popular programming languages, and it has gained widespread use in the machine learning community. == History == Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands; it was conceived as a successor to the ABC programming language, which was inspired by SETL, capable of exception handling and interfacing with the Amoeba operating system. Python implementation began in December 1989. Van Rossum assumed sole responsibility for the project, as the lead developer, until 12 July 2018, when he announced his "permanent vacation" from responsibilities as Python's "benevolent dictator for life" (BDFL); this title was bestowed on him by the Python community to reflect his long-term commitment as the project's chief decision-maker. (He has since come out of retirement and is self-titled "BDFL-emeritus".) In January 2019, active Python core developers elected a five-member Steering Council to lead the project. The name Python is said to derive from the British comedy series Monty Python's Flying Circus. Python 2.0 was released on 16 October 2000, with many major new features such as list comprehensions, cycle-detecting garbage collection, reference counting, and Unicode support. Python 2.7's end-of-life was initially set for 2015, and then postponed to 2020 out of concern that a large body of existing code could not easily be forward-ported to Python 3. It no longer receives security patches or updates. While Python 2.7 and older versions are officially unsupported, a different unofficial Python implementation, PyPy, continues to support Python 2, i.e., "2.7.18+" (plus 3.10), with the plus signifying (at least some) "backported security updates". Python 3.0 was released on 3 December 2008, with some new semantics and changed syntax. At least every Python release since (the now unsupported) 3.5 has added some syntax to the language; a few later releases have removed outdated modules and have changed semantics, at least in a minor way. As of 8 April 2025, Python 3.13.3 is the latest stable release (it's highly recommended to upgrade to it, or upgrade any other older 3.x release). This version currently receives full bug-fix and security updates, while Python 3.12—released in October 2023—had active bug-fix support only until April 2025, and since then only security fixes. Python 3.9 is the oldest supported version of Python (albeit in the 'security support' phase), because Python 3.8 has become an end-of-life product. Starting with Python 3.13, it and later versions receive two years of full support (which has increased from one and a half years), followed by three years of security support; this is the same total duration of support as previously. Security updates were expedited in 2021 and again twice in 2022. More issues were fixed in 2023 and in September 2024 (for Python versions 3.8.20 through 3.12.6)—all versions (including 2.7) had been insecure because of issues leading to possible remote code execution and web-cache poisoning. Python 3.10 added the | union type operator and added structural pattern matching capability to the language, with the new match and case keywords. Python 3.11 expanded exception handling functionality. Python 3.12 added the new keyword type. Notable changes from version 3.10 to 3.11 include increased program execution speed and improved error reporting. Python 3.11 is claimed to be 10–60% faster than Python 3.10, and Python 3.12 increases by an additional 5%. Python 3.12 also includes improved error messages (again improved in 3.14) and many other changes. Python 3.13 introduced more syntax for types; a new and improved interactive interpreter (REPL), featuring multi-line editing and color support; an incremental garbage collector, which results in shorter pauses for collection in programs that have many objects, as well as increasing the improved speed in 3.11 and 3.12); an experimental just-in-time (JIT) compiler (such features need to be enabled specifically for the increase in speed); and an experimental free-threaded build mode, which disables the global interpreter lock (GIL), allowing threads to run more concurrently, as enabled inpython3.13t or python3.13t.exe. Python Enhancement Proposal (PEP) 711 proposes PyBI—a standard format for distributing Python binaries. Python 3.14.0 is now in the beta 1 phase (introduces e.g. a new opt-in interpreter, up to 30% faster). Python 3.15 will "Make UTF-8 mode default"; This mode is supported in all current Python versions, but it currently must be opted into. UTF-8 is already used by default on Windows (and other operating systems) for most purposes; an exception is opening files. Enabling UTF-8 also makes code fully cross-platform. Potentially breaking changes Python 3.0 introduced very breaking changes, but all breaking changes in 3.x discussed below, are designed to affect few users. Python 3.12 dropped some outdated modules, and more will be dropped in the future, deprecated as of 3.13; already deprecated array 'u' format code will emit DeprecationWarning since 3.13 and will be removed in Python 3.16. The 'w' format code should be used instead. Part of ctypes is also deprecated and http.server.CGIHTTPRequestHandler will emit a DeprecationWarning, and will be removed in 3.15. Using that code already has a high potential for both security and functionality bugs. Parts of the typing module are deprecated, e.g. creating a typing.NamedTuple class using keyword arguments to denote the fields and such (and more) will be disallowed in Python 3.15. Python 3.12 removed wstr meaning Python extensions need to be modified. Python 3.13 introduces some changes in behavior, i.e., new "well-defined semantics", fixing bugs, and removing many deprecated classes, functions and methods (as well as some of the Python/C API and outdated modules). "The old implementation of locals() and frame.f_locals was slow, inconsistent and buggy, and it had many corner cases and oddities. Code that works around those may need revising; code that uses locals() for simple templating or print debugging should continue to work correctly." Python 3.13 introduces the experimental free-threaded build mode, which disables the Global Interpreter Lock (GIL); the GIL is a feature of CPython that previously prevented multiple threads from executing Python bytecode simultaneously. This optional build, introduced through PEP 703, enables better exploitation of multi-core CPUs. By allowing multiple threads to run Python code in parallel, the free-threaded mode addresses long-standing performance bottlenecks associated with the GIL. This change offers a new path for parallelism in Python, without resorting to multiprocessing or external concurrency frameworks. Regarding annotations in upcoming Python version: "In Python 3.14, from __future__ import annotations will continue to work as it did before, converting annotations into strings." Python 3.14 drops the PGP digital verification signatures, it had deprecated in version 3.11, when its replacement Sigstore was added for all CPython artifacts; the use of PGP has been criticized by security practitioners. Some additional standard-library modules will be removed in Python 3.15 or 3.16, as will be many deprecated classes, functions and methods. == Design philosophy and features == Python is a multi-paradigm programming language. Object-oriented programming and structured programming are fully supported, and many of their features support functional programming and aspect-oriented programming (including metaprogramming and metaobjects). Many other paradigms are supported via extensions, including design by contract and logic programming. Python is often referred to as a 'glue language' because it can seamlessly integrate components written in other languages. Python uses dynamic typing and a combination of reference counting and a cycle-detecting garbage collector for memory management. It uses dynamic name resolution (late binding), which binds method and variable names during program execution. Python's design offers some support for functional programming in the Lisp tradition. It has filter,mapandreduce functions; list comprehensions, dictionaries, sets, and generator expressions. The standard library has two modules (itertools and functools) that implement functional tools borrowed from Haskell and Standard ML. Python's core philosophy is summarized in the Zen of Python (PEP 20), which includes aphorisms such as these: Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Readability counts. However, Python features regularly violate these principles and have received criticism for adding unnecessary language bloat. Responses to these criticisms note that the Zen of Python is a guideline rather than a rule. The addition of some new features had been controversial: Guido van Rossum resigned as Benevolent Dictator for Life after conflict about adding the assignment expression operator in Python 3.8. Nevertheless, rather than building all functionality into its core, Python was designed to be highly extensible via modules. This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. Van Rossum's vision of a small core language with a large standard library and easily extensible interpreter stemmed from his frustrations with ABC, which represented the opposite approach. Python claims to strive for a simpler, less-cluttered syntax and grammar, while giving developers a choice in their coding methodology. In contrast to Perl's motto "there is more than one way to do it", Python advocates an approach where "there should be one—and preferably only one—obvious way to do it.". In practice, however, Python provides many ways to achieve a given goal. There are, for example, at least three ways to format a string literal, with no certainty as to which one a programmer should use. Alex Martelli is a Fellow at the Python Software Foundation and Python book author; he wrote that "To describe something as 'clever' is not considered a compliment in the Python culture." Python's developers usually try to avoid premature optimization; they also reject patches to non-critical parts of the CPython reference implementation that would offer marginal increases in speed at the cost of clarity. Execution speed can be improved by moving speed-critical functions to extension modules written in languages such as C, or by using a just-in-time compiler like PyPy. It is also possible to cross-compile to other languages; but this approach either fails to achieve the expected speed-up, since Python is a very dynamic language, or only a restricted subset of Python is compiled (with potential minor semantic changes). Python's developers aim for the language to be fun to use. This goal is reflected in the name—a tribute to the British comedy group Monty Python—and in playful approaches to some tutorials and reference materials. For instance, some code examples use the terms "spam" and "eggs" (in reference to a Monty Python sketch), rather than the typical terms "foo" and "bar". A common neologism in the Python community is pythonic, which has a wide range of meanings related to program style. Pythonic code may use Python idioms well; be natural or show fluency in the language; or conform with Python's minimalist philosophy and emphasis on readability. == Syntax and semantics == Python is meant to be an easily readable language. Its formatting is visually uncluttered and often uses English keywords where other languages use punctuation. Unlike many other languages, it does not use curly brackets to delimit blocks, and semicolons after statements are allowed but rarely used. It has fewer syntactic exceptions and special cases than C or Pascal. === Indentation === Python uses whitespace indentation, rather than curly brackets or keywords, to delimit blocks. An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block. Thus, the program's visual structure accurately represents its semantic structure. This feature is sometimes termed the off-side rule. Some other languages use indentation this way; but in most, indentation has no semantic meaning. The recommended indent size is four spaces. === Statements and control flow === Python's statements include the following: The assignment statement, using a single equals sign = The if statement, which conditionally executes a block of code, along with else and elif (a contraction of else if) The for statement, which iterates over an iterable object, capturing each element to a local variable for use by the attached block The while statement, which executes a block of code as long as its condition is true The try statement, which allows exceptions raised in its attached code block to be caught and handled by except clauses (or new syntax except* in Python 3.11 for exception groups); the try statement also ensures that clean-up code in a finally block is always run regardless of how the block exits The raise statement, used to raise a specified exception or re-raise a caught exception The class statement, which executes a block of code and attaches its local namespace to a class, for use in object-oriented programming The def statement, which defines a function or method The with statement, which encloses a code block within a context manager, allowing resource-acquisition-is-initialization (RAII)-like behavior and replacing a common try/finally idiom Examples of a context include acquiring a lock before some code is run, and then releasing the lock; or opening and then closing a file The break statement, which exits a loop The continue statement, which skips the rest of the current iteration and continues with the next The del statement, which removes a variable—deleting the reference from the name to the value, and producing an error if the variable is referred to before it is redefined The pass statement, serving as a NOP (i.e., no operation), which is syntactically needed to create an empty code block The assert statement, used in debugging to check for conditions that should apply The yield statement, which returns a value from a generator function (and also an operator); used to implement coroutines The return statement, used to return a value from a function The import and from statements, used to import modules whose functions or variables can be used in the current program The match and case statements, analogous to a switch statement construct, which compares an expression against one or more cases as a control-flow measure The assignment statement (=) binds a name as a reference to a separate, dynamically allocated object. Variables may subsequently be rebound at any time to any object. In Python, a variable name is a generic reference holder without a fixed data type; however, it always refers to some object with a type. This is called dynamic typing—in contrast to statically-typed languages, where each variable may contain only a value of a certain type. Python does not support tail call optimization or first-class continuations; according to Van Rossum, the language never will. However, better support for coroutine-like functionality is provided by extending Python's generators. Before 2.5, generators were lazy iterators; data was passed unidirectionally out of the generator. From Python 2.5 on, it is possible to pass data back into a generator function; and from version 3.3, data can be passed through multiple stack levels. === Expressions === Python's expressions include the following: The +, -, and * operators for mathematical addition, subtraction, and multiplication are similar to other languages, but the behavior of division differs. There are two types of division in Python: floor division (or integer division) //, and floating-point division /. Python uses the ** operator for exponentiation. Python uses the + operator for string concatenation. The language uses the * operator for duplicating a string a specified number of times. The @ infix operator is intended to be used by libraries such as NumPy for matrix multiplication. The syntax :=, called the "walrus operator", was introduced in Python 3.8. This operator assigns values to variables as part of a larger expression. In Python, == compares two objects by value. Python's is operator may be used to compare object identities (i.e., comparison by reference), and comparisons may be chained—for example, a <= b <= c. Python uses and, or, and not as Boolean operators. Python has a type of expression called a list comprehension, and a more general expression called a generator expression. Anonymous functions are implemented using lambda expressions; however, there may be only one expression in each body. Conditional expressions are written as x if c else y. (This is different in operand order from the c ? x : y operator common to many other languages.) Python makes a distinction between lists and tuples. Lists are written as [1, 2, 3], are mutable, and cannot be used as the keys of dictionaries (since dictionary keys must be immutable in Python). Tuples, written as (1, 2, 3), are immutable and thus can be used as the keys of dictionaries, provided that all of the tuple's elements are immutable. The + operator can be used to concatenate two tuples, which does not directly modify their contents, but produces a new tuple containing the elements of both. For example, given the variable t initially equal to (1, 2, 3), executing t = t + (4, 5) first evaluates t + (4, 5), which yields (1, 2, 3, 4, 5); this result is then assigned back to t—thereby effectively "modifying the contents" of t while conforming to the immutable nature of tuple objects. Parentheses are optional for tuples in unambiguous contexts. Python features sequence unpacking where multiple expressions, each evaluating to something assignable (e.g., a variable or a writable property) are associated just as in forming tuple literal; as a whole, the results are then put on the left-hand side of the equal sign in an assignment statement. This statement expects an iterable object on the right-hand side of the equal sign to produce the same number of values as the writable expressions on the left-hand side; while iterating, the statement assigns each of the values produced on the right to the corresponding expression on the left. Python has a "string format" operator % that functions analogously to printf format strings in the C language—e.g. "spam=%s eggs=%d" % ("blah", 2) evaluates to "spam=blah eggs=2". In Python 2.6+ and 3+, this operator was supplemented by the format() method of the str class, e.g., "spam={0} eggs={1}".format("blah", 2). Python 3.6 added "f-strings": spam = "blah"; eggs = 2; f'spam={spam} eggs={eggs}'. Strings in Python can be concatenated by "adding" them (using the same operator as for adding integers and floats); e.g., "spam" + "eggs" returns "spameggs". If strings contain numbers, they are concatenated as strings rather than as integers, e.g. "2" + "2" returns "22". Python supports string literals in several ways: Delimited by single or double quotation marks; single and double quotation marks have equivalent functionality (unlike in Unix shells, Perl, and Perl-influenced languages). Both marks use the backslash (\) as an escape character. String interpolation became available in Python 3.6 as "formatted string literals". Triple-quoted, i.e., starting and ending with three single or double quotation marks; this may span multiple lines and function like here documents in shells, Perl, and Ruby. Raw string varieties, denoted by prefixing the string literal with r. Escape sequences are not interpreted; hence raw strings are useful where literal backslashes are common, such as in regular expressions and Windows-style paths. (Compare "@-quoting" in C#.) Python has array index and array slicing expressions in lists, which are written as a[key], a[start:stop] or a[start:stop:step]. Indexes are zero-based, and negative indexes are relative to the end. Slices take elements from the start index up to, but not including, the stop index. The (optional) third slice parameter, called step or stride, allows elements to be skipped or reversed. Slice indexes may be omitted—for example, a[:] returns a copy of the entire list. Each element of a slice is a shallow copy. In Python, a distinction between expressions and statements is rigidly enforced, in contrast to languages such as Common Lisp, Scheme, or Ruby. This distinction leads to duplicating some functionality, for example: List comprehensions vs. for-loops Conditional expressions vs. if blocks The eval() vs. exec() built-in functions (in Python 2, exec is a statement); the former function is for expressions, while the latter is for statements A statement cannot be part of an expression; because of this restriction, expressions such as list and dict comprehensions (and lambda expressions) cannot contain statements. As a particular case, an assignment statement such as a = 1 cannot be part of the conditional expression of a conditional statement. === Methods === Methods of objects are functions attached to the object's class; the syntax for normal methods and functions, instance.method(argument), is syntactic sugar for Class.method(instance, argument). Python methods have an explicit self parameter to access instance data, in contrast to the implicit self (or this) parameter in some object-oriented programming languages (e.g., C++, Java, Objective-C, Ruby). Python also provides methods, often called dunder methods (because their names begin and end with double underscores); these methods allow user-defined classes to modify how they are handled by native operations including length, comparison, arithmetic, and type conversion. === Typing === Python uses duck typing, and it has typed objects but untyped variable names. Type constraints are not checked at definition time; rather, operations on an object may fail at usage time, indicating that the object is not of an appropriate type. Despite being dynamically typed, Python is strongly typed, forbidding operations that are poorly defined (e.g., adding a number and a string) rather than quietly attempting to interpret them. Python allows programmers to define their own types using classes, most often for object-oriented programming. New instances of classes are constructed by calling the class, for example, SpamClass() or EggsClass()); the classes are instances of the metaclass type (which is an instance of itself), thereby allowing metaprogramming and reflection. Before version 3.0, Python had two kinds of classes, both using the same syntax: old-style and new-style. Current Python versions support the semantics of only the new style. Python supports optional type annotations. These annotations are not enforced by the language, but may be used by external tools such as mypy to catch errors. Mypy also supports a Python compiler called mypyc, which leverages type annotations for optimization. === Arithmetic operations === Python includes conventional symbols for arithmetic operators (+, -, *, /), the floor-division operator //, and the modulo operator %. (With the module operator, a remainder can be negative, e.g., 4 % -3 == -2.) Python also offers the ** symbol for exponentiation, e.g. 5**3 == 125 and 9**0.5 == 3.0; it also offers the matrix‑multiplication operator @ . These operators work as in traditional mathematics; with the same precedence rules, the infix operators + and - can also be unary, to represent positive and negative numbers respectively. Division between integers produces floating-point results. The behavior of division has changed significantly over time: The current version of Python (i.e., since 3.0) changed the / operator to always represent floating-point division, e.g., 5/2 == 2.5. The floor division // operator was introduced. Thus 7//3 == 2, -7//3 == -3, 7.5//3 == 2.0, and -7.5//3 == -3.0. For outdated Python 2.7 adding the from __future__ import division statement causes a module in Python 2.7 to use Python 3.0 rules for division instead (see above). In Python terms, the / operator represents true division (or simply division), while the // operator represents floor division. Before version 3.0, the / operator represents classic division. Rounding towards negative infinity, though a different method than in most languages, adds consistency to Python. For instance, this rounding implies that the equation (a + b)//b == a//b + 1 is always true. The rounding also implies that the equation b*(a//b) + a%b == a is valid for both positive and negative values of a. As expected, the result of a%b lies in the half-open interval [0, b), where b is a positive integer; however, maintaining the validity of the equation requires that the result must lie in the interval (b, 0] when b is negative. Python provides a round function for rounding a float to the nearest integer. For tie-breaking, Python 3 uses the round to even method: round(1.5) and round(2.5) both produce 2. Python versions before 3 used the round-away-from-zero method: round(0.5) is 1.0, and round(-0.5) is −1.0. Python allows Boolean expressions that contain multiple equality relations to be consistent with general usage in mathematics. For example, the expression a < b < c tests whether a is less than b and b is less than c. C-derived languages interpret this expression differently: in C, the expression would first evaluate a < b, resulting in 0 or 1, and that result would then be compared with c. Python uses arbitrary-precision arithmetic for all integer operations. The Decimal type/class in the decimal module provides decimal floating-point numbers to a pre-defined arbitrary precision with several rounding modes. The Fraction class in the fractions module provides arbitrary precision for rational numbers. Due to Python's extensive mathematics library and the third-party library NumPy, the language is frequently used for scientific scripting in tasks such as numerical data processing and manipulation. === Function syntax === Functions are created in Python by using the def keyword. A function is defined similarly to how it is called, by first providing the function name and then the required parameters. Here is an example of a function that prints its inputs: To assign a default value to a function parameter in case no actual value is provided at run time, variable-definition syntax can be used inside the function header. == Code examples == "Hello, World!" program: Program to calculate the factorial of a positive integer: == Libraries == Python's large standard library is commonly cited as one of its greatest strengths. For Internet-facing applications, many standard formats and protocols such as MIME and HTTP are supported. The language includes modules for creating graphical user interfaces, connecting to relational databases, generating pseudorandom numbers, arithmetic with arbitrary-precision decimals, manipulating regular expressions, and unit testing. Some parts of the standard library are covered by specifications—for example, the Web Server Gateway Interface (WSGI) implementation wsgiref follows PEP 333—but most parts are specified by their code, internal documentation, and test suites. However, because most of the standard library is cross-platform Python code, only a few modules must be altered or rewritten for variant implementations. As of 13 March 2025, the Python Package Index (PyPI), the official repository for third-party Python software, contains over 614,339 packages. These have a wide range of functionality, including the following: == Development environments == Most Python implementations (including CPython) include a read–eval–print loop (REPL); this permits the environment to function as a command line interpreter, with which users enter statements sequentially and receive results immediately. Python is also bundled with an integrated development environment (IDE) called IDLE, which is oriented toward beginners. Other shells, including IDLE and IPython, add additional capabilities such as improved auto-completion, session-state retention, and syntax highlighting. Standard desktop IDEs include PyCharm, IntelliJ Idea, Visual Studio Code; there are also web browser-based IDEs, such as the following environments: SageMath, for developing science- and math-related programs; Jupyter Notebooks, an open-source interactive computing platform; PythonAnywhere, a browser-based IDE and hosting environment; and Canopy IDE, a commercial IDE that emphasizes scientific computing. == Implementations == === Reference implementation === CPython is the reference implementation of Python. This implementation is written in C, meeting the C11 standard (since version 3.11, older versions use the C89 standard with several select C99 features), but third-party extensions are not limited to older C versions—e.g., they can be implemented using C11 or C++. CPython compiles Python programs into an intermediate bytecode, which is then executed by a virtual machine. CPython is distributed with a large standard library written in a combination of C and native Python. CPython is available for many platforms, including Windows and most modern Unix-like systems, including macOS (and Apple M1 Macs, since Python 3.9.1, using an experimental installer). Starting with Python 3.9, the Python installer intentionally fails to install on Windows 7 and 8; Windows XP was supported until Python 3.5, with unofficial support for VMS. Platform portability was one of Python's earliest priorities. During development of Python 1 and 2, even OS/2 and Solaris were supported; since that time, support has been dropped for many platforms. All current Python versions (since 3.7) support only operating systems that feature multithreading, by now supporting not nearly as many operating systems (dropping many outdated) than in the past. === Other implementations === All alternative implementations have at least slightly different semantic. For example, an alternative may include unordered dictionaries, in contrast to other current Python versions. As another example in the larger Python ecosystem, PyPy does not support the full C Python API. Alternative implementations include the following: PyPy is a fast, compliant interpreter of Python 2.7 and 3.10. PyPy's just-in-time compiler often improves speed significantly relative to CPython, but PyPy does not support some libraries written in C. PyPy offers support for the RISC-V instruction-set architecture, for example. Codon is an implentation with an ahead-of-time (AOT) compiler, which compiles a statically-typed Python-like language whose "syntax and semantics are nearly identical to Python's, there are some notable differences" For example, Codon uses 64-bit machine integers for speed, not arbitrarily as with Python; Codon developers claim that speedups over CPython are usually on the order of ten to a hundred times. Codon compiles to machine code (via LLVM) and supports native multithreading. Codon can also compile to Python extension modules that can be imported and used from Python. MicroPython and CircuitPython are Python 3 variants that are optimized for microcontrollers, including the Lego Mindstorms EV3. Pyston is a variant of the Python runtime that uses just-in-time compilation to speed up execution of Python programs. Cinder is a performance-oriented fork of CPython 3.8 that features a number of optimizations, including bytecode inline caching, eager evaluation of coroutines, a method-at-a-time JIT, and an experimental bytecode compiler. The Snek embedded computing language "is Python-inspired, but it is not Python. It is possible to write Snek programs that run under a full Python system, but most Python programs will not run under Snek." Snek is compatible with 8-bit AVR microcontrollers such as ATmega 328P-based Arduino, as well as larger microcontrollers that are compatible with MicroPython. Snek is an imperative language that (unlike Python) omits object-oriented programming. Snek supports only one numeric data type, which features 32-bit single precision (resembling JavaScript numbers, though smaller). === Unsupported implementations === Stackless Python is a significant fork of CPython that implements microthreads. This implementation uses the call stack differently, thus allowing massively concurrent programs. PyPy also offers a stackless version. Just-in-time Python compilers have been developed, but are now unsupported: Google began a project named Unladen Swallow in 2009: this project aimed to speed up the Python interpreter five-fold by using LLVM, and improve multithreading capability for scaling to thousands of cores, while typical implementations are limited by the global interpreter lock. Psyco is a discontinued just-in-time specializing compiler, which integrates with CPython and transforms bytecode to machine code at runtime. The emitted code is specialized for certain data types and is faster than standard Python code. Psyco does not support Python 2.7 or later. PyS60 was a Python 2 interpreter for Series 60 mobile phones, which was released by Nokia in 2005. The interpreter implemented many modules from Python's standard library, as well as additional modules for integration with the Symbian operating system. The Nokia N900 also supports Python through the GTK widget library, allowing programs to be written and run on the target device. === Cross-compilers to other languages === There are several compilers/transpilers to high-level object languages; the source language is unrestricted Python, a subset of Python, or a language similar to Python: Brython, Transcrypt, and Pyjs compile Python to JavaScript. (The latest release of Pyjs was in 2012.) Cython compiles a superset of Python to C. The resulting code can be used with Python via direct C-level API calls into the Python interpreter. PyJL compiles/transpiles a subset of Python to "human-readable, maintainable, and high-performance Julia source code". Despite the developers' performance claims, this is not possible for arbitrary Python code; that is, compiling to a faster language or machine code is known to be impossible in the general case. The semantics of Python might potentially be changed, but in many cases speedup is possible with few or no changes in the Python code. The faster Julia source code can then be used from Python or compiled to machine code. Nuitka compiles Python into C. This compiler works with Python 3.4 to 3.12 (and 2.6 and 2.7) for Python's main supported platforms (and Windows 7 or even Windows XP) and for Android. The compiler developers claim full support for Python 3.10, partial support for Python 3.11 and 3.12, and experimental support for Python 3.13. Nuitka supports macOS including Apple Silicon-based versions. The compiler is free of cost, though it has commercial add-ons (e.g., for hiding source code). Numba is a JIT compiler that is used from Python; the compiler translates a subset of Python and NumPy code into fast machine code. This tool is enabled by adding a decorator to the relevant Python code. Pythran compiles a subset of Python 3 to C++ (C++11). RPython can be compiled to C, and it is used to build the PyPy interpreter for Python. The Python → 11l → C++ transpiler compiles a subset of Python 3 to C++ (C++17). There are also specialized compilers: MyHDL is a Python-based hardware description language (HDL) that converts MyHDL code to Verilog or VHDL code. Some older projects existed, as well as compilers not designed for use with Python 3.x and related syntax: Google's Grumpy transpiles Python 2 to Go. The latest release was in 2017. IronPython allows running Python 2.7 programs with the .NET Common Language Runtime. An alpha version (released in 2021), is available for "Python 3.4, although features and behaviors from later versions may be included." Jython compiles Python 2.7 to Java bytecode, allowing the use of Java libraries from a Python program. Pyrex (last released in 2010) and Shed Skin (last released in 2013) compile to C and C++ respectively. === Performance === A perforance comparison among various Python implementations, using a non-numerical (combinatorial) workload, was presented at EuroSciPy '13. In addition, Python's performance relative to other programming languages is benchmarked by The Computer Language Benchmarks Game. There are several approaches to optimizing Python performance, given the inherent slowness of an interpreted language. These approaches include the following strategies or tools: Just-in-time compilation: Dynamically compiling Python code just before it is executed. This technique is used in libraries such as Numba and PyPy. Static compilation: Python code is compiled into machine code sometime before execution. An example of this approach is Cython, which compiles Python into C. Concurrency and parallelism: Multiple tasks can be run simultaneously. Python contains modules such as `multiprocessing` to support this form of parallelism. Moreover, this approach helps to overcome limitations of the Global Interpreter Lock (GIL) in CPU tasks. Efficient data structures: Performance can also be improved by using data types such as Set for membership tests, or deque from collections for queue operations. == Language Development == Python's development is conducted largely through the Python Enhancement Proposal (PEP) process; this process is the primary mechanism for proposing major new features, collecting community input on issues, and documenting Python design decisions. Python coding style is covered in PEP 8. Outstanding PEPs are reviewed and commented on by the Python community and the steering council. Enhancement of the language corresponds with development of the CPython reference implementation. The mailing list python-dev is the primary forum for the language's development. Specific issues were originally discussed in the Roundup bug tracker hosted by the foundation. In 2022, all issues and discussions were migrated to GitHub. Development originally took place on a self-hosted source-code repository running Mercurial, until Python moved to GitHub in January 2017. CPython's public releases have three types, distinguished by which part of the version number is incremented: Backward-incompatible versions, where code is expected to break and must be manually ported. The first part of the version number is incremented. These releases happen infrequently—version 3.0 was released 8 years after 2.0. According to Guido van Rossum, a version 4.0 will probably never exist. Major or "feature" releases are largely compatible with the previous version but introduce new features. The second part of the version number is incremented. Starting with Python 3.9, these releases are expected to occur annually. Each major version is supported by bug fixes for several years after its release. Bug fix releases, which introduce no new features, occur approximately every three months; these releases are made when a sufficient number of bugs have been fixed upstream since the last release. Security vulnerabilities are also patched in these releases. The third and final part of the version number is incremented. Many alpha, beta, and release-candidates are also released as previews and for testing before final releases. Although there is a rough schedule for releases, they are often delayed if the code is not ready yet. Python's development team monitors the state of the code by running a large unit test suite during development. The major academic conference on Python is PyCon. There are also special Python mentoring programs, such as PyLadies. == API documentation generators == Tools that can generate documentation for Python API include pydoc (available as part of the standard library); Sphinx; and Pdoc and its forks, Doxygen and Graphviz. == Naming == Python's name is inspired by the British comedy group Monty Python, whom Python creator Guido van Rossum enjoyed while developing the language. Monty Python references appear frequently in Python code and culture; for example, the metasyntactic variables often used in Python literature are spam and eggs, rather than the traditional foo and bar. The official Python documentation also contains various references to Monty Python routines. Python users are sometimes referred to as "Pythonistas". The affix Py is often used when naming Python applications or libraries. Some examples include the following: Pygame, a binding of Simple DirectMedia Layer to Python (commonly used to create games); PyQt and PyGTK, which bind Qt and GTK to Python respectively; PyPy, a Python implementation originally written in Python; NumPy, a Python library for numerical processing. == Popularity == Since 2003, Python has consistently ranked in the top ten of the most popular programming languages in the TIOBE Programming Community Index; as of December 2022, Python was the most popular language. Python was selected as Programming Language of the Year (for "the highest rise in ratings in a year") in 2007, 2010, 2018, and 2020—the only language to have done so four times as of 2020). In the TIOBE Index, monthly rankings are based on the volume of searches for programming languages on Google, Amazon, Wikipedia, Bing, and 20 other platforms. According to the accompanying graph, Python has shown a marked upward trend since the early 2000s, eventually passing more established languages such as C, C++, and Java. This trend can be attributed to Python's readable syntax, comprehensive standard library, and application in data science and machine learning fields. Large organizations that use Python include Wikipedia, Google, Yahoo!, CERN, NASA, Facebook, Amazon, Instagram, Spotify, and some smaller entities such as Industrial Light & Magic and ITA. The social news networking site Reddit was developed mostly in Python. Organizations that partly use Python include Discord and Baidu. == Types of Use == Python has many uses, including the following: Scripting for web applications Scientific computing Artificial-intelligence and machine-learning projects Graphical user interfaces and desktop environments Embedded scripting in software and hardware products Operating systems Information security Python can serve as a scripting language for web applications, e.g., via the mod_wsgi module for the Apache web server. With Web Server Gateway Interface, a standard API has evolved to facilitate these applications. Web frameworks such as Django, Pylons, Pyramid, TurboGears, web2py, Tornado, Flask, Bottle, and Zope support developers in the design and maintenance of complex applications. Pyjs and IronPython can be used to develop the client-side of Ajax-based applications. SQLAlchemy can be used as a data mapper to a relational database. Twisted is a framework to program communication between computers; this framework is used by Dropbox, for example. Libraries such as NumPy, SciPy and Matplotlib allow the effective use of Python in scientific computing, with specialized libraries such as Biopython and Astropy providing domain-specific functionality. SageMath is a computer algebra system with a notebook interface that is programmable in Python; the SageMath library covers many aspects of mathematics, including algebra, combinatorics, numerical mathematics, number theory, and calculus. OpenCV has Python bindings with a rich set of features for computer vision and image processing. Python is commonly used in artificial-intelligence and machine-learning projects, with support from libraries such as TensorFlow, Keras, Pytorch, scikit-learn and ProbLog (a logic language). As a scripting language with a modular architecture, simple syntax, and rich text processing tools, Python is often used for natural language processing. The combination of Python and Prolog has proven useful for AI applications, with Prolog providing knowledge representation and reasoning capabilities. The Janus system, in particular, exploits similarities between these two languages, in part because of their dynamic typing and their simple, recursive data structures. This combination is typically applied natural language processing, visual query answering, geospatial reasoning, and handling semantic web data. The Natlog system, implemented in Python, uses Definite Clause Grammars (DCGs) to create prompts for two types of generators: text-to-text generators such as GPT3, and text-to-image generators such as DALL-E or Stable Diffusion. Python can be used for graphical user interfaces (GUIs), by using libraries such as Tkinter. Similarly, for the One Laptop per Child XO computer, most of the Sugar desktop environment is written in Python (as of 2008). Python is embedded in many software products (and some hardware products) as a scripting language. These products include the following: finite element method software such as Abaqus, 3D parametric modelers such as FreeCAD, 3D animation packages such as 3ds Max, Blender, Cinema 4D, Lightwave, Houdini, Maya, modo, MotionBuilder, Softimage, the visual effects compositor Nuke, 2D imaging programs such as GIMP, Inkscape, Scribus and Paint Shop Pro, and musical notation programs such as scorewriter and capella. Similarly, GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers. Esri promotes Python as the best choice for writing scripts in ArcGIS. Python has also been used in several video games, and it has been adopted as first of the three programming languages available in Google App Engine (the other two being Java and Go). LibreOffice includes Python, and its developers plan to replace Java with Python; LibreOffice's Python Scripting Provider is a core feature since version 4.0 (from 7 February 2013). Among hardware products, the Raspberry Pi single-board computer project has adopted Python as its main user-programming language. Many operating systems include Python as a standard component. Python ships with most Linux distributions, AmigaOS 4 (using Python 2.7), FreeBSD (as a package), NetBSD, and OpenBSD (as a package); it can be used from the command line (terminal). Many Linux distributions use installers written in Python: Ubuntu uses the Ubiquity installer, while Red Hat Linux and Fedora Linux use the Anaconda installer. Gentoo Linux uses Python in its package management system, Portage. Python is used extensively in the information security industry, including in exploit development. == Languages influenced by Python == Python's design and philosophy have influenced many other programming languages: Boo uses indentation, a similar syntax, and a similar object model. Cobra uses indentation and a similar syntax; its Acknowledgements document lists Python first among influencing languages. CoffeeScript, a programming language that cross-compiles to JavaScript, has a Python-inspired syntax. ECMAScript–JavaScript borrowed iterators and generators from Python. GDScript, a Python-like scripting language that is built in to the Godot game engine. Go is designed for "speed of working in a dynamic language like Python"; Go shares Python's syntax for slicing arrays. Groovy was motivated by a desire to incorporate the Python design philosophy into Java. Julia was designed to be "as usable for general programming as Python". Mojo is a non-strict superset of Python (e.g., omitting classes, and adding struct). Nim uses indentation and a similar syntax. Ruby's creator, Yukihiro Matsumoto, said that "I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. That's why I decided to design my own language." Swift, a programming language developed by Apple, has some Python-inspired syntax. Kotlin blends Python and Java features, which minimizes boilerplate code and enhances developer efficiency. Python's development practices have also been emulated by other languages. For example, Python requires a document that describes the rationale and context for any language change; this document is known as a Python Enhancement Proposal or PEP. This practice is also used by the developers of Tcl, Erlang, and Swift. == See also == Python syntax and semantics pip (package manager) List of programming languages History of programming languages Comparison of programming languages == Notes == == References == === Sources === "Python for Artificial Intelligence". Python Wiki. 19 July 2012. Archived from the original on 1 November 2012. Retrieved 3 December 2012. Paine, Jocelyn, ed. (August 2005). "AI in Python". AI Expert Newsletter. Amzi!. Archived from the original on 26 March 2012. Retrieved 11 February 2012. "PyAIML 0.8.5 : Python Package Index". Pypi.python.org. Retrieved 17 July 2013. Russell, Stuart J. & Norvig, Peter (2009). Artificial Intelligence: A Modern Approach (3rd ed.). Upper Saddle River, NJ: Prentice Hall. ISBN 978-0-13-604259-4. == Further reading == Downey, Allen (July 2024). Think Python: How to Think Like a Computer Scientist (3rd ed.). O'Reilly Media. ISBN 978-1098155438. Lutz, Mark (2013). Learning Python (5th ed.). O'Reilly Media. ISBN 978-0-596-15806-4. Summerfield, Mark (2009). Programming in Python 3 (2nd ed.). Addison-Wesley Professional. ISBN 978-0-321-68056-3. Ramalho, Luciano (May 2022). Fluent Python. O'Reilly Media. ISBN 978-1-4920-5632-4. == External links == Official website The Python Tutorial
https://en.wikipedia.org/wiki/Python_(programming_language)
In computer science, array programming refers to solutions that allow the application of operations to an entire set of values at once. Such solutions are commonly used in scientific and engineering settings. Modern programming languages that support array programming (also known as vector or multidimensional languages) have been engineered specifically to generalize operations on scalars to apply transparently to vectors, matrices, and higher-dimensional arrays. These include APL, J, Fortran, MATLAB, Analytica, Octave, R, Cilk Plus, Julia, Perl Data Language (PDL), Raku (programming language). In these languages, an operation that operates on entire arrays can be called a vectorized operation, regardless of whether it is executed on a vector processor, which implements vector instructions. Array programming primitives concisely express broad ideas about data manipulation. The level of concision can be dramatic in certain cases: it is not uncommon to find array programming language one-liners that require several pages of object-oriented code. == Concepts of array == The fundamental idea behind array programming is that operations apply at once to an entire set of values. This makes it a high-level programming model as it allows the programmer to think and operate on whole aggregates of data, without having to resort to explicit loops of individual scalar operations. Kenneth E. Iverson described the rationale behind array programming (actually referring to APL) as follows: most programming languages are decidedly inferior to mathematical notation and are little used as tools of thought in ways that would be considered significant by, say, an applied mathematician. The thesis is that the advantages of executability and universality found in programming languages can be effectively combined, in a single coherent language, with the advantages offered by mathematical notation. it is important to distinguish the difficulty of describing and of learning a piece of notation from the difficulty of mastering its implications. For example, learning the rules for computing a matrix product is easy, but a mastery of its implications (such as its associativity, its distributivity over addition, and its ability to represent linear functions and geometric operations) is a different and much more difficult matter. Indeed, the very suggestiveness of a notation may make it seem harder to learn because of the many properties it suggests for explorations. [...] Users of computers and programming languages are often concerned primarily with the efficiency of execution of algorithms, and might, therefore, summarily dismiss many of the algorithms presented here. Such dismissal would be short-sighted since a clear statement of an algorithm can usually be used as a basis from which one may easily derive a more efficient algorithm. The basis behind array programming and thinking is to find and exploit the properties of data where individual elements are similar or adjacent. Unlike object orientation which implicitly breaks down data to its constituent parts (or scalar quantities), array orientation looks to group data and apply a uniform handling. Function rank is an important concept to array programming languages in general, by analogy to tensor rank in mathematics: functions that operate on data may be classified by the number of dimensions they act on. Ordinary multiplication, for example, is a scalar ranked function because it operates on zero-dimensional data (individual numbers). The cross product operation is an example of a vector rank function because it operates on vectors, not scalars. Matrix multiplication is an example of a 2-rank function, because it operates on 2-dimensional objects (matrices). Collapse operators reduce the dimensionality of an input data array by one or more dimensions. For example, summing over elements collapses the input array by 1 dimension. == Uses == Array programming is very well suited to implicit parallelization; a topic of much research nowadays. Further, Intel and compatible CPUs developed and produced after 1997 contained various instruction set extensions, starting from MMX and continuing through SSSE3 and 3DNow!, which include rudimentary SIMD array capabilities. This has continued into the 2020s with instruction sets such as AVX-512, making modern CPUs sophisticated vector processors. Array processing is distinct from parallel processing in that one physical processor performs operations on a group of items simultaneously while parallel processing aims to split a larger problem into smaller ones (MIMD) to be solved piecemeal by numerous processors. Processors with multiple cores and GPUs with thousands of general computing cores are common as of 2023. == Languages == The canonical examples of array programming languages are Fortran, APL, and J. Others include: A+, Analytica, Chapel, IDL, Julia, K, Klong, Q, MATLAB, GNU Octave, Scilab, FreeMat, Perl Data Language (PDL), R, Raku, S-Lang, SAC, Nial, ZPL, Futhark, and TI-BASIC. === Scalar languages === In scalar languages such as C and Pascal, operations apply only to single values, so a+b expresses the addition of two numbers. In such languages, adding one array to another requires indexing and looping, the coding of which is tedious. In array-based languages, for example in Fortran, the nested for-loop above can be written in array-format in one line, or alternatively, to emphasize the array nature of the objects, While scalar languages like C do not have native array programming elements as part of the language proper, this does not mean programs written in these languages never take advantage of the underlying techniques of vectorization (i.e., utilizing a CPU's vector-based instructions if it has them or by using multiple CPU cores). Some C compilers like GCC at some optimization levels detect and vectorize sections of code that its heuristics determine would benefit from it. Another approach is given by the OpenMP API, which allows one to parallelize applicable sections of code by taking advantage of multiple CPU cores. === Array languages === In array languages, operations are generalized to apply to both scalars and arrays. Thus, a+b expresses the sum of two scalars if a and b are scalars, or the sum of two arrays if they are arrays. An array language simplifies programming but possibly at a cost known as the abstraction penalty. Because the additions are performed in isolation from the rest of the coding, they may not produce the optimally most efficient code. (For example, additions of other elements of the same array may be subsequently encountered during the same execution, causing unnecessary repeated lookups.) Even the most sophisticated optimizing compiler would have an extremely hard time amalgamating two or more apparently disparate functions which might appear in different program sections or sub-routines, even though a programmer could do this easily, aggregating sums on the same pass over the array to minimize overhead). ==== Ada ==== The previous C code would become the following in the Ada language, which supports array-programming syntax. ==== APL ==== APL uses single character Unicode symbols with no syntactic sugar. This operation works on arrays of any rank (including rank 0), and on a scalar and an array. Dyalog APL extends the original language with augmented assignments: ==== Analytica ==== Analytica provides the same economy of expression as Ada. A := A + B; ==== BASIC ==== Dartmouth BASIC had MAT statements for matrix and array manipulation in its third edition (1966). ==== Mata ==== Stata's matrix programming language Mata supports array programming. Below, we illustrate addition, multiplication, addition of a matrix and a scalar, element by element multiplication, subscripting, and one of Mata's many inverse matrix functions. ==== MATLAB ==== The implementation in MATLAB allows the same economy allowed by using the Fortran language. A variant of the MATLAB language is the GNU Octave language, which extends the original language with augmented assignments: Both MATLAB and GNU Octave natively support linear algebra operations such as matrix multiplication, matrix inversion, and the numerical solution of system of linear equations, even using the Moore–Penrose pseudoinverse. The Nial example of the inner product of two arrays can be implemented using the native matrix multiplication operator. If a is a row vector of size [1 n] and b is a corresponding column vector of size [n 1]. a * b; By contrast, the entrywise product is implemented as: a .* b; The inner product between two matrices having the same number of elements can be implemented with the auxiliary operator (:), which reshapes a given matrix into a column vector, and the transpose operator ': A(:)' * B(:); ==== rasql ==== The rasdaman query language is a database-oriented array-programming language. For example, two arrays could be added with the following query: ==== R ==== The R language supports array paradigm by default. The following example illustrates a process of multiplication of two matrices followed by an addition of a scalar (which is, in fact, a one-element vector) and a vector: ==== Raku ==== Raku supports the array paradigm via its Metaoperators. The following example demonstrates the addition of arrays @a and @b using the Hyper-operator in conjunction with the plus operator. == Mathematical reasoning and language notation == The matrix left-division operator concisely expresses some semantic properties of matrices. As in the scalar equivalent, if the (determinant of the) coefficient (matrix) A is not null then it is possible to solve the (vectorial) equation A * x = b by left-multiplying both sides by the inverse of A: A−1 (in both MATLAB and GNU Octave languages: A^-1). The following mathematical statements hold when A is a full rank square matrix: A^-1 *(A * x)==A^-1 * (b) (A^-1 * A)* x ==A^-1 * b (matrix-multiplication associativity) x = A^-1 * b where == is the equivalence relational operator. The previous statements are also valid MATLAB expressions if the third one is executed before the others (numerical comparisons may be false because of round-off errors). If the system is overdetermined – so that A has more rows than columns – the pseudoinverse A+ (in MATLAB and GNU Octave languages: pinv(A)) can replace the inverse A−1, as follows: pinv(A) *(A * x)==pinv(A) * (b) (pinv(A) * A)* x ==pinv(A) * b (matrix-multiplication associativity) x = pinv(A) * b However, these solutions are neither the most concise ones (e.g. still remains the need to notationally differentiate overdetermined systems) nor the most computationally efficient. The latter point is easy to understand when considering again the scalar equivalent a * x = b, for which the solution x = a^-1 * b would require two operations instead of the more efficient x = b / a. The problem is that generally matrix multiplications are not commutative as the extension of the scalar solution to the matrix case would require: (a * x)/ a ==b / a (x * a)/ a ==b / a (commutativity does not hold for matrices!) x * (a / a)==b / a (associativity also holds for matrices) x = b / a The MATLAB language introduces the left-division operator \ to maintain the essential part of the analogy with the scalar case, therefore simplifying the mathematical reasoning and preserving the conciseness: A \ (A * x)==A \ b (A \ A)* x ==A \ b (associativity also holds for matrices, commutativity is no more required) x = A \ b This is not only an example of terse array programming from the coding point of view but also from the computational efficiency perspective, which in several array programming languages benefits from quite efficient linear algebra libraries such as ATLAS or LAPACK. Returning to the previous quotation of Iverson, the rationale behind it should now be evident: it is important to distinguish the difficulty of describing and of learning a piece of notation from the difficulty of mastering its implications. For example, learning the rules for computing a matrix product is easy, but a mastery of its implications (such as its associativity, its distributivity over addition, and its ability to represent linear functions and geometric operations) is a different and much more difficult matter. Indeed, the very suggestiveness of a notation may make it seem harder to learn because of the many properties it suggests for explorations. == Third-party libraries == The use of specialized and efficient libraries to provide more terse abstractions is also common in other programming languages. In C++ several linear algebra libraries exploit the language's ability to overload operators. In some cases a very terse abstraction in those languages is explicitly influenced by the array programming paradigm, as the NumPy extension library to Python, Armadillo and Blitz++ libraries do. == See also == Array slicing List of array programming languages Automatic vectorization == References == == External links == "No stinking loops" programming Discovering Array Languages "Types of Arrays" programming
https://en.wikipedia.org/wiki/Array_programming
Defensive programming is a form of defensive design intended to develop programs that are capable of detecting potential security abnormalities and make predetermined responses. It ensures the continuing function of a piece of software under unforeseen circumstances. Defensive programming practices are often used where high availability, safety, or security is needed. Defensive programming is an approach to improve software and source code, in terms of: General quality – reducing the number of software bugs and problems. Making the source code comprehensible – the source code should be readable and understandable so it is approved in a code audit. Making the software behave in a predictable manner despite unexpected inputs or user actions. Overly defensive programming, however, may safeguard against errors that will never be encountered, thus incurring run-time and maintenance costs. == Secure programming == Secure programming is the subset of defensive programming concerned with computer security. Security is the concern, not necessarily safety or availability (the software may be allowed to fail in certain ways). As with all kinds of defensive programming, avoiding bugs is a primary objective; however, the motivation is not as much to reduce the likelihood of failure in normal operation (as if safety were the concern), but to reduce the attack surface – the programmer must assume that the software might be misused actively to reveal bugs, and that bugs could be exploited maliciously. The function will result in undefined behavior when the input is over 1000 characters. Some programmers may not feel that this is a problem, supposing that no user will enter such a long input. This particular bug demonstrates a vulnerability which enables buffer overflow exploits. Here is a solution to this example: == Offensive programming == Offensive programming is a category of defensive programming, with the added emphasis that certain errors should not be handled defensively. In this practice, only errors from outside the program's control are to be handled (such as user input); the software itself, as well as data from within the program's line of defense, are to be trusted in this methodology. === Trusting internal data validity === Overly defensive programming Offensive programming === Trusting software components === Overly defensive programming Offensive programming == Techniques == Here are some defensive programming techniques: === Intelligent source code reuse === If existing code is tested and known to work, reusing it may reduce the chance of bugs being introduced. However, reusing code is not always good practice. Reuse of existing code, especially when widely distributed, can allow for exploits to be created that target a wider audience than would otherwise be possible and brings with it all the security and vulnerabilities of the reused code. When considering using existing source code, a quick review of the modules(sub-sections such as classes or functions) will help eliminate or make the developer aware of any potential vulnerabilities and ensure it is suitable to use in the project. ==== Legacy problems ==== Before reusing old source code, libraries, APIs, configurations and so forth, it must be considered if the old work is valid for reuse, or if it is likely to be prone to legacy problems. Legacy problems are problems inherent when old designs are expected to work with today's requirements, especially when the old designs were not developed or tested with those requirements in mind. Many software products have experienced problems with old legacy source code; for example: Legacy code may not have been designed under a defensive programming initiative, and might therefore be of much lower quality than newly designed source code. Legacy code may have been written and tested under conditions which no longer apply. The old quality assurance tests may have no validity any more. Example 1: legacy code may have been designed for ASCII input but now the input is UTF-8. Example 2: legacy code may have been compiled and tested on 32-bit architectures, but when compiled on 64-bit architectures, new arithmetic problems may occur (e.g., invalid signedness tests, invalid type casts, etc.). Example 3: legacy code may have been targeted for offline machines, but becomes vulnerable once network connectivity is added. Legacy code is not written with new problems in mind. For example, source code written in 1990 is likely to be prone to many code injection vulnerabilities, because most such problems were not widely understood at that time. Notable examples of the legacy problem: BIND 9, presented by Paul Vixie and David Conrad as "BINDv9 is a complete rewrite", "Security was a key consideration in design", naming security, robustness, scalability and new protocols as key concerns for rewriting old legacy code. Microsoft Windows suffered from "the" Windows Metafile vulnerability and other exploits related to the WMF format. Microsoft Security Response Center describes the WMF-features as "Around 1990, WMF support was added... This was a different time in the security landscape... were all completely trusted", not being developed under the security initiatives at Microsoft. Oracle is combating legacy problems, such as old source code written without addressing concerns of SQL injection and privilege escalation, resulting in many security vulnerabilities which have taken time to fix and also generated incomplete fixes. This has given rise to heavy criticism from security experts such as David Litchfield, Alexander Kornbrust, Cesar Cerrudo. An additional criticism is that default installations (largely a legacy from old versions) are not aligned with their own security recommendations, such as Oracle Database Security Checklist, which is hard to amend as many applications require the less secure legacy settings to function correctly. === Canonicalization === Malicious users are likely to invent new kinds of representations of incorrect data. For example, if a program attempts to reject accessing the file "/etc/passwd", a cracker might pass another variant of this file name, like "/etc/./passwd". Canonicalization libraries can be employed to avoid bugs due to non-canonical input. === Low tolerance against "potential" bugs === Assume that code constructs that appear to be problem prone (similar to known vulnerabilities, etc.) are bugs and potential security flaws. The basic rule of thumb is: "I'm not aware of all types of security exploits. I must protect against those I do know of and then I must be proactive!". === Other ways of securing code === One of the most common problems is unchecked use of constant-size or pre-allocated structures for dynamic-size data such as inputs to the program (the buffer overflow problem). This is especially common for string data in C. C library functions like gets should never be used since the maximum size of the input buffer is not passed as an argument. C library functions like scanf can be used safely, but require the programmer to take care with the selection of safe format strings, by sanitizing it before using it. Encrypt/authenticate all important data transmitted over networks. Do not attempt to implement your own encryption scheme, use a proven one instead. Message checking with a hash or similar technology will also help secure data sent over a network. ==== The three rules of data security ==== All data is important until proven otherwise. All data is tainted until proven otherwise. All code is insecure until proven otherwise. You cannot prove the security of any code in userland, or, more commonly known as: "never trust the client". These three rules about data security describe how to handle any data, internally or externally sourced: All data is important until proven otherwise - means that all data must be verified as garbage before being destroyed. All data is tainted until proven otherwise - means that all data must be handled in a way that does not expose the rest of the runtime environment without verifying integrity. All code is insecure until proven otherwise - while a slight misnomer, does a good job reminding us to never assume our code is secure as bugs or undefined behavior may expose the project or system to attacks such as common SQL injection attacks. ==== More Information ==== If data is to be checked for correctness, verify that it is correct, not that it is incorrect. Design by contract Assertions (also called assertive programming) Prefer exceptions to return codes Generally speaking, it is preferable to throw exception messages that enforce part of your API contract and guide the developer instead of returning error code values that do not point to where the exception occurred or what the program stack looked liked, Better logging and exception handling will increase robustness and security of your software, while minimizing developer stress. == See also == Computer security == References == == External links == CERT Secure Coding Standards
https://en.wikipedia.org/wiki/Defensive_programming
Generic programming is a style of computer programming in which algorithms are written in terms of data types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. This approach, pioneered in the programming language ML in 1973, permits writing common functions or data types that differ only in the set of types on which they operate when used, thus reducing duplicate code. Generic programming was introduced to the mainstream with Ada in 1977. With templates in C++, generic programming became part of the repertoire of professional library design. The techniques were further improved and parameterized types were introduced in the influential 1994 book Design Patterns. New techniques were introduced by Andrei Alexandrescu in his 2001 book Modern C++ Design: Generic Programming and Design Patterns Applied. Subsequently, D implemented the same ideas. Such software entities are known as generics in Ada, C#, Delphi, Eiffel, F#, Java, Nim, Python, Go, Rust, Swift, TypeScript, and Visual Basic (.NET). They are known as parametric polymorphism in ML, Scala, Julia, and Haskell. (Haskell terminology also uses the term generic for a related but somewhat different concept.) The term generic programming was originally coined by David Musser and Alexander Stepanov in a more specific sense than the above, to describe a programming paradigm in which fundamental requirements on data types are abstracted from across concrete examples of algorithms and data structures and formalized as concepts, with generic functions implemented in terms of these concepts, typically using language genericity mechanisms as described above. == Stepanov–Musser and other generic programming paradigms == Generic programming is defined in Musser & Stepanov (1989) as follows, Generic programming centers around the idea of abstracting from concrete, efficient algorithms to obtain generic algorithms that can be combined with different data representations to produce a wide variety of useful software. The "generic programming" paradigm is an approach to software decomposition whereby fundamental requirements on types are abstracted from across concrete examples of algorithms and data structures and formalized as concepts, analogously to the abstraction of algebraic theories in abstract algebra. Early examples of this programming approach were implemented in Scheme and Ada, although the best known example is the Standard Template Library (STL), which developed a theory of iterators that is used to decouple sequence data structures and the algorithms operating on them. For example, given N sequence data structures, e.g. singly linked list, vector etc., and M algorithms to operate on them, e.g. find, sort etc., a direct approach would implement each algorithm specifically for each data structure, giving N × M combinations to implement. However, in the generic programming approach, each data structure returns a model of an iterator concept (a simple value type that can be dereferenced to retrieve the current value, or changed to point to another value in the sequence) and each algorithm is instead written generically with arguments of such iterators, e.g. a pair of iterators pointing to the beginning and end of the subsequence or range to process. Thus, only N + M data structure-algorithm combinations need be implemented. Several iterator concepts are specified in the STL, each a refinement of more restrictive concepts e.g. forward iterators only provide movement to the next value in a sequence (e.g. suitable for a singly linked list or a stream of input data), whereas a random-access iterator also provides direct constant-time access to any element of the sequence (e.g. suitable for a vector). An important point is that a data structure will return a model of the most general concept that can be implemented efficiently—computational complexity requirements are explicitly part of the concept definition. This limits the data structures a given algorithm can be applied to and such complexity requirements are a major determinant of data structure choice. Generic programming similarly has been applied in other domains, e.g. graph algorithms. Although this approach often uses language features of compile-time genericity and templates, it is independent of particular language-technical details. Generic programming pioneer Alexander Stepanov wrote, Generic programming is about abstracting and classifying algorithms and data structures. It gets its inspiration from Knuth and not from type theory. Its goal is the incremental construction of systematic catalogs of useful, efficient and abstract algorithms and data structures. Such an undertaking is still a dream. I believe that iterator theories are as central to Computer Science as theories of rings or Banach spaces are central to Mathematics. Bjarne Stroustrup noted, Following Stepanov, we can define generic programming without mentioning language features: Lift algorithms and data structures from concrete examples to their most general and abstract form. Other programming paradigms that have been described as generic programming include Datatype generic programming as described in "Generic Programming – an Introduction". The Scrap your boilerplate approach is a lightweight generic programming approach for Haskell. In this article we distinguish the high-level programming paradigms of generic programming, above, from the lower-level programming language genericity mechanisms used to implement them (see Programming language support for genericity). For further discussion and comparison of generic programming paradigms, see. == Programming language support for genericity == Genericity facilities have existed in high-level languages since at least the 1970s in languages such as ML, CLU and Ada, and were subsequently adopted by many object-based and object-oriented languages, including BETA, C++, D, Eiffel, Java, and DEC's now defunct Trellis-Owl. Genericity is implemented and supported differently in various programming languages; the term "generic" has also been used differently in various programming contexts. For example, in Forth the compiler can execute code while compiling and one can create new compiler keywords and new implementations for those words on the fly. It has few words that expose the compiler behaviour and therefore naturally offers genericity capacities that, however, are not referred to as such in most Forth texts. Similarly, dynamically typed languages, especially interpreted ones, usually offer genericity by default as both passing values to functions and value assignment are type-indifferent and such behavior is often used for abstraction or code terseness, however this is not typically labeled genericity as it's a direct consequence of the dynamic typing system employed by the language. The term has been used in functional programming, specifically in Haskell-like languages, which use a structural type system where types are always parametric and the actual code on those types is generic. These uses still serve a similar purpose of code-saving and rendering an abstraction. Arrays and structs can be viewed as predefined generic types. Every usage of an array or struct type instantiates a new concrete type, or reuses a previous instantiated type. Array element types and struct element types are parameterized types, which are used to instantiate the corresponding generic type. All this is usually built-in in the compiler and the syntax differs from other generic constructs. Some extensible programming languages try to unify built-in and user defined generic types. A broad survey of genericity mechanisms in programming languages follows. For a specific survey comparing suitability of mechanisms for generic programming, see. === In object-oriented languages === When creating container classes in statically typed languages, it is inconvenient to write specific implementations for each datatype contained, especially if the code for each datatype is virtually identical. For example, in C++, this duplication of code can be circumvented by defining a class template: Above, T is a placeholder for whatever type is specified when the list is created. These "containers-of-type-T", commonly called templates, allow a class to be reused with different datatypes as long as certain contracts such as subtypes and signature are kept. This genericity mechanism should not be confused with inclusion polymorphism, which is the algorithmic usage of exchangeable sub-classes: for instance, a list of objects of type Moving_Object containing objects of type Animal and Car. Templates can also be used for type-independent functions as in the Swap example below: The C++ template construct used above is widely cited as the genericity construct that popularized the notion among programmers and language designers and supports many generic programming idioms. The D language also offers fully generic-capable templates based on the C++ precedent but with a simplified syntax. The Java language has provided genericity facilities syntactically based on C++'s since the introduction of Java Platform, Standard Edition (J2SE) 5.0. C# 2.0, Oxygene 1.5 (formerly Chrome) and Visual Basic (.NET) 2005 have constructs that exploit the support for generics present in Microsoft .NET Framework since version 2.0. ==== Generics in Ada ==== Ada has had generics since it was first designed in 1977–1980. The standard library uses generics to provide many services. Ada 2005 adds a comprehensive generic container library to the standard library, which was inspired by C++'s Standard Template Library. A generic unit is a package or a subprogram that takes one or more generic formal parameters. A generic formal parameter is a value, a variable, a constant, a type, a subprogram, or even an instance of another, designated, generic unit. For generic formal types, the syntax distinguishes between discrete, floating-point, fixed-point, access (pointer) types, etc. Some formal parameters can have default values. To instantiate a generic unit, the programmer passes actual parameters for each formal. The generic instance then behaves just like any other unit. It is possible to instantiate generic units at run-time, for example inside a loop. ===== Example ===== The specification of a generic package: Instantiating the generic package: Using an instance of a generic package: ===== Advantages and limits ===== The language syntax allows precise specification of constraints on generic formal parameters. For example, it is possible to specify that a generic formal type will only accept a modular type as the actual. It is also possible to express constraints between generic formal parameters; for example: In this example, Array_Type is constrained by both Index_Type and Element_Type. When instantiating the unit, the programmer must pass an actual array type that satisfies these constraints. The disadvantage of this fine-grained control is a complicated syntax, but, because all generic formal parameters are completely defined in the specification, the compiler can instantiate generics without looking at the body of the generic. Unlike C++, Ada does not allow specialised generic instances, and requires that all generics be instantiated explicitly. These rules have several consequences: the compiler can implement shared generics: the object code for a generic unit can be shared between all instances (unless the programmer requests inlining of subprograms, of course). As further consequences: there is no possibility of code bloat (code bloat is common in C++ and requires special care, as explained below). it is possible to instantiate generics at run-time, and at compile time, since no new object code is required for a new instance. actual objects corresponding to a generic formal object are always considered to be non-static inside the generic; see Generic formal objects in the Wikibook for details and consequences. all instances of a generic being exactly the same, it is easier to review and understand programs written by others; there are no "special cases" to take into account. all instantiations being explicit, there are no hidden instantiations that might make it difficult to understand the program. Ada does not permit arbitrary computation at compile time, because operations on generic arguments are performed at runtime. ==== Templates in C++ ==== C++ uses templates to enable generic programming techniques. The C++ Standard Library includes the Standard Template Library or STL that provides a framework of templates for common data structures and algorithms. Templates in C++ may also be used for template metaprogramming, which is a way of pre-evaluating some of the code at compile-time rather than run-time. Using template specialization, C++ Templates are Turing complete. ===== Technical overview ===== There are many kinds of templates, the most common being function templates and class templates. A function template is a pattern for creating ordinary functions based upon the parameterizing types supplied when instantiated. For example, the C++ Standard Template Library contains the function template max(x, y) that creates functions that return either x or y, whichever is larger. max() could be defined like this: Specializations of this function template, instantiations with specific types, can be called just like an ordinary function: The compiler examines the arguments used to call max and determines that this is a call to max(int, int). It then instantiates a version of the function where the parameterizing type T is int, making the equivalent of the following function: This works whether the arguments x and y are integers, strings, or any other type for which the expression x < y is sensible, or more specifically, for any type for which operator< is defined. Common inheritance is not needed for the set of types that can be used, and so it is very similar to duck typing. A program defining a custom data type can use operator overloading to define the meaning of < for that type, thus allowing its use with the max() function template. While this may seem a minor benefit in this isolated example, in the context of a comprehensive library like the STL it allows the programmer to get extensive functionality for a new data type, just by defining a few operators for it. Merely defining < allows a type to be used with the standard sort(), stable_sort(), and binary_search() algorithms or to be put inside data structures such as sets, heaps, and associative arrays. C++ templates are completely type safe at compile time. As a demonstration, the standard type complex does not define the < operator, because there is no strict order on complex numbers. Therefore, max(x, y) will fail with a compile error, if x and y are complex values. Likewise, other templates that rely on < cannot be applied to complex data unless a comparison (in the form of a functor or function) is provided. E.g.: A complex cannot be used as key for a map unless a comparison is provided. Unfortunately, compilers historically generate somewhat esoteric, long, and unhelpful error messages for this sort of error. Ensuring that a certain object adheres to a method protocol can alleviate this issue. Languages which use compare instead of < can also use complex values as keys. Another kind of template, a class template, extends the same concept to classes. A class template specialization is a class. Class templates are often used to make generic containers. For example, the STL has a linked list container. To make a linked list of integers, one writes list<int>. A list of strings is denoted list<string>. A list has a set of standard functions associated with it, that work for any compatible parameterizing types. ===== Template specialization ===== A powerful feature of C++'s templates is template specialization. This allows alternative implementations to be provided based on certain characteristics of the parameterized type that is being instantiated. Template specialization has two purposes: to allow certain forms of optimization, and to reduce code bloat. For example, consider a sort() template function. One of the primary activities that such a function does is to swap or exchange the values in two of the container's positions. If the values are large (in terms of the number of bytes it takes to store each of them), then it is often quicker to first build a separate list of pointers to the objects, sort those pointers, and then build the final sorted sequence. If the values are quite small however it is usually fastest to just swap the values in-place as needed. Furthermore, if the parameterized type is already of some pointer-type, then there is no need to build a separate pointer array. Template specialization allows the template creator to write different implementations and to specify the characteristics that the parameterized type(s) must have for each implementation to be used. Unlike function templates, class templates can be partially specialized. That means that an alternate version of the class template code can be provided when some of the template parameters are known, while leaving other template parameters generic. This can be used, for example, to create a default implementation (the primary specialization) that assumes that copying a parameterizing type is expensive and then create partial specializations for types that are cheap to copy, thus increasing overall efficiency. Clients of such a class template just use specializations of it without needing to know whether the compiler used the primary specialization or some partial specialization in each case. Class templates can also be fully specialized, which means that an alternate implementation can be provided when all of the parameterizing types are known. ===== Advantages and disadvantages ===== Some uses of templates, such as the max() function, were formerly filled by function-like preprocessor macros (a legacy of the C language). For example, here is a possible implementation of such macro: Macros are expanded (copy pasted) by the preprocessor, before program compiling; templates are actual real functions. Macros are always expanded inline; templates can also be inline functions when the compiler deems it appropriate. However, templates are generally considered an improvement over macros for these purposes. Templates are type-safe. Templates avoid some of the common errors found in code that makes heavy use of function-like macros, such as evaluating parameters with side effects twice. Perhaps most importantly, templates were designed to be applicable to much larger problems than macros. There are four primary drawbacks to the use of templates: supported features, compiler support, poor error messages (usually with pre C++20 substitution failure is not an error (SFINAE)), and code bloat: Templates in C++ lack many features, which makes implementing them and using them in a straightforward way often impossible. Instead programmers have to rely on complex tricks which leads to bloated, hard to understand and hard to maintain code. Current developments in the C++ standards exacerbate this problem by making heavy use of these tricks and building a lot of new features for templates on them or with them intended. Many compilers historically had poor support for templates, thus the use of templates could make code somewhat less portable. Support may also be poor when a C++ compiler is being used with a linker that is not C++-aware, or when attempting to use templates across shared library boundaries. Compilers can produce confusing, long, and sometimes unhelpful error messages when errors are detected in code that uses SFINAE. This can make templates difficult to develop with. Finally, the use of templates requires the compiler to generate a separate instance of the templated class or function for every type parameters used with it. (This is necessary because types in C++ are not all the same size, and the sizes of data fields are important to how classes work.) So the indiscriminate use of templates can lead to code bloat, resulting in excessively large executables. However, judicious use of template specialization and derivation can dramatically reduce such code bloat in some cases:So, can derivation be used to reduce the problem of code replicated because templates are used? This would involve deriving a template from an ordinary class. This technique proved successful in curbing code bloat in real use. People who do not use a technique like this have found that replicated code can cost megabytes of code space even in moderate size programs. Templated classes or functions may require an explicit specialization of the template class which would require rewriting of an entire class for a specific template parameters used by it. The extra instantiations generated by templates can also cause some debuggers to have difficulty working gracefully with templates. For example, setting a debug breakpoint within a template from a source file may either miss setting the breakpoint in the actual instantiation desired or may set a breakpoint in every place the template is instantiated. Also, the implementation source code for the template must be completely available (e.g. included in a header) to the translation unit (source file) using it. Templates, including much of the Standard Library, if not included in header files, cannot be compiled. (This is in contrast to non-templated code, which may be compiled to binary, providing only a declarations header file for code using it.) This may be a disadvantage by exposing the implementing code, which removes some abstractions, and could restrict its use in closed-source projects. ==== Templates in D ==== The D language supports templates based in design on C++. Most C++ template idioms work in D without alteration, but D adds some functionality: Template parameters in D are not restricted to just types and primitive values (as it was in C++ before C++20), but also allow arbitrary compile-time values (such as strings and struct literals), and aliases to arbitrary identifiers, including other templates or template instantiations. Template constraints and the static if statement provide an alternative to respectively C++'s C++ concepts and if constexpr. The is(...) expression allows speculative instantiation to verify an object's traits at compile time. The auto keyword and the typeof expression allow type inference for variable declarations and function return values, which in turn allows "Voldemort types" (types that do not have a global name). Templates in D use a different syntax than in C++: whereas in C++ template parameters are wrapped in angular brackets (Template<param1, param2>), D uses an exclamation sign and parentheses: Template!(param1, param2). This avoids the C++ parsing difficulties due to ambiguity with comparison operators. If there is only one parameter, the parentheses can be omitted. Conventionally, D combines the above features to provide compile-time polymorphism using trait-based generic programming. For example, an input range is defined as any type that satisfies the checks performed by isInputRange, which is defined as follows: A function that accepts only input ranges can then use the above template in a template constraint: ===== Code generation ===== In addition to template metaprogramming, D also provides several features to enable compile-time code generation: The import expression allows reading a file from disk and using its contents as a string expression. Compile-time reflection allows enumerating and inspecting declarations and their members during compiling. User-defined attributes allow users to attach arbitrary identifiers to declarations, which can then be enumerated using compile-time reflection. Compile-time function execution (CTFE) allows a subset of D (restricted to safe operations) to be interpreted during compiling. String mixins allow evaluating and compiling the contents of a string expression as D code that becomes part of the program. Combining the above allows generating code based on existing declarations. For example, D serialization frameworks can enumerate a type's members and generate specialized functions for each serialized type to perform serialization and deserialization. User-defined attributes could further indicate serialization rules. The import expression and compile-time function execution also allow efficiently implementing domain-specific languages. For example, given a function that takes a string containing an HTML template and returns equivalent D source code, it is possible to use it in the following way: ==== Genericity in Eiffel ==== Generic classes have been a part of Eiffel since the original method and language design. The foundation publications of Eiffel, use the term genericity to describe creating and using generic classes. ===== Basic, unconstrained genericity ===== Generic classes are declared with their class name and a list of one or more formal generic parameters. In the following code, class LIST has one formal generic parameter G The formal generic parameters are placeholders for arbitrary class names that will be supplied when a declaration of the generic class is made, as shown in the two generic derivations below, where ACCOUNT and DEPOSIT are other class names. ACCOUNT and DEPOSIT are considered actual generic parameters as they provide real class names to substitute for G in actual use. Within the Eiffel type system, although class LIST [G] is considered a class, it is not considered a type. However, a generic derivation of LIST [G] such as LIST [ACCOUNT] is considered a type. ===== Constrained genericity ===== For the list class shown above, an actual generic parameter substituting for G can be any other available class. To constrain the set of classes from which valid actual generic parameters can be chosen, a generic constraint can be specified. In the declaration of class SORTED_LIST below, the generic constraint dictates that any valid actual generic parameter will be a class that inherits from class COMPARABLE. The generic constraint ensures that elements of a SORTED_LIST can in fact be sorted. ==== Generics in Java ==== Support for the generics, or "containers-of-type-T" was added to the Java programming language in 2004 as part of J2SE 5.0. In Java, generics are only checked at compile time for type correctness. The generic type information is then removed via a process called type erasure, to maintain compatibility with old JVM implementations, making it unavailable at runtime. For example, a List<String> is converted to the raw type List. The compiler inserts type casts to convert the elements to the String type when they are retrieved from the list, reducing performance compared to other implementations such as C++ templates. ==== Genericity in .NET [C#, VB.NET] ==== Generics were added as part of .NET Framework 2.0 in November 2005, based on a research prototype from Microsoft Research started in 1999. Although similar to generics in Java, .NET generics do not apply type erasure,: 208–209  but implement generics as a first class mechanism in the runtime using reification. This design choice provides additional functionality, such as allowing reflection with preservation of generic types, and alleviating some of the limits of erasure (such as being unable to create generic arrays). This also means that there is no performance hit from runtime casts and normally expensive boxing conversions. When primitive and value types are used as generic arguments, they get specialized implementations, allowing for efficient generic collections and methods. As in C++ and Java, nested generic types such as Dictionary<string, List<int>> are valid types, however are advised against for member signatures in code analysis design rules. .NET allows six varieties of generic type constraints using the where keyword including restricting generic types to be value types, to be classes, to have constructors, and to implement interfaces. Below is an example with an interface constraint: The MakeAtLeast() method allows operation on arrays, with elements of generic type T. The method's type constraint indicates that the method is applicable to any type T that implements the generic IComparable<T> interface. This ensures a compile time error, if the method is called if the type does not support comparison. The interface provides the generic method CompareTo(T). The above method could also be written without generic types, simply using the non-generic Array type. However, since arrays are contravariant, the casting would not be type safe, and the compiler would be unable to find certain possible errors that would otherwise be caught when using generic types. In addition, the method would need to access the array items as objects instead, and would require casting to compare two elements. (For value types like types such as int this requires a boxing conversion, although this can be worked around using the Comparer<T> class, as is done in the standard collection classes.) A notable behavior of static members in a generic .NET class is static member instantiation per run-time type (see example below). ==== Genericity in Pascal ==== For Pascal, generics were first implemented in 2006, in the implementation Free Pascal. ===== In Delphi ===== The Object Pascal dialect Delphi acquired generics in the 2007 Delphi 11 release by CodeGear, initially only with the .NET compiler (since discontinued) before being added to the native code in the 2009 Delphi 12 release. The semantics and abilities of Delphi generics are largely modelled on those of generics in .NET 2.0, though the implementation is by necessity quite different. Here is a more or less direct translation of the first C# example shown above: As with C#, methods and whole types can have one or more type parameters. In the example, TArray is a generic type (defined by the language) and MakeAtLeast a generic method. The available constraints are very similar to the available constraints in C#: any value type, any class, a specific class or interface, and a class with a parameterless constructor. Multiple constraints act as an additive union. ===== In Free Pascal ===== Free Pascal implemented generics in 2006 in version 2.2.0, before Delphi and with different syntax and semantics. However, since FPC version 2.6.0, the Delphi-style syntax is available when using the language mode {$mode Delphi}. Thus, Free Pascal code supports generics in either style. Delphi and Free Pascal example: === Functional languages === ==== Genericity in Haskell ==== The type class mechanism of Haskell supports generic programming. Six of the predefined type classes in Haskell (including Eq, the types that can be compared for equality, and Show, the types whose values can be rendered as strings) have the special property of supporting derived instances. This means that a programmer defining a new type can state that this type is to be an instance of one of these special type classes, without providing implementations of the class methods as is usually necessary when declaring class instances. All the necessary methods will be "derived" – that is, constructed automatically – based on the structure of the type. For example, the following declaration of a type of binary trees states that it is to be an instance of the classes Eq and Show: This results in an equality function (==) and a string representation function (show) being automatically defined for any type of the form BinTree T provided that T itself supports those operations. The support for derived instances of Eq and Show makes their methods == and show generic in a qualitatively different way from parametrically polymorphic functions: these "functions" (more accurately, type-indexed families of functions) can be applied to values of various types, and although they behave differently for every argument type, little work is needed to add support for a new type. Ralf Hinze (2004) has shown that a similar effect can be achieved for user-defined type classes by certain programming techniques. Other researchers have proposed approaches to this and other kinds of genericity in the context of Haskell and extensions to Haskell (discussed below). ===== PolyP ===== PolyP was the first generic programming language extension to Haskell. In PolyP, generic functions are called polytypic. The language introduces a special construct in which such polytypic functions can be defined via structural induction over the structure of the pattern functor of a regular datatype. Regular datatypes in PolyP are a subset of Haskell datatypes. A regular datatype t must be of kind * → *, and if a is the formal type argument in the definition, then all recursive calls to t must have the form t a. These restrictions rule out higher-kinded datatypes and nested datatypes, where the recursive calls are of a different form. The flatten function in PolyP is here provided as an example: ===== Generic Haskell ===== Generic Haskell is another extension to Haskell, developed at Utrecht University in the Netherlands. The extensions it provides are: Type-indexed values are defined as a value indexed over the various Haskell type constructors (unit, primitive types, sums, products, and user-defined type constructors). In addition, we can also specify the behaviour of a type-indexed values for a specific constructor using constructor cases, and reuse one generic definition in another using default cases. The resulting type-indexed value can be specialized to any type. Kind-indexed types are types indexed over kinds, defined by giving a case for both * and k → k'. Instances are obtained by applying the kind-indexed type to a kind. Generic definitions can be used by applying them to a type or kind. This is called generic application. The result is a type or value, depending on which sort of generic definition is applied. Generic abstraction enables generic definitions be defined by abstracting a type parameter (of a given kind). Type-indexed types are types that are indexed over the type constructors. These can be used to give types to more involved generic values. The resulting type-indexed types can be specialized to any type. As an example, the equality function in Generic Haskell: ==== Clean ==== Clean offers generic programming based PolyP and the Generic Haskell as supported by the GHC ≥ 6.0. It parametrizes by kind as those but offers overloading. === Other languages === Languages in the ML family support generic programming through parametric polymorphism and generic modules called functors. Both Standard ML and OCaml provide functors, which are similar to class templates and to Ada's generic packages. Scheme syntactic abstractions also have a connection to genericity – these are in fact a superset of C++ templates. A Verilog module may take one or more parameters, to which their actual values are assigned upon the instantiation of the module. One example is a generic register array where the array width is given via a parameter. Such an array, combined with a generic wire vector, can make a generic buffer or memory module with an arbitrary bit width out of a single module implementation. VHDL, being derived from Ada, also has generic abilities. C supports "type-generic expressions" using the _Generic keyword: == See also == Concept (generic programming) Partial evaluation Template metaprogramming Type polymorphism == References == == Sources == == Further reading == Gabriel Dos Reis and Jaakko Järvi, What is Generic Programming?, LCSD 2005 Archived 28 August 2019 at the Wayback Machine. Gibbons, Jeremy (2007). Backhouse, R.; Gibbons, J.; Hinze, R.; Jeuring, J. (eds.). Datatype-generic programming. Spring School on Datatype-Generic Programming 2006. Lecture Notes in Computer Science. Vol. 4719. Heidelberg: Springer. pp. 1–71. CiteSeerX 10.1.1.159.1228. Meyer, Bertrand (1986). "Genericity versus inheritance". Conference proceedings on Object-oriented programming systems, languages and applications - OOPSLA '86. pp. 391–405. doi:10.1145/28697.28738. ISBN 0897912047. S2CID 285030. == External links == generic-programming.org Alexander A. Stepanov, Collected Papers of Alexander A. Stepanov (creator of the STL) C++, D Walter Bright, Templates Revisited. David Vandevoorde, Nicolai M Josuttis, C++ Templates: The Complete Guide, 2003 Addison-Wesley. ISBN 0-201-73484-2 C#, .NET Jason Clark, "Introducing Generics in the Microsoft CLR," September 2003, MSDN Magazine, Microsoft. Jason Clark, "More on Generics in the Microsoft CLR," October 2003, MSDN Magazine, Microsoft. M. Aamir Maniar, Generics.Net. An open source generics library for C#. Delphi, Object Pascal Nick Hodges, "Delphi 2009 Reviewers Guide," October 2008, Embarcadero Developer Network, Embarcadero. Craig Stuntz, "Delphi 2009 Generics and Type Constraints," October 2008 Dr. Bob, "Delphi 2009 Generics" Free Pascal: Free Pascal Reference guide Chapter 8: Generics, Michaël Van Canneyt, 2007 Delphi for Win32: Generics with Delphi 2009 Win32, Sébastien DOERAENE, 2008 Delphi for .NET: Delphi Generics, Felix COLIBRI, 2008 Eiffel Eiffel ISO/ECMA specification document Haskell Johan Jeuring, Sean Leather, José Pedro Magalhães, and Alexey Rodriguez Yakushev. Libraries for Generic Programming in Haskell. Utrecht University. Dæv Clarke, Johan Jeuring and Andres Löh, The Generic Haskell user's guide Ralf Hinze, "Generics for the Masses," In Proceedings of the ACM SIGPLAN International Conference on Functional Programming (ICFP), 2004. Simon Peyton Jones, editor, The Haskell 98 Language Report, Revised 2002. Ralf Lämmel and Simon Peyton Jones, "Scrap Your Boilerplate: A Practical Design Pattern for Generic Programming," In Proceedings of the ACM SIGPLAN International Workshop on Types in Language Design and Implementation (TLDI'03), 2003. (Also see the website devoted to this research) Andres Löh, Exploring Generic Haskell, PhD thesis, 2004 Utrecht University. ISBN 90-393-3765-9 Generic Haskell: a language for generic programming Java Gilad Bracha, Generics in the Java Programming Language, 2004. Maurice Naftalin and Philip Wadler, Java Generics and Collections, 2006, O'Reilly Media, Inc. ISBN 0-596-52775-6 Peter Sestoft, Java Precisely, Second Edition, 2005 MIT Press. ISBN 0-262-69325-9 Generic Programming in Java, 2004 Sun Microsystems, Inc. Angelika Langer, Java Generics FAQs
https://en.wikipedia.org/wiki/Generic_programming
Procedural programming is a programming paradigm, classified as imperative programming, that involves implementing the behavior of a computer program as procedures (a.k.a. functions, subroutines) that call each other. The resulting program is a series of steps that forms a hierarchy of calls to its constituent procedures. The first major procedural programming languages appeared c. 1957–1964, including Fortran, ALGOL, COBOL, PL/I and BASIC. Pascal and C were published c. 1970–1972. Computer processors provide hardware support for procedural programming through a stack register and instructions for calling procedures and returning from them. Hardware support for other types of programming is possible, like Lisp machines or Java processors, but no attempt was commercially successful. == Development practices == Certain software development practices are often employed with procedural programming in order to enhance quality and lower development and maintenance costs. === Modularity and scoping === Modularity is about organizing the procedures of a program into separate modules—each of which has a specific and understandable purpose. Minimizing the scope of variables and procedures can enhance software quality by reducing the cognitive load of procedures and modules. A program lacking modularity or wide scoping tends to have procedures that consume many variables that other procedures also consume. The resulting code is relatively hard to understand and to maintain. === Sharing === Since a procedure can specify a well-defined interface and be self-contained it supports code reuse—in particular via the software library. == Comparison with other programming paradigms == === Imperative programming === Procedural programming is classified as an imperative programming, because it involves direct command of execution. Procedural is a sub-class of imperative since procedural includes block and scope concepts, whereas imperative describes a more general concept that does not require such features. Procedural languages generally use reserved words that define blocks, such as if, while, and for, to implement control flow, whereas non-structured imperative languages (i.e. assembly language) use goto and branch tables for this purpose. === Object-oriented programming === Also classified as imperative, object-oriented programming (OOP) involves dividing a program implementation into objects that expose behavior (methods) and data (members) via a well-defined interface. In contrast, procedural programming is about dividing the program implementation into variables, data structures, and subroutines. An important distinction is that while procedural involves procedures to operate on data structures, OOP bundles the two together. An object is a data structure and the behavior associated with that data structure. Some OOP languages support the class concept which allows for creating an object based on a definition. Nomenclature varies between the two, although they have similar semantics: === Functional programming === The principles of modularity and code reuse in functional languages are fundamentally the same as in procedural languages, since they both stem from structured programming. For example: Procedures correspond to functions. Both allow the reuse of the same code in various parts of the programs, and at various points of its execution. By the same token, procedure calls correspond to function application. Functions and their modularly separated from each other in the same manner, by the use of function arguments, return values and variable scopes. The main difference between the styles is that functional programming languages remove or at least deemphasize the imperative elements of procedural programming. The feature set of functional languages is therefore designed to support writing programs as much as possible in terms of pure functions: Whereas procedural languages model execution of the program as a sequence of imperative commands that may implicitly alter shared state, functional programming languages model execution as the evaluation of complex expressions that only depend on each other in terms of arguments and return values. For this reason, functional programs can have a free order of code execution, and the languages may offer little control over the order in which various parts of the program are executed; for example, the arguments to a procedure invocation in Scheme are evaluated in an arbitrary order. Functional programming languages support (and heavily use) first-class functions, anonymous functions and closures, although these concepts have also been included in procedural languages at least since Algol 68. Functional programming languages tend to rely on tail call optimization and higher-order functions instead of imperative looping constructs. Many functional languages, however, are in fact impurely functional and offer imperative/procedural constructs that allow the programmer to write programs in procedural style, or in a combination of both styles. It is common for input/output code in functional languages to be written in a procedural style. There do exist a few esoteric functional languages (like Unlambda) that eschew structured programming precepts for the sake of being difficult to program in (and therefore challenging). These languages are the exception to the common ground between procedural and functional languages. === Logic programming === In logic programming, a program is a set of premises, and computation is performed by attempting to prove candidate theorems. From this point of view, logic programs are declarative, focusing on what the problem is, rather than on how to solve it. However, the backward reasoning technique, implemented by SLD resolution, used to solve problems in logic programming languages such as Prolog, treats programs as goal-reduction procedures. Thus clauses of the form: H :- B1, …, Bn. have a dual interpretation, both as procedures to show/solve H, show/solve B1 and … and Bn and as logical implications: B1 and … and Bn implies H. A skilled logic programmer uses the procedural interpretation to write programs that are effective and efficient, and uses the declarative interpretation to help ensure that programs are correct. == See also == Declarative programming Functional programming (contrast) Imperative programming Logic programming Object-oriented programming Programming paradigms Programming language Structured programming SQL procedural extensions == References == == External links ==
https://en.wikipedia.org/wiki/Procedural_programming
Goal programming is a branch of multiobjective optimization, which in turn is a branch of multi-criteria decision analysis (MCDA). It can be thought of as an extension or generalisation of linear programming to handle multiple, normally conflicting objective measures. Each of these measures is given a goal or target value to be achieved. Deviations are measured from these goals both above and below the target. Unwanted deviations from this set of target values are then minimised in an achievement function. This can be a vector or a weighted sum dependent on the goal programming variant used. As satisfaction of the target is deemed to satisfy the decision maker(s), an underlying satisficing philosophy is assumed. Goal programming is used to perform three types of analysis: Determine the required resources to achieve a desired set of objectives. Determine the degree of attainment of the goals with the available resources. Providing the best satisfying solution under a varying amount of resources and priorities of the goals. == History == Goal programming was first used by Charnes, Cooper and Ferguson in 1955, although the actual name first appeared in a 1961 text by Charnes and Cooper. Seminal works by Lee, Ignizio, Ignizio and Cavalier, and Romero followed. Schniederjans gives in a bibliography of a large number of pre-1995 articles relating to goal programming, and Jones and Tamiz give an annotated bibliography of the period 1990-2000. A recent textbook by Jones and Tamiz . gives a comprehensive overview of the state-of-the-art in goal programming. The first engineering application of goal programming, due to Ignizio in 1962, was the design and placement of the antennas employed on the second stage of the Saturn V. This was used to launch the Apollo space capsule that landed the first men on the moon. == Variants == The initial goal programming formulations ordered the unwanted deviations into a number of priority levels, with the minimisation of a deviation in a higher priority level being infinitely more important than any deviations in lower priority levels. This is known as lexicographic or pre-emptive goal programming. Ignizio gives an algorithm showing how a lexicographic goal programme can be solved as a series of linear programmes. Lexicographic goal programming is used when there exists a clear priority ordering amongst the goals to be achieved. If the decision maker is more interested in direct comparisons of the objectives then weighted or non-pre-emptive goal programming should be used. In this case, all the unwanted deviations are multiplied by weights, reflecting their relative importance, and added together as a single sum to form the achievement function. Deviations measured in different units cannot be summed directly due to the phenomenon of incommensurability. Hence each unwanted deviation is multiplied by a normalisation constant to allow direct comparison. Popular choices for normalisation constants are the goal target value of the corresponding objective (hence turning all deviations into percentages) or the range of the corresponding objective (between the best and the worst possible values, hence mapping all deviations onto a zero-one range). For decision makers more interested in obtaining a balance between the competing objectives, Chebyshev goal programming is used. Introduced by Flavell in 1976, this variant seeks to minimise the maximum unwanted deviation, rather than the sum of deviations. This utilises the Chebyshev distance metric. == Strengths and weaknesses == A major strength of goal programming is its simplicity and ease of use. This accounts for the large number of goal programming applications in many and diverse fields. Linear goal programmes can be solved using linear programming software as either a single linear programme, or in the case of the lexicographic variant, a series of connected linear programmes. Goal programming can hence handle relatively large numbers of variables, constraints and objectives. A debated weakness is the ability of goal programming to produce solutions that are not Pareto efficient. This violates a fundamental concept of decision theory, that no rational decision maker will knowingly choose a solution that is not Pareto efficient. However, techniques are available to detect when this occurs and project the solution onto the Pareto efficient solution in an appropriate manner. The setting of appropriate weights in the goal programming model is another area that has caused debate, with some authors suggesting the use of the analytic hierarchy process or interactive methods for this purpose. Also, the weights of the objective functions can be calculated based on their preference using the ordinal priority approach. == See also == Decision-making software == External links == LiPS — Free easy-to-use GUI program intended for solving linear, integer and goal programming problems. LINSOLVE - Free Windows command-line window linear programming and linear goal programming] == References ==
https://en.wikipedia.org/wiki/Goal_programming
In computer programming, initialization or initialisation is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized. Programming constructs which perform initialization are typically called initializers and initializer lists. Initialization is distinct from (and preceded by) declaration, although the two can sometimes be conflated in practice. The complement of initialization is finalization, which is primarily used for objects, but not variables. Initialization is done either by statically embedding the value at compile time, or else by assignment at run time. A section of code that performs such initialization is generally known as "initialization code" and may include other, one-time-only, functions such as opening files; in object-oriented programming, initialization code may be part of a constructor (class method) or an initializer (instance method). Setting a memory location to hexadecimal zeroes is also sometimes known as "clearing" and is often performed by an exclusive or instruction (both operands specifying the same variable), at machine code level, since it requires no additional memory access. == C family of languages == === Initializer === In C/C99/C++, an initializer is an optional part of a declarator. It consists of the '=' character followed by an expression or a comma-separated list of expressions placed in curly brackets (braces). The latter list is sometimes called the "initializer list" or "initialization list" (although the term "initializer list" is formally reserved for initialization of class/struct members in C++; see below). A declaration which creates a data object, instead of merely describing its existence, is commonly called a definition. Many find it convenient to draw a distinction between the terms "declaration" and "definition", as in the commonly seen phrase "the distinction between a declaration and definition...", implying that a declaration merely designates a data object (or function). In fact, according to the C++ standard, a definition is a declaration. Still, the usage "declarations and definitions", although formally incorrect, is common. Although all definitions are declarations, not all declarations are definitions. C examples: C++ examples: === Initializer list === In C++, a constructor of a class/struct can have an initializer list within the definition but prior to the constructor body. It is important to note that when you use an initialization list, the values are not assigned to the variable. They are initialized. In the below example, 0 is initialized into re and im. Example: Here, the construct : re(0), im(0) is the initializer list. Sometimes the term "initializer list" is also used to refer to the list of expressions in the array or struct initializer. C++11 provides for a more powerful concept of initializer lists, by means of a template, called std::initializer_list. === Default initialization === Data initialization may occur without explicit syntax in a program to do so. For example, if static variables are declared without an initializer, then those of primitive data types are initialized with the value of zero of the corresponding type, while static objects of class type are initialized with their default constructors. == See also == Object lifetime Finalizer Process & related Finalization Pattern == References ==
https://en.wikipedia.org/wiki/Initialization_(programming)
Linear programming (LP), also called linear optimization, is a method to achieve the best outcome (such as maximum profit or lowest cost) in a mathematical model whose requirements and objective are represented by linear relationships. Linear programming is a special case of mathematical programming (also known as mathematical optimization). More formally, linear programming is a technique for the optimization of a linear objective function, subject to linear equality and linear inequality constraints. Its feasible region is a convex polytope, which is a set defined as the intersection of finitely many half spaces, each of which is defined by a linear inequality. Its objective function is a real-valued affine (linear) function defined on this polytope. A linear programming algorithm finds a point in the polytope where this function has the largest (or smallest) value if such a point exists. Linear programs are problems that can be expressed in standard form as: Find a vector x that maximizes c T x subject to A x ≤ b and x ≥ 0 . {\displaystyle {\begin{aligned}&{\text{Find a vector}}&&\mathbf {x} \\&{\text{that maximizes}}&&\mathbf {c} ^{\mathsf {T}}\mathbf {x} \\&{\text{subject to}}&&A\mathbf {x} \leq \mathbf {b} \\&{\text{and}}&&\mathbf {x} \geq \mathbf {0} .\end{aligned}}} Here the components of x {\displaystyle \mathbf {x} } are the variables to be determined, c {\displaystyle \mathbf {c} } and b {\displaystyle \mathbf {b} } are given vectors, and A {\displaystyle A} is a given matrix. The function whose value is to be maximized ( x ↦ c T x {\displaystyle \mathbf {x} \mapsto \mathbf {c} ^{\mathsf {T}}\mathbf {x} } in this case) is called the objective function. The constraints A x ≤ b {\displaystyle A\mathbf {x} \leq \mathbf {b} } and x ≥ 0 {\displaystyle \mathbf {x} \geq \mathbf {0} } specify a convex polytope over which the objective function is to be optimized. Linear programming can be applied to various fields of study. It is widely used in mathematics and, to a lesser extent, in business, economics, and some engineering problems. There is a close connection between linear programs, eigenequations, John von Neumann's general equilibrium model, and structural equilibrium models (see dual linear program for details). Industries that use linear programming models include transportation, energy, telecommunications, and manufacturing. It has proven useful in modeling diverse types of problems in planning, routing, scheduling, assignment, and design. == History == The problem of solving a system of linear inequalities dates back at least as far as Fourier, who in 1827 published a method for solving them, and after whom the method of Fourier–Motzkin elimination is named. In the late 1930s, Soviet mathematician Leonid Kantorovich and American economist Wassily Leontief independently delved into the practical applications of linear programming. Kantorovich focused on manufacturing schedules, while Leontief explored economic applications. Their groundbreaking work was largely overlooked for decades. The turning point came during World War II when linear programming emerged as a vital tool. It found extensive use in addressing complex wartime challenges, including transportation logistics, scheduling, and resource allocation. Linear programming proved invaluable in optimizing these processes while considering critical constraints such as costs and resource availability. Despite its initial obscurity, the wartime successes propelled linear programming into the spotlight. Post-WWII, the method gained widespread recognition and became a cornerstone in various fields, from operations research to economics. The overlooked contributions of Kantorovich and Leontief in the late 1930s eventually became foundational to the broader acceptance and utilization of linear programming in optimizing decision-making processes. Kantorovich's work was initially neglected in the USSR. About the same time as Kantorovich, the Dutch-American economist T. C. Koopmans formulated classical economic problems as linear programs. Kantorovich and Koopmans later shared the 1975 Nobel Memorial Prize in Economic Sciences. In 1941, Frank Lauren Hitchcock also formulated transportation problems as linear programs and gave a solution very similar to the later simplex method. Hitchcock had died in 1957, and the Nobel Memorial Prize is not awarded posthumously. From 1946 to 1947 George B. Dantzig independently developed general linear programming formulation to use for planning problems in the US Air Force. In 1947, Dantzig also invented the simplex method that, for the first time efficiently, tackled the linear programming problem in most cases. When Dantzig arranged a meeting with John von Neumann to discuss his simplex method, von Neumann immediately conjectured the theory of duality by realizing that the problem he had been working in game theory was equivalent. Dantzig provided formal proof in an unpublished report "A Theorem on Linear Inequalities" on January 5, 1948. Dantzig's work was made available to public in 1951. In the post-war years, many industries applied it in their daily planning. Dantzig's original example was to find the best assignment of 70 people to 70 jobs. The computing power required to test all the permutations to select the best assignment is vast; the number of possible configurations exceeds the number of particles in the observable universe. However, it takes only a moment to find the optimum solution by posing the problem as a linear program and applying the simplex algorithm. The theory behind linear programming drastically reduces the number of possible solutions that must be checked. The linear programming problem was first shown to be solvable in polynomial time by Leonid Khachiyan in 1979, but a larger theoretical and practical breakthrough in the field came in 1984 when Narendra Karmarkar introduced a new interior-point method for solving linear-programming problems. == Uses == Linear programming is a widely used field of optimization for several reasons. Many practical problems in operations research can be expressed as linear programming problems. Certain special cases of linear programming, such as network flow problems and multicommodity flow problems, are considered important enough to have much research on specialized algorithms. A number of algorithms for other types of optimization problems work by solving linear programming problems as sub-problems. Historically, ideas from linear programming have inspired many of the central concepts of optimization theory, such as duality, decomposition, and the importance of convexity and its generalizations. Likewise, linear programming was heavily used in the early formation of microeconomics, and it is currently utilized in company management, such as planning, production, transportation, and technology. Although the modern management issues are ever-changing, most companies would like to maximize profits and minimize costs with limited resources. Google also uses linear programming to stabilize YouTube videos. == Standard form == Standard form is the usual and most intuitive form of describing a linear programming problem. It consists of the following three parts: A linear (or affine) function to be maximized e.g. f ( x 1 , x 2 ) = c 1 x 1 + c 2 x 2 {\displaystyle f(x_{1},x_{2})=c_{1}x_{1}+c_{2}x_{2}} Problem constraints of the following form e.g. a 11 x 1 + a 12 x 2 ≤ b 1 a 21 x 1 + a 22 x 2 ≤ b 2 a 31 x 1 + a 32 x 2 ≤ b 3 {\displaystyle {\begin{matrix}a_{11}x_{1}+a_{12}x_{2}&\leq b_{1}\\a_{21}x_{1}+a_{22}x_{2}&\leq b_{2}\\a_{31}x_{1}+a_{32}x_{2}&\leq b_{3}\\\end{matrix}}} Non-negative variables e.g. x 1 ≥ 0 x 2 ≥ 0 {\displaystyle {\begin{matrix}x_{1}\geq 0\\x_{2}\geq 0\end{matrix}}} The problem is usually expressed in matrix form, and then becomes: max { c T x ∣ x ∈ R n ∧ A x ≤ b ∧ x ≥ 0 } {\displaystyle \max\{\,\mathbf {c} ^{\mathsf {T}}\mathbf {x} \mid \mathbf {x} \in \mathbb {R} ^{n}\land A\mathbf {x} \leq \mathbf {b} \land \mathbf {x} \geq 0\,\}} Other forms, such as minimization problems, problems with constraints on alternative forms, and problems involving negative variables can always be rewritten into an equivalent problem in standard form. === Example === Suppose that a farmer has a piece of farm land, say L hectares, to be planted with either wheat or barley or some combination of the two. The farmer has F kilograms of fertilizer and P kilograms of pesticide. Every hectare of wheat requires F1 kilograms of fertilizer and P1 kilograms of pesticide, while every hectare of barley requires F2 kilograms of fertilizer and P2 kilograms of pesticide. Let S1 be the selling price of wheat and S2 be the selling price of barley, per hectare. If we denote the area of land planted with wheat and barley by x1 and x2 respectively, then profit can be maximized by choosing optimal values for x1 and x2. This problem can be expressed with the following linear programming problem in the standard form: In matrix form this becomes: maximize [ S 1 S 2 ] [ x 1 x 2 ] {\displaystyle {\begin{bmatrix}S_{1}&S_{2}\end{bmatrix}}{\begin{bmatrix}x_{1}\\x_{2}\end{bmatrix}}} subject to [ 1 1 F 1 F 2 P 1 P 2 ] [ x 1 x 2 ] ≤ [ L F P ] , [ x 1 x 2 ] ≥ [ 0 0 ] . {\displaystyle {\begin{bmatrix}1&1\\F_{1}&F_{2}\\P_{1}&P_{2}\end{bmatrix}}{\begin{bmatrix}x_{1}\\x_{2}\end{bmatrix}}\leq {\begin{bmatrix}L\\F\\P\end{bmatrix}},\,{\begin{bmatrix}x_{1}\\x_{2}\end{bmatrix}}\geq {\begin{bmatrix}0\\0\end{bmatrix}}.} == Augmented form (slack form) == Linear programming problems can be converted into an augmented form in order to apply the common form of the simplex algorithm. This form introduces non-negative slack variables to replace inequalities with equalities in the constraints. The problems can then be written in the following block matrix form: Maximize z {\displaystyle z} : [ 1 − c T 0 0 A I ] [ z x s ] = [ 0 b ] {\displaystyle {\begin{bmatrix}1&-\mathbf {c} ^{\mathsf {T}}&0\\0&\mathbf {A} &\mathbf {I} \end{bmatrix}}{\begin{bmatrix}z\\\mathbf {x} \\\mathbf {s} \end{bmatrix}}={\begin{bmatrix}0\\\mathbf {b} \end{bmatrix}}} x ≥ 0 , s ≥ 0 {\displaystyle \mathbf {x} \geq 0,\mathbf {s} \geq 0} where s {\displaystyle \mathbf {s} } are the newly introduced slack variables, x {\displaystyle \mathbf {x} } are the decision variables, and z {\displaystyle z} is the variable to be maximized. === Example === The example above is converted into the following augmented form: where x 3 , x 4 , x 5 {\displaystyle x_{3},x_{4},x_{5}} are (non-negative) slack variables, representing in this example the unused area, the amount of unused fertilizer, and the amount of unused pesticide. In matrix form this becomes: Maximize z {\displaystyle z} : [ 1 − S 1 − S 2 0 0 0 0 1 1 1 0 0 0 F 1 F 2 0 1 0 0 P 1 P 2 0 0 1 ] [ z x 1 x 2 x 3 x 4 x 5 ] = [ 0 L F P ] , [ x 1 x 2 x 3 x 4 x 5 ] ≥ 0. {\displaystyle {\begin{bmatrix}1&-S_{1}&-S_{2}&0&0&0\\0&1&1&1&0&0\\0&F_{1}&F_{2}&0&1&0\\0&P_{1}&P_{2}&0&0&1\\\end{bmatrix}}{\begin{bmatrix}z\\x_{1}\\x_{2}\\x_{3}\\x_{4}\\x_{5}\end{bmatrix}}={\begin{bmatrix}0\\L\\F\\P\end{bmatrix}},\,{\begin{bmatrix}x_{1}\\x_{2}\\x_{3}\\x_{4}\\x_{5}\end{bmatrix}}\geq 0.} == Duality == Every linear programming problem, referred to as a primal problem, can be converted into a dual problem, which provides an upper bound to the optimal value of the primal problem. In matrix form, we can express the primal problem as: Maximize cTx subject to Ax ≤ b, x ≥ 0; with the corresponding symmetric dual problem, Minimize bTy subject to ATy ≥ c, y ≥ 0. An alternative primal formulation is: Maximize cTx subject to Ax ≤ b; with the corresponding asymmetric dual problem, Minimize bTy subject to ATy = c, y ≥ 0. There are two ideas fundamental to duality theory. One is the fact that (for the symmetric dual) the dual of a dual linear program is the original primal linear program. Additionally, every feasible solution for a linear program gives a bound on the optimal value of the objective function of its dual. The weak duality theorem states that the objective function value of the dual at any feasible solution is always greater than or equal to the objective function value of the primal at any feasible solution. The strong duality theorem states that if the primal has an optimal solution, x*, then the dual also has an optimal solution, y*, and cTx*=bTy*. A linear program can also be unbounded or infeasible. Duality theory tells us that if the primal is unbounded then the dual is infeasible by the weak duality theorem. Likewise, if the dual is unbounded, then the primal must be infeasible. However, it is possible for both the dual and the primal to be infeasible. See dual linear program for details and several more examples. == Variations == === Covering/packing dualities === A covering LP is a linear program of the form: Minimize: bTy, subject to: ATy ≥ c, y ≥ 0, such that the matrix A and the vectors b and c are non-negative. The dual of a covering LP is a packing LP, a linear program of the form: Maximize: cTx, subject to: Ax ≤ b, x ≥ 0, such that the matrix A and the vectors b and c are non-negative. ==== Examples ==== Covering and packing LPs commonly arise as a linear programming relaxation of a combinatorial problem and are important in the study of approximation algorithms. For example, the LP relaxations of the set packing problem, the independent set problem, and the matching problem are packing LPs. The LP relaxations of the set cover problem, the vertex cover problem, and the dominating set problem are also covering LPs. Finding a fractional coloring of a graph is another example of a covering LP. In this case, there is one constraint for each vertex of the graph and one variable for each independent set of the graph. == Complementary slackness == It is possible to obtain an optimal solution to the dual when only an optimal solution to the primal is known using the complementary slackness theorem. The theorem states: Suppose that x = (x1, x2, ... , xn) is primal feasible and that y = (y1, y2, ... , ym) is dual feasible. Let (w1, w2, ..., wm) denote the corresponding primal slack variables, and let (z1, z2, ... , zn) denote the corresponding dual slack variables. Then x and y are optimal for their respective problems if and only if xj zj = 0, for j = 1, 2, ... , n, and wi yi = 0, for i = 1, 2, ... , m. So if the i-th slack variable of the primal is not zero, then the i-th variable of the dual is equal to zero. Likewise, if the j-th slack variable of the dual is not zero, then the j-th variable of the primal is equal to zero. This necessary condition for optimality conveys a fairly simple economic principle. In standard form (when maximizing), if there is slack in a constrained primal resource (i.e., there are "leftovers"), then additional quantities of that resource must have no value. Likewise, if there is slack in the dual (shadow) price non-negativity constraint requirement, i.e., the price is not zero, then there must be scarce supplies (no "leftovers"). == Theory == === Existence of optimal solutions === Geometrically, the linear constraints define the feasible region, which is a convex polytope. A linear function is a convex function, which implies that every local minimum is a global minimum; similarly, a linear function is a concave function, which implies that every local maximum is a global maximum. An optimal solution need not exist, for two reasons. First, if the constraints are inconsistent, then no feasible solution exists: For instance, the constraints x ≥ 2 and x ≤ 1 cannot be satisfied jointly; in this case, we say that the LP is infeasible. Second, when the polytope is unbounded in the direction of the gradient of the objective function (where the gradient of the objective function is the vector of the coefficients of the objective function), then no optimal value is attained because it is always possible to do better than any finite value of the objective function. === Optimal vertices (and rays) of polyhedra === Otherwise, if a feasible solution exists and if the constraint set is bounded, then the optimum value is always attained on the boundary of the constraint set, by the maximum principle for convex functions (alternatively, by the minimum principle for concave functions) since linear functions are both convex and concave. However, some problems have distinct optimal solutions; for example, the problem of finding a feasible solution to a system of linear inequalities is a linear programming problem in which the objective function is the zero function (i.e., the constant function taking the value zero everywhere). For this feasibility problem with the zero-function for its objective-function, if there are two distinct solutions, then every convex combination of the solutions is a solution. The vertices of the polytope are also called basic feasible solutions. The reason for this choice of name is as follows. Let d denote the number of variables. Then the fundamental theorem of linear inequalities implies (for feasible problems) that for every vertex x* of the LP feasible region, there exists a set of d (or fewer) inequality constraints from the LP such that, when we treat those d constraints as equalities, the unique solution is x*. Thereby we can study these vertices by means of looking at certain subsets of the set of all constraints (a discrete set), rather than the continuum of LP solutions. This principle underlies the simplex algorithm for solving linear programs. == Algorithms == === Basis exchange algorithms === ==== Simplex algorithm of Dantzig ==== The simplex algorithm, developed by George Dantzig in 1947, solves LP problems by constructing a feasible solution at a vertex of the polytope and then walking along a path on the edges of the polytope to vertices with non-decreasing values of the objective function until an optimum is reached for sure. In many practical problems, "stalling" occurs: many pivots are made with no increase in the objective function. In rare practical problems, the usual versions of the simplex algorithm may actually "cycle". To avoid cycles, researchers developed new pivoting rules. In practice, the simplex algorithm is quite efficient and can be guaranteed to find the global optimum if certain precautions against cycling are taken. The simplex algorithm has been proved to solve "random" problems efficiently, i.e. in a cubic number of steps, which is similar to its behavior on practical problems. However, the simplex algorithm has poor worst-case behavior: Klee and Minty constructed a family of linear programming problems for which the simplex method takes a number of steps exponential in the problem size. In fact, for some time it was not known whether the linear programming problem was solvable in polynomial time, i.e. of complexity class P. ==== Criss-cross algorithm ==== Like the simplex algorithm of Dantzig, the criss-cross algorithm is a basis-exchange algorithm that pivots between bases. However, the criss-cross algorithm need not maintain feasibility, but can pivot rather from a feasible basis to an infeasible basis. The criss-cross algorithm does not have polynomial time-complexity for linear programming. Both algorithms visit all 2D corners of a (perturbed) cube in dimension D, the Klee–Minty cube, in the worst case. === Interior point === In contrast to the simplex algorithm, which finds an optimal solution by traversing the edges between vertices on a polyhedral set, interior-point methods move through the interior of the feasible region. ==== Ellipsoid algorithm, following Khachiyan ==== This is the first worst-case polynomial-time algorithm ever found for linear programming. To solve a problem which has n variables and can be encoded in L input bits, this algorithm runs in O ( n 6 L ) {\displaystyle O(n^{6}L)} time. Leonid Khachiyan solved this long-standing complexity issue in 1979 with the introduction of the ellipsoid method. The convergence analysis has (real-number) predecessors, notably the iterative methods developed by Naum Z. Shor and the approximation algorithms by Arkadi Nemirovski and D. Yudin. ==== Projective algorithm of Karmarkar ==== Khachiyan's algorithm was of landmark importance for establishing the polynomial-time solvability of linear programs. The algorithm was not a computational break-through, as the simplex method is more efficient for all but specially constructed families of linear programs. However, Khachiyan's algorithm inspired new lines of research in linear programming. In 1984, N. Karmarkar proposed a projective method for linear programming. Karmarkar's algorithm improved on Khachiyan's worst-case polynomial bound (giving O ( n 3.5 L ) {\displaystyle O(n^{3.5}L)} ). Karmarkar claimed that his algorithm was much faster in practical LP than the simplex method, a claim that created great interest in interior-point methods. Since Karmarkar's discovery, many interior-point methods have been proposed and analyzed. ==== Vaidya's 87 algorithm ==== In 1987, Vaidya proposed an algorithm that runs in O ( n 3 ) {\displaystyle O(n^{3})} time. ==== Vaidya's 89 algorithm ==== In 1989, Vaidya developed an algorithm that runs in O ( n 2.5 ) {\displaystyle O(n^{2.5})} time. Formally speaking, the algorithm takes O ( ( n + d ) 1.5 n L ) {\displaystyle O((n+d)^{1.5}nL)} arithmetic operations in the worst case, where d {\displaystyle d} is the number of constraints, n {\displaystyle n} is the number of variables, and L {\displaystyle L} is the number of bits. ==== Input sparsity time algorithms ==== In 2015, Lee and Sidford showed that linear programming can be solved in O ~ ( ( n n z ( A ) + d 2 ) d L ) {\displaystyle {\tilde {O}}((nnz(A)+d^{2}){\sqrt {d}}L)} time, where O ~ {\displaystyle {\tilde {O}}} denotes the soft O notation, and n n z ( A ) {\displaystyle nnz(A)} represents the number of non-zero elements, and it remains taking O ( n 2.5 L ) {\displaystyle O(n^{2.5}L)} in the worst case. ==== Current matrix multiplication time algorithm ==== In 2019, Cohen, Lee and Song improved the running time to O ~ ( ( n ω + n 2.5 − α / 2 + n 2 + 1 / 6 ) L ) {\displaystyle {\tilde {O}}((n^{\omega }+n^{2.5-\alpha /2}+n^{2+1/6})L)} time, ω {\displaystyle \omega } is the exponent of matrix multiplication and α {\displaystyle \alpha } is the dual exponent of matrix multiplication. α {\displaystyle \alpha } is (roughly) defined to be the largest number such that one can multiply an n × n {\displaystyle n\times n} matrix by a n × n α {\displaystyle n\times n^{\alpha }} matrix in O ( n 2 ) {\displaystyle O(n^{2})} time. In a followup work by Lee, Song and Zhang, they reproduce the same result via a different method. These two algorithms remain O ~ ( n 2 + 1 / 6 L ) {\displaystyle {\tilde {O}}(n^{2+1/6}L)} when ω = 2 {\displaystyle \omega =2} and α = 1 {\displaystyle \alpha =1} . The result due to Jiang, Song, Weinstein and Zhang improved O ~ ( n 2 + 1 / 6 L ) {\displaystyle {\tilde {O}}(n^{2+1/6}L)} to O ~ ( n 2 + 1 / 18 L ) {\displaystyle {\tilde {O}}(n^{2+1/18}L)} . === Comparison of interior-point methods and simplex algorithms === The current opinion is that the efficiencies of good implementations of simplex-based methods and interior point methods are similar for routine applications of linear programming. However, for specific types of LP problems, it may be that one type of solver is better than another (sometimes much better), and that the structure of the solutions generated by interior point methods versus simplex-based methods are significantly different with the support set of active variables being typically smaller for the latter one. == Open problems and recent work == There are several open problems in the theory of linear programming, the solution of which would represent fundamental breakthroughs in mathematics and potentially major advances in our ability to solve large-scale linear programs. Does LP admit a strongly polynomial-time algorithm? Does LP admit a strongly polynomial-time algorithm to find a strictly complementary solution? Does LP admit a polynomial-time algorithm in the real number (unit cost) model of computation? This closely related set of problems has been cited by Stephen Smale as among the 18 greatest unsolved problems of the 21st century. In Smale's words, the third version of the problem "is the main unsolved problem of linear programming theory." While algorithms exist to solve linear programming in weakly polynomial time, such as the ellipsoid methods and interior-point techniques, no algorithms have yet been found that allow strongly polynomial-time performance in the number of constraints and the number of variables. The development of such algorithms would be of great theoretical interest, and perhaps allow practical gains in solving large LPs as well. Although the Hirsch conjecture was recently disproved for higher dimensions, it still leaves the following questions open. Are there pivot rules which lead to polynomial-time simplex variants? Do all polytopal graphs have polynomially bounded diameter? These questions relate to the performance analysis and development of simplex-like methods. The immense efficiency of the simplex algorithm in practice despite its exponential-time theoretical performance hints that there may be variations of simplex that run in polynomial or even strongly polynomial time. It would be of great practical and theoretical significance to know whether any such variants exist, particularly as an approach to deciding if LP can be solved in strongly polynomial time. The simplex algorithm and its variants fall in the family of edge-following algorithms, so named because they solve linear programming problems by moving from vertex to vertex along edges of a polytope. This means that their theoretical performance is limited by the maximum number of edges between any two vertices on the LP polytope. As a result, we are interested in knowing the maximum graph-theoretical diameter of polytopal graphs. It has been proved that all polytopes have subexponential diameter. The recent disproof of the Hirsch conjecture is the first step to prove whether any polytope has superpolynomial diameter. If any such polytopes exist, then no edge-following variant can run in polynomial time. Questions about polytope diameter are of independent mathematical interest. Simplex pivot methods preserve primal (or dual) feasibility. On the other hand, criss-cross pivot methods do not preserve (primal or dual) feasibility – they may visit primal feasible, dual feasible or primal-and-dual infeasible bases in any order. Pivot methods of this type have been studied since the 1970s. Essentially, these methods attempt to find the shortest pivot path on the arrangement polytope under the linear programming problem. In contrast to polytopal graphs, graphs of arrangement polytopes are known to have small diameter, allowing the possibility of strongly polynomial-time criss-cross pivot algorithm without resolving questions about the diameter of general polytopes. == Integer unknowns == If all of the unknown variables are required to be integers, then the problem is called an integer programming (IP) or integer linear programming (ILP) problem. In contrast to linear programming, which can be solved efficiently in the worst case, integer programming problems are in many practical situations (those with bounded variables) NP-hard. 0–1 integer programming or binary integer programming (BIP) is the special case of integer programming where variables are required to be 0 or 1 (rather than arbitrary integers). This problem is also classified as NP-hard, and in fact the decision version was one of Karp's 21 NP-complete problems. If only some of the unknown variables are required to be integers, then the problem is called a mixed integer (linear) programming (MIP or MILP) problem. These are generally also NP-hard because they are even more general than ILP programs. There are however some important subclasses of IP and MIP problems that are efficiently solvable, most notably problems where the constraint matrix is totally unimodular and the right-hand sides of the constraints are integers or – more general – where the system has the total dual integrality (TDI) property. Advanced algorithms for solving integer linear programs include: cutting-plane method Branch and bound Branch and cut Branch and price if the problem has some extra structure, it may be possible to apply delayed column generation. Such integer-programming algorithms are discussed by Padberg and in Beasley. == Integral linear programs == A linear program in real variables is said to be integral if it has at least one optimal solution which is integral, i.e., made of only integer values. Likewise, a polyhedron P = { x ∣ A x ≥ 0 } {\displaystyle P=\{x\mid Ax\geq 0\}} is said to be integral if for all bounded feasible objective functions c, the linear program { max c x ∣ x ∈ P } {\displaystyle \{\max cx\mid x\in P\}} has an optimum x ∗ {\displaystyle x^{*}} with integer coordinates. As observed by Edmonds and Giles in 1977, one can equivalently say that the polyhedron P {\displaystyle P} is integral if for every bounded feasible integral objective function c, the optimal value of the linear program { max c x ∣ x ∈ P } {\displaystyle \{\max cx\mid x\in P\}} is an integer. Integral linear programs are of central importance in the polyhedral aspect of combinatorial optimization since they provide an alternate characterization of a problem. Specifically, for any problem, the convex hull of the solutions is an integral polyhedron; if this polyhedron has a nice/compact description, then we can efficiently find the optimal feasible solution under any linear objective. Conversely, if we can prove that a linear programming relaxation is integral, then it is the desired description of the convex hull of feasible (integral) solutions. Terminology is not consistent throughout the literature, so one should be careful to distinguish the following two concepts, in an integer linear program, described in the previous section, variables are forcibly constrained to be integers, and this problem is NP-hard in general, in an integral linear program, described in this section, variables are not constrained to be integers but rather one has proven somehow that the continuous problem always has an integral optimal value (assuming c is integral), and this optimal value may be found efficiently since all polynomial-size linear programs can be solved in polynomial time. One common way of proving that a polyhedron is integral is to show that it is totally unimodular. There are other general methods including the integer decomposition property and total dual integrality. Other specific well-known integral LPs include the matching polytope, lattice polyhedra, submodular flow polyhedra, and the intersection of two generalized polymatroids/g-polymatroids – e.g. see Schrijver 2003. == Solvers and scripting (programming) languages == Permissive licenses: Copyleft (reciprocal) licenses: MINTO (Mixed Integer Optimizer, an integer programming solver which uses branch and bound algorithm) has publicly available source code but is not open source. Proprietary licenses: == See also == == Notes == == References == == Further reading == == External links == Guidance On Formulating LP Problems Mathematical Programming Glossary The Linear Programming FAQ Benchmarks For Optimisation Software
https://en.wikipedia.org/wiki/Linear_programming
Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect or "concern" of the desired functionality. A module interface expresses the elements that are provided and required by the module. The elements defined in the interface are detectable by other modules. The implementation contains the working code that corresponds to the elements declared in the interface. Modular programming is closely related to structured programming and object-oriented programming, all having the same goal of facilitating construction of large software programs and systems by decomposition into smaller pieces, and all originating around the 1960s. While the historical usage of these terms has been inconsistent, "modular programming" now refers to the high-level decomposition of the code of an entire program into pieces: structured programming to the low-level code use of structured control flow, and object-oriented programming to the data use of objects, a kind of data structure. In object-oriented programming, the use of interfaces as an architectural pattern to construct modules is known as interface-based programming. == History == Modular programming, in the form of subsystems (particularly for I/O) and software libraries, dates to early software systems, where it was used for code reuse. Modular programming per se, with a goal of modularity, developed in the late 1960s and 1970s, as a larger-scale analog of the concept of structured programming (1960s). The term "modular programming" dates at least to the National Symposium on Modular Programming, organized at the Information and Systems Institute in July 1968 by Larry Constantine; other key concepts were information hiding (1972) and separation of concerns (SoC, 1974). Modules were not included in the original specification for ALGOL 68 (1968), but were included as extensions in early implementations, ALGOL 68-R (1970) and ALGOL 68C (1970), and later formalized. One of the first languages designed from the start for modular programming was the short-lived Modula (1975), by Niklaus Wirth. Another early modular language was Mesa (1970s), by Xerox PARC, and Wirth drew on Mesa as well as the original Modula in its successor, Modula-2 (1978), which influenced later languages, particularly through its successor, Modula-3 (1980s). Modula's use of dot-qualified names, like M.a to refer to object a from module M, coincides with notation to access a field of a record (and similarly for attributes or methods of objects), and is now widespread, seen in C++, C#, Dart, Go, Java, OCaml, and Python, among others. Modular programming became widespread from the 1980s: the original Pascal language (1970) did not include modules, but later versions, notably UCSD Pascal (1978) and Turbo Pascal (1983) included them in the form of "units", as did the Pascal-influenced Ada (1980). The Extended Pascal ISO 10206:1990 standard kept closer to Modula2 in its modular support. Standard ML (1984) has one of the most complete module systems, including functors (parameterized modules) to map between modules. In the 1980s and 1990s, modular programming was overshadowed by and often conflated with object-oriented programming, particularly due to the popularity of C++ and Java. For example, the C family of languages had support for objects and classes in C++ (originally C with Classes, 1980) and Objective-C (1983), only supporting modules 30 years or more later. Java (1995) supports modules in the form of packages, though the primary unit of code organization is a class. However, Python (1991) prominently used both modules and objects from the start, using modules as the primary unit of code organization and "packages" as a larger-scale unit; and Perl 5 (1994) includes support for both modules and objects, with a vast array of modules being available from CPAN (1993). OCaml (1996) followed ML by supporting modules and functors. Modular programming is now widespread, and found in virtually all major languages developed since the 1990s. The relative importance of modules varies between languages, and in class-based object-oriented languages there is still overlap and confusion with classes as a unit of organization and encapsulation, but these are both well-established as distinct concepts. == Terminology == The term assembly (as in .NET languages like C#, F# or Visual Basic .NET) or package (as in Dart, Go or Java) is sometimes used instead of module. In other implementations, these are distinct concepts; in Python a package is a collection of modules, while in Java 9 the introduction of the new module concept (a collection of packages with enhanced access control) was implemented. Furthermore, the term "package" has other uses in software (for example .NET NuGet packages). A component is a similar concept, but typically refers to a higher level; a component is a piece of a whole system, while a module is a piece of an individual program. The scale of the term "module" varies significantly between languages; in Python it is very small-scale and each file is a module, while in Java 9 it is planned to be large-scale, where a module is a collection of packages, which are in turn collections of files. Other terms for modules include unit, used in Pascal dialects. == Language support == Languages that formally support the module concept include Ada, ALGOL, BlitzMax, C++, C#, Clojure, COBOL, Common Lisp, D, Dart, eC, Erlang, Elixir, Elm, F, F#, Fortran, Go, Haskell, IBM/360 Assembler, Control Language (CL), IBM RPG, Java, Julia, MATLAB, ML, Modula, Modula-2, Modula-3, Morpho, NEWP, Oberon, Oberon-2, Objective-C, OCaml, several Pascal derivatives (Component Pascal, Object Pascal, Turbo Pascal, UCSD Pascal), Perl, PHP, PL/I, PureBasic, Python, R, Ruby, Rust, JavaScript, Visual Basic (.NET) and WebDNA. In the Java programming language, the term "package" is used for the analog of modules in the JLS; — see Java package. "Modules", a kind of collection of packages, were introduced in Java 9 as part of Project Jigsaw; these were earlier called "superpackages" were planned for Java 7. Conspicuous examples of languages that lack support for modules are C and have been C++ and Pascal in their original form, C and C++ do, however, allow separate compilation and declarative interfaces to be specified using header files. Modules were added to Objective-C in iOS 7 (2013); to C++ with C++20, and Pascal was superseded by Modula and Oberon, which included modules from the start, and various derivatives that included modules. JavaScript has had native modules since ECMAScript 2015. C++ modules have allowed backwards compatibility with headers (with "header units"). Dialects of C allow for modules, for example Clang supports modules for the C language, though the syntax and semantics of Clang C modules differ from C++ modules significantly. Modular programming can be performed even where the programming language lacks explicit syntactic features to support named modules, like, for example, in C. This is done by using existing language features, together with, for example, coding conventions, programming idioms and the physical code structure. IBM i also uses modules when programming in the Integrated Language Environment (ILE). == Key aspects == With modular programming, concerns are separated such that modules perform logically discrete functions, interacting through well-defined interfaces. Often modules form a directed acyclic graph (DAG); in this case a cyclic dependency between modules is seen as indicating that these should be a single module. In the case where modules do form a DAG they can be arranged as a hierarchy, where the lowest-level modules are independent, depending on no other modules, and higher-level modules depend on lower-level ones. A particular program or library is a top-level module of its own hierarchy, but can in turn be seen as a lower-level module of a higher-level program, library, or system. When creating a modular system, instead of creating a monolithic application (where the smallest component is the whole), several smaller modules are written separately so when they are composed together, they construct the executable application program. Typically, these are also compiled separately, via separate compilation, and then linked by a linker. A just-in-time compiler may perform some of this construction "on-the-fly" at run time. These independent functions are commonly classified as either program control functions or specific task functions. Program control functions are designed to work for one program. Specific task functions are closely prepared to be applicable for various programs. This makes modular designed systems, if built correctly, far more reusable than a traditional monolithic design, since all (or many) of these modules may then be reused (without change) in other projects. This also facilitates the "breaking down" of projects into several smaller projects. Theoretically, a modularized software project will be more easily assembled by large teams, since no team members are creating the whole system, or even need to know about the system as a whole. They can focus just on the assigned smaller task. == See also == Architecture description language – Standardized language on architecture description Cohesion (computer science) – Degree to which elements within a module belong together Component-based software engineering – Engineering focused on building software from reusable components Conway's law – Adage linking organization and system structure Coupling (computer science) – Degree of interdependence between software modulesPages displaying short descriptions of redirect targets David Parnas – Canadian software engineer Information hiding – Principle of computer program design (encapsulation) Library (computing) – Collection of resources used to develop a computer program List of system quality attributes – Non-functional requirements for system evaluation Modular design – Design approach Plug-in (computing) – Software component that extends the functionality of existing software Snippet (programming) – Small region of re-usable source code, machine code, or text Structured Analysis – Software engineering methodPages displaying short descriptions of redirect targets Structured programming – Programming paradigm based on control flow Cross-cutting concern – Concept in aspect-oriented software development == References == == External links == How To Decompose a System into Modules SMC Platform
https://en.wikipedia.org/wiki/Modular_programming
Pair programming is a software development technique in which two programmers work together at one workstation. One, the driver, writes code while the other, the observer or navigator, reviews each line of code as it is typed in. The two programmers switch roles frequently. While reviewing, the observer also considers the "strategic" direction of the work, coming up with ideas for improvements and likely future problems to address. This is intended to free the driver to focus all of their attention on the "tactical" aspects of completing the current task, using the observer as a safety net and guide. == Economics == Pair programming increases the man-hours required to deliver code compared to programmers working individually. However, the resulting code has fewer defects. Along with code development time, other factors like field support costs and quality assurance also figure into the return on investment. Pair programming might theoretically offset these expenses by reducing defects in the programs. In addition to preventing mistakes as they are made, other intangible benefits may exist. For example, the courtesy of rejecting phone calls or other distractions while working together, taking fewer breaks at agreed-upon intervals or sharing breaks to return phone calls (but returning to work quickly since someone is waiting). One member of the team might have more focus and help drive or awaken the other if they lose focus, and that role might periodically change. One member might know about a topic or technique that the other does not, which might eliminate delays to finding or testing a solution, or allow for a better solution, thus effectively expanding the skill set, knowledge, and experience of a programmer as compared to working alone. Each of these intangible benefits, and many more, may be challenging to accurately measure but can contribute to more efficient working hours. == Design quality == A system with two programmers possesses greater potential for the generation of more diverse solutions to problems for three reasons: the programmers bring different prior experiences to the task; they may assess information relevant to the task in different ways; they stand in different relationships to the problem by their functional roles. In an attempt to share goals and plans, the programmers must overtly negotiate a shared course of action when a conflict arises between them. In doing so, they consider a larger number of ways of solving the problem than a single programmer alone might do. This significantly improves the design quality of the program as it reduces the chances of selecting a poor method. == Satisfaction == In an online survey of pair programmers from 2000, 96% of programmers stated that they enjoyed working more while pair programming than programming alone. Furthermore, 95% said that they were more confident in their work when they pair programmed. However, as the survey was among self-selected pair programmers, it did not account for programmers who were forced to pair program. == Learning == Knowledge is constantly shared between pair programmers, whether in the industry or in a classroom. Many sources suggest that students show higher confidence when programming in pairs, and many learn whether it be from tips on programming language rules to overall design skills. In "promiscuous pairing", each programmer communicates and works with all the other programmers on the team rather than pairing only with one partner, which causes knowledge of the system to spread throughout the whole team. Pair programming allows programmers to examine their partner's code and provide feedback, which is necessary to increase their own ability to develop monitoring mechanisms for their own learning activities. == Team-building and communication == Pair programming allows team members to share quickly, making them less likely to have agendas hidden from each other. This helps pair programmers learn to communicate more easily. "This raises the communication bandwidth and frequency within the project, increasing overall information flow within the team." == Studies == There are both empirical studies and meta-analyses of pair programming. The empirical studies tend to examine the level of productivity and the quality of the code, while meta-analyses may focus on biases introduced by the process of testing and publishing. A meta-analysis found pairs typically consider more design alternatives than programmers working alone, arrive at simpler, more maintainable designs, and catch design defects earlier. However, it raised concerns that its findings may have been influenced by "signs of publication bias among published studies on pair programming." It concluded that "pair programming is not uniformly beneficial or effective." Although pair programmers may complete a task faster than a solo programmer, the total number of man-hours increases. A manager would have to balance faster completion of the work and reduced testing and debugging time against the higher cost of coding. The relative weight of these factors can vary by project and task. The benefit of pairing is greatest on tasks that the programmers do not fully understand before they begin: that is, challenging tasks that call for creativity and sophistication, and for novices as compared to experts. Pair programming could be helpful for attaining high quality and correctness on complex programming tasks, but it would also increase the development effort (cost) significantly. On simple tasks, which the pair already fully understands, pairing results in a net drop in productivity. It may reduce the code development time but also risks reducing the quality of the program. Productivity can also drop when novice–novice pairing is used without sufficient availability of a mentor to coach them. A study of programmers using AI assistance tools such as GitHub Copilot found that while some programmers conceived of AI assistance as similar to pair programming, in practice the use of such tools is very different in terms of the programmer experience, with the human programmer having to transition repeatedly between driver and navigator roles. == Indicators of non-performance == There are indicators that a pair is not performing well: Disengagement may present as one of the members physically withdraws away from the keyboard, accesses email, or even falls asleep. The "Watch the Master" phenomenon can arise if one member is more experienced than the other. In this situation, the junior member may take the observer role, deferring to the senior member of the pair for the majority of coding activity. This can easily lead to disengagement. == Pairing variations == Expert–expert Expert–expert pairing may seem to be the obvious choice for the highest productivity and can produce great results, but it often yields little insight into new ways to solve problems, as both parties are unlikely to question established practices. Expert–novice Expert–novice pairing creates many opportunities for the expert to mentor the novice. This pairing can also introduce new ideas, as the novice is more likely to question established practices. The expert, now required to explain established practices, is also more likely to question them. However, in this pairing, an intimidated novice may passively "watch the master" and hesitate to participate meaningfully. Also, some experts may not have the patience needed to allow constructive novice participation. Novice–novice Novice–novice pairing can produce results significantly better than two novices working independently, although this practice is generally discouraged because it is harder for novices to develop good habits without a proper role model. == Remote pair programming == Remote pair programming, also known as virtual pair programming or distributed pair programming, is pair programming in which the two programmers are in different locations, working via a collaborative real-time editor, shared desktop, or a remote pair programming IDE plugin. Remote pairing introduces difficulties not present in face-to-face pairing, such as extra delays for coordination, depending more on "heavyweight" task-tracking tools instead of "lightweight" ones like index cards, and loss of verbal communication resulting in confusion and conflicts over such things as who "has the keyboard". Tool support could be provided by: Whole-screen sharing software Terminal multiplexers Specialized distributed editing tools Audio chat programs or VoIP software could be helpful when the screen sharing software does not provide two-way audio capability. Use of headsets keep the programmers' hands free Cloud development environments Collaborative pair programming services == See also == Extreme programming Joint attention Team programming (also known as mob programming) == References == == External links == wikiHow: How to Pair Program How-to guide; contains common wisdom on how to make pair programming work. Tuple:Pair Programming Guide Pair programming guide that covers paring styles, antipatterns, and more. Includes example paring videos. c2:PairProgramming c2:PairProgrammingPattern c2:PairRotationFrequency
https://en.wikipedia.org/wiki/Pair_programming
In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow. Many languages that apply this style attempt to minimize or eliminate side effects by describing what the program must accomplish in terms of the problem domain, rather than describing how to accomplish it as a sequence of the programming language primitives (the how being left up to the language's implementation). This is in contrast with imperative programming, which implements algorithms in explicit steps. Declarative programming often considers programs as theories of a formal logic, and computations as deductions in that logic space. Declarative programming may greatly simplify writing parallel programs. Common declarative languages include those of database query languages (e.g., SQL, XQuery), regular expressions, logic programming (e.g. Prolog, Datalog, answer set programming), functional programming, configuration management, and algebraic modeling systems. == Definition == Declarative programming is often defined as any style of programming that is not imperative. A number of other common definitions attempt to define it by simply contrasting it with imperative programming. For example: A high-level program that describes what a computation should perform. Any programming language that lacks side effects (or more specifically, is referentially transparent). A language with a clear correspondence to mathematical logic. These definitions overlap substantially. Declarative programming is a non-imperative style of programming in which programs describe their desired results without explicitly listing commands or steps that must be performed. Functional and logic programming languages are characterized by a declarative programming style. In logic programming, programs consist of sentences expressed in logical form, and computation uses those sentences to solve problems, which are also expressed in logical form. In a pure functional language, such as Haskell, all functions are without side effects, and state changes are only represented as functions that transform the state, which is explicitly represented as a first-class object in the program. Although pure functional languages are non-imperative, they often provide a facility for describing the effect of a function as a series of steps. Other functional languages, such as Lisp, OCaml and Erlang, support a mixture of procedural and functional programming. Some logic programming languages, such as Prolog, and database query languages, such as SQL, while declarative in principle, also support a procedural style of programming. == Subparadigms == Declarative programming is an umbrella term that includes a number of better-known programming paradigms. === Constraint programming === Constraint programming states relations between variables in the form of constraints that specify the properties of the target solution. The set of constraints is solved by giving a value to each variable so that the solution is consistent with the maximum number of constraints. Constraint programming often complements other paradigms: functional, logical, or even imperative programming. === Domain-specific languages === Well-known examples of declarative domain-specific languages (DSLs) include the yacc parser generator input language, QML, the Make build specification language, Puppet's configuration management language, regular expressions, Datalog, answer set programming and a subset of SQL (SELECT queries, for example). DSLs have the advantage of being useful while not necessarily needing to be Turing-complete, which makes it easier for a language to be purely declarative. Many markup languages such as HTML, MXML, XAML, XSLT or other user-interface markup languages are often declarative. HTML, for example, only describes what should appear on a webpage - it specifies neither control flow for rendering a page nor the page's possible interactions with a user. As of 2013, some software systems combine traditional user-interface markup languages (such as HTML) with declarative markup that defines what (but not how) the back-end server systems should do to support the declared interface. Such systems, typically using a domain-specific XML namespace, may include abstractions of SQL database syntax or parameterized calls to web services using representational state transfer (REST) and SOAP. === Functional programming === Functional programming languages such as Haskell, Scheme, and ML evaluate expressions via function application. Unlike the related but more imperative paradigm of procedural programming, functional programming places little emphasis on explicit sequencing. Instead, computations are characterised by various kinds of recursive higher-order function application and composition, and as such can be regarded simply as a set of mappings between domains and codomains. Many functional languages, including most of those in the ML and Lisp families, are not purely functional, and thus allow the introduction of stateful effects in programs. === Hybrid languages === Makefiles, for example, specify dependencies in a declarative fashion, but include an imperative list of actions to take as well. Similarly, yacc specifies a context free grammar declaratively, but includes code snippets from a host language, which is usually imperative (such as C). === Logic programming === Logic programming languages, such as Prolog, Datalog and answer set programming, compute by proving that a goal is a logical consequence of the program, or by showing that the goal is true in a model defined by the program. Prolog computes by reducing goals to subgoals, top-down using backward reasoning, whereas most Datalog systems compute bottom-up using forward reasoning. Answer set programs typically use SAT solvers to generate a model of the program. === Modeling === Models, or mathematical representations, of physical systems may be implemented in computer code that is declarative. The code contains a number of equations, not imperative assignments, that describe ("declare") the behavioral relationships. When a model is expressed in this formalism, a computer is able to perform algebraic manipulations to best formulate the solution algorithm. The mathematical causality is typically imposed at the boundaries of the physical system, while the behavioral description of the system itself is declarative or acausal. Declarative modeling languages and environments include Analytica, Modelica and Simile. == Examples == === Lisp === Lisp is a family of programming languages loosely inspired by mathematical notation and Alonzo Church's lambda calculus. Some dialects, such as Common Lisp, are primarily imperative but support functional programming. Others, such as Scheme, are designed for functional programming. In Scheme, the factorial function can be defined as follows: This defines the factorial function using its recursive definition. In contrast, it is more typical to define a procedure for an imperative language. In lisps and lambda calculus, functions are generally first-class citizens. Loosely, this means that functions can be inputs and outputs for other functions. This can simplify the definition of some functions. For example, writing a function to output the first n square numbers in Racket can be done accordingly: The map function accepts a function and a list; the output is a list of results of the input function on each element of the input list. === ML === ML (1973) stands for "Meta Language." ML is statically typed, and function arguments and return types may be annotated. ML is not as bracket-centric as Lisp, and instead uses a wider variety of syntax to codify the relationship between code elements, rather than appealing to list ordering and nesting to express everything. The following is an application of times_10: times_10 2 It returns "20 : int", that is, 20, a value of type int. Like Lisp, ML is tailored to process lists, though all elements of a list must be the same type. === Prolog === Prolog (1972) stands for "PROgramming in LOGic." It was developed for natural language question answering, using SL resolution both to deduce answers to queries and to parse and generate natural language sentences. The building blocks of a Prolog program are facts and rules. Here is a simple example: Given this program, the query eat(tom,jerry) succeeds, while eat(jerry,tom) fails. Moreover, the query eat(X,jerry) succeeds with the answer substitution X=tom. Prolog executes programs top-down, using SLD resolution to reason backwards, reducing goals to subgoals. In this example, it uses the last rule of the program to reduce the goal of answering the query eat(X,jerry) to the subgoals of first finding an X such that big(X) holds and then of showing that small(jerry) holds. It repeatedly uses rules to further reduce subgoals to other subgoals, until it eventually succeeds in unifying all subgoals with facts in the program. This backward reasoning, goal-reduction strategy treats rules in logic programs as procedures, and makes Prolog both a declarative and procedural programming language. The broad range of Prolog applications is highlighted in the Year of Prolog Book, celebrating the 50 year anniversary of Prolog. === Datalog === The origins of Datalog date back to the beginning of logic programming, but it was identified as a separate area around 1977. Syntactically and semantically, it is a subset of Prolog. But because it does not have compound terms, it is not Turing-complete. Most Datalog systems execute programs bottom-up, using rules to reason forwards, deriving new facts from existing facts, and terminating when there are no new facts that can be derived, or when the derived facts unify with the query. In the above example, a typical Datalog system would first derive the new facts: Using these facts, it would then derive the additional fact: It would then terminate, both because no new, additional facts can be derived, and because the newly derived fact unifies with the query Datalog has been applied to such problems as data integration, information extraction, networking, security, cloud computing and machine learning. === Answer Set Programming === Answer set programming (ASP) evolved in the late 1990s, based on the stable model (answer set) semantics of logic programming. Like Datalog, it is a subset of Prolog; and, because it does not have compound terms, it is not Turing-complete. Most implementations of ASP execute a program by first "grounding" the program, replacing all variables in rules by constants in all possible ways, and then using a propositional SAT solver, such as the DPLL algorithm to generate one or more models of the program. Its applications are oriented towards solving difficult search problems and knowledge representation. == See also == Inductive programming List of declarative programming languages == References == == External links == Frans Coenen. Characteristics of declarative programming languages. 1999. Robert Harper. What, If Anything, Is A Declarative Language?. 2013. "There Is Such A Thing As A Declarative Language, and It's The World's Best DSL". 2013. Olof Torgersson. A Note on Declarative Programming Paradigms and the Future of Definitional Programming. 1996.
https://en.wikipedia.org/wiki/Declarative_programming
Broadcast programming is the practice of organizing or ordering (scheduling) of broadcast media shows, typically radio and television, in a daily, weekly, monthly, quarterly, or season-long schedule. Modern broadcasters use broadcast automation to regularly change the scheduling of their shows to build an audience for a new show, retain that audience, or compete with other broadcasters' shows. Most broadcast television shows are presented weekly in prime time or daily in other dayparts, though there are many exceptions. At a micro level, scheduling is the minute planning of the transmission; what to broadcast and when, ensuring an adequate or maximum utilization of airtime. Television scheduling strategies are employed to give shows the best possible chance of attracting and retaining an audience. They are used to deliver shows to audiences when they are most likely to want to watch them and deliver audiences to advertisers in the composition that makes their advertising most likely to be effective. With the growth of digital platforms and services allowing non-linear, on-demand access to television content, this approach to broadcasting has since been referred to using the retronym linear (such as linear television and linear channels). == History == With the beginning of scheduled television in 1936, television programming was initially only concerned with filling a few hours each evening – the hours now known as prime time. Over time, though, television began to be seen during the daytime and late at night, as well on the weekends. As air time increased, so did the demand for new material. With the exception of sports television, variety shows became much more important in prime time. == Scheduling strategies == === Lead-ins and lead-outs === Broadcasters may schedule a program to air before or after a widely viewed tent-pole program, such as a popular series, or a special such as a high-profile sporting event (such as, in the United States, the Super Bowl), in the hope that audience flow will encourage the audience to tune-in early or stay for the second program. The second program is usually one that the broadcaster wants to promote to a wider audience, such as a new or lower-profile series. Sometimes, a lower-profile program may be scheduled between two tentpole programs, a technique known as hammocking. Lead-outs can sometimes help to launch new programs and talent; in 1982, NBC premiered Late Night with David Letterman as a lead-out for its long-running late-night talk show The Tonight Show Starring Johnny Carson. Characterized by an off-beat style appealing to young adults, Late Night helped launch the career of host David Letterman, and influence later entries into the genre. Despite Carson's endorsement of Letterman as a successor following his 1992 retirement, NBC chose Jay Leno instead, and Letterman departed for CBS to host a spiritual successor—Late Show with David Letterman—beginning in the 1993–94 season. Late Night would continue as a franchise with hosts such as Conan O'Brien and Jimmy Fallon—both of whom would later go on to host The Tonight Show. The same season, Fox scheduled The X-Files as a lead-out for its sci-fi western The Adventures of Brisco County Jr., with the expectation that Brisco County Jr. would serve as the anchor of its Friday-night lineup. However, The X-Files proved to be significantly more successful, and would eventually run for nine seasons. By contrast, viewership for Brisco County Jr. declined throughout the season, and the show was cancelled. Fox attempted to use other sci-fi shows as a lead-in for The X-Files (such as Sliders and VR.5), but they were similarly unsuccessful. A weak lead-in can have an impact on the viewership of programs that follow; NBC's 2009 attempt to strip the talk show The Jay Leno Show (a spiritual successor to Leno's tenure of The Tonight Show after Conan O'Brien succeeded him) in a 10:00 p.m. ET/PT timeslot proved detrimental to the viewership of late local newscasts on its affiliates. NBC subsequently announced plans to shorten The Jay Leno Show to a half hour and move it to 11:35 p.m. ET/PT in late-February 2010, displacing The Tonight Show from its traditional timeslot. This proposal led to a public conflict between O'Brien and NBC, and ultimately resulted in his departure from the network, and the reinstatement of Jay Leno as host of The Tonight Show. === Blocks === Block programming is the practice of scheduling a group of complementary programs together. Blocks are typically built around specific genres (i.e. a block focusing specifically on sitcoms), target audiences, or other factors, with their programming often promoted collectively under blanket titles (such as ABC's "TGIF" lineup, All TV's "Jeepney TV sa All TV", and NBC's "Must See TV"). === Bridging === Bridging is the practice of discouraging the audience from changing channels during the "junctions" between specific programs. This can be done, primarily, by airing promos for the next program near the end of the preceding program, such as during its credits, or reducing the length of the junction between two programs as much as possible (hot switching). The host of the next program may similarly make a brief appearance near the end of the preceding program (sometimes interacting directly with the host) to provide a preview; in news broadcasting, this is typically referred to as a "throw" or "toss". A bridge was used by ABC between Roseanne and the December 1992 series premiere of The Jackie Thomas Show, a new sitcom co-created by Roseanne and Tom Arnold of Roseanne fame. A scene of the Connor family watching its opening on TV seamlessly transitioned into the program itself, with no junction in between. ABC commissioned a minute-by-minute Nielsen ratings report, which showed that the majority of viewers from Roseanne had been retained during the premiere. Owing to both programs' news comedy formats, the Comedy Central program The Daily Show used newscast-style toss segments to promote its new spin-off and lead-out, The Colbert Report, in which host Jon Stewart would engage in a comedic conversation with the latter's host, Stephen Colbert, via split-screen. On the December 18, 2014 episode of The Daily Show, this segment was used to seamlessly segue into the series finale of The Colbert Report. At its conclusion, the show transitioned back to Stewart (giving the impression that the entire Colbert Report episode was merely a segment of The Daily Show), who concluded his show with its traditional closing segment "Your Moment of Zen" (which featured an outtake from a previous toss segment) as normal. In some cases, a channel may intentionally allow a program to overrun into the next half-hour timeslot rather than end exactly on the half-hour, in order to discourage viewers from "surfing" away at traditional junction periods (since they had missed the beginnings of programs on other channels already). This can, however, cause disruptions with recorders if they are not aware of the scheduling (typically, digital video recorders can be configured to automatically record for a set length of time before and after a schedule's given timeslot in program guide data to account for possible variances). For a period, TBS intentionally scheduled all of its programs at 5 and 35 minutes past the hour rather than exactly on the half hour (a practice it marketed as "Turner Time"), to attract viewers tuning away from other channels. === Crossovers === Crossovers can be organized between multiple programs, in which a single storyline is extended across episodes of two or more separate programs. Typically, these involve programs that form a single franchise or shared universe, such as NBC's Chicago franchise and Law & Order: Special Victims Unit (all created by Dick Wolf), and the ABC dramas Grey's Anatomy and Station 19 (both created by Shonda Rhimes). === Counterprogramming === Counterprogramming is the practice of deliberately scheduling programming to attract viewers away from another, major program. Counterprogramming efforts often involve scheduling a contrasting program of a different genre or demographic, targeting viewers who may not be interested in the major program (such as a sporting event, which typically draws a predominantly-male audience, against an awards show that attracts a predominantly-female audience). Despite frequently being among the top U.S. television broadcasts of all time, the Super Bowl has had a prominent history of being counterprogrammed in this manner. One of the most prominent examples of this practice was Fox's 1992 airing of a special live episode of In Living Color against the game's halftime show. Programs can also be counterprogrammed by a direct competitor in the same time slot, often resulting in the two programs attempting to attract viewers away from each other through publicity stunts and other tactics; these tactics have most notably been seen in counterprogramming efforts surrounding professional wrestling, including the Monday and Wednesday Night Wars of the 1990s and 2020s respectively. In some cases, broadcasters may attempt to adjust their schedules in order to avert attempts at counterprogramming, such as getting a slightly earlier time slot (in the hope that once viewers have become committed to a show they will not switch channels), scheduling the competing program on a different night, or moving it to a different portion of the television season to avoid competition altogether. === Dayparting === Dayparting is the practice of dividing the day into several parts, during each of which a different type program is appropriate for that time is aired. Daytime television shows are most often geared toward a particular demographic, and what the target audience typically engages in at that time. === Stripping === Stripping is the practice of running a single series in a consistent, daily time slot throughout the week, usually on weekdays. Daytime programs such as talk shows, court shows, game shows, and soap operas, are typically aired in a strip format. Outside of serial drama formats such as telenovelas where popular, strips are rarely used for first-run entertainment programming outside of limited events. Syndicated reruns of network programs that originally aired on a weekly basis are often aired as strips. Shows that are syndicated in this way generally have to have run for several seasons (the rule of thumb is usually 100 episodes) in order to have enough episodes to run without significant repeats. === Marathons === A marathon is the scheduling of a continuous, long-term block of programming as an event, usually devoted to airings of a single program or film franchise. When conducted using television series, a marathon may either consist of episodes aired in sequential order, or focus on episodes sharing specific themes. Marathons are often aired on holidays (such as Syfy's annual The Twilight Zone marathon on New Year's Day, and Game Show Network airing a Charles Nelson Reilly-hosted marathon of game show series finales on New Year's Eve in 1999), as counterprogramming for major events airing on other channels (such as the Super Bowl in the U.S.), to lead into new episodes of a series, or to commemorate milestones/events surrounding a specific series or franchise (such as an anniversary, or the network's acquisition of rights to broadcast a certain series or franchise). Some marathons may focus on the roles of a specific entertainer; the death of Betty White resulted in several networks scheduling marathons of programming on or around January 17, 2022—which would have been White's 100th birthday—featuring her television appearances, such as Hallmark Channel airing a marathon of The Golden Girls, and both Buzzr and Game Show Network airing marathons of her game show appearances. While longer marathons are typically reserved for major events, the popularization of binge-watching via streaming services in the 2010s led to many U.S. cable networks adopting marathon-like blocks of programs as their regular schedule. To compete with the release practices of streaming services, TBS premiered entire seasons of its police sitcom Angie Tribeca in a marathon format. Similarly, free ad-supported streaming television (FAST) services often feature linear channels that are narrowly-focused towards specific programs or franchises. === Theming === A broadcaster may temporarily dedicate all or parts of its schedule over a period of time to a specific theme. A well-known instance of a themed lineup is Discovery Channel's annual "Shark Week". Themed schedules are a common practice around major holidays—such as Valentine's Day, Halloween, and Christmas—where channels may air episodes of programs, specials, and films that relate to the holiday. Channels may also air marathons of their signature programs and film rights to target viewers who are on vacation. The U.S. basic cable networks Freeform (25 Days of Christmas, 31 Days of Halloween) and Hallmark Channel are known for broadcasting long-term holiday programming events. After experiencing success with its Countdown to Christmas event, Hallmark Channel adopted a practice of dividing its programming into similarly-branded "seasons" year-round, which are accompanied by thematically appropriate original series and television films. This strategy was part of an effort to position the channel as "a year-round destination for celebrations", and is synergistic with Hallmark Cards' core greeting card and collectibles businesses. === Time slot === A show's time slot or place in the schedule could be crucial to its success or failure; generally, earlier prime time slots have a stronger appeal towards family viewing and younger demographics, while later time slots generally appeal more towards older demographics. Some time slots, colloquially known as "graveyard slots" or "death slots", are prone to having smaller potential audiences (with one such example in the U.S. being Friday nights), or insurmountable competition from highly rated series. == See also == Audience flow Broadcast clock Effects of time zones on North American broadcasting Electronic media Fall schedule Interstitial program Radio Computing Services – automated scheduling for radio stations Timeshift channel TV Guide TV listings == References ==
https://en.wikipedia.org/wiki/Broadcast_programming
A programming game is a video game that incorporates elements of computer programming, enabling the player to direct otherwise autonomous units within the game to follow commands in a domain-specific programming language, often represented as a visual language to simplify the programming metaphor. Programming games broadly fall into two areas: single-player games where the programming elements either make up part of or the whole of a puzzle game, and multiplayer games where the player's automated program is pitted against other players' programs. == As puzzle games == Early games in the genre include System 15000 and Hacker, released in 1984 and 1985 respectively. Programming games have been used as part of puzzle games, challenging the player to achieve a specific result once the program starts operating. An example of such a game is SpaceChem, where the player must use its visual language to manipulate two waldos as to disassemble and reassemble chemical molecules. In such games, players are able to test and debug their program as often as necessary until they find a solution that works. Many of these games encourage the player to find the most efficient program, measured by the number of timesteps needed or number of commands required. Other similar games include Human Resource Machine, Infinifactory, and TIS-100. Zachtronics is a video game development company known for its programming-centric puzzle games. Other games incorporate the elements of programming as portions of puzzles in the larger game. For example, Hack 'n' Slash include a metaphor of being able to access the internal programs and variables of objects represented in the game world, pausing the rest of the game as the player engages this programming interface, and modify the object's program as to progress further; this might be changing the state of an object from being indestructible to destructible. Other similar games with this type of programming approach include Transistor, else Heart.Break(), Glitchspace, and Pony Island. Another approach used in some graphical games with programming elements is to present the player with a command line interface to issue orders via a domain-specific language to direct objects within the game, allowing the player to reissue commands as the situation changes rather than crafting a pre-made program. Games like Quadrilateral Cowboy and Duskers have the user command several small robotic creatures in tandem through the language of code to reach a certain goal. Hackmud presents the player with a simulated mainframe interface through which they issue commands to progress forward. == As competitive games == Many programming games involve controlling entities such as robots, tanks or bacteria which seek to destroy each other. Such games can be considered environments of digital organisms, related to artificial life simulations. An early example is Core War (1984), where programs written in a standardized assembly-like language battle for space in a finite memory (virtual magnetic cores). Players are given tools to develop and test out their programs within the game's domain-specific language before submitting the program to a central server. The server then executes the program against others and reports the results to the player, from which they can make changes or improvements to the program. There are different tournaments and leagues for the programming games where the characters can compete with each other. Usually a script is optimized for a special strategy. Similar approaches are used for more traditional games; the World Computer Chess Championship consists of matches between programs written for the abstract strategy game of chess. The competitive programming game has also found its way to various board games such as RoboRally or Robot Turtles, typically where a program becomes a premade deck of playing cards played one by one to execute that code. Researchers presented RoboCode as a "problem-based learning" substrate for teaching programming. == Related areas == Open world games that feature the ability for players to construct environments from an array of building blocks have often been used by more advanced players to construct logic circuits and more advanced programs from the fundamental blocks. Minecraft is one such example, as while the game provides a limited set of blocks that mimic switches and electric circuits, users have been able to create basic functional computers within the virtual world, and at least one modification is aimed to teach children how to program on the virtual computer in a simplistic language. Several sites, such as Codecademy, help to teach real-world programming languages through gamification, where video game principles are used to motivate the user. == See also == Programming games category List of digital organism simulators Visual programming language Zachtronics == References == == External links == The Programming Games Wiki Many inactive programming games listed at AIforge A History of Programming Games
https://en.wikipedia.org/wiki/Programming_game
A computer program is a sequence or set of instructions in a programming language for a computer to execute. It is one component of software, which also includes documentation and other intangible components. A computer program in its human-readable form is called source code. Source code needs another computer program to execute because computers can only execute their native machine instructions. Therefore, source code may be translated to machine instructions using a compiler written for the language. (Assembly language programs are translated using an assembler.) The resulting file is called an executable. Alternatively, source code may execute within an interpreter written for the language. If the executable is requested for execution, then the operating system loads it into memory and starts a process. The central processing unit will soon switch to this process so it can fetch, decode, and then execute each machine instruction. If the source code is requested for execution, then the operating system loads the corresponding interpreter into memory and starts a process. The interpreter then loads the source code into memory to translate and execute each statement. Running the source code is slower than running an executable. Moreover, the interpreter must be installed on the computer. == Example computer program == The "Hello, World!" program is used to illustrate a language's basic syntax. The syntax of the language BASIC (1964) was intentionally limited to make the language easy to learn. For example, variables are not declared before being used. Also, variables are automatically initialized to zero. Here is an example computer program, in Basic, to average a list of numbers: Once the mechanics of basic computer programming are learned, more sophisticated and powerful languages are available to build large computer systems. == History == Improvements in software development are the result of improvements in computer hardware. At each stage in hardware's history, the task of computer programming changed dramatically. === Analytical Engine === In 1837, Jacquard's loom inspired Charles Babbage to attempt to build the Analytical Engine. The names of the components of the calculating device were borrowed from the textile industry. In the textile industry, yarn was brought from the store to be milled. The device had a store which consisted of memory to hold 1,000 numbers of 50 decimal digits each. Numbers from the store were transferred to the mill for processing. The engine was programmed using two sets of perforated cards. One set directed the operation and the other set inputted the variables. However, the thousands of cogged wheels and gears never fully worked together. Ada Lovelace worked for Charles Babbage to create a description of the Analytical Engine (1843). The description contained Note G which completely detailed a method for calculating Bernoulli numbers using the Analytical Engine. This note is recognized by some historians as the world's first computer program. === Universal Turing machine === In 1936, Alan Turing introduced the Universal Turing machine, a theoretical device that can model every computation. It is a finite-state machine that has an infinitely long read/write tape. The machine can move the tape back and forth, changing its contents as it performs an algorithm. The machine starts in the initial state, goes through a sequence of steps, and halts when it encounters the halt state. All present-day computers are Turing complete. === ENIAC === The Electronic Numerical Integrator And Computer (ENIAC) was built between July 1943 and Fall 1945. It was a Turing complete, general-purpose computer that used 17,468 vacuum tubes to create the circuits. At its core, it was a series of Pascalines wired together. Its 40 units weighed 30 tons, occupied 1,800 square feet (167 m2), and consumed $650 per hour (in 1940s currency) in electricity when idle. It had 20 base-10 accumulators. Programming the ENIAC took up to two months. Three function tables were on wheels and needed to be rolled to fixed function panels. Function tables were connected to function panels by plugging heavy black cables into plugboards. Each function table had 728 rotating knobs. Programming the ENIAC also involved setting some of the 3,000 switches. Debugging a program took a week. It ran from 1947 until 1955 at Aberdeen Proving Ground, calculating hydrogen bomb parameters, predicting weather patterns, and producing firing tables to aim artillery guns. === Stored-program computers === Instead of plugging in cords and turning switches, a stored-program computer loads its instructions into memory just like it loads its data into memory. As a result, the computer could be programmed quickly and perform calculations at very fast speeds. Presper Eckert and John Mauchly built the ENIAC. The two engineers introduced the stored-program concept in a three-page memo dated February 1944. Later, in September 1944, John von Neumann began working on the ENIAC project. On June 30, 1945, von Neumann published the First Draft of a Report on the EDVAC, which equated the structures of the computer with the structures of the human brain. The design became known as the von Neumann architecture. The architecture was simultaneously deployed in the constructions of the EDVAC and EDSAC computers in 1949. The IBM System/360 (1964) was a family of computers, each having the same instruction set architecture. The Model 20 was the smallest and least expensive. Customers could upgrade and retain the same application software. The Model 195 was the most premium. Each System/360 model featured multiprogramming—having multiple processes in memory at once. When one process was waiting for input/output, another could compute. IBM planned for each model to be programmed using PL/1. A committee was formed that included COBOL, Fortran and ALGOL programmers. The purpose was to develop a language that was comprehensive, easy to use, extendible, and would replace Cobol and Fortran. The result was a large and complex language that took a long time to compile. Computers manufactured until the 1970s had front-panel switches for manual programming. The computer program was written on paper for reference. An instruction was represented by a configuration of on/off settings. After setting the configuration, an execute button was pressed. This process was then repeated. Computer programs also were automatically inputted via paper tape, punched cards or magnetic-tape. After the medium was loaded, the starting address was set via switches, and the execute button was pressed. === Very Large Scale Integration === A major milestone in software development was the invention of the Very Large Scale Integration (VLSI) circuit (1964). Robert Noyce, co-founder of Fairchild Semiconductor (1957) and Intel (1968), achieved a technological improvement to refine the production of field-effect transistors (1963). The goal is to alter the electrical resistivity and conductivity of a semiconductor junction. First, naturally occurring silicate minerals are converted into polysilicon rods using the Siemens process. The Czochralski process then converts the rods into a monocrystalline silicon, boule crystal. The crystal is then thinly sliced to form a wafer substrate. The planar process of photolithography then integrates unipolar transistors, capacitors, diodes, and resistors onto the wafer to build a matrix of metal–oxide–semiconductor (MOS) transistors. The MOS transistor is the primary component in integrated circuit chips. Originally, integrated circuit chips had their function set during manufacturing. During the 1960s, controlling the electrical flow migrated to programming a matrix of read-only memory (ROM). The matrix resembled a two-dimensional array of fuses. The process to embed instructions onto the matrix was to burn out the unneeded connections. There were so many connections, firmware programmers wrote a computer program on another chip to oversee the burning. The technology became known as Programmable ROM. In 1971, Intel installed the computer program onto the chip and named it the Intel 4004 microprocessor. The terms microprocessor and central processing unit (CPU) are now used interchangeably. However, CPUs predate microprocessors. For example, the IBM System/360 (1964) had a CPU made from circuit boards containing discrete components on ceramic substrates. === x86 series === In 1978, the modern software development environment began when Intel upgraded the Intel 8080 to the Intel 8086. Intel simplified the Intel 8086 to manufacture the cheaper Intel 8088. IBM embraced the Intel 8088 when they entered the personal computer market (1981). As consumer demand for personal computers increased, so did Intel's microprocessor development. The succession of development is known as the x86 series. The x86 assembly language is a family of backward-compatible machine instructions. Machine instructions created in earlier microprocessors were retained throughout microprocessor upgrades. This enabled consumers to purchase new computers without having to purchase new application software. The major categories of instructions are: Memory instructions to set and access numbers and strings in random-access memory. Integer arithmetic logic unit (ALU) instructions to perform the primary arithmetic operations on integers. Floating point ALU instructions to perform the primary arithmetic operations on real numbers. Call stack instructions to push and pop words needed to allocate memory and interface with functions. Single instruction, multiple data (SIMD) instructions to increase speed when multiple processors are available to perform the same algorithm on an array of data. === Changing programming environment === VLSI circuits enabled the programming environment to advance from a computer terminal (until the 1990s) to a graphical user interface (GUI) computer. Computer terminals limited programmers to a single shell running in a command-line environment. During the 1970s, full-screen source code editing became possible through a text-based user interface. Regardless of the technology available, the goal is to program in a programming language. == Programming paradigms and languages == Programming language features exist to provide building blocks to be combined to express programming ideals. Ideally, a programming language should: express ideas directly in the code. express independent ideas independently. express relationships among ideas directly in the code. combine ideas freely. combine ideas only where combinations make sense. express simple ideas simply. The programming style of a programming language to provide these building blocks may be categorized into programming paradigms. For example, different paradigms may differentiate: procedural languages, functional languages, and logical languages. different levels of data abstraction. different levels of class hierarchy. different levels of input datatypes, as in container types and generic programming. Each of these programming styles has contributed to the synthesis of different programming languages. A programming language is a set of keywords, symbols, identifiers, and rules by which programmers can communicate instructions to the computer. They follow a set of rules called a syntax. Keywords are reserved words to form declarations and statements. Symbols are characters to form operations, assignments, control flow, and delimiters. Identifiers are words created by programmers to form constants, variable names, structure names, and function names. Syntax Rules are defined in the Backus–Naur form. Programming languages get their basis from formal languages. The purpose of defining a solution in terms of its formal language is to generate an algorithm to solve the underlining problem. An algorithm is a sequence of simple instructions that solve a problem. === Generations of programming language === The evolution of programming languages began when the EDSAC (1949) used the first stored computer program in its von Neumann architecture. Programming the EDSAC was in the first generation of programming language. The first generation of programming language is machine language. Machine language requires the programmer to enter instructions using instruction numbers called machine code. For example, the ADD operation on the PDP-11 has instruction number 24576. The second generation of programming language is assembly language. Assembly language allows the programmer to use mnemonic instructions instead of remembering instruction numbers. An assembler translates each assembly language mnemonic into its machine language number. For example, on the PDP-11, the operation 24576 can be referenced as ADD in the source code. The four basic arithmetic operations have assembly instructions like ADD, SUB, MUL, and DIV. Computers also have instructions like DW (Define Word) to reserve memory cells. Then the MOV instruction can copy integers between registers and memory. The basic structure of an assembly language statement is a label, operation, operand, and comment. Labels allow the programmer to work with variable names. The assembler will later translate labels into physical memory addresses. Operations allow the programmer to work with mnemonics. The assembler will later translate mnemonics into instruction numbers. Operands tell the assembler which data the operation will process. Comments allow the programmer to articulate a narrative because the instructions alone are vague. The key characteristic of an assembly language program is it forms a one-to-one mapping to its corresponding machine language target. The third generation of programming language uses compilers and interpreters to execute computer programs. The distinguishing feature of a third generation language is its independence from particular hardware. Early languages include Fortran (1958), COBOL (1959), ALGOL (1960), and BASIC (1964). In 1973, the C programming language emerged as a high-level language that produced efficient machine language instructions. Whereas third-generation languages historically generated many machine instructions for each statement, C has statements that may generate a single machine instruction. Moreover, an optimizing compiler might overrule the programmer and produce fewer machine instructions than statements. Today, an entire paradigm of languages fill the imperative, third generation spectrum. The fourth generation of programming language emphasizes what output results are desired, rather than how programming statements should be constructed. Declarative languages attempt to limit side effects and allow programmers to write code with relatively few errors. One popular fourth generation language is called Structured Query Language (SQL). Database developers no longer need to process each database record one at a time. Also, a simple select statement can generate output records without having to understand how they are retrieved. === Imperative languages === Imperative languages specify a sequential algorithm using declarations, expressions, and statements: A declaration introduces a variable name to the computer program and assigns it to a datatype – for example: var x: integer; An expression yields a value – for example: 2 + 2 yields 4 A statement might assign an expression to a variable or use the value of a variable to alter the program's control flow – for example: x := 2 + 2; if x = 4 then do_something(); ==== Fortran ==== FORTRAN (1958) was unveiled as "The IBM Mathematical FORmula TRANslating system". It was designed for scientific calculations, without string handling facilities. Along with declarations, expressions, and statements, it supported: arrays. subroutines. "do" loops. It succeeded because: programming and debugging costs were below computer running costs. it was supported by IBM. applications at the time were scientific. However, non-IBM vendors also wrote Fortran compilers, but with a syntax that would likely fail IBM's compiler. The American National Standards Institute (ANSI) developed the first Fortran standard in 1966. In 1978, Fortran 77 became the standard until 1991. Fortran 90 supports: records. pointers to arrays. ==== COBOL ==== COBOL (1959) stands for "COmmon Business Oriented Language". Fortran manipulated symbols. It was soon realized that symbols did not need to be numbers, so strings were introduced. The US Department of Defense influenced COBOL's development, with Grace Hopper being a major contributor. The statements were English-like and verbose. The goal was to design a language so managers could read the programs. However, the lack of structured statements hindered this goal. COBOL's development was tightly controlled, so dialects did not emerge to require ANSI standards. As a consequence, it was not changed for 15 years until 1974. The 1990s version did make consequential changes, like object-oriented programming. ==== Algol ==== ALGOL (1960) stands for "ALGOrithmic Language". It had a profound influence on programming language design. Emerging from a committee of European and American programming language experts, it used standard mathematical notation and had a readable, structured design. Algol was first to define its syntax using the Backus–Naur form. This led to syntax-directed compilers. It added features like: block structure, where variables were local to their block. arrays with variable bounds. "for" loops. functions. recursion. Algol's direct descendants include Pascal, Modula-2, Ada, Delphi and Oberon on one branch. On another branch the descendants include C, C++ and Java. ==== Basic ==== BASIC (1964) stands for "Beginner's All-Purpose Symbolic Instruction Code". It was developed at Dartmouth College for all of their students to learn. If a student did not go on to a more powerful language, the student would still remember Basic. A Basic interpreter was installed in the microcomputers manufactured in the late 1970s. As the microcomputer industry grew, so did the language. Basic pioneered the interactive session. It offered operating system commands within its environment: The 'new' command created an empty slate. Statements evaluated immediately. Statements could be programmed by preceding them with line numbers. The 'list' command displayed the program. The 'run' command executed the program. However, the Basic syntax was too simple for large programs. Recent dialects added structure and object-oriented extensions. Microsoft's Visual Basic is still widely used and produces a graphical user interface. ==== C ==== C programming language (1973) got its name because the language BCPL was replaced with B, and AT&T Bell Labs called the next version "C". Its purpose was to write the UNIX operating system. C is a relatively small language, making it easy to write compilers. Its growth mirrored the hardware growth in the 1980s. Its growth also was because it has the facilities of assembly language, but uses a high-level syntax. It added advanced features like: inline assembler. arithmetic on pointers. pointers to functions. bit operations. freely combining complex operators. C allows the programmer to control which region of memory data is to be stored. Global variables and static variables require the fewest clock cycles to store. The stack is automatically used for the standard variable declarations. Heap memory is returned to a pointer variable from the malloc() function. The global and static data region is located just above the program region. (The program region is technically called the text region. It is where machine instructions are stored.) The global and static data region is technically two regions. One region is called the initialized data segment, where variables declared with default values are stored. The other region is called the block started by segment, where variables declared without default values are stored. Variables stored in the global and static data region have their addresses set at compile time. They retain their values throughout the life of the process. The global and static region stores the global variables that are declared on top of (outside) the main() function. Global variables are visible to main() and every other function in the source code. On the other hand, variable declarations inside of main(), other functions, or within { } block delimiters are local variables. Local variables also include formal parameter variables. Parameter variables are enclosed within the parenthesis of a function definition. Parameters provide an interface to the function. Local variables declared using the static prefix are also stored in the global and static data region. Unlike global variables, static variables are only visible within the function or block. Static variables always retain their value. An example usage would be the function int increment_counter(){static int counter = 0; counter++; return counter;} The stack region is a contiguous block of memory located near the top memory address. Variables placed in the stack are populated from top to bottom. A stack pointer is a special-purpose register that keeps track of the last memory address populated. Variables are placed into the stack via the assembly language PUSH instruction. Therefore, the addresses of these variables are set during runtime. The method for stack variables to lose their scope is via the POP instruction. Local variables declared without the static prefix, including formal parameter variables, are called automatic variables and are stored in the stack. They are visible inside the function or block and lose their scope upon exiting the function or block. The heap region is located below the stack. It is populated from the bottom to the top. The operating system manages the heap using a heap pointer and a list of allocated memory blocks. Like the stack, the addresses of heap variables are set during runtime. An out of memory error occurs when the heap pointer and the stack pointer meet. C provides the malloc() library function to allocate heap memory. Populating the heap with data is an additional copy function. Variables stored in the heap are economically passed to functions using pointers. Without pointers, the entire block of data would have to be passed to the function via the stack. ==== C++ ==== In the 1970s, software engineers needed language support to break large projects down into modules. One obvious feature was to decompose large projects physically into separate files. A less obvious feature was to decompose large projects logically into abstract data types. At the time, languages supported concrete (scalar) datatypes like integer numbers, floating-point numbers, and strings of characters. Abstract datatypes are structures of concrete datatypes, with a new name assigned. For example, a list of integers could be called integer_list. In object-oriented jargon, abstract datatypes are called classes. However, a class is only a definition; no memory is allocated. When memory is allocated to a class and bound to an identifier, it is called an object. Object-oriented imperative languages developed by combining the need for classes and the need for safe functional programming. A function, in an object-oriented language, is assigned to a class. An assigned function is then referred to as a method, member function, or operation. Object-oriented programming is executing operations on objects. Object-oriented languages support a syntax to model subset/superset relationships. In set theory, an element of a subset inherits all the attributes contained in the superset. For example, a student is a person. Therefore, the set of students is a subset of the set of persons. As a result, students inherit all the attributes common to all persons. Additionally, students have unique attributes that other people do not have. Object-oriented languages model subset/superset relationships using inheritance. Object-oriented programming became the dominant language paradigm by the late 1990s. C++ (1985) was originally called "C with Classes". It was designed to expand C's capabilities by adding the object-oriented facilities of the language Simula. An object-oriented module is composed of two files. The definitions file is called the header file. Here is a C++ header file for the GRADE class in a simple school application: A constructor operation is a function with the same name as the class name. It is executed when the calling operation executes the new statement. A module's other file is the source file. Here is a C++ source file for the GRADE class in a simple school application: Here is a C++ header file for the PERSON class in a simple school application: Here is a C++ source file for the PERSON class in a simple school application: Here is a C++ header file for the STUDENT class in a simple school application: Here is a C++ source file for the STUDENT class in a simple school application: Here is a driver program for demonstration: Here is a makefile to compile everything: === Declarative languages === Imperative languages have one major criticism: assigning an expression to a non-local variable may produce an unintended side effect. Declarative languages generally omit the assignment statement and the control flow. They describe what computation should be performed and not how to compute it. Two broad categories of declarative languages are functional languages and logical languages. The principle behind a functional language is to use lambda calculus as a guide for a well defined semantic. In mathematics, a function is a rule that maps elements from an expression to a range of values. Consider the function: times_10(x) = 10 * x The expression 10 * x is mapped by the function times_10() to a range of values. One value happens to be 20. This occurs when x is 2. So, the application of the function is mathematically written as: times_10(2) = 20 A functional language compiler will not store this value in a variable. Instead, it will push the value onto the computer's stack before setting the program counter back to the calling function. The calling function will then pop the value from the stack. Imperative languages do support functions. Therefore, functional programming can be achieved in an imperative language, if the programmer uses discipline. However, a functional language will force this discipline onto the programmer through its syntax. Functional languages have a syntax tailored to emphasize the what. A functional program is developed with a set of primitive functions followed by a single driver function. Consider the snippet: function max( a, b ){/* code omitted */} function min( a, b ){/* code omitted */} function range( a, b, c ) { return max( a, max( b, c ) ) - min( a, min( b, c ) ); } The primitives are max() and min(). The driver function is range(). Executing: put( range( 10, 4, 7) ); will output 6. Functional languages are used in computer science research to explore new language features. Moreover, their lack of side-effects have made them popular in parallel programming and concurrent programming. However, application developers prefer the object-oriented features of imperative languages. ==== Lisp ==== Lisp (1958) stands for "LISt Processor". It is tailored to process lists. A full structure of the data is formed by building lists of lists. In memory, a tree data structure is built. Internally, the tree structure lends nicely for recursive functions. The syntax to build a tree is to enclose the space-separated elements within parenthesis. The following is a list of three elements. The first two elements are themselves lists of two elements: ((A B) (HELLO WORLD) 94) Lisp has functions to extract and reconstruct elements. The function head() returns a list containing the first element in the list. The function tail() returns a list containing everything but the first element. The function cons() returns a list that is the concatenation of other lists. Therefore, the following expression will return the list x: cons(head(x), tail(x)) One drawback of Lisp is when many functions are nested, the parentheses may look confusing. Modern Lisp environments help ensure parenthesis match. As an aside, Lisp does support the imperative language operations of the assignment statement and goto loops. Also, Lisp is not concerned with the datatype of the elements at compile time. Instead, it assigns (and may reassign) the datatypes at runtime. Assigning the datatype at runtime is called dynamic binding. Whereas dynamic binding increases the language's flexibility, programming errors may linger until late in the software development process. Writing large, reliable, and readable Lisp programs requires forethought. If properly planned, the program may be much shorter than an equivalent imperative language program. Lisp is widely used in artificial intelligence. However, its usage has been accepted only because it has imperative language operations, making unintended side-effects possible. ==== ML ==== ML (1973) stands for "Meta Language". ML checks to make sure only data of the same type are compared with one another. For example, this function has one input parameter (an integer) and returns an integer: ML is not parenthesis-eccentric like Lisp. The following is an application of times_10(): times_10 2 It returns "20 : int". (Both the results and the datatype are returned.) Like Lisp, ML is tailored to process lists. Unlike Lisp, each element is the same datatype. Moreover, ML assigns the datatype of an element at compile time. Assigning the datatype at compile time is called static binding. Static binding increases reliability because the compiler checks the context of variables before they are used. ==== Prolog ==== Prolog (1972) stands for "PROgramming in LOGic". It is a logic programming language, based on formal logic. The language was developed by Alain Colmerauer and Philippe Roussel in Marseille, France. It is an implementation of Selective Linear Definite clause resolution, pioneered by Robert Kowalski and others at the University of Edinburgh. The building blocks of a Prolog program are facts and rules. Here is a simple example: After all the facts and rules are entered, then a question can be asked: Will Tom eat Jerry? The following example shows how Prolog will convert a letter grade to its numeric value: Here is a comprehensive example: 1) All dragons billow fire, or equivalently, a thing billows fire if the thing is a dragon: 2) A creature billows fire if one of its parents billows fire: 3) A thing X is a parent of a thing Y if X is the mother of Y or X is the father of Y: 4) A thing is a creature if the thing is a dragon: 5) Norberta is a dragon, and Puff is a creature. Norberta is the mother of Puff. Rule (2) is a recursive (inductive) definition. It can be understood declaratively, without the need to understand how it is executed. Rule (3) shows how functions are represented by using relations. Here, the mother and father functions ensure that every individual has only one mother and only one father. Prolog is an untyped language. Nonetheless, inheritance can be represented by using predicates. Rule (4) asserts that a creature is a superclass of a dragon. Questions are answered using backward reasoning. Given the question: Prolog generates two answers : Practical applications for Prolog are knowledge representation and problem solving in artificial intelligence. === Object-oriented programming === Object-oriented programming is a programming method to execute operations (functions) on objects. The basic idea is to group the characteristics of a phenomenon into an object container and give the container a name. The operations on the phenomenon are also grouped into the container. Object-oriented programming developed by combining the need for containers and the need for safe functional programming. This programming method need not be confined to an object-oriented language. In an object-oriented language, an object container is called a class. In a non-object-oriented language, a data structure (which is also known as a record) may become an object container. To turn a data structure into an object container, operations need to be written specifically for the structure. The resulting structure is called an abstract datatype. However, inheritance will be missing. Nonetheless, this shortcoming can be overcome. Here is a C programming language header file for the GRADE abstract datatype in a simple school application: The grade_new() function performs the same algorithm as the C++ constructor operation. Here is a C programming language source file for the GRADE abstract datatype in a simple school application: In the constructor, the function calloc() is used instead of malloc() because each memory cell will be set to zero. Here is a C programming language header file for the PERSON abstract datatype in a simple school application: Here is a C programming language source file for the PERSON abstract datatype in a simple school application: Here is a C programming language header file for the STUDENT abstract datatype in a simple school application: Here is a C programming language source file for the STUDENT abstract datatype in a simple school application: Here is a driver program for demonstration: Here is a makefile to compile everything: The formal strategy to build object-oriented objects is to: Identify the objects. Most likely these will be nouns. Identify each object's attributes. What helps to describe the object? Identify each object's actions. Most likely these will be verbs. Identify the relationships from object to object. Most likely these will be verbs. For example: A person is a human identified by a name. A grade is an achievement identified by a letter. A student is a person who earns a grade. === Syntax and semantics === The syntax of a computer program is a list of production rules which form its grammar. A programming language's grammar correctly places its declarations, expressions, and statements. Complementing the syntax of a language are its semantics. The semantics describe the meanings attached to various syntactic constructs. A syntactic construct may need a semantic description because a production rule may have an invalid interpretation. Also, different languages might have the same syntax; however, their behaviors may be different. The syntax of a language is formally described by listing the production rules. Whereas the syntax of a natural language is extremely complicated, a subset of the English language can have this production rule listing: a sentence is made up of a noun-phrase followed by a verb-phrase; a noun-phrase is made up of an article followed by an adjective followed by a noun; a verb-phrase is made up of a verb followed by a noun-phrase; an article is 'the'; an adjective is 'big' or an adjective is 'small'; a noun is 'cat' or a noun is 'mouse'; a verb is 'eats'; The words in bold-face are known as non-terminals. The words in 'single quotes' are known as terminals. From this production rule listing, complete sentences may be formed using a series of replacements. The process is to replace non-terminals with either a valid non-terminal or a valid terminal. The replacement process repeats until only terminals remain. One valid sentence is: sentence noun-phrase verb-phrase article adjective noun verb-phrase the adjective noun verb-phrase the big noun verb-phrase the big cat verb-phrase the big cat verb noun-phrase the big cat eats noun-phrase the big cat eats article adjective noun the big cat eats the adjective noun the big cat eats the small noun the big cat eats the small mouse However, another combination results in an invalid sentence: the small mouse eats the big cat Therefore, a semantic is necessary to correctly describe the meaning of an eat activity. One production rule listing method is called the Backus–Naur form (BNF). BNF describes the syntax of a language and itself has a syntax. This recursive definition is an example of a metalanguage. The syntax of BNF includes: ::= which translates to is made up of a[n] when a non-terminal is to its right. It translates to is when a terminal is to its right. | which translates to or. < and > which surround non-terminals. Using BNF, a subset of the English language can have this production rule listing: Using BNF, a signed-integer has the production rule listing: Notice the recursive production rule: This allows for an infinite number of possibilities. Therefore, a semantic is necessary to describe a limitation of the number of digits. Notice the leading zero possibility in the production rules: Therefore, a semantic is necessary to describe that leading zeros need to be ignored. Two formal methods are available to describe semantics. They are denotational semantics and axiomatic semantics. == Software engineering and computer programming == Software engineering is a variety of techniques to produce quality computer programs. Computer programming is the process of writing or editing source code. In a formal environment, a systems analyst will gather information from managers about all the organization's processes to automate. This professional then prepares a detailed plan for the new or modified system. The plan is analogous to an architect's blueprint. === Performance objectives === The systems analyst has the objective to deliver the right information to the right person at the right time. The critical factors to achieve this objective are: The quality of the output. Is the output useful for decision-making? The accuracy of the output. Does it reflect the true situation? The format of the output. Is the output easily understood? The speed of the output. Time-sensitive information is important when communicating with the customer in real time. === Cost objectives === Achieving performance objectives should be balanced with all of the costs, including: Development costs. Uniqueness costs. A reusable system may be expensive. However, it might be preferred over a limited-use system. Hardware costs. Operating costs. Applying a systems development process will mitigate the axiom: the later in the process an error is detected, the more expensive it is to correct. === Waterfall model === The waterfall model is an implementation of a systems development process. As the waterfall label implies, the basic phases overlap each other: The investigation phase is to understand the underlying problem. The analysis phase is to understand the possible solutions. The design phase is to plan the best solution. The implementation phase is to program the best solution. The maintenance phase lasts throughout the life of the system. Changes to the system after it is deployed may be necessary. Faults may exist, including specification faults, design faults, or coding faults. Improvements may be necessary. Adaption may be necessary to react to a changing environment. === Computer programmer === A computer programmer is a specialist responsible for writing or modifying the source code to implement the detailed plan. A programming team is likely to be needed because most systems are too large to be completed by a single programmer. However, adding programmers to a project may not shorten the completion time. Instead, it may lower the quality of the system. To be effective, program modules need to be defined and distributed to team members. Also, team members must interact with one another in a meaningful and effective way. Computer programmers may be programming in the small: programming within a single module. Chances are a module will execute modules located in other source code files. Therefore, computer programmers may be programming in the large: programming modules so they will effectively couple with each other. Programming-in-the-large includes contributing to the application programming interface (API). === Program modules === Modular programming is a technique to refine imperative language programs. Refined programs may reduce the software size, separate responsibilities, and thereby mitigate software aging. A program module is a sequence of statements that are bounded within a block and together identified by a name. Modules have a function, context, and logic: The function of a module is what it does. The context of a module are the elements being performed upon. The logic of a module is how it performs the function. The module's name should be derived first by its function, then by its context. Its logic should not be part of the name. For example, function compute_square_root( x ) or function compute_square_root_integer( i : integer ) are appropriate module names. However, function compute_square_root_by_division( x ) is not. The degree of interaction within a module is its level of cohesion. Cohesion is a judgment of the relationship between a module's name and its function. The degree of interaction between modules is the level of coupling. Coupling is a judgement of the relationship between a module's context and the elements being performed upon. === Cohesion === The levels of cohesion from worst to best are: Coincidental Cohesion: A module has coincidental cohesion if it performs multiple functions, and the functions are completely unrelated. For example, function read_sales_record_print_next_line_convert_to_float(). Coincidental cohesion occurs in practice if management enforces silly rules. For example, "Every module will have between 35 and 50 executable statements." Logical Cohesion: A module has logical cohesion if it has available a series of functions, but only one of them is executed. For example, function perform_arithmetic( perform_addition, a, b ). Temporal Cohesion: A module has temporal cohesion if it performs functions related to time. One example, function initialize_variables_and_open_files(). Another example, stage_one(), stage_two(), ... Procedural Cohesion: A module has procedural cohesion if it performs multiple loosely related functions. For example, function read_part_number_update_employee_record(). Communicational Cohesion: A module has communicational cohesion if it performs multiple closely related functions. For example, function read_part_number_update_sales_record(). Informational Cohesion: A module has informational cohesion if it performs multiple functions, but each function has its own entry and exit points. Moreover, the functions share the same data structure. Object-oriented classes work at this level. Functional Cohesion: a module has functional cohesion if it achieves a single goal working only on local variables. Moreover, it may be reusable in other contexts. === Coupling === The levels of coupling from worst to best are: Content Coupling: A module has content coupling if it modifies a local variable of another function. COBOL used to do this with the alter verb. Common Coupling: A module has common coupling if it modifies a global variable. Control Coupling: A module has control coupling if another module can modify its control flow. For example, perform_arithmetic( perform_addition, a, b ). Instead, control should be on the makeup of the returned object. Stamp Coupling: A module has stamp coupling if an element of a data structure passed as a parameter is modified. Object-oriented classes work at this level. Data Coupling: A module has data coupling if all of its input parameters are needed and none of them are modified. Moreover, the result of the function is returned as a single object. === Data flow analysis === Data flow analysis is a design method used to achieve modules of functional cohesion and data coupling. The input to the method is a data-flow diagram. A data-flow diagram is a set of ovals representing modules. Each module's name is displayed inside its oval. Modules may be at the executable level or the function level. The diagram also has arrows connecting modules to each other. Arrows pointing into modules represent a set of inputs. Each module should have only one arrow pointing out from it to represent its single output object. (Optionally, an additional exception arrow points out.) A daisy chain of ovals will convey an entire algorithm. The input modules should start the diagram. The input modules should connect to the transform modules. The transform modules should connect to the output modules. == Functional categories == Computer programs may be categorized along functional lines. The main functional categories are application software and system software. System software includes the operating system, which couples computer hardware with application software. The purpose of the operating system is to provide an environment where application software executes in a convenient and efficient manner. Both application software and system software execute utility programs. At the hardware level, a microcode program controls the circuits throughout the central processing unit. === Application software === Application software is the key to unlocking the potential of the computer system. Enterprise application software bundles accounting, personnel, customer, and vendor applications. Examples include enterprise resource planning, customer relationship management, and supply chain management software. Enterprise applications may be developed in-house as a one-of-a-kind proprietary software. Alternatively, they may be purchased as off-the-shelf software. Purchased software may be modified to provide custom software. If the application is customized, then either the company's resources are used or the resources are outsourced. Outsourced software development may be from the original software vendor or a third-party developer. The potential advantages of in-house software are features and reports may be developed exactly to specification. Management may also be involved in the development process and offer a level of control. Management may decide to counteract a competitor's new initiative or implement a customer or vendor requirement. A merger or acquisition may necessitate enterprise software changes. The potential disadvantages of in-house software are time and resource costs may be extensive. Furthermore, risks concerning features and performance may be looming. The potential advantages of off-the-shelf software are upfront costs are identifiable, the basic needs should be fulfilled, and its performance and reliability have a track record. The potential disadvantages of off-the-shelf software are it may have unnecessary features that confuse end users, it may lack features the enterprise needs, and the data flow may not match the enterprise's work processes. ==== Application service provider ==== One approach to economically obtaining a customized enterprise application is through an application service provider. Specialty companies provide hardware, custom software, and end-user support. They may speed the development of new applications because they possess skilled information system staff. The biggest advantage is it frees in-house resources from staffing and managing complex computer projects. Many application service providers target small, fast-growing companies with limited information system resources. On the other hand, larger companies with major systems will likely have their technical infrastructure in place. One risk is having to trust an external organization with sensitive information. Another risk is having to trust the provider's infrastructure reliability. === Operating system === An operating system is the low-level software that supports a computer's basic functions, such as scheduling processes and controlling peripherals. In the 1950s, the programmer, who was also the operator, would write a program and run it. After the program finished executing, the output may have been printed, or it may have been punched onto paper tape or cards for later processing. More often than not the program did not work. The programmer then looked at the console lights and fiddled with the console switches. If less fortunate, a memory printout was made for further study. In the 1960s, programmers reduced the amount of wasted time by automating the operator's job. A program called an operating system was kept in the computer at all times. The term operating system may refer to two levels of software. The operating system may refer to the kernel program that manages the processes, memory, and devices. More broadly, the operating system may refer to the entire package of the central software. The package includes a kernel program, command-line interpreter, graphical user interface, utility programs, and editor. ==== Kernel Program ==== The kernel's main purpose is to manage the limited resources of a computer: The kernel program should perform process scheduling, which is also known as a context switch. The kernel creates a process control block when a computer program is selected for execution. However, an executing program gets exclusive access to the central processing unit only for a time slice. To provide each user with the appearance of continuous access, the kernel quickly preempts each process control block to execute another one. The goal for system developers is to minimize dispatch latency. The kernel program should perform memory management. When the kernel initially loads an executable into memory, it divides the address space logically into regions. The kernel maintains a master-region table and many per-process-region (pregion) tables—one for each running process. These tables constitute the virtual address space. The master-region table is used to determine where its contents are located in physical memory. The pregion tables allow each process to have its own program (text) pregion, data pregion, and stack pregion. The program pregion stores machine instructions. Since machine instructions do not change, the program pregion may be shared by many processes of the same executable. To save time and memory, the kernel may load only blocks of execution instructions from the disk drive, not the entire execution file completely. The kernel is responsible for translating virtual addresses into physical addresses. The kernel may request data from the memory controller and, instead, receive a page fault. If so, the kernel accesses the memory management unit to populate the physical data region and translate the address. The kernel allocates memory from the heap upon request by a process. When the process is finished with the memory, the process may request for it to be freed. If the process exits without requesting all allocated memory to be freed, then the kernel performs garbage collection to free the memory. The kernel also ensures that a process only accesses its own memory, and not that of the kernel or other processes. The kernel program should perform file system management. The kernel has instructions to create, retrieve, update, and delete files. The kernel program should perform device management. The kernel provides programs to standardize and simplify the interface to the mouse, keyboard, disk drives, printers, and other devices. Moreover, the kernel should arbitrate access to a device if two processes request it at the same time. The kernel program should perform network management. The kernel transmits and receives packets on behalf of processes. One key service is to find an efficient route to the target system. The kernel program should provide system level functions for programmers to use. Programmers access files through a relatively simple interface that in turn executes a relatively complicated low-level I/O interface. The low-level interface includes file creation, file descriptors, file seeking, physical reading, and physical writing. Programmers create processes through a relatively simple interface that in turn executes a relatively complicated low-level interface. Programmers perform date/time arithmetic through a relatively simple interface that in turn executes a relatively complicated low-level time interface. The kernel program should provide a communication channel between executing processes. For a large software system, it may be desirable to engineer the system into smaller processes. Processes may communicate with one another by sending and receiving signals. Originally, operating systems were programmed in assembly; however, modern operating systems are typically written in higher-level languages like C, Objective-C, and Swift. === Utility program === A utility program is designed to aid system administration and software execution. Operating systems execute hardware utility programs to check the status of disk drives, memory, speakers, and printers. A utility program may optimize the placement of a file on a crowded disk. System utility programs monitor hardware and network performance. When a metric is outside an acceptable range, a trigger alert is generated. Utility programs include compression programs so data files are stored on less disk space. Compressed programs also save time when data files are transmitted over the network. Utility programs can sort and merge data sets. Utility programs detect computer viruses. === Microcode program === A microcode program is the bottom-level interpreter that controls the data path of software-driven computers. (Advances in hardware have migrated these operations to hardware execution circuits.) Microcode instructions allow the programmer to more easily implement the digital logic level—the computer's real hardware. The digital logic level is the boundary between computer science and computer engineering. A logic gate is a tiny transistor that can return one of two signals: on or off. Having one transistor forms the NOT gate. Connecting two transistors in series forms the NAND gate. Connecting two transistors in parallel forms the NOR gate. Connecting a NOT gate to a NAND gate forms the AND gate. Connecting a NOT gate to a NOR gate forms the OR gate. These five gates form the building blocks of binary algebra—the digital logic functions of the computer. Microcode instructions are mnemonics programmers may use to execute digital logic functions instead of forming them in binary algebra. They are stored in a central processing unit's (CPU) control store. These hardware-level instructions move data throughout the data path. The micro-instruction cycle begins when the microsequencer uses its microprogram counter to fetch the next machine instruction from random-access memory. The next step is to decode the machine instruction by selecting the proper output line to the hardware module. The final step is to execute the instruction using the hardware module's set of gates. Instructions to perform arithmetic are passed through an arithmetic logic unit (ALU). The ALU has circuits to perform elementary operations to add, shift, and compare integers. By combining and looping the elementary operations through the ALU, the CPU performs its complex arithmetic. Microcode instructions move data between the CPU and the memory controller. Memory controller microcode instructions manipulate two registers. The memory address register is used to access each memory cell's address. The memory data register is used to set and read each cell's contents. Microcode instructions move data between the CPU and the many computer buses. The disk controller bus writes to and reads from hard disk drives. Data is also moved between the CPU and other functional units via the peripheral component interconnect express bus. == Notes == == References ==
https://en.wikipedia.org/wiki/Computer_program
The terms local programme, local programming, local content or local television refers to a television program made by a television station or independent television producer for broadcast only within the station's transmission area or television market. Local programmes can encompass the whole range of programme genres but will usually only cover subjects or people of particular interest to an audience within the station's coverage area. For example, a local sports programme will present results, interviews and coverage of games or matches, just like a network sports programme, but it would only feature teams and players from within the broadcaster's transmission area. In some cases a television network programme may include a local element as well. This is particularly the case in the United Kingdom and still happens today with Politics Show. The BBC regions will all opt-out at the same time from the main programme to present a locally produced segment. Sometimes locally made programmes that are not too specific to the transmission area, will be sold to other local stations for broadcast in their region. Historically there was a large percentage of local programming on television. Late in the 20th century this has significantly fallen. In many cases the only local programmes on a television station today will be the local newscast. The above can also apply to radio. A national radio network may have local studios or affiliates who opt-out at various times to present local programs and content. In the late-1950s, many of the early Australian television series such as Melbourne Magazine (1957), Sydney Tonight (1956–1959), and TV Talent Scout (1957–1958) were broadcast in only a single city. == Canada == In Canada, historically local television stations produced a significant volume of local programming, including newscasts, locally or regionally oriented talk shows, and variety entertainment programs such as Tiny Talent Time or Homegrown Cafe; a few stations, such as CHCH-TV in Hamilton, Ontario and CJOH in Ottawa, also distributed some of their local programming more widely through television syndication, most notably CHCH's Hilarious House of Frightenstein and CJOH's You Can't Do That on Television, both of which were broadcast across both Canada and the United States. With the cross-national consolidation of Canadian media ownership in the 1990s and 2000s, network-affiliated stations now rarely produce much more than their own local or regional newscasts, although some stations may continue to produce a small amount of additional local programming. Independent stations may produce more local programming, although such stations are now rare in the Canadian media landscape. In radio, virtually all Canadian commercial radio stations are officially programmed locally, although many stations cut costs by contracting some dayparts out to voice-tracked hosts who are not actually located in the station's physical studio or even necessarily in the same city, using a home studio, and may even be performing their show from the United States. The CBC Radio One, CBC Radio 2, Ici Radio-Canada Première and Ici Musique networks consist primarily of networked national programming, although all include some degree of local programming in certain time blocks. Radio One and Première stations have a significant number of production centres which create and air their own local morning and/or afternoon talk shows, while Radio 2's and Ici Musique's local content is limited to local news and weather updates. == United States == The term is also generally accepted to refer to television programming that is not produced by a broadcast or other media source for national or international distribution (broadcast syndication). Usually programming of local interest is produced by either a Public, educational, and government access (PEG) television organization, cable TV operator or broadcast network affiliate stations that offer local radio news and television news. === Placeholder use of term === Additionally, the term is used in a more generic form in the United States, Canada, Mexico and other countries in the Western Hemisphere as a placeholder term within published national program guide listings in publications such as the post-2006 format TV Guide or USA Today which only carry the default schedules of national networks, where the "local programming" designation replaces detailed listings for a local station that would be impossible to print in a national publication. Outside of local newscasts and some rare non-news programming however, the term merely describes time periods under a local station's control, where syndicated content airs rather than true local programming. For equivalent electronic program guide listings for set-top boxes, the term is used mainly with PEG stations and networks which do not have a schedule compiled by a cable operator as a default placeholder; other instances are with only broadcast stations who outright refuse or do not release their program listings due to lack of staff, though as advertisers usually demand a minimum schedule to place their ads on a television station (and most of these stations are associated with smaller national digital subchannel networks which do provide a default schedule for distribution), the vast majority of broadcast stations do provide program listings. Wikipedia itself also uses this designation in its series of American network television schedule articles for non-network programming time. == United Kingdom == Many local television stations in the United Kingdom ceased broadcasting due to a lack of viability, but some stations are still being broadcast, including: Midlands Asian Television (MATV) NVTV (Northern Visions Television), Belfast That's TV == See also == Advertorial, a common form of local programming in North America where local businesses advertise their products and services List of local children's television series (United States) Local television in Greece Local origination (disambiguation) Network affiliate Regional television in Australia Regional variation == References ==
https://en.wikipedia.org/wiki/Local_programming
An integer programming problem is a mathematical optimization or feasibility program in which some or all of the variables are restricted to be integers. In many settings the term refers to integer linear programming (ILP), in which the objective function and the constraints (other than the integer constraints) are linear. Integer programming is NP-complete. In particular, the special case of 0–1 integer linear programming, in which unknowns are binary, and only the restrictions must be satisfied, is one of Karp's 21 NP-complete problems. If some decision variables are not discrete, the problem is known as a mixed-integer programming problem. == Canonical and standard form for ILPs == In integer linear programming, the canonical form is distinct from the standard form. An integer linear program in canonical form is expressed thus (note that it is the x {\displaystyle \mathbf {x} } vector which is to be decided): maximize x ∈ Z n c T x subject to A x ≤ b , x ≥ 0 {\displaystyle {\begin{aligned}&{\underset {\mathbf {x} \in \mathbb {Z} ^{n}}{\text{maximize}}}&&\mathbf {c} ^{\mathrm {T} }\mathbf {x} \\&{\text{subject to}}&&A\mathbf {x} \leq \mathbf {b} ,\\&&&\mathbf {x} \geq \mathbf {0} \end{aligned}}} and an ILP in standard form is expressed as maximize x ∈ Z n c T x subject to A x + s = b , s ≥ 0 , x ≥ 0 , {\displaystyle {\begin{aligned}&{\underset {\mathbf {x} \in \mathbb {Z} ^{n}}{\text{maximize}}}&&\mathbf {c} ^{\mathrm {T} }\mathbf {x} \\&{\text{subject to}}&&A\mathbf {x} +\mathbf {s} =\mathbf {b} ,\\&&&\mathbf {s} \geq \mathbf {0} ,\\&&&\mathbf {x} \geq \mathbf {0} ,\end{aligned}}} where c ∈ R n , b ∈ R m {\displaystyle \mathbf {c} \in \mathbb {R} ^{n},\mathbf {b} \in \mathbb {R} ^{m}} are vectors and A ∈ R m × n {\displaystyle A\in \mathbb {R} ^{m\times n}} is a matrix. As with linear programs, ILPs not in standard form can be converted to standard form by eliminating inequalities, introducing slack variables ( s {\displaystyle \mathbf {s} } ) and replacing variables that are not sign-constrained with the difference of two sign-constrained variables. == Example == The plot on the right shows the following problem. maximize x , y ∈ Z y subject to − x + y ≤ 1 3 x + 2 y ≤ 12 2 x + 3 y ≤ 12 x , y ≥ 0 {\displaystyle {\begin{aligned}{\underset {x,y\in \mathbb {Z} }{\text{maximize}}}\quad &y\\{\text{subject to}}\quad &-x+y\leq 1\\&3x+2y\leq 12\\&2x+3y\leq 12\\&x,y\geq 0\end{aligned}}} The feasible integer points are shown in red, and the red dashed lines indicate their convex hull, which is the smallest convex polyhedron that contains all of these points. The blue lines together with the coordinate axes define the polyhedron of the LP relaxation, which is given by the inequalities without the integrality constraint. The goal of the optimization is to move the black dashed line as far upward while still touching the polyhedron. The optimal solutions of the integer problem are the points ( 1 , 2 ) {\displaystyle (1,2)} and ( 2 , 2 ) {\displaystyle (2,2)} that both have an objective value of 2. The unique optimum of the relaxation is ( 1.8 , 2.8 ) {\displaystyle (1.8,2.8)} with objective value of 2.8. If the solution of the relaxation is rounded to the nearest integers, it is not feasible for the ILP. See projection into simplex == Proof of NP-hardness == The following is a reduction from minimum vertex cover to integer programming that will serve as the proof of NP-hardness. Let G = ( V , E ) {\displaystyle G=(V,E)} be an undirected graph. Define a linear program as follows: min ∑ v ∈ V y v y v + y u ≥ 1 ∀ u , v ∈ E y v ∈ Z + ∀ v ∈ V {\displaystyle {\begin{aligned}\min \sum _{v\in V}y_{v}\\y_{v}+y_{u}&\geq 1&&\forall u,v\in E\\y_{v}&\in \mathbb {Z^{+}} &&\forall v\in V\end{aligned}}} Given that the constraints limit y v {\displaystyle y_{v}} to either 0 or 1, any feasible solution to the integer program is a subset of vertices. The first constraint implies that at least one end point of every edge is included in this subset. Therefore, the solution describes a vertex cover. Additionally given some vertex cover C, y v {\displaystyle y_{v}} can be set to 1 for any v ∈ C {\displaystyle v\in C} and to 0 for any v ∉ C {\displaystyle v\not \in C} thus giving us a feasible solution to the integer program. Thus we can conclude that if we minimize the sum of y v {\displaystyle y_{v}} we have also found the minimum vertex cover. == Variants == Mixed-integer linear programming (MILP) involves problems in which only some of the variables, x i {\displaystyle x_{i}} , are constrained to be integers, while other variables are allowed to be non-integers. Zero–one linear programming (or binary integer programming) involves problems in which the variables are restricted to be either 0 or 1. Any bounded integer variable can be expressed as a combination of binary variables. For example, given an integer variable, 0 ≤ x ≤ U {\displaystyle 0\leq x\leq U} , the variable can be expressed using ⌊ log 2 ⁡ U ⌋ + 1 {\displaystyle \lfloor \log _{2}U\rfloor +1} binary variables: x = x 1 + 2 x 2 + 4 x 3 + ⋯ + 2 ⌊ log 2 ⁡ U ⌋ x ⌊ log 2 ⁡ U ⌋ + 1 . {\displaystyle x=x_{1}+2x_{2}+4x_{3}+\cdots +2^{\lfloor \log _{2}U\rfloor }x_{\lfloor \log _{2}U\rfloor +1}.} == Applications == There are two main reasons for using integer variables when modeling problems as a linear program: The integer variables represent quantities that can only be integer. For example, it is not possible to build 3.7 cars. The integer variables represent decisions (e.g. whether to include an edge in a graph) and so should only take on the value 0 or 1. These considerations occur frequently in practice and so integer linear programming can be used in many applications areas, some of which are briefly described below. === Production planning === Mixed-integer programming has many applications in industrial productions, including job-shop modelling. One important example happens in agricultural production planning and involves determining production yield for several crops that can share resources (e.g. land, labor, capital, seeds, fertilizer, etc.). A possible objective is to maximize the total production, without exceeding the available resources. In some cases, this can be expressed in terms of a linear program, but the variables must be constrained to be integer. === Scheduling === These problems involve service and vehicle scheduling in transportation networks. For example, a problem may involve assigning buses or subways to individual routes so that a timetable can be met, and also to equip them with drivers. Here binary decision variables indicate whether a bus or subway is assigned to a route and whether a driver is assigned to a particular train or subway. The zero–one programming technique has been successfully applied to solve a project selection problem in which projects are mutually exclusive and/or technologically interdependent. === Territorial partitioning === Territorial partitioning or districting problems consist of partitioning a geographical region into districts in order to plan some operations while considering different criteria or constraints. Some requirements for this problem are: contiguity, compactness, balance or equity, respect of natural boundaries, and socio-economic homogeneity. Some applications for this type of problem include: political districting, school districting, health services districting and waste management districting. === Telecommunications networks === The goal of these problems is to design a network of lines to install so that a predefined set of communication requirements are met and the total cost of the network is minimal. This requires optimizing both the topology of the network along with setting the capacities of the various lines. In many cases, the capacities are constrained to be integer quantities. Usually there are, depending on the technology used, additional restrictions that can be modeled as linear inequalities with integer or binary variables. === Cellular networks === The task of frequency planning in GSM mobile networks involves distributing available frequencies across the antennas so that users can be served and interference is minimized between the antennas. This problem can be formulated as an integer linear program in which binary variables indicate whether a frequency is assigned to an antenna. === Other applications === Cash flow matching Energy system optimization UAV guidance Transit map layouting == Algorithms == The naive way to solve an ILP is to simply remove the constraint that x is integer, solve the corresponding LP (called the LP relaxation of the ILP), and then round the entries of the solution to the LP relaxation. But, not only may this solution not be optimal, it may not even be feasible; that is, it may violate some constraint. === Using total unimodularity === While in general the solution to LP relaxation will not be guaranteed to be integral, if the ILP has the form max c T x {\displaystyle \max \mathbf {c} ^{\mathrm {T} }\mathbf {x} } such that A x = b {\displaystyle A\mathbf {x} =\mathbf {b} } where A {\displaystyle A} and b {\displaystyle \mathbf {b} } have all integer entries and A {\displaystyle A} is totally unimodular, then every basic feasible solution is integral. Consequently, the solution returned by the simplex algorithm is guaranteed to be integral. To show that every basic feasible solution is integral, let x {\displaystyle \mathbf {x} } be an arbitrary basic feasible solution . Since x {\displaystyle \mathbf {x} } is feasible, we know that A x = b {\displaystyle A\mathbf {x} =\mathbf {b} } . Let x 0 = [ x n 1 , x n 2 , ⋯ , x n j ] {\displaystyle \mathbf {x} _{0}=[x_{n_{1}},x_{n_{2}},\cdots ,x_{n_{j}}]} be the elements corresponding to the basis columns for the basic solution x {\displaystyle \mathbf {x} } . By definition of a basis, there is some square submatrix B {\displaystyle B} of A {\displaystyle A} with linearly independent columns such that B x 0 = b {\displaystyle B\mathbf {x} _{0}=\mathbf {b} } . Since the columns of B {\displaystyle B} are linearly independent and B {\displaystyle B} is square, B {\displaystyle B} is nonsingular, and therefore by assumption, B {\displaystyle B} is unimodular and so det ( B ) = ± 1 {\displaystyle \det(B)=\pm 1} . Also, since B {\displaystyle B} is nonsingular, it is invertible and therefore x 0 = B − 1 b {\displaystyle \mathbf {x} _{0}=B^{-1}\mathbf {b} } . By definition, B − 1 = B a d j det ( B ) = ± B a d j {\displaystyle B^{-1}={\frac {B^{\mathrm {adj} }}{\det(B)}}=\pm B^{\mathrm {adj} }} . Here B a d j {\displaystyle B^{\mathrm {adj} }} denotes the adjugate of B {\displaystyle B} and is integral because B {\displaystyle B} is integral. Therefore, ⇒ B − 1 = ± B a d j is integral. ⇒ x 0 = B − 1 b is integral. ⇒ Every basic feasible solution is integral. {\displaystyle {\begin{aligned}&\Rightarrow B^{-1}=\pm B^{\mathrm {adj} }{\text{ is integral.}}\\&\Rightarrow \mathbf {x} _{0}=B^{-1}b{\text{ is integral.}}\\&\Rightarrow {\text{Every basic feasible solution is integral.}}\end{aligned}}} Thus, if the matrix A {\displaystyle A} of an ILP is totally unimodular, rather than use an ILP algorithm, the simplex method can be used to solve the LP relaxation and the solution will be integer. === Exact algorithms === When the matrix A {\displaystyle A} is not totally unimodular, there are a variety of algorithms that can be used to solve integer linear programs exactly. One class of algorithms are cutting plane methods, which work by solving the LP relaxation and then adding linear constraints that drive the solution towards being integer without excluding any integer feasible points. Another class of algorithms are variants of the branch and bound method. For example, the branch and cut method that combines both branch and bound and cutting plane methods. Branch and bound algorithms have a number of advantages over algorithms that only use cutting planes. One advantage is that the algorithms can be terminated early and as long as at least one integral solution has been found, a feasible, although not necessarily optimal, solution can be returned. Further, the solutions of the LP relaxations can be used to provide a worst-case estimate of how far from optimality the returned solution is. Finally, branch and bound methods can be used to return multiple optimal solutions. === Exact algorithms for a small number of variables === Suppose A {\displaystyle A} is an m-by-n integer matrix and b {\displaystyle \mathbf {b} } is an m-by-1 integer vector. We focus on the feasibility problem, which is to decide whether there exists an n-by-1 vector x {\displaystyle \mathbf {x} } satisfying A x ≤ b {\displaystyle A\mathbf {x} \leq \mathbf {b} } . Let V be the maximum absolute value of the coefficients in A {\displaystyle A} and b {\displaystyle \mathbf {b} } . If n (the number of variables) is a fixed constant, then the feasibility problem can be solved in time polynomial in m and log V. This is trivial for the case n=1. The case n=2 was solved in 1981 by Herbert Scarf. The general case was solved in 1983 by Hendrik Lenstra, combining ideas by László Lovász and Peter van Emde Boas. Doignon's theorem asserts that an integer program is feasible whenever every subset of 2 n {\displaystyle 2^{n}} constraints is feasible; a method combining this result with algorithms for LP-type problems can be used to solve integer programs in time that is linear in m {\displaystyle m} and fixed-parameter tractable (FPT) in n {\displaystyle n} , but possibly doubly exponential in n {\displaystyle n} , with no dependence on V {\displaystyle V} . In the special case of 0-1 ILP, Lenstra's algorithm is equivalent to complete enumeration: the number of all possible solutions is fixed (2n), and checking the feasibility of each solution can be done in time poly(m, log V). In the general case, where each variable can be an arbitrary integer, complete enumeration is impossible. Here, Lenstra's algorithm uses ideas from Geometry of numbers. It transforms the original problem into an equivalent one with the following property: either the existence of a solution x {\displaystyle \mathbf {x} } is obvious, or the value of x n {\displaystyle x_{n}} (the n-th variable) belongs to an interval whose length is bounded by a function of n. In the latter case, the problem is reduced to a bounded number of lower-dimensional problems. The run-time complexity of the algorithm has been improved in several steps: The original algorithm of Lenstra had run-time 2 O ( n 3 ) ⋅ ( m ⋅ log ⁡ V ) O ( 1 ) {\displaystyle 2^{O(n^{3})}\cdot (m\cdot \log V)^{O(1)}} . Kannan presented an improved algorithm with run-time n O ( n ) ⋅ ( m ⋅ log ⁡ V ) O ( 1 ) {\displaystyle n^{O(n)}\cdot (m\cdot \log V)^{O(1)}} . Frank and Tardos presented an improved algorithm with run-time n 2.5 n ⋅ 2 O ( n ) ⋅ ( m ⋅ log ⁡ V ) O ( 1 ) {\displaystyle n^{2.5n}\cdot 2^{O(n)}\cdot (m\cdot \log V)^{O(1)}} .: Prop.8  Dadush presented an improved algorithm with run-time n n ⋅ 2 O ( n ) ⋅ ( m ⋅ log ⁡ V ) O ( 1 ) {\displaystyle n^{n}\cdot 2^{O(n)}\cdot (m\cdot \log V)^{O(1)}} . Reis and Rothvoss presented an improved algorithm with run-time ( log ⁡ n ) O ( n ) ⋅ ( m ⋅ log ⁡ V ) O ( 1 ) {\displaystyle (\log n)^{O(n)}\cdot (m\cdot \log V)^{O(1)}} . These algorithms can also be used for mixed integer linear programs (MILP) - programs in which some variables are integer and some variables are real. The original algorithm of Lenstra: Sec.5  has run-time 2 O ( n 3 ) ⋅ p o l y ( d , L ) {\displaystyle 2^{O(n^{3})}\cdot poly(d,L)} , where n is the number of integer variables, d is the number of continuous variables, and L is the binary encoding size of the problem. Using techniques from later algorithms, the factor 2 O ( n 3 ) {\displaystyle 2^{O(n^{3})}} can be improved to 2 O ( n log ⁡ n ) {\displaystyle 2^{O(n\log n)}} or to n n {\displaystyle n^{n}} . === Heuristic methods === Since integer linear programming is NP-hard, many problem instances are intractable and so heuristic methods must be used instead. For example, tabu search can be used to search for solutions to ILPs. To use tabu search to solve ILPs, moves can be defined as incrementing or decrementing an integer constrained variable of a feasible solution while keeping all other integer-constrained variables constant. The unrestricted variables are then solved for. Short-term memory can consist of previously tried solutions while medium-term memory can consist of values for the integer constrained variables that have resulted in high objective values (assuming the ILP is a maximization problem). Finally, long-term memory can guide the search towards integer values that have not previously been tried. Other heuristic methods that can be applied to ILPs include Hill climbing Simulated annealing Reactive search optimization Ant colony optimization Hopfield neural networks There are also a variety of other problem-specific heuristics, such as the k-opt heuristic for the traveling salesman problem. A disadvantage of heuristic methods is that if they fail to find a solution, it cannot be determined whether it is because there is no feasible solution or whether the algorithm simply was unable to find one. Further, it is usually impossible to quantify how close to optimal a solution returned by these methods are. == Sparse integer programming == It is often the case that the matrix A {\displaystyle A} that defines the integer program is sparse. In particular, this occurs when the matrix has a block structure, which is the case in many applications. The sparsity of the matrix can be measured as follows. The graph of A {\displaystyle A} has vertices corresponding to columns of A {\displaystyle A} , and two columns form an edge if A {\displaystyle A} has a row where both columns have nonzero entries. Equivalently, the vertices correspond to variables, and two variables form an edge if they share an inequality. The sparsity measure d {\displaystyle d} of A {\displaystyle A} is the minimum of the tree-depth of the graph of A {\displaystyle A} and the tree-depth of the graph of the transpose of A {\displaystyle A} . Let a {\displaystyle a} be the numeric measure of A {\displaystyle A} defined as the maximum absolute value of any entry of A {\displaystyle A} . Let n {\displaystyle n} be the number of variables of the integer program. Then it was shown in 2018 that integer programming can be solved in strongly polynomial and fixed-parameter tractable time parameterized by a {\displaystyle a} and d {\displaystyle d} . That is, for some computable function f {\displaystyle f} and some constant k {\displaystyle k} , integer programming can be solved in time f ( a , d ) n k {\displaystyle f(a,d)n^{k}} . In particular, the time is independent of the right-hand side b {\displaystyle b} and objective function c {\displaystyle c} . Moreover, in contrast to the classical result of Lenstra, where the number n {\displaystyle n} of variables is a parameter, here the number n {\displaystyle n} of variables is a variable part of the input. == See also == Constrained least squares Diophantine equation – Polynomial equation whose integer solutions are sought == References == == Further reading == George L. Nemhauser; Laurence A. Wolsey (1988). Integer and combinatorial optimization. Wiley. ISBN 978-0-471-82819-8. Alexander Schrijver (1998). Theory of linear and integer programming. John Wiley and Sons. ISBN 978-0-471-98232-6. Laurence A. Wolsey (1998). Integer programming. Wiley. ISBN 978-0-471-28366-9. Dimitris Bertsimas; Robert Weismantel (2005). Optimization over integers. Dynamic Ideas. ISBN 978-0-9759146-2-5. John K. Karlof (2006). Integer programming: theory and practice. CRC Press. ISBN 978-0-8493-1914-3. H. Paul Williams (2009). Logic and Integer Programming. Springer. ISBN 978-0-387-92279-9. Michael Jünger; Thomas M. Liebling; Denis Naddef; George Nemhauser; William R. Pulleyblank; Gerhard Reinelt; Giovanni Rinaldi; Laurence A. Wolsey, eds. (2009). 50 Years of Integer Programming 1958-2008: From the Early Years to the State-of-the-Art. Springer. ISBN 978-3-540-68274-5. Der-San Chen; Robert G. Batson; Yu Dang (2010). Applied Integer Programming: Modeling and Solution. John Wiley and Sons. ISBN 978-0-470-37306-4. Gerard Sierksma; Yori Zwols (2015). Linear and Integer Optimization: Theory and Practice. CRC Press. ISBN 978-1-498-71016-9. == External links == A Tutorial on Integer Programming Conference Integer Programming and Combinatorial Optimization, IPCO The Aussois Combinatorial Optimization Workshop
https://en.wikipedia.org/wiki/Integer_programming
Programming is a form of music production and performance using electronic devices and computer software, such as sequencers and workstations or hardware synthesizers, sampler and sequencers, to generate sounds of musical instruments. These musical sounds are created through the use of music coding languages. There are many music coding languages of varying complexity. Music programming is also frequently used in modern pop and rock music from various regions of the world, and sometimes in jazz and contemporary classical music. It gained popularity in the 1950s and has been emerging ever since. Music programming is the process in which a musician produces a sound or "patch" (be it from scratch or with the aid of a synthesizer/sampler), or uses a sequencer to arrange a song. == Coding languages == Music coding languages are used to program the electronic devices to produce the instrumental sounds they make. Each coding language has its own level of difficulty and function. === Alda === The music coding language Alda provides a tutorial on coding music and is, "designed for musicians who do not know how to program, as well as programmers who do not know how to music". The website also has links to install, tutorial, cheat sheet, docs, and community for anyone visiting the website. === LC === LC computer music programming language is a more complex computer music programming language meant for more experienced coders. One of the differences between this language and other music coding languages is that, "Unlike existing unit-generator languages, LC provides objects as well as library functions and methods that can directly represent microsounds and related manipulations that are involved in microsound synthesis." == History and development == Music programming has had a vast history of development leading to the creation of different programs and languages. Each development comes with more function and utility and each decade tends to favor a certain program and or piece of equipment. === MUSIC-N === The first digital synthesis family of computer programs and languages being MUSIC-N created by Max Mathews. The development of these programs, allowed for more flexibility and utility, eventually leading them to become fully developed languages. As programs such as MUSIC I, MUSIC II and MUSIC III were developed, which were all created by Max Matthews, new technologies were incorporated in such as the table-lookup oscillator in MUSIC II and the unit generator in MUSIC III. The breakthrough technologies such as the unit generator, which acted as a building block for music programming software, and the acoustic compiler, which allowed "unlimited number of sound synthesis structures to be created in the computer", further the complexity and evolution of music programming systems. === Drum machines === Around the time of the 1950s, electric rhythm machines began to make way into popular music. These machines began to gain much traction amongst many artists as they saw it as a way to create percussion sounds in an easier and more efficient way. Artists who used this kind of technology include J. J. Cale, Sly Stone, Phil Collins, Marvin Gaye, and Prince. Some of the popular drum machines through the time of the 1950s-1970s were the Side Man, Ace Tone's Rhythm Ace, Korg's Doncamatic, and Maestro's Rhythm King. In 1979, the LM-1 drum machine computer was released by guitarist Roger Linn, its goal being to help artists achieve realistic sounding drum sounds. This drum machine had eight different drum sounds: kick drum, snare, hi-hat, cabasa, tambourine, two tom toms, two congas, cowbell, clave, and handclaps. The different sounds could be recorded individually and they sounded real because of the high frequencies of the sound (28 kHz). Some notable artists who used the LM-1 were Peter Gabriel, Stevie Wonder, Michael Jackson, and Madonna. These developments continued to happen in future decades leading to the creation of new electrical instruments such as the Theremin, Hammond organ, electric guitar, synthesizer, and digital sampler. Other technologies such as the phonograph, tape-recorder, and compact disc have enabled artists to create and produce sounds without the use of live musicians. === Music programming in the 1980s === The music programming innovations of the 1980s brought many new unique sounds to this style of music. Popular music sounds during this time were the gated reverb, synthesizers, drum machines with 1980s sounds, vocal reverb, delay, and harmonization, and master bus mix downs and tape. Music programming began to emerge around this time which drew up controversy. Many artists were adapting more towards this technology and the traditional way music was made and recorded began to change. For instance, many artists began to record their beats by programming instead of recording a live drummer. === Music programming in the early 2000s === Today, music programming is very common, with artists using software on a computer to produce music and not actually using physical instruments. These different programs are called digital audio workstations (DAW) and are used for editing, recording, and mixing music files. Most DAW programs incorporate the use of MIDI technology, which allows for music production software to carry out communication between electronic instruments, computers, and other related devices. While most DAWs carry out the same function and do the same thing, there are some that require less expertise and are easier for beginners to operate. These programs can be run on personal computers. Popular DAWs include: FL Studio, Avid Pro Tools, Apple Logic Pro X, Magix Acid Pro, Ableton Live, Presonus Studio One, Magix Samplitude Pro X, Cockos Reaper, Propellerhead Reason, Steinberg Cubase Pro, GarageBand, and Bitwig Studio. == Equipment == Technology: digital audio workstation, drum machine, groovebox, sampler, sequencer, synthesizer and MIDI == References == == External links == Dobrian, Chris (1988). "Music Programming: An Introductory Essay". Claire Trevor School of the Arts, University of California, Irvine.
https://en.wikipedia.org/wiki/Programming_(music)
Fetal programming, also known as prenatal programming, is the theory that environmental cues experienced during fetal development play a seminal role in determining health trajectories across the lifespan. Three main forms of programming that occur due to changes in the maternal environment are: Changes in development that lead to greater disease risk; Genetic changes that alter disease risk; Epigenetic changes which alter disease risk of not only the child but also that of the next generation - i.e., after a famine, grandchildren of women who were pregnant during the famine, are born smaller than the normal size, despite nutritional deficiencies having been fulfilled. These changes in the maternal environmental can be due to nutritional alteration, hormonal fluctuations or exposure to toxins. == History == === Dutch famine 1944–45 === In 1944–45, the German blockade of the Netherlands led to a lack of food supplies, causing the Dutch famine of 1944–45. The famine caused severe malnutrition among the population, including women in various stages of pregnancy. The Dutch Famine Birth Cohort Study examined the impact of lack of nutrition on children born during or after this famine. It showed that throughout their life, these children were at greater risk of diabetes, cardiovascular disease, obesity, and other non-communicable diseases. === Barker hypothesis === In the 1980s, David Barker began a research study on this topic. The Barker Hypothesis, or Thrifty phenotype, forms the basis for much of the research conducted on fetal programming. This hypothesis states that if the fetus is exposed to low nutrition, it will adapt to that environment. Nutrients are diverted towards the developing heart, brain, and other essential fetal organs. The body also undergoes metabolic alterations that ensure survival despite low nutrition but may cause problems with normal or high nutrition. This leads to increased risk of metabolic syndrome. == Nutritional status == The developing fetus forms an impression of the world into which it will be born via its mother's nutritional status. Its development is thus modulated to create the best chance of survival. However, excessive or insufficient nutrition in the mother can provoke maladaptive developmental responses in the fetus, which in turn manifest in the form of post-natal diseases. This may have such a profound effect on the fetus’s adult life that it can even outweigh lifestyle factors. === Excessive nutrition === Body mass index before pregnancy and weight gain during pregnancy are linked to high blood pressure in the offspring during adulthood. Mouse models suggest that this is due to high levels of the fetal hormone leptin, which is present in the blood of individuals who are overweight or obese. There is a theory that this hormone hurts the regulatory systems of the fetus, and renders it impossible to maintain normal blood pressure levels. === Insufficient nutrition === Pre-eclampsia, involving oxygen deprivation and death of trophoblastic cells that make up most of the placenta, is a disease which is often associated with maladaptive long-term consequences of inappropriate fetal programming. Here, an inadequately developed and poorly functioning placenta fails to meet the fetus’s nutritional needs during gestation, either by altering its selection for nutrients that can cross into fetal blood or restricting total volume thereof. Consequences of this for the fetus in adult life include cardiovascular and metabolic conditions. == Hormonal influence == A delicate balance of hormones during pregnancy is regarded as highly relevant to fetal programming and may significantly influence the outcome of the offspring. Placental endocrine transfer from the mother to the developing fetus could be altered by the mental state of the mother, due to affected glucocorticoid transfer that takes place across the placenta. === Thyroid === Thyroid hormones play an instrumental role during the early development of the fetus's brain. Therefore, mothers suffering from thyroid-related issues and altered thyroid hormone levels may inadvertently trigger structural and functional changes in the fetal brain. The fetus can produce its thyroid hormones from the onset of the second trimester; however, maternal thyroid hormones are important for brain development before and after the baby can synthesize the hormones while still in the uterus. Due to this, the baby may experience an increased risk of neurological or psychiatric diseases later in life. === Cortisol === Cortisol (and glucocorticoids more generally) is the most well-studied hormonal mechanism that may have prenatal programming effects. Although cortisol has normative developmental effects during prenatal development, excess cortisol exposure has deleterious effects on fetal growth, the postnatal function of physiological systems such as the hypothalamic-pituitary-adrenal axis and brain structure or connectivity (e.g., amygdala). During gestation, cortisol concentrations in maternal circulation are up to ten times higher than cortisol concentrations in fetal circulation. The maternal-to-fetal cortisol gradient is maintained by the placenta, which forms a structural and enzymatic barrier to cortisol. During the first two trimesters of gestation intrauterine cortisol is primarily produced by the maternal adrenal glands. However, during the third trimester the fetal adrenal glands begin to endogenously produce cortisol and become responsible for most intrauterine cortisol by the time the fetus reaches term. == Psychological stress and psychopathology == Mental state of the mother during pregnancy affects the fetus in the uterus, predominantly via hormones and genetics. The mother's mood, including maternal prenatal anxiety, depression and stress during pregnancy correlates with altered outcomes for the child. That being said, not every fetus exposed to these factors is affected in the same way and to the same degree, and genetic and environmental factors are believed to have a significant degree of influence. === Depression === Maternal depression poses one of the greatest risks for increased vulnerability to adverse outcomes for a baby that is developing in the uterus, especially in terms of susceptibility to a variety of psychological conditions. Mechanisms that may explain the connection between maternal depression and the offspring's future health are mostly unclear and form a current area of active research. Genetic inheritance that may be rendering the child more susceptible may play a role, including the effect on the intrauterine environment for the baby whilst the mother suffers from depression. === Psychological stress === Maternally experienced psychological stress that occurs either before or during gestation can have intergenerational effects on offspring. Stress experienced during gestation has been linked with preterm delivery, low birth weight, and increased risk of psychopathology. The new mother may suffer from after-effects too, such as postpartum depression, and subsequently may find parenting more difficult as compared to those who did not experience as much stress during their pregnancies. == Toxins == Toxins such as alcohol, tobacco, and certain drugs to which the baby is exposed during its development are thought to contribute to fetal programming, especially via alterations to the HPA axis. If the exposure occurs during a critical phase of fetal development, it could have drastic and dire consequences for the fetus. === Alcohol === Prenatal and/or early postnatal exposure to alcohol (ethanol) has been found to hurt a child's neuroendocrine and behavioral factors. Alcohol passes through the placenta on being ingested by the mother during her pregnancy, and makes its way to the baby in utero. Changes posed to the fetus through ethanol exposure may significantly effect growth and development; these are collectively known as fetal alcohol spectrum disorders (FASD). The exact interaction between ethanol and the developing fetus is complex and largely uncertain, however, several direct and indirect effects have been observed as the fetus matures. Predominant among these are irregularities in the fetus's endocrine, metabolic, and physiological functions. === Smoking === The negative consequences of smoking are well-known, and these may be even more apparent during pregnancy. Exposure to tobacco smoke during pregnancy, commonly known as in utero maternal tobacco smoke exposure (MTSE), can contribute towards various problems in babies of smoking mothers. About 20% of mothers smoke whilst pregnant and this is associated with increased risk of complications, such as preterm birth, decreased fetal growth leading to lower birth weight, and impaired fetal lung development. === Drugs === There is evidence pointing towards pharmacological programming of the fetus during the first trimester. One type of drugs which is suspected of influencing the developing baby when used during pregnancy is anti-hypertensive drugs. Pre-eclampsia (a condition of hypertension during pregnancy) is a serious problem for the majority of pregnant mothers and can predispose the mother to a variety of complications, including increased risk of mortality and problems during parturition. == References == == External links == MRC Lifecourse Epidemiology Unit page at the University of Southampton Fetal Programming page on the Centre for Fetal Programming's website.
https://en.wikipedia.org/wiki/Fetal_programming
Logic programming is a programming, database and knowledge representation paradigm based on formal logic. A logic program is a set of sentences in logical form, representing knowledge about some problem domain. Computation is performed by applying logical reasoning to that knowledge, to solve problems in the domain. Major logic programming language families include Prolog, Answer Set Programming (ASP) and Datalog. In all of these languages, rules are written in the form of clauses: A :- B1, ..., Bn. and are read as declarative sentences in logical form: A if B1 and ... and Bn. A is called the head of the rule, B1, ..., Bn is called the body, and the Bi are called literals or conditions. When n = 0, the rule is called a fact and is written in the simplified form: A. Queries (or goals) have the same syntax as the bodies of rules and are commonly written in the form: ?- B1, ..., Bn. In the simplest case of Horn clauses (or "definite" clauses), all of the A, B1, ..., Bn are atomic formulae of the form p(t1 ,..., tm), where p is a predicate symbol naming a relation, like "motherhood", and the ti are terms naming objects (or individuals). Terms include both constant symbols, like "charles", and variables, such as X, which start with an upper case letter. Consider, for example, the following Horn clause program: Given a query, the program produces answers. For instance for a query ?- parent_child(X, william), the single answer is Various queries can be asked. For instance the program can be queried both to generate grandparents and to generate grandchildren. It can even be used to generate all pairs of grandchildren and grandparents, or simply to check if a given pair is such a pair: Although Horn clause logic programs are Turing complete, for most practical applications, Horn clause programs need to be extended to "normal" logic programs with negative conditions. For example, the definition of sibling uses a negative condition, where the predicate = is defined by the clause X = X : Logic programming languages that include negative conditions have the knowledge representation capabilities of a non-monotonic logic. In ASP and Datalog, logic programs have only a declarative reading, and their execution is performed by means of a proof procedure or model generator whose behaviour is not meant to be controlled by the programmer. However, in the Prolog family of languages, logic programs also have a procedural interpretation as goal-reduction procedures. From this point of view, clause A :- B1,...,Bn is understood as: to solve A, solve B1, and ... and solve Bn. Negative conditions in the bodies of clauses also have a procedural interpretation, known as negation as failure: A negative literal not B is deemed to hold if and only if the positive literal B fails to hold. Much of the research in the field of logic programming has been concerned with trying to develop a logical semantics for negation as failure and with developing other semantics and other implementations for negation. These developments have been important, in turn, for supporting the development of formal methods for logic-based program verification and program transformation. == History == The use of mathematical logic to represent and execute computer programs is also a feature of the lambda calculus, developed by Alonzo Church in the 1930s. However, the first proposal to use the clausal form of logic for representing computer programs was made by Cordell Green. This used an axiomatization of a subset of LISP, together with a representation of an input-output relation, to compute the relation by simulating the execution of the program in LISP. Foster and Elcock's Absys, on the other hand, employed a combination of equations and lambda calculus in an assertional programming language that places no constraints on the order in which operations are performed. Logic programming, with its current syntax of facts and rules, can be traced back to debates in the late 1960s and early 1970s about declarative versus procedural representations of knowledge in artificial intelligence. Advocates of declarative representations were notably working at Stanford, associated with John McCarthy, Bertram Raphael and Cordell Green, and in Edinburgh, with John Alan Robinson (an academic visitor from Syracuse University), Pat Hayes, and Robert Kowalski. Advocates of procedural representations were mainly centered at MIT, under the leadership of Marvin Minsky and Seymour Papert. Although it was based on the proof methods of logic, Planner, developed by Carl Hewitt at MIT, was the first language to emerge within this proceduralist paradigm. Planner featured pattern-directed invocation of procedural plans from goals (i.e. goal-reduction or backward chaining) and from assertions (i.e. forward chaining). The most influential implementation of Planner was the subset of Planner, called Micro-Planner, implemented by Gerry Sussman, Eugene Charniak and Terry Winograd. Winograd used Micro-Planner to implement the landmark, natural-language understanding program SHRDLU. For the sake of efficiency, Planner used a backtracking control structure so that only one possible computation path had to be stored at a time. Planner gave rise to the programming languages QA4, Popler, Conniver, QLISP, and the concurrent language Ether. Hayes and Kowalski in Edinburgh tried to reconcile the logic-based declarative approach to knowledge representation with Planner's procedural approach. Hayes (1973) developed an equational language, Golux, in which different procedures could be obtained by altering the behavior of the theorem prover. In the meanwhile, Alain Colmerauer in Marseille was working on natural-language understanding, using logic to represent semantics and using resolution for question-answering. During the summer of 1971, Colmerauer invited Kowalski to Marseille, and together they discovered that the clausal form of logic could be used to represent formal grammars and that resolution theorem provers could be used for parsing. They observed that some theorem provers, like hyper-resolution, behave as bottom-up parsers and others, like SL resolution (1971) behave as top-down parsers. It was in the following summer of 1972, that Kowalski, again working with Colmerauer, developed the procedural interpretation of implications in clausal form. It also became clear that such clauses could be restricted to definite clauses or Horn clauses, and that SL-resolution could be restricted (and generalised) to SLD resolution. Kowalski's procedural interpretation and SLD were described in a 1973 memo, published in 1974. Colmerauer, with Philippe Roussel, used the procedural interpretation as the basis of Prolog, which was implemented in the summer and autumn of 1972. The first Prolog program, also written in 1972 and implemented in Marseille, was a French question-answering system. The use of Prolog as a practical programming language was given great momentum by the development of a compiler by David H. D. Warren in Edinburgh in 1977. Experiments demonstrated that Edinburgh Prolog could compete with the processing speed of other symbolic programming languages such as Lisp. Edinburgh Prolog became the de facto standard and strongly influenced the definition of ISO standard Prolog. Logic programming gained international attention during the 1980s, when it was chosen by the Japanese Ministry of International Trade and Industry to develop the software for the Fifth Generation Computer Systems (FGCS) project. The FGCS project aimed to use logic programming to develop advanced Artificial Intelligence applications on massively parallel computers. Although the project initially explored the use of Prolog, it later adopted the use of concurrent logic programming, because it was closer to the FGCS computer architecture. However, the committed choice feature of concurrent logic programming interfered with the language's logical semantics and with its suitability for knowledge representation and problem solving applications. Moreover, the parallel computer systems developed in the project failed to compete with advances taking place in the development of more conventional, general-purpose computers. Together these two issues resulted in the FGCS project failing to meet its objectives. Interest in both logic programming and AI fell into world-wide decline. In the meanwhile, more declarative logic programming approaches, including those based on the use of Prolog, continued to make progress independently of the FGCS project. In particular, although Prolog was developed to combine declarative and procedural representations of knowledge, the purely declarative interpretation of logic programs became the focus for applications in the field of deductive databases. Work in this field became prominent around 1977, when Hervé Gallaire and Jack Minker organized a workshop on logic and databases in Toulouse. The field was eventually renamed as Datalog. This focus on the logical, declarative reading of logic programs was given further impetus by the development of constraint logic programming in the 1980s and Answer Set Programming in the 1990s. It is also receiving renewed emphasis in recent applications of Prolog The Association for Logic Programming (ALP) was founded in 1986 to promote Logic Programming. Its official journal until 2000, was The Journal of Logic Programming. Its founding editor-in-chief was J. Alan Robinson. In 2001, the journal was renamed The Journal of Logic and Algebraic Programming, and the official journal of ALP became Theory and Practice of Logic Programming, published by Cambridge University Press. == Concepts == Logic programs enjoy a rich variety of semantics and problem solving methods, as well as a wide range of applications in programming, databases, knowledge representation and problem solving. === Algorithm = Logic + Control === The procedural interpretation of logic programs, which uses backward reasoning to reduce goals to subgoals, is a special case of the use of a problem-solving strategy to control the use of a declarative, logical representation of knowledge to obtain the behaviour of an algorithm. More generally, different problem-solving strategies can be applied to the same logical representation to obtain different algorithms. Alternatively, different algorithms can be obtained with a given problem-solving strategy by using different logical representations. The two main problem-solving strategies are backward reasoning (goal reduction) and forward reasoning, also known as top-down and bottom-up reasoning, respectively. In the simple case of a propositional Horn clause program and a top-level atomic goal, backward reasoning determines an and-or tree, which constitutes the search space for solving the goal. The top-level goal is the root of the tree. Given any node in the tree and any clause whose head matches the node, there exists a set of child nodes corresponding to the sub-goals in the body of the clause. These child nodes are grouped together by an "and". The alternative sets of children corresponding to alternative ways of solving the node are grouped together by an "or". Any search strategy can be used to search this space. Prolog uses a sequential, last-in-first-out, backtracking strategy, in which only one alternative and one sub-goal are considered at a time. For example, subgoals can be solved in parallel, and clauses can also be tried in parallel. The first strategy is called and-parallel and the second strategy is called or-parallel. Other search strategies, such as intelligent backtracking, or best-first search to find an optimal solution, are also possible. In the more general, non-propositional case, where sub-goals can share variables, other strategies can be used, such as choosing the subgoal that is most highly instantiated or that is sufficiently instantiated so that only one procedure applies. Such strategies are used, for example, in concurrent logic programming. In most cases, backward reasoning from a query or goal is more efficient than forward reasoning. But sometimes with Datalog and Answer Set Programming, there may be no query that is separate from the set of clauses as a whole, and then generating all the facts that can be derived from the clauses is a sensible problem-solving strategy. Here is another example, where forward reasoning beats backward reasoning in a more conventional computation task, where the goal ?- fibonacci(n, Result) is to find the nth fibonacci number: Here the relation fibonacci(N, M) stands for the function fibonacci(N) = M, and the predicate N is Expression is Prolog notation for the predicate that instantiates the variable N to the value of Expression. Given the goal of computing the fibonacci number of n, backward reasoning reduces the goal to the two subgoals of computing the fibonacci numbers of n-1 and n-2. It reduces the subgoal of computing the fibonacci number of n-1 to the two subgoals of computing the fibonacci numbers of n-2 and n-3, redundantly computing the fibonacci number of n-2. This process of reducing one fibonacci subgoal to two fibonacci subgoals continues until it reaches the numbers 0 and 1. Its complexity is of the order 2n. In contrast, forward reasoning generates the sequence of fibonacci numbers, starting from 0 and 1 without any recomputation, and its complexity is linear with respect to n. Prolog cannot perform forward reasoning directly. But it can achieve the effect of forward reasoning within the context of backward reasoning by means of tabling: Subgoals are maintained in a table, along with their solutions. If a subgoal is re-encountered, it is solved directly by using the solutions already in the table, instead of re-solving the subgoals redundantly. === Relationship with functional programming === Logic programming can be viewed as a generalisation of functional programming, in which functions are a special case of relations. For example, the function, mother(X) = Y, (every X has only one mother Y) can be represented by the relation mother(X, Y). In this respect, logic programs are similar to relational databases, which also represent functions as relations. Compared with relational syntax, functional syntax is more compact for nested functions. For example, in functional syntax the definition of maternal grandmother can be written in the nested form: The same definition in relational notation needs to be written in the unnested, flattened form: However, nested syntax can be regarded as syntactic sugar for unnested syntax. Ciao Prolog, for example, transforms functional syntax into relational form and executes the resulting logic program using the standard Prolog execution strategy. Moreover, the same transformation can be used to execute nested relations that are not functional. For example: === Relationship with relational programming === The term relational programming has been used to cover a variety of programming languages that treat functions as a special case of relations. Some of these languages, such as miniKanren and relational linear programming are logic programming languages in the sense of this article. However, the relational language RML is an imperative programming language whose core construct is a relational expression, which is similar to an expression in first-order predicate logic. Other relational programming languages are based on the relational calculus or relational algebra. === Semantics of Horn clause programs === Viewed in purely logical terms, there are two approaches to the declarative semantics of Horn clause logic programs: One approach is the original logical consequence semantics, which understands solving a goal as showing that the goal is a theorem that is true in all models of the program. In this approach, computation is theorem-proving in first-order logic; and both backward reasoning, as in SLD resolution, and forward reasoning, as in hyper-resolution, are correct and complete theorem-proving methods. Sometimes such theorem-proving methods are also regarded as providing a separate proof-theoretic (or operational) semantics for logic programs. But from a logical point of view, they are proof methods, rather than semantics. The other approach to the declarative semantics of Horn clause programs is the satisfiability semantics, which understands solving a goal as showing that the goal is true (or satisfied) in some intended (or standard) model of the program. For Horn clause programs, there always exists such a standard model: It is the unique minimal model of the program. Informally speaking, a minimal model is a model that, when it is viewed as the set of all (variable-free) facts that are true in the model, contains no smaller set of facts that is also a model of the program. For example, the following facts represent the minimal model of the family relationships example in the introduction of this article. All other variable-free facts are false in the model: The satisfiability semantics also has an alternative, more mathematical characterisation as the least fixed point of the function that uses the rules in the program to derive new facts from existing facts in one step of inference. Remarkably, the same problem-solving methods of forward and backward reasoning, which were originally developed for the logical consequence semantics, are equally applicable to the satisfiability semantics: Forward reasoning generates the minimal model of a Horn clause program, by deriving new facts from existing facts, until no new additional facts can be generated. Backward reasoning, which succeeds by reducing a goal to subgoals, until all subgoals are solved by facts, ensures that the goal is true in the minimal model, without generating the model explicitly. The difference between the two declarative semantics can be seen with the definitions of addition and multiplication in successor arithmetic, which represents the natural numbers 0, 1, 2, ... as a sequence of terms of the form 0, s(0), s(s(0)), .... In general, the term s(X) represents the successor of X, namely X + 1. Here are the standard definitions of addition and multiplication in functional notation: X + 0 = X. X + s(Y) = s(X + Y). i.e. X + (Y + 1) = (X + Y) + 1 X × 0 = 0. X × s(Y) = X + (X × Y). i.e. X × (Y + 1) = X + (X × Y). Here are the same definitions as a logic program, using add(X, Y, Z) to represent X + Y = Z, and multiply(X, Y, Z) to represent X × Y = Z: The two declarative semantics both give the same answers for the same existentially quantified conjunctions of addition and multiplication goals. For example 2 × 2 = X has the solution X = 4; and X × X = X + X has two solutions X = 0 and X = 2: However, with the logical-consequence semantics, there are non-standard models of the program, in which, for example, add(s(s(0)), s(s(0)), s(s(s(s(s(0)))))), i.e. 2 + 2 = 5 is true. But with the satisfiability semantics, there is only one model, namely the standard model of arithmetic, in which 2 + 2 = 5 is false. In both semantics, the goal ?- add(s(s(0)), s(s(0)), s(s(s(s(s(0)))))) fails. In the satisfiability semantics, the failure of the goal means that the truth value of the goal is false. But in the logical consequence semantics, the failure means that the truth value of the goal is unknown. === Negation as failure === Negation as failure (NAF), as a way of concluding that a negative condition not p holds by showing that the positive condition p fails to hold, was already a feature of early Prolog systems. The resulting extension of SLD resolution is called SLDNF. A similar construct, called "thnot", also existed in Micro-Planner. The logical semantics of NAF was unresolved until Keith Clark showed that, under certain natural conditions, NAF is an efficient, correct (and sometimes complete) way of reasoning with the logical consequence semantics using the completion of a logic program in first-order logic. Completion amounts roughly to regarding the set of all the program clauses with the same predicate in the head, say: A :- Body1. ... A :- Bodyk. as a definition of the predicate: A iff (Body1 or ... or Bodyk) where iff means "if and only if". The completion also includes axioms of equality, which correspond to unification. Clark showed that proofs generated by SLDNF are structurally similar to proofs generated by a natural deduction style of reasoning with the completion of the program. Consider, for example, the following program: Given the goal of determining whether tom should receive a sanction, the first rule succeeds in showing that tom should be punished: This is because tom is a thief, and it cannot be shown that tom should be rehabilitated. It cannot be shown that tom should be rehabilitated, because it cannot be shown that tom is a minor. If, however, we receive new information that tom is indeed a minor, the previous conclusion that tom should be punished is replaced by the new conclusion that tom should be rehabilitated: This property of withdrawing a conclusion when new information is added, is called non-monotonicity, and it makes logic programming a non-monotonic logic. But, if we are now told that tom is violent, the conclusion that tom should be punished will be reinstated: The completion of this program is: The notion of completion is closely related to John McCarthy's circumscription semantics for default reasoning, and to Ray Reiter's closed world assumption. The completion semantics for negation is a logical consequence semantics, for which SLDNF provides a proof-theoretic implementation. However, in the 1980s, the satisfiability semantics became more popular for logic programs with negation. In the satisfiability semantics, negation is interpreted according to the classical definition of truth in an intended or standard model of the logic program. In the case of logic programs with negative conditions, there are two main variants of the satisfiability semantics: In the well-founded semantics, the intended model of a logic program is a unique, three-valued, minimal model, which always exists. The well-founded semantics generalises the notion of inductive definition in mathematical logic. XSB Prolog implements the well-founded semantics using SLG resolution. In the alternative stable model semantics, there may be no intended models or several intended models, all of which are minimal and two-valued. The stable model semantics underpins answer set programming (ASP). Both the well-founded and stable model semantics apply to arbitrary logic programs with negation. However, both semantics coincide for stratified logic programs. For example, the program for sanctioning thieves is (locally) stratified, and all three semantics for the program determine the same intended model: Attempts to understand negation in logic programming have also contributed to the development of abstract argumentation frameworks. In an argumentation interpretation of negation, the initial argument that tom should be punished because he is a thief, is attacked by the argument that he should be rehabilitated because he is a minor. But the fact that tom is violent undermines the argument that tom should be rehabilitated and reinstates the argument that tom should be punished. === Metalogic programming === Metaprogramming, in which programs are treated as data, was already a feature of early Prolog implementations. For example, the Edinburgh DEC10 implementation of Prolog included "an interpreter and a compiler, both written in Prolog itself". The simplest metaprogram is the so-called "vanilla" meta-interpreter: where true represents an empty conjunction, and (B,C) is a composite term representing the conjunction of B and C. The predicate clause(A,B) means that there is a clause of the form A :- B. Metaprogramming is an application of the more general use of a metalogic or metalanguage to describe and reason about another language, called the object language. Metalogic programming allows object-level and metalevel representations to be combined, as in natural language. For example, in the following program, the atomic formula attends(Person, Meeting) occurs both as an object-level formula, and as an argument of the metapredicates prohibited and approved. === Relationship with the Computational-representational understanding of mind === In his popular Introduction to Cognitive Science, Paul Thagard includes logic and rules as alternative approaches to modelling human thinking. He argues that rules, which have the form IF condition THEN action, are "very similar" to logical conditionals, but they are simpler and have greater psychological plausibility (page 51). Among other differences between logic and rules, he argues that logic uses deduction, but rules use search (page 45) and can be used to reason either forward or backward (page 47). Sentences in logic "have to be interpreted as universally true", but rules can be defaults, which admit exceptions (page 44). He states that "unlike logic, rule-based systems can also easily represent strategic information about what to do" (page 45). For example, "IF you want to go home for the weekend, and you have bus fare, THEN you can catch a bus". He does not observe that the same strategy of reducing a goal to subgoals can be interpreted, in the manner of logic programming, as applying backward reasoning to a logical conditional: All of these characteristics of rule-based systems - search, forward and backward reasoning, default reasoning, and goal-reduction - are also defining characteristics of logic programming. This suggests that Thagard's conclusion (page 56) that: Much of human knowledge is naturally described in terms of rules, and many kinds of thinking such as planning can be modeled by rule-based systems. also applies to logic programming. Other arguments showing how logic programming can be used to model aspects of human thinking are presented by Keith Stenning and Michiel van Lambalgen in their book, Human Reasoning and Cognitive Science. They show how the non-monotonic character of logic programs can be used to explain human performance on a variety of psychological tasks. They also show (page 237) that "closed–world reasoning in its guise as logic programming has an appealing neural implementation, unlike classical logic." In The Proper Treatment of Events, Michiel van Lambalgen and Fritz Hamm investigate the use of constraint logic programming to code "temporal notions in natural language by looking at the way human beings construct time". === Knowledge representation === The use of logic to represent procedural knowledge and strategic information was one of the main goals contributing to the early development of logic programming. Moreover, it continues to be an important feature of the Prolog family of logic programming languages today. However, many applications of logic programming, including Prolog applications, increasingly focus on the use of logic to represent purely declarative knowledge. These applications include both the representation of general commonsense knowledge and the representation of domain specific expertise. Commonsense includes knowledge about cause and effect, as formalised, for example, in the situation calculus, event calculus and action languages. Here is a simplified example, which illustrates the main features of such formalisms. The first clause states that a fact holds immediately after an event initiates (or causes) the fact. The second clause is a frame axiom, which states that a fact that holds at a time continues to hold at the next time unless it is terminated by an event that happens at the time. This formulation allows more than one event to occur at the same time: Here holds is a meta-predicate, similar to solve above. However, whereas solve has only one argument, which applies to general clauses, the first argument of holds is a fact and the second argument is a time (or state). The atomic formula holds(Fact, Time) expresses that the Fact holds at the Time. Such time-varying facts are also called fluents. The atomic formula happens(Event, Time) expresses that the Event happens at the Time. The following example illustrates how these clauses can be used to reason about causality in a toy blocks world. Here, in the initial state at time 0, a green block is on a table and a red block is stacked on the green block (like a traffic light). At time 0, the red block is moved to the table. At time 1, the green block is moved onto the red block. Moving an object onto a place terminates the fact that the object is on any place, and initiates the fact that the object is on the place to which it is moved: Forward reasoning and backward reasoning generate the same answers to the goal holds(Fact, Time). But forward reasoning generates fluents progressively in temporal order, and backward reasoning generates fluents regressively, as in the domain-specific use of regression in the situation calculus. Logic programming has also proved to be useful for representing domain-specific expertise in expert systems. But human expertise, like general-purpose commonsense, is mostly implicit and tacit, and it is often difficult to represent such implicit knowledge in explicit rules. This difficulty does not arise, however, when logic programs are used to represent the existing, explicit rules of a business organisation or legal authority. For example, here is a representation of a simplified version of the first sentence of the British Nationality Act, which states that a person who is born in the UK becomes a British citizen at the time of birth if a parent of the person is a British citizen at the time of birth: Historically, the representation of a large portion of the British Nationality Act as a logic program in the 1980s was "hugely influential for the development of computational representations of legislation, showing how logic programming enables intuitively appealing representations that can be directly deployed to generate automatic inferences". More recently, the PROLEG system, initiated in 2009 and consisting of approximately 2500 rules and exceptions of civil code and supreme court case rules in Japan, has become possibly the largest legal rule base in the world. == Variants and extensions == === Prolog === The SLD resolution rule of inference is neutral about the order in which subgoals in the bodies of clauses can be selected for solution. For the sake of efficiency, Prolog restricts this order to the order in which the subgoals are written. SLD is also neutral about the strategy for searching the space of SLD proofs. Prolog searches this space, top-down, depth-first, trying different clauses for solving the same (sub)goal in the order in which the clauses are written. This search strategy has the advantage that the current branch of the tree can be represented efficiently by a stack. When a goal clause at the top of the stack is reduced to a new goal clause, the new goal clause is pushed onto the top of the stack. When the selected subgoal in the goal clause at the top of the stack cannot be solved, the search strategy backtracks, removing the goal clause from the top of the stack, and retrying the attempted solution of the selected subgoal in the previous goal clause using the next clause that matches the selected subgoal. Backtracking can be restricted by using a subgoal, called cut, written as !, which always succeeds but cannot be backtracked. Cut can be used to improve efficiency, but can also interfere with the logical meaning of clauses. In many cases, the use of cut can be replaced by negation as failure. In fact, negation as failure can be defined in Prolog, by using cut, together with any literal, say fail, that unifies with the head of no clause: Prolog provides other features, in addition to cut, that do not have a logical interpretation. These include the built-in predicates assert and retract for destructively updating the state of the program during program execution. For example, the toy blocks world example above can be implemented without frame axioms using destructive change of state: The sequence of move events and the resulting locations of the blocks can be computed by executing the query: Various extensions of logic programming have been developed to provide a logical framework for such destructive change of state. The broad range of Prolog applications, both in isolation and in combination with other languages is highlighted in the Year of Prolog Book, celebrating the 50 year anniversary of Prolog in 2022. Prolog has also contributed to the development of other programming languages, including ALF, Fril, Gödel, Mercury, Oz, Ciao, Visual Prolog, XSB, and λProlog. === Constraint logic programming === Constraint logic programming (CLP) combines Horn clause logic programming with constraint solving. It extends Horn clauses by allowing some predicates, declared as constraint predicates, to occur as literals in the body of a clause. Constraint predicates are not defined by the facts and rules in the program, but are predefined by some domain-specific model-theoretic structure or theory. Procedurally, subgoals whose predicates are defined by the program are solved by goal-reduction, as in ordinary logic programming, but constraints are simplified and checked for satisfiability by a domain-specific constraint-solver, which implements the semantics of the constraint predicates. An initial problem is solved by reducing it to a satisfiable conjunction of constraints. Interestingly, the first version of Prolog already included a constraint predicate dif(term1, term2), from Philippe Roussel's 1972 PhD thesis, which succeeds if both of its arguments are different terms, but which is delayed if either of the terms contains a variable. The following constraint logic program represents a toy temporal database of john's history as a teacher: Here ≤ and < are constraint predicates, with their usual intended semantics. The following goal clause queries the database to find out when john both taught logic and was a professor: The solution 2010 ≤ T, T ≤ 2012 results from simplifying the constraints 2005 ≤ T, T ≤ 2012, 2010 ≤ T, T < 2014. Constraint logic programming has been used to solve problems in such fields as civil engineering, mechanical engineering, digital circuit verification, automated timetabling, air traffic control, and finance. It is closely related to abductive logic programming. === Datalog === Datalog is a database definition language, which combines a relational view of data, as in relational databases, with a logical view, as in logic programming. Relational databases use a relational calculus or relational algebra, with relational operations, such as union, intersection, set difference and cartesian product to specify queries, which access a database. Datalog uses logical connectives, such as or, and and not in the bodies of rules to define relations as part of the database itself. It was recognized early in the development of relational databases that recursive queries cannot be expressed in either relational algebra or relational calculus, and that this defficiency can be remedied by introducing a least-fixed-point operator. In contrast, recursive relations can be defined naturally by rules in logic programs, without the need for any new logical connectives or operators. Datalog differs from more general logic programming by having only constants and variables as terms. Moreover, all facts are variable-free, and rules are restricted, so that if they are executed bottom-up, then the derived facts are also variable-free. For example, consider the family database: Bottom-up execution derives the following set of additional facts and terminates: Top-down execution derives the same answers to the query: But then it goes into an infinite loop. However, top-down execution with tabling gives the same answers and terminates without looping. === Answer set programming === Like Datalog, Answer Set programming (ASP) is not Turing-complete. Moreover, instead of separating goals (or queries) from the program to be used in solving the goals, ASP treats the whole program as a goal, and solves the goal by generating a stable model that makes the goal true. For this purpose, it uses the stable model semantics, according to which a logic program can have zero, one or more intended models. For example, the following program represents a degenerate variant of the map colouring problem of colouring two countries red or green: The problem has four solutions represented by four stable models: To represent the standard version of the map colouring problem, we need to add a constraint that two adjacent countries cannot be coloured the same colour. In ASP, this constraint can be written as a clause of the form: With the addition of this constraint, the problem now has only two solutions: The addition of constraints of the form :- Body. eliminates models in which Body is true. Confusingly, constraints in ASP are different from constraints in CLP. Constraints in CLP are predicates that qualify answers to queries (and solutions of goals). Constraints in ASP are clauses that eliminate models that would otherwise satisfy goals. Constraints in ASP are like integrity constraints in databases. This combination of ordinary logic programming clauses and constraint clauses illustrates the generate-and-test methodology of problem solving in ASP: The ordinary clauses define a search space of possible solutions, and the constraints filter out unwanted solutions. Most implementations of ASP proceed in two steps: First they instantiate the program in all possible ways, reducing it to a propositional logic program (known as grounding). Then they apply a propositional logic problem solver, such as the DPLL algorithm or a Boolean SAT solver. However, some implementations, such as s(CASP) use a goal-directed, top-down, SLD resolution-like procedure without grounding. === Abductive logic programming === Abductive logic programming (ALP), like CLP, extends normal logic programming by allowing the bodies of clauses to contain literals whose predicates are not defined by clauses. In ALP, these predicates are declared as abducible (or assumable), and are used as in abductive reasoning to explain observations, or more generally to add new facts to the program (as assumptions) to solve goals. For example, suppose we are given an initial state in which a red block is on a green block on a table at time 0: Suppose we are also given the goal: The goal can represent an observation, in which case a solution is an explanation of the observation. Or the goal can represent a desired future state of affairs, in which case a solution is a plan for achieving the goal. We can use the rules for cause and effect presented earlier to solve the goal, by treating the happens predicate as abducible: ALP solves the goal by reasoning backwards and adding assumptions to the program, to solve abducible subgoals. In this case there are many alternative solutions, including: Here tick is an event that marks the passage of time without initiating or terminating any fluents. There are also solutions in which the two move events happen at the same time. For example: Such solutions, if not desired, can be removed by adding an integrity constraint, which is like a constraint clause in ASP: Abductive logic programming has been used for fault diagnosis, planning, natural language processing and machine learning. It has also been used to interpret negation as failure as a form of abductive reasoning. === Inductive logic programming === Inductive logic programming (ILP) is an approach to machine learning that induces logic programs as hypothetical generalisations of positive and negative examples. Given a logic program representing background knowledge and positive examples together with constraints representing negative examples, an ILP system induces a logic program that generalises the positive examples while excluding the negative examples. ILP is similar to ALP, in that both can be viewed as generating hypotheses to explain observations, and as employing constraints to exclude undesirable hypotheses. But in ALP the hypotheses are variable-free facts, and in ILP the hypotheses are general rules. For example, given only background knowledge of the mother_child and father_child relations, and suitable examples of the grandparent_child relation, current ILP systems can generate the definition of grandparent_child, inventing an auxiliary predicate, which can be interpreted as the parent_child relation: Stuart Russell has referred to such invention of new concepts as the most important step needed for reaching human-level AI. Recent work in ILP, combining logic programming, learning and probability, has given rise to the fields of statistical relational learning and probabilistic inductive logic programming. === Concurrent logic programming === Concurrent logic programming integrates concepts of logic programming with concurrent programming. Its development was given a big impetus in the 1980s by its choice for the systems programming language of the Japanese Fifth Generation Project (FGCS). A concurrent logic program is a set of guarded Horn clauses of the form: H :- G1, ..., Gn | B1, ..., Bn. The conjunction G1, ... , Gn is called the guard of the clause, and | is the commitment operator. Declaratively, guarded Horn clauses are read as ordinary logical implications: H if G1 and ... and Gn and B1 and ... and Bn. However, procedurally, when there are several clauses whose heads H match a given goal, then all of the clauses are executed in parallel, checking whether their guards G1, ... , Gn hold. If the guards of more than one clause hold, then a committed choice is made to one of the clauses, and execution proceeds with the subgoals B1, ..., Bn of the chosen clause. These subgoals can also be executed in parallel. Thus concurrent logic programming implements a form of "don't care nondeterminism", rather than "don't know nondeterminism". For example, the following concurrent logic program defines a predicate shuffle(Left, Right, Merge), which can be used to shuffle two lists Left and Right, combining them into a single list Merge that preserves the ordering of the two lists Left and Right: Here, [] represents the empty list, and [Head | Tail] represents a list with first element Head followed by list Tail, as in Prolog. (Notice that the first occurrence of | in the second and third clauses is the list constructor, whereas the second occurrence of | is the commitment operator.) The program can be used, for example, to shuffle the lists [ace, queen, king] and [1, 4, 2] by invoking the goal clause: The program will non-deterministically generate a single solution, for example Merge = [ace, queen, 1, king, 4, 2]. Carl Hewitt has argued that, because of the indeterminacy of concurrent computation, concurrent logic programming cannot implement general concurrency. However, according to the logical semantics, any result of a computation of a concurrent logic program is a logical consequence of the program, even though not all logical consequences can be derived. === Concurrent constraint logic programming === Concurrent constraint logic programming combines concurrent logic programming and constraint logic programming, using constraints to control concurrency. A clause can contain a guard, which is a set of constraints that may block the applicability of the clause. When the guards of several clauses are satisfied, concurrent constraint logic programming makes a committed choice to use only one. === Higher-order logic programming === Several researchers have extended logic programming with higher-order programming features derived from higher-order logic, such as predicate variables. Such languages include the Prolog extensions HiLog and λProlog. === Linear logic programming === Basing logic programming within linear logic has resulted in the design of logic programming languages that are considerably more expressive than those based on classical logic. Horn clause programs can only represent state change by the change in arguments to predicates. In linear logic programming, one can use the ambient linear logic to support state change. Some early designs of logic programming languages based on linear logic include LO, Lolli, ACL, and Forum. Forum provides a goal-directed interpretation of all linear logic. === Object-oriented logic programming === F-logic extends logic programming with objects and the frame syntax. Logtalk extends the Prolog programming language with support for objects, protocols, and other OOP concepts. It supports most standard-compliant Prolog systems as backend compilers. === Transaction logic programming === Transaction logic is an extension of logic programming with a logical theory of state-modifying updates. It has both a model-theoretic semantics and a procedural one. An implementation of a subset of Transaction logic is available in the Flora-2 system. Other prototypes are also available. == See also == Automated theorem proving Boolean satisfiability problem Constraint logic programming Control theory Datalog Fril Functional programming Fuzzy logic Inductive logic programming Linear logic Logic in computer science (includes Formal methods) Logic programming languages Programmable logic controller R++ Reasoning system Rule-based machine learning Satisfiability Syntax and semantics of logic programming == Citations == == Sources == === General introductions === Baral, C.; Gelfond, M. (1994). "Logic programming and knowledge representation" (PDF). The Journal of Logic Programming. 19–20: 73–148. doi:10.1016/0743-1066(94)90025-6. Kowalski, R. A. (1988). "The early years of logic programming" (PDF). Communications of the ACM. 31: 38–43. doi:10.1145/35043.35046. S2CID 12259230. [1] Lloyd, J. W. (1987). Foundations of Logic Programming (2nd ed.). Springer-Verlag. === Other sources === John McCarthy. "Programs with common sense". Symposium on Mechanization of Thought Processes. National Physical Laboratory. Teddington, England. 1958. Miller, Dale; Nadathur, Gopalan; Pfenning, Frank; Scedrov, Andre (1991). "Uniform proofs as a foundation for logic programming". Annals of Pure and Applied Logic. 51 (1–2): 125–157. doi:10.1016/0168-0072(91)90068-W. Ehud Shapiro (Editor). Concurrent Prolog. MIT Press. 1987. James Slagle. "Experiments with a Deductive Question-Answering Program". CACM. December 1965. Gabbay, Dov M.; Hogger, Christopher John; Robinson, J.A., eds. (1993-1998). Handbook of Logic in Artificial Intelligence and Logic Programming.Vols. 1–5, Oxford University Press. == Further reading == Carl Hewitt. "Procedural Embedding of Knowledge in Planner". IJCAI 1971. Carl Hewitt. "The Repeated Demise of Logic Programming and Why It Will Be Reincarnated". AAAI Spring Symposium: What Went Wrong and Why: Lessons from AI Research and Applications 2006: 2–9. Evgeny Dantsin, Thomas Eiter, Georg Gottlob, Andrei Voronkov: Complexity and expressive power of logic programming. ACM Comput. Surv. 33(3): 374–425 (2001) Ulf Nilsson and Jan Maluszynski, Logic, Programming and Prolog == External links == Logic Programming Virtual Library entry Bibliographies on Logic Programming Archived 2008-12-04 at the Wayback Machine Association for Logic Programming (ALP) Theory and Practice of Logic Programming (journal) Logic programming in C++ with Castor Logic programming Archived 2011-09-03 at the Wayback Machine in Oz Prolog Development Center Racklog: Logic Programming in Racket
https://en.wikipedia.org/wiki/Logic_programming
In computer science, a semaphore is a variable or abstract data type used to control access to a common resource by multiple threads and avoid critical section problems in a concurrent system such as a multitasking operating system. Semaphores are a type of synchronization primitive. A trivial semaphore is a plain variable that is changed (for example, incremented or decremented, or toggled) depending on programmer-defined conditions. A useful way to think of a semaphore as used in a real-world system is as a record of how many units of a particular resource are available, coupled with operations to adjust that record safely (i.e., to avoid race conditions) as units are acquired or become free, and, if necessary, wait until a unit of the resource becomes available. Though semaphores are useful for preventing race conditions, they do not guarantee their absence. Semaphores that allow an arbitrary resource count are called counting semaphores, while semaphores that are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary semaphores and are used to implement locks. The semaphore concept was invented by Dutch computer scientist Edsger Dijkstra in 1962 or 1963, when Dijkstra and his team were developing an operating system for the Electrologica X8. That system eventually became known as the THE multiprogramming system. == Library analogy == Suppose a physical library has ten identical study rooms, to be used by one student at a time. Students must request a room from the front desk. If no rooms are free, students wait at the desk until someone relinquishes a room. When a student has finished using a room, the student must return to the desk and indicate that the room is free. In the simplest implementation, the clerk at the front desk knows only the number of free rooms available. This requires that all of the students use their room while they have signed up for it and return it when they are done. When a student requests a room, the clerk decreases this number. When a student releases a room, the clerk increases this number. The room can be used for as long as desired, and so it is not possible to book rooms ahead of time. In this scenario, the front desk count-holder represents a counting semaphore, the rooms are the resource, and the students represent processes/threads. The value of the semaphore in this scenario is initially 10, with all rooms empty. When a student requests a room, they are granted access, and the value of the semaphore is changed to 9. After the next student comes, it drops to 8, then 7, and so on. If someone requests a room and the current value of the semaphore is 0, they are forced to wait until a room is freed (when the count is increased from 0). If one of the rooms was released, but there are several students waiting, then any method can be used to select the one who will occupy the room (like FIFO or randomly picking one). And of course, a student must inform the clerk about releasing their room only after really leaving it. === Important observations === When used to control access to a pool of resources, a semaphore tracks only how many resources are free. It does not keep track of which of the resources are free. Some other mechanism (possibly involving more semaphores) may be required to select a particular free resource. The paradigm is especially powerful because the semaphore count may serve as a useful trigger for a number of different actions. The librarian above may turn the lights off in the study hall when there are no students remaining, or may place a sign that says the rooms are very busy when most of the rooms are occupied. The success of the protocol requires applications to follow it correctly. Fairness and safety are likely to be compromised (which practically means a program may behave slowly, act erratically, hang, or crash) if even a single process acts incorrectly. This includes: requesting a resource and forgetting to release it; releasing a resource that was never requested; holding a resource for a long time without needing it; using a resource without requesting it first (or after releasing it). Even if all processes follow these rules, multi-resource deadlock may still occur when there are different resources managed by different semaphores and when processes need to use more than one resource at a time, as illustrated by the dining philosophers problem. == Semantics and implementation == Counting semaphores are equipped with two operations, historically denoted as P and V (see § Operation names for alternative names). Operation V increments the semaphore S, and operation P decrements it. The value of the semaphore S is the number of units of the resource that are currently available. The P operation wastes time or sleeps until a resource protected by the semaphore becomes available, at which time the resource is immediately claimed. The V operation is the inverse: it makes a resource available again after the process has finished using it. One important property of semaphore S is that its value cannot be changed except by using the V and P operations. A simple way to understand wait (P) and signal (V) operations is: wait: Decrements the value of the semaphore variable by 1. If the new value of the semaphore variable is negative, the process executing wait is blocked (i.e., added to the semaphore's queue). Otherwise, the process continues execution, having used a unit of the resource. signal: Increments the value of the semaphore variable by 1. After the increment, if the pre-increment value was negative (meaning there are processes waiting for a resource), it transfers a blocked process from the semaphore's waiting queue to the ready queue. Many operating systems provide efficient semaphore primitives that unblock a waiting process when the semaphore is incremented. This means that processes do not waste time checking the semaphore value unnecessarily. The counting semaphore concept can be extended with the ability to claim or return more than one "unit" from the semaphore, a technique implemented in Unix. The modified V and P operations are as follows, using square brackets to indicate atomic operations, i.e., operations that appear indivisible to other processes: function V(semaphore S, integer I): [S ← S + I] function P(semaphore S, integer I): repeat: [if S ≥ I: S ← S − I break] However, the rest of this section refers to semaphores with unary V and P operations, unless otherwise specified. To avoid starvation, a semaphore has an associated queue of processes (usually with FIFO semantics). If a process performs a P operation on a semaphore that has the value zero, the process is added to the semaphore's queue and its execution is suspended. When another process increments the semaphore by performing a V operation, and there are processes on the queue, one of them is removed from the queue and resumes execution. When processes have different priorities the queue may be ordered thereby, such that the highest priority process is taken from the queue first. If the implementation does not ensure atomicity of the increment, decrement, and comparison operations, there is a risk of increments or decrements being forgotten, or of the semaphore value becoming negative. Atomicity may be achieved by using a machine instruction that can read, modify, and write the semaphore in a single operation. Without such a hardware instruction, an atomic operation may be synthesized by using a software mutual exclusion algorithm. On uniprocessor systems, atomic operations can be ensured by temporarily suspending preemption or disabling hardware interrupts. This approach does not work on multiprocessor systems where it is possible for two programs sharing a semaphore to run on different processors at the same time. To solve this problem in a multiprocessor system, a locking variable can be used to control access to the semaphore. The locking variable is manipulated using a test-and-set-lock command. == Examples == === Trivial example === Consider a variable A and a boolean variable S. A is only accessed when S is marked true. Thus, S is a semaphore for A. One can imagine a stoplight signal (S) just before a train station (A). In this case, if the signal is green, then one can enter the train station. If it is yellow or red (or any other color), the train station cannot be accessed. === Login queue === Consider a system that can only support ten users (S=10). Whenever a user logs in, P is called, decrementing the semaphore S by 1. Whenever a user logs out, V is called, incrementing S by 1 representing a login slot that has become available. When S is 0, any users wishing to log in must wait until S increases. The login request is enqueued onto a FIFO queue until a slot is freed. Mutual exclusion is used to ensure that requests are enqueued in order. Whenever S increases (login slots available), a login request is dequeued, and the user owning the request is allowed to log in. If S is already greater than 0, then login requests are immediately dequeued. === Producer–consumer problem === In the producer–consumer problem, one process (the producer) generates data items and another process (the consumer) receives and uses them. They communicate using a queue of maximum size N and are subject to the following conditions: the consumer must wait for the producer to produce something if the queue is empty; the producer must wait for the consumer to consume something if the queue is full. The semaphore solution to the producer–consumer problem tracks the state of the queue with two semaphores: emptyCount, the number of empty places in the queue, and fullCount, the number of elements in the queue. To maintain integrity, emptyCount may be lower (but never higher) than the actual number of empty places in the queue, and fullCount may be lower (but never higher) than the actual number of items in the queue. Empty places and items represent two kinds of resources, empty boxes and full boxes, and the semaphores emptyCount and fullCount maintain control over these resources. The binary semaphore useQueue ensures that the integrity of the state of the queue itself is not compromised, for example, by two producers attempting to add items to an empty queue simultaneously, thereby corrupting its internal state. Alternatively a mutex could be used in place of the binary semaphore. The emptyCount is initially N, fullCount is initially 0, and useQueue is initially 1. The producer does the following repeatedly: produce: P(emptyCount) P(useQueue) putItemIntoQueue(item) V(useQueue) V(fullCount) The consumer does the following repeatedly consume: P(fullCount) P(useQueue) item ← getItemFromQueue() V(useQueue) V(emptyCount) Below is a substantive example: A single consumer enters its critical section. Since fullCount is 0, the consumer blocks. Several producers enter the producer critical section. No more than N producers may enter their critical section due to emptyCount constraining their entry. The producers, one at a time, gain access to the queue through useQueue and deposit items in the queue. Once the first producer exits its critical section, fullCount is incremented, allowing one consumer to enter its critical section. Note that emptyCount may be much lower than the actual number of empty places in the queue, for example, where many producers have decremented it but are waiting their turn on useQueue before filling empty places. Note that emptyCount + fullCount ≤ N always holds, with equality if and only if no producers or consumers are executing their critical sections. === Passing the baton pattern === The "Passing the baton" pattern proposed by Gregory R. Andrews is a generic scheme to solve many complex concurrent programming problems in which multiple processes compete for the same resource with complex access conditions (such as satisfying specific priority criteria or avoiding starvation). Given a shared resource, the pattern requires a private "priv" semaphore (initialized to zero) for each process (or class of processes) involved and a single mutual exclusion "mutex" semaphore (initialized to one). The pseudo-code for each process is: The pseudo-code of the resource acquisition and release primitives are: Both primitives in turn use the "pass_the_baton" method, whose pseudo-code is: Remarks The pattern is called "passing the baton" because a process that releases the resource as well as a freshly reactivated process will activate at most one suspended process, that is, shall "pass the baton to it". The mutex is released only when a process is going to suspend itself (resource_acquire), or when pass_the_baton is unable to reactivate another suspended process. == Operation names == The canonical names V and P come from the initials of Dutch words. V is generally explained as verhogen ("increase"). Several explanations have been offered for P, including proberen ("to test" or "to try"), passeren ("pass"), and pakken ("grab"). Dijkstra's earliest paper on the subject gives passering ("passing") as the meaning for P, and vrijgave ("release") as the meaning for V. It also mentions that the terminology is taken from that used in railroad signals. Dijkstra subsequently wrote that he intended P to stand for prolaag, short for probeer te verlagen, literally "try to reduce", or to parallel the terms used in the other case, "try to decrease". In ALGOL 68, the Linux kernel, and in some English textbooks, the V and P operations are called, respectively, up and down. In software engineering practice, they are often called signal and wait, release and acquire (standard Java library), or post and pend. Some texts call them vacate and procure to match the original Dutch initials. == Semaphores vs. mutexes == A mutex is a locking mechanism that sometimes uses the same basic implementation as the binary semaphore. However, they differ in how they are used. While a binary semaphore may be colloquially referred to as a mutex, a true mutex has a more specific use-case and definition, in that only the task that locked the mutex is supposed to unlock it. This constraint aims to handle some potential problems of using semaphores: Priority inversion: If the mutex knows who locked it and is supposed to unlock it, it is possible to promote the priority of that task whenever a higher-priority task starts waiting on the mutex. Premature task termination: Mutexes may also provide deletion safety, where the task holding the mutex cannot be accidentally deleted. (This is also a cost; if the mutex can prevent a task from being reclaimed, then a garbage collector has to monitor the mutex.) Termination deadlock: If a mutex-holding task terminates for any reason, the OS can release the mutex and signal waiting tasks of this condition. Recursion deadlock: a task is allowed to lock a reentrant mutex multiple times as it unlocks it an equal number of times. Accidental release: An error is raised on the release of the mutex if the releasing task is not its owner. == See also == Async/await Flag (programming) Synchronization (computer science) Cigarette smokers problem Dining philosophers problem Readers–writers problem Sleeping barber problem Monitor Spurious wakeup == References == == External links == === Introductions === Hilsheimer, Volker (2004). "Implementing a Read/Write Mutex" (Web page). Qt Quarterly, Issue 11 - Q3 2004 Zelenski, Julie; Parlante, Nick. "Thread and Semaphore Examples" (PDF). Handout. CS107 Programming Paradigms. Spring 2008 (23). Stanford Engineering Everywhere (SEE). === References === Dijkstra, Edsger W. Cooperating sequential processes (EWD-123) (PDF). E.W. Dijkstra Archive. Center for American History, University of Texas at Austin. (transcription) (September 1965) "semaphore.h - semaphores (REALTIME)". The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004 Edition. Open Group. 2004. Downey, Allen B. (2016) [2005]. "The Little Book of Semaphores" (2nd ed.). Green Tea Press. Leppäjärvi, Jouni (May 11, 2008). "A pragmatic, historically oriented survey on the universality of synchronization primitives" (PDF). University of Oulu, Finland.
https://en.wikipedia.org/wiki/Semaphore_(programming)
Object-oriented programming (OOP) is a programming paradigm based on the concept of objects. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and implemented in code). In OOP, computer programs are designed by making them out of objects that interact with one another. Many of the most widely used programming languages (such as C++, Java, and Python) support object-oriented programming to a greater or lesser degree, typically as part of multiple paradigms in combination with others such as imperative programming and declarative programming. Significant object-oriented languages include Ada, ActionScript, C++, Common Lisp, C#, Dart, Eiffel, Fortran 2003, Haxe, Java, JavaScript, Kotlin, Logo, MATLAB, Objective-C, Object Pascal, Perl, PHP, Python, R, Raku, Ruby, Scala, SIMSCRIPT, Simula, Smalltalk, Swift, Vala and Visual Basic.NET. == History == The idea of "objects" in programming started with the artificial intelligence group at MIT in the late 1950s and early 1960s. Here, "object" referred to LISP atoms with identified properties (attributes). Another early example was Sketchpad created by Ivan Sutherland at MIT in 1960–1961. In the glossary of his technical report, Sutherland defined terms like "object" and "instance" (with the class concept covered by "master" or "definition"), albeit specialized to graphical interaction. Later, in 1968, AED-0, MIT's version of the ALGOL programming language, connected data structures ("plexes") and procedures, prefiguring what were later termed "messages", "methods", and "member functions". Topics such as data abstraction and modular programming were common points of discussion at this time. Meanwhile, in Norway, Simula was developed during the years 1961–1967. Simula introduced essential object-oriented ideas, such as classes, inheritance, and dynamic binding. Simula was used mainly by researchers involved with physical modelling, like the movement of ships and their content through cargo ports. Simula is generally accepted as being the first language with the primary features and framework of an object-oriented language. Influenced by both MIT and Simula, Alan Kay began developing his own ideas in November 1966. He would go on to create Smalltalk, an influential object-oriented programming language. By 1967, Kay was already using the term "object-oriented programming" in conversation. Although sometimes called the "father" of object-oriented programming, Kay has said his ideas differ from how object-oriented programming is commonly understood, and has implied that the computer science establishment did not adopt his notion. A 1976 MIT memo co-authored by Barbara Liskov lists Simula 67, CLU, and Alphard as object-oriented languages, but does not mention Smalltalk. In the 1970s, the first version of the Smalltalk programming language was developed at Xerox PARC by Alan Kay, Dan Ingalls and Adele Goldberg. Smalltalk-72 was notable for use of objects at the language level and its graphical development environment. Smalltalk was a fully dynamic system, allowing users to create and modify classes as they worked. Much of the theory of OOP was developed in the context of Smalltalk, for example multiple inheritance. In the late 1970s and 1980s, object-oriented programming rose to prominence. The Flavors object-oriented Lisp was developed starting 1979, introducing multiple inheritance and mixins. In August 1981, Byte Magazine highlighted Smalltalk and OOP, introducing these ideas to a wide audience. LOOPS, the object system for Interlisp-D, was influenced by Smalltalk and Flavors, and a paper about it was published in 1982. In 1986, the first Conference on Object-Oriented Programming, Systems, Languages, and Applications (OOPSLA) was attended by 1,000 people. This conference marked the beginning of efforts to consolidate Lisp object systems, eventually resulting in the Common Lisp Object System. In the 1980s, there were a few attempts to design processor architectures that included hardware support for objects in memory, but these were not successful. Examples include the Intel iAPX 432 and the Linn Smart Rekursiv. In the mid-1980s, new object-oriented languages like Objective-C, C++, and Eiffel emerged. Objective-C was developed by Brad Cox, who had used Smalltalk at ITT Inc.. Bjarne Stroustrup created C++ based on his experience using Simula for his PhD thesis. Bertrand Meyer produced the first design of the Eiffel language in 1985, which focused on software quality using a design by contract approach. In the 1990s, object-oriented programming became the main way of programming, especially as more languages supported it. These included Visual FoxPro 3.0, C++, and Delphi. OOP became even more popular with the rise of graphical user interfaces, which used objects for buttons, menus and other elements. One well-known example is Apple's Cocoa framework, used on Mac OS X and written in Objective-C. OOP toolkits also enhanced the popularity of event-driven programming. At ETH Zürich, Niklaus Wirth and his colleagues created new approaches to OOP. Modula-2 (1978) and Oberon (1987), included a distinctive approach to object orientation, classes, and type checking across module boundaries. Inheritance is not obvious in Wirth's design since his nomenclature looks in the opposite direction: It is called type extension and the viewpoint is from the parent down to the inheritor. Many programming languages that existed before OOP have added object-oriented features, including Ada, BASIC, Fortran, Pascal, and COBOL. This sometimes caused compatibility and maintainability issues, as these languages were not originally designed with OOP in mind. In the new millenium, new languages like Python and Ruby have emerged that combine object-oriented and procedural styles. The most commercially important "pure" object-oriented languages continue to be Java, developed by Sun Microsystems, as well as C# and Visual Basic.NET (VB.NET), both designed for Microsoft's .NET platform. These languages show the benefits of OOP by creating abstractions from implementation. The .NET platform supports cross-language inheritance, allowing programs to use objects from multiple languages together. == Features == Object-oriented programming focuses on working with objects, but not all OOP languages have every feature linked to OOP. Below are some common features of languages that are considered strong in OOP or support it along with other programming styles. Important exceptions are also noted. Christopher J. Date pointed out that comparing OOP with other styles, like relational programming, is difficult because there isn't a clear, agreed-upon definition of OOP. === Imperative programming === Features from imperative and structured programming are present in OOP languages and are also found in non-OOP languages. Variables hold different data types like integers, strings, lists, and hash tables. Some data types are built-in while others result from combining variables using memory pointers. Procedures – also known as functions, methods, routines, or subroutines – take input, generate output, and work with data. Modern languages include structured programming constructs like loops and conditionals. Support for modular programming lets programmers organize related procedures into files and modules. This makes programs easier to manage. Each modules has its own namespace, so items in one module will not conflict with items in another. Object-oriented programming (OOP) was created to make code easier to reuse and maintain. However, it was not designed to clearly show the flow of a program's instructions—that was left to the compiler. As computers began using more parallel processing and multiple threads, it became more important to understand and control how instructions flow. This is difficult to do with OOP. === Objects === An object is a type of data structure that has two main parts: fields and methods. Fields may also be known as members, attributes, or properties, and hold information in the form of state variables. Methods are actions, subroutines, or procedures, defining the object's behavior in code. Objects are usually stored in memory, and in many programming languages, they work like pointers that link directly to a contiguous block containing the object instances's data. Objects can contain other objects. This is called object composition. For example, an Employee object might have an Address object inside it, along with other information like "first_name" and "position". This type of structures shows "has-a" relationships, like "an employee has an address". Some believe that OOP places too much focus on using objects rather than on algorithms and data structures. For example, programmer Rob Pike pointed out that OOP can make programmers think more about type hierarchy than composition. He has called object-oriented programming "the Roman numerals of computing". Rich Hickey, creator of Clojure, described OOP as overly simplistic, especially when it comes to representing real-world things that change over time. Alexander Stepanov said that OOP tries to fit everything into a single type, which can be limiting. He argued that sometimes we need multisorted algebras—families of interfaces that span multiple types, such as in generic programming. Stepanov also said that calling everything an "object" doesn't add much understanding. ==== Real-world modeling and relationships ==== Sometimes, objects represent real-world things and processes in digital form. For example, a graphics program may have objects such as "circle", "square", and "menu". An online shopping system might have objects such as "shopping cart", "customer", and "product". Niklaus Wirth said, "This paradigm [OOP] closely reflects the structure of systems in the real world and is therefore well suited to model complex systems with complex behavior". However, more often, objects represent abstract entities, like an open file or a unit converter. Not everyone agrees that OOP makes it easy to copy the real world exactly or that doing so is even necessary. Bob Martin suggests that because classes are software, their relationships don't match the real-world relationships they represent. Bertrand Meyer argues in Object-Oriented Software Construction, that a program is not a model of the world but a model of some part of the world; "Reality is a cousin twice removed". Steve Yegge noted that natural languages lack the OOP approach of strictly prioritizing things (objects/nouns) before actions (methods/verbs), as opposed to functional programming which does the reverse. This can sometimes make OOP solutions more complicated than those written in procedural programming. === Inheritance === Most OOP languages allow reusing and extending code through "inheritance". This inheritance can use either "classes" or "prototypes", which have some differences but use similar terms for ideas like "object" and "instance". ==== Class-based ==== In class-based programming, the most common type of OOP, every object is an instance of a specific class. The class defines the data format, like variables (e.g., name, age) and methods (actions the object can take). Every instance of the class has the same set of variables and methods. Objects are created using a special method in the class known as a constructor. Here are a few key terms in class-based OOP: Class variables – belong to the class itself, so all objects in the class share one copy. Instance variables – belong to individual objects; every object has its own version of these variables. Member variables – refers to both the class and instance variables that are defined by a particular class. Class methods – linked to the class itself and can only use class variables. Instance methods – belong to individual objects, and can use both instance and class variables Classes may inherit from other classes, creating a hierarchy of "subclasses". For example, an "Employee" class might inherit from a "Person" class. This means the Employee object will have all the variables from Person (like name variables) plus any new variables (like job position and salary). Similarly, the subclass may expand the interface with new methods. Most languages also allow the subclass to override the methods defined by superclasses. Some languages support multiple inheritance, where a class can inherit from more than one class, and other languages similarly support mixins or traits. For example, a mixin called UnicodeConversionMixin might add a method unicode_to_ascii() to both a FileReader and a WebPageScraper class. Some classes are abstract, meaning they cannot be directly instantiated into objects; they're only meant to be inherited into other classes. Other classes are utility classes which contain only class variables and methods and are not meant to be instantiated or subclassed. ==== Prototype-based ==== In prototype-based programming, there aren't any classes. Instead, each object is linked to another object, called its prototype or parent. In Self, an object may have multiple or no parents, but in the most popular prototype-based language, Javascript, every object has exactly one prototype link, up to the base Object type whose prototype is null. The prototype acts as a model for new objects. For example, if you have an object fruit, you can make two objects apple and orange, based on it. There is no fruit class, but they share traits from the fruit prototype. Prototype-based languages also allow objects to have their own unique properties, so the apple object might have an attribute sugar_content, while the orange or fruit objects do not. ==== No inheritance ==== Some languages, like Go, don't use inheritance at all. Instead, they encourage "composition over inheritance", where objects are built using smaller parts instead of parent-child relationships. For example, instead of inheriting from class Person, the Employee class could simply contain a Person object. This lets the Employee class control how much of Person it exposes to other parts of the program. Delegation is another language feature that can be used as an alternative to inheritance. Programmers have different opinions on inheritance. Bjarne Stroustrup, author of C++, has stated that it is possible to do OOP without inheritance. Rob Pike has criticized inheritance for creating complicated hierarchies instead of simpler solutions. ==== Inheritance and behavioral subtyping ==== People often think that if one class inherits from another, it means the subclass "is a" more specific version of the original class. This presumes the program semantics are that objects from the subclass can always replace objects from the original class without problems. This concept is known as behavioral subtyping, more specifically the Liskov substitution principle. However, this is often not true, especially in programming languages that allow mutable objects, objects that change after they are created. In fact, subtype polymorphism as enforced by the type checker in OOP languages cannot guarantee behavioral subtyping in most if not all contexts. For example, the circle-ellipse problem is notoriously difficult to handle using OOP's concept of inheritance. Behavioral subtyping is undecidable in general, so it cannot be easily implemented by a compiler. Because of this, programmers must carefully design class hierarchies to avoid mistakes that the programming language itself cannot catch. === Dynamic dispatch === When a method is called on an object, the object itself—not outside code—decides which specific code to run. This process, called dynamic dispatch, usually happens at run time by checking a table linked to the object to find the correct method. In this context, a method call is also known as message passing, meaning the method name and its inputs are like a message sent to the object for it to act on. If the method choice depends on more than one type of object (such as other objects passed as parameters), it's called multiple dispatch. Dynamic dispatch works together with inheritance: if an object doesn't have the requested method, it looks up to its parent class (delegation), and continues up the chain until it finds the method or reaches the top. === Data abstraction and encapsulation === Data abstraction is a way of organizing code so that only certain parts of the data are visible to related functions (data hiding). This helps prevent mistakes and makes the program easier to manage. Because data abstraction works well, many programming styles, like object-oriented programming and functional programming, use it as a key principle. Encapsulation is another important idea in programming. It means keeping the internal details of an object hidden from the outside code. This makes it easier to change how an object works on the inside without affecting other parts of the program, such as in code refactoring. Encapsulation also helps keep related code together (decoupling), making it easier for programmers to understand. In object-oriented programming, objects act as a barrier between their internal workings and external code. Outside code can only interact with an object by calling specific public methods or variables. If a class only allows access to its data through methods and not directly, this is called information hiding. When designing a program, it's often recommended to keep data as hidden as possible. This means using local variables inside functions when possible, then private variables (which only the object can use), and finally public variables (which can be accessed by any part of the program) if necessary. Keeping data hidden helps prevent problems when changing the code later. Some programming languages, like Java, control information hiding by marking variables as private (hidden) or public (accessible). Other languages, like Python, rely on naming conventions, such as starting a private method's name with an underscore. Intermediate levels of access also exist, such as Java's protected keyword, (which allows access from the same class and its subclasses, but not objects of a different class), and the internal keyword in C#, Swift, and Kotlin, which restricts access to files within the same module. Abstraction and information hiding are important concepts in programming, especially in object-oriented languages. Programs often create many copies of objects, and each one works independently. Supporters of this approach say it makes code easier to reuse and intuitively represents real-world situations. However, others argue that object-oriented programming does not enhance readability or modularity. Eric S. Raymond has written that object-oriented programming languages tend to encourage thickly layered programs that destroy transparency. Raymond compares this unfavourably to the approach taken with Unix and the C programming language. One programming principle, called the "open/closed principle", says that classes and functions should be "open for extension, but closed for modification". Luca Cardelli has stated that OOP languages have "extremely poor modularity properties with respect to class extension and modification", and tend to be extremely complex. The latter point is reiterated by Joe Armstrong, the principal inventor of Erlang, who is quoted as saying: The problem with object-oriented languages is they've got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle. Leo Brodie says that information hiding can lead to copying the same code in multiple places (duplicating code), which goes against the don't repeat yourself rule of software development. === Polymorphism === Polymorphism is the use of one symbol to represent multiple different types. In object-oriented programming, polymorphism more specifically refers to subtyping or subtype polymorphism, where a function can work with a specific interface and thus manipulate entities of different classes in a uniform manner. For example, imagine a program has two shapes: a circle and a square. Both come from a common class called "Shape." Each shape has its own way of drawing itself. With subtype polymorphism, the program doesn't need to know the type of each shape, and can simply call the "Draw" method for each shape. The programming language runtime will ensure the correct version of the "Draw" method runs for each shape. Because the details of each shape are handled inside their own classes, this makes the code simpler and more organized, enabling strong separation of concerns. === Open recursion === In object-oriented programming, objects have methods that can change or use the object's data. Many programming languages use a special word, like this or self, to refer to the current object. In languages that support open recursion, a method in an object can call other methods in the same object, including itself, using this special word. This allows a method in one class to call another method defined later in a subclass, a feature known as late binding. == OOP languages == OOP languages can be grouped into different types based on how they support and use objects: Pure OOP languages: In these languages, everything is treated as an object, even basic things like numbers and characters. They are designed to fully support and enforce OOP. Examples: Ruby, Scala, Smalltalk, Eiffel, Emerald, JADE, Self, Raku. Mostly OOP languages: These languages focus on OOP but also include some procedural programming features. Examples: Java, Python, C++, C#, Delphi/Object Pascal, VB.NET. Retrofitted OOP languages: These were originally designed for other types of programming but later added some OOP features. Examples: PHP, JavaScript, Perl, Visual Basic (derived from BASIC), MATLAB, COBOL 2002, Fortran 2003, ABAP, Ada 95, Pascal. Unique OOP languages: These languages have OOP features like classes and inheritance but use them in their own way. Examples: Oberon, BETA. Object-based languages: These support some OOP ideas but avoid traditional class-based inheritance in favor of direct manipulation of objects. Examples: JavaScript, Lua, Modula-2, CLU, Go. Multi-paradigm languages: These support both OOP and other programming styles, but OOP is not the predominant style in the language. Examples include Tcl, where TclOO allows both prototype-based and class-based OOP, and Common Lisp, with its Common Lisp Object System. === Popularity and reception === Many popular programming languages, like C++, Java, and Python, use object-oriented programming. In the past, OOP was widely accepted, but recently, some programmers have criticized it and prefer functional programming instead. A study by Potok et al. found no major difference in productivity between OOP and other methods. Paul Graham, a well-known computer scientist, believes big companies like OOP because it helps manage large teams of average programmers. He argues that OOP adds structure, making it harder for one person to make serious mistakes, but at the same time restrains smart programmers. Eric S. Raymond, a Unix programmer and open-source software advocate, argues that OOP is not the best way to write programs. Richard Feldman says that, while OOP features helped some languages stay organized, their popularity comes from other reasons. Lawrence Krubner argues that OOP doesn't offer special advantages compared to other styles, like functional programming, and can make coding more complicated. Luca Cardelli says that OOP is slower and takes longer to compile than procedural programming. === OOP in dynamic languages === In recent years, object-oriented programming (OOP) has become very popular in dynamic programming languages. Some languages, like Python, PowerShell, Ruby and Groovy, were designed with OOP in mind. Others, like Perl, PHP, and ColdFusion, started as non-OOP languages but added OOP features later (starting with Perl 5, PHP 4, and ColdFusion version 6). On the web, HTML, XHTML, and XML documents use the Document Object Model (DOM), which works with the JavaScript language. JavaScript is a well-known example of a prototype-based language. Instead of using classes like other OOP languages, JavaScript creates new objects by copying (or "cloning") existing ones. Another language that uses this method is Lua. === OOP in a network protocol === When computers communicate in a client-server system, they send messages to request services. For example, a simple message might include a length field (showing how big the message is), a code that identifies the type of message, and a data value. These messages can be designed as structured objects that both the client and server understand, so that each type of message corresponds to a class of objects in the client and server code. More complex messages might include structured objects as additional details. The client and server need to know how to serialize and deserialize these messages so they can be transmitted over the network, and map them to the appropriate object types. Both clients and servers can be thought of as complex object-oriented systems. The Distributed Data Management Architecture (DDM) uses this idea by organizing objects into four levels: Basic message details - Information like message length, type, and data. Objects and collections - Similar to how objects work in Smalltalk, storing messages and their details. Managers - Like file directories, these organize and store data, as well as provide memory and processing power. They are similar to IBM i Objects. Clients and servers - These are full systems that include managers and handle security, directory services, and multitasking. The first version of DDM defined distributed file services. Later, it was expanded to support databases through the Distributed Relational Database Architecture (DRDA). == Design patterns == Design patterns are common solutions to problems in software design. Some design patterns are especially useful for object-oriented programming, and design patterns are typically introduced in an OOP context. === Object patterns === The following are notable software design patterns for OOP objects. Function object: Class with one main method that acts like an anonymous function (in C++, the function operator, operator()) Immutable object: does not change state after creation First-class object: can be used without restriction Container object: contains other objects Factory object: creates other objects Metaobject: Used to create other objects (similar to a class, but an object) Prototype object: a specialized metaobject that creates new objects by copying itself Singleton object: only instance of its class for the lifetime of the program Filter object: receives a stream of data as its input and transforms it into the object's output A common anti-pattern is the God object, an object that knows or does too much. === Gang of Four design patterns === Design Patterns: Elements of Reusable Object-Oriented Software is a famous book published in 1994 by four authors: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. People often call them the "Gang of Four". The book talks about the strengths and weaknesses of object-oriented programming and explains 23 common ways to solve programming problems. These solutions, called "design patterns," are grouped into three types: Creational patterns (5): Factory method pattern, Abstract factory pattern, Singleton pattern, Builder pattern, Prototype pattern Structural patterns (7): Adapter pattern, Bridge pattern, Composite pattern, Decorator pattern, Facade pattern, Flyweight pattern, Proxy pattern Behavioral patterns (11): Chain-of-responsibility pattern, Command pattern, Interpreter pattern, Iterator pattern, Mediator pattern, Memento pattern, Observer pattern, State pattern, Strategy pattern, Template method pattern, Visitor pattern === Object-orientation and databases === Both object-oriented programming and relational database management systems (RDBMSs) are widely used in software today. However, relational databases don't store objects directly, which creates a challenge when using them together. This issue is called object-relational impedance mismatch. To solve this problem, developers use different methods, but none of them are perfect. One of the most common solutions is object-relational mapping (ORM), which helps connect object-oriented programs to relational databases. Examples of ORM tools include Visual FoxPro, Java Data Objects, and Ruby on Rails ActiveRecord. Some databases, called object databases, are designed to work with object-oriented programming. However, they have not been as popular or successful as relational databases. Date and Darwen have proposed a theoretical foundation that uses OOP as a kind of customizable type system to support RDBMSs, but it forbids objects containing pointers to other objects. === Responsibility- vs. data-driven design === In responsibility-driven design, classes are built around what they need to do and the information they share, in the form of a contract. This is different from data-driven design, where classes are built based on the data they need to store. According to Wirfs-Brock and Wilkerson, the originators of responsibility-driven design, responsibility-driven design is the better approach. === SOLID and GRASP guidelines === SOLID is a set of five rules for designing good software, created by Michael Feathers: Single responsibility principle: A class should have only one reason to change. Open/closed principle: Software entities should be open for extension, but closed for modification. Liskov substitution principle: Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. Interface segregation principle: Clients should not be forced to depend upon interfaces that they do not use. Dependency inversion principle: Depend upon abstractions, not concretes. GRASP (General Responsibility Assignment Software Patterns) is another set of software design rules, created by Craig Larman, that helps developers assign responsibilities to different parts of a program: Creator Principle: allows classes create objects they closely use. Information Expert Principle: assigns tasks to classes with the needed information. Low Coupling Principle: reduces class dependencies to improve flexibility and maintainability. High Cohesion Principle: designing classes with a single, focused responsibility. Controller Principle: assigns system operations to separate classes that manage flow and interactions. Polymorphism: allows different classes to be used through a common interface, promoting flexibility and reuse. Pure Fabrication Principle: create helper classes to improve design, boost cohesion, and reduce coupling. == Formal semantics == In object-oriented programming, objects are things that exist while a program is running. An object can represent anything, like a person, a place, a bank account, or a table of data. Many researchers have tried to formally define how OOP works. Records are the basis for understanding objects. They can represent fields, and also methods, if function literals can be stored. However, inheritance presents difficulties, particularly with the interactions between open recursion and encapsulated state. Researchers have used recursive types and co-algebraic data types to incorporate essential features of OOP. Abadi and Cardelli defined several extensions of System F<: that deal with mutable objects, allowing both subtype polymorphism and parametric polymorphism (generics), and were able to formally model many OOP concepts and constructs. Although far from trivial, static analysis of object-oriented programming languages such as Java is a mature field, with several commercial tools. == See also == Comparison of programming languages (object-oriented programming) Component-based software engineering Object association Object modeling language Object-oriented analysis and design Object-oriented ontology === Systems === CADES Common Object Request Broker Architecture (CORBA) Distributed Component Object Model Jeroo === Modeling languages === IDEF4 Interface description language UML == References == == Further reading == Abadi, Martin; Luca Cardelli (1998). A Theory of Objects. Springer Verlag. ISBN 978-0-387-94775-4. Abelson, Harold; Gerald Jay Sussman (1997). Structure and Interpretation of Computer Programs. MIT Press. ISBN 978-0-262-01153-2. Archived from the original on 26 December 2017. Retrieved 22 January 2006. Armstrong, Deborah J. (February 2006). "The Quarks of Object-Oriented Development". Communications of the ACM. 49 (2): 123–128. doi:10.1145/1113034.1113040. ISSN 0001-0782. S2CID 11485502. Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN 978-0134685991. Booch, Grady (1997). Object-Oriented Analysis and Design with Applications. Addison-Wesley. ISBN 978-0-8053-5340-2. Eeles, Peter; Oliver Sims (1998). Building Business Objects. John Wiley & Sons. ISBN 978-0-471-19176-6. Gamma, Erich; Richard Helm; Ralph Johnson; John Vlissides (1995). Design Patterns: Elements of Reusable Object Oriented Software. Addison-Wesley. Bibcode:1995dper.book.....G. ISBN 978-0-201-63361-0. Harmon, Paul; William Morrissey (1996). The Object Technology Casebook – Lessons from Award-Winning Business Applications. John Wiley & Sons. ISBN 978-0-471-14717-6. Jacobson, Ivar (1992). Object-Oriented Software Engineering: A Use Case-Driven Approach. Addison-Wesley. Bibcode:1992oose.book.....J. ISBN 978-0-201-54435-0. Kay, Alan. The Early History of Smalltalk. Archived from the original on 4 April 2005. Retrieved 18 April 2005. Meyer, Bertrand (1997). Object-Oriented Software Construction. Prentice Hall. ISBN 978-0-13-629155-8. Pecinovsky, Rudolf (2013). OOP – Learn Object Oriented Thinking & Programming. Bruckner Publishing. ISBN 978-80-904661-8-0. Rumbaugh, James; Michael Blaha; William Premerlani; Frederick Eddy; William Lorensen (1991). Object-Oriented Modeling and Design. Prentice Hall. ISBN 978-0-13-629841-0. Schach, Stephen (2006). Object-Oriented and Classical Software Engineering, Seventh Edition. McGraw-Hill. ISBN 978-0-07-319126-3. Schreiner, Axel-Tobias (1993). Object oriented programming with ANSI-C. Hanser. hdl:1850/8544. ISBN 978-3-446-17426-9. Taylor, David A. (1992). Object-Oriented Information Systems – Planning and Implementation. John Wiley & Sons. ISBN 978-0-471-54364-0. Weisfeld, Matt (2009). The Object-Oriented Thought Process, Third Edition. Addison-Wesley. ISBN 978-0-672-33016-2. West, David (2004). Object Thinking (Developer Reference). Microsoft Press. ISBN 978-0-7356-1965-4. == External links == Introduction to Object Oriented Programming Concepts (OOP) and More by L.W.C. Nirosh Discussion on Cons of OOP OOP Concepts (Java Tutorials)
https://en.wikipedia.org/wiki/Object-oriented_programming
In aspect and functional programming, advice describes a class of functions which modify other functions when the latter are run; it is a certain function, method or procedure that is to be applied at a given join point of a program. == Use == The practical use of advice functions is generally to modify or otherwise extend the behavior of functions which cannot or should not be readily modified or extended. For instance, the Emacspeak Emacs-addon makes extensive use of advice: it must modify thousands of existing Emacs modules and functions such that it can produce audio output for the blind corresponding to the visual presentation, but it would be infeasible to copy all of them and redefine them to produce audio output in addition to their normal outputs; so, the Emacspeak programmers define advice functions which run before and after. For a simple Emacs example: suppose after a user corrected a mis-spelled word using the Emacs ispell module, they wanted to re-spellcheck the entire buffer. ispell-word offers no such functionality, even if the corrected word appears frequently in the buffer. The user could track down the definition of ispell-word, copy it into their personal Emacs files, and add the desired functionality there, but this is tedious and, worse, brittle (the user's version is now out of sync with the core Emacs implementation, if it even works without further refactoring). What the user wants is quite simple — just to run another command any time ispell-word runs. Using advice, it can be done as simply as this: While this example is obviously trivial, the strength of advice, especially when compared to similar facilities such as Python decorators and Java annotations, lies in the fact that not only do the advised functions / methods not need to be designed to accept advice, but also the advice themselves need not be designed to be usable as advice - they're just normal functions. The availability of evaluation throughout the lifetime of a piece of code (cf. code staging) in Lisp allows advice to be inlined automatically into any other code in a variety of ways. Any piece of code can be advised to carry out any other computation before, after, around, or instead of its original definition. === Readability === Advice has the potential to introduce confusion, as a piece of advice applied to a function is not apparent to a user who tracks down the function's source definition to learn about it. In such cases, advice acts almost like a COMEFROM, a joke facility added to INTERCAL to spoof the spaghettification attendant to the extensive use of GOTOs. In practice, however, such issues rarely present themselves. Upstream developers and maintainers of Lisp packages and modules never use advice, since there is no advantage to be gained by advising functions when their original source definitions can be freely rewritten to include the desired features. Advice is only useful in that it enables downstream users to subsequently modify default behaviour in a way that does not require propagation of such modifications into the core implementation's source definition. == Implementations == A form of advices were part of C with Classes in the late 1970s and early 1980s, namely functions called call and return defined in a class, which were called before (respectively, after) member functions of the class. However, these were dropped from C++. Advices are part of the Common Lisp Object System (CLOS), as :before, :after, and :around methods, which are combined with the primary method under "standard method combination". Common Lisp implementations provide advice functionality (in addition to the standard method combination for CLOS) as extensions. LispWorks supports advising functions, macros and CLOS methods. EmacsLisp added advice-related code in version 19.28, 1994. == History == The following is taken from a discussion at the mailing list aosd-discuss. Pascal Costanza contributed the following: The term "advice" goes back to the term advising as introduced by Warren Teitelman in his PhD thesis in 1966. Here is a quote from Chapter 3 of his thesis: Advising is the basic innovation in the model, and in the PILOT system. Advising consists of inserting new procedures at any or all of the entry or exit points to a particular procedure (or class of procedures). The procedures inserted are called "advice procedures" or simply "advice". Since each piece of advice is itself a procedure, it has its own entries and exits. In particular, this means that the execution of advice can cause the procedure that it modifies to be bypassed completely, e.g., by specifying as an exit from the advice one of the exits from the original procedure; or the advice may change essential variables and continue with the computation so that the original procedure is executed, but with modified variables. Finally, the advice may not alter the execution or affect the original procedure at all, e.g., it may merely perform some additional computation such as printing a message or recording history. Since advice can be conditional, the decision as to what is to be done can depend on the results of the computation up to that point. The principal advantage of advising is that the user need not be concerned about the details of the actual changes in his program, nor the internal representation of advice. He can treat the procedure to be advised as a unit, a single block, and make changes to it without concern for the particulars of this block. This may be contrasted with editing in which the programmer must be cognizant of the internal structure of the procedure. "Advising" found its way into BBN Lisp and later into Xerox PARC's Interlisp. It also found its way to Flavors, the first object-oriented extension to Lisp developed at MIT. They were subsumed under the notion of method combination. Since method combination and macros are closely related, it's also interesting to note that the first macro system was described in 1963, three years before Warren Teitelman's PhD thesis. == See also == Function decorator (w.r.t. Python) Aspect-oriented software development#Advice bodies == Notes == Gregor Kiczales comments the above as follows: == References == == External links == Teitelman's PhD thesis, PILOT: A Step Toward Man-Computer Symbiosis (AITR-221) Interlisp reference manual from 1974 "Origin of Advice"
https://en.wikipedia.org/wiki/Advice_(programming)
In computing, reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change. With this paradigm, it is possible to express static (e.g., arrays) or dynamic (e.g., event emitters) data streams with ease, and also communicate that an inferred dependency within the associated execution model exists, which facilitates the automatic propagation of the changed data flow. For example, in an imperative programming setting, a := b + c would mean that a is being assigned the result of b + c at the instant the expression is evaluated, and later, the values of b and c can be changed with no effect on the value of a. On the other hand, in reactive programming, the value of a is automatically updated whenever the values of b or c change, without the program having to explicitly re-state the statement a := b + c to re-assign the value of a. Another example is a hardware description language such as Verilog, where reactive programming enables changes to be modeled as they propagate through circuits. Reactive programming has been proposed as a way to simplify the creation of interactive user interfaces and near-real-time system animation. For example, in a model–view–controller (MVC) architecture, reactive programming can facilitate changes in an underlying model being reflected automatically in an associated view. == Approaches to creating reactive programming languages == Several popular approaches are employed in the creation of reactive programming languages. One approach is the specification of dedicated languages that are specific to various domain constraints. Such constraints usually are characterized by real-time, embedded computing or hardware description. Another approach involves the specification of general-purpose languages that include support for reactivity. Other approaches are articulated in the definition, and use of programming libraries, or embedded domain-specific languages, that enable reactivity alongside or on top of the programming language. Specification and use of these different approaches results in language capability trade-offs. In general, the more restricted a language is, the more its associated compilers and analysis tools are able to inform developers (e.g., in performing analysis for whether programs are able to execute in actual real-time). Functional trade-offs in specificity may result in deterioration of the general applicability of a language. == Programming models and semantics == A variety of models and semantics govern reactive programming. We can loosely split them along the following dimensions: Synchrony: synchronous versus asynchronous model of time Determinism: deterministic versus non-deterministic evaluation process and results Update process: callback versus dataflow versus actor == Implementation techniques and challenges == === Essence of implementations === Reactive programming language runtimes are represented by a graph that identifies the dependencies among the involved reactive values. In such a graph, nodes represent the act of computing, and edges model dependency relationships. Such a runtime employs said graph, to help it keep track of the various computations, which must be executed anew, once an involved input changes value. ==== Change propagation algorithms ==== The most common approaches to data propagation are: Pull: The value consumer is in fact proactive, in that it regularly queries the observed source for values and reacts whenever a relevant value is available. This practice of regularly checking for events or value changes is commonly referred to as polling. Push: The value consumer receives a value from the source whenever the value becomes available. These values are self-contained, e.g. they contain all the necessary information, and no further information needs to be queried by the consumer. Push-pull: The value consumer receives a change notification, which is a short description of the change, e.g. "some value changed" – this is the push part. However, the notification does not contain all the necessary information (which means it does not contain the actual values), so the consumer needs to query the source for more information (the specific value) after it receives the notification – this is the pull part. This method is commonly used when there is a large volume of data that the consumers might be potentially interested in. So in order to reduce throughput and latency, only light-weight notifications are sent; and then those consumers which require more information will request that specific information. This approach also has the drawback that the source might be overwhelmed by many requests for additional information after a notification is sent. ==== What to push? ==== At the implementation level, event reaction consists of the propagation across a graph's information, which characterizes the existence of change. Consequently, computations that are affected by such change then become outdated and must be flagged for re-execution. Such computations are then usually characterized by the transitive closure of the change (i.e. the full set of transitive dependencies a source affects) in its associated source. Change propagation may then lead to an update in the value of the graph's sinks. Graph propagated information can consist of a node's complete state, i.e., the computation result of the involved node. In such cases, the node's previous output is then ignored. Another method involves delta propagation i.e. incremental change propagation. In this case, information is proliferated along a graph's edges, which consist only of deltas describing how the previous node was changed. This approach is especially important when nodes hold large amounts of state data, which would otherwise be expensive to recompute from scratch. Delta propagation is essentially an optimization that has been extensively studied via the discipline of incremental computing, whose approach requires runtime satisfaction involving the view-update problem. This problem is infamously characterized by the use of database entities, which are responsible for the maintenance of changing data views. Another common optimization is employment of unary change accumulation and batch propagation. Such a solution can be faster because it reduces communication among involved nodes. Optimization strategies can then be employed that reason about the nature of the changes contained within, and make alterations accordingly (e.g. two changes in the batch can cancel each other, and thus, simply be ignored). Yet another available approach, is described as invalidity notification propagation. This approach causes nodes with invalid input to pull updates, thus resulting in the update of their own outputs. There are two principal ways employed in the building of a dependency graph: The graph of dependencies are maintained implicitly within an event loop. Registration of explicit callbacks then results in the creation of implicit dependencies. Therefore, control inversion, which is induced via callback, is thus left in place. However, making callbacks functional (i.e. returning state value instead of unit value) necessitates that such callbacks become compositional. A graph of dependencies is program-specific and generated by a programmer. This facilitates an addressing of the callback's control inversion in two ways: either a graph is specified explicitly (typically using a domain-specific language (DSL), which may be embedded), or a graph is implicitly defined with expression and generation using an effective, archetypal language. === Implementation challenges in reactive programming === ==== Glitches ==== When propagating changes, it is possible to pick propagation orders such that the value of an expression is not a natural consequence of the source program. We can illustrate this easily with an example. Suppose seconds is a reactive value that changes every second to represent the current time (in seconds). Consider this expression: t = seconds + 1 g = (t > seconds) Because t should always be greater than seconds, this expression should always evaluate to a true value. Unfortunately, this can depend on the order of evaluation. When seconds changes, two expressions have to update: seconds + 1 and the conditional. If the first evaluates before the second, then this invariant will hold. If, however, the conditional updates first, using the old value of t and the new value of seconds, then the expression will evaluate to a false value. This is called a glitch. Some reactive languages are glitch-free and prove this property. This is usually achieved by topologically sorting expressions and updating values in topological order. This can, however, have performance implications, such as delaying the delivery of values (due to the order of propagation). In some cases, therefore, reactive languages permit glitches, and developers must be aware of the possibility that values may temporarily fail to correspond to the program source, and that some expressions may evaluate multiple times (for instance, t > seconds may evaluate twice: once when the new value of seconds arrives, and once more when t updates). ==== Cyclic dependencies ==== Topological sorting of dependencies depends on the dependency graph being a directed acyclic graph (DAG). In practice, a program may define a dependency graph that has cycles. Usually, reactive programming languages expect such cycles to be "broken" by placing some element along a "back edge" to permit reactive updating to terminate. Typically, languages provide an operator like delay that is used by the update mechanism for this purpose, since a delay implies that what follows must be evaluated in the "next time step" (allowing the current evaluation to terminate). ==== Interaction with mutable state ==== Reactive languages typically assume that their expressions are purely functional. This allows an update mechanism to choose different orders in which to perform updates, and leave the specific order unspecified (thereby enabling optimizations). When a reactive language is embedded in a programming language with state, however, it may be possible for programmers to perform mutable operations. How to make this interaction smooth remains an open problem. In some cases, it is possible to have principled partial solutions. Two such solutions include: A language might offer a notion of a "mutable cell". A mutable cell is one that the reactive update system is aware of, so that changes made to the cell propagate to the rest of the reactive program. This enables the non-reactive part of the program to perform a traditional mutation while enabling reactive code to be aware of and respond to this update, thus maintaining the consistency of the relationship between values in the program. An example of a reactive language that provides such a cell is FrTime. Properly encapsulated object-oriented libraries offer an encapsulated notion of state. In principle, it is therefore possible for such a library to interact smoothly with the reactive portion of a language. For instance, callbacks can be installed in the getters of the object-oriented library to notify the reactive update engine about state changes, and changes in the reactive component can be pushed to the object-oriented library through getters. FrTime employs such a strategy. ==== Dynamic updating of the graph of dependencies ==== In some reactive languages, the graph of dependencies is static, i.e., the graph is fixed throughout the program's execution. In other languages, the graph can be dynamic, i.e., it can change as the program executes. For a simple example, consider this illustrative example (where seconds is a reactive value): t = if ((seconds mod 2) == 0): seconds + 1 else: seconds - 1 end t + 1 Every second, the value of this expression changes to a different reactive expression, which t + 1 then depends on. Therefore, the graph of dependencies updates every second. Permitting dynamic updating of dependencies provides significant expressive power (for instance, dynamic dependencies routinely occur in graphical user interface (GUI) programs). However, the reactive update engine must decide whether to reconstruct expressions each time, or to keep an expression's node constructed but inactive; in the latter case, ensure that they do not participate in the computation when they are not supposed to be active. == Concepts == === Degrees of explicitness === Reactive programming languages can range from very explicit ones where data flows are set up by using arrows, to implicit where the data flows are derived from language constructs that look similar to those of imperative or functional programming. For example, in an implicitly lifted functional reactive programming (FRP), a function call might implicitly cause a node in a data flow graph to be constructed. Reactive programming libraries for dynamic languages (such as the Lisp "Cells" and Python "Trellis" libraries) can construct a dependency graph from runtime analysis of the values read during a function's execution, allowing data flow specifications to be both implicit and dynamic. Sometimes the term reactive programming refers to the architectural level of software engineering, where individual nodes in the data flow graph are ordinary programs that communicate with each other. === Static or dynamic === Reactive programming can be purely static where the data flows are set up statically, or be dynamic where the data flows can change during the execution of a program. The use of data switches in the data flow graph could to some extent make a static data flow graph appear as dynamic, and blur the distinction slightly. True dynamic reactive programming however could use imperative programming to reconstruct the data flow graph. === Higher-order reactive programming === Reactive programming could be said to be of higher order if it supports the idea that data flows could be used to construct other data flows. That is, the resulting value out of a data flow is another data flow graph that is executed using the same evaluation model as the first. === Data flow differentiation === Ideally all data changes are propagated instantly, but this cannot be assured in practice. Instead, it might be necessary to give different parts of the data flow graph different evaluation priorities. This can be called differentiated reactive programming. For example, in a word processor, the marking of spelling errors need not be totally in sync with the inserting of characters. Here differentiated reactive programming could potentially be used to give the spell checker lower priority, allowing it to be delayed while keeping other data-flows instantaneous. However, such differentiation introduces additional design complexity. For example, deciding how to define the different data flow areas, and how to handle event passing between different data flow areas. === Evaluation models of reactive programming === Evaluation of reactive programs is not necessarily based on how stack-based programming languages are evaluated. Instead, when some data is changed, the change is propagated to all data that is derived partially or completely from the data that was changed. This change propagation could be achieved in a number of ways, where perhaps the most natural way is an invalidate/lazy-revalidate scheme. It could be problematic simply to naively propagate a change using a stack, because of potential exponential update complexity if the data structure has a certain shape. One such shape can be described as "repeated diamonds shape", and has the following structure: An→Bn→An+1, An→Cn→An+1, where n=1,2... This problem could be overcome by propagating invalidation only when some data is not already invalidated, and later re-validate the data when needed using lazy evaluation. One inherent problem for reactive programming is that most computations that would be evaluated and forgotten in a normal programming language, needs to be represented in the memory as data-structures. This could potentially make reactive programming highly memory consuming. However, research on what is called lowering could potentially overcome this problem. On the other side, reactive programming is a form of what could be described as "explicit parallelism", and could therefore be beneficial for utilizing the power of parallel hardware. ==== Similarities with observer pattern ==== Reactive programming has principal similarities with the observer pattern commonly used in object-oriented programming. However, integrating the data flow concepts into the programming language would make it easier to express them and could therefore increase the granularity of the data flow graph. For example, the observer pattern commonly describes data-flows between whole objects/classes, whereas object-oriented reactive programming could target the members of objects/classes. == Approaches == === Imperative === It is possible to fuse reactive programming with ordinary imperative programming. In such a paradigm, imperative programs operate upon reactive data structures. Such a set-up is analogous to imperative constraint programming; however, while imperative constraint programming manages bidirectional data-flow constraints, imperative reactive programming manages one-way data-flow constraints. One reference implementation is the proposed Quantum runtime extension to JavaScript . === Object-oriented === Object-oriented reactive programming (OORP) is a combination of object-oriented programming and reactive programming. Perhaps the most natural way to make such a combination is as follows: instead of methods and fields, objects have reactions that automatically re-evaluate when the other reactions they depend on have been modified. If an OORP language maintains its imperative methods, it would also fall under the category of imperative reactive programming. === Functional === Functional reactive programming (FRP) is a programming paradigm for reactive programming on functional programming. === Actor based === Actors have been proposed to design reactive systems, often in combination with Functional reactive programming (FRP) and Reactive Streams to develop distributed reactive systems. === Rule based === A relatively new category of programming languages uses constraints (rules) as main programming concept. It consists of reactions to events, which keep all constraints satisfied. Not only does this facilitate event-based reactions, but it makes reactive programs instrumental to the correctness of software. An example of a rule based reactive programming language is Ampersand, which is founded in relation algebra. == Implementations == ReactiveX, an API for implementing reactive programming with streams, observables and operators with multiple language implementations including RxJs, RxJava, Rx.NET, RxPy and RxSwift. Elm, a reactive composition of web user interfaces. Reactive Streams, a JVM standard for asynchronous stream processing with non-blocking backpressure ObservableComputations, a cross-platform .NET implementation. Svelte, brings reactivity in the form of a variant JavaScript syntax that looks like JavaScript but is naturally reactive where JavaScript normally isn't. Solid.js brings reactivity to JavaScript without changing JavaScript syntax semantics, along with reactive JSX templating. Quantum JS, a runtime extension to JavaScript that brings imperative reactive programming to the language, creating a whole new category in the reactivity spectrum. Rimmel.js, a modern functional-reactive JavaScript UI library designed with RxJS streams in mind. == See also == Observable (Computing), observable in reactive programming. == References == == External links == A survey on reactive programming A 2013 paper by E. Bainomugisha, A. Lombide Carreton, T. Van Cutsem, S. Mostinckx, and W. De Meuter that surveys and provides a taxonomy of existing reactive programming approaches. MIMOSA Project of INRIA - ENSMP, a general site about reactive programming. Deprecating the Observer Pattern A 2010 paper by Ingo Maier, Tiark Rompf and Martin Odersky outlining a reactive programming framework for the Scala programming language. Deprecating the Observer Pattern with Scala.React A 2012 paper by Ingo RxJS, the Reactive Extensions library for "composing asynchronous [...] programs using observable sequences" Tackling the Awkward Squad for Reactive Programming: The Actor-Reactor Model A 2020 paper that proposes a model of "actors" and "reactors" to avoid the issues that arise when combining imperative code with reactive code.
https://en.wikipedia.org/wiki/Reactive_programming
glob() () is a libc function for globbing, which is the archetypal use of pattern matching against the names in a filesystem directory such that a name pattern is expanded into a list of names matching that pattern. Although globbing may now refer to glob()-style pattern matching of any string, not just expansion into a list of filesystem names, the original meaning of the term is still widespread. The glob() function and the underlying gmatch() function originated at Bell Labs in the early 1970s alongside the original AT&T UNIX itself and had a formative influence on the syntax of UNIX command line utilities and therefore also on the present-day reimplementations thereof. In their original form, glob() and gmatch() derived from code used in Bell Labs in-house utilities that developed alongside the original Unix in the early 1970s. Among those utilities were also two command line tools called glob and find; each could be used to pass a list of matching filenames to other command line tools, and they shared the backend code subsequently formalized as glob() and gmatch(). Shell-statement-level globbing by default became commonplace following the "builtin"-integration of globbing-functionality into the 7th edition of the Unix shell in 1978. The Unix shell's -f option to disable globbing — i.e. revert to literal "file" mode — appeared in the same version. The glob pattern quantifiers now standardized by POSIX.2 (IEEE Std 1003.2) fall into two groups, and can be applied to any character sequence ("string"), not just to directory entries. "Metacharacters" (also called "Wildcards"): ? (not in brackets) matches any character exactly once. * (not in brackets) matches a string of zero or more characters. "Ranges/sets": [...], where the first character within the brackets is not '!', matches any single character among the characters specified in the brackets. If the first character within brackets is '!', then the [!...] matches any single character that is not among the characters specified in the brackets. The characters in the brackets may be a list ([abc]) or a range ([a-c]) or denote a character class (like [[:space:]] where the inner brackets are part of the classname). POSIX does not mandate multi-range ([a-c0-3]) support, which derive originally from regular expressions. As reimplementations of Bell Labs' UNIX proliferated, so did reimplementations of its Bell Labs' libc and shell, and with them glob() and globbing. Today, glob() and globbing are standardized by the POSIX.2 specification and are integral part of every Unix-like libc ecosystem and shell, including AT&T Bourne shell-compatible Korn shell (ksh), Z shell (zsh), Almquist shell (ash) and its derivatives and reimplementations such as busybox, toybox, GNU bash, Debian dash. == Origin == The glob command, short for global, originates in the earliest versions of Bell Labs' Unix. The command interpreters of the early versions of Unix (1st through 6th Editions, 1969–1975) relied on a separate program to expand wildcard characters in unquoted arguments to a command: /etc/glob. That program performed the expansion and supplied the expanded list of file paths to the command for execution. Glob was originally written in the B programming language. It was the first piece of mainline Unix software to be developed in a high-level programming language. Later, this functionality was provided as a C library function, glob(), used by programs such as the shell. It is usually defined based on a function named fnmatch(), which tests for whether a string matches a given pattern - the program using this function can then iterate through a series of strings (usually filenames) to determine which ones match. Both functions are a part of POSIX: the functions defined in POSIX.1 since 2001, and the syntax defined in POSIX.2. The idea of defining a separate match function started with wildmat (wildcard match), a simple library to match strings against Bourne Shell globs. Traditionally, globs do not match hidden files in the form of Unix dotfiles; to match them the pattern must explicitly start with .. For example, * matches all visible files while .* matches all hidden files. == Syntax == The most common wildcards are *, ?, and […]. Normally, the path separator character (/ on Linux/Unix, MacOS, etc. or \ on Windows) will never be matched. Some shells, such as Unix shell have functionality allowing users to circumvent this. === Unix-like === On Unix-like systems *, ? is defined as above while […] has two additional meanings: The ranges are also allowed to include pre-defined character classes, equivalence classes for accented characters, and collation symbols for hard-to-type characters. They are defined to match up with the brackets in POSIX regular expressions. Unix globbing is handled by the shell per POSIX tradition. Globbing is provided on filenames at the command line and in shell scripts. The POSIX-mandated case statement in shells provides pattern-matching using glob patterns. Some shells (such as the C shell and Bash) support additional syntax known as alternation or brace expansion. Because it is not part of the glob syntax, it is not provided in case. It is only expanded on the command line before globbing. The Bash shell also supports the following extensions: Extended globbing (extglob): allows other pattern matching operators to be used to match multiple occurrences of a pattern enclosed in parentheses, essentially providing the missing kleene star and alternation for describing regular languages. It can be enabled by setting the extglob shell option. This option came from ksh93. The GNU fnmatch and glob has an identical extension. globstar: allows ** on its own as a name component to recursively match any number of layers of non-hidden directories. Also supported by the JavaScript libraries and Python's glob. === Windows and DOS === The original DOS was a clone of CP/M designed to work on Intel's 8088 and 8086 processors. Windows shells, following DOS, do not traditionally perform any glob expansion in arguments passed to external programs. Shells may use an expansion for their own builtin commands: Windows PowerShell has all the common syntax defined as stated above without any additions. COMMAND.COM and cmd.exe have most of the common syntax with some limitations: There is no […] and for COMMAND.COM the * may only appear at the end of the pattern. It can not appear in the middle of a pattern, except immediately preceding the filename extension separator dot. Windows and DOS programs receive a long command-line string instead of argv-style parameters, and it is their responsibility to perform any splitting, quoting, or glob expansion. There is technically no fixed way of describing wildcards in programs since they are free to do what they wish. Two common glob expanders include: The Microsoft C Runtime (msvcrt) command-line expander, which only supports ? and *. Both ReactOS (crt/misc/getargs.c) and Wine (msvcrt/data.c) contain a compatible open-source implementation of __getmainargs, the function operating under-the-hood, in their core CRT. The Cygwin and MSYS dcrt0.cc command-line expander, which uses the unix-style glob() routine under-the-hood, after splitting the arguments. Most other parts of Windows, including the Indexing Service, use the MS-DOS style of wildcards found in CMD. A relic of the 8.3 filename age, this syntax pays special attention to dots in the pattern and the text (filename). Internally this is done using three extra wildcard characters, <>". On the Windows API end, the glob() equivalent is FindFirstFile, and fnmatch() corresponds to its underlying RtlIsNameInExpression. (Another fnmatch analogue is PathMatchSpec.) Both open-source msvcrt expanders use FindFirstFile, so 8.3 filename quirks will also apply in them. === SQL === The SQL LIKE operator has an equivalent to ? and * but not […]. Standard SQL uses a glob-like syntax for simple string matching in its LIKE operator, although the term "glob" is not generally used in the SQL community. The percent sign (%) matches zero or more characters and the underscore (_) matches exactly one. Many implementations of SQL have extended the LIKE operator to allow a richer pattern-matching language, incorporating character ranges ([…]), their negation, and elements of regular expressions. == Compared to regular expressions == Globs do not include syntax for the Kleene star which allows multiple repetitions of the preceding part of the expression; thus they are not considered regular expressions, which can describe the full set of regular languages over any given finite alphabet. Globs attempt to match the entire string (for example, S*.DOC matches S.DOC and SA.DOC, but not POST.DOC or SURREY.DOCKS), whereas, depending on implementation details, regular expressions may match a substring. === Implementing as regular expressions === The original Mozilla proxy auto-config implementation, which provides a glob-matching function on strings, uses a replace-as-RegExp implementation as above. The bracket syntax happens to be covered by regex in such an example. Python's fnmatch uses a more elaborate procedure to transform the pattern into a regular expression. == Other implementations == Beyond their uses in shells, globs patterns also find use in a variety of programming languages, mainly to process human input. A glob-style interface for returning files or an fnmatch-style interface for matching strings are found in the following programming languages: C and C++ do not have built-in support for glob patterns in the ISO-defined standard libraries, however on Unix-like systems C and C++ may include <glob.h> from the C POSIX library to use glob(). C++ itself does not have direct support for glob patterns, however they may be approximated using the <filesystem> and <regex> headers, using std::filesystem::directory_iterator() and std::regex_match(). C# has multiple libraries available through NuGet such as Glob or DotNet.Glob. D has a globMatch function in the std.path module. JavaScript has a library called minimatch which is used internally by npm, and micromatch, a purportedly more optimized, accurate and safer globbing implementation used by Babel and yarn. Go has a Glob function in the filepath package. Java has a Files class in the package java.nio.file, containing methods that can operate on glob patterns. Haskell has a Glob package with the main module System.FilePath.Glob. The pattern syntax is based on a subset of Zsh's. It tries to optimize the given pattern and should be noticeably faster than a naïve character-by-character matcher. Perl has both a glob function (as discussed in Larry Wall's book Programming Perl) and a Glob extension which mimics the BSD glob routine. Perl's angle brackets can be used to glob as well: <*.log>. PHP has a glob function. Python has a glob module in the standard library which performs wildcard pattern matching on filenames, and an fnmatch module with functions for matching strings or filtering lists based on these same wildcard patterns. Guido van Rossum, author of the Python programming language, wrote and contributed a glob routine to BSD Unix in 1986. There were previous implementations of glob, e.g., in the ex and ftp programs in previous releases of BSD. Ruby has a glob method for the Dir class which performs wildcard pattern matching on filenames. Several libraries such as Rant and Rake provide a FileList class which has a glob method or use the method FileList.[] identically. Rust has multiple libraries that can match glob patterns, the most popular of these being the glob crate. SQLite has a GLOB function. Tcl contains a globbing facility. == See also == Regular expression Wildcard character Matching wildcards == References ==
https://en.wikipedia.org/wiki/Glob_(programming)
In computer programming, a directive or pragma (from "pragmatic") is a language construct that specifies how a compiler (or other translator) should process its input. Depending on the programming language, directives may or may not be part of the grammar of the language and may vary from compiler to compiler. They can be processed by a preprocessor to specify compiler behavior, or function as a form of in-band parameterization. In some cases directives specify global behavior, while in other cases they only affect a local section, such as a block of programming code. In some cases, such as some C programs, directives are optional compiler hints and may be ignored, but normally they are prescriptive and must be followed. However, a directive does not perform any action in the language itself, but rather only a change in the behavior of the compiler. This term could be used to refer to proprietary third-party tags and commands (or markup) embedded in code that result in additional executable processing that extend the existing compiler, assembler and language constructs present in the development environment. The term "directive" is also applied in a variety of ways that are similar to the term command. == The C preprocessor == In C and C++, the language supports a simple macro preprocessor. Source lines that should be handled by the preprocessor, such as #define and #include are referred to as preprocessor directives. Syntactic constructs similar to C's preprocessor directives, such as C#'s #if, are also typically called "directives", although in these cases there may not be any real preprocessing phase involved. All preprocessor commands, except for defined (when following a conditional directive), begin with a hash symbol (#). Until C++26, the keywords export, import and module were partially handled by the preprocessor. == History == Directives date to JOVIAL. COBOL has a COPY directive. In ALGOL 68, directives are known as pragmats (from "pragmatic"), and denoted pragmat or pr; in newer languages, notably C, this has been abbreviated to "pragma" (no 't'). A common use of pragmats in ALGOL 68 is in specifying a stropping regime, meaning "how keywords are indicated". Various such directives follow, specifying the POINT, UPPER, RES (reserved), or quote regimes. Note the use of stropping for the pragmat keyword itself (abbreviated pr), either in the POINT or quote regimes: Today directives are best known in the C language, of early 1970s vintage, and continued through the current C99 standard, where they are either instructions to the C preprocessor, or, in the form of #pragma, directives to the compiler itself. They are also used to some degree in more modern languages; see below. == Other languages == In Ada, compiler directives are called pragmas (short for "pragmatic information"). In Common Lisp, directives are called declarations, and are specified using the declare construct (also proclaim or declaim). With one exception, declarations are optional, and do not affect the semantics of the program. The one exception is special, which must be specified where appropriate. In Turbo Pascal, directives are called significant comments, because in the language grammar they follow the same syntax as comments. In Turbo Pascal, a significant comment is a comment whose first character is a dollar sign and whose second character is a letter; for example, the equivalent of C's #include "file" directive is the significant comment {$I "file"}. In Perl, the keyword "use", which imports modules, can also be used to specify directives, such as use strict; or use utf8;. Haskell pragmas are specified using a specialized comment syntax, e.g. {-# INLINE foo #-}. It is also possible to use the C preprocessor in Haskell, by writing {-# LANGUAGE CPP #-}. PHP uses the directive declare(strict_types=1). In PL/I, directives begin with a Percent sign (%) and end with a semicolon (;), e.g., %INCLUDE foo;, %NOPRINT;, %PAGE;, %POP;, %SKIP;, the same as with preprocessor statements. Python has two directives – from __future__ import feature (defined in PEP 236 -- Back to the __future__), which changes language features (and uses the existing module import syntax, as in Perl), and the coding directive (in a comment) to specify the encoding of a source code file (defined in PEP 263 -- Defining Python Source Code Encodings). A more general directive statement was proposed and rejected in PEP 244 -- The `directive' statement; these all date to 2001. ECMAScript also adopts the use syntax for directives, with the difference that pragmas are declared as string literals (e.g. "use strict";, or "use asm";), rather than a function call. In Visual Basic, the keyword "Option" is used for directives: Option Explicit On|Off - When on disallows implicit declaration of variables at first use requiring explicit declaration beforehand. Option Compare Binary - Results in string comparisons based on a sort order derived from the internal binary representations of the characters - e.g. for the English/European code page (ANSI 1252) A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø. Affects intrinsic operators (e.g. =, <>, <, >), the Select Case block, and VB runtime library string functions (e.g. InStr). Option Compare Text - Results in string comparisons based on a case-insensitive text sort order determined by your system's locale - e.g. for the English/European code page (ANSI 1252) (A=a) < (À = à) < (B=b) < (E=e) < (Ê = ê) < (Z=z) < (Ø = ø). Affects intrinsic operators (e.g. =, <>, <, >), the Select Case block, and VB runtime library string functions (e.g. InStr). Option Strict On|Off - When on disallows: typeless programming - where declarations which lack an explicit type are implicitly typed as Object. late-binding (i.e. dynamic dispatch to CLR, DLR, and COM objects) on values statically typed as Object. implicit narrowing conversions - requiring all conversions to narrower types (e.g. from Long to Integer, Object to String, Control to TextBox) be explicit in code using conversion operators (e.g. CInt, DirectCast, CType). Option Infer On|Off - When on enables the compiler to infer the type of local variables from their initializers. In Ruby, interpreter directives are referred to as pragmas and are specified by top-of-file comments that follow a key: value notation. For example, coding: UTF-8 indicates that the file is encoded via the UTF-8 character encoding. In C#, compiler directives are called pre-processing directives. C# does not technically handle these using a preprocessor, but rather directly in the code. There are a number of different compiler directives, which mostly align with those from C and C++, including #pragma, which is specifically used to control compiler warnings and debugger checksums. C# also features some directives not used in C or C++, including #nullable and #region. C# also does not allow function-like macros, but does allow regular macros, for purposes such as conditional compilation. The SQLite DBMS includes a PRAGMA directive that is used to introduce commands that are not compatible with other DBMS. In Solidity, compiler directives are called pragmas, and are specified using the `pragma` keyword. === Assembly language === In assembly language, directives, also referred to as pseudo-operations or "pseudo-ops", generally specify such information as the target machine, mark separations between code sections, define and change assembly-time variables, define macros, designate conditional and repeated code, define reserved memory areas, and so on. Some, but not all, assemblers use a specific syntax to differentiate pseudo-ops from instruction mnemonics, such as prefacing the pseudo-op with a period, such as the pseudo-op .END, which might direct the assembler to stop assembling code. === PL/SQL === Oracle Corporation's PL/SQL procedural language includes a set of compiler directives, known as "pragmas". == See also == #pragma once – Preprocessor directive in C and C++ == Footnotes == == References == == External links == OpenMP Website OpenACC Website OpenHMPP Website
https://en.wikipedia.org/wiki/Directive_(programming)
A symbol in computer programming is a primitive data type whose instances have a human-readable form. Symbols can be used as identifiers. In some programming languages, they are called atoms. Uniqueness is enforced by holding them in a symbol table. The most common use of symbols by programmers is to perform language reflection (particularly for callbacks), and the most common indirectly is their use to create object linkages. In the most trivial implementation, they are essentially named integers; e.g., the enumerated type in C language. == Support == The following programming languages provide runtime support for symbols: === Julia === Symbols in Julia are interned strings used to represent identifiers in parsed Julia code(ASTs) and as names or labels to identify entities (for example as keys in a dictionary). === Lisp === A symbol in Lisp is unique in a namespace (or package in Common Lisp). Symbols can be tested for equality with the function EQ. Lisp programs can generate new symbols at runtime. When Lisp reads data that contains textual represented symbols, existing symbols are referenced. If a symbol is unknown, the Lisp reader creates a new symbol. In Common Lisp, symbols have the following attributes: a name, a value, a function, a list of properties and a package. In Common Lisp it is also possible that a symbol is not interned in a package. Such symbols can be printed, but when read back, a new symbol needs to be created. Since it is not interned, the original symbol can not be retrieved from a package. In Common Lisp symbols may use any characters, including whitespace, such as spaces and newlines. If a symbol contains a whitespace character, it needs to be written as |this is a symbol|. Symbols can be used as identifiers for any kind of named programming constructs: variables, functions, macros, classes, types, goto tags and more. Symbols can be interned in a package. Keyword symbols are self-evaluating, and interned in the package named KEYWORD. ==== Examples ==== The following is a simple external representation of a Common Lisp symbol: Symbols can contain whitespace (and all other characters): In Common Lisp symbols with a leading colon in their printed representations are keyword symbols. These are interned in the keyword package. A printed representation of a symbol may include a package name. Two colons are written between the name of the package and the name of the symbol. Packages can export symbols. Then only one colon is written between the name of the package and the name of the symbol. Symbols, which are not interned in a package, can also be created and have a notation: === PostScript === In PostScript, references to name objects can be either literal or executable, influencing the behaviour of the interpreter when encountering them. The cvx and cvl operators can be used to convert between the two forms. When names are constructed from strings by means of the cvn operator, the set of allowed characters is unrestricted. === Prolog === In Prolog, symbols (or atoms) are the main primitive data types, similar to numbers. The exact notation may differ in different Prolog dialects. However, it is always quite simple (no quotations or special beginning characters are necessary). Contrary to many other languages, it is possible to give symbols a meaning by creating some Prolog facts and/or rules. ==== Examples ==== The following example demonstrates two facts (describing what father is) and one rule (describing the meaning of sibling). These three sentences use symbols (father, zeus, hermes, perseus and sibling) and some abstract variables (X, Y and Z). The mother relationship is omitted for clarity. === Ruby === In Ruby, symbols can be created with a literal form, or by converting a string. They can be used as an identifier or an interned string. Two symbols with the same contents will always refer to the same object. It is considered a best practice to use symbols as keys to an associative array in Ruby. ==== Examples ==== The following is a simple example of a symbol literal in Ruby: Strings can be coerced into symbols, vice versa: Symbols are objects of the Symbol class in Ruby: Symbols are commonly used to dynamically send messages to (call methods on) objects: Symbols as keys of an associative array: === Smalltalk === In Smalltalk, symbols can be created with a literal form, or by converting a string. They can be used as an identifier or an interned string. Two symbols with the same contents will always refer to the same object. In most Smalltalk implementations, selectors (method names) are implemented as symbols. ==== Examples ==== The following is a simple example of a symbol literal in Smalltalk: Strings can be coerced into symbols, vice versa: Symbols conform to the symbol protocol, and their class is called Symbol in most implementations: Symbols are commonly used to dynamically send messages to (call methods on) objects: == References ==
https://en.wikipedia.org/wiki/Symbol_(programming)
A "Hello, World!" program is usually a simple computer program that emits (or displays) to the screen (often the console) a message similar to "Hello, World!". A small piece of code in most general-purpose programming languages, this program is used to illustrate a language's basic syntax. Such a program is often the first written by a student of a new programming language, but it can also be used as a sanity check to ensure that the computer software intended to compile or run source code is correctly installed, and that its operator understands how to use it. == History == While several small test programs have existed since the development of programmable computers, the tradition of using the phrase "Hello, World!" as a test message was influenced by an example program in the 1978 book The C Programming Language, with likely earlier use in BCPL. The example program from the book prints "hello, world", and was inherited from a 1974 Bell Laboratories internal memorandum by Brian Kernighan, Programming in C: A Tutorial: In the above example, the main( ) function defines where the program should start executing. The function body consists of a single statement, a call to the printf() function, which stands for "print formatted"; it outputs to the console whatever is passed to it as the parameter, in this case the string "hello, world". The C-language version was preceded by Kernighan's own 1972 A Tutorial Introduction to the Language B, where the first known version of the program is found in an example used to illustrate external variables: The program above prints hello, world! on the terminal, including a newline character. The phrase is divided into multiple variables because in B a character constant is limited to four ASCII characters. The previous example in the tutorial printed hi! on the terminal, and the phrase hello, world! was introduced as a slightly longer greeting that required several character constants for its expression. The Jargon File reports that "hello, world" instead originated in 1967 with the language BCPL. Outside computing, use of the exact phrase began over a decade prior; it was the catchphrase of New York radio disc jockey William B. Williams beginning in the 1950s. == Variations == "Hello, World!" programs vary in complexity between different languages. In some languages, particularly scripting languages, the "Hello, World!" program can be written as one statement, while in others (more so many low-level languages) many more statements can be required. For example, in Python, to print the string Hello, World! followed by a newline, one only needs to write print("Hello, World!"). In contrast, the equivalent code in C++ requires the import of the input/output (I/O) software library, the manual declaration of an entry point, and the explicit instruction that the output string should be sent to the standard output stream. The phrase "Hello, World!" has seen various deviations in casing and punctuation, such as "hello world" which lacks the capitalization of the leading H and W, and the presence of the comma or exclamation mark. Some devices limit the format to specific variations, such as all-capitalized versions on systems that support only capital letters, while some esoteric programming languages may have to print a slightly modified string. Other human languages have been used as the output; for example, a tutorial for the Go language emitted both English and Chinese or Japanese characters, demonstrating the language's built-in Unicode support. Another notable example is the Rust language, whose management system automatically inserts a "Hello, World" program when creating new projects. Some languages change the function of the "Hello, World!" program while maintaining the spirit of demonstrating a simple example. Functional programming languages, such as Lisp, ML, and Haskell, tend to substitute a factorial program for "Hello, World!", as functional programming emphasizes recursive techniques, whereas the original examples emphasize I/O, which violates the spirit of pure functional programming by producing side effects. Languages otherwise able to print "Hello, World!" (assembly language, C, VHDL) may also be used in embedded systems, where text output is either difficult (requiring added components or communication with another computer) or nonexistent. For devices such as microcontrollers, field-programmable gate arrays, and complex programmable logic devices (CPLDs), "Hello, World!" may thus be substituted with a blinking light-emitting diode (LED), which demonstrates timing and interaction between components. The Debian and Ubuntu Linux distributions provide the "Hello, World!" program through their software package manager systems, which can be invoked with the command hello. It serves as a sanity check and a simple example of installing a software package. For developers, it provides an example of creating a .deb package, either traditionally or using debhelper, and the version of hello used, GNU Hello, serves as an example of writing a GNU program. Variations of the "Hello, World!" program that produce a graphical output (as opposed to text output) have also been shown. Sun demonstrated a "Hello, World!" program in Java based on scalable vector graphics, and the XL programming language features a spinning Earth "Hello, World!" using 3D computer graphics. Mark Guzdial and Elliot Soloway have suggested that the "hello, world" test message may be outdated now that graphics and sound can be manipulated as easily as text. In computer graphics, rendering a triangle – called "Hello Triangle" – is sometimes used as an introductory example for graphics libraries. == Time to Hello World == "Time to hello world" (TTHW) is the time it takes to author a "Hello, World!" program in a given programming language. This is one measure of a programming language's ease of use. Since the program is meant as an introduction for people unfamiliar with the language, a more complex "Hello, World!" program may indicate that the programming language is less approachable. For instance, the first publicly known "Hello, World!" program in Malbolge (which actually output "HEllO WORld") took two years to be announced, and it was produced not by a human but by a code generator written in Common Lisp (see § Variations, above). The concept has been extended beyond programming languages to APIs, as a measure of how simple it is for a new developer to get a basic example working; a shorter time indicates an easier API for developers to adopt. == Wikipedia articles containing "Hello, World!" programs == == See also == "99 Bottles of Beer" as used in computer science Bad Apple!! § Use of video as a graphical and audio test (graphic equivalent to "Hello, World!" for old hardware) Foobar Java Pet Store Just another Perl hacker Outline of computer science TPK algorithm Coding == References == == External links == The Hello World Collection "Hello world/Text". Rosetta Code. 23 May 2024. "GitHub – leachim6/hello-world: Hello world in every computer language. Thanks to everyone who contributes to this, make sure to see CONTRIBUTING.md for contribution instructions!". GitHub. 30 October 2021. "Unsung Heroes of IT: Part One: Brian Kernighan". TheUnsungHeroesOfIT.com. Archived from the original on 26 March 2016. Retrieved 23 August 2014.
https://en.wikipedia.org/wiki/%22Hello,_World!%22_program
Probabilistic programming (PP) is a programming paradigm based on the declarative specification of probabilistic models, for which inference is performed automatically. Probabilistic programming attempts to unify probabilistic modeling and traditional general purpose programming in order to make the former easier and more widely applicable. It can be used to create systems that help make decisions in the face of uncertainty. Programming languages following the probabilistic programming paradigm are referred to as "probabilistic programming languages" (PPLs). == Applications == Probabilistic reasoning has been used for a wide variety of tasks such as predicting stock prices, recommending movies, diagnosing computers, detecting cyber intrusions and image detection. However, until recently (partially due to limited computing power), probabilistic programming was limited in scope, and most inference algorithms had to be written manually for each task. Nevertheless, in 2015, a 50-line probabilistic computer vision program was used to generate 3D models of human faces based on 2D images of those faces. The program used inverse graphics as the basis of its inference method, and was built using the Picture package in Julia. This made possible "in 50 lines of code what used to take thousands". The Gen probabilistic programming library (also written in Julia) has been applied to vision and robotics tasks. More recently, the probabilistic programming system Turing.jl has been applied in various pharmaceutical and economics applications. Probabilistic programming in Julia has also been combined with differentiable programming by combining the Julia package Zygote.jl with Turing.jl. Probabilistic programming languages are also commonly used in Bayesian cognitive science to develop and evaluate models of cognition. == Probabilistic programming languages == PPLs often extend from a basic language. For instance, Turing.jl is based on Julia, Infer.NET is based on .NET Framework, while PRISM extends from Prolog. However, some PPLs, such as WinBUGS, offer a self-contained language that maps closely to the mathematical representation of the statistical models, with no obvious origin in another programming language. The language for WinBUGS was implemented to perform Bayesian computation using Gibbs Sampling and related algorithms. Although implemented in a relatively unknown programming language (Component Pascal), this language permits Bayesian inference for a wide variety of statistical models using a flexible computational approach. The same BUGS language may be used to specify Bayesian models for inference via different computational choices ("samplers") and conventions or defaults, using a standalone program WinBUGS (or related R packages, rbugs and r2winbugs) and JAGS (Just Another Gibbs Sampler, another standalone program with related R packages including rjags, R2jags, and runjags). More recently, other languages to support Bayesian model specification and inference allow different or more efficient choices for the underlying Bayesian computation, and are accessible from the R data analysis and programming environment, e.g.: Stan, NIMBLE and NUTS. The influence of the BUGS language is evident in these later languages, which even use the same syntax for some aspects of model specification. Several PPLs are in active development, including some in beta test. Two popular tools are Stan and PyMC. === Relational === A probabilistic relational programming language (PRPL) is a PPL specially designed to describe and infer with probabilistic relational models (PRMs). A PRM is usually developed with a set of algorithms for reducing, inference about and discovery of concerned distributions, which are embedded into the corresponding PRPL. === Probabilistic logic programming === Probabilistic logic programming is a programming paradigm that extends logic programming with probabilities. Most approaches to probabilistic logic programming are based on the distribution semantics, which splits a program into a set of probabilistic facts and a logic program. It defines a probability distribution on interpretations of the Herbrand universe of the program. === List of probabilistic programming languages === This list summarises the variety of PPLs that are currently available, and clarifies their origins. == Difficulty == Reasoning about variables as probability distributions causes difficulties for novice programmers, but these difficulties can be addressed through use of Bayesian network visualizations and graphs of variable distributions embedded within the source code editor. As many PPLs rely on the specification of priors on the variables of interest, specifying informed priors is often difficult for novices. In some cases, libraries such as PyMC provide automated methods to find the parameterization of informed priors. == See also == Statistical relational learning Inductive programming Bayesian programming Plate notation == Notes == == External links == Foundations of Probabilistic Programming List of Probabilistic Model Mini Language Toolkits
https://en.wikipedia.org/wiki/Probabilistic_programming
Offensive programming is a name used for the branch of defensive programming that expressly departs from defensive principles when dealing with errors resulting from software bugs. Although the name is a reaction to extreme interpretations of defensive programming, the two are not fundamentally in conflict. Rather, offensive programming adds an explicit priority of not tolerating errors in wrong places: the point where it departs from extreme interpretations of defensive programming is in preferring the presence of errors from within the program's line of defense to be blatantly obvious over the hypothetical safety benefit of tolerating them. This preference is also what justifies using assertions. == Distinguishing errors == The premise for offensive programming is to distinguish between expectable errors, coming from outside the program's line of defense, however improbable, versus preventable internal errors that shall not happen if all its software components behave as expected. Contrasting examples: == Bug detection strategies == Offensive programming is concerned with failing, so to disprove the programmer's assumptions. Producing an error message may be a secondary goal. Strategies: No unnecessary checks: Trusting that other software components behave as specified, so to not paper over any unknown problem, is the basic principle. In particular, some errors may already be guaranteed to crash the program (depending on programming language or running environment), for example dereferencing a null pointer. As such, null pointer checks are unnecessary for the purpose of stopping the program (but can be used to print error messages). Assertions – checks that can be disabled – are the preferred way to check things that should be unnecessary to check, such as design contracts between software components. Remove fallback code (limp mode) and fallback data (default values): These can hide defects in the main implementation, or, from the user point of view, hide the fact that the software is working suboptimally. Special attention to unimplemented parts may be needed as part of factory acceptance testing, as yet unimplemented code is at no stage of test driven development discoverable by failing unit tests. Remove shortcut code (see the strategy pattern): A simplified code path may hide bugs in a more generic code path if the generic code almost never gets to run. Since the two are supposed to produce the same result, the simplified one can be eliminated. == See also == Fail-fast system == References ==
https://en.wikipedia.org/wiki/Offensive_programming
Neuro-linguistic programming (NLP) is a pseudoscientific approach to communication, personal development, and psychotherapy that first appeared in Richard Bandler and John Grinder's book The Structure of Magic I (1975). NLP asserts a connection between neurological processes, language, and acquired behavioral patterns, and that these can be changed to achieve specific goals in life. According to Bandler and Grinder, NLP can treat problems such as phobias, depression, tic disorders, psychosomatic illnesses, near-sightedness, allergy, the common cold, and learning disorders, often in a single session. They also say that NLP can model the skills of exceptional people, allowing anyone to acquire them. NLP has been adopted by some hypnotherapists as well as by companies that run seminars marketed as leadership training to businesses and government agencies. No scientific evidence supports the claims made by NLP advocates, and it has been called a pseudoscience. Scientific reviews have shown that NLP is based on outdated metaphors of the brain's inner workings that are inconsistent with current neurological theory, and that NLP contains numerous factual errors. Reviews also found that research that favored NLP contained significant methodological flaws, and that three times as many studies of a much higher quality failed to reproduce the claims made by Bandler, Grinder, and other NLP practitioners. == Early development == According to Bandler and Grinder, NLP consists of a methodology termed modeling, plus a set of techniques that they derived from its initial applications. They derived many of the fundamental techniques from the work of Virginia Satir, Milton Erickson and Fritz Perls. Bandler and Grinder also drew upon the theories of Gregory Bateson, and Noam Chomsky (particularly transformational grammar). Bandler and Grinder say that their methodology can codify the structure inherent to the therapeutic "magic" as performed in therapy by Perls, Satir and Erickson, and indeed inherent to any complex human activity. From that codification, they say, the structure and its activity can be learned by others. Their 1975 book, The Structure of Magic I: A Book about Language and Therapy, is intended to be a codification of the therapeutic techniques of Perls and Satir. Bandler and Grinder say that they used their own process of modeling to model Virginia Satir so they could produce what they termed the Meta-Model, a model for gathering information and challenging a client's language and underlying thinking. They say that by challenging linguistic distortions, specifying generalizations, and recovering deleted information in the client's statements, the transformational grammar concept of surface structure yields a more complete representation of the underlying deep structure and therefore has therapeutic benefit. Also derived from Satir were anchoring, future pacing and representational systems. In contrast, the Milton-Model—a model of the purportedly hypnotic language of Milton Erickson—was described by Bandler and Grinder as "artfully vague" and metaphoric. The Milton-Model is used in combination with the Meta-Model as a softener, to induce "trance" and to deliver indirect therapeutic suggestion. Psychologist Jean Mercer writes that Chomsky's theories "appear to be irrelevant" to NLP. Linguist Karen Stollznow describes Bandler's and Grinder's reference to such experts as namedropping. Other than Satir, the people they cite as influences did not collaborate with Bandler or Grinder. Chomsky himself has no association with NLP, with his work being theoretical in nature and having no therapeutic element. Stollznow writes, "[o]ther than borrowing terminology, NLP does not bear authentic resemblance to any of Chomsky's theories or philosophies—linguistic, cognitive or political." According to André Muller Weitzenhoffer, a researcher in the field of hypnosis, "the major weakness of Bandler and Grinder's linguistic analysis is that so much of it is built upon untested hypotheses and is supported by totally inadequate data." Weitzenhoffer adds that Bandler and Grinder misuse formal logic and mathematics, redefine or misunderstand terms from the linguistics lexicon (e.g., nominalization), create a scientific façade by needlessly complicating Ericksonian concepts with unfounded claims, make factual errors, and disregard or confuse concepts central to the Ericksonian approach. More recently, Bandler has stated, "NLP is based on finding out what works and formalizing it. In order to formalize patterns I utilized everything from linguistics to holography ... The models that constitute NLP are all formal models based on mathematical, logical principles such as predicate calculus and the mathematical equations underlying holography." There is no mention of the mathematics of holography nor of holography in general in Spitzer's, or Grinder's account of the development of NLP. On the matter of the development of NLP, Grinder recollects: My memories about what we thought at the time of discovery (with respect to the classic code we developed—that is, the years 1973 through 1978) are that we were quite explicit that we were out to overthrow a paradigm and that, for example, I, for one, found it very useful to plan this campaign using in part as a guide the excellent work of Thomas Kuhn (The Structure of Scientific Revolutions) in which he detailed some of the conditions which historically have obtained in the midst of paradigm shifts. For example, I believe it was very useful that neither one of us were qualified in the field we first went after—psychology and in particular, its therapeutic application; this being one of the conditions which Kuhn identified in his historical study of paradigm shifts. The philosopher Robert Todd Carroll responded that Grinder has not understood Kuhn's text on the history and philosophy of science, The Structure of Scientific Revolutions. Carroll replies: (a) individual scientists never have nor are they ever able to create paradigm shifts volitionally and Kuhn does not suggest otherwise; (b) Kuhn's text does not contain the idea that being unqualified in a field of science is a prerequisite to producing a result that necessitates a paradigm shift in that field and (c) The Structure of Scientific Revolutions is foremost a work of history and not an instructive text on creating paradigm shifts and such a text is not possible—extraordinary discovery is not a formulaic procedure. Carroll explains that a paradigm shift is not a planned activity, rather it is an outcome of scientific effort within the dominant paradigm that produces data that cannot be adequately accounted for within the current paradigm—hence a paradigm shift, i.e. the adoption of a new paradigm. In developing NLP, Bandler and Grinder were not responding to a paradigmatic crisis in psychology nor did they produce any data that caused a paradigmatic crisis in psychology. There is no sense in which Bandler and Grinder caused or participated in a paradigm shift. "What did Grinder and Bandler do that makes it impossible to continue doing psychology ... without accepting their ideas? Nothing," argues Carroll. === Commercialization and evaluation === By the late 1970s, the human potential movement had developed into an industry and provided a market for some NLP ideas. At the center of this growth was the Esalen Institute at Big Sur, California. Perls had led numerous Gestalt therapy seminars at Esalen. Satir was an early leader and Bateson was a guest teacher. Bandler and Grinder have said that in addition to being a therapeutic method, NLP was also a study of communication and began marketing it as a business tool, writing that, "if any human being can do anything, so can you." After 150 students paid $1,000 each for a ten-day workshop in Santa Cruz, California, Bandler and Grinder gave up academic writing and started producing popular books from seminar transcripts, such as Frogs into Princes, which sold more than 270,000 copies. According to court documents relating to an intellectual property dispute between Bandler and Grinder, Bandler made more than $800,000 in 1980 from workshop and book sales. A community of psychotherapists and students began to form around Bandler and Grinder's initial works, leading to the growth and spread of NLP as a theory and practice. For example, Tony Robbins trained with Grinder and utilized a few ideas from NLP as part of his own self-help and motivational speaking programmes. Bandler led several unsuccessful efforts to exclude other parties from using NLP. Meanwhile, the rising number of practitioners and theorists led NLP to become even less uniform than it was at its foundation. Prior to the decline of NLP, scientific researchers began testing its theoretical underpinnings empirically, with research indicating a lack of empirical support for NLP's essential theories. The 1990s were characterized by fewer scientific studies evaluating the methods of NLP than the previous decade. Tomasz Witkowski attributes this to a declining interest in the debate as the result of a lack of empirical support for NLP from its proponents. == Main components and core concepts == NLP can be understood in terms of three broad components: subjectivity, consciousness, and learning. According to Bandler and Grinder, people experience the world subjectively, creating internal representations of their experiences. These representations involve the five senses and language. In other words, our conscious experiences take the form of sights, sounds, feelings, smells, and tastes. When we imagine something, recall an event, or think about the future, we utilize these same sensory systems within our minds Furthermore it is stated that these subjective representations of experience have a discernible structure, a pattern. Bandler and Grinder assert that behavior (both our own and others') can be understood through these sensory-based internal representations. Behavior here includes verbal and non-verbal communication, as well as effective or adaptive behaviors and less helpful or "pathological" ones. They also assert that behavior in both the self and other people can be modified by manipulating these sense-based subjective representations. NLP posits that consciousness can be divided into conscious and unconscious components. The part of our internal representations operating outside our direct awareness is referred to as the "unconscious mind". Finally, NLP uses a method of learning called "modeling", designed to replicate expertise in any field. According to Bandler and Grinder, by analyzing the sequence of sensory and linguistic representations used by an expert while performing a skill, it's possible to create a mental model that can be learned by others. == Techniques or set of practices == According to one study by Steinbach, a classic interaction in NLP can be understood in terms of several major stages including establishing rapport, gleaning information about a problem mental state and desired goals, using specific tools and techniques to make interventions, and integrating proposed changes into the client's life. The entire process is guided by the non-verbal responses of the client. The first is the act of establishing and maintaining rapport between the practitioner and the client which is achieved through pacing and leading the verbal (e.g., sensory predicates and keywords) and non-verbal behavior (e.g., matching and mirroring non-verbal behavior, or responding to eye movements) of the client. Once rapport is established, the practitioner may gather information about the client's present state as well as help the client define a desired state or goal for the interaction. The practitioner pays attention to the verbal and non-verbal responses as the client defines the present state and desired state and any resources that may be required to bridge the gap. The client is typically encouraged to consider the consequences of the desired outcome, and how they may affect his or her personal or professional life and relationships, taking into account any positive intentions of any problems that may arise. The practitioner thereafter assists the client in achieving the desired outcomes by using certain tools and techniques to change internal representations and responses to stimuli in the world. Finally, the practitioner helps the client to mentally rehearse and integrate the changes into his or her life. For example, the client may be asked to envision what it is like having already achieved the outcome. According to Stollznow, "NLP also involves fringe discourse analysis and 'practical' guidelines for 'improved' communication. For example, one text asserts 'when you adopt the "but" word, people will remember what you said afterwards. With the "and" word, people remember what you said before and after.'" == Applications == === Alternative medicine === NLP has been promoted as being able to treat a variety of diseases including Parkinson's disease, HIV/AIDS and cancer. Such claims have no supporting medical evidence. People who use NLP as a form of treatment risk serious adverse health consequences as it can delay the provision of effective medical care. === Psychotherapeutic === Early books about NLP had a psychotherapeutic focus given that the early models were psychotherapists. As an approach to psychotherapy, NLP shares similar core assumptions and foundations in common with some contemporary brief and systemic practices, such as solution focused brief therapy. NLP has also been acknowledged as having influenced these practices with its reframing techniques which seeks to achieve behavior change by shifting its context or meaning, for example, by finding the positive connotation of a thought or behavior. The two main therapeutic uses of NLP are, firstly, as an adjunct by therapists practicing in other therapeutic disciplines and, secondly, as a specific therapy called Neurolinguistic Psychotherapy. According to Stollznow, "Bandler and Grinder's infamous Frogs into Princes and their other books boast that NLP is a cure-all that treats a broad range of physical and mental conditions and learning difficulties, including epilepsy, myopia and dyslexia. With its promises to cure schizophrenia, depression and Post Traumatic Stress Disorder, and its dismissal of psychiatric illnesses as psychosomatic, NLP shares similarities with Scientology and the Citizens Commission on Human Rights (CCHR)." A systematic review of experimental studies by Sturt et al. (2012) concluded that "there is little evidence that NLP interventions improve health-related outcomes." In his review of NLP, Stephen Briers writes, "NLP is not really a cohesive therapy but a ragbag of different techniques without a particularly clear theoretical basis ... [and its] evidence base is virtually non-existent." Eisner writes, "NLP appears to be a superficial and gimmicky approach to dealing with mental health problems. Unfortunately, NLP appears to be the first in a long line of mass marketing seminars that purport to virtually cure any mental disorder ... it appears that NLP has no empirical or scientific support as to the underlying tenets of its theory or clinical effectiveness. What remains is a mass-marketed serving of psychopablum." André Muller Weitzenhoffer—a friend and peer of Milton Erickson—wrote, "Has NLP really abstracted and explicated the essence of successful therapy and provided everyone with the means to be another Whittaker, Virginia Satir, or Erickson? ... [NLP's] failure to do this is evident because today there is no multitude of their equals, not even another Whittaker, Virginia Satir, or Erickson. Ten years should have been sufficient time for this to happen. In this light, I cannot take NLP seriously ... [NLP's] contributions to our understanding and use of Ericksonian techniques are equally dubious. Patterns I and II are poorly written works that were an overambitious, pretentious effort to reduce hypnotism to a magic of words." Clinical psychologist Stephen Briers questions the value of the NLP maxim—a presupposition in NLP jargon—"there is no failure, only feedback". Briers argues that the denial of the existence of failure diminishes its instructive value. He offers Walt Disney, Isaac Newton and J.K. Rowling as three examples of unambiguous acknowledged personal failure that served as an impetus to great success. According to Briers, it was "the crash-and-burn type of failure, not the sanitised NLP Failure Lite, i.e. the failure-that-isn't really-failure sort of failure" that propelled these individuals to success. Briers contends that adherence to the maxim leads to self-deprecation. According to Briers, personal endeavour is a product of invested values and aspirations and the dismissal of personally significant failure as mere feedback effectively denigrates what one values. Briers writes, "Sometimes we need to accept and mourn the death of our dreams, not just casually dismiss them as inconsequential." Briers also contends that the NLP maxim is narcissistic, self-centered and divorced from notions of moral responsibility. === Other uses === Although the original core techniques of NLP were therapeutic in orientation their generic nature enabled them to be applied to other fields. These applications include persuasion, sales, negotiation, management training, sports, teaching, coaching, team building, public speaking, and in the process of hiring employees. == Scientific criticism == In the early 1980s, NLP was advertised as an important advance in psychotherapy and counseling, and attracted some interest in counseling research and clinical psychology. However, as controlled trials failed to show any benefit from NLP and its advocates made increasingly dubious claims, scientific interest in NLP faded. Numerous literature reviews and meta-analyses have failed to show evidence for NLP's assumptions or effectiveness as a therapeutic method. While some NLP practitioners have argued that the lack of empirical support is due to insufficient research which tests NLP, the consensus scientific opinion is that NLP is pseudoscience and that attempts to dismiss the research findings based on these arguments "[constitute]s an admission that NLP does not have an evidence base and that NLP practitioners are seeking a post-hoc credibility." Surveys in the academic community have shown NLP to be widely discredited among scientists. Among the reasons for considering NLP a pseudoscience are that evidence in favor of it is limited to anecdotes and personal testimony that it is not informed by scientific understanding of neuroscience and linguistics, and that the name "neuro-linguistic programming" uses jargon words to impress readers and obfuscate ideas, whereas NLP itself does not relate any phenomena to neural structures and has nothing in common with linguistics or programming. In education, NLP has been used as a key example of pseudoscience. == As a quasi-religion == Sociologists and anthropologists have categorized NLP as a quasi-religion belonging to the New Age and/or Human Potential Movements. Medical anthropologist Jean M. Langford categorizes NLP as a form of folk magic; that is to say, a practice with symbolic efficacy—as opposed to physical efficacy—that is able to effect change through nonspecific effects (e.g., placebo). To Langford, NLP is akin to a syncretic folk religion "that attempts to wed the magic of folk practice to the science of professional medicine". Bandler and Grinder were influenced by the shamanism described in the books of Carlos Castaneda. Concepts like "double induction" and "stopping the world", central to NLP modeling, were incorporated from these influences. Some theorists characterize NLP as a type of "psycho-shamanism", and its focus on modeling has been compared to ritual practices in certain syncretic religions. The emphasis on lineage from an NLP guru has also been likened to similar concepts in some Eastern religions. Aupers, Houtman, and Bovbjerg identify NLP as a New Age "psycho-religion". Bovbjerg argues that New Age movements center on a transcendent "other". While monotheistic religions seek communion with a divine being, this focus shifts inward in these movements, with the "other" becoming the unconscious self. Bovbjerg posits that this emphasis on the unconscious and its hidden potential underlies NLP techniques promoting self-perfection through ongoing transformation. Bovbjerg's secular critique echoes the conservative Christian perspective, as exemplified by David Jeremiah. He argues that NLP's emphasis on self-transformation and internal power conflicts with the Christian belief in salvation through divine grace. == Legal disputes == === Founding, initial disputes, and settlement (1979–1981) === In 1979, Richard Bandler and John Grinder established the Society of Neuro-Linguistic Programming (NLP) to manage commercial applications of NLP, including training, materials, and certification. The founding agreement conferred exclusive rights to profit from NLP training and certification upon Bandler's corporate entity, Not Ltd. Around November 1980, Bandler and Grinder had ceased collaboration for undisclosed reasons. On September 25, 1981, Bandler filed suit against Grinder's corporate entity, Unlimited Ltd., in the Superior Court of California, County of Santa Cruz seeking injunctive relief and damages arising from Grinder's NLP-related commercial activities; the Court issued a judgment in Bandler's favor on October 29, 1981. The subsequent settlement agreement granted Grinder a 10-year license to conduct NLP seminars, offer NLP certification, and utilize the NLP name, subject to royalty payments to Bandler. === Further litigation and consequences (1996–2000) === Bandler commenced further civil actions against Unlimited Ltd., various figures within the NLP community, and 200 initially unnamed defendants in July 1996 and January 1997. Bandler alleged violations of the initial settlement terms by Grinder and sought damages of no less than US$10,000,000.00 from each defendant. In February 2000, the Court ruled against Bandler. The judgment asserted that Bandler had misrepresented his exclusive ownership of NLP intellectual property and sole authority over Society of NLP membership and certification. === Trademark revocation (1997) === In December 1997, a separate civil proceeding initiated by Tony Clarkson resulted in the revocation of Bandler's UK trademark of NLP. The Court ruled in Clarkson's favor. === Resolution and legacy (2000) === Bandler and Grinder reached a settlement in late 2000, acknowledging their status as co-creators and co-founders of NLP and committing to refrain from disparaging one another's NLP-related endeavors. Due to these disputes and settlements, the terms "NLP" and "neuro-linguistic programming" remain in the public domain. No single party holds exclusive rights, and there are no restrictions on offering NLP certifications. The designations "NLP" and "neuro-linguistic programming" are not owned, trademarked, or subject to centralized regulation. Consequently, there are no restrictions on individuals self-identifying as "NLP master practitioners" or "NLP master trainers". This decentralization has led to numerous certifying associations. === Decentralization and criticism === This lack of centralized control means there is no single standard for NLP practice or training. Practitioners can market their own methodologies, leading to inconsistencies within the field. This has been a source of criticism, highlighted by an incident in 2009 where a British television presenter registered his cat with the British Board of Neuro Linguistic Programming (BBNLP), demonstrating the organization's lax credentialing. Critics like Karen Stollznow find irony in the initial legal battles between Bandler and Grinder, considering their failure to apply their own NLP principles to resolve their conflict. Others, such as Grant Devilly, characterize NLP associations as "granfalloons"—a term implying a lack of unifying principles or a shared sense of purpose. == See also == Avatar Course Family systems therapy Frank Farrelly List of New Age topics List of unproven and disproven cancer treatments Solution-focused brief therapy Notable practitioners Steve Andreas Paul McKenna == Notes == == References == === Citations === === Works cited === Primary sources Secondary sources == Further reading == == External links == The dictionary definition of Neuro-linguistic programming at Wiktionary Media related to Neuro-linguistic programming at Wikimedia Commons Quotations related to Neuro-linguistic programming at Wikiquote
https://en.wikipedia.org/wiki/Neuro-linguistic_programming
Literate programming is a programming paradigm introduced in 1984 by Donald Knuth in which a computer program is given as an explanation of how it works in a natural language, such as English, interspersed (embedded) with snippets of macros and traditional source code, from which compilable source code can be generated. The approach is used in scientific computing and in data science routinely for reproducible research and open access purposes. Literate programming tools are used by millions of programmers today. The literate programming paradigm, as conceived by Donald Knuth, represents a move away from writing computer programs in the manner and order imposed by the compiler, and instead gives programmers macros to develop programs in the order demanded by the logic and flow of their thoughts. Literate programs are written as an exposition of logic in more natural language in which macros are used to hide abstractions and traditional source code, more like the text of an essay. Literate programming (LP) tools are used to obtain two representations from a source file: one understandable by a compiler or interpreter, the "tangled" code, and another for viewing as formatted documentation, which is said to be "woven" from the literate source. While the first generation of literate programming tools were computer language-specific, the later ones are language-agnostic and exist beyond the individual programming languages. == History and philosophy == Literate programming was first introduced in 1984 by Donald Knuth, who intended it to create programs that were suitable literature for human beings. He implemented it at Stanford University as a part of his research on algorithms and digital typography. The implementation was called "WEB" since he believed that it was one of the few three-letter words of English that had not yet been applied to computing. However, it resembles the complicated nature of software delicately pieced together from simple materials. The practice of literate programming has seen an important resurgence in the 2010s with the use of computational notebooks, especially in data science. == Concept == Literate programming is writing out the program logic in a human language with included (separated by a primitive markup) code snippets and macros. Macros in a literate source file are simply title-like or explanatory phrases in a human language that describe human abstractions created while solving the programming problem, and hiding chunks of code or lower-level macros. These macros are similar to the algorithms in pseudocode typically used in teaching computer science. These arbitrary explanatory phrases become precise new operators, created on the fly by the programmer, forming a meta-language on top of the underlying programming language. A preprocessor is used to substitute arbitrary hierarchies, or rather "interconnected 'webs' of macros", to produce the compilable source code with one command ("tangle"), and documentation with another ("weave"). The preprocessor also provides an ability to write out the content of the macros and to add to already created macros in any place in the text of the literate program source file, thereby disposing of the need to keep in mind the restrictions imposed by traditional programming languages or to interrupt the flow of thought. === Advantages === According to Knuth, literate programming provides higher-quality programs, since it forces programmers to explicitly state the thoughts behind the program, making poorly thought-out design decisions more obvious. Knuth also claims that literate programming provides a first-rate documentation system, which is not an add-on, but is grown naturally in the process of exposition of one's thoughts during a program's creation. The resulting documentation allows the author to restart their own thought processes at any later time, and allows other programmers to understand the construction of the program more easily. This differs from traditional documentation, in which a programmer is presented with source code that follows a compiler-imposed order, and must decipher the thought process behind the program from the code and its associated comments. The meta-language capabilities of literate programming are also claimed to facilitate thinking, giving a higher "bird's eye view" of the code and increasing the number of concepts the mind can successfully retain and process. Applicability of the concept to programming on a large scale, that of commercial-grade programs, is proven by an edition of TeX code as a literate program. Knuth also claims that literate programming can lead to easy porting of software to multiple environments, and even cites the implementation of TeX as an example. === Contrast with documentation generation === Literate programming is very often misunderstood to refer only to formatted documentation produced from a common file with both source code and comments – which is properly called documentation generation – or to voluminous commentaries included with code. This is the converse of literate programming: well-documented code or documentation extracted from code follows the structure of the code, with documentation embedded in the code; while in literate programming, code is embedded in documentation, with the code following the structure of the documentation. This misconception has led to claims that comment-extraction tools, such as the Perl Plain Old Documentation or Java Javadoc systems, are "literate programming tools". However, because these tools do not implement the "web of abstract concepts" hiding behind the system of natural-language macros, or provide an ability to change the order of the source code from a machine-imposed sequence to one convenient to the human mind, they cannot properly be called literate programming tools in the sense intended by Knuth. == Workflow == Implementing literate programming consists of two steps: Weaving: Generating a comprehensive document about the program and its maintenance. Tangling: Generating machine executable code Weaving and tangling are done on the same source so that they are consistent with each other. == Example == A classic example of literate programming is the literate implementation of the standard Unix wc word counting program. Knuth presented a CWEB version of this example in Chapter 12 of his Literate Programming book. The same example was later rewritten for the noweb literate programming tool. This example provides a good illustration of the basic elements of literate programming. === Creation of macros === The following snippet of the wc literate program shows how arbitrary descriptive phrases in a natural language are used in a literate program to create macros, which act as new "operators" in the literate programming language, and hide chunks of code or other macros. The mark-up notation consists of double angle brackets (<<...>>) that indicate macros. The @ symbol, in a noweb file, indicates the beginning of a documentation chunk. The <<*>> symbol stands for the "root", topmost node the literate programming tool will start expanding the web of macros from. Actually, writing out the expanded source code can be done from any section or subsection (i.e. a piece of code designated as <<name of the chunk>>=, with the equal sign), so one literate program file can contain several files with machine source code. The unraveling of the chunks can be done in any place in the literate program text file, not necessarily in the order they are sequenced in the enclosing chunk, but as is demanded by the logic reflected in the explanatory text that envelops the whole program. === Program as a web === Macros are not the same as "section names" in standard documentation. Literate programming macros hide the real code behind themselves, and be used inside any low-level machine language operators, often inside logical operators such as if, while or case. This can be seen in the following wc literate program. The macros stand for any chunk of code or other macros, and are more general than top-down or bottom-up "chunking", or than subsectioning. Donald Knuth said that when he realized this, he began to think of a program as a web of various parts. === Order of human logic, not that of the compiler === In a noweb literate program besides the free order of their exposition, the chunks behind macros, once introduced with <<...>>=, can be grown later in any place in the file by simply writing <<name of the chunk>>= and adding more content to it, as the following snippet illustrates (+ is added by the document formatter for readability, and is not in the code). The grand totals must be initialized to zero at the beginning of the program. If we made these variables local to main, we would have to do this initialization explicitly; however, C globals are automatically zeroed. (Or rather,``statically zeroed.'⁠' (Get it?) <<Global variables>>+= long tot_word_count, tot_line_count, tot_char_count; /* total number of words, lines, chars */ @ === Record of the train of thought === The documentation for a literate program is produced as part of writing the program. Instead of comments provided as side notes to source code a literate program contains the explanation of concepts on each level, with lower level concepts deferred to their appropriate place, which allows for better communication of thought. The snippets of the literate wc above show how an explanation of the program and its source code are interwoven. Such exposition of ideas creates the flow of thought that is like a literary work. Knuth wrote a "novel" which explains the code of the interactive fiction game Colossal Cave Adventure. === Remarkable examples === Axiom, which is evolved from Scratchpad, a computer algebra system developed by IBM. It is now being developed by Tim Daly, one of the developers of Scratchpad, Axiom is totally written as a literate program. == Literate programming practices == The first published literate programming environment was WEB, introduced by Knuth in 1981 for his TeX typesetting system; it uses Pascal as its underlying programming language and TeX for typesetting of the documentation. The complete commented TeX source code was published in Knuth's TeX: The program, volume B of his 5-volume Computers and Typesetting. Knuth had privately used a literate programming system called DOC as early as 1979. He was inspired by the ideas of Pierre-Arnoul de Marneffe. The free CWEB, written by Knuth and Silvio Levy, is WEB adapted for C and C++, runs on most operating systems, and can produce TeX and PDF documentation. There are various other implementations of the literate programming concept as given below. Many of the newer among these do not have macros and hence do not comply with the order of human logic principle, which makes them perhaps "semi-literate" tools. These, however, allow cellular execution of code which makes them more along the lines of exploratory programming tools. Other useful tools include: == See also == Documentation generator – the inverse on literate programming where documentation is embedded in and generated from source code Notebook interface – virtual notebook environment used for literate programming Sweave and Knitr – examples of use of the "noweb"-like Literate Programming tool inside the R language for creation of dynamic statistical reports Self-documenting code – source code that can be easily understood without documentation == References == == Further reading == == External links == LiterateProgramming at WikiWikiWeb Literate Programming FAQ at CTAN
https://en.wikipedia.org/wiki/Literate_programming
In computer programming, dataflow programming is a programming paradigm that models a program as a directed graph of the data flowing between operations, thus implementing dataflow principles and architecture. Dataflow programming languages share some features of functional languages, and were generally developed in order to bring some functional concepts to a language more suitable for numeric processing. Some authors use the term datastream instead of dataflow to avoid confusion with dataflow computing or dataflow architecture, based on an indeterministic machine paradigm. Dataflow programming was pioneered by Jack Dennis and his graduate students at MIT in the 1960s. == Considerations == Traditionally, a program is modelled as a series of operations happening in a specific order; this may be referred to as sequential,: p.3  procedural, control flow (indicating that the program chooses a specific path), or imperative programming. The program focuses on commands, in line with the von Neumann: p.3  vision of sequential programming, where data is normally "at rest".: p.7  In contrast, dataflow programming emphasizes the movement of data and models programs as a series of connections. Explicitly defined inputs and outputs connect operations, which function like black boxes.: p.2  An operation runs as soon as all of its inputs become valid. Thus, dataflow languages are inherently parallel and can work well in large, decentralized systems.: p.3  === State === One of the key concepts in computer programming is the idea of state, essentially a snapshot of various conditions in the system. Most programming languages require a considerable amount of state information, which is generally hidden from the programmer. Often, the computer itself has no idea which piece of information encodes the enduring state. This is a serious problem, as the state information needs to be shared across multiple processors in parallel processing machines. Most languages force the programmer to add extra code to indicate which data and parts of the code are important to the state. This code tends to be both expensive in terms of performance, as well as difficult to read or debug. Explicit parallelism is one of the main reasons for the poor performance of Enterprise Java Beans when building data-intensive, non-OLTP applications. Where a sequential program can be imagined as a single worker moving between tasks (operations), a dataflow program is more like a series of workers on an assembly line, each doing a specific task whenever materials are available. Since the operations are only concerned with the availability of data inputs, they have no hidden state to track, and are all "ready" at the same time. === Representation === Dataflow programs are represented in different ways. A traditional program is usually represented as a series of text instructions, which is reasonable for describing a serial system which pipes data between small, single-purpose tools that receive, process, and return. Dataflow programs start with an input, perhaps the command line parameters, and illustrate how that data is used and modified. The flow of data is explicit, often visually illustrated as a line or pipe. In terms of encoding, a dataflow program might be implemented as a hash table, with uniquely identified inputs as the keys, used to look up pointers to the instructions. When any operation completes, the program scans down the list of operations until it finds the first operation where all inputs are currently valid, and runs it. When that operation finishes, it will typically output data, thereby making another operation become valid. For parallel operation, only the list needs to be shared; it is the state of the entire program. Thus the task of maintaining state is removed from the programmer and given to the language's runtime. On machines with a single processor core where an implementation designed for parallel operation would simply introduce overhead, this overhead can be removed completely by using a different runtime. === Incremental updates === Some recent dataflow libraries such as Differential/Timely Dataflow have used incremental computing for much more efficient data processing. == History == A pioneer dataflow language was BLOck DIagram (BLODI), published in 1961 by John Larry Kelly, Jr., Carol Lochbaum and Victor A. Vyssotsky for specifying sampled data systems. A BLODI specification of functional units (amplifiers, adders, delay lines, etc.) and their interconnections was compiled into a single loop that updated the entire system for one clock tick. In a 1966 Ph.D. thesis, The On-line Graphical Specification of Computer Procedures, Bert Sutherland created one of the first graphical dataflow programming frameworks in order to make parallel programming easier. Subsequent dataflow languages were often developed at the large supercomputer labs. POGOL, an otherwise conventional data-processing language developed at NSA, compiled large-scale applications composed of multiple file-to-file operations, e.g. merge, select, summarize, or transform, into efficient code that eliminated the creation of or writing to intermediate files to the greatest extent possible. SISAL, a popular dataflow language developed at Lawrence Livermore National Laboratory, looks like most statement-driven languages, but variables should be assigned once. This allows the compiler to easily identify the inputs and outputs. A number of offshoots of SISAL have been developed, including SAC, Single Assignment C, which tries to remain as close to the popular C programming language as possible. The United States Navy funded development of signal processing graph notation (SPGN) and ACOS starting in the early 1980s. This is in use on a number of platforms in the field today. A more radical concept is Prograph, in which programs are constructed as graphs onscreen, and variables are replaced entirely with lines linking inputs to outputs. Prograph was originally written on the Macintosh, which remained single-processor until the introduction of the DayStar Genesis MP in 1996. There are many hardware architectures oriented toward the efficient implementation of dataflow programming models. MIT's tagged token dataflow architecture was designed by Greg Papadopoulos. Data flow has been proposed as an abstraction for specifying the global behavior of distributed system components: in the live distributed objects programming model, distributed data flows are used to store and communicate state, and as such, they play the role analogous to variables, fields, and parameters in Java-like programming languages. == Languages == Dataflow programming languages include: Céu (programming language) ASCET AviSynth scripting language, for video processing BMDFM Binary Modular Dataflow Machine CAL Cuneiform, a functional workflow language. CMS Pipelines Hume Joule Keysight VEE KNIME is a free and open-source data analytics, reporting and integration platform LabVIEW, G Linda Lucid Lustre Max/MSP Microsoft Visual Programming Language - A component of Microsoft Robotics Studio designed for robotics programming Nextflow: a workflow language Orange - An open-source, visual programming tool for data mining, statistical data analysis, and machine learning. Oz now also distributed since 1.4.0 Pipeline Pilot Prograph Pure Data Quartz Composer - Designed by Apple; used for graphic animations and effects SAC Single assignment C SIGNAL (a dataflow-oriented synchronous language enabling multi-clock specifications) Simulink SISAL SystemVerilog - A hardware description language Verilog - A hardware description language absorbed into the SystemVerilog standard in 2009 VisSim - A block diagram language for simulation of dynamic systems and automatic firmware generation VHDL - A hardware description language Wapice IOT-TICKET implements an unnamed visual dataflow programming language for IoT data analysis and reporting. XEE (Starlight) XML engineering environment XProc == Libraries == Apache Beam: Java/Scala SDK that unifies streaming (and batch) processing with several execution engines supported (Apache Spark, Apache Flink, Google Dataflow etc.) Apache Flink: Java/Scala library that allows streaming (and batch) computations to be run atop a distributed Hadoop (or other) cluster Apache Spark SystemC: Library for C++, mainly aimed at hardware design. TensorFlow: A machine-learning library based on dataflow programming. == See also == Actor model Data-driven programming Digital signal processing Event-driven programming Flow-based programming Functional reactive programming Glossary of reconfigurable computing High-performance reconfigurable computing Incremental computing Parallel programming model Partitioned global address space Pipeline (Unix) Quantum circuit Signal programming Stream processing Yahoo Pipes == References == == External links == Book: Dataflow and Reactive Programming Systems Basics of Dataflow Programming in F# and C# Dataflow Programming - Concept, Languages and Applications Static Scheduling of Synchronous Data Flow Programs for Digital Signal Processing Handling huge loads without adding complexity The basic concepts of dataflow programming, Dr. Dobb's, Sept. 2011
https://en.wikipedia.org/wiki/Dataflow_programming
Differentiable programming is a programming paradigm in which a numeric computer program can be differentiated throughout via automatic differentiation. This allows for gradient-based optimization of parameters in the program, often via gradient descent, as well as other learning approaches that are based on higher-order derivative information. Differentiable programming has found use in a wide variety of areas, particularly scientific computing and machine learning. One of the early proposals to adopt such a framework in a systematic fashion to improve upon learning algorithms was made by the Advanced Concepts Team at the European Space Agency in early 2016. == Approaches == Most differentiable programming frameworks work by constructing a graph containing the control flow and data structures in the program. Attempts generally fall into two groups: Static, compiled graph-based approaches such as TensorFlow, Theano, and MXNet. They tend to allow for good compiler optimization and easier scaling to large systems, but their static nature limits interactivity and the types of programs that can be created easily (e.g. those involving loops or recursion), as well as making it harder for users to reason effectively about their programs. A proof-of-concept compiler toolchain called Myia uses a subset of Python as a front end and supports higher-order functions, recursion, and higher-order derivatives. Operator overloading, dynamic graph-based approaches such as PyTorch, NumPy's autograd package, and Pyaudi. Their dynamic and interactive nature lets most programs be written and reasoned about more easily. However, they lead to interpreter overhead (particularly when composing many small operations), poorer scalability, and reduced benefit from compiler optimization. The use of just-in-time compilation has emerged recently as a possible solution to overcome some of the bottlenecks of interpreted languages. The C++ heyoka and Python package heyoka.py make large use of this technique to offer advanced differentiable programming capabilities (also at high orders). A package for the Julia programming language – Zygote – works directly on Julia's intermediate representation. A limitation of earlier approaches is that they are only able to differentiate code written in a suitable manner for the framework, limiting their interoperability with other programs. Newer approaches resolve this issue by constructing the graph from the language's syntax or IR, allowing arbitrary code to be differentiated. == Applications == Differentiable programming has been applied in areas such as combining deep learning with physics engines in robotics, solving electronic-structure problems with differentiable density functional theory, differentiable ray tracing, differentiable imaging, image processing, and probabilistic programming. == Multidisciplinary application == Differentiable programming is making significant strides in various fields beyond its traditional applications. In healthcare and life sciences, for example, it is being used for deep learning in biophysics-based modelling of molecular mechanisms, in areas such as protein structure prediction and drug discovery. These applications demonstrate the potential of differentiable programming in contributing to significant advancements in understanding complex biological systems and improving healthcare solutions. == See also == Differentiable function Machine learning == Notes == == References ==
https://en.wikipedia.org/wiki/Differentiable_programming
Brokered programming (also known as time-buy and blocktime) is a form of broadcast content in which the show's producer pays a radio or television station for air time, rather than exchanging programming for pay or the opportunity to play spot commercials. A brokered program is typically not capable of garnering enough support from advertisements to pay for itself, and may be controversial, esoteric or an advertisement in itself. == Overview == === Common examples === Common examples are religious and political programs and talk-show-format programs similar to infomercial on television. Others are hobby programs or vanity programs paid for by the host and/or their supporters, and may be intended to promote the host's personality, for instance in preparation for a political campaign, or to promote a product, service or business that the host is closely associated with. A live vanity show may be carried on several stations by remote broadcast or simulcast, with the producer paying multiple stations an airtime fee. Financial advisors and planners often produce this kind of programming. Brokered commercial programs promote products or services by scripting shows made to sound similar to talk radio or news programming, and may even include calls from actual listeners (or actors playing the part of listeners). The programs are a specific type of infomercial, as they focus on a topic related to the product and repeatedly steer listeners and "callers" to a particular website and/or toll-free telephone number in order to purchase the product being featured. Although presented in the style of live programs, these are typically pre-recorded and supplied to stations on tape, disc, or digital downloadable formats, such as MP3 files. Such programming is most common on talk radio stations and used to fill non-prime time slots and to augment income from spot-advertisement sales during normal programs. Most of these programs feature a disclaimer at either the beginning or the end of the program (or both), usually read by the program's host or (most often) by a separate announcer; some radio stations play a standard disclaimer before all such programs. Certain mainstream sports and entertainment broadcasts may resort to buying brokered airtime to air on television if they cannot secure a deal that pays rights fees or a barter agreement. Examples include the last years of the Professional Bowlers Tour, Major League Baseball's short-lived The Baseball Network venture in the mid-1990s, professional football leagues such as the United Football League and Alliance of American Football, and motorsports events produced and sponsored by Lucas Oil. In the case of professional football, brokered programming has typically not been feasible in the long term, as the sport requires rights fees to make it viable; leagues that have relied on brokering television time have collapsed in short order due to financial losses. Regional sports networks also pad their non-play-by-play schedule with brokered shows catering to niches like high school sports, poker, and all-terrain vehicles. Some packages of high school football and basketball games are brokered more with the specific purposes of college recruiting and future name, image, and likeness deals in mind rather than the actual team matchup, which is mainly prevalent with nationally-ranked high school athletic powers that do not play traditional local schedules against local opponents and highlight certain heavily-recruited players. === Radio === ==== Talk radio ==== Although some syndicators of multi-topic, ad-supported talk shows may pay a fee to stations with very large Arbitron-verified listenership, the same syndicator will normally charge a fee to small stations and may charge nothing to stations with moderate listenership. Each arrangement depends on whether the station can deliver enough listeners to allow the syndicator to earn money from ad sales. Syndicated programs normally carry a number of their own advertisements that must be played during commercial breaks, but set aside time for local stations to play their own advertisements. Stations also frequently employ one or more of their own hosts, but at some small stations these hosts may be unpaid volunteers motivated by the chance to promote an agenda, gain personal exposure or get work experience. The use of brokered programming varies by station -- some stations, mainly news radio and sports radio stations, use brokered programming to fill holes in some dayparts, especially during the late-night hours and weekends. The format of brokered programs varies; many sports radio stations will use brokered programs from sports handicappers and prognosticators to fit their format, while news and talk radio stations will often rely on brokered programs that sell vitamin or nutritional supplements, financial planning products and services, and alternative medical products, fitting those stations' older audiences. Sometimes, even programs dealing with gardening and home improvement (usually presented on weekend mornings on many talk radio stations) are broadcast under a brokered arrangement, as was the case with KRLD gardening expert Neil Sperry before his show was canceled outright in 2010. Program time is often brokered to churches on Sunday mornings in a manner that parallels televangelism; there are also religious stations that rely primarily on brokered programs, and these stations often get the derisive title of "pay for pray," a play on the unethical practice of "pay for play" on music stations. There are also some AM radio stations that are dedicated to the brokered format, selling time for as little as 15 minutes or even selling the entire broadcasting day to a single entity, with the station holding the broadcast license and providing the facilities. That long-form type of brokered programming is especially popular among ethnic and religious broadcasters as well as with privately owned U.S.-based shortwave radio broadcasters. ==== Music radio programs ==== Brokered programs are not exclusive to talk radio; music radio programs can also be brokered. The brokered format, popular among specialty and niche music formats (e.g. polka music), usually involves the show itself lining up its own advertising and paying the station for its airtime. The idea reduces the risk for the station and assures the show remains on the air as long as the show's producers continue to pay the station's airtime fee. === Record companies === Record companies (through independent promoters) may also purchase brokered time on music stations to have the station play a new single as a "preview", which has the potential to be inserted onto a station's general playlist but has not received the traction to do so. These spots are often the length of the song with an introduction and disclaimer at the end of the song stating the artist, album title, and releasing label, and come under titles such as CD Preview. The segments must be carefully disclaimed by the record companies so as to not violate payola laws and the playing of the song, as it is paid for, cannot be applied to song popularity charts, as has happened in the early 2000s with some forms of this concept. === Brokered time through agencies === Oftentimes broadcasters will seek the help of an ad agency to secure a brokered radio show. Agencies such as I Buy Time in Dallas, Texas or Bayliss Media Group in Los Angeles, California have the knowledge on how to negotiate a lower per-hour rate than what may be quoted by the radio station to the individual broadcaster. === Local marketing agreements === If a station sells all of its time to a programmer, essentially leasing the station, it is a local marketing agreement (LMA). Like owning a station, this counts toward United States Federal Communications Commission (FCC) and Canadian Radio-television and Telecommunications Commission (CRTC) caps that prevent excessive concentration of media ownership in the U.S. and Canada. However, in the case of television stations, LMA's do not count towards caps in the U.S. == Examples of brokered, non-religious programming == Financial planning/advice/services Investors Edge with Gary Kaltbaum The Mutual Fund Show The Ray Lucia Show Other ASAP (via A2Z and TV5) Eat Bulaga! (via TV5 and RPTV/RPN) Goin' Bulilit (via A2Z and All TV) It's Showtime (via A2Z, All TV and GMA Network) The Kevin Trudeau Show Maalaala Mo Kaya (via A2Z and All TV) Music Ernest Tubb's Midnite Jamboree Sports Calling All Sports With Roc and Manuch News and Talk Magandang Buhay (via A2Z and All TV) NewsWatch Plus (via RPTV/RPN and Aliw Channel 23) Radio Sputnik (via RM Broadcasting) TV Patrol (via A2Z, All TV, DWPM Radyo 630 and PRTV Prime Media) == See also == Talk radio Infomercial Leased access (for cable television) Advertising == Footnotes ==
https://en.wikipedia.org/wiki/Brokered_programming
"Epigrams on Programming" is an article by Alan Perlis published in 1982, for ACM's SIGPLAN journal. The epigrams are a series of short, programming-language-neutral, humorous statements about computers and programming, which are widely quoted. It first appeared in SIGPLAN Notices 17(9), September 1982. In epigram #54, Perlis coined the term "Turing tarpit", which he defined as a programming language where "everything is possible but nothing of interest is easy." == References == Perlis, A. J. (September 1982). "Epigrams on programming". ACM SIGPLAN Notices. 17 (9). New York, NY, USA: Association for Computing Machinery: 7–13. doi:10.1145/947955.1083808. Archived from the original on January 17, 1999. == External links == List of quotes (Yale) Full article text -- (including so-called "meta epigrams", numbers 122-130)
https://en.wikipedia.org/wiki/Epigrams_on_Programming
A programming paradigm is a relatively high-level way to conceptualize and structure the implementation of a computer program. A programming language can be classified as supporting one or more paradigms. Paradigms are separated along and described by different dimensions of programming. Some paradigms are about implications of the execution model, such as allowing side effects, or whether the sequence of operations is defined by the execution model. Other paradigms are about the way code is organized, such as grouping into units that include both state and behavior. Yet others are about syntax and grammar. Some common programming paradigms include (shown in hierarchical relationship): Imperative – code directly controls execution flow and state change, explicit statements that change a program state procedural – organized as procedures that call each other object-oriented – organized as objects that contain both data structure and associated behavior, uses data structures consisting of data fields and methods together with their interactions (objects) to design programs Class-based – object-oriented programming in which inheritance is achieved by defining classes of objects, versus the objects themselves Prototype-based – object-oriented programming that avoids classes and implements inheritance via cloning of instances Declarative – code declares properties of the desired result, but not how to compute it, describes what computation should perform, without specifying detailed state changes functional – a desired result is declared as the value of a series of function evaluations, uses evaluation of mathematical functions and avoids state and mutable data logic – a desired result is declared as the answer to a question about a system of facts and rules, uses explicit mathematical logic for programming reactive – a desired result is declared with data streams and the propagation of change Concurrent programming – has language constructs for concurrency, these may involve multi-threading, support for distributed computing, message passing, shared resources (including shared memory), or futures Actor programming – concurrent computation with actors that make local decisions in response to the environment (capable of selfish or competitive behaviour) Constraint programming – relations between variables are expressed as constraints (or constraint networks), directing allowable solutions (uses constraint satisfaction or simplex algorithm) Dataflow programming – forced recalculation of formulas when data values change (e.g. spreadsheets) Distributed programming – has support for multiple autonomous computers that communicate via computer networks Generic programming – uses algorithms written in terms of to-be-specified-later types that are then instantiated as needed for specific types provided as parameters Metaprogramming – writing programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime Template metaprogramming – metaprogramming methods in which a compiler uses templates to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled Reflective programming – metaprogramming methods in which a program modifies or extends itself Pipeline programming – a simple syntax change to add syntax to nest function calls to language originally designed with none Rule-based programming – a network of rules of thumb that comprise a knowledge base and can be used for expert systems and problem deduction & resolution Visual programming – manipulating program elements graphically rather than by specifying them textually (e.g. Simulink); also termed diagrammatic programming' Online presence management is distinct from Web presence management in that the former is generally a marketing and messaging discipline while the latter is Governance,risk management, and compliance operational and security discipline. == Overview == Programming paradigms come from computer science research into existing practices of software development. The findings allow for describing and comparing programming practices and the languages used to code programs. For perspective, other fields of research study software engineering processes and describe various methodologies to describe and compare them. A programming language can be described in terms of paradigms. Some languages support only one paradigm. For example, Smalltalk supports object-oriented and Haskell supports functional. Most languages support multiple paradigms. For example, a program written in C++, Object Pascal, or PHP can be purely procedural, purely object-oriented, or can contain aspects of both paradigms, or others. When using a language that supports multiple paradigms, the developer chooses which paradigm elements to use. But, this choice may not involve considering paradigms per se. The developer often uses the features of a language as the language provides them and to the extent that the developer knows them. Categorizing the resulting code by paradigm is often an academic activity done in retrospect. Languages categorized as imperative paradigm have two main features: they state the order in which operations occur, with constructs that explicitly control that order, and they allow side effects, in which state can be modified at one point in time, within one unit of code, and then later read at a different point in time inside a different unit of code. The communication between the units of code is not explicit. In contrast, languages in the declarative paradigm do not state the order in which to execute operations. Instead, they supply a number of available operations in the system, along with the conditions under which each is allowed to execute. The implementation of the language's execution model tracks which operations are free to execute and chooses the order independently. More at Comparison of multi-paradigm programming languages. In object-oriented programming, code is organized into objects that contain state that is owned by and (usually) controlled by the code of the object. Most object-oriented languages are also imperative languages. In object-oriented programming, programs are treated as a set of interacting objects. In functional programming, programs are treated as a sequence of stateless function evaluations. When programming computers or systems with many processors, in process-oriented programming, programs are treated as sets of concurrent processes that act on a logical shared data structures. Many programming paradigms are as well known for the techniques they forbid as for those they support. For instance, pure functional programming disallows side-effects, while structured programming disallows the goto construct. Partly for this reason, new paradigms are often regarded as doctrinaire or overly rigid by those accustomed to older ones. Yet, avoiding certain techniques can make it easier to understand program behavior, and to prove theorems about program correctness. Programming paradigms can also be compared with programming models, which allows invoking an execution model by using only an API. Programming models can also be classified into paradigms based on features of the execution model. For parallel computing, using a programming model instead of a language is common. The reason is that details of the parallel hardware leak into the abstractions used to program the hardware. This causes the programmer to have to map patterns in the algorithm onto patterns in the execution model (which have been inserted due to leakage of hardware into the abstraction). As a consequence, no one parallel programming language maps well to all computation problems. Thus, it is more convenient to use a base sequential language and insert API calls to parallel execution models via a programming model. Such parallel programming models can be classified according to abstractions that reflect the hardware, such as shared memory, distributed memory with message passing, notions of place visible in the code, and so forth. These can be considered flavors of programming paradigm that apply to only parallel languages and programming models. == Criticism == Some programming language researchers criticise the notion of paradigms as a classification of programming languages, e.g. Harper, and Krishnamurthi. They argue that many programming languages cannot be strictly classified into one paradigm, but rather include features from several paradigms. See Comparison of multi-paradigm programming languages. == History == Different approaches to programming have developed over time. Classification of each approach was either described at the time the approach was first developed, but often not until some time later, retrospectively. An early approach consciously identified as such is structured programming, advocated since the mid 1960s. The concept of a programming paradigm as such dates at least to 1978, in the Turing Award lecture of Robert W. Floyd, entitled The Paradigms of Programming, which cites the notion of paradigm as used by Thomas Kuhn in his The Structure of Scientific Revolutions (1962). Early programming languages did not have clearly defined programming paradigms and sometimes programs made extensive use of goto statements. Liberal use of which lead to spaghetti code which is difficult to understand and maintain. This led to the development of structured programming paradigms that disallowed the use of goto statements; only allowing the use of more structured programming constructs. == Languages and paradigms == === Machine code === Machine code is the lowest-level of computer programming as it is machine instructions that define behavior at the lowest level of abstract possible for a computer. As it is the most prescriptive way to code it is classified as imperative. It is sometimes called the first-generation programming language. === Assembly === Assembly language introduced mnemonics for machine instructions and memory addresses. Assembly is classified as imperative and is sometimes called the second-generation programming language. In the 1960s, assembly languages were developed to support library COPY and quite sophisticated conditional macro generation and preprocessing abilities, CALL to subroutine, external variables and common sections (globals), enabling significant code re-use and isolation from hardware specifics via the use of logical operators such as READ/WRITE/GET/PUT. Assembly was, and still is, used for time-critical systems and often in embedded systems as it gives the most control of what the machine does. === Procedural languages === Procedural languages, also called the third-generation programming languages are the first described as high-level languages. They support vocabulary related to the problem being solved. For example, COmmon Business Oriented Language (COBOL) – uses terms like file, move and copy. FORmula TRANslation (FORTRAN) – using mathematical language terminology, it was developed mainly for scientific and engineering problems. ALGOrithmic Language (ALGOL) – focused on being an appropriate language to define algorithms, while using mathematical language terminology, targeting scientific and engineering problems, just like FORTRAN. Programming Language One (PL/I) – a hybrid commercial-scientific general purpose language supporting pointers. Beginners All purpose Symbolic Instruction Code (BASIC) – it was developed to enable more people to write programs. C – a general-purpose programming language, initially developed by Dennis Ritchie between 1969 and 1973 at AT&T Bell Labs. These languages are classified as procedural paradigm. They directly control the step by step process that a computer program follows. The efficacy and efficiency of such a program is therefore highly dependent on the programmer's skill. === Object-oriented programming === In attempt to improve on procedural languages, object-oriented programming (OOP) languages were created, such as Simula, Smalltalk, C++, Eiffel, Python, PHP, Java, and C#. In these languages, data and methods to manipulate the data are in the same code unit called an object. This encapsulation ensures that the only way that an object can access data is via methods of the object that contains the data. Thus, an object's inner workings may be changed without affecting code that uses the object. There is controversy raised by Alexander Stepanov, Richard Stallman and other programmers, concerning the efficacy of the OOP paradigm versus the procedural paradigm. The need for every object to have associative methods leads some skeptics to associate OOP with software bloat; an attempt to resolve this dilemma came through polymorphism. Although most OOP languages are third-generation, it is possible to create an object-oriented assembler language. High Level Assembly (HLA) is an example of this that fully supports advanced data types and object-oriented assembly language programming – despite its early origins. Thus, differing programming paradigms can be seen rather like motivational memes of their advocates, rather than necessarily representing progress from one level to the next. Precise comparisons of competing paradigms' efficacy are frequently made more difficult because of new and differing terminology applied to similar entities and processes together with numerous implementation distinctions across languages. === Declarative languages === A declarative programming program describes what the problem is, not how to solve it. The program is structured as a set of properties to find in the expected result, not as a procedure to follow. Given a database or a set of rules, the computer tries to find a solution matching all the desired properties. An archetype of a declarative language is the fourth generation language SQL, and the family of functional languages and logic programming. Functional programming is a subset of declarative programming. Programs written using this paradigm use functions, blocks of code intended to behave like mathematical functions. Functional languages discourage changes in the value of variables through assignment, making a great deal of use of recursion instead. The logic programming paradigm views computation as automated reasoning over a body of knowledge. Facts about the problem domain are expressed as logic formulas, and programs are executed by applying inference rules over them until an answer to the problem is found, or the set of formulas is proved inconsistent. === Other paradigms === Symbolic programming is a paradigm that describes programs able to manipulate formulas and program components as data. Programs can thus effectively modify themselves, and appear to "learn", making them suited for applications such as artificial intelligence, expert systems, natural-language processing and computer games. Languages that support this paradigm include Lisp and Prolog. Differentiable programming structures programs so that they can be differentiated throughout, usually via automatic differentiation. Literate programming, as a form of imperative programming, structures programs as a human-centered web, as in a hypertext essay: documentation is integral to the program, and the program is structured following the logic of prose exposition, rather than compiler convenience. Symbolic programming techniques such as reflective programming (reflection), which allow a program to refer to itself, might also be considered as a programming paradigm. However, this is compatible with the major paradigms and thus is not a real paradigm in its own right. == See also == == References == == External links == Classification of the principal programming paradigms How programming paradigms evolve and get adopted?
https://en.wikipedia.org/wiki/Programming_paradigm
A programming tool or software development tool is a computer program that is used to develop another computer program, usually by helping the developer manage computer files. For example, a programmer may use a tool called a source code editor to edit source code files, and then a compiler to convert the source code into machine code files. They may also use build tools that automatically package executable program and data files into shareable packages or install kits. A set of tools that are run one after another, with each tool feeding its output to the next one, is called a toolchain. An integrated development environment (IDE) integrates the function of several tools into a single program. Usually, an IDE provides a source code editor as well as other built-in or plug-in tools that help with compiling, debugging, and testing. Whether a program is considered a development tool can be subjective. Some programs, such as the GNU compiler collection, are used exclusively for software development while others, such as Notepad, are not meant specifically for development but are nevertheless often used for programming. == Categories == Notable categories of development tools: Assembler – Converts assembly language into machine code Bug tracking system – Software application that records software bugs Build automation – Building software via an unattended fashion Code review software – Activity where one or more people check a program's code Compiler – Computer program which translates code from one programming language to another Compiler-compiler – Program that generates parsers or compilers, a.k.a. parser generator Debugger – Computer program used to test and debug other programs Decompiler – Program translating executable to source code Disassembler – Computer program to translate machine language into assembly language Documentation generator – Automation technology for creating software documentation Graphical user interface builder – Software development tool Linker – Program that combines intermediate build files into an executable file Memory debugger – Software memory problem finder Minifier – Removal of unnecessary characters in code without changing its functionality Pretty-printer – Formatting to make code or markup easier to readPages displaying short descriptions of redirect targets Performance profiler – Measuring the time or resources used by a section of a computer program Static code analyzer – Analysis of computer programs without executing themPages displaying short descriptions of redirect targets Source code editor – Text editor specializing in software codePages displaying short descriptions of redirect targets Source code generation – Type of computer programmingPages displaying short descriptions of redirect targets Version control system – Stores and tracks versions of files == See also == Call graph – Structure in computing Comparison of integrated development environments – Notable software packages that are nominal IDE Computer aided software engineering – Domain of software toolsPages displaying short descriptions of redirect targets Git – Distributed version control software system GitHub – Software development collaboration platform Lint – Tool to flag poor computer code List of software engineering topics – Overview of and topical guide to software engineeringPages displaying short descriptions of redirect targets List of unit testing frameworks Manual memory management – Computer memory management methodology Memory leak – When a computer program fails to release unnecessary memory Reverse-engineering – Process of extracting design information from anything artificialPages displaying short descriptions of redirect targets Revision Control System – Version-control system Software development kit – Set of software development tools Software engineering – Engineering approach to software development SourceForge – Software discovery and hosting platform for B2B and open source software SWIG – Open-source programming tool Toolkits for User Innovation – Design methodPages displaying short descriptions of redirect targets Valgrind – Programming tool for profiling, memory debugging and memory leak detection == References == == External links == Media related to Programming tools at Wikimedia Commons
https://en.wikipedia.org/wiki/Programming_tool
Go is a high-level general purpose programming language that is statically typed and compiled. It is known for the simplicity of its syntax and the efficiency of development that it enables by the inclusion of a large standard library supplying many needs for common projects. It was designed at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson, and publicly announced in November of 2009. It is syntactically similar to C, but also has memory safety, garbage collection, structural typing, and CSP-style concurrency. It is often referred to as Golang to avoid ambiguity and because of its former domain name, golang.org, but its proper name is Go. There are two major implementations: The original, self-hosting compiler toolchain, initially developed inside Google; A frontend written in C++, called gofrontend, originally a GCC frontend, providing gccgo, a GCC-based Go compiler; later extended to also support LLVM, providing an LLVM-based Go compiler called gollvm. A third-party source-to-source compiler, GopherJS, transpiles Go to JavaScript for front-end web development. == History == Go was designed at Google in 2007 to improve programming productivity in an era of multicore, networked machines and large codebases. The designers wanted to address criticisms of other languages in use at Google, but keep their useful characteristics: Static typing and run-time efficiency (like C) Readability and usability (like Python) High-performance networking and multiprocessing Its designers were primarily motivated by their shared dislike of C++. Go was publicly announced in November 2009, and version 1.0 was released in March 2012. Go is widely used in production at Google and in many other organizations and open-source projects. In retrospect the Go authors judged Go to be successful due to the overall engineering work around the language, including the runtime support for the language's concurrency feature. Although the design of most languages concentrates on innovations in syntax, semantics, or typing, Go is focused on the software development process itself. ... The principal unusual property of the language itself—concurrency—addressed problems that arose with the proliferation of multicore CPUs in the 2010s. But more significant was the early work that established fundamentals for packaging, dependencies, build, test, deployment, and other workaday tasks of the software development world, aspects that are not usually foremost in language design. === Branding and styling === The Gopher mascot was introduced in 2009 for the open source launch of the language. The design, by Renée French, borrowed from a c. 2000 WFMU promotion. In November 2016, the Go and Go Mono fonts were released by type designers Charles Bigelow and Kris Holmes specifically for use by the Go project. Go is a humanist sans-serif resembling Lucida Grande, and Go Mono is monospaced. Both fonts adhere to the WGL4 character set and were designed to be legible with a large x-height and distinct letterforms. Both Go and Go Mono adhere to the DIN 1450 standard by having a slashed zero, lowercase l with a tail, and an uppercase I with serifs. In April 2018, the original logo was redesigned by brand designer Adam Smith. The new logo is a modern, stylized GO slanting right with trailing streamlines. (The Gopher mascot remained the same.) === Generics === The lack of support for generic programming in initial versions of Go drew considerable criticism. The designers expressed an openness to generic programming and noted that built-in functions were in fact type-generic, but are treated as special cases; Pike called this a weakness that might be changed at some point. The Google team built at least one compiler for an experimental Go dialect with generics, but did not release it. In August 2018, the Go principal contributors published draft designs for generic programming and error handling and asked users to submit feedback. However, the error handling proposal was eventually abandoned. In June 2020, a new draft design document was published that would add the necessary syntax to Go for declaring generic functions and types. A code translation tool, go2go, was provided to allow users to try the new syntax, along with a generics-enabled version of the online Go Playground. Generics were finally added to Go in version 1.18 on March 15, 2022. === Versioning === Go 1 guarantees compatibility for the language specification and major parts of the standard library. All versions up through the current Go 1.24 release have maintained this promise. Go uses a go1.[major].[patch] versioning format, such as go1.24.0 and each major Go release is supported until there are two newer major releases. Unlike most software, Go calls the second number in a version the major, i.e., in go1.24.0 the 24 is the major version. This is because Go plans to never reach 2.0, prioritizing backwards compatibility over potential breaking changes. == Design == Go is influenced by C (especially the Plan 9 dialect), but with an emphasis on greater simplicity and safety. It consists of: A syntax and environment adopting patterns more common in dynamic languages: Optional concise variable declaration and initialization through type inference (x := 0 instead of var x int = 0; or var x = 0;) Fast compilation Remote package management (go get) and online package documentation Distinctive approaches to particular problems: Built-in concurrency primitives: light-weight processes (goroutines), channels, and the select statement An interface system in place of virtual inheritance, and type embedding instead of non-virtual inheritance A toolchain that, by default, produces statically linked native binaries without external Go dependencies A desire to keep the language specification simple enough to hold in a programmer's head, in part by omitting features that are common in similar languages. === Syntax === Go's syntax includes changes from C aimed at keeping code concise and readable. A combined declaration/initialization operator was introduced that allows the programmer to write i := 3 or s := "Hello, world!", without specifying the types of variables used. This contrasts with C's int i = 3; and const char *s = "Hello, world!";. Go also removes the requirement to use parentheses in if statement conditions. Semicolons still terminate statements; but are implicit when the end of a line occurs. Methods may return multiple values, and returning a result, err pair is the conventional way a method indicates an error to its caller in Go. Go adds literal syntaxes for initializing struct parameters by name and for initializing maps and slices. As an alternative to C's three-statement for loop, Go's range expressions allow concise iteration over arrays, slices, strings, maps, and channels. fmt.Println("Hello World!") is a statement. In Go, statements are separated by ending a line (hitting the Enter key) or by a semicolon ";". Hitting the Enter key adds ";" to the end of the line implicitly (does not show up in the source code). The left curly bracket { cannot come at the start of a line. === Types === Go has a number of built-in types, including numeric ones (byte, int64, float32, etc.), Booleans, and byte strings (string). Strings are immutable; built-in operators and keywords (rather than functions) provide concatenation, comparison, and UTF-8 encoding/decoding. Record types can be defined with the struct keyword. For each type T and each non-negative integer constant n, there is an array type denoted [n]T; arrays of differing lengths are thus of different types. Dynamic arrays are available as "slices", denoted []T for some type T. These have a length and a capacity specifying when new memory needs to be allocated to expand the array. Several slices may share their underlying memory. Pointers are available for all types, and the pointer-to-T type is denoted *T. Address-taking and indirection use the & and * operators, as in C, or happen implicitly through the method call or attribute access syntax. There is no pointer arithmetic, except via the special unsafe.Pointer type in the standard library. For a pair of types K, V, the type map[K]V is the type mapping type-K keys to type-V values, though Go Programming Language specification does not give any performance guarantees or implementation requirements for map types. Hash tables are built into the language, with special syntax and built-in functions. chan T is a channel that allows sending values of type T between concurrent Go processes. Aside from its support for interfaces, Go's type system is nominal: the type keyword can be used to define a new named type, which is distinct from other named types that have the same layout (in the case of a struct, the same members in the same order). Some conversions between types (e.g., between the various integer types) are pre-defined and adding a new type may define additional conversions, but conversions between named types must always be invoked explicitly. For example, the type keyword can be used to define a type for IPv4 addresses, based on 32-bit unsigned integers as follows: With this type definition, ipv4addr(x) interprets the uint32 value x as an IP address. Simply assigning x to a variable of type ipv4addr is a type error. Constant expressions may be either typed or "untyped"; they are given a type when assigned to a typed variable if the value they represent passes a compile-time check. Function types are indicated by the func keyword; they take zero or more parameters and return zero or more values, all of which are typed. The parameter and return values determine a function type; thus, func(string, int32) (int, error) is the type of functions that take a string and a 32-bit signed integer, and return a signed integer (of default width) and a value of the built-in interface type error. Any named type has a method set associated with it. The IP address example above can be extended with a method for checking whether its value is a known standard: Due to nominal typing, this method definition adds a method to ipv4addr, but not on uint32. While methods have special definition and call syntax, there is no distinct method type. ==== Interface system ==== Go provides two features that replace class inheritance. The first is embedding, which can be viewed as an automated form of composition. The second are its interfaces, which provides runtime polymorphism.: 266  Interfaces are a class of types and provide a limited form of structural typing in the otherwise nominal type system of Go. An object which is of an interface type is also of another type, much like C++ objects being simultaneously of a base and derived class. The design of Go interfaces was inspired by protocols from the Smalltalk programming language. Multiple sources use the term duck typing when describing Go interfaces. Although the term duck typing is not precisely defined and therefore not wrong, it usually implies that type conformance is not statically checked. Because conformance to a Go interface is checked statically by the Go compiler (except when performing a type assertion), the Go authors prefer the term structural typing. The definition of an interface type lists required methods by name and type. Any object of type T for which functions exist matching all the required methods of interface type I is an object of type I as well. The definition of type T need not (and cannot) identify type I. For example, if Shape, Square and Circle are defined as then both a Square and a Circle are implicitly a Shape and can be assigned to a Shape-typed variable.: 263–268  In formal language, Go's interface system provides structural rather than nominal typing. Interfaces can embed other interfaces with the effect of creating a combined interface that is satisfied by exactly the types that implement the embedded interface and any methods that the newly defined interface adds.: 270  The Go standard library uses interfaces to provide genericity in several places, including the input/output system that is based on the concepts of Reader and Writer.: 282–283  Besides calling methods via interfaces, Go allows converting interface values to other types with a run-time type check. The language constructs to do so are the type assertion, which checks against a single potential type:and the type switch, which checks against multiple types:The empty interface interface{} is an important base case because it can refer to an item of any concrete type. It is similar to the Object class in Java or C# and is satisfied by any type, including built-in types like int.: 284  Code using the empty interface cannot simply call methods (or built-in operators) on the referred-to object, but it can store the interface{} value, try to convert it to a more useful type via a type assertion or type switch, or inspect it with Go's reflect package. Because interface{} can refer to any value, it is a limited way to escape the restrictions of static typing, like void* in C but with additional run-time type checks. The interface{} type can be used to model structured data of any arbitrary schema in Go, such as JSON or YAML data, by representing it as a map[string]interface{} (map of string to empty interface). This recursively describes data in the form of a dictionary with string keys and values of any type. Interface values are implemented using pointer to data and a second pointer to run-time type information. Like some other types implemented using pointers in Go, interface values are nil if uninitialized. ==== Generic code using parameterized types ==== Since version 1.18, Go supports generic code using parameterized types. Functions and types now have the ability to be generic using type parameters. These type parameters are specified within square brackets, right after the function or type name. The compiler transforms the generic function or type into non-generic by substituting type arguments for the type parameters provided, either explicitly by the user or type inference by the compiler. This transformation process is referred to as type instantiation. Interfaces now can define a set of types (known as type set) using | (Union) operator, as well as a set of methods. These changes were made to support type constraints in generics code. For a generic function or type, a constraint can be thought of as the type of the type argument: a meta-type. This new ~T syntax will be the first use of ~ as a token in Go. ~T means the set of all types whose underlying type is T. ==== Enumerated types ==== === Package system === In Go's package system, each package has a path (e.g., "compress/bzip2" or "golang.org/x/net/html") and a name (e.g., bzip2 or html). By default other packages' definitions must always be prefixed with the other package's name. However the name used can be changed from the package name, and if imported as _, then no package prefix is required. Only the capitalized names from other packages are accessible: io.Reader is public but bzip2.reader is not. The go get command can retrieve packages stored in a remote repository and developers are encouraged to develop packages inside a base path corresponding to a source repository (such as example.com/user_name/package_name) to reduce the likelihood of name collision with future additions to the standard library or other external libraries. === Concurrency: goroutines and channels === The Go language has built-in facilities, as well as library support, for writing concurrent programs. The runtime is asynchronous: program execution that performs for example a network read will be suspended until data is available to process, allowing other parts of the program to perform other work. This is built into the runtime and does not require any changes in program code. The go runtime also automatically schedules concurrent operations (goroutines) across multiple CPUs; this can achieve parallelism for a properly written program. The primary concurrency construct is the goroutine, a type of green thread.: 280–281  A function call prefixed with the go keyword starts a function in a new goroutine. The language specification does not specify how goroutines should be implemented, but current implementations multiplex a Go process's goroutines onto a smaller set of operating-system threads, similar to the scheduling performed in Erlang and Haskell's GHC runtime implementation.: 10  While a standard library package featuring most of the classical concurrency control structures (mutex locks, etc.) is available,: 151–152  idiomatic concurrent programs instead prefer channels, which send messages between goroutines. Optional buffers store messages in FIFO order: 43  and allow sending goroutines to proceed before their messages are received.: 233  Channels are typed, so that a channel of type chan T can only be used to transfer messages of type T. Special syntax is used to operate on them; <-ch is an expression that causes the executing goroutine to block until a value comes in over the channel ch, while ch <- x sends the value x (possibly blocking until another goroutine receives the value). The built-in switch-like select statement can be used to implement non-blocking communication on multiple channels; see below for an example. Go has a memory model describing how goroutines must use channels or other operations to safely share data. The existence of channels does not by itself set Go apart from actor model-style concurrent languages like Erlang, where messages are addressed directly to actors (corresponding to goroutines). In the actor model, channels are themselves actors, therefore addressing a channel just means to address an actor. The actor style can be simulated in Go by maintaining a one-to-one correspondence between goroutines and channels, but the language allows multiple goroutines to share a channel or a single goroutine to send and receive on multiple channels.: 147  From these tools one can build concurrent constructs like worker pools, pipelines (in which, say, a file is decompressed and parsed as it downloads), background calls with timeout, "fan-out" parallel calls to a set of services, and others. Channels have also found uses further from the usual notion of interprocess communication, like serving as a concurrency-safe list of recycled buffers, implementing coroutines (which helped inspire the name goroutine), and implementing iterators. Concurrency-related structural conventions of Go (channels and alternative channel inputs) are derived from Tony Hoare's communicating sequential processes model. Unlike previous concurrent programming languages such as Occam or Limbo (a language on which Go co-designer Rob Pike worked), Go does not provide any built-in notion of safe or verifiable concurrency. While the communicating-processes model is favored in Go, it is not the only one: all goroutines in a program share a single address space. This means that mutable objects and pointers can be shared between goroutines; see § Lack of data race safety, below. ==== Suitability for parallel programming ==== Although Go's concurrency features are not aimed primarily at parallel processing, they can be used to program shared-memory multi-processor machines. Various studies have been done into the effectiveness of this approach. One of these studies compared the size (in lines of code) and speed of programs written by a seasoned programmer not familiar with the language and corrections to these programs by a Go expert (from Google's development team), doing the same for Chapel, Cilk and Intel TBB. The study found that the non-expert tended to write divide-and-conquer algorithms with one go statement per recursion, while the expert wrote distribute-work-synchronize programs using one goroutine per processor core. The expert's programs were usually faster, but also longer. ==== Lack of data race safety ==== Go's approach to concurrency can be summarized as "don't communicate by sharing memory; share memory by communicating". There are no restrictions on how goroutines access shared data, making data races possible. Specifically, unless a program explicitly synchronizes via channels or other means, writes from one goroutine might be partly, entirely, or not at all visible to another, often with no guarantees about ordering of writes. Furthermore, Go's internal data structures like interface values, slice headers, hash tables, and string headers are not immune to data races, so type and memory safety can be violated in multithreaded programs that modify shared instances of those types without synchronization. Instead of language support, safe concurrent programming thus relies on conventions; for example, Chisnall recommends an idiom called "aliases xor mutable", meaning that passing a mutable value (or pointer) over a channel signals a transfer of ownership over the value to its receiver.: 155  The gc toolchain has an optional data race detector that can check for unsynchronized access to shared memory during runtime since version 1.1, additionally a best-effort race detector is also included by default since version 1.6 of the gc runtime for access to the map data type. === Binaries === The linker in the gc toolchain creates statically linked binaries by default; therefore all Go binaries include the Go runtime. === Omissions === Go deliberately omits certain features common in other languages, including (implementation) inheritance, assertions, pointer arithmetic, implicit type conversions, untagged unions, and tagged unions. The designers added only those facilities that all three agreed on. Of the omitted language features, the designers explicitly argue against assertions and pointer arithmetic, while defending the choice to omit type inheritance as giving a more useful language, encouraging instead the use of interfaces to achieve dynamic dispatch and composition to reuse code. Composition and delegation are in fact largely automated by struct embedding; according to researchers Schmager et al., this feature "has many of the drawbacks of inheritance: it affects the public interface of objects, it is not fine-grained (i.e, no method-level control over embedding), methods of embedded objects cannot be hidden, and it is static", making it "not obvious" whether programmers will overuse it to the extent that programmers in other languages are reputed to overuse inheritance. Exception handling was initially omitted in Go due to lack of a "design that gives value proportionate to the complexity". An exception-like panic/recover mechanism that avoids the usual try-catch control structure was proposed and released in the March 30, 2010 snapshot. The Go authors advise using it for unrecoverable errors such as those that should halt an entire program or server request, or as a shortcut to propagate errors up the stack within a package. Across package boundaries, Go includes a canonical error type, and multi-value returns using this type are the standard idiom. == Style == The Go authors put substantial effort into influencing the style of Go programs: Indentation, spacing, and other surface-level details of code are automatically standardized by the gofmt tool. It uses tabs for indentation and blanks for alignment. Alignment assumes that an editor is using a fixed-width font. golint does additional style checks automatically, but has been deprecated and archived by the Go maintainers. Tools and libraries distributed with Go suggest standard approaches to things like API documentation (godoc), testing (go test), building (go build), package management (go get), and so on. Go enforces rules that are recommendations in other languages, for example banning cyclic dependencies, unused variables or imports, and implicit type conversions. The omission of certain features (for example, functional-programming shortcuts like map and Java-style try/finally blocks) tends to encourage a particular explicit, concrete, and imperative programming style. On day one the Go team published a collection of Go idioms, and later also collected code review comments, talks, and official blog posts to teach Go style and coding philosophy. == Tools == The main Go distribution includes tools for building, testing, and analyzing code: go build, which builds Go binaries using only information in the source files themselves, no separate makefiles go test, for unit testing and microbenchmarks as well as fuzzing go fmt, for formatting code go install, for retrieving and installing remote packages go vet, a static analyzer looking for potential errors in code go run, a shortcut for building and executing code go doc, for displaying documentation go generate, a standard way to invoke code generators go mod, for creating a new module, adding dependencies, upgrading dependencies, etc. go tool, for invoking developer tools (added in Go version 1.24) It also includes profiling and debugging support, fuzzing capabilities to detect bugs, runtime instrumentation (for example, to track garbage collection pauses), and a data race detector. Another tool maintained by the Go team but is not included in Go distributions is gopls, a language server that provides IDE features such as intelligent code completion to Language Server Protocol compatible editors. An ecosystem of third-party tools adds to the standard distribution, such as gocode, which enables code autocompletion in many text editors, goimports, which automatically adds/removes package imports as needed, and errcheck, which detects code that might unintentionally ignore errors. == Examples == === Hello world === where "fmt" is the package for formatted I/O, similar to C's C file input/output. === Concurrency === The following simple program demonstrates Go's concurrency features to implement an asynchronous program. It launches two lightweight threads ("goroutines"): one waits for the user to type some text, while the other implements a timeout. The select statement waits for either of these goroutines to send a message to the main routine, and acts on the first message to arrive (example adapted from David Chisnall's book).: 152  === Testing === The testing package provides support for automated testing of go packages. Target function example: Test code (note that assert keyword is missing in Go; tests live in <filename>_test.go at the same package): It is possible to run tests in parallel. === Web app === The net/http package provides support for creating web applications. This example would show "Hello world!" when localhost:8080 is visited. == Applications == Go has found widespread adoption in various domains due to its robust standard library and ease of use. Popular applications include: Caddy, a web server that automates the process of setting up HTTPS, Docker, which provides a platform for containerization, aiming to ease the complexities of software development and deployment, Kubernetes, which automates the deployment, scaling, and management of containerized applications, CockroachDB, a distributed SQL database engineered for scalability and strong consistency, and Hugo, a static site generator that prioritizes speed and flexibility, allowing developers to create websites efficiently. == Reception == The interface system, and the deliberate omission of inheritance, were praised by Michele Simionato, who likened these characteristics to those of Standard ML, calling it "a shame that no popular language has followed [this] particular route". Dave Astels at Engine Yard wrote in 2009: Go is extremely easy to dive into. There are a minimal number of fundamental language concepts and the syntax is clean and designed to be clear and unambiguous. Go is still experimental and still a little rough around the edges. Go was named Programming Language of the Year by the TIOBE Programming Community Index in its first year, 2009, for having a larger 12-month increase in popularity (in only 2 months, after its introduction in November) than any other language that year, and reached 13th place by January 2010, surpassing established languages like Pascal. By June 2015, its ranking had dropped to below 50th in the index, placing it lower than COBOL and Fortran. But as of January 2017, its ranking had surged to 13th, indicating significant growth in popularity and adoption. Go was again awarded TIOBE Programming Language of the Year in 2016. Bruce Eckel has stated: The complexity of C++ (even more complexity has been added in the new C++), and the resulting impact on productivity, is no longer justified. All the hoops that the C++ programmer had to jump through in order to use a C-compatible language make no sense anymore -- they're just a waste of time and effort. Go makes much more sense for the class of problems that C++ was originally intended to solve. A 2011 evaluation of the language and its gc implementation in comparison to C++ (GCC), Java and Scala by a Google engineer found: Go offers interesting language features, which also allow for a concise and standardized notation. The compilers for this language are still immature, which reflects in both performance and binary sizes. The evaluation got a rebuttal from the Go development team. Ian Lance Taylor, who had improved the Go code for Hundt's paper, had not been aware of the intention to publish his code, and says that his version was "never intended to be an example of idiomatic or efficient Go"; Russ Cox then optimized the Go code, as well as the C++ code, and got the Go code to run almost as fast as the C++ version and more than an order of magnitude faster than the code in the paper. Go's nil combined with the lack of algebraic types leads to difficulty handling failures and base cases. Go does not allow an opening brace to appear on its own line, which forces all Go programmers to use the same brace style. Go has been criticized for focusing on simplicity of implementation rather than correctness and flexibility; as an example, the language uses POSIX file semantics on all platforms, and therefore provides incorrect information on platforms such as Windows (which do not follow the aforementioned standard). A study showed that it is as easy to make concurrency bugs with message passing as with shared memory, sometimes even more. == Naming dispute == On November 10, 2009, the day of the general release of the language, Francis McCabe, developer of the Go! programming language (note the exclamation point), requested a name change of Google's language to prevent confusion with his language, which he had spent 10 years developing. McCabe raised concerns that "the 'big guy' will end up steam-rollering over" him, and this concern resonated with the more than 120 developers who commented on Google's official issues thread saying they should change the name, with some even saying the issue contradicts Google's motto of: Don't be evil. On October 12, 2010, the filed public issue ticket was closed by Google developer Russ Cox (@rsc) with the custom status "Unfortunate" accompanied by the following comment: "There are many computing products and services named Go. In the 11 months since our release, there has been minimal confusion of the two languages." == See also == Fat pointer Comparison of programming languages == Notes == == References == == Further reading == == External links == Official website
https://en.wikipedia.org/wiki/Go_(programming_language)
Quadratic programming (QP) is the process of solving certain mathematical optimization problems involving quadratic functions. Specifically, one seeks to optimize (minimize or maximize) a multivariate quadratic function subject to linear constraints on the variables. Quadratic programming is a type of nonlinear programming. "Programming" in this context refers to a formal procedure for solving mathematical problems. This usage dates to the 1940s and is not specifically tied to the more recent notion of "computer programming." To avoid confusion, some practitioners prefer the term "optimization" — e.g., "quadratic optimization." == Problem formulation == The quadratic programming problem with n variables and m constraints can be formulated as follows. Given: a real-valued, n-dimensional vector c, an n×n-dimensional real symmetric matrix Q, an m×n-dimensional real matrix A, and an m-dimensional real vector b, the objective of quadratic programming is to find an n-dimensional vector x, that will where xT denotes the vector transpose of x, and the notation Ax ⪯ b means that every entry of the vector Ax is less than or equal to the corresponding entry of the vector b (component-wise inequality). === Constrained least squares === As a special case when Q is symmetric positive-definite, the cost function reduces to least squares: where Q = RTR follows from the Cholesky decomposition of Q and c = −RT d. Conversely, any such constrained least squares program can be equivalently framed as a quadratic programming problem, even for a generic non-square R matrix. === Generalizations === When minimizing a function f in the neighborhood of some reference point x0, Q is set to its Hessian matrix H(f(x0)) and c is set to its gradient ∇f(x0). A related programming problem, quadratically constrained quadratic programming, can be posed by adding quadratic constraints on the variables. == Solution methods == For general problems a variety of methods are commonly used, including interior point, active set, augmented Lagrangian, conjugate gradient, gradient projection, extensions of the simplex algorithm. In the case in which Q is positive definite, the problem is a special case of the more general field of convex optimization. === Equality constraints === Quadratic programming is particularly simple when Q is positive definite and there are only equality constraints; specifically, the solution process is linear. By using Lagrange multipliers and seeking the extremum of the Lagrangian, it may be readily shown that the solution to the equality constrained problem Minimize 1 2 x T Q x + c T x {\displaystyle {\text{Minimize}}\quad {\tfrac {1}{2}}\mathbf {x} ^{\mathrm {T} }Q\mathbf {x} +\mathbf {c} ^{\mathrm {T} }\mathbf {x} } subject to E x = d {\displaystyle {\text{subject to}}\quad E\mathbf {x} =\mathbf {d} } is given by the linear system [ Q E ⊤ E 0 ] [ x λ ] = [ − c d ] {\displaystyle {\begin{bmatrix}Q&E^{\top }\\E&0\end{bmatrix}}{\begin{bmatrix}\mathbf {x} \\\lambda \end{bmatrix}}={\begin{bmatrix}-\mathbf {c} \\\mathbf {d} \end{bmatrix}}} where λ is a set of Lagrange multipliers which come out of the solution alongside x. The easiest means of approaching this system is direct solution (for example, LU factorization), which for small problems is very practical. For large problems, the system poses some unusual difficulties, most notably that the problem is never positive definite (even if Q is), making it potentially very difficult to find a good numeric approach, and there are many approaches to choose from dependent on the problem. If the constraints don't couple the variables too tightly, a relatively simple attack is to change the variables so that constraints are unconditionally satisfied. For example, suppose d = 0 (generalizing to nonzero is straightforward). Looking at the constraint equations: E x = 0 {\displaystyle E\mathbf {x} =0} introduce a new variable y defined by Z y = x {\displaystyle Z\mathbf {y} =\mathbf {x} } where y has dimension of x minus the number of constraints. Then E Z y = 0 {\displaystyle EZ\mathbf {y} =\mathbf {0} } and if Z is chosen so that EZ = 0 the constraint equation will be always satisfied. Finding such Z entails finding the null space of E, which is more or less simple depending on the structure of E. Substituting into the quadratic form gives an unconstrained minimization problem: 1 2 x ⊤ Q x + c ⊤ x ⟹ 1 2 y ⊤ Z ⊤ Q Z y + ( Z ⊤ c ) ⊤ y {\displaystyle {\tfrac {1}{2}}\mathbf {x} ^{\top }Q\mathbf {x} +\mathbf {c} ^{\top }\mathbf {x} \quad \implies \quad {\tfrac {1}{2}}\mathbf {y} ^{\top }Z^{\top }QZ\mathbf {y} +\left(Z^{\top }\mathbf {c} \right)^{\top }\mathbf {y} } the solution of which is given by: Z ⊤ Q Z y = − Z ⊤ c {\displaystyle Z^{\top }QZ\mathbf {y} =-Z^{\top }\mathbf {c} } Under certain conditions on Q, the reduced matrix ZTQZ will be positive definite. It is possible to write a variation on the conjugate gradient method which avoids the explicit calculation of Z. == Lagrangian duality == The Lagrangian dual of a quadratic programming problem is also a quadratic programming problem. To see this let us focus on the case where c = 0 and Q is positive definite. We write the Lagrangian function as L ( x , λ ) = 1 2 x ⊤ Q x + λ ⊤ ( A x − b ) . {\displaystyle L(x,\lambda )={\tfrac {1}{2}}x^{\top }Qx+\lambda ^{\top }(Ax-b).} Defining the (Lagrangian) dual function g(λ) as g ( λ ) = inf x L ( x , λ ) {\displaystyle g(\lambda )=\inf _{x}L(x,\lambda )} , we find an infimum of L, using ∇ x L ( x , λ ) = 0 {\displaystyle \nabla _{x}L(x,\lambda )=0} and positive-definiteness of Q: x ∗ = − Q − 1 A ⊤ λ . {\displaystyle x^{*}=-Q^{-1}A^{\top }\lambda .} Hence the dual function is g ( λ ) = − 1 2 λ ⊤ A Q − 1 A ⊤ λ − λ ⊤ b , {\displaystyle g(\lambda )=-{\tfrac {1}{2}}\lambda ^{\top }AQ^{-1}A^{\top }\lambda -\lambda ^{\top }b,} and so the Lagrangian dual of the quadratic programming problem is maximize λ ≥ 0 − 1 2 λ ⊤ A Q − 1 A ⊤ λ − λ ⊤ b . {\displaystyle {\text{maximize}}_{\lambda \geq 0}\quad -{\tfrac {1}{2}}\lambda ^{\top }AQ^{-1}A^{\top }\lambda -\lambda ^{\top }b.} Besides the Lagrangian duality theory, there are other duality pairings (e.g. Wolfe, etc.). == Run-time complexity == === Convex quadratic programming === For positive definite Q, when the problem is convex, the ellipsoid method solves the problem in (weakly) polynomial time. Ye and Tse present a polynomial-time algorithm, which extends Karmarkar's algorithm from linear programming to convex quadratic programming. On a system with n variables and L input bits, their algorithm requires O(L n) iterations, each of which can be done using O(L n3) arithmetic operations, for a total runtime complexity of O(L2 n4). Kapoor and Vaidya present another algorithm, which requires O(L * log L * n3.67 * log n) arithmetic operations. === Non-convex quadratic programming === If Q is indefinite, (so the problem is non-convex) then the problem is NP-hard. A simple way to see this is to consider the non-convex quadratic constraint xi2 = xi. This constraint is equivalent to requiring that xi is in {0,1}, that is, xi is a binary integer variable. Therefore, such constraints can be used to model any integer program with binary variables, which is known to be NP-hard. Moreover, these non-convex problems might have several stationary points and local minima. In fact, even if Q has only one negative eigenvalue, the problem is (strongly) NP-hard. Moreover, finding a KKT point of a non-convex quadratic program is CLS-hard. == Mixed-integer quadratic programming == There are some situations where one or more elements of the vector x will need to take on integer values. This leads to the formulation of a mixed-integer quadratic programming (MIQP) problem. Applications of MIQP include water resources and the construction of index funds. == Solvers and scripting (programming) languages == == Extensions == Polynomial optimization is a more general framework, in which the constraints can be polynomial functions of any degree, not only 2. == See also == Sequential quadratic programming Linear programming Critical line method == References == == Further reading == Cottle, Richard W.; Pang, Jong-Shi; Stone, Richard E. (1992). The linear complementarity problem. Computer Science and Scientific Computing. Boston, MA: Academic Press, Inc. pp. xxiv+762 pp. ISBN 978-0-12-192350-1. MR 1150683. Garey, Michael R.; Johnson, David S. (1979). Computers and Intractability: A Guide to the Theory of NP-Completeness. W.H. Freeman. ISBN 978-0-7167-1045-5. A6: MP2, pg.245. Gould, Nicholas I. M.; Toint, Philippe L. (2000). "A Quadratic Programming Bibliography" (PDF). RAL Numerical Analysis Group Internal Report 2000-1. == External links == A page about quadratic programming NEOS Optimization Guide: Quadratic Programming Quadratic Programming Archived 2023-04-08 at the Wayback Machine Cubic programming and beyond, in Operations Research stack exchange
https://en.wikipedia.org/wiki/Quadratic_programming
Constraint programming (CP) is a paradigm for solving combinatorial problems that draws on a wide range of techniques from artificial intelligence, computer science, and operations research. In constraint programming, users declaratively state the constraints on the feasible solutions for a set of decision variables. Constraints differ from the common primitives of imperative programming languages in that they do not specify a step or sequence of steps to execute, but rather the properties of a solution to be found. In addition to constraints, users also need to specify a method to solve these constraints. This typically draws upon standard methods like chronological backtracking and constraint propagation, but may use customized code like a problem-specific branching heuristic. Constraint programming takes its root from and can be expressed in the form of constraint logic programming, which embeds constraints into a logic program. This variant of logic programming is due to Jaffar and Lassez, who extended in 1987 a specific class of constraints that were introduced in Prolog II. The first implementations of constraint logic programming were Prolog III, CLP(R), and CHIP. Instead of logic programming, constraints can be mixed with functional programming, term rewriting, and imperative languages. Programming languages with built-in support for constraints include Oz (functional programming) and Kaleidoscope (imperative programming). Mostly, constraints are implemented in imperative languages via constraint solving toolkits, which are separate libraries for an existing imperative language. == Constraint logic programming == Constraint programming is an embedding of constraints in a host language. The first host languages used were logic programming languages, so the field was initially called constraint logic programming. The two paradigms share many important features, like logical variables and backtracking. Today most Prolog implementations include one or more libraries for constraint logic programming. The difference between the two is largely in their styles and approaches to modeling the world. Some problems are more natural (and thus, simpler) to write as logic programs, while some are more natural to write as constraint programs. The constraint programming approach is to search for a state of the world in which a large number of constraints are satisfied at the same time. A problem is typically stated as a state of the world containing a number of unknown variables. The constraint program searches for values for all the variables. Temporal concurrent constraint programming (TCC) and non-deterministic temporal concurrent constraint programming (MJV) are variants of constraint programming that can deal with time. == Constraint satisfaction problem == A constraint is a relation between multiple variables that limits the values these variables can take simultaneously. Three categories of constraints exist: extensional constraints: constraints are defined by enumerating the set of values that would satisfy them; arithmetic constraints: constraints are defined by an arithmetic expression, i.e., using < , > , ≤ , ≥ , = , ≠ , . . . {\displaystyle <,>,\leq ,\geq ,=,\neq ,...} ; logical constraints: constraints are defined with an explicit semantics, i.e., AllDifferent, AtMost,... Assignment is the association of a variable to a value from its domain. A partial assignment is when a subset of the variables of the problem has been assigned. A total assignment is when all the variables of the problem have been assigned. During the search of the solutions of a CSP, a user can wish for: finding a solution (satisfying all the constraints); finding all the solutions of the problem; proving the unsatisfiability of the problem. == Constraint optimization problem == A constraint optimization problem (COP) is a constraint satisfaction problem associated to an objective function. An optimal solution to a minimization (maximization) COP is a solution that minimizes (maximizes) the value of the objective function. During the search of the solutions of a COP, a user can wish for: finding a solution (satisfying all the constraints); finding the best solution with respect to the objective; proving the optimality of the best found solution; proving the unsatisfiability of the problem. == Perturbation vs refinement models == Languages for constraint-based programming follow one of two approaches: Refinement model: variables in the problem are initially unassigned, and each variable is assumed to be able to contain any value included in its range or domain. As computation progresses, values in the domain of a variable are pruned if they are shown to be incompatible with the possible values of other variables, until a single value is found for each variable. Perturbation model: variables in the problem are assigned a single initial value. At different times one or more variables receive perturbations (changes to their old value), and the system propagates the change trying to assign new values to other variables that are consistent with the perturbation. Constraint propagation in constraint satisfaction problems is a typical example of a refinement model, and formula evaluation in spreadsheets are a typical example of a perturbation model. The refinement model is more general, as it does not restrict variables to have a single value, it can lead to several solutions to the same problem. However, the perturbation model is more intuitive for programmers using mixed imperative constraint object-oriented languages. == Domains == The constraints used in constraint programming are typically over some specific domains. Some popular domains for constraint programming are: Boolean domains, where only true/false constraints apply (SAT problem) integer domains, rational domains interval domains, in particular for scheduling problems linear domains, where only linear functions are described and analyzed (although approaches to non-linear problems do exist) finite domains, where constraints are defined over finite sets mixed domains, involving two or more of the above Finite domains is one of the most successful domains of constraint programming. In some areas (like operations research) constraint programming is often identified with constraint programming over finite domains. == Constraint propagation == Local consistency conditions are properties of constraint satisfaction problems related to the consistency of subsets of variables or constraints. They can be used to reduce the search space and make the problem easier to solve. Various kinds of local consistency conditions are leveraged, including node consistency, arc consistency, and path consistency. Every local consistency condition can be enforced by a transformation that changes the problem without changing its solutions. Such a transformation is called constraint propagation. Constraint propagation works by reducing domains of variables, strengthening constraints, or creating new ones. This leads to a reduction of the search space, making the problem easier to solve by some algorithms. Constraint propagation can also be used as an unsatisfiability checker, incomplete in general but complete in some particular cases. == Constraint solving == There are three main algorithmic techniques for solving constraint satisfaction problems: backtracking search, local search, and dynamic programming. === Backtracking search === Backtracking search is a general algorithm for finding all (or some) solutions to some computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate ("backtracks") as soon as it determines that the candidate cannot possibly be completed to a valid solution. === Local Search === Local search is an incomplete method for finding a solution to a problem. It is based on iteratively improving an assignment of the variables until all constraints are satisfied. In particular, local search algorithms typically modify the value of a variable in an assignment at each step. The new assignment is close to the previous one in the space of assignment, hence the name local search. === Dynamic programming === Dynamic programming is both a mathematical optimization method and a computer programming method. It refers to simplifying a complicated problem by breaking it down into simpler sub-problems in a recursive manner. While some decision problems cannot be taken apart this way, decisions that span several points in time do often break apart recursively. Likewise, in computer science, if a problem can be solved optimally by breaking it into sub-problems and then recursively finding the optimal solutions to the sub-problems, then it is said to have optimal substructure. == Example == The syntax for expressing constraints over finite domains depends on the host language. The following is a Prolog program that solves the classical alphametic puzzle SEND+MORE=MONEY in constraint logic programming: The interpreter creates a variable for each letter in the puzzle. The operator ins is used to specify the domains of these variables, so that they range over the set of values {0,1,2,3, ..., 9}. The constraints S#\=0 and M#\=0 means that these two variables cannot take the value zero. When the interpreter evaluates these constraints, it reduces the domains of these two variables by removing the value 0 from them. Then, the constraint all_different(Digits) is considered; it does not reduce any domain, so it is simply stored. The last constraint specifies that the digits assigned to the letters must be such that "SEND+MORE=MONEY" holds when each letter is replaced by its corresponding digit. From this constraint, the solver infers that M=1. All stored constraints involving variable M are awakened: in this case, constraint propagation on the all_different constraint removes value 1 from the domain of all the remaining variables. Constraint propagation may solve the problem by reducing all domains to a single value, it may prove that the problem has no solution by reducing a domain to the empty set, but may also terminate without proving satisfiability or unsatisfiability. The label literals are used to actually perform search for a solution. == See also == Combinatorial optimization Concurrent constraint logic programming Constraint logic programming Heuristic algorithms List of constraint programming languages Mathematical optimization Nurse scheduling problem Regular constraint Satisfiability modulo theories Traveling tournament problem == References == == External links == Association for Constraint Programming CP Conference Series Guide to Constraint Programming The Mozart Programming System at archive.today (archived December 5, 2012), an Oz-based free software (X Window System style) Cork Constraint Computation Centre at archive.today (archived January 7, 2013)
https://en.wikipedia.org/wiki/Constraint_programming
Software consists of computer programs that instruct the execution of a computer. Software also includes design documents and specifications. The history of software is closely tied to the development of digital computers in the mid-20th century. Early programs were written in the machine language specific to the hardware. The introduction of high-level programming languages in 1958 allowed for more human-readable instructions, making software development easier and more portable across different computer architectures. Software in a programming language is run through a compiler or interpreter to execute on the architecture's hardware. Over time, software has become complex, owing to developments in networking, operating systems, and databases. Software can generally be categorized into two main types: operating systems, which manage hardware resources and provide services for applications application software, which performs specific tasks for users The rise of cloud computing has introduced the new software delivery model Software as a Service (SaaS). In SaaS, applications are hosted by a provider and accessed over the Internet. The process of developing software involves several stages. The stages include software design, programming, testing, release, and maintenance. Software quality assurance and security are critical aspects of software development, as bugs and security vulnerabilities can lead to system failures and security breaches. Additionally, legal issues such as software licenses and intellectual property rights play a significant role in the distribution of software products. == History == The first use of the word software to describe computer programs is credited to mathematician John Wilder Tukey in 1958. The first programmable computers, which appeared at the end of the 1940s, were programmed in machine language. Machine language is difficult to debug and not portable across different computers. Initially, hardware resources were more expensive than human resources. As programs became complex, programmer productivity became the bottleneck. The introduction of high-level programming languages in 1958 hid the details of the hardware and expressed the underlying algorithms into the code . Early languages include Fortran, Lisp, and COBOL. == Types == There are two main types of software: Operating systems are "the layer of software that manages a computer's resources for its users and their applications". There are three main purposes that an operating system fulfills: Allocating resources between different applications, deciding when they will receive central processing unit (CPU) time or space in memory. Providing an interface that abstracts the details of accessing hardware details (like physical memory) to make things easier for programmers. Offering common services, such as an interface for accessing network and disk devices. This enables an application to be run on different hardware without needing to be rewritten. Application software runs on top of the operating system and uses the computer's resources to perform a task. There are many different types of application software because the range of tasks that can be performed with modern computers is so large. Applications account for most software and require the environment provided by an operating system, and often other applications, in order to function. Software can also be categorized by how it is deployed. Traditional applications are purchased with a perpetual license for a specific version of the software, downloaded, and run on hardware belonging to the purchaser. The rise of the Internet and cloud computing enabled a new model, software as a service (SaaS), in which the provider hosts the software (usually built on top of rented infrastructure or platforms) and provides the use of the software to customers, often in exchange for a subscription fee. By 2023, SaaS products—which are usually delivered via a web application—had become the primary method that companies deliver applications. == Software development and maintenance == Software companies aim to deliver a high-quality product on time and under budget. A challenge is that software development effort estimation is often inaccurate. Software development begins by conceiving the project, evaluating its feasibility, analyzing the business requirements, and making a software design. Most software projects speed up their development by reusing or incorporating existing software, either in the form of commercial off-the-shelf (COTS) or open-source software. Software quality assurance is typically a combination of manual code review by other engineers and automated software testing. Due to time constraints, testing cannot cover all aspects of the software's intended functionality, so developers often focus on the most critical functionality. Formal methods are used in some safety-critical systems to prove the correctness of code, while user acceptance testing helps to ensure that the product meets customer expectations. There are a variety of software development methodologies, which vary from completing all steps in order to concurrent and iterative models. Software development is driven by requirements taken from prospective users, as opposed to maintenance, which is driven by events such as a change request. Frequently, software is released in an incomplete state when the development team runs out of time or funding. Despite testing and quality assurance, virtually all software contains bugs where the system does not work as intended. Post-release software maintenance is necessary to remediate these bugs when they are found and keep the software working as the environment changes over time. New features are often added after the release. Over time, the level of maintenance becomes increasingly restricted before being cut off entirely when the product is withdrawn from the market. As software ages, it becomes known as legacy software and can remain in use for decades, even if there is no one left who knows how to fix it. Over the lifetime of the product, software maintenance is estimated to comprise 75 percent or more of the total development cost. Completing a software project involves various forms of expertise, not just in software programmers but also testing, documentation writing, project management, graphic design, user experience, user support, marketing, and fundraising. == Quality and security == Software quality is defined as meeting the stated requirements as well as customer expectations. Quality is an overarching term that can refer to a code's correct and efficient behavior, its reusability and portability, or the ease of modification. It is usually more cost-effective to build quality into the product from the beginning rather than try to add it later in the development process. Higher quality code will reduce lifetime cost to both suppliers and customers as it is more reliable and easier to maintain. Software failures in safety-critical systems can be very serious including death. By some estimates, the cost of poor quality software can be as high as 20 to 40 percent of sales. Despite developers' goal of delivering a product that works entirely as intended, virtually all software contains bugs. The rise of the Internet also greatly increased the need for computer security as it enabled malicious actors to conduct cyberattacks remotely. If a bug creates a security risk, it is called a vulnerability. Software patches are often released to fix identified vulnerabilities, but those that remain unknown (zero days) as well as those that have not been patched are still liable for exploitation. Vulnerabilities vary in their ability to be exploited by malicious actors, and the actual risk is dependent on the nature of the vulnerability as well as the value of the surrounding system. Although some vulnerabilities can only be used for denial of service attacks that compromise a system's availability, others allow the attacker to inject and run their own code (called malware), without the user being aware of it. To thwart cyberattacks, all software in the system must be designed to withstand and recover from external attack. Despite efforts to ensure security, a significant fraction of computers are infected with malware. == Encoding and execution == === Programming languages === Programming languages are the format in which software is written. Since the 1950s, thousands of different programming languages have been invented; some have been in use for decades, while others have fallen into disuse. Some definitions classify machine code—the exact instructions directly implemented by the hardware—and assembly language—a more human-readable alternative to machine code whose statements can be translated one-to-one into machine code—as programming languages. Programs written in the high-level programming languages used to create software share a few main characteristics: knowledge of machine code is not necessary to write them, they can be ported to other computer systems, and they are more concise and human-readable than machine code. They must be both human-readable and capable of being translated into unambiguous instructions for computer hardware. === Compilation, interpretation, and execution === The invention of high-level programming languages was simultaneous with the compilers needed to translate them automatically into machine code. Most programs do not contain all the resources needed to run them and rely on external libraries. Part of the compiler's function is to link these files in such a way that the program can be executed by the hardware. Once compiled, the program can be saved as an object file and the loader (part of the operating system) can take this saved file and execute it as a process on the computer hardware. Some programming languages use an interpreter instead of a compiler. An interpreter converts the program into machine code at run time, which makes them 10 to 100 times slower than compiled programming languages. == Legal issues == === Liability === Software is often released with the knowledge that it is incomplete or contains bugs. Purchasers knowingly buy it in this state, which has led to a legal regime where liability for software products is significantly curtailed compared to other products. === Licenses === Since the mid-1970s, software and its source code have been protected by copyright law that vests the owner with the exclusive right to copy the code. The underlying ideas or algorithms are not protected by copyright law, but are sometimes treated as a trade secret and concealed by such methods as non-disclosure agreements. A software copyright is often owned by the person or company that financed or made the software (depending on their contracts with employees or contractors who helped to write it). Some software is in the public domain and has no restrictions on who can use it, copy or share it, or modify it; a notable example is software written by the United States Government. Free and open-source software also allow free use, sharing, and modification, perhaps with a few specified conditions. The use of some software is governed by an agreement (software license) written by the copyright holder and imposed on the user. Proprietary software is usually sold under a restrictive license that limits its use and sharing. Some free software licenses require that modified versions must be released under the same license, which prevents the software from being sold or distributed under proprietary restrictions. === Patents === Patents give an inventor an exclusive, time-limited license for a novel product or process. Ideas about what software could accomplish are not protected by law and concrete implementations are instead covered by copyright law. In some countries, a requirement for the claimed invention to have an effect on the physical world may also be part of the requirements for a software patent to be held valid. Software patents have been historically controversial. Before the 1998 case State Street Bank & Trust Co. v. Signature Financial Group, Inc., software patents were generally not recognized in the United States. In that case, the Supreme Court decided that business processes could be patented. Patent applications are complex and costly, and lawsuits involving patents can drive up the cost of products. Unlike copyrights, patents generally only apply in the jurisdiction where they were issued. == Impact == Engineer Capers Jones writes that "computers and software are making profound changes to every aspect of human life: education, work, warfare, entertainment, medicine, law, and everything else". It has become ubiquitous in everyday life in developed countries. In many cases, software augments the functionality of existing technologies such as household appliances and elevators. Software also spawned entirely new technologies such as the Internet, video games, mobile phones, and GPS. New methods of communication, including email, forums, blogs, microblogging, wikis, and social media, were enabled by the Internet. Massive amounts of knowledge exceeding any paper-based library are now available with a quick web search. Most creative professionals have switched to software-based tools such as computer-aided design, 3D modeling, digital image editing, and computer animation. Almost every complex device is controlled by software. == References == === Sources ===
https://en.wikipedia.org/wiki/Software
Programming productivity (also called software productivity or development productivity) describes the degree of the ability of individual programmers or development teams to build and evolve software systems. Productivity traditionally refers to the ratio between the quantity of software produced and the cost spent for it. Here the delicacy lies in finding a reasonable way to define software quantity. == Terminology == Productivity is an important topic investigated in disciplines as various as manufacturing, organizational psychology, industrial engineering, strategic management, finance, accounting, marketing and economics. Levels of analysis include the individual, the group, divisional, organizational and national levels. Due to this diversity, there is no clear-cut definition of productivity and its influencing factors, although research has been conducted for more than a century. Like in software engineering, this lack of common agreement on what actually constitutes productivity, is perceived as a major obstacle for a substantiated discussion of productivity. The following definitions describe the best consensus on the terminology. === Productivity === While there is no commonly agreed on definition of productivity, there appears to be an agreement that productivity describes the ratio between output and input: Productivity = Output / Input However, across the various disciplines different notions and, particularly, different measurement units for input and output can be found. The manufacturing industry typically uses a straightforward relation between the number of units produced and the number of units consumed. Non-manufacturing industries usually use man-hours or similar units to enable comparison between outputs and inputs. One basic agreement is that the meaning of productivity and the means for measuring it vary depending on what context is under evaluation. In a manufacturing company the possible contexts are: the individual machine or manufacturing system; the manufacturing function, for example assembly; the manufacturing process for a single product or group of related products; the factory; and the company's entire factory system As long classical production processes are considered a straightforward metric of productivity is simple: how many units of a product of specified quality is produced by which costs. For intellectual work, productivity is much trickier. How do we measure the productivity of authors, scientists, or engineers? Due to the rising importance of knowledge work (as opposed to manual work), many researchers tried to develop productivity measurement means that can be applied in a non-manufacturing context. It is commonly agreed that the nature of knowledge work fundamentally differs from manual work and, hence, factors besides the simple output/input ratio need to be taken into account, e.g. quality, timeliness, autonomy, project success, customer satisfaction and innovation. However, the research communities in neither discipline have been able to establish broadly applicable and accepted means for productivity measurement yet. The same holds for more specific area of programming productivity. === Profitability === Profitability and performance are closely linked and are, in fact, often confused. However, as profitability is usually defined as the ratio between revenue and cost Profitability = Revenue / Cost It has a wider scope than performance, i.e. the number of factors that influence profitability is greater than the number of factors than influence productivity. Particularly, profitability can change without any change to the productivity, e.g. due to external conditions like cost or price inflation. Besides that, the interdependency between productivity and profitability is usually delayed, i.e. gains in productivity are rarely reflected in immediate profitability gains are more likely realized on the long-term. === Performance === The term performance is even broader than productivity and profitability and covers a plethora of factors that influence a company's success. Hence, well-known performance controlling instruments like the Balanced Scorecard do include productivity as a factor that is central but not unique. Other relevant factors are e.g. the customers’ or stakeholders’ perception of the company. === Efficiency and effectiveness === Efficiency and effectiveness are terms that provide further confusion as they themselves are often mixed up and, additionally, efficiency is often confused with productivity. The difference between efficiency and effectiveness is usually explained informally as efficiency is doing things right and effectiveness is doing the right things. While there are numerous other definitions, there is a certain agreement that efficiency refers to the utilisation of resources and mainly influences the required input of the productivity ratio. Effectiveness on the other hand mainly influences the output of the productivity ratio as it usually has direct consequences for the customer. Effectiveness can be defined as "the ability to reach a desired output". Generally, it is assumed, that efficiency can be quantified, e.g. by utilization rates, considerably more easily than effectiveness. === Quality === Tangen states: "Improvements in quality, other than the fact that no-fault products add to output levels, ought not to be included in the concept of productivity." However, most of the classic literature in non-software disciplines, especially in the manufacturing area, does not explicitly discuss the role of quality of the output in the productivity ratio. More recent works from non-manufacturing disciplines have a stronger focus on knowledge, office or white-collar work and hence increasingly discuss the role of quality with respect to quality. Drucker stresses the importance of quality for the evaluation of knowledge worker productivity: "Productivity of knowledge work therefore has to aim first at obtaining quality—and not minimum quality but optimum if not maximum quality. Only then can one ask: "What is the volume, the quantity of work?"" Saari captures the importance of quality with his extended formula for productivity: Total productivity = (Output quality and quantity)/(Input quality and quantity) However, it appears that these efforts to include the quality in the determination of productivity did not lead to an operationalizable concept yet. It currently remains unclear how to quantify the vague terms “Output quality and quantity” as well as “Input quality and quantity”, let alone to calculate the ratio. == State of the art == In software development things are more complicated than in the production of goods. Software development is an engineering process. === COCOMO II === Boehm was one of the first researchers that systematically approached the field of software productivity. His cost estimation model COCOMO - now COCOMO II - is standard software engineering knowledge. In this model, he defines a set of factors that influence productivity, such as the required reliability or the capability of the analysts. These factors have been widely reused in other similar productivity approaches. The rest of the model is based on function points and finally source lines of code (LOC). The limitations of LOC as a productivity measure are well-known. === Jones's software productivity === Jones is the author of a series of books on software productivity. Besides several theoretical considerations his main contribution is the systematic provision and integration of a large amount of data relevant for productivity analyses. In at least two of his books, he gives a number of productivity factors but also points out that for each project a different set of factors are influential. These factors can form a basis for productivity assessments and for comparison with industrial averages. This is one such list: The 20 factors whose quantified impacts on software projects have been determined from historical data are the following: Programming language used Program size The experience of programmers and design personnel The novelty of requirements The complexity of the program and its data The use of structured programming methods Program class or the distribution method Program type of the application area Tools and environmental conditions Enhancing existing programs or systems Maintaining existing programs or systems Reusing existing modules and standard designs Program generators Fourth-generation languages Geographic separation of development locations Defect potentials and removal methods Existing documentation Prototyping before main development begins Project teams and organization structures Morale and compensation of staff === Function points === Function points were proposed in 1977 by Albrecht as a better size measure for software than LOC. In that it is based on the specification of the software and thereby aims at measuring the size of its functionality rather than the code itself. The reason is that the size of the code not only depends on the size of the functionality but also on the capability of the programmer: better programmers will produce less code for the same functionality. The function points have undergone several redesigns over the years mainly driven by the International Function Point User Group (IFPUG). This group is large with over 1200 companies as member which shows the rather strong acceptance of this measure. However, in many domains it still lacks practical application because it is often conceived as only applicable to business information systems. === Value-based software engineering === Several researchers proposed economic-driven or value-based software engineering as an important paradigm in future software engineering research. Boehm and Huang point out that is it not only important to track the costs in a software project but also the real earned value, i.e. the value for the customer. They explain that it is important to create the software business case and keep it up to date. In essence, value-based software engineering focuses on the customer value, mainly measured in monetary units. === Peopleware === The famous book Peopleware: Productive Projects and Teams by de Marco and Lister brought the importance of people-related factors to the attention of a broader audience. They collected in many software projects experiences with good and bad management practice that have an influence on the productivity of the team. They and others showed that these are the decisive issues in software engineering but were only able to describe them anecdotally. == Factors influencing programming productivity == There are probably a large number of factors influencing the programming productivity of individuals and teams. For example, the used software development process probably influences the effectiveness and efficiency of a team. The personalities of software programmers influence the used coding styles which, in turn, influence the productivity of the programmers. == In popular culture == In 2007, the xkcd comic popularized the concept of a Ballmer Peak—that a programmer, with just the right amount of inebriation, achieves a high state of productivity. The Ballmer Peak is named after former Microsoft CEO, Steve Ballmer, and is likely a play on Balmer series of hydrogen spectral lines named for Johann Balmer. == References == == Further reading == Software Cost Estimation with Cocomo II, Barry W. Boehm et al., Prentice Hall, 2000. ISBN 978-0-13-026692-7. Developing Products in Half the Time: New Rules, New Tools, Preston G. Smith and Donald G. Reinertsen, Wiley, 1997. ISBN 978-0-471-29252-4. Programming Productivity, Capers Jones, Mcgraw-Hill, 1986. ISBN 978-0-07-032811-2. Estimating Software Costs, Capers Jones, McGraw-Hill, 2007. ISBN 978-0-07-148300-1.
https://en.wikipedia.org/wiki/Programming_productivity
Egoless programming is a style of computer programming in which personal factors are minimized so that quality may be improved. The cooperative methods suggested are similar to those used by other collective ventures such as Wikipedia. == History == The concept was first propounded by Gerald M. Weinberg in his 1971 book, The Psychology of Computer Programming. == Peer reviews of code == To ensure quality, reviews of code by other programmers are made. The concept of egoless programming emphasises that such reviews should be made in a friendly, collegial way in which personal feelings are put aside. Structured walkthroughs are one way of making such a formal review. == Strengths == Works best for complex tasks. ('difficult' used in ) Open communication channels allow information to flow freely to team members Greater conformity that helps in consistent documentation Team members have greater job satisfaction. == Weaknesses == Projects take longer to complete. Projects experience a higher failure rate due to the decentralized nature of and volume of communication between members of the team. Risky shift phenomenon – Programmers attempt riskier solutions to solve a software problem. Simple tasks are made more difficult by open communication channels. Note: The single paper cited for 'Strengths & Weaknesses' is from 1981 and says in its conclusions: Most of the research on group problem-solving behavior was conducted in a laboratory setting with students and tasks of short duration. None of these task/structure recommendations have been tested in a software development environment. == Rival concepts == Egoless programming explicitly minimizes constraints of hierarchy and status so as to enable the free exchange of ideas and improvements. It may be contrasted with the chief programmer team concept which emphasises specialisation and leadership in teams so that they work in a more disciplined way. == See also == List of software development philosophies Software review Egolessness == References == == External links == The Ten Commandments of Egoless Programming
https://en.wikipedia.org/wiki/Egoless_programming
In programming, a gotcha is a valid construct in a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome. == Example == The classic gotcha in C/C++ is the construct It is syntactically valid: it puts the value of b into a and then executes code if a is non-zero. Sometimes this is even intended. However most commonly it is a typo: the programmer probably meant which executes code if a and b are equal. Modern compilers will usually generate a warning when encountering the former construct (conditional branch on assignment, not comparison), depending on compiler options (e.g., the -Wall option for gcc). To avoid this gotcha, some programming languages such include specific syntax for when this is desired behavior, such as Python's "walrus" operator (:=). In languages where this specific syntax does not exist, there is a recommendation to keep the constants in the left side of the comparison, e.g. 42 == x rather than x == 42. This way, using = instead of == will cause a compiler error (see Yoda conditions). Many kinds of gotchas are not detected by compilers, however. == See also == Usability == References == == Further reading == Stephen C. Dewhurst (2003). C++ Gotchas (Avoiding Common Problems in Coding and Design). Addison-Wesley. ISBN 0321125185. == External links == C Traps and Pitfalls by Andrew Koenig C++ Gotchas A programmer's guide to avoiding and correcting ninety-nine of the most common, destructive, and interesting C++ design and programming errors, by Stephen C. Dewhurst
https://en.wikipedia.org/wiki/Gotcha_(programming)
In software engineering, "programming in the large" and "programming in the small" refer to two different aspects of writing software. "Programming in the large" means designing a larger system as a composition of smaller parts, and "programming in the small" means creating those smaller parts by writing lines of code in a programming language. The terms were coined by Frank DeRemer and Hans Kron in their 1975 paper "Programming-in-the-large versus programming-in-the-small", in which they argue that the two are essentially different activities, and that typical programming languages, and the practice of structured programming, provide good support for the latter, but not for the former. This may be compared to the later Ousterhout's dichotomy, which distinguishes between system programming languages (for components) and scripting languages (for glue code, connecting components). == Description == Fred Brooks identifies that the way an individual program is created is different from how a programming systems product is created. The former likely does one relatively simple task well. It is probably coded by a single engineer, is complete in itself, and is ready to run on the system on which it was developed. The programming activity was probably fairly short-lived as simple tasks are quick and easy to complete. This is the endeavor that DeRemer and Kron describe as programming in the small. Compare with the activities associated with a programming systems project, again as identified by Brooks. Such a project is typified by medium-sized or large industrial teams working on the project for many months to several years. The project is likely to be split up into several or hundreds of separate modules which individually are of a similar complexity to the individual programs described above. However, each module will define an interface to its surrounding modules. Brooks describes how programming systems projects are typically run as formal projects that follow industry best practices and will comprise testing, documentation and ongoing maintenance activities as well as activities to ensure that the product is generalized to work in different scenarios including on systems other than the development systems on which it was created. == Programming in the large == In software development, programming in the large can involve programming by larger groups of people or by smaller groups over longer time periods. Either of these conditions will result in large, and hence complicated, programs that can be challenging for maintainers to understand. With programming in the large, coding managers place emphasis on partitioning work into modules with precisely-specified interactions. This requires careful planning and documentation. With programming in the large, program changes can become difficult. If a change operates across module boundaries, the work of many people may need re-doing. Because of this, one goal of programming in the large involves setting up modules that will not need altering in the event of probable changes. This is achieved by designing modules so they have high cohesion and loose coupling. Programming in the large requires management skills. The process of building abstractions aims not just to describe something that can work but also to direct the efforts of people who will make it work. The concept was introduced by Frank DeRemer and Hans Kron in their 1975 paper "Programming-in-the-Large Versus Programming-in-the-Small", IEEE Trans. on Soft. Eng. 2(2). In computer science terms, programming in the large can refer to programming code that represents the high-level state transition logic of a system. This logic encodes information such as when to wait for messages, when to send messages, when to compensate for failed non-ACID transactions, etc. A language that was designed to explicitly support programming in the large is BPEL. == Programming in the small == In software development, programming in the small describes the activity of writing a small program. Small programs are typified by being small in terms of their source code size, are easy to specify, quick to code and typically perform one task or a few very closely related tasks very well. Programming in the small can involve programming by individuals or small groups over short time periods and may involve less formal practices (for instance less emphasis on documentation or testing), tools and programming languages (e.g. the selection of a loosely typed scripting language in preference to a strictly typed programming language). Programming in the small can also describe an approach to building prototype software, or when rapid application development is more important than stability or correctness. In computer science terms, programming in the small deals with short-lived programmatic behavior, often executed as a single ACID transaction and which allows access to local logic and resources such as files, databases, etc. == References == == Further reading == DeRemer, Frank; Kron, Hans (1975). "Programming-in-the large versus programming-in-the-small". Proceedings of the international conference on Reliable software. Los Angeles, California: Association for Computing Machinery. pp. 114–121. doi:10.1145/800027.808431.
https://en.wikipedia.org/wiki/Programming_in_the_large_and_programming_in_the_small
Comet is a web application model in which a long-held HTTPS request allows a web server to push data to a browser, without the browser explicitly requesting it. Comet is an umbrella term, encompassing multiple techniques for achieving this interaction. All these methods rely on features included by default in browsers, such as JavaScript, rather than on non-default plugins. The Comet approach differs from the original model of the web, in which a browser requests a complete web page at a time. The use of Comet techniques in web development predates the use of the word Comet as a neologism for the collective techniques. Comet is known by several other names, including Ajax Push, Reverse Ajax, Two-way-web, HTTP Streaming, and HTTP server push among others. The term Comet is not an acronym, but was coined by Alex Russell in his 2006 blog post. In recent years, the standardisation and widespread support of WebSocket and Server-sent events has rendered the Comet model obsolete. == History == === Early Java applets === The ability to embed Java applets into browsers (starting with Netscape Navigator 2.0 in March 1996) made two-way sustained communications possible, using a raw TCP socket to communicate between the browser and the server. This socket can remain open as long as the browser is at the document hosting the applet. Event notifications can be sent in any format – text or binary – and decoded by the applet. === The first browser-to-browser communication framework === The very first application using browser-to-browser communications was Tango Interactive, implemented in 1996–98 at the Northeast Parallel Architectures Center (NPAC) at Syracuse University using DARPA funding. TANGO architecture has been patented by Syracuse University. TANGO framework has been extensively used as a distance education tool. The framework has been commercialized by CollabWorx and used in a dozen or so Command&Control and Training applications in the United States Department of Defense. === First Comet applications === The first set of Comet implementations dates back to 2000, with the Pushlets, Lightstreamer, and KnowNow projects. Pushlets, a framework created by Just van den Broecke, was one of the first open source implementations. Pushlets were based on server-side Java servlets, and a client-side JavaScript library. Bang Networks – a Silicon Valley start-up backed by Netscape co-founder Marc Andreessen – had a lavishly-financed attempt to create a real-time push standard for the entire web. In April 2001, Chip Morningstar began developing a Java-based (J2SE) web server which used two HTTP sockets to keep open two communications channels between the custom HTTP server he designed and a client designed by Douglas Crockford; a functioning demo system existed as of June 2001. The server and client used a messaging format that the founders of State Software, Inc. assented to coin as JSON following Crockford's suggestion. The entire system, the client libraries, the messaging format known as JSON and the server, became the State Application Framework, parts of which were sold and used by Sun Microsystems, Amazon.com, EDS and Volkswagen. In March 2006, software engineer Alex Russell coined the term Comet in a post on his personal blog. The new term was a play on Ajax (Ajax and Comet both being common household cleaners in the USA). In 2006, some applications exposed those techniques to a wider audience: Meebo’s multi-protocol web-based chat application enabled users to connect to AOL, Yahoo, and Microsoft chat platforms through the browser; Google added web-based chat to Gmail; JotSpot, a startup since acquired by Google, built Comet-based real-time collaborative document editing. New Comet variants were created, such as the Java-based ICEfaces JSF framework (although they prefer the term "Ajax Push"). Others that had previously used Java-applet based transports switched instead to pure-JavaScript implementations. == Implementations == Comet applications attempt to eliminate the limitations of the page-by-page web model and traditional polling by offering two-way sustained interaction, using a persistent or long-lasting HTTP connection between the server and the client. Since browsers and proxies are not designed with server events in mind, several techniques to achieve this have been developed, each with different benefits and drawbacks. The biggest hurdle is the HTTP 1.1 specification, which states "this specification... encourages clients to be conservative when opening multiple connections". Therefore, holding one connection open for real-time events has a negative impact on browser usability: the browser may be blocked from sending a new request while waiting for the results of a previous request, e.g., a series of images. This can be worked around by creating a distinct hostname for real-time information, which is an alias for the same physical server. This strategy is an application of domain sharding. Specific methods of implementing Comet fall into two major categories: streaming and long polling. === Streaming === An application using streaming Comet opens a single persistent connection from the client browser to the server for all Comet events. These events are incrementally handled and interpreted on the client side every time the server sends a new event, with neither side closing the connection. Specific techniques for accomplishing streaming Comet include the following: ==== Hidden iframe ==== A basic technique for dynamic web application is to use a hidden iframe HTML element (an inline frame, which allows a website to embed one HTML document inside another). This invisible iframe is sent as a chunked block, which implicitly declares it as infinitely long (sometimes called "forever frame"). As events occur, the iframe is gradually filled with script tags, containing JavaScript to be executed in the browser. Because browsers render HTML pages incrementally, each script tag is executed as it is received. Some browsers require a specific minimum document size before parsing and execution is started, which can be obtained by initially sending 1–2 kB of padding spaces. One benefit of the iframes method is that it works in every common browser. Two downsides of this technique are the lack of a reliable error handling method, and the impossibility of tracking the state of the request calling process. ==== XMLHttpRequest ==== The XMLHttpRequest (XHR) object, a tool used by Ajax applications for browser–server communication, can also be pressed into service for server–browser Comet messaging by generating a custom data format for an XHR response, and parsing out each event using browser-side JavaScript; relying only on the browser firing the onreadystatechange callback each time it receives new data. === Ajax with long polling === None of the above streaming transports work across all modern browsers without negative side-effects. This forces Comet developers to implement several complex streaming transports, switching between them depending on the browser. Consequently, many Comet applications use long polling, which is easier to implement on the browser side, and works, at minimum, in every browser that supports XHR. As the name suggests, long polling requires the client to poll the server for an event (or set of events). The browser makes an Ajax-style request to the server, which is kept open until the server has new data to send to the browser, which is sent to the browser in a complete response. The browser initiates a new long polling request in order to obtain subsequent events. IETF RFC 6202 "Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP" compares long polling and HTTP streaming. Specific technologies for accomplishing long-polling include the following: ==== XMLHttpRequest long polling ==== For the most part, XMLHttpRequest long polling works like any standard use of XHR. The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. ==== Script tag long polling ==== While any Comet transport can be made to work across subdomains, none of the above transports can be used across different second-level domains (SLDs), due to browser security policies designed to prevent cross-site scripting attacks. That is, if the main web page is served from one SLD, and the Comet server is located at another SLD (which does not have cross-origin resource sharing enabled), Comet events cannot be used to modify the HTML and DOM of the main page, using those transports. This problem can be sidestepped by creating a proxy server in front of one or both sources, making them appear to originate from the same domain. However, this is often undesirable for complexity or performance reasons. Unlike iframes or XMLHttpRequest objects, script tags can be pointed at any URI, and JavaScript code in the response will be executed in the current HTML document. This creates a potential security risk for both servers involved, though the risk to the data provider (in our case, the Comet server) can be avoided using JSONP. A long-polling Comet transport can be created by dynamically creating script elements, and setting their source to the location of the Comet server, which then sends back JavaScript (or JSONP) with some event as its payload. Each time the script request is completed, the browser opens a new one, just as in the XHR long polling case. This method has the advantage of being cross-browser while still allowing cross-domain implementations. == Alternatives == Browser-native technologies are inherent in the term Comet. Attempts to improve non-polling HTTP communication have come from multiple sides: The HTML 5 specification produced by the Web Hypertext Application Technology Working Group (WHATWG) specifies so called server-sent events, which defines a new JavaScript interface EventSource and a new MIME type text/event-stream. The HTML 5 WebSocket API working specifies a method for creating a persistent connection with a server and receiving messages via an onmessage callback. The Bayeux protocol by the Dojo Foundation. It leaves browser-specific transports in place, and defines a higher-level protocol for communication between browser and server, with the aim of allowing re-use of client-side JavaScript code with multiple Comet servers, and allowing the same Comet server to communicate with multiple client-side JavaScript implementations. Bayeux is based on a publish/subscribe model, so servers supporting Bayeux have publish/subscribe built-in. The BOSH protocol by the XMPP standards foundation. It emulates a bidirectional stream between the browser and server by using two synchronous HTTP connections. The JSONRequest object, proposed by Douglas Crockford, would be an alternative to the XHR object. Use of plugins, such as Java applets or the proprietary Adobe Flash (using RTMP protocol for data streaming to Flash applications). These have the advantage of working identically across all browsers with the appropriate plugin installed and need not rely on HTTP connections, but the disadvantage of requiring the plugin to be installed Google announced a new Channel API for Google App Engine, implementing a Comet-like API with the help of a client JavaScript library on the browser. This API has been deprecated. == See also == Push technology Pull technology == Notes == == References == == External links == "Comet Daily". Archived from the original on 2008-01-04. Retrieved 2007-11-29. Comet Daily provides information about Comet techniques.*
https://en.wikipedia.org/wiki/Comet_(programming)
Block programming (also known as a strand in British broadcasting) is the arrangement of programs on radio or television so that those of a particular genre, theme, or target audience are united. == Overview == Block programming involves scheduling a series of related shows which are likely to attract and hold a given audience for a long period of time. Notable examples of overt block programming were NBC's Thursday evening "Must See TV" lineup, which included two hours of sitcoms and one hour of ER, All TV's "Jeepney TV sa All TV" lineup, which consisting the replay of selected Filipino drama series produced by ABS-CBN Studios, a simulcast of ABS-CBN's daily morning talk show Magandang Buhay, and a simulcast of ABS-CBN News' afternoon newscast TV Patrol Express, and Channel 4's "T4" program which often ran sitcoms back-to-back for an hour or more. Reruns on cable television are often assembled into similar blocks to fill several hours of generally little-watched daytime periods. A particularly long program block, especially one that does not air on a regular schedule, is known as a marathon. Block programming in radio also refers to programming content that appeals to various demographics in time blocks, usually corresponding to the top or bottom of the hour or the quarter-hour periods. For example, various musical genres might be featured, such as a country music hour, a three-hour afternoon block of jazz, or a four-hour Saturday night '70s disco show. Generally speaking, block programming is anathema to modern competitive commercial radio, which traditionally uses uniform formats, other than a handful of speciality shows in off-peak hours such as weekends (for instance, the infamous beaver hours in Canadian radio). The general rationale for not using block programming is that listeners expect a certain type of music when they tune into a radio station and breaking from that format will turn those listeners away from the station; likewise, a station that airs its programming in hodgepodge blocks will have difficulty building listener loyalty, as listeners' music will only be on for a few hours of the day. This argument for homogenized radio was also a driving force behind the effective death of freeform radio in the late 20th century. The case of talk radio is indicative of the decline of block programming: prior to the 1980s, it was not uncommon to mix various blocks of talk programming together on one station, but this has declined dramatically in the late 1990s and beyond. A listener to a conservative talk radio station will have little interest in a progressive talk radio, sports radio or hot talk block, which reaches a different demographic; stations that have attempted the block strategy have historically been unsuccessful. Block programming of this nature is alive and well on outlets like public radio (such as NPR, the BBC, or CBC) and in multicultural radio serving broad ethnic and cultural audiences, although even in this realm the idea of block programming is declining due to competition for donations. Some programming blocks have become so popular that they have been transformed to full-fledged 24-hour channels. Current channels which started as program blocks include Disney Jr. (which is still a program block on Disney Channel); the Nick Jr. Channel (based on the Nick Jr. block that still airs on Nickelodeon); Boomerang (which was once a program block on Cartoon Network); PBS Kids (which is still a program block on PBS) and MeTV Toons (which was once a programming block on MeTV). In addition, TV Land airs older shows that were once aired on sister channel Nickelodeon's Nick at Nite program block. Adult Swim is also a Cartoon Network programming block. However, since the 2010s, new programming blocks have become rare due to airing programming in a regular format or with little or no brand reference within the programming block. == See also == Audience flow Lists of programming blocks Strip programming Broadcast programming Dayparting Marathon (media) == References ==
https://en.wikipedia.org/wiki/Block_programming
Systems programming, or system programming, is the activity of programming computer system software. The primary distinguishing characteristic of systems programming when compared to application programming is that application programming aims to produce software which provides services to the user directly (e.g. word processor), whereas systems programming aims to produce software and software platforms which provide services to other software, are performance constrained, or both (e.g. operating systems, computational science applications, game engines, industrial automation, and software as a service applications). Systems programming requires a great degree of hardware awareness. Its goal is to achieve efficient use of available resources, either because the software itself is performance-critical or because even small efficiency improvements directly transform into significant savings of time or money. == Overview == The following attributes characterize systems programming: The programmer can make assumptions about the hardware and other properties of the system that the program runs on, and will often exploit those properties, for example by using an algorithm that is known to be efficient when used with specific hardware. Usually a low-level programming language or programming language dialect is used so that: Programs can operate in resource-constrained environments Programs can be efficient with little runtime overhead, possibly having either a small runtime library or none at all Programs may use direct and "raw" control over memory access and control flow The programmer may write parts of the program directly in assembly language Often systems programs cannot be run in a debugger. Running the program in a simulated environment can sometimes be used to reduce this problem. In systems programming, often limited programming facilities are available. The use of automatic garbage collection is not common and debugging is sometimes hard to do. The runtime library, if available at all, is usually far less powerful, and does less error checking. Because of those limitations, monitoring and logging are often used; operating systems may have extremely elaborate logging subsystems. Implementing certain parts in operating systems and networking requires systems programming, for example implementing paging (virtual memory) or a device driver for an operating system. == History == Originally systems programmers invariably wrote in assembly language. Experiments with hardware support in high level languages in the late 1960s led to such languages as PL/S, BLISS, BCPL, and extended ALGOL for Burroughs large systems. Forth also has applications as a systems language. In the 1970s, C became widespread, aided by the growth of Unix. More recently a subset of C++ called Embedded C++ has seen some use, for instance it is used in the I/O Kit drivers of macOS. Engineers working at Google created Go in 2007 to address developer productivity in large distributed systems, with developer-focused features such as Concurrency, Garbage Collection, and faster program compilation than C and C++. In 2015 Rust came out, a general-purpose programming language often used in systems programming. Rust was designed with memory safety in mind and to be as performant as C and C++. == Alternative meaning == For historical reasons, some organizations use the term systems programmer to describe a job function which would be more accurately termed systems administrator. This is particularly true in organizations whose computer resources have historically been dominated by mainframes, although the term is even used to describe job functions which do not involve mainframes. This usage arose because administration of IBM mainframes often involved the writing of custom assembler code (IBM's Basic Assembly Language (BAL)), which integrated with the operating system such as OS/MVS, DOS/VSE or VM/CMS. Indeed, some IBM software products had substantial code contributions from customer programming staff. This type of programming is progressively less common, and increasingly done in C rather than Assembly, but the term systems programmer is still used as the de-facto job title for staff administering IBM mainframes even in cases where they do not regularly engage in systems programming activities. == See also == Ousterhout's dichotomy System programming language Scripting language Interrupt handler Computer Programming == References == == Further reading == Systems Programming by John J. Donovan
https://en.wikipedia.org/wiki/Systems_programming
In computer programming, a parameter, a.k.a. formal argument, is a variable that represents an argument, a.k.a. actual argument, a.k.a. actual parameter, to a subroutine call.. A function's signature defines its parameters. A call invocation involves evaluating each argument expression of a call and associating the result with the corresponding parameter. For example, consider subroutine def add(x, y): return x + y. Variables x and y are parameters. For call add(2, 3), the expressions 2 and 3 are arguments. For call add(a+1, b+2), the arguments are a+1 and b+2. Parameter passing is defined by a programming language. Evaluation strategy defines the semantics for how parameters can be declared and how arguments are passed to a subroutine. Generally, with call by value, a parameter acts like a new, local variable initialized to the value of the argument. If the argument is a variable, the subroutine cannot modify the argument state because the parameter is a copy. With call by reference, which requires the argument to be a variable, the parameter is an alias of the argument. == Example == The following program defines a function named SalesTax with one parameter named price; both typed double. For call SalesTax(10.00), the argument 10.00 is evaluated to a double value (10) and assigned to parameter variable price. The function is executed and returns the value 0.5. == Parameters and arguments == The terms parameter and argument may have different meanings in different programming languages. Sometimes they are used interchangeably, and the context is used to distinguish the meaning. The term parameter (sometimes called formal parameter) is often used to refer to the variable as found in the function declaration, while argument (sometimes called actual parameter) refers to the actual input supplied at a function call statement. For example, if one defines a function as def f(x): ..., then x is the parameter, and if it is called by a = ...; f(a) then a is the argument. A parameter is an (unbound) variable, while the argument can be a literal or variable or more complex expression involving literals and variables. In case of call by value, what is passed to the function is the value of the argument – for example, f(2) and a = 2; f(a) are equivalent calls – while in call by reference, with a variable as argument, what is passed is a reference to that variable - even though the syntax for the function call could stay the same. The specification for pass-by-reference or pass-by-value would be made in the function declaration and/or definition. Parameters appear in procedure definitions; arguments appear in procedure calls. In the function definition f(x) = x*x the variable x is a parameter; in the function call f(2) the value 2 is the argument of the function. Loosely, a parameter is a type, and an argument is an instance. A parameter is an intrinsic property of the procedure, included in its definition. For example, in many languages, a procedure to add two supplied integers together and calculate the sum would need two parameters, one for each integer. In general, a procedure may be defined with any number of parameters, or no parameters at all. If a procedure has parameters, the part of its definition that specifies the parameters is called its parameter list. By contrast, the arguments are the expressions supplied to the procedure when it is called, usually one expression matching one of the parameters. Unlike the parameters, which form an unchanging part of the procedure's definition, the arguments may vary from call to call. Each time a procedure is called, the part of the procedure call that specifies the arguments is called the argument list. Although parameters are also commonly referred to as arguments, arguments are sometimes thought of as the actual values or references assigned to the parameter variables when the subroutine is called at run-time. When discussing code that is calling into a subroutine, any values or references passed into the subroutine are the arguments, and the place in the code where these values or references are given is the parameter list. When discussing the code inside the subroutine definition, the variables in the subroutine's parameter list are the parameters, while the values of the parameters at runtime are the arguments. For example, in C, when dealing with threads it is common to pass in an argument of type void* and cast it to an expected type: To better understand the difference, consider the following function written in C: The function Sum has two parameters, named addend1 and addend2. It adds the values passed into the parameters, and returns the result to the subroutine's caller (using a technique automatically supplied by the C compiler). The code which calls the Sum function might look like this: The variables value1 and value2 are initialized with values. value1 and value2 are both arguments to the sum function in this context. At runtime, the values assigned to these variables are passed to the function Sum as arguments. In the Sum function, the parameters addend1 and addend2 are evaluated, yielding the arguments 40 and 2, respectively. The values of the arguments are added, and the result is returned to the caller, where it is assigned to the variable sum_value. Because of the difference between parameters and arguments, it is possible to supply inappropriate arguments to a procedure. The call may supply too many or too few arguments; one or more of the arguments may be a wrong type; or arguments may be supplied in the wrong order. Any of these situations causes a mismatch between the parameter and argument lists, and the procedure will often return an unintended answer or generate a runtime error. === Alternative convention in Eiffel === Within the Eiffel software development method and language, the terms argument and parameter have distinct uses established by convention. The term argument is used exclusively in reference to a routine's inputs, and the term parameter is used exclusively in type parameterization for generic classes. Consider the following routine definition: The routine sum takes two arguments addend1 and addend2, which are called the routine's formal arguments. A call to sum specifies actual arguments, as shown below with value1 and value2. Parameters are also thought of as either formal or actual. Formal generic parameters are used in the definition of generic classes. In the example below, the class HASH_TABLE is declared as a generic class which has two formal generic parameters, G representing data of interest and K representing the hash key for the data: When a class becomes a client to HASH_TABLE, the formal generic parameters are substituted with actual generic parameters in a generic derivation. In the following attribute declaration, my_dictionary is to be used as a character string based dictionary. As such, both data and key formal generic parameters are substituted with actual generic parameters of type STRING. == Datatypes == In strongly typed programming languages, each parameter's type must be specified in the procedure declaration. Languages using type inference attempt to discover the types automatically from the function's body and usage. Dynamically typed programming languages defer type resolution until run-time. Weakly typed languages perform little to no type resolution, relying instead on the programmer for correctness. Some languages use a special keyword (e.g. void) to indicate that the subroutine has no parameters; in formal type theory, such functions take an empty parameter list (whose type is not void, but rather unit). == Argument passing == The exact mechanism for assigning arguments to parameters, called argument passing, depends upon the evaluation strategy used for that parameter (typically call by value), which may be specified using keywords. === Default arguments === Some programming languages such as Ada, C++, Clojure, Common Lisp, Fortran 90, Python, Ruby, Tcl, and Windows PowerShell allow for a default argument to be explicitly or implicitly given in a subroutine's declaration. This allows the caller to omit that argument when calling the subroutine. If the default argument is explicitly given, then that value is used if it is not provided by the caller. If the default argument is implicit (sometimes by using a keyword such as Optional) then the language provides a well-known value (such as null, Empty, zero, an empty string, etc.) if a value is not provided by the caller. PowerShell example: Default arguments can be seen as a special case of the variable-length argument list. === Variable-length parameter lists === Some languages allow subroutines to be defined to accept a variable number of arguments. For such languages, the subroutines must iterate through the list of arguments. PowerShell example: === Named parameters === Some programming languages—such as Ada and Windows PowerShell—allow subroutines to have named parameters. This allows the calling code to be more self-documenting. It also provides more flexibility to the caller, often allowing the order of the arguments to be changed, or for arguments to be omitted as needed. PowerShell example: === Multiple parameters in functional languages === In lambda calculus, each function has exactly one parameter. What is thought of as functions with multiple parameters is usually represented in lambda calculus as a function which takes the first argument, and returns a function which takes the rest of the arguments; this is a transformation known as currying. Some programming languages, like ML and Haskell, follow this scheme. In these languages, every function has exactly one parameter, and what may look like the definition of a function of multiple parameters, is actually syntactic sugar for the definition of a function that returns a function, etc. Function application is left-associative in these languages as well as in lambda calculus, so what looks like an application of a function to multiple arguments is correctly evaluated as the function applied to the first argument, then the resulting function applied to the second argument, etc. == Output parameters == An output parameter, also known as an out parameter or return parameter, is a parameter used for output, rather than the more usual use for input. Using call by reference parameters, or call by value parameters where the value is a reference, as output parameters is an idiom in some languages, notably C and C++, while other languages have built-in support for output parameters. Languages with built-in support for output parameters include Ada (see Ada subprograms), Fortran (since Fortran 90; see Fortran "intent"), various procedural extensions to SQL, such as PL/SQL (see PL/SQL functions) and Transact-SQL, C# and the .NET Framework, Swift, and the scripting language TScript (see TScript function declarations). More precisely, one may distinguish three types of parameters or parameter modes: input parameters, output parameters, and input/output parameters; these are often denoted in, out, and in out or inout. An input argument (the argument to an input parameter) must be a value, such as an initialized variable or literal, and must not be redefined or assigned to; an output argument must be an assignable variable, but it need not be initialized, any existing value is not accessible, and must be assigned a value; and an input/output argument must be an initialized, assignable variable, and can optionally be assigned a value. The exact requirements and enforcement vary between languages – for example, in Ada 83 output parameters can only be assigned to, not read, even after assignment (this was removed in Ada 95 to remove the need for an auxiliary accumulator variable). These are analogous to the notion of a value in an expression being an r-value (has a value), an l-value (can be assigned), or an r-value/l-value (has a value and can be assigned), respectively, though these terms have specialized meanings in C. In some cases only input and input/output are distinguished, with output being considered a specific use of input/output, and in other cases only input and output (but not input/output) are supported. The default mode varies between languages: in Fortran 90 input/output is default, while in C# and SQL extensions input is default, and in TScript each parameter is explicitly specified as input or output. Syntactically, parameter mode is generally indicated with a keyword in the function declaration, such as void f(out int x) in C#. Conventionally output parameters are often put at the end of the parameter list to clearly distinguish them, though this is not always followed. TScript uses a different approach, where in the function declaration input parameters are listed, then output parameters, separated by a colon (:) and there is no return type to the function itself, as in this function, which computes the size of a text fragment: Parameter modes are a form of denotational semantics, stating the programmer's intent and allowing compilers to catch errors and apply optimizations – they do not necessarily imply operational semantics (how the parameter passing actually occurs). Notably, while input parameters can be implemented by call by value, and output and input/output parameters by call by reference – and this is a straightforward way to implement these modes in languages without built-in support – this is not always how they are implemented. This distinction is discussed in detail in the Ada '83 Rationale, which emphasizes that the parameter mode is abstracted from which parameter passing mechanism (by reference or by copy) is actually implemented. For instance, while in C# input parameters (default, no keyword) are passed by value, and output and input/output parameters (out and ref) are passed by reference, in PL/SQL input parameters (IN) are passed by reference, and output and input/output parameters (OUT and IN OUT) are by default passed by value and the result copied back, but can be passed by reference by using the NOCOPY compiler hint. A syntactically similar construction to output parameters is to assign the return value to a variable with the same name as the function. This is found in Pascal and Fortran 66 and Fortran 77, as in this Pascal example: This is semantically different in that when called, the function is simply evaluated – it is not passed a variable from the calling scope to store the output in. === Use === The primary use of output parameters is to return multiple values from a function, while the use of input/output parameters is to modify state using parameter passing (rather than by shared environment, as in global variables). An important use of returning multiple values is to solve the semipredicate problem of returning both a value and an error status – see Semipredicate problem: Multivalued return. For example, to return two variables from a function in C, one may write: where x is an input parameter and width and height are output parameters. A common use case in C and related languages is for exception handling, where a function places the return value in an output variable, and returns a Boolean corresponding to whether the function succeeded or not. An archetypal example is the TryParse method in .NET, especially C#, which parses a string into an integer, returning true on success and false on failure. This has the following signature: and may be used as follows: Similar considerations apply to returning a value of one of several possible types, where the return value can specify the type and then value is stored in one of several output variables. === Drawbacks === Output parameters are often discouraged in modern programming, essentially as being awkward, confusing, and too low-level – commonplace return values are considerably easier to understand and work with. Notably, output parameters involve functions with side effects (modifying the output parameter) and are semantically similar to references, which are more confusing than pure functions and values, and the distinction between output parameters and input/output parameters can be subtle. Further, since in common programming styles most parameters are simply input parameters, output parameters and input/output parameters are unusual and hence susceptible to misunderstanding. Output and input/output parameters prevent function composition, since the output is stored in variables, rather than in the value of an expression. Thus one must initially declare a variable, and then each step of a chain of functions must be a separate statement. For example, in C++ the following function composition: when written with output and input/output parameters instead becomes (for F it is an output parameter, for G an input/output parameter): In the special case of a function with a single output or input/output parameter and no return value, function composition is possible if the output or input/output parameter (or in C/C++, its address) is also returned by the function, in which case the above becomes: === Alternatives === There are various alternatives to the use cases of output parameters. For returning multiple values from a function, an alternative is to return a tuple. Syntactically this is clearer if automatic sequence unpacking and parallel assignment can be used, as in Go or Python, such as: For returning a value of one of several types, a tagged union can be used instead; the most common cases are nullable types (option types), where the return value can be null to indicate failure. For exception handling, one can return a nullable type, or raise an exception. For example, in Python one might have either: or, more idiomatically: The micro-optimization of not requiring a local variable and copying the return when using output variables can also be applied to conventional functions and return values by sufficiently sophisticated compilers. The usual alternative to output parameters in C and related languages is to return a single data structure containing all return values. For example, given a structure encapsulating width and height, one can write: In object-oriented languages, instead of using input/output parameters, one can often use call by sharing, passing a reference to an object and then mutating the object, though not changing which object the variable refers to. == See also == Command-line argument Evaluation strategy Operator overloading Free variables and bound variables == Notes == == References ==
https://en.wikipedia.org/wiki/Parameter_(computer_programming)
R is a programming language for statistical computing and data visualization. It has been adopted in the fields of data mining, bioinformatics and data analysis/data science. The core R language is augmented by a large number of extension software packages, which contain reusable code, documentation, and sample data. R software is open-source and free software. R is a GNU Project and licensed under the GNU General Public License. It is written primarily in C, Fortran, and R itself. Precompiled executables are provided for various operating systems. As an interpreted language, R has a native command line interface. Moreover, multiple third-party graphical user interfaces are available, such as RStudio—an integrated development environment—and Jupyter—a notebook interface. == History == R was started by professors Ross Ihaka and Robert Gentleman as a programming language to teach introductory statistics at the University of Auckland. The language was inspired by the S programming language, with most S programs able to run unaltered in R. The language was also inspired by Scheme's lexical scoping, allowing for local variables. The name of the language, R, comes from being both an S language successor as well as the shared first letter of the authors, Ross and Robert. In August 1993, Ihaka and Gentleman posted a binary of R on StatLib — a data archive website. At the same time, they announced the posting on the s-news mailing list. On 5 December 1997, R became a GNU project when version 0.60 was released. On 29 February 2000, the 1.0 version was released. == Packages == R packages are collections of functions, documentation, and data that expand R. For example, packages can add reporting features (using packages like RMarkdown, Quarto, knitr, and Sweave) and the capability to implement various statistical techniques (such as linear, generalized linear and nonlinear modeling, classical statistical tests, spatial analysis, time-series analysis, and clustering). Perceived easy package installation and usability have contributed to the language's adoption in data science. Immediately available when starting R, base packages provide the basic and necessary syntax and commands for programming, computing, graphics production, basic arithmetic, and statistical functionality. An example R package is the tidyverse package, which bundles several subsidiary packages to provide a common interface. It specializes in tasks related to accessing and processing "tidy data", which are data contained in a two-dimensional table with a single row for each observation and a single column for each variable. Installing a package occurs only once. For example, to install the tidyverse package: To load the functions, data, and documentation of a package, one executes the library() function. To load tidyverse: The Comprehensive R Archive Network (CRAN) was founded in 1997 by Kurt Hornik and Friedrich Leisch to host R's source code, executable files, documentation, and user-created packages. Its name and scope mimic the Comprehensive TeX Archive Network (CTAN) and the Comprehensive Perl Archive Network (CPAN). CRAN originally had three mirroring sites and twelve contributed packages. As of 16 October 2024, it has 99 mirrors and 21,513 contributed packages. Packages are also available on repositories like R-Forge, Omegahat, and GitHub. On the CRAN web site as a form of guidance, Task Views lists packages on CRAN that are relevant for tasks related to a certain topics, such as causal inference, finance, genetics, high-performance computing, machine learning, medical imaging, meta-analysis, social sciences, and spatial statistics. The Bioconductor project provides packages for genomic data analysis, complementary DNA, microarray, and high-throughput sequencing methods. == Community == There are three main groups that help support R software development: The R Core Team was founded in 1997 to maintain the R source code. The R Foundation for Statistical Computing was founded in April 2003 to provide financial support. The R Consortium is a Linux Foundation project to develop R infrastructure. The R Journal is an open access, academic journal which features short to medium-length articles on the use and development of R. It includes articles on packages, programming tips, CRAN news, and foundation news. The R community hosts many conferences and in-person meetups. These groups include: UseR!: an annual international R user conference (website) Directions in Statistical Computing (DSC) (website) R-Ladies: an organization to promote gender diversity in the R community (website) SatRdays: R-focused conferences held on Saturdays (website) R Conference (website) posit::conf (formerly known as rstudio::conf) (website) On social media sites like Twitter, the hashtag #rstats can be used to keep up with new developments in the R community. == Examples == === Hello, World! === "Hello, World!" program: Alternatively: === Basic syntax === The following examples illustrate the basic syntax of the language and use of the command-line interface. In R, the generally preferred assignment operator is an arrow made from two characters <-, although = can be used in some cases. === Structure of a function === R is able to create functions to add new functionality for reuse. Objects created within the body of the function (which are enclosed by curly brackets) remain only accessible from within the function, and any data type may be returned. In R, almost all functions and all user-defined functions are closures. Example of creating a function to perform some arithmetic calculation: Usage output: It is possible to define functions to be used as infix operators with the special syntax `%name%` where "name" is the function variable name: Since version 4.1.0 functions can be written in a short notation, which is useful for passing anonymous functions to higher-order functions: === Native pipe operator === In R version 4.1.0, a native pipe operator, |>, was introduced. This operator allows users to chain functions together one after another, instead of a nested function call. Another alternative to nested functions, in contrast to using the pipe character, is using intermediate objects: While the pipe operator can produce code that is easier to read, it has been advised to pipe together at most 10 to 15 lines and chunk code into sub-tasks which are saved into objects with meaningful names. Here is an example with fewer than 10 lines that some readers may still struggle to grasp without intermediate named steps: === Object-oriented programming === The R language has native support for object-oriented programming. There are two native frameworks, the so-called S3 and S4 systems. The former, being more informal, supports single dispatch on the first argument and objects are assigned to a class by just setting a "class" attribute in each object. The latter is a Common Lisp Object System (CLOS)-like system of formal classes (also derived from S) and generic methods that supports multiple dispatch and multiple inheritance In the example, summary is a generic function that dispatches to different methods depending on whether its argument is a numeric vector or a "factor": === Modeling and plotting === The R language has built-in support for data modeling and graphics. The following example shows how R can generate and plot a linear model with residuals. Output: === Mandelbrot set === This Mandelbrot set example highlights the use of complex numbers. It models the first 20 iterations of the equation z = z2 + c, where c represents different complex constants. Install the package that provides the write.gif() function beforehand: R Source code: == Version names == All R version releases from 2.14.0 onward have codenames that make reference to Peanuts comics and films. In 2018, core R developer Peter Dalgaard presented a history of R releases since 1997. Some notable early releases before the named releases include: Version 1.0.0 released on 29 February 2000 (2000-02-29), a leap day Version 2.0.0 released on 4 October 2004 (2004-10-04), "which at least had a nice ring to it" The idea of naming R version releases was inspired by the Debian and Ubuntu version naming system. Dalgaard also noted that another reason for the use of Peanuts references for R codenames is because, "everyone in statistics is a P-nut". == Interfaces == R comes installed with a command line console, but it is not the only way to interface with R. By integrated development environment (IDE): R.app (OSX/macOS only) Rattle GUI R Commander RKWard RStudio Tinn-R By general purpose IDEs: Eclipse via the StatET plugin Visual Studio via R Tools for Visual Studio. By source-code editors: Emacs Vim via the Nvim-R plugin Kate LyX via Sweave WinEdt (website) Jupyter (website) By other scripting languages: Python (website) Perl (website) Ruby (source code) F# (website) Julia (source code). By general purpose programming languages: Java via the Rserve socket server .NET C# (website) Statistical frameworks which use R in the background include Jamovi and JASP. == Implementations == The main R implementation is written primarily in C, Fortran, and R itself. Other implementations include: pretty quick R (pqR), by Radford M. Neal, attempts to improve memory management. Renjin is an implementation of R for the Java Virtual Machine. CXXR and Riposte are implementations of R written in C++. Oracle's FastR is an implementation of R, built on GraalVM. TIBCO Software, creator of S-PLUS, wrote TERR — an R implementation to integrate with Spotfire. Microsoft R Open (MRO) was an R implementation. As of 30 June 2021, Microsoft started to phase out MRO in favor of the CRAN distribution. == Commercial support == Although R is an open-source project, some companies provide commercial support: Oracle provides commercial support for the Big Data Appliance, which integrates R into its other products. IBM provides commercial support for in-Hadoop execution of R. == See also == Comparison of numerical-analysis software Comparison of statistical packages List of numerical-analysis software List of statistical software Rmetrics == Notes == == References == == Further reading == Wickham, Hadley; Çetinkaya-Rundel, Mine; Grolemund, Garrett (2023). R for data science: import, tidy, transform, visualize, and model data (2nd ed.). Beijing Boston Farnham Sebastopol Tokyo: O'Reilly. ISBN 978-1-4920-9740-2. Gagolewski, Marek (2024). Deep R Programming. doi:10.5281/ZENODO.7490464. ISBN 978-0-6455719-2-9. == External links == R Technical Papers Big Book of R, curated list of R-related programming books Books Related to R - R Project, partially annotated curated list of books relating to R or S.
https://en.wikipedia.org/wiki/R_(programming_language)
Parametric programming is a type of mathematical optimization, where the optimization problem is solved as a function of one or multiple parameters. Developed in parallel to sensitivity analysis, its earliest mention can be found in a thesis from 1952. Since then, there have been considerable developments for the cases of multiple parameters, presence of integer variables as well as nonlinearities. == Notation == In general, the following optimization problem is considered J ∗ ( θ ) = min x ∈ R n f ( x , θ ) subject to g ( x , θ ) ≤ 0. θ ∈ Θ ⊂ R m {\displaystyle {\begin{aligned}J^{*}(\theta )=&\min _{x\in \mathbb {R} ^{n}}f(x,\theta )\\&{\text{subject to }}g(x,\theta )\leq 0.\\&\theta \in \Theta \subset \mathbb {R} ^{m}\end{aligned}}} where x {\displaystyle x} is the optimization variable, θ {\displaystyle \theta } are the parameters, f ( x , θ ) {\displaystyle f(x,\theta )} is the objective function and g ( x , θ ) {\displaystyle g(x,\theta )} denote the constraints. J ∗ {\displaystyle J^{*}} denotes a function whose output is the optimal value of the objective function f {\displaystyle f} . The set Θ {\displaystyle \Theta } is generally referred to as parameter space. The optimal value (i.e. result of solving the optimization problem) is obtained by evaluating the function with an argument θ {\displaystyle \theta } . == Classification == Depending on the nature of f ( x , θ ) {\displaystyle f(x,\theta )} and g ( x , θ ) {\displaystyle g(x,\theta )} and whether the optimization problem features integer variables, parametric programming problems are classified into different sub-classes: If more than one parameter is present, i.e. m > 1 {\displaystyle m>1} , then it is often referred to as multiparametric programming problem If integer variables are present, then the problem is referred to as (multi)parametric mixed-integer programming problem If constraints are affine, then additional classifications depending to nature of the objective function in (multi)parametric (mixed-integer) linear, quadratic and nonlinear programming problems is performed. Note that this generally assumes the constraints to be affine. == Applications == === In control theory generally and in process industries === The connection between parametric programming and model predictive control for process manufacturing, established in 2000, has contributed to an increased interest in the topic. Parametric programming supplies the idea that optimization problems can be parametrized as functions that can be evaluated (similar to a lookup table). This in turns allows the optimization algorithms in optimal controllers to be implemented as pre-computed (off-line) mathematical functions, which may in some cases be simpler and faster to evaluate than solving a full optimization problem on-line. This also opens up the possibility of creating optimal controllers on chips (MPC on chip). However, the off-line parametrization of optimal solutions runs into the curse of dimensionality as the number of possible solutions grows with the dimensionality and number of constraints in the problem. === In CNC programming === Parametric programming in the context of CNC (computer numerical control) is defining part-cutting cycles in terms of variables with reassignable values rather than via hardcoded/hardwired instances. An archetypically simple example is writing a G-code program to machine a family of washers: there is often no need to write 15 programs for 15 members of the family with various hole diameters, outer diameters, thicknesses, and materials, when it is practical instead to write 1 program that calls various variables and reads their current values from a table of assignments. The program then instructs the machine slides and spindles to move to various positions at various velocities, accordingly, addressing not only the sizes of the part (i.e., OD, ID, thickness) but also even the speeds and feeds needed for any given material (e.g., low-carbon steel, high-carbon steel; stainless steel of whichever grade; bronze, brass, or aluminum of whichever grade; polymer of whichever type). Custom Macros are often used in such programming. == References ==
https://en.wikipedia.org/wiki/Parametric_programming
An esoteric programming language (sometimes shortened to esolang) is a programming language designed to test the boundaries of computer programming language design, as a proof of concept, as software art, as a hacking interface to another language (particularly functional programming or procedural programming languages), or as a joke. The use of the word esoteric distinguishes them from languages that working developers use to write software. The creators of most esolangs do not intend them to be used for mainstream programming, although some esoteric features, such as visuospatial syntax, have inspired practical applications in the arts. Such languages are often popular among hackers and hobbyists. Usability is rarely a goal for designers of esoteric programming languages; often their design leads to quite the opposite. Their usual aim is to remove or replace conventional language features while still maintaining a language that is Turing-complete, or even one for which the computational class is unknown. == History == The earliest, and still the canonical example of an esoteric programming language, is INTERCAL, designed in 1972 by Don Woods and James M. Lyon, who said that their intention was to create a programming language unlike any with which they were familiar. It parodied elements of established programming languages of the day such as Fortran, COBOL and assembly language. For many years, INTERCAL was represented only by paper copies of the INTERCAL manual. Its revival in 1990 as an implementation in C under Unix stimulated a wave of interest in the intentional design of esoteric computer languages. In 1993, Wouter van Oortmerssen created FALSE, a small stack-oriented programming language with syntax designed to make the code inherently obfuscated, confusing and unreadable. Its compiler is only 1024 bytes in size. This inspired Urban Müller to create an even smaller language, the now-infamous Brainfuck, which consists of only eight recognized characters. Along with Chris Pressey's Befunge (like FALSE, but with a two-dimensional instruction pointer), Brainfuck is now one of the best-supported esoteric programming languages, with canonical examples of minimal Turing tarpits and needlessly obfuscated language features. Brainfuck is related to the P′′ family of Turing machines. == Common features == While esoteric programming languages differ in many ways, there are some common traits that characterize many languages, such as parody, minimalism, and the goal of making programming difficult. Many esoteric programming languages, such as brainfuck, and similar, use single characters as commands, however, it is not uncommon for languages to read line by line like conventional programming languages. === Unique data representations === Conventional imperative programming languages typically allow data to be stored in variables, but esoteric languages may utilize different methods of storing and accessing data. Languages like Brainfuck and Malbolge only permit data to be read through a single pointer, which must be moved to a location of interest before data is read. Others, like Befunge and Shakespeare, utilize one or more stacks to hold data, leading to a manner of execution akin to Reverse Polish notation. Finally, there are languages which explore alternative forms of number representation: the Brainfuck variant Boolfuck only permits operations on single bits, while Malbolge and INTERCAL variant TriINTERCAL replace bits altogether with a base 3 ternary system. === Unique instruction representations === Esoteric languages also showcase unique ways of representing program instructions. Some languages, such as Befunge and Piet, represent programs in two or more dimensions, with program control moving around in multiple possible directions through the program. This differs from conventional languages in which a program is a set of instructions usually encountered in sequence. Other languages modify instructions to appear in an unusual form, often one that can be read by humans with an alternate meaning to the underlying instructions. Shakespeare achieves this by making all programs resemble Shakespearian plays. Chef achieves the same by having all programs be recipes. Chef is particularly notable in that some have created programs that successfully function both as a program and as a recipe, demonstrating the ability of the language to produce this double meaning. === Difficulty to read and write === Many esoteric programming languages are designed to produce code that is deeply obfuscated, making it difficult to read and to write. The purpose of this may be to provide an interesting puzzle or challenge for program writers: Malbolge for instance was explicitly designed to be challenging, and so it has features like self-modifying code and highly counterintuitive operations. On the other hand, some esoteric languages become difficult to write due to their other design choices. Brainfuck is committed to the idea of a minimalist instruction set, so even though its instructions are straightforward in principle, the code that arises is difficult for a human to read. INTERCAL's difficulty arises as a result of the choice to avoid operations used in any other programming language, which stems from its origin as a parody of other languages. === Parody and spoof === One of the aims of esoteric programming languages is to parody or spoof existing languages and trends in the field of programming. For instance, the first esoteric language INTERCAL began as a spoof of languages used in the 1960s, such as APL, Fortran, and COBOL. INTERCAL's rules appear to be the inverse of rules in these other languages. However, the subject of parody is not always another established programming language. Shakespeare can be viewed as spoofing the structure of Shakespearean plays, for instance. The language Ook! is a parody of Brainfuck, where Brainfuck's eight commands are replaced by various orangutan sounds like "Ook. Ook?" == Examples == === Befunge === Befunge allows the instruction pointer to roam in multiple dimensions through the code. For example, the following program displays "Hello World" by pushing the characters in reverse order onto the stack, then printing the characters in a loop which circulates clockwise through the instructions >, :, v, _, ,, and ^. There are many versions of Befunge, the most common being Befunge-93, named as such because of its release year. === Binary lambda calculus === Binary lambda calculus is designed from an algorithmic information theory perspective to allow for the densest possible code with the most minimal means, featuring a 29-byte self interpreter, a 21-byte prime number sieve, and a 112-byte Brainfuck interpreter. === Brainfuck === Brainfuck is designed for extreme minimalism and leads to obfuscated code, with programs containing only eight distinct characters. The following program outputs "Hello, world!": All characters other than +-<>,.[] are ignored. === Chicken === Chicken has just three tokens, the word "chicken", " " (the space character), and the newline character. The compiler interprets the number of "chickens" on a line as an opcode instruction which it uses to manipulate data on a stack. A simple chicken program can contain dozens of lines with nothing but the word "chicken" repeated countless times. Chicken was invented by Torbjörn Söderstedt who drew his inspiration for the language from a parody of a scientific dissertation. === Chef === Chef is a stack-oriented programming language created by David Morgan-Mar, designed to make programs look like cooking recipes. Programs consist of a title, a list of variables and their data values, and a list of stack manipulation instructions. A joking design principle states that "program recipes should not only generate valid output, but be easy to prepare and delicious", and Morgan-Mar notes that an example "Hello, World!" program with 101 eggs and 111 cups (~26,640 mL) oil would produce "a lot of food for one person." === FRACTRAN === A FRACTRAN program is an ordered list of positive fractions together with an initial positive integer input n {\displaystyle n} . The program is run by multiplying the integer n {\displaystyle n} by the first fraction f {\displaystyle f} in the list for which n f {\displaystyle nf} is an integer. The integer n {\displaystyle n} is then replaced by n f {\displaystyle nf} and the rule is repeated. If no fraction in the list produces an integer when multiplied by n {\displaystyle n} , the program halts. FRACTRAN was invented by mathematician John Conway. === GolfScript === Programs in GolfScript, a language created for code golf, consist of lists of items, each of which is pushed onto the stack as it is encountered, with the exception of variables which have code blocks as their value, in which case the code is executed. === INTERCAL === INTERCAL, short for "Compiler Language With No Pronounceable Acronym", was created in 1972 as a parody to satirize aspects of the various programming languages at the time. === JSFuck === JSFuck is an esoteric programming style of JavaScript, where code is written using only six characters: [, ], (, ), !, and +. Unlike Brainfuck, which requires its own compiler or interpreter, JSFuck is valid JavaScript code, meaning JSFuck programs can be run in any web browser or engine that interprets JavaScript. It has been used in a number of cross-site scripting (XSS) attacks on websites such as eBay due to its ability to evade cross-site scripting detection filters. === LOLCODE === LOLCODE is designed to resemble the speech of lolcats. The following is the "Hello World" example: HAI CAN HAS STDIO? VISIBLE "HAI WORLD!" KTHXBYE While the semantics of LOLCODE is not unusual, its syntax has been described as a linguistic phenomenon, representing an unusual example of informal speech and internet slang in programming. === Malbolge === Malbolge (named after the 8th circle of Hell) was designed to be the most difficult and esoteric programming language. Among other features, code is self-modifying by design and the effect of an instruction depends on its address in memory. === Piet === Piet is a language designed by David Morgan-Mar, whose programs are bitmaps that look like abstract art. The execution is guided by a "pointer" that moves around the image, from one continuous coloured region to the next. Procedures are carried out when the pointer exits a region. There are 20 colours for which behaviour is specified: 18 "colourful" colours, which are ordered by a 6-step hue cycle and a 3-step brightness cycle; and black and white, which are not ordered. When exiting a "colourful" colour and entering another one, the performed procedure is determined by the number of steps of change in hue and brightness. Black cannot be entered; when the pointer tries to enter a black region, the rules of choosing the next block are changed instead. If all possible rules are tried, the program terminates. Regions outside the borders of the image are also treated as black. White does not perform operations, but allows the pointer to "pass through". The behaviour of colours other than the 20 specified is left to the compiler or interpreter. Variables are stored in memory as signed integers in a single stack. Most specified procedures deal with operations on that stack, while others deal with input/output and with the rules by which the compilation pointer moves. Piet was named after the Dutch painter Piet Mondrian. The original intended name, Mondrian, was already taken by an open-source statistical data-visualization system. === Shakespeare === Shakespeare Programming Language (SPL) is designed to make programs look like Shakespearean plays. For example, the following statement declares a point in the program which can be reached via a GOTO-type statement: Act I: Hamlet's insults and flattery. === Unlambda === Unlambda is a minimalist functional programming language based on SKI calculus, but combined with first-class continuations and imperative I/O (with input usually requiring the use of continuations). === Whitespace === Whitespace uses only whitespace characters (space, tab, and return), ignoring all other characters, which can therefore be used for comments. This is the reverse of many traditional languages, which do not distinguish between different whitespace characters, treating tab and space the same. It also allows Whitespace programs to be hidden in the source code of programs in languages like C. == Cultural context == The cultural context of esolangs has been studied by Geoff Cox, who writes that esolangs "shift attention from command and control toward cultural expression and refusal", seeing esolangs as similar to code art and code poetry, such as Mez Breeze's mezangelle, a belief shared by others in field. Daniel Temkin describes Brainfuck as "refusing to ease the boundary between human expression and assembly code and thereby taking us on a ludicrous journey of logic," exposing the inherent conflict between human thinking and computer logic by deconstructing their relationship. He connects programming within an esolang to performing an event score such as those of the Fluxus movement, where playing out the irregular rules of the logic in code makes the point of view of the language clear. == References == == Bibliography == Paloque-Bergès, Camille (2009). "Langages ésotériques". Poétique des codes sur le réseau informatique. Archives contemporaines. ISBN 978-2-914610-70-4. Cox, Geoff (2013). Speaking Code: Coding as Aesthetic and Political Expression. MIT Press. ISBN 978-0-262-01836-4. Kneusel, Ronald (2022). Strange Code: Esoteric Languages That Make Programming Fun Again. No Starch Press. ISBN 978-1718502406. == External links == Esolang, the esoteric programming languages wiki
https://en.wikipedia.org/wiki/Esoteric_programming_language
A programmer, computer programmer or coder is an author of computer source code – someone with skill in computer programming. The professional titles software developer and software engineer are used for jobs that require a programmer. == Identification == Sometimes a programmer or job position is identified by the language used or target platform. For example, assembly programmer, web developer. == Job title == The job titles that include programming tasks have differing connotations across the computer industry and to different individuals. The following are notable descriptions. A software developer primarily implements software based on specifications and fixes bugs. Other duties may include reviewing code changes and testing. To achieve the required skills for the job, they might obtain a computer science or associate degree, attend a programming boot camp or be self-taught. A software engineer usually is responsible for the same tasks as a developer plus broader responsibilities of software engineering including architecting and designing new features and applications, targeting new platforms, managing the software development lifecycle (design, implementation, testing, and deployment), leading a team of programmers, communicating with customers, managers and other engineers, considering system stability and quality, and exploring software development methodologies. Sometimes, a software engineer is required to have a degree in software engineering, computer engineering, or computer science. Some countries legally require an engineering degree to be called engineer. == History == British countess and mathematician Ada Lovelace is often considered to be the first computer programmer. She authored an algorithm, which was published in October 1842, for calculating Bernoulli numbers on the Charles Babbage analytical engine. Because the machine was not completed in her lifetime, she never experienced the algorithm in action. In 1941, German civil engineer Konrad Zuse was the first person to execute a program on a working, program-controlled, electronic computer. From 1943 to 1945, per computer scientist Wolfgang K. Giloi and AI professor Raúl Rojas et al., Zuse created the first, high-level programming language, Plankalkül. Members of the 1945 ENIAC programming team of Kay McNulty, Betty Jennings, Betty Snyder, Marlyn Wescoff, Fran Bilas and Ruth Lichterman have since been credited as the first professional computer programmers. == The software industry == The first company founded specifically to provide software products and services was the Computer Usage Company in 1955. Before that time, computers were programmed either by customers or the few commercial computer manufacturers of the time, such as Sperry Rand and IBM. The software industry expanded in the early 1960s, almost immediately after computers were first sold in mass-produced quantities. Universities, governments, and businesses created a demand for software. Many of these programs were written in-house by full-time staff programmers; some were distributed between users of a particular machine for no charge, while others were sold on a commercial basis. Other firms, such as Computer Sciences Corporation (founded in 1959), also started to grow. Computer manufacturers soon started bundling operating systems, system software and programming environments with their machines; the IBM 1620 came with the 1620 Symbolic Programming System and FORTRAN. The industry expanded greatly with the rise of the personal computer (PC) in the mid-1970s, which brought computing to the average office worker. In the following years, the PC also helped create a constantly growing market for games, applications and utility software. This resulted in increased demand for software developers for that period of time. == Nature of the work == Computer programmers write, test, debug, and maintain the detailed instructions, called computer programs, that computers must follow to perform their functions. Programmers also conceive, design, and test logical structures for solving problems by computer. Many technical innovations in programming — advanced computing technologies and sophisticated new languages and programming tools — have redefined the role of a programmer and elevated much of the programming work done today. Job titles and descriptions may vary, depending on the organization. Programmers work in many settings, including corporate information technology (IT) departments, big software companies, small service firms and government entities of all sizes. Many professional programmers also work for consulting companies at client sites as contractors. Licensing is not typically required to work as a programmer, although professional certifications are commonly held by programmers. Programming is considered a profession. Programmers' work varies widely depending on the type of business for which they are writing programs. For example, the instructions involved in updating financial records are very different from those required to duplicate conditions on an aircraft for pilots training in a flight simulator. Simple programs can be written in a few hours. More complex ones may require more than a year of work, while others are never considered 'complete' but rather are continuously improved as long as they stay in use. In most cases, several programmers work together as a team under a senior programmer's supervision. === Types of software === Programming editors, also known as source code editors, are text editors that are specifically designed for programmers or developers to write the source code of an application or a program. Most of these editors include features useful for programmers, which may include color syntax highlighting, auto indentation, auto-complete, bracket matching, syntax check, and allows plug-ins. These features aid the users during coding, debugging and testing. == Globalization == === Market changes in the UK === According to BBC News, 17% of computer science students could not find work in their field six months after graduation in 2009 which was the highest rate of the university subjects surveyed while 0% of medical students were unemployed in the same survey. === Market changes in the US === After the crash of the dot-com bubble (1999–2001) and the Great Recession (2008), many U.S. programmers were left without work or with lower wages. In addition, enrollment in computer-related degrees and other STEM degrees (STEM attrition) in the US has been dropping for years, especially for women, which, according to Beaubouef and Mason, could be attributed to a lack of general interest in science and mathematics and also out of an apparent fear that programming will be subject to the same pressures as manufacturing and agriculture careers. For programmers, the U.S. Bureau of Labor Statistics (BLS) Occupational Outlook originally predicted a growth for programmers of 12 percent from 2010 to 2020 and thereafter a decline of -7 percent from 2016 to 2026, a further decline of -9 percent from 2019 to 2029, a decline of -10 percent from 2021 to 2031. and then a decline of -11 percent from 2022 to 2032. Since computer programming can be done from anywhere in the world, companies sometimes hire programmers in countries where wages are lower. If domestic demand has increased, it is mainly to replace existing programmers who have retired or switched occupations. However, for software developers BLS projects current growth at 17% that is down from their prediction from 2019 to 2029 of a 22% increase in employment, from 1,469,200 to 1,785,200 jobs with a median base salary of $110,000 per year. This prediction is lower than the earlier 2010 to 2020 predicted increase of 30% for software developers. Though the distinction is somewhat ambiguous, software developers engage in a wider array of aspects of application development and are generally higher skilled than programmers, making outsourcing less of a risk. Another reason for the decline for programmers is their skills are being merged with other professions, such as developers, as employers increase the requirements for a position over time (i.e. Full-stack developer). Then there is the additional concern that recent advances in artificial intelligence might drastically impact the demand for future generations of Software professions. === Market changes in Japan === As of 2024 in Japan, the demand for programmers is increasing rapidly due mainly to the aging demographics of their workforce and their low birth rate not being sufficient for replacement has led to more use of AI to help fill the gap. On the other hand, despite the fact that there are more than 1.2 million programmers in Japan as of 2020, more than 40% of Japanese companies say they do not have enough skilled and qualified IT personnel, including programmers; by 2030, the number of programmers will exceed 1.6 million, but about 800 000 people, including programmers, a shortage of engineers is expected to occur. == See also == List of programmers List of programming languages Software development process Software engineering Systems architect Video game programmer == References == == Further reading == Weinberg, Gerald M., The Psychology of Computer Programming, New York: Van Nostrand Reinhold, 1971 An experiential study of the nature of programming work: Lucas, Rob (March–April 2010). "Dreaming in Code". New Left Review (62): 125–132. Archived from the original on 24 April 2012. Thompson, Clive (2019). Coders: The Making of a New Tribe and the Remaking of the World. Penguin Press. ISBN 978-0735220560. == External links == The US Department of Labor description of: Computer programmers Software developers
https://en.wikipedia.org/wiki/Programmer
Programming complexity (or software complexity) is a term that includes software properties that affect internal interactions. Several commentators distinguish between the terms "complex" and "complicated". Complicated implies being difficult to understand, but ultimately knowable. Complex, by contrast, describes the interactions between entities. As the number of entities increases, the number of interactions between them increases exponentially, making it impossible to know and understand them all. Similarly, higher levels of complexity in software increase the risk of unintentionally interfering with interactions, thus increasing the risk of introducing defects when changing the software. In more extreme cases, it can make modifying the software virtually impossible. The idea of linking software complexity to software maintainability has been explored extensively by Professor Manny Lehman, who developed his Laws of Software Evolution. He and his co-author Les Belady explored numerous software metrics that could be used to measure the state of software, eventually concluding that the only practical solution is to use deterministic complexity models. == Types == The complexity of an existing program determines the complexity of changing the program. Problem complexity can be divided into two categories: Accidental complexity relates to difficulties a programmer faces due to the software engineering tools. Selecting a better tool set or a higher-level programming language may reduce it. Accidental complexity often results from not using the domain to frame the form of the solution. Domain-driven design can help minimize accidental complexity. Essential complexity is caused by the characteristics of the problem to be solved and cannot be reduced. == Measures == Several measures of software complexity have been proposed. Many of these, although yielding a good representation of complexity, do not lend themselves to easy measurement. Some of the more commonly used metrics are McCabe's cyclomatic complexity metric Halstead's software science metrics Henry and Kafura introduced "Software Structure Metrics Based on Information Flow" in 1981, which measures complexity as a function of "fan-in" and "fan-out". They define fan-in of a procedure as the number of local flows into that procedure plus the number of data structures from which that procedure retrieves information. Fan-out is defined as the number of local flows out of that procedure plus the number of data structures that the procedure updates. Local flows relate to data passed to, and from procedures that call or are called by, the procedure in question. Henry and Kafura's complexity value is defined as "the procedure length multiplied by the square of fan-in multiplied by fan-out" (Length ×(fan-in × fan-out)²). Chidamber and Kemerer introduced "A Metrics Suite for Object-Oriented Design" in 1994, focusing on metrics for object-oriented code. They introduce six OO complexity metrics: (1) weighted methods per class; (2) coupling between object classes; (3) response for a class; (4) number of children; (5) depth of inheritance tree; and (6) lack of cohesion of methods. Several other metrics can be used to measure programming complexity: Branching complexity (Sneed Metric) Data access complexity (Card Metric) Data complexity (Chapin Metric) Data flow complexity (Elshof Metric) Decisional complexity (McClure Metric) Path Complexity (Bang Metric) Tesler's Law is an adage in human–computer interaction stating that every application has an inherent amount of complexity that cannot be removed or hidden. == Chidamber and Kemerer Metrics == Chidamber and Kemerer proposed a set of programing complexity metrics widely used in measurements and academic articles: weighted methods per class, coupling between object classes, response for a class, number of children, depth of inheritance tree, and lack of cohesion of methods, described below: Weighted methods per class ("WMC") W M C = ∑ i = 1 n c i {\displaystyle WMC=\sum _{i=1}^{n}c_{i}} n is the number of methods on the class c i {\displaystyle c_{i}} is the complexity of the method Coupling between object classes ("CBO") number of other class which is coupled (using or being used) Response for a class ("RFC") R F C = | R S | {\displaystyle RFC=|RS|} where R S = { M } ∪ a l l i { R i } {\displaystyle RS=\{M\}\cup _{all\ i}\{R_{i}\}} R i {\displaystyle R_{i}} is set of methods called by method i M {\displaystyle M} is the set of methods in the class Number of children ("NOC") sum of all classes that inherit this class or a descendant of it Depth of inheritance tree ("DIT") maximum depth of the inheritance tree for this class Lack of cohesion of methods ("LCOM") Measures the intersection of the attributes used in common by the class methods L C O M = { | P | − | Q | , if | P | > | Q | 0 , otherwise {\displaystyle LCOM={\begin{cases}|P|-|Q|,&{\text{if }}|P|>|Q|\\0,&{\text{otherwise }}\end{cases}}} Where P = { ( I i , I j ) | I i ∩ I j = ∅ } {\displaystyle P=\{(I_{i},I_{j})|I_{i}\cap I_{j}=\emptyset \}} And Q = { ( I i , I j ) | I i ∩ I j ≠ ∅ } {\displaystyle Q=\{(I_{i},I_{j})|I_{i}\cap I_{j}\neq \emptyset \}} With I i {\displaystyle I_{i}} is the set of attributes (instance variables) accessed (read from or written to) by the i {\displaystyle i} -th method of the class == See also == Programming paradigm Software crisis == References ==
https://en.wikipedia.org/wiki/Programming_complexity
In computer programming, flag can refer to one or more bits that are used to store a binary value or a Boolean variable for signaling special code conditions, such as file empty or full queue statuses. Flags may be found as members of a defined data structure, such as a database record, and the meaning of the value contained in a flag will generally be defined in relation to the data structure it is part of. In many cases, the binary value of a flag will be understood to represent one of several possible states or statuses. In other cases, the binary values may represent one or more attributes in a bit field, often related to abilities or permissions, such as "can be written to" or "can be deleted". However, there are many other possible meanings that can be assigned to flag values. One common use of flags is to mark or designate data structures for future processing. Within microprocessors and other logic devices, flags are commonly used to control or indicate the intermediate or final state or outcome of different operations. Microprocessors typically have, for example, a status register that is composed of such flags, and the flags are used to indicate various post-operation conditions, such as when there has been an arithmetic overflow. The flags can be utilized in subsequent operations, such as in processing conditional jump instructions. For example a je (Jump if Equal) instruction in the x86 assembly language will result in a jump if the Z (zero) flag was set by some previous operation. A command line switch is also referred to as a "flag". Command line programs often start with an option parser that translates command line switches into flags in the sense of this article. == See also == Bit field Control register Enumerated type FLAGS register (computing) Program status word Semaphore (programming) Status register == References ==
https://en.wikipedia.org/wiki/Flag_(programming)
Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making specific disciplined use of the structured control flow constructs of selection (if/then/else) and repetition (while and for), block structures, and subroutines. It emerged in the late 1950s with the appearance of the ALGOL 58 and ALGOL 60 programming languages, with the latter including support for block structures. Contributing factors to its popularity and widespread acceptance, at first in academia and later among practitioners, include the discovery of what is now known as the structured program theorem in 1966, and the publication of the influential "Go To Statement Considered Harmful" open letter in 1968 by Dutch computer scientist Edsger W. Dijkstra, who coined the term "structured programming". Structured programming is most frequently used with deviations that allow for clearer programs in some particular cases, such as when exception handling has to be performed. == Elements == === Control structures === Following the structured program theorem, all programs are seen as composed of three control structures: "Sequence"; ordered statements or subroutines executed in sequence. "Selection"; one of a number of statements is executed depending on the state of the program. This is usually expressed with keywords such as if..then..else..endif. The conditional statement should have at least one true condition and each condition should have one exit point at max. "Iteration"; a statement or block is executed until the program reaches a certain state, or operations have been applied to every element of a collection. This is usually expressed with keywords such as while, repeat, for or do..until. Often it is recommended that each loop should only have one entry point (and in the original structural programming, also only one exit point, and a few languages enforce this). === Subroutines === Subroutines; callable units such as procedures, functions, methods, or subprograms are used to allow a sequence to be referred to by a single statement. === Blocks === Blocks are used to enable groups of statements to be treated as if they were one statement. Block-structured languages have a syntax for enclosing structures in some formal way, such as an if-statement bracketed by if..fi as in ALGOL 68, or a code section bracketed by BEGIN..END, as in PL/I and Pascal, whitespace indentation as in Python, or the curly braces {...} of C and many later languages. == Structured programming languages == It is possible to do structured programming with any programming language enabling code blocks and the three types of control structures, even though a procedural programming language is able to break the structure. Some of the languages initially used for structured programming include: ALGOL, Pascal, PL/I, Ada and RPL but most new procedural programming languages since that time have included features to encourage structured programming, and sometimes deliberately left out features – notably GOTO – in an effort to make unstructured programming more difficult. Structured programming (sometimes known as modular programming) enforces a logical structure on the program being written to make it more efficient and easier to understand and modify. == History == === Theoretical foundation === The structured program theorem provides the theoretical basis of structured programming. It states that three ways of combining programs—sequencing, selection, and iteration—are sufficient to express any computable function. This observation did not originate with the structured programming movement; these structures are sufficient to describe the instruction cycle of a central processing unit, as well as the operation of a Turing machine. Therefore, a processor is always executing a "structured program" in this sense, even if the instructions it reads from memory are not part of a structured program. However, authors usually credit the result to a 1966 paper by Böhm and Jacopini, possibly because Dijkstra cited this paper himself. The structured program theorem does not address how to write and analyze a usefully structured program. These issues were addressed during the late 1960s and early 1970s, with major contributions by Dijkstra, Robert W. Floyd, Tony Hoare, Ole-Johan Dahl, and David Gries. === Debate === P. J. Plauger, an early adopter of structured programming, described his reaction to the structured program theorem: Us converts waved this interesting bit of news under the noses of the unreconstructed assembly-language programmers who kept trotting forth twisty bits of logic and saying, 'I betcha can't structure this.' Neither the proof by Böhm and Jacopini nor our repeated successes at writing structured code brought them around one day sooner than they were ready to convince themselves. Donald Knuth accepted the principle that programs must be written with provability in mind, but he disagreed with abolishing the GOTO statement, and as of 2018 has continued to use it in his programs. In his 1974 paper, "Structured Programming with Goto Statements", he gave examples where he believed that a direct jump leads to clearer and more efficient code without sacrificing provability. Knuth proposed a looser structural constraint: It should be possible to draw a program's flow chart with all forward branches on the left, all backward branches on the right, and no branches crossing each other. Many of those knowledgeable in compilers and graph theory have advocated allowing only reducible flow graphs. Structured programming theorists gained a major ally in the 1970s after IBM researcher Harlan Mills applied his interpretation of structured programming theory to the development of an indexing system for The New York Times research file. The project was a great engineering success, and managers at other companies cited it in support of adopting structured programming, although Dijkstra criticized the ways that Mills's interpretation differed from the published work. As late as 1987 it was still possible to raise the question of structured programming in a computer science journal. Frank Rubin did so in that year with an open letter titled "'GOTO Considered Harmful' Considered Harmful". Numerous objections followed, including a response from Dijkstra that sharply criticized both Rubin and the concessions other writers made when responding to him. === Outcome === By the end of the 20th century, nearly all computer scientists were convinced that it is useful to learn and apply the concepts of structured programming. High-level programming languages that originally lacked programming structures, such as FORTRAN, COBOL, and BASIC, now have them. == Common deviations == While goto has now largely been replaced by the structured constructs of selection (if/then/else) and repetition (while and for), few languages are purely structured. The most common deviation, found in many languages, is the use of a return statement for early exit from a subroutine. This results in multiple exit points, instead of the single exit point required by structured programming. There are other constructions to handle cases that are awkward in purely structured programming. === Early exit === The most common deviation from structured programming is early exit from a function or loop. At the level of functions, this is a return statement. At the level of loops, this is a break statement (terminate the loop) or continue statement (terminate the current iteration, proceed with next iteration). In structured programming, these can be replicated by adding additional branches or tests, but for returns from nested code this can add significant complexity. C is an early and prominent example of these constructs. Some newer languages also have "labeled breaks", which allow breaking out of more than just the innermost loop. Exceptions also allow early exit, but have further consequences, and thus are treated below. Multiple exits can arise for a variety of reasons, most often either that the subroutine has no more work to do (if returning a value, it has completed the calculation), or has encountered "exceptional" circumstances that prevent it from continuing, hence needing exception handling. The most common problem in early exit is that cleanup or final statements are not executed – for example, allocated memory is not deallocated, or open files are not closed, causing memory leaks or resource leaks. These must be done at each return site, which is brittle and can easily result in bugs. For instance, in later development, a return statement could be overlooked by a developer, and an action that should be performed at the end of a subroutine (e.g., a trace statement) might not be performed in all cases. Languages without a return statement, such as standard Pascal and Seed7, do not have this problem. Most modern languages provide language-level support to prevent such leaks; see detailed discussion at resource management. Most commonly this is done via unwind protection, which ensures that certain code is guaranteed to be run when execution exits a block; this is a structured alternative to having a cleanup block and a goto. This is most often known as try...finally, and considered a part of exception handling. In case of multiple return statements introducing try...finally, without exceptions might look strange. Various techniques exist to encapsulate resource management. An alternative approach, found primarily in C++, is Resource Acquisition Is Initialization, which uses normal stack unwinding (variable deallocation) at function exit to call destructors on local variables to deallocate resources. Kent Beck, Martin Fowler and co-authors have argued in their refactoring books that nested conditionals may be harder to understand than a certain type of flatter structure using multiple exits predicated by guard clauses. Their 2009 book flatly states that "one exit point is really not a useful rule. Clarity is the key principle: If the method is clearer with one exit point, use one exit point; otherwise don’t". They offer a cookbook solution for transforming a function consisting only of nested conditionals into a sequence of guarded return (or throw) statements, followed by a single unguarded block, which is intended to contain the code for the common case, while the guarded statements are supposed to deal with the less common ones (or with errors). Herb Sutter and Andrei Alexandrescu also argue in their 2004 C++ tips book that the single-exit point is an obsolete requirement. In his 2004 textbook, David Watt writes that "single-entry multi-exit control flows are often desirable". Using Tennent's framework notion of sequencer, Watt uniformly describes the control flow constructs found in contemporary programming languages and attempts to explain why certain types of sequencers are preferable to others in the context of multi-exit control flows. Watt writes that unrestricted gotos (jump sequencers) are bad because the destination of the jump is not self-explanatory to the reader of a program until the reader finds and examines the actual label or address that is the target of the jump. In contrast, Watt argues that the conceptual intent of a return sequencer is clear from its own context, without having to examine its destination. Watt writes that a class of sequencers known as escape sequencers, defined as a "sequencer that terminates execution of a textually enclosing command or procedure", encompasses both breaks from loops (including multi-level breaks) and return statements. Watt also notes that while jump sequencers (gotos) have been somewhat restricted in languages like C, where the target must be an inside the local block or an encompassing outer block, that restriction alone is not sufficient to make the intent of gotos in C self-describing and so they can still produce "spaghetti code". Watt also examines how exception sequencers differ from escape and jump sequencers; this is explained in the next section of this article. In contrast to the above, Bertrand Meyer wrote in his 2009 textbook that instructions like break and continue "are just the old goto in sheep's clothing" and strongly advised against their use. === Exception handling === Based on the coding error from the Ariane 501 disaster, software developer Jim Bonang argues that any exceptions thrown from a function violate the single-exit paradigm, and proposes that all inter-procedural exceptions should be forbidden. Bonang proposes that all single-exit conforming C++ should be written along the lines of: Peter Ritchie also notes that, in principle, even a single throw right before the return in a function constitutes a violation of the single-exit principle, but argues that Dijkstra's rules were written in a time before exception handling became a paradigm in programming languages, so he proposes to allow any number of throw points in addition to a single return point. He notes that solutions that wrap exceptions for the sake of creating a single-exit have higher nesting depth and thus are more difficult to comprehend, and even accuses those who propose to apply such solutions to programming languages that support exceptions of engaging in cargo cult thinking. David Watt also analyzes exception handling in the framework of sequencers (introduced in this article in the previous section on early exits.) Watt notes that an abnormal situation (generally exemplified with arithmetic overflows or input/output failures like file not found) is a kind of error that "is detected in some low-level program unit, but [for which] a handler is more naturally located in a high-level program unit". For example, a program might contain several calls to read files, but the action to perform when a file is not found depends on the meaning (purpose) of the file in question to the program and thus a handling routine for this abnormal situation cannot be located in low-level system code. Watts further notes that introducing status flags testing in the caller, as single-exit structured programming or even (multi-exit) return sequencers would entail, results in a situation where "the application code tends to get cluttered by tests of status flags" and that "the programmer might forgetfully or lazily omit to test a status flag. In fact, abnormal situations represented by status flags are by default ignored!" He notes that in contrast to status flags testing, exceptions have the opposite default behavior, causing the program to terminate unless the programmer explicitly deals with the exception in some way, possibly by adding code to willfully ignore it. Based on these arguments, Watt concludes that jump sequencers or escape sequencers (discussed in the previous section) are not as suitable as a dedicated exception sequencer with the semantics discussed above. The textbook by Louden and Lambert emphasizes that exception handling differs from structured programming constructs like while loops because the transfer of control "is set up at a different point in the program than that where the actual transfer takes place. At the point where the transfer actually occurs, there may be no syntactic indication that control will in fact be transferred." Computer science professor Arvind Kumar Bansal also notes that in languages which implement exception handling, even control structures like for, which have the single-exit property in absence of exceptions, no longer have it in presence of exceptions, because an exception can prematurely cause an early exit in any part of the control structure; for instance if init() throws an exception in for (init(); check(); increm()), then the usual exit point after check() is not reached. Citing multiple prior studies by others (1999–2004) and their own results, Westley Weimer and George Necula wrote that a significant problem with exceptions is that they "create hidden control-flow paths that are difficult for programmers to reason about". The necessity to limit code to single-exit points appears in some contemporary programming environments focused on parallel computing, such as OpenMP. The various parallel constructs from OpenMP, like parallel do, do not allow early exits from inside to the outside of the parallel construct; this restriction includes all manner of exits, from break to C++ exceptions, but all of these are permitted inside the parallel construct if the jump target is also inside it. === Multiple entry === More rarely, subprograms allow multiple entry. This is most commonly only re-entry into a coroutine (or generator/semicoroutine), where a subprogram yields control (and possibly a value), but can then be resumed where it left off. There are a number of common uses of such programming, notably for streams (particularly input/output), state machines, and concurrency. From a code execution point of view, yielding from a coroutine is closer to structured programming than returning from a subroutine, as the subprogram has not actually terminated, and will continue when called again – it is not an early exit. However, coroutines mean that multiple subprograms have execution state – rather than a single call stack of subroutines – and thus introduce a different form of complexity. It is very rare for subprograms to allow entry to an arbitrary position in the subprogram, as in this case the program state (such as variable values) is uninitialized or ambiguous, and this is very similar to a goto. === State machines === Some programs, particularly parsers and communications protocols, have a number of states that follow each other in a way that is not easily reduced to the basic structures, and some programmers implement the state-changes with a jump to the new state. This type of state-switching is often used in the Linux kernel. However, it is possible to structure these systems by making each state-change a separate subprogram and using a variable to indicate the active state (see trampoline). Alternatively, these can be implemented via coroutines, which dispense with the trampoline. == See also == DRAKON Minimal evaluation Nassi–Shneiderman diagram Structure chart Structured concurrency Switch statement == References == === Citations === === Sources === == External links == BPStruct - A tool to structure concurrent systems (programs, process models) J. Darlinton; M. Ghanem; H. W. To (1993), "Structured Parallel Programming", In Programming Models for Massively Parallel Computers. IEEE Computer Society Press. 1993: 160–169, CiteSeerX 10.1.1.37.4610
https://en.wikipedia.org/wiki/Structured_programming
The Public Broadcasting Service (PBS) is an American public broadcaster and non-commercial, free-to-air television network based in Arlington, Virginia. PBS is a publicly funded nonprofit organization and the most prominent provider of educational programs to public television stations in the United States, distributing shows such as Frontline, Nova, PBS News Hour, Masterpiece, Mister Rogers' Neighborhood, Sesame Street, Barney & Friends and American Experience. Certain stations also provide spillover service to Canada. PBS is funded by a combination of member station dues, the Corporation for Public Broadcasting, pledge drives, and donations from both private foundations and individual citizens. All proposed funding for programming is subject to a set of standards to ensure the program is free of influence from the funding source. PBS has over 350 member television stations, many owned by educational institutions, nonprofit groups both independent or affiliated with one particular local public school district or collegiate educational institution, or entities owned by or related to state government. == History == PBS was established on November 3, 1969, by Hartford N. Gunn Jr. (president of WGBH), John Macy (president of CPB), James Day (last president of National Educational Television), and Kenneth A. Christiansen (chairman of the department of broadcasting at the University of Florida). It began operations on October 5, 1970, taking over many of the functions of its predecessor, National Educational Television (NET), which later merged with Newark, New Jersey station WNDT to form WNET. In 1973, it merged with Educational Television Stations. Around the same time, the groups started out the National Public Affairs Broadcast Center (later National Public Affairs Center for Television), which offered news and national affairs to the service. The group was later merged into member station WETA-TV in 1972. Immediately after public disclosure of the Watergate scandal, on May 17, 1973, the United States Senate Watergate Committee commenced proceedings; PBS broadcast the proceedings nationwide, with Robert MacNeil and Jim Lehrer as commentators. Although all of the Big Three TV Networks ran coverage of the hearings, PBS re-broadcast them on prime time. For seven months, nightly "gavel-to-gavel" broadcasts drew great public interest, and raised the profile of the fledgling PBS network. In 1991, the Corporation for Public Broadcasting resumed funding for most PBS shows that debuted prior to 1977, with the exceptions of Washington Week in Review and Wall Street Week (CPB resumed funding of Washington Week in 1997). In 1994, The Chronicle of Philanthropy released the results of the largest study on the popularity and credibility of charitable and non-profit organizations. PBS ranked as the 11th "most popular charity/non-profit in America" from over 100 charities researched in the study conducted by the industry publication, with 38.2% of Americans over the age of 12 choosing "love" and "like a lot" for PBS. Since the mid-2000s, Roper Opinion Research polls commissioned by PBS have consistently placed the service as the most-trusted national institution in the United States. A 2016–2017 study by Nielsen Media Research found 80% of all US television households view the network's programs over the course of a year. However, PBS is not responsible for all programming carried on public television stations, a large proportion of which may come from its member stations—including WGBH-TV, WETA-TV, WNET, WTTW, WQED, WHYY-TV, Twin Cities PBS—American Public Television, and independent producers. This distinction regarding the origin of different programs on the service presents a frequent source of viewer confusion. In December 2009, PBS signed up for the Nielsen ratings audience measurement reports, and began to be included in its primetime and daily "Television Index" reports, alongside the major commercial broadcast networks. In May 2011, PBS announced that it would incorporate breaks containing underwriter spots for corporate and foundation sponsors, program promotions and identification spots within four breaks placed within episodes of Nature and NOVA, airing episodes broken up into segments of up to 15 minutes, rather than airing them as straight 50- to 55-minute episodes. The strategy began that fall, with the intent to expand the in-program breaks to the remainder of the schedule if successful. In 2011, PBS released apps for iOS and Android to allow viewing of full-length videos on mobile devices. "PBS UK" was launched as a paid subscription channel in the United Kingdom on November 1, 2011, featuring American documentary programming sourced from PBS. Better identifying its subject matter, this channel was renamed "PBS America" on July 4, 2012. The channel has subsequently become available in other parts of Europe and Australia. On February 28, 2012, PBS partnered with AOL to launch Makers: Women Who Make America, a digital documentary series focusing on high-achieving women in male-dominated industries such as war, comedy, space, business, Hollywood and politics. PBS initially struggled to compete with online media such as YouTube for market share. In a 2012 speech to 850 top executives from PBS stations, Senior Vice President of Digital Jason Seiken warned that PBS was in danger of being disrupted by YouTube studios such as Maker Studios. In the speech, later described as a "seminal moment" for public television, he laid out his vision for a new style of PBS digital video production. Station leadership rallied around his vision and Seiken formed PBS Digital Studios, which began producing educational but edgy videos, something Seiken called "PBS-quality with a YouTube sensibility". The studio's first hit, an auto-tuned version of the theme from one of their most famous television programs, Mister Rogers' Neighborhood, was one of YouTube's 10 most viral videos of 2012. By 2013, monthly video views on PBS.org had risen from 2 million to a quarter-billion, PBS.org traffic had surpassed that of the CBS, NBC, and ABC web sites, PBSKids.org had become the dominant US children's site for video, and PBS had won more 2013 Webby Awards than any other media company in the world. On May 8, 2013, full-length episodes of PBS' prime time, news and children's programs were made available through the Roku streaming player; programming is available on Roku as separate streaming channels for "PBS" and "PBS Kids" content. Some content is only available with a PBS Passport member benefit subscription. On July 1, 2016, Amazon Prime Video and PBS Distribution entered into a multi-year agreement which saw several PBS Kids series on other streaming services move to Amazon Prime Video. PBS Distribution partnered with MultiChoice to launch PBS Kids on May 22, 2019, on DStv and GOtv subscription platforms across its Sub-Saharan Africa footprint. In mid-2021, the channel was added to Australia's Foxtel subscription platform. At the summer 2019 Television Critics Association press tour day for PBS on July 29, 2019, it was announced that MVPD YouTube TV would begin to carry PBS programming and member stations in the fall of 2019. Member stations have the choice of having their traditional channel on the service with its full programming schedule received by Google over-the-air and uploaded to the service, a YouTube TV-only feed provided by the station with some programming substitutions due to lack of digital rights, or a PBS-provided feed with limited localization, though with no local programming or pledge drive programming. In 2019, PBS announced plans to move its headquarters to another building in the Crystal Gateway complex, while remaining in Crystal City, Virginia, and did so in 2020, which included a top building sign visible off the Richmond Highway. On August 4, 2020, the Amazon Prime Video platform added a "PBS Documentaries" package. As of that time it offered four separately-subscribable selections of PBS programming in the United States, "PBS Documentaries", "PBS Living" (also on Apple TV), "PBS Masterpiece" (also in Canada) and "PBS KIDS". In the UK, a "PBS America" documentaries package became available on Amazon Prime Video. On September 3, 2020, PBS began to offer a livestream of their member stations for free via its website (as well as the websites from the member stations), on smart TVs, and on their mobile apps. However, only a small handful of stations currently do not have a livestream of their stations set up. Jefferson Graham of USA Today called it "arguably the best bargain in streaming". July 1, 2021, saw a PBS Julia Child channel added to Pluto TV and Tubi in the United States. The channels "PBS Antiques Roadshow", "Julia Child", "Antiques Road Trip" and "PBS Nature" were added to a number of American FAST platforms in January 2023. Antiques Road Trip later became available in Australia. The channels "PBS Food" (in the United States) and "PBS History" (in the UK and Australia) launched on certain FAST platforms in late 2023. The channel "PBS Retro" was added to Roku's live TV channel lineup in the United States on April 23, 2024, airing PBS Kids shows from the 70s, 80s and 90s. The "PBS Science" channel became available in Australia in 2024. It is also available in the UK and Ireland. == Operations == Even with its status as a non-profit and educational television network, PBS engages in program distribution. PBS provides television content and related services to its member stations, each of which together cooperatively owns the network. Unlike the affiliates for commercial TV networks, each non-profit PBS member station is charged with the responsibility of programming local content such as news, interviews, cultural, and public affairs programs for its individual market or state that supplements content provided by PBS and other public television distributors. In a commercial broadcast television network structure, affiliates give up portions of their local advertising airtime in exchange for carrying network programming, and the network pays its affiliates a share of the revenue it earns from advertising. By contrast, PBS member stations pay fees for the shows acquired and distributed by the national organization. Under this relationship, PBS member stations have greater latitude in local scheduling than their commercial broadcasting counterparts. Scheduling of PBS-distributed series may vary greatly depending on the market. This can be a source of tension as stations seek to preserve their localism, and PBS strives to market a consistent national lineup. However, PBS has a policy of "common carriage", which requires most stations to clear the national prime time programs on a common programming schedule to market them nationally more effectively. Management at former Los Angeles member KCET cited unresolvable financial and programming disputes among its major reasons for leaving PBS after over 40 years in January 2011, although it would return to PBS in 2019. Although PBS has a set schedule of programming, particularly in regard to its prime time schedule, member stations reserve the right to schedule PBS-distributed programming in other time slots or not clear it at all if they choose to do so; few of the service's members carry all its programming. Most PBS stations timeshift some distributed programs. Once PBS accepts a program offered for distribution, PBS, rather than the originating member station, retains exclusive rebroadcasting rights during an agreed period. Suppliers, however, retain the right to sell the program's intellectual property in non-broadcast media such as DVDs, books, and sometimes PBS-licensed merchandise. == Programming == The evening and primetime schedule on PBS features a diverse array of programming including fine arts (Great Performances); drama (Masterpiece, Downton Abbey, American Family: Journey of Dreams); science (Nova, Nature); history (American Experience, American Masters, History Detectives, Antiques Roadshow); music (Austin City Limits, Soundstage); public affairs (Frontline, PBS NewsHour, Washington Week, Nightly Business Report); independent films and documentaries (P.O.V., Independent Lens); home improvement (This Old House); and interviews (Amanpour & Company, Tavis Smiley, The Dick Cavett Show). In 2012, PBS began organizing much of its prime time programming around a genre-based schedule (for example, drama series encompass the Sunday schedule, while science-related programs are featured on Wednesdays). Unlike its radio counterpart, National Public Radio, PBS does not have a central program production arm or news division. All of the programming carried by PBS, whether news, documentary or entertainment, is created by (or in most cases produced under contract with) other parties, such as individual member stations. Boston member WGBH-TV is one of the largest producers of educational television programming, including shows like American Experience, Arthur (with Canada-based CINAR), Masterpiece Theatre, Nova, Antiques Roadshow and Frontline as well as many other children's and lifestyle programs. News programs are produced by WETA-TV (PBS News Hour) in Washington, D.C., WNET in New York City and WPBT in Miami. Newark, New Jersey/New York City member WNET produces or distributes programs such as Secrets of the Dead, Nature, and Cyberchase. PBS also works with other networks for programming such as CNN International for Amanpour & Company which is a co-production of CNN International and WNET. PBS member stations are known for rebroadcasting British television costume dramas, comedies and science fiction programs (acquired from the BBC and other sources) such as Downton Abbey; 'Allo 'Allo!; Are You Being Served?; The Benny Hill Show, Red Dwarf; The Fall and Rise of Reginald Perrin; Father Ted; Fawlty Towers; Harry Enfield & Chums; Keeping Up Appearances; Monty Python's Flying Circus; Mr. Bean, The Vicar of Dibley, the original run of Doctor Who, and Sherlock. However, a significant amount of sharing takes place. The BBC and British broadcasters such as Channel 4 often cooperate with PBS stations, producing material that is shown on both sides of the Atlantic. Less frequently, Canadian, Australian and other international programming appears on PBS stations (such as The Red Green Show, currently distributed by syndicator Executive Program Services); public broadcasting syndicators are more likely to offer this programming to U.S.-based public television stations. PBS is not the only distributor of public television programming to the member stations. Other distributors have emerged from the roots of companies that maintained loosely held regional public television stations in the 1960s. Boston-based American Public Television, also formerly known as Eastern Educational Network and the American Program Service, among other names, is another major distributor of programming to U.S. non-commercial stations. The National Educational Telecommunications Association (NETA, formerly SECA) is another distributor, with properties including The Shapies and Jerry Yarnell School of Fine Art. In addition, the member stations themselves also produce a variety of local shows, some of which subsequently receive national distribution through PBS or other distributors. Rerun programming, especially domestic programming not originally produced for public television, is generally uncommon on PBS or its member stations. The most prominent exception to this is The Lawrence Welk Show, which has aired continuously in reruns on PBS (through the Oklahoma Educational Television Authority) almost every weekend since 1986. Reruns of programs originally produced for public television are common, especially with former PBS shows whose hosts have retired or died (for example, The Joy of Painting and Mister Rogers' Neighborhood). Children's programming (such as Clifford the Big Red Dog and DragonflyTV, the latter of which is also syndicated on commercial television) is rerun extensively. In 2020 and 2021, PBS served as the over-the-air home to select specials from the Peanuts library, under sublicense from Apple; the deal was not renewed in 2022. === PBS Kids === Launched as PTV on July 11, 1994, PBS Kids is the brand for children's programs aired by PBS. PBS Kids, launched in 1999 and operated until 2005, was largely funded by satellite provider DirecTV. The original channel ceased operations on September 26, 2005, in favor of PBS Kids Sprout, a commercial digital cable and satellite television channel originally operated as a joint venture between PBS, Comcast, Sesame Workshop and Apax Partners (NBCUniversal, which Comcast acquired in 2011, later acquired the other partners' interests in the channel in 2012). However, the original programming block still exists on PBS, filling daytime and in some cases, weekend morning schedules on its member stations; many members also carry 24-hour locally programmed children's networks featuring PBS Kids content on one of their digital subchannels. A revived version of the PBS Kids Channel was launched on January 16, 2017. As of 2019, PBS Kids is the only children's programming block on U.S. broadcast television. PAs the children's programs it distributes are intended to educate as well as entertain its target audience, PBS and its stations have long been in compliance with educational programming guidelines set by the Federal Communications Commission in response to the enactment of the Children's Television Act of 1990. Many member stations have historically also broadcast distance education and other instructional television programs, typically during daytime slots; though with the advent of digital television, which has allowed stations to carry these programs on digital subchannels in lieu of the main PBS feed or exclusively over online, many member stations/networks have replaced distance education content with children's and other programming. As of February 2023, the duration of the PBS Kids block was reduced from 13 hours of daily programming including both before- and after-school programs, down to eight hours primarily in the mornings. This move was meant to cater to more general audiences in the afternoons, and as part of an ongoing move of kids programming to on-demand streaming services. As PBS is often known for doing, PBS Kids has broadcast imported series from other countries; these include British series originally broadcast by the BBC and ITV. Through American Public Television, many PBS stations also began airing the Australian series Raggs on June 4, 2007. Some of the programs broadcast as part of the service's children's lineup or through public broadcast syndication directly to its members have subsequently been syndicated to commercial television outlets (such as Ghostwriter and The Magic School Bus). === Sports === Many PBS member stations and networks—including Mississippi Public Broadcasting (MHSAA), Georgia Public Broadcasting (GHSA), Maine Public Broadcasting Network (MPA), Iowa PBS (IGHSAU), Nebraska Public Media (NSAA), and WKYU-TV (Western Kentucky Hilltoppers)—locally broadcast high school and college sports. From the 1980s onward, the national PBS network has not typically carried sporting events, mainly because the broadcast rights to most sporting events have become more cost-prohibitive in that timeframe, especially for nonprofits with limited revenue potential; in addition, starting with the respective launches of the MountainWest Sports Network (now defunct) and Big Ten Network in 2006 and 2007 and the later launches of the Pac-12 Network and ESPN's SEC Network and ACC Network, athletic conferences have acquired rights for all of their member university's sports programs for their cable channels, restricting their use from PBS member stations, even those associated with their own universities. From 1976 to 1989, KQED produced a series of Bundesliga matches under the banner Soccer Made in Germany, with Toby Charles announcing. PBS also carried tennis events, as well as Ivy League football. Notable football commentators included Upton Bell, Marty Glickman, Bob Casciola, Brian Dowling, Sean McDonough and Jack Corrigan. Other sports programs included interview series such as The Way It Was and The Sporting Life. == Governance == The board of directors is responsible for governing and setting policy for PBS, consisting of 27 members: 14 professional directors (station managers), 12 general directors (outside directors), and the PBS president. All PBS Board members serve three-year terms, without pay. PBS member stations elect the 14 professional directors; the board elects the 12 general directors and appoints the PBS president and CEO; and the entire board elects its officers. == Member stations == As of March 2015, PBS maintains current memberships with 354 television stations encompassing 50 states, the District of Columbia and four U.S. possessions; as such, it is the only television broadcaster in the United States—commercial or non-commercial—which has station partners licensed in every U.S. state (by comparison, none of the five major commercial broadcast networks has affiliates in certain states where PBS has members, most notably New Jersey). The service has an estimated national reach of 93.74% of all households in the United States (or 292,926,047 Americans with at least one television set). PBS stations are commonly operated by nonprofit organizations, state agencies, local authorities (such as municipal boards of education), or universities in their city of license; this is similar (albeit more centralized in states where a licensee owns multiple stations rebroadcasting the main PBS member) to the early model of commercial broadcasting in the U.S., in which network-affiliated stations were initially owned by companies that owned few to no other television stations elsewhere in the country. In some U.S. states, a group of PBS stations throughout the entire state may be organized into a single regional "subnetwork" (such as Alabama Public Television and Arkansas PBS); in this model, PBS programming and other content is distributed by the originating station in the subnetwork to other full-power stations that serve as satellites as well as any low-power translators in other areas of the state. Some states may be served by such a regional network and simultaneously have PBS member stations in a certain city (such as the case with secondary member KBDI-TV in Denver, which is not related to Colorado member network Rocky Mountain PBS and its flagship station and primary Denver PBS member, KRMA-TV) that operate autonomously from the regional member network. As opposed to the present commercial broadcasting model in which network programs are often carried exclusively on one television station in a given market, PBS may maintain more than one member station in certain markets, which may be owned by the licensee of the market's primary PBS member station or owned by a separate licensee (as a prime example, KOCE-TV, KLCS and KVCR-DT—which are all individually owned—serve as PBS stations for the Los Angeles market; KCET served as the market's primary PBS member until it left the service in January 2011, at which time it was replaced by KOCE). KCET rejoined PBS in 2019, thus giving the Los Angeles area four different member stations. For these cases, PBS uses the Program Differentiation Plan, which divides by percentage the number of programs distributed by the service that each member can carry on their schedule; often, this assigns a larger proportion of PBS-distributed programming to the primary member station, with the secondary members being allowed to carry a lesser number of program offerings from the service's schedule. Unlike public broadcasters in most other countries, PBS cannot own any of the stations that broadcasts its programming; therefore, it is one of the few television programming bodies that does not have any owned-and-operated stations. This is partly due to the origins of the PBS stations themselves, and partly due to historical broadcast license issues. === Participating stations === Most PBS member stations have produced at least some nationally distributed programs. Current regularly scheduled programming on the PBS national feed is produced by a smaller group of stations, including: WGBH-TV (Arthur, NOVA, Masterpiece, Frontline, Fetch! with Ruff Ruffman, Martha Speaks, Peep and the Big Wide World, Between the Lions, Curious George, Lidia's Kitchen, Design Squad, Jamie Oliver, etc.) WNET (Nature, PBS NewsHour Weekend, Cyberchase, Amanpour & Company, Wishbone etc.) Previously Connecticut Public Television and now WNET (Barney & Friends, Bob the Builder, Thomas & Friends, etc.) WETA-TV (PBS News Hour, Washington Week, A Capitol Fourth (annually), America's Test Kitchen, This Old House, Pati's Mexican Table, BBC World News, etc.) WTTW (Nature Cat, WordWorld, Kidsongs) Maryland Public Television (MotorWeek, Space Racers, Wimzie's House, Zoboomafoo, Julia Child) KLRU (Austin City Limits) KCET (Sid the Science Kid) PBS SoCal (Lost L.A.) KQED (The Cat in the Hat Knows a Lot About That!, Yan Can Cook: Spice Kingdom) Oregon Public Broadcasting (History Detectives, Rick Steves' Europe (season 10)) PBS North Carolina (The Woodwright's Shop) South Carolina ETV (Studio See, The Magic School Bus, A Chef's Life) WXXI-TV (Biz Kid$) WQED (Mister Rogers' Neighborhood) Twin Cities PBS (KTCA-TV/KTCI-TV) (Newton's Apple, DragonflyTV, SciGirls, Hero Elementary) KCTS-TV (Rick Steves' Europe) Arkansas PBS (State of the Art) WYES-TV (Kevin Belton) == PBS networks == PBS has spun off a number of television networks, often in partnership with other media companies. PBS YOU, a distance education and how-to service operated between 2000 and 2006, and was largely succeeded by Create (a similarly formatted network owned by American Public Television). The 24-hour PBS Kids Channel has had two iterations in the age of digital television; one which existed between 1999 and 2005 (being superseded by PBS Kids Sprout), and the current version which was launched in 2017. World began operations in 2007 as a service operated by PBS but is now managed by American Public Television. PBS has also restructured its satellite feed system, simplifying HD02 (PBS West) into a timeshift feed for the Pacific Time Zone, rather than a high-definition complement to its formerly primary SD feed. PBS Kids Go! was proposed as a replacement broadcast network for the original 1999–2005 version of the PBS Kids Channel; however, plans to launch the network were folded in 2006. Programming from the PBS Satellite Service has also been carried by certain member stations or regional member networks to fill their overnight schedules (particularly those that have transitioned to a 24-hour schedule since the late 1990s), in lieu of providing programming sourced from outside public television distributors or repeats of local programming (program promotions shown on the satellite feed advertise upcoming programs as being aired on PBS during the timeslot card normally used as a placeholder for member outlets to insert local airtime information). Some or all of these services are available on a digital cable tier of many cable providers, on a free-to-air (FTA) satellite receiver receiving from PBS Satellite Service, as well as via subscription-based direct broadcast satellite providers. With the exception of Sprout, some of these services, including those from PBS member stations and networks, have not made contracts with Internet-distributed over-the-top MVPD services such as Sling TV and the now defunct PlayStation Vue. With the transition to over-the-air digital television broadcasts, many of the services are also often now available as standard-definition multicast channels on the digital signals of some member stations, while HD02 (PBS West) serves as a secondary HD feed. With the absence of advertising, network identification on these PBS networks was limited to use at the end of the program, which includes the standard series of bumpers from the "Be More" campaign. === Independent networks === While not operated or controlled by PBS proper, additional public broadcasting networks are available and carried by PBS member stations. The following three are also distributed by PBS via satellite. From 2002 to 2011, Buffalo, New York member station WNED-TV operated ThinkBright TV, a service that was carried on several stations in upstate New York. Several state networks also offer a public affairs subchannel network offering full-time coverage of state government events and legislative/judicial proceedings in the same vein as C-SPAN's coverage of the federal government. Many PBS stations also carried MHz Worldview from the MHz Networks until 2020 when MHz Networks announced its discontinuation of the network on March 1, 2020. Since then, many stations has switched to World Channel as well as First Nations Experience. A separate but related concept is the state network, where a group of stations across a state simulcast a single programming schedule from a central facility, which may include specialty subchannels unique to that broadcaster. == Visual identity == PBS introduced its first iconographic logo in 1971, a multi-colored wordmark of the network's initials with the P designed to resemble a silhouette of a human face. The logo was designed by Ernie Smith and Herb Lubalin of the Lubalin Smith Carnase design firm. Lubalin's human face "P", known internally at PBS as "Everyman", but more commonly known as the "P-Head", became the basis for all subsequent PBS logos. In 1984, PBS introduced a new version of the logo, designed by Tom Geismar of Chermayeff & Geismar. Chermayeff & Geismar felt that the Lubalin-designed logo was too similar to those of the three dominant commercial networks of the time, and they sought "to develop a symbol that could stand for the more inclusive concept of 'public television'". They inverted Lubalin's Everyman "P" to face to the right instead of the left, and repeated the outline as a series to represent a "multitude" of people. The symbol was subsequently renamed "Everyone". The repeated outline of the face has also been interpreted to suggest a degree of multiculturalism, as well as the public service aspect of the PBS mission. The logo has been used in various forms since: from 1998 onward, the Geismar logo has been rendered in white on a circle. On November 4, 2019, in honor of the network's 50th anniversary, PBS unveiled a revamped brand identity by Lippincott, intended to be better-suited for use on digital platforms. The Geismar logo was tweaked, a new custom sans-serif typeface known as PBS Sans was commissioned for the logo and other branding elements (which replaces the slab serif typeface used in the PBS logo since 1984), and electric blue and white were adopted as corporate colors. The network is allowing flexibility in implementation, but is no longer allowing the logo to be displayed independently of the PBS name. Upon the launch of the new logo, some members rebranded themselves to include PBS in their name for the first time, such as Wisconsin Public Television rebranding as PBS Wisconsin. PBS is paying out grants to at least 100 members to cover costs associated with the rebranding. == Reception == === Critical response === PBS has been praised by critics for its variety of programming. Tim Goodman of The Hollywood Reporter marked PBS' airing of Downton Abbey as a turning point for the network's reputation and program variety. He also wrote, "It's PBS's time to shine" and said that the network "is an endless bounty of riches...Ain't this great?" Stevenonymous of BuzzFeed wrote, "PBS isn't just TV anymore." David Zurawik of The Baltimore Sun wrote, "If you want a reason to believe in PBS...here it is." Mekeisha Madden Toby of TheWrap wrote, "There is a lot to love...on PBS." Kristen McQuinn of Book Riot wrote, "PBS is awesome in every way." Caroline Framke of Variety wrote, "There's still no beating PBS." Alyssa Rosenburg of The Washington Post wrote, "PBS is a unifying thread...through our cultural fabric." Margaret Renkl of The New York Times wrote, "By aiming to unite...PBS might save us yet." Margie Barron of Entertainment Today wrote, "PBS remains a beacon...that inspires." The Marketing & Research Resources survey, said that PBS is the "#1 most trusted media 19 years in a row." In 2021, the network had 14 News & Documentary Emmy Award nominations, more than any other organization. Matt Roush of TV Insider wrote, "PBS is and always has been a bright light." For the PBS Arts program, Rob Owen of Pittsburgh Post-Gazette wrote, "A gift to viewers." === On-air fundraising === Since 53% to 60% of public television's revenues come from private membership donations and grants, most stations solicit individual donations by methods including fundraising, pledge drives or telethons, which disrupt regularly scheduled programming. This has been perceived as potentially annoying since regularly scheduled programming is often replaced with specials aimed at a wider audience (such as music specials aimed at the Baby Boomer generation and financial, health and motivational programs) to solicit new members and donations; during fundraising events, these programs are often interrupted within the broadcast by long-form segments (of six to eight minutes in length) encouraging viewers to donate to their PBS member. Underwriting spots are aired at the end of each program, which differ from traditional commercials in several ways. Each spot must be approved to meet several guidelines. The main guidelines state that underwriting spots cannot be qualitative in any way, nor can they have any call to action. == Controversies == === Accusations of political/ideological bias === A 1982 broadcast of the United States Information Agency program Let Poland be Poland about the martial law declared in Poland in 1981 was condemned by broadcasters in communist Eastern Europe, who labeled it as "provocative and anticommunist" propaganda, reflecting the regimes' opposition to criticism of their actions or ideology. In 1999, at least three public television stations were caught selling or trading their mailing lists with the Democratic National Committee. Under IRS regulations, nonprofit organizations are prohibited from participating in political actions. Officials from the Corporation for Public Broadcasting condemned the practice and conducted an investigation into the matter. The stations involved were in New York, Boston, and Washington. Individual programs aired by PBS have been the targets of organized campaigns by individuals and groups with opposing views, including by former United States Secretary of Education Margaret Spellings in 2005. Nonetheless, in every year since 2004, surveys of Americans have shown PBS to have been consistently ranked as the most trusted institution in comparison to commercial broadcast and cable television, newspapers, and streaming services, and in January 2021, Americans valued tax dollars spent on PBS behind only military defense and oversight of food and drug safety. ==== Accusations during Tomlinson tenure ==== In September 2003, Kenneth Tomlinson was chosen as chairman of the CPB board. He criticized PBS and NPR for what he alleged to be a "liberal bias". His efforts sparked complaints of political pressure. To partially balance out the perceived left-leaning PBS shows, from June 2004 to July 2005, PBS aired Tucker Carlson: Unfiltered with conservative commentator Tucker Carlson, and from September 2004 to December 2005, PBS aired The Journal Editorial Report with Paul Gigot, a conservative editor of The Wall Street Journal editorial page. In December 2004, Bill Moyers resigned as a PBS regular, citing political pressure to alter the content of his program, and saying Tomlinson had pursued a "vendetta" against him. In May 2005, two House Democrats requested the CPB inspector general investigate the complaints of political interference. The inspector general's report was issued in November 2005 and described possible political influence on personnel decisions, including e-mail correspondence between Tomlinson and the White House which indicated that Tomlinson "was strongly motivated by political considerations in filling the president/CEO position", a position filled in June 2005 by former Republican National Committee co-chair Patricia Harrison. Tomlinson resigned from the CPB board on November 3, 2005. ==== Accusations since the Tomlinson tenure ==== In January 2021, Michael Beller, the chief attorney for PBS, resigned after being caught on tape suggesting that the children of Donald Trump supporters should be sent to re-education camps. === Second Trump administration === In January 2025, Federal Communications Commission (FCC) Chair Brendan Carr ordered an investigation of the corporate underwriting sponsorships of PBS and NPR member stations for possible violations of FCC regulations prohibiting noncommercial broadcasters from airing advertisements. On May 1, 2025, President Donald Trump issued Executive Order 14290 directing the Corporation for Public Broadcasting and all federal agencies to end funding for PBS and NPR, alleging biased news coverage in violation of the Public Broadcasting Act of 1967 and that public funding for news programming was "not only outdated and unnecessary but corrosive to the appearance of journalistic independence" in the current U.S. media market. In response, President and CEO Paula Kerger called the executive order "blatantly unlawful" in a press release and suggested that the order would likely be challenged in court. In 1981, Congress amended the Public Broadcasting Act to authorize noncommercial station licensees to offer services and facilities in exchange for remuneration on the condition that it not interfere with their provision of public telecommunications services. In 1984, the FCC adopted a policy allowing noncommercial stations to broadcast underwriting spots from for-profit entities that provided donations or underwriting. While the FCC prohibited underwriting spots from including certain specific content (e.g. promotion of the contributor's products, services, or business, comparative or qualitative descriptions of products, price information, calls to action, or inducements to buy, sell, or lease products), the FCC placed no limit of the length of the underwriting spots and permitted the use of logos and slogans for the purpose of identifying the contributor, business location information and phone numbers, value-neutral descriptions of product or service lines, brand and trade names, and product and service listings. In 2012, the Corporation for Public Broadcasting issued a report commissioned by Congress and prepared by Booz & Company that noted that such underwriting accounted for less than one-fifth of the revenue for public television and radio stations (and had declined substantially due to the Great Recession), and along with a 2007 Government Accountability Office report about public television specifically, the Booz & Company report concluded that growth in such underwriting revenue was unlikely and that allowing public broadcasters to air advertisements would not offset a decline in federal funding and would contribute to a decline in support from other sources. Analysis of CPB data published by the Pew Research Center in August 2023 found that underwriting revenue for NPR member stations from 2008 through 2021 was mostly flat and fell below 2009 levels in 2021 following the COVID-19 recession, while corporate funding for PBS member stations ranged from 17% to 23% of total revenue from 2015 through 2022. === Lawsuit with Pacific Arts === In the 1990s, PBS became involved in a dispute over home video licensing rights with Pacific Arts Corporation, a multimedia company owned and operated by former Monkees guitarist Michael Nesmith. In 1990, Pacific Arts secured a contract with PBS to distribute their back catalog of programming on VHS under the PBS Home Video banner. However, in the early 1990s, Pacific Arts and PBS went through a series of serious disagreements. Lawsuits were filed: by Nesmith and Pacific Arts against PBS for breach of contract, intentional misrepresentation, intentional concealment, negligent misrepresentation, and interference with contract; and by PBS against Nesmith and Pacific Arts for lost royalties. The lawsuits escalated in 1994 and 1995 into major litigation between the parties over these rights and payments. PBS and Nesmith and Pacific Arts vigorously prosecuted these multimillion-dollar counter-suits. The six plaintiffs included PBS, WGBH-TV, WNET, the Ken Burns-owned American Documentaries and Radio Pioneers Film Project and the Children's Television Workshop. They sought approximately $5 million in disputed royalties, advances, guarantees and license fees for programs and the use of the PBS logo from the defendants Pacific Arts and Nesmith. Due to the cost of the litigation, Pacific Arts was forced to cease distribution operations and suspended the use of the PBS logo on the Pacific Arts videos. Though Pacific Arts distribution system had ceased operating, the various plaintiffs were counting on capturing a personal financial guarantee Nesmith had made to PBS in the original PBS deal in 1990. The cases went to jury trial in Federal Court in Los Angeles in February 1999. After three days of deliberation, the jury unanimously sided with Nesmith. The court awarded Pacific Arts $14,625,000 for loss of its rights library, plus $29,250,000 in punitive damages. The jury awarded $3 million to Nesmith personally, including $2 million in punitive damages for a total award to Nesmith and Pacific Arts of $48,875,000. The jury resolved the outstanding license fee issues by ordering Pacific Arts and Nesmith to pay approximately $1.2 million to American Documentaries for The Civil War, about $230,000 to WGBH-TV, and $150,000 to WNET. Following the ruling, Nesmith expressed his personal disappointment with PBS and was quoted by BBC News as stating "It's like finding your grandmother stealing your stereo. You're happy to get your stereo back, but it's sad to find out your grandmother is a thief." The decision never went to an appeals court and the final amount paid to Pacific Arts and Nesmith was an undisclosed sum agreed to in an out-of-court settlement. == Warning, Alert and Response Network (WARN) == PBS provides an alternative path for Wireless Emergency Alerts to wireless carriers through its Warning, Alert and Response Network (WARN). The alerts are transmitted through the PBS satellite network on the AMC-21 satellite to PBS stations, who then broadcast the messages over their transmitters for reception by wireless carriers at their cell sites. The WARN network is funded by a grant through National Telecommunications and Information Administration (NTIA). == See also == American Public Media List of United States over-the-air television networks PBS America Public Radio International Public, educational, and government access (PEG) Television in the United States === Similar public broadcasting services === TVOntario, Knowledge Network China Education Television Arte France 5 ARD, ZDF Educational Broadcasting System == References == == Further reading == Bullert, B.J. (1997). Public Television: Politics and the Battle over Documentary Film. Rutgers University Press. ISBN 978-0-813-52470-2. Dornfeld, Barry (1998). Producing Public Television, Producing Public Culture. Princeton University Press. Engelman, Ralph (1996). Public Radio and Television in America: A Political History. Sage Publications. Ledbetter, James (1998). Made Possible by: The Death of Public Broadcasting in the United States. Verso. ISBN 978-1-859-84029-0. Pachelbel, Johann (1932). UPI Television Network logo. Art Scott. == External links == Official website PBS "Red Book" (presentation guidelines for PBS programming) Current, the newspaper about public TV and radio in the United States Designing Healthy Communities by PBS PBS Editorial Standards and Practices "Articles of Incorporation of Public Broadcasting Service". Current. American University School of Communication. November 3, 1969. Retrieved January 15, 2025.
https://en.wikipedia.org/wiki/PBS
Comment programming, also known as comment-driven development (CDD), is a (mostly) satirical software development technique that is heavily based on commenting out code. In comment programming, the comment tags are not used to describe what a certain piece of code is doing, but rather to stop some parts of the code from being executed. The aim is to have the commented code at the developer's disposal at any time it might be needed. This is especially useful when the requirements change rapidly. In this case, they happen to revert to older versions of themselves, thus making the programmer either write the code again, or revert parts of the code from the versioning repository, which would be more time-consuming. With comment programming, when such a request for reverting to an old implementation arises, the developer just comments out the current implementation and uncomments the previous. It is advisable to add short descriptive comments to blocks of commented code. == Practical uses == When it comes to a work environment, it isn't about who knows the most terms out of a textbook. Instead, we are faced with problems that we aren't sure how to solve. When someone else reads a users' program, it is important for them to understand how the problem was gone about and not just to see the answer. Even if someone decides to go into something other than computer programming, they will be well equipped with the habit of comments and showing others how they thought and solved specific problems. A related, but separate, more practical use of comments is for creating stubs with comments describing a feature (usually using special tags) ahead of future development of that feature. For example, this programming process can be used for prototyping a new design pattern. This is done by creating a new structure of classes or functions without any implementation and adding the implementation at a later date. Studies show that there are mainly two types of comments being used across programs. Preconditional and Postconditional are the two biggest ideas that computer programmers should use when developing projects. Preconditional comes before the function or method have been written. They are used to describe what each block of code is supposed to do. This can guide users in the right direction if someone is trying to debug or dissect code. Postconditional comments are used after the function or set of statements have been written. They are generally used to explain to the reader why they chose to go about the problem in that manner. Pseudocode Example: In the example, there is a structure around a click event handler. However, comment programming is used instead of a real implementation. The idea is that many functions can be written like this, and then the design can be reworked and revisited without having to refactor a lot of source code. == Popular culture == MSDN Sweden produced a video for April Fools' Day 2010, where they satirically presented CDD as if it were a serious methodology. MCT is a tool made for programmers in order to help relieve some of the complexity in computer code. Instead of normal comments, this tool allows the addition of videos, animations, images, and voiceovers. Users are able to download this software online and can add these tools by using the cursor to drag over the line or lines they want to explain. Users are also able to add audio or hand gestures as comments. This can help explain the reasoning behind functions and how a program executes. == References ==
https://en.wikipedia.org/wiki/Comment_programming
The Apollo program, also known as Project Apollo, was the United States human spaceflight program led by NASA, which successfully landed the first humans on the Moon in 1969. Apollo followed Project Mercury that put the first Americans in space. It was conceived in 1960 as a three-person spacecraft during President Dwight D. Eisenhower's administration. Apollo was later dedicated to President John F. Kennedy's national goal for the 1960s of "landing a man on the Moon and returning him safely to the Earth" in an address to Congress on May 25, 1961. It was the third American human spaceflight program to fly, preceded by Project Gemini conceived in 1961 to extend spaceflight capability in support of Apollo. Kennedy's goal was accomplished on the Apollo 11 mission when astronauts Neil Armstrong and Buzz Aldrin landed their Apollo Lunar Module (LM) on July 20, 1969, and walked on the lunar surface, while Michael Collins remained in lunar orbit in the command and service module (CSM), and all three landed safely on Earth in the Pacific Ocean on July 24. Five subsequent Apollo missions also landed astronauts on the Moon, the last, Apollo 17, in December 1972. In these six spaceflights, twelve people walked on the Moon. Apollo ran from 1961 to 1972, with the first crewed flight in 1968. It encountered a major setback in 1967 when an Apollo 1 cabin fire killed the entire crew during a prelaunch test. After the first successful landing, sufficient flight hardware remained for nine follow-on landings with a plan for extended lunar geological and astrophysical exploration. Budget cuts forced the cancellation of three of these. Five of the remaining six missions achieved successful landings, but the Apollo 13 landing had to be aborted after an oxygen tank exploded en route to the Moon, crippling the CSM. The crew barely managed a safe return to Earth by using the lunar module as a "lifeboat" on the return journey. Apollo used the Saturn family of rockets as launch vehicles, which were also used for an Apollo Applications Program, which consisted of Skylab, a space station that supported three crewed missions in 1973–1974, and the Apollo–Soyuz Test Project, a joint United States-Soviet Union low Earth orbit mission in 1975. Apollo set several major human spaceflight milestones. It stands alone in sending crewed missions beyond low Earth orbit. Apollo 8 was the first crewed spacecraft to orbit another celestial body, and Apollo 11 was the first crewed spacecraft to land humans on one. Overall, the Apollo program returned 842 pounds (382 kg) of lunar rocks and soil to Earth, greatly contributing to the understanding of the Moon's composition and geological history. The program laid the foundation for NASA's subsequent human spaceflight capability and funded construction of its Johnson Space Center and Kennedy Space Center. Apollo also spurred advances in many areas of technology incidental to rocketry and human spaceflight, including avionics, telecommunications, and computers. == Name == The program was named after Apollo, the Greek god of light, music, and the Sun, by NASA manager Abe Silverstein, who later said, "I was naming the spacecraft like I'd name my baby." Silverstein chose the name at home one evening, early in 1960, because he felt "Apollo riding his chariot across the Sun was appropriate to the grand scale of the proposed program". The context of this was that the program focused at its beginning mainly on developing an advanced crewed spacecraft, the Apollo command and service module, succeeding the Mercury program. A lunar landing became the focus of the program only in 1961. Thereafter Project Gemini instead followed the Mercury program to test and study advanced crewed spaceflight technology. == Background == === Origin and spacecraft feasibility studies === The Apollo program was conceived during the Eisenhower administration in early 1960, as a follow-up to Project Mercury. While the Mercury capsule could support only one astronaut on a limited Earth orbital mission, Apollo would carry three. Possible missions included ferrying crews to a space station, circumlunar flights, and eventual crewed lunar landings. In July 1960, NASA Deputy Administrator Hugh L. Dryden announced the Apollo program to industry representatives at a series of Space Task Group conferences. Preliminary specifications were laid out for a spacecraft with a mission module cabin separate from the command module (piloting and reentry cabin), and a propulsion and equipment module. On August 30, a feasibility study competition was announced, and on October 25, three study contracts were awarded to General Dynamics/Convair, General Electric, and the Glenn L. Martin Company. Meanwhile, NASA performed its own in-house spacecraft design studies led by Maxime Faget, to serve as a gauge to judge and monitor the three industry designs. === Political pressure builds === In November 1960, John F. Kennedy was elected president after a campaign that promised American superiority over the Soviet Union in the fields of space exploration and missile defense. Up to the election of 1960, Kennedy had been speaking out against the "missile gap" that he and many other senators said had developed between the Soviet Union and the United States due to the inaction of President Eisenhower. Beyond military power, Kennedy used aerospace technology as a symbol of national prestige, pledging to make the US not "first but, first and, first if, but first period". Despite Kennedy's rhetoric, he did not immediately come to a decision on the status of the Apollo program once he became president. He knew little about the technical details of the space program, and was put off by the massive financial commitment required by a crewed Moon landing. When Kennedy's newly appointed NASA Administrator James E. Webb requested a 30 percent budget increase for his agency, Kennedy supported an acceleration of NASA's large booster program but deferred a decision on the broader issue. On April 12, 1961, Soviet cosmonaut Yuri Gagarin became the first person to fly in space, reinforcing American fears about being left behind in a technological competition with the Soviet Union. At a meeting of the US House Committee on Science and Astronautics one day after Gagarin's flight, many congressmen pledged their support for a crash program aimed at ensuring that America would catch up. Kennedy was circumspect in his response to the news, refusing to make a commitment on America's response to the Soviets. On April 20, Kennedy sent a memo to Vice President Lyndon B. Johnson, asking Johnson to look into the status of America's space program, and into programs that could offer NASA the opportunity to catch up. Johnson responded approximately one week later, concluding that "we are neither making maximum effort nor achieving results necessary if this country is to reach a position of leadership." His memo concluded that a crewed Moon landing was far enough in the future that it was likely the United States would achieve it first. On May 25, 1961, twenty days after the first American crewed spaceflight Freedom 7, Kennedy proposed the crewed Moon landing in a Special Message to the Congress on Urgent National Needs: Now it is time to take longer strides—time for a great new American enterprise—time for this nation to take a clearly leading role in space achievement, which in many ways may hold the key to our future on Earth. ... I believe that this nation should commit itself to achieving the goal, before this decade is out, of landing a man on the Moon and returning him safely to the Earth. No single space project in this period will be more impressive to mankind, or more important in the long-range exploration of space; and none will be so difficult or expensive to accomplish. == NASA expansion == At the time of Kennedy's proposal, only one American had flown in space—less than a month earlier—and NASA had not yet sent an astronaut into orbit. Even some NASA employees doubted whether Kennedy's ambitious goal could be met. By 1963, Kennedy even came close to agreeing to a joint US-USSR Moon mission, to eliminate duplication of effort. With the clear goal of a crewed landing replacing the more nebulous goals of space stations and circumlunar flights, NASA decided that, in order to make progress quickly, it would discard the feasibility study designs of Convair, GE, and Martin, and proceed with Faget's command and service module design. The mission module was determined to be useful only as an extra room, and therefore unnecessary. They used Faget's design as the specification for another competition for spacecraft procurement bids in October 1961. On November 28, 1961, it was announced that North American Aviation had won the contract, although its bid was not rated as good as the Martin proposal. Webb, Dryden and Robert Seamans chose it in preference due to North American's longer association with NASA and its predecessor. Landing humans on the Moon by the end of 1969 required the most sudden burst of technological creativity, and the largest commitment of resources ($25 billion; $182 billion in 2023 US dollars) ever made by any nation in peacetime. At its peak, the Apollo program employed 400,000 people and required the support of over 20,000 industrial firms and universities. On July 1, 1960, NASA established the Marshall Space Flight Center (MSFC) in Huntsville, Alabama. MSFC designed the heavy lift-class Saturn launch vehicles, which would be required for Apollo. === Manned Spacecraft Center === It became clear that managing the Apollo program would exceed the capabilities of Robert R. Gilruth's Space Task Group, which had been directing the nation's crewed space program from NASA's Langley Research Center. So Gilruth was given authority to grow his organization into a new NASA center, the Manned Spacecraft Center (MSC). A site was chosen in Houston, Texas, on land donated by Rice University, and Administrator Webb announced the conversion on September 19, 1961. It was also clear NASA would soon outgrow its practice of controlling missions from its Cape Canaveral Air Force Station launch facilities in Florida, so a new Mission Control Center would be included in the MSC. In September 1962, by which time two Project Mercury astronauts had orbited the Earth, Gilruth had moved his organization to rented space in Houston, and construction of the MSC facility was under way, Kennedy visited Rice to reiterate his challenge in a famous speech: But why, some say, the Moon? Why choose this as our goal? And they may well ask, why climb the highest mountain? Why, 35 years ago, fly the Atlantic? ... We choose to go to the Moon. We choose to go to the Moon in this decade and do the other things, not because they are easy, but because they are hard; because that goal will serve to organize and measure the best of our energies and skills; because that challenge is one that we are willing to accept, one we are unwilling to postpone, and one we intend to win ... The MSC was completed in September 1963. It was renamed by the United States Congress in honor of Lyndon B. Johnson soon after his death in 1973. === Launch Operations Center === It also became clear that Apollo would outgrow the Canaveral launch facilities in Florida. The two newest launch complexes were already being built for the Saturn I and IB rockets at the northernmost end: LC-34 and LC-37. But an even bigger facility would be needed for the mammoth rocket required for the crewed lunar mission, so land acquisition was started in July 1961 for a Launch Operations Center (LOC) immediately north of Canaveral at Merritt Island. The design, development and construction of the center was conducted by Kurt H. Debus, a member of Wernher von Braun's original V-2 rocket engineering team. Debus was named the LOC's first Director. Construction began in November 1962. Following Kennedy's death, President Johnson issued an executive order on November 29, 1963, to rename the LOC and Cape Canaveral in honor of Kennedy. The LOC included Launch Complex 39, a Launch Control Center, and a 130-million-cubic-foot (3,700,000 m3) Vertical Assembly Building (VAB). in which the space vehicle (launch vehicle and spacecraft) would be assembled on a mobile launcher platform and then moved by a crawler-transporter to one of several launch pads. Although at least three pads were planned, only two, designated A and B, were completed in October 1965. The LOC also included an Operations and Checkout Building (OCB) to which Gemini and Apollo spacecraft were initially received prior to being mated to their launch vehicles. The Apollo spacecraft could be tested in two vacuum chambers capable of simulating atmospheric pressure at altitudes up to 250,000 feet (76 km), which is nearly a vacuum. === Organization === Administrator Webb realized that in order to keep Apollo costs under control, he had to develop greater project management skills in his organization, so he recruited George E. Mueller for a high management job. Mueller accepted, on the condition that he have a say in NASA reorganization necessary to effectively administer Apollo. Webb then worked with Associate Administrator (later Deputy Administrator) Seamans to reorganize the Office of Manned Space Flight (OMSF). On July 23, 1963, Webb announced Mueller's appointment as Deputy Associate Administrator for Manned Space Flight, to replace then Associate Administrator D. Brainerd Holmes on his retirement effective September 1. Under Webb's reorganization, the directors of the Manned Spacecraft Center (Gilruth), Marshall Space Flight Center (von Braun), and the Launch Operations Center (Debus) reported to Mueller. Based on his industry experience on Air Force missile projects, Mueller realized some skilled managers could be found among high-ranking officers in the U.S. Air Force, so he got Webb's permission to recruit General Samuel C. Phillips, who gained a reputation for his effective management of the Minuteman program, as OMSF program controller. Phillips's superior officer Bernard A. Schriever agreed to loan Phillips to NASA, along with a staff of officers under him, on the condition that Phillips be made Apollo Program Director. Mueller agreed, and Phillips managed Apollo from January 1964, until it achieved the first human landing in July 1969, after which he returned to Air Force duty. Charles Fishman, in One Giant Leap, estimated the number of people and organizations involved into the Apollo program as "410,000 men and women at some 20,000 different companies contributed to the effort". == Choosing a mission mode == Once Kennedy had defined a goal, the Apollo mission planners were faced with the challenge of designing a spacecraft that could meet it while minimizing risk to human life, limiting cost, and not exceeding limits in possible technology and astronaut skill. Four possible mission modes were considered: Direct Ascent: The spacecraft would be launched as a unit and travel directly to the lunar surface, without first going into lunar orbit. A 50,000-pound (23,000 kg) Earth return ship would land all three astronauts atop a 113,000-pound (51,000 kg) descent propulsion stage, which would be left on the Moon. This design would have required development of the extremely powerful Saturn C-8 or Nova launch vehicle to carry a 163,000-pound (74,000 kg) payload to the Moon. Earth Orbit Rendezvous (EOR): Multiple rocket launches (up to 15 in some plans) would carry parts of the Direct Ascent spacecraft and propulsion units for translunar injection (TLI). These would be assembled into a single spacecraft in Earth orbit. Lunar Surface Rendezvous: Two spacecraft would be launched in succession. The first, an automated vehicle carrying propellant for the return to Earth, would land on the Moon, to be followed some time later by the crewed vehicle. Propellant would have to be transferred from the automated vehicle to the crewed vehicle. Lunar Orbit Rendezvous (LOR): This turned out to be the winning configuration, which achieved the goal with Apollo 11 on July 20, 1969: a single Saturn V launched a 96,886-pound (43,947 kg) spacecraft that was composed of a 63,608-pound (28,852 kg) Apollo command and service module which remained in orbit around the Moon and a 33,278-pound (15,095 kg) two-stage Apollo Lunar Module spacecraft which was flown by two astronauts to the surface, flown back to dock with the command module and was then discarded. Landing the smaller spacecraft on the Moon, and returning an even smaller part (10,042 pounds or 4,555 kilograms) to lunar orbit, minimized the total mass to be launched from Earth, but this was the last method initially considered because of the perceived risk of rendezvous and docking. In early 1961, direct ascent was generally the mission mode in favor at NASA. Many engineers feared that rendezvous and docking, maneuvers that had not been attempted in Earth orbit, would be nearly impossible in lunar orbit. LOR advocates including John Houbolt at Langley Research Center emphasized the important weight reductions that were offered by the LOR approach. Throughout 1960 and 1961, Houbolt campaigned for the recognition of LOR as a viable and practical option. Bypassing the NASA hierarchy, he sent a series of memos and reports on the issue to Associate Administrator Robert Seamans; while acknowledging that he spoke "somewhat as a voice in the wilderness", Houbolt pleaded that LOR should not be discounted in studies of the question. Seamans's establishment of an ad hoc committee headed by his special technical assistant Nicholas E. Golovin in July 1961, to recommend a launch vehicle to be used in the Apollo program, represented a turning point in NASA's mission mode decision. This committee recognized that the chosen mode was an important part of the launch vehicle choice, and recommended in favor of a hybrid EOR-LOR mode. Its consideration of LOR—as well as Houbolt's ceaseless work—played an important role in publicizing the workability of the approach. In late 1961 and early 1962, members of the Manned Spacecraft Center began to come around to support LOR, including the newly hired deputy director of the Office of Manned Space Flight, Joseph Shea, who became a champion of LOR. The engineers at Marshall Space Flight Center (MSFC), who were heavily invested in direct ascent, took longer to become convinced of its merits, but their conversion was announced by Wernher von Braun at a briefing on June 7, 1962. But even after NASA reached internal agreement, it was far from smooth sailing. Kennedy's science advisor Jerome Wiesner, who had expressed his opposition to human spaceflight to Kennedy before the President took office, and had opposed the decision to land people on the Moon, hired Golovin, who had left NASA, to chair his own "Space Vehicle Panel", ostensibly to monitor, but actually to second-guess NASA's decisions on the Saturn V launch vehicle and LOR by forcing Shea, Seamans, and even Webb to defend themselves, delaying its formal announcement to the press on July 11, 1962, and forcing Webb to still hedge the decision as "tentative". Wiesner kept up the pressure, even making the disagreement public during a two-day September visit by the President to Marshall Space Flight Center. Wiesner blurted out "No, that's no good" in front of the press, during a presentation by von Braun. Webb jumped in and defended von Braun, until Kennedy ended the squabble by stating that the matter was "still subject to final review". Webb held firm and issued a request for proposal to candidate Lunar Excursion Module (LEM) contractors. Wiesner finally relented, unwilling to settle the dispute once and for all in Kennedy's office, because of the President's involvement with the October Cuban Missile Crisis, and fear of Kennedy's support for Webb. NASA announced the selection of Grumman as the LEM contractor in November 1962. Space historian James Hansen concludes that: Without NASA's adoption of this stubbornly held minority opinion in 1962, the United States may still have reached the Moon, but almost certainly it would not have been accomplished by the end of the 1960s, President Kennedy's target date. The LOR method had the advantage of allowing the lander spacecraft to be used as a "lifeboat" in the event of a failure of the command ship. Some documents prove this theory was discussed before and after the method was chosen. In 1964 an MSC study concluded, "The LM [as lifeboat] ... was finally dropped, because no single reasonable CSM failure could be identified that would prohibit use of the SPS." Ironically, just such a failure happened on Apollo 13 when an oxygen tank explosion left the CSM without electrical power. The lunar module provided propulsion, electrical power and life support to get the crew home safely. == Spacecraft == Faget's preliminary Apollo design employed a cone-shaped command module, supported by one of several service modules providing propulsion and electrical power, sized appropriately for the space station, cislunar, and lunar landing missions. Once Kennedy's Moon landing goal became official, detailed design began of a command and service module (CSM) in which the crew would spend the entire direct-ascent mission and lift off from the lunar surface for the return trip, after being soft-landed by a larger landing propulsion module. The final choice of lunar orbit rendezvous changed the CSM's role to the translunar ferry used to transport the crew, along with a new spacecraft, the Lunar Excursion Module (LEM, later shortened to LM (Lunar Module) but still pronounced ) which would take two individuals to the lunar surface and return them to the CSM. === Command and service module === The command module (CM) was the conical crew cabin, designed to carry three astronauts from launch to lunar orbit and back to an Earth ocean landing. It was the only component of the Apollo spacecraft to survive without major configuration changes as the program evolved from the early Apollo study designs. Its exterior was covered with an ablative heat shield, and had its own reaction control system (RCS) engines to control its attitude and steer its atmospheric entry path. Parachutes were carried to slow its descent to splashdown. The module was 11.42 feet (3.48 m) tall, 12.83 feet (3.91 m) in diameter, and weighed approximately 12,250 pounds (5,560 kg). A cylindrical service module (SM) supported the command module, with a service propulsion engine and an RCS with propellants, and a fuel cell power generation system with liquid hydrogen and liquid oxygen reactants. A high-gain S-band antenna was used for long-distance communications on the lunar flights. On the extended lunar missions, an orbital scientific instrument package was carried. The service module was discarded just before reentry. The module was 24.6 feet (7.5 m) long and 12.83 feet (3.91 m) in diameter. The initial lunar flight version weighed approximately 51,300 pounds (23,300 kg) fully fueled, while a later version designed to carry a lunar orbit scientific instrument package weighed just over 54,000 pounds (24,000 kg). North American Aviation won the contract to build the CSM, and also the second stage of the Saturn V launch vehicle for NASA. Because the CSM design was started early before the selection of lunar orbit rendezvous, the service propulsion engine was sized to lift the CSM off the Moon, and thus was oversized to about twice the thrust required for translunar flight. Also, there was no provision for docking with the lunar module. A 1964 program definition study concluded that the initial design should be continued as Block I which would be used for early testing, while Block II, the actual lunar spacecraft, would incorporate the docking equipment and take advantage of the lessons learned in Block I development. === Apollo Lunar Module === The Apollo Lunar Module (LM) was designed to descend from lunar orbit to land two astronauts on the Moon and take them back to orbit to rendezvous with the command module. Not designed to fly through the Earth's atmosphere or return to Earth, its fuselage was designed totally without aerodynamic considerations and was of an extremely lightweight construction. It consisted of separate descent and ascent stages, each with its own engine. The descent stage contained storage for the descent propellant, surface stay consumables, and surface exploration equipment. The ascent stage contained the crew cabin, ascent propellant, and a reaction control system. The initial LM model weighed approximately 33,300 pounds (15,100 kg), and allowed surface stays up to around 34 hours. An extended lunar module (ELM) weighed over 36,200 pounds (16,400 kg), and allowed surface stays of more than three days. The contract for design and construction of the lunar module was awarded to Grumman Aircraft Engineering Corporation, and the project was overseen by Thomas J. Kelly. == Launch vehicles == Before the Apollo program began, Wernher von Braun and his team of rocket engineers had started work on plans for very large launch vehicles, the Saturn series, and the even larger Nova series. In the midst of these plans, von Braun was transferred from the Army to NASA and was made Director of the Marshall Space Flight Center. The initial direct ascent plan to send the three-person Apollo command and service module directly to the lunar surface, on top of a large descent rocket stage, would require a Nova-class launcher, with a lunar payload capability of over 180,000 pounds (82,000 kg). The June 11, 1962, decision to use lunar orbit rendezvous enabled the Saturn V to replace the Nova, and the MSFC proceeded to develop the Saturn rocket family for Apollo. Since Apollo, like Mercury, used more than one launch vehicle for space missions, NASA used spacecraft-launch vehicle combination series numbers: AS-10x for Saturn I, AS-20x for Saturn IB, and AS-50x for Saturn V (compare Mercury-Redstone 3, Mercury-Atlas 6) to designate and plan all missions, rather than numbering them sequentially as in Project Gemini. This was changed by the time human flights began. === Little Joe II === Since Apollo, like Mercury, would require a launch escape system (LES) in case of a launch failure, a relatively small rocket was required for qualification flight testing of this system. A rocket bigger than the Little Joe used by Mercury would be required, so the Little Joe II was built by General Dynamics/Convair. After an August 1963 qualification test flight, four LES test flights (A-001 through 004) were made at the White Sands Missile Range between May 1964 and January 1966. === Saturn I === Saturn I, the first US heavy lift launch vehicle, was initially planned to launch partially equipped CSMs in low Earth orbit tests. The S-I first stage burned RP-1 with liquid oxygen (LOX) oxidizer in eight clustered Rocketdyne H-1 engines, to produce 1,500,000 pounds-force (6,670 kN) of thrust. The S-IV second stage used six liquid hydrogen-fueled Pratt & Whitney RL-10 engines with 90,000 pounds-force (400 kN) of thrust. The S-V third stage flew inactively on Saturn I four times. The first four Saturn I test flights were launched from LC-34, with only the first stage live, carrying dummy upper stages filled with water. The first flight with a live S-IV was launched from LC-37. This was followed by five launches of boilerplate CSMs (designated AS-101 through AS-105) into orbit in 1964 and 1965. The last three of these further supported the Apollo program by also carrying Pegasus satellites, which verified the safety of the translunar environment by measuring the frequency and severity of micrometeorite impacts. In September 1962, NASA planned to launch four crewed CSM flights on the Saturn I from late 1965 through 1966, concurrent with Project Gemini. The 22,500-pound (10,200 kg) payload capacity would have severely limited the systems which could be included, so the decision was made in October 1963 to use the uprated Saturn IB for all crewed Earth orbital flights. === Saturn IB === The Saturn IB was an upgraded version of the Saturn I. The S-IB first stage increased the thrust to 1,600,000 pounds-force (7,120 kN) by uprating the H-1 engine. The second stage replaced the S-IV with the S-IVB-200, powered by a single J-2 engine burning liquid hydrogen fuel with LOX, to produce 200,000 pounds-force (890 kN) of thrust. A restartable version of the S-IVB was used as the third stage of the Saturn V. The Saturn IB could send over 40,000 pounds (18,100 kg) into low Earth orbit, sufficient for a partially fueled CSM or the LM. Saturn IB launch vehicles and flights were designated with an AS-200 series number, "AS" indicating "Apollo Saturn" and the "2" indicating the second member of the Saturn rocket family. === Saturn V === Saturn V launch vehicles and flights were designated with an AS-500 series number, "AS" indicating "Apollo Saturn" and the "5" indicating Saturn V. The three-stage Saturn V was designed to send a fully fueled CSM and LM to the Moon. It was 33 feet (10.1 m) in diameter and stood 363 feet (110.6 m) tall with its 96,800-pound (43,900 kg) lunar payload. Its capability grew to 103,600 pounds (47,000 kg) for the later advanced lunar landings. The S-IC first stage burned RP-1/LOX for a rated thrust of 7,500,000 pounds-force (33,400 kN), which was upgraded to 7,610,000 pounds-force (33,900 kN). The second and third stages burned liquid hydrogen; the third stage was a modified version of the S-IVB, with thrust increased to 230,000 pounds-force (1,020 kN) and capability to restart the engine for translunar injection after reaching a parking orbit. == Astronauts == NASA's director of flight crew operations during the Apollo program was Donald K. "Deke" Slayton, one of the original Mercury Seven astronauts who was medically grounded in September 1962 due to a heart murmur. Slayton was responsible for making all Gemini and Apollo crew assignments. Thirty-two astronauts were assigned to fly missions in the Apollo program. Twenty-four of these left Earth's orbit and flew around the Moon between December 1968 and December 1972 (three of them twice). Half of the 24 walked on the Moon's surface, though none of them returned to it after landing once. One of the moonwalkers was a trained geologist. Of the 32, Gus Grissom, Ed White, and Roger Chaffee were killed during a ground test in preparation for the Apollo 1 mission. The Apollo astronauts were chosen from the Project Mercury and Gemini veterans, plus from two later astronaut groups. All missions were commanded by Gemini or Mercury veterans. Crews on all development flights (except the Earth orbit CSM development flights) through the first two landings on Apollo 11 and Apollo 12, included at least two (sometimes three) Gemini veterans. Harrison Schmitt, a geologist, was the first NASA scientist astronaut to fly in space, and landed on the Moon on the last mission, Apollo 17. Schmitt participated in the lunar geology training of all of the Apollo landing crews. NASA awarded all 32 of these astronauts its highest honor, the Distinguished Service Medal, given for "distinguished service, ability, or courage", and personal "contribution representing substantial progress to the NASA mission". The medals were awarded posthumously to Grissom, White, and Chaffee in 1969, then to the crews of all missions from Apollo 8 onward. The crew that flew the first Earth orbital test mission Apollo 7, Walter M. Schirra, Donn Eisele, and Walter Cunningham, were awarded the lesser NASA Exceptional Service Medal, because of discipline problems with the flight director's orders during their flight. In October 2008, the NASA Administrator decided to award them the Distinguished Service Medals. For Schirra and Eisele, this was posthumously. == Lunar mission profile == The first lunar landing mission was planned to proceed: === Profile variations === The first three lunar missions (Apollo 8, Apollo 10, and Apollo 11) used a free return trajectory, keeping a flight path coplanar with the lunar orbit, which would allow a return to Earth in case the SM engine failed to make lunar orbit insertion. Landing site lighting conditions on later missions dictated a lunar orbital plane change, which required a course change maneuver soon after TLI, and eliminated the free-return option. After Apollo 12 placed the second of several seismometers on the Moon, the jettisoned LM ascent stages on Apollo 12 and later missions were deliberately crashed on the Moon at known locations to induce vibrations in the Moon's structure. The only exceptions to this were the Apollo 13 LM which burned up in the Earth's atmosphere, and Apollo 16, where a loss of attitude control after jettison prevented making a targeted impact. As another active seismic experiment, the S-IVBs on Apollo 13 and subsequent missions were deliberately crashed on the Moon instead of being sent to solar orbit. Starting with Apollo 13, descent orbit insertion was to be performed using the service module engine instead of the LM engine, in order to allow a greater fuel reserve for landing. This was actually done for the first time on Apollo 14, since the Apollo 13 mission was aborted before landing. == Development history == === Uncrewed flight tests === Two Block I CSMs were launched from LC-34 on suborbital flights in 1966 with the Saturn IB. The first, AS-201 launched on February 26, reached an altitude of 265.7 nautical miles (492.1 km) and splashed down 4,577 nautical miles (8,477 km) downrange in the Atlantic Ocean. The second, AS-202 on August 25, reached 617.1 nautical miles (1,142.9 km) altitude and was recovered 13,900 nautical miles (25,700 km) downrange in the Pacific Ocean. These flights validated the service module engine and the command module heat shield. A third Saturn IB test, AS-203 launched from pad 37, went into orbit to support design of the S-IVB upper stage restart capability needed for the Saturn V. It carried a nose cone instead of the Apollo spacecraft, and its payload was the unburned liquid hydrogen fuel, the behavior of which engineers measured with temperature and pressure sensors, and a TV camera. This flight occurred on July 5, before AS-202, which was delayed because of problems getting the Apollo spacecraft ready for flight. === Preparation for crewed flight === Two crewed orbital Block I CSM missions were planned: AS-204 and AS-205. The Block I crew positions were titled Command Pilot, Senior Pilot, and Pilot. The Senior Pilot would assume navigation duties, while the Pilot would function as a systems engineer. The astronauts would wear a modified version of the Gemini spacesuit. After an uncrewed LM test flight AS-206, a crew would fly the first Block II CSM and LM in a dual mission known as AS-207/208, or AS-278 (each spacecraft would be launched on a separate Saturn IB). The Block II crew positions were titled Commander, Command Module Pilot, and Lunar Module Pilot. The astronauts would begin wearing a new Apollo A6L spacesuit, designed to accommodate lunar extravehicular activity (EVA). The traditional visor helmet was replaced with a clear "fishbowl" type for greater visibility, and the lunar surface EVA suit would include a water-cooled undergarment. Deke Slayton, the grounded Mercury astronaut who became director of flight crew operations for the Gemini and Apollo programs, selected the first Apollo crew in January 1966, with Grissom as Command Pilot, White as Senior Pilot, and rookie Donn F. Eisele as Pilot. But Eisele dislocated his shoulder twice aboard the KC135 weightlessness training aircraft, and had to undergo surgery on January 27. Slayton replaced him with Chaffee. NASA announced the final crew selection for AS-204 on March 21, 1966, with the backup crew consisting of Gemini veterans James McDivitt and David Scott, with rookie Russell L. "Rusty" Schweickart. Mercury/Gemini veteran Wally Schirra, Eisele, and rookie Walter Cunningham were announced on September 29 as the prime crew for AS-205. In December 1966, the AS-205 mission was canceled, since the validation of the CSM would be accomplished on the 14-day first flight, and AS-205 would have been devoted to space experiments and contribute no new engineering knowledge about the spacecraft. Its Saturn IB was allocated to the dual mission, now redesignated AS-205/208 or AS-258, planned for August 1967. McDivitt, Scott and Schweickart were promoted to the prime AS-258 crew, and Schirra, Eisele and Cunningham were reassigned as the Apollo 1 backup crew. ==== Program delays ==== The spacecraft for the AS-202 and AS-204 missions were delivered by North American Aviation to the Kennedy Space Center with long lists of equipment problems which had to be corrected before flight; these delays caused the launch of AS-202 to slip behind AS-203, and eliminated hopes the first crewed mission might be ready to launch as soon as November 1966, concurrently with the last Gemini mission. Eventually, the planned AS-204 flight date was pushed to February 21, 1967. North American Aviation was prime contractor not only for the Apollo CSM, but for the Saturn V S-II second stage as well, and delays in this stage pushed the first uncrewed Saturn V flight AS-501 from late 1966 to November 1967. (The initial assembly of AS-501 had to use a dummy spacer spool in place of the stage.) The problems with North American were severe enough in late 1965 to cause Manned Space Flight Administrator George Mueller to appoint program director Samuel Phillips to head a "tiger team" to investigate North American's problems and identify corrections. Phillips documented his findings in a December 19 letter to NAA president Lee Atwood, with a strongly worded letter by Mueller, and also gave a presentation of the results to Mueller and Deputy Administrator Robert Seamans. Meanwhile, Grumman was also encountering problems with the Lunar Module, eliminating hopes it would be ready for crewed flight in 1967, not long after the first crewed CSM flights. ==== Apollo 1 fire ==== Grissom, White, and Chaffee decided to name their flight Apollo 1 as a motivational focus on the first crewed flight. They trained and conducted tests of their spacecraft at North American, and in the altitude chamber at the Kennedy Space Center. A "plugs-out" test was planned for January, which would simulate a launch countdown on LC-34 with the spacecraft transferring from pad-supplied to internal power. If successful, this would be followed by a more rigorous countdown simulation test closer to the February 21 launch, with both spacecraft and launch vehicle fueled. The plugs-out test began on the morning of January 27, 1967, and immediately was plagued with problems. First, the crew noticed a strange odor in their spacesuits which delayed the sealing of the hatch. Then, communications problems frustrated the astronauts and forced a hold in the simulated countdown. During this hold, an electrical fire began in the cabin and spread quickly in the high pressure, 100% oxygen atmosphere. Pressure rose high enough from the fire that the cabin inner wall burst, allowing the fire to erupt onto the pad area and frustrating attempts to rescue the crew. The astronauts were asphyxiated before the hatch could be opened. NASA immediately convened an accident review board, overseen by both houses of Congress. While the determination of responsibility for the accident was complex, the review board concluded that "deficiencies existed in command module design, workmanship and quality control". At the insistence of NASA Administrator Webb, North American removed Harrison Storms as command module program manager. Webb also reassigned Apollo Spacecraft Program Office (ASPO) Manager Joseph Francis Shea, replacing him with George Low. To remedy the causes of the fire, changes were made in the Block II spacecraft and operational procedures, the most important of which were use of a nitrogen/oxygen mixture instead of pure oxygen before and during launch, and removal of flammable cabin and space suit materials. The Block II design already called for replacement of the Block I plug-type hatch cover with a quick-release, outward opening door. NASA discontinued the crewed Block I program, using the Block I spacecraft only for uncrewed Saturn V flights. Crew members would also exclusively wear modified, fire-resistant A7L Block II space suits, and would be designated by the Block II titles, regardless of whether a LM was present on the flight or not. ==== Uncrewed Saturn V and LM tests ==== On April 24, 1967, Mueller published an official Apollo mission numbering scheme, using sequential numbers for all flights, crewed or uncrewed. The sequence would start with Apollo 4 to cover the first three uncrewed flights while retiring the Apollo 1 designation to honor the crew, per their widows' wishes. In September 1967, Mueller approved a sequence of mission types which had to be successfully accomplished in order to achieve the crewed lunar landing. Each step had to be successfully accomplished before the next ones could be performed, and it was unknown how many tries of each mission would be necessary; therefore letters were used instead of numbers. The A missions were uncrewed Saturn V validation; B was uncrewed LM validation using the Saturn IB; C was crewed CSM Earth orbit validation using the Saturn IB; D was the first crewed CSM/LM flight (this replaced AS-258, using a single Saturn V launch); E would be a higher Earth orbit CSM/LM flight; F would be the first lunar mission, testing the LM in lunar orbit but without landing (a "dress rehearsal"); and G would be the first crewed landing. The list of types covered follow-on lunar exploration to include H lunar landings, I for lunar orbital survey missions, and J for extended-stay lunar landings. The delay in the CSM caused by the fire enabled NASA to catch up on human-rating the LM and Saturn V. Apollo 4 (AS-501) was the first uncrewed flight of the Saturn V, carrying a Block I CSM on November 9, 1967. The capability of the command module's heat shield to survive a trans-lunar reentry was demonstrated by using the service module engine to ram it into the atmosphere at higher than the usual Earth-orbital reentry speed. Apollo 5 (AS-204) was the first uncrewed test flight of the LM in Earth orbit, launched from pad 37 on January 22, 1968, by the Saturn IB that would have been used for Apollo 1. The LM engines were successfully test-fired and restarted, despite a computer programming error which cut short the first descent stage firing. The ascent engine was fired in abort mode, known as a "fire-in-the-hole" test, where it was lit simultaneously with jettison of the descent stage. Although Grumman wanted a second uncrewed test, George Low decided the next LM flight would be crewed. This was followed on April 4, 1968, by Apollo 6 (AS-502) which carried a CSM and a LM Test Article as ballast. The intent of this mission was to achieve trans-lunar injection, followed closely by a simulated direct-return abort, using the service module engine to achieve another high-speed reentry. The Saturn V experienced pogo oscillation, a problem caused by non-steady engine combustion, which damaged fuel lines in the second and third stages. Two S-II engines shut down prematurely, but the remaining engines were able to compensate. The damage to the third stage engine was more severe, preventing it from restarting for trans-lunar injection. Mission controllers were able to use the service module engine to essentially repeat the flight profile of Apollo 4. Based on the good performance of Apollo 6 and identification of satisfactory fixes to the Apollo 6 problems, NASA declared the Saturn V ready to fly crew, canceling a third uncrewed test. === Crewed development missions === Apollo 7, launched from LC-34 on October 11, 1968, was the C mission, crewed by Schirra, Eisele, and Cunningham. It was an 11-day Earth-orbital flight which tested the CSM systems. Apollo 8 was planned to be the D mission in December 1968, crewed by McDivitt, Scott and Schweickart, launched on a Saturn V instead of two Saturn IBs. In the summer it had become clear that the LM would not be ready in time. Rather than waste the Saturn V on another simple Earth-orbiting mission, ASPO Manager George Low suggested the bold step of sending Apollo 8 to orbit the Moon instead, deferring the D mission to the next mission in March 1969, and eliminating the E mission. This would keep the program on track. The Soviet Union had sent two tortoises, mealworms, wine flies, and other lifeforms around the Moon on September 15, 1968, aboard Zond 5, and it was believed they might soon repeat the feat with human cosmonauts. The decision was not announced publicly until successful completion of Apollo 7. Gemini veterans Frank Borman and Jim Lovell, and rookie William Anders captured the world's attention by making ten lunar orbits in 20 hours, transmitting television pictures of the lunar surface on Christmas Eve, and returning safely to Earth. The following March, LM flight, rendezvous and docking were successfully demonstrated in Earth orbit on Apollo 9, and Schweickart tested the full lunar EVA suit with its portable life support system (PLSS) outside the LM. The F mission was successfully carried out on Apollo 10 in May 1969 by Gemini veterans Thomas P. Stafford, John Young and Eugene Cernan. Stafford and Cernan took the LM to within 50,000 feet (15 km) of the lunar surface. The G mission was achieved on Apollo 11 in July 1969 by an all-Gemini veteran crew consisting of Neil Armstrong, Michael Collins and Buzz Aldrin. Armstrong and Aldrin performed the first landing at the Sea of Tranquility at 20:17:40 UTC on July 20, 1969. They spent a total of 21 hours, 36 minutes on the surface, and spent 2 hours, 31 minutes outside the spacecraft, walking on the surface, taking photographs, collecting material samples, and deploying automated scientific instruments, while continuously sending black-and-white television back to Earth. The astronauts returned safely on July 24. That's one small step for [a] man, one giant leap for mankind. === Production lunar landings === In November 1969, Charles "Pete" Conrad became the third person to step onto the Moon, which he did while speaking more informally than had Armstrong: Whoopee! Man, that may have been a small one for Neil, but that's a long one for me. Conrad and rookie Alan L. Bean made a precision landing of Apollo 12 within walking distance of the Surveyor 3 uncrewed lunar probe, which had landed in April 1967 on the Ocean of Storms. The command module pilot was Gemini veteran Richard F. Gordon Jr. Conrad and Bean carried the first lunar surface color television camera, but it was damaged when accidentally pointed into the Sun. They made two EVAs totaling 7 hours and 45 minutes. On one, they walked to the Surveyor, photographed it, and removed some parts which they returned to Earth. The contracted batch of 15 Saturn Vs was enough for lunar landing missions through Apollo 20. Shortly after Apollo 11, NASA publicized a preliminary list of eight more planned landing sites after Apollo 12, with plans to increase the mass of the CSM and LM for the last five missions, along with the payload capacity of the Saturn V. These final missions would combine the I and J types in the 1967 list, allowing the CMP to operate a package of lunar orbital sensors and cameras while his companions were on the surface, and allowing them to stay on the Moon for over three days. These missions would also carry the Lunar Roving Vehicle (LRV) increasing the exploration area and allowing televised liftoff of the LM. Also, the Block II spacesuit was revised for the extended missions to allow greater flexibility and visibility for driving the LRV. The success of the first two landings allowed the remaining missions to be crewed with a single veteran as commander, with two rookies. Apollo 13 launched Lovell, Jack Swigert, and Fred Haise in April 1970, headed for the Fra Mauro formation. But two days out, a liquid oxygen tank exploded, disabling the service module and forcing the crew to use the LM as a "lifeboat" to return to Earth. Another NASA review board was convened to determine the cause, which turned out to be a combination of damage of the tank in the factory, and a subcontractor not making a tank component according to updated design specifications. Apollo was grounded again, for the remainder of 1970 while the oxygen tank was redesigned and an extra one was added. ==== Mission cutbacks ==== About the time of the first landing in 1969, it was decided to use an existing Saturn V to launch the Skylab orbital laboratory pre-built on the ground, replacing the original plan to construct it in orbit from several Saturn IB launches; this eliminated Apollo 20. NASA's yearly budget also began to shrink in light of the successful landing, and NASA also had to make funds available for the development of the upcoming Space Shuttle. By 1971, the decision was made to also cancel missions 18 and 19. The two unused Saturn Vs became museum exhibits at the John F. Kennedy Space Center on Merritt Island, Florida, George C. Marshall Space Center in Huntsville, Alabama, Michoud Assembly Facility in New Orleans, Louisiana, and Lyndon B. Johnson Space Center in Houston, Texas. The cutbacks forced mission planners to reassess the original planned landing sites in order to achieve the most effective geological sample and data collection from the remaining four missions. Apollo 15 had been planned to be the last of the H series missions, but since there would be only two subsequent missions left, it was changed to the first of three J missions. Apollo 13's Fra Mauro mission was reassigned to Apollo 14, commanded in February 1971 by Mercury veteran Alan Shepard, with Stuart Roosa and Edgar Mitchell. This time the mission was successful. Shepard and Mitchell spent 33 hours and 31 minutes on the surface, and completed two EVAs totalling 9 hours 24 minutes, which was a record for the longest EVA by a lunar crew at the time. In August 1971, just after conclusion of the Apollo 15 mission, President Richard Nixon proposed canceling the two remaining lunar landing missions, Apollo 16 and 17. Office of Management and Budget Deputy Director Caspar Weinberger was opposed to this, and persuaded Nixon to keep the remaining missions. ==== Extended missions ==== Apollo 15 was launched on July 26, 1971, with David Scott, Alfred Worden and James Irwin. Scott and Irwin landed on July 30 near Hadley Rille, and spent just under two days, 19 hours on the surface. In over 18 hours of EVA, they collected about 77 kilograms (170 lb) of lunar material. Apollo 16 landed in the Descartes Highlands on April 20, 1972. The crew was commanded by John Young, with Ken Mattingly and Charles Duke. Young and Duke spent just under three days on the surface, with a total of over 20 hours EVA. Apollo 17 was the last of the Apollo program, landing in the Taurus–Littrow region in December 1972. Eugene Cernan commanded Ronald E. Evans and NASA's first scientist-astronaut, geologist Harrison H. Schmitt. Schmitt was originally scheduled for Apollo 18, but the lunar geological community lobbied for his inclusion on the final lunar landing. Cernan and Schmitt stayed on the surface for just over three days and spent just over 23 hours of total EVA. ==== Canceled missions ==== Several missions were planned for but were canceled before details were finalized. == Mission summary == Source: Apollo by the Numbers: A Statistical Reference (Orloff 2004). == Samples returned == The Apollo program returned over 382 kg (842 lb) of lunar rocks and soil to the Lunar Receiving Laboratory in Houston. Today, 75% of the samples are stored at the Lunar Sample Laboratory Facility built in 1979. The rocks collected from the Moon are extremely old compared to rocks found on Earth, as measured by radiometric dating techniques. They range in age from about 3.2 billion years for the basaltic samples derived from the lunar maria, to about 4.6 billion years for samples derived from the highlands crust. As such, they represent samples from a very early period in the development of the Solar System, that are largely absent on Earth. One important rock found during the Apollo Program is dubbed the Genesis Rock, retrieved by astronauts David Scott and James Irwin during the Apollo 15 mission. This anorthosite rock is composed almost exclusively of the calcium-rich feldspar mineral anorthite, and is believed to be representative of the highland crust. A geochemical component called KREEP was discovered by Apollo 12, which has no known terrestrial counterpart. KREEP and the anorthositic samples have been used to infer that the outer portion of the Moon was once completely molten (see lunar magma ocean). Almost all the rocks show evidence of impact process effects. Many samples appear to be pitted with micrometeoroid impact craters, which is never seen on Earth rocks, due to the thick atmosphere. Many show signs of being subjected to high-pressure shock waves that are generated during impact events. Some of the returned samples are of impact melt (materials melted near an impact crater.) All samples returned from the Moon are highly brecciated as a result of being subjected to multiple impact events. From analyses of the composition of the returned lunar samples, it is now believed that the Moon was created through the impact of a large astronomical body with Earth. == Costs == Apollo cost $25.4 billion or approximately $257 billion (2023) using improved cost analysis. Of this amount, $20.2 billion ($145 billion adjusted) was spent on the design, development, and production of the Saturn family of launch vehicles, the Apollo spacecraft, spacesuits, scientific experiments, and mission operations. The cost of constructing and operating Apollo-related ground facilities, such as the NASA human spaceflight centers and the global tracking and data acquisition network, added an additional $5.2 billion ($37.3 billion adjusted). The amount grows to $28 billion ($280 billion adjusted) if the costs for related projects such as Project Gemini and the robotic Ranger, Surveyor, and Lunar Orbiter programs are included. NASA's official cost breakdown, as reported to Congress in the Spring of 1973, is as follows: Accurate estimates of human spaceflight costs were difficult in the early 1960s, as the capability was new and management experience was lacking. Preliminary cost analysis by NASA estimated $7 billion – $12 billion for a crewed lunar landing effort. NASA Administrator James Webb increased this estimate to $20 billion before reporting it to Vice President Johnson in April 1961. Project Apollo was a massive undertaking, representing the largest research and development project in peacetime. At its peak, it employed over 400,000 employees and contractors around the country and accounted for more than half of NASA's total spending in the 1960s. After the first Moon landing, public and political interest waned, including that of President Nixon, who wanted to rein in federal spending. NASA's budget could not sustain Apollo missions which cost, on average, $445 million ($2.66 billion adjusted) each while simultaneously developing the Space Shuttle. The final fiscal year of Apollo funding was 1973. == Apollo Applications Program == Looking beyond the crewed lunar landings, NASA investigated several post-lunar applications for Apollo hardware. The Apollo Extension Series (Apollo X) proposed up to 30 flights to Earth orbit, using the space in the Spacecraft Lunar Module Adapter (SLA) to house a small orbital laboratory (workshop). Astronauts would continue to use the CSM as a ferry to the station. This study was followed by design of a larger orbital workshop to be built in orbit from an empty S-IVB Saturn upper stage and grew into the Apollo Applications Program (AAP). The workshop was to be supplemented by the Apollo Telescope Mount, which could be attached to the ascent stage of the lunar module via a rack. The most ambitious plan called for using an empty S-IVB as an interplanetary spacecraft for a Venus fly-by mission. The S-IVB orbital workshop was the only one of these plans to make it off the drawing board. Dubbed Skylab, it was assembled on the ground rather than in space, and launched in 1973 using the two lower stages of a Saturn V. It was equipped with an Apollo Telescope Mount. Skylab's last crew departed the station on February 8, 1974, and the station itself re-entered the atmosphere in 1979 after development of the Space Shuttle was delayed too long to save it. The Apollo–Soyuz program also used Apollo hardware for the first joint nation spaceflight, paving the way for future cooperation with other nations in the Space Shuttle and International Space Station programs. == Recent observations == In 2008, Japan Aerospace Exploration Agency's SELENE probe observed evidence of the halo surrounding the Apollo 15 Lunar Module blast crater while orbiting above the lunar surface. Beginning in 2009, NASA's robotic Lunar Reconnaissance Orbiter, while orbiting 50 kilometers (31 mi) above the Moon, photographed the remnants of the Apollo program left on the lunar surface, and each site where crewed Apollo flights landed. All of the U.S. flags left on the Moon during the Apollo missions were found to still be standing, with the exception of the one left during the Apollo 11 mission, which was blown over during that mission's lift-off from the lunar surface; the degree to which these flags retain their original colors remains unknown. The flags cannot be seen through a telescope from Earth. In a November 16, 2009, editorial, The New York Times opined: [T]here's something terribly wistful about these photographs of the Apollo landing sites. The detail is such that if Neil Armstrong were walking there now, we could make him out, make out his footsteps even, like the astronaut footpath clearly visible in the photos of the Apollo 14 site. Perhaps the wistfulness is caused by the sense of simple grandeur in those Apollo missions. Perhaps, too, it's a reminder of the risk we all felt after the Eagle had landed—the possibility that it might be unable to lift off again and the astronauts would be stranded on the Moon. But it may also be that a photograph like this one is as close as we're able to come to looking directly back into the human past ... There the [Apollo 11] lunar module sits, parked just where it landed 40 years ago, as if it still really were 40 years ago and all the time since merely imaginary. == Legacy == === Science and engineering === The Apollo program has been described as the greatest technological achievement in human history. Apollo stimulated many areas of technology, leading to over 1,800 spinoff products as of 2015, including advances in the development of cordless power tools, fireproof materials, heart monitors, solar panels, digital imaging, and the use of liquid methane as fuel. The flight computer design used in both the lunar and command modules was, along with the Polaris and Minuteman missile systems, the driving force behind early research into integrated circuits (ICs). By 1963, Apollo was using 60 percent of the United States' production of ICs. The crucial difference between the requirements of Apollo and the missile programs was Apollo's much greater need for reliability. While the Navy and Air Force could work around reliability problems by deploying more missiles, the political and financial cost of failure of an Apollo mission was unacceptably high. Technologies and techniques required for Apollo were developed by Project Gemini. The Apollo project was enabled by NASA's adoption of new advances in semiconductor electronic technology, including metal–oxide–semiconductor field-effect transistors (MOSFETs) in the Interplanetary Monitoring Platform (IMP) and silicon integrated circuit chips in the Apollo Guidance Computer (AGC). === Cultural impact === The crew of Apollo 8 sent the first live televised pictures of the Earth and the Moon back to Earth, and read from the creation story in the Book of Genesis, on Christmas Eve 1968. An estimated one-quarter of the population of the world saw—either live or delayed—the Christmas Eve transmission during the ninth orbit of the Moon, and an estimated one-fifth of the population of the world watched the live transmission of the Apollo 11 moonwalk. The Apollo program also affected environmental activism in the 1970s due to photos taken by the astronauts. The most well known include Earthrise, taken by William Anders on Apollo 8, and The Blue Marble, taken by the Apollo 17 astronauts. The Blue Marble was released during a surge in environmentalism, and became a symbol of the environmental movement as a depiction of Earth's frailty, vulnerability, and isolation amid the vast expanse of space. According to The Economist, Apollo succeeded in accomplishing President Kennedy's goal of taking on the Soviet Union in the Space Race by accomplishing a singular and significant achievement, to demonstrate the superiority of the free-market system. The publication noted the irony that in order to achieve the goal, the program required the organization of tremendous public resources within a vast, centralized government bureaucracy. === Apollo 11 broadcast data restoration project === Prior to Apollo 11's 40th anniversary in 2009, NASA searched for the original videotapes of the mission's live televised moonwalk. After an exhaustive three-year search, it was concluded that the tapes had probably been erased and reused. A new digitally remastered version of the best available broadcast television footage was released instead. == Depictions on film == === Documentaries === Numerous documentary films cover the Apollo program and the Space Race, including: === Docudramas === Some missions have been dramatized: === Fictional === The Apollo program has been the focus of several works of fiction, including: Apollo 18 (2011), horror movie which was released to negative reviews. Men in Black 3 (2012), Science Fiction/Comedy movie. Agent J played by Will Smith goes back to the Apollo 11 launch in 1969 to ensure that a global protection system is launched in to space. For All Mankind (2019), TV series depicting an alternate history in which the Soviet Union was the first country to successfully land a man on the Moon. Indiana Jones and the Dial of Destiny (2023), fifth Indiana Jones film, in which Jürgen Voller, a NASA member and ex-Nazi involved with the Apollo program, wants to time travel. The New York City parade for the Apollo 11 crew is portrayed as a plot point. == See also == == Notes == == References == === Citations === === Sources === == Further reading == == External links == Apollo program history at NASA's Human Space Flight (HSF) website The Apollo Program at the NASA History Program Office "Apollo Spinoffs". Archived from the original on April 4, 2012. The Apollo Program at the National Air and Space Museum Apollo 35th Anniversary Interactive Feature at NASA (in Flash) Lunar Mission Timeline at the Lunar and Planetary Institute Apollo Collection, The University of Alabama in Huntsville Archives and Special Collections === NASA reports === Apollo Program Summary Report (PDF), NASA, JSC-09423, April 1975 NASA History Series Publications Project Apollo Drawings and Technical Diagrams at the NASA History Program Office The Apollo Lunar Surface Journal Archived June 18, 2004, at the Wayback Machine edited by Eric M. Jones and Ken Glover The Apollo Flight Journal by W. David Woods, et al. === Multimedia === NASA Apollo Program images and videos Apollo Image Archive at Arizona State University Audio recording and transcript of President John F. Kennedy, NASA administrator James Webb, et al., discussing the Apollo agenda (White House Cabinet Room, November 21, 1962) The Project Apollo Archive by Kipp Teague is a large repository of Apollo images, videos, and audio recordings The Project Apollo Archive on Flickr Apollo Image Atlas—almost 25,000 lunar images, Lunar and Planetary Institute The short film The Time of Apollo (1975) is available for free viewing and download at the Internet Archive. The short film The Time of Apollo (1975) is available for free viewing and download at the National Archives. The Journeys of Apollo – NASA Documentary on YouTube Apollo (11, 13 and 17) in real time multimedia project
https://en.wikipedia.org/wiki/Apollo_program
Radio programming is the process of organising a schedule of radio content for commercial broadcasting and public broadcasting by radio stations. == History == The original inventors of radio, from Guglielmo Marconi's time on, expected it to be used for one-on-one wireless communication tasks where telephones and telegraphs could not be used because of the problems involved in stringing copper wires from one point to another, such as in ship-to-shore communications. Those inventors had no expectations whatever that radio would become a major mass media entertainment and information medium earning many millions of dollars in revenues annually through radio advertising commercials or sponsorship. These latter uses were brought about after 1920 by business entrepreneurs such as David Sarnoff, who created the National Broadcasting Company (NBC), and William S. Paley, who built Columbia Broadcasting System (CBS). These broadcasting (as opposed to narrowcasting) business organizations began to be called network affiliates, because they consisted of loose chains of individual stations located in various cities, all transmitting the standard overall-system supplied fare, often at synchronised agreed-upon times. Some of these radio network stations were owned and operated by the networks, while others were independent radio owned by entrepreneurs allied with the respective networks. By selling blocks of time to advertisers, the medium was able to quickly become profitable and offer its products to listeners for free, provided they invested in a radio receiver set. The new medium had grown rapidly through the 1930s, vastly increasing both the size of its audience and its profits. In those early days, it was customary for a corporation to sponsor an entire half-hour radio program, placing its commercials at the beginning and the end. This is in contrast to the pattern which developed late in the 20th century in both television and radio, where small slices of time were sold to many sponsors and no corporation claimed or wanted sponsorship of the entire show, except in rare cases. These later commercials also filled a much larger portion of the total program time than they had in the earlier days. In the early radio age, content typically included a balance of comedy, drama, news, music and sports reporting. Variety radio programs included the most famous Hollywood talent of the day. During the 1920s, radio focused on musical entertainment, the Grand Ole Opry, has been focused on broadcasting country music since it began in 1925. Radio soap operas began in the U.S. in 1930 with Painted Dreams. Lørdagsbarnetimen, a Norwegian children's show, with its premiere in 1924 interrupted only by the Second World War, was the longest running radio show in the world until it ceased production in 2010. In the early 1950s, television programming eroded the popularity of radio comedy, drama and variety shows. By the late 1950s, radio broadcasting took on much the form it has today – strongly focused on music, talk, news and sports, though drama can still be heard, especially on the BBC. == References ==
https://en.wikipedia.org/wiki/Radio_programming
A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method. The syntax for reading and writing of properties is like for fields, but property reads and writes are (usually) translated to 'getter' and 'setter' method calls. The field-like syntax is easier to read and write than many method calls, yet the interposition of method calls "under the hood" allows for data validation, active updating (e.g., of GUI elements), or implementation of what may be called "read-only fields". == Support in languages == Programming languages that support properties include ActionScript 3, C#, D, Delphi/Free Pascal, eC, F#, Kotlin, JavaScript, Objective-C 2.0, Python, Scala, Swift, Lua, and Visual Basic. Some object-oriented languages, such as Java and C++, do not support properties, requiring the programmer to define a pair of accessor and mutator methods instead. Oberon-2 provides an alternative mechanism using object variable visibility flags. Other languages designed for the Java Virtual Machine, such as Groovy, natively support properties. While C++ does not have first class properties, they can be emulated with operator overloading. Also note that some C++ compilers support first class properties as language extensions. In Microsoft Visual Studio, GCC, and llvm/clang, the __declspec(property) creates properties similar to C#. Borland C++ and Borland/CodeGear/Embarcadero C++Builder use the __property keyword. In many object oriented languages properties are implemented as a pair of accessor/mutator methods, but accessed using the same syntax as for public fields. Omitting a method from the pair yields a read-only or an uncommon write-only property. In some languages with no built-in support for properties, a similar construct can be implemented as a single method that either returns or changes the underlying data, depending on the context of its invocation. Such techniques are used e.g. in Perl. Some languages (Ruby, Smalltalk) achieve property-like syntax using normal methods, sometimes with a limited amount of syntactic sugar. == Syntax variants == Some languages follow well-established syntax conventions for formally specifying and utilizing properties and methods. Among these conventions: Dot notation Bracket notation === Dot notation === The following example demonstrates dot notation in JavaScript. === Bracket notation === The following example demonstrates bracket notation in JavaScript. == Example syntax == === C# === Recent C# versions also allow "auto-implemented properties" where the backing field for the property is generated by the compiler during compilation. This means that the property must have a setter. However, it can be private. === C++ === C++ does not have first class properties, but there exist several ways to emulate properties to a limited degree. Two of which follow: ==== Using Standard C++ ==== Also see Stack Overflow for a more detailed example. ==== C++, Microsoft, GCC, LLVM/clang and C++Builder-specific ==== An example taken from the MSDN documentation page. === D === In D version 2, each property accessor or mutator must be marked with @property: === Delphi/Free Pascal === === eC === === F# === === JavaScript === === ActionScript 3.0 === === Objective-C 2.0 === The above example could be used in an arbitrary method like this: === PHP === === Python === Properties only work correctly for new-style classes (classes that have object as a superclass), and are only available in Python 2.2 and newer (see the relevant section of the tutorial Unifying types and classes in Python 2.2). Python 2.6 added a new syntax involving decorators for defining properties. === Ruby === Ruby also provides automatic getter/setter synthesizers defined as instance methods of Class. === Visual Basic === ==== Visual Basic (.NET 2003–2010) ==== ==== Visual Basic (only .NET 2010) ==== ==== Visual Basic 6 ==== == See also == Attribute (computing) Bound property Field (computer science) Indexer (programming) Method (computer programming) Mutator method Uniform access principle == References ==
https://en.wikipedia.org/wiki/Property_(programming)
In computer programming, assembly language (alternatively assembler language or symbolic machine code), often referred to simply as assembly and commonly abbreviated as ASM or asm, is any low-level programming language with a very strong correspondence between the instructions in the language and the architecture's machine code instructions. Assembly language usually has one statement per machine instruction (1:1), but constants, comments, assembler directives, symbolic labels of, e.g., memory locations, registers, and macros are generally also supported. The first assembly code in which a language is used to represent machine code instructions is found in Kathleen and Andrew Donald Booth's 1947 work, Coding for A.R.C.. Assembly code is converted into executable machine code by a utility program referred to as an assembler. The term "assembler" is generally attributed to Wilkes, Wheeler and Gill in their 1951 book The Preparation of Programs for an Electronic Digital Computer, who, however, used the term to mean "a program that assembles another program consisting of several sections into a single program". The conversion process is referred to as assembly, as in assembling the source code. The computational step when an assembler is processing a program is called assembly time. Because assembly depends on the machine code instructions, each assembly language is specific to a particular computer architecture. Sometimes there is more than one assembler for the same architecture, and sometimes an assembler is specific to an operating system or to particular operating systems. Most assembly languages do not provide specific syntax for operating system calls, and most assembly languages can be used universally with any operating system, as the language provides access to all the real capabilities of the processor, upon which all system call mechanisms ultimately rest. In contrast to assembly languages, most high-level programming languages are generally portable across multiple architectures but require interpreting or compiling, much more complicated tasks than assembling. In the first decades of computing, it was commonplace for both systems programming and application programming to take place entirely in assembly language. While still irreplaceable for some purposes, the majority of programming is now conducted in higher-level interpreted and compiled languages. In "No Silver Bullet", Fred Brooks summarised the effects of the switch away from assembly language programming: "Surely the most powerful stroke for software productivity, reliability, and simplicity has been the progressive use of high-level languages for programming. Most observers credit that development with at least a factor of five in productivity, and with concomitant gains in reliability, simplicity, and comprehensibility." Today, it is typical to use small amounts of assembly language code within larger systems implemented in a higher-level language, for performance reasons or to interact directly with hardware in ways unsupported by the higher-level language. For instance, just under 2% of version 4.9 of the Linux kernel source code is written in assembly; more than 97% is written in C. == Assembly language syntax == Assembly language uses a mnemonic to represent, e.g., each low-level machine instruction or opcode, each directive, typically also each architectural register, flag, etc. Some of the mnemonics may be built-in and some user-defined. Many operations require one or more operands in order to form a complete instruction. Most assemblers permit named constants, registers, and labels for program and memory locations, and can calculate expressions for operands. Thus, programmers are freed from tedious repetitive calculations and assembler programs are much more readable than machine code. Depending on the architecture, these elements may also be combined for specific instructions or addressing modes using offsets or other data as well as fixed addresses. Many assemblers offer additional mechanisms to facilitate program development, to control the assembly process, and to aid debugging. Some are column oriented, with specific fields in specific columns; this was very common for machines using punched cards in the 1950s and early 1960s. Some assemblers have free-form syntax, with fields separated by delimiters, e.g., punctuation, white space. Some assemblers are hybrid, with, e.g., labels, in a specific column and other fields separated by delimiters; this became more common than column-oriented syntax in the 1960s. == Terminology == A macro assembler is an assembler that includes a macroinstruction facility so that (parameterized) assembly language text can be represented by a name, and that name can be used to insert the expanded text into other code. Open code refers to any assembler input outside of a macro definition. A cross assembler (see also cross compiler) is an assembler that is run on a computer or operating system (the host system) of a different type from the system on which the resulting code is to run (the target system). Cross-assembling facilitates the development of programs for systems that do not have the resources to support software development, such as an embedded system or a microcontroller. In such a case, the resulting object code must be transferred to the target system, via read-only memory (ROM, EPROM, etc.), a programmer (when the read-only memory is integrated in the device, as in microcontrollers), or a data link using either an exact bit-by-bit copy of the object code or a text-based representation of that code (such as Intel hex or Motorola S-record). A high-level assembler is a program that provides language abstractions more often associated with high-level languages, such as advanced control structures (IF/THEN/ELSE, DO CASE, etc.) and high-level abstract data types, including structures/records, unions, classes, and sets. A microassembler is a program that helps prepare a microprogram to control the low level operation of a computer. A meta-assembler is "a program that accepts the syntactic and semantic description of an assembly language, and generates an assembler for that language", or that accepts an assembler source file along with such a description and assembles the source file in accordance with that description. "Meta-Symbol" assemblers for the SDS 9 Series and SDS Sigma series of computers are meta-assemblers. Sperry Univac also provided a Meta-Assembler for the UNIVAC 1100/2200 series. inline assembler (or embedded assembler) is assembler code contained within a high-level language program. This is most often used in systems programs which need direct access to the hardware. == Key concepts == === Assembler === An assembler program creates object code by translating combinations of mnemonics and syntax for operations and addressing modes into their numerical equivalents. This representation typically includes an operation code ("opcode") as well as other control bits and data. The assembler also calculates constant expressions and resolves symbolic names for memory locations and other entities. The use of symbolic references is a key feature of assemblers, saving tedious calculations and manual address updates after program modifications. Most assemblers also include macro facilities for performing textual substitution – e.g., to generate common short sequences of instructions as inline, instead of called subroutines. Some assemblers may also be able to perform some simple types of instruction set-specific optimizations. One concrete example of this may be the ubiquitous x86 assemblers from various vendors. Called jump-sizing, most of them are able to perform jump-instruction replacements (long jumps replaced by short or relative jumps) in any number of passes, on request. Others may even do simple rearrangement or insertion of instructions, such as some assemblers for RISC architectures that can help optimize a sensible instruction scheduling to exploit the CPU pipeline as efficiently as possible. Assemblers have been available since the 1950s, as the first step above machine language and before high-level programming languages such as Fortran, Algol, COBOL and Lisp. There have also been several classes of translators and semi-automatic code generators with properties similar to both assembly and high-level languages, with Speedcode as perhaps one of the better-known examples. There may be several assemblers with different syntax for a particular CPU or instruction set architecture. For instance, an instruction to add memory data to a register in a x86-family processor might be add eax,[ebx], in original Intel syntax, whereas this would be written addl (%ebx),%eax in the AT&T syntax used by the GNU Assembler. Despite different appearances, different syntactic forms generally generate the same numeric machine code. A single assembler may also have different modes in order to support variations in syntactic forms as well as their exact semantic interpretations (such as FASM-syntax, TASM-syntax, ideal mode, etc., in the special case of x86 assembly programming). ==== Number of passes ==== There are two types of assemblers based on how many passes through the source are needed (how many times the assembler reads the source) to produce the object file. One-pass assemblers process the source code once. For symbols used before they are defined, the assembler will emit "errata" after the eventual definition, telling the linker or the loader to patch the locations where the as yet undefined symbols had been used. Multi-pass assemblers create a table with all symbols and their values in the first passes, then use the table in later passes to generate code. In both cases, the assembler must be able to determine the size of each instruction on the initial passes in order to calculate the addresses of subsequent symbols. This means that if the size of an operation referring to an operand defined later depends on the type or distance of the operand, the assembler will make a pessimistic estimate when first encountering the operation, and if necessary, pad it with one or more "no-operation" instructions in a later pass or the errata. In an assembler with peephole optimization, addresses may be recalculated between passes to allow replacing pessimistic code with code tailored to the exact distance from the target. The original reason for the use of one-pass assemblers was memory size and speed of assembly – often a second pass would require storing the symbol table in memory (to handle forward references), rewinding and rereading the program source on tape, or rereading a deck of cards or punched paper tape. Later computers with much larger memories (especially disc storage), had the space to perform all necessary processing without such re-reading. The advantage of the multi-pass assembler is that the absence of errata makes the linking process (or the program load if the assembler directly produces executable code) faster. Example: in the following code snippet, a one-pass assembler would be able to determine the address of the backward reference BKWD when assembling statement S2, but would not be able to determine the address of the forward reference FWD when assembling the branch statement S1; indeed, FWD may be undefined. A two-pass assembler would determine both addresses in pass 1, so they would be known when generating code in pass 2. S1 B FWD ... FWD EQU * ... BKWD EQU * ... S2 B BKWD ==== High-level assemblers ==== More sophisticated high-level assemblers provide language abstractions such as: High-level procedure/function declarations and invocations Advanced control structures (IF/THEN/ELSE, SWITCH) High-level abstract data types, including structures/records, unions, classes, and sets Sophisticated macro processing (although available on ordinary assemblers since the late 1950s for, e.g., the IBM 700 series and IBM 7000 series, and since the 1960s for IBM System/360 (S/360), amongst other machines) Object-oriented programming features such as classes, objects, abstraction, polymorphism, and inheritance See Language design below for more details. === Assembly language === A program written in assembly language consists of a series of mnemonic processor instructions and meta-statements (known variously as declarative operations, directives, pseudo-instructions, pseudo-operations and pseudo-ops), comments and data. Assembly language instructions usually consist of an opcode mnemonic followed by an operand, which might be a list of data, arguments or parameters. Some instructions may be "implied", which means the data upon which the instruction operates is implicitly defined by the instruction itself—such an instruction does not take an operand. The resulting statement is translated by an assembler into machine language instructions that can be loaded into memory and executed. For example, the instruction below tells an x86/IA-32 processor to move an immediate 8-bit value into a register. The binary code for this instruction is 10110 followed by a 3-bit identifier for which register to use. The identifier for the AL register is 000, so the following machine code loads the AL register with the data 01100001. 10110000 01100001 This binary computer code can be made more human-readable by expressing it in hexadecimal as follows. B0 61 Here, B0 means "Move a copy of the following value into AL", and 61 is a hexadecimal representation of the value 01100001, which is 97 in decimal. Assembly language for the 8086 family provides the mnemonic MOV (an abbreviation of move) for instructions such as this, so the machine code above can be written as follows in assembly language, complete with an explanatory comment if required, after the semicolon. This is much easier to read and to remember. In some assembly languages (including this one) the same mnemonic, such as MOV, may be used for a family of related instructions for loading, copying and moving data, whether these are immediate values, values in registers, or memory locations pointed to by values in registers or by immediate (a.k.a. direct) addresses. Other assemblers may use separate opcode mnemonics such as L for "move memory to register", ST for "move register to memory", LR for "move register to register", MVI for "move immediate operand to memory", etc. If the same mnemonic is used for different instructions, that means that the mnemonic corresponds to several different binary instruction codes, excluding data (e.g. the 61h in this example), depending on the operands that follow the mnemonic. For example, for the x86/IA-32 CPUs, the Intel assembly language syntax MOV AL, AH represents an instruction that moves the contents of register AH into register AL. The hexadecimal form of this instruction is: 88 E0 The first byte, 88h, identifies a move between a byte-sized register and either another register or memory, and the second byte, E0h, is encoded (with three bit-fields) to specify that both operands are registers, the source is AH, and the destination is AL. In a case like this where the same mnemonic can represent more than one binary instruction, the assembler determines which instruction to generate by examining the operands. In the first example, the operand 61h is a valid hexadecimal numeric constant and is not a valid register name, so only the B0 instruction can be applicable. In the second example, the operand AH is a valid register name and not a valid numeric constant (hexadecimal, decimal, octal, or binary), so only the 88 instruction can be applicable. Assembly languages are always designed so that this sort of lack of ambiguity is universally enforced by their syntax. For example, in the Intel x86 assembly language, a hexadecimal constant must start with a numeral digit, so that the hexadecimal number 'A' (equal to decimal ten) would be written as 0Ah or 0AH, not AH, specifically so that it cannot appear to be the name of register AH. (The same rule also prevents ambiguity with the names of registers BH, CH, and DH, as well as with any user-defined symbol that ends with the letter H and otherwise contains only characters that are hexadecimal digits, such as the word "BEACH".) Returning to the original example, while the x86 opcode 10110000 (B0) copies an 8-bit value into the AL register, 10110001 (B1) moves it into CL and 10110010 (B2) does so into DL. Assembly language examples for these follow. The syntax of MOV can also be more complex as the following examples show. In each case, the MOV mnemonic is translated directly into one of the opcodes 88-8C, 8E, A0-A3, B0-BF, C6 or C7 by an assembler, and the programmer normally does not have to know or remember which. Transforming assembly language into machine code is the job of an assembler, and the reverse can at least partially be achieved by a disassembler. Unlike high-level languages, there is a one-to-one correspondence between many simple assembly statements and machine language instructions. However, in some cases, an assembler may provide pseudoinstructions (essentially macros) which expand into several machine language instructions to provide commonly needed functionality. For example, for a machine that lacks a "branch if greater or equal" instruction, an assembler may provide a pseudoinstruction that expands to the machine's "set if less than" and "branch if zero (on the result of the set instruction)". Most full-featured assemblers also provide a rich macro language (discussed below) which is used by vendors and programmers to generate more complex code and data sequences. Since the information about pseudoinstructions and macros defined in the assembler environment is not present in the object program, a disassembler cannot reconstruct the macro and pseudoinstruction invocations but can only disassemble the actual machine instructions that the assembler generated from those abstract assembly-language entities. Likewise, since comments in the assembly language source file are ignored by the assembler and have no effect on the object code it generates, a disassembler is always completely unable to recover source comments. Each computer architecture has its own machine language. Computers differ in the number and type of operations they support, in the different sizes and numbers of registers, and in the representations of data in storage. While most general-purpose computers are able to carry out essentially the same functionality, the ways they do so differ; the corresponding assembly languages reflect these differences. Multiple sets of mnemonics or assembly-language syntax may exist for a single instruction set, typically instantiated in different assembler programs. In these cases, the most popular one is usually that supplied by the CPU manufacturer and used in its documentation. Two examples of CPUs that have two different sets of mnemonics are the Intel 8080 family and the Intel 8086/8088. Because Intel claimed copyright on its assembly language mnemonics (on each page of their documentation published in the 1970s and early 1980s, at least), some companies that independently produced CPUs compatible with Intel instruction sets invented their own mnemonics. The Zilog Z80 CPU, an enhancement of the Intel 8080A, supports all the 8080A instructions plus many more; Zilog invented an entirely new assembly language, not only for the new instructions but also for all of the 8080A instructions. For example, where Intel uses the mnemonics MOV, MVI, LDA, STA, LXI, LDAX, STAX, LHLD, and SHLD for various data transfer instructions, the Z80 assembly language uses the mnemonic LD for all of them. A similar case is the NEC V20 and V30 CPUs, enhanced copies of the Intel 8086 and 8088, respectively. Like Zilog with the Z80, NEC invented new mnemonics for all of the 8086 and 8088 instructions, to avoid accusations of infringement of Intel's copyright. (It is questionable whether such copyrights can be valid, and later CPU companies such as AMD and Cyrix republished Intel's x86/IA-32 instruction mnemonics exactly with neither permission nor legal penalty.) It is doubtful whether in practice many people who programmed the V20 and V30 actually wrote in NEC's assembly language rather than Intel's; since any two assembly languages for the same instruction set architecture are isomorphic (somewhat like English and Pig Latin), there is no requirement to use a manufacturer's own published assembly language with that manufacturer's products. === "Hello, world!" on x86 Linux === In 32-bit assembly language for Linux on an x86 processor, "Hello, world!" can be printed like this. == Language design == === Basic elements === There is a large degree of diversity in the way the authors of assemblers categorize statements and in the nomenclature that they use. In particular, some describe anything other than a machine mnemonic or extended mnemonic as a pseudo-operation (pseudo-op). A typical assembly language consists of 3 types of instruction statements that are used to define program operations: Opcode mnemonics Data definitions Assembly directives ==== Opcode mnemonics and extended mnemonics ==== Instructions (statements) in assembly language are generally very simple, unlike those in high-level languages. Generally, a mnemonic is a symbolic name for a single executable machine language instruction (an opcode), and there is at least one opcode mnemonic defined for each machine language instruction. Each instruction typically consists of an operation or opcode plus zero or more operands. Most instructions refer to a single value or a pair of values. Operands can be immediate (value coded in the instruction itself), registers specified in the instruction or implied, or the addresses of data located elsewhere in storage. This is determined by the underlying processor architecture: the assembler merely reflects how this architecture works. Extended mnemonics are often used to specify a combination of an opcode with a specific operand, e.g., the System/360 assemblers use B as an extended mnemonic for BC with a mask of 15 and NOP ("NO OPeration" – do nothing for one step) for BC with a mask of 0. Extended mnemonics are often used to support specialized uses of instructions, often for purposes not obvious from the instruction name. For example, many CPU's do not have an explicit NOP instruction, but do have instructions that can be used for the purpose. In 8086 CPUs the instruction xchg ax,ax is used for nop, with nop being a pseudo-opcode to encode the instruction xchg ax,ax. Some disassemblers recognize this and will decode the xchg ax,ax instruction as nop. Similarly, IBM assemblers for System/360 and System/370 use the extended mnemonics NOP and NOPR for BC and BCR with zero masks. For the SPARC architecture, these are known as synthetic instructions. Some assemblers also support simple built-in macro-instructions that generate two or more machine instructions. For instance, with some Z80 assemblers the instruction ld hl,bc is recognized to generate ld l,c followed by ld h,b. These are sometimes known as pseudo-opcodes. Mnemonics are arbitrary symbols; in 1985 the IEEE published Standard 694 for a uniform set of mnemonics to be used by all assemblers. The standard has since been withdrawn. ==== Data directives ==== There are instructions used to define data elements to hold data and variables. They define the type of data, the length and the alignment of data. These instructions can also define whether the data is available to outside programs (programs assembled separately) or only to the program in which the data section is defined. Some assemblers classify these as pseudo-ops. ==== Assembly directives ==== Assembly directives, also called pseudo-opcodes, pseudo-operations or pseudo-ops, are commands given to an assembler "directing it to perform operations other than assembling instructions". Directives affect how the assembler operates and "may affect the object code, the symbol table, the listing file, and the values of internal assembler parameters". Sometimes the term pseudo-opcode is reserved for directives that generate object code, such as those that generate data. The names of pseudo-ops often start with a dot to distinguish them from machine instructions. Pseudo-ops can make the assembly of the program dependent on parameters input by a programmer, so that one program can be assembled in different ways, perhaps for different applications. Or, a pseudo-op can be used to manipulate presentation of a program to make it easier to read and maintain. Another common use of pseudo-ops is to reserve storage areas for run-time data and optionally initialize their contents to known values. Symbolic assemblers let programmers associate arbitrary names (labels or symbols) with memory locations and various constants. Usually, every constant and variable is given a name so instructions can reference those locations by name, thus promoting self-documenting code. In executable code, the name of each subroutine is associated with its entry point, so any calls to a subroutine can use its name. Inside subroutines, GOTO destinations are given labels. Some assemblers support local symbols which are often lexically distinct from normal symbols (e.g., the use of "10$" as a GOTO destination). Some assemblers, such as NASM, provide flexible symbol management, letting programmers manage different namespaces, automatically calculate offsets within data structures, and assign labels that refer to literal values or the result of simple computations performed by the assembler. Labels can also be used to initialize constants and variables with relocatable addresses. Assembly languages, like most other computer languages, allow comments to be added to program source code that will be ignored during assembly. Judicious commenting is essential in assembly language programs, as the meaning and purpose of a sequence of binary machine instructions can be difficult to determine. The "raw" (uncommented) assembly language generated by compilers or disassemblers is quite difficult to read when changes must be made. === Macros === Many assemblers support predefined macros, and others support programmer-defined (and repeatedly re-definable) macros involving sequences of text lines in which variables and constants are embedded. The macro definition is most commonly a mixture of assembler statements, e.g., directives, symbolic machine instructions, and templates for assembler statements. This sequence of text lines may include opcodes or directives. Once a macro has been defined its name may be used in place of a mnemonic. When the assembler processes such a statement, it replaces the statement with the text lines associated with that macro, then processes them as if they existed in the source code file (including, in some assemblers, expansion of any macros existing in the replacement text). Macros in this sense date to IBM autocoders of the 1950s. Macro assemblers typically have directives to, e.g., define macros, define variables, set variables to the result of an arithmetic, logical or string expression, iterate, conditionally generate code. Some of those directives may be restricted to use within a macro definition, e.g., MEXIT in HLASM, while others may be permitted within open code (outside macro definitions), e.g., AIF and COPY in HLASM. In assembly language, the term "macro" represents a more comprehensive concept than it does in some other contexts, such as the pre-processor in the C programming language, where its #define directive typically is used to create short single line macros. Assembler macro instructions, like macros in PL/I and some other languages, can be lengthy "programs" by themselves, executed by interpretation by the assembler during assembly. Since macros can have 'short' names but expand to several or indeed many lines of code, they can be used to make assembly language programs appear to be far shorter, requiring fewer lines of source code, as with higher level languages. They can also be used to add higher levels of structure to assembly programs, optionally introduce embedded debugging code via parameters and other similar features. Macro assemblers often allow macros to take parameters. Some assemblers include quite sophisticated macro languages, incorporating such high-level language elements as optional parameters, symbolic variables, conditionals, string manipulation, and arithmetic operations, all usable during the execution of a given macro, and allowing macros to save context or exchange information. Thus a macro might generate numerous assembly language instructions or data definitions, based on the macro arguments. This could be used to generate record-style data structures or "unrolled" loops, for example, or could generate entire algorithms based on complex parameters. For instance, a "sort" macro could accept the specification of a complex sort key and generate code crafted for that specific key, not needing the run-time tests that would be required for a general procedure interpreting the specification. An organization using assembly language that has been heavily extended using such a macro suite can be considered to be working in a higher-level language since such programmers are not working with a computer's lowest-level conceptual elements. Underlining this point, macros were used to implement an early virtual machine in SNOBOL4 (1967), which was written in the SNOBOL Implementation Language (SIL), an assembly language for a virtual machine. The target machine would translate this to its native code using a macro assembler. This allowed a high degree of portability for the time. Macros were used to customize large scale software systems for specific customers in the mainframe era and were also used by customer personnel to satisfy their employers' needs by making specific versions of manufacturer operating systems. This was done, for example, by systems programmers working with IBM's Conversational Monitor System / Virtual Machine (VM/CMS) and with IBM's "real time transaction processing" add-ons, Customer Information Control System CICS, and ACP/TPF, the airline/financial system that began in the 1970s and still runs many large computer reservation systems (CRS) and credit card systems today. It is also possible to use solely the macro processing abilities of an assembler to generate code written in completely different languages, for example, to generate a version of a program in COBOL using a pure macro assembler program containing lines of COBOL code inside assembly time operators instructing the assembler to generate arbitrary code. IBM OS/360 uses macros to perform system generation. The user specifies options by coding a series of assembler macros. Assembling these macros generates a job stream to build the system, including job control language and utility control statements. This is because, as was realized in the 1960s, the concept of "macro processing" is independent of the concept of "assembly", the former being in modern terms more word processing, text processing, than generating object code. The concept of macro processing appeared, and appears, in the C programming language, which supports "preprocessor instructions" to set variables, and make conditional tests on their values. Unlike certain previous macro processors inside assemblers, the C preprocessor is not Turing-complete because it lacks the ability to either loop or "go to", the latter allowing programs to loop. Despite the power of macro processing, it fell into disuse in many high level languages (major exceptions being C, C++ and PL/I) while remaining a perennial for assemblers. Macro parameter substitution is strictly by name: at macro processing time, the value of a parameter is textually substituted for its name. The most famous class of bugs resulting was the use of a parameter that itself was an expression and not a simple name when the macro writer expected a name. In the macro: foo: macro a load a*b the intention was that the caller would provide the name of a variable, and the "global" variable or constant b would be used to multiply "a". If foo is called with the parameter a-c, the macro expansion of load a-c*b occurs. To avoid any possible ambiguity, users of macro processors can parenthesize formal parameters inside macro definitions, or callers can parenthesize the input parameters. === Support for structured programming === Packages of macros have been written providing structured programming elements to encode execution flow. The earliest example of this approach was in the Concept-14 macro set, originally proposed by Harlan Mills (March 1970), and implemented by Marvin Kessler at IBM's Federal Systems Division, which provided IF/ELSE/ENDIF and similar control flow blocks for OS/360 assembler programs. This was a way to reduce or eliminate the use of GOTO operations in assembly code, one of the main factors causing spaghetti code in assembly language. This approach was widely accepted in the early 1980s (the latter days of large-scale assembly language use). IBM's High Level Assembler Toolkit includes such a macro package. Another design was A-Natural, a "stream-oriented" assembler for 8080/Z80 processors from Whitesmiths Ltd. (developers of the Unix-like Idris operating system, and what was reported to be the first commercial C compiler). The language was classified as an assembler because it worked with raw machine elements such as opcodes, registers, and memory references; but it incorporated an expression syntax to indicate execution order. Parentheses and other special symbols, along with block-oriented structured programming constructs, controlled the sequence of the generated instructions. A-natural was built as the object language of a C compiler, rather than for hand-coding, but its logical syntax won some fans. There has been little apparent demand for more sophisticated assemblers since the decline of large-scale assembly language development. In spite of that, they are still being developed and applied in cases where resource constraints or peculiarities in the target system's architecture prevent the effective use of higher-level languages. Assemblers with a strong macro engine allow structured programming via macros, such as the switch macro provided with the Masm32 package (this code is a complete program): == Use of assembly language == When the stored-program computer was introduced, programs were written in machine code, and loaded into the computer from punched paper tape or toggled directly into memory from console switches. Kathleen Booth "is credited with inventing assembly language" based on theoretical work she began in 1947, while working on the ARC2 at Birkbeck, University of London, following consultation by Andrew Booth (later her husband) with mathematician John von Neumann and physicist Herman Goldstine at the Institute for Advanced Study. In late 1948, the Electronic Delay Storage Automatic Calculator (EDSAC) had an assembler (named "initial orders") integrated into its bootstrap program. It used one-letter mnemonics developed by David Wheeler, who is credited by the IEEE Computer Society as the creator of the first "assembler". Reports on the EDSAC introduced the term "assembly" for the process of combining fields into an instruction word. SOAP (Symbolic Optimal Assembly Program) was an assembly language for the IBM 650 computer written by Stan Poley in 1955. Assembly languages eliminated much of the error-prone, tedious, and time-consuming first-generation programming needed with the earliest computers, freeing programmers from tedium such as remembering numeric codes and calculating addresses. They were once widely used for all sorts of programming. By the late 1950s their use had largely been supplanted by higher-level languages in the search for improved programming productivity. Today, assembly language is still used for direct hardware manipulation, access to specialized processor instructions, or to address critical performance issues. Typical uses are device drivers, low-level embedded systems, and real-time systems (see § Current usage). Numerous programs were written entirely in assembly language. The Burroughs MCP (1961) was the first computer for which an operating system was not developed entirely in assembly language; it was written in Executive Systems Problem Oriented Language (ESPOL), an Algol dialect. Many commercial applications were written in assembly language as well, including a large amount of the IBM mainframe software developed by large corporations. COBOL, FORTRAN and some PL/I eventually displaced assembly language, although a number of large organizations retained assembly-language application infrastructures well into the 1990s. Assembly language was the primary development language for 8-bit home computers such as the Apple II, Atari 8-bit computers, ZX Spectrum, and Commodore 64. Interpreted BASIC on these systems did not offer maximum execution speed and full use of facilities to take full advantage of the available hardware. Assembly language was the default choice for programming 8-bit consoles such as the Atari 2600 and Nintendo Entertainment System. Key software for IBM PC compatibles such as MS-DOS, Turbo Pascal, and the Lotus 1-2-3 spreadsheet was written in assembly language. As computer speed grew exponentially, assembly language became a tool for speeding up parts of programs, such as the rendering of Doom, rather than a dominant development language. In the 1990s, assembly language was used to maximise performance from systems such as the Sega Saturn, and as the primary language for arcade hardware using the TMS34010 integrated CPU/GPU such as Mortal Kombat and NBA Jam. === Current usage === There has been debate over the usefulness and performance of assembly language relative to high-level languages. Although assembly language has specific niche uses where it is important (see below), there are other tools for optimization. As of July 2017, the TIOBE index of programming language popularity ranks assembly language at 11, ahead of Visual Basic, for example. Assembler can be used to optimize for speed or optimize for size. In the case of speed optimization, modern optimizing compilers are claimed to render high-level languages into code that can run as fast as hand-written assembly, despite some counter-examples. The complexity of modern processors and memory sub-systems makes effective optimization increasingly difficult for compilers and assembly programmers alike. Increasing processor performance has meant that most CPUs sit idle most of the time, with delays caused by predictable bottlenecks such as cache misses, I/O operations and paging, making raw code execution speed a non-issue for many programmers. There are still certain computer programming domains in which the use of assembly programming is more common: Writing code for systems with older processors that have limited high-level language options such as the Atari 2600, Commodore 64, and graphing calculators. Programs for these computers of the 1970s and 1980s are often written in the context of demoscene or retrogaming subcultures. Code that must interact directly with the hardware, for example in device drivers and interrupt handlers. In an embedded processor or DSP, high-repetition interrupts require the shortest number of cycles per interrupt, such as an interrupt that occurs 1000 or 10000 times a second. Programs that need to use processor-specific instructions not implemented in a compiler. A common example is the bitwise rotation instruction at the core of many encryption algorithms, as well as querying the parity of a byte or the 4-bit carry of an addition. Stand-alone executables that are required to execute without recourse to the run-time components or libraries associated with a high-level language, such as the firmware for telephones, automobile fuel and ignition systems, air-conditioning control systems,and security systems. Programs with performance-sensitive inner loops, where assembly language provides optimization opportunities that are difficult to achieve in a high-level language. For example, linear algebra with BLAS or discrete cosine transformation (e.g. SIMD assembly version from x264). Programs that create vectorized functions for programs in higher-level languages such as C. In the higher-level language this is sometimes aided by compiler intrinsic functions which map directly to SIMD mnemonics, but nevertheless result in a one-to-one assembly conversion specific for the given vector processor. Real-time programs such as simulations, flight navigation systems, and medical equipment. For example, in a fly-by-wire system, telemetry must be interpreted and acted upon within strict time constraints. Such systems must eliminate sources of unpredictable delays, which may be created by interpreted languages, automatic garbage collection, paging operations, or preemptive multitasking. Choosing assembly or lower-level languages for such systems gives programmers greater visibility and control over processing details. Cryptographic algorithms that must always take strictly the same time to execute, preventing timing attacks. Video encoders and decoders such as rav1e (an encoder for AV1) and dav1d (the reference decoder for AV1) contain assembly to leverage AVX2 and ARM Neon instructions when available. Modify and extend legacy code written for IBM mainframe computers. Situations where complete control over the environment is required, in extremely high-security situations where nothing can be taken for granted. Computer viruses, bootloaders, certain device drivers, or other items very close to the hardware or low-level operating system. Instruction set simulators for monitoring, tracing and debugging where additional overhead is kept to a minimum. Situations where no high-level language exists, on a new or specialized processor for which no cross compiler is available. Reverse engineering and modifying program files such as: existing binaries that may or may not have originally been written in a high-level language, for example when trying to recreate programs for which source code is not available or has been lost, or cracking copy protection of proprietary software. Video games (also termed ROM hacking), which is possible via several methods. The most widely employed method is altering program code at the assembly language level. Assembly language is still taught in most computer science and electronic engineering programs. Although few programmers today regularly work with assembly language as a tool, the underlying concepts remain important. Such fundamental topics as binary arithmetic, memory allocation, stack processing, character set encoding, interrupt processing, and compiler design would be hard to study in detail without a grasp of how a computer operates at the hardware level. Since a computer's behaviour is fundamentally defined by its instruction set, the logical way to learn such concepts is to study an assembly language. Most modern computers have similar instruction sets. Therefore, studying a single assembly language is sufficient to learn the basic concepts, recognize situations where the use of assembly language might be appropriate, and to see how efficient executable code can be created from high-level languages. === Typical applications === Assembly language is typically used in a system's boot code, the low-level code that initializes and tests the system hardware prior to booting the operating system and is often stored in ROM. (BIOS on IBM-compatible PC systems and CP/M is an example.) Assembly language is often used for low-level code, for instance for operating system kernels, which cannot rely on the availability of pre-existing system calls and must indeed implement them for the particular processor architecture on which the system will be running. Some compilers translate high-level languages into assembly first before fully compiling, allowing the assembly code to be viewed for debugging and optimization purposes. Some compilers for relatively low-level languages, such as Pascal or C, allow the programmer to embed assembly language directly in the source code (so called inline assembly). Programs using such facilities can then construct abstractions using different assembly language on each hardware platform. The system's portable code can then use these processor-specific components through a uniform interface. Assembly language is useful in reverse engineering. Many programs are distributed only in machine code form which is straightforward to translate into assembly language by a disassembler, but more difficult to translate into a higher-level language through a decompiler. Tools such as the Interactive Disassembler make extensive use of disassembly for such a purpose. This technique is used by hackers to crack commercial software, and competitors to produce software with similar results from competing companies. Assembly language is used to enhance speed of execution, especially in early personal computers with limited processing power and RAM. Assemblers can be used to generate blocks of data, with no high-level language overhead, from formatted and commented source code, to be used by other code. == See also == Compiler Comparison of assemblers Disassembler Hexadecimal Instruction set architecture Little man computer – an educational computer model with a base-10 assembly language Nibble Typed assembly language == Notes == == References == == Further reading == Bartlett, Jonathan (2004). Programming from the Ground Up - An introduction to programming using linux assembly language. Bartlett Publishing. ISBN 0-9752838-4-7. Archived from the original on 2020-03-24. Retrieved 2020-03-24. [4] Britton, Robert (2003). MIPS Assembly Language Programming. Prentice Hall. ISBN 0-13-142044-5. Calingaert, Peter (1979) [1978-11-05]. Written at University of North Carolina at Chapel Hill. Horowitz, Ellis (ed.). Assemblers, Compilers, and Program Translation. Computer software engineering series (1st printing, 1st ed.). Potomac, Maryland, US: Computer Science Press, Inc. ISBN 0-914894-23-4. ISSN 0888-2088. LCCN 78-21905. Retrieved 2020-03-20. (2+xiv+270+6 pages) Duntemann, Jeff (2000). Assembly Language Step-by-Step. Wiley. ISBN 0-471-37523-3. Hyde, Randall (2010). The Art of Assembly Language (2nd ed.). No Starch Press. ISBN 978-1593272074. Jorgensen, Ed. "x86-64 Assembly Language Programming with Ubuntu" (PDF). Kann, Charles W. (2015). "Introduction to MIPS Assembly Language Programming". Archived from the original on 2020-03-24. Retrieved 2020-03-24. Kann, Charles W. (2021). "Introduction to Assembly Language Programming: From Soup to Nuts: ARM Edition". Open Educational Resources. Norton, Peter; Socha, John (1986). Peter Norton's Assembly Language Book for the IBM PC. New York, US: Brady Books. Singer, Michael (1980). PDP-11. Assembler Language Programming and Machine Organization. New York, US: John Wiley & Sons. Sweetman, Dominic (1999). See MIPS Run. Morgan Kaufmann Publishers. ISBN 1-55860-410-3. Waldron, John (1998). Introduction to RISC Assembly Language Programming. Addison Wesley. ISBN 0-201-39828-1. "ASM Community Book". 2009. Archived from the original on 2013-05-30. Retrieved 2013-05-30. ("An online book full of helpful ASM info, tutorials and code examples" by the ASM Community, archived at the internet archive.) == External links == Assembly Language and Learning Assembly Language pages on WikiWikiWeb Assembly Language Programming Examples
https://en.wikipedia.org/wiki/Assembly_language
In computer science, programming by demonstration (PbD) is an end-user development technique for teaching a computer or a robot new behaviors by demonstrating the task to transfer directly instead of programming it through machine commands. The terms programming by example (PbE) and programming by demonstration (PbD) appeared in software development research as early as the mid 1980s to define a way to define a sequence of operations without having to learn a programming language. The usual distinction in literature between these terms is that in PbE the user gives a prototypical product of the computer execution, such as a row in the desired results of a query; while in PbD the user performs a sequence of actions that the computer must repeat, generalizing it to be used in different data sets. These two terms were first undifferentiated, but PbE then tended to be mostly adopted by software development researchers while PbD tended to be adopted by robotics researchers. Today, PbE refers to an entirely different concept, supported by new programming languages that are similar to simulators. This framework can be contrasted with Bayesian program synthesis. == Robot programming by demonstration == The PbD paradigm is first attractive to the robotics industry due to the costs involved in the development and maintenance of robot programs. In this field, the operator often has implicit knowledge on the task to achieve (he/she knows how to do it), but does not have usually the programming skills (or the time) required to reconfigure the robot. Demonstrating how to achieve the task through examples thus allows to learn the skill without explicitly programming each detail. The first PbD strategies proposed in robotics were based on teach-in, guiding or play-back methods that consisted basically in moving the robot (through a dedicated interface or manually) through a set of relevant configurations that the robot should adopt sequentially (position, orientation, state of the gripper). The method was then progressively ameliorated by focusing principally on the teleoperation control and by using different interfaces such as vision. However, these PbD methods still used direct repetition, which was useful in industry only when conceiving an assembly line using exactly the same product components. To apply this concept to products with different variants or to apply the programs to new robots, the generalization issue became a crucial point. To address this issue, the first attempts at generalizing the skill were mainly based on the help of the user through queries about the user's intentions. Then, different levels of abstractions were proposed to resolve the generalization issue, basically dichotomized in learning methods at a symbolic level or at a trajectory level. The development of humanoid robots naturally brought a growing interest in robot programming by demonstration. As a humanoid robot is supposed by its nature to adapt to new environments, not only the human appearance is important but the algorithms used for its control require flexibility and versatility. Due to the continuously changing environments and to the huge varieties of tasks that a robot is expected to perform, the robot requires the ability to continuously learn new skills and adapt the existing skills to new contexts. Research in PbD also progressively departed from its original purely engineering perspective to adopt an interdisciplinary approach, taking insights from neuroscience and social sciences to emulate the process of imitation in humans and animals. With the increasing consideration of this body of work in robotics, the notion of Robot programming by demonstration (also known as RPD or RbD) was also progressively replaced by the more biological label of Learning by imitation. === Neurally-imprinted Stable Vector Fields (NiVF) === Neurally-imprinted Stable Vector Fields (NiVF) was introduced as a novel learning scheme during ESANN 2013 and show how to imprint vector fields into neurals networks such as Extreme Learning Machines (ELMs) in a guaranteed stable manner. Furthermore, the paper won the best student paper award. The networks represent movements, where asymptotic stability is incorporated through constraints derived from Lyapunov stability theory. It is shown that this approach successfully performs stable and smooth point-to-point movements learned from human handwriting movements. It is also possible to learn the Lyapunov candidate that is used for stabilization of the dynamical system. For this reason, neural learning scheme that estimates stable dynamical systems from demonstrations based on a two-stage process are needed: first, a data-driven Lyapunov function candidate is estimated. Second, stability is incorporated by means of a novel method to respect local constraints in the neural learning. This allows for learning stable dynamics while simultaneously sustaining the accuracy of the dynamical system and robustly generate complex movements. === Diffeomorphic Transformations === Diffeomorphic transformations turn out to be particularly suitable for substantially increasing the learnability of dynamical systems for robotic motions. The stable estimator of dynamical systems (SEDS) is an interesting approach to learn time invariant systems to control robotic motions. However, this is restricted to dynamical systems with only quadratic Lyapunov functions. The new approach Tau-SEDS overcomes this limitations in a mathematical elegant manner. === Parameterized skills === After a task was demonstrated by a human operator, the trajectory is stored in a database. Getting easier access to the raw data is realized with parameterized skills. A skill is requesting a database and generates a trajectory. For example, at first the skill “opengripper(slow)” is sent to the motion database and in response, the stored movement of the robotarm is provided. The parameters of a skill allow to modify the policy to fulfill external constraints. A skill is an interface between task names, given in natural language and the underlying spatiotemporal movement in the 3d space, which consists of points. Single skills can be combined into a task for defining longer motion sequences from a high level perspective. For practical applications, different actions are stored in a skill library. For increasing the abstraction level further, skills can be converted into dynamic movement primitives (DMP). They generate a robot trajectory on the fly which was unknown at the time of the demonstration. This helps to increase the flexibility of the solver. == Non-robotic use == For final users, to automate a workflow in a complex tool (e.g. Photoshop), the most simple case of PbD is the macro recorder. == See also == Programming by example Inductive programming Macro recorder Supervised learning == References == Cypher, Allen (1993), Watch What I Do: Programming by Demonstration, Daniel C. Halbert, MIT Press, ISBN 978-0-262-03213-1 Lieberman, Henry (2001), Your Wish is My Command: Programming By Example, Ben Shneiderman, Morgan Kaufmann, ISBN 978-1-55860-688-3 == External links == === Reviews papers === Billard, Aude (2008), "Robot Programming by Demonstration", Springer Handbook of Robotics (PDF), S. Calinon, R. Dillmann and S. Schaal, MIT Press, pp. 1371–1394, doi:10.1007/978-3-540-30301-5_60, ISBN 978-3-540-23957-4. Schaal, Stefan; Ijspeert, Auke; Billard, Aude (2003), "Computational approaches to motor learning by imitation", Philosophical Transactions of the Royal Society of London. Series B: Biological Sciences, 358 (1431): 537–547, doi:10.1098/rstb.2002.1258, PMC 1693137, PMID 12689379 Robots that imitate humans, Cynthia Breazeal and Brian Scassellati, Trends in Cognitive Sciences, 6:1, 2002, pp. 481–87 Billard, A, "Imitation", in Arbib, MA (ed.), Handbook of Brain Theory and Neural Networks, MIT Press, pp. 566–69. Schaal, S (1999), "Is imitation learning the route to humanoid robots?", Trends in Cognitive Sciences (PDF). === Special issues in journals === IEEE Transactions on Systems, Man, and Cybernetics, April 2007, 37:2. RSJ Advanced Robotics, vol. 21, number 13. Neural Networks, Elsevier. Robotics & Autonomous Systems (PDF), Elsevier, 2006. === Key laboratories and people === Machine Learning techniques for Robot Programming by Demonstration, Lausanne, VD, CH: EPFL LASA, archived from the original on 2012-05-01. Reinforcement Learning and Learning of Motor Primitives, SC, USA: USC CLMC Lab. Calinon, Sylvain, Interactive teacher-student (trainer/coach-trainee/client) kinesthetic demonstration, CH. Bentivegna, Darrin, Teaching air hockey to a humanoid robot, JP: ATR, archived from the original on 2008-01-27. Community activities on closely related topics Technical Committee on Human-Robot Interaction & Coordination, IEEE Robotics and Automation, archived from the original on 2011-07-26. Technical Committee on Robot Learning, IEEE Robotics and Automation, archived from the original on 2011-07-26. === Videos === A robot that learns to cook an omelet: "Short Version", YouTube, FR. "Long Version", YouTube, FR. A robot that learns to unscrew a bottle of coke: "Unscrew Coke Bottle", YouTube, DE.
https://en.wikipedia.org/wiki/Programming_by_demonstration
An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build such a connection or interface is called an API specification. A computer system that meets this standard is said to implement or expose an API. The term API may refer either to the specification or to the implementation. In contrast to a user interface, which connects a computer to a person, an application programming interface connects computers or pieces of software to each other. It is not intended to be used directly by a person (the end user) other than a computer programmer who is incorporating it into software. An API is often made up of different parts which act as tools or services that are available to the programmer. A program or a programmer that uses one of these parts is said to call that portion of the API. The calls that make up the API are also known as subroutines, methods, requests, or endpoints. An API specification defines these calls, meaning that it explains how to use or implement them. One purpose of APIs is to hide the internal details of how a system works, exposing only those parts a programmer will find useful and keeping them consistent even if the internal details later change. An API may be custom-built for a particular pair of systems, or it may be a shared standard allowing interoperability among many systems. The term API is often used to refer to web APIs, which allow communication between computers that are joined by the internet. There are also APIs for programming languages, software libraries, computer operating systems, and computer hardware. APIs originated in the 1940s, though the term did not emerge until the 1960s and 70s. == Purpose == An API opens a software system to interactions from the outside. It allows two software systems to communicate across a boundary — an interface — using mutually agreed-upon signals. In other words, an API connects software entities together. Unlike a user interface, an API is typically not visible to users. It is an "under the hood" portion of a software system, used for machine-to-machine communication. A well-designed API exposes only objects or actions needed by software or software developers. It hides details that have no use. This abstraction simplifies programming. Building software using APIs has been compared to using building-block toys, such as Lego bricks. Software services or software libraries are analogous to the bricks; they may be joined together via their APIs, composing a new software product. The process of joining is called integration. As an example, consider a weather sensor that offers an API. When a certain message is transmitted to the sensor, it will detect the current weather conditions and reply with a weather report. The message that activates the sensor is an API call, and the weather report is an API response. A weather forecasting app might integrate with a number of weather sensor APIs, gathering weather data from throughout a geographical area. An API is often compared to a contract. It represents an agreement between parties: a service provider who offers the API and the software developers who rely upon it. If the API remains stable, or if it changes only in predictable ways, developers' confidence in the API will increase. This may increase their use of the API. == History of the term == The term API initially described an interface only for end-user-facing programs, known as application programs. This origin is still reflected in the name "application programming interface." Today, the term is broader, including also utility software and even hardware interfaces. The idea of the API is much older than the term itself. British computer scientists Maurice Wilkes and David Wheeler worked on a modular software library in the 1940s for EDSAC, an early computer. The subroutines in this library were stored on punched paper tape organized in a filing cabinet. This cabinet also contained what Wilkes and Wheeler called a "library catalog" of notes about each subroutine and how to incorporate it into a program. Today, such a catalog would be called an API (or an API specification or API documentation) because it instructs a programmer on how to use (or "call") each subroutine that the programmer needs. Wilkes and Wheeler's book The Preparation of Programs for an Electronic Digital Computer contains the first published API specification. Joshua Bloch considers that Wilkes and Wheeler "latently invented" the API, because it is more of a concept that is discovered than invented. The term "application program interface" (without an -ing suffix) is first recorded in a paper called Data structures and techniques for remote computer graphics presented at an AFIPS conference in 1968. The authors of this paper use the term to describe the interaction of an application—a graphics program in this case—with the rest of the computer system. A consistent application interface (consisting of Fortran subroutine calls) was intended to free the programmer from dealing with idiosyncrasies of the graphics display device, and to provide hardware independence if the computer or the display were replaced. The term was introduced to the field of databases by C. J. Date in a 1974 paper called The Relational and Network Approaches: Comparison of the Application Programming Interface. An API became a part of the ANSI/SPARC framework for database management systems. This framework treated the application programming interface separately from other interfaces, such as the query interface. Database professionals in the 1970s observed these different interfaces could be combined; a sufficiently rich application interface could support the other interfaces as well. This observation led to APIs that supported all types of programming, not just application programming. By 1990, the API was defined simply as "a set of services available to a programmer for performing certain tasks" by technologist Carl Malamud. The idea of the API was expanded again with the dawn of remote procedure calls and web APIs. As computer networks became common in the 1970s and 80s, programmers wanted to call libraries located not only on their local computers, but on computers located elsewhere. These remote procedure calls were well supported by the Java language in particular. In the 1990s, with the spread of the internet, standards like CORBA, COM, and DCOM competed to become the most common way to expose API services. Roy Fielding's dissertation Architectural Styles and the Design of Network-based Software Architectures at UC Irvine in 2000 outlined Representational state transfer (REST) and described the idea of a "network-based Application Programming Interface" that Fielding contrasted with traditional "library-based" APIs. XML and JSON web APIs saw widespread commercial adoption beginning in 2000 and continuing as of 2021. The web API is now the most common meaning of the term API. The Semantic Web proposed by Tim Berners-Lee in 2001 included "semantic APIs" that recast the API as an open, distributed data interface rather than a software behavior interface. Proprietary interfaces and agents became more widespread than open ones, but the idea of the API as a data interface took hold. Because web APIs are widely used to exchange data of all kinds online, API has become a broad term describing much of the communication on the internet. When used in this way, the term API has overlap in meaning with the term communication protocol. == Types == === Libraries and frameworks === The interface to a software library is one type of API. The API describes and prescribes the "expected behavior" (a specification) while the library is an "actual implementation" of this set of rules. A single API can have multiple implementations (or none, being abstract) in the form of different libraries that share the same programming interface. The separation of the API from its implementation can allow programs written in one language to use a library written in another. For example, because Scala and Java compile to compatible bytecode, Scala developers can take advantage of any Java API. API use can vary depending on the type of programming language involved. An API for a procedural language such as Lua could consist primarily of basic routines to execute code, manipulate data or handle errors while an API for an object-oriented language, such as Java, would provide a specification of classes and its class methods. Hyrum's law states that "With a sufficient number of users of an API, it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody." Meanwhile, several studies show that most applications that use an API tend to use a small part of the API. Language bindings are also APIs. By mapping the features and capabilities of one language to an interface implemented in another language, a language binding allows a library or service written in one language to be used when developing in another language. Tools such as SWIG and F2PY, a Fortran-to-Python interface generator, facilitate the creation of such interfaces. An API can also be related to a software framework: a framework can be based on several libraries implementing several APIs, but unlike the normal use of an API, the access to the behavior built into the framework is mediated by extending its content with new classes plugged into the framework itself. Moreover, the overall program flow of control can be out of the control of the caller and in the framework's hands by inversion of control or a similar mechanism. === Operating systems === An API can specify the interface between an application and the operating system. POSIX, for example, specifies a set of common APIs that aim to enable an application written for a POSIX conformant operating system to be compiled for another POSIX conformant operating system. Linux and Berkeley Software Distribution are examples of operating systems that implement the POSIX APIs. Microsoft has shown a strong commitment to a backward-compatible API, particularly within its Windows API (Win32) library, so older applications may run on newer versions of Windows using an executable-specific setting called "Compatibility Mode". An API differs from an application binary interface (ABI) in that an API is source code based while an ABI is binary based. For instance, POSIX provides APIs while the Linux Standard Base provides an ABI. === Remote APIs === Remote APIs allow developers to manipulate remote resources through protocols, specific standards for communication that allow different technologies to work together, regardless of language or platform. For example, the Java Database Connectivity API allows developers to query many different types of databases with the same set of functions, while the Java remote method invocation API uses the Java Remote Method Protocol to allow invocation of functions that operate remotely, but appear local to the developer. Therefore, remote APIs are useful in maintaining the object abstraction in object-oriented programming; a method call, executed locally on a proxy object, invokes the corresponding method on the remote object, using the remoting protocol, and acquires the result to be used locally as a return value. A modification of the proxy object will also result in a corresponding modification of the remote object. === Web APIs === Web APIs are the defined interfaces through which interactions happen between an enterprise and applications that use its assets, which also is a Service Level Agreement (SLA) to specify the functional provider and expose the service path or URL for its API users. An API approach is an architectural approach that revolves around providing a program interface to a set of services to different applications serving different types of consumers. When used in the context of web development, an API is typically defined as a set of specifications, such as Hypertext Transfer Protocol (HTTP) request messages, along with a definition of the structure of response messages, usually in an Extensible Markup Language (XML) or JavaScript Object Notation (JSON) format. An example might be a shipping company API that can be added to an eCommerce-focused website to facilitate ordering shipping services and automatically include current shipping rates, without the site developer having to enter the shipper's rate table into a web database. While "web API" historically has been virtually synonymous with web service, the recent trend (so-called Web 2.0) has been moving away from Simple Object Access Protocol (SOAP) based web services and service-oriented architecture (SOA) towards more direct representational state transfer (REST) style web resources and resource-oriented architecture (ROA). Part of this trend is related to the Semantic Web movement toward Resource Description Framework (RDF), a concept to promote web-based ontology engineering technologies. Web APIs allow the combination of multiple APIs into new applications known as mashups. In the social media space, web APIs have allowed web communities to facilitate sharing content and data between communities and applications. In this way, content that is created in one place dynamically can be posted and updated to multiple locations on the web. For example, Twitter's REST API allows developers to access core Twitter data and the Search API provides methods for developers to interact with Twitter Search and trends data. == Design == The design of an API has significant impact on its usage. The principle of information hiding describes the role of programming interfaces as enabling modular programming by hiding the implementation details of the modules so that users of modules need not understand the complexities inside the modules. Thus, the design of an API attempts to provide only the tools a user would expect. The design of programming interfaces represents an important part of software architecture, the organization of a complex piece of software. == Release policies == APIs are one of the more common ways technology companies integrate. Those that provide and use APIs are considered as being members of a business ecosystem. The main policies for releasing an API are: Private: The API is for internal company use only. Partner: Only specific business partners can use the API. For example, vehicle for hire companies such as Uber and Lyft allow approved third-party developers to directly order rides from within their apps. This allows the companies to exercise quality control by curating which apps have access to the API, and provides them with an additional revenue stream. Public: The API is available for use by the public. For example, Microsoft makes the Windows API public, and Apple releases its API Cocoa, so that software can be written for their platforms. Not all public APIs are generally accessible by everybody. For example, Internet service providers like Cloudflare or Voxility, use RESTful APIs to allow customers and resellers access to their infrastructure information, DDoS stats, network performance or dashboard controls. Access to such APIs is granted either by “API tokens”, or customer status validations. === Public API implications === An important factor when an API becomes public is its "interface stability". Changes to the API—for example adding new parameters to a function call—could break compatibility with the clients that depend on that API. When parts of a publicly presented API are subject to change and thus not stable, such parts of a particular API should be documented explicitly as "unstable". For example, in the Google Guava library, the parts that are considered unstable, and that might change soon, are marked with the Java annotation @Beta. A public API can sometimes declare parts of itself as deprecated or rescinded. This usually means that part of the API should be considered a candidate for being removed, or modified in a backward incompatible way. Therefore, these changes allow developers to transition away from parts of the API that will be removed or not supported in the future. Client code may contain innovative or opportunistic usages that were not intended by the API designers. In other words, for a library with a significant user base, when an element becomes part of the public API, it may be used in diverse ways. On February 19, 2020, Akamai published their annual “State of the Internet” report, showcasing the growing trend of cybercriminals targeting public API platforms at financial services worldwide. From December 2017 through November 2019, Akamai witnessed 85.42 billion credential violation attacks. About 20%, or 16.55 billion, were against hostnames defined as API endpoints. Of these, 473.5 million have targeted financial services sector organizations. == Documentation == API documentation describes what services an API offers and how to use those services, aiming to cover everything a client would need to know for practical purposes. Documentation is crucial for the development and maintenance of applications using the API. API documentation is traditionally found in documentation files but can also be found in social media such as blogs, forums, and Q&A websites. Traditional documentation files are often presented via a documentation system, such as Javadoc or Pydoc, that has a consistent appearance and structure. However, the types of content included in the documentation differs from API to API. In the interest of clarity, API documentation may include a description of classes and methods in the API as well as "typical usage scenarios, code snippets, design rationales, performance discussions, and contracts", but implementation details of the API services themselves are usually omitted. It can take a number of forms, including instructional documents, tutorials, and reference works. It'll also include a variety of information types, including guides and functionalities. Restrictions and limitations on how the API can be used are also covered by the documentation. For instance, documentation for an API function could note that its parameters cannot be null, that the function itself is not thread safe. Because API documentation tends to be comprehensive, it is a challenge for writers to keep the documentation updated and for users to read it carefully, potentially yielding bugs. API documentation can be enriched with metadata information like Java annotations. This metadata can be used by the compiler, tools, and by the run-time environment to implement custom behaviors or custom handling. It is possible to generate API documentation in a data-driven manner. By observing many programs that use a given API, it is possible to infer the typical usages, as well the required contracts and directives. Then, templates can be used to generate natural language from the mined data. == Dispute over copyright protection for APIs == In 2010, Oracle Corporation sued Google for having distributed a new implementation of Java embedded in the Android operating system. Google had not acquired any permission to reproduce the Java API, although permission had been given to the similar OpenJDK project. Judge William Alsup ruled in the Oracle v. Google case that APIs cannot be copyrighted in the U.S. and that a victory for Oracle would have widely expanded copyright protection to a "functional set of symbols" and allowed the copyrighting of simple software commands: To accept Oracle's claim would be to allow anyone to copyright one version of code to carry out a system of commands and thereby bar all others from writing its different versions to carry out all or part of the same commands. Alsup's ruling was overturned in 2014 on appeal to the Court of Appeals for the Federal Circuit, though the question of whether such use of APIs constitutes fair use was left unresolved. In 2016, following a two-week trial, a jury determined that Google's reimplementation of the Java API constituted fair use, but Oracle vowed to appeal the decision. Oracle won on its appeal, with the Court of Appeals for the Federal Circuit ruling that Google's use of the APIs did not qualify for fair use. In 2019, Google appealed to the Supreme Court of the United States over both the copyrightability and fair use rulings, and the Supreme Court granted review. Due to the COVID-19 pandemic, the oral hearings in the case were delayed until October 2020. The case was decided by the Supreme Court in Google's favor. == Examples == == See also == == References == == Further reading == Taina Bucher (16 November 2013). "Objects of Intense Feeling: The Case of the Twitter API". Computational Culture (3). ISSN 2047-2390. Argues that "APIs are far from neutral tools" and form a key part of contemporary programming, understood as a fundamental part of culture. What is an API? – in the U.S. Supreme Court opinion, Google v. Oracle 2021, pp. 3–7 – "For each task, there is computer code; API (also known as Application Program Interface) is the method for calling that 'computer code' (instruction – like a recipe – rather than cooking instruction, this is machine instruction) to be carry out" Maury, Innovation and Change – Cory Ondrejka \ February 28, 2014 \ " ...proposed a public API to let computers talk to each other". (Textise URL) == External links == Forrester : IT industry : API Case : Google v. Oracle – May 20, 2021 – content format: Audio with text – length 26:41
https://en.wikipedia.org/wiki/API
In computer science, function-level programming refers to one of the two contrasting programming paradigms identified by John Backus in his work on programs as mathematical objects, the other being value-level programming. In his 1977 Turing Award lecture, Backus set forth what he considered to be the need to switch to a different philosophy in programming language design: Programming languages appear to be in trouble. Each successive language incorporates, with a little cleaning up, all the features of its predecessors plus a few more. [...] Each new language claims new and fashionable features... but the plain fact is that few languages make programming sufficiently cheaper or more reliable to justify the cost of producing and learning to use them. He designed FP to be the first programming language to specifically support the function-level programming style. A function-level program is variable-free (cf. point-free programming), since program variables, which are essential in value-level definitions, are not needed in function-level programs. == Introduction == In the function-level style of programming, a program is built directly from programs that are given at the outset, by combining them with program-forming operations or functionals. Thus, in contrast with the value-level approach that applies the given programs to values to form a succession of values culminating in the desired result value, the function-level approach applies program-forming operations to the given programs to form a succession of programs culminating in the desired result program. As a result, the function-level approach to programming invites study of the space of programs under program-forming operations, looking to derive useful algebraic properties of these program-forming operations. The function-level approach offers the possibility of making the set of programs a mathematical space by emphasizing the algebraic properties of the program-forming operations over the space of programs. Another potential advantage of the function-level view is the ability to use only strict functions and thereby have bottom-up semantics, which are the simplest kind of all. Yet another is the existence of function-level definitions that are not the lifted (that is, lifted from a lower value-level to a higher function-level) image of any existing value-level one: these (often terse) function-level definitions represent a more powerful style of programming not available at the value-level. == Contrast to functional programming == When Backus studied and publicized his function-level style of programming, his message was mostly misunderstood as supporting the traditional functional programming style languages instead of his own FP and its successor FL. Backus calls functional programming applicative programming; his function-level programming is a particular, constrained type. A key distinction from functional languages is that Backus' language has the following hierarchy of types: atoms functions, which take atoms to atoms Higher-order functions (which he calls "functional forms"), which take one or two functions to functions ...and the only way to generate new functions is to use one of the functional forms, which are fixed: you cannot build your own functional form (at least not within FP; you can within FFP (Formal FP)). This restriction means that functions in FP are a module (generated by the built-in functions) over the algebra of functional forms, and are thus algebraically tractable. For instance, the general question of equality of two functions is equivalent to the halting problem, and is undecidable, but equality of two functions in FP is just equality in the algebra, and thus (Backus imagines) easier. Even today, many users of lambda style languages often misinterpret Backus' function-level approach as a restrictive variant of the lambda style, which is a de facto value-level style. In fact, Backus would not have disagreed with the 'restrictive' accusation: he argued that it was precisely due to such restrictions that a well-formed mathematical space could arise, in a manner analogous to the way structured programming limits programming to a restricted version of all the control-flow possibilities available in plain, unrestricted unstructured programs. The value-free style of FP is closely related to the equational logic of a cartesian-closed category. == Example languages == The canonical function-level programming language is FP. Others include FL, and J. == See also == Concatenative programming language Functional programming, declarative programming (compare) Tacit programming Value-level programming, imperative programming (contrast) == References == == External links == Function Level Programs As Mathematical Objects from John Backus From Function Level Semantics to Program Transformation and Optimization SpringerLink see point 1.2 and 1.3 Closed applicative languages, FP and FL, in John W. Backus (Publications) or the original Programming Language Semantics and Closed Applicative Languages Instance variables, a way out of the variable abstinence
https://en.wikipedia.org/wiki/Function-level_programming
Strip programming or stripping is a technique used for scheduling television and radio programming to ensure consistency and coherency. Television or radio programs of a particular style (such as a television series) are given a regular daily time slot during the week, so that it appears as a strip straight across the weekly schedule. For example, radio and television broadcasters may program a news program at rush hours every day, or at least every weekday. Strip programming is used to deliver consistent content to targeted audiences. Broadcasters know or predict the times at which certain demographics will be listening to or watching their programs and play them at that time. Most television dayparts outside of prime time use strip programming five days a week (with some selected programs also being stripped on one or both days of the weekend), with the same programs being broadcast every day at the same time to target specific demographics. Strip programming is sometimes criticized as making programming too predictable, and reducing diversity and uniqueness. == Overview == Strip scheduling often applies to any program that airs on multiple consecutive days during the calendar week (most commonly Monday through Friday), whether carried through a television network (such as with a talk show, news program, soap opera, or telenovela) or in syndication. It is commonly restricted to describing the airing of television programs that were originally broadcast on a weekly basis during their original run: The West Wing could be stripped but not Jeopardy!, as Jeopardy! was originally intended to be run daily. It can also refer to shows in prime time that run daily, such as with the short-lived The Jay Leno Show in 2009 and 2010. For much of the 1960s and into the early 1990s, stripping for syndication was one of, if not the primary profit component of the studio production model in American television. A show became far more profitable if it succeeded in getting three full U.S. seasons (about 75 episodes) or more, as then it was possible to strip it for fifteen weeks (15×5=75) before needing to repeat episodes. Once a series attained five seasons (which would push the show over the 100 episodes threshold), it would be a full six months before it would repeat. For Star Trek, in particular, this was relevant. Only due to an unprecedented letter-writing campaign was the show renewed for its third season, and it did not begin to attain wider popularity until appearing in syndication for a number of years. If it had failed to be renewed for a third season, it would not have been syndicated, and its subsequent popularity and influence would likely not have occurred. Many other shows with lukewarm response in their initial runs became widely appreciated cult favorites as a result of syndication, or helped keep cultural memes associated with them far more widely known than if the shows had only been viewable during their initial time frame. Michael Grade was responsible for introducing stripped and stranded schedules to the BBC's television service in the United Kingdom in his role as controller of BBC1: from February 18, 1985, onward, the weekday evening schedule has consisted almost entirely of half-hour or hour-long programs starting on the hour, or half-hour (the BBC channels never carried spot advertising). For example, Grade's new schedule provided at 19:00, the talk show Wogan thrice weekly and two episodes of EastEnders and fixed the national news at 18:00 and 21:00, and regional news at 18:30. Before this date, programs might start at almost any time and programs could have different times on consecutive weeks or even days, for example: Compare with a 2007 schedule for the same channel: Stripping has also become an even more common practice on many British channels since the introduction of multi-channel cable and satellite television in the 1990s. In many other countries, new episodes of various series are aired every weekday. For example, if such a station gets the most recent season of a television series originating from the United States, the episodes will air in this way for two or three weeks, after which they are replaced by another show in the same timeslot. In Australia, Network Ten and its sister station Eleven have stripped The Simpsons for many years, airing the show daily at 6:00 p.m., which is traditionally the news hour on rivals Seven Network and Nine Network. Despite some attempts to fill this slot with original programming, The Simpsons stripped at 6:00 p.m. remained a mainstay of Australian television, only ending when CBS Corporation took control of Ten and Eleven in 2017 and ended their output deal with 20th Century Fox Television; 7mate now carries it in various timeslots. == References ==
https://en.wikipedia.org/wiki/Strip_programming
In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types, functions, and other entities in source code and documentation. Reasons for using a naming convention (as opposed to allowing programmers to choose any character sequence) include the following: To reduce the effort needed to read and understand source code; To enable code reviews to focus on issues more important than syntax and naming standards. To enable code quality review tools to focus their reporting mainly on significant issues other than syntax and style preferences. The choice of naming conventions can be a controversial issue, with partisans of each holding theirs to be the best and others to be inferior. Colloquially, this is said to be a matter of dogma. Many companies have also established their own set of conventions. == Potential benefits == Benefits of a naming convention can include the following: to provide additional information (i.e., metadata) about the use to which an identifier is put; to help formalize expectations and promote consistency within a development team; to enable the use of automated refactoring or search and replace tools with minimal potential for error; to enhance clarity in cases of potential ambiguity; to enhance the aesthetic and professional appearance of work product (for example, by disallowing overly long names, comical or "cute" names, or abbreviations); to help avoid "naming collisions" that might occur when the work product of different organizations is combined (see also: namespaces); to provide meaningful data to be used in project handovers which require submission of program source code and all relevant documentation; to provide better understanding in case of code reuse after a long interval of time. == Challenges == The choice of naming conventions (and the extent to which they are enforced) is often a contentious issue, with partisans holding their viewpoint to be the best and others to be inferior. Moreover, even with known and well-defined naming conventions in place, some organizations may fail to consistently adhere to them, causing inconsistency and confusion. These challenges may be exacerbated if the naming convention rules are internally inconsistent, arbitrary, difficult to remember, or otherwise perceived as more burdensome than beneficial. == Readability == Well-chosen identifiers make it significantly easier for developers and analysts to understand what the system is doing and how to fix or extend the source code to apply for new needs. For example, although is syntactically correct, its purpose is not evident. Contrast this with: which implies the intent and meaning of the source code, at least to those familiar with the context of the statement. Experiments suggest that identifier style affects recall and precision and that familiarity with a style speeds recall. == Common elements == The exact rules of a naming convention depend on the context in which they are employed. Nevertheless, there are several common elements that influence most if not all naming conventions in common use today. === Length of identifiers === Fundamental elements of all naming conventions are the rules related to identifier length (i.e., the finite number of individual characters allowed in an identifier). Some rules dictate a fixed numerical bound, while others specify less precise heuristics or guidelines. Identifier length rules are routinely contested in practice, and subject to much debate academically. Some considerations: shorter identifiers may be preferred as more expedient, because they are easier to type (although many IDEs and text-editors provide text-completion, which mitigates this) extremely short identifiers (such as 'i' or 'j') are very difficult to uniquely distinguish using automated search and replace tools (although this is not an issue for regex-based tools) longer identifiers may be preferred because short identifiers cannot encode enough information or appear too cryptic longer identifiers may be disfavored because of visual clutter It is an open research issue whether some programmers prefer shorter identifiers because they are easier to type, or think up, than longer identifiers, or because in many situations a longer identifier simply clutters the visible code and provides no perceived additional benefit. Brevity in programming could be in part attributed to: early linkers which required variable names to be restricted to 6 characters to save memory. A later "advance" allowed longer variable names to be used for human comprehensibility, but where only the first few characters were significant. In some versions of BASIC such as TRS-80 Level 2 Basic, long names were allowed, but only the first two letters were significant. This feature permitted erroneous behaviour that could be difficult to debug, for example when names such as "VALUE" and "VAT" were used and intended to be distinct. early source code editors lacking autocomplete early low-resolution monitors with limited line length (e.g. only 80 characters) much of computer science originating from mathematics, where variable names are traditionally only a single letter === Letter case and numerals === Some naming conventions limit whether letters may appear in uppercase or lowercase. Other conventions do not restrict letter case, but attach a well-defined interpretation based on letter case. Some naming conventions specify whether alphabetic, numeric, or alphanumeric characters may be used, and if so, in what sequence. === Multiple-word identifiers === A common recommendation is "Use meaningful identifiers." A single word may not be as meaningful, or specific, as multiple words. Consequently, some naming conventions specify rules for the treatment of "compound" identifiers containing more than one word. As most programming languages do not allow whitespace in identifiers, a method of delimiting each word is needed (to make it easier for subsequent readers to interpret which characters belong to which word). Historically some early languages, notably FORTRAN (1955) and ALGOL (1958), allowed spaces within identifiers, determining the end of identifiers by context. This was abandoned in later languages due to the difficulty of tokenization. It is possible to write names by simply concatenating words, and this is sometimes used, as in mypackage for Java package names, though legibility suffers for longer terms, so usually some form of separation is used. ==== Delimiter-separated words ==== One approach is to delimit separate words with a non-alphanumeric character. The two characters commonly used for this purpose are the hyphen ("-") and the underscore ("_"); e.g., the two-word name "two words" would be represented as "two-words" or "two_words". The hyphen is used by nearly all programmers writing COBOL (1959), Forth (1970), and Lisp (1958); it is also common in Unix for commands and packages, and is used in CSS. This convention has no standard name, though it may be referred to as lisp-case or COBOL-CASE (compare Pascal case), kebab-case, brochette-case, or other variants. Of these, kebab-case, dating at least to 2012, has achieved some currency since. By contrast, languages in the FORTRAN/ALGOL tradition, notably languages in the C and Pascal families, used the hyphen for the subtraction infix operator, and did not wish to require spaces around it (as free-form languages), preventing its use in identifiers. An alternative is to use underscores; this is common in the C family (including Python), with lowercase words, being found for example in The C Programming Language (1978), and has come to be known as snake case or snail case. Underscores with uppercase, as in UPPER_CASE, are commonly used for C preprocessor macros, hence known as MACRO_CASE, and for environment variables in Unix, such as BASH_VERSION in bash. Sometimes this is humorously referred to as SCREAMING_SNAKE_CASE (alternatively SCREAMING_SNAIL_CASE). ==== Letter case-separated words ==== Another approach is to indicate word boundaries using medial capitalization, called "camelCase", "PascalCase", and many other names, thus respectively rendering "two words" as "twoWords" or "TwoWords". This convention is commonly used in Pascal, Java, C#, and Visual Basic. Treatment of initialisms in identifiers (e.g. the "XML" and "HTTP" in XMLHttpRequest) varies. Some dictate that they be lowercase (e.g. XmlHttpRequest) to ease typing, readability and ease of segmentation, whereas others leave them uppercased (e.g. XMLHTTPRequest) for accuracy. ==== Examples of multiple-word identifier formats ==== == Metadata and hybrid conventions == Some naming conventions represent rules or requirements that go beyond the requirements of a specific project or problem domain, and instead reflect a greater overarching set of principles defined by the software architecture, underlying programming language or other kind of cross-project methodology. === Hungarian notation === Perhaps the most well-known is Hungarian notation, which encodes either the purpose ("Apps Hungarian") or the type ("Systems Hungarian") of a variable in its name. For example, the prefix "sz" for the variable szName indicates that the variable is a null-terminated string. === Positional notation === A style used for very short (eight characters and less) could be: LCCIIL01, where LC would be the application (Letters of Credit), C for COBOL, IIL for the particular process subset, and the 01 a sequence number. This sort of convention is still in active use in mainframes dependent upon JCL and is also seen in the 8.3 (maximum eight characters with period separator followed by three character file type) MS-DOS style. === Composite word scheme (OF Language) === IBM's "OF Language" was documented in an IMS (Information Management System) manual. It detailed the PRIME-MODIFIER-CLASS word scheme, which consisted of names like "CUST-ACT-NO" to indicate "customer account number". PRIME words were meant to indicate major "entities" of interest to a system. MODIFIER words were used for additional refinement, qualification and readability. CLASS words ideally would be a very short list of data types relevant to a particular application. Common CLASS words might be: NO (number), ID (identifier), TXT (text), AMT (amount), QTY (quantity), FL (flag), CD (code), W (work) and so forth. In practice, the available CLASS words would be a list of less than two dozen terms. CLASS words, typically positioned on the right (suffix), served much the same purpose as Hungarian notation prefixes. The purpose of CLASS words, in addition to consistency, was to specify to the programmer the data type of a particular data field. Prior to the acceptance of BOOLEAN (two values only) fields, FL (flag) would indicate a field with only two possible values. == Language-specific conventions == === ActionScript === Adobe's Coding Conventions and Best Practices suggests naming standards for ActionScript that are mostly consistent with those of ECMAScript. The style of identifiers is similar to that of Javascript. === Ada === In Ada, the only recommended style of identifiers is Mixed_Case_With_Underscores. === APL === In APL dialects, the delta (Δ) is used between words, e.g. PERFΔSQUARE (no lowercase traditionally existed in older APL versions). If the name used underscored letters, then the delta underbar (⍙) would be used instead. === C and C++ === In C and C++, keywords and standard library identifiers are mostly lowercase. In the C standard library, abbreviated names are the most common (e.g. isalnum for a function testing whether a character is alphanumeric), while the C++ standard library often uses an underscore as a word separator (e.g. out_of_range). Identifiers representing macros are, by convention, written using only uppercase letters and underscores, for example NULL and EINVAL (this is related to the convention in many programming languages of using all-upper-case identifiers for constants). Names containing double underscore or beginning with an underscore and a capital letter are reserved for implementation (compiler, standard library) and should not be used (e.g. __reserved or _Reserved). This is superficially similar to stropping, but the semantics differ: the underscores are part of the value of the identifier, rather than being quoting characters (as is stropping): the value of __foo is __foo (which is reserved), not foo (but in a different namespace). === C# === C# naming conventions generally follow the guidelines published by Microsoft for all .NET languages (see the .NET section, below), but no conventions are enforced by the C# compiler. The Microsoft guidelines recommend the exclusive use of only PascalCase and camelCase, with the latter used only for method parameter names and method-local variable names (including method-local const values). A special exception to PascalCase is made for two-letter acronyms that begin an identifier; in these cases, both letters are capitalized (for example, IOStream); this is not the case for longer acronyms (for example, XmlStream). The guidelines further recommend that the name given to an interface be PascalCase preceded by the capital letter I, as in IEnumerable. The Microsoft guidelines for naming fields are specific to static, public, and protected fields; fields that are not static and that have other accessibility levels (such as internal and private) are explicitly not covered by the guidelines. The most common practice is to use PascalCase for the names of all fields, except for those which are private (and neither const nor static), which are given names that use camelCase preceded by a single underscore; for example, _totalCount. Any identifier name may be prefixed by the commercial-at symbol (@), without any change in meaning. That is, both factor and @factor refer to the same object. By convention, this prefix is only used in cases when the identifier would otherwise be either a reserved keyword (such as for and while), which may not be used as an identifier without the prefix, or a contextual keyword (such as from and where), in which cases the prefix is not strictly required (at least not at its declaration; for example, although the declaration dynamic dynamic; is valid, this would typically be seen as dynamic @dynamic; to indicate to the reader immediately that the latter is a variable name). === Dart/Flutter === In the Dart language, used in the Flutter SDK, the conventions are similar to those of Java, except that constants are written in lowerCamelCase. Dart imposes the syntactic rule that non-local identifiers beginning with an underscore (_) are treated as private (since the language does not have explicit keywords for public or private access). Additionally, source file names do not follow Java's "one public class per source file, name must match" rule, instead using snake_case for filenames. === Go === In Go, the convention is to use MixedCaps or mixedCaps rather than underscores to write multiword names. When referring to structs or functions, the first letter specifies the visibility for external packages. Making the first letter uppercase exports that piece of code, while lowercase makes it only usable within the current scope. === Java === In Java, naming conventions for identifiers have been established and suggested by various Java communities such as Sun Microsystems, Netscape, AmbySoft, etc. A sample of naming conventions set by Sun Microsystems are listed below, where a name in "CamelCase" is one composed of a number of words joined without spaces, with each word's -- excluding the first word's -- initial letter in capitals – for example "camelCase". Java compilers do not enforce these rules, but failing to follow them may result in confusion and erroneous code. For example, widget.expand() and Widget.expand() imply significantly different behaviours: widget.expand() implies an invocation to method expand() in an instance named widget, whereas Widget.expand() implies an invocation to static method expand() in class Widget. One widely used Java coding style dictates that UpperCamelCase be used for classes and lowerCamelCase be used for instances and methods. Recognising this usage, some IDEs, such as Eclipse, implement shortcuts based on CamelCase. For instance, in Eclipse's content assist feature, typing just the upper-case letters of a CamelCase word will suggest any matching class or method name (for example, typing "NPE" and activating content assist could suggest NullPointerException). Initialisms of three or more letters are CamelCase instead of uppercase (e.g., parseDbmXmlFromIPAddress instead of parseDBMXMLFromIPAddress). One may also set the boundary at two or more letters (e.g. parseDbmXmlFromIpAddress). === JavaScript === The built-in JavaScript libraries use the same naming conventions as Java. Data types and constructor functions use upper camel case (RegExp, TypeError, XMLHttpRequest, DOMObject) and methods use lower camel case (getElementById, getElementsByTagNameNS, createCDATASection). In order to be consistent most JavaScript developers follow these conventions. See also: Douglas Crockford's conventions === Lisp === Common practice in most Lisp dialects is to use dashes to separate words in identifiers, as in with-open-file and make-hash-table. Dynamic variable names conventionally start and end with asterisks: *map-walls*. Constants names are marked by plus signs: +map-size+. === .NET === Microsoft .NET recommends UpperCamelCase, also known as PascalCase, for most identifiers. (lowerCamelCase is recommended for parameters and variables) and is a shared convention for the .NET languages. Microsoft further recommends that no type prefix hints (also known as Hungarian notation) are used. Instead of using Hungarian notation it is recommended to end the name with the base class' name; LoginButton instead of BtnLogin. === Objective-C === Objective-C has a common coding style that has its roots in Smalltalk . Top-level entities, including classes, protocols, categories, as well as C constructs that are used in Objective-C programs like global variables and functions, are in UpperCamelCase with a short all-uppercase prefix denoting namespace, like NSString, UIAppDelegate, NSApp or CGRectMake. Constants may optionally be prefixed with a lowercase letter "k" like kCFBooleanTrue. Instance variables of an object use lowerCamelCase prefixed with an underscore, like _delegate and _tableView. Method names use multiple lowerCamelCase parts separated by colons that delimit arguments, like: application:didFinishLaunchingWithOptions:, stringWithFormat: and isRunning. === Pascal, Modula-2 and Oberon === Wirthian languages Pascal, Modula-2 and Oberon generally use Capitalized or UpperCamelCase identifiers for programs, modules, constants, types and procedures, and lowercase or lowerCamelCase identifiers for math constants, variables, formal parameters and functions. While some dialects support underscore and dollar signs in identifiers, snake case and macro case is more likely confined to use within foreign API interfaces. === Perl === Perl takes some cues from its C heritage for conventions. Locally scoped variables and subroutine names are lowercase with infix underscores. Subroutines and variables meant to be treated as private are prefixed with an underscore. Package variables are title cased. Declared constants are all caps. Package names are camel case excepting pragmata—e.g., strict and mro—which are lowercase. === PHP === PHP recommendations are contained in PSR-1 (PHP Standard Recommendation 1) and PSR-12. According to PSR-1, class names should be in PascalCase, class constants should be in MACRO_CASE, and function and method names should be in camelCase. === Python and Ruby === Python and Ruby both recommend UpperCamelCase for class names, CAPITALIZED_WITH_UNDERSCORES for constants, and snake_case for other names. In Python, if a name is intended to be "private", it is prefixed by one or two underscores. Private variables are enforced in Python only by convention. Names can also be suffixed with an underscore to prevent conflict with Python keywords. Prefixing with double underscores changes behaviour in classes with regard to name mangling. Prefixing and suffixing with double underscores - the so-called "dunder" ("double under") methods in Python - are reserved for "magic names" which fulfill special behaviour in Python objects. === R === While there is no official style guide for R, the tidyverse style guide from R-guru Hadley Wickham sets the standard for most users. This guide recommends using only numbers, lowercase letters and underscores for file, variable and function names e.g. fit_models.R. The Bioconductor style guide recommends UpperCamelCase for class names and lowerCamelCase for variable and function names. Its predecessors S and S-PLUS did not allow underscores in variable and function names, but instead used the period as a delimiter. As a result, many base functions in R still have a period as delimiter e.g. as.data.frame(). Hidden objects can be created with the dot prefix e.g. .hidden_object. These objects do not appear in the global environment. The dot prefix is often used by package developers for functions that are purely internal and are not supposed to be used by end users. It is similar to the underscore prefix in Python. === Raku === Raku follows more or less the same conventions as Perl, except that it allows an infix hyphen - or an apostrophe ' (or single quote) within an identifier (but not two in a row), provided that it is followed by an alphabetic character. Raku programmers thus often use kebab case in their identifiers; for example, fish-food and don't-do-that are valid identifiers. === Rust === Rust recommends UpperCamelCase for type aliases and struct, trait, enum, and enum variant names, SCREAMING_SNAKE_CASE for constants or statics and snake_case for variable, function and struct member names. === Swift === Swift has shifted its naming conventions with each individual release. However a major update with Swift 3.0 stabilised the naming conventions for lowerCamelCase across variables and function declarations. Constants are usually defined by enum types or constant parameters that are also written this way. Class and other object type declarations are UpperCamelCase. As of Swift 3.0 there have been made clear naming guidelines for the language in an effort to standardise the API naming and declaration conventions across all third party APIs. == See also == Category:Naming conventions Checkstyle Coding conventions List of tools for static code analysis Namespace Naming convention Sigil (computer programming) Syntax (programming languages) == References == == External links == coding-guidelines.com has a pdf that uses linguistics and psychology to attempt a cost/benefit analysis of identifier naming issues
https://en.wikipedia.org/wiki/Naming_convention_(programming)
Dryad was a research project at Microsoft Research for a general purpose runtime for execution of data parallel applications. The research prototypes of the Dryad and DryadLINQ data-parallel processing frameworks are available in source form at GitHub. == Overview == Microsoft made several preview releases of this technology available as add-ons to Windows HPC Server 2008 R2. An application written for Dryad is modeled as a directed acyclic graph (DAG). The DAG defines the dataflow of the application, and the vertices of the graph defines the operations that are to be performed on the data. The "computational vertices" are written using sequential constructs, devoid of any concurrency or mutual exclusion semantics. The Dryad runtime parallelizes the dataflow graph by distributing the computational vertices across various execution engines (which can be multiple processor cores on the same computer or different physical computers connected by a network, as in a cluster). Scheduling of the computational vertices on the available hardware is handled by the Dryad runtime, without any explicit intervention by the developer of the application or administrator of the network. The flow of data between one computational vertex to another is implemented by using communication "channels" between the vertices, which in physical implementation is realized by TCP/IP streams, shared memory or temporary files. A stream is used at runtime to transport a finite number of structured Items. Dryad defines a domain-specific language, which is implemented via a C++ library, that is used to create and model a Dryad execution graph. Computational vertices are written using standard C++ constructs. To make them accessible to the Dryad runtime, they must be encapsulated in a class that inherits from the GraphNode base class. The graph is defined by adding edges; edges are added by using a composition operator (defined by Dryad) that connects two graphs (or two nodes of a graph) with an edge. Managed code wrappers for the Dryad API can also be written. There exist several high-level language compilers which use Dryad as a runtime; examples include Scope (Structured Computations Optimized for Parallel Execution) and DryadLINQ. In October 2011, Microsoft discontinued active development on Dryad, shifting focus to the Apache Hadoop framework. == References == == Further reading == "Dryad: Distributed Data-Parallel Programs from Sequential Building Blocks" (PDF). Microsoft Research. Retrieved 2007-12-04. "SCOPE: Easy and Efficient Parallel Processing of Massive Data Sets" (PDF). Microsoft Research. Retrieved 2009-01-21. == External links == Dryad: Programming the Data Center Archived 2007-09-12 at the Wayback Machine Dryad Home Video of Michael Isard explaining Dryad at Google
https://en.wikipedia.org/wiki/Dryad_(programming)
This is a list of television programs broadcast by Nickelodeon in the United States. The channel was first tested on December 1, 1977, as an experimental local channel in Columbus, Ohio. On April 1, 1979, the channel expanded into a national network named Nickelodeon. The first program broadcast on Nickelodeon was Pinwheel, a preschool series created by Dr. Vivian Horner, who also conceived the idea for the channel itself. At its launch, Nickelodeon was commercial-free and mainly featured educational shows. By 1984, the channel began accepting traditional commercials and introduced more entertainment-focused programming. In January 1988, the network launched a weekday morning block for preschoolers called Nick Jr., which carried Pinwheel and other educational series. Around the same time, Nickelodeon began investing in original animated shows, which premiered in 1991 under the "Nicktoons" branding. Since then, the channel has consistently aired a mix of original live-action and animated titles. == Current programming == === Original programming === ==== Animated ==== ==== Programming from Paramount+ ==== ==== Live-action ==== ===== Comedy ===== ===== News and sports ===== ==== Preschool series ==== ==== Programming from Paramount+ ==== ==== Specials ==== ==== Educational series ==== === Acquired programming === ==== Animated ==== ==== Preschool series ==== == Upcoming programming == === Original programming === ==== Animated ==== ==== Live-action ==== ===== Comedy ===== ==== Preschool series ==== === Acquired programming === ==== Preschool series ==== == Former programming == === Original programming === ==== Animated ==== ==== Live-action ==== ===== Comedy ===== ===== Drama ===== ===== Game shows ===== ===== Variety programs ===== ==== Programming from Paramount+ ==== ==== Preschool ==== ===== Animated preschool series ===== ===== Live-action preschool series ===== ==== Programming from Noggin ==== ==== Miniseries/other ==== === Former acquired programming === ==== Former acquired animated series ==== ==== Former acquired live-action comedy series ==== ==== Former acquired action series ==== ==== Former acquired reality series ==== American Ninja Warrior (2019) ==== Former acquired drama series ==== ==== Former acquired variety series ==== ==== Former acquired preschool series ==== == Programming blocks == === Seasonal programming blocks === == See also == Nick on CBS List of programs broadcast by Nick at Nite List of programs broadcast by Nicktoons List of programs broadcast by Noggin List of programs broadcast by TeenNick List of programs broadcast by the Nick Jr. Channel List of Nickelodeon Animation Studio productions List of Nickelodeon original films List of Nickelodeon short films == Notes == == References ==
https://en.wikipedia.org/wiki/List_of_programs_broadcast_by_Nickelodeon
ESPN (an initialism of their original name, which was the Entertainment and Sports Programming Network) is an American international basic cable sports channel owned by the Walt Disney Company (80% and operational control) and Hearst Communications (20%) through the joint venture ESPN Inc. The company was founded in 1979 by Bill Rasmussen, Scott Rasmussen and Ed Eagan. ESPN broadcasts primarily from studio facilities located in Bristol, Connecticut. The network also operates offices and auxiliary studios in Miami, Orlando, New York City, Las Vegas, Seattle, Charlotte, Washington, D.C., and Los Angeles. James Pitaro has been chairman since March 5, 2018, following the resignation of John Skipper on December 18, 2017. As of December 2023, ESPN is available to approximately 70 million pay television households in the United States—down from its 2011 peak of 100 million households. It operates regional channels in Africa, Australia, Latin America, and the Netherlands. In Canada, it owns a 20% interest in The Sports Network (TSN) and its five sister networks. Despite the network's success, criticism of ESPN includes accusations of biased coverage. == History == === Background and Launch === Bill Rasmussen came up with the concept of ESPN in May 1978, after he was fired from his job with the World Hockey Association's New England Whalers. Rasmussen and his ESPN co-founder Ed Eagan, joined by Rasmussen's son Scott (who had also been let go by the Whalers), first rented office space in Plainville, Connecticut. However, the plan to base ESPN there was put on hold because of a local ordinance prohibiting buildings from bearing rooftop satellite dishes. Available land to build their own facility on was quickly found in Bristol, Connecticut (where the channel remains headquartered to this day), with funding to buy the property provided by Getty Oil, which purchased 85% of the company from Bill Rasmussen on February 22, 1979, in an attempt to diversify the company's holdings. This helped the credibility of the fledgling company; however, there were still many doubters about the viability of their sports channel concept. Another event that helped build ESPN's credibility was securing an advertising agreement with Anheuser-Busch in the spring of 1979; the company invested $1 million to be the "exclusive beer advertised on the network". ESPN launched on September 7, 1979, beginning with the first telecast of what would become the channel's flagship program, SportsCenter. Taped in front of a small live audience inside the Bristol studios, it was broadcast to 1.4 million cable subscribers throughout the United States. One month after launch, Chris Berman joined the network; he would continue to be an on-air fixture for decades. === 1980s to 2000s === ESPN's next big step forward came when the channel acquired the rights to broadcast coverage of the early rounds of the NCAA Division I men's basketball tournament. It first aired its games in March 1980, helping bring attention to what is today known as "March Madness". The channel's tournament coverage also launched the broadcasting career of Dick Vitale, who at the time he joined ESPN had just been fired as head coach of the Detroit Pistons. In April of that year ESPN began televising the NFL draft, bringing it also to a mass audience and over time creating a television "event". That same month the network began broadcasting Top Rank Boxing on ESPN, marking the beginning of its involvement with televised professional boxing. The show lasted 16 years, and ESPN has since shown boxing live intermittently with other shows including ESPN Friday Night Fights and others. For a period during the 1980s, the network had boxing tournaments, crowning champions in different boxing weight divisions as "ESPN champions". The next major stepping stone for ESPN came throughout a couple of months in 1984. During this period, the American Broadcasting Company (ABC) purchased 100% of ESPN from the Rasmussens and Getty Oil. Under Getty ownership, the channel was unable to compete for the television rights to major sports events contracts as its majority corporate parent would not provide the funding, leading ESPN to lose out for broadcast deals with the National Hockey League (to USA Network) and NCAA Division I college football (to TBS). For years, the NFL, NBA, and Major League Baseball refused to consider cable as a means of broadcasting some of their games. However, with the backing of ABC, ESPN's ability to compete for major sports contracts greatly increased, and gave it credibility within the sports broadcasting industry. Later that year, the U.S. Supreme Court ruled in NCAA v. Board of Regents of the University of Oklahoma (1984) that the NCAA could no longer monopolize the rights to negotiate the contracts for college football games, allowing each school to negotiate broadcast deals on their own. ESPN took full advantage and began to broadcast a large number of NCAA football games, creating an opportunity for fans to be able to view multiple games each weekend (instead of just one), the same deal that the NCAA had previously negotiated with TBS. ESPN's breakthrough moment occurred in 1987 when it secured a contract with the NFL to broadcast eight games during that year's regular season – all of which aired on Sunday nights, marking the first broadcasts of Sunday NFL primetime games. ESPN's Sunday Night Football games would become the highest-rated NFL telecasts for the next 17 years (before losing the rights to NBC in 2006). The channel's decision to broadcast NFL games on Sunday evenings resulted in a decline in viewership for the daytime games shown on the major broadcast networks, marking the first time that ESPN had been a legitimate competitor to NBC and CBS, which had long dominated the sports television market. In 1992, ESPN launched ESPN Radio, a national sports talk radio network providing analysis and commentary programs (including shows such as Mike and Mike in the Morning and The Herd) as well as audio play-by-play of sporting events (including some simulcast with the ESPN television channel). On October 10, 1993, ESPN2 – a secondary channel that originally was programmed with a separate lineup of niche sports popular with males 18–49 years old (with snowboarding and the World Series of Poker as its headliners) as well as serving as an overflow channel for ESPN – launched on cable systems reaching to 10 million subscribers. It became the fastest-growing cable channel in the U.S. during the 1990s, eventually expanding its national reach to 75 million subscribers. Ownership of ABC, and thus control of ESPN, was acquired by Capital Cities Communications in 1985. ESPN's parent company renamed themselves as Capital Cities/ABC Inc. Capital Cities/ABC Inc. was then acquired by the Walt Disney Company in 1996 and was re-branded as Walt Disney Television. === 2000s === Challenges began to appear in the 2000s. ESPN began to shed viewers, more than 10 million over a period of several years in the 2010s even while paying large sums of money for the broadcast rights to properties like the NFL, NBA and College Football Playoff. On April 26, 2017, approximately 100 ESPN employees were notified that their positions with the sports network had been terminated, among them athletes-turned-analysts Trent Dilfer and Danny Kanell, and noted journalists like NFL beat reporter Ed Werder and Major League Baseball expert Jayson Stark. Further cost-cutting measures taken included moving the studio operations of ESPNU to Bristol from Charlotte, North Carolina, reducing its longtime MLB studio show Baseball Tonight to Sundays as a lead-in to the primetime game and adding the MLB Network-produced Intentional Talk to ESPN2's daily lineup. On April 12, 2018, ESPN began a supplemental over-the-top streaming service known as ESPN+. After having last carried national-televised NHL games in 2004, ESPN and ABC agreed in March 2021 on a seven-year contract to televise games, with some airing on ESPN+ and Hulu. The contract also awarded four of the seven Stanley Cup Finals to both ESPN and ABC. All other nationally televised games would air on TBS and TNT under a separate deal the league struck with Turner Sports the following month. On August 8, 2023, ESPN and Penn Entertainment announced a deal to brand Penn's sportsbooks with ESPN branding. Penn's existing Barstool Sportsbook would be rebranded as ESPN Bet in late-2023. On February 6, 2024, ESPN announced a joint venture with Fox Sports and TNT Sports known as Venu Sports, including the three organizations' main linear sports channels and associated media rights. It was originally planned to launch in fall 2024. However, following legal issues (including an antitrust lawsuit by FuboTV), the service was ultimately cancelled. In May 2025, ESPN announced that it would officially launch an ESPN-branded direct-to-consumer product later that year, which will incorporate ESPN's main channels and content from ESPN+, and become the main streaming offering for all ESPN subscribers. == Programming == Alongside its live sports broadcasts, ESPN also airs a variety of sports highlight, talk, and documentary-styled shows. These include: Around the Horn – Competitive debating between four sports writers across the country College GameDay (basketball) – Weekly college basketball show airing from the Saturday Primetime game of the week site College GameDay (football) – Weekly college football preview show airing from the site of a major college football game E:60 – An investigative newsmagazine program focusing on American and international sports First Take – A daily morning talk show with Stephen A. Smith and Molly Qerim (moved from ESPN2 on January 3, 2017) Get Up! – A daily morning show, focusing on the previous night's game results and the burning sports issues of the day Monday Night Countdown – Weekly recap show aired on Monday evenings during the NFL season, also serves as the pre-game show for Monday Night Football Pardon the Interruption – A daily afternoon talk show where Tony Kornheiser and Michael Wilbon debate an array of sports topics SportsCenter – The flagship program of ESPN, a daily sports news program delivering the latest sports news and highlights Sunday NFL Countdown – Weekly preview show that airs on Sunday mornings during the NFL season The Pat McAfee Show – A daily afternoon talk show with news, opinion, and analysis Many of ESPN's documentary programs (such as 30 for 30 and Nine for IX) are produced by ESPN Films, a film division created in March 2008 as a restructuring of ESPN Original Entertainment, a programming division that was originally formed in 2001. 30 for 30 started airing in 2009 and continues airing to this day. Each episode is through the eyes of a well known filmmaker and has featured some of the biggest directors in Hollywood. The 30 for 30 film O.J.: Made in America won the Academy Award for Best Documentary Feature in 2017, the first such Oscar for ESPN. Ultimate Fighting Championship signed a five-year contract with ESPN starting 2019 on ESPN and ESPN+ which estimate every quarter 2 event on UFC on ESPN and 6 events on UFC Fight Night on ESPN+. In March 2019, ESPN announced a new betting-themed daily program, Daily Wager, hosted by the network's gambling analyst Doug Kezirian. The program was ESPN's first regularly scheduled program solely dedicated to gaming-related content. On May 14, 2019, ESPN announced a deal with casino operator Caesars Entertainment to establish an ESPN-branded studio at The LINQ Hotel & Casino in Las Vegas to produce betting-themed content. In order to help offset the impact of COVID-19 on its business, Walt Disney CEO Bob Chapek indicated during a 4th quarter fiscal year 2021 earnings conference that the company would increase its presence in online sports betting, including in partnership with third parties. In 2023, The Pat McAfee Show moved to ESPN as part of a five-year $85 million deal. The show replaced the Noon ET airing of SportsCenter and This Just In with Max Kellerman. == Related channels == === ESPN on ABC === Since September 2006, ESPN has been integrated with the sports division of sister broadcast network ABC, with sports events televised on that network airing under the banner ESPN on ABC; much of ABC's sports coverage since the rebranding has become increasingly limited to secondary coverage of sporting events whose broadcast rights are held by ESPN (such as NBA games, NHL games, and the X Games and its related qualifying events) as well as a limited array of events not broadcast on ESPN (most notably, the NBA Finals). === ESPN2 === ESPN2 was launched on October 1, 1993. It carried a broad mix of event coverage from conventional sports—including auto racing, college basketball and NHL hockey—to extreme sports—such as BMX, skateboarding and motocross. The "ESPN BottomLine", a ticker displaying sports news and scores during all programming that is now used by all of ESPN's networks, originated on ESPN2 in 1995. In the late 1990s, ESPN2 was gradually reformatted to serve as a secondary outlet for ESPN's mainstream sports programming. === ESPNews === ESPNews is a subscription television network that was launched on November 1, 1996, originally focusing solely on sports news, highlights, and press conferences. Since August 2010, the network has gradually incorporated encores of ESPN's various sports debate and entertainment shows and video simulcasts of ESPN Radio shows, in addition to sports news programming. Since the 2013 cancellation of Highlight Express, programming consists mainly of rebroadcasts of SportsCenter. ESPNews also serves as an overflow feed due to programming conflicts caused by sporting events on the other ESPN networks. === ESPN Deportes === ESPN Deportes (Spanish pronunciation: [i.es.piˈen deˈpoɾtes], "ESPN Sports") is a subscription television network that was originally launched in July 2001 to provide Spanish simulcasts of certain Major League Baseball telecasts from ESPN. It became a 24-hour sports channel in January 2004. === ESPNU === ESPNU is a subscription television network that launched on March 4, 2005, that focuses on college athletics including basketball, football, baseball, college swimming, and ice hockey. === SEC Network === SEC Network is a subscription television network that launched on August 14, 2014, focusing on the coverage of sporting events sanctioned by the Southeastern Conference. Created as a result of a 20-year broadcast partnership between the two entities, the network is a joint venture between the conference and ESPN Inc., which operates the network. === ACC Network === Launching on August 22, 2019, the ACC Network is a subscription television network that focuses on the sporting events of the Atlantic Coast Conference as part of a current agreement extending to the 2036–37 academic term as a joint venture of network operator ESPN Inc. and the ACC. === ESPN+ === ESPN+ is an American over-the-top subscription video streaming service available in the United States, owned by the ESPN division of the Walt Disney Company, in partnership with ESPN Inc. === Other services === ESPN HD ESPN launched its high definition simulcast feed, originally branded as ESPNHD, on March 30, 2003, with an Opening Day broadcast of the Texas Rangers and Anaheim Angels. All studio shows based in Bristol and at L. A. Live, along with most live event telecasts on ESPN, are broadcast in high definition. ESPN is one of the few television networks with an all-digital infrastructure. Archived non-HD programming is presented in 4:3 standard definition with stylized pillarboxing. Pardon the Interruption and Around the Horn began airing in HD on September 27, 2010, with the relocation of the production of both shows into the facility housing the Washington, D.C., bureau for ABC News. ESPN broadcasts HD programming in the 720p resolution format, because ABC executives proposed a progressive scan signal that resolves fluid and high-speed motion in sports better, particularly during slow-motion replays. The network's Digital Center itself natively holds 2160p UHD/4K operations and equipment. In 2011, ESPNHD began to downplay its distinct promotional logo in preparation for the conversion of its standard definition feed from a 4:3 full-screen to a letterboxed format (via the application of the AFD #10 display flag), which occurred on June 1 of that year. WatchESPN WatchESPN was a website for desktop computers, as well as an application for smartphones and tablet computers that allowed subscribers of participating pay-TV providers to watch live streams of programming from ESPN and its sister networks (except for ESPN Classic), including most sporting events, on computers, mobile devices, Apple TV, Roku and Xbox Live via their TV Everywhere login provided by their cable provider. The service originally launched on October 25, 2010, as ESPN Networks, a streaming service that provided a live stream of ESPN exclusive to Time Warner Cable subscribers. ESPN3, an online streaming service providing live streams and replays of global sports events that launched in 2005 as a separate website, was incorporated into the WatchESPN platform on August 31, 2011. Likewise, ESPN+ was launched in April 2018 as an add-on subscription for $4.99 per month. On June 1, 2019, WatchESPN was discontinued with the service's full merger into the ESPN app. ESPN Events ESPN Regional Television (formerly branded as ESPN Plus) is the network's syndication arm, which produces collegiate sporting events for free-to-air television stations throughout the United States (primarily those affiliated with networks such as The CW and MyNetworkTV or independent stations). ESPN Plus syndicates college football and basketball games from the American Athletic Conference, Big 12 Conference, Mid-American Conference, Metro Atlantic Athletic Conference, Sun Belt Conference and the Western Athletic Conference. ESPN on Snapchat ESPN distributes various content on Snapchat Discover, including a Snapchat-only version of SportsCenter. ESPN MVP ESPN MVP (initially known as Mobile ESPN) was a 2005 attempt at operating a mobile virtual network operator with exclusive mobile content, first as a phone feature, then after its termination into a Verizon Wireless paid service. Technologies developed for it have since been transferred to the network's successful mobile strategy in the smartphone era. === Former services === ESPN Classic ESPN Classic was a subscription television network that launched in 1995 as Classic Sports Network, founded by Brian Bedol and Steve Greenberg. ESPN Inc. purchased Classic Sports Network in 1997 for $175 million, rebranding the channel as "ESPN Classic" in 1998. The channel broadcast notable archived sporting events (originally including events from earlier decades, but later focusing mainly on events from the 1990s and later), as well as sports documentaries and sports-themed movies. It was discontinued on December 31, 2021. Longhorn Network The Longhorn Network was a subscription television network that launched on August 26, 2011, focusing on events from the Texas Longhorns varsity sports teams of the University of Texas at Austin. It features events from the 20 sports sanctioned by the Texas athletic department, along with original programming (including historical, academic and cultural content). It was discontinued on June 30, 2024, a day before the Longhorns' move to the Southeastern Conference. == International channels == ESPN owns and operates regional channels in Brazil, Caribbean, Latin America, Netherlands, Oceania and Sub-Saharan Africa. In Canada, ESPN is a minority owner of The Sports Network (TSN) and the French-language Réseau des sports (RDS). ESPN also has a minority stake in J Sports in Japan. == ESPN Bet == ESPN moved into the sports betting scene in November 2023 with plans to launch their sportsbook app "ESPN Bet" on November 14. In a partnership with Penn Entertainment, ESPN Bet began in 17 states. Once live, ESPN featured betting odds from their own sportsbook on their content. == Criticism == ESPN has been criticized for focusing too much on men's college and professional sports (particularly the NBA and NFL), and very little on women's sports or extreme sports. Baseball, ice hockey, and soccer fans have also criticized ESPN for not giving their respective sports more coverage. Other criticism has focused on ethnicity in ESPN's varying mediated forms, as well as carriage fees and issues regarding the exportation of ESPN content. Some critics argue that ESPN's success is their ability to provide other enterprise and investigative sports news while competing with other hard sports-news-producing outlets such as Yahoo! Sports and Fox Sports. Some scholars have challenged ESPN's journalistic integrity, calling for an expanded standard of professionalism to prevent biased coverage and conflicts of interest. On October 8, 2019, Deadspin reported that an internal memo was sent to ESPN employees instructing them to avoid any political discussions regarding the People's Republic of China and Hong Kong in the aftermath of a tweet by Houston Rockets general manager Daryl Morey. == Awards == National Hispanic Media Coalition's "Outstanding Commitment and Outreach to the Latino Community", 2016 ESPN has won 232 Sports Emmy Awards in 35 years of eligibility. In 2024, ESPN apologized for submitting fake names for Sports Emmy award consideration over many years, and returned 37 trophies that had been awarded to ineligible recipients to the National Academy of Television Arts and Sciences. == See also == List of ESPN personalities List of past ESPN personalities ESPN on ABC ESPN2 ESPN+ ESPN Films Maxx Zoom Wieden+Kennedy == References == == Bibliography == == External links == Official website
https://en.wikipedia.org/wiki/ESPN
This is a list of most-watched Netflix original programming in total hours viewed, in the first 28 days of being uploaded to Netflix. These statistics are released by Netflix based on its proprietary engagement metrics. == Series == Television shows on Netflix with over 200 million views in their first 28 days. == Films == Films on Netflix with over 100 million views in their first 28 days. == References == == External links == Official website
https://en.wikipedia.org/wiki/List_of_most-watched_Netflix_original_programming
Snippet is a programming term for a small region of re-usable source code, machine code, or text. Ordinarily, these are formally defined operative units to incorporate into larger programming modules. Snippet management is a feature of some text editors, program source code editors, IDEs, and related software. It allows the user to avoid repetitive typing in the course of routine edit operations. == Definition == In programming practice, "snippet" refers narrowly to a portion of source code that is literally included by an editor program into a file, and is a form of copy and paste programming. This concrete inclusion is in contrast to abstraction methods, such as functions or macros, which are abstraction within the language. Snippets are thus primarily used when these abstractions are not available or not desired, such as in languages that lack abstraction, or for clarity and absence of overhead. Snippets are similar to having static preprocessing included in the editor, and do not require support by a compiler. On the flip side, this means that snippets cannot be invariably modified after the fact, and thus is vulnerable to all of the problems of copy and paste programming. For this reason snippets are primarily used for simple sections of code (with little logic), or for boilerplate, such as copyright notices, function prototypes, common control structures, or standard library imports. == Overview == Snippet management is a text editor feature popular among software developers or others who routinely require content from a catalogue of repeatedly entered text (such as with source code or boilerplate). Often this feature is justified because the content varies only slightly (or not at all) each time it is entered. === Snippets in text editors === Text editors that include this feature ordinarily provide a mechanism to manage the catalogue, and separate "snippets" in the same manner that the text editor and operating system allow management of separate files. These basic management abilities include operations such as viewing, adding, editing, deleting, sorting, filtering, grouping, renaming, and storing snippets in a repository, catalogue, or database. Some editors provide a macro ability to snippets allowing function prototypes and variable control structures to be generated based on a standard template. === Snippets in IDEs === Some programmer's applications such as Eclipse, NetBeans, and Microsoft's Visual Studio (uses TextMate-inspired snippets underhood) and other IDEs include built-in parts of structure for ease of coding. Other applications such as Macromedia Dreamweaver make use of these code snippets as well for Web development. === Snippets in JIT compilers === Just-in-time (JIT) compilers can "splice together" pre-compiled sections of code as longer object code/machine code segments. This reduces interpret time significantly and simultaneously speeds execution. === Snippets in shells === Snippets may be used inside commandline interfaces like bash, zsh (GNU Linux/Unix-like) or powershell (MS Windows). Features like completion and placeholders substitution may or may not be supported. == Example == Consider the process of swapping the values of two variables, x and y. Assuming weak typing and not being concerned about name collision, this is represented by the code: temp = x x = y y = temp When the snippet is inserted, the programmer is prompted for the values of the two parameters. Assuming they are type foo and bar, which are the actual names of the variables they wish to swap, this will yield the code: temp = foo foo = bar bar = temp If the snippet is subsequently changed, say to use __temp instead of temp, it will not change the code that has already been inserted, but will be used in subsequent insertions of the snippet. A snippet for this might be represented as: temp = $1 $1 = $2 $2 = temp == Conventions == In addition to the basic management abilities described previously, snippet management features can be classified according to the scope of interactivity between snippets and the text editor or application that hosts them. These snippet feature groups include: plain-text or "static" snippets interactive or "dynamic" snippets scriptable snippets Static Snippets of this type consist primarily of fixed text that the user can choose to insert into the current document. The user is not able to specify anything else, except perhaps the cursor position relative to the newly inserted text. Static snippets are similar to simple macros, excepting that macro are often evaluated (or inserted) by a command-line program instead of IDE. Dynamic Snippets consist of fixed text combined with dynamic elements (placeholders) which are allowed to be modified either by editor or by user. The user may specify both the content of the dynamic elements, as well as their position relative to the fixed text, as part of choosing what to insert into the current document. Examples of dynamic elements could be variables such as the current date or system time, or input from the user that is supplied via a GUI, or input from another application. (see also: programmable macro). Scriptable Snippets consist of runnable segments of code in either a macro language or a scripting language. Scriptable snippets provide the greatest degree of flexibility to the user, although that depends somewhat on the programming languages supported by the text editor, and whether or not the programming language is well-known, or particular and unique to that specific editor. The type of scripting support varies, but may include features such as running shell commands, providing a GUI dialog or other methods of user interaction with the operating system; other applications; or other sub-components of the hosting application itself. == Snippet placeholders == Placeholders are elements within a snippet that are left to be supplied by the user or other external process. The values for placeholders are not determined until the text of the snippet is inserted during an editing session. Placeholders may have special markup syntax that allows the editor to identify the boundaries of placeholders relative to the other text in the current edit buffer. Other applications employ graphical user interfaces and modal dialog boxes that allow the user to enter one or more values to be supplied for the placeholders. === Placeholder identifiers === Placeholders are usually indicated by some special character or sequence of characters to distinguish them from the rest of the snippet text. Some systems allow snippet placeholders to be named identifiers. The identifiers may be useful for supporting such features as placeholder duplication or placeholder transformation. The following example uses the identifiers first_name, last_name, and item: Example of a snippet in TexMate syntax: === Placeholder duplication === This allows the user to indicate that the value supplied for one placeholder should be replicated in multiple places, relative to the entire text of the programmable snippet. In the previous example, the named placeholder first_name is an example of this usage. === Placeholder transformation === This allows the user to indicate that one or more values supplied for a placeholder should be replicated and transformed in other places within the text of the programmable snippet. For example, the user may supply a document title in one part of the snippet, and specify that the document title should be repeated in other places, with the first instance being all-uppercase and every other instance being lower-case. == Snippet programming features == For applications that support scriptable snippets, the range of supported programming features varies. The following enumerates some of the features that are commonly implemented for programmable snippets. === Plain text === Although plain text is a fundamental feature included even with applications that support only non-programmable "static" snippets, programmable snippets are also used for working with plain text. One common complication, however, is that environments that support programmable snippets often have to make distinctions between what counts as "plain text" and what counts as "programming instructions". Further complicating this distinction is the fact that applications that support programmable snippets almost always include support for recognition of multiple programming languages, either through basic syntax highlighting or execution of embedded commands. For these and other reasons, emitting plain text from programmable snippets almost always entails being careful to avoid problems with syntax and delimiter collisions. === Constants and variables === Programmable snippets often include an ability to establish a binding to an existing variable scope or namespace, from which the user can select any of various constants or variables. These might include values such as the email address of the currently logged-in user on a given machine, the current system time and date, or the output value of a function. Scriptable snippets are often associated with one or more currently active files. Consequently, variables may also include environment variables and arguments that specify the filename, cursor position, and parent directory among other stats relating to the files in a current editing session. === Interpreted code === Scriptable snippets may allow execution of code in one or more programming languages. This may include one or more standalone languages, or a language that is specific to the application in which the language is hosted. == Alternatives == The most basic alternative to code snippets is subroutines in libraries. Subroutines can be incorporated into a reusable software library and shared between multiple programming projects. Design patterns in object-oriented programming, and functional programming, are both techniques that can allow programmers to avoid or reduce the practice of repeatedly inserting snippets into different pieces of code with slight variations each time. In languages in the C family, preprocessors are sometimes used for this purpose. The disadvantage of this approach however is that it's harder to remember pattern or documentation. === Software assistance === As of 2021 some sophisticated deep-learning tooling emerged that can help to infer specific functionality from a human readable text and generate corresponding source code snippets (e.g. GitHub Copilot). == See also == == References ==
https://en.wikipedia.org/wiki/Snippet_(programming)
In software systems, encapsulation refers to the bundling of data with the mechanisms or methods that operate on the data. It may also refer to the limiting of direct access to some of that data, such as an object's components. Essentially, encapsulation prevents external code from being concerned with the internal workings of an object. Encapsulation allows developers to present a consistent interface that is independent of its internal implementation. As one example, encapsulation can be used to hide the values or state of a structured data object inside a class. This prevents clients from directly accessing this information in a way that could expose hidden implementation details or violate state invariance maintained by the methods. Encapsulation also encourages programmers to put all the code that is concerned with a certain set of data in the same class, which organizes it for easy comprehension by other programmers. Encapsulation is a technique that encourages decoupling. All object-oriented programming (OOP) systems support encapsulation, but encapsulation is not unique to OOP. Implementations of abstract data types, modules, and libraries also offer encapsulation. The similarity has been explained by programming language theorists in terms of existential types. == Meaning == In object-oriented programming languages, and other related fields, encapsulation refers to one of two related but distinct notions, and sometimes to the combination thereof: A language mechanism for restricting direct access to some of the object's components. A language construct that facilitates the bundling of data with the methods (or other functions) operating on those data. Some programming language researchers and academics use the first meaning alone or in combination with the second as a distinguishing feature of object-oriented programming, while some programming languages that provide lexical closures view encapsulation as a feature of the language orthogonal to object orientation. The second definition reflects that in many object-oriented languages, and other related fields, the components are not hidden automatically and this can be overridden. Thus, information hiding is defined as a separate notion by those who prefer the second definition. The features of encapsulation are supported using classes in most object-oriented languages, although other alternatives also exist. Encapsulation may also refer to containing a repetitive or complex process in a single unit to be invoked. Object-oriented programming facilitate this at both the method and class levels. This definition is also applicable to procedural programming. === Encapsulation and inheritance === The authors of Design Patterns discuss the tension between inheritance and encapsulation at length and state that in their experience, designers overuse inheritance. They claim that inheritance often breaks encapsulation, given that inheritance exposes a subclass to the details of its parent's implementation. As described by the yo-yo problem, overuse of inheritance and therefore encapsulation, can become too complicated and hard to debug. == Information hiding == Under the definition that encapsulation "can be used to hide data members and member functions", the internal representation of an object is generally hidden outside of the object's definition. Typically, only the object's own methods can directly inspect or manipulate its fields. Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state. A supposed benefit of encapsulation is that it can reduce system complexity, and thus increase robustness, by allowing the developer to limit the interdependencies between software components. Some languages like Smalltalk and Ruby only allow access via object methods, but most others (e.g., C++, C#, Delphi or Java) offer the programmer some control over what is hidden, typically via keywords like public and private. ISO C++ standard refers to protected, private and public as "access specifiers" and that they do not "hide any information". Information hiding is accomplished by furnishing a compiled version of the source code that is interfaced via a header file. Almost always, there is a way to override such protection – usually via reflection API (Ruby, Java, C#, etc.), sometimes by mechanism like name mangling (Python), or special keyword usage like friend in C++. Systems that provide object-level capability-based security (adhering to the object-capability model) are an exception, and guarantee strong encapsulation. === Examples === ==== Restricting data fields ==== Languages like C++, C#, Java, PHP, Swift, and Delphi offer ways to restrict access to data fields. Below is an example in C# that shows how access to a data field can be restricted through the use of a private keyword: Below is an example in Java: Encapsulation is also possible in non-object-oriented languages. In C, for example, a structure can be declared in the public API via the header file for a set of functions that operate on an item of data containing data members that are not accessible to clients of the API with the extern keyword. Clients call the API functions to allocate, operate on, and deallocate objects of an opaque data type. The contents of this type are known and accessible only to the implementation of the API functions; clients cannot directly access its contents. The source code for these functions defines the actual contents of the structure: ==== Name mangling ==== Below is an example of Python, which does not support variable access restrictions. However, the convention is that a variable whose name is prefixed by an underscore should be considered private. == See also == Inheritance (object-oriented programming) Object-oriented programming Software design pattern Facade pattern == Citations == == References == Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN 978-0134685991.
https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)
Mesa is a programming language developed in the mid 1970s at the Xerox Palo Alto Research Center in Palo Alto, California, United States. The language name was a pun based upon the programming language catchphrases of the time, because Mesa is a "high level" programming language. Mesa is an ALGOL-like language with strong support for modular programming. Every library module has at least two source files: a definitions file specifying the library's interface plus one or more program files specifying the implementation of the procedures in the interface. To use a library, a program or higher-level library must "import" the definitions. The Mesa compiler type-checks all uses of imported entities; this combination of separate compilation with type-checking was unusual at the time. Mesa introduced several other innovations in language design and implementation, notably in the handling of software exceptions, thread synchronization, and incremental compilation. Mesa was developed on the Xerox Alto, one of the first personal computers with a graphical user interface, however, most of the Alto's system software was written in BCPL. Mesa was the system programming language of the later Xerox Star workstations, and for the GlobalView desktop environment. Xerox PARC later developed Cedar, which was a superset of Mesa. Mesa and Cedar had a major influence on the design of other important languages, such as Modula-2 and Java, and was an important vehicle for the development and dissemination of the fundamentals of GUIs, networked environments, and the other advances Xerox contributed to the field of computer science. == History == Mesa was originally designed in the Computer Systems Laboratory (CSL), a branch of the Xerox Palo Alto Research Center, for the Alto, an experimental micro-coded workstation. Initially, its spread was confined to PARC and a few universities to which Xerox had donated some Altos. Mesa was later adopted as the systems programming language for Xerox's commercial workstations such as the Xerox 8010 (Xerox Star, Dandelion) and Xerox 6085 (Daybreak), in particular for the Pilot operating system. A secondary development environment, called the Xerox Development Environment (XDE) allowed developers to debug both the operating system Pilot as well as ViewPoint GUI applications using a world swap mechanism. This allowed the entire "state" of the world to be swapped out, and allowed low-level system crashes which paralyzed the whole system to be debugged. This technique did not scale very well to large application images (several megabytes), and so the Pilot/Mesa world in later releases moved away from the world swap view when the micro-coded machines were phased out in favor of SPARC workstations and Intel PCs running a Mesa PrincOps emulator for the basic hardware instruction set. Mesa was compiled into a stack-machine language, purportedly with the highest code density ever achieved (roughly 4 bytes per high-level language statement). This was touted in a 1981 paper where implementors from the Xerox Systems Development Department (then, the development arm of PARC), tuned up the instruction set and published a paper on the resultant code density. Mesa was taught via the Mesa Programming Course that took people through the wide range of technology Xerox had available at the time and ended with the programmer writing a "hack", a workable program designed to be useful. An actual example of such a hack is the BWSMagnifier, which was written in 1988 and allowed people to magnify sections of the workstation screen as defined by a resizable window and a changeable magnification factor. Trained Mesa programmers from Xerox were well versed in the fundamental of GUIs, networking, exceptions, and multi-threaded programming, almost a decade before they became standard tools of the trade. Within Xerox, Mesa was eventually superseded by the Cedar programming language. Many Mesa programmers and developers left Xerox in 1985; some of them went to DEC Systems Research Center where they used their experience with Mesa in the design of Modula-2+, and later of Modula-3. == Main features == === Semantics === Mesa was a strongly typed programming language with type-checking across module boundaries, but with enough flexibility in its type system that heap allocators could be written in Mesa. Due to its strict separation between interface and implementation, Mesa allows true incremental compilation and encourages architecture- and platform-independent programming. They also simplified source-level debugging, including remote debugging via the Ethernet. Mesa had rich exception handling facilities, with four types of exceptions. It had support for thread synchronization via monitors. Mesa was the first language to implement monitor BROADCAST, a concept introduced by the Pilot operating system. === Syntax === Mesa has an "imperative" and "algebraic" syntax, based on ALGOL and Pascal rather than on BCPL or C; for instance, compound commands are indicated by the BEGIN and END keywords rather than braces. In Mesa, all keywords are written in uppercase. Due to PARC's using the 1963 variant of ASCII rather than the more common 1967 variant, the Alto's character set included a left-pointing arrow (←) rather than an underscore. The result of this is that Alto programmers (including those using Mesa, Smalltalk etc.) conventionally used camelCase for compound identifiers, a practice which was incorporated in PARC's standard programming style. On the other hand, the availability of the left-pointing arrow allowed them to use it for the assignment operator, as it originally had been in ALGOL. When the Mesa designers wanted to implement an exception facility, they hired a recent M.Sc. graduate from Colorado who had written his thesis on exception handling facilities in algorithmic languages. This led to the richest exception facility for its time, with primitives SIGNAL, ERROR, ABORT, RETRY, CATCH, and CONTINUE. As the language did not have type-safe checks to verify full coverage for signal handling, uncaught exceptions were a common cause of bugs in released software. == Cedar == Mesa was the precursor to the programming language Cedar. Cedar's main additions were garbage collection, dynamic types, better string support through ropes, a limited form of type parameterization, and special syntax for identifying the type-safe parts of multi-module software packages, to ensure deterministic execution and prevent memory leaks. == Descendants == The United States Department of Defense approached Xerox to use Mesa for its "IronMan" programming language (see Steelman language requirements), but Xerox declined due to conflicting goals. Xerox PARC employees argued that Mesa was a proprietary advantage that made Xerox software engineers more productive than engineers at other companies. The Department of Defense instead eventually chose and developed the Ada programming language from the candidates. The original Star Desktop evolved into the ViewPoint Desktop and later became GlobalView which was ported to various Unix platforms, such as SunOS Unix and AIX. A Mesa to C compiler was written and the resulting code compiled for the target platform. This was a workable solution but made it nearly impossible to develop on the Unix machines since the power of the Mesa compiler and associated tool chain was lost using this approach. There was some commercial success on Sun SPARC workstations in the publishing world, but this approach resulted in isolating the product to narrow market opportunities. In 1976, during a sabbatical at Xerox PARC, Niklaus Wirth became acquainted with Mesa, which had a major influence in the design of his Modula-2 language. Java explicitly refers to Mesa as a predecessor. == See also == History of the graphical user interface == References == == External links == Mesa Programming Language Manual, Version 5 (1979) at bitsavers.org Other Mesa documents at bitsavers.org World-Stop Debuggers Archived 26 August 2016 at the Wayback Machine, Don Gillies, Xerox SDD/ISD Employee, 1984–86. Teitelman, Warren (April 1984). "A Tour Through Cedar". IEEE Software. 1 (2): 44–73. CiteSeerX 10.1.1.105.3163. doi:10.1109/ms.1984.234050.
https://en.wikipedia.org/wiki/Mesa_(programming_language)
A geometric program (GP) is an optimization problem of the form minimize f 0 ( x ) subject to f i ( x ) ≤ 1 , i = 1 , … , m g i ( x ) = 1 , i = 1 , … , p , {\displaystyle {\begin{array}{ll}{\mbox{minimize}}&f_{0}(x)\\{\mbox{subject to}}&f_{i}(x)\leq 1,\quad i=1,\ldots ,m\\&g_{i}(x)=1,\quad i=1,\ldots ,p,\end{array}}} where f 0 , … , f m {\displaystyle f_{0},\dots ,f_{m}} are posynomials and g 1 , … , g p {\displaystyle g_{1},\dots ,g_{p}} are monomials. In the context of geometric programming (unlike standard mathematics), a monomial is a function from R + + n {\displaystyle \mathbb {R} _{++}^{n}} to R {\displaystyle \mathbb {R} } defined as x ↦ c x 1 a 1 x 2 a 2 ⋯ x n a n {\displaystyle x\mapsto cx_{1}^{a_{1}}x_{2}^{a_{2}}\cdots x_{n}^{a_{n}}} where c > 0 {\displaystyle c>0\ } and a i ∈ R {\displaystyle a_{i}\in \mathbb {R} } . A posynomial is any sum of monomials. Geometric programming is closely related to convex optimization: any GP can be made convex by means of a change of variables. GPs have numerous applications, including component sizing in IC design, aircraft design, maximum likelihood estimation for logistic regression in statistics, and parameter tuning of positive linear systems in control theory. == Convex form == Geometric programs are not in general convex optimization problems, but they can be transformed to convex problems by a change of variables and a transformation of the objective and constraint functions. In particular, after performing the change of variables y i = log ⁡ ( x i ) {\displaystyle y_{i}=\log(x_{i})} and taking the log of the objective and constraint functions, the functions f i {\displaystyle f_{i}} , i.e., the posynomials, are transformed into log-sum-exp functions, which are convex, and the functions g i {\displaystyle g_{i}} , i.e., the monomials, become affine. Hence, this transformation transforms every GP into an equivalent convex program. In fact, this log-log transformation can be used to convert a larger class of problems, known as log-log convex programming (LLCP), into an equivalent convex form. == Software == Several software packages exist to assist with formulating and solving geometric programs. MOSEK is a commercial solver capable of solving geometric programs as well as other non-linear optimization problems. CVXOPT is an open-source solver for convex optimization problems. GPkit is a Python package for cleanly defining and manipulating geometric programming models. There are a number of example GP models written with this package here. GGPLAB is a MATLAB toolbox for specifying and solving geometric programs (GPs) and generalized geometric programs (GGPs). CVXPY is a Python-embedded modeling language for specifying and solving convex optimization problems, including GPs, GGPs, and LLCPs. == See also == Signomial Clarence Zener == References ==
https://en.wikipedia.org/wiki/Geometric_programming
The International Conference on Functional Programming (ICFP) is an annual academic conference in the field of computer science sponsored by the ACM SIGPLAN, in association with IFIP Working Group 2.8 (Functional Programming). The conference focuses on functional programming and related areas of programming languages, logic, compilers and software development. The ICFP was first held in 1996, replacing two biennial conferences: the Functional Programming and Computer Architecture (FPCA) and LISP and Functional Programming (LFP). The conference location alternates between Europe and North America, with occasional appearances in other continents. The conference usually lasts 3 days, surrounded by co-located workshops devoted to particular functional languages or application areas. The ICFP has also held an open annual programming contest since 1998, called the ICFP Programming Contest. == History == 2012: 17th ACM SIGPLAN International Conference on Functional Programming in Copenhagen, Denmark (General Chair: Peter Thiemann, University of Freiburg; Program Chair: Robby Findler, Northwestern University) == See also == Related conferences FSCD : International Conference on Formal Structures for Computation and Deduction FLOPS: International Symposium on Functional and Logic Programming IFL: International Symposia on Implementation and Application of Functional Languages ISMM: International Symposium on Memory Management MPC: International Conference on Mathematics of Program Construction PLDI: Programming Language Design and Implementation POPL: Principles of Programming Languages PPDP: International Conference on Principles and Practice of Declarative Programming TFP: Symposium on Trends in Functional Programming TLCA: International Conference on Typed Lambda Calculi and Applications TLDI: International Workshop on Types in Language Design and Implementation SAS: International Static Analysis Symposium Related journals Journal of Functional Programming Journal of Functional and Logic Programming Higher-Order and Symbolic Computation ACM Transactions on Programming Languages and Systems == References == == External links == ICFP main site ICFP 2023 conference ICFP Programming Contest
https://en.wikipedia.org/wiki/International_Conference_on_Functional_Programming
In computer science, automatic programming is a type of computer programming in which some mechanism generates a computer program, to allow human programmers to write the code at a higher abstraction level. There has been little agreement on the precise definition of automatic programming, mostly because its meaning has changed over time. David Parnas, tracing the history of "automatic programming" in published research, noted that in the 1940s it described automation of the manual process of punching paper tape. Later it referred to translation of high-level programming languages like Fortran and ALGOL. In fact, one of the earliest programs identifiable as a compiler was called Autocode. Parnas concluded that "automatic programming has always been a euphemism for programming in a higher-level language than was then available to the programmer." Program synthesis is one type of automatic programming where a procedure is created from scratch, based on mathematical requirements. == Origin == Mildred Koss, an early UNIVAC programmer, explains: "Writing machine code involved several tedious steps—breaking down a process into discrete instructions, assigning specific memory locations to all the commands, and managing the I/O buffers. After following these steps to implement mathematical routines, a sub-routine library, and sorting programs, our task was to look at the larger programming process. We needed to understand how we might reuse tested code and have the machine help in programming. As we programmed, we examined the process and tried to think of ways to abstract these steps to incorporate them into higher-level language. This led to the development of interpreters, assemblers, compilers, and generators—programs designed to operate on or produce other programs, that is, automatic programming." == Generative programming == Generative programming and the related term meta-programming are concepts whereby programs can be written "to manufacture software components in an automated way" just as automation has improved "production of traditional commodities such as garments, automobiles, chemicals, and electronics." The goal is to improve programmer productivity. It is often related to code-reuse topics such as component-based software engineering. == Source-code generation == Source-code generation is the process of generating source code based on a description of the problem or an ontological model such as a template and is accomplished with a programming tool such as a template processor or an integrated development environment (IDE). These tools allow the generation of source code through any of various means. Modern programming languages are well supported by tools like Json4Swift (Swift) and Json2Kotlin (Kotlin). Programs that could generate COBOL code include: the DYL250/DYL260/DYL270/DYL280 series Business Controls Corporation's SB-5 Peat Marwick Mitchell's PMM2170 application-program-generator package These application generators supported COBOL inserts and overrides. A macro processor, such as the C preprocessor, which replaces patterns in source code according to relatively simple rules, is a simple form of source-code generator. Source-to-source code generation tools also exist. Large language models such as ChatGPT are capable of generating a program's source code from a description of the program given in a natural language. Many relational database systems provide a function that will export the content of the database as SQL data definition queries, which may then be executed to re-import the tables and their data, or migrate them to another RDBMS. == Low-code applications == A low-code development platform (LCDP) is software that provides an environment programmers use to create application software through graphical user interfaces and configuration instead of traditional computer programming. == See also == Automatic bug fixing Automated machine learning Comparison of code generation tools Feature-oriented programming GitHub Copilot Language-oriented programming Modeling language Program transformation Semantic translation Vocabulary-based transformation Fourth-generation programming language Low-code development platforms Emergent Coding == Notes == == References == Generative Programming: Methods, Tools, and Applications by Krzysztof Czarnecki and Ulrich W. Eisenecker, Addison Wesley, 2000. == External links == Code Generation for Dummies
https://en.wikipedia.org/wiki/Automatic_programming
C++ (, pronounced "C plus plus" and sometimes abbreviated as CPP or CXX) is a high-level, general-purpose programming language created by Danish computer scientist Bjarne Stroustrup. First released in 1985 as an extension of the C programming language, adding object-oriented (OOP) features, it has since expanded significantly over time adding more OOP and other features; as of 1997/C++98 standardization, C++ has added functional features, in addition to facilities for low-level memory manipulation for systems like microcomputers or to make operating systems like Linux or Windows, and even later came features like generic (template) programming. C++ is usually implemented as a compiled language, and many vendors provide C++ compilers, including the Free Software Foundation, LLVM, Microsoft, Intel, Embarcadero, Oracle, and IBM. C++ was designed with systems programming and embedded, resource-constrained software and large systems in mind, with performance, efficiency, and flexibility of use as its design highlights. C++ has also been found useful in many other contexts, with key strengths being software infrastructure and resource-constrained applications, including desktop applications, video games, servers (e.g., e-commerce, web search, or databases), and performance-critical applications (e.g., telephone switches or space probes). C++ is standardized by the International Organization for Standardization (ISO), with the latest standard version ratified and published by ISO in October 2024 as ISO/IEC 14882:2024 (informally known as C++23). The C++ programming language was initially standardized in 1998 as ISO/IEC 14882:1998, which was then amended by the C++03, C++11, C++14, C++17, and C++20 standards. The current C++23 standard supersedes these with new features and an enlarged standard library. Before the initial standardization in 1998, C++ was developed by Stroustrup at Bell Labs since 1979 as an extension of the C language; he wanted an efficient and flexible language similar to C that also provided high-level features for program organization. Since 2012, C++ has been on a three-year release schedule with C++26 as the next planned standard. Despite its widespread adoption, some notable programmers have criticized the C++ language, including Linus Torvalds, Richard Stallman, Joshua Bloch, Ken Thompson, and Donald Knuth. This is largely due to its manual memory management, which makes it vulnerable to buffer overflow bugs, which represent a security risk. == History == In 1979, Bjarne Stroustrup, a Danish computer scientist, began work on "C with Classes", the predecessor to C++. The motivation for creating a new language originated from Stroustrup's experience in programming for his PhD thesis. Stroustrup found that Simula had features that were very helpful for large software development, but the language was too slow for practical use, while BCPL was fast but too low-level to be suitable for large software development. When Stroustrup started working in AT&T Bell Labs, he had the problem of analyzing the UNIX kernel with respect to distributed computing. Remembering his PhD experience, Stroustrup set out to enhance the C language with Simula-like features. C was chosen because it was general-purpose, fast, portable, and widely used. In addition to C and Simula's influences, other languages influenced this new language, including ALGOL 68, Ada, CLU, and ML. Initially, Stroustrup's "C with Classes" added features to the C compiler, Cpre, including classes, derived classes, strong typing, inlining, and default arguments. In 1982, Stroustrup started to develop a successor to C with Classes, which he named "C++" (++ being the increment operator in C) after going through several other names. New features were added, including virtual functions, function name and operator overloading, references, constants, type-safe free-store memory allocation (new/delete), improved type checking, and BCPL-style single-line comments with two forward slashes (//). Furthermore, Stroustrup developed a new, standalone compiler for C++, Cfront. In 1984, Stroustrup implemented the first stream input/output library. The idea of providing an output operator rather than a named output function was suggested by Doug McIlroy (who had previously suggested Unix pipes). In 1985, the first edition of The C++ Programming Language was released, which became the definitive reference for the language, as there was not yet an official standard. The first commercial implementation of C++ was released in October of the same year. In 1989, C++ 2.0 was released, followed by the updated second edition of The C++ Programming Language in 1991. New features in 2.0 included multiple inheritance, abstract classes, static member functions, const member functions, and protected members. In 1990, The Annotated C++ Reference Manual was published. This work became the basis for the future standard. Later feature additions included templates, exceptions, namespaces, new casts, and a Boolean type. In 1998, C++98 was released, standardizing the language, and a minor update (C++03) was released in 2003. After C++98, C++ evolved relatively slowly until, in 2011, the C++11 standard was released, adding numerous new features, enlarging the standard library further, and providing more facilities to C++ programmers. After a minor C++14 update released in December 2014, various new additions were introduced in C++17. After becoming finalized in February 2020, a draft of the C++20 standard was approved on 4 September 2020, and officially published on 15 December 2020. On January 3, 2018, Stroustrup was announced as the 2018 winner of the Charles Stark Draper Prize for Engineering, "for conceptualizing and developing the C++ programming language". In December 2022, C++ ranked third on the TIOBE index, surpassing Java for the first time in the history of the index. As of November 2024, the language ranks second after Python, with Java being in third. === Etymology === According to Stroustrup, "the name signifies the evolutionary nature of the changes from C." This name is credited to Rick Mascitti (mid-1983) and was first used in December 1983. When Mascitti was questioned informally in 1992 about the naming, he indicated that it was given in a tongue-in-cheek spirit. The name comes from C's ++ operator (which increments the value of a variable) and a common naming convention of using "+" to indicate an enhanced computer program. During C++'s development period, the language had been referred to as "new C" and "C with Classes" before acquiring its final name. === Philosophy === Throughout C++'s life, its development and evolution has been guided by a set of principles: It must be driven by actual problems and its features should be immediately useful in real world programs. Every feature should be implementable (with a reasonably obvious way to do so). Programmers should be free to pick their own programming style, and that style should be fully supported by C++. Allowing a useful feature is more important than preventing every possible misuse of C++. It should provide facilities for organizing programs into separate, well-defined parts, and provide facilities for combining separately developed parts. No implicit violations of the type system (but allow explicit violations; that is, those explicitly requested by the programmer). User-created types need to have the same support and performance as built-in types. Unused features should not negatively impact created executables (e.g. in lower performance). There should be no language beneath C++ (except assembly language). C++ should work alongside other existing programming languages, rather than fostering its own separate and incompatible programming environment. If the programmer's intent is unknown, allow the programmer to specify it by providing manual control. === Standardization === C++ is standardized by an ISO working group known as JTC1/SC22/WG21. So far, it has published seven revisions of the C++ standard and is currently working on the next revision, C++26. In 1998, the ISO working group standardized C++ for the first time as ISO/IEC 14882:1998, which is informally known as C++98. In 2003, it published a new version of the C++ standard called ISO/IEC 14882:2003, which fixed problems identified in C++98. The next major revision of the standard was informally referred to as "C++0x", but it was not released until 2011. C++11 (14882:2011) included many additions to both the core language and the standard library. In 2014, C++14 (also known as C++1y) was released as a small extension to C++11, featuring mainly bug fixes and small improvements. The Draft International Standard ballot procedures completed in mid-August 2014. After C++14, a major revision C++17, informally known as C++1z, was completed by the ISO C++ committee in mid July 2017 and was approved and published in December 2017. As part of the standardization process, ISO also publishes technical reports and specifications: ISO/IEC TR 18015:2006 on the use of C++ in embedded systems and on performance implications of C++ language and library features, ISO/IEC TR 19768:2007 (also known as the C++ Technical Report 1) on library extensions mostly integrated into C++11, ISO/IEC TR 29124:2010 on special mathematical functions, integrated into C++17, ISO/IEC TR 24733:2011 on decimal floating-point arithmetic, ISO/IEC TS 18822:2015 on the standard filesystem library, integrated into C++17, ISO/IEC TS 19570:2015 on parallel versions of the standard library algorithms, integrated into C++17, ISO/IEC TS 19841:2015 on software transactional memory, ISO/IEC TS 19568:2015 on a new set of library extensions, some of which are already integrated into C++17, ISO/IEC TS 19217:2015 on the C++ concepts, integrated into C++20, ISO/IEC TS 19571:2016 on the library extensions for concurrency, some of which are already integrated into C++20, ISO/IEC TS 19568:2017 on a new set of general-purpose library extensions, ISO/IEC TS 21425:2017 on the library extensions for ranges, integrated into C++20, ISO/IEC TS 22277:2017 on coroutines, integrated into C++20, ISO/IEC TS 19216:2018 on the networking library, ISO/IEC TS 21544:2018 on modules, integrated into C++20, ISO/IEC TS 19570:2018 on a new set of library extensions for parallelism ISO/IEC TS 23619:2021 on new extensions for reflective programming (reflection), ISO/IEC TS 9922:2024 on new set of concurrency extensions, and ISO/IEC TS 19568:2024 on another new set of library extensions. More technical specifications are in development and pending approval. == Language == The C++ language has two main components: a direct mapping of hardware features provided primarily by the C subset, and zero-overhead abstractions based on those mappings. Stroustrup describes C++ as "a light-weight abstraction programming language [designed] for building and using efficient and elegant abstractions"; and "offering both hardware access and abstraction is the basis of C++. Doing it efficiently is what distinguishes it from other languages." C++ inherits most of C's syntax. A hello world program that conforms to the C standard is also a valid C++ hello world program. The following is Bjarne Stroustrup's version of the Hello world program that uses the C++ Standard Library stream facility to write a message to standard output: == Standard library == The C++ standard consists of two parts: the core language and the standard library. C++ programmers expect the latter on every major implementation of C++; it includes aggregate types (vectors, lists, maps, sets, queues, stacks, arrays, tuples), algorithms (find, for_each, binary_search, random_shuffle, etc.), input/output facilities (iostream, for reading from and writing to the console and files), filesystem library, localisation support, smart pointers for automatic memory management, regular expression support, multi-threading library, atomics support (allowing a variable to be read or written to by at most one thread at a time without any external synchronisation), time utilities (measurement, getting current time, etc.), a system for converting error reporting that does not use C++ exceptions into C++ exceptions, a random number generator, and a slightly modified version of the C standard library (to make it comply with the C++ type system). A large part of the C++ library is based on the Standard Template Library (STL). Useful tools provided by the STL include containers as the collections of objects (such as vectors and lists), iterators that provide array-like access to containers, and algorithms that perform operations such as searching and sorting. Furthermore, (multi)maps (associative arrays) and (multi)sets are provided, all of which export compatible interfaces. Therefore, using templates it is possible to write generic algorithms that work with any container or on any sequence defined by iterators. As in C, the features of the library may be accessed by using the #include directive to include a standard header. The C++ Standard Library provides 105 standard headers, of which 27 are deprecated. With the introduction of modules in C++20, these headers may be accessed with import, and in C++23, the entire standard library can now be directly imported as module itself, with import std;. Currently, the C++ standard library provides two modules, std and std.compat (a compatibility module for std which exports C standard library facilities into the global namespace). The standard incorporates the STL that was originally designed by Alexander Stepanov, who experimented with generic algorithms and containers for many years. When he started with C++, he finally found a language where it was possible to create generic algorithms (e.g., STL sort) that perform even better than, for example, the C standard library qsort, thanks to C++ features like using inlining and compile-time binding instead of function pointers. The standard does not refer to it as "STL", as it is merely a part of the standard library, but the term is still widely used to distinguish it from the rest of the standard library (input/output streams, internationalization, diagnostics, the C library subset, etc.). Most C++ compilers, and all major ones, provide a standards-conforming implementation of the C++ standard library. == C++ Core Guidelines == The C++ Core Guidelines are an initiative led by Bjarne Stroustrup, the inventor of C++, and Herb Sutter, the convener and chair of the C++ ISO Working Group, to help programmers write 'Modern C++' by using best practices for the language standards C++11 and newer, and to help developers of compilers and static checking tools to create rules for catching bad programming practices. The main aim is to efficiently and consistently write type and resource safe C++. The Core Guidelines were announced in the opening keynote at CPPCon 2015. The Guidelines are accompanied by the Guideline Support Library (GSL), a header only library of types and functions to implement the Core Guidelines and static checker tools for enforcing Guideline rules. == Compatibility == To give compiler vendors greater freedom, the C++ standards committee decided not to dictate the implementation of name mangling, exception handling, and other implementation-specific features. The downside of this decision is that object code produced by different compilers is expected to be incompatible. There are, however, attempts to standardize compilers for particular machines or operating systems. For example, the Itanium C++ ABI is processor-independent (despite its name) and is implemented by GCC and Clang. === With C === C++ is often considered to be a superset of C but this is not strictly true. Most C code can easily be made to compile correctly in C++ but there are a few differences that cause some valid C code to be invalid or behave differently in C++. For example, C allows implicit conversion from void* to other pointer types but C++ does not (for type safety reasons). Also, C++ defines many new keywords, such as new and class, which may be used as identifiers (for example, variable names) in a C program. Some incompatibilities have been removed by the 1999 revision of the C standard (C99), which now supports C++ features such as line comments (//) and declarations mixed with code. On the other hand, C99 introduced a number of new features that C++ did not support that were incompatible or redundant in C++, such as variable-length arrays, native complex-number types (however, the std::complex class in the C++ standard library provides similar functionality, although not code-compatible), designated initializers, compound literals, and the restrict keyword. Some of the C99-introduced features were included in the subsequent version of the C++ standard, C++11 (out of those which were not redundant). However, the C++11 standard introduces new incompatibilities, such as disallowing assignment of a string literal to a character pointer, which remains valid C. To intermix C and C++ code, any function declaration or definition that is to be called from/used both in C and C++ must be declared with C linkage by placing it within an extern "C" {/*...*/} block. Such a function may not rely on features depending on name mangling (i.e., function overloading). === Inline assembly === Programs developed in C or C++ often utilize inline assembly to take advantage of its low-level functionalities, greater speed, and enhanced control compared to high-level programming languages when optimizing for performance is essential. C++ provides support for embedding assembly language using asm declarations, but the compatibility of inline assembly varies significantly between compilers and architectures. Unlike high-level language features such as Python or Java, assembly code is highly dependent on the underlying processor and compiler implementation. ==== Variations across compilers ==== Different C++ compilers implement inline assembly in distinct ways. GCC (GNU Compiler Collection) and Clang: Use the GCC extended inline assembly syntax. Using __asm__ keyword instead of asm when writing code that can be compiled with -ansi and -std options, which allows specifying input/output operands and clobbered registers. This approach is widely adopted, including by Intel and IBM compilers. MSVC (Microsoft Visual C++): The inline assembler is built into the compiler. Previously supported inline assembly via the __asm keyword, but this support has been removed in 64-bit mode, requiring separate .asm modules instead. TI ARM Clang and Embedded Compilers: Some embedded system compilers, like Texas Instruments' TI Arm Clang, allow inline assembly but impose stricter rules to avoid conflicts with register conventions and calling conventions. ==== Interoperability between C++ and Assembly ==== C++ provides two primary methods of integrating ASM code. 1. Standalone assembly files – Assembly code is written separately and linked with C++ code. 2. Inline assembly – Assembly code is embedded within C++ code using compiler-specific extensions. Example Code for ASM Compatibility When calling an assembly function from C++, use extern "C" to prevent C++ name mangling. Global variables in assembly must be declared as extern in C++ and marked .global in assembly. Inline assembly allows embedding ASM directly in C++ using the asm keyword. == See also == Carbon (programming language) Comparison of programming languages List of C++ compilers Outline of C++ Category:C++ libraries == Footnotes == == References == == Further reading == == External links == JTC1/SC22/WG21 – the ISO/IEC C++ Standard Working Group Standard C++ Foundation – a non-profit organization that promotes the use and understanding of standard C++. Bjarne Stroustrup is a director of the organization. C++ Keywords C++ Expressions C++ Operator Precedence
https://en.wikipedia.org/wiki/C%2B%2B
In mathematics, nonlinear programming (NLP) is the process of solving an optimization problem where some of the constraints are not linear equalities or the objective function is not a linear function. An optimization problem is one of calculation of the extrema (maxima, minima or stationary points) of an objective function over a set of unknown real variables and conditional to the satisfaction of a system of equalities and inequalities, collectively termed constraints. It is the sub-field of mathematical optimization that deals with problems that are not linear. == Definition and discussion == Let n, m, and p be positive integers. Let X be a subset of Rn (usually a box-constrained one), let f, gi, and hj be real-valued functions on X for each i in {1, ..., m} and each j in {1, ..., p}, with at least one of f, gi, and hj being nonlinear. A nonlinear programming problem is an optimization problem of the form minimize f ( x ) subject to g i ( x ) ≤ 0 for each i ∈ { 1 , … , m } h j ( x ) = 0 for each j ∈ { 1 , … , p } x ∈ X . {\displaystyle {\begin{aligned}{\text{minimize }}&f(x)\\{\text{subject to }}&g_{i}(x)\leq 0{\text{ for each }}i\in \{1,\dotsc ,m\}\\&h_{j}(x)=0{\text{ for each }}j\in \{1,\dotsc ,p\}\\&x\in X.\end{aligned}}} Depending on the constraint set, there are several possibilities: feasible problem is one for which there exists at least one set of values for the choice variables satisfying all the constraints. an infeasible problem is one for which no set of values for the choice variables satisfies all the constraints. That is, the constraints are mutually contradictory, and no solution exists; the feasible set is the empty set. unbounded problem is a feasible problem for which the objective function can be made to be better than any given finite value. Thus there is no optimal solution, because there is always a feasible solution that gives a better objective function value than does any given proposed solution. Most realistic applications feature feasible problems, with infeasible or unbounded problems seen as a failure of an underlying model. In some cases, infeasible problems are handled by minimizing a sum of feasibility violations. Some special cases of nonlinear programming have specialized solution methods: If the objective function is concave (maximization problem), or convex (minimization problem) and the constraint set is convex, then the program is called convex and general methods from convex optimization can be used in most cases. If the objective function is quadratic and the constraints are linear, quadratic programming techniques are used. If the objective function is a ratio of a concave and a convex function (in the maximization case) and the constraints are convex, then the problem can be transformed to a convex optimization problem using fractional programming techniques. == Applicability == A typical non-convex problem is that of optimizing transportation costs by selection from a set of transportation methods, one or more of which exhibit economies of scale, with various connectivities and capacity constraints. An example would be petroleum product transport given a selection or combination of pipeline, rail tanker, road tanker, river barge, or coastal tankship. Owing to economic batch size the cost functions may have discontinuities in addition to smooth changes. In experimental science, some simple data analysis (such as fitting a spectrum with a sum of peaks of known location and shape but unknown magnitude) can be done with linear methods, but in general these problems are also nonlinear. Typically, one has a theoretical model of the system under study with variable parameters in it and a model the experiment or experiments, which may also have unknown parameters. One tries to find a best fit numerically. In this case one often wants a measure of the precision of the result, as well as the best fit itself. == Methods for solving a general nonlinear program == === Analytic methods === Under differentiability and constraint qualifications, the Karush–Kuhn–Tucker (KKT) conditions provide necessary conditions for a solution to be optimal. If some of the functions are non-differentiable, subdifferential versions of Karush–Kuhn–Tucker (KKT) conditions are available. Under convexity, the KKT conditions are sufficient for a global optimum. Without convexity, these conditions are sufficient only for a local optimum. In some cases, the number of local optima is small, and one can find all of them analytically and find the one for which the objective value is smallest. === Numeric methods === In most realistic cases, it is very hard to solve the KKT conditions analytically, and so the problems are solved using numerical methods. These methods are iterative: they start with an initial point, and then proceed to points that are supposed to be closer to the optimal point, using some update rule. There are three kinds of update rules:: 5.1.2  Zero-order routines - use only the values of the objective function and constraint functions at the current point; First-order routines - use also the values of the gradients of these functions; Second-order routines - use also the values of the Hessians of these functions. Third-order routines (and higher) are theoretically possible, but not used in practice, due to the higher computational load and little theoretical benefit. === Branch and bound === Another method involves the use of branch and bound techniques, where the program is divided into subclasses to be solved with convex (minimization problem) or linear approximations that form a lower bound on the overall cost within the subdivision. With subsequent divisions, at some point an actual solution will be obtained whose cost is equal to the best lower bound obtained for any of the approximate solutions. This solution is optimal, although possibly not unique. The algorithm may also be stopped early, with the assurance that the best possible solution is within a tolerance from the best point found; such points are called ε-optimal. Terminating to ε-optimal points is typically necessary to ensure finite termination. This is especially useful for large, difficult problems and problems with uncertain costs or values where the uncertainty can be estimated with an appropriate reliability estimation. == Implementations == There exist numerous nonlinear programming solvers, including open source: ALGLIB (C++, C#, Java, Python API) implements several first-order and derivative-free nonlinear programming solvers NLopt (C/C++ implementation, with numerous interfaces including Julia, Python, R, MATLAB/Octave), includes various nonlinear programming solvers SciPy (de facto standard for scientific Python) has scipy.optimize solver, which includes several nonlinear programming algorithms (zero-order, first order and second order ones). IPOPT (C++ implementation, with numerous interfaces including C, Fortran, Java, AMPL, R, Python, etc.) is an interior point method solver (zero-order, and optionally first order and second order derivatives). == Numerical Examples == === 2-dimensional example === A simple problem (shown in the diagram) can be defined by the constraints x 1 ≥ 0 x 2 ≥ 0 x 1 2 + x 2 2 ≥ 1 x 1 2 + x 2 2 ≤ 2 {\displaystyle {\begin{aligned}x_{1}&\geq 0\\x_{2}&\geq 0\\x_{1}^{2}+x_{2}^{2}&\geq 1\\x_{1}^{2}+x_{2}^{2}&\leq 2\end{aligned}}} with an objective function to be maximized f ( x ) = x 1 + x 2 {\displaystyle f(\mathbf {x} )=x_{1}+x_{2}} where x = (x1, x2). === 3-dimensional example === Another simple problem (see diagram) can be defined by the constraints x 1 2 − x 2 2 + x 3 2 ≤ 2 x 1 2 + x 2 2 + x 3 2 ≤ 10 {\displaystyle {\begin{aligned}x_{1}^{2}-x_{2}^{2}+x_{3}^{2}&\leq 2\\x_{1}^{2}+x_{2}^{2}+x_{3}^{2}&\leq 10\end{aligned}}} with an objective function to be maximized f ( x ) = x 1 x 2 + x 2 x 3 {\displaystyle f(\mathbf {x} )=x_{1}x_{2}+x_{2}x_{3}} where x = (x1, x2, x3). == See also == Curve fitting Least squares minimization Linear programming nl (format) Nonlinear least squares List of optimization software Quadratically constrained quadratic programming Werner Fenchel, who created the foundation for nonlinear programming == References == == Further reading == Avriel, Mordecai (2003). Nonlinear Programming: Analysis and Methods. Dover Publishing. ISBN 0-486-43227-0. Bazaraa, Mokhtar S. and Shetty, C. M. (1979). Nonlinear programming. Theory and algorithms. John Wiley & Sons. ISBN 0-471-78610-1. Bonnans, J. Frédéric; Gilbert, J. Charles; Lemaréchal, Claude; Sagastizábal, Claudia A. (2006). Numerical optimization: Theoretical and practical aspects. Universitext (Second revised ed. of translation of 1997 French ed.). Berlin: Springer-Verlag. pp. xiv+490. doi:10.1007/978-3-540-35447-5. ISBN 3-540-35445-X. MR 2265882. Luenberger, David G.; Ye, Yinyu (2008). Linear and nonlinear programming. International Series in Operations Research & Management Science. Vol. 116 (Third ed.). New York: Springer. pp. xiv+546. ISBN 978-0-387-74502-2. MR 2423726. Nocedal, Jorge and Wright, Stephen J. (1999). Numerical Optimization. Springer. ISBN 0-387-98793-2. Jan Brinkhuis and Vladimir Tikhomirov, Optimization: Insights and Applications, 2005, Princeton University Press == External links == Mathematical Programming Glossary
https://en.wikipedia.org/wiki/Nonlinear_programming
Minification (also minimisation or minimization) is the process of removing all unnecessary characters from the source code of interpreted programming languages or markup languages without changing its functionality. These unnecessary characters usually include whitespace characters, new line characters, comments, and sometimes block delimiters, which are used to add readability to the code but are not required for it to execute. Minification reduces the size of the source code, making its transmission over a network (e.g. the Internet) more efficient. In programmer culture, aiming at extremely minified source code is the purpose of recreational code golf competitions and a part of the demoscene. Minification can be distinguished from the more general concept of data compression in that the minified source can be interpreted immediately without the need for a decompression step: the same interpreter can work with both the original as well as with the minified source. The goals of minification are not the same as the goals of obfuscation; the former is often intended to be reversed using a pretty-printer or unminifier. However, to achieve its goals, minification sometimes uses techniques also used by obfuscation; for example, shortening variable names and refactoring the source code. When minification uses such techniques, the pretty-printer or unminifier can only fully reverse the minification process if it is supplied details of the transformations done by such techniques. If not supplied those details, the reversed source code will contain different variable names and control flow, even though it will have the same functionality as the original source code. == Example == For example, the JavaScript code is equivalent to but longer than == History == In 2001 Douglas Crockford introduced JSMin, which removed comments and whitespace from JavaScript code. It was followed by YUI Compressor in 2007. In 2009, Google opened up its Closure toolkit, including Closure Compiler which contained a source mapping feature together with a Firefox extension called Closure Inspector. In 2010, Mihai Bazon introduced UglifyJS, which was superseded by UglifyJS2 in 2012; the rewrite was to allow for source map support. From 2017, Alex Lam took over maintenance and development of UglifyJS2, replacing it with UglifyJS3 which unified the CLI with the API. In 2018, Terser has been forked from uglify-es and has gained momentum since; in 2020 it outstripped UglifyJS when measured in daily downloads. == Source mapping == A source map is a file format that allows software tools for JavaScript to display different code to a user than the code actually executed by the computer. For example, to aid in debugging of minified code, by "mapping" this code to the original unminified source code instead. The original format was created by Joseph Schorr as part of the Closure Inspector minification project. Version 2 and 3 of the format reduced the size of the map files considerably. == Types == === Tools === Visual Studio Code comes with minification support for several languages. It can readily browse the Visual Studio Marketplace to download and install additional minifiers. JavaScript optimizers can minify and generate source maps. In addition certain online tools can compress CSS files. === Web development === Components and libraries for Web applications and websites have been developed to optimize file requests and reduce page load times by shrinking the size of various files. JavaScript and Cascading Style Sheets (CSS) resources may be minified, preserving their behavior while considerably reducing their file size. Libraries available online are capable of minification and optimization to varying degrees. Some libraries also merge multiple script files into a single file for client download. JavaScript source maps can make code readable and debuggable even after it has been combined and minified. == References ==
https://en.wikipedia.org/wiki/Minification_(programming)
Verse is a static typed object-oriented programming language created by Epic Games. It was released alongside UEFN in March 2023 and was authored by a team of well-known programmers led by Simon Peyton Jones, and Epic Games CEO Tim Sweeney. Verse is designed to interact with Fortnite Creative's existing ‍​devices system. As of June 2024, UEFN remains the only way to interpret, parse, compile or run Verse code; plans to implement the language into the release of Unreal Engine 6 have been discussed. == Features == === Modules and importing === Verse supports modular programming, allowing developers to import specific modules required for their scripts. Commonly used modules include the API digests that are generated every time a project containing verse is opened. There is an API digest to access and interact with Fortnite objects, Verse objects, and Unreal Engine objects. Developers can also create their own modules and import them into scripts if needed. === Classes and objects === Verse employs a class-based object-oriented programming model. Developers can define classes to represent various game entities and behaviors. For example: hello_world_device := class(creative_device): OnBegin<override>()<suspends>:void= Print("Hello, world!") Print("2 + 2 = {2 + 2}") The above code defines a new class inheriting from `creative_device` and prints the traditional "Hello, world" message. All classes inherited from a `creative_device' can be placed into the engine's spatial environment when compiled. The `creative_device` class is necessary to interact with the pre-existing Fortnite Creative toolset. === Functions and methods === Verse allows defining functions within classes. These can perform various operations, such as mathematical calculations, game logic, and more. The example below is a method to determine if a character is looking at a specific location. IsLookingAtLocation(Character:fort_character, LocationToCheck: vector3, Threshold: float):logic === Event handling === The language supports event-driven programming, where events like EliminatedEvent and PlayerAddedEvent can trigger specified functions. Events can also be subscribed to and listened for. === Mathematical and spatial operations === Verse supports various mathematical functions necessary for game development, such as calculating magnitudes, normalizing vectors, and converting rotations to direction vectors. The spatial math module provides classes and functions for vector and rotational math, essential for game development tasks like positioning and movement.Cos, Normalize, Distance , ArcTan, and Lerp are a few of the functions are available for mathematical operations. ==== Lambda calculus ==== Verse code shares several similarities with lambda calculus, particularly in how it handles functions and data. In lambda calculus, functions are first-class citizens, meaning they can be passed as arguments to other functions, returned as values from other functions, and assigned to variables; while in Verse functions can be passed around and manipulated similarly, showcasing the functional programming paradigm. Examples include methods like Normalize(v1:vector3) and DrawDebugLine(LineStart: vector3, LineEnd: vector3). Verse supports lambda expressions and anonymous functions, allowing for inline function definitions, similar to how lambda functions are used in languages like Python or JavaScript. Verse also allows for composing functions by chaining method calls and passing functions as parameters. The declarative style used in lambda calculus is also a prominent feature of Verse for defining data transformations and computations rather than an imperative control flow model. This is seen in functions like Normalize and DrawDebugLine which are defined declaratively. == Future plans == Epic Games has described Verse as the programming language for the metaverse and has factored mass scalability into its development. Until the proposed convergence with Unreal Engine, it is yet to be seen how Verse will behave interacting with various systems and processes outside of the Fortnite ecosystem. == References == == External links == Official website
https://en.wikipedia.org/wiki/Verse_(programming_language)
Cargo cult programming is a style of computer programming characterized by the ritual inclusion of code or program structures that serve no real purpose. Cargo cult programming is symptomatic of a programmer not understanding either a bug they were attempting to solve or the apparent solution (compare shotgun debugging, deep magic). The term cargo cult programmer may apply when anyone inexperienced with the problem at hand copies some program code from one place to another with little understanding of how it works or whether it is required. Cargo cult programming can also refer to the practice of applying a design pattern or coding style blindly without understanding the reasons behind that design principle. Some examples are adding unnecessary comments to self-explanatory code, overzealous adherence to the conventions of a programming paradigm, or adding deletion code for objects that garbage collection automatically collects. == Etymology == Cargo cults are millenarian movements that arose in Melanesia under colonial rule, and inspired Richard Feynman to coin the expression cargo cult science. In Feynman's description, after the end of the Second World War practitioners believed that air delivery of cargo would resume if they carried out the proper rituals, such as building runways, lighting fires next to them, and wearing headphones carved from wood while sitting in fabricated control towers. "The form is perfect. It looks exactly the way it looked before. But it doesn’t work." The term then became used more widely as a metaphor for empty rituals. The term "cargo-cult programming" appeared in version 2.5.1 of the Jargon File, a glossary of computing slang, released in January 1991. The term "cargo cult" in anthropology, meanwhile, is increasingly avoided for failing to represent the complexity of Melanesian beliefs. == Cargo cult software engineering == A related term to cargo cult programming in software engineering is cargo cult software engineering, coined by Steve McConnell.: 23-26  McConnell describes software development organizations that attempt to emulate more successful development houses, either by slavishly following a software development process without understanding the reasoning behind it, or by attempting to emulate a commitment-oriented development approach (in which software developers devote large amounts of time and energy toward seeing their projects succeed) by mandating the long hours and unpaid overtime, while in successful companies these might instead be consequences of high motivation instead of causes of success. In both cases, McConnell contends that competence ultimately determines whether a project succeeds or fails, regardless of the development approach taken; furthermore, he claims that incompetent "imposter organizations" (which merely imitate the form of successful software development organizations) are in fact engaging in what he calls cargo cult software engineering.: 11–13  == See also == Black box Cargo cult science Copy-and-paste programming GitHub Copilot Magic (programming) Magical thinking Vibe coding == References == == Further reading ==
https://en.wikipedia.org/wiki/Cargo_cult_programming
In the field of mathematical optimization, stochastic programming is a framework for modeling optimization problems that involve uncertainty. A stochastic program is an optimization problem in which some or all problem parameters are uncertain, but follow known probability distributions. This framework contrasts with deterministic optimization, in which all problem parameters are assumed to be known exactly. The goal of stochastic programming is to find a decision which both optimizes some criteria chosen by the decision maker, and appropriately accounts for the uncertainty of the problem parameters. Because many real-world decisions involve uncertainty, stochastic programming has found applications in a broad range of areas ranging from finance to transportation to energy optimization. == Methods == Several stochastic programming methods have been developed: Scenario-based methods including Sample Average Approximation Stochastic integer programming for problems in which some variables must be integers Chance constrained programming for dealing with constraints that must be satisfied with a given probability Stochastic dynamic programming Markov decision process Benders decomposition == Two-stage problem definition == The basic idea of two-stage stochastic programming is that (optimal) decisions should be based on data available at the time the decisions are made and cannot depend on future observations. The two-stage formulation is widely used in stochastic programming. The general formulation of a two-stage stochastic programming problem is given by: min x ∈ X { g ( x ) = f ( x ) + E ξ [ Q ( x , ξ ) ] } {\displaystyle \min _{x\in X}\{g(x)=f(x)+E_{\xi }[Q(x,\xi )]\}} where Q ( x , ξ ) {\displaystyle Q(x,\xi )} is the optimal value of the second-stage problem min y { q ( y , ξ ) | T ( ξ ) x + W ( ξ ) y = h ( ξ ) } . {\displaystyle \min _{y}\{q(y,\xi )\,|\,T(\xi )x+W(\xi )y=h(\xi )\}.} The classical two-stage linear stochastic programming problems can be formulated as min x ∈ R n g ( x ) = c T x + E ξ [ Q ( x , ξ ) ] subject to A x = b x ≥ 0 {\displaystyle {\begin{array}{llr}\min \limits _{x\in \mathbb {R} ^{n}}&g(x)=c^{T}x+E_{\xi }[Q(x,\xi )]&\\{\text{subject to}}&Ax=b&\\&x\geq 0&\end{array}}} where Q ( x , ξ ) {\displaystyle Q(x,\xi )} is the optimal value of the second-stage problem min y ∈ R m q ( ξ ) T y subject to T ( ξ ) x + W ( ξ ) y = h ( ξ ) y ≥ 0 {\displaystyle {\begin{array}{llr}\min \limits _{y\in \mathbb {R} ^{m}}&q(\xi )^{T}y&\\{\text{subject to}}&T(\xi )x+W(\xi )y=h(\xi )&\\&y\geq 0&\end{array}}} In such formulation x ∈ R n {\displaystyle x\in \mathbb {R} ^{n}} is the first-stage decision variable vector, y ∈ R m {\displaystyle y\in \mathbb {R} ^{m}} is the second-stage decision variable vector, and ξ ( q , T , W , h ) {\displaystyle \xi (q,T,W,h)} contains the data of the second-stage problem. In this formulation, at the first stage we have to make a "here-and-now" decision x {\displaystyle x} before the realization of the uncertain data ξ {\displaystyle \xi } , viewed as a random vector, is known. At the second stage, after a realization of ξ {\displaystyle \xi } becomes available, we optimize our behavior by solving an appropriate optimization problem. At the first stage we optimize (minimize in the above formulation) the cost c T x {\displaystyle c^{T}x} of the first-stage decision plus the expected cost of the (optimal) second-stage decision. We can view the second-stage problem simply as an optimization problem which describes our supposedly optimal behavior when the uncertain data is revealed, or we can consider its solution as a recourse action where the term W y {\displaystyle Wy} compensates for a possible inconsistency of the system T x ≤ h {\displaystyle Tx\leq h} and q T y {\displaystyle q^{T}y} is the cost of this recourse action. The considered two-stage problem is linear because the objective functions and the constraints are linear. Conceptually this is not essential and one can consider more general two-stage stochastic programs. For example, if the first-stage problem is integer, one could add integrality constraints to the first-stage problem so that the feasible set is discrete. Non-linear objectives and constraints could also be incorporated if needed. === Distributional assumption === The formulation of the above two-stage problem assumes that the second-stage data ξ {\displaystyle \xi } is modeled as a random vector with a known probability distribution. This would be justified in many situations. For example, the distribution of ξ {\displaystyle \xi } could be inferred from historical data if one assumes that the distribution does not significantly change over the considered period of time. Also, the empirical distribution of the sample could be used as an approximation to the distribution of the future values of ξ {\displaystyle \xi } . If one has a prior model for ξ {\displaystyle \xi } , one could obtain a posteriori distribution by a Bayesian update. == Scenario-based approach == === Discretization === To solve the two-stage stochastic problem numerically, one often needs to assume that the random vector ξ {\displaystyle \xi } has a finite number of possible realizations, called scenarios, say ξ 1 , … , ξ K {\displaystyle \xi _{1},\dots ,\xi _{K}} , with respective probability masses p 1 , … , p K {\displaystyle p_{1},\dots ,p_{K}} . Then the expectation in the first-stage problem's objective function can be written as the summation: E [ Q ( x , ξ ) ] = ∑ k = 1 K p k Q ( x , ξ k ) {\displaystyle E[Q(x,\xi )]=\sum \limits _{k=1}^{K}p_{k}Q(x,\xi _{k})} and, moreover, the two-stage problem can be formulated as one large linear programming problem (this is called the deterministic equivalent of the original problem, see section § Deterministic equivalent of a stochastic problem). When ξ {\displaystyle \xi } has an infinite (or very large) number of possible realizations the standard approach is then to represent this distribution by scenarios. This approach raises three questions, namely: How to construct scenarios, see § Scenario construction; How to solve the deterministic equivalent. Optimizers such as CPLEX, and GLPK can solve large linear/nonlinear problems. The NEOS Server, hosted at the University of Wisconsin, Madison, allows free access to many modern solvers. The structure of a deterministic equivalent is particularly amenable to apply decomposition methods, such as Benders' decomposition or scenario decomposition; How to measure quality of the obtained solution with respect to the "true" optimum. These questions are not independent. For example, the number of scenarios constructed will affect both the tractability of the deterministic equivalent and the quality of the obtained solutions. === Stochastic linear programming === A stochastic linear program is a specific instance of the classical two-stage stochastic program. A stochastic LP is built from a collection of multi-period linear programs (LPs), each having the same structure but somewhat different data. The k t h {\displaystyle k^{th}} two-period LP, representing the k t h {\displaystyle k^{th}} scenario, may be regarded as having the following form: Minimize f T x + g T y + h k T z k subject to T x + U y = r V k y + W k z k = s k x , y , z k ≥ 0 {\displaystyle {\begin{array}{lccccccc}{\text{Minimize}}&f^{T}x&+&g^{T}y&+&h_{k}^{T}z_{k}&&\\{\text{subject to}}&Tx&+&Uy&&&=&r\\&&&V_{k}y&+&W_{k}z_{k}&=&s_{k}\\&x&,&y&,&z_{k}&\geq &0\end{array}}} The vectors x {\displaystyle x} and y {\displaystyle y} contain the first-period variables, whose values must be chosen immediately. The vector z k {\displaystyle z_{k}} contains all of the variables for subsequent periods. The constraints T x + U y = r {\displaystyle Tx+Uy=r} involve only first-period variables and are the same in every scenario. The other constraints involve variables of later periods and differ in some respects from scenario to scenario, reflecting uncertainty about the future. Note that solving the k t h {\displaystyle k^{th}} two-period LP is equivalent to assuming the k t h {\displaystyle k^{th}} scenario in the second period with no uncertainty. In order to incorporate uncertainties in the second stage, one should assign probabilities to different scenarios and solve the corresponding deterministic equivalent. ==== Deterministic equivalent of a stochastic problem ==== With a finite number of scenarios, two-stage stochastic linear programs can be modelled as large linear programming problems. This formulation is often called the deterministic equivalent linear program, or abbreviated to deterministic equivalent. (Strictly speaking a deterministic equivalent is any mathematical program that can be used to compute the optimal first-stage decision, so these will exist for continuous probability distributions as well, when one can represent the second-stage cost in some closed form.) For example, to form the deterministic equivalent to the above stochastic linear program, we assign a probability p k {\displaystyle p_{k}} to each scenario k = 1 , … , K {\displaystyle k=1,\dots ,K} . Then we can minimize the expected value of the objective, subject to the constraints from all scenarios: Minimize f ⊤ x + g ⊤ y + p 1 h 1 ⊤ z 1 + p 2 h 2 T z 2 + ⋯ + p K h K ⊤ z K subject to T x + U y = r V 1 y + W 1 z 1 = s 1 V 2 y + W 2 z 2 = s 2 ⋮ ⋱ ⋮ V K y + W K z K = s K x , y , z 1 , z 2 , … , z K ≥ 0 {\displaystyle {\begin{array}{lccccccccccccc}{\text{Minimize}}&f^{\top }x&+&g^{\top }y&+&p_{1}h_{1}^{\top }z_{1}&+&p_{2}h_{2}^{T}z_{2}&+&\cdots &+&p_{K}h_{K}^{\top }z_{K}&&\\{\text{subject to}}&Tx&+&Uy&&&&&&&&&=&r\\&&&V_{1}y&+&W_{1}z_{1}&&&&&&&=&s_{1}\\&&&V_{2}y&&&+&W_{2}z_{2}&&&&&=&s_{2}\\&&&\vdots &&&&&&\ddots &&&&\vdots \\&&&V_{K}y&&&&&&&+&W_{K}z_{K}&=&s_{K}\\&x&,&y&,&z_{1}&,&z_{2}&,&\ldots &,&z_{K}&\geq &0\\\end{array}}} We have a different vector z k {\displaystyle z_{k}} of later-period variables for each scenario k {\displaystyle k} . The first-period variables x {\displaystyle x} and y {\displaystyle y} are the same in every scenario, however, because we must make a decision for the first period before we know which scenario will be realized. As a result, the constraints involving just x {\displaystyle x} and y {\displaystyle y} need only be specified once, while the remaining constraints must be given separately for each scenario. === Scenario construction === In practice it might be possible to construct scenarios by eliciting experts' opinions on the future. The number of constructed scenarios should be relatively modest so that the obtained deterministic equivalent can be solved with reasonable computational effort. It is often claimed that a solution that is optimal using only a few scenarios provides more adaptable plans than one that assumes a single scenario only. In some cases such a claim could be verified by a simulation. In theory some measures of guarantee that an obtained solution solves the original problem with reasonable accuracy. Typically in applications only the first stage optimal solution x ∗ {\displaystyle x^{*}} has a practical value since almost always a "true" realization of the random data will be different from the set of constructed (generated) scenarios. Suppose ξ {\displaystyle \xi } contains d {\displaystyle d} independent random components, each of which has three possible realizations (for example, future realizations of each random parameters are classified as low, medium and high), then the total number of scenarios is K = 3 d {\displaystyle K=3^{d}} . Such exponential growth of the number of scenarios makes model development using expert opinion very difficult even for reasonable size d {\displaystyle d} . The situation becomes even worse if some random components of ξ {\displaystyle \xi } have continuous distributions. ==== Monte Carlo sampling and Sample Average Approximation (SAA) Method ==== A common approach to reduce the scenario set to a manageable size is by using Monte Carlo simulation. Suppose the total number of scenarios is very large or even infinite. Suppose further that we can generate a sample ξ 1 , ξ 2 , … , ξ N {\displaystyle \xi ^{1},\xi ^{2},\dots ,\xi ^{N}} of N {\displaystyle N} realizations of the random vector ξ {\displaystyle \xi } . Usually the sample is assumed to be independent and identically distributed (i.i.d sample). Given a sample, the expectation function q ( x ) = E [ Q ( x , ξ ) ] {\displaystyle q(x)=E[Q(x,\xi )]} is approximated by the sample average q ^ N ( x ) = 1 N ∑ j = 1 N Q ( x , ξ j ) {\displaystyle {\hat {q}}_{N}(x)={\frac {1}{N}}\sum _{j=1}^{N}Q(x,\xi ^{j})} and consequently the first-stage problem is given by g ^ N ( x ) = min x ∈ R n c T x + 1 N ∑ j = 1 N Q ( x , ξ j ) subject to A x = b x ≥ 0 {\displaystyle {\begin{array}{rlrrr}{\hat {g}}_{N}(x)=&\min \limits _{x\in \mathbb {R} ^{n}}&c^{T}x+{\frac {1}{N}}\sum _{j=1}^{N}Q(x,\xi ^{j})&\\&{\text{subject to}}&Ax&=&b\\&&x&\geq &0\end{array}}} This formulation is known as the Sample Average Approximation method. The SAA problem is a function of the considered sample and in that sense is random. For a given sample ξ 1 , ξ 2 , … , ξ N {\displaystyle \xi ^{1},\xi ^{2},\dots ,\xi ^{N}} the SAA problem is of the same form as a two-stage stochastic linear programming problem with the scenarios ξ j {\displaystyle \xi ^{j}} ., j = 1 , … , N {\displaystyle j=1,\dots ,N} , each taken with the same probability p j = 1 N {\displaystyle p_{j}={\frac {1}{N}}} . === Statistical inference === Consider the following stochastic programming problem Here X {\displaystyle X} is a nonempty closed subset of R n {\displaystyle \mathbb {R} ^{n}} , ξ {\displaystyle \xi } is a random vector whose probability distribution P {\displaystyle P} is supported on a set Ξ ⊂ R d {\displaystyle \Xi \subset \mathbb {R} ^{d}} , and Q : X × Ξ → R {\displaystyle Q:X\times \Xi \rightarrow \mathbb {R} } . In the framework of two-stage stochastic programming, Q ( x , ξ ) {\displaystyle Q(x,\xi )} is given by the optimal value of the corresponding second-stage problem. Assume that g ( x ) {\displaystyle g(x)} is well defined and finite valued for all x ∈ X {\displaystyle x\in X} . This implies that for every x ∈ X {\displaystyle x\in X} the value Q ( x , ξ ) {\displaystyle Q(x,\xi )} is finite almost surely. Suppose that we have a sample ξ 1 , … , ξ N {\displaystyle \xi ^{1},\dots ,\xi ^{N}} of N {\displaystyle N} realizations of the random vector ξ {\displaystyle \xi } . This random sample can be viewed as historical data of N {\displaystyle N} observations of ξ {\displaystyle \xi } , or it can be generated by Monte Carlo sampling techniques. Then we can formulate a corresponding sample average approximation By the law of large numbers we have that, under some regularity conditions 1 N ∑ j = 1 N Q ( x , ξ j ) {\displaystyle {\frac {1}{N}}\sum _{j=1}^{N}Q(x,\xi ^{j})} converges pointwise with probability 1 to E [ Q ( x , ξ ) ] {\displaystyle E[Q(x,\xi )]} as N → ∞ {\displaystyle N\rightarrow \infty } . Moreover, under mild additional conditions the convergence is uniform. We also have E [ g ^ N ( x ) ] = g ( x ) {\displaystyle E[{\hat {g}}_{N}(x)]=g(x)} , i.e., g ^ N ( x ) {\displaystyle {\hat {g}}_{N}(x)} is an unbiased estimator of g ( x ) {\displaystyle g(x)} . Therefore, it is natural to expect that the optimal value and optimal solutions of the SAA problem converge to their counterparts of the true problem as N → ∞ {\displaystyle N\rightarrow \infty } . ==== Consistency of SAA estimators ==== Suppose the feasible set X {\displaystyle X} of the SAA problem is fixed, i.e., it is independent of the sample. Let ϑ ∗ {\displaystyle \vartheta ^{*}} and S ∗ {\displaystyle S^{*}} be the optimal value and the set of optimal solutions, respectively, of the true problem and let ϑ ^ N {\displaystyle {\hat {\vartheta }}_{N}} and S ^ N {\displaystyle {\hat {S}}_{N}} be the optimal value and the set of optimal solutions, respectively, of the SAA problem. Let g : X → R {\displaystyle g:X\rightarrow \mathbb {R} } and g ^ N : X → R {\displaystyle {\hat {g}}_{N}:X\rightarrow \mathbb {R} } be a sequence of (deterministic) real valued functions. The following two properties are equivalent: for any x ¯ ∈ X {\displaystyle {\overline {x}}\in X} and any sequence { x N } ⊂ X {\displaystyle \{x_{N}\}\subset X} converging to x ¯ {\displaystyle {\overline {x}}} it follows that g ^ N ( x N ) {\displaystyle {\hat {g}}_{N}(x_{N})} converges to g ( x ¯ ) {\displaystyle g({\overline {x}})} the function g ( ⋅ ) {\displaystyle g(\cdot )} is continuous on X {\displaystyle X} and g ^ N ( ⋅ ) {\displaystyle {\hat {g}}_{N}(\cdot )} converges to g ( ⋅ ) {\displaystyle g(\cdot )} uniformly on any compact subset of X {\displaystyle X} If the objective of the SAA problem g ^ N ( x ) {\displaystyle {\hat {g}}_{N}(x)} converges to the true problem's objective g ( x ) {\displaystyle g(x)} with probability 1, as N → ∞ {\displaystyle N\rightarrow \infty } , uniformly on the feasible set X {\displaystyle X} . Then ϑ ^ N {\displaystyle {\hat {\vartheta }}_{N}} converges to ϑ ∗ {\displaystyle \vartheta ^{*}} with probability 1 as N → ∞ {\displaystyle N\rightarrow \infty } . Suppose that there exists a compact set C ⊂ R n {\displaystyle C\subset \mathbb {R} ^{n}} such that the set S {\displaystyle S} of optimal solutions of the true problem is nonempty and is contained in C {\displaystyle C} the function g ( x ) {\displaystyle g(x)} is finite valued and continuous on C {\displaystyle C} the sequence of functions g ^ N ( x ) {\displaystyle {\hat {g}}_{N}(x)} converges to g ( x ) {\displaystyle g(x)} with probability 1, as N → ∞ {\displaystyle N\rightarrow \infty } , uniformly in x ∈ C {\displaystyle x\in C} for N {\displaystyle N} large enough the set S ^ N {\displaystyle {\hat {S}}_{N}} is nonempty and S ^ N ⊂ C {\displaystyle {\hat {S}}_{N}\subset C} with probability 1 then ϑ ^ N → ϑ ∗ {\displaystyle {\hat {\vartheta }}_{N}\rightarrow \vartheta ^{*}} and D ( S ∗ , S ^ N ) → 0 {\displaystyle \mathbb {D} (S^{*},{\hat {S}}_{N})\rightarrow 0} with probability 1 as N → ∞ {\displaystyle N\rightarrow \infty } . Note that D ( A , B ) {\displaystyle \mathbb {D} (A,B)} denotes the deviation of set A {\displaystyle A} from set B {\displaystyle B} , defined as In some situations the feasible set X {\displaystyle X} of the SAA problem is estimated, then the corresponding SAA problem takes the form where X N {\displaystyle X_{N}} is a subset of R n {\displaystyle \mathbb {R} ^{n}} depending on the sample and therefore is random. Nevertheless, consistency results for SAA estimators can still be derived under some additional assumptions: Suppose that there exists a compact set C ⊂ R n {\displaystyle C\subset \mathbb {R} ^{n}} such that the set S {\displaystyle S} of optimal solutions of the true problem is nonempty and is contained in C {\displaystyle C} the function g ( x ) {\displaystyle g(x)} is finite valued and continuous on C {\displaystyle C} the sequence of functions g ^ N ( x ) {\displaystyle {\hat {g}}_{N}(x)} converges to g ( x ) {\displaystyle g(x)} with probability 1, as N → ∞ {\displaystyle N\rightarrow \infty } , uniformly in x ∈ C {\displaystyle x\in C} for N {\displaystyle N} large enough the set S ^ N {\displaystyle {\hat {S}}_{N}} is nonempty and S ^ N ⊂ C {\displaystyle {\hat {S}}_{N}\subset C} with probability 1 if x N ∈ X N {\displaystyle x_{N}\in X_{N}} and x N {\displaystyle x_{N}} converges with probability 1 to a point x {\displaystyle x} , then x ∈ X {\displaystyle x\in X} for some point x ∈ S ∗ {\displaystyle x\in S^{*}} there exists a sequence x N ∈ X N {\displaystyle x_{N}\in X_{N}} such that x N → x {\displaystyle x_{N}\rightarrow x} with probability 1. then ϑ ^ N → ϑ ∗ {\displaystyle {\hat {\vartheta }}_{N}\rightarrow \vartheta ^{*}} and D ( S ∗ , S ^ N ) → 0 {\displaystyle \mathbb {D} (S^{*},{\hat {S}}_{N})\rightarrow 0} with probability 1 as N → ∞ {\displaystyle N\rightarrow \infty } . ==== Asymptotics of the SAA optimal value ==== Suppose the sample ξ 1 , … , ξ N {\displaystyle \xi ^{1},\dots ,\xi ^{N}} is i.i.d. and fix a point x ∈ X {\displaystyle x\in X} . Then the sample average estimator g ^ N ( x ) {\displaystyle {\hat {g}}_{N}(x)} , of g ( x ) {\displaystyle g(x)} , is unbiased and has variance 1 N σ 2 ( x ) {\displaystyle {\frac {1}{N}}\sigma ^{2}(x)} , where σ 2 ( x ) := V a r [ Q ( x , ξ ) ] {\displaystyle \sigma ^{2}(x):=Var[Q(x,\xi )]} is supposed to be finite. Moreover, by the central limit theorem we have that where → D {\displaystyle {\xrightarrow {\mathcal {D}}}} denotes convergence in distribution and Y x {\displaystyle Y_{x}} has a normal distribution with mean 0 {\displaystyle 0} and variance σ 2 ( x ) {\displaystyle \sigma ^{2}(x)} , written as N ( 0 , σ 2 ( x ) ) {\displaystyle {\mathcal {N}}(0,\sigma ^{2}(x))} . In other words, g ^ N ( x ) {\displaystyle {\hat {g}}_{N}(x)} has asymptotically normal distribution, i.e., for large N {\displaystyle N} , g ^ N ( x ) {\displaystyle {\hat {g}}_{N}(x)} has approximately normal distribution with mean g ( x ) {\displaystyle g(x)} and variance 1 N σ 2 ( x ) {\displaystyle {\frac {1}{N}}\sigma ^{2}(x)} . This leads to the following (approximate) 100 ( 1 − α ) {\displaystyle 100(1-\alpha )} % confidence interval for f ( x ) {\displaystyle f(x)} : where z α / 2 := Φ − 1 ( 1 − α / 2 ) {\displaystyle z_{\alpha /2}:=\Phi ^{-1}(1-\alpha /2)} (here Φ ( ⋅ ) {\displaystyle \Phi (\cdot )} denotes the cdf of the standard normal distribution) and is the sample variance estimate of σ 2 ( x ) {\displaystyle \sigma ^{2}(x)} . That is, the error of estimation of g ( x ) {\displaystyle g(x)} is (stochastically) of order O ( N ) {\displaystyle O({\sqrt {N}})} . == Applications and examples == === Biological applications === Stochastic dynamic programming is frequently used to model animal behaviour in such fields as behavioural ecology. Empirical tests of models of optimal foraging, life-history transitions such as fledging in birds and egg laying in parasitoid wasps have shown the value of this modelling technique in explaining the evolution of behavioural decision making. These models are typically many-staged, rather than two-staged. === Economic applications === Stochastic dynamic programming is a useful tool in understanding decision making under uncertainty. The accumulation of capital stock under uncertainty is one example; often it is used by resource economists to analyze bioeconomic problems where the uncertainty enters in such as weather, etc. === Example: multistage portfolio optimization === The following is an example from finance of multi-stage stochastic programming. Suppose that at time t = 0 {\displaystyle t=0} we have initial capital W 0 {\displaystyle W_{0}} to invest in n {\displaystyle n} assets. Suppose further that we are allowed to rebalance our portfolio at times t = 1 , … , T − 1 {\displaystyle t=1,\dots ,T-1} but without injecting additional cash into it. At each period t {\displaystyle t} we make a decision about redistributing the current wealth W t {\displaystyle W_{t}} among the n {\displaystyle n} assets. Let x 0 = ( x 10 , … , x n 0 ) {\displaystyle x_{0}=(x_{10},\dots ,x_{n0})} be the initial amounts invested in the n assets. We require that each x i 0 {\displaystyle x_{i0}} is nonnegative and that the balance equation ∑ i = 1 n x i 0 = W 0 {\displaystyle \sum _{i=1}^{n}x_{i0}=W_{0}} should hold. Consider the total returns ξ t = ( ξ 1 t , … , ξ n t ) {\displaystyle \xi _{t}=(\xi _{1t},\dots ,\xi _{nt})} for each period t = 1 , … , T {\displaystyle t=1,\dots ,T} . This forms a vector-valued random process ξ 1 , … , ξ T {\displaystyle \xi _{1},\dots ,\xi _{T}} . At time period t = 1 {\displaystyle t=1} , we can rebalance the portfolio by specifying the amounts x 1 = ( x 11 , … , x n 1 ) {\displaystyle x_{1}=(x_{11},\dots ,x_{n1})} invested in the respective assets. At that time the returns in the first period have been realized so it is reasonable to use this information in the rebalancing decision. Thus, the second-stage decisions, at time t = 1 {\displaystyle t=1} , are actually functions of realization of the random vector ξ 1 {\displaystyle \xi _{1}} , i.e., x 1 = x 1 ( ξ 1 ) {\displaystyle x_{1}=x_{1}(\xi _{1})} . Similarly, at time t {\displaystyle t} the decision x t = ( x 1 t , … , x n t ) {\displaystyle x_{t}=(x_{1t},\dots ,x_{nt})} is a function x t = x t ( ξ [ t ] ) {\displaystyle x_{t}=x_{t}(\xi _{[t]})} of the available information given by ξ [ t ] = ( ξ 1 , … , ξ t ) {\displaystyle \xi _{[t]}=(\xi _{1},\dots ,\xi _{t})} the history of the random process up to time t {\displaystyle t} . A sequence of functions x t = x t ( ξ [ t ] ) {\displaystyle x_{t}=x_{t}(\xi _{[t]})} , t = 0 , … , T − 1 {\displaystyle t=0,\dots ,T-1} , with x 0 {\displaystyle x_{0}} being constant, defines an implementable policy of the decision process. It is said that such a policy is feasible if it satisfies the model constraints with probability 1, i.e., the nonnegativity constraints x i t ( ξ [ t ] ) ≥ 0 {\displaystyle x_{it}(\xi _{[t]})\geq 0} , i = 1 , … , n {\displaystyle i=1,\dots ,n} , t = 0 , … , T − 1 {\displaystyle t=0,\dots ,T-1} , and the balance of wealth constraints, ∑ i = 1 n x i t ( ξ [ t ] ) = W t , {\displaystyle \sum _{i=1}^{n}x_{it}(\xi _{[t]})=W_{t},} where in period t = 1 , … , T {\displaystyle t=1,\dots ,T} the wealth W t {\displaystyle W_{t}} is given by W t = ∑ i = 1 n ξ i t x i , t − 1 ( ξ [ t − 1 ] ) , {\displaystyle W_{t}=\sum _{i=1}^{n}\xi _{it}x_{i,t-1}(\xi _{[t-1]}),} which depends on the realization of the random process and the decisions up to time t {\displaystyle t} . Suppose the objective is to maximize the expected utility of this wealth at the last period, that is, to consider the problem max E [ U ( W T ) ] . {\displaystyle \max E[U(W_{T})].} This is a multistage stochastic programming problem, where stages are numbered from t = 0 {\displaystyle t=0} to t = T − 1 {\displaystyle t=T-1} . Optimization is performed over all implementable and feasible policies. To complete the problem description one also needs to define the probability distribution of the random process ξ 1 , … , ξ T {\displaystyle \xi _{1},\dots ,\xi _{T}} . This can be done in various ways. For example, one can construct a particular scenario tree defining time evolution of the process. If at every stage the random return of each asset is allowed to have two continuations, independent of other assets, then the total number of scenarios is 2 n T . {\displaystyle 2^{nT}.} In order to write dynamic programming equations, consider the above multistage problem backward in time. At the last stage t = T − 1 {\displaystyle t=T-1} , a realization ξ [ T − 1 ] = ( ξ 1 , … , ξ T − 1 ) {\displaystyle \xi _{[T-1]}=(\xi _{1},\dots ,\xi _{T-1})} of the random process is known and x T − 2 {\displaystyle x_{T-2}} has been chosen. Therefore, one needs to solve the following problem max x T − 1 E [ U ( W T ) | ξ [ T − 1 ] ] subject to W T = ∑ i = 1 n ξ i T x i , T − 1 ∑ i = 1 n x i , T − 1 = W T − 1 x T − 1 ≥ 0 {\displaystyle {\begin{array}{lrclr}\max \limits _{x_{T-1}}&E[U(W_{T})|\xi _{[T-1]}]&\\{\text{subject to}}&W_{T}&=&\sum _{i=1}^{n}\xi _{iT}x_{i,T-1}\\&\sum _{i=1}^{n}x_{i,T-1}&=&W_{T-1}\\&x_{T-1}&\geq &0\end{array}}} where E [ U ( W T ) | ξ [ T − 1 ] ] {\displaystyle E[U(W_{T})|\xi _{[T-1]}]} denotes the conditional expectation of U ( W T ) {\displaystyle U(W_{T})} given ξ [ T − 1 ] {\displaystyle \xi _{[T-1]}} . The optimal value of the above problem depends on W T − 1 {\displaystyle W_{T-1}} and ξ [ T − 1 ] {\displaystyle \xi _{[T-1]}} and is denoted Q T − 1 ( W T − 1 , ξ [ T − 1 ] ) {\displaystyle Q_{T-1}(W_{T-1},\xi _{[T-1]})} . Similarly, at stages t = T − 2 , … , 1 {\displaystyle t=T-2,\dots ,1} , one should solve the problem max x t E [ Q t + 1 ( W t + 1 , ξ [ t + 1 ] ) | ξ [ t ] ] subject to W t + 1 = ∑ i = 1 n ξ i , t + 1 x i , t ∑ i = 1 n x i , t = W t x t ≥ 0 {\displaystyle {\begin{array}{lrclr}\max \limits _{x_{t}}&E[Q_{t+1}(W_{t+1},\xi _{[t+1]})|\xi _{[t]}]&\\{\text{subject to}}&W_{t+1}&=&\sum _{i=1}^{n}\xi _{i,t+1}x_{i,t}\\&\sum _{i=1}^{n}x_{i,t}&=&W_{t}\\&x_{t}&\geq &0\end{array}}} whose optimal value is denoted by Q t ( W t , ξ [ t ] ) {\displaystyle Q_{t}(W_{t},\xi _{[t]})} . Finally, at stage t = 0 {\displaystyle t=0} , one solves the problem max x 0 E [ Q 1 ( W 1 , ξ [ 1 ] ) ] subject to W 1 = ∑ i = 1 n ξ i , 1 x i 0 ∑ i = 1 n x i 0 = W 0 x 0 ≥ 0 {\displaystyle {\begin{array}{lrclr}\max \limits _{x_{0}}&E[Q_{1}(W_{1},\xi _{[1]})]&\\{\text{subject to}}&W_{1}&=&\sum _{i=1}^{n}\xi _{i,1}x_{i0}\\&\sum _{i=1}^{n}x_{i0}&=&W_{0}\\&x_{0}&\geq &0\end{array}}} ==== Stagewise independent random process ==== For a general distribution of the process ξ t {\displaystyle \xi _{t}} , it may be hard to solve these dynamic programming equations. The situation simplifies dramatically if the process ξ t {\displaystyle \xi _{t}} is stagewise independent, i.e., ξ t {\displaystyle \xi _{t}} is (stochastically) independent of ξ 1 , … , ξ t − 1 {\displaystyle \xi _{1},\dots ,\xi _{t-1}} for t = 2 , … , T {\displaystyle t=2,\dots ,T} . In this case, the corresponding conditional expectations become unconditional expectations, and the function Q t ( W t ) {\displaystyle Q_{t}(W_{t})} , t = 1 , … , T − 1 {\displaystyle t=1,\dots ,T-1} does not depend on ξ [ t ] {\displaystyle \xi _{[t]}} . That is, Q T − 1 ( W T − 1 ) {\displaystyle Q_{T-1}(W_{T-1})} is the optimal value of the problem max x T − 1 E [ U ( W T ) ] subject to W T = ∑ i = 1 n ξ i T x i , T − 1 ∑ i = 1 n x i , T − 1 = W T − 1 x T − 1 ≥ 0 {\displaystyle {\begin{array}{lrclr}\max \limits _{x_{T-1}}&E[U(W_{T})]&\\{\text{subject to}}&W_{T}&=&\sum _{i=1}^{n}\xi _{iT}x_{i,T-1}\\&\sum _{i=1}^{n}x_{i,T-1}&=&W_{T-1}\\&x_{T-1}&\geq &0\end{array}}} and Q t ( W t ) {\displaystyle Q_{t}(W_{t})} is the optimal value of max x t E [ Q t + 1 ( W t + 1 ) ] subject to W t + 1 = ∑ i = 1 n ξ i , t + 1 x i , t ∑ i = 1 n x i , t = W t x t ≥ 0 {\displaystyle {\begin{array}{lrclr}\max \limits _{x_{t}}&E[Q_{t+1}(W_{t+1})]&\\{\text{subject to}}&W_{t+1}&=&\sum _{i=1}^{n}\xi _{i,t+1}x_{i,t}\\&\sum _{i=1}^{n}x_{i,t}&=&W_{t}\\&x_{t}&\geq &0\end{array}}} for t = T − 2 , … , 1 {\displaystyle t=T-2,\dots ,1} . == Software tools == === Modelling languages === All discrete stochastic programming problems can be represented with any algebraic modeling language, manually implementing explicit or implicit non-anticipativity to make sure the resulting model respects the structure of the information made available at each stage. An instance of an SP problem generated by a general modelling language tends to grow quite large (linearly in the number of scenarios), and its matrix loses the structure that is intrinsic to this class of problems, which could otherwise be exploited at solution time by specific decomposition algorithms. Extensions to modelling languages specifically designed for SP are starting to appear, see: AIMMS – supports the definition of SP problems EMP SP (Extended Mathematical Programming for Stochastic Programming) – a module of GAMS created to facilitate stochastic programming (includes keywords for parametric distributions, chance constraints and risk measures such as Value at risk and Expected shortfall). SAMPL – a set of extensions to AMPL specifically designed to express stochastic programs (includes syntax for chance constraints, integrated chance constraints and robust optimization problems) They both can generate SMPS instance level format, which conveys in a non-redundant form the structure of the problem to the solver. == See also == Chance-constrained portfolio selection Correlation gap EMP for Stochastic Programming Entropic value at risk FortSP SAMPL algebraic modeling language Scenario optimization Stochastic optimization == References == == Further reading == John R. Birge and François V. Louveaux. Introduction to Stochastic Programming. Springer Verlag, New York, 1997. Kall, Peter; Wallace, Stein W. (1994). Stochastic programming. Wiley-Interscience Series in Systems and Optimization. Chichester: John Wiley & Sons, Ltd. pp. xii+307. ISBN 0-471-95158-7. MR 1315300. G. Ch. Pflug: Optimization of Stochastic Models. The Interface between Simulation and Optimization. Kluwer, Dordrecht, 1996. András Prékopa. Stochastic Programming. Kluwer Academic Publishers, Dordrecht, 1995. Andrzej Ruszczynski and Alexander Shapiro (eds.) (2003) Stochastic Programming. Handbooks in Operations Research and Management Science, Vol. 10, Elsevier. Shapiro, Alexander; Dentcheva, Darinka; Ruszczyński, Andrzej (2009). Lectures on stochastic programming: Modeling and theory (PDF). MPS/SIAM Series on Optimization. Vol. 9. Philadelphia, PA: Society for Industrial and Applied Mathematics (SIAM). pp. xvi+436. ISBN 978-0-89871-687-0. MR 2562798. Archived from the original (PDF) on 2020-03-24. Retrieved 2010-09-22. {{cite book}}: Unknown parameter |agency= ignored (help) Stein W. Wallace and William T. Ziemba (eds.) (2005) Applications of Stochastic Programming. MPS-SIAM Book Series on Optimization 5 King, Alan J.; Wallace, Stein W. (2012). Modeling with Stochastic Programming. Springer Series in Operations Research and Financial Engineering. New York: Springer. ISBN 978-0-387-87816-4. == External links == Stochastic Programming Community Home Page
https://en.wikipedia.org/wiki/Stochastic_programming
Scratch is a high-level, block-based visual programming language and website aimed primarily at children as an educational tool, with a target audience of ages 8 to 16. Users on the site can create projects on the website using a block-like interface. Scratch was conceived and designed through collaborative National Science Foundation grants awarded to Mitchel Resnick and Yasmin Kafai. Scratch is developed by the MIT Media Lab and has been translated into 70+ languages, being used in most parts of the world. Scratch is taught and used in after-school centers, schools, and colleges, as well as other public knowledge institutions. As of 15 February 2023, community statistics on the language's official website show more than 123 million projects shared by over 103 million users, and more than 95 million monthly website visits. Overall, more than 1.15 billion projects have been created in total, with the site reaching its one billionth project on April 12th, 2024. Scratch takes its name from a technique used by disk jockeys called "scratching", where vinyl records are clipped together and manipulated on a turntable to produce different sound effects and music. Like scratching, the website lets users mix together different media (including graphics, sound, and other programs) in creative ways by creating and "remixing" projects, like video games, animations, music, and simulations. == Scratch 3.0 == === User interface === The Scratch interface is divided into three main sections: a stage area, block palette, and a coding area to place and arrange the blocks into scripts that can be run by pressing the green flag or clicking on the code itself. Users may also create their own code blocks, which will appear in the "My Blocks" section. The stage area features the results (e.g., animations, turtle graphics, either in a small or normal size, with a full-screen option also available) and all sprites' thumbnails being listed in the bottom area. The stage uses x and y coordinates, with 0,0 being the stage center. With a sprite selected at the bottom of the staging area, blocks of code can be applied by dragging them from the block palette into the coding area. The Costumes tab allows users to change the look of the sprite with a vector and bitmap editor in order to create various effects, including animation. The Sounds tab allows attaching sounds and music to a sprite. When creating sprites and also backgrounds, users can draw their own sprites manually, choose a sprite from the library, or upload an image. The table below shows the categories of the programming blocks: === Offline editing === An offline "Desktop Editor" for Scratch 3.0 is available for Microsoft Windows 10 and above in the Microsoft Store, Apple's macOS, ChromeOS, and Android; this allows the creation and playing of Scratch programs offline. The offline editor can also be downloaded in previous versions, such as Scratch 2.0 and Scratch 1.4 (an archive of older versions is found here). === Extensions === In Scratch, extensions add extra blocks and features that can be used in projects. In Scratch 2.0, the extensions were all hardware-based and Pen was a normal category. Software-based extensions were added in Scratch 3.0, such as text-to-speech voices, along with some new hardware-based extensions like the micro:bit. The extensions are listed below. ==== Physical ==== LEGO Mindstorms EV3 – Control motors and receive sensor data from the Lego Mindstorms EV3 Makey Makey – Use Makey Makey to control projects LEGO Education WeDo 2.0 – control motors and receive sensor data from the Lego WeDo micro:bit – Use of a micro:bit to control projects LEGO BOOST – Bring robotic creations to life Go Direct Force & Acceleration – Sense pull, push, motion, and spin ==== Digital ==== Many of the digital extensions in Scratch 3.0 used to be regular block categories that were moved to the extensions section to reduce clutter. These include: Music – Play digital instruments (drums, trumpets, violins, pianos, and more). Previously part of the Sound category. Pen – Draw on the Stage with a variety of thicknesses and color. Previously a normal block category. Video Sensing – Detect motion with the camera. Previously in the Sensing category. New digital extensions have also been added in collaborations with commercial companies. These include: Text to Speech – Converts words in a text into voice output, especially having an option for languages (variety of voices, supplied by Amazon) Translate – Uses Google Translate to translate text from one language into a variety of other languages, including Arabic, Chinese, Dutch, English, French, Greek, Norwegian, and Japanese Makey Makey – Options for better key pressing and press multiple keys in order. You can grab a join block if you want more control on the extension. A paper published in 2019 by NYU argues and illustrates, for coding music with Scratch, "that the music and sound blocks as currently implemented in Scratch may limit and frustrate meaningful music-making for children, the core user base for Scratch." === Scratch Lab === The Scratch Lab displays experiments from the Scratch Team, intended to explore whether new features may be added to the full website in the future. Experimental features currently under development include: Video Sprites – Fill sprites with live video. Face Sensing – Make animated costumes and games that interact with your face. Animated Text – Bring words to life with colors, fonts, and animations. == Community of users == Scratch is used in many different settings: schools, museums, libraries, community centers, and homes. Scratch is designed primarily for users aged 8–16, but it is used by all ages and has a sizeable adult user base as of 2009. This wide outreach has created many surrounding communities, both physical and digital. In April 2020, the Tiobe ranking of the world's programming languages included Scratch in the top 20. According to Tiobe, there are 50 million projects written in Scratch, and every month one million new projects are added. === Educational users === Scratch is used as the introductory language because the creation of interesting programs is relatively easy, and skills learned can be applied to other programming languages such as Python and Java. Scratch is not exclusively for creating games. With the provided visuals, programmers can create animations, text, stories, music, art, and more. There are already many programs that students can use to learn topics in math, history, and even photography. Scratch allows teachers to create conceptual and visual lessons and science lab assignments with animations that help visualize difficult concepts. Within the social sciences, instructors can create quizzes, games, and tutorials with interactive elements. Using Scratch allows young people to understand the logic of programming and how to creatively build and collaborate. Scratch is taught to more than 800 schools and 70 colleges of the DAV organization in India and across the world. In higher education, Scratch is used in the first week of Harvard University's CS50 introductory computer science course. === Online community === Users of Scratch are called "Scratchers". Scratchers have the capability to share their projects and receive feedback. Projects can be uploaded directly from the development environment to the Scratch website and any member of the community can view and download the full source code to study or to remix into new projects. Scratchers can also create project studios, comment, favorite, and "love" others' projects, follow other members to see their projects and activity, and share ideas. Projects range from games and animations to practical tools. Additionally, to encourage the creation and sharing amongst users, the website frequently establishes "Scratch Design Studio" challenges. The MIT Scratch Team works to ensure that this community maintains a friendly and respectful environment for all people. Educators have their own online community called ScratchEd, developed and supported by the Harvard Graduate School of Education. In this community, Scratch educators share stories, exchange resources, and ask questions. === Scratch Studios === Scratchers can upload their projects to studios where other Scratchers can upload their project for others to see and for other Scratchers to view, comment and remix their project. A studio usually consists of different projects made by Scratchers. Some Scratch studios are created by Scratchers to put all their projects into one library. === Scratch Wiki === The Scratch Wiki is a support resource for Scratch and information about its website, history, and phenomena surrounding it. Although supported by the Scratch Team (the developers of Scratch), it is primarily written by Scratch users (Scratchers) and is hosted independently of the main Scratch website. There are other wikis in languages besides English available on the Scratch Wiki base domain. === Roles === Roles are displayed as a label under a user's username on profile pages and on forum posts. To prevent vandalism, new accounts have the "New Scratcher" role, as opposed by the usual "Scratcher" role. Some restrictions are imposed onto New Scratcher accounts, including the inability to use cloud data and a minimum 30 second cooldown period between posting comments. After a period of time of interacting and creating projects, an account will be eligible to gain the Scratcher role. Official moderators and developers of Scratch are labeled as part of the "Scratch Team" and usually have an asterisk at the end of their username. The site also has special types of accounts for Students and Educators to use Scratch in the classroom. === Censorship === In August 2020, GreatFire announced that the Chinese government had blocked access to the Scratch website. At the time, it was estimated that more than three million people in China were using it. The outlet cited the fact that Macau, Hong Kong and Taiwan were listed as countries on the website. == Code base == The source code for the project editor in all three major versions, as well as a majority of the current website, is hosted publicly on GitHub across various repositories. Scratch 3.0 is JavaScript-based, 2.0 is programmed in ActionScript, and the 1.x versions were based on Squeak, which itself is based on Smalltalk-80. 2.0 had an experimental JavaScript-based interpreter that was being developed in parallel with the ActionScript version. In 3.0, Scratch blocks are implemented using Blockly, a JavaScript library developed by Google for creating block-based visual programming languages. On 13 May 2014, a year after the release of Scratch 2.0, it was announced by a developer on the Scratch Forums that 2.0 would become open source. == Events == Scratch Educators can gather in person at Scratch Educator Meetups. At these gatherings, Scratch Educators learn from each other and share ideas and strategies that support computational creativity. An annual "Scratch Week", formerly known as "Scratch Day", is declared in May each year. Community members are encouraged to host an event on or around this day, large or small, that celebrates Scratch. These events are held worldwide, and a listing can be found on the Scratch Day website. Scratch Week is a series focusing on Scratch activities on the Scratch website. Every April Fools' Day, the Scratch Team will play pranks on users and add Easter eggs, one example being that all event blocks in projects turn into cat versions of the same blocks. == History == In the early 2000s, the MIT Media Lab's Lifelong Kindergarten group (LLK) was developing visual programming languages targeted towards children. In 2003, Mitchel Resnick, Yasmin Kafai, and John Maeda were awarded a National Science Foundation grant for the development of a new programming environment for children to express themselves with code. The LLK, led by Mitchel Resnick, in partnership with Yasmin Kafai's team at UCLA worked closely with Computer Clubhouses in Boston and Los Angeles to develop Scratch, grounding its design in the practices and social dynamics of these after-school youth centers. It started as a basic programming language, with no labeled categories and no green flag. Similar to AgentSheets Scratch employed concepts of Tactile Programming later known as blocks-based programming. Scratch was made with the intention to teach kids to program. The philosophy of Scratch encourages the sharing, reuse, and combination of code, as indicated by the team slogan, "Imagine, Program, Share". Users can make their own projects, or they may choose to "remix" someone else's project. Projects created and remixed with Scratch are licensed under the Creative Commons Attribution-Share Alike License. Scratch automatically gives credit to the user who created the original project and program in the top part of the project page. Scratch was developed based on ongoing interaction with youth and staff at Computer Clubhouses. The use of Scratch at Computer Clubhouses served as a model for other after-school centers demonstrating how informal learning settings can support the development of technological fluency. Scratch 2.0 was released on 9 May 2013. The update changed the look of the site and included both an online project editor and an offline editor. Custom blocks could now be defined within projects, along with several other improvements. The Scratch 2.0 Offline editor could be downloaded for Windows, Mac, and Linux directly from Scratch's website, although support for Linux was later dropped. The unofficial mobile version had to be downloaded from the Scratch forums. Scratch 3.0 was first announced by the Scratch Team in 2016. Several public alpha versions were released between then and January 2018, after which the pre-beta "Preview" versions were released. A beta version of Scratch 3.0 was released on 1 August 2018. for use on most browsers; with the notable exception of Internet Explorer. Scratch 3.0, the first 3.x release version, was released on 2 January 2019. On 28 June 2023, the header and links on the Scratch Website changed from blue to purple, and new optional high-contrast block colors were introduced, to make the site easier for colorblind people to read and use. In 2013, the Scratch Foundation (formerly the Code-To-Learn Foundation) was founded, and on March 11, 2019, the Scratch Team separated from the MIT Media Lab and moved to the Scratch Foundation. The MIT Media Lab continues to collaborate closely with the Scratch Foundation. == Filetypes == In Scratch 1.4, an *.sb file was the file format used to store projects. An *.sb file is divided into four sections: "header", this 10-byte header contains the ASCII string "ScratchV02" in versions higher than Scratch 1.2, and "ScratchV01" in Scratch 1.2 and below "infoSize", encodes the length of the project's infoObjects. A 4-byte long, 32-bit, big-Endian integer. "infoObjects", a dictionary-format data section. It contains: "thumbnail", a thumbnail of the project's stage; "author", the username of the project's creator; "comment", the Project Notes; "history", the save and upload log; "scratch-version", the version of Scratch used to save the file; "contents", an object table with the Stage as the root. All objects in the program are stored here as references. Scratch 2.0 uses the *.sb2 file format. These are essentially zip files containing a .json file as well as the contents of the Scratch project including sounds (stored as .wav) and images (stored as .png). Each filetype, excluding the project.json, is stored as a number, starting at 0 and counting up with each additional file. The image file labeled "0.png" is always a 480x360 white image, but "0.wav" will still be the earliest non-deleted file. The ScratchX experimental version of Scratch used the .sbx file format. Scratch 3.0 uses the *.sb3 format. == Older versions == Although the main Scratch website now runs only the current version (Scratch 3.0), the offline editors for Scratch 2.0 (and the earlier Scratch 1.4) are still available for download and can be used to create and run games locally. It is still possible to upload projects from the Scratch 2.0 launcher, which are immediately converted into Scratch 3.0 when uploaded to the main site. There is also an offline version of Scratch 3.0. === Technology === The editor of Scratch 1.4 and below was written in Squeak, while its online project viewer was written in Java, and a player written in Adobe Flash was later added. Scratch 2.0 relied on Adobe Flash for the online version, and Adobe AIR for the offline editor. These have fallen out of favor, and Adobe dropped support for them at the end of 2020. Scratch 2.0 changed how sounds were imported, so many Scratch 1.4 sounds stopped working. (The project file was changed from *.sb to *.sb2). === Interface === In Scratch 2.0, the stage area is on the left side, with the programming blocks palette in the middle, and the coding area on the right. Extensions are in the "More Blocks" section of the palette. The web version of Scratch 2.0 introduced project autosaving.: 23  The blocks palette in Scratch 2.0 is made of discrete sections that are not scrollable from one to the next; the table below shows the different sections: Scratch 2.0 introduced the backpack, which can be used to transfer scripts, sprites, costumes, and sounds between projects.: 14–15  == Features == Scratch uses event-driven programming with multiple active objects called sprites. Sprites can be drawn, as vector or bitmap graphics, from scratch in a simple editor that is part of Scratch, or can be imported from external sources. Scratch 3.0 only supports one-dimensional arrays, known as "lists", and floating-point scalars and strings are supported but with limited string manipulation ability. There is a strong contrast between the powerful multimedia functions and multi-threaded programming style and the rather limited scope of the Scratch programming language. === Scratch 2.0 features === Scratch 2.0 does not treat procedures as first class structures and has limited file I/O options with Scratch 2.0 Extension Protocol, an experimental extension feature that allows interaction between Scratch 2.0 and other programs. The Extension protocol allows interfacing with hardware boards such as Lego Mindstorms or Arduino. Scratch 2.0 also has the following features: Smart block switching Two-column category menu Reverse order of project controls Display stage on left side Square block inputs Compact editor Collapsing sprite properties Scratch 2.0 themes === Snap! (Build Your Own Blocks) === A more advanced visual programming language inspired by Scratch is Snap!, featuring first class procedures (their mathematical foundations are also called lambda calculus), first-class lists (including lists of lists), and first-class truly object-oriented sprites with prototyping inheritance, and nestable sprites, which are not part of Scratch. Snap! (previously "BYOB") was developed by Jens Mönig with documentation provided by Brian Harvey from University of California, Berkeley and has been used to teach "The Beauty and Joy of Computing" introductory course in CS for non-CS-major students. Both of them were members of the Scratch Team before designing "Snap!". === ScratchJr === In July 2014, ScratchJr was released for iPad, and in 2016, ScratchJr for Android. Although heavily inspired by Scratch and co-led by Mitch Resnick, it is nonetheless a complete rewrite designed for younger children—targeting ages 5 through 7. == Community-made modifications == Due to the open source nature of Scratch, numerous forks and browser extensions have been created by the community that aim to improve or modify the user experience. ScratchTools and Scratch Addons are some examples of open-sourced browser extensions that add many upgrades and new features to the Scratch website and editor. TurboWarp is a fork of the Scratch 3.0 editor that compiles Scratch into JavaScript code when a project is run, resulting in projects' general preformances boosting significantly. In addition, there are many technical settings and the same addons that Scratch Addons provides. TurboWarp can also export projects to standalone HTML5, Bundle (macOS) and EXE files. Users can also create their own extensions for Scratch 3.0 using JavaScript. Although the intention for Scratch 3.0 was to allow unofficial JavaScript extensions to be developed by users, it was abandoned due to moderation risks. As a result, the official site doesn't allow JavaScript extensions to be added, but several modifications of Scratch do. Before 2.0, a number of Scratch forks were created using the source code of Scratch 1.4. These programs usually only included a few extra blocks not present in Scratch. == See also == Blockly, an interface used by Scratch to make the code blocks. Snap! (programming language) Swift Playgrounds Alice (software) Twine (software) Lego Mindstorms EV3 Kodu Game Lab Code.org Programmable Cricket PWCT Visual programming language Pencil Code (programming language) == References == == External links == Official website Scratch Lab
https://en.wikipedia.org/wiki/Scratch_(programming_language)
A programming model is an execution model coupled to an API or a particular pattern of code. In this style, there are actually two execution models in play: the execution model of the base programming language and the execution model of the programming model. An example is Spark where Java is the base language, and Spark is the programming model. Execution may be based on what appear to be library calls. Other examples include the POSIX Threads library and Hadoop's MapReduce. In both cases, the execution model of the programming model is different from that of the base language in which the code is written. For example, the C programming language has no behavior in its execution model for input/output or thread behavior. But such behavior can be invoked from C syntax, by making what appears to be a call to a normal C library. What distinguishes a programming model from a normal library is that the behavior of the call cannot be understood in terms of the language the program is written in. For example, the behavior of calls to the POSIX thread library cannot be understood in terms of the C language. The reason is that the call invokes an execution model that is different from the execution model of the language. This invocation of an outside execution model is the defining characteristic of a programming model, in contrast to a programming language. In parallel computing, the execution model often must expose features of the hardware in order to achieve high performance. The large amount of variation in parallel hardware causes a concurrent need for a similarly large number of parallel execution models. It is impractical to make a new language for each execution model, hence it is a common practice to invoke the behaviors of the parallel execution model via an API. So, most of the programming effort is done via parallel programming models rather than parallel languages. The terminology around such programming models tends to focus on the details of the hardware that inspired the execution model, and in that insular world the mistaken belief is formed that a programming model is only for the case when an execution model is closely matched to hardware features. == References ==
https://en.wikipedia.org/wiki/Programming_model
Genetic programming (GP) is an evolutionary algorithm, an artificial intelligence technique mimicking natural evolution, which operates on a population of programs. It applies the genetic operators selection according to a predefined fitness measure, mutation and crossover. The crossover operation involves swapping specified parts of selected pairs (parents) to produce new and different offspring that become part of the new generation of programs. Some programs not selected for reproduction are copied from the current generation to the new generation. Mutation involves substitution of some random part of a program with some other random part of a program. Then the selection and other operations are recursively applied to the new generation of programs. Typically, members of each new generation are on average more fit than the members of the previous generation, and the best-of-generation program is often better than the best-of-generation programs from previous generations. Termination of the evolution usually occurs when some individual program reaches a predefined proficiency or fitness level. It may and often does happen that a particular run of the algorithm results in premature convergence to some local maximum which is not a globally optimal or even good solution. Multiple runs (dozens to hundreds) are usually necessary to produce a very good result. It may also be necessary to have a large starting population size and variability of the individuals to avoid pathologies. == History == The first record of the proposal to evolve programs is probably that of Alan Turing in 1950 in "Computing Machinery and Intelligence". There was a gap of 25 years before the publication of John Holland's 'Adaptation in Natural and Artificial Systems' laid out the theoretical and empirical foundations of the science. In 1981, Richard Forsyth demonstrated the successful evolution of small programs, represented as trees, to perform classification of crime scene evidence for the UK Home Office. Although the idea of evolving programs, initially in the computer language Lisp, was current amongst John Holland's students, it was not until they organised the first Genetic Algorithms (GA) conference in Pittsburgh that Nichael Cramer published evolved programs in two specially designed languages, which included the first statement of modern "tree-based" Genetic Programming (that is, procedural languages organized in tree-based structures and operated on by suitably defined GA-operators). In 1988, John Koza (also a PhD student of John Holland) patented his invention of a GA for program evolution. This was followed by publication in the International Joint Conference on Artificial Intelligence IJCAI-89. Koza followed this with 205 publications on “Genetic Programming” (GP), name coined by David Goldberg, also a PhD student of John Holland. However, it is the series of 4 books by Koza, starting in 1992 with accompanying videos, that really established GP. Subsequently, there was an enormous expansion of the number of publications with the Genetic Programming Bibliography, surpassing 10,000 entries. In 2010, Koza listed 77 results where Genetic Programming was human competitive. The departure of GP from the rigid, fixed-length representations typical of early GA models was not entirely without precedent. Early work on variable-length representations laid the groundwork. One notable example is Messy Genetic Algorithms, which introduced irregular, variable-length chromosomes to address building block disruption and positional bias in standard GAs. Another precursor was robot trajectory programming, where genome representations encoded program instructions for robotic movements—structures inherently variable in length. Even earlier, unfixed-length representations were proposed in a doctoral dissertation by Cavicchio, who explored adaptive search using simulated evolution. His work provided foundational ideas for flexible program structures. In 1996, Koza started the annual Genetic Programming conference which was followed in 1998 by the annual EuroGP conference, and the first book in a GP series edited by Koza. 1998 also saw the first GP textbook. GP continued to flourish, leading to the first specialist GP journal and three years later (2003) the annual Genetic Programming Theory and Practice (GPTP) workshop was established by Rick Riolo. Genetic Programming papers continue to be published at a diversity of conferences and associated journals. Today there are nineteen GP books including several for students. === Foundational work in GP === Early work that set the stage for current genetic programming research topics and applications is diverse, and includes software synthesis and repair, predictive modeling, data mining, financial modeling, soft sensors, design, and image processing. Applications in some areas, such as design, often make use of intermediate representations, such as Fred Gruau's cellular encoding. Industrial uptake has been significant in several areas including finance, the chemical industry, bioinformatics and the steel industry. == Methods == === Program representation === GP evolves computer programs, traditionally represented in memory as tree structures. Trees can be easily evaluated in a recursive manner. Every internal node has an operator function and every terminal node has an operand, making mathematical expressions easy to evolve and evaluate. Thus traditionally GP favors the use of programming languages that naturally embody tree structures (for example, Lisp; other functional programming languages are also suitable). Non-tree representations have been suggested and successfully implemented, such as linear genetic programming which perhaps suits the more traditional imperative languages. The commercial GP software Discipulus uses automatic induction of binary machine code ("AIM") to achieve better performance. μGP uses directed multigraphs to generate programs that fully exploit the syntax of a given assembly language. Multi expression programming uses Three-address code for encoding solutions. Other program representations on which significant research and development have been conducted include programs for stack-based virtual machines, and sequences of integers that are mapped to arbitrary programming languages via grammars. Cartesian genetic programming is another form of GP, which uses a graph representation instead of the usual tree based representation to encode computer programs. Most representations have structurally noneffective code (introns). Such non-coding genes may seem to be useless because they have no effect on the performance of any one individual. However, they alter the probabilities of generating different offspring under the variation operators, and thus alter the individual's variational properties. Experiments seem to show faster convergence when using program representations that allow such non-coding genes, compared to program representations that do not have any non-coding genes. Instantiations may have both trees with introns and those without; the latter are called canonical trees. Special canonical crossover operators are introduced that maintain the canonical structure of parents in their children. === Initialisation === The methods for creation of the initial population include: Grow creates the individuals sequentially. Every GP tree is created starting from the root, creating functional nodes with children as well as terminal nodes up to a certain depth. Full is similar to the Grow. The difference is that all brunches in a tree are of same predetermined depth. Ramped half-and-half creates a populations consisting of m d − 1 {\displaystyle md-1} parts and a maximum depth of m d {\displaystyle md} for its trees. The first part has a maximum depth of 2, second of 3 and so on up to the m d − 1 {\displaystyle md-1} -th part with maximum depth m d {\displaystyle md} . Half of every part is created by Grow, while the other part is created by Full. === Selection === Selection is a process whereby certain individuals are selected from the current generation that would serve as parents for the next generation. The individuals are selected probabilistically such that the better performing individuals have a higher chance of getting selected. The most commonly used selection method in GP is tournament selection, although other methods such as fitness proportionate selection, lexicase selection, and others have been demonstrated to perform better for many GP problems. Elitism, which involves seeding the next generation with the best individual (or best n individuals) from the current generation, is a technique sometimes employed to avoid regression. === Crossover === In Genetic Programming two fit individuals are chosen from the population to be parents for one or two children. In tree genetic programming, these parents are represented as inverted lisp like trees, with their root nodes at the top. In subtree crossover in each parent a subtree is randomly chosen. (Highlighted with yellow in the animation.) In the root donating parent (in the animation on the left) the chosen subtree is removed and replaced with a copy of the randomly chosen subtree from the other parent, to give a new child tree. Sometimes two child crossover is used, in which case the removed subtree (in the animation on the left) is not simply deleted but is copied to a copy of the second parent (here on the right) replacing (in the copy) its randomly chosen subtree. Thus this type of subtree crossover takes two fit trees and generates two child trees. The tree-based approach in Genetic Programming also shares structural and procedural similarities with earlier knowledge-based and topology-oriented crossover methods. Specifically, analogous crossover and homologous crossover, both implemented in robot trajectory planning, exhibit a resemblance to subtree operations in tree GP. These crossover mechanisms were described in the context of heuristic optimisation strategies in robotics. === Replication === Some individuals selected according to fitness criteria do not participate in crossover, but are copied into the next generation, akin to asexual reproduction in the natural world. They may be further subject to mutation. === Mutation === There are many types of mutation in genetic programming. They start from a fit syntactically correct parent and aim to randomly create a syntactically correct child. In the animation a subtree is randomly chosen (highlighted by yellow). It is removed and replaced by a randomly generated subtree. Other mutation operators select a leaf (external node) of the tree and replace it with a randomly chosen leaf. Another mutation is to select at random a function (internal node) and replace it with another function with the same arity (number of inputs). Hoist mutation randomly chooses a subtree and replaces it with a subtree within itself. Thus hoist mutation is guaranteed to make the child smaller. Leaf and same arity function replacement ensure the child is the same size as the parent. Whereas subtree mutation (in the animation) may, depending upon the function and terminal sets, have a bias to either increase or decrease the tree size. Other subtree based mutations try to carefully control the size of the replacement subtree and thus the size of the child tree. Similarly there are many types of linear genetic programming mutation, each of which tries to ensure the mutated child is still syntactically correct. == Applications == GP has been successfully used as an automatic programming tool, a machine learning tool and an automatic problem-solving engine. GP is especially useful in the domains where the exact form of the solution is not known in advance or an approximate solution is acceptable (possibly because finding the exact solution is very difficult). Some of the applications of GP are curve fitting, data modeling, symbolic regression, feature selection, classification, etc. John R. Koza mentions 76 instances where Genetic Programming has been able to produce results that are competitive with human-produced results (called Human-competitive results). Since 2004, the annual Genetic and Evolutionary Computation Conference (GECCO) holds Human Competitive Awards (called Humies) competition, where cash awards are presented to human-competitive results produced by any form of genetic and evolutionary computation. GP has won many awards in this competition over the years. == Meta-genetic programming == Meta-genetic programming is the proposed meta-learning technique of evolving a genetic programming system using genetic programming itself. It suggests that chromosomes, crossover, and mutation were themselves evolved, therefore like their real life counterparts should be allowed to change on their own rather than being determined by a human programmer. Meta-GP was formally proposed by Jürgen Schmidhuber in 1987. Doug Lenat's Eurisko is an earlier effort that may be the same technique. It is a recursive but terminating algorithm, allowing it to avoid infinite recursion. In the "autoconstructive evolution" approach to meta-genetic programming, the methods for the production and variation of offspring are encoded within the evolving programs themselves, and programs are executed to produce new programs to be added to the population. Critics of this idea often say this approach is overly broad in scope. However, it might be possible to constrain the fitness criterion onto a general class of results, and so obtain an evolved GP that would more efficiently produce results for sub-classes. This might take the form of a meta evolved GP for producing human walking algorithms which is then used to evolve human running, jumping, etc. The fitness criterion applied to the meta GP would simply be one of efficiency. == See also == Bio-inspired computing Covariance Matrix Adaptation Evolution Strategy (CMA-ES) Evolutionary image processing Fitness approximation Genetic improvement Genetic representation Grammatical evolution Inductive programming Linear genetic programming Multi expression programming Propagation of schema == References == == External links == Aymen S Saket & Mark C Sinclair Genetic Programming and Evolvable Machines, a journal Evo2 for genetic programming GP bibliography The Hitch-Hiker's Guide to Evolutionary Computation Riccardo Poli, William B. Langdon, Nicholas F. McPhee, John R. Koza, "A Field Guide to Genetic Programming" (2008) Genetic Programming, a community maintained resource
https://en.wikipedia.org/wiki/Genetic_programming
In computer programming, a block or code block or block of code is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements. A programming language that permits the creation of blocks, including blocks nested within other blocks, is called a block-structured programming language. Blocks are fundamental to structured programming, where control structures are formed from blocks. Blocks have two functions: to group statements so that they can be treated as one statement, and to define scopes for names to distinguish them from the same name used elsewhere. In a block-structured programming language, the objects named in outer blocks are visible inside inner blocks, unless they are masked by an object declared with the same name. == History == Ideas of block structure were developed in the 1950s during the development of the first autocodes, and were formalized in the Algol 58 and Algol 60 reports. Algol 58 introduced the notion of the "compound statement", which was related solely to control flow. The subsequent Revised Report which described the syntax and semantics of Algol 60 introduced the notion of a block and block scope, with a block consisting of " A sequence of declarations followed by a sequence of statements and enclosed between begin and end..." in which "[e]very declaration appears in a block in this way and is valid only for that block." == Syntax == Blocks use different syntax in different languages. Several broad families are: the ALGOL family in which blocks are delimited by the keywords "begin" and "end" or equivalent. In C, blocks are delimited by curly braces - "{" and "}". ALGOL 68 uses parentheses. Parentheses - "(" and ")", are used in the MS-DOS batch language indentation, as in Python and Haskell s-expressions with a syntactic keyword such as prog or let (as in the Lisp family) In 1968 (with ALGOL 68), then in Edsger W. Dijkstra's 1974 Guarded Command Language the conditional and iterative code block are alternatively terminated with the block reserved word reversed: e.g. if ~ then ~ elif ~ else ~ fi, case ~ in ~ out ~ esac and for ~ while ~ do ~ od == Limitations == Some languages which support blocks with declarations do not fully support all declarations; for instance many C-derived languages do not permit a function definition within a block (nested functions). And unlike its ancestor Algol, Pascal does not support the use of blocks with their own declarations inside the begin and end of an existing block, only compound statements enabling sequences of statements to be grouped together in if, while, repeat and other control statements. == Basic semantics == The semantic meaning of a block is twofold. Firstly, it provides the programmer with a way for creating arbitrarily large and complex structures that can be treated as units. Secondly, it enables the programmer to limit the scope of variables and sometimes other objects that have been declared. In early languages such as Fortran IV and BASIC, there were no statement blocks or control structures other than simple forms of loops. Conditionals were implemented using conditional goto statements: The logical structure of the program is not reflected in the language, and analyzing when a given statement is executed can be difficult. Blocks allow the programmer to treat a group of statements as a unit, and the default values which had to appear in initialization in this style of programming can, with a block structure, be placed closer to the decision: Use of blocks in the above fragment of Pascal clarifies the programmer's intent, and enables combining the resulting blocks into a nested hierarchy of conditional statements. The structure of the code reflects the programmer's thinking more closely, making it easier to understand and modify. The above source code can be made even clearer by taking the inner if statement out of the outer one altogether, placing the two blocks one after the other to be executed consecutively. Semantically there is little difference in this case, and the use of block structure, supported by indenting for readability, makes it easy for the programmer to refactor the code. In primitive languages, variables had broad scope. For instance, an integer variable called IEMPNO might be used in one part of a Fortran subroutine to denote an employee social security number (ssn), but during maintenance work on the same subroutine, a programmer might accidentally use the same variable, IEMPNO, for a different purpose, and this could result in a bug that was difficult to trace. Block structure makes it easier for programmers to control scope to a minute level. In the above Scheme fragment, empno is used to identify both the manager and their underlings each by their respective ssn, but because the underling ssn is declared within an inner block it does not interact with the variable of the same name that contains the manager's ssn. In practice, considerations of clarity would probably lead the programmer to choose distinct variable names, but they have the choice and it is more difficult to introduce a bug inadvertently. == Hoisting == In some languages, a variable can be declared at function scope even within enclosed blocks. For example, in JavaScript, variables declared with var have function scope. == See also == Basic block Block scope Closure (computer programming) Control flow == References ==
https://en.wikipedia.org/wiki/Block_(programming)