| Errata for first printing of "An Introduction to Ray Tracing" |
|
An Introduction to Ray Tracing, edited by Andrew Glassner, Morgan Kaufmann, 1989. The first book on ray tracing. Ancient, but most of the information is still valid - math is math, data structures are data structures. Download the PDF (recommended) or DJVU version for free. Find other ray tracing books, free and otherwise, on our Ray Tracing Resources Page. Errata The errata that follows are errors reported since January 20, 2019, when the book was released as a free PDF and DJVU file. These errors are corrected in the free PDF version of the book (but not the DJVU): p. 138-141, sections 2.6 and 2.7, have been rewritten entirely, due to a cascading effect of small algebraic blunders near the start. These are in the PDF as pages 138-rev1 and 139-rev1. (superceded by the fix above, but one error in the original text that is fixed in the PDF) p. 139, in the third line of equation (7c), the "T" should be "N" (since going from the second to third line is substituting in the relationship T = \alpha I + \beta N from eq (6b). (thanks to Matt Pharr) p. 327, "Path racing" should be "Path tracing". (thanks to Matt Pharr) The remaining errata below is originally from The Wayback Machine. All of these errors are corrected in the PDF and DJVU versions. This errata listing is here for people who have the first printing of the book. p. 86, last paragraph before Algebraic Surfaces header: change "where all the the intersections of the ray with all the objects in the CSG tree are required" to end as "may be required". ----- p. 88, equation "t = etc": change from "t = etc" to "t = -etc", i.e. a minus sign is missing, so negate the right hand side of the equation. ----- p. 91, last formula in the Sphere section (in the text): change to x1^2 + y1^2 + z1^2 = 1 ^ subscript was "0" ----- p. 91, in the Paraboloid section, second equation: change the two minus signs to plus signs (i.e. before z1 and z0). ----- p. 93, torus equation corrections: change two equations a2 = 2(x1^2+y1^2+z1^2)((x0^2+y0^2+z0^2)-(a^2+b^2)) + 4 * (x0x1+y0y1+z0z1)^2 + 4a^2z1^2 ^ ^^ ^ was "2" add was "-" a1 = 4 * (x0x1+y0y1+z0z1)((x0^2+y0^2+z0^2)-(a^2+b^2)) + 8a^2 * z0 * z1 ^ was "-" a0 = ((x0^2+y0^2+z0^2)-(a^2+b^2))^2 - 4a^2(b^2-z0^2) ^ squaring was left off ----- p. 95, last sentence before the Simplicial Splines and Steiner Patches section: change "of" to "or, i.e. it should read "numerical techniques or subdivision algorithms". ----- p. 95, last formula on the page: change to z(u,v) = h y(v) ^ subscript was "x" ----- p. 100, Figure 7 is wrong. The upper figure is in error; the lower part is correct. In the upper figure, the outer contour is the silhouette of a 3D parametric surface. Curve c1 is the intersection of one plane with that surface, and c2 is the intersection of another plane, perpendicular to the first. The line of intersection of the two planes is collinear with the ray, indicated by the line with the arrow. The other three lines in the figure are extraneous and should be ignored. The lower part of the figure shows the two curves in uv space. ----- p. 101, the last sentence in the Bicubic Patches section: change "this can involve a loss of extra computation" should be "this can involve extra computation". ----- p. 101, the second equation in the Numerical Methods section: change the second "=" in the line to a "+" (it's the only equation with two "=" in it). ----- p. 105, the 2-D line equation: change to (y1)x - (x1)y - (x0y1 - y0x1) = 0 ^ was a "+" ----- p. 108, formula for f: This does not agree with Fig. 10. Using the same notation as in the figure, change to: For this shape, f is 2 2 2 2 (x-r (u)) + (y-r (u)) + (z - r (u)) - a (u) = 0 x y z where (r , r , r ) is the center of the sphere and a is the radius. x y z ----- p. 140, equation (7h): missing right parenthesis, change to "...- 1)))N." ----- p. 148, section on distribution term D, 8th line: change "the angle between L and H" to "the angle between N and H". ----- p. 156, section 5.4, 2nd paragraph: change "spectral transmission curve" to "specular transmission curve". ----- p. 158, in Fdt(lambda) definition: change "diffuse reflection" to "diffuse transmission". ----- p. 158, line immediately after Fdt(lambda) definition: change "We note that the diffuse reflectance" to "We note that the diffuse transmittance". ----- p. 238, Fig. 24: A chunk is missing in the upper left corner. The labels should read: "Directions crossed with", and "Applies to". ----- p. 260, reference by Gervautz: change "Comput. Graph." to "Computers and Graphics". ----- p. 288, immediately after the DERIVATION OF REFRACTION FORMULAS header: The introductory paragraph is missing. It reads: We derive three alternative formulas for the refracted ray direction in ray tracing in order to prove their equivalence and to demonstrate the process of translating physical laws into optimized computational formulas. It is common knowledge that light rays refract when they strike an interface between two different transparent media, such as air-water, air-glass, or glass-water. In 1621 Dutch mathematician Willebrord Snell discovered a formula quantifying this observation: the ratio of the sines of the incident and refracted angles equals the ratio of the indices of refraction of the two materials. Snell's law is: eta sin( theta ) = eta sin( theta ) 1 1 2 2 where theta-sub-1 is the angle of incidence, theta-sub-2 is the angle of refraction (both measured from the perpendicular to the interface) and eta-sub-1 and eta-sub-2 are the two indices of refraction on the incident and refracted sides of the interface, respectively. Light passing through a material slows relative to its speed in a vacuum by a factor equal to the index of refraction of that material. In fact, Snell's law is a simple consequence of this speed variation and Fermat's _Principle of Least Time_, which states that light takes the fastest path to get from one point to another [Feynman63]. For computation we need to recast Snell's law in terms of (x,y,z) direction vectors. This can be done in several different ways. In the derivations below we make extensive use of angles and trigonometry, but thankfully, it is possible to eliminate all of these terms from the final formulas, so theta-sub-1 and theta-sub-2 need never be computed. As a convention, vectors are upper case and scalars are lower case. ----- END |


What is new in Ring 1.12?¶
In this chapter we will learn about the changes and new features in Ring 1.12 release.
List of changes and new features¶
Ring 1.12 comes with the next features!
- Go Game
- ASCII Table application
- BMI Calculator application
- Calendar application
- Julian Day Calendar application
- Tutorial: Number to Words
- Load Again Command
- ring_state_filetokens() function
- Embedded Ring Object File
- Better RingRayLib
- More Improvements
Go Game¶
An implementation for the Go Game
ASCII Table application¶
Simple application for displaying the ASCII table
BMI Calculator application¶
Simple application for calculating the BMI
Calendar application¶
The Calendar for Year 2020
Julian Day Calendar application¶
The Julian Day Calendar application
Tutorial: Number to Words¶
Folder : ring/samples/other/number2words
Load Again Command¶
Ring 1.12 comes with the Load Again command
Using this command we can load the Ring source file which contains constants more than one time.
This is useful when using Ring source files for translations through global constants.
Example:
The next function is part from a project which support Arabic and English languages
The files english.ring and arabic.ring contains constants for translation
One of these files is loaded in the start of the program
Loading the same file again using the (Load) command is not possible
Because the (Load) command load the same source file only for the first time and ignore next times.
So we have to use the (Load Again) command.
Where we can use these files again during the runtime as in the next code
func setLang nLanguage
if C_ENV_DEFAULT_LANG = nLanguage
return
ok
C_ENV_DEFAULT_LANG = nLanguage
# Change the language
switch nLanguage
on C_TRANSLATION_ENGLISH
load again "translation/english.ring"
on C_TRANSLATION_ARABIC
load again "translation/arabic.ring"
off
ring_state_filetokens() function¶
Using the ring_state_filetokens() function we can get all the tokens in the ring source code file.
C_FILENAME = "test_tokens.ring"
C_WIDTH = 12
# write the file
write(C_FILENAME,'
see "Hello, World!"
? 3*2+3
Name = "Ring"
? Name
')
# Token Type
C_KEYWORD = 0
C_OPERATOR = 1
C_LITERAL = 2
C_NUMBER = 3
C_IDENTIFIER = 4
C_ENDLINE = 5
# Keywords List
aKEYWORDS = ["IF","TO","OR","AND","NOT","FOR","NEW","FUNC",
"FROM","NEXT","LOAD","ELSE","SEE","WHILE","OK","CLASS","RETURN","BUT",
"END","GIVE","BYE","EXIT","TRY","CATCH","DONE","SWITCH","ON","OTHER","OFF",
"IN","LOOP","PACKAGE","IMPORT","PRIVATE","STEP","DO","AGAIN","CALL","ELSEIF",
"PUT","GET","CASE","DEF","ENDFUNC","ENDCLASS","ENDPACKAGE",
"CHANGERINGKEYWORD","CHANGERINGOPERATOR","LOADSYNTAX"]
pState = ring_state_new()
aList = ring_state_filetokens(pState,C_FILENAME)
PrintTokens(aList)
ring_state_delete(pState)
func PrintTokens aList
for aToken in aList
switch aToken[1]
on C_KEYWORD
? Width("Keyword",C_WIDTH) + ": " + aKeywords[0+aToken[2]]
on C_OPERATOR
? Width("Operator",C_WIDTH) + ": " + aToken[2]
on C_LITERAL
? Width("Literal",C_WIDTH) + ": " + aToken[2]
on C_NUMBER
? Width("Number",C_WIDTH) + ": " + aToken[2]
on C_IDENTIFIER
? Width("Identifier",C_WIDTH) + ": " + aToken[2]
on C_ENDLINE
? "EndLine"
off
next
func Width cText,nWidth
return cText+copy(" ",nWidth-len(cText))
Output:
EndLine
Keyword : SEE
Literal : Hello, World!
EndLine
Operator : ?
Number : 3
Operator : *
Number : 2
Operator : +
Number : 3
EndLine
Identifier : name
Operator : =
Literal : Ring
EndLine
Operator : ?
Identifier : name
EndLine
Generate Embedded Ring Object File¶
We can generate embedded object file (C source code) from the source code file (*.ring) using -geo option
Command:
ring test.ring -geo
This command will generate at least three files
test.c
ringappcode.c
ringappcode.h
More files could be generated based on the project size
The generated files will pass the byte code to Ring VM to be executed
Better RingRayLib¶
More Samples are added to RingRayLib
- Sound Loading Playing
- Texture Source
- Music Playing Streaming
- Rectangle scaling
- Colors Palette
- Following Eyes
- Collision Area
- Bezier Lines
- Images Generation
- Fiften Puzzle Game
- Cubic Map
Screen Shot:
More Improvements¶
- New Samples
- ring/samples/other/Hex2UTF8.ring
- ring/samples/other/CalmoSoftPrimesTable.ring
- ring/samples/other/CalmoSoftTicTacToeGame.ring
- ring/samples/other/CalmoSoftSimpleGoGame.ring
- ring/samples/other/arabicmysql.ring
- ring/samples/other/CalmoSoftExtraCube.ring
- ring/samples/other/DynamicCode/anonfunc.ring
- ring/samples/other/DynamicCode/deletethisfile.ring
- ring/samples/other/DynamicCode/modifythisfile.ring
- ring/samples/other/changesyntax/ArabicDemo.ring
- ring/samples/other/changesyntax/EnglishDemo.ring
- ring/samples/other/changesyntax/ChangeKeywordsArabic.ring
- ring/samples/other/changesyntax/ChangeKeywordsEnglish.ring
- ring/samples/other/changesyntax/pascal.ring
- ring/samples/other/hijridate.ring
- Ring Notepad - Project Files - set minimum width based on desktop screen width
- Ring Notepad - Output Window - Move the Cursor to the end of text
- Ring Notepad - Output Window - Correct displaying for line breaks
- Form Designer - Better Style - Controls colors and size
- VideoMusicPlayer is updated to work as expected after RingQt update
- FlappyBird3000 - Fast response on Android
- Snake Game : Change the default window size (800x600)
- Maze Game : Change the default window size (800x600)
- Maze Game : Move the camera with the player
- Maze Game : Restarting the game will hide the (You Win) message
- Game Engine : display error message when we can’t create the game window
- Ring Tests : Added File build.sh for building on Linux and macOS
- RingQt : Updated to Qt 5.12.6
- RingQt : Added QQMLEngine class
- RingQt : Added files for building RingQt without Bluetooth support
- RingQt : The size of the events code is changed from 100 characters to 200 characters
- RingQt : Correct links for Qt documentation in RingQt classes chapter
- RingQt for Android : Better code for executing the ring object file (ringo)
- Ring2EXE configuration files are updated for RingQt to correctly distribute RingQt apps
- Code Generator : Convert function names to lower case when generating the functions for structures
- OSCopyFolder() function is updated to copy the files in sub folders too
- fgetpos() function is updated to work as expected
- IsFunction() function is updated to be not case sensitive
- Space() function is updated to clear the output string with spaces
- Ring Compiler : Added file buildclang.bat for building on Windows using Clang compiler
- Ring VM - Internal hash function is updated
- Ring VM - Better Code for setting pVM->aSetProperty when creating new objects
- Ring VM - Better Code for state managment


Technical Architecture
The "Platform Comms Gateway" in figure above represents the External Component that Openfire will forward all incoming messages to for processing. The implementation of this feature is deployed as the XC Manager bundle. This bundle is dependent on a configuration file called "xc.properties" that needs to be in the ${VIRGO_HOME}/pickup directory
#Configuration for the the XMPP Server. XCManager reads following config
host=societies.local
# Make sure xcmanager (or XCManager) is spelled the same way as in your
# Openfire configuration. It is case sensitive!
subDomain=xcmanager.societies.local
secretKey=password.societies.local
Having every single Service Bundle registering with the XC Manager does not scale. It is preferable that a Group Manager registers and manages access to each of the end-point services. In the example depicted in Figure 27, the "Examples Comms Manager" component will implement the remote interfaces that allow services to communicate remotely. Also, it will receive requests from remote services which it then will route to the relevant local services.


Sorry, your browser does not support JavaScript!
A browser without support for JavaScript will show the text inside the <noscript> element.


string pg_fetch_result ( resource $result , int $row , mixed $field )
string pg_fetch_result ( resource $result , mixed $field )
pg_fetch_result() returns the value of a particular row and field (column) in a PostgreSQL result resource. Note: This function used to be called pg_result().
Boolean is returned as "t" or "f". All other types, including arrays are returned as strings formatted in the same default PostgreSQL manner that you would see in the psql program. Database NULL values are returned as NULL. FALSE is returned if row exceeds the number of rows in the set, or on any other error.


PREFONTAINE A film review by James Berardinelli Copyright 1997 James Berardinelli
RATING (0 TO 10): 6.5 Alternative Scale: **1/2 out of ****
United States, 1997 U.S. Release Date: 1/24/97 (wide) Running Length: 1:46 MPAA Classification: PG-13 (Profanity, mature themes) Theatrical Aspect Ratio: 1.85:1
Cast: Jared Leto, R. Lee Ermey, Ed O'Neill, Lindsay Crouse, Amy Locane, Peter Anthony Jacobs, Henri Lubatti, Laurel Holloman Director: Steve James Producers: Jon Lutz, Irby Smith, Mark Doonan, Peter Gilbert Screenplay: Steve James and Eugene Corr Cinematography: Peter Gilbert Music: Mason Daring U.S. Distributor: Hollywood Pictures
Steve James and Peter Gilbert, the men behind 1995's unexpected sensation, HOOP DREAMS, must have a fondness for the documentary format, since they have attempted to apply it to their first narrative feature. PREFONTAINE, based on the life of the '70s track phenom who captivated the United States' imagination, is presented as half-story, half faux documentary, with actors who have been unconvincingly aged by bad makeup jobs looking back two decades and reminiscing about the title character.
I suppose that James and Gilbert intended to be somewhat unconventional with this approach (maybe to differentiate their film from PRE, another Prefontaine bio-pic due to arrive in theaters during the Fall), but it isn't wholly successful. For the most part, the documentary segments, in addition to being unilluminating, are intrusive. Every time we're getting into the story, it seems that there's a cut away to someone in the "present" who has a point to make about their friend/son/boyfriend/student. Fortunately, this distracting technique largely disappears during the film's second half.
During the early '70s, Steve Prefontaine was the James Dean of track. The University of Oregon student set nearly every NCAA distance record before competing in the 1972 Munich Olympics, where he failed to win a medal. Following his spectacular downfall on the world's stage, Prefontaine (or "Pre" as he was commonly called) never recaptured the public's imagination the way he had in his halcyon pre-Olympic days. He was gearing up for an appearance in the 1976 Montreal games when, at the age of 24, he died in an alcohol-related single car accident that further accentuated his similarities to Dean.
Prefontaine's sole goal in life was to win, and his arrogant self- confidence rubbed both friends and enemies the wrong way. Losing gracefully was anathema. He ran every race to win, but, when it came to the biggest race of his life, he didn't quite have enough. Not only did Prefontaine miss the gold, but he fell to fourth place and didn't even earn the bronze. The obsessive drive and determination of the young athlete are characteristics that James' film effectively captures. There are areas of Prefontaine's personality that are left half-explored (such as his family relationships), but the competitive spirit bubbles to the surface.
Jared Leto does such an excellent job of imitating Prefontaine that the film makers are able to seamlessly intercut archival footage of the real figure with that of Leto and not destroy the illusion. In fact, Leto looks so much like Pre that contemporaries of the track star have commented about how eerie it is watching the film. Other than Leto, who is PREFONTAINE's central focus, everyone in the cast has a supporting role. R. Lee Ermey plays Bill Bowerman, Pre's tough-talking coach. Ed O'Neill is Bowerman's assistant, Bill Dellinger. Linsay Crouse is Pre's mother, Peter Anthony Jacobs is his father, and Amy Locane and Laurel Holloman are his two girlfriends.
When James stays in the '70s, he fashions an involving, occasionally gripping, motion picture. The sequences at the Munich Olympics, which feature footage of Jim McKay reporting on the tragic death of 11 Israeli athletes at the hands of Arab terrorists, are extremely well-constructed. The blend of new material and genuine video creates a disturbing "you are there" sensation. Nothing else in PREFONTAINE works quite as well as this.
Because it mostly follows classic true-to-life sports movie formulas, Prefontaine's story is undeniably cinematic, although it's essentially missing a final act. That's not because the main character dies, but because he loses the big race without ever getting a chance to make recompense. James tries too hard to bring closure to Pre's life, and, as a result, strays a little too far into melodrama. The tearful reminiscences at the end, not to mention some of the stuff at the funeral, lay it on thickly.
It will be interesting to see how the bigger budgeted PRE develops the same story, although it probably won't look anything like a documentary. PREFONTAINE loses some of its dramatic energy by opting for that approach. Still, structural problems aside, the film effectively conveys a great deal of information about the track legend without ever adopting a didactic tone. We feel things along with Pre, and, by the time the final credits roll, we have developed an appreciation for what the sports world lost on that night in 1975 when track's most colorful athlete crossed his last finish line.
- James Berardinelli e-mail<EMAIL_ADDRESS>ReelViews web site: http://www.cybernex.net/~berardin
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


This course is a foundation to anyone who aspires to become a DevOps Engineer, a Service Engineer in the field of Enterprise Infrastructures. The following professionals are the key beneficiaries of this course :
- DevOps Engineer
- Build and Release Engineer,
- AppOps Engineer,
- Site Reliability Engineer
- System Administrator
- Operations Engineer
- Automation Engineer


PostIt
Welcome Blessing
Account Setting
Logout
View all Groups
Add Group
Add Users
View Messages
Post Message
All Groups
My Family
6 users in the Group
Add New User
BootCamp Cycle 23 Friends
24 users in the Group
Add New User
Close Friends
4 users in the Group
Add New User


- available_locales
- deep_symbolize_keys
- default
- init_translations
- initialized?
- interpolate
- interpolate_with_deprecated_syntax
- load_file
- load_rb
- load_translations
- load_yml
- localize
- lookup
- merge_translations
- pluralize
- reload!
- store_translations
- translate
- translations
| DEPRECATED_INTERPOLATORS | = | { '%d' => '{{count}}', '%s' => '{{value}}' } |
| INTERPOLATION_RESERVED_KEYS | = | %w(scope default) |
| MATCH | = | /(\\\\)?\{\{([^\}]+)\}\}/ |
Returns an array of locales for which translations are available
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 73 73: def available_locales 74: init_translations unless initialized? 75: translations.keys 76: end
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 68 68: def initialized? 69: @initialized ||= false 70: end
Accepts a list of paths to translation files. Loads translations from plain Ruby (*.rb) or YAML files (*.yml). See load_rb and load_yml for details.
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 12 12: def load_translations(*filenames) 13: filenames.each { |filename| load_file(filename) } 14: end
Acts the same as strftime, but returns a localized version of the formatted date string. Takes a key from the date/time formats translations as a format argument (e.g., :short in :’date.formats‘).
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 48 48: def localize(locale, object, format = :default) 49: raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime) 50: 51: type = object.respond_to?(:sec) ? 'time' : 'date' 52: # TODO only translate these if format is a String? 53: formats = translate(locale, "#{type}.formats""#{type}.formats") 54: format = formats[format.to_sym] if formats && formats[format.to_sym] 55: # TODO raise exception unless format found? 56: format = format.to_s.dup 57: 58: # TODO only translate these if the format string is actually present 59: # TODO check which format strings are present, then bulk translate then, then replace them 60: format.gsub!(/%a/, translate(locale, "date.abbr_day_names""date.abbr_day_names")[object.wday]) 61: format.gsub!(/%A/, translate(locale, "date.day_names""date.day_names")[object.wday]) 62: format.gsub!(/%b/, translate(locale, "date.abbr_month_names""date.abbr_month_names")[object.mon]) 63: format.gsub!(/%B/, translate(locale, "date.month_names""date.month_names")[object.mon]) 64: format.gsub!(/%p/, translate(locale, "time.#{object.hour < 12 ? :am : :pm}""time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour 65: object.strftime(format) 66: end
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 78 78: def reload! 79: @initialized = false 80: @translations = nil 81: end
Stores translations for the given locale in memory. This uses a deep merge for the translations hash, so existing translations will be overwritten by new ones only at the deepest level of the hash.
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 20 20: def store_translations(locale, data) 21: merge_translations(locale, data) 22: end
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 24 24: def translate(locale, key, options = {}) 25: raise InvalidLocale.new(locale) if locale.nil? 26: return key.map { |k| translate(locale, k, options) } if key.is_a? Array 27: 28: reserved = :scope, :default 29: count, scope, default = options.values_at(:count, *reserved) 30: options.delete(:default) 31: values = options.reject { |name, value| reserved.include?(name) } 32: 33: entry = lookup(locale, key, scope) 34: if entry.nil? 35: entry = default(locale, default, options) 36: if entry.nil? 37: raise(I18n::MissingTranslationData.new(locale, key, options)) 38: end 39: end 40: entry = pluralize(locale, entry, count) 41: entry = interpolate(locale, entry, values) 42: entry 43: end
Return a new hash with all keys and nested keys converted to symbols.
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 205 205: def deep_symbolize_keys(hash) 206: hash.inject({}) { |result, (key, value)| 207: value = deep_symbolize_keys(value) if value.is_a? Hash 208: result[(key.to_sym rescue key) || key] = value 209: result 210: } 211: end
Evaluates a default translation. If the given default is a String it is used literally. If it is a Symbol it will be translated with the given options. If it is an Array the first translation yielded will be returned.
I.e., default(locale, [:foo, ‘default’]) will return default if translate(locale, :foo) does not yield a result.
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 118 118: def default(locale, default, options = {}) 119: case default 120: when String then default 121: when Symbol then translate locale, default, options 122: when Array then default.each do |obj| 123: result = default(locale, obj, options.dup) and return result 124: end and nil 125: end 126: rescue MissingTranslationData 127: nil 128: end
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 84 84: def init_translations 85: load_translations(*I18n.load_path.flatten) 86: @initialized = true 87: end
Interpolates values into a given string.
interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X' # => "file test.txt opened by {{user}}"
Note that you have to double escape the \ when you want to escape the {{…}} key in a string (once for the string and once for the interpolation).
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 151 151: def interpolate(locale, string, values = {}) 152: return string unless string.is_a?(String) 153: 154: string.gsub(MATCH) do 155: escaped, pattern, key = $1, $2, $2.to_sym 156: 157: if escaped 158: pattern 159: elsif INTERPOLATION_RESERVED_KEYS.include?(pattern) 160: raise ReservedInterpolationKey.new(pattern, string) 161: elsif !values.include?(key) 162: raise MissingInterpolationArgument.new(pattern, string) 163: else 164: values[key].to_s 165: end 166: end 167: end
[ show source ]
# File vendor/rails/activerecord/lib/active_record/i18n_interpolation_deprecation.rb, line 12 12: def interpolate_with_deprecated_syntax(locale, string, values = {}) 13: return string unless string.is_a?(String) 14: 15: string = string.gsub(/%d|%s/) do |s| 16: instead = DEPRECATED_INTERPOLATORS[s] 17: ActiveSupport::Deprecation.warn "using #{s} in messages is deprecated; use #{instead} instead." 18: instead 19: end 20: 21: interpolate_without_deprecated_syntax(locale, string, values) 22: end
Loads a single translations file by delegating to load_rb or load_yml depending on the file extension and directly merges the data to the existing translations. Raises I18n::UnknownFileType for all other file extensions.
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 173 173: def load_file(filename) 174: type = File.extname(filename).tr('.', '').downcase 175: raise UnknownFileType.new(type, filename) unless respond_to?("load_#{type}""load_#{type}") 176: data = send "load_#{type}""load_#{type}", filename # TODO raise a meaningful exception if this does not yield a Hash 177: data.each { |locale, d| merge_translations(locale, d) } 178: end
Loads a plain Ruby translations file. eval‘ing the file must yield a Hash containing translation data with locales as toplevel keys.
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 182 182: def load_rb(filename) 183: eval(IO.read(filename), binding, filename) 184: end
Loads a YAML translations file. The data must have locales as toplevel keys.
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 188 188: def load_yml(filename) 189: YAML::load(IO.read(filename)) 190: end
Looks up a translation from the translations hash. Returns nil if eiher key is nil, or locale, scope or key do not exist as a key in the nested translations hash. Splits keys or scopes containing dots into multiple keys, i.e. currency.format is regarded the same as %w(currency format).
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 98 98: def lookup(locale, key, scope = []) 99: return unless key 100: init_translations unless initialized? 101: keys = I18n.send(:normalize_translation_keys, locale, key, scope) 102: keys.inject(translations) do |result, k| 103: if (x = result[k.to_sym]).nil? 104: return nil 105: else 106: x 107: end 108: end 109: end
Deep merges the given translations hash with the existing translations for the given locale
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 194 194: def merge_translations(locale, data) 195: locale = locale.to_sym 196: translations[locale] ||= {} 197: data = deep_symbolize_keys(data) 198: 199: # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809 200: merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } 201: translations[locale].merge!(data, &merger) 202: end
Picks a translation from an array according to English pluralization rules. It will pick the first translation if count is not equal to 1 and the second translation if it is equal to 1. Other backends can implement more flexible or complex pluralization rules.
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 134 134: def pluralize(locale, entry, count) 135: return entry unless entry.is_a?(Hash) and count 136: # raise InvalidPluralizationData.new(entry, count) unless entry.is_a?(Hash) 137: key = :zero if count == 0 && entry.has_key?(:zero) 138: key ||= count == 1 ? :one : :other 139: raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key) 140: entry[key] 141: end
[ show source ]
# File vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb, line 89 89: def translations 90: @translations ||= {} 91: end


--- layout: post title: Value Types Initialisation date: 2009-11-20 21:49:17.000000000 +01:00 categories: [] tags: [] status: publish type: post published: true meta: {} author: login: admin email<EMAIL_ADDRESS>display_name: Philippe first_name: Philippe last_name: Vlérick excerpt: !ruby/object:Hpricot::Doc options: {} ---
Value Types are a bit special. I won’t go down to the basics, but the differ from Reference Types by holding directly a value instead of a reference.
There are two interesting cases that I’m going to elaborate on. They pretty much make sense, but a little explanation cannot hurt.
Here is a very simple struct that I will use to demonstrate my point:
struct DaysAndHours { public int Days { get; private set; } public int Hours { get; private set; } public override string ToString() { return String.Format("{0} day(s) and {1} hour(s)", Days, Hours); } }
Notes:
Now, let’s say that I declare a variable of this type, and never assign it. The normal rules of the compiler will apply:
However, if you run the debugger, you can see the variable’s content. If it was a Reference Type, it would be null, but in this case, you can see all that the content is there, with all the fields being at their default value:
The trick is that, when declaring the variable dh, the instance is allocated on the stack. However, the C# compiler don’t let you do that and wants to make sure you called the new keyword for that value type.
In my struct, I lazily used automatically implemented properties that were introduced in C# 3. This leads to a compiler error when using a custom constructor like this one:
public DaysAndHours(int days, int hours) { Days = days; Hours = hours; }
The compiler will report the following error:
Backing field for automatically implemented property 'DaysAndHours.Days' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.
This makes a lot of sense, as the backing fields for these properties have not been initialized. However, we cannot access the backing field, so we cannot initialize the field. Hopefully, the default parameter less constructor will do that, so calling it is sufficient to make sure the backing fields are initialized:
public DaysAndHours(int days, int hours) : this() { Days = days; Hours = hours; }
Always remember that you cannot prevent a struct to be constructed using the default constructor, that has the same visibility as the struct itself. If you are using automatic properties, you have to explicitly call the default constructor in order to initialise the backing fields as you can’t access them directly.


Met office issues urgent warning over freezing fog as temperatures plummet
by LBCThe Met Office has issued a new yellow weather warning across a large swathe of the UK as freezing fog moves in.
Forecasters have warned freezing fog is set to blanket Britain on Tuesday with the potential for transport chaos on the roads.
The Met Office has issued a yellow weather warning for freezing fog from 4am to 11am as temperatures in parts of the UK were predicted to fall as low as -9.
With predictions, visibility could drop as low as just 100m in places on Tuesday morning commuters are being advised to check their journeys before they travel.
Police have warned those driving on the road network to ensure they defrost their cars and take extra care on the roads.
Met Office experts have warned fog spreading across London, Bath and Birmingham, will cause disruption to travel services.
"Some dense fog and freezing fog patches on Tuesday morning likely leading to some travel disruption," the Met Office spokesman said.
People are being told to expect "slower journey times with delays to bus and train services possible."
Meanwhile "there is a chance of delays or cancellations to flights."
The worst-affected areas include most of the Midlands, Home Counties and southeast of England. Temperatures in these regions will struggle to exceed 5C on Tuesday.
Public Health England issued a cold weather warning from 9 am on Monday until 12 pm on Wednesday.
Dr Emer OConnell, a consultant at PHE, advised people to look out for anyone who may need help staying warm.
She said: "Older people and those with heart and lung problems are at risk of getting sick in cold weather. Keep an eye out for those who may need help staying warm. Ensure they wear lots of thin layers and have everything they need."