text:
Organic Chemistry/Spectroscopy

There are several spectroscopic techniques which can be used to identify organic molecules: infrared (IR), mass spectroscopy (MS) UV/visible spectroscopy (UV/Vis) and nuclear magnetic resonance (NMR).

IR, NMR and UV/vis spectroscopy are based on observing the frequencies of electromagnetic radiation absorbed and emitted by molecules. MS is based on measuring the mass of the molecule and any fragments of the molecule which may be produced in the MS instrument.

UV/Vis Spectroscopy
UV/Vis spectroscopy is an absorption spectroscopy technique that utilizes electromagnetic radiation in the 10 nm to 700 nm range. The energy associated with light between these wavelengths can be absorbed by both non-bonding n-electrons and π-electrons residing within a molecular orbital. This absorption of energy causes the promotion of an electron from the highest occupied molecular orbital (HOMO) to the lowest unoccupied molecular orbital (LUMO). More specifically, the electron is said to undergo either an n→π* transition or π→π* transition. It is also this absorption of visible light energy that gives rise to the perceived color of pigmented compounds. As a result of this phenomena, UV/Vis is a technique often employed in organic chemistry in order to identify the presence of free electrons or double (π) bonds within a molecule. The wavelength that is most absorbed by the molecule is known as the λ-max, and it is this number that can be used to make comparative analysis of different molecules. This spectroscopic technique can also be used to identify some molecules with large conjugated π-systems or carbonyl groups by utilizing the Woodward-Fieser rules, which relies on a set of empirical values to predict the λ-max of a compound.

NMR Spectroscopy
Nuclear Magnetic Resonance (NMR) Spectroscopy is one of the most useful analytical techniques for determining the structure of an organic compound. There are two main types of NMR, 1H-NMR (Proton NMR) and 13C-NMR (Carbon NMR). NMR is based on the fact that the nuclei of atoms have a quantized property called spin. When a magnetic field is applied to a 1H or 13C nucleus, the nucleus can align either with (spin +1/2) or against (spin -1/2) the applied magnetic field.

These two states have different potential energies and the energy difference depends on the strength of the magnetic field. The strength of the magnetic field about a nucleus, however, depends on the chemical environment around the nucleus. For example, the negatively charged electrons around and near the nucleus can shield the nucleus from the magnetic field, lowering the strength of the effective magnetic field felt by the nucleus. This, in turn, will lower the energy needed to transition between the +1/2 and -1/2 states. Therefore, the transition energy will be lower for nuclei attached to electron donating groups (such as alkyl groups) and higher for nuclei attached to electron withdrawing groups (such as a hydroxyl group).

In an NMR machine, the compound being analyzed is placed in a strong magnetic field and irradiated with radio waves to cause all the 1H and 13C nuclei to occupy the higher energy -1/2 state. As the nuclei relax back to the +1/2 state, they release radio waves corresponding to the energy of the difference between the two spin states. The radio waves are recorded and analyzed by computer to give an intensity versus frequency plot of the sample. This information can then be used to determine the structure of the compound.

Aromatics in H-NMR Electron Donating Groups vs. Electron Withdrawing Groups

On monosubstituted rings, electron donating groups resonate at high chemical shifts. Electron donating groups increase the electron density by releasing electrons into a reaction center, thus stabilizing the carbocation. An example of an electron donating group is methyl (-CH3).

Accordingly, electron withdrawing groups are represented at low chemical shifts. Electron withdrawing groups pull electrons away from a reacting center. This can stabilize an electron rich carbanion. Some examples of electron withdrawing groups are halogens (-Cl, -F) and carboxylic acid (-COOH).

Looking at the H NMR spectrum of ethyl benzene, we see that the methyl group is the most electron withdrawing, so it appears at the lowest chemical shift. The aromatic phenyl group is the most electron donating, so it has the highest chemical shift.

Disubstituted Rings

The sum of integrated intensity values for the entire aromatic region shows how many substituents are attached to the ring, so a total value of 4 indicates that the ring has 2 substituents. When a benzene ring has two substituent groups, each exerts an influence on following substitution reactions. The site at which a new substituent is introduced depends on the orientation of the existing groups and their individual directing effects. For a disubstituted benzene ring, there are three possible NMR patterns.

Note that para-substituted rings usually show two symmetric sets of peaks that look like doublets.

The order of these peaks is dependent on the nature of the two substituents. For example, the three NMR spectra of chloronitrobenzene isomers are below:

=Mass Spectrometry=

A mass spectroscope measures the exact mass of ions, relative to the charge. Many times, some form of separation is done beforehand, enabling a spectrum to be collected on a relatively pure sample. An organic sample can be introduced into a mass spectroscope and ionised. This also breaks some molecules into smaller fragments.

The resulting mass spectrum shows:

1) The heaviest ion is simply the ionised molecule itself. We can simply record its mass.

2) Other ions are fragments of the molecule and give information about its structure. Common fragments are:

=Infrared spectroscopy.=

Absorbing infrared radiation makes covalent bonds vibrate. Different types of bond absorb different wavelengths of infrared: Instead of wavelength, infrared spectroscopists record the wavenumber; the number of waves that fit into 1 cm. (This is easily converted to the energy of the wave.)

For some reason the spectra are recorded backwards (from 4000 to 500 cm-1 is typical), often with a different scale below 1000 cm-1 (to see the fingerprint region more clearly) and upside-down (% radiation transmitted is recorded instead of the absorbance of radiation).

The wavenumbers of the absorbed IR radiation are characteristic of many bonds, so IR spectroscopy can determine which functional groups are contained in the sample. For example, the carbonyl (C=O) bond will absorb at 1650-1760cm-1.

Summary of absorptions of bonds in organic molecules
Infrared Spectroscopy Correlation Table

Absorptions listed in cm-1.

Typical method

A beam of infra-red light is produced and split into two separate beams. One is passed through the sample, the other passed through a reference which is often the substance the sample is dissolved in. The beams are both reflected back towards a detector, however first they pass through a splitter which quickly alternates which of the two beams enters the detector. The two signals are then compared and a printout is obtained.

A reference is used for two reasons:
 * This prevents fluctuations in the output of the source affecting the data

 * This allows the effects of the solvent to be negated (the reference is usually a pure form of the solvent the sample is in).

=References & notes=

SDBS is a free on-line database of Spectral analysis including many IR, NMR and MS graphs.

title: Organic Chemistry/Spectroscopy


text:
Calculus/Higher Order Derivatives

The second derivative, or second order derivative, is the derivative of the derivative of a function. The derivative of the function $$f(x)$$ may be denoted by $$f'(x)$$, and its double (or "second") derivative is denoted by $$f''(x)$$. This is read as "$$f$$ double prime of $$x$$", or "The second derivative of $$f(x)$$". Because the derivative of function $$f$$ is defined as a function representing the slope of function $$f$$, the double derivative is the function representing the slope of the first derivative function.

Furthermore, the third derivative is the derivative of the derivative of the derivative of a function, which can be represented by $$f'''(x)$$. This is read as "$$f$$ triple prime of $$x$$", or "The third derivative of $$f(x)$$". This can continue as long as the resulting derivative is itself differentiable, with the fourth derivative, the fifth derivative, and so on. Any derivative beyond the first derivative can be referred to as a higher order derivative.

Notation
Let $$f(x)$$ be a function in terms of $$x$$. The following are notations for higher order derivatives.

Warning: You should not write $$f^n(x)$$ to indicate the $$n$$-th derivative, as this is easily confused with the quantity $$f(x)$$ all raised to the nth power.

The Leibniz notation, which is useful because of its precision, follows from

 * $$\frac{d}{dx}\left(\frac{df}{dx}\right)=\frac{d^2f}{dx^2}$$

Newton's dot notation extends to the second derivative, $$\ddot y$$, but typically no further in the applications where this notation is common.

Examples
Find the third derivative of $$f(x)=4x^5+6x^3+2x+1$$ with respect to $$x$$.
 * Example 1

Repeatedly apply the Power Rule to find the derivatives.

 * $$f'(x)=20x^4+18x^2+2$$
 * $$f''(x)=80x^3+36x$$
 * $$f'''(x)=240x^2+36$$

Find the 3rd derivative of $$f(x)=12\sin(x)+\frac{1}{x+2}+2x$$ with respect to $$x$$.
 * Example 2

 * $$f'(x)=12\cos(x)-\frac{1}{(x+2)^2}+2$$
 * $$f''(x)=-12\sin(x)+\frac{2}{(x+2)^3}$$
 * $$f'''(x)=-12\cos(x)-\frac{6}{(x+2)^4}$$

For applications of the second derivative in finding a curve's concavity and points of inflection, see "Extrema and Points of Inflection" and "Extreme Value Theorem". For applications of higher order derivatives in physics, see the "Kinematics" section.
 * Applications

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: Calculus/Higher Order Derivatives


text:
Sanskrit/Introduction

Sanskrit is an ancient language of the Indo-European family, from which is descended many languages found in northern India. The language is also known as 'devabhāṣā' (language of the gods) or 'devavaani' (voice of the gods). Since the 10th century CE, Sanskrit has been primarily written in the Devanaagari script, but it is common for the language to be printed or written in Indian vernacular scripts. The word Sanskrit is derived from the word 'saṃskṛtá' meaning "polished" or "perfectly done". The earliest form of Sanskrit is known as Vedic Sanskrit and was spoken by the people of India in the second millennium BCE. Classical Sanskrit, mostly associated with religion, philosophy, and literature, emerged later in the 5th century BCE after PaaNini's extensive grammar codified the language.

Sanskrit has a rich literary tradition whose most famous poets and playwrights include is Kaalidaasa, mostly known for his compositions Meghadutam, Kumaarasambhavam, Abhijnaanasakuntalam, and Raghuvamsam. The Vedas are written in the Sanskrit language and are the roots of Vedic culture. They are considered to be a collection of great knowledge and spiritual puissance. Samskrita Bharati, an NGO, has taken the initiative to popularize the Sanskrit language.

title: Sanskrit/Introduction


text:
German/Level I/Das Fest

Lesson I.10: Das Fest

This lesson deals with the Christmas time in the German language countries, where you learn some traditions and vocabularies about Christmas. You'll also learn about "there is" and "there are" in German and about the dative case.

Dialogue
Read and listen to the following dialogue between mother and daughter: Roswitha and Anja. Both of them want to decorate for Christmas.

 * In Austria Adventkranz

Es gibt

 * The English words there is and there are are both in German es gibt. When you ask someone, if there's a snowman, you say Gibt es hier einen Schneemann?. Many German native speaker put the words gibt and es into gibt's.

Weihnachten in Deutschland
In Germany the advent season begins on Sunday four weeks before Christmas. It's the day where many families decorate their houses or flats, begin to bake some biscuits and start to sing some Christmas carols. One typical decoration is the advent wreath, which has four candles - one candle is lit in the first week, two candles in the second week, etc. - and normally stands on the dining table or on the coffee table. Another tradition, especially for children, is the advent calendar that you hang on the wall. They've often got 24 doors and you're only allowed to open one a day. Other typical Christmas decorations are a crib, a Räuchermann - a wooden figure that blows flavour of incense cones - in Northern Germany a Moosmann, Christmas pyramids and Schwibbogen and nutcrackers and poinsettias and much more. Most Christmas markets start in the first week of Advent. There you can buy some little Christmas presents, decorations, ride some carnival rides, and often drink some hot spiced wine - the children drink punch for children, listen to carolers and enjoy a warm, snowy atmosphere. On the 6th of December, German children celebrate St. Nicholas Day. The children put a boot in front of the door and wait until St. Nicholas brings little presents that are often sweets, walnuts, apples, tangerines and oranges. Bad children get birching by Knecht Ruprecht (which is now forbidden in Germany). Pupils do a secret Santa with other pupils on the last school days before the Christmas holidays, which are often two or three weeks long. St. Nicholas looks similar to Santa Claus who brings big presents on the evening of the 24th of December; in Southern Germany Christkind brings the presents. Most families decorate their Christmas trees on this day with Christmas baubles and tinsel and candles and so forth. After the Christmas dinner, the whole family sits next to the Christmas tree and exchanges gifts.

 * Do you have the Christmas spirit yet? -  Bist du schon in Weihnachtsstimmung?
 * Do you decorate your house this year? -  Schmückst du dieses Jahr dein Haus?
 * On St. Nicholas Day gets Julian a little present. - An Nikolaustag bekommt Julian ein kleines Geschenk.
 * The Queen takes every year a Christmas Day Speech.  -  Die Queen hält jedes Jahr eine Weihnachtsansprache.
 * The whole room is sweet with cinnamon. - Der ganze Raum duftet nach Zimt.

Dativsätze

 * The Dativ, also called 3. Fall or Wemfall is in the German language the third object.
 * Die Kokosmakronen gehören der Anja. - You ask: Wem gehören die Kokosmakronen? - the answer is: Der Anja (gehören die Kokosmakronen).
 * Lisa schenkt (dem) Björn ein Spekulatius - You ask: Wem schenkt Lisa ein Spekulatius? - the answer is: Dem Björn (schenkt Lisa ein Spekulatius).

Weihnachtsessen
das Plätzchen, der Keks        cookie die Ausstecher                 cookie cutter das Nudelholz                  rolling pin die Vanillekipferl             vanilla cornets der Lebkuchen                  gingerbread das Lebkuchenhaus              gingerbread house die Kokosmakrone               coconut macaroon die Spitzbuben                 jammy dodgers, linzer eye a biscuit with currant jam and icing powdered sugar die Pfeffernuss                spice nut der Christstollen              stollen die Marzipankartoffel          marzipan potato die Weihnachtsgans             Christmas goose der Weihnachtskarpfen          Christmas carp der Truthahn                   turkey Würstchen und Kartoffelsalat   sausages and potato salad das Spekulatius                almond biscuit der Baumkuchen                 pyramid cake der Mürbeteig                  shortcrust der Springerle                 springerle das Bethmännchen               bethmännchen typical Frankfurt marzipan biscuits der Zimtstern                  star-shaped cinnamon biscuit das Früchtebrot                fruitcake der Bratapfel                  roast apple der Dominostein                domino  a candy that you can eat in advent time die Zuckerstange               candy cane der Glühwein                   hot spiced wine der Kinderpunsch               punch for children das Kenkentjüch                kenkentjüch cookies from northern Germany die gebrannte Mandeln          roasted almonds das Weihnachtsessen            Christmas dinner das Hirschhornsalz             salt of harts horn der Zimt                       cinnamon der Puderzucker                icing powdered sugar das Aroma                      flavour

So in Swabian they call it Plätzle or Brötle and in Bavaria Platzerl. In Switzerland they call it Guetsli. In Austria and Bavaria they call it Nudelwalker and in Switzerland Wallholz.
 * In the southern part of Germany they have other words for Plätzchen.
 * Other names for Nudelholz are Teigrolle, Wellholz, Wälgerholz and Rollholz rare.

title: German/Level I/Das Fest


text:
Talk:Using Firefox

About

 * Started: 1 June 2004
 * Size: ?? words
 * Templates:
 * Templates:
 * Templates:

To Do
This is a just a general list of things to work on or ideas to consider. Feel free to add, comment, or strike out items from the list.
 * Customizing the Firefox interface
 * feature set and differences between IE - perhaps this can help?
 * maybe we could add tips to make it more 'book-like'? does a tip box type thing exist in wikibooks?
 * possibly organize our categories (mouse shortcuts could be merged w/ keyboard shortcuts)
 * Very good idea--Midnightcomm 17:39, 16 January 2006 (UTC)

 * external links - forums, extension/theme links, help
 * plugins
 * useful extensions - we can't expect a user to wade through hundreds of extensions
 * safe-mode
 * separate profiles
 * pop-up blocking
 * more images
 * possibly a FAQ? (how to block ads, single window mode, change key combinations)?
 * theme info

Keyboard shortcut changes
For 1.0 PR some keyboard shortcuts will be changing:

 * Download manager, Windows & Mac OS X: Ctrl+J
 * Download manager, Unix: none
 * Web search, All platforms: Ctrl+K
 * Web search, Windows & Mac OS X: Ctrl+E
 * Web search, Unix: Ctrl+J

See also bug 250396 and bug 258694

-- Greg K Nicholson 15:41, 11 Sep 2004 (UTC)

Keyboard shortcuts:

Updated the main document since 1.0 PR's release. Page Info no longer seems to have a keyboard shortcut. Need confirmation from Mac OS X and Linux users that Backspace for Back and Shift+Backspace for Forward are Windows-only. Confirmation of other platform-specific keyboard shortcuts would be nice.

Perhaps a two-dimensional table with one column per OS would be better?

-- Greg K Nicholson 03:34, 25 Sep 2004 (UTC)

The list of Firefox keyboard shortcuts appears to be current.

--Eibwen 03:52, 25 Sep 2004 (UTC)

update
When you press the update extensions button, does it update extensions that you downloaded from sites other than mozilla update? if i download one from extensionsmirror.nl or from a private website, does it get updated, too? - Omegatron 20:10, 9 Nov 2004 (UTC)

 * I'm pretty sure it does. - Omegatron 16:47, 23 Nov 2004 (UTC)

I learned all kinds of cool stuff here! thanks!--dgd 17:02, 31 Aug 2004 (UTC)

The ultimate adblock.txt file
We should have an "ultimate adblock.txt" file here, in the style of this thread: http://aasted.org/adblock/viewtopic.php?t=45 It should remove everything commonly considered ads, but not have any false positives. Suitable for someone just installing Firefox for the first time. A wiki is perfect for this because people can correct each other's bad entries (which will give false positives) and compress several entries into one with regular expressions.

We can start it off with something like this:

[Adblock] *.ad.* */Banner/* */ad/* */adclick/* *doubleclick.net*

I think a better starting point would be http://www.pierceive.com/ It seems to be the best filter set available, and closest to an "ultimate filter list" (minus filters for certain things like trackers). Best to start with that and create a list of filters to be added in append mode.

Keep this quote in mind:

 * "The idea of compiling the ultimate filter list is appealing, but may present problems. The reason for this is that Adblock works by matching the address of every blockable object against every filter in the list. In algorithmic terms, this scales as O(M*N).

 * This is actually not a very effective way of doing it, but it's necessary because of the use of filters instead of just blacklisting certain servers, and as long as the list is kept small most of us will never notice any delays.

 * What I'm trying to say is that compiling a huge list of every ad-directory on every server on the planet will scale extremely badly. The idea of creating a "beginner's list" is very good, though, but should perhaps be limited to containing very generic filters (*/ads/*, *doubleclick*, etc). At the moment, every filter-list should be adapted to the needs of the individual user and his surfing habits."

We should point it out to that thread after it gets started, too. - Omegatron 18:31, 24 Jan 2005 (UTC)

I've hosted a pretty basic adblock file that was originally posted on TotalFark, and which I've improved slightly. It can be found at my filespace. To download it, move to the root directory (delete the filename from the address bar) and right-click, selecting "Save Link As." If you feel a need to update, feel free to replace this link. -TotalFarker Atvar

Here is another: http://www.geocities.com/pierceive/adblock/ - Omegatron 13:28, 22 July 2005 (UTC)

1.5 release?
Perhaps any new information should use the 1.5 RC or the latest nightlies instead of 1.0x, so that it won't need to be converted to reflect the new release. I'm going to try and start working on this when I have time, especially since the new release is nearing. -Gflores 02:53, 7 November 2005 (UTC)

Firefox in Wikipedia
There's a ton of information on Firefox in Wikipedia. In fact, it's even been on the main page as a feature article. Most of it is encyclopedic information that won't be pertinent in a wikibook, but some things like Features of Firefox will be very helpful. Some other things that we could use is history of Firefox and general tidbits of background information that would make this wikibook more complete. Gflores 04:17, 12 November 2005 (UTC)
 * Added

How to use the Internet?
Beyond the technical aspects of an application, many people don't know "how to use the Internet" in a basic way. Where's the guide on these topics?
 * Evaluating credibility, timeliness, and bias of a site
 * How to use a search engine
 * How to narrow down a broad search
 * How to read the results page
 * How to discern between paid ads and "organic" results
 * Using special sites (such as maps.google.com) to find special kinds of information
 * How to identify phishing sites and protect oneself regarding fraud and privacy

--AndrewZ

"How to create a plugin"
Hi, I've commented out "How to create a plugin" because Plugins are flash, quicktime, etc. If it's supposed to be a Search Plugin, please change that. Pilif12p (talk) 17:07, 6 August 2010 (UTC)

title: Talk:Using Firefox


text:
User:Soska~enwikibooks

Soska is an undergraduate student of International Relations at the Technical University of Lisbon, ISCSP.

title: User:Soska~enwikibooks


text:
Serial Programming/Forming Data Packets

Just about every idea for communicating between computers involves "data packets", especially when more than 2 computers are involved.

The idea is very similar to putting a check in an envelope to mail to the electricity company. We take the data (the "check") we want to send to a particular computer, and we place it inside an "envelope" that includes the address of that particular computer.

A packet of data starts with a preamble, followed by a header, followed by the raw data, and finishes up with a few more bytes of transmission-related error-detection information -- often a Fletcher-32  checksum. We will talk more about what we do with this error-detection information in the next chapter, Serial Programming/Error Correction Methods.

The accountant at the electricity company throws away the envelope when she gets the check. She already knows the address of her own company. Does this mean the "overhead" of the envelope is useless ? No.

In a similar way, once a computer receives a packet, it immediately throws away the preamble. If the computer sees that the packet is addressed to itself, and has no errors, then it discards the wrapper and keeps the data.

The header contains the destination address information used by all the routers and switches to send the complete packet to the correct destination address, like a paper envelope bears the destination address used by the postal workers that carry the mail to the correct destination address. Most protocol use a header that, like most paper mail envelopes, also include the source address and a few other bits of transmission-related information.

Unfortunately, there are dozens of slightly different, incompatible protocols for data packets, because people pick slightly different ways to represent the address information and the error-detection information.

... gateways between incompatible protocols ...

Packet size tradeoffs
Protocol designers pick a maximum and minimum packet size based on many tradeoffs.
 * packets should be "small" to prevent one transmitter transmitting a long packet from hogging the network.
 * packets should be "small" so that a single error can be corrected by retransmitting one small packet rather than one large packet.
 * packets should be "large" so more time is spent transmitting good data and less time is spent on overhead (preamble, header, footer, postamble, and between-packet gap).
 * the packet header and trailing footer should be short, to reduce overhead.
 * the footer should hold a large error-detection codeword field, because a shorter codeword is more likely to incorrectly accept an error-riddled packet (we discuss error-detection in more detail in the next chapter, ../Error Correction Methods/).
 * making the packet header a little longer, so that meaningful fields fall on byte or word boundaries, rather than highly encoded bit fields, makes it easier for a CPU to interpret them, allowing lower-cost network hardware.
 * making the packet header a little longer -- instead of a single error-detection field that covers the whole packet, we have one error-detection field for the header, and another error-detection field for the data -- allows a node to immediately reject a packet with a bit error in the destination address or the length field, avoiding needless processing. The same CRC polynomial is used for both. Such an "extra" CRC that covers only the header is used in several file formats -- it's an optional feature of the MPEG audio file format,  an optional feature of the gzip format, etc.

 * fixed-size packets -- where all packets fall into a few length categories -- do not require a "length" field, and simplify buffer allocation, but waste "internal" data space on padding the last packet when you want to send data that is not an exact multiple of the fixed data size.

Start-of-packet and transparency tradeoffs
Unfortunately, it is impossible for any communication protocol to have all these nice-to-have features:
 * transparency: data communication is transparent and "8 bit clean" -- (a) any possible data file can be transmitted, (b) byte sequences in the file always handled as data, and never mis-interpreted as something else, and (c) the destination receives the entire data file without error, without any additions or deletions.
 * simple copy: forming packets is easiest if we simply blindly copy data from the source to the data field of the packet without change.
 * unique start: the start-of-packet symbol is easy to recognize, because it is a known constant byte that never occurs anywhere else in the headers, header CRC, data payload, or data CRC.
 * 8-bit: only uses 8-bit bytes.

Some communication protocols break transparency, requiring extra complexity elsewhere -- requiring higher network layers to implement work-arounds such as binary-to-text encoding or else suffer mysterious errors, as with the Time Independent Escape Sequence.

Some communication protocols break "8-bit" -- i.e., in addition to the 256 possible bytes, they have "extra symbols". Some communication protocols have just a few extra non-data symbols -- such as the "long pause" used as part of the Hayes escape sequence; the "long break" used as part of the SDI-12 protocol; "command characters" or "control symbols" in 4B5B coding, 8b/10b encoding; etc. Other systems, such as 9-bit protocols, transmit 9 bit symbols. Typically the first 9-bit symbol of a packet has its high bit set to 1, waking up all nodes; then each node checks the destination address of the packet, and all nodes other than the addressed node go back to sleep. The rest of the data in the packet (and the ACK response) is transmitted as 9 bit symbols with the high bit cleared to 0, effectively 8 bit values, which is ignored by the sleeping nodes. (This is similar to the way that all data bytes in a MIDI message are effectively 7 bit values; the high bit is set only on the first byte in a MIDI message). Alas, some UARTs make it awkward, difficult, or impossible to send and receive such 9-bit characters.

Some communication protocols break "unique start" -- i.e., they allow the no-longer-unique start-of-packet symbol to occur elsewhere -- most often because we are sending a file that includes that byte, and "simple copy" puts that byte in the data payload. When a receiver is first turned on, or when cables are unplugged and later reconnected, or when noise corrupts what was intended to be the real start-of-packet symbol, the receiver will incorrectly interpret that data as the start-of-packet. Even though the receiver usually recognizes that something is wrong (checksum failure), a single such noise glitch may lead to a cascade of many lost packets, as the receiver goes back and forth between (incorrectly) interpreting that data byte in the payload as a start-of-packet, and then (incorrectly) interpreting a real start-of-packet symbol as payload data. Even worse, such common problems may cause the receiver to lose track of where characters begin and end. Early protocol designers believed that once synchronization has been lost, there must be a unique start-of-packet character sequence required to regain synchronization. Later protocol designers have designed a few protocols, such as CRC-based framing, that not only break "unique start" -- allow the data payload contain the same byte sequence as the start-of-packet, supporting simple-copy transparency -- they don't even need a fixed unchanging start-of-packet character sequence.

In order to keep the "unique start" feature, many communication protocols break "simple copy". This requires a little extra software and a little more time per packet than simply copying the data -- which is usually insignificant with modern processors. The awkwardness comes from (a) making sure that the entire process -- the transmitter encoding/escaping a chunk of raw data into a packet payload that must not include the start-of-packet byte, and the receiver decoding/unescaping the packet payload into a chunk of raw data -- is completely transparent to any possible sequence of raw data bytes, even if those bytes include one or more start-of-packet bytes, and (b) since the encoded/escaped payload data inevitably requires more bytes than the raw data, we must make sure we don't overflow any buffers even with the worst possible expansion, and (c) unlike "simple copy" where a constant bitrate of payload data bits results in the same constant goodput of raw data bits, we must make sure that the system is designed to handle the variations in payload data bitrate or raw data bit goodput or both. Some of this awkwardness can be reduced by using consistent-overhead byte stuffing (COBS). rather than variable-overhead byte stuffing techniques such as the one used by SLIP.

Calculate the CRC and append it to the packet *before* encoding both the raw data and the CRC with COBS.

preamble
Two popular approaches to preambles are:

 * The first transmitter sends just enough preamble bits for this hop's receiver to lock on. Then it sends the packet. That receiver, once it knows it needs to forward the packet another hop, transmits a fresh new full-size preamble over the next hop, followed by the data packet. The benefit is that a relatively short, fixed-length preamble is adequate no matter how many hops the data packet jumps over.

 * The first transmitter sends a much longer preamble, much longer than is really necessary for this hop's receiver to lock on. Then it sends the packet. That receiver, as soon at it detects the preamble, immediately transmits each incoming bit out the other port(s) until it gets to the end of the packet. The benefit is that relay nodes can be extremely simple, since they don't have to store any data. Preamble consumption (5-4-3 rule) makes the preamble get shorter and shorter after each hop -- too many bits lost and eventually there is not enough preamble bits to lock on and the entire packet is lost.

For further reading

 * Optical and radio receivers usually require a preamble of some minimum length in order to synchronize bit clocks. For detailed information on calculating exactly how long (how many transitions) the preamble needs to be, see Clock and Data Recovery/Structures and types of CDRs/The CDR based on a first order PLL.
 * http://intcomm.wiki.taoriver.net/moin.cgi/ProtocolMadness
 * UDP
 * Internet Technologies/Protocols including TCP/IP and HTTP
 * ATM
 * VSCP - Very Simple Control Protocol http://www.vscp.org/ "The protocol is free"
 * "Protocol Design Folklore" by Radia Perlman. Jan 15, 2001. http://www.awprofessional.com/articles/article.asp?p=20482
 * "Devices that play together, work together: UPnP defines common protocols and procedures to guarantee interoperability among network-enabled PCs, appliances, and wireless devices." article by Edward F Steinfeld, EDN, 9/13/2001 http://www.reed-electronics.com/ednmag/index.asp?layout=article&articleid=CA154802&spacedesc=readersChoice&rid=0&rme=0&cfd=1
 * CAN bus http://computer-solutions.co.uk/ http://computer-solutions.co.uk/gendev/can-module.htm
 * "CMX-MicroNet is the first system that allows TCP/IP
 * and other protocols to be run natively on small processors
 * ... [including] AVR, PIC 18, M16C."

 * "byteflight is a high speed data bus protocol for automotive applications" http://byteflight.com/
 * Nagle's rule ... The Nagle algorithm. "Nagle's rule is a heuristic to avoid sending particularly small IP packets, also called tinygrams. Tinygrams are usually created by interactive networking tools that transmit single keystrokes, such as telnet or rsh. Tinygrams can become particularly wasteful on low-bandwidth links like SLIP. The Nagle algorithm attempts to avoid them by holding back transmission of TCP data briefly under some circumstances." -- http://www.tldp.org/LDP/nag/node45.html
 * The SLIMP3 Client Protocol
 * Beej's Guide to Network Programming Using Internet Sockets by Brian "Beej" Hall 2005-11-05
 * "RF Link Using the Z86E08" describes yet another "simple" packet protocol ... also mentions a preamble to train the RF receiver just before the rest of the packet.
 * Algorithm Implementation/Checksums
 * ... other packet protocols ? ...
 * Communication Systems/Packet Data Systems
 * Communication Networks

title: Serial Programming/Forming Data Packets


text:
Prolog/Introduction

This section covers the installation of a prolog compiler, loading your first program, and querying it. It then explains how to use facts and variables in your programs and queries.

Getting Started
Before anything can be done, a prolog compiler and a text editor need to be installed on your system. A text editor will allow you to write your prolog programs and the prolog compiler (also known as the interpreter) will allow you to execute them.

Prolog Compilers

The following prolog implementations are free (at least for personal or educational use, be sure to read the terms). Simply download one and install it according to the instructions on the website:

 * B-Prolog
 * http://www.picat-lang.org/bprolog/
 * A Prolog compiler for standard Prolog with extended features such as tabling and constraint solving. Supports many platforms.

 * SWI Prolog (recommended for use with this book)
 * https://www.swi-prolog.org/
 * A small and robust open-source implementation that is compliant with both Prolog standards (ISO and Edinburgh) and has many extra libraries and built-in predicates. There's even a separate toolkit for creating windows and graphics, called XPCE. Supports many platforms.
 * GNU Prolog
 * http://www.gprolog.org/ (was: http://pauillac.inria.fr/~diaz/gnu-prolog/ )
 * A relatively new open source implementation. Has support for Constraint Logic Programming, an extension of prolog.
 * Visual Prolog
 * http://www.visual-prolog.com/
 * A complete development environment for an Object-Oriented extension of Prolog. Includes compiler, linker, text editor, graphical dialog editors, build system, debugger, large library, and much more

The following implementations aren't free:
 * SICSTUS Prolog
 * http://www.sics.se/
 * Probably the most well known professional prolog implementation and development suite. ISO-compliant, many libraries and support for constraint logic programming. Free for evaluation.
 * Quintus Prolog
 * http://www.sics.se/quintus/
 * An especially robust and dependable implementation intended for commercial use and research projects by the same company that makes SICSTUS. Free for evaluation.

Text Editors

The programs that you will write are simple text files, to be read and written with any text editor. Some prolog implementations come with their own editor, but for those that don't here's a list of text editors. These provide the basic function that are useful for writing prolog programs, such as indentation, bracket matching and some can even be adjusted to highlight the syntax of your prolog code.

 * Crimson Editor
 * http://www.crimsoneditor.com/
 * A free text-editor for windows with many features.
 * GNU Emacs
 * http://www.gnu.org/software/emacs/emacs.html
 * A free, open-source implementation of unix' classic text editor. May be difficult to understand, has lots of features.
 * Vim
 * http://www.vim.org/
 * A free, open-source implementation of Emacs' long-standing rival.
 * Textpad
 * http://www.textpad.com/
 * A windows text-editor with many features. Free for evaluation.
 * Eclipse Prolog Plugin
 * http://eclipse.ime.usp.br/projetos/grad/plugin-prolog/index.html
 * A free plugin for Eclipse.

First Steps
Once you've installed your prolog implementation, it's time to write the first program and load it into the interpreter (mainly to see if everything works). Fire up your text editor and create a text file with just the following line in it:

human(john).

Be precise, capitalization is important in prolog, as is the period. This will be your program (also known as the database or the knowledge base). Give it a nice name like prolog1.pl and save it. ''Note: The extension pl isn't officially associated with prolog and can cause conflicts if you're also programming in Perl, which uses .pl as well. If this is a problem you can use pro or pr or anything you like just as well.'' Now start your prolog interpreter. Most prolog interpreters will show you a window with some startup information and then the line

?-

with a cursor behind it. There is usually a menu for loading files into the interpreter. If there isn't, you can type the following to load your file:

consult('FILEPATH').

And press enter. Once again, be precise, no capitals and remember the dot. Replace FILEPATH with the name and directory of your file. For instance if your file is located in C:\My Documents\Prolog\prolog1.pl then use consult('c:/my documents/prolog/prolog1.pl'). or the shorthand ['c:/my documents/prolog/prolog1.pl'].

Note that the slashes are the other way around, since the backslash (\) has special meaning in Prolog (and most other languages). If you are using a UNIX based system such as Linux, the commands may look something like this

consult('/home/yourName/prolog/prolog1.pl'). ['/home/yourName/prolog/prolog1.pl'].

Your interpreter will now hopefully tell you that the file is loaded correctly. If it doesn't, consult the help file or manual of your implementations on how to consult files.

Also, you can tell prolog interpreter to load file automatically, if running it with the key, like this : prolog -s /home/yourName/prolog/prolog1.pl

After some information you will see

?-

To see if everything is working, type

human(john).

(don't forget the period) and press Enter. Prolog will answer with

true.

Type

human(Who).

, press Enter and Prolog will answer

Who = john.

To exit prolog, type

halt.

Syntax, Facts and Queries
The line human(john). in the previous example was a prolog sentence in the form of a predicate. This type of sentence is called a fact. Predicates consist of one word of one or more characters, all lowercase, possibly followed by a number of terms. The following are examples of valid predicates:

human(john) father(david, john) abc(def,ghi,jkl,m) tree p(a ,f ,d)

The terms (the 'words' within parentheses) can take many forms, but for now we will stick to constants. These are words, again all lowercase. The first character of both a predicate and a constant needs to be a letter. Using predicates we can add facts to a program:

human(john). human(suzie). human(eliza). man(david). man(john). woman(suzie). woman(eliza). parent(david, john). parent(john, eliza). parent(suzie, eliza).

Note the period '.' behind each line to show that the line is over. This is very important, if you forget it, your interpreter will not understand the program. You should also be aware that the names chosen for the predicates and terms do not actually mean anything to the prolog interpreter. They're just chosen to show what meaning you have for the program. We could easily replace the word human with the word spaceship everywhere and the interpreter wouldn't know the difference.

If we load the above program into the interpreter we can run a query on it. If you type human(john).

Prolog will answer

true.

and if you type woman(john).

Prolog will answer

false.

This also seems fairly obvious, but it's important to see it the right way. If you ask Prolog, it means you are asking Prolog if this statement is true. Clearly Prolog can't see from the statement whether it's true, so it consults your file. It checks all the lines in the program to see if anyone matches the statement and answers Yes if it finds one. If it doesn't, it answers. Note that if you ask

?- human(david).

Prolog will answer, because we have not added that fact to the database. This is important: if Prolog can't prove something from the program, it will consider it not true. This is known as the closed world assumption.

Variables
We'll update the program with human(david), so that all people in the database are human, and either a man or a woman

human(david). human(john). human(suzie). human(eliza). man(david). man(john). woman(suzie). woman(eliza). parent(david, john). parent(john, eliza). parent(suzie, eliza).

What we have now is still not a very expressive language. We can gain a lot more expressiveness by using variables in our query. A variable is a word, just like terms and predicates, with the exception that it starts with an uppercase letter and can have both upper and lowercase characters after that. Consider the following query

human(A).

Now, the term of the predicate is a variable. Prolog will try to bind a term to the variable. In other words, you are asking Prolog what A needs to be for human(A) to be true.

?- human(A).

Prolog will answer

A = david ;

Which is true, because the database contains the line human(david). If you press enter, Prolog will answer Yes and give you back your cursor. If you press semicolon  Prolog will show you the rest of the possibilities

A = john ; A = suzie ; A = eliza.

After eliza, there are no further possibilities. If you query Prolog with more than one variable it will show you all instantiations of the variables for which the query is true: ?- parent(Parent, Child).

Parent = david Child = john ;

Parent = john Child = eliza ;

Parent = suzie Child = eliza ;

No

When prolog is asked a query with a variable it will check all lines of the program, and attempt to unify each predicate with the query. This means that it will check if the query matches the predicate when the variables are instantiated a certain way. It can unify human(A) with human(john) by making A john, but it can't unify man(A) with human(john), because the predicates don't match.

If we want to make it even more difficult for prolog we can use two predicates in our query, for instance: ?- human(A), parent(B,A). Now we are asking prolog for a human A who has a parent B. The comma means and, indicating that both predicates need to be true, for the query to be true. To check this query, prolog will first find an instantiation to make the first predicate true--say it make A equal to john--and then it will try to make the second predicate true--with A equal to john. If it has found two instantiations for A and B that make both predicates true, it will return them to you. You can press Enter to end the program, or a semi-colon to see more options.

Prolog may make a choice for A, to satisfy the first predicate that doesn't work with the second. Say it chooses A = suzie to satisfy human(A); no choice for B will satisfy parent(B, suzie), so prolog will give up its choice of suzie for A, and try another name. This is called backtracking.

In the example above, prolog will first find human(david) in the program and unify A with david. To make the second predicate true, it needs to find an instantiation for parent(B, david). It can't find any, so it will look for a new instantiation of human(A). It tries the next option: A = john. Now it needs to instantiate parent(B, john). It finds B = david in the line parent(david, john) and reports back to you A = john B = david

If you press semicolon it will try to find a new instantiation for the second predicate. If that fails it will try to find a new instantiation for the first predicate and so forth until it runs out of options.

There is one special variable, called the anonymous variable, for which the underscore (_) character is used. When you use this character in a query, you basically say that you don't care how this variable is instantiated, i.e. you don't care which term it's bound to, as long as it's bound to something. If you ask Prolog ?- parent(A, _). Prolog will answer

A = david; A = john; A = suzie;

It will not tell you how it instantiates _. However if you ask Prolog ?- abc(_,_,_). This will not be true by default, Prolog needs to find an instantiation for all three anonymous variables in the database, such as abc(d,e,f). Since the predicate abc isn't in the database at all, the query fails. You can use the anonymous variable in your database as well. Placing

human(_).

in your database will mean that any term, whether it already exists or not, is human. So the queries ?- human(mark). and ?- human(orange).

would be true with the above fact in the database. Here the anonymous variable is used to state a property of all objects, instead of just one. If we want to state that a specific group of objects has a certain property, we need rules. The next section deals with this.

Examples
The following program describes the public transport systems of some cities: transport(dresden, tram). transport(amsterdam, tram). transport(amsterdam, subway). transport(new_york, subway).

We can ask prolog if there is a city which has both a tram system and a subway: ?- transport(A, subway), transport(A, tram). A = amsterdam ; fail.

Exercises
(x) Find a Family Tree somewhere, or make one up (a real one will make it easier to check your answers). Implement part of the tree (around ten people) in a prolog program using the predicates woman/1, man/1, parent/2. The number behind the predicate describes how many arguments the predicate takes. So parent/2 describes a predicate like parent(john, mary).

You can peruse w:Category:Family_trees for a suitable family tree.

Write prolog queries for the following commands and questions. Don't worry if some people are returned more than once. We'll discover how to deal with this later on.

 * 1) List the women in the database
 * 2) List the children in the database
 * 3) List all combinations of a father and his son.
 * 4) which women have both a father and a son in the database?

Can you think of a way to display those women that do not have a father listed in the database? Can you describe what you would need to write such a query?

The answers to select excercises can be found here: Prolog/Introduction/Answers

title: Prolog/Introduction


text:
Physics with Calculus/Mechanics/Velocity and Acceleration

Conservation of mass : The total mass in a closed system remains constant. Mass can not be created or destroyed[*]. It can, however, change forms.

Density is defined as mass divided by volume

$$\rho = \frac{m}{V}$$

[*] Usually. There are exceptions in some extreme situations.


text:
User:Beoba~enwikibooks

Want some rye? Course ya do!

title: User:Beoba~enwikibooks


text:
Conplanet/Geography

Conworld : Conplanet : Geography

As with most conplanet creation, what you will do here depends on the degree of realism you want. This page assumes that you are going for a high level of realism; diversions from this are at your own discretion.

Oceans and Continents
On the Earth, the only real example we have of large bodies of water, ocean formation is tied closely with volcanism and tectonics. It appears that oceans are largely formed through water vapour expelled by volcanoes, as well as possibly from infalling comets.

The exact shapes of the continents are seemingly random, but there do seem to be tendencies:

 * Islands usually form over weak spots in tectonic plates (Hawai'i) or where continents have been torn, like taffy, leaving 'bits' behind.
 * If the coastline is close to a source of glaciers, it will have a jagged coastline or a rocky beach.
 * Sand that flows off of a coast could create shifting sandbars and sand islands, especially if it's in a sound.
 * Parts of continental plates are under water, causing relatively shallow shelf seas.

Prevailing Currents and Winds
Having a good understanding of prevailing winds will also help you to model your planet's weather.

Mountain Ranges
Mountains form on converging plate boundaries. Coastal Ranges are created by subducting oceanic plates thrusting up more magma below the crust. Volcanic peaks are formed by diverging or converging boundaries where magma is channelled through the crust. Age of mountains will have an effect on their appearance. For example: Sharp, angular summits will not exist in an ancient, eroded mountain chain, but will form in a newer, more active converging boundary.

Rivers
Notable characteristics about rivers:
 * Rivers usually rise in mountains and then flow to the sea.
 * They always start in high elevations and move to lower elevations.
 * Rivers primarily flow from the seaward sides of mountain ranges to the ocean.

That is why several important rivers start in the Himalayas and flow through India to the Pacific (the nearest ocean) rather than flowing through central Asia to the Arctic Ocean. (This is not exclusively true, though; the Mississippi, for example, starts from a rather nondescript lake in Minnesota and flows to the Gulf of Mexico, all the while going through relatively dry land. However, the Mississippi still travels downslope, and does not go to the relatively more distant Hudson Bay.)

Common mistakes of conworld creators in placing realistic rivers are:
 * Major rivers splitting far from their mouths. Real rivers do not do this.
 * Rivers going one side of a mountain range, through the mountains, to the other side. This would require rivers flowing from a low place to a high place. Going through pre-existing broad valleys is possible, but otherwise, the river would simply flow around the mountains.
 * Rivers that start in the ocean. This does not happen in real life.
 * Rivers flowing two ways out of the same lake. Again, this does not happen in real life. (Except for Gatun Lake and Balsam Lake, but both lakes exist as part of canal systems).

Elevation
That the height of certain geographical features varies widely from those of others seems self-explanatory, but it is a feature of Congeography that many conworlders forget to include. Knowing the elevation of certain areas on a given conmap can help with mapping rivers (as mentioned above), modeling a place's weather, and can even indirectly affect the culture of that area (due to advantages or disadvantages in location).

title: Conplanet/Geography


text:
User:Jamesbooker

Hi!

My name is James Booker (hence the username, eh?). I live in a town called Heanor in the county of Derbyshire, England. Derbyshire is one of many counties in the mid-regions of England known as the Midlands.

History
I joined Wikibooks on the 1st September 2004, and Wikipedia a few weeks before that. I instantly fell in love with the Wikipedia ethic, but found that anything I could contribute to the Wikipedia seemed to already have been done, and so I started looking at the sister projects, where I discovered Wikibooks and the Wikiversity! Since then I only really use Wikipedia as content-reference for Wikibooks.

Interests
My interests are computer programming in PHP, C++, Delphi and a multitude of other languages. I enjoy playing my PS2 and GameCube (I'm an obsessive of the Final Fantasy series, and intend on setting up the complete guidebook here to the entire series) and spending as much time as possible with my fiancé, Rebecca.

My aims in being here are to help expand the Wikibooks project to the point that complete authoratitive texts can be enjoyed by students from all over the world.

My Bookshelf
Wikibooks/Schools I either read or contribute to.

 * Programming:PHP
 * School_of_Music
 * Musictionary

title: User:Jamesbooker


text:
User talk:Ciciban

Hallole,

bei den de-Wikibooks bin ich Administrator, aber das hilft beim Übertragen der Bücher nichts. Ich bin aber dabei, einen Bot zu schreiben, der das erledigen kann. Im Moment sieht es recht gut aus, dass das klappt. Bei den Bildern bin ich mir noch unsicher ob ich es hinbekommen, aber es sieht auch da gut aus.--berni 09:24, 2 Sep 2004 (UTC)

title: User talk:Ciciban


text:
User talk:Jamesbooker

Please add topics to me as new sections with the [+] button next to the 'edit this page link.

Final Fantasy
I actually do have that page on my watchlist, but am not the editor of it. Jonel is the main writer of the page, so you should probably contact him on it.

 * I've actually become fairly busy and don't have much time for editing the Final Fantasy pages. As far as your suggestion on the FF talk page, James, the 'game info' section is basically a beginning of what you were talking about.  Please do add information about the FF series. - Jonel 17:20, 19 Sep 2004 (UTC)

 * Well, I've just discovered [www.gamewiki.org|GameWiki] so I think I'll put it all there instead. - James Booker 10:54, 20 Sep 2004 (UTC)

Wikiversity
I saw your name on the Wikiversity participant's list, you may be very experienced in mathematics already, but I'm trying out instructing a Calculus course if you're interested, go to Wikiveristy, check out the mathematics department, pure mathematics, and in the course list is included Calculus. Fephisto 22:53, 9 July 2006 (UTC)

title: User talk:Jamesbooker


text:
Cookbook:Eggplant Pasta

| Pasta

This tasty vegetable stew is great served with your favorite pasta.

Ingredients

 * 1 eggplant (aubergine)
 * 1 large onion, chopped
 * 1 tbsp olive oil
 * Salt to taste
 * 2 tins of peeled tomatoes
 * 1 chile pepper
 * Handfuls of fresh basil
 * Dried Italian herbs mixture (marjoram, basil, capsicum, oregano, rosemary, parsley, garlic, thyme; often sold pre-mixed)
 * Fresh garlic, crushed
 * Pasta, cooked

Procedure

 * 1) Slice eggplant and cover in salt. Leave for at least 30 minutes.
 * 2) Rinse salt away, then squeeze until almost dry (this removes sourness).
 * 3) Cut eggplant into chip-sized pieces and fry in oil.
 * 4) Add onion and cook briefly.
 * 5) Add all other ingredients and simmer for 30 minutes.
 * 6) Serve with freshly cooked pasta.

Notes, tips, and variations

 * The amounts of the various ingredients are not really important. Experiment and adjust to taste.
 * It is often better to prepare the vegetables the night before as this gives time for the flavours of the chili pepper, garlic, and herbs to diffuse through the mix.
 * Spiral pasta is a good choice, as it holds the sauce to itself.

Warnings

 * Always wash your hands after handling chili peppers. Be especially careful not to touch your eyes.

title: Cookbook:Eggplant Pasta


text:
User:Eggplantpasta~enwikibooks

Hello. My real name is Brett Roper but I was forced to use the name Eggplantpasta because being the 74715th user on Slashdot the more sensible names of Brett and Eggplant were already taken.

I'm a computer programmer from Perth, Western Australia.

Feel free to email me (after removing the spam filter) at brett at pudiga dot org.

title: User:Eggplantpasta~enwikibooks


text:
Distributed Systems

Memory model
Every process in Unix has an address space that looks like this:

global vars—text segment—heap—stack

Remember the low memory is at the top, and the high memory is at the bottom. So when items are added to the stack, and it grows upwards, each element has a lower memory address.

fork is your friend
You should know what this does:

main {    int i, cpid; cpid = fork; if (cpid < 0) exit(1); else if (cpid == 0) { /* this is the child process. */        for (i=0; i<1000; i++) printf("child: %d\n", i); exit(0); }    else { /* this is parent process */ for (i=0; i<1000; i++) printf("parent: %d\n", i); waitpid(cpid); } return 0; }

The call to fork creates a new process with an entire new address space. That means a copy is made of everything: new global vars, new text code, new heap, and new stack. Even object dynamically allocated with malloc are copied. Remember that the pointers to those dynamically-allocated objects are set based on relative addressing, so even the new copied memory is allocated somewhere else, the pointers into the heap still work.

process states
The four most popular UNIX process states are ready, waiting, running, and zombie. The first three are easy. Zombie processes are child processes that have completed and are waiting for their parents to clean them up. Usually parents clean up completed (zombie) child processes by calling wait or waitpid.

If the parent process dies before the child process finishes, eventually the root process will come around and clean them up.

simple example
So, after fork, if each process has its own memory space, how to set up communication? With pipes! Each process may have its own file descriptor table, but they still reference the same files.

Example pipe code, where child reads and parent writes:

NOTE: feel free to add in all that error-checking goodness, but try to keep the point obvious

int p[2]; pipe(p); /* call by address. */ cpid = fork; if (cpid < 0) exit(1); /* child process */ if (cpid == 0) { close(p[1]); /* child won't need to write, so close. */    read(p[0], buf, len); close(p[0]); _exit(0); /* read man 3 exit and man _exit to understand the difference. */ } /* parent */ else { close(p[0]); /* parents can be so close-minded! */    write(p[1], buf, len); close(p[1]); waitpid(cpid); }

Study and understand the above code.

Implementing a very simple shell with pipes
We've all done stuff like this at the command line:

$ ls -l | sort | head

But how does that work? In MS-DOS, this functionality was implemented sort of like this:

ls -l > /tmpfile1 sort /tmpfile1 > /tmpfile2 head /tmpfile2

The three tasks were run sequentially, rather than concurrently. This is bad if the output of the first program is enormous, and this setup certainly can't handle an infinite stream of data.

You can implement the ls -l | sort | head stuff in C. To keep it manageable, the following code implements "ls | wc -l" instead:

int pipes[2]; pipe(pipes); int pid = fork; if(pid < 0) /* Check for error */ {    fprintf(stderr, "fork unsuccessful."); exit(1); } if(0 == pid) /* We are the child */ {    /*      * We don't need the writing end of the pipe. This closes it. */    close(pipes[1]); /*     * Duplicate our output pipe to file descriptor 0. * This means that anything that would normally be read from stdin * is now read from the pipe. */    dup2(pipes[0], 0); /*     * We've duplicated the pipe, so there is no need to leave this copy * hanging around. */    close(pipes[0]); /*     * Execute the "wc -l" command. This replaces our process. */    execlp("wc", "wc", "-l", (char*)0); } else /* We must be the parent */ {    /*      * We don't need the reading end of the pipe. This closes it. */    close(pipes[0]); /*     * This duplicates the pipe into stdout. This means that standard * output is redirected into the pipe. */    dup2(pipes[1], 1); /*     * Since we've duplicated this end of the pipe, we won't need it      * anymore. */    close(pipes[1]); /*     * We're done setting up. This replaces us with the "ls" part of the * command. */    execlp("ls", "ls", (char*)0); }

TODO: talk more about how execv works.

Implementing I/O redirection with pipes
Another classic:

ls -l > out.txt

How can you do?

TODO: finish

err?

Threads
wikipedia thread article

Threads share memory, processes don't. They both allow programs to do multiple things simultaneously (concurrently). Most of the time on Linux, when people talk about threads, they're really talking about POSIX threads, aka pthreads.

Simple pthread example
Example pthread code: int i; /* i is global, so it is visible to all functions. */ static void *foo {    int k;     for (k=0; k<10; k++) { sleep(1); printf("thread foo: %d.\n", i++); }    return NULL; } static void *bar {    int k;     for (k=0; k<10; k++) { sleep(1); printf("thread bar: %d.\n", i++); }    return NULL; } int main { int x;   pthread_t t1, t2; x = pthread_create(&t1, NULL, foo, NULL); if (x != 0) printf("pthread foo failed.\n"); x = pthread_create(&t2, NULL, bar, NULL); if (x != 0) printf("pthread bar failed.\n"); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("all pthreads finished.\n"); return 0; }
 * 1) include
 * 2) include
 * 3) include

This is a slice of the output:

$ ./pthreadfun thread foo: 0. thread bar: 1. thread foo: 2. ... thread foo: 18. thread bar: 19. all pthreads finished.

Hopefully the main point is jumping out at you. Foo and bar alternately increment up the global integer i.

Exercise
Rewrite the above code to use fork and create two processes rather than two threads. Then find what is the maximum value of i and explain the difference with this threaded version.

Kernel threads vs. user threads
pthreads are kernel-space threads, meaning that the OS scheduler is aware of the multiple threads. Each thread has an entry in the OS schedule table.

There are also user-level threads, where the kernel is unaware of the threads. The process must handle scheduling itself. User-level threads require two-level scheduling:

OS scheduler handles all processes Process handles all threads.

One user-level thread can block all the other threads for the process if the programmer isn't careful. If a user-level thread makes some blocking system call, then the OS will suspend that process until that system call returns.

User threads have the advantage of allowing switching between threads in a process much more quickly than kernel-level threads. The process does the context-switching itself.

Solaris hybrid threads
Sun Solaris version 2.3 offered hybrid threads which attempt to combine the speed of user-level threads with the advantages of kernel-level threads. The hybrid threads minimize the OS scheduling cost of switching between threads at the kernel level, but they also allow a thread to make a blocking system call without blocking the entire process.

The system allowed for threads and lightweight processes. The OS scheduler only saw the lightweight processes. Each thread is attached to a lightweight process. Threads can share a process, so one application with multiple threads may appear to the OS scheduler as a single process.

In a program with two threads both bound to a single process, if thread 1 makes a blocking system call, then the OS will block the process. Meanwhile, in order to allow thread 2 to still run, the OS will create new process, detach thread 2 from the first process, and then attach it to the new process.

critical sections and mutexes
If threads are going to share vars, you need to be careful they don't both try to alter memory simultaneously.

Consider this classic C code:

i++;

This looks like one operation (add one to i), but it translates to three operations in assembly code:

lda i; load the value stored in var i into the eax register. inc;   increment up the eax register. sta i; store the value in the eax register into the var i.

Read the C programming appendix in this book for more information on how to convert a C program to assembly using gcc.

Since threads share memory, it is possible for one thread to start to do something, then get suspended by the OS scheduler.

Imagine if two threads exist and i is a global integer, initially set to 99. Each thread wants to increment up i by one, so each thread will do the three assembly steps above. After we are finished, we expect to find i set to 101.

First thread 1 starts:

lda i;   eax register holds 99. inc i;   now, eax holds 100.

Now, imagine at this point the OS scheduler suspends thread 1 and starts thread 2:

lda i;   load 99 from i into eax. This is bad!!! inc i;   increment eax to 100. sta i;   store 100 into i.

And then, the OS allows thread 1 to finish:

sta i;   store eax into i.  but eax only has 100!

So now you see how two threads accessing common variables can be risky. The worst part about this bug is that it will be inconsistent and hard to reproduce. The i++ statement is called a critical section because we need to makes sure that only one thread has access to the variable in that section.

One solution is to use some kind of lock, like this, in each thread:

lock(ilock); i++; unlock(ilock);

Then if thread1 gets suspended, and thread2 starts, it will block on the lock(ilock) call. To do this for real, we can use mutexes. A mutex is like a semaphore that only has values of 1 or 0. The threads in this code will lock and unlock a mutex before trying to increment up i, so you avoid the above problem.

pthread_mutex_t ilock = PTHREAD_MUTEX_INITIALIZER; int i; static void *f1 {    pthread_mutex_lock(&ilock); i++; pthread_mutex_unlock(&ilock); return NULL; } static void *f2 {    pthread_mutex_lock(&ilock); i++; pthread_mutex_unlock(&ilock); return NULL; } int main {    pthread_t t1, t2; int x;    i = 99; x = pthread_create(&t1, NULL, f1, NULL); if (x != 0) printf("pthread foo failed.\n"); x = pthread_create(&t2, NULL, f2, NULL); if (x != 0) printf("pthread bar failed.\n"); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("all pthreads finished.\n"); printf("i set to %d.\n", i); return 0; }
 * 1) include
 * 2) include

That's it!

Another solution to this problem is to use a "increment" instruction that really is atomic. (The "lock" and "unlock" functions use just such an atomic instruction). Such atomic functions (and how they can be used to avoid data corruption and deadlocks) are discussed at Lock-free and wait-free algorithms.

Producer and Consumer model
This hobgoblin shows up all the time in the real world. The chef makes bowls of soup for the diner. The chef has to wait for the diner to ask for soup, and the diner has to wait for the chef to announce the soup is ready. If you ain't careful, you can end up with a deadlock which is just as nasty as it sounds.

A deadlock involves two processes (p1 and p2) and two resources (r1 and r2). Each process needs exclusive access to both resources to finish. The deadlock happens when p1 holds r1 and waits for r2 to be released, and p2 holds r2 and waits for r1. As you can see, neither process can continue.

This pseudocode illustrates how to set up a producer/consumer system and not fear deadlocks:

/*  static soupbuffer buff; semaphore moreplease, soupisready; producerthread {    lock(moreplease);       wait until the kids ask for more. cooksoup(buff);        refill the soup pot. unlock(soupisready);   announce that soup is ready. } consumerthread {    lock(soupisready);      wait until the soup is ready. eatsoup(buff);         empty the soup pot. unlock(moreplease);    ask for more soup. } */

Shared memory
System V provides shared memory. One process can allocate some memory as shared memory, then other processes can attach to that memory, and these processes can communicate.

one process can use shmget to allocate memory. then that process can use shmat to aim a pointer at that memory.

another process can use shmat to attach a pointer to that same memory.

shmdt will detach the pointer from shared memory.

shmctl can be used to free the allocated memory.

You can use  to check on any allocated shared memory, which is a nice way to check if your program freed all allocated memory. will delete allocated shared memory.

Signals
Signals are neat. When you hit Ctrl+C to kill a process, you're really sending SIGINT to that process. Similarly, Ctrl+Z sends SIGTSTP and `kill -9 pid` sends the 9th signal, SIGKILL. The full listing of available signals is in the seventh section of the manual pages (`man -s 7 signal`).

signal handlers
When a process receives a signal, the corresponding function is invoked. In the case of SIGKILL, the function causes the code to exit. Many of these signals can be trapped and reassigned to a custom function as illustrated in the following code:

void sighandler(void) {    printf("i am un-SIGINT-able!\n"); } int main {    signal(SIGINT, sighandler); perror("signal"); while (1) { printf("sleeping...\n"); sleep(1); }    return 0; }
 * 1) include
 * 2) include
 * 3) include

Compile and run the program above and then try to kill it with Ctrl+c. Now, try to kill the program with `kill -s SIGKILL pid`.

When Ctrl+c is pressed, the process is sent the SIGINT signal; however instead of terminating, the custom function sighandler is invoked. Since the SIGKILL signal is not trapped, the code exited normally.

The signal function will not let you write a handler for SIGKILL.

In HP-UX, after the signal arrives, the signal handler is forgotten for that signal. So, often inside the signal handler, it re-registers it self as the handler: void sighandler(void) {    printf("i am un-SIGINT-able!\n"); signal(SIGINT, sighandler); }

In Linux, this is not necessary.

sigalarm
The SIGALRM signal can be raised by the alarm function, so it's a good way to generate a signal inside your program. The below code illustrates:

signal(SIGALRM, onintr); alarm(3); while (1) ; /* run forever. */ void onintr {    printf("3 second violation.\n"); alarm(3); }

This program will run until you kill it.

Signals and setjmp/longjmp
This code calls the SIGALARM handler when the process receives the SIGALARM signal, and then inside the handler, jumps out of the handler without returning.

jmp_buf env; main {    setjmp(env); signal(SIGALRM, onintr); } void onintr {    printf("SIGALRM handler...\n"); longjmp(env); }

There's an issue that might not be obvious. After a process gets a signal, then it calls the signal handler. If another signal comes in while the first signal is still being processed, the process will ignore that second signal. The OS "blocks" the signal while the handler is running.

When the handler finishes, as part of its return, the OS allows the process to get new signals.

If we jump out of a function with longjmp, then the signal handler will never return, and the process will never hear any new signals of that type coming in. However, don't worry! You can manually unblock the signal and then jump out.

This alternate handler shows how:

void handler {    sigset_t set; sigempty(&set); sigaddset(&set, SIGALRM); sigprocmask(SIG_UNBLOCK, &set, NULL); printf("3 second\n"); longjmp(env); }

You can use the functions sigsetjmp and siglongjmp to jump out of a signal handler and optionally reset the signal mask. The below code shows an example. You'll have to use Ctrl-C to end the program:

sigjmp_buf env; void sh {    printf("handler received signal.\n"); siglongjmp(env, 99); } int main {    int k;     k = sigsetjmp(env, 1); if (k == 0) { printf("setting alarm for 4 seconds in the future.\n"); signal(SIGALRM, sh); alarm(4); while (1) { printf("sleeping...\n"); sleep(1); }    }     else { printf("k: %d.\n", k); alarm(3); printf("set alarm for another 3 seconds in the future.\n"); while (1) { printf("sleeping...\n"); sleep(1); }    }     return 0; }
 * 1) include
 * 2) include
 * 3) include
 * 4) include

Signals and pause
If you want to wait for an event, but don't want to resort to some kind of spin lock, you can use the  function to suspend a running process until a signal occurs.

Example code:

void sh {    printf("Caught SIGALRM\n"); } int main {    signal(SIGALRM, sh); printf("Registered sh as a SIGALRM signal handler.\n"           "BTW, sh is %d and &sh is %d.\n", (int) sh, (int) &sh); alarm(3); printf("Alarm scheduled in three seconds. Calling pause...\n"); printf("RAHUL IS IN WIKIPEDIA WEBSITE AT CHITKARA UNIVERSITY NEAR CHANDIGARH"); pause; printf("pause must have returned.\n"); return 0; }
 * 1) include
 * 2) include
 * 3) include

Also notice that the second print statement casts the function sh to an integer, and also casts the address of sh as an integer. Here's the output of the program:

$ ./pausefun Registered sh as a SIGALRM signal handler. BTW, sh is 134513700 and &sh is 134513700. Alarm scheduled in three seconds. Calling pause... Caught SIGALRM pause must have returned.

Notice that sh after being cast to an integer is the same as the address of sh. That 134513700 is the memory address in the text section of the sh function. Although it may seem a little strange at first, from the OS point of view, functions are really just another kind of data.

Message passing
message passing is distinct from communication via pipes because the receiver can select a particular message from the message queue. With pipes, the receiver just grabs some number of bytes off the front.

The type arg allows priority scheduling. If the 4th arg of msgrcv is > 0, then system will find the first message with the type equal to that specified 4th arg.

If type is < 0, then system will find the first message with the lowest type where type is below the absolute value of type.

If we have these messages: Name:Type A:400 B:200 C:300 D:200 E:100

Then type -250 would return B.

The following two programs show message passing.

mpi1.c:

typedef struct mymsgbuf {    int type; char msg[64]; } mtype; int main {    int msg1, msg2, i;     mtype m1, m2; msg1 = msgget(KEY1, PERM | IPC_CREAT); msg2 = msgget(KEY2, PERM | IPC_CREAT); msgrcv(msg2, &m2, 64, 0, 0); printf("mpi1 received msg: \"%s\" from message queue %d.\n", m2.msg, msg2); m1.type = 20; strcpy(m1.msg, "I doubt"); printf("mpi1 about to send \"%s\" to message queue %d.\n", m1.msg, msg1); i = msgsnd(msg1, &m1, 64, 0); printf("mpi1 sent \"%s\" to message queue %d with return code %d.\n", m1.msg, msg1, i); sleep(1); msgctl(msg1, IPC_RMID, (struct msqid_ds *) 0); msgctl(msg2, IPC_RMID, (struct msqid_ds *) 0); return 0; }
 * 1) include
 * 2) include <sys/ipc.h>
 * 3) include <sys/msg.h>
 * 4) include <stdio.h>
 * 5) include <string.h>
 * 6) include <unistd.h>
 * 1) define KEY1 9870
 * 2) define KEY2 7890
 * 3) define PERM 0666

mpi2.c:

typedef struct mymsgbuf {    int type; char msg[64]; } mtype; int main {    int msg1, msg2, i;     mtype m1, m2; m1.type = 10; strcpy(m1.msg, "Indians will win..."); /* attach to message queues. */    msg1 = msgget(KEY1, PERM); msg2 = msgget(KEY2, PERM); if (msg1 == -1 || msg2 == -1) perror("mpi2 msgget"); /* send message to mpi1. */    printf("mpi2 about to send message \"%s\" to message queue %d.\n", m1.msg, msg2); msgsnd(msg2, &m1, 64, 0); /* send message to mpi2. */    strcpy(m2.msg, "..."); /*    msgrcv(msg2, &m2, 64, 0, 0); */    i = msgrcv(msg1, &m2, 64, 0, 0); if (i == -1) perror("mpi2 msgrcv"); printf("mpi2 received msg: \"%s\" from message queue %d with return code %d.\n", m2.msg, msg1, i); /* cleanup. */    msgctl(msg1, IPC_RMID, (struct msqid_ds *) 0); msgctl(msg2, IPC_RMID, (struct msqid_ds *) 0); return 0; }
 * 1) define KEY1 9870
 * 2) define KEY2 7890
 * 3) define PERM 0666

Now compile mpi1.c into mpi1 and compile mpi2.c as mpi2: $ gcc -o mpi1 mpi1.c $ gcc -o mpi2 mpi2.c

Now run mpi1 in background and then run mpi2: $ ./mpi1 & [1] 29151 $ ./mpi2 mpi2 about to send message "Indians will win..." to message queue 2195457. mpi1 received msg: "Indians will win..." from message queue 2195457. mpi1 about to send "I doubt" to message queue 2162688. mpi1 sent "I doubt" to message queue 2162688 with return code 0. mpi2 received msg: "I doubt" from message queue 2162688 with return code 64. [1]+ Done                    ./mpi1

All about the stack
This section describes what happens in the stack and registers when one function calls another function and passes a few parameters.

Imagine we have this C code:

void foo(x, y, z) { int i, j; } int a, b, c; a = 4; b = 5; c = 6; foo(a, b, c);

Behind the scenes, first c gets pushed, then b, then a, then the return address of the calling function. This is what the stack looks like (the stuff at the top was the most recently pushed object):

-8   j  -4    i   0  ebp +4  return address +8   a +12    b +16    c

segfaults revealed!
We've all seen this lovely error: $ ./try Segmentation fault

Most of the time, you find out something like is the problem: char ss[3]; strcpy(ss, "this is a way too long string!\n");

After this command: char ss[3]; the stack can fit three characters into one 4-byte word.

-4         ; this is the space (4 bytes, 1 word) allocated for ss[3]. 0    ebp +4    r.a.

Now watch what happens when the strcpy command fills in the stack:

-4     't', 'h', 'i' ,'s'   ; we can fit the first 4 chars here, but the rest spill over. 0     ' ', 'i', 's', ' a'  ; ACK! we just overwrote the old base pointer! +4     ' ', 'w', 'a', 'y',  ; now we're doomed; when this function calls it will try to hop to                              ; the return address stored here, but that has been overwritten.

So hopefully it is more clear what a segfault is. Your program is trying to hop to a memory address outside the process memory, and the OS puts the smack down.

OSI reference
7 layers:

 * application
 * presentation
 * session
 * transport
 * network
 * data link
 * physical

In Unix, the first three (application, presentation, and session) are often bundled together.

Imagine that a network looks like this:

A---Router1---Router2---B.

If a process (application) on A wants to communicate with a process on B, this is sort of what happens:

The transport layer adds A's port and B's RPC server port.

The network layer adds A's IP address and B's IP address.

Any communication from A must go through the two routers first.

The data link layer adds A's mac address and router 1's mac address.

The physical layer converts the frame into the physical signal.

When the message is received by router 1, the frame is read in and sent to the bottom of the OSI model. Router 1's mac address is removed and replaced with Router 2's mac address.

Inodes
Each directory is actually a file. That file lists the names of files and subdirectories in that directory. It associates names to inodes.

Each inode has the following data:
 * userID
 * groupID
 * mode
 * timestamp (accessed, created, modified all tracked separately)
 * link count
 * file size
 * direct pointers to 10 data blocks that contain file contents
 * single indirect pointer to a data block that points to data blocks that contain the file contents
 * double indirect pointer to a data block ...

Addressing
Since each inode has 10 direct address pointers, if a file is small enough to fit on 10 data blocks or less, then the inode can use direct addressing.

If we assume that we use 4 bytes to specify the disk address, then we can have 232 different addresses. If we set the data block size to 4 kb, then one data block can hold 1000 addresses. So, with single indirect addressing, we can point to a file that uses 1000 data blocks of data.

Therefore, the maximum allowed file size for single indirect addressing (assuming 4kb data blocks and 4byte addresses) is 4 megabytes (1000 data blocks * 4 kb per data block).

Easy formula: data block size / disk address = max file size.

Of course, in double or triple (or quadruple, quintuple, etc.) addressing, you just gotta take the analysis out further.

There are advantages and disadvantages of small vs. large data blocks. Lots of small files and big data blocks causes low utilization. For example, your  file may only have 300 bytes of data, but it has to use at least one data block, so if your data block is 4kb in size, well, that's a lot of wasted space.

However, small blocks lead to big files being scattered out across lots of data blocks, and so the hard drive reader has to skip all over the place gathering up the data. Large data blocks reduce fragmentation.

As the number of blocks per file increases, disk IO cost increases.

Linking
Each directory has a table that maps file names to inode numbers. A file can have any number of names associated with it. Each inode keeps track of its link count. The command  edits the directory and removes the entry that maps foo.txt to a particular inode. If that inode has zero links, then it is deleted.

You might want to read the man page for ln at this point to understand the difference between soft and hard links.

RAID
Compared to a monolithic system, a distributed system can have a much lower chance that the system will fail today—even though the distributed system has a much higher chance that one part will fail today. High-availability distributed systems use techniques inspired by RAID (redundant array of inexpensive disks) to tolerate a failure in any one part, without loss of data or functionality.

For more details, see
 * minimizing hard disk drive failure and data loss
 * LPI Linux Certification/Configuring RAID

The set-user-ID bit
The set-user-ID bit (sometimes shortened to setuid or simply suid) alters how the OS handles permissions. For example, the  command allows a user to change her login shell, like from bash to tcsh. The login shell for each user is stored in /etc/passwd, but users don't have write access. So how can a user run chsh and change that file? The answer is with suid bits. Look at the permissions on chsh:

$ ls -l `which chsh` -rwsr-xr-x   1 root     root        28088 2004-11-02 16:51 /usr/bin/chsh

So, what is that s in there for? That, my friend, is the set-user-ID bit, which means that this program runs as if it were executed by root.

A program with the setuid bit set (or the similar setgid bit) will be run with the privileges of the program's owning user or group respectively.

Remote Procedure Calls
Remote procedure calls (RPC) are a way hiding all the details of running a process on a far away remote machine.

If A wants to make a remote procedure call on host B, then A needs B's RPC server port.

An RPC frame includes:
 * function number
 * parameters

The command  will list what RPC services are running on the machine.

Generally developing RPC program involves eight steps:

rpcgen -C rdb.x will generate 4 output files:
 * Build and test conventional application.
 * Divide the program by choosing a set of procedures to move to a remote machine. Place the selected procedures in a separate file.
 * Write a rpcgen specification file for the remote program. Choose a program number and version number. The specification file should be named with a .x suffix.  For example, a remote database program could have a spec file of
 * Run rpcgen command to check the specification file. If the file is valid, rpcgen will generate source code that will be used to build the client and server. Example:

gcc -o rdb rdb.c rdb_clnt.c rdb_xdr.c
 * Write stub interface routines for the client and server side. You can use the code developed in step 1. For example, you might write a   file that handles the client interface, and a   to handle the work on the server side.
 * Compile and link the client program.

gcc -o rdb_svc rdb_svc_proc.c rdb_svc.c rdb_xdr.c
 * Compile and link the server program.

 * Start server and invoke client.

Distributed Algorithms
Properties of distributed algorithms
 * Information can be scattered among machines.
 * Each process makes decisions based on local information.
 * Machines can share information.
 * A single point of failure should not cause the entire system to crash.
 * Machines can't rely on a single common clock or global time.

A simple example of how non-global clocks cause problems:
 * 1) you compile foo.c (via make) to foo.o on machine A.
 * 2) you log in to machine B, which has a clock that is 15 minutes behind B.
 * 3) You edit foo.c again, then run make.  make compares the timestamp on foo.o to foo.c and foo.o is still newer, so make will not recompile foo.o.

Synchronization
Physical clocks agree with "real time" like Universal Coordinated Time.

Logical clocks don't worry about being accurate to some global standard. Instead, all machines in a system try to agree with each other.

Keeping a local physical clock synchronized is challenging because even if the machine can contact the authoritative time server, there is some propagation delay.

How often does a machine need to request an update from a time server? Assume that the machine has a clock $$C$$ that increments at rate $$dC$$.

The UTC clock $$t$$ increments at rate $$dt$$.

If $$dC/dt = 1$$ then the local physical clock C is perfect and doesn't need to be updated.

If $$dC/dt > 1$$ then the local physical clock C runs at a faster rate.

If $$dC/dt < 1$$ then the local physical clock C runs at a slower rate then the time server.

$$\rho$$ represents the maximum drift rate specified by a manufacturer.

$$1 - \rho <= dC/dt <= 1 + \rho$$

$$\delta$$ represents the maximum tolerable error. every $$\delta/\rho$$ period, a machine must request an update.

As the error tolerance $$\delta$$ increases, update frequency falls. As drift rate $$\rho$$ goes up, the update frequency goes up also.

setjmp and longjump
Use these to do what C++, python, Java, etc. does with throwing exceptions. First call setjmp to set a location to jump to. Then other functions can call longjump to exit the current function and how to the location specified in setjmp.

functions with variable-length arguments
In other words, how does printf(...) work?

conditional compilation
One example: main {    #ifdef DEBUG printf("this is a debug statement!\n"); #endif }

$ gcc -DDEBUG prog.c; ./a.out this is a debug statement!

$gcc prog.c; ./a.out $

In the second compilation, the printf block ain't included.

Another similar trick is used to prevent the same header file from being included repeatedly. It is common for one C program to have multiple .c files which include multiple .h files. You can put this code at the top of your .h file to prevent the same .h file from being included redundantly:

/* function foo is a worn-out cliche. */ int foo;
 * 1) ifndef _FOO_H
 * 2) define _FOO_H 1
 * 1) endif

make and makefiles
Four type of statements are allowed in Makefiles: macros, dependency rules, commands, and comments. Here's a trivial example makefile:

CC = /usr/bin/gcc CFLAGS = -Wall -pedantic -g proxy: proxy.c proxy.h   $(CC) $(CFLAGS) proxy proxy.c debug-proxy: proxy.c proxy.h    $(CC) $(CFLAGS) -DDEBUG -o proxy proxy.c clean: /bin/rm -f *~ httpd a.out httpd.log proxy proxy.log CACHE.*
 * 1) saves me the trouble of typing all those flags.

I can run any statement by typing make and the name. Or by default, make will run the first rule it hits if it gets no arg.

$ make          # runs make proxy $ make clean    #runs /bin/rm -f ....

Macros are accessible after being declared by either $(CFLAGS) or ${CFLAGS}. $CFLAGS is not valid. If the macro is one letter, like

A = a.out

Then $A is valid. But you should stay away from that anyway, because lots of the single-char macros already have meaning.

Each tab underneath a dependency rule starts a new shell, so if you want to change shell stuff, you gotta do it all on one line:

bogus: echo $$PWD; cd ..; echo $$PWD; echo $$PWD;

The output:

$ make bogus echo $PWD; cd ..; echo $PWD /home/student/wiwilson/cis620 /home/student/wiwilson echo $pwd

BTW, if you want to suppress the default echoing of the commands, put an @ at the beginning:

bored: echo "meh" @echo "snah"

And here's the output:

$ make bored echo "meh" meh snah

How one make command can recursively call make in subdirectories:

SRCDIR = src1 src2 OBJ   = src1/f1.o src2/f2.o snake: ${SRCDIR} ${OBJ} ${CC} -o snake ${OBJ} ${SRCDIR}: /tmp cd $@; make

This confused me at first. The $@ symbol refers to the target for the rule, in this case, the ${SRCDIR}.

You can use makedepend inside a makefile to resolve all that hairy .h stuff automatically:

CFILES = main.c foo.c bar.c depend: makedepend $(CFILES)
 * 1) don't edit below here.

TODO: show example before and after Makefile.

If you have lots and lots of files and you want to compile them all into objects, this rule works:

.c.o:    $(CC) -c $<

Converting C to assembly
gcc -S try.c

This will convert your program to assembly code, using GNU syntax. gcc will create a file called try.s

gcc -S -masm=intel try.c

This will convert your code to assembly code using intel syntax. This may only work on intel CPUs.

You can convert try.s to an executable like so:

gcc try.s

And you can even compile the executable for use with gdb:

gcc -g try.s

And then you can step through the underlying assembly code in gdb. Hurray!

4.1.1 POSIX Threads
The task for this exercise was to rewrite the example code to use fork rather than threads. You should have something similar to this:

int main {    /*      * The name of our process. This lets us tell the difference when we     * do output. */    const char* name; /*     * Our counter variable. Because this is all in one function, it need not * be global. */    int i;     i = 0; pid_t pid = fork; if(pid == 0) {        name = "Child"; }    else {        name = "Parent"; }    /* Our output loop. */    int j;     for(j = 0; j < 10; j++) {        sleep(1); printf("%s process: %d\n", name, i); i++; }    return 0; }
 * 1) include <stdio.h>
 * 2) include <unistd.h>
 * 3) include <sys/types.h>

You were also asked in what way the output was different, and why. In the version that made use of POSIX Threads, the counter was incremented twice each second: once by each thread. When fork was used, it was only incremented once. The reason for this is that when fork is called, the child process writes to its own copy of the counter. When threads are used, however, both threads share their memory space. This means that they are both writing to the same copy of the counter, and it is incremented twice.

Contributors
Please, give yourself credit if you've made any contributions!

Matthew Wilson Started this textbook in Fall 2004, while enrolled in a graduate comparative operating systems interfaces course at Cleveland State University.

Lachlan Gunn

title: Distributed Systems


text:
What You Should Know About Medicines

Table of Contents

 * 1) /Introduction/
 * 2) /Why Medicines?/
 * 3) /How Medicines Work/
 * 4) /Administration Basics/
 * 5) Medications
 * 6) Anticoagulants
 * 7) Antipyretics
 * 8) /Antidepressants/
 * 9) Anticonvulsants
 * 10) Analgesics and Painkillers
 * 11) Anticholesterols
 * 12) Anxiolytics
 * 13) Antipsychotics
 * 14) Beta Blockers
 * 15) Calcium Channel Blockers
 * 16) Angiotensin Converting Enzyme Inhibitors (ACE Inhibitors)
 * 17) Angiotensin Receptor Blockers (ARB's)
 * 18) Diuretics
 * 19) Neuropathic
 * 20) Nonsteroidal anti-inflammatory drugs (NSAIDs)
 * 21) Opioids
 * 22) Diabetes Medications
 * 23) Stimulants
 * 24) Statins
 * 25) Z-Drugs
 * 26) Symptoms
 * 27) /Anorexia/
 * 28) Diaphoresis
 * 29) Anxiety
 * 30) Anxiolytic
 * 31) Aggression
 * 32) Constipation
 * 33) Coma
 * 34) /Delirium/
 * 35) Delusions
 * 36) /Dementia/
 * 37) /Depression/
 * 38) Dissociation
 * 39) Dysphoria
 * 40) /Epilepsy/
 * 41) /Nausea/
 * 42) Obtundation
 * 43) Vomiting
 * 44) /Euphoria/
 * 45) /Disinhibition/
 * 46) Impulsivity
 * 47) Hyperactivity
 * 48) /Inflammation/
 * 49) Psychosis
 * 50) Agitation
 * 51) Edema
 * 52) Sepsis
 * 53) Sedation
 * 54) Dizziness
 * 55) Malaise
 * 56) Weight Gain
 * 57) Xerostomia
 * 58) Headache
 * 59) Tic
 * 60) Tremor
 * 61) Somnolence
 * 62) Dispensing
 * 63) Tablets, pills, and capsules
 * 64) Liquids
 * 65) Sublingual
 * 66) Topical and transdermal
 * 67) Injection
 * 68) Inhalation
 * 69) Suppository
 * 70) Opthalmologic
 * 71) Implant
 * 72) Film
 * 73) Drug Interactions
 * 74) Side Effects
 * 75) Severe Allergic Reaction
 * 76) Paradoxical Reaction
 * 77) Poisoning
 * 78) Reye's Syndrome
 * 79) Tardive Dyskensia
 * 80) Neuroleptic Malignant Syndrome (NMS)
 * 81) Serotonin Syndrome
 * 82) Overdose
 * 83) Headache
 * 84) /Nausea/
 * 85) Mild Sedation
 * 86) Dependence
 * 87) /Tolerance/
 * 88) Addiction
 * 89) /Safe Disposal/
 * 90) Special populations
 * 91) /Children/
 * 92) /The Elderly/
 * 93) /Diabetics/
 * 94) /Kidney Problems/
 * 95) Appendices
 * 96) /Common Medications by Brand Name/
 * 97) /Common Medications by Use/
 * 98) /Glossary of Pharmacological Abbreviations/

title: What You Should Know About Medicines


text:
User:Dhuss~enwikibooks

Well I figured this is better than nothing... My current pet project is GNU/Linux For Newbies. Help out if you can please.

title: User:Dhuss~enwikibooks


text:
User:April Follies

I am an old user of/contributor to WikiPedia, and now WikiBooks. I had in the past tried to work on my own Wiki-based textbook, but a lack of time on my part, and too few contributors to carry it forward while I was absent, left it languishing. I'm hoping that the WikiBooks project can bring new vitality to it, and that, conversely, the material started there can add some helpful work to WikiBooks project.

title: User:April Follies


text:
User:Whosyourjudas~enwikibooks

Hi there! Please see my Wikipedia User Page for information about me.

title: User:Whosyourjudas~enwikibooks


text:
Applicable Mathematics/Systems of Equations

A good deal of real world problems can be represented by various equations. Often, we will have more than one equation for a given problem.

=Substitution= Substitution uses letters, such as x, y, or z, as representations of unknown values. These letters are used in both equations and expressions as tools to solve many different types of problems. In some cases, the value of the letter is known. If so, by using the substitution method, a numerical value replaces the letter given. Then, after the letter is replaced by a number, the expression or equation is simplified.

People & Feet
In a room of people we know there are twice as many feet as people, and we can represent this with the equation $$f = 2p$$, where $$f$$ represents the number of feet, and $$p$$ represents the number of people. Knowing there are 20 people, then we can make another equation $$p = 20$$. Listing out the two equations we have:

So we know there are 40 feet.

Houses & Floorspace
Other situations can get more complex though. Suppose that your neighbor's house is 1.5 times as large as yours, but if you don't count your neighbor's 50 square unit basement, they are the same size. How many square units are the respective houses? Let $$y$$ be the area of your entire floor, and $$n$$ the area of your neighbor's floor. The problem can represented by the two equations.

Here, you have two equations as before, but this time they both have two variables, while in the last example, one equation had one variable and the other had two. However, you can still use substitution though you just have to substitute with the equation's expression instead of a constant. Now we substitute $$n$$ in the second equation for the right-hand side of the first equation:

Now we can substitute the area of your floor into the first equation to get the area of your neighbours floor:

Systems of Linear Equations
Above we covered two real world examples (albeit simplified) that systems of equations are useful for solving. Equations composed of two or more linear functions are called Linear equations. Sets of these linear equations are called System of linear equations. Simply put, linear equations can only be solved if the number of Variables is equal to or less than the number of equations provided. The most common way of solving systems of equations is to use substitution, as shown above. However, we can represent the equations using matrices, allowing us to see patterns easier and perform operations more easily. Lets start with a set of 3 equations:

The matrix on the left represents the coefficients of the variables, and is called a coefficient matrix. On the right the right-hand side of the equation is included in the matrix, giving us what is called an augmented matrix.

Solving the above equation would look like the table on the left below normally, whereas the matrix solution would look like the table on the right.


text:
Beginning Mathematics/Logic and Deductive Reasoning

Logic has a long history, and is one of the central tenets of western thought. Going back to the ancient philosophers, logic has been the attempt to devise a system for ascertaining truth via thought. Logic falls under the category of deductive reasoning, meaning it is used to establish truth based upon already established truths, called postulates or axioms.

The oldest and most influential axiom system would be from Euclid's Elements, the classic geometry text, which ranks as one of the most important books of all time. Euclid starts off his first book with 23 definitions and 5 postulates. The postulates basically describe what can be done with an unmarked ruler and a compass. For instance, the first postulate says that a line can be drawn between two points. The second says that lines can be extended, and the third says that circles can be drawn with a center and a given radius.