I still have some older posts using Alex Gorbachev's Syntaxhighlighter. Unfortunately his project is unmaintained so I forked and fixed the build process and I'm now making the results available on this page.
Use the theme selector at the top right of this page to preview themes and download the required js and css files. To apply client-side syntax highlighting on your site, please follow the usage instructions from the original wiki pages.
applescript
-- Dialog set dialogReply to display dialog "Dialog Text" ¬ default answer "Text Answer" ¬ hidden answer false ¬ buttons {"Skip", "Okay", "Cancel"} ¬ default button "Okay" ¬ cancel button "Skip" ¬ with title "Dialog Window Title" ¬ with icon note ¬ giving up after 15 display alert "Hello, world!" buttons {"Rudely decline", "Happily accept"} set theAnswer to button returned of the result if theAnswer is "Happily accept" then beep 5 else say "Piffle!" end if
as3
/* Copyright (c) 2009, Adobe Systems Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.adobe.air.crypto { import com.adobe.crypto.SHA256; import flash.data.EncryptedLocalStore; import flash.utils.ByteArray; /** * The EncryptionKeyGenerator class generates an encryption key value, such as you would use * to encrypt files or data. For example, the encryption key is suitable to use as * an encryption key for an encrypted AIR local SQL (SQLite) database. * * <p>This class uses techniques and algorithms that are designed for maximum * data privacy and security. Use this class to generate an encryption key if your * application requires data to be encrypted on a per-user level (in other words, * if only one user of the application should be able to access his or her data). * In some situations you may also want to use per-user encryption for data even * if the application design specifies that other users can access the data. For more * information, see * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS34990ABF-C893-47ec-B813-9C9D9587A398.html">Considerations for using encryption with a database</a>" * in the guide * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p> * * <p>The generated encryption key is based on a password that you provide. For any given * password, in the same AIR application * running in the same user account on the same machine, the encryption key result is * the same.</p> * * <p>To generate an encryption key from a password, use the <code>getEncryptionKey()</code> * method. To confirm that a password is a "strong" password before calling the * <code>getEncryptionKey()</code> method, use the <code>validateStrongPassword()</code> * method.</p> * * <p>In addition, the EncryptionKeyGenerator includes a utility constant, * <code>ENCRYPTED_DB_PASSWORD_ERROR_ID</code>. This constant matches the error ID of * the SQLError error that occurs when code that is attempting to open an encrypted database * provides the wrong encryption key.</p> * * <p>This class is designed to create an encryption key suitable for providing the highest * level of data privacy and security. In order to achieve that level of security, a few * security principles must be followed:</p> * * <ul> * <li>Your application should never store the user-entered password</li> * <li>Your application should never store the encryption key returned by the * <code>getEncryptionKey()</code> method.</li> * <li>Instead, each time the user runs the application and attempts to access the database, * your application code should call the <code>getEncryptionKey()</code> method to * regenerate the encryption key.</li> * </ul> * * <p>For more information about data security, and an explanation of the security techniques * used in the EncryptionKeyGenerator class, see * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS61068DCE-9499-4d40-82B8-B71CC35D832C.html">Example: Generating and using an encryption key</a>" * in the guide * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p> */ public class EncryptionKeyGenerator { // ------- Constants ------- /** * This constant matches the error ID (3138) of the SQLError error that occurs when * code that is attempting to open an encrypted database provides the wrong * encryption key. */ public static const ENCRYPTED_DB_PASSWORD_ERROR_ID:uint = 3138; private static const STRONG_PASSWORD_PATTERN:RegExp = /(?=^.{8,32}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/; private static const SALT_ELS_KEY:String = "com.adobe.air.crypto::EncryptedDBSalt$$$"; // ------- Constructor ------- /** * Creates a new EncryptionKeyGenerator instance. */ public function EncryptionKeyGenerator() {} // ------- Public methods ------- /** * Checks a password and returns a value indicating whether the password is a "strong" * password. The criteria for a strong password are: * * <ul> * <li>Minimum 8 characters</li> * <li>Maxmium 32 characters</li> * <li>Contains at least one lowercase letter</li> * <li>Contains at least one uppercase letter</li> * <li>Contains at least one number or symbol character</li> * </ul> * * @param password The password to check * * @return A value indicating whether the password is a strong password (<code>true</code>) * or not (<code>false</code>). */ public function validateStrongPassword(password:String):Boolean { if (password == null || password.length <= 0) { return false; } return STRONG_PASSWORD_PATTERN.test(password); } /** * Uses a password to generate a 16-byte encryption key. The return value is suitable * to use as an encryption key for an encrypted AIR local SQL (SQLite) database. * * <p>For any given * password, calling the <code>getEncryptionKey()</code> method from the same AIR application * running in the same user account on the same machine, the encryption key result is * the same. * * <p>This method is designed to create an encryption key suitable for providing the highest * level of data privacy and security. In order to achieve that level of security, your * application must follow several security principles:</p> * * <ul> * <li>Your application can never store the user-entered password</li> * <li>Your application can never store the encryption key returned by the * <code>getEncryptionKey()</code> method.</li> * <li>Instead, each time the user runs the application and attempts to access the database, * call the <code>getEncryptionKey()</code> method to regenerate the encryption key.</li> * </ul> * * <p>For more information about data security, and an explanation of the security techniques * used in the EncryptionKeyGenerator class, see * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS61068DCE-9499-4d40-82B8-B71CC35D832C.html">Example: Generating and using an encryption key</a>" * in the guide * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p> * * @param password The password to use to generate the encryption key. * @param overrideSaltELSKey The EncryptionKeyGenerator creates and stores a random value * (known as a <i>salt</i>) as part of the process of * generating the encryption key. The first time an application * calls the <code>getEncryptionKey()</code> method, the salt * value is created and stored in the AIR application's encrypted * local store (ELS). From then on, the salt value is loaded from the * ELS. * <p>If you wish to provide a custom String ELS key for storing * the salt value, specify a value for the <code>overrideSaltELSKey</code> * parameter. If the parameter is <code>null</code> (the default) * a default key name is used.</p> * * @return The generated encryption key, a 16-byte ByteArray object. * * @throws ArgumentError If the specified password is not a "strong" password according to the * criteria explained in the <code>validateStrongPassword()</code> * method description * * @throws ArgumentError If a non-<code>null</code> value is specified for the <code>overrideSaltELSKey</code> * parameter, and the value is an empty String (<code>""</code>) */ public function getEncryptionKey(password:String, overrideSaltELSKey:String=null):ByteArray { if (!validateStrongPassword(password)) { throw new ArgumentError("The password must be a strong password. It must be 8-32 characters long. It must contain at least one uppercase letter, at least one lowercase letter, and at least one number or symbol."); } if (overrideSaltELSKey != null && overrideSaltELSKey.length <= 0) { throw new ArgumentError("If an overrideSaltELSKey parameter value is specified, it can't be an empty String."); } var concatenatedPassword:String = concatenatePassword(password); var saltKey:String; if (overrideSaltELSKey == null) { saltKey = SALT_ELS_KEY; } else { saltKey = overrideSaltELSKey; } var salt:ByteArray = EncryptedLocalStore.getItem(saltKey); if (salt == null) { salt = makeSalt(); EncryptedLocalStore.setItem(saltKey, salt); } var unhashedKey:ByteArray = xorBytes(concatenatedPassword, salt); var hashedKey:String = SHA256.hashBytes(unhashedKey); var encryptionKey:ByteArray = generateEncryptionKey(hashedKey); return encryptionKey; } // ------- Creating encryption key ------- private function concatenatePassword(pwd:String):String { var len:int = pwd.length; var targetLength:int = 32; if (len == targetLength) { return pwd; } var repetitions:int = Math.floor(targetLength / len); var excess:int = targetLength % len; var result:String = ""; for (var i:uint = 0; i < repetitions; i++) { result += pwd; } result += pwd.substr(0, excess); return result; } private function makeSalt():ByteArray { var result:ByteArray = new ByteArray; for (var i:uint = 0; i < 8; i++) { result.writeUnsignedInt(Math.round(Math.random() * uint.MAX_VALUE)); } return result; } private function xorBytes(passwordString:String, salt:ByteArray):ByteArray { var result:ByteArray = new ByteArray(); for (var i:uint = 0; i < 32; i += 4) { // Extract 4 bytes from the password string and convert to a uint var o1:uint = passwordString.charCodeAt(i) << 24; o1 += passwordString.charCodeAt(i + 1) << 16; o1 += passwordString.charCodeAt(i + 2) << 8; o1 += passwordString.charCodeAt(i + 3); salt.position = i; var o2:uint = salt.readUnsignedInt(); var xor:uint = o1 ^ o2; result.writeUnsignedInt(xor); } return result; } private function generateEncryptionKey(hash:String):ByteArray { var result:ByteArray = new ByteArray(); // select a range of 128 bits (32 hex characters) from the hash // In this case, we'll use the bits starting from position 17 for (var i:uint = 0; i < 32; i += 2) { var position:uint = i + 17; var hex:String = hash.substr(position, 2); var byte:int = parseInt(hex, 16); result.writeByte(byte); } return result; } } }
bash
#!/bin/bash X=3 Y=4 empty_string="" if [ $X -lt $Y ] # is $X less than $Y ? then echo "\$X=${X}, which is smaller than \$Y=${Y}" fi if [ -n "$empty_string" ]; then echo "empty string is non_empty" fi if [ -e "${HOME}/.fvwmrc" ]; then # test to see if ~/.fvwmrc exists echo "you have a .fvwmrc file" if [ -L "${HOME}/.fvwmrc" ]; then # is it a symlink ? echo "it's a symbolic link" elif [ -f "${HOME}/.fvwmrc" ]; then # is it a regular file ? echo "it's a regular file" fi else echo "you have no .fvwmrc file" fi
coldfusion
<!--- temperature.cfc ---> <cfcomponent> <cffunction name="FtoC" access="public" returntype="numeric"> <cfargument name="fahrenheit" required="yes" type="numeric" /> <cfset answer= (fahrenheit - 32)*100/180 /> <cfreturn answer /> </cffunction> </cfcomponent> <!--- test.cfm ---> <cfset fDegrees = 212 /> <cfinvoke component="temperature" method="FtoC" returnvariable="result"> <cfinvokeargument name="fahrenheit" value="#fDegrees#" /> </cfinvoke> <cfoutput>#fDegrees#°F = #result#°C</cfoutput> <br />
cpp
/* $Id: main.cpp,v 1.1 2004/01/25 22:57:25 zongo Exp $ ** ** Ark - Libraries, Tools & Programs for MORPG developpements. ** Copyright (C) 1999-2004 The Contributors of the Ark Project ** Please see the file "AUTHORS" for a list of contributors ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <iostream> #include <sstream> #include <string> #include "xmlRead.h" #include "ogreGeometryReader.h" #include "ogreMeshReader.h" /****************************************************************************/ class OgreSkeletonReader { std::ostream& errors; public: OgreSkeletonReader(std::ostream& e) : errors(e) {} void parse(XmlNode& root) { } bool write(std::ostream& os) { return true; } }; /****************************************************************************/ void parseStory (XmlNode& node) { for (XmlNode cur=node.firstChild() ; cur ; cur=cur.nextSibling()) { if (cur.isName("keyword")) { std::string key = cur.getString(); std::cout << "keyword: " << key << std::endl; } } } void parseDocument(const char *filename) { XmlDocument doc(filename); if (!doc) { std::cerr << "Document not parsed successfully." << std::endl; return; } XmlNode root(doc); if (!root) { std::cerr << "Empty document." << std::endl; return; } if (root.isName("mesh")) { MeshParameters defaults; OgreMeshReader mesh(std::cerr, defaults); mesh.parseMesh(root); mesh.write(std::cout); } else if (root.isName("skeleton")) { OgreSkeletonReader skel(std::cerr); skel.parse(root); skel.write(std::cout); } else { std::cerr << "Unsupported XML file." << std::endl; } } int main(int argc, char **argv) { if (argc <= 1) { std::cerr << "Usage: " << argv[0] << " file.xml" << std::endl; return -1; } const char* filename = argv[1]; parseDocument(filename); return 0; }
csharp
using System; using System.Text.RegularExpressions; namespace SharpVectors.Dom.Css { /// <summary> /// The CSSFontFaceRule interface represents a @font-face rule in a CSS style sheet. The @font-face rule is used to hold a set of font descriptions. /// </summary> /// <developer>niklas@protocol7.com</developer> /// <completed>80</completed> public class CssFontFaceRule : CssRule, ICssFontFaceRule { #region Static members private static Regex regex = new Regeх(@"^@font-face"); /// <summary> /// Parses a string containging CSS and creates a CssFontFaceRule instance if found as the first content /// </summary> internal static CssRule Parse(ref string css, object parent, bool readOnly, string[] replacedStrings, CssStyleSheetType origin) { Match match = regex.Match(css); if(match.Success) { CssFontFaceRule rule = new CssFontFaceRule(match, parent, readOnly, replacedStrings, origin); css = css.Substring(match.Length); rule.style = new CssStyleDeclaration(ref css, rule, true, origin); return rule; } else { // didn't match => do nothing return null; } } #endregion #region Constructors /// <summary> /// The constructor for CssFontFaceRule /// </summary> /// <param name="match">The Regex match that found the charset rule</param> /// <param name="parent">The parent rule or parent stylesheet</param> /// <param name="readOnly">True if this instance is readonly</param> /// <param name="replacedStrings">An array of strings that have been replaced in the string used for matching. These needs to be put back use the DereplaceStrings method</param> /// <param name="origin">The type of CssStyleSheet</param> internal CssFontFaceRule(Match match, object parent, bool readOnly, string[] replacedStrings, CssStyleSheetType origin) : base(parent, true, replacedStrings, origin) { // always read-only } #endregion #region Implementation of ICssFontFaceRule private CssStyleDeclaration style; /// <summary> /// The declaration-block of this rule. /// </summary> public ICssStyleDeclaration Style { get { return style; } } #endregion #region Implementation of ICssRule /// <summary> /// The type of the rule. The expectation is that binding-specific casting methods can be used to cast down from an instance of the CSSRule interface to the specific derived interface implied by the type. /// </summary> public override CssRuleType Type { get { return CssRuleType.FontFaceRule; } } #endregion } }
css
.syntaxhighlighter, .syntaxhighlighter .bold, .syntaxhighlighter .italic, .syntaxhighlighter .line .number, .syntaxhighlighter.nogutter .line .number, .syntaxhighlighter .line .content, .syntaxhighlighter .line .content code, .syntaxhighlighter .line .content .block, .syntaxhighlighter .line .content .spaces, .syntaxhighlighter.nogutter .line .content, .syntaxhighlighter .bar, .syntaxhighlighter.collapsed .bar, .syntaxhighlighter.nogutter .bar, .syntaxhighlighter .ruler, .syntaxhighlighter.collapsed .lines, .syntaxhighlighter.collapsed .ruler, .syntaxhighlighter.printing, .syntaxhighlighter.printing .tools, .syntaxhighlighter.printing li, .syntaxhighlighter .toolbar, .syntaxhighlighter.nogutter .toolbar, .syntaxhighlighter.collapsed .toolbar, .syntaxhighlighter .toolbar a, .syntaxhighlighter .toolbar a:hover { margin: 0; padding: 0; border: 0; outline: 0; background: none; text-align: left; float: none; vertical-align: baseline; position: static; left: auto; top: auto; right: auto; bottom: auto; height: auto; width: auto; line-height: normal; font-family: "Consolas", "Monaco", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace; font-weight: normal; font-style: normal; font-size: 100%; } .syntaxhighlighter { font-size: 16px; width: 99%; overflow: auto; margin: 18px 0 18px 0 !important; padding-top: 1px; /* adds a little border on top when controls are hidden */ } .syntaxhighlighter .bold { font-weight: bold; } .syntaxhighlighter .italic { font-style: italic; } .syntaxhighlighter .line .number { float: left; width: 45px; padding-right: 5px; text-align: right; display: block; } /* Disable numbers when no gutter option is set */ .syntaxhighlighter.nogutter .line .number { display: none; } .syntaxhighlighter .line .content { margin-left: 50px; padding-left: 4px; display: block; } .syntaxhighlighter .line .content .block { display: block; padding-left: 18px; text-indent: -18px; } .syntaxhighlighter .line .content .spaces { display: none; } /* Disable border and margin on the lines when no gutter option is set */ .syntaxhighlighter.nogutter .line .content { margin-left: 0; border-left: none; } .syntaxhighlighter .bar { padding-left: 50px; } .syntaxhighlighter.collapsed .bar, .syntaxhighlighter.nogutter .bar { padding-left: 0px; } .syntaxhighlighter .ruler { padding-left: 4px; overflow: hidden; padding-bottom: 2px; } /* Adjust some properties when collapsed */ .syntaxhighlighter.collapsed .lines, .syntaxhighlighter.collapsed .ruler { display: none; } /* Additional modifications when in print-view */ .syntaxhighlighter.printing { border: none !important; } .syntaxhighlighter.printing .bar { display: none !important; } /* Styles for the tools */ .syntaxhighlighter .toolbar { font-size: 80%; font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; padding: 1px 5px 5px 5px; } .syntaxhighlighter.nogutter .toolbar { border-left: 0; } .syntaxhighlighter.collapsed .toolbar { border-bottom: 0; } .syntaxhighlighter .toolbar a { text-decoration: none; margin-right: 10px; } .syntaxhighlighter .toolbar a:hover { text-decoration: underline; margin-right: 10px; }
delphi
{ $OmniXML: OmniXML/extras/OmniXMLShared.pas,v 1.1 2004/06/07 13:06:32 mr Exp $ } {$WEAKPACKAGEUNIT ON} (*:XML helper unit. Contains class to manage shared XML document (stored in the resizable shared memory). @author Primoz Gabrijelcic @desc <pre> (c) 2002 Primoz Gabrijelcic Free for personal and commercial use. No rights reserved. Author : Primoz Gabrijelcic Creation date : 2002-05-13 Last modification : 2002-09-24 Version : 1.01 </pre>*)(* History: 1.01: 2002-09-24 - Added property TGpSharedXML.CachedXML. 1.0: 2002-05-13 - Created. *) unit OmniXMLShared; interface uses Windows, GpSharedMemory, OmniXMLProperties; type {:Shared XML document. } TGpSharedXML = class private sxOwnsXML : boolean; sxSharedMemory: TGpSharedMemory; sxXMLDoc : TGpXMLDoc; protected function Acquire(forWriting: boolean; timeout: DWORD): TGpXMLDoc; function GetName: string; function GetXML: TGpXMLDoc; public constructor Create(sharedMemoryName: string; xmlDoc: TGpXMLDoc; maxSize: cardinal; ownsXML: boolean = true); virtual; destructor Destroy; override; function BeginUpdate(timeout: DWORD): TGpXMLDoc; virtual; procedure EndUpdate; virtual; function Read(timeout: DWORD): TGpXMLDoc; virtual; property CachedXML: TGpXMLDoc read sxXMLDoc; property Name: string read GetName; property XML: TGpXMLDoc read GetXML; end; { TGpSharedXML } {:Shared XML list. } TGpSharedXMLList = class(TGpSharedXML) public constructor Create(sharedMemoryName: string; xmlList: TGpXMLDocList; maxSize: cardinal; ownsXML: boolean = true); reintroduce; virtual; function Count: integer; end; { TGpSharedXMLList } implementation uses {$IFDEF DebugXML} OmniXMLUtils, uDbg, {$ENDIF DebugXML} SysUtils; { TGpSharedXML } function TGpSharedXML.Acquire(forWriting: boolean; timeout: DWORD): TGpXMLDoc; begin Result := nil; if sxSharedMemory.AcquireMemory(forWriting, timeout) <> nil then begin if (not sxSharedMemory.Modified) or sxXMLDoc.LoadFromStream(sxSharedMemory.AsStream) then Result := sxXMLDoc; if not assigned(Result) then sxSharedMemory.ReleaseMemory; {$IFDEF DebugXML} if assigned(Result) then Debugger.LogFmtMsg('Acquire: %s',[XMLSaveToString(sxXMLDoc.XMLDoc)]); {$ENDIF DebugXML} end; end; { TGpSharedXML.Acquire } function TGpSharedXML.BeginUpdate(timeout: DWORD): TGpXMLDoc; begin Result := Acquire(true, timeout); end; { TGpSharedXML.BeginUpdate } constructor TGpSharedXML.Create(sharedMemoryName: string; xmlDoc: TGpXMLDoc; maxSize: cardinal; ownsXML: boolean); begin inherited Create; sxSharedMemory := TGpSharedMemory.Create(sharedMemoryName, 0, maxSize); sxXMLDoc := xmlDoc; sxOwnsXML := ownsXML; end; { TGpSharedXML.Create } destructor TGpSharedXML.Destroy; begin if sxOwnsXML then FreeAndNil(sxXMLDoc) else sxXMLDoc := nil; FreeAndNil(sxSharedMemory); inherited; end; { TGpSharedXML.Destroy } procedure TGpSharedXML.EndUpdate; begin {$IFDEF DebugXML} Debugger.LogFmtMsg('Release: %s',[XMLSaveToString(sxXMLDoc.XMLDoc)]); {$ENDIF DebugXML} if sxSharedMemory.IsWriting then sxXMLDoc.SaveToStream(sxSharedMemory.AsStream); if sxSharedMemory.Acquired then sxSharedMemory.ReleaseMemory; end; { TGpSharedXML.EndUpdate } function TGpSharedXML.GetName: string; begin Result := sxSharedMemory.Name; end; { TGpSharedXML.GetName } function TGpSharedXML.GetXML: TGpXMLDoc; begin if not sxSharedMemory.Acquired then Result := nil else Result := sxXMLDoc; end; { TGpSharedXML.GetXML } function TGpSharedXML.Read(timeout: DWORD): TGpXMLDoc; begin Result := Acquire(false, timeout); EndUpdate; end; { TGpSharedXML.Read } { TGpSharedXMLList } function TGpSharedXMLList.Count: integer; begin Result := (XML as TGpXMLDocList).Count; end; { TGpSharedXMLList.Count } constructor TGpSharedXMLList.Create(sharedMemoryName: string; xmlList: TGpXMLDocList; maxSize: cardinal; ownsXML: boolean); begin inherited Create(sharedMemoryName, xmlList, maxSize, ownsXML); end; { TGpSharedXMLList.Create } {$IFDEF DebugXML} initialization NxStartDebug; finalization NxEndDebug; {$ENDIF DebugXML} end.
diff
--- ...\index.php-rev104.svn000.tmp.php 2008-10-13 20:34:44.000000000 -0300 +++ ...\index.php 2008-10-13 16:31:46.000000000 -0300 @@ -90,36 +90,34 @@ \$url .= \$arg; } return \$url; } -//<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -//<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> ?> -<!DOCTYPE html - PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>SyntaxHighlighter</title> <link type="text/css" rel="stylesheet" href="Styles/shCore.css"/> <link type="text/css" rel="stylesheet" href="Styles/shTheme<?= \$current_theme ?>.css"/> <link href="Styles/TestPages.css" rel="stylesheet" type="text/css"/> </head> <body> - <!-- -<pre class="brush: c#"> -/** test */ - hello -</pre> -<h1>SyntaxHighlighter 2.0</h1> -<p><a href="http://code.google.com/p/syntaxhighlighter/">http://code.google.com/p/syntaxhighlighter/</a></p> ---> +<script type="text/javascript" src="Scripts/shCore.js"></script> +<? foreach (\$brushes as \$brush => \$label) : ?> +<script type="text/javascript" src="Scripts/shBrush<?= \$brush ?>.js"></script> +<? endforeach; ?> +<script type="text/javascript"> +//<!-- +var syntaxHighlighterConfig = {}; +//--> +</script> + <h2><?= \$title ?></h2> <div class="layout"> <select onchange="setTheme(this)" size="1"> <? foreach (\$themes as \$theme => \$label) : ?> @@ -166,16 +164,11 @@ <div class="footer"> Copyright 2004-2008 Alex Gorbatchev.<br/> </div> </div> -<script type="text/javascript" src="Scripts/shCore.js"></script> -<? foreach (\$brushes as \$brush => \$label) : ?> -<script type="text/javascript" src="Scripts/shBrush<?= \$brush ?>.js"></script> -<? endforeach; ?> <script type="text/javascript"> //<!-- function themeUrl(value) { return url("theme", value); @@ -202,20 +195,14 @@ function setTheme(sender) { window.location = themeUrl(sender.options[sender.selectedIndex].value); } -if(window.isBloggerMode == true) - SyntaxHighlighter.BloggerMode(); -SyntaxHighlighter.ClipboardSwf = 'Scripts/clipboard.swf'; +syntaxHighlighterConfig.clipboardSwf = 'Scripts/clipboard.swf'; -window.onload = function() -{ + SyntaxHighlighter.highlight(); -} //--> </script> </body> </html>
erlang
update(File, In, Out) -> InFile = File ++ In, OutFile = File ++ Out, case is_file(OutFile) of true -> case writeable(OutFile) of true -> outofdate(InFile, OutFile); false -> %% can't write so we can't update false end; false -> %% doesn't exist true end.
groovy
import groovy.swing.SwingBuilder import static java.awt.BorderLayout.* import java.awt.event.* // set up variables count = 0 def textlabel def text = "Actions: " def update = { c -> text += c textlabel.text = text } // create the listener def closureMap = [ mousePressed: { update 'M' }, keyPressed: { update 'K' }, focusLost: { update 'F' }, windowIconified: { update 'W' } ] def interfaces = [WindowListener, KeyListener, MouseListener, FocusListener] def listener = ProxyGenerator.instantiateAggregate(closureMap, interfaces) // now the GUI def swing = new SwingBuilder() def frame = swing.frame(title:'Frame') { borderLayout() textlabel = label(text:text, constraints: NORTH) button = button(text:'Click Me', constraints: SOUTH) } frame.addWindowListener listener ['Key', 'Mouse', 'Focus'].each { button."add${it}Listener" listener textlabel."add${it}Listener" listener } frame.pack() frame.show()
haxe
class Test { static function main() { var people = [ "Elizabeth" => "Programmer", "Joel" => "Designer" ]; for (name in people.keys()) { var job = people[name]; trace('$name is a $job'); } } }
java
package tutorial; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String execute() { name = "Hello, " + name + "!"; return SUCCESS; } }
javafx
import javafx.scene.input.MouseEvent; import javafx.scene.Scene; import javafx.scene.shape.Circle; import javafx.scene.transform.Scale; import javafx.stage.Stage; /** * @author Patrick Webster */ var mouseX: Number; var mouseY: Number; var scale: Float = (-2.3 - 1.0) * -1.; var egg: Circle; Stage { title: "Easing Raw Egg" scene: Scene { height: 0x1AB width: 0X20C content: egg = Circle { centerX: bind mouseX centerY: bind mouseY radius: 323.456e-02 transforms: Scale { // Egg eases to moving mouse cursor pivotX: bind mouseX pivotY: bind mouseY x: bind scale * .02298E3 y: bind scale * 32.56789 } onMouseMoved: function( me: MouseEvent ) { updateMousePosition(me); } onMouseWheelMoved: function( we: MouseEvent ) { updateMousePosition(we); updateScale(we); } } } } function updateMousePosition(me : MouseEvent) : Void { mouseX = me.x; mouseY = me.y; } function updateScale(we: MouseEvent) : Float { var newScale = scale + (we.wheelRotation * -0.1); if (newScale < 1.0) return scale = 1.0000000e+00; return scale = newScale; }
javascript
/** * This is a JavaScript sample. */ var matches = require('./matches'); module.exports = { /** * Applies all regular expression to the code and stores all found * matches in the `this.matches` array. */ parse: function(code, regexList, opts) { var result = []; regexList = regexList || []; for (var i = 0, l = regexList.length; i < l; i++) // BUG: length returns len+1 for array if methods added to prototype chain (oising@gmail.com) if (typeof regexList[i] === 'object') result = result.concat(matches.find(code, regexList[i])); result = matches.sort(result); result = matches.removeNested(result); result = matches.compact(result); return result; } };
perl
#!/usr/bin/perl use strict; use warnings; use LWP::Socket; use FCGI::ProcManager qw/ pm_manage pm_pre_dispatch pm_post_dispatch /; # Prepare content and headers my $content = join "", map { $_ } <DATA>; my $headers ="HTTP/1.1 200 OK\r\n" . "Server: FlaresunsFakeServer/2009-09-10\r\n" . "Content-Type: text/html\r\n" . "Content-Length: " . length($content). "\r\n" . "Connection: close\r\n\r\n"; # Prepare and open socket my $sock = new LWP::Socket(); $sock->bind('127.0.0.1', '8080'); $sock->listen(10); # Create 5 childs pm_manage(n_processes => 5); while ( my $socket = $sock->accept(10) ) { pm_pre_dispatch(); $socket->write($headers); $socket->write($content); $socket->shutdown(); pm_post_dispatch(); } $sock->shutdown(); __DATA__ <html> <head><title>Hi</title></head> <body> <h1>Hello from Habr!</h1> </body> </html>
php
<?php if (!defined('MEDIAWIKI')) exit(1); $wgExtensionFunctions[] = "wfSyntaxHighlighterExtension"; $wgExtensionCredits['other'][] = array( 'name' => 'SyntaxHighlighter', 'author' => array('Alex Gorbatchev'), 'version' => '1.0', 'url' => 'http://alexgorbatchev.com/projects/syntaxhighlighter', 'description' => 'Provides tight integration with SyntaxHighlighter.' ); // Path to the SyntaxHighlighter scripts $wgSyntaxHighlighterScriptPath = "{$wgScriptPath}/extensions/SyntaxHighlighter/scripts"; // Path to the SyntaxHighlighter styles $wgSyntaxHighlighterStylesPath = "{$wgScriptPath}/extensions/SyntaxHighlighter/styles"; // Theme CSS file $wgSyntaxHighlighterTheme = "shThemeDefault.css"; // Brushes to include on the page $wgSyntaxHighlighterBrushes = array( 'shBrushBash.js', 'shBrushCpp.js', 'shBrushCSharp.js', 'shBrushCss.js', 'shBrushDelphi.js', 'shBrushDiff.js', 'shBrushGroovy.js', 'shBrushJava.js', 'shBrushJScript.js', 'shBrushPhp.js', 'shBrushPlain.js', 'shBrushPython.js', 'shBrushRuby.js', 'shBrushScala.js', 'shBrushSql.js', 'shBrushVb.js', 'shBrushXml.js' ); $dir = dirname(__FILE__) . '/'; function wfSyntaxHighlighterExtension() { global $wgOut, $wgScriptPath, $wgParser, $wgSyntaxHighlighterBrushes, $wgSyntaxHighlighterScriptPath, $wgSyntaxHighlighterStylesPath, $wgSyntaxHighlighterTheme; // Make shCore.js the very first script to be included (before all the brushes) array_unshift($wgSyntaxHighlighterBrushes, 'shCore.js'); $home = $wgSyntaxHighlighterScriptPath; // Add all scripts to the header foreach ($wgSyntaxHighlighterBrushes as $script) $wgOut->addScript("<script type=\"text/javascript\" src=\"{$wgSyntaxHighlighterScriptPath}/$script\"></script>\n"); // Add CSS links foreach (array('shCore.css', $wgSyntaxHighlighterTheme) as $css) $wgOut->addHeadItem($css, "<link type=\"text/css\" rel=\"stylesheet\" href=\"{$wgSyntaxHighlighterStylesPath}/$css\"/>\n"); // Add initialization code $wgOut->addScript( "<script type=\"text/javascript\">". "var syntaxHighlighterConfig = { clipboardSwf: '{$wgSyntaxHighlighterScriptPath}/clipboard.swf' };". "SyntaxHighlighter.highlight();". "</script>\n" ); // Finally, set up a MediaWiki hook to the <sh /> tag $wgParser->setHook("sh", "wfSyntaxHighlighterExtensionRender"); return true; } function wfSyntaxHighlighterExtensionRender($input, $argv, $parser) { $args = ""; while (list($key, $val) = each($argv)) $args .= "$key: $val;"; $input = htmlspecialchars($input); return "<pre class=\"$args\">\n$input\n</pre>"; }
plain
This is just plain text brush... Maybe somebody will need it :)
powershell
$request = [System.Net.WebRequest]::Create("http://www.somelocation.com/testlink.aspx") $response = $request.GetResponse() $requestStream = $response.GetResponseStream() $readStream = new-object System.IO.StreamReader $requestStream new-variable db $db = $readStream.ReadToEnd() $readStream.Close() $response.Close()
python
#!/usr/bin/python """ xml2html: Convert XML to HTML *** SUPERSEDED by pyslt *** Uses SAX (event-based parsing). ***LICENSE*** """ _ID = '$Id: xml2html-1.01-1.py,v 1.1.1.1 2000/01/15 14:37:46 ecoaccess Exp $' import sys, copy from xml.sax.drivers.drv_xmlproc_val import * class myParser(SAX_XPValParser): """XML parser.""" psl = None def handle_doctype(self, rootname, pub_id, sys_id): self.dtd_handler.doctypeDecl(rootname, pub_id, sys_id, self.psl) class docHandler: """XML Document events handler.""" def characters(self, ch, start, length): """Handle a character data event. The data are contained in the substring of ch starting at position start and of length length.""" print ch[start:start+length], def endDocument(self): """Handle an event for the end of a document.""" pass def endElement(self, name): """Handle an event for the end of an element.""" print self.translation_table[name].end() def ignorableWhitespace(self, ch, start, length): """Handle an event for ignorable whitespace in element content. The data are contained in the substring of ch starting at position start and of length length.""" pass def processingInstruction(self, target, data): """Handle a processing instruction event.""" pass def setDocumentLocator(self, locator): """Receive an object for locating the origin of SAX document events. locator is an object of type Locator.""" pass def startDocument(self): """Handle an event for the beginning of a document.""" pass def startElement(self, name, atts): """Handle an event for the beginning of an element. atts is an object of type AttributeList.""" print self.translation_table[name].start(atts), class dtdHandler: """Document Type Definition events handler.""" def notationDecl(self, name, publicId, systemId): """Handle a notation declaration event.""" pass def unparsedEntityDecl(self, name, publicId, systemId, ndata): """Handle an unparsed entity declaration event.""" pass def doctypeDecl(self, rootname, pub_id, sys_id, psl=None): """Handle a Doctype Declaration event.""" #print "Document type: %s" % rootname # Here is where I would need to load in the appropriate translation # table. if psl: x = {'kludge': {}} execfile(psl, globals(), locals()) translation_table = x['kludge'] else: if rootname == "Bylaws": from org.ecoaccess.dtd.Bylaws import translation_table elif rootname == "Funspec": from org.ecoaccess.dtd.Funspec import translation_table else: translation_table = {} docHandler.translation_table = translation_table # --- Main prog if __name__ == '__main__': p=myParser() if len(sys.argv) > 2: p.psl = sys.argv[2] p.setDocumentHandler(docHandler()) p.setDTDHandler(dtdHandler()) p.parse(sys.argv[1])
ruby
class Post < ActiveRecord::Base DEFAULT_LIMIT = 15 acts_as_taggable has_many :comments, :dependent => :destroy has_many :approved_comments, :class_name => 'Comment' before_validation :generate_slug before_validation :set_dates before_save :apply_filter validates_presence_of :title, :slug, :body validate :validate_published_at_natural def validate_published_at_natural errors.add("published_at_natural", "Unable to parse time") unless published? end attr_accessor :minor_edit def minor_edit @minor_edit ||= "1" end def minor_edit? self.minor_edit == "1" end def published? published_at? end attr_accessor :published_at_natural def published_at_natural @published_at_natural ||= published_at.send_with_default(:strftime, 'now', "%Y-%m-%d %H:%M") end class << self def build_for_preview(params) post = Post.new(params) post.generate_slug post.set_dates post.apply_filter TagList.from(params[:tag_list]).each do |tag| post.tags << Tag.new(:name => tag) end post end def find_recent(options = {}) tag = options.delete(:tag) options = { :order => 'posts.published_at DESC', :conditions => ['published_at < ?', Time.zone.now], :limit => DEFAULT_LIMIT }.merge(options) if tag find_tagged_with(tag, options) else find(:all, options) end end def find_by_permalink(year, month, day, slug, options = {}) begin day = Time.parse([year, month, day].collect(&:to_i).join("-")).midnight post = find_all_by_slug(slug, options).detect do |post| [:year, :month, :day].all? {|time| post.published_at.send(time) == day.send(time) } end rescue ArgumentError # Invalid time post = nil end post || raise(ActiveRecord::RecordNotFound) end def find_all_grouped_by_month posts = find( :all, :order => 'posts.published_at DESC', :conditions => ['published_at < ?', Time.now] ) month = Struct.new(:date, :posts) posts.group_by(&:month).inject([]) {|a, v| a << month.new(v[0], v[1])} end end def destroy_with_undo transaction do self.destroy return DeletePostUndo.create_undo(self) end end def month published_at.beginning_of_month end def apply_filter self.body_html = EnkiFormatter.format_as_xhtml(self.body) end def set_dates self.edited_at = Time.now if self.edited_at.nil? || !minor_edit? self.published_at = Chronic.parse(self.published_at_natural) end def denormalize_comments_count! Post.update_all(["approved_comments_count = ?", self.approved_comments.count], ["id = ?", self.id]) end def generate_slug self.slug = self.title.dup if self.slug.blank? self.slug.slugorize! end # TODO: Contribute this back to acts_as_taggable_on_steroids plugin def tag_list=(value) value = value.join(", ") if value.respond_to?(:join) super(value) end end
sass
$background : white !default; $line_alt1_background : $background !default; $line_alt2_background : $background !default; $line_highlighted_background : #e0e0e0 !default; $line_highlighted_number : black !default; $gutter_text : #afafaf !default; $gutter_border_color : #6ce26c !default; $gutter_border : 3px solid $gutter_border_color !default; $toolbar_collapsed_a : #00f !default; $toolbar_collapsed_a_hover : #f00 !default; $toolbar_collapsed_background : #fff !default; $toolbar_collapsed_border : 1px solid $gutter_border_color !default; $toolbar_a : #fff !default; $toolbar_a_hover : #000 !default; $toolbar_background : $gutter_border_color !default; $toolbar_border : none !default; $code_plain : black !default; $code_comments : #008200 !default; $code_string : blue !default; $code_keyword : #006699 !default; $code_preprocessor : gray !default; $code_variable : #aa7700 !default; $code_value : #009900 !default; $code_functions : #ff1493 !default; $code_constants : #0066cc !default; $code_script : $code_keyword !default; $code_script_background : none !default; $code_color1 : gray !default; $code_color2 : #ff1493 !default; $code_color3 : red !default; $caption_color : $code_plain !default; @mixin round_corners_custom($top, $right, $bottom, $left) { -moz-border-radius: $top $right $bottom $left !important; -webkit-border-radius: $top $right $bottom $left !important; } @mixin round_corners($radius) { @include round_corners_custom($radius, $radius, $radius, $radius); } .syntaxhighlighter { a, div, code, table, table td, table tr, table tbody, table thead, table caption, textarea { @include round_corners(0); background: none !important; border: 0 !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; line-height: 1.1em !important; margin: 0 !important; outline: 0 !important; overflow: visible !important; padding: 0 !important; position: static !important; right: auto !important; text-align: left !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; font: { family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; weight: normal !important; style: normal !important; size: 1em !important; } min: { // For IE8, FF & WebKit height: inherit !important; // For IE7 height: auto !important; } } } .syntaxhighlighter { width: 100% !important; margin: 1em 0 1em 0 !important; position: relative !important; overflow: auto !important; font-size: 1em !important; &.source { overflow: hidden !important; } // set up bold and italic .bold { font-weight: bold !important; } .italic { font-style: italic !important; } .line { white-space: pre !important; } // main table and columns table { width: 100% !important; caption { text-align: left !important; padding: .5em 0 0.5em 1em !important; } td.code { width: 100% !important; .container { position: relative !important; textarea { box-sizing: border-box !important; position: absolute !important; left: 0 !important; top: 0 !important; width: 100% !important; height: 100% !important; border: none !important; background: white !important; padding-left: 1em !important; overflow: hidden !important; white-space: pre !important; } } } // middle spacing between line numbers and lines td.gutter .line { text-align: right !important; padding: 0 0.5em 0 1em !important; } td.code .line { padding: 0 1em !important; } } &.nogutter { td.code { .container textarea, .line { padding-left: 0em !important; } } } &.show { display: block !important; } // Adjust some properties when collapsed &.collapsed { table { display: none !important; } .toolbar { padding: 0.1em 0.8em 0em 0.8em !important; font-size: 1em !important; position: static !important; width: auto !important; height: auto !important; span { display: inline !important; margin-right: 1em !important; a { padding: 0 !important; display: none !important; &.expandSource { display: inline !important; } } } } } // Styles for the toolbar .toolbar { position: absolute !important; right: 1px !important; top: 1px !important; width: 11px !important; height: 11px !important; font-size: 10px !important; z-index: 10 !important; span.title { display: inline !important; } a { display: block !important; text-align: center !important; text-decoration: none !important; padding-top: 1px !important; &.expandSource { display: none !important; } } } &.ie { font-size: .9em !important; padding: 1px 0 1px 0 !important; .toolbar { line-height: 8px !important; a { padding-top: 0px !important; } } } // Print view. // Colors are based on the default theme without background. &.printing { .line.alt1 .content, .line.alt2 .content, .line.highlighted .number, .line.highlighted.alt1 .content, .line.highlighted.alt2 .content { background: none !important; } // Gutter line numbers .line { .number { color: #bbbbbb !important; } // Add border to the lines .content { color: black !important; } } // Toolbar when visible .toolbar { display: none !important; } a { text-decoration: none !important; } .plain, .plain a { color: black !important; } .comments, .comments a { color: #008200 !important; } .string, .string a { color: blue !important; } .keyword { color: #006699 !important; font-weight: bold !important; } .preprocessor { color: gray !important; } .variable { color: #aa7700 !important; } .value { color: #009900 !important; } .functions { color: #ff1493 !important; } .constants { color: #0066cc !important; } .script { font-weight: bold !important; } .color1, .color1 a { color: gray !important; } .color2, .color2 a { color: #ff1493 !important; } .color3, .color3 a { color: red !important; } .break, .break a { color: black !important; } } } // Interface elements. .syntaxhighlighter { background-color: $background !important; // Highlighed line number .line { &.alt1 { background-color: $line_alt1_background !important; } &.alt2 { background-color: $line_alt2_background !important; } // Highlighed line &.highlighted { &.alt1, &.alt2 { background-color: $line_highlighted_background !important; } &.number { color: $line_highlighted_number !important; } } } table { caption { color: $caption_color !important; } td.code { .container { textarea { background: $background; color: $code_plain; } } } } // Add border to the lines .gutter { color: $gutter_text !important; .line { border-right: $gutter_border !important; &.highlighted { background-color: $gutter_border_color !important; color: $background !important; } } } &.printing .line .content { border: none !important; } &.collapsed { overflow: visible !important; .toolbar { color: $toolbar_collapsed_a !important; background: $toolbar_collapsed_background !important; border: $toolbar_collapsed_border !important; a { color: $toolbar_collapsed_a !important; &:hover { color: $toolbar_collapsed_a_hover !important; } } } } .toolbar { color: $toolbar_a !important; background: $toolbar_background !important; border: $toolbar_border !important; a { color: $toolbar_a !important; &:hover { color: $toolbar_a_hover !important; } } } // Actual syntax highlighter colors. .plain, .plain a { color: $code_plain !important; } .comments, .comments a { color: $code_comments !important; } .string, .string a { color: $code_string !important; } .keyword { font-weight: bold !important; color: $code_keyword !important; } .preprocessor { color: $code_preprocessor !important; } .variable { color: $code_variable !important; } .value { color: $code_value !important; } .functions { color: $code_functions !important; } .constants { color: $code_constants !important; } .script { font-weight: bold !important; color: $code_script !important; background-color: $code_script_background !important; } .color1, .color1 a { color: $code_color1 !important; } .color2, .color2 a { color: $code_color2 !important; } .color3, .color3 a { color: $code_color3 !important; } }
scala
package examples /** Illustrate the use of pattern matching in Scala. * Like patterns.scala, but uses extractors for representation independence */ object extractorPatterns { /** We need an abstract base class for trees. Subclasses with * the 'case' modifier can be used in pattern matching expressions * to deconstruct trees. * * Here, we replaced case classes of patterns.scala with objects * that hide the actual implementation of Branch and Leaf. Note * that the remaining code does not change. In this way, we * can change the implementation later without affecting clients, * which is called representation independence. */ abstract class Tree object Branch { /* method to contruct branches @see extractorPatterns.tree1 */ def apply(left: Tree, right: Tree): Tree = new BranchImpl(left, right) /* extractor method referenced in match expressions @see extractorPatterns.sumLeaves */ def unapply(x:Tree): Option[(Tree,Tree)] = x match { case y:BranchImpl => Some(y.left, y.right) case _ => None } private class BranchImpl(val left:Tree, val right:Tree) extends Tree } object Leaf { /* method to contruct leaves @see tree1 */ def apply(x:Int): Tree = new LeafImpl(x); /* extractor method referenced in match expressions @see extractorPatterns.sumLeaves */ def unapply(x:Tree): Option[Int] = x match { case y:LeafImpl => Some(y.x) case _ => None } private class LeafImpl(val x: Int) extends Tree } /** Case classes have an implicit constructor methods which allows * to create objects withouth the 'new' keyword. It saves some typing * and makes code clearer. * * Here, the task of the case class constructor is performed by the * method Branch.apply - the singleton Branch is treated as if it * were a function value. This trick works with any value that has * an apply method. */ val tree1 = Branch(Branch(Leaf(1), Leaf(2)), Branch(Leaf(3), Leaf(4))) /** Return the sum of numbers found in leaves. * 'match' is a generalization of 'switch' in C-like languages * * Patterns consist of case class constructors (which can * be nested), and lower case variables which are * bound to the values with which the class has been constructed. * * For extractors, it is not the name of a case class, but the name of * the singleton object Branch which is used to refer to its extractor method * Branch.unapply - the pattern is the 'reverse' of a method * call, with the result being matched in the subpatterns. This works * for any value that has an appropriate extractor method. */ def sumLeaves(t: Tree): Int = t match { case Branch(l, r) => sumLeaves(l) + sumLeaves(r) case Leaf(x) => x } /** This illustrates the use of Option types. Since the * method is not known in advance to find 'x', the * return type is an Option. Options have two possible * values, either 'Some' or 'None'. It is a type-safe * way around 'null' values. */ def find[A, B](it: Iterator[Pair[A, B]], x: A): Option[B] = { var result: Option[B] = None while (it.hasNext && result == None) { val Pair(x1, y) = it.next; if (x == x1) result = Some(y) } result } def printFinds[A](xs: List[Pair[A, String]], x: A) = find(xs.elements, x) match { case Some(y) => println(y) case None => println("no match") } def main(args: Array[String]) { println("sum of leafs=" + sumLeaves(tree1)); printFinds(List(Pair(3, "three"), Pair(4, "four")), 4) } }
sql
-- Data model to support XML exchange with thecontent repository of -- the ArsDigita Community System -- Copyright (C) 1999-2000 ArsDigita Corporation -- Author: Karl Goldstein (karlg@arsdigita.com) -- $Id: content-xml.sql,v 1.3 2001/04/28 19:58:39 donb Exp $ -- This is free software distributed under the terms of the GNU Public -- License. Full text of the license is available from the GNU Project: -- http://www.fsf.org/copyleft/gpl.html -- A sequence for uniquely identifying uploaded XML documents until -- they are inserted into the repository create sequence cr_xml_doc_seq; -- create global temporary table cr_xml_docs ( -- doc_id integer primary key, -- doc CLOB -- ) on commit delete rows; create table cr_xml_docs ( doc_id integer primary key, doc text ); comment on table cr_xml_docs is ' A temporary table for holding uploaded XML documents for the duration of a transaction, until they can be inserted into the content repository. ';
swift
var dict = ["a": "Apple", // set up the Dictionary "b": "Banana", "c": "Cherry"] let bananaIndex = dict.indexForKey("b")! // retrieve an index println(dict[bananaIndex]) // subscript via DictionaryIndex<String, String> > (b, Banana) println(dict["c"]) // subscript via String key > Optional("Cherry") let set: Set = ["Apple", "Banana", "Cherry"] // set up the Set let start: Int = set.startIndex println(set[start]) > Cherry println(set["Apple"]) error: type 'Index' does not conform to protocol 'StringLiteralConvertible' /* Checked equality (true) on equal big sets in 0.923960983753204 Checked equality (false) on different-size big sets in 2.98023223876953e-06 Checked equality (false) on same-size unequal big sets in 0.908538997173309 */
tap
1..4 ok 1 - Input file opened not ok 2 - First line of the input valid ok 3 - Read the rest of the file not ok 4 - Summarized correctly # TODO Not written yet
typescript
/** * TypeScript lets you write JavaScript the way you really want to. * TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. * Any browser. Any host. Any OS. Open Source. */ class Animal { constructor(public name: string) { } move(meters: number) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name: string) { super(name); } move() { alert("Slithering..."); super.move(5); } } class Horse extends Animal { constructor(name: string) { super(name); } move() { alert("Galloping..."); super.move(45); } } var sam = new Snake("Sammy the Python"); var tom: Animal = new Horse("Tommy the Palomino"); sam.move(); tom.move(34);
vb
' ' DotNetNuke - http://www.dotnetnuke.com ' Copyright (c) 2002-2005 ' by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca ) ' ' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ' documentation files (the "Software"), to deal in the Software without restriction, including without limitation ' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and ' to permit persons to whom the Software is furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all copies or substantial portions ' of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. ' Imports System Imports System.Xml Imports System.Collections Imports System.Reflection Imports System.Diagnostics Imports DotNetNuke.Framework.Providers Namespace DotNetNuke.Common.Utilities ''' ----------------------------------------------------------------------------- ''' <summary> ''' The Config class provides access to the web.config file ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [cnurse] 11/15/2005 documented ''' </history> ''' ----------------------------------------------------------------------------- Public Class Config #Region "Shared Methods" Public Shared Function AddAppSetting(ByVal xmlDoc As XmlDocument, ByVal Key As String, ByVal Value As String) As XmlDocument Dim xmlElement As xmlElement ' retrieve the appSettings node Dim xmlAppSettings As xmlNode = xmlDoc.SelectSingleNode("//appSettings") If Not xmlAppSettings Is Nothing Then ' get the node based on key Dim xmlNode As xmlNode = xmlAppSettings.SelectSingleNode(("//add[@key='" + Key + "']")) If Not xmlNode Is Nothing Then ' update the existing element xmlElement = CType(xmlNode, xmlElement) xmlElement.SetAttribute("value", Value) Else ' create a new element xmlElement = xmlDoc.CreateElement("add") xmlElement.SetAttribute("key", Key) xmlElement.SetAttribute("value", Value) xmlAppSettings.AppendChild(xmlElement) End If End If ' return the xml doc Return xmlDoc End Function ''' ----------------------------------------------------------------------------- ''' <summary> ''' Gets the default connection String as specified in the provider. ''' </summary> ''' <returns>The connection String</returns> ''' <remarks></remarks> ''' <history> ''' [cnurse] 11/15/2005 created ''' </history> ''' ----------------------------------------------------------------------------- Public Shared Function GetConnectionString() As String Dim _providerConfiguration As ProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data") ' Read the configuration specific information for this provider Dim objProvider As Provider = CType(_providerConfiguration.Providers(_providerConfiguration.DefaultProvider), Provider) Return GetConnectionString(objProvider.Attributes("connectionStringName")) End Function ''' ----------------------------------------------------------------------------- ''' <summary> ''' Gets the specified connection String ''' </summary> ''' <param name="name">Name of Connection String to return</param> ''' <returns>The connection String</returns> ''' <remarks></remarks> ''' <history> ''' [cnurse] 11/15/2005 created ''' </history> ''' ----------------------------------------------------------------------------- Public Shared Function GetConnectionString(ByVal name As String) As String Dim connectionString As String = "" If connectionString = "" Then 'check if connection string is specified in <appsettings> (ASP.NET 1.1 / DNN v3.x) If name <> "" Then connectionString = Config.GetSetting(name) End If End If Return connectionString End Function Public Shared Function GetSetting(ByVal setting As String) As String Return System.Configuration.ConfigurationSettings.AppSettings(setting) End Function Public Shared Function GetSection(ByVal section As String) As Object Return System.Configuration.ConfigurationSettings.GetConfig(section) End Function Public Shared Function Load() As XmlDocument ' open the web.config file Dim xmlDoc As New XmlDocument xmlDoc.Load(Common.Globals.ApplicationMapPath & "\web.config") Return xmlDoc End Function Public Shared Function Load(ByVal filename As String) As XmlDocument ' open the config file Dim xmlDoc As New XmlDocument xmlDoc.Load(Common.Globals.ApplicationMapPath & "\" & filename) Return xmlDoc End Function Public Shared Function Save(ByVal xmlDoc As XmlDocument) As String Try ' save the config file Dim writer As New XmlTextWriter(Common.Globals.ApplicationMapPath & "\web.config", Nothing) writer.Formatting = Formatting.Indented xmlDoc.WriteTo(writer) writer.Flush() writer.Close() Return "" Catch exc As Exception ' the file may be read-only or the file permissions may not be set properly Return exc.Message End Try End Function Public Shared Function Save(ByVal xmlDoc As XmlDocument, ByVal filename As String) As String Try ' save the config file Dim writer As New XmlTextWriter(Common.Globals.ApplicationMapPath & "\" & filename, Nothing) writer.Formatting = Formatting.Indented xmlDoc.WriteTo(writer) writer.Flush() writer.Close() Return "" Catch exc As Exception ' the file may be read-only or the file permissions may not be set properly Return exc.Message End Try End Function Public Shared Function UpdateMachineKey(ByVal xmlConfig As XmlDocument) As XmlDocument Dim objSecurity As New PortalSecurity Dim validationKey As String = objSecurity.CreateKey(20) Dim decryptionKey As String = objSecurity.CreateKey(24) xmlConfig = AddAppSetting(xmlConfig, "MachineValidationKey", validationKey) xmlConfig = AddAppSetting(xmlConfig, "MachineDecryptionKey", decryptionKey) xmlConfig = AddAppSetting(xmlConfig, "InstallationDate", Date.Today.ToShortDateString) Return xmlConfig End Function #End Region End Class End Namespace
xml
<?xml version="1.0" encoding="utf-8" ?> <!-- comments --> <rootNode xmlns:namespace="http://www.w3.org/TR/html4/"> <childNodes> <childNode attribute1 = "value" namespace:attribute2='value' attribute3=''/> <childNode /> <childNode /> <childNode /> <childNode attr1="value" attr2="10" attr3="hello" > value </childNode> <namespace:childNode> <![CDATA[ this is some CDATA content <!-- comments inside cdata --> <b alert='false'>tags inside cdata</b> ]]> value = "plain string outside" hello = world </namespace:childNode> </childNodes> </rootNode> <!-- Multiline comments <b>tag</b> -->