Compare commits

...

124 Commits

Author SHA1 Message Date
Joshua Peek
2696a9c5e7 Linguist 2.4.0 2012-12-10 09:47:42 -06:00
Joshua Peek
7c170972a0 Add shell samples 2012-12-10 09:45:54 -06:00
Joshua Peek
d00dfd82c1 Add samples for apache and nginx confs 2012-12-10 09:37:42 -06:00
Joshua Peek
9003139119 Can't have 2 same primary extensions 2012-12-10 09:30:55 -06:00
Joshua Peek
36e867ec76 Require newer pygments 2012-12-10 09:18:35 -06:00
Joshua Peek
cf4813979c Remove already defined extensions 2012-12-10 09:14:19 -06:00
Joshua Peek
7e12c3eff1 Update samples 2012-12-10 09:13:14 -06:00
Joshua Peek
281cc985bf Merge pull request #288 from wagenet/handlebars
Add Handlebars
2012-12-10 07:06:59 -08:00
Joshua Peek
dcc2be0781 Merge branch 'master' into dont-explode-on-invalid-shebang
Conflicts:
	lib/linguist/samples.json
	test/test_tokenizer.rb
2012-12-10 09:02:24 -06:00
Joshua Peek
161d076bfd Remove duplicate extension 2012-12-10 09:00:17 -06:00
Joshua Peek
09fbcc9a72 Merge pull request #298 from johanatan/master
Adds Elm.
2012-12-10 06:58:32 -08:00
Joshua Peek
ee2b92cf82 Merge pull request #307 from mislav/aliases
A couple of useful language aliases
2012-12-10 06:55:09 -08:00
Mislav Marohnić
720914b290 add filename tests for shell config files 2012-12-06 23:54:22 +01:00
Daniel Micay
16f8e54ed7 detect common shell config files 2012-12-06 23:53:55 +01:00
Andy Li
50ecb63058 haXe is now "Haxe"
According to https://groups.google.com/forum/#!topic/haxelang/O7PB-ZrX4i4/discussion

The lexer in Pygments is not renamed yet, so just stay as is at the moment.
2012-12-06 23:42:04 +01:00
Tobin Fricke
586650f01c add .C and .H as file extensions for C++
"C" and "H" are two file extensions recognized by gcc as indicating C++
source code. The full list may be found here:
http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Overall-Options.html#index-file-name-suffix-71
2012-12-06 23:28:32 +01:00
Mislav Marohnić
ae753e6e88 add Nginx language 2012-12-06 23:25:54 +01:00
Mislav Marohnić
04a2845e91 add ApacheConf language
Recognizes httpd/apache2.conf and .htaccess files
2012-12-06 23:25:29 +01:00
Mislav Marohnić
acb20d95ca "coffee-script" ☞ CoffeeScript 2012-12-06 23:04:53 +01:00
Mislav Marohnić
d3ebe1844d add HTTP language
Useful for `curl -i` dumps. Had to add primary_extension although this
data is usually not saved in files, but shown as code blocks.
2012-12-04 16:26:11 +01:00
Mislav Marohnić
fc8492e8f7 "yml" ☞ YAML 2012-12-04 16:11:52 +01:00
Mislav Marohnić
ff5ffd0482 "rss/xsd/xsl/wsdl" ☞ XML 2012-12-04 16:11:52 +01:00
Mislav Marohnić
50db6d0150 "latex" ☞ TeX 2012-12-04 16:11:52 +01:00
Mislav Marohnić
2e0b854428 "obj-j" ☞ Objective-J 2012-12-04 16:11:52 +01:00
Mislav Marohnić
1dfb44cff7 "obj-c/objc" ☞ Objective-C 2012-12-04 16:11:51 +01:00
Mislav Marohnić
0a8fad2040 "make" ☞ Makefile 2012-12-04 16:11:51 +01:00
Mislav Marohnić
9b97d3ac8a "erb" ☞ RHTML 2012-12-04 16:11:51 +01:00
Mislav Marohnić
26e78c0c1b "xhtml" ☞ HTML 2012-12-04 16:11:51 +01:00
Joshua Peek
b036e8d3c2 Merge pull request #305 from DominikTo/php-cli
Fixed detection of PHP CLI scripts (added samples)
2012-12-02 07:54:14 -08:00
Dominik Tobschall
f84a904ad8 fixed typo 2012-12-02 14:11:04 +01:00
Dominik Tobschall
b1684037d6 added php cli samples 2012-12-02 14:05:52 +01:00
Jonathan Leonard
1c85d0b38a Added Elm. 2012-11-25 20:39:58 -08:00
Ben Lavender
ec3434cf1d Don't explode on invalid shebang 2012-11-18 20:56:06 -06:00
Peter Wagenet
0e20f6d454 Added Handlebars language 2012-11-12 17:16:18 -08:00
Joshua Peek
d92d208a45 Fix tests for pygments.rb 0.3.x 2012-10-07 15:39:02 -05:00
Joshua Peek
b798e28bfb No warnings 2012-10-07 15:37:09 -05:00
Joshua Peek
ebd6077cd7 Add wrap flag to text languages 2012-10-07 15:34:13 -05:00
Joshua Peek
9e9500dfa9 Linguist 2.3.4 2012-09-24 10:54:17 -05:00
Joshua Peek
04cc100fba Rebuild samples db 2012-09-24 10:52:05 -05:00
Joshua Peek
31e33f99f2 Ensure lang is skipped on any binary file 2012-09-24 10:51:39 -05:00
Joshua Peek
7c51b90586 Skip empty sample 2012-09-24 10:50:49 -05:00
Joshua Peek
2b36f73da6 Some comments are triggering charlock binary 2012-09-24 10:48:22 -05:00
Joshua Peek
d96dd473b8 Rebuild samples db 2012-09-24 10:12:18 -05:00
Joshua Peek
f9066ffb7b Sort exts and filenames 2012-09-24 10:12:05 -05:00
Joshua Peek
945941d529 Update samples db 2012-09-24 10:07:58 -05:00
Joshua Peek
10e875e899 Print out samples db diffs 2012-09-24 10:07:08 -05:00
Justin Palmer
d24e5c938e sample directory needs uppercase E 2012-09-20 15:23:58 -07:00
Justin Palmer
aa069a336f add color to ecl language 2012-09-20 15:16:06 -07:00
Justin Palmer
662fc2ee9d Merge remote-tracking branch 'rengolin/ecl' 2012-09-20 15:07:41 -07:00
Ryan Tomayko
567cd6ef68 Merge pull request #250 from github/mac-format
Handle Mac Format when splitting lines
2012-09-11 14:17:21 -07:00
Ryan Tomayko
887a050db9 Only search the first 4K chars for \r 2012-09-10 01:56:08 -07:00
Ryan Tomayko
bda895eaae Test Mac Format detection and line splitting 2012-09-10 01:52:30 -07:00
Ryan Tomayko
2e49c06f47 Handle Mac Format when splitting lines 2012-09-10 01:05:48 -07:00
Joshua Peek
ae137847b4 Linguist 2.3.3 2012-09-04 09:32:21 -05:00
Scott J. Goldman
5443dc50a3 Merge pull request #247 from github/check-size-first
When testing if a blob is indexable or safe to colorize, check size first
2012-09-02 00:09:51 -07:00
Scott J. Goldman
fc435a2541 Linguist 2.3.2 2012-09-02 00:08:37 -07:00
Scott J. Goldman
04394750e7 When testing if a blob is safe to colorize, check size first
Similar to e415a13
2012-09-02 00:08:37 -07:00
Scott J. Goldman
e415a1351b When testing if a blob is indexable, check size first
Otherwise, charlock_holmes will allocate another large binary
buffer for testing the encoding, which is a problem if the binary
blob is many hundreds of MB large. It'll just fail and crash ruby.
2012-08-31 22:47:19 -07:00
Joshua Peek
6ec907a915 Merge pull request #245 from jcazevedo/master
Add Shell sample
2012-08-28 10:55:11 -07:00
Joao Azevedo
1f55f01fa9 Add Shell sample 2012-08-28 18:01:46 +01:00
Joshua Peek
5d79b88875 Linguist 2.3.1 2012-08-27 11:34:55 -05:00
Joshua Peek
458890b4b9 Add C++ sample 2012-08-27 11:33:28 -05:00
Joshua Peek
89267f792d Rebuild samples db 2012-08-27 11:30:44 -05:00
Joshua Peek
b183fcca05 Only read up to 100KB 2012-08-27 11:30:38 -05:00
Joshua Peek
684a57dbc0 Add another C sample 2012-08-27 11:21:57 -05:00
Joshua Peek
400086a5c8 Add more C samples
Closes #237
2012-08-23 13:38:16 -05:00
Joshua Peek
38b966a554 Linguist 2.3.0 2012-08-20 11:50:35 -05:00
Joshua Peek
31b0df67b7 Require newer mime-type gem 2012-08-20 11:42:04 -05:00
Joshua Peek
cfe496e9fc Drop mime type module
Closes #206
2012-08-20 11:40:32 -05:00
Joshua Peek
b85aeaad3e Inline mime type lookup into blob helper 2012-08-20 11:33:16 -05:00
Joshua Peek
64f3509222 Remove other mime type hacks 2012-08-20 11:29:22 -05:00
Joshua Peek
f8df871d85 Only double check binary mime type when lazy loading blob 2012-08-20 11:20:37 -05:00
Joshua Peek
620150d188 Only double check with binary mime type when lazy loading blob 2012-08-20 11:14:45 -05:00
Joshua Peek
630dca515a Trim down mime type overrides that are old or now pushed upstream
Related #206
2012-08-20 11:11:42 -05:00
Joshua Peek
d2de997fcc Add more Prolog samples
Closes #233
2012-08-20 10:48:36 -05:00
Joshua Peek
b8711f8ccf Merge pull request #228 from github/cpp-samples
Add more C++ samples
2012-08-20 08:36:10 -07:00
Joshua Peek
34aaab19b2 Rebuild samples db 2012-08-20 10:34:37 -05:00
Joshua Peek
220108857c Skip emiting comment tokens 2012-08-20 10:34:07 -05:00
Joshua Peek
657adaabec Add more C++ samples
Closes #225
2012-08-15 11:57:55 -07:00
Joshua Peek
a41f40a30e Remove extname from bin out 2012-08-15 09:31:01 -07:00
Joshua Peek
080cd097ba Merge branch 'brcooley-master' 2012-08-13 18:18:04 -07:00
Joshua Peek
866e446dbe Rebuild samples db 2012-08-13 18:17:47 -07:00
Joshua Peek
897f39083d Rename to magic .script! ext 2012-08-13 18:17:44 -07:00
brc
f8a7d11808 Adding extensionless script to Shell samples 2012-08-13 18:07:28 -07:00
Joshua Peek
ed70d29943 Linguist 2.2.1 2012-08-07 10:39:29 -05:00
Joshua Peek
dbb089f610 Fix nil data passed to generated 2012-08-07 10:39:08 -05:00
Joshua Peek
23357736b1 Merge branch 'kassi-master' 2012-08-06 10:23:12 -05:00
Joshua Peek
a35fa88f50 Add more applescript samples 2012-08-06 10:22:38 -05:00
Joshua Peek
a13f246e4f Update samples db 2012-08-06 09:54:40 -05:00
Karsten Silkenbäumer
f55e53c650 Removed scpt sample due to binary file format (extension) 2012-08-06 16:49:09 +02:00
Karsten Silkenbäumer
b6a7b41783 Change primary extension for applescript 2012-08-05 23:51:24 +02:00
Karsten Silkenbäumer
704a3e03d6 Add type programming to applescript 2012-08-05 23:48:26 +02:00
Joshua Peek
566eaefda9 Linguist 2.2.0 2012-08-03 16:47:34 -05:00
Joshua Peek
047d23862e Still index .txt 2012-08-03 16:34:53 -05:00
Joshua Peek
804e23e995 Extract seperate language detection method 2012-08-03 16:03:06 -05:00
Joshua Peek
41b7d13aa7 Extract generated blob check into its own module 2012-08-03 15:47:50 -05:00
Joshua Peek
4531103033 Forgot to move hidden samples to the correct dir 2012-08-03 15:25:38 -05:00
Joshua Peek
96267e8696 Sort test assertion 2012-08-03 15:11:30 -05:00
Joshua Peek
16a67cb852 Move shebang detection into classifier
Fixes #203
2012-08-03 15:07:36 -05:00
Joshua Peek
fbbaff09cd Stop treating text as a language 2012-08-03 13:55:51 -05:00
Joshua Peek
6014bd015e Change find_by_filename api to return all matching languages 2012-08-03 13:53:12 -05:00
Joshua Peek
4a06d2ea7e Merge branch 'jeanSapristi-master' 2012-07-24 11:51:54 -05:00
Joshua Peek
22efcf7aff Update samples db 2012-07-24 11:51:37 -05:00
Joshua Peek
e5d302459f Fix tokenzing empty strings 2012-07-24 11:49:29 -05:00
Joshua Peek
7aac87681b Add brackets to tokens 2012-07-24 11:28:46 -05:00
Joshua Peek
53300ca581 Add brackets to tokens 2012-07-24 11:28:27 -05:00
Joshua Peek
52833b58d5 Rebuild samples db 2012-07-24 11:23:42 -05:00
Joshua Peek
f5705eaf38 Parse float tokens 2012-07-24 11:23:06 -05:00
Joshua Peek
e2a91bba3e json extension is provided by samples 2012-07-24 11:12:57 -05:00
Joshua Peek
be1340bafc Add a few more json samples 2012-07-24 11:12:33 -05:00
Joshua Peek
9777798cf7 Move max json into json samples 2012-07-24 11:10:57 -05:00
Joshua Peek
b7c4d96e5f Max extensions are already covered by samples 2012-07-24 11:05:08 -05:00
Joshua Peek
e816a0a1b1 Update samples db 2012-07-24 11:04:24 -05:00
Joshua Peek
1bc9f555e6 Fix max samples dir 2012-07-24 11:03:34 -05:00
Joshua Peek
059f661eb6 Rename Max/MSP to Max 2012-07-24 11:03:09 -05:00
jeanSapristi
efbcd51ff6 Add samples for MaxMSP 2012-07-24 17:40:04 +02:00
Nicolas Danet
9f782fc261 Update lib/linguist/languages.yml 2012-07-24 12:25:03 +03:00
Nicolas Danet
5c2bdfd733 Add extensions for Max/MSP 2012-07-24 09:03:06 +03:00
Joshua Peek
ade20e4b46 Linguist 2.1.2 2012-07-23 17:20:36 -05:00
Joshua Peek
aedbe1d5b7 Rebuild samples db 2012-07-23 17:20:05 -05:00
Joshua Peek
65d05e02c9 name can be nil 2012-07-23 17:19:11 -05:00
Joshua Peek
b4378ca89f Linguist 2.1.1 2012-07-23 16:59:19 -05:00
Joshua Peek
12b27deb78 Allow for newer version of pygments.rb 2012-07-23 16:58:57 -05:00
Renato Golin
da6cf8dbb4 Add ECL programming language and test 2012-07-12 09:09:32 +01:00
110 changed files with 30107 additions and 9974 deletions

View File

@@ -3,9 +3,7 @@ require 'rake/testtask'
task :default => :test
Rake::TestTask.new do |t|
t.warning = true
end
Rake::TestTask.new
task :samples do
require 'linguist/samples'

View File

@@ -23,7 +23,6 @@ elsif File.file?(path)
puts "#{blob.name}: #{blob.loc} lines (#{blob.sloc} sloc)"
puts " type: #{type}"
puts " extension: #{blob.pathname.extname}"
puts " mime type: #{blob.mime_type}"
puts " language: #{blob.language}"

View File

@@ -1,6 +1,6 @@
Gem::Specification.new do |s|
s.name = 'github-linguist'
s.version = '2.1.0'
s.version = '2.4.0'
s.summary = "GitHub Language detection"
s.authors = "GitHub"
@@ -10,8 +10,9 @@ Gem::Specification.new do |s|
s.add_dependency 'charlock_holmes', '~> 0.6.6'
s.add_dependency 'escape_utils', '~> 0.2.3'
s.add_dependency 'mime-types', '~> 1.18'
s.add_dependency 'pygments.rb', '~> 0.2.13'
s.add_dependency 'mime-types', '~> 1.19'
s.add_dependency 'pygments.rb', '>= 0.3.0'
s.add_development_dependency 'mocha'
s.add_development_dependency 'json'
s.add_development_dependency 'rake'
s.add_development_dependency 'yajl-ruby'

View File

@@ -1,5 +1,5 @@
require 'linguist/blob_helper'
require 'linguist/generated'
require 'linguist/language'
require 'linguist/mime'
require 'linguist/repository'
require 'linguist/samples'

View File

@@ -1,10 +1,9 @@
require 'linguist/classifier'
require 'linguist/generated'
require 'linguist/language'
require 'linguist/mime'
require 'linguist/samples'
require 'charlock_holmes'
require 'escape_utils'
require 'mime/types'
require 'pygments'
require 'yaml'
@@ -21,7 +20,23 @@ module Linguist
#
# Returns a String
def extname
File.extname(name)
File.extname(name.to_s)
end
# Internal: Lookup mime type for extension.
#
# Returns a MIME::Type
def _mime_type
if defined? @_mime_type
@_mime_type
else
guesses = ::MIME::Types.type_for(extname.to_s)
# Prefer text mime types over binary
@_mime_type = guesses.detect { |type| type.ascii? } ||
# Otherwise use the first guess
guesses.first
end
end
# Public: Get the actual blob mime type
@@ -33,7 +48,14 @@ module Linguist
#
# Returns a mime type String.
def mime_type
@mime_type ||= Mime.mime_for(extname)
_mime_type ? _mime_type.to_s : 'text/plain'
end
# Internal: Is the blob binary according to its mime type
#
# Return true or false
def binary_mime_type?
_mime_type ? _mime_type.binary? : false
end
# Public: Get the Content-Type header value
@@ -84,15 +106,6 @@ module Linguist
@detect_encoding ||= CharlockHolmes::EncodingDetector.new.detect(data) if data
end
# Public: Is the blob binary according to its mime type
#
# Return true or false
def binary_mime_type?
if mime_type = Mime.lookup_mime_type_for(extname)
mime_type.binary?
end
end
# Public: Is the blob binary?
#
# Return true or false
@@ -129,15 +142,6 @@ module Linguist
['.png', '.jpg', '.jpeg', '.gif'].include?(extname)
end
# Public: Is the blob likely to have a shebang?
#
# Return true or false
def shebang_extname?
extname.empty? &&
mode &&
(mode.to_i(8) & 05) == 05
end
MEGABYTE = 1024 * 1024
# Public: Is the blob too big to load?
@@ -156,7 +160,7 @@ module Linguist
#
# Return true or false
def safe_to_colorize?
text? && !large? && !high_ratio_of_long_lines?
!large? && text? && !high_ratio_of_long_lines?
end
# Internal: Does the blob have a ratio of long lines?
@@ -200,7 +204,31 @@ module Linguist
#
# Returns an Array of lines
def lines
@lines ||= (viewable? && data) ? data.split("\n", -1) : []
@lines ||=
if viewable? && data
data.split(line_split_character, -1)
else
[]
end
end
# Character used to split lines. This is almost always "\n" except when Mac
# Format is detected in which case it's "\r".
#
# Returns a split pattern string.
def line_split_character
@line_split_character ||= (mac_format?? "\r" : "\n")
end
# Public: Is the data in ** Mac Format **. This format uses \r (0x0d) characters
# for line ends and does not include a \n (0x0a).
#
# Returns true when mac format is detected.
def mac_format?
return if !viewable?
if pos = data[0, 4096].index("\r")
data[pos + 1] != ?\n
end
end
# Public: Get number of lines of code
@@ -221,143 +249,16 @@ module Linguist
lines.grep(/\S/).size
end
# Internal: Compute average line length.
#
# Returns Integer.
def average_line_length
if lines.any?
lines.inject(0) { |n, l| n += l.length } / lines.length
else
0
end
end
# Public: Is the blob a generated file?
#
# Generated source code is supressed in diffs and is ignored by
# language statistics.
#
# Requires Blob#data
#
# Includes:
# - XCode project XML files
# - Minified JavaScript
# - Compiled CoffeeScript
# - PEG.js-generated parsers
#
# Please add additional test coverage to
# `test/test_blob.rb#test_generated` if you make any changes.
# May load Blob#data
#
# Return true or false
def generated?
if name == 'Gemfile.lock' || minified_javascript? || compiled_coffeescript? ||
xcode_project_file? || generated_net_docfile? || generated_parser?
true
else
false
end
end
# Internal: Is the blob an XCode project file?
#
# Generated if the file extension is an XCode project
# file extension.
#
# Returns true of false.
def xcode_project_file?
['.xib', '.nib', '.storyboard', '.pbxproj', '.xcworkspacedata', '.xcuserstate'].include?(extname)
end
# Internal: Is the blob minified JS?
#
# Consider JS minified if the average line length is
# greater then 100c.
#
# Returns true or false.
def minified_javascript?
return unless extname == '.js'
average_line_length > 100
end
# Internal: Is the blob of JS a parser generated by PEG.js?
#
# Requires Blob#data
#
# PEG.js-generated parsers are not meant to be consumed by humans.
#
# Return true or false
def generated_parser?
return false unless extname == '.js'
# PEG.js-generated parsers include a comment near the top of the file
# that marks them as such.
if lines[0..4].join('') =~ /^(?:[^\/]|\/[^\*])*\/\*(?:[^\*]|\*[^\/])*Generated by PEG.js/
return true
end
false
end
# Internal: Is the blob of JS generated by CoffeeScript?
#
# Requires Blob#data
#
# CoffeScript is meant to output JS that would be difficult to
# tell if it was generated or not. Look for a number of patterns
# output by the CS compiler.
#
# Return true or false
def compiled_coffeescript?
return false unless extname == '.js'
# CoffeeScript generated by > 1.2 include a comment on the first line
if lines[0] =~ /^\/\/ Generated by /
return true
end
if lines[0] == '(function() {' && # First line is module closure opening
lines[-2] == '}).call(this);' && # Second to last line closes module closure
lines[-1] == '' # Last line is blank
score = 0
lines.each do |line|
if line =~ /var /
# Underscored temp vars are likely to be Coffee
score += 1 * line.gsub(/(_fn|_i|_len|_ref|_results)/).count
# bind and extend functions are very Coffee specific
score += 3 * line.gsub(/(__bind|__extends|__hasProp|__indexOf|__slice)/).count
end
end
# Require a score of 3. This is fairly arbitrary. Consider
# tweaking later.
score >= 3
else
false
end
end
# Internal: Is this a generated documentation file for a .NET assembly?
#
# Requires Blob#data
#
# .NET developers often check in the XML Intellisense file along with an
# assembly - however, these don't have a special extension, so we have to
# dig into the contents to determine if it's a docfile. Luckily, these files
# are extremely structured, so recognizing them is easy.
#
# Returns true or false
def generated_net_docfile?
return false unless extname.downcase == ".xml"
return false unless lines.count > 3
# .NET Docfiles always open with <doc> and their first tag is an
# <assembly> tag
return lines[1].include?("<doc>") &&
lines[2].include?("<assembly>") &&
lines[-2].include?("</doc>")
@_generated ||= Generated.generated?(name, lambda { data })
end
# Public: Should the blob be indexed for searching?
@@ -373,16 +274,18 @@ module Linguist
#
# Return true or false
def indexable?
if binary?
if size > 100 * 1024
false
elsif binary?
false
elsif extname == '.txt'
true
elsif language.nil?
false
elsif !language.searchable?
false
elsif generated?
false
elsif size > 100 * 1024
false
else
true
end
@@ -394,30 +297,15 @@ module Linguist
#
# Returns a Language or nil if none is detected
def language
if defined? @language
@language
return @language if defined? @language
if defined?(@data) && @data.is_a?(String)
data = @data
else
@language = guess_language
data = lambda { (binary_mime_type? || binary?) ? "" : self.data }
end
end
# Internal: Guess language
#
# Please add additional test coverage to
# `test/test_blob.rb#test_language` if you make any changes.
#
# Returns a Language or nil
def guess_language
return if binary_mime_type?
# Disambiguate between multiple language extensions
disambiguate_extension_language ||
# See if there is a Language for the extension
Language.find_by_filename(name) ||
# Try to detect Language from shebang line
shebang_language
@language = Language.detect(name.to_s, data, mode)
end
# Internal: Get the lexer of the blob.
@@ -427,86 +315,6 @@ module Linguist
language ? language.lexer : Pygments::Lexer.find_by_name('Text only')
end
# Internal: Disambiguates between multiple language extensions.
#
# Returns a Language or nil.
def disambiguate_extension_language
if Language.ambiguous?(extname)
possible_languages = Language.all.select { |l| l.extensions.include?(extname) }.map(&:name)
if possible_languages.any?
if result = Classifier.classify(Samples::DATA, data, possible_languages).first
Language[result[0]]
end
end
end
end
# Internal: Extract the script name from the shebang line
#
# Requires Blob#data
#
# Examples
#
# '#!/usr/bin/ruby'
# # => 'ruby'
#
# '#!/usr/bin/env ruby'
# # => 'ruby'
#
# '#!/usr/bash/python2.4'
# # => 'python'
#
# Please add additional test coverage to
# `test/test_blob.rb#test_shebang_script` if you make any changes.
#
# Returns a script name String or nil
def shebang_script
# Fail fast if blob isn't viewable?
return unless viewable?
if lines.any? && (match = lines[0].match(/(.+)\n?/)) && (bang = match[0]) =~ /^#!/
bang.sub!(/^#! /, '#!')
tokens = bang.split(' ')
pieces = tokens.first.split('/')
if pieces.size > 1
script = pieces.last
else
script = pieces.first.sub('#!', '')
end
script = script == 'env' ? tokens[1] : script
# python2.4 => python
if script =~ /((?:\d+\.?)+)/
script.sub! $1, ''
end
# Check for multiline shebang hacks that exec themselves
#
# #!/bin/sh
# exec foo "$0" "$@"
#
if script == 'sh' &&
lines[0...5].any? { |l| l.match(/exec (\w+).+\$0.+\$@/) }
script = $1
end
script
end
end
# Internal: Get Language for shebang script
#
# Returns the Language or nil
def shebang_language
# Skip file extensions unlikely to have shebangs
return unless shebang_extname?
if script = shebang_script
Language[script]
end
end
# Public: Highlight syntax of blob
#
# options - A Hash of options (defaults to {})

162
lib/linguist/generated.rb Normal file
View File

@@ -0,0 +1,162 @@
module Linguist
class Generated
# Public: Is the blob a generated file?
#
# name - String filename
# data - String blob data. A block also maybe passed in for lazy
# loading. This behavior is deprecated and you should always
# pass in a String.
#
# Return true or false
def self.generated?(name, data)
new(name, data).generated?
end
# Internal: Initialize Generated instance
#
# name - String filename
# data - String blob data
def initialize(name, data)
@name = name
@extname = File.extname(name)
@_data = data
end
attr_reader :name, :extname
# Lazy load blob data if block was passed in.
#
# Awful, awful stuff happening here.
#
# Returns String data.
def data
@data ||= @_data.respond_to?(:call) ? @_data.call() : @_data
end
# Public: Get each line of data
#
# Returns an Array of lines
def lines
# TODO: data should be required to be a String, no nils
@lines ||= data ? data.split("\n", -1) : []
end
# Internal: Is the blob a generated file?
#
# Generated source code is supressed in diffs and is ignored by
# language statistics.
#
# Please add additional test coverage to
# `test/test_blob.rb#test_generated` if you make any changes.
#
# Return true or false
def generated?
name == 'Gemfile.lock' ||
minified_javascript? ||
compiled_coffeescript? ||
xcode_project_file? ||
generated_net_docfile? ||
generated_parser?
end
# Internal: Is the blob an XCode project file?
#
# Generated if the file extension is an XCode project
# file extension.
#
# Returns true of false.
def xcode_project_file?
['.xib', '.nib', '.storyboard', '.pbxproj', '.xcworkspacedata', '.xcuserstate'].include?(extname)
end
# Internal: Is the blob minified JS?
#
# Consider JS minified if the average line length is
# greater then 100c.
#
# Returns true or false.
def minified_javascript?
return unless extname == '.js'
if lines.any?
(lines.inject(0) { |n, l| n += l.length } / lines.length) > 100
else
false
end
end
# Internal: Is the blob of JS generated by CoffeeScript?
#
# CoffeScript is meant to output JS that would be difficult to
# tell if it was generated or not. Look for a number of patterns
# output by the CS compiler.
#
# Return true or false
def compiled_coffeescript?
return false unless extname == '.js'
# CoffeeScript generated by > 1.2 include a comment on the first line
if lines[0] =~ /^\/\/ Generated by /
return true
end
if lines[0] == '(function() {' && # First line is module closure opening
lines[-2] == '}).call(this);' && # Second to last line closes module closure
lines[-1] == '' # Last line is blank
score = 0
lines.each do |line|
if line =~ /var /
# Underscored temp vars are likely to be Coffee
score += 1 * line.gsub(/(_fn|_i|_len|_ref|_results)/).count
# bind and extend functions are very Coffee specific
score += 3 * line.gsub(/(__bind|__extends|__hasProp|__indexOf|__slice)/).count
end
end
# Require a score of 3. This is fairly arbitrary. Consider
# tweaking later.
score >= 3
else
false
end
end
# Internal: Is this a generated documentation file for a .NET assembly?
#
# .NET developers often check in the XML Intellisense file along with an
# assembly - however, these don't have a special extension, so we have to
# dig into the contents to determine if it's a docfile. Luckily, these files
# are extremely structured, so recognizing them is easy.
#
# Returns true or false
def generated_net_docfile?
return false unless extname.downcase == ".xml"
return false unless lines.count > 3
# .NET Docfiles always open with <doc> and their first tag is an
# <assembly> tag
return lines[1].include?("<doc>") &&
lines[2].include?("<assembly>") &&
lines[-2].include?("</doc>")
end
# Internal: Is the blob of JS a parser generated by PEG.js?
#
# PEG.js-generated parsers are not meant to be consumed by humans.
#
# Return true or false
def generated_parser?
return false unless extname == '.js'
# PEG.js-generated parsers include a comment near the top of the file
# that marks them as such.
if lines[0..4].join('') =~ /^(?:[^\/]|\/[^\*])*\/\*(?:[^\*]|\*[^\/])*Generated by PEG.js/
return true
end
false
end
end
end

View File

@@ -2,6 +2,7 @@ require 'escape_utils'
require 'pygments'
require 'yaml'
require 'linguist/classifier'
require 'linguist/samples'
module Linguist
@@ -11,23 +12,15 @@ module Linguist
# Languages are defined in `lib/linguist/languages.yml`.
class Language
@languages = []
@overrides = {}
@index = {}
@name_index = {}
@alias_index = {}
@extension_index = {}
@filename_index = {}
@extension_index = Hash.new { |h,k| h[k] = [] }
@filename_index = Hash.new { |h,k| h[k] = [] }
# Valid Languages types
TYPES = [:data, :markup, :programming]
# Internal: Test if extension maps to multiple Languages.
#
# Returns true or false.
def self.ambiguous?(extension)
@overrides.include?(extension)
end
# Internal: Create a new Language object
#
# attributes - A hash of attributes
@@ -60,34 +53,47 @@ module Linguist
raise ArgumentError, "Extension is missing a '.': #{extension.inspect}"
end
unless ambiguous?(extension)
# Index the extension with a leading ".": ".rb"
@extension_index[extension] = language
# Index the extension without a leading ".": "rb"
@extension_index[extension.sub(/^\./, '')] = language
end
end
language.overrides.each do |extension|
if extension !~ /^\./
raise ArgumentError, "Extension is missing a '.': #{extension.inspect}"
end
if l = @overrides[extension]
raise ArgumentError, "#{extension} is already overridden by #{l.name}"
end
@overrides[extension] = language
@extension_index[extension] << language
end
language.filenames.each do |filename|
@filename_index[filename] = language
@filename_index[filename] << language
end
language
end
# Public: Detects the Language of the blob.
#
# name - String filename
# data - String blob data. A block also maybe passed in for lazy
# loading. This behavior is deprecated and you should always
# pass in a String.
# mode - Optional String mode (defaults to nil)
#
# Returns Language or nil.
def self.detect(name, data, mode = nil)
# A bit of an elegant hack. If the file is exectable but extensionless,
# append a "magic" extension so it can be classified with other
# languages that have shebang scripts.
if File.extname(name).empty? && mode && (mode.to_i(8) & 05) == 05
name += ".script!"
end
possible_languages = find_by_filename(name)
if possible_languages.length > 1
data = data.call() if data.respond_to?(:call)
if data.nil? || data == ""
nil
elsif result = Classifier.classify(Samples::DATA, data, possible_languages.map(&:name)).first
Language[result[0]]
end
else
possible_languages.first
end
end
# Public: Get all Languages
#
# Returns an Array of Languages
@@ -123,33 +129,19 @@ module Linguist
@alias_index[name]
end
# Public: Look up Language by extension.
#
# extension - The extension String. May include leading "."
#
# Examples
#
# Language.find_by_extension('.rb')
# # => #<Language name="Ruby">
#
# Returns the Language or nil if none was found.
def self.find_by_extension(extension)
@extension_index[extension]
end
# Public: Look up Language by filename.
# Public: Look up Languages by filename.
#
# filename - The path String.
#
# Examples
#
# Language.find_by_filename('foo.rb')
# # => #<Language name="Ruby">
# # => [#<Language name="Ruby">]
#
# Returns the Language or nil if none was found.
# Returns all matching Languages or [] if none were found.
def self.find_by_filename(filename)
basename, extname = File.basename(filename), File.extname(filename)
@filename_index[basename] || @extension_index[extname]
@filename_index[basename] + @extension_index[extname]
end
# Public: Look up Language by its name or lexer.
@@ -230,13 +222,13 @@ module Linguist
raise(ArgumentError, "#{@name} is missing lexer")
@ace_mode = attributes[:ace_mode]
@wrap = attributes[:wrap] || false
# Set legacy search term
@search_term = attributes[:search_term] || default_alias_name
# Set extensions or default to [].
@extensions = attributes[:extensions] || []
@overrides = attributes[:overrides] || []
@filenames = attributes[:filenames] || []
unless @primary_extension = attributes[:primary_extension]
@@ -321,6 +313,11 @@ module Linguist
# Returns a String name or nil
attr_reader :ace_mode
# Public: Should language lines be wrapped
#
# Returns true or false
attr_reader :wrap
# Public: Get extensions
#
# Examples
@@ -344,11 +341,6 @@ module Linguist
# Returns the extension String.
attr_reader :primary_extension
# Internal: Get overridden extensions.
#
# Returns the extensions Array.
attr_reader :overrides
# Public: Get filenames
#
# Examples
@@ -476,12 +468,12 @@ module Linguist
:aliases => options['aliases'],
:lexer => options['lexer'],
:ace_mode => options['ace_mode'],
:wrap => options['wrap'],
:group_name => options['group'],
:searchable => options.key?('searchable') ? options['searchable'] : true,
:search_term => options['search_term'],
:extensions => options['extensions'].sort,
:primary_extension => options['primary_extension'],
:overrides => options['overrides'],
:filenames => options['filenames'],
:popular => popular.include?(name)
)

View File

@@ -10,12 +10,12 @@
# aliases - An Array of additional aliases (implicitly
# includes name.downcase)
# ace_mode - A String name of Ace Mode (if available)
# wrap - Boolean wrap to enable line wrapping (default: false)
# extension - An Array of associated extensions
# primary_extension - A String for the main extension associated with
# the language. Must be unique. Used when a Language is picked
# from a dropdown and we need to automatically choose an
# extension.
# overrides - An Array of extensions that takes precedence over conflicts
# searchable - Boolean flag to enable searching (defaults to true)
# search_term - Deprecated: Some languages maybe indexed under a
# different alias. Avoid defining new exceptions.
@@ -63,17 +63,22 @@ Ada:
- .adb
- .ads
ApacheConf:
type: markup
aliases:
- apache
primary_extension: .apacheconf
Apex:
type: programming
lexer: Text only
primary_extension: .cls
overrides:
- .cls
AppleScript:
type: programming
aliases:
- osascript
primary_extension: .scpt
primary_extension: .applescript
Arc:
type: programming
@@ -157,8 +162,6 @@ Bro:
C:
type: programming
color: "#555"
overrides:
- .h
primary_extension: .c
extensions:
- .w
@@ -183,8 +186,10 @@ C++:
- cpp
primary_extension: .cpp
extensions:
- .C
- .c++
- .cxx
- .H
- .h++
- .hh
- .hxx
@@ -247,6 +252,7 @@ CoffeeScript:
color: "#244776"
aliases:
- coffee
- coffee-script
primary_extension: .coffee
extensions:
- ._coffee
@@ -371,6 +377,14 @@ Ecere Projects:
extensions:
- .epj
Ecl:
type: programming
color: "#8a1267"
primary_extension: .ecl
lexer: ECL
extensions:
- .eclxml
Eiffel:
type: programming
lexer: Text only
@@ -387,6 +401,12 @@ Elixir:
- .ex
- .exs
Elm:
type: programming
lexer: Haskell
group: Haskell
primary_extension: .elm
Emacs Lisp:
type: programming
lexer: Scheme
@@ -533,8 +553,6 @@ Groovy:
Groovy Server Pages:
group: Groovy
lexer: Java Server Page
overrides:
- .gsp
aliases:
- gsp
primary_extension: .gsp
@@ -542,6 +560,8 @@ Groovy Server Pages:
HTML:
type: markup
ace_mode: html
aliases:
- xhtml
primary_extension: .html
extensions:
- .htm
@@ -560,6 +580,8 @@ HTML+ERB:
type: markup
group: HTML
lexer: RHTML
aliases:
- erb
primary_extension: .erb
extensions:
- .erb
@@ -572,22 +594,20 @@ HTML+PHP:
extensions:
- .phtml
HaXe:
type: programming
lexer: haXe
ace_mode: haxe
color: "#346d51"
primary_extension: .hx
extensions:
- .hx
- .hxml
- .mtt
HTTP:
type: data
primary_extension: .http
Haml:
group: HTML
type: markup
primary_extension: .haml
Handlebars:
type: markup
lexer: Text only
primary_extension: .handlebars
Haskell:
type: programming
color: "#29b544"
@@ -596,6 +616,15 @@ Haskell:
- .hs
- .hsc
Haxe:
type: programming
lexer: haXe
ace_mode: haxe
color: "#346d51"
primary_extension: .hx
extensions:
- .hxsl
INI:
type: data
extensions:
@@ -604,8 +633,6 @@ INI:
- .prefs
- .properties
primary_extension: .ini
filenames:
- .gitconfig
IRC log:
lexer: IRC logs
@@ -634,8 +661,6 @@ JSON:
ace_mode: json
searchable: false
primary_extension: .json
extensions:
- .json
Java:
type: programming
@@ -724,6 +749,8 @@ Lua:
- .nse
Makefile:
aliases:
- make
extensions:
- .mak
- .mk
@@ -743,6 +770,7 @@ Markdown:
type: markup
lexer: Text only
ace_mode: markdown
wrap: true
primary_extension: .md
extensions:
- .markdown
@@ -757,13 +785,15 @@ Matlab:
extensions:
- .matlab
Max/MSP:
Max:
type: programming
color: "#ce279c"
lexer: Text only
aliases:
- max/msp
- maxmsp
search_term: max/msp
primary_extension: .mxt
extensions:
- .mxt
MiniD: # Legacy
searchable: false
@@ -796,6 +826,11 @@ Nemerle:
color: "#0d3c6e"
primary_extension: .n
Nginx:
type: markup
lexer: Nginx configuration file
primary_extension: .nginxconf
Nimrod:
type: programming
color: "#37775b"
@@ -841,8 +876,9 @@ ObjDump:
Objective-C:
type: programming
color: "#438eff"
overrides:
- .m
aliases:
- obj-c
- objc
primary_extension: .m
extensions:
- .mm
@@ -850,6 +886,8 @@ Objective-C:
Objective-J:
type: programming
color: "#ff0c5a"
aliases:
- obj-j
primary_extension: .j
extensions:
- .j
@@ -915,8 +953,6 @@ Perl:
ace_mode: perl
color: "#0298c3"
primary_extension: .pl
overrides:
- .pl
extensions:
- .PL
- .perl
@@ -983,8 +1019,6 @@ R:
type: programming
color: "#198ce7"
lexer: S
overrides:
- .r
primary_extension: .r
extensions:
- .r
@@ -1128,15 +1162,6 @@ Shell:
- bash
- zsh
primary_extension: .sh
filenames:
- .bash_profile
- .bashrc
- .profile
- .zlogin
- .zsh
- .zshrc
- bashrc
- zshrc
Smalltalk:
type: programming
@@ -1181,6 +1206,8 @@ Tcsh:
TeX:
type: markup
ace_mode: latex
aliases:
- latex
primary_extension: .tex
extensions:
- .aux
@@ -1195,18 +1222,11 @@ Tea:
type: markup
primary_extension: .tea
Text:
type: data
lexer: Text only
ace_mode: text
primary_extension: .txt
extensions:
- .txt
Textile:
type: markup
lexer: Text only
ace_mode: textile
wrap: true
primary_extension: .textile
extensions:
- .textile
@@ -1216,8 +1236,6 @@ Turing:
color: "#45f715"
lexer: Text only
primary_extension: .t
overrides:
- .t
extensions:
- .tu
@@ -1249,8 +1267,6 @@ Verilog:
type: programming
lexer: verilog
color: "#848bf3"
overrides:
- .v
primary_extension: .v
VimL:
@@ -1263,8 +1279,6 @@ VimL:
extensions:
- .vim
filenames:
- .gvimrc
- .vimrc
- vimrc
- gvimrc
@@ -1283,6 +1297,11 @@ Visual Basic:
XML:
type: markup
ace_mode: xml
aliases:
- rss
- xsd
- xsl
- wsdl
primary_extension: .xml
extensions:
- .glade
@@ -1328,12 +1347,12 @@ XSLT:
YAML:
type: markup
aliases:
- yml
primary_extension: .yml
extensions:
- .yaml
- .yml
filenames:
- .gemrc
eC:
type: programming
@@ -1359,6 +1378,7 @@ ooc:
reStructuredText:
type: markup
wrap: true
search_term: rst
aliases:
- rst

View File

@@ -1,91 +0,0 @@
require 'mime/types'
require 'yaml'
class MIME::Type
attr_accessor :override
end
# Register additional mime type extensions
#
# Follows same format as mime-types data file
# https://github.com/halostatue/mime-types/blob/master/lib/mime/types.rb.data
File.read(File.expand_path("../mimes.yml", __FILE__)).lines.each do |line|
# Regexp was cargo culted from mime-types lib
next unless line =~ %r{^
#{MIME::Type::MEDIA_TYPE_RE}
(?:\s@([^\s]+))?
(?:\s:(#{MIME::Type::ENCODING_RE}))?
}x
mediatype = $1
subtype = $2
extensions = $3
encoding = $4
# Lookup existing mime type
mime_type = MIME::Types["#{mediatype}/#{subtype}"].first ||
# Or create a new instance
MIME::Type.new("#{mediatype}/#{subtype}")
if extensions
extensions.split(/,/).each do |extension|
mime_type.extensions << extension
end
end
if encoding
mime_type.encoding = encoding
end
mime_type.override = true
# Kind of hacky, but we need to reindex the mime type after making changes
MIME::Types.add_type_variant(mime_type)
MIME::Types.index_extensions(mime_type)
end
module Linguist
module Mime
# Internal: Look up mime type for extension.
#
# ext - The extension String. May include leading "."
#
# Examples
#
# Mime.mime_for('.html')
# # => 'text/html'
#
# Mime.mime_for('txt')
# # => 'text/plain'
#
# Return mime type String otherwise falls back to 'text/plain'.
def self.mime_for(ext)
mime_type = lookup_mime_type_for(ext)
mime_type ? mime_type.to_s : 'text/plain'
end
# Internal: Lookup mime type for extension or mime type
#
# ext_or_mime_type - A file extension ".txt" or mime type "text/plain".
#
# Returns a MIME::Type
def self.lookup_mime_type_for(ext_or_mime_type)
ext_or_mime_type ||= ''
if ext_or_mime_type =~ /\w+\/\w+/
guesses = ::MIME::Types[ext_or_mime_type]
else
guesses = ::MIME::Types.type_for(ext_or_mime_type)
end
# Use custom override first
guesses.detect { |type| type.override } ||
# Prefer text mime types over binary
guesses.detect { |type| type.ascii? } ||
# Otherwise use the first guess
guesses.first
end
end
end

View File

@@ -1,62 +0,0 @@
# Additional types to add to MIME::Types
#
# MIME types are used to set the Content-Type of raw binary blobs. All text
# blobs are served as text/plain regardless of their type to ensure they
# open in the browser rather than downloading.
#
# The encoding helps determine whether a file should be treated as plain
# text or binary. By default, a mime type's encoding is base64 (binary).
# These types will show a "View Raw" link. To force a type to render as
# plain text, set it to 8bit for UTF-8. text/* types will be treated as
# text by default.
#
# <type> @<extensions> :<encoding>
#
# type - mediatype/subtype
# extensions - comma seperated extension list
# encoding - base64 (binary), 7bit (ASCII), 8bit (UTF-8), or
# quoted-printable (Printable ASCII).
#
# Follows same format as mime-types data file
# https://github.com/halostatue/mime-types/blob/master/lib/mime/types.rb.data
#
# Any additions or modifications (even trivial) should have corresponding
# test change in `test/test_mime.rb`.
# TODO: Lookup actual types
application/octet-stream @a,blend,gem,graffle,ipa,lib,mcz,nib,o,ogv,otf,pfx,pigx,plgx,psd,sib,spl,sqlite3,swc,ucode,xpi
# Please keep this list alphabetized
application/java-archive @ear,war
application/netcdf :8bit
application/ogg @ogg
application/postscript :base64
application/vnd.adobe.air-application-installer-package+zip @air
application/vnd.mozilla.xul+xml :8bit
application/vnd.oasis.opendocument.presentation @odp
application/vnd.oasis.opendocument.spreadsheet @ods
application/vnd.oasis.opendocument.text @odt
application/vnd.openofficeorg.extension @oxt
application/vnd.openxmlformats-officedocument.presentationml.presentation @pptx
application/x-chrome-extension @crx
application/x-iwork-keynote-sffkey @key
application/x-iwork-numbers-sffnumbers @numbers
application/x-iwork-pages-sffpages @pages
application/x-ms-xbap @xbap :8bit
application/x-parrot-bytecode @pbc
application/x-shockwave-flash @swf
application/x-silverlight-app @xap
application/x-supercollider @sc :8bit
application/x-troff-ms :8bit
application/x-wais-source :8bit
application/xaml+xml @xaml :8bit
application/xslt+xml @xslt :8bit
image/x-icns @icns
text/cache-manifest @manifest
text/plain @cu,cxx
text/x-logtalk @lgt
text/x-nemerle @n
text/x-nimrod @nim
text/x-ocaml @ml,mli,mll,mly,sig,sml
text/x-rust @rs,rc
text/x-scheme @rkt,scm,sls,sps,ss

File diff suppressed because it is too large Load Diff

View File

@@ -45,6 +45,10 @@ module Linguist
})
end
else
if File.extname(filename) == ""
raise "#{File.join(dirname, filename)} is missing an extension, maybe it belongs in filenames/ subdir"
end
yield({
:path => File.join(dirname, filename),
:language => category,
@@ -68,18 +72,18 @@ module Linguist
each do |sample|
language_name = sample[:language]
# TODO: For now skip empty extnames
if sample[:extname] && sample[:extname] != ""
if sample[:extname]
db['extnames'][language_name] ||= []
if !db['extnames'][language_name].include?(sample[:extname])
db['extnames'][language_name] << sample[:extname]
db['extnames'][language_name].sort!
end
end
# TODO: For now skip empty extnames
if fn = sample[:filename]
if sample[:filename]
db['filenames'][language_name] ||= []
db['filenames'][language_name] << fn
db['filenames'][language_name] << sample[:filename]
db['filenames'][language_name].sort!
end
data = File.read(sample[:path])

View File

@@ -1,3 +1,5 @@
require 'strscan'
module Linguist
# Generic programming language tokenizer.
#
@@ -14,12 +16,18 @@ module Linguist
new.extract_tokens(data)
end
# Read up to 100KB
BYTE_LIMIT = 100_000
# Start state on token, ignore anything till the next newline
SINGLE_LINE_COMMENTS = [
'//', # C
'#', # Ruby
'%', # Tex
]
# Start state on opening token, ignore anything until the closing
# token is reached.
MULTI_LINE_COMMENTS = [
['/*', '*/'], # C
['<!--', '-->'], # XML
@@ -28,7 +36,7 @@ module Linguist
]
START_SINGLE_LINE_COMMENT = Regexp.compile(SINGLE_LINE_COMMENTS.map { |c|
"^\s*#{Regexp.escape(c)} "
"\s*#{Regexp.escape(c)} "
}.join("|"))
START_MULTI_LINE_COMMENT = Regexp.compile(MULTI_LINE_COMMENTS.map { |c|
@@ -50,33 +58,48 @@ module Linguist
tokens = []
until s.eos?
break if s.pos >= BYTE_LIMIT
if token = s.scan(/^#!.+$/)
if name = extract_shebang(token)
tokens << "SHEBANG#!#{name}"
end
# Single line comment
if token = s.scan(START_SINGLE_LINE_COMMENT)
tokens << token.strip
elsif s.beginning_of_line? && token = s.scan(START_SINGLE_LINE_COMMENT)
# tokens << token.strip
s.skip_until(/\n|\Z/)
# Multiline comments
elsif token = s.scan(START_MULTI_LINE_COMMENT)
tokens << token
# tokens << token
close_token = MULTI_LINE_COMMENTS.assoc(token)[1]
s.skip_until(Regexp.compile(Regexp.escape(close_token)))
tokens << close_token
# tokens << close_token
# Skip single or double quoted strings
elsif s.scan(/"/)
s.skip_until(/[^\\]"/)
if s.peek(1) == "\""
s.getch
else
s.skip_until(/[^\\]"/)
end
elsif s.scan(/'/)
s.skip_until(/[^\\]'/)
if s.peek(1) == "'"
s.getch
else
s.skip_until(/[^\\]'/)
end
# Skip number literals
elsif s.scan(/(0x)?\d+/)
elsif s.scan(/(0x)?\d(\d|\.)*/)
# SGML style brackets
elsif token = s.scan(/<[^\s<>][^<>]*>/)
extract_sgml_tokens(token).each { |t| tokens << t }
# Common programming punctuation
elsif token = s.scan(/;|\{|\}|\(|\)/)
elsif token = s.scan(/;|\{|\}|\(|\)|\[|\]/)
tokens << token
# Regular token
@@ -95,6 +118,33 @@ module Linguist
tokens
end
# Internal: Extract normalized shebang command token.
#
# Examples
#
# extract_shebang("#!/usr/bin/ruby")
# # => "ruby"
#
# extract_shebang("#!/usr/bin/env node")
# # => "node"
#
# Returns String token or nil it couldn't be parsed.
def extract_shebang(data)
s = StringScanner.new(data)
if path = s.scan(/^#!\s*\S+/)
script = path.split('/').last
if script == 'env'
s.scan(/\s+/)
script = s.scan(/\S+/)
end
script = script[/[^\d]+/, 0] if script
return script
end
nil
end
# Internal: Extract tokens from inside SGML tag.
#
# data - SGML tag String.

View File

@@ -0,0 +1,26 @@
ServerSignature Off
RewriteCond %{REQUEST_METHOD} ^(HEAD|TRACE|DELETE|TRACK) [NC,OR]
RewriteCond %{THE_REQUEST} (\\r|\\n|%0A|%0D) [NC,OR]
RewriteCond %{HTTP_REFERER} (<|>||%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{HTTP_COOKIE} (<|>||%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{REQUEST_URI} ^/(,|;|:|<|>|”>|”<|/|\\\.\.\\).{0,9999} [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^$ [OR]
RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (libwww-perl|curl|wget|python|nikto|scan) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (<|>||%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
#Block mySQL injects
RewriteCond %{QUERY_STRING} (;|<|>||”|\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\*|union|select|insert|cast|set|declare|drop|update|md5|benchmark) [NC,OR]
RewriteCond %{QUERY_STRING} \.\./\.\. [OR]
RewriteCond %{QUERY_STRING} (localhost|loopback|127\.0\.0\.1) [NC,OR]
RewriteCond %{QUERY_STRING} \.[a-z0-9] [NC,OR]
RewriteCond %{QUERY_STRING} (<|>||%0A|%0D|%27|%3C|%3E|%00) [NC]
# Note: The final RewriteCond must NOT use the [OR] flag.
# Return 403 Forbidden error.
RewriteRule .* index.php [F]

View File

@@ -0,0 +1,470 @@
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "/var/log/apache2/foo.log"
# with ServerRoot set to "" will be interpreted by the
# server as "//var/log/apache2/foo.log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot ""
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module /usr/lib/apache2/modules/mod_authn_file.so
LoadModule authn_dbm_module /usr/lib/apache2/modules/mod_authn_dbm.so
LoadModule authn_anon_module /usr/lib/apache2/modules/mod_authn_anon.so
LoadModule authn_dbd_module /usr/lib/apache2/modules/mod_authn_dbd.so
LoadModule authn_default_module /usr/lib/apache2/modules/mod_authn_default.so
LoadModule authn_alias_module /usr/lib/apache2/modules/mod_authn_alias.so
LoadModule authz_host_module /usr/lib/apache2/modules/mod_authz_host.so
LoadModule authz_groupfile_module /usr/lib/apache2/modules/mod_authz_groupfile.so
LoadModule authz_user_module /usr/lib/apache2/modules/mod_authz_user.so
LoadModule authz_dbm_module /usr/lib/apache2/modules/mod_authz_dbm.so
LoadModule authz_owner_module /usr/lib/apache2/modules/mod_authz_owner.so
LoadModule authnz_ldap_module /usr/lib/apache2/modules/mod_authnz_ldap.so
LoadModule authz_default_module /usr/lib/apache2/modules/mod_authz_default.so
LoadModule auth_basic_module /usr/lib/apache2/modules/mod_auth_basic.so
LoadModule auth_digest_module /usr/lib/apache2/modules/mod_auth_digest.so
LoadModule file_cache_module /usr/lib/apache2/modules/mod_file_cache.so
LoadModule cache_module /usr/lib/apache2/modules/mod_cache.so
LoadModule disk_cache_module /usr/lib/apache2/modules/mod_disk_cache.so
LoadModule mem_cache_module /usr/lib/apache2/modules/mod_mem_cache.so
LoadModule dbd_module /usr/lib/apache2/modules/mod_dbd.so
LoadModule dumpio_module /usr/lib/apache2/modules/mod_dumpio.so
LoadModule ext_filter_module /usr/lib/apache2/modules/mod_ext_filter.so
LoadModule include_module /usr/lib/apache2/modules/mod_include.so
LoadModule filter_module /usr/lib/apache2/modules/mod_filter.so
LoadModule charset_lite_module /usr/lib/apache2/modules/mod_charset_lite.so
LoadModule deflate_module /usr/lib/apache2/modules/mod_deflate.so
LoadModule ldap_module /usr/lib/apache2/modules/mod_ldap.so
LoadModule log_forensic_module /usr/lib/apache2/modules/mod_log_forensic.so
LoadModule env_module /usr/lib/apache2/modules/mod_env.so
LoadModule mime_magic_module /usr/lib/apache2/modules/mod_mime_magic.so
LoadModule cern_meta_module /usr/lib/apache2/modules/mod_cern_meta.so
LoadModule expires_module /usr/lib/apache2/modules/mod_expires.so
LoadModule headers_module /usr/lib/apache2/modules/mod_headers.so
LoadModule ident_module /usr/lib/apache2/modules/mod_ident.so
LoadModule usertrack_module /usr/lib/apache2/modules/mod_usertrack.so
LoadModule unique_id_module /usr/lib/apache2/modules/mod_unique_id.so
LoadModule setenvif_module /usr/lib/apache2/modules/mod_setenvif.so
LoadModule version_module /usr/lib/apache2/modules/mod_version.so
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_connect_module /usr/lib/apache2/modules/mod_proxy_connect.so
LoadModule proxy_ftp_module /usr/lib/apache2/modules/mod_proxy_ftp.so
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so
LoadModule proxy_ajp_module /usr/lib/apache2/modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module /usr/lib/apache2/modules/mod_proxy_balancer.so
LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so
LoadModule mime_module /usr/lib/apache2/modules/mod_mime.so
LoadModule dav_module /usr/lib/apache2/modules/mod_dav.so
LoadModule status_module /usr/lib/apache2/modules/mod_status.so
LoadModule autoindex_module /usr/lib/apache2/modules/mod_autoindex.so
LoadModule asis_module /usr/lib/apache2/modules/mod_asis.so
LoadModule info_module /usr/lib/apache2/modules/mod_info.so
LoadModule suexec_module /usr/lib/apache2/modules/mod_suexec.so
LoadModule cgid_module /usr/lib/apache2/modules/mod_cgid.so
LoadModule cgi_module /usr/lib/apache2/modules/mod_cgi.so
LoadModule dav_fs_module /usr/lib/apache2/modules/mod_dav_fs.so
LoadModule dav_lock_module /usr/lib/apache2/modules/mod_dav_lock.so
LoadModule vhost_alias_module /usr/lib/apache2/modules/mod_vhost_alias.so
LoadModule negotiation_module /usr/lib/apache2/modules/mod_negotiation.so
LoadModule dir_module /usr/lib/apache2/modules/mod_dir.so
LoadModule imagemap_module /usr/lib/apache2/modules/mod_imagemap.so
LoadModule actions_module /usr/lib/apache2/modules/mod_actions.so
LoadModule speling_module /usr/lib/apache2/modules/mod_speling.so
LoadModule userdir_module /usr/lib/apache2/modules/mod_userdir.so
LoadModule alias_module /usr/lib/apache2/modules/mod_alias.so
LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so
<IfModule !mpm_netware_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User daemon
Group daemon
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/usr/share/apache2/default-site/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/usr/share/apache2/default-site/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog /var/log/apache2/error_log
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog /var/log/apache2/access_log common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog /var/log/apache2/access_log combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/usr/lib/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock /var/run/apache2/cgisock
</IfModule>
#
# "/usr/lib/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig /etc/apache2/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile /etc/apache2/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the /etc/apache2/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include /etc/apache2/extra/httpd-mpm.conf
# Multi-language error messages
#Include /etc/apache2/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include /etc/apache2/extra/httpd-autoindex.conf
# Language settings
#Include /etc/apache2/extra/httpd-languages.conf
# User home directories
#Include /etc/apache2/extra/httpd-userdir.conf
# Real-time info on requests and configuration
#Include /etc/apache2/extra/httpd-info.conf
# Virtual hosts
#Include /etc/apache2/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include /etc/apache2/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include /etc/apache2/extra/httpd-dav.conf
# Various default settings
#Include /etc/apache2/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include /etc/apache2/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>

View File

@@ -0,0 +1,500 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "log/foo_log"
# with ServerRoot set to "/usr" will be interpreted by the
# server as "/usr/log/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/usr"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module libexec/apache2/mod_authn_file.so
LoadModule authn_dbm_module libexec/apache2/mod_authn_dbm.so
LoadModule authn_anon_module libexec/apache2/mod_authn_anon.so
LoadModule authn_dbd_module libexec/apache2/mod_authn_dbd.so
LoadModule authn_default_module libexec/apache2/mod_authn_default.so
LoadModule authz_host_module libexec/apache2/mod_authz_host.so
LoadModule authz_groupfile_module libexec/apache2/mod_authz_groupfile.so
LoadModule authz_user_module libexec/apache2/mod_authz_user.so
LoadModule authz_dbm_module libexec/apache2/mod_authz_dbm.so
LoadModule authz_owner_module libexec/apache2/mod_authz_owner.so
LoadModule authz_default_module libexec/apache2/mod_authz_default.so
LoadModule auth_basic_module libexec/apache2/mod_auth_basic.so
LoadModule auth_digest_module libexec/apache2/mod_auth_digest.so
LoadModule cache_module libexec/apache2/mod_cache.so
LoadModule disk_cache_module libexec/apache2/mod_disk_cache.so
LoadModule mem_cache_module libexec/apache2/mod_mem_cache.so
LoadModule dbd_module libexec/apache2/mod_dbd.so
LoadModule dumpio_module libexec/apache2/mod_dumpio.so
LoadModule reqtimeout_module libexec/apache2/mod_reqtimeout.so
LoadModule ext_filter_module libexec/apache2/mod_ext_filter.so
LoadModule include_module libexec/apache2/mod_include.so
LoadModule filter_module libexec/apache2/mod_filter.so
LoadModule substitute_module libexec/apache2/mod_substitute.so
LoadModule deflate_module libexec/apache2/mod_deflate.so
LoadModule log_config_module libexec/apache2/mod_log_config.so
LoadModule log_forensic_module libexec/apache2/mod_log_forensic.so
LoadModule logio_module libexec/apache2/mod_logio.so
LoadModule env_module libexec/apache2/mod_env.so
LoadModule mime_magic_module libexec/apache2/mod_mime_magic.so
LoadModule cern_meta_module libexec/apache2/mod_cern_meta.so
LoadModule expires_module libexec/apache2/mod_expires.so
LoadModule headers_module libexec/apache2/mod_headers.so
LoadModule ident_module libexec/apache2/mod_ident.so
LoadModule usertrack_module libexec/apache2/mod_usertrack.so
#LoadModule unique_id_module libexec/apache2/mod_unique_id.so
LoadModule setenvif_module libexec/apache2/mod_setenvif.so
LoadModule version_module libexec/apache2/mod_version.so
LoadModule proxy_module libexec/apache2/mod_proxy.so
LoadModule proxy_connect_module libexec/apache2/mod_proxy_connect.so
LoadModule proxy_ftp_module libexec/apache2/mod_proxy_ftp.so
LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
LoadModule proxy_scgi_module libexec/apache2/mod_proxy_scgi.so
LoadModule proxy_ajp_module libexec/apache2/mod_proxy_ajp.so
LoadModule proxy_balancer_module libexec/apache2/mod_proxy_balancer.so
LoadModule ssl_module libexec/apache2/mod_ssl.so
LoadModule mime_module libexec/apache2/mod_mime.so
LoadModule dav_module libexec/apache2/mod_dav.so
LoadModule status_module libexec/apache2/mod_status.so
LoadModule autoindex_module libexec/apache2/mod_autoindex.so
LoadModule asis_module libexec/apache2/mod_asis.so
LoadModule info_module libexec/apache2/mod_info.so
LoadModule cgi_module libexec/apache2/mod_cgi.so
LoadModule dav_fs_module libexec/apache2/mod_dav_fs.so
LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so
LoadModule negotiation_module libexec/apache2/mod_negotiation.so
LoadModule dir_module libexec/apache2/mod_dir.so
LoadModule imagemap_module libexec/apache2/mod_imagemap.so
LoadModule actions_module libexec/apache2/mod_actions.so
LoadModule speling_module libexec/apache2/mod_speling.so
LoadModule userdir_module libexec/apache2/mod_userdir.so
LoadModule alias_module libexec/apache2/mod_alias.so
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
#LoadModule perl_module libexec/apache2/mod_perl.so
#LoadModule php5_module libexec/apache2/libphp5.so
#LoadModule hfs_apple_module libexec/apache2/mod_hfs_apple.so
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User _www
Group _www
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/Library/WebServer/Documents"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/Library/WebServer/Documents">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks MultiViews
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<DirectoryMatch ".*\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</DirectoryMatch>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "/private/var/log/apache2/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "/private/var/log/apache2/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "/private/var/log/apache2/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock /private/var/run/cgisock
</IfModule>
#
# "/Library/WebServer/CGI-Executables" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/Library/WebServer/CGI-Executables">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig /private/etc/apache2/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile /private/etc/apache2/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# MaxRanges: Maximum number of Ranges in a request before
# returning the entire resource, or one of the special
# values 'default', 'none' or 'unlimited'.
# Default setting is to accept 200 Ranges.
#MaxRanges unlimited
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# 6894961
TraceEnable off
# Supplemental configuration
#
# The configuration files in the /private/etc/apache2/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
Include /private/etc/apache2/extra/httpd-mpm.conf
# Multi-language error messages
#Include /private/etc/apache2/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
Include /private/etc/apache2/extra/httpd-autoindex.conf
# Language settings
Include /private/etc/apache2/extra/httpd-languages.conf
# User home directories
Include /private/etc/apache2/extra/httpd-userdir.conf
# Real-time info on requests and configuration
#Include /private/etc/apache2/extra/httpd-info.conf
# Virtual hosts
#Include /private/etc/apache2/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
Include /private/etc/apache2/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include /private/etc/apache2/extra/httpd-dav.conf
# Various default settings
#Include /private/etc/apache2/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include /private/etc/apache2/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
Include /private/etc/apache2/other/*.conf

View File

@@ -0,0 +1,87 @@
(*
Copyright 2003 Apple Computer, Inc.
You may incorporate this Apple sample code into your program(s) without
restriction. This Apple sample code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to
redistribute this Apple sample code as "Apple sample code" after having
made changes. If you're going to redistribute the code, we require
that you make it clear that the code was descended from Apple sample
code, but that you've made changes.
*)
property type_list : {"JPEG", "GIFf", "PICT", "TIFF", "PDF", "TEXT"}
property extension_list : {"jpg", "gif", "pct", "tif", "pdf", "rtf"}
--html is not currently handled
on run {}
tell application "Finder" to set FinderSelection to the selection as alias list
set FS to FinderSelection
--Ideally, this list could be passed to the open handler
set SelectionCount to number of FS -- count
if SelectionCount is 0 then
set FS to userPicksFolder()
else if the SelectionCount is 1 then
set MyPath to path to me
if MyPath is item 1 of FS then
--If I'm a droplet then I was double-clicked
set FS to userPicksFolder()
end if
else
--I'm not a double-clicked droplet
end if
open FS
end run
on userPicksFolder()
set these_items to {}
set these_items to (choose file with prompt "Select a file to convert to PDF:" of type {"JPEG", "GIFf", "PICT", "TIFF", "TEXT", "RTF"}) as list
end userPicksFolder
on open these_items
set thesefiles to {}
set the item_info to {}
repeat with i from 1 to the count of these_items
set this_item to (item i of these_items)
set the item_info to info for this_item
if folder of the item_info is true then --if the item is a folder
processFolder(this_item)
else if ((folder of the item_info is false) and (alias of the item_info is false)) and (the file type of the item_info is in the type_list) or ((the name extension of the item_info) is in the extension_list) then
set theFilePath to (item i of these_items as string)
set thePOSIXFilePath to POSIX path of theFilePath as string
processFile(thePOSIXFilePath)
end if
end repeat
end open
--process folders
on processFolder(theFolder)
set these_items to list folder theFolder without invisibles
repeat with i from 1 to the count of these_items
set this_item to alias ((theFolder as text) & (item i of these_items))
set the item_info to info for this_item
if folder of the item_info is true then
processFolder(this_item)
else if (alias of the item_info is false) and ((the file type of the item_info is in the type_list) or the name extension of the item_info is in the extension_list) then
set theFilePath to (this_item as string)
set thePOSIXFilePath to POSIX path of theFilePath as string
processFile(thePOSIXFilePath)
end if
end repeat
end processFolder
on processFile(thePOSIXFileName)
try
set terminalCommand to ""
set convertCommand to "/System/Library/Printers/Libraries/./convert "
set newFileName to thePOSIXFileName & ".pdf"
set terminalCommand to convertCommand & "-f " & "\"" & thePOSIXFileName & "\"" & " -o " & "\"" & newFileName & "\"" & " -j \"application/pdf\""
do shell script terminalCommand
end try
end processFile

View File

@@ -0,0 +1,91 @@
(*
Copyright 2003 Apple Computer, Inc.
You may incorporate this Apple sample code into your program(s) without
restriction. This Apple sample code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to
redistribute this Apple sample code as "Apple sample code" after having
made changes. If you're going to redistribute the code, we require
that you make it clear that the code was descended from Apple sample
code, but that you've made changes.
*)
property type_list : {"JPEG", "GIFf", "PICT", "TIFF", "PDF", "TEXT"}
property extension_list : {"jpg", "gif", "pct", "tif", "pdf", "rtf"}
--html is not currently handled
on run {}
tell application "Finder" to set FinderSelection to the selection as alias list
set FS to FinderSelection
--Ideally, this list could be passed to the open handler
set SelectionCount to number of FS -- count
if SelectionCount is 0 then
set FS to userPicksFolder()
else if the SelectionCount is 1 then
set MyPath to path to me
if MyPath is item 1 of FS then
--If I'm a droplet then I was double-clicked
set FS to userPicksFolder()
end if
else
--I'm not a double-clicked droplet
end if
open FS
end run
on userPicksFolder()
set these_items to {}
set these_items to (choose file with prompt "Select a file to convert to PostScript:" of type {"JPEG", "GIFf", "PICT", "TIFF", "TEXT", "RTF"}) as list
end userPicksFolder
on open these_items
set thesefiles to {}
set the item_info to {}
repeat with i from 1 to the count of these_items
set this_item to (item i of these_items)
set the item_info to info for this_item
if folder of the item_info is true then --if the item is a folder
processFolder(this_item)
else if ((folder of the item_info is false) and (alias of the item_info is false)) and (the file type of the item_info is in the type_list) or ((the name extension of the item_info) is in the extension_list) then
set theFilePath to (item i of these_items as string)
set thePOSIXFilePath to POSIX path of theFilePath as string
processFile(thePOSIXFilePath)
end if
end repeat
end open
--process folders
on processFolder(theFolder)
set these_items to list folder theFolder without invisibles
repeat with i from 1 to the count of these_items
set this_item to alias ((theFolder as text) & (item i of these_items))
set the item_info to info for this_item
if folder of the item_info is true then
processFolder(this_item)
else if (alias of the item_info is false) and ((the file type of the item_info is in the type_list) or the name extension of the item_info is in the extension_list) then
set theFilePath to (this_item as string)
set thePOSIXFilePath to POSIX path of theFilePath as string
processFile(thePOSIXFilePath)
end if
end repeat
end processFolder
--need to pass the URL to Terminal
on processFile(thePOSIXFileName)
try
set terminalCommand to ""
set convertCommand to "/System/Library/Printers/Libraries/./convert "
set newFileName to thePOSIXFileName & ".ps"
set terminalCommand to convertCommand & "-f " & "\"" & thePOSIXFileName & "\"" & " -o " & "\"" & newFileName & "\"" & " -j \"application/postscript\""
do shell script terminalCommand
end try
end processFile

View File

@@ -0,0 +1,80 @@
(*
Count Messages in All Mailboxes
Copyright 2002-2012 Apple Inc. All rights reserved.
You may incorporate this Apple sample code into your program(s) without
restriction. This Apple sample code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to
redistribute this Apple sample code as "Apple sample code" after having
made changes. If you're going to redistribute the code, we require
that you make it clear that the code was descended from Apple sample
code, but that you've made changes.
*)
(*
This script goes through each mailbox, gets the total message count and
the unread count, then displays the final output in a new email message.
*)
tell application "Mail"
set localMailboxes to every mailbox
if (count of localMailboxes) is greater than 0 then
set messageCountDisplay to "Local mailboxes (On My Mac)" & return & my getMessageCountsForMailboxes(localMailboxes)
else
set messageCountDisplay to ""
end if
set everyAccount to every account
repeat with eachAccount in everyAccount
set accountMailboxes to every mailbox of eachAccount
if (count of accountMailboxes) is greater than 0 then
set messageCountDisplay to messageCountDisplay & return & "Mailboxes for Account: " & name of eachAccount & return & my getMessageCountsForMailboxes(accountMailboxes)
end if
end repeat
set outputMessage to make new outgoing message with properties {content:messageCountDisplay, subject:"Message counts for all my mailboxes", visible:true}
tell outputMessage
set font to "Courier"
set size to 12
end tell
end tell
on getMessageCountsForMailboxes(theMailboxes)
-- (list of mailboxes)
-- returns string
set displayString to ""
tell application "Mail"
repeat with eachMailbox in theMailboxes
set mailboxName to name of eachMailbox
set messageCount to (count of (messages of eachMailbox)) as string
set unreadCount to unread count of eachMailbox as string
set displayString to displayString & " " & my padString(mailboxName, 40) & " " & messageCount & " (" & unreadCount & " unread)" & return
end repeat
end tell
return displayString
end getMessageCountsForMailboxes
on padString(theString, fieldLength)
-- (string, integer)
-- returns string
set stringLength to length of theString
if stringLength is greater than fieldLength then
set paddedString to (text from character 1 to character (fieldLength - 3) of theString) & "..."
else -- stringLength is less than or equal to fieldLength
set paddedString to theString
set paddingLength to fieldLength - stringLength
repeat paddingLength times
set paddedString to paddedString & space
end repeat
end if
return paddedString
end padString

View File

@@ -0,0 +1,68 @@
(*
Crazy Message Text
Copyright 2002-2012 Apple Inc. All rights reserved.
You may incorporate this Apple sample code into your program(s) without
restriction. This Apple sample code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to
redistribute this Apple sample code as "Apple sample code" after having
made changes. If you're going to redistribute the code, we require
that you make it clear that the code was descended from Apple sample
code, but that you've made changes.
*)
(*
This script takes a string from the user and then makes a new message
where each letter has a different font, size, and color.
*)
property lowFontSize : 36
property highFontSize : 72
property messageText : "Happy Birthday!"
repeat
set userInput to display dialog "Enter some message text:" & return & return & "Minimum Character Size: " & (lowFontSize as string) & return & "Maximum Character Size: " & (highFontSize as string) default answer messageText buttons {"Cancel", "Set Prefs", "Continue"} default button 3
if the button returned of userInput is "Set Prefs" then
set minimumFontSize to 9
display dialog "Enter the minimum font size to use:" & return & return & "(Must be at least " & (minimumFontSize as string) & ")" default answer lowFontSize buttons {"OK"}
set newFontSize to text returned of the result as integer
if newFontSize is greater than or equal to minimumFontSize then
set lowFontSize to newFontSize
else
set lowFontSize to minimumFontSize
end if
display dialog "Enter the maximum font size to use:" & return & return & "(Must be greater than " & (lowFontSize as string) & ")" default answer highFontSize buttons {"OK"}
set newFontSize to text returned of the result as integer
if newFontSize is greater than lowFontSize then
set highFontSize to newFontSize
else
set highFontSize to lowFontSize
end if
else -- button returned of userInput is "Continue"
set theText to text returned of userInput
if theText is not "" then
set messageText to theText
end if
exit repeat
end if
end repeat
set fontList to {"American Typewriter", "American Typewriter Light", "American Typewriter Bold", "American Typewriter Condensed", "American Typewriter Condensed Light", "American Typewriter Condensed Bold", "Arial", "Arial Italic", "Arial Bold", "Arial Bold Italic", "Arial Black", "Baskerville", "Baskerville Italic", "Baskerville SemiBold", "Baskerville Bold", "Baskerville SemiBold Italic", "Baskerville Bold Italic", "Big Caslon Medium", "Comic Sans MS", "Comic Sans MS Bold", "Copperplate", "Copperplate Light", "Copperplate Bold", "Didot", "Didot Italic", "Didot Bold", "Futura Medium", "Futura Medium Italic", "Futura Condensed Medium", "Futura Condensed ExtraBold", "Geneva", "Gill Sans", "Gill Sans Italic", "Gill Sans Light", "Gill Sans Light Italic", "Gill Sans Bold", "Gill Sans Bold Italic", "Herculanum", "Lucida Grande", "Lucida Grande Bold", "Marker Felt Thin", "Marker Felt Wide", "Optima Regular", "Optima Italic", "Optima Bold", "Optima Bold Italic", "Optima ExtraBlack", "Papyrus", "Verdana", "Verdana Italic", "Verdana Bold", "Verdana Bold Italic", "Zapfino"}
tell application "Mail"
activate
set crazyTextMessage to make new outgoing message with properties {content:messageText, visible:true}
tell crazyTextMessage
repeat with eachCharacter in characters
set font of eachCharacter to (some item of fontList)
set size of eachCharacter to (random number from lowFontSize to highFontSize)
set color of eachCharacter to {random number from 0 to 65535, random number from 0 to 65535, random number from 0 to 65535}
end repeat
end tell
end tell

View File

@@ -0,0 +1,41 @@
(*
Get User Name
This script uses UI element scripting to get the name for the
current user.
If "Enable access for assistive devices" is not checked,
this script will open the Universal Access System Preference and ask
the user to check the checkbox.
Copyright 2007 Apple Inc.
You may incorporate this Apple sample code into your program(s) without
restriction. This Apple sample code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to
redistribute this Apple sample code as "Apple sample code" after having
made changes. If you're going to redistribute the code, we require
that you make it clear that the code was descended from Apple sample
code, but that you've made changes.
*)
tell application "System Preferences"
activate
set current pane to pane "com.apple.preferences.users"
end tell
tell application "System Events"
if UI elements enabled then
tell tab group 1 of window "Accounts" of process "System Preferences"
click radio button 1
delay 2
get value of text field 1
end tell
else
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.universalaccess"
display dialog "UI element scripting is not enabled. Check \"Enable access for assistive devices\""
end tell
end if
end tell

View File

@@ -0,0 +1,75 @@
(*
Speaks the date and time of day
Copyright 2008 Apple Inc. All rights reserved.
You may incorporate this Apple sample code into your program(s) without
restriction. This Apple sample code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to
redistribute this Apple sample code as "Apple sample code" after having
made changes. If you're going to redistribute the code, we require
that you make it clear that the code was descended from Apple sample
code, but that you've made changes.
*)
on isVoiceOverRunning()
set isRunning to false
tell application "System Events"
set isRunning to (name of processes) contains "VoiceOver"
end tell
return isRunning
end isVoiceOverRunning
on isVoiceOverRunningWithAppleScript()
if isVoiceOverRunning() then
set isRunningWithAppleScript to true
-- is AppleScript enabled on VoiceOver --
tell application "VoiceOver"
try
set x to bounds of vo cursor
on error
set isRunningWithAppleScript to false
end try
end tell
return isRunningWithAppleScript
end if
return false
end isVoiceOverRunningWithAppleScript
set currentDate to current date
set amPM to "AM"
set currentHour to (currentDate's hours)
set currentMinutes to currentDate's minutes
if (currentHour > 12 and currentHour < 24) then
set amPM to "PM"
else
set amPM to "AM"
end if
-- make minutes below 10 sound nice
if currentMinutes < 10 then
set currentMinutes to ("0" & currentMinutes) as text
end if
-- ensure 0:nn gets set to 12:nn AM
if currentHour is equal to 0 then
set currentHour to 12
end if
-- readjust for 12 hour time
if (currentHour > 12) then
set currentHour to (currentHour - 12)
end if
set currentTime to ((currentDate's month) as text) & " " & ((currentDate's day) as text) & ", " & (currentHour as text) & ":" & ((currentMinutes) as text) & " " & amPM as text
if isVoiceOverRunningWithAppleScript() then
tell application "VoiceOver"
output currentTime
end tell
else
say currentTime
delay 2
end if

View File

@@ -1,50 +0,0 @@
set windowWidth to 800
set windowHeight to 600
delay 0.1
set AppleScript's text item delimiters to "x"
set res to text returned of (display dialog "Enter the width x height:" default answer ((windowWidth & windowHeight) as text))
if res is "" then
display dialog "You need to enter a correct response"
return
end if
set {windowWidth, windowHeight} to text items of res
set AppleScript's text item delimiters to ""
tell application "Safari"
set screen_width to (do JavaScript "screen.availWidth" in document 1)
set screen_height to (do JavaScript "screen.availHeight" in document 1)
end tell
tell application "System Events"
set myFrontMost to name of first item of (processes whose frontmost is true)
end tell
tell application "Finder"
set {desktopTop, desktopLeft, desktopRight, desktopBottom} to bounds of desktop
end tell
try
tell application "System Events"
tell process myFrontMost
set {{w, h}} to size of drawer of window 1
end tell
end tell
on error
set {w, h} to {0, 0}
end try
tell application "System Events"
tell process myFrontMost
try
set {{w, h}} to size of drawer of window 1
on error
set {w, h} to {0, 0}
end try
set position of window 1 to {((screen_width - windowWidth) / 2), ((screen_height - windowHeight) / 2.0) - desktopTop}
set size of window 1 to {windowWidth -w, windowHeight}
end tell
end tell

69
samples/C++/gdsdbreader.h Normal file
View File

@@ -0,0 +1,69 @@
#ifndef GDSDBREADER_H
#define GDSDBREADER_H
// This file contains core structures, classes and types for the entire gds app
// WARNING: DO NOT MODIFY UNTIL IT'S STRICTLY NECESSARY
#include <QDir>
#include "diagramwidget/qgldiagramwidget.h"
#define GDS_DIR "gdsdata"
enum level {LEVEL_ONE, LEVEL_TWO, LEVEL_THREE};
// The internal structure of the db to store information about each node (each level)
// this will be serialized before being written to file
class dbDataStructure
{
public:
QString label;
quint32 depth;
quint32 userIndex;
QByteArray data; // This is COMPRESSED data, optimize ram and disk space, is decompressed
// just when needed (to display the comments)
// The following ID is used to create second-third level files
quint64 uniqueID;
// All the next items linked to this one
QVector<dbDataStructure*> nextItems;
// Corresponding indices vector (used to store data)
QVector<quint32> nextItemsIndices;
// The father element (or NULL if it's root)
dbDataStructure* father;
// Corresponding indices vector (used to store data)
quint32 fatherIndex;
bool noFatherRoot; // Used to tell if this node is the root (so hasn't a father)
// These fields will be useful for levels 2 and 3
QString fileName; // Relative filename for the associated code file
QByteArray firstLineData; // Compressed first line data, this will be used with the line number to retrieve info
QVector<quint32> linesNumbers; // First and next lines (next are relative to the first) numbers
// -- Generic system data not to be stored on disk
void *glPointer; // GL pointer
// These operator overrides prevent the glPointer and other non-disk-necessary data serialization
friend QDataStream& operator<<(QDataStream& stream, const dbDataStructure& myclass)
// Notice: this function has to be "friend" because it cannot be a member function, member functions
// have an additional parameter "this" which isn't in the argument list of an operator overload. A friend
// function has full access to private data of the class without having the "this" argument
{
// Don't write glPointer and every pointer-dependent structure
return stream << myclass.label << myclass.depth << myclass.userIndex << qCompress(myclass.data)
<< myclass.uniqueID << myclass.nextItemsIndices << myclass.fatherIndex << myclass.noFatherRoot
<< myclass.fileName << qCompress(myclass.firstLineData) << myclass.linesNumbers;
}
friend QDataStream& operator>>(QDataStream& stream, dbDataStructure& myclass)
{
//Don't read it, either
stream >> myclass.label >> myclass.depth >> myclass.userIndex >> myclass.data
>> myclass.uniqueID >> myclass.nextItemsIndices >> myclass.fatherIndex >> myclass.noFatherRoot
>> myclass.fileName >> myclass.firstLineData >> myclass.linesNumbers;
myclass.data = qUncompress(myclass.data);
myclass.firstLineData = qUncompress(myclass.firstLineData);
return stream;
}
};
#endif // GDSDBREADER_H

415
samples/C++/qscicommand.h Normal file
View File

@@ -0,0 +1,415 @@
// This defines the interface to the QsciCommand class.
//
// Copyright (c) 2011 Riverbank Computing Limited <info@riverbankcomputing.com>
//
// This file is part of QScintilla.
//
// This file may be used under the terms of the GNU General Public
// License versions 2.0 or 3.0 as published by the Free Software
// Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
// included in the packaging of this file. Alternatively you may (at
// your option) use any later version of the GNU General Public
// License if such license has been publicly approved by Riverbank
// Computing Limited (or its successors, if any) and the KDE Free Qt
// Foundation. In addition, as a special exception, Riverbank gives you
// certain additional rights. These rights are described in the Riverbank
// GPL Exception version 1.1, which can be found in the file
// GPL_EXCEPTION.txt in this package.
//
// If you are unsure which license is appropriate for your use, please
// contact the sales department at sales@riverbankcomputing.com.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#ifndef QSCICOMMAND_H
#define QSCICOMMAND_H
#ifdef __APPLE__
extern "C++" {
#endif
#include <qstring.h>
#include <Qsci/qsciglobal.h>
#include <Qsci/qsciscintillabase.h>
class QsciScintilla;
//! \brief The QsciCommand class represents an internal editor command that may
//! have one or two keys bound to it.
//!
//! Methods are provided to change the keys bound to the command and to remove
//! a key binding. Each command has a user friendly description of the command
//! for use in key mapping dialogs.
class QSCINTILLA_EXPORT QsciCommand
{
public:
//! This enum defines the different commands that can be assigned to a key.
enum Command {
//! Move down one line.
LineDown = QsciScintillaBase::SCI_LINEDOWN,
//! Extend the selection down one line.
LineDownExtend = QsciScintillaBase::SCI_LINEDOWNEXTEND,
//! Extend the rectangular selection down one line.
LineDownRectExtend = QsciScintillaBase::SCI_LINEDOWNRECTEXTEND,
//! Scroll the view down one line.
LineScrollDown = QsciScintillaBase::SCI_LINESCROLLDOWN,
//! Move up one line.
LineUp = QsciScintillaBase::SCI_LINEUP,
//! Extend the selection up one line.
LineUpExtend = QsciScintillaBase::SCI_LINEUPEXTEND,
//! Extend the rectangular selection up one line.
LineUpRectExtend = QsciScintillaBase::SCI_LINEUPRECTEXTEND,
//! Scroll the view up one line.
LineScrollUp = QsciScintillaBase::SCI_LINESCROLLUP,
//! Scroll to the start of the document.
ScrollToStart = QsciScintillaBase::SCI_SCROLLTOSTART,
//! Scroll to the end of the document.
ScrollToEnd = QsciScintillaBase::SCI_SCROLLTOEND,
//! Scroll vertically to centre the current line.
VerticalCentreCaret = QsciScintillaBase::SCI_VERTICALCENTRECARET,
//! Move down one paragraph.
ParaDown = QsciScintillaBase::SCI_PARADOWN,
//! Extend the selection down one paragraph.
ParaDownExtend = QsciScintillaBase::SCI_PARADOWNEXTEND,
//! Move up one paragraph.
ParaUp = QsciScintillaBase::SCI_PARAUP,
//! Extend the selection up one paragraph.
ParaUpExtend = QsciScintillaBase::SCI_PARAUPEXTEND,
//! Move left one character.
CharLeft = QsciScintillaBase::SCI_CHARLEFT,
//! Extend the selection left one character.
CharLeftExtend = QsciScintillaBase::SCI_CHARLEFTEXTEND,
//! Extend the rectangular selection left one character.
CharLeftRectExtend = QsciScintillaBase::SCI_CHARLEFTRECTEXTEND,
//! Move right one character.
CharRight = QsciScintillaBase::SCI_CHARRIGHT,
//! Extend the selection right one character.
CharRightExtend = QsciScintillaBase::SCI_CHARRIGHTEXTEND,
//! Extend the rectangular selection right one character.
CharRightRectExtend = QsciScintillaBase::SCI_CHARRIGHTRECTEXTEND,
//! Move left one word.
WordLeft = QsciScintillaBase::SCI_WORDLEFT,
//! Extend the selection left one word.
WordLeftExtend = QsciScintillaBase::SCI_WORDLEFTEXTEND,
//! Move right one word.
WordRight = QsciScintillaBase::SCI_WORDRIGHT,
//! Extend the selection right one word.
WordRightExtend = QsciScintillaBase::SCI_WORDRIGHTEXTEND,
//! Move to the end of the previous word.
WordLeftEnd = QsciScintillaBase::SCI_WORDLEFTEND,
//! Extend the selection to the end of the previous word.
WordLeftEndExtend = QsciScintillaBase::SCI_WORDLEFTENDEXTEND,
//! Move to the end of the next word.
WordRightEnd = QsciScintillaBase::SCI_WORDRIGHTEND,
//! Extend the selection to the end of the next word.
WordRightEndExtend = QsciScintillaBase::SCI_WORDRIGHTENDEXTEND,
//! Move left one word part.
WordPartLeft = QsciScintillaBase::SCI_WORDPARTLEFT,
//! Extend the selection left one word part.
WordPartLeftExtend = QsciScintillaBase::SCI_WORDPARTLEFTEXTEND,
//! Move right one word part.
WordPartRight = QsciScintillaBase::SCI_WORDPARTRIGHT,
//! Extend the selection right one word part.
WordPartRightExtend = QsciScintillaBase::SCI_WORDPARTRIGHTEXTEND,
//! Move to the start of the document line.
Home = QsciScintillaBase::SCI_HOME,
//! Extend the selection to the start of the document line.
HomeExtend = QsciScintillaBase::SCI_HOMEEXTEND,
//! Extend the rectangular selection to the start of the document line.
HomeRectExtend = QsciScintillaBase::SCI_HOMERECTEXTEND,
//! Move to the start of the displayed line.
HomeDisplay = QsciScintillaBase::SCI_HOMEDISPLAY,
//! Extend the selection to the start of the displayed line.
HomeDisplayExtend = QsciScintillaBase::SCI_HOMEDISPLAYEXTEND,
//! Move to the start of the displayed or document line.
HomeWrap = QsciScintillaBase::SCI_HOMEWRAP,
//! Extend the selection to the start of the displayed or document
//! line.
HomeWrapExtend = QsciScintillaBase::SCI_HOMEWRAPEXTEND,
//! Move to the first visible character in the document line.
VCHome = QsciScintillaBase::SCI_VCHOME,
//! Extend the selection to the first visible character in the document
//! line.
VCHomeExtend = QsciScintillaBase::SCI_VCHOMEEXTEND,
//! Extend the rectangular selection to the first visible character in
//! the document line.
VCHomeRectExtend = QsciScintillaBase::SCI_VCHOMERECTEXTEND,
//! Move to the first visible character of the displayed or document
//! line.
VCHomeWrap = QsciScintillaBase::SCI_VCHOMEWRAP,
//! Extend the selection to the first visible character of the
//! displayed or document line.
VCHomeWrapExtend = QsciScintillaBase::SCI_VCHOMEWRAPEXTEND,
//! Move to the end of the document line.
LineEnd = QsciScintillaBase::SCI_LINEEND,
//! Extend the selection to the end of the document line.
LineEndExtend = QsciScintillaBase::SCI_LINEENDEXTEND,
//! Extend the rectangular selection to the end of the document line.
LineEndRectExtend = QsciScintillaBase::SCI_LINEENDRECTEXTEND,
//! Move to the end of the displayed line.
LineEndDisplay = QsciScintillaBase::SCI_LINEENDDISPLAY,
//! Extend the selection to the end of the displayed line.
LineEndDisplayExtend = QsciScintillaBase::SCI_LINEENDDISPLAYEXTEND,
//! Move to the end of the displayed or document line.
LineEndWrap = QsciScintillaBase::SCI_LINEENDWRAP,
//! Extend the selection to the end of the displayed or document line.
LineEndWrapExtend = QsciScintillaBase::SCI_LINEENDWRAPEXTEND,
//! Move to the start of the document.
DocumentStart = QsciScintillaBase::SCI_DOCUMENTSTART,
//! Extend the selection to the start of the document.
DocumentStartExtend = QsciScintillaBase::SCI_DOCUMENTSTARTEXTEND,
//! Move to the end of the document.
DocumentEnd = QsciScintillaBase::SCI_DOCUMENTEND,
//! Extend the selection to the end of the document.
DocumentEndExtend = QsciScintillaBase::SCI_DOCUMENTENDEXTEND,
//! Move up one page.
PageUp = QsciScintillaBase::SCI_PAGEUP,
//! Extend the selection up one page.
PageUpExtend = QsciScintillaBase::SCI_PAGEUPEXTEND,
//! Extend the rectangular selection up one page.
PageUpRectExtend = QsciScintillaBase::SCI_PAGEUPRECTEXTEND,
//! Move down one page.
PageDown = QsciScintillaBase::SCI_PAGEDOWN,
//! Extend the selection down one page.
PageDownExtend = QsciScintillaBase::SCI_PAGEDOWNEXTEND,
//! Extend the rectangular selection down one page.
PageDownRectExtend = QsciScintillaBase::SCI_PAGEDOWNRECTEXTEND,
//! Stuttered move up one page.
StutteredPageUp = QsciScintillaBase::SCI_STUTTEREDPAGEUP,
//! Stuttered extend the selection up one page.
StutteredPageUpExtend = QsciScintillaBase::SCI_STUTTEREDPAGEUPEXTEND,
//! Stuttered move down one page.
StutteredPageDown = QsciScintillaBase::SCI_STUTTEREDPAGEDOWN,
//! Stuttered extend the selection down one page.
StutteredPageDownExtend = QsciScintillaBase::SCI_STUTTEREDPAGEDOWNEXTEND,
//! Delete the current character.
Delete = QsciScintillaBase::SCI_CLEAR,
//! Delete the previous character.
DeleteBack = QsciScintillaBase::SCI_DELETEBACK,
//! Delete the previous character if not at start of line.
DeleteBackNotLine = QsciScintillaBase::SCI_DELETEBACKNOTLINE,
//! Delete the word to the left.
DeleteWordLeft = QsciScintillaBase::SCI_DELWORDLEFT,
//! Delete the word to the right.
DeleteWordRight = QsciScintillaBase::SCI_DELWORDRIGHT,
//! Delete right to the end of the next word.
DeleteWordRightEnd = QsciScintillaBase::SCI_DELWORDRIGHTEND,
//! Delete the line to the left.
DeleteLineLeft = QsciScintillaBase::SCI_DELLINELEFT,
//! Delete the line to the right.
DeleteLineRight = QsciScintillaBase::SCI_DELLINERIGHT,
//! Delete the current line.
LineDelete = QsciScintillaBase::SCI_LINEDELETE,
//! Cut the current line to the clipboard.
LineCut = QsciScintillaBase::SCI_LINECUT,
//! Copy the current line to the clipboard.
LineCopy = QsciScintillaBase::SCI_LINECOPY,
//! Transpose the current and previous lines.
LineTranspose = QsciScintillaBase::SCI_LINETRANSPOSE,
//! Duplicate the current line.
LineDuplicate = QsciScintillaBase::SCI_LINEDUPLICATE,
//! Select the whole document.
SelectAll = QsciScintillaBase::SCI_SELECTALL,
//! Move the selected lines up one line.
MoveSelectedLinesUp = QsciScintillaBase::SCI_MOVESELECTEDLINESUP,
//! Move the selected lines down one line.
MoveSelectedLinesDown = QsciScintillaBase::SCI_MOVESELECTEDLINESDOWN,
//! Duplicate the selection.
SelectionDuplicate = QsciScintillaBase::SCI_SELECTIONDUPLICATE,
//! Convert the selection to lower case.
SelectionLowerCase = QsciScintillaBase::SCI_LOWERCASE,
//! Convert the selection to upper case.
SelectionUpperCase = QsciScintillaBase::SCI_UPPERCASE,
//! Cut the selection to the clipboard.
SelectionCut = QsciScintillaBase::SCI_CUT,
//! Copy the selection to the clipboard.
SelectionCopy = QsciScintillaBase::SCI_COPY,
//! Paste from the clipboard.
Paste = QsciScintillaBase::SCI_PASTE,
//! Toggle insert/overtype.
EditToggleOvertype = QsciScintillaBase::SCI_EDITTOGGLEOVERTYPE,
//! Insert a platform dependent newline.
Newline = QsciScintillaBase::SCI_NEWLINE,
//! Insert a formfeed.
Formfeed = QsciScintillaBase::SCI_FORMFEED,
//! Indent one level.
Tab = QsciScintillaBase::SCI_TAB,
//! De-indent one level.
Backtab = QsciScintillaBase::SCI_BACKTAB,
//! Cancel any current operation.
Cancel = QsciScintillaBase::SCI_CANCEL,
//! Undo the last command.
Undo = QsciScintillaBase::SCI_UNDO,
//! Redo the last command.
Redo = QsciScintillaBase::SCI_REDO,
//! Zoom in.
ZoomIn = QsciScintillaBase::SCI_ZOOMIN,
//! Zoom out.
ZoomOut = QsciScintillaBase::SCI_ZOOMOUT,
};
//! Return the command that will be executed by this instance.
Command command() const {return scicmd;}
//! Execute the command.
void execute();
//! Binds the key \a key to the command. If \a key is 0 then the key
//! binding is removed. If \a key is invalid then the key binding is
//! unchanged. Valid keys are any visible or control character or any
//! of \c Key_Down, \c Key_Up, \c Key_Left, \c Key_Right, \c Key_Home,
//! \c Key_End, \c Key_PageUp, \c Key_PageDown, \c Key_Delete,
//! \c Key_Insert, \c Key_Escape, \c Key_Backspace, \c Key_Tab and
//! \c Key_Return. Keys may be modified with any combination of \c SHIFT,
//! \c CTRL, \c ALT and \c META.
//!
//! \sa key(), setAlternateKey(), validKey()
void setKey(int key);
//! Binds the alternate key \a altkey to the command. If \a key is 0
//! then the alternate key binding is removed.
//!
//! \sa alternateKey(), setKey(), validKey()
void setAlternateKey(int altkey);
//! The key that is currently bound to the command is returned.
//!
//! \sa setKey(), alternateKey()
int key() const {return qkey;}
//! The alternate key that is currently bound to the command is
//! returned.
//!
//! \sa setAlternateKey(), key()
int alternateKey() const {return qaltkey;}
//! If the key \a key is valid then true is returned.
static bool validKey(int key);
//! The user friendly description of the command is returned.
QString description() const;
private:
friend class QsciCommandSet;
QsciCommand(QsciScintilla *qs, Command cmd, int key, int altkey,
const char *desc);
void bindKey(int key,int &qk,int &scik);
QsciScintilla *qsCmd;
Command scicmd;
int qkey, scikey, qaltkey, scialtkey;
const char *descCmd;
QsciCommand(const QsciCommand &);
QsciCommand &operator=(const QsciCommand &);
};
#ifdef __APPLE__
}
#endif
#endif

116
samples/C++/qsciprinter.h Normal file
View File

@@ -0,0 +1,116 @@
// This module defines interface to the QsciPrinter class.
//
// Copyright (c) 2011 Riverbank Computing Limited <info@riverbankcomputing.com>
//
// This file is part of QScintilla.
//
// This file may be used under the terms of the GNU General Public
// License versions 2.0 or 3.0 as published by the Free Software
// Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
// included in the packaging of this file. Alternatively you may (at
// your option) use any later version of the GNU General Public
// License if such license has been publicly approved by Riverbank
// Computing Limited (or its successors, if any) and the KDE Free Qt
// Foundation. In addition, as a special exception, Riverbank gives you
// certain additional rights. These rights are described in the Riverbank
// GPL Exception version 1.1, which can be found in the file
// GPL_EXCEPTION.txt in this package.
//
// If you are unsure which license is appropriate for your use, please
// contact the sales department at sales@riverbankcomputing.com.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#ifndef QSCIPRINTER_H
#define QSCIPRINTER_H
#ifdef __APPLE__
extern "C++" {
#endif
#include <qprinter.h>
#include <Qsci/qsciglobal.h>
#include <Qsci/qsciscintilla.h>
QT_BEGIN_NAMESPACE
class QRect;
class QPainter;
QT_END_NAMESPACE
class QsciScintillaBase;
//! \brief The QsciPrinter class is a sub-class of the Qt QPrinter class that
//! is able to print the text of a Scintilla document.
//!
//! The class can be further sub-classed to alter to layout of the text, adding
//! headers and footers for example.
class QSCINTILLA_EXPORT QsciPrinter : public QPrinter
{
public:
//! Constructs a printer paint device with mode \a mode.
QsciPrinter(PrinterMode mode = ScreenResolution);
//! Destroys the QsciPrinter instance.
virtual ~QsciPrinter();
//! Format a page, by adding headers and footers for example, before the
//! document text is drawn on it. \a painter is the painter to be used to
//! add customised text and graphics. \a drawing is true if the page is
//! actually being drawn rather than being sized. \a painter drawing
//! methods must only be called when \a drawing is true. \a area is the
//! area of the page that will be used to draw the text. This should be
//! modified if it is necessary to reserve space for any customised text or
//! graphics. By default the area is relative to the printable area of the
//! page. Use QPrinter::setFullPage() because calling printRange() if you
//! want to try and print over the whole page. \a pagenr is the number of
//! the page. The first page is numbered 1.
virtual void formatPage(QPainter &painter, bool drawing, QRect &area,
int pagenr);
//! Return the number of points to add to each font when printing.
//!
//! \sa setMagnification()
int magnification() const {return mag;}
//! Sets the number of points to add to each font when printing to \a
//! magnification.
//!
//! \sa magnification()
virtual void setMagnification(int magnification);
//! Print a range of lines from the Scintilla instance \a qsb. \a from is
//! the first line to print and a negative value signifies the first line
//! of text. \a to is the last line to print and a negative value
//! signifies the last line of text. true is returned if there was no
//! error.
virtual int printRange(QsciScintillaBase *qsb, int from = -1, int to = -1);
//! Return the line wrap mode used when printing. The default is
//! QsciScintilla::WrapWord.
//!
//! \sa setWrapMode()
QsciScintilla::WrapMode wrapMode() const {return wrap;}
//! Sets the line wrap mode used when printing to \a wmode.
//!
//! \sa wrapMode()
virtual void setWrapMode(QsciScintilla::WrapMode wmode);
private:
int mag;
QsciScintilla::WrapMode wrap;
QsciPrinter(const QsciPrinter &);
QsciPrinter &operator=(const QsciPrinter &);
};
#ifdef __APPLE__
}
#endif
#endif

1267
samples/C/rf_io.c Normal file

File diff suppressed because it is too large Load Diff

682
samples/C/rf_io.h Normal file
View File

@@ -0,0 +1,682 @@
/**
** Copyright (c) 2011-2012, Karapetsas Eleftherios
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
** 2. 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.
** 3. Neither the name of the Original Author of Refu nor the names of its contributors may be used to endorse or promote products derived from
**
** 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 HOLDER 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.
**/
#ifndef REFU_IO_H
#define REFU_IO_H
#include <rf_setup.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C"
{// opening bracket for calling from C++
#endif
// New line feed
#define RF_LF 0xA
// Carriage Return
#define RF_CR 0xD
#ifdef REFU_WIN32_VERSION
#define i_PLUSB_WIN32 "b"
#else
#define i_PLUSB_WIN32 ""
#endif
// This is the type that represents the file offset
#ifdef _MSC_VER
typedef __int64 foff_rft;
#else
#include <sys/types.h>
typedef off64_t foff_rft;
#endif
///Fseek and Ftelll definitions
#ifdef _MSC_VER
#define rfFseek(i_FILE_,i_OFFSET_,i_WHENCE_) _fseeki64(i_FILE_,i_OFFSET_,i_WHENCE_)
#define rfFtell(i_FILE_) _ftelli64(i_FILE_)
#else
#define rfFseek(i_FILE_,i_OFFSET_,i_WHENCE_) fseeko64(i_FILE_,i_OFFSET_,i_WHENCE_)
#define rfFtell(i_FILE_) ftello64(i_FILE_)
#endif
/**
** @defgroup RF_IOGRP I/O
** @addtogroup RF_IOGRP
** @{
**/
// @brief Reads a UTF-8 file descriptor until end of line or EOF is found and returns a UTF-8 byte buffer
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// When the compile flag @c RF_NEWLINE_CRLF is defined (the default case at Windows) then this function
// shall not be adding any CR character that is found in the file behind a newline character since this is
// the Windows line ending scheme. Beware though that the returned read bytes value shall still count the CR character inside.
//
// @param[in] f The file descriptor to read
// @param[out] utf8 Give here a refence to an unitialized char* that will be allocated inside the function
// and contain the utf8 byte buffer. Needs to be freed by the caller explicitly later
// @param[out] byteLength Give an @c uint32_t here to receive the length of the @c utf8 buffer in bytes
// @param[out] bufferSize Give an @c uint32_t here to receive the capacity of the @c utf8 buffer in bytes
// @param[out] eof Pass a pointer to a char to receive a true or false value in case the end of file
// with reading this line
// @return Returns either a positive number for success that represents the number of bytes read from @c f and and error in case something goes wrong.
// The possible errors to return are the same as rfFgets_UTF8()
i_DECLIMEX_ int32_t rfFReadLine_UTF8(FILE* f,char** utf8,uint32_t* byteLength,uint32_t* bufferSize,char* eof);
// @brief Reads a Big Endian UTF-16 file descriptor until end of line or EOF is found and returns a UTF-8 byte buffer
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// When the compile flag @c RF_NEWLINE_CRLF is defined (the default case at Windows) then this function
// shall not be adding any CR character that is found in the file behind a newline character since this is
// the Windows line ending scheme. Beware though that the returned read bytes value shall still count the CR character inside.
//
// @param[in] f The file descriptor to read
// @param[out] utf8 Give here a refence to an unitialized char* that will be allocated inside the function
// and contain the utf8 byte buffer. Needs to be freed by the caller explicitly later
// @param[out] byteLength Give an @c uint32_t here to receive the length of the @c utf8 buffer in bytes
// @param[out] eof Pass a pointer to a char to receive a true or false value in case the end of file
// with reading this line
// @return Returns either a positive number for success that represents the number of bytes read from @c f and and error in case something goes wrong.
// + Any error that can be returned by @ref rfFgets_UTF16BE()
// + @c RE_UTF16_INVALID_SEQUENCE: Failed to decode the UTF-16 byte stream of the file descriptor
// + @c RE_UTF8_ENCODING: Failed to encode the UTF-16 of the file descriptor into UTF-8
i_DECLIMEX_ int32_t rfFReadLine_UTF16BE(FILE* f,char** utf8,uint32_t* byteLength,char* eof);
// @brief Reads a Little Endian UTF-16 file descriptor until end of line or EOF is found and returns a UTF-8 byte buffer
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// When the compile flag @c RF_NEWLINE_CRLF is defined (the default case at Windows) then this function
// shall not be adding any CR character that is found in the file behind a newline character since this is
// the Windows line ending scheme. Beware though that the returned read bytes value shall still count the CR character inside.
//
// @param[in] f The file descriptor to read
// @param[out] utf8 Give here a refence to an unitialized char* that will be allocated inside the function
// and contain the utf8 byte buffer. Needs to be freed by the caller explicitly later
// @param[out] byteLength Give an @c uint32_t here to receive the length of the @c utf8 buffer in bytes
// @param[out] eof Pass a pointer to a char to receive a true or false value in case the end of file
// with reading this line
// @return Returns either a positive number for success that represents the number of bytes read from @c f and and error in case something goes wrong.
// + Any error that can be returned by @ref rfFgets_UTF16LE()
// + @c RE_UTF16_INVALID_SEQUENCE: Failed to decode the UTF-16 byte stream of the file descriptor
// + @c RE_UTF8_ENCODING: Failed to encode the UTF-16 of the file descriptor into UTF-8
i_DECLIMEX_ int32_t rfFReadLine_UTF16LE(FILE* f,char** utf8,uint32_t* byteLength,char* eof);
// @brief Reads a Big Endian UTF-32 file descriptor until end of line or EOF is found and returns a UTF-8 byte buffer
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// When the compile flag @c RF_NEWLINE_CRLF is defined (the default case at Windows) then this function
// shall not be adding any CR character that is found in the file behind a newline character since this is
// the Windows line ending scheme. Beware though that the returned read bytes value shall still count the CR character inside.
//
// @param[in] f The file descriptor to read
// @param[out] utf8 Give here a refence to an unitialized char* that will be allocated inside the function
// and contain the utf8 byte buffer. Needs to be freed by the caller explicitly later
// @param[out] byteLength Give an @c uint32_t here to receive the length of the @c utf8 buffer in bytes
// @param[out] eof Pass a pointer to a char to receive a true or false value in case the end of file
// with reading this line
// @return Returns either a positive number for success that represents the number of bytes read from @c f and and error in case something goes wrong.
// + Any error that can be returned by @ref rfFgets_UTF32BE()
// + @c RE_UTF8_ENCODING: Failed to encode the UTF-16 of the file descriptor into UTF-8
i_DECLIMEX_ int32_t rfFReadLine_UTF32BE(FILE* f,char** utf8,uint32_t* byteLength,char* eof);
// @brief Reads a Little Endian UTF-32 file descriptor until end of line or EOF is found and returns a UTF-8 byte buffer
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// When the compile flag @c RF_NEWLINE_CRLF is defined (the default case at Windows) then this function
// shall not be adding any CR character that is found in the file behind a newline character since this is
// the Windows line ending scheme. Beware though that the returned read bytes value shall still count the CR character inside.
//
// @param[in] f The file descriptor to read
// @param[out] utf8 Give here a refence to an unitialized char* that will be allocated inside the function
// and contain the utf8 byte buffer. Needs to be freed by the caller explicitly later
// @param[out] byteLength Give an @c uint32_t here to receive the length of the @c utf8 buffer in bytes
// @param[out] eof Pass a pointer to a char to receive a true or false value in case the end of file
// with reading this line
// @return Returns either a positive number for success that represents the number of bytes read from @c f and and error in case something goes wrong.
// + Any error that can be returned by @ref rfFgets_UTF32LE()
// + @c RE_UTF8_ENCODING: Failed to encode the UTF-16 of the file descriptor into UTF-8
i_DECLIMEX_ int32_t rfFReadLine_UTF32LE(FILE* f,char** utf8,uint32_t* byteLength,char* eof);
// @brief Gets a number of bytes from a BIG endian UTF-32 file descriptor
//
// This is a function that's similar to c library fgets but it also returns the number of bytes read. Reads in from the file until @c num bytes
// have been read or new line or EOF character has been encountered.
//
// The function will read until @c num characters are read and if @c num
// would take us to the middle of a UTF32 character then the next character shall also be read
// and the function will return the number of bytes read.
// Since the function null terminates the buffer the given @c buff needs to be of at least
// @c num+7 size to cater for the worst case.
//
// The final bytestream stored inside @c buff is in the endianess of the system.
//
// If right after the last character read comes the EOF, the function
// shall detect so and assign @c true to @c eof.
//
// In Windows where file endings are in the form of 2 bytes CR-LF (Carriage return - NewLine) this function
// shall just ignore the carriage returns and not return it inside the return buffer at @c buff.
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param[in] buff A buffer to be filled with the contents of the file. Should be of size at least @c num+7
// @param[in] num The maximum number of bytes to read from within the file NOT including the null terminating character(which in itelf is 4 bytes). Should be a multiple of 4
// @param[in] f A valid FILE descriptor from which to read the bytes
// @param[out] eof Pass a reference to a char to receive a true/false value for whether EOF has been reached.
// @return Returns the actual number of bytes read or an error if there was a problem.
// The possible errors are:
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgets_UTF32BE(char* buff,uint32_t num,FILE* f,char* eof);
// @brief Gets a number of bytes from a Little endian UTF-32 file descriptor
//
// This is a function that's similar to c library fgets but it also returns the number of bytes read. Reads in from the file until @c num bytes
// have been read or new line or EOF character has been encountered.
//
// The function will read until @c num characters are read and if @c num
// would take us to the middle of a UTF32 character then the next character shall also be read
// and the function will return the number of bytes read.
// Since the function null terminates the buffer the given @c buff needs to be of at least
// @c num+7 size to cater for the worst case.
//
// The final bytestream stored inside @c buff is in the endianess of the system.
//
// If right after the last character read comes the EOF, the function
// shall detect so and assign @c true to @c eof.
//
// In Windows where file endings are in the form of 2 bytes CR-LF (Carriage return - NewLine) this function
// shall just ignore the carriage returns and not return it inside the return buffer at @c buff.
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param[in] buff A buffer to be filled with the contents of the file. Should be of size at least @c num+7
// @param[in] num The maximum number of bytes to read from within the file NOT including the null terminating character(which in itelf is 4 bytes). Should be a multiple of 4
// @param[in] f A valid FILE descriptor from which to read the bytes
// @param[out] eof Pass a reference to a char to receive a true/false value for whether EOF has been reached.
// @return Returns the actual number of bytes read or an error if there was a problem.
// The possible errors are:
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgets_UTF32LE(char* buff,uint32_t num,FILE* f,char* eof);
// @brief Gets a number of bytes from a BIG endian UTF-16 file descriptor
//
// This is a function that's similar to c library fgets but it also returns the number of bytes read. Reads in from the file until @c num bytes
// have been read or new line or EOF character has been encountered.
//
// The function will read until @c num characters are read and if @c num
// would take us to the middle of a UTF16 character then the next character shall also be read
// and the function will return the number of bytes read.
// Since the function null terminates the buffer the given @c buff needs to be of at least
// @c num+5 size to cater for the worst case.
//
// The final bytestream stored inside @c buff is in the endianess of the system.
//
// If right after the last character read comes the EOF, the function
// shall detect so and assign @c true to @c eof.
//
// In Windows where file endings are in the form of 2 bytes CR-LF (Carriage return - NewLine) this function
// shall just ignore the carriage returns and not return it inside the return buffer at @c buff.
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param[in] buff A buffer to be filled with the contents of the file. Should be of size at least @c num+5
// @param[in] num The maximum number of bytes to read from within the file NOT including the null terminating character(which in itelf is 2 bytes). Should be a multiple of 2
// @param[in] f A valid FILE descriptor from which to read the bytes
// @param[out] eof Pass a reference to a char to receive a true/false value for whether EOF has been reached.
// @return Returns the actual number of bytes read or an error if there was a problem.
// The possible errors are:
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgets_UTF16BE(char* buff,uint32_t num,FILE* f,char* eof);
// @brief Gets a number of bytes from a Little endian UTF-16 file descriptor
//
// This is a function that's similar to c library fgets but it also returns the number of bytes read. Reads in from the file until @c num bytes
// have been read or new line or EOF character has been encountered.
//
// The function will read until @c num characters are read and if @c num
// would take us to the middle of a UTF16 character then the next character shall also be read
// and the function will return the number of bytes read.
// Since the function null terminates the buffer the given @c buff needs to be of at least
// @c num+5 size to cater for the worst case.
//
// The final bytestream stored inside @c buff is in the endianess of the system.
//
// If right after the last character read comes the EOF, the function
// shall detect so and assign @c true to @c eof.
//
// In Windows where file endings are in the form of 2 bytes CR-LF (Carriage return - NewLine) this function
// shall just ignore the carriage returns and not return it inside the return buffer at @c buff.
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param[in] buff A buffer to be filled with the contents of the file. Should be of size at least @c num+2
// @param[in] num The maximum number of bytes to read from within the file NOT including the null terminating character(which in itelf is 2 bytes). Should be a multiple of 2
// @param[in] f A valid FILE descriptor from which to read the bytes
// @param[out] eof Pass a reference to a char to receive a true/false value for whether EOF has been reached.
// @return Returns the actual number of bytes read or an error if there was a problem.
// The possible errors are:
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgets_UTF16LE(char* buff,uint32_t num,FILE* f,char* eof);
// @brief Gets a number of bytes from a UTF-8 file descriptor
//
// This is a function that's similar to c library fgets but it also returns the number of bytes read. Reads in from the file until @c num characters
// have been read or new line or EOF character has been encountered.
//
// The function automatically adds a null termination character at the end of
// @c buff but this character is not included in the returned actual number of bytes.
//
// The function will read until @c num characters are read and if @c num
// would take us to the middle of a UTF8 character then the next character shall also be read
// and the function will return the number of bytes read.
// Since the function null terminates the buffer the given @c buff needs to be of at least
// @c num+4 size to cater for the worst case.
//
// If right after the last character read comes the EOF, the function
// shall detect so and assign @c true to @c eof.
//
// In Windows where file endings are in the form of 2 bytes CR-LF (Carriage return - NewLine) this function
// shall just ignore the carriage returns and not return it inside the return buffer at @c buff.
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param[in] buff A buffer to be filled with the contents of the file. Should of size at least @c num+4
// @param[in] num The maximum number of bytes to read from within the file NOT including the null terminating character(which in itelf is 1 byte)
// @param[in] f A valid FILE descriptor from which to read the bytes
// @param[out] eof Pass a reference to a char to receive a true/false value for whether EOF has been reached.
// @return Returns the actual number of bytes read or an error if there was a problem.
// The possible errors are:
// + @c RE_UTF8_INVALID_SEQUENCE_INVALID_BYTE: If an invalid UTF-8 byte has been found
// + @c RE_UTF8_INVALID_SEQUENCE_CONBYTE: If during parsing the file we were expecting a continuation
// byte and did not find it
// + @c RE_UTF8_INVALID_SEQUENCE_END: If the null character is encountered in between bytes that should
// have been continuation bytes
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgets_UTF8(char* buff,uint32_t num,FILE* f,char* eof);
// @brief Gets a unicode character from a UTF-8 file descriptor
//
// This function attempts to assume a more modern fgetc() role for UTF-8 encoded files.
// Reads bytes from the File descriptor @c f until a full UTF-8 unicode character has been read
//
// After this function the file pointer will have moved either by @c 1, @c 2, @c 3 or @c 4
// bytes if the return value is positive. You can see how much by checking the return value.
//
// You shall need to provide an integer at @c c to contain either the decoded Unicode
// codepoint or the UTF-8 endoced byte depending on the value of the @c cp argument.
//
// @param f A valid FILE descriptor from which to read the bytes
// @param c Pass an int that will receive either the unicode code point value or
// the UTF8 bytes depending on the value of the @c cp flag
// @param cp A boolean flag. If @c true then the int passed at @c c will contain the unicode code point
// of the read character, so the UTF-8 will be decoded.
// If @c false the int passed at @c c will contain the value of the read bytes in UTF-8 without any decoding
// @return Returns the number of bytes read (either @c 1, @c 2, @c 3 or @c 4) or an error if the function
// fails for some reason. Possible error values are:
// + @c RE_FILE_EOF: The end of file has been found while reading. If the end of file is encountered
// in the middle of a UTF-8 encoded character where we would be expecting something different
// and @c RE_UTF8_INVALID_SEQUENCE_END error is also logged
// + @c RE_UTF8_INVALID_SEQUENCE_INVALID_BYTE: If an invalid UTF-8 byte has been found
// + @c RE_UTF8_INVALID_SEQUENCE_CONBYTE: If during parsing the file we were expecting a continuation
// byte and did not find it
// + @c RE_UTF8_INVALID_SEQUENCE_END: If the null character is encountered in between bytes that should
// have been continuation bytes
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgetc_UTF8(FILE* f,uint32_t *c,char cp);
// @brief Gets a unicode character from a UTF-16 Big Endian file descriptor
//
// This function attempts to assume a more modern fgetc() role for UTF-16 encoded files.
// Reads bytes from the File descriptor @c f until a full UTF-16 unicode character has been read
//
// After this function the file pointer will have moved either by @c 2 or @c 4
// bytes if the return value is positive. You can see how much by checking the return value.
//
// You shall need to provide an integer at @c c to contain either the decoded Unicode
// codepoint or the Bigendian encoded UTF-16 bytes depending on the value of @c the cp argument.
//
// @param f A valid FILE descriptor from which to read the bytes
// @param c Pass an int that will receive either the unicode code point value or
// the UTF16 bytes depending on the value of the @c cp flag
// @param cp A boolean flag. If @c true then the int passed at @c c will contain the unicode code point
// of the read character, so the UTF-16 will be decoded.
// If @c false the int passed at @c c will contain the value of the read bytes in UTF-16 without any decoding
// @return Returns the number of bytes read (either @c 2 or @c 4) or an error if the function
// fails for some reason. Possible error values are:
// + @c RE_UTF16_INVALID_SEQUENCE: Either the read word or its surrogate pair if 4 bytes were read held illegal values
// + @c RE_UTF16_NO_SURRPAIR: According to the first read word a surrogate pair was expected but none was found
// + @c RE_FILE_EOF: The end of file has been found while reading. If the end of file is encountered
// while we expect a UTF-16 surrogate pair an appropriate error is logged
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgetc_UTF16BE(FILE* f,uint32_t *c,char cp);
// @brief Gets a unicode character from a UTF-16 Little Endian file descriptor
//
// This function attempts to assume a more modern fgetc() role for UTF-16 encoded files.
// Reads bytes from the File descriptor @c f until a full UTF-16 unicode character has been read
//
// After this function the file pointer will have moved either by @c 2 or @c 4
// bytes if the return value is positive. You can see how much by checking the return value.
//
// You shall need to provide an integer at @c c to contain either the decoded Unicode
// codepoint or the Bigendian encoded UTF-16 bytes depending on the value of @c the cp argument.
//
// @param f A valid FILE descriptor from which to read the bytes
// @param c Pass an int that will receive either the unicode code point value or
// the UTF16 bytes depending on the value of the @c cp flag
// @param cp A boolean flag. If @c true then the int passed at @c c will contain the unicode code point
// of the read character, so the UTF-16 will be decoded.
// If @c false the int passed at @c c will contain the value of the read bytes in UTF-16 without any decoding
// @return Returns the number of bytes read (either @c 2 or @c 4) or an error if the function
// fails for some reason. Possible error values are:
// + @c RE_UTF16_INVALID_SEQUENCE: Either the read word or its surrogate pair if 4 bytes were read held illegal values
// + @c RE_UTF16_NO_SURRPAIR: According to the first read word a surrogate pair was expected but none was found
// + @c RE_FILE_EOF: The end of file has been found while reading. If the end of file is encountered
// while we expect a UTF-16 surrogate pair an appropriate error is logged
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgetc_UTF16LE(FILE* f,uint32_t *c,char cp);
// @brief Gets a unicode character from a UTF-32 Little Endian file descriptor
//
// This function attempts to assume a more modern fgetc() role for UTF-32 encoded files.
// Reads bytes from the File descriptor @c f until a full UTF-32 unicode character has been read
//
// After this function the file pointer will have moved by @c 4
// bytes if the return value is positive.
//
// You shall need to provide an integer at @c to contain the UTF-32 codepoint.
//
// @param f A valid FILE descriptor from which to read the bytes
// @param c Pass an int that will receive either the unicode code point value or
// the UTF16 bytes depending on the value of the @c cp flag
// If @c false the int passed at @c c will contain the value of the read bytes in UTF-16 without any decoding
// @return Returns either @c RF_SUCCESS for succesfull readin or one of the following errors:
// + @c RE_FILE_EOF: The end of file has been found while reading.
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgetc_UTF32LE(FILE* f,uint32_t *c);
// @brief Gets a unicode character from a UTF-32 Big Endian file descriptor
//
// This function attempts to assume a more modern fgetc() role for UTF-32 encoded files.
// Reads bytes from the File descriptor @c f until a full UTF-32 unicode character has been read
//
// After this function the file pointer will have moved by @c 4
// bytes if the return value is positive.
//
// You shall need to provide an integer at @c to contain the UTF-32 codepoint.
//
// @param f A valid FILE descriptor from which to read the bytes
// @param c Pass an int that will receive either the unicode code point value or
// the UTF16 bytes depending on the value of the @c cp flag
// If @c false the int passed at @c c will contain the value of the read bytes in UTF-16 without any decoding
// @return Returns either @c RF_SUCCESS for succesfull readin or one of the following errors:
// + @c RE_FILE_EOF: The end of file has been found while reading.
// + @c RE_FILE_READ: If during reading the file there was an unknown read error
// + @c RE_FILE_READ_BLOCK: If the read operation failed due to the file descriptor being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the file descriptor's mode was not correctly set for reading
// + @c RE_FILE_POS_OVERFLOW: If during reading, the current file position can't be represented by the system
// + @c RE_INTERRUPT: If during reading, there was a system interrupt
// + @c RE_FILE_IO: If there was a physical I/O error
// + @c RE_FILE_NOSPACE: If reading failed due to insufficient storage space
i_DECLIMEX_ int32_t rfFgetc_UTF32BE(FILE* f,uint32_t *c);
// @brief Moves a unicode character backwards in a big endian UTF-32 file stream
//
// @param f The file stream
// @param c Returns the character we moved back to as a unicode codepoint
// @return Returns either @c RF_SUCCESS for success or one of the following errors:
// + @c RE_FILE_POS_OVERFLOW: If during trying to read the current file's position it can't be represented by the system
// + @c RE_FILE_BAD: If The file descriptor is corrupt/illegal
// + @c RE_FILE_NOTFILE: If the file descriptor is not a file but something else. e.g. socket.
// + @c RE_FILE_GETFILEPOS: If the file's position could not be retrieved for some unknown reason
// + @c RE_FILE_WRITE_BLOCK: While attempting to move the file pointer, it was occupied by another thread, and the no block flag was set
// + @c RE_INTERRUPT: Operating on the file failed due to a system interrupt
// + @c RE_FILE_IO: There was a physical I/O error
// + @c RE_FILE_NOSPACE: There was no space on the device holding the file
// + @c RE_FILE_NOTFILE: The device we attempted to manipulate is non-existent
// + @c RE_FILE_READ: If during reading the file there was an error
// + @c RE_FILE_READ_BLOCK: If during reading the file the read operation failed due to the file being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the underlying file descriptor's mode was not correctly set for reading
i_DECLIMEX_ int32_t rfFback_UTF32BE(FILE* f,uint32_t *c);
// @brief Moves a unicode character backwards in a little endian UTF-32 file stream
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param f The file stream
// @param c Returns the character we moved back to as a unicode codepoint
// @return Returns either @c RF_SUCCESS for success or one of the following errors:
// + @c RE_FILE_POS_OVERFLOW: If during trying to read the current file's position it can't be represented by the system
// + @c RE_FILE_BAD: If The file descriptor is corrupt/illegal
// + @c RE_FILE_NOTFILE: If the file descriptor is not a file but something else. e.g. socket.
// + @c RE_FILE_GETFILEPOS: If the file's position could not be retrieved for some unknown reason
// + @c RE_FILE_WRITE_BLOCK: While attempting to move the file pointer, it was occupied by another thread, and the no block flag was set
// + @c RE_INTERRUPT: Operating on the file failed due to a system interrupt
// + @c RE_FILE_IO: There was a physical I/O error
// + @c RE_FILE_NOSPACE: There was no space on the device holding the file
// + @c RE_FILE_NOTFILE: The device we attempted to manipulate is non-existent
// + @c RE_FILE_READ: If during reading the file there was an error
// + @c RE_FILE_READ_BLOCK: If during reading the file the read operation failed due to the file being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the underlying file descriptor's mode was not correctly set for reading
i_DECLIMEX_ int32_t rfFback_UTF32LE(FILE* f,uint32_t *c);
// @brief Moves a unicode character backwards in a big endian UTF-16 file stream
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param f The file stream
// @param c Returns the character we moved back to as a unicode codepoint
// @return Returns either the number of bytes moved backwards (either @c 4 or @c 2) for success or one of the following errors:
// + @c RE_UTF16_INVALID_SEQUENCE: Either the read word or its surrogate pair if 4 bytes were read held illegal values
// + @c RE_FILE_POS_OVERFLOW: If during trying to read the current file's position it can't be represented by the system
// + @c RE_FILE_BAD: If The file descriptor is corrupt/illegal
// + @c RE_FILE_NOTFILE: If the file descriptor is not a file but something else. e.g. socket.
// + @c RE_FILE_GETFILEPOS: If the file's position could not be retrieved for some unknown reason
// + @c RE_FILE_WRITE_BLOCK: While attempting to move the file pointer, it was occupied by another thread, and the no block flag was set
// + @c RE_INTERRUPT: Operating on the file failed due to a system interrupt
// + @c RE_FILE_IO: There was a physical I/O error
// + @c RE_FILE_NOSPACE: There was no space on the device holding the file
// + @c RE_FILE_NOTFILE: The device we attempted to manipulate is non-existent
// + @c RE_FILE_READ: If during reading the file there was an error
// + @c RE_FILE_READ_BLOCK: If during reading the file the read operation failed due to the file being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the underlying file descriptor's mode was not correctly set for reading
i_DECLIMEX_ int32_t rfFback_UTF16BE(FILE* f,uint32_t *c);
// @brief Moves a unicode character backwards in a little endian UTF-16 file stream
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param f The file stream
// @param c Returns the character we moved back to as a unicode codepoint
// @return Returns either the number of bytes moved backwards (either @c 4 or @c 2) for success or one of the following errors:
// + @c RE_UTF16_INVALID_SEQUENCE: Either the read word or its surrogate pair if 4 bytes were read held illegal values
// + @c RE_FILE_POS_OVERFLOW: If during trying to read the current file's position it can't be represented by the system
// + @c RE_FILE_BAD: If The file descriptor is corrupt/illegal
// + @c RE_FILE_NOTFILE: If the file descriptor is not a file but something else. e.g. socket.
// + @c RE_FILE_GETFILEPOS: If the file's position could not be retrieved for some unknown reason
// + @c RE_FILE_WRITE_BLOCK: While attempting to move the file pointer, it was occupied by another thread, and the no block flag was set
// + @c RE_INTERRUPT: Operating on the file failed due to a system interrupt
// + @c RE_FILE_IO: There was a physical I/O error
// + @c RE_FILE_NOSPACE: There was no space on the device holding the file
// + @c RE_FILE_NOTFILE: The device we attempted to manipulate is non-existent
// + @c RE_FILE_READ: If during reading the file there was an error
// + @c RE_FILE_READ_BLOCK: If during reading the file the read operation failed due to the file being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the underlying file descriptor's mode was not correctly set for reading
i_DECLIMEX_ int32_t rfFback_UTF16LE(FILE* f,uint32_t *c);
// @brief Moves a unicode character backwards in a UTF-8 file stream
//
// The file descriptor at @c f must have been opened in <b>binary</b> and not text mode. That means that if under
// Windows make sure to call fopen with "wb", "rb" e.t.c. instead of the simple "w", "r" e.t.c. since the initial
// default value under Windows is text mode. Alternatively you can set the initial value using _get_fmode() and
// _set_fmode(). For more information take a look at the msdn pages here:
// http://msdn.microsoft.com/en-us/library/ktss1a9b.aspx
//
// @param f The file stream
// @param c Returns the character we moved back to as a unicode codepoint
// @return Returns either the number of bytes moved backwards for success (either @c 4, @c 3, @c 2 or @c 1) or one of the following errors:
// + @c RE_UTF8_INVALID_SEQUENCE: If during moving bacwards in the file unexpected UTF-8 bytes were found
// + @c RE_FILE_POS_OVERFLOW: If during trying to read the current file's position it can't be represented by the system
// + @c RE_FILE_BAD: If The file descriptor is corrupt/illegal
// + @c RE_FILE_NOTFILE: If the file descriptor is not a file but something else. e.g. socket.
// + @c RE_FILE_GETFILEPOS: If the file's position could not be retrieved for some unknown reason
// + @c RE_FILE_WRITE_BLOCK: While attempting to move the file pointer, it was occupied by another thread, and the no block flag was set
// + @c RE_INTERRUPT: Operating on the file failed due to a system interrupt
// + @c RE_FILE_IO: There was a physical I/O error
// + @c RE_FILE_NOSPACE: There was no space on the device holding the file
// + @c RE_FILE_NOTFILE: The device we attempted to manipulate is non-existent
// + @c RE_FILE_READ: If during reading the file there was an error
// + @c RE_FILE_READ_BLOCK: If during reading the file the read operation failed due to the file being occupied by another thread
// + @c RE_FILE_MODE: If during reading the file the underlying file descriptor's mode was not correctly set for reading
i_DECLIMEX_ int32_t rfFback_UTF8(FILE* f,uint32_t *c);
// @brief Opens another process as a pipe
//
// This function is a cross-platform popen wrapper. In linux it uses popen and in Windows it uses
// _popen.
// @lmsFunction
// @param command The string with the command to execute. Is basically the name of the program/process you want to spawn
// with its full path and its parameters. @inhtype{String,StringX} @tmpSTR
// @param mode The mode you want the pipe to work in. There are two possible values:
// + @c "r" The calling process can read the spawned command's standard output via the returned stream.
// + @c "w" The calling process can write to the spawned command's standard input via the returned stream.
//
// Anything else will result in an error
// @return For success popen will return a FILE descriptor that can be used to either read or write from the pipe.
// If there was an error @c 0 is returned and an error is logged.
#ifdef RF_IAMHERE_FOR_DOXYGEN
i_DECLIMEX_ FILE* rfPopen(void* command,const char* mode);
#else
i_DECLIMEX_ FILE* i_rfPopen(void* command,const char* mode);
#define rfPopen(i_CMD_,i_MODE_) i_rfLMS_WRAP2(FILE*,i_rfPopen,i_CMD_,i_MODE_)
#endif
// @brief Closes a pipe
//
// This function is a cross-platform wrapper for pclose. It closes a file descriptor opened with @ref rfPopen() and
// returns the exit code of the process that was running
// @param stream The file descriptor of the pipe returned by @ref rfPopen() that we want to close
// @return Returns the exit code of the process or -1 if there was an error
i_DECLIMEX_ int rfPclose(FILE* stream);
// @} End of I/O group
#ifdef __cplusplus
}///closing bracket for calling from C++
#endif
#endif//include guards end

2348
samples/C/rfc_string.c Normal file

File diff suppressed because it is too large Load Diff

1459
samples/C/rfc_string.h Normal file

File diff suppressed because it is too large Load Diff

1363
samples/C/wglew.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +1,3 @@
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(** This file is deprecated, for a tree on list, use [Mergesort.v]. *)
(** A development of Treesort on Heap trees. It has an average
complexity of O(n.log n) but of O() in the worst case (e.g. if
the list is already sorted) *)
@@ -88,9 +78,9 @@ Section defs.
forall P:Tree -> Type,
P Tree_Leaf ->
(forall (a:A) (T1 T2:Tree),
leA_Tree a T1 ->
leA_Tree a T2 ->
is_heap T1 -> P T1 -> is_heap T2 -> P T2 -> P (Tree_Node a T1 T2)) ->
leA_Tree a T1 ->
leA_Tree a T2 ->
is_heap T1 -> P T1 -> is_heap T2 -> P T2 -> P (Tree_Node a T1 T2)) ->
forall T:Tree, is_heap T -> P T.
Proof.
simple induction T; auto with datatypes.
@@ -105,9 +95,9 @@ Section defs.
forall P:Tree -> Set,
P Tree_Leaf ->
(forall (a:A) (T1 T2:Tree),
leA_Tree a T1 ->
leA_Tree a T2 ->
is_heap T1 -> P T1 -> is_heap T2 -> P T2 -> P (Tree_Node a T1 T2)) ->
leA_Tree a T1 ->
leA_Tree a T2 ->
is_heap T1 -> P T1 -> is_heap T2 -> P T2 -> P (Tree_Node a T1 T2)) ->
forall T:Tree, is_heap T -> P T.
Proof.
simple induction T; auto with datatypes.
@@ -135,13 +125,13 @@ Section defs.
(forall a, HdRel leA a l1 -> HdRel leA a l2 -> HdRel leA a l) ->
merge_lem l1 l2.
Require Import Morphisms.
Instance: Equivalence (@meq A).
Proof. constructor; auto with datatypes. red. apply meq_trans. Defined.
Instance: Proper (@meq A ++> @meq _ ++> @meq _) (@munion A).
Proof. intros x y H x' y' H'. now apply meq_congr. Qed.
Lemma merge :
forall l1:list A, Sorted leA l1 ->
forall l2:list A, Sorted leA l2 -> merge_lem l1 l2.
@@ -150,8 +140,8 @@ Section defs.
apply merge_exist with l2; auto with datatypes.
rename l1 into l.
revert l2 H0. fix 1. intros.
destruct l2 as [|a0 l0].
apply merge_exist with (a :: l); simpl; auto with datatypes.
destruct l2 as [|a0 l0].
apply merge_exist with (a :: l); simpl; auto with datatypes.
elim (leA_dec a a0); intros.
(* 1 (leA a a0) *)
@@ -159,18 +149,18 @@ Section defs.
destruct (merge l H (a0 :: l0) H0).
apply merge_exist with (a :: l1). clear merge merge0.
auto using cons_sort, cons_leA with datatypes.
simpl. rewrite m. now rewrite munion_ass.
intros. apply cons_leA.
simpl. rewrite m. now rewrite munion_ass.
intros. apply cons_leA.
apply (@HdRel_inv _ leA) with l; trivial with datatypes.
(* 2 (leA a0 a) *)
apply Sorted_inv in H0. destruct H0.
destruct (merge0 l0 H0). clear merge merge0.
apply merge_exist with (a0 :: l1);
destruct (merge0 l0 H0). clear merge merge0.
apply merge_exist with (a0 :: l1);
auto using cons_sort, cons_leA with datatypes.
simpl; rewrite m. simpl. setoid_rewrite munion_ass at 1. rewrite munion_comm.
repeat rewrite munion_ass. setoid_rewrite munion_comm at 3. reflexivity.
intros. apply cons_leA.
intros. apply cons_leA.
apply (@HdRel_inv _ leA) with l0; trivial with datatypes.
Qed.
@@ -186,7 +176,7 @@ Section defs.
match t with
| Tree_Leaf => emptyBag
| Tree_Node a t1 t2 =>
munion (contents t1) (munion (contents t2) (singletonBag a))
munion (contents t1) (munion (contents t2) (singletonBag a))
end.
@@ -272,11 +262,11 @@ Section defs.
apply flat_exist with (a :: l); simpl; auto with datatypes.
apply meq_trans with
(munion (list_contents _ eqA_dec l1)
(munion (list_contents _ eqA_dec l2) (singletonBag a))).
(munion (list_contents _ eqA_dec l2) (singletonBag a))).
apply meq_congr; auto with datatypes.
apply meq_trans with
(munion (singletonBag a)
(munion (list_contents _ eqA_dec l1) (list_contents _ eqA_dec l2))).
(munion (list_contents _ eqA_dec l1) (list_contents _ eqA_dec l2))).
apply munion_rotate.
apply meq_right; apply meq_sym; trivial with datatypes.
Qed.

View File

@@ -1,11 +1,3 @@
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Require Import Omega Relations Multiset SetoidList.
(** This file is deprecated, use [Permutation.v] instead.
@@ -154,7 +146,7 @@ Lemma permut_add_cons_inside :
Proof.
intros;
replace (a :: l) with ([] ++ a :: l); trivial;
apply permut_add_inside; trivial.
apply permut_add_inside; trivial.
Qed.
Lemma permut_middle :
@@ -168,8 +160,8 @@ Lemma permut_sym_app :
Proof.
intros l1 l2;
unfold permutation, meq;
intro a; do 2 rewrite list_contents_app; simpl;
auto with arith.
intro a; do 2 rewrite list_contents_app; simpl;
auto with arith.
Qed.
Lemma permut_rev :

View File

@@ -1,17 +1,5 @@
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*********************************************************************)
(** * List permutations as a composition of adjacent transpositions *)
(*********************************************************************)
(* Adapted in May 2006 by Jean-Marc Notin from initial contents by
Laurent Théry (Huffmann contribution, October 2003) *)
Laurent Thery (Huffmann contribution, October 2003) *)
Require Import List Setoid Compare_dec Morphisms.
Import ListNotations. (* For notations [] and [a;b;c] *)

View File

@@ -1,10 +1,2 @@
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Require Export Sorted.
Require Export Mergesort.

42
samples/Ecl/sample.ecl Normal file
View File

@@ -0,0 +1,42 @@
/*
* Multi-line comment
*/
#option ('slidingJoins', true);
namesRecord :=
RECORD
string20 surname;
string10 forename;
integer2 age;
integer2 dadAge;
integer2 mumAge;
END;
namesRecord2 :=
record
string10 extra;
namesRecord;
end;
namesTable := dataset('x',namesRecord,FLAT);
namesTable2 := dataset('y',namesRecord2,FLAT);
integer2 aveAgeL(namesRecord l) := (l.dadAge+l.mumAge)/2;
integer2 aveAgeR(namesRecord2 r) := (r.dadAge+r.mumAge)/2;
// Standard join on a function of left and right
output(join(namesTable, namesTable2, aveAgeL(left) = aveAgeR(right)));
//Several simple examples of sliding join syntax
output(join(namesTable, namesTable2, left.age >= right.age - 10 and left.age <= right.age +10));
output(join(namesTable, namesTable2, left.age between right.age - 10 and right.age +10));
output(join(namesTable, namesTable2, left.age between right.age + 10 and right.age +30));
output(join(namesTable, namesTable2, left.age between (right.age + 20) - 10 and (right.age +20) + 10));
output(join(namesTable, namesTable2, aveAgeL(left) between aveAgeR(right)+10 and aveAgeR(right)+40));
//Same, but on strings. Also includes age to ensure sort is done by non-sliding before sliding.
output(join(namesTable, namesTable2, left.surname between right.surname[1..10]+'AAAAAAAAAA' and right.surname[1..10]+'ZZZZZZZZZZ' and left.age=right.age));
output(join(namesTable, namesTable2, left.surname between right.surname[1..10]+'AAAAAAAAAA' and right.surname[1..10]+'ZZZZZZZZZZ' and left.age=right.age,all));
//This should not generate a self join
output(join(namesTable, namesTable, left.age between right.age - 10 and right.age +10));

127
samples/Elm/Basic.elm Normal file
View File

@@ -0,0 +1,127 @@
import List (intercalate,intersperse)
import Website.Skeleton
import Website.ColorScheme
addFolder folder lst =
let add (x,y) = (x, folder ++ y ++ ".elm") in
let f (n,xs) = (n, map add xs) in
map f lst
elements = addFolder "Elements/"
[ ("Primitives",
[ ("Text" , "HelloWorld")
, ("Images", "Image")
, ("Fitted Images", "FittedImage")
, ("Videos", "Video")
, ("Markdown", "Markdown")
])
, ("Formatting",
[ ("Size" , "Size")
, ("Opacity" , "Opacity")
, ("Text" , "Text")
, ("Typeface", "Typeface")
])
, ("Layout",
[ ("Simple Flow", "FlowDown1a")
, ("Flow Down" , "FlowDown2")
, ("Layers" , "Layers")
, ("Positioning", "Position")
, ("Spacers" , "Spacer")
])
, ("Collage", [ ("Lines" , "Lines")
, ("Shapes" , "Shapes")
, ("Sprites" , "Sprite")
, ("Elements" , "ToForm")
, ("Colors" , "Color")
, ("Textures" , "Texture")
, ("Transforms", "Transforms")
])
]
functional = addFolder "Functional/"
[ ("Recursion",
[ ("Factorial" , "Factorial")
, ("List Length", "Length")
, ("Zip" , "Zip")
, ("Quick Sort" , "QuickSort")
])
, ("Functions",
[ ("Anonymous Functions", "Anonymous")
, ("Application" , "Application")
, ("Composition" , "Composition")
, ("Infix Operators" , "Infix")
])
, ("Higher-Order",
[ ("Map" , "Map")
, ("Fold" , "Sum")
, ("Filter" , "Filter")
, ("ZipWith", "ZipWith")
])
, ("Data Types",
[ ("Maybe", "Maybe")
, ("Boolean Expressions", "BooleanExpressions")
, ("Tree", "Tree")
])
]
reactive = addFolder "Reactive/"
[ ("Mouse", [ ("Position", "Position")
, ("Presses" , "IsDown")
, ("Clicks" , "CountClicks")
, ("Position+Image", "ResizeYogi")
, ("Position+Collage" , "Transforms")
-- , ("Hover" , "IsAbove")
])
,("Keyboard",[ ("Keys Down" , "KeysDown")
, ("Key Presses", "CharPressed")
])
, ("Window", [ ("Size", "ResizePaint")
, ("Centering", "Centering")
])
, ("Time", [ ("Before and After", "Between")
, ("Every" , "Every")
, ("Clock" , "Clock")
])
, ("Input", [ ("Text Fields", "TextField")
, ("Passwords" , "Password")
, ("Check Boxes", "CheckBox")
, ("String Drop Down", "StringDropDown")
, ("Drop Down", "DropDown")
])
, ("Random", [ ("Randomize", "Randomize") ])
, ("HTTP", [ ("Zip Codes", "ZipCodes") ])
, ("Filters",[ ("Sample", "SampleOn")
, ("Keep If", "KeepIf")
, ("Drop Repeats", "DropRepeats")
])
]
example (name, loc) = Text.link ("/edit/examples/" ++ loc) (toText name)
toLinks (title, links) =
flow right [ width 130 (text $ toText " " ++ italic (toText title))
, text (intercalate (bold . Text.color accent4 $ toText " &middot; ") $ map example links)
]
insertSpace lst = case lst of { x:xs -> x : spacer 1 5 : xs ; [] -> [] }
subsection w (name,info) =
flow down . insertSpace . intersperse (spacer 1 1) . map (width w) $
(text . bold $ toText name) : map toLinks info
words = [markdown|
### Basic Examples
Each example listed below focuses on a single function or concept.
These examples demonstrate all of the basic building blocks of Elm.
|]
content w =
words : map (subsection w) [ ("Display",elements), ("React",reactive), ("Compute",functional) ]
exampleSets w = flow down . map (width w) . intersperse (plainText " ") $ content w
main = lift (skeleton exampleSets) Window.width

32
samples/Elm/QuickSort.elm Normal file
View File

@@ -0,0 +1,32 @@
main = asText (qsort [3,9,1,8,5,4,7])
qsort lst =
case lst of
x:xs -> qsort (filter ((>=)x) xs) ++ [x] ++ qsort (filter ((<)x) xs)
[] -> []
{---------------------
QuickSort works as follows:
- Choose a pivot element which be placed in the "middle" of the sorted list.
In our case we are choosing the first element as the pivot.
- Gather all of the elements less than the pivot (the first filter).
We know that these must come before our pivot element in the sorted list.
Note: ((>=)x) === (\y -> (>=) x y) === (\y -> x >= y)
- Gather all of the elements greater than the pivot (the second filter).
We know that these must come after our pivot element in the sorted list.
- Run `qsort` on the lesser elements, producing a sorted list that contains
only elements less than the pivot. Put these before the pivot.
- Run `qsort` on the greater elements, producing a sorted list. Put these
after the pivot.
Note that choosing a bad pivot can have bad effects. Take a sorted list with
N elements. The pivot will always be the lowest member, meaning that it does
not divide the list very evenly. The list of lessers has 0 elements
and the list of greaters has N-1 elemens. This means qsort will be called
N times, each call looking through the entire list. This means, in the worst
case, QuickSort will make N^2 comparisons.
----------------------}

91
samples/Elm/Tree.elm Normal file
View File

@@ -0,0 +1,91 @@
{-----------------------------------------------------------------
Overview: A "Tree" represents a binary tree. A "Node" in a binary
tree always has two children. A tree can also be "Empty". Below
I have defined "Tree" and a number of useful functions.
This example also includes some challenge problems :)
-----------------------------------------------------------------}
data Tree a = Node a (Tree a) (Tree a) | Empty
empty = Empty
singleton v = Node v Empty Empty
insert x tree =
case tree of
Empty -> singleton x
Node y left right ->
if x == y then tree else
if x < y then Node y (insert x left) right
else Node y left (insert x right)
fromList xs = foldl insert empty xs
depth tree =
case tree of
Node v left right -> 1 + max (depth left) (depth right)
Empty -> 0
map f tree =
case tree of
Node v left right -> Node (f v) (map f left) (map f right)
Empty -> Empty
t1 = fromList [1,2,3]
t2 = fromList [2,1,3]
main = flow down [ display "depth" depth t1
, display "depth" depth t2
, display "map ((+)1)" (map ((+)1)) t2
]
display name f v =
text . monospace . toText $
concat [ show (f v), " &lArr; ", name, " ", show v ]
{-----------------------------------------------------------------
Exercises:
(1) Sum all of the elements of a tree.
sum :: Tree Number -> Number
(2) Flatten a tree into a list.
flatten :: Tree a -> [a]
(3) Check to see if an element is in a given tree.
isElement :: a -> Tree a -> Bool
(4) Write a general fold function that acts on trees. The fold
function does not need to guarantee a particular order of
traversal.
fold :: (a -> b -> b) -> b -> Tree a -> b
(5) Use "fold" to do exercises 1-3 in one line each. The best
readable versions I have come up have the following length
in characters including spaces and function name:
sum: 16
flatten: 21
isElement: 46
See if you can match or beat me! Don't forget about currying
and partial application!
(6) Can "fold" be used to implement "map" or "depth"?
(7) Try experimenting with different ways to traverse a
tree: pre-order, in-order, post-order, depth-first, etc.
More info at: http://en.wikipedia.org/wiki/Tree_traversal
-----------------------------------------------------------------}

View File

@@ -0,0 +1,6 @@
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>

View File

@@ -0,0 +1,11 @@
<div class="post">
<h1>By {{fullName author}}</h1>
<div class="body">{{body}}</div>
<h1>Comments</h1>
{{#each comments}}
<h2>By {{fullName author}}</h2>
<div class="body">{{body}}</div>
{{/each}}
</div>

367
samples/JSON/Hello.maxhelp Normal file
View File

@@ -0,0 +1,367 @@
{
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 5,
"minor" : 1,
"revision" : 9
}
,
"rect" : [ 198.0, 92.0, 365.0, 407.0 ],
"bglocked" : 0,
"defrect" : [ 198.0, 92.0, 365.0, 407.0 ],
"openrect" : [ 0.0, 0.0, 0.0, 0.0 ],
"openinpresentation" : 0,
"default_fontsize" : 14.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 0,
"gridsize" : [ 20.0, 20.0 ],
"gridsnaponopen" : 0,
"toolbarvisible" : 1,
"boxanimatetime" : 200,
"imprint" : 0,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"boxes" : [ {
"box" : {
"maxclass" : "button",
"patching_rect" : [ 260.0, 260.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"id" : "obj-22"
}
}
, {
"box" : {
"maxclass" : "button",
"patching_rect" : [ 240.0, 260.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"id" : "obj-20"
}
}
, {
"box" : {
"maxclass" : "button",
"patching_rect" : [ 220.0, 260.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"id" : "obj-18"
}
}
, {
"box" : {
"maxclass" : "button",
"patching_rect" : [ 200.0, 260.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"id" : "obj-16"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "route 0 1 2 3",
"patching_rect" : [ 200.0, 220.0, 99.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 5,
"outlettype" : [ "", "", "", "", "" ],
"fontsize" : 14.0,
"id" : "obj-14"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "r jojo",
"patching_rect" : [ 200.0, 180.0, 41.0, 23.0 ],
"numinlets" : 0,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "" ],
"fontsize" : 14.0,
"color" : [ 0.827451, 0.737255, 0.835294, 1.0 ],
"id" : "obj-13"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "s jojo",
"patching_rect" : [ 20.0, 340.0, 43.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 0,
"fontsize" : 14.0,
"color" : [ 0.827451, 0.737255, 0.835294, 1.0 ],
"id" : "obj-12"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "append toto",
"patching_rect" : [ 20.0, 300.0, 84.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "" ],
"fontsize" : 14.0,
"id" : "obj-11"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "% 4",
"patching_rect" : [ 20.0, 260.0, 35.0, 23.0 ],
"numinlets" : 2,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "int" ],
"fontsize" : 14.0,
"id" : "obj-10"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "counter",
"patching_rect" : [ 20.0, 220.0, 73.0, 23.0 ],
"numinlets" : 5,
"fontname" : "Arial",
"numoutlets" : 4,
"outlettype" : [ "int", "", "", "int" ],
"fontsize" : 14.0,
"id" : "obj-9"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "metro 250",
"patching_rect" : [ 20.0, 180.0, 74.0, 23.0 ],
"numinlets" : 2,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"fontsize" : 14.0,
"id" : "obj-8"
}
}
, {
"box" : {
"maxclass" : "toggle",
"patching_rect" : [ 20.0, 140.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "int" ],
"id" : "obj-7"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "t 0",
"patching_rect" : [ 140.0, 80.0, 26.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "int" ],
"fontsize" : 14.0,
"id" : "obj-5"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "t 1",
"patching_rect" : [ 20.0, 80.0, 26.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "int" ],
"fontsize" : 14.0,
"id" : "obj-4"
}
}
, {
"box" : {
"maxclass" : "message",
"text" : "Goodbye World !",
"patching_rect" : [ 140.0, 40.0, 115.0, 21.0 ],
"numinlets" : 2,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "" ],
"fontsize" : 14.0,
"id" : "obj-3"
}
}
, {
"box" : {
"maxclass" : "message",
"text" : "Hello World !",
"patching_rect" : [ 20.0, 40.0, 90.0, 21.0 ],
"numinlets" : 2,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "" ],
"fontsize" : 14.0,
"id" : "obj-2"
}
}
],
"lines" : [ {
"patchline" : {
"source" : [ "obj-2", 0 ],
"destination" : [ "obj-4", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-3", 0 ],
"destination" : [ "obj-5", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-4", 0 ],
"destination" : [ "obj-7", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-5", 0 ],
"destination" : [ "obj-7", 0 ],
"hidden" : 0,
"midpoints" : [ 149.5, 121.0, 29.5, 121.0 ]
}
}
, {
"patchline" : {
"source" : [ "obj-7", 0 ],
"destination" : [ "obj-8", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-8", 0 ],
"destination" : [ "obj-9", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-9", 0 ],
"destination" : [ "obj-10", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-10", 0 ],
"destination" : [ "obj-11", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-11", 0 ],
"destination" : [ "obj-12", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-13", 0 ],
"destination" : [ "obj-14", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-14", 0 ],
"destination" : [ "obj-16", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-14", 1 ],
"destination" : [ "obj-18", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-14", 2 ],
"destination" : [ "obj-20", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-14", 3 ],
"destination" : [ "obj-22", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
]
}
}

368
samples/JSON/Hello.maxpat Normal file
View File

@@ -0,0 +1,368 @@
{
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 5,
"minor" : 1,
"revision" : 9
}
,
"rect" : [ 198.0, 92.0, 365.0, 407.0 ],
"bglocked" : 0,
"defrect" : [ 198.0, 92.0, 365.0, 407.0 ],
"openrect" : [ 0.0, 0.0, 0.0, 0.0 ],
"openinpresentation" : 0,
"default_fontsize" : 14.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 0,
"gridsize" : [ 20.0, 20.0 ],
"gridsnaponopen" : 0,
"toolbarvisible" : 1,
"boxanimatetime" : 200,
"imprint" : 0,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"boxes" : [ {
"box" : {
"maxclass" : "button",
"patching_rect" : [ 260.0, 260.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"id" : "obj-22"
}
}
, {
"box" : {
"maxclass" : "button",
"patching_rect" : [ 240.0, 260.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"id" : "obj-20"
}
}
, {
"box" : {
"maxclass" : "button",
"patching_rect" : [ 220.0, 260.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"id" : "obj-18"
}
}
, {
"box" : {
"maxclass" : "button",
"patching_rect" : [ 200.0, 260.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"id" : "obj-16"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "route 0 1 2 3",
"patching_rect" : [ 200.0, 220.0, 99.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 5,
"outlettype" : [ "", "", "", "", "" ],
"fontsize" : 14.0,
"id" : "obj-14"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "r jojo",
"patching_rect" : [ 200.0, 180.0, 41.0, 23.0 ],
"numinlets" : 0,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "" ],
"fontsize" : 14.0,
"color" : [ 0.827451, 0.737255, 0.835294, 1.0 ],
"id" : "obj-13"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "s jojo",
"patching_rect" : [ 20.0, 340.0, 43.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 0,
"fontsize" : 14.0,
"color" : [ 0.827451, 0.737255, 0.835294, 1.0 ],
"id" : "obj-12"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "append toto",
"patching_rect" : [ 20.0, 300.0, 84.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "" ],
"fontsize" : 14.0,
"id" : "obj-11"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "% 4",
"patching_rect" : [ 20.0, 260.0, 35.0, 23.0 ],
"numinlets" : 2,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "int" ],
"fontsize" : 14.0,
"id" : "obj-10"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "counter",
"patching_rect" : [ 20.0, 220.0, 73.0, 23.0 ],
"numinlets" : 5,
"fontname" : "Arial",
"numoutlets" : 4,
"outlettype" : [ "int", "", "", "int" ],
"fontsize" : 14.0,
"id" : "obj-9"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "metro 250",
"patching_rect" : [ 20.0, 180.0, 74.0, 23.0 ],
"numinlets" : 2,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"fontsize" : 14.0,
"id" : "obj-8"
}
}
, {
"box" : {
"maxclass" : "toggle",
"patching_rect" : [ 20.0, 140.0, 20.0, 20.0 ],
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "int" ],
"id" : "obj-7"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "t 0",
"patching_rect" : [ 140.0, 80.0, 26.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "int" ],
"fontsize" : 14.0,
"id" : "obj-5"
}
}
, {
"box" : {
"maxclass" : "newobj",
"text" : "t 1",
"patching_rect" : [ 20.0, 80.0, 26.0, 23.0 ],
"numinlets" : 1,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "int" ],
"fontsize" : 14.0,
"id" : "obj-4"
}
}
, {
"box" : {
"maxclass" : "message",
"text" : "Goodbye World !",
"patching_rect" : [ 140.0, 40.0, 115.0, 21.0 ],
"numinlets" : 2,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "" ],
"fontsize" : 14.0,
"presentation_rect" : [ 137.0, 42.0, 0.0, 0.0 ],
"id" : "obj-3"
}
}
, {
"box" : {
"maxclass" : "message",
"text" : "Hello World !",
"patching_rect" : [ 20.0, 40.0, 90.0, 21.0 ],
"numinlets" : 2,
"fontname" : "Arial",
"numoutlets" : 1,
"outlettype" : [ "" ],
"fontsize" : 14.0,
"id" : "obj-2"
}
}
],
"lines" : [ {
"patchline" : {
"source" : [ "obj-14", 3 ],
"destination" : [ "obj-22", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-14", 2 ],
"destination" : [ "obj-20", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-14", 1 ],
"destination" : [ "obj-18", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-14", 0 ],
"destination" : [ "obj-16", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-13", 0 ],
"destination" : [ "obj-14", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-11", 0 ],
"destination" : [ "obj-12", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-10", 0 ],
"destination" : [ "obj-11", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-9", 0 ],
"destination" : [ "obj-10", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-8", 0 ],
"destination" : [ "obj-9", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-7", 0 ],
"destination" : [ "obj-8", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-5", 0 ],
"destination" : [ "obj-7", 0 ],
"hidden" : 0,
"midpoints" : [ 149.5, 121.0, 29.5, 121.0 ]
}
}
, {
"patchline" : {
"source" : [ "obj-4", 0 ],
"destination" : [ "obj-7", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-3", 0 ],
"destination" : [ "obj-5", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
, {
"patchline" : {
"source" : [ "obj-2", 0 ],
"destination" : [ "obj-4", 0 ],
"hidden" : 0,
"midpoints" : [ ]
}
}
]
}
}

23
samples/JSON/person.json Normal file
View File

@@ -0,0 +1,23 @@
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
}

View File

@@ -0,0 +1,7 @@
{
"id": 1,
"name": "Foo",
"price": 123,
"tags": ["Bar","Eek"],
"stock": { "warehouse":300, "retail":20 }
}

47
samples/JSON/schema.json Normal file
View File

@@ -0,0 +1,47 @@
{
"name":"Product",
"properties":
{
"id":
{
"type":"number",
"description":"Product identifier",
"required":true
},
"name":
{
"type":"string",
"description":"Name of the product",
"required":true
},
"price":
{
"type":"number",
"minimum":0,
"required":true
},
"tags":
{
"type":"array",
"items":
{
"type":"string"
}
},
"stock":
{
"type":"object",
"properties":
{
"warehouse":
{
"type":"number"
},
"retail":
{
"type":"number"
}
}
}
}
}

View File

@@ -0,0 +1,7 @@
#!/usr/bin/env node
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

1
samples/Max/Hello.mxt Normal file
View File

@@ -0,0 +1 @@
max v2;

View File

@@ -0,0 +1,70 @@
user www www;
worker_processes 5;
error_log logs/error.log;
pid logs/nginx.pid;
worker_rlimit_nofile 8192;
events {
worker_connections 4096;
}
http {
include conf/mime.types;
include /etc/nginx/proxy.conf;
include /etc/nginx/fastcgi.conf;
index index.html index.htm index.php;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] $status '
'"$request" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
tcp_nopush on;
server_names_hash_bucket_size 128; # this seems to be required for some vhosts
server { # php/fastcgi
listen 80;
server_name domain1.com www.domain1.com;
access_log logs/domain1.access.log main;
root html;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:1025;
}
}
server { # simple reverse-proxy
listen 80;
server_name domain2.com www.domain2.com;
access_log logs/domain2.access.log main;
# serve static files
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root /var/www/virtual/big.server.com/htdocs;
expires 30d;
}
# pass requests for dynamic content to rails/turbogears/zope, et al
location / {
proxy_pass http://127.0.0.1:8080;
}
}
upstream big_server_com {
server 127.0.0.3:8000 weight=5;
server 127.0.0.3:8001 weight=5;
server 192.168.0.1:8000;
server 192.168.0.1:8001;
}
server { # simple load balancing
listen 80;
server_name big.server.com;
access_log logs/big.server.access.log main;
location / {
proxy_pass http://big_server_com;
}
}
}

View File

@@ -0,0 +1,4 @@
#!/usr/bin/php
<?php
echo "PHP\n";

4
samples/PHP/php.script! Normal file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env php
<?php
echo "PHP\n";

2
samples/Perl/perl.script! Executable file
View File

@@ -0,0 +1,2 @@
#!/usr/local/bin/perl
print "Perl\n"

68
samples/Prolog/calc.pl Normal file
View File

@@ -0,0 +1,68 @@
action_module(calculator) .
%[-,-,d1,-] --push(D)--> [-,-,D,-] if mode(init)
push(D) < -
mode(init),
deny([displayed(D1),mode(init)]),
affirm([displayed(D),mode(cont)]).
%[-,-,D1,-] --push(D)--> [-,-,10*D1+D,-] if mode(cont)
push(D) < -
mode(cont),
deny(displayed(D1)),
New = 10*D1 + D,
affirm(displayed(New)).
%[a,op,d,m] --push(clear)--> [0,nop,0,0]
push(clear) < -
deny([accumulator(A),op(O),displayed(D),memory(M),mode(X)]),
affirm([accumulator(0),op(nop),displayed(0),memory(0),mode(init)]).
%[a,op,d,m] --push(mem_rec)--> [a,op,m,m]
push(mem_rec) < -
memory(M),
deny([displayed(D),mode(X)]),
affirm([displayed(M),mode(init)]).
%[a,op,d,m] --push(plus)--> [op(a,d),plus,d,m]
push(plus) < -
displayed(D),
deny([accumulator(A),op(O),mode(X)]),
eval(O,A,D,V), ; use normal arithmetic, i.e., V=O(A,D)
affirm([accumulator(V),op(plus),mode(init)]).
%[a,op,d,m] --push(minus)--> [op(a,d,minus,d,m]
push(minus) lt -
displayed(D),
deny([accumulator(A),op(O),mode(X)]),
eval(O,A,D,V), ; use normal arithmetic, i.e., V=O(A,D)
affirm([accumulator(V),op(minus),mode(init)]).
%[a,op,d,m] --push(times)--> [op(a,d),times,d,m]
push(times) < -
displayed(D),
deny([accumulator(A),op(O),mode(X)]),
eval(O,A,D,V), ; use normal arithmetic, i.e., V=O(A,D)
affirm([accumulator(V),op(times),mode(init)]).
%[a,op,d,m] --push(equal)--> [a,nop,op(a,d),m]
push(equal) < -
accumulator(A),
deny([op(O),displayed(D),mode(X)]),
eval(O,A,D,V),
affirm([op(nop),displayed(V),mode(init)]).
%[a,op,d,m] --push(mem_plus)--> [a,nop,v,plus(m,v)] where v=op(a,d)
push(mem_plus) < -
accumulator(A),
deny([op(O),displayed(D),memory(M),mode(X)]),
eval(O,A,D,V),
eval(plus,M,V,V1),
affirm([op(nop),displayed(V),memory(V1),mode(init)]).
%[a,op,d,m] --push(plus_minus)--> [a,op,-d,m]
push(clear) < -
deny([displayed(D),mode(X)]),
eval(minus,0,D,V),
affirm([displayed(V),mode(init)]).

View File

@@ -0,0 +1,94 @@
%%----- normalize(+Wff,-NormalClauses) ------
normalize(Wff,NormalClauses) :-
conVert(Wff,[],S),
cnF(S,T),
flatten_and(T,U),
make_clauses(U,NormalClauses).
%%----- make a sequence out of a conjunction -----
flatten_and(X /\ Y, F) :-
!,
flatten_and(X,A),
flatten_and(Y, B),
sequence_append(A,B,F).
flatten_and(X,X).
%%----- make a sequence out of a disjunction -----
flatten_or(X \/ Y, F) :-
!,
flatten_or(X,A),
flatten_or(Y,B),
sequence_append(A,B,F).
flatten_or(X,X).
%%----- append two sequences -------------------------------
sequence_append((X,R),S,(X,T)) :- !, sequence_append(R,S,T).
sequence_append((X),S,(X,S)).
%%----- separate into positive and negative literals -----------
separate((A,B),P,N) :-
!,
(A = ~X -> N=[X|N1],
separate(B,P,N1)
;
P=[A|P1],
separate(B,P1,N) ).
separate(A,P,N) :-
(A = ~X -> N=[X],
P = []
;
P=[A],
N = [] ).
%%----- tautology ----------------------------
tautology(P,N) :- some_occurs(N,P).
some_occurs([F|R],B) :-
occurs(F,B) | some_occurs(R,B).
occurs(A,[F|_]) :-
A == F,
!.
occurs(A,[_|R]) :-
occurs(A,R).
make_clauses((A,B),C) :-
!,
flatten_or(A,F),
separate(F,P,N),
(tautology(P,N) ->
make_clauses(B,C)
;
make_clause(P,N,D),
C = [D|R],
make_clauses(B,R) ).
make_clauses(A,C) :-
flatten_or(A,F),
separate(F,P,N),
(tautology(P,N) ->
C = []
;
make_clause(P,N,D),
C = [D] ).
make_clause([],N, false :- B) :-
!,
make_sequence(N,B,',').
make_clause(P,[],H) :-
!,
make_sequence(P,H,'|').
make_clause(P,N, H :- T) :-
make_sequence(P,H,'|'),
make_sequence(N,T,',').
make_sequence([A],A,_) :- !.
make_sequence([F|R],(F|S),'|') :-
make_sequence(R,S,'|').
make_sequence([F|R],(F,S),',') :-
make_sequence(R,S,',').
write_list([F|R]) :-
write(F), write('.'), nl,
write_list(R).
write_list([]).

287
samples/Prolog/puzzle.pl Normal file
View File

@@ -0,0 +1,287 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% A* Algorithm
%%%
%%%
%%% Nodes have form S#D#F#A
%%% where S describes the state or configuration
%%% D is the depth of the node
%%% F is the evaluation function value
%%% A is the ancestor list for the node
:- op(400,yfx,'#'). /* Node builder notation */
solve(State,Soln) :- f_function(State,0,F),
search([State#0#F#[]],S), reverse(S,Soln).
f_function(State,D,F) :- h_function(State,H),
F is D + H.
search([State#_#_#Soln|_], Soln) :- goal(State).
search([B|R],S) :- expand(B,Children),
insert_all(Children,R,Open),
search(Open,S).
insert_all([F|R],Open1,Open3) :- insert(F,Open1,Open2),
insert_all(R,Open2,Open3).
insert_all([],Open,Open).
insert(B,Open,Open) :- repeat_node(B,Open), ! .
insert(B,[C|R],[B,C|R]) :- cheaper(B,C), ! .
insert(B,[B1|R],[B1|S]) :- insert(B,R,S), !.
insert(B,[],[B]).
repeat_node(P#_#_#_, [P#_#_#_|_]).
cheaper( _#_#F1#_ , _#_#F2#_ ) :- F1 < F2.
expand(State#D#_#S,All_My_Children) :-
bagof(Child#D1#F#[Move|S],
(D1 is D+1,
move(State,Child,Move),
f_function(Child,D1,F)),
All_My_Children).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% 8-puzzle solver
%%%
%%%
%%% State have form A/B/C/D/E/F/G/H/I
%%% where {A,...,I} = {0,...,8}
%%% 0 represents the empty tile
%%%
goal(1/2/3/8/0/4/7/6/5).
%%% The puzzle moves
left( A/0/C/D/E/F/H/I/J , 0/A/C/D/E/F/H/I/J ).
left( A/B/C/D/0/F/H/I/J , A/B/C/0/D/F/H/I/J ).
left( A/B/C/D/E/F/H/0/J , A/B/C/D/E/F/0/H/J ).
left( A/B/0/D/E/F/H/I/J , A/0/B/D/E/F/H/I/J ).
left( A/B/C/D/E/0/H/I/J , A/B/C/D/0/E/H/I/J ).
left( A/B/C/D/E/F/H/I/0 , A/B/C/D/E/F/H/0/I ).
up( A/B/C/0/E/F/H/I/J , 0/B/C/A/E/F/H/I/J ).
up( A/B/C/D/0/F/H/I/J , A/0/C/D/B/F/H/I/J ).
up( A/B/C/D/E/0/H/I/J , A/B/0/D/E/C/H/I/J ).
up( A/B/C/D/E/F/0/I/J , A/B/C/0/E/F/D/I/J ).
up( A/B/C/D/E/F/H/0/J , A/B/C/D/0/F/H/E/J ).
up( A/B/C/D/E/F/H/I/0 , A/B/C/D/E/0/H/I/F ).
right( A/0/C/D/E/F/H/I/J , A/C/0/D/E/F/H/I/J ).
right( A/B/C/D/0/F/H/I/J , A/B/C/D/F/0/H/I/J ).
right( A/B/C/D/E/F/H/0/J , A/B/C/D/E/F/H/J/0 ).
right( 0/B/C/D/E/F/H/I/J , B/0/C/D/E/F/H/I/J ).
right( A/B/C/0/E/F/H/I/J , A/B/C/E/0/F/H/I/J ).
right( A/B/C/D/E/F/0/I/J , A/B/C/D/E/F/I/0/J ).
down( A/B/C/0/E/F/H/I/J , A/B/C/H/E/F/0/I/J ).
down( A/B/C/D/0/F/H/I/J , A/B/C/D/I/F/H/0/J ).
down( A/B/C/D/E/0/H/I/J , A/B/C/D/E/J/H/I/0 ).
down( 0/B/C/D/E/F/H/I/J , D/B/C/0/E/F/H/I/J ).
down( A/0/C/D/E/F/H/I/J , A/E/C/D/0/F/H/I/J ).
down( A/B/0/D/E/F/H/I/J , A/B/F/D/E/0/H/I/J ).
%%% the heuristic function
h_function(Puzz,H) :- p_fcn(Puzz,P),
s_fcn(Puzz,S),
H is P + 3*S.
%%% the move
move(P,C,left) :- left(P,C).
move(P,C,up) :- up(P,C).
move(P,C,right) :- right(P,C).
move(P,C,down) :- down(P,C).
%%% the Manhattan distance function
p_fcn(A/B/C/D/E/F/G/H/I, P) :-
a(A,Pa), b(B,Pb), c(C,Pc),
d(D,Pd), e(E,Pe), f(F,Pf),
g(G,Pg), h(H,Ph), i(I,Pi),
P is Pa+Pb+Pc+Pd+Pe+Pf+Pg+Ph+Pg+Pi.
a(0,0). a(1,0). a(2,1). a(3,2). a(4,3). a(5,4). a(6,3). a(7,2). a(8,1).
b(0,0). b(1,1). b(2,0). b(3,1). b(4,2). b(5,3). b(6,2). b(7,3). b(8,2).
c(0,0). c(1,2). c(2,1). c(3,0). c(4,1). c(5,2). c(6,3). c(7,4). c(8,3).
d(0,0). d(1,1). d(2,2). d(3,3). d(4,2). d(5,3). d(6,2). d(7,2). d(8,0).
e(0,0). e(1,2). e(2,1). e(3,2). e(4,1). e(5,2). e(6,1). e(7,2). e(8,1).
f(0,0). f(1,3). f(2,2). f(3,1). f(4,0). f(5,1). f(6,2). f(7,3). f(8,2).
g(0,0). g(1,2). g(2,3). g(3,4). g(4,3). g(5,2). g(6,2). g(7,0). g(8,1).
h(0,0). h(1,3). h(2,3). h(3,3). h(4,2). h(5,1). h(6,0). h(7,1). h(8,2).
i(0,0). i(1,4). i(2,3). i(3,2). i(4,1). i(5,0). i(6,1). i(7,2). i(8,3).
%%% the out-of-cycle function
s_fcn(A/B/C/D/E/F/G/H/I, S) :-
s_aux(A,B,S1), s_aux(B,C,S2), s_aux(C,F,S3),
s_aux(F,I,S4), s_aux(I,H,S5), s_aux(H,G,S6),
s_aux(G,D,S7), s_aux(D,A,S8), s_aux(E,S9),
S is S1+S2+S3+S4+S5+S6+S7+S8+S9.
s_aux(0,0) :- !.
s_aux(_,1).
s_aux(X,Y,0) :- Y is X+1, !.
s_aux(8,1,0) :- !.
s_aux(_,_,2).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% 8-puzzle animation -- using VT100 character graphics
%%%
%%%
%%%
puzzle(P) :- solve(P,S),
animate(P,S),
message.
animate(P,S) :- initialize(P),
cursor(1,2), write(S),
cursor(1,22), write('Hit ENTER to step solver.'),
get0(_X),
play_back(S).
:- dynamic location/3.
initialize(A/B/C/D/E/F/H/I/J) :-
cls,
retractall(location(_,_,_)),
assert(location(A,20,5)),
assert(location(B,30,5)),
assert(location(C,40,5)),
assert(location(F,40,10)),
assert(location(J,40,15)),
assert(location(I,30,15)),
assert(location(H,20,15)),
assert(location(D,20,10)),
assert(location(E,30,10)), draw_all.
draw_all :- draw(1), draw(2), draw(3), draw(4),
draw(5), draw(6), draw(7), draw(8).
%%% play_back([left,right,up,...]).
play_back([M|R]) :- call(M), get0(_X), play_back(R).
play_back([]) :- cursor(1,24). %%% Put cursor out of the way
message :- nl,nl,
write(' ********************************************'), nl,
write(' * Enter 8-puzzle goals in the form ... *'), nl,
write(' * ?- puzzle(0/8/1/2/4/3/7/6/5). *'), nl,
write(' * Enter goal ''message'' to reread this. *'), nl,
write(' ********************************************'), nl, nl.
cursor(X,Y) :- put(27), put(91), %%% ESC [
write(Y),
put(59), %%% ;
write(X),
put(72). %%% M
%%% clear the screen, quickly
cls :- put(27), put("["), put("2"), put("J").
%%% video attributes -- bold and blink not working
plain :- put(27), put("["), put("0"), put("m").
reverse_video :- put(27), put("["), put("7"), put("m").
%%% Tile objects, character map(s)
%%% Each tile should be drawn using the character map,
%%% drawn at 'location', which is asserted and retracted
%%% by 'playback'.
character_map(N, [ [' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ', N ,' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' '] ]).
%%% move empty tile (spot) to the left
left :- retract(location(0,X0,Y0)),
Xnew is X0 - 10,
location(Tile,Xnew,Y0),
assert(location(0,Xnew,Y0)),
right(Tile),right(Tile),right(Tile),
right(Tile),right(Tile),
right(Tile),right(Tile),right(Tile),
right(Tile),right(Tile).
up :- retract(location(0,X0,Y0)),
Ynew is Y0 - 5,
location(Tile,X0,Ynew),
assert(location(0,X0,Ynew)),
down(Tile),down(Tile),down(Tile),down(Tile),down(Tile).
right :- retract(location(0,X0,Y0)),
Xnew is X0 + 10,
location(Tile,Xnew,Y0),
assert(location(0,Xnew,Y0)),
left(Tile),left(Tile),left(Tile),left(Tile),left(Tile),
left(Tile),left(Tile),left(Tile),left(Tile),left(Tile).
down :- retract(location(0,X0,Y0)),
Ynew is Y0 + 5,
location(Tile,X0,Ynew),
assert(location(0,X0,Ynew)),
up(Tile),up(Tile),up(Tile),up(Tile),up(Tile).
draw(Obj) :- reverse_video, character_map(Obj,M),
location(Obj,X,Y),
draw(X,Y,M), plain.
%%% hide tile
hide(Obj) :- character_map(Obj,M),
location(Obj,X,Y),
hide(X,Y,M).
hide(_,_,[]).
hide(X,Y,[R|G]) :- hide_row(X,Y,R),
Y1 is Y + 1,
hide(X,Y1,G).
hide_row(_,_,[]).
hide_row(X,Y,[_|R]) :- cursor(X,Y),
write(' '),
X1 is X + 1,
hide_row(X1,Y,R).
%%% draw tile
draw(_,_,[]).
draw(X,Y,[R|G]) :- draw_row(X,Y,R),
Y1 is Y + 1,
draw(X,Y1,G).
draw_row(_,_,[]).
draw_row(X,Y,[P|R]) :- cursor(X,Y),
write(P),
X1 is X + 1,
draw_row(X1,Y,R).
%%% Move an Object up
up(Obj) :- hide(Obj),
retract(location(Obj,X,Y)),
Y1 is Y - 1,
assert(location(Obj,X,Y1)),
draw(Obj).
down(Obj) :- hide(Obj),
retract(location(Obj,X,Y)),
Y1 is Y + 1,
assert(location(Obj,X,Y1)),
draw(Obj).
left(Obj) :- hide(Obj),
retract(location(Obj,X,Y)),
X1 is X - 1,
assert(location(Obj,X1,Y)),
draw(Obj).
right(Obj) :- hide(Obj),
retract(location(Obj,X,Y)),
X1 is X + 1,
assert(location(Obj,X1,Y)),
draw(Obj).
:- message.

View File

@@ -0,0 +1,13 @@
partition([], _, [], []).
partition([X|Xs], Pivot, Smalls, Bigs) :-
( X @< Pivot ->
Smalls = [X|Rest],
partition(Xs, Pivot, Rest, Bigs)
; Bigs = [X|Rest],
partition(Xs, Pivot, Smalls, Rest)
).
quicksort([]) --> [].
quicksort([X|Xs]) -->
{ partition(Xs, X, Smaller, Bigger) },
quicksort(Smaller), [X], quicksort(Bigger).

21
samples/Prolog/turing.pl Normal file
View File

@@ -0,0 +1,21 @@
turing(Tape0, Tape) :-
perform(q0, [], Ls, Tape0, Rs),
reverse(Ls, Ls1),
append(Ls1, Rs, Tape).
perform(qf, Ls, Ls, Rs, Rs) :- !.
perform(Q0, Ls0, Ls, Rs0, Rs) :-
symbol(Rs0, Sym, RsRest),
once(rule(Q0, Sym, Q1, NewSym, Action)),
action(Action, Ls0, Ls1, [NewSym|RsRest], Rs1),
perform(Q1, Ls1, Ls, Rs1, Rs).
symbol([], b, []).
symbol([Sym|Rs], Sym, Rs).
action(left, Ls0, Ls, Rs0, Rs) :- left(Ls0, Ls, Rs0, Rs).
action(stay, Ls, Ls, Rs, Rs).
action(right, Ls0, [Sym|Ls0], [Sym|Rs], Rs).
left([], [], Rs0, [b|Rs0]).
left([L|Ls], Ls, Rs, [L|Rs]).

View File

@@ -1,2 +1,2 @@
#! /usr/bin/env ruby -w -Ilib:test
echo "Ruby"
puts "Ruby"

2
samples/Shell/bash.script! Executable file
View File

@@ -0,0 +1,2 @@
#!/bin/bash
echo "bash"

View File

@@ -0,0 +1 @@
/usr/bin/clear

View File

@@ -0,0 +1,36 @@
##
# Environment...
##
# Set up some variables for 'screen'
if [ -z "${SCREENDIR}" ];then echo -n
export SCREENDIR="${HOME}/.screen"
# Save my screen sockets within my $HOME dir
fi
## PATH
export PATH=/usr/local/bin:/usr/local/sbin:/usr/xpg4/bin:/usr/sbin:/usr/bin:/usr/sfw/bin:/usr/ccs/bin:/usr/openwin/bin:/opt/mysql/current/bin
export MANPATH=/usr/local/man:/usr/share/man
## Random ENV...
# Set $TERM to 'vt100' (a safe default) if, for some
# reason, it is set to 'network' (which is not valid!)
if [ ${TERM} == 'network' ];then echo -n
export TERM='vt100'
# not 'nsterm' because if its 'network' we're
# probly not in Terminal.app
fi
# Set $COLORTERM, all this does is trick *some* apps into
# using color in the terminal, which should happen anyway.
if [ -z "${COLORTERM}" ];then echo -n
export COLORTERM="${TERM}"
fi
# another color option, this one for BSD's ls
if [ -z "${CLICOLOR}" ];then echo -n
export CLICOLOR='1' # can be set to anything, actually
fi
# If $DISPLAY is not already set, set it!
if [ -z "${DISPLAY}" ];then echo -n
export DISPLAY=':0'
fi
##
# Source the bash rc file
[ -r "${HOME}/.bashrc" ] && . "${HOME}/.bashrc"

View File

@@ -0,0 +1,119 @@
##
# Functions... *MUCH* better than aliases, and they do more too!
# but they clutter the environment... (try typing just 'set' at the prompt)
##
# The reason that some of these are... odd... is because
# I had to convert them early because bash can't do positional
# arguments in aliases! functionName () { do something $@<-arguments ; }
function ls { command ls -Fh "$@"; }
# 'command ls' to prevent loop; -A for .file, -F for dir/ link@,
# -h for 5k 3m 1g, -o for printing flags (uchg)...
function l { ls -l "$@"; } # -l to list in long format...
function ll { l "$@" | less -XF ; } # pipe into 'more'
##
# Tips and Ticks... from http://www.caliban.org/bash/index.shtml
##
# The $CDPATH variable is so that you can be in /path/to/something and 'cd'
# to 'somethingElse' and end up in /not/the/same/path/to/somethingElse.
# iWould use it if it didn't ALWAYS echo the directory it changes to!
#CDPATH='.:~'
#
# HISTIGNORE="&:l:ls:ls *:l *:cd:cd *:[bf]g:exit:quit:q:sleep *"
# History ignores commands that include any l/ls/cd etc
# This kicks-ass! It drops repeats and other useless
# things from the command history!
HISTIGNORE="[bf]g:exit:quit:q:sleep *"
# I want to see l/ls/cd in my history
HISTCONTROL=ignoreboth
# ignores both commands that start with a space or a tab, and duplicates
# other options are as follows:
# `ignorespace' means to not enter lines which begin with a space or tab into the history list.
# `ignoredups' means to not enter lines which match the last entered line.
# `ignoreboth' combines the two options.
shopt -s cdspell extglob progcomp
# Spell check for 'cd', extended globbing, programmable completion
##
# Bash Completion... Cannibalised from bash_completion 20030929
# Completion defaults... Yes, its long...
# Basically this sets up many useful defaults for command completion, these
# should probly be built into bash. Use bash_completions itself if you want
# more functionality and don't mind the hacks it uses.
complete -f -X '!*.?(t)bz2' bunzip2 bzcat bzcmp bzdiff bzegrep bzfgrep bzgrep
complete -f -X '!*.@(zip|ZIP|jar|JAR|exe|EXE|pk3|war|wsz|ear|zargo|xpi)' unzip zipinfo
complete -f -X '*.Z' compress znew
complete -f -X '!*.@(Z|gz|tgz|Gz|dz)' gunzip zcmp zdiff zcat zegrep zfgrep zgrep zless zmore
complete -f -X '!*.Z' uncompress
complete -f -X '!*.@(gif|jp?(e)g|tif?(f)|pn[gm]|p[bgp]m|bmp|xpm|ico|xwd|tga|GIF|JP?(E)G|TIF?(F)|PN[GM]|P[BGP]M|BMP|XPM|ICO|XWD|TGA)' ee display
complete -f -X '!*.@(gif|jp?(e)g|tif?(f)|png|p[bgp]m|bmp|x[bp]m|rle|rgb|pcx|fits|pm|GIF|JPG|JP?(E)G|TIF?(F)|PNG|P[BGP]M|BMP|X[BP]M|RLE|RGB|PCX|FITS|PM)' xv qiv
complete -f -X '!*.@(@(?(e)ps|?(E)PS|pdf|PDF)?(.gz|.GZ|.Z))' gv ggv
complete -f -X '!*.@(dvi|DVI)?(.@(gz|Z|bz2))' xdvi
complete -f -X '!*.@(dvi|DVI)' dvips dviselect dvitype
complete -f -X '!*.@(pdf|PDF)' acroread xpdf
complete -f -X '!*.texi*' makeinfo texi2html
complete -f -X '!*.@(?(la)tex|?(LA)TEX|texi|TEXI|dtx|DTX|ins|INS)' tex latex slitex jadetex pdfjadetex pdftex pdflatex texi2dvi
complete -f -X '!*.@(mp3|MP3|m3u)' mpg123 mpg321
complete -f -X '!*.@(mp?(e)g|MP?(E)G|wma|avi|AVI|asf|vob|bin|dat|vcd|ps|pes|fli|viv|rm|ram|yuv|mov|MOV|qt|QT|wmv|mp3|MP3|ogg|OGG|ogm|OGM|mp4|MP4|wav|WAV)' xine
complete -f -X '!*.@(avi|asf|wmv)' aviplay
complete -f -X '!*.@(rm|ram|smi?(l))' realplay
complete -f -X '!*.@(mp?(e)g|avi|mov|qt)' xanim
complete -f -X '!*.@(ogg|OGG|m3u)' ogg123
complete -f -X '!*.@(mp3|MP3|ogg|OGG|pls|m3u)' gqmpeg freeamp
complete -f -X '!*.@(mp[23]|MP[23]|ogg|OGG|wav|WAV|pls|m3u|xm|mod|s[3t]m|it|mtm|ult|flac)' xmms
complete -f -X '!*.fig' xfig
complete -f -X '!*.@(mid?(i))' timidity playmidi
complete -f -X '.*|*.@(o|so|so.!(conf)|a|tar?(.@(gz|bz2))|tgz|tbz2|rpm|zip|ZIP|gif|GIF|jp?(e)g|JP?(E)G|mp3|MP3|mp?(e)g|MPG|avi|AVI|asf|ASF|ogg|OGG|class|CLASS)' vi vim gvim rvim view rview rgvim rgview gview emacs
complete -f -X '!*.@(exe|EXE|com|COM|scr|SCR)' wine
complete -f -X '!*.@(zip|ZIP|z|Z|gz|GZ|tgz|TGZ)' bzme
complete -f -X '!*.@(?([xX]|[sS])[hH][tT][mM]?([lL]))' netscape mozilla lynx opera w3m galeon curl dillo elinks links
#
complete -u su passwd groups # user commands see only users
complete -A stopped -P '%' bg # bg completes with stopped jobs
complete -j -P '%' fg jobs disown # other job commands
complete -v readonly unset export # readonly and unset complete with shell variables
complete -A setopt set # set completes with set options
complete -A shopt shopt # shopt completes with shopt options
complete -A helptopic help # helptopics
complete -a unalias # unalias completes with aliases
complete -A binding bind # bind completes with readline bindings (make this more intelligent)
complete -c command type which man #sudo # type, which, man complete on commands
complete -d pushd cd rmdir # Make directory commands see only directories
complete -W ' ' alias # no filenames for alias,
##
# Set the prompt
##
PS1="[\h:\w] \[\033[1;34m\]\u\[\033[0m\]\\$ "
# My prompt line: "[gaelicWizard:~/Documents] user$ " user is in blue
# Or: "[gaelicWizard:~/Documents] root# " root is in blue
##
# Aliases:
##
# Aliases frequently used...
alias ..='cd ..;l'
alias cd..='cd ..'
alias which='type' # 'which' in (t)csh is same(?) as 'type' in bash...
alias quit='exit'
alias q='quit' # and 'q' is even shorter! :-D
alias v='vim'
alias rehash='. ~/.bashrc;' # source ~/.bashrc after I edit it
alias pg='ps -afe|grep -v grep|grep'
alias make='gmake'
alias patch='gpatch'
alias sed='gsed'
alias awk='nawk'
alias diff='gdiff'
alias grep='ggrep'
alias find='gfind'
alias ps='/usr/ucb/ps'
alias whoami='/usr/ucb/whoami'
alias ping='ping -s'
alias man='GROFF_NO_SGR= TCAT="less -s" TROFF="groff -Tascii" man -t'
# The rest are uncategorised and fairly random... :-)
shopt -s histappend
PROMPT_COMMAND='echo -ne "\033]0;${USER} on ${HOSTNAME} at ${PWD}\007" && history -a'
export PATH=/usr/local/bin:/usr/local/sbin:/usr/xpg4/bin:/usr/sbin:/usr/bin:/usr/sfw/bin:/usr/ccs/bin:/usr/openwin/bin:/opt/mysql/current/bin

View File

@@ -0,0 +1,5 @@
umask 022
set path=(/opt/local/bin /opt/local/sbin /bin /usr/bin)
if ( $?prompt ) then
set history=32
endif

View File

@@ -0,0 +1,2 @@
stty -istrip
# setenv TERM `tset -Q -`

View File

@@ -0,0 +1,3 @@
# Store dirs stack
# See ~/.dotfiles/oh-my-zsh/plugins/dirspersist.plugin.zsh
dirpersiststore

View File

@@ -0,0 +1,28 @@
##############################################################################
#Import the shell-agnostic (Bash or Zsh) environment config
##############################################################################
source ~/.profile
##############################################################################
# History Configuration
##############################################################################
HISTSIZE=5000 #How many lines of history to keep in memory
HISTFILE=~/.zsh_history #Where to save history to disk
SAVEHIST=5000 #Number of history entries to save to disk
HISTDUP=erase #Erase duplicates in the history file
setopt appendhistory #Append history to the history file (no overwriting)
setopt sharehistory #Share history across terminals
setopt incappendhistory #Immediately append to the history file, not just when a term is killed
##############################################################################
# sjl/z-zsh setup
##############################################################################
#. ~/.dotfiles/z-zsh/z.sh
#function precmd () {
# z --add "$(pwd -P)"
#}
##############################################################################
# rupa/z setup
##############################################################################
. ~/.dotfiles/z-rupa/z.sh

View File

@@ -0,0 +1,2 @@
fpath=($fpath $HOME/.zsh/func)
typeset -U fpath

View File

@@ -0,0 +1 @@
/usr/bin/clear

View File

@@ -0,0 +1,36 @@
##
# Environment...
##
# Set up some variables for 'screen'
if [ -z "${SCREENDIR}" ];then echo -n
export SCREENDIR="${HOME}/.screen"
# Save my screen sockets within my $HOME dir
fi
## PATH
export PATH=/usr/local/bin:/usr/local/sbin:/usr/xpg4/bin:/usr/sbin:/usr/bin:/usr/sfw/bin:/usr/ccs/bin:/usr/openwin/bin:/opt/mysql/current/bin
export MANPATH=/usr/local/man:/usr/share/man
## Random ENV...
# Set $TERM to 'vt100' (a safe default) if, for some
# reason, it is set to 'network' (which is not valid!)
if [ ${TERM} == 'network' ];then echo -n
export TERM='vt100'
# not 'nsterm' because if its 'network' we're
# probly not in Terminal.app
fi
# Set $COLORTERM, all this does is trick *some* apps into
# using color in the terminal, which should happen anyway.
if [ -z "${COLORTERM}" ];then echo -n
export COLORTERM="${TERM}"
fi
# another color option, this one for BSD's ls
if [ -z "${CLICOLOR}" ];then echo -n
export CLICOLOR='1' # can be set to anything, actually
fi
# If $DISPLAY is not already set, set it!
if [ -z "${DISPLAY}" ];then echo -n
export DISPLAY=':0'
fi
##
# Source the bash rc file
[ -r "${HOME}/.bashrc" ] && . "${HOME}/.bashrc"

View File

@@ -0,0 +1,119 @@
##
# Functions... *MUCH* better than aliases, and they do more too!
# but they clutter the environment... (try typing just 'set' at the prompt)
##
# The reason that some of these are... odd... is because
# I had to convert them early because bash can't do positional
# arguments in aliases! functionName () { do something $@<-arguments ; }
function ls { command ls -Fh "$@"; }
# 'command ls' to prevent loop; -A for .file, -F for dir/ link@,
# -h for 5k 3m 1g, -o for printing flags (uchg)...
function l { ls -l "$@"; } # -l to list in long format...
function ll { l "$@" | less -XF ; } # pipe into 'more'
##
# Tips and Ticks... from http://www.caliban.org/bash/index.shtml
##
# The $CDPATH variable is so that you can be in /path/to/something and 'cd'
# to 'somethingElse' and end up in /not/the/same/path/to/somethingElse.
# iWould use it if it didn't ALWAYS echo the directory it changes to!
#CDPATH='.:~'
#
# HISTIGNORE="&:l:ls:ls *:l *:cd:cd *:[bf]g:exit:quit:q:sleep *"
# History ignores commands that include any l/ls/cd etc
# This kicks-ass! It drops repeats and other useless
# things from the command history!
HISTIGNORE="[bf]g:exit:quit:q:sleep *"
# I want to see l/ls/cd in my history
HISTCONTROL=ignoreboth
# ignores both commands that start with a space or a tab, and duplicates
# other options are as follows:
# `ignorespace' means to not enter lines which begin with a space or tab into the history list.
# `ignoredups' means to not enter lines which match the last entered line.
# `ignoreboth' combines the two options.
shopt -s cdspell extglob progcomp
# Spell check for 'cd', extended globbing, programmable completion
##
# Bash Completion... Cannibalised from bash_completion 20030929
# Completion defaults... Yes, its long...
# Basically this sets up many useful defaults for command completion, these
# should probly be built into bash. Use bash_completions itself if you want
# more functionality and don't mind the hacks it uses.
complete -f -X '!*.?(t)bz2' bunzip2 bzcat bzcmp bzdiff bzegrep bzfgrep bzgrep
complete -f -X '!*.@(zip|ZIP|jar|JAR|exe|EXE|pk3|war|wsz|ear|zargo|xpi)' unzip zipinfo
complete -f -X '*.Z' compress znew
complete -f -X '!*.@(Z|gz|tgz|Gz|dz)' gunzip zcmp zdiff zcat zegrep zfgrep zgrep zless zmore
complete -f -X '!*.Z' uncompress
complete -f -X '!*.@(gif|jp?(e)g|tif?(f)|pn[gm]|p[bgp]m|bmp|xpm|ico|xwd|tga|GIF|JP?(E)G|TIF?(F)|PN[GM]|P[BGP]M|BMP|XPM|ICO|XWD|TGA)' ee display
complete -f -X '!*.@(gif|jp?(e)g|tif?(f)|png|p[bgp]m|bmp|x[bp]m|rle|rgb|pcx|fits|pm|GIF|JPG|JP?(E)G|TIF?(F)|PNG|P[BGP]M|BMP|X[BP]M|RLE|RGB|PCX|FITS|PM)' xv qiv
complete -f -X '!*.@(@(?(e)ps|?(E)PS|pdf|PDF)?(.gz|.GZ|.Z))' gv ggv
complete -f -X '!*.@(dvi|DVI)?(.@(gz|Z|bz2))' xdvi
complete -f -X '!*.@(dvi|DVI)' dvips dviselect dvitype
complete -f -X '!*.@(pdf|PDF)' acroread xpdf
complete -f -X '!*.texi*' makeinfo texi2html
complete -f -X '!*.@(?(la)tex|?(LA)TEX|texi|TEXI|dtx|DTX|ins|INS)' tex latex slitex jadetex pdfjadetex pdftex pdflatex texi2dvi
complete -f -X '!*.@(mp3|MP3|m3u)' mpg123 mpg321
complete -f -X '!*.@(mp?(e)g|MP?(E)G|wma|avi|AVI|asf|vob|bin|dat|vcd|ps|pes|fli|viv|rm|ram|yuv|mov|MOV|qt|QT|wmv|mp3|MP3|ogg|OGG|ogm|OGM|mp4|MP4|wav|WAV)' xine
complete -f -X '!*.@(avi|asf|wmv)' aviplay
complete -f -X '!*.@(rm|ram|smi?(l))' realplay
complete -f -X '!*.@(mp?(e)g|avi|mov|qt)' xanim
complete -f -X '!*.@(ogg|OGG|m3u)' ogg123
complete -f -X '!*.@(mp3|MP3|ogg|OGG|pls|m3u)' gqmpeg freeamp
complete -f -X '!*.@(mp[23]|MP[23]|ogg|OGG|wav|WAV|pls|m3u|xm|mod|s[3t]m|it|mtm|ult|flac)' xmms
complete -f -X '!*.fig' xfig
complete -f -X '!*.@(mid?(i))' timidity playmidi
complete -f -X '.*|*.@(o|so|so.!(conf)|a|tar?(.@(gz|bz2))|tgz|tbz2|rpm|zip|ZIP|gif|GIF|jp?(e)g|JP?(E)G|mp3|MP3|mp?(e)g|MPG|avi|AVI|asf|ASF|ogg|OGG|class|CLASS)' vi vim gvim rvim view rview rgvim rgview gview emacs
complete -f -X '!*.@(exe|EXE|com|COM|scr|SCR)' wine
complete -f -X '!*.@(zip|ZIP|z|Z|gz|GZ|tgz|TGZ)' bzme
complete -f -X '!*.@(?([xX]|[sS])[hH][tT][mM]?([lL]))' netscape mozilla lynx opera w3m galeon curl dillo elinks links
#
complete -u su passwd groups # user commands see only users
complete -A stopped -P '%' bg # bg completes with stopped jobs
complete -j -P '%' fg jobs disown # other job commands
complete -v readonly unset export # readonly and unset complete with shell variables
complete -A setopt set # set completes with set options
complete -A shopt shopt # shopt completes with shopt options
complete -A helptopic help # helptopics
complete -a unalias # unalias completes with aliases
complete -A binding bind # bind completes with readline bindings (make this more intelligent)
complete -c command type which man #sudo # type, which, man complete on commands
complete -d pushd cd rmdir # Make directory commands see only directories
complete -W ' ' alias # no filenames for alias,
##
# Set the prompt
##
PS1="[\h:\w] \[\033[1;34m\]\u\[\033[0m\]\\$ "
# My prompt line: "[gaelicWizard:~/Documents] user$ " user is in blue
# Or: "[gaelicWizard:~/Documents] root# " root is in blue
##
# Aliases:
##
# Aliases frequently used...
alias ..='cd ..;l'
alias cd..='cd ..'
alias which='type' # 'which' in (t)csh is same(?) as 'type' in bash...
alias quit='exit'
alias q='quit' # and 'q' is even shorter! :-D
alias v='vim'
alias rehash='. ~/.bashrc;' # source ~/.bashrc after I edit it
alias pg='ps -afe|grep -v grep|grep'
alias make='gmake'
alias patch='gpatch'
alias sed='gsed'
alias awk='nawk'
alias diff='gdiff'
alias grep='ggrep'
alias find='gfind'
alias ps='/usr/ucb/ps'
alias whoami='/usr/ucb/whoami'
alias ping='ping -s'
alias man='GROFF_NO_SGR= TCAT="less -s" TROFF="groff -Tascii" man -t'
# The rest are uncategorised and fairly random... :-)
shopt -s histappend
PROMPT_COMMAND='echo -ne "\033]0;${USER} on ${HOSTNAME} at ${PWD}\007" && history -a'
export PATH=/usr/local/bin:/usr/local/sbin:/usr/xpg4/bin:/usr/sbin:/usr/bin:/usr/sfw/bin:/usr/ccs/bin:/usr/openwin/bin:/opt/mysql/current/bin

View File

@@ -0,0 +1,5 @@
umask 022
set path=(/opt/local/bin /opt/local/sbin /bin /usr/bin)
if ( $?prompt ) then
set history=32
endif

View File

@@ -0,0 +1,2 @@
stty -istrip
# setenv TERM `tset -Q -`

View File

@@ -0,0 +1,3 @@
# Store dirs stack
# See ~/.dotfiles/oh-my-zsh/plugins/dirspersist.plugin.zsh
dirpersiststore

View File

@@ -0,0 +1,28 @@
##############################################################################
#Import the shell-agnostic (Bash or Zsh) environment config
##############################################################################
source ~/.profile
##############################################################################
# History Configuration
##############################################################################
HISTSIZE=5000 #How many lines of history to keep in memory
HISTFILE=~/.zsh_history #Where to save history to disk
SAVEHIST=5000 #Number of history entries to save to disk
HISTDUP=erase #Erase duplicates in the history file
setopt appendhistory #Append history to the history file (no overwriting)
setopt sharehistory #Share history across terminals
setopt incappendhistory #Immediately append to the history file, not just when a term is killed
##############################################################################
# sjl/z-zsh setup
##############################################################################
#. ~/.dotfiles/z-zsh/z.sh
#function precmd () {
# z --add "$(pwd -P)"
#}
##############################################################################
# rupa/z setup
##############################################################################
. ~/.dotfiles/z-rupa/z.sh

View File

@@ -0,0 +1,2 @@
fpath=($fpath $HOME/.zsh/func)
typeset -U fpath

View File

@@ -0,0 +1 @@
export PATH="/usr/local/bin:/usr/bin:/bin"

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env
echo "wat"

View File

@@ -0,0 +1,55 @@
#!/bin/bash
#
# Bash script to "plugin" to the dotfile repository, does a lot of fun stuff
# like turning the normal dotfiles (eg .bashrc) into symlinks to this
# repository's versions of those files (ensure that updates are just a
# 'git pull' away), optionally moving old files so that they can be
# preserved, setting up a cron job to automate the aforementioned git
# pull, and maybe some more fun stuff
#
shopt -s nocasematch # This makes pattern matching case-insensitive
POSTFIX="local"
URL="https://github.com/brcooley/.f.git"
PUSHURL="git@github.com:brcooley/.f.git"
overwrite=true
print_help () {
echo -e "\nA script to keep dotfiles up to date\n"
echo "Options:"
echo " -k, --keep-local Keeps local copies of dotfiles by appending"
echo " \"$POSTFIX\" to them"
exit 0
}
for opt in $@; do
case $opt in
-k | --keep-local) overwrite=false;;
-h | --help) print_help;;
esac
done
for f in .*; do
if [ "$f" = ".git" -o "$f" = "." -o "$f" = ".." -o "$f" = ".f" ]; then continue; fi
if [ -f "$HOME/$f" ]; then
if [ $overwrite = false ]; then
mv "$HOME/$f" "$HOME/${f}_$POSTFIX"
else
rm "$HOME/$f"
fi
# echo "Moving ~/$f to $HOME/${f}_$POSTFIX"
fi
ln -s "$PWD/$f" "$HOME/$f"
done
# Git versions prior to 1.7.? (1.7.1 confirmed) do not have a --local option
git config --local remote.origin.url "$URL"
git config --local remote.origin.pushurl "$PUSHURL"
crontab .jobs.cron
source ~/.bashrc
echo "Plugin succesful"

432
samples/Shell/sbt.script! Executable file
View File

@@ -0,0 +1,432 @@
#!/usr/bin/env bash
#
# A more capable sbt runner, coincidentally also called sbt.
# Author: Paul Phillips <paulp@typesafe.com>
# todo - make this dynamic
declare -r sbt_release_version=0.11.3
declare -r sbt_snapshot_version=0.13.0-SNAPSHOT
unset sbt_jar sbt_dir sbt_create sbt_snapshot sbt_launch_dir
unset scala_version java_home sbt_explicit_version
unset verbose debug quiet
build_props_sbt () {
if [[ -f project/build.properties ]]; then
versionLine=$(grep ^sbt.version project/build.properties)
versionString=${versionLine##sbt.version=}
echo "$versionString"
fi
}
update_build_props_sbt () {
local ver="$1"
local old=$(build_props_sbt)
if [[ $ver == $old ]]; then
return
elif [[ -f project/build.properties ]]; then
perl -pi -e "s/^sbt\.version=.*\$/sbt.version=${ver}/" project/build.properties
grep -q '^sbt.version=' project/build.properties || echo "sbt.version=${ver}" >> project/build.properties
echo !!!
echo !!! Updated file project/build.properties setting sbt.version to: $ver
echo !!! Previous value was: $old
echo !!!
fi
}
sbt_version () {
if [[ -n $sbt_explicit_version ]]; then
echo $sbt_explicit_version
else
local v=$(build_props_sbt)
if [[ -n $v ]]; then
echo $v
else
echo $sbt_release_version
fi
fi
}
echoerr () {
echo 1>&2 "$@"
}
vlog () {
[[ $verbose || $debug ]] && echoerr "$@"
}
dlog () {
[[ $debug ]] && echoerr "$@"
}
# this seems to cover the bases on OSX, and someone will
# have to tell me about the others.
get_script_path () {
local path="$1"
[[ -L "$path" ]] || { echo "$path" ; return; }
local target=$(readlink "$path")
if [[ "${target:0:1}" == "/" ]]; then
echo "$target"
else
echo "$(dirname $path)/$target"
fi
}
# a ham-fisted attempt to move some memory settings in concert
# so they need not be dicked around with individually.
get_mem_opts () {
local mem=${1:-1536}
local perm=$(( $mem / 4 ))
(( $perm > 256 )) || perm=256
(( $perm < 1024 )) || perm=1024
local codecache=$(( $perm / 2 ))
echo "-Xms${mem}m -Xmx${mem}m -XX:MaxPermSize=${perm}m -XX:ReservedCodeCacheSize=${codecache}m"
}
die() {
echo "Aborting: $@"
exit 1
}
make_url () {
groupid="$1"
category="$2"
version="$3"
echo "http://typesafe.artifactoryonline.com/typesafe/ivy-$category/$groupid/sbt-launch/$version/sbt-launch.jar"
}
declare -r default_jvm_opts="-Dfile.encoding=UTF8"
declare -r default_sbt_opts="-XX:+CMSClassUnloadingEnabled"
declare -r default_sbt_mem=1536
declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy"
declare -r sbt_opts_file=".sbtopts"
declare -r jvm_opts_file=".jvmopts"
declare -r latest_28="2.8.2"
declare -r latest_29="2.9.1"
declare -r latest_210="2.10.0-SNAPSHOT"
declare -r script_path=$(get_script_path "$BASH_SOURCE")
declare -r script_dir="$(dirname $script_path)"
declare -r script_name="$(basename $script_path)"
# some non-read-onlies set with defaults
declare java_cmd=java
declare sbt_launch_dir="$script_dir/.lib"
declare sbt_mem=$default_sbt_mem
# pull -J and -D options to give to java.
declare -a residual_args
declare -a java_args
declare -a scalac_args
declare -a sbt_commands
build_props_scala () {
if [[ -f project/build.properties ]]; then
versionLine=$(grep ^build.scala.versions project/build.properties)
versionString=${versionLine##build.scala.versions=}
echo ${versionString%% .*}
fi
}
execRunner () {
# print the arguments one to a line, quoting any containing spaces
[[ $verbose || $debug ]] && echo "# Executing command line:" && {
for arg; do
if printf "%s\n" "$arg" | grep -q ' '; then
printf "\"%s\"\n" "$arg"
else
printf "%s\n" "$arg"
fi
done
echo ""
}
exec "$@"
}
sbt_groupid () {
case $(sbt_version) in
0.7.*) echo org.scala-tools.sbt ;;
0.10.*) echo org.scala-tools.sbt ;;
0.11.[12]) echo org.scala-tools.sbt ;;
*) echo org.scala-sbt ;;
esac
}
sbt_artifactory_list () {
local version0=$(sbt_version)
local version=${version0%-SNAPSHOT}
local url="http://typesafe.artifactoryonline.com/typesafe/ivy-snapshots/$(sbt_groupid)/sbt-launch/"
dlog "Looking for snapshot list at: $url "
curl -s --list-only "$url" | \
grep -F $version | \
perl -e 'print reverse <>' | \
perl -pe 's#^<a href="([^"/]+).*#$1#;'
}
make_release_url () {
make_url $(sbt_groupid) releases $(sbt_version)
}
# argument is e.g. 0.13.0-SNAPSHOT
# finds the actual version (with the build id) at artifactory
make_snapshot_url () {
for ver in $(sbt_artifactory_list); do
local url=$(make_url $(sbt_groupid) snapshots $ver)
dlog "Testing $url"
curl -s --head "$url" >/dev/null
dlog "curl returned: $?"
echo "$url"
return
done
}
jar_url () {
case $(sbt_version) in
0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;;
*-SNAPSHOT) make_snapshot_url ;;
*) make_release_url ;;
esac
}
jar_file () {
echo "$sbt_launch_dir/$1/sbt-launch.jar"
}
download_url () {
local url="$1"
local jar="$2"
echo "Downloading sbt launcher $(sbt_version):"
echo " From $url"
echo " To $jar"
mkdir -p $(dirname "$jar") && {
if which curl >/dev/null; then
curl --fail --silent "$url" --output "$jar"
elif which wget >/dev/null; then
wget --quiet -O "$jar" "$url"
fi
} && [[ -f "$jar" ]]
}
acquire_sbt_jar () {
sbt_url="$(jar_url)"
sbt_jar="$(jar_file $(sbt_version))"
[[ -f "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar"
}
usage () {
cat <<EOM
Usage: $script_name [options]
-h | -help print this message
-v | -verbose this runner is chattier
-d | -debug set sbt log level to Debug
-q | -quiet set sbt log level to Error
-no-colors disable ANSI color codes
-sbt-create start sbt even if current directory contains no sbt project
-sbt-dir <path> path to global settings/plugins directory (default: ~/.sbt/<version>)
-sbt-boot <path> path to shared boot directory (default: ~/.sbt/boot in 0.11 series)
-ivy <path> path to local Ivy repository (default: ~/.ivy2)
-mem <integer> set memory options (default: $sbt_mem, which is
$(get_mem_opts $sbt_mem) )
-no-share use all local caches; no sharing
-offline put sbt in offline mode
-jvm-debug <port> Turn on JVM debugging, open at the given port.
-batch Disable interactive mode
# sbt version (default: from project/build.properties if present, else latest release)
!!! The only way to accomplish this pre-0.12.0 if there is a build.properties file which
!!! contains an sbt.version property is to update the file on disk. That's what this does.
-sbt-version <version> use the specified version of sbt
-sbt-jar <path> use the specified jar as the sbt launcher
-sbt-snapshot use a snapshot version of sbt
-sbt-launch-dir <path> directory to hold sbt launchers (default: $sbt_launch_dir)
# scala version (default: as chosen by sbt)
-28 use $latest_28
-29 use $latest_29
-210 use $latest_210
-scala-home <path> use the scala build at the specified directory
-scala-version <version> use the specified version of scala
# java version (default: java from PATH, currently $(java -version |& grep version))
-java-home <path> alternate JAVA_HOME
# jvm options and output control
JAVA_OPTS environment variable holding jvm args, if unset uses "$default_jvm_opts"
SBT_OPTS environment variable holding jvm args, if unset uses "$default_sbt_opts"
.jvmopts if file is in sbt root, it is prepended to the args given to the jvm
.sbtopts if file is in sbt root, it is prepended to the args given to **sbt**
-Dkey=val pass -Dkey=val directly to the jvm
-J-X pass option -X directly to the jvm (-J is stripped)
-S-X add -X to sbt's scalacOptions (-S is stripped)
In the case of duplicated or conflicting options, the order above
shows precedence: JAVA_OPTS lowest, command line options highest.
EOM
}
addJava () {
dlog "[addJava] arg = '$1'"
java_args=( "${java_args[@]}" "$1" )
}
addSbt () {
dlog "[addSbt] arg = '$1'"
sbt_commands=( "${sbt_commands[@]}" "$1" )
}
addScalac () {
dlog "[addScalac] arg = '$1'"
scalac_args=( "${scalac_args[@]}" "$1" )
}
addResidual () {
dlog "[residual] arg = '$1'"
residual_args=( "${residual_args[@]}" "$1" )
}
addResolver () {
addSbt "set resolvers in ThisBuild += $1"
}
addDebugger () {
addJava "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1"
}
get_jvm_opts () {
# echo "${JAVA_OPTS:-$default_jvm_opts}"
# echo "${SBT_OPTS:-$default_sbt_opts}"
[[ -f "$jvm_opts_file" ]] && cat "$jvm_opts_file"
}
process_args ()
{
require_arg () {
local type="$1"
local opt="$2"
local arg="$3"
if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then
die "$opt requires <$type> argument"
fi
}
while [[ $# -gt 0 ]]; do
case "$1" in
-h|-help) usage; exit 1 ;;
-v|-verbose) verbose=1 && shift ;;
-d|-debug) debug=1 && shift ;;
-q|-quiet) quiet=1 && shift ;;
-ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;;
-mem) require_arg integer "$1" "$2" && sbt_mem="$2" && shift 2 ;;
-no-colors) addJava "-Dsbt.log.noformat=true" && shift ;;
-no-share) addJava "$noshare_opts" && shift ;;
-sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;;
-sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;;
-debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;;
-offline) addSbt "set offline := true" && shift ;;
-jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;;
-batch) exec </dev/null && shift ;;
-sbt-create) sbt_create=true && shift ;;
-sbt-snapshot) sbt_explicit_version=$sbt_snapshot_version && shift ;;
-sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;;
-sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;;
-sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;;
-scala-version) require_arg version "$1" "$2" && addSbt "set scalaVersion := \"$2\"" && shift 2 ;;
-scala-home) require_arg path "$1" "$2" && addSbt "set scalaHome in ThisBuild := Some(file(\"$2\"))" && shift 2 ;;
-java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;;
-D*) addJava "$1" && shift ;;
-J*) addJava "${1:2}" && shift ;;
-S*) addScalac "${1:2}" && shift ;;
-28) addSbt "++ $latest_28" && shift ;;
-29) addSbt "++ $latest_29" && shift ;;
-210) addSbt "++ $latest_210" && shift ;;
*) addResidual "$1" && shift ;;
esac
done
[[ $debug ]] && {
case $(sbt_version) in
0.7.*) addSbt "debug" ;;
*) addSbt "set logLevel in Global := Level.Debug" ;;
esac
}
[[ $quiet ]] && {
case $(sbt_version) in
0.7.*) ;;
*) addSbt "set logLevel in Global := Level.Error" ;;
esac
}
}
# if .sbtopts exists, prepend its contents to $@ so it can be processed by this runner
[[ -f "$sbt_opts_file" ]] && {
sbtargs=()
while IFS= read -r arg; do
sbtargs=( "${sbtargs[@]}" "$arg" )
done <"$sbt_opts_file"
set -- "${sbtargs[@]}" "$@"
}
# process the combined args, then reset "$@" to the residuals
process_args "$@"
set -- "${residual_args[@]}"
argumentCount=$#
# set scalacOptions if we were given any -S opts
[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\""
# Update build.properties no disk to set explicit version - sbt gives us no choice
[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version"
echo "Detected sbt version $(sbt_version)"
[[ -n "$scala_version" ]] && echo "Overriding scala version to $scala_version"
# no args - alert them there's stuff in here
(( $argumentCount > 0 )) || echo "Starting $script_name: invoke with -help for other options"
# verify this is an sbt dir or -create was given
[[ -f ./build.sbt || -d ./project || -n "$sbt_create" ]] || {
cat <<EOM
$(pwd) doesn't appear to be an sbt project.
If you want to start sbt anyway, run:
$0 -sbt-create
EOM
exit 1
}
# pick up completion if present; todo
[[ -f .sbt_completion.sh ]] && source .sbt_completion.sh
# no jar? download it.
[[ -f "$sbt_jar" ]] || acquire_sbt_jar || {
# still no jar? uh-oh.
echo "Download failed. Obtain the jar manually and place it at $sbt_jar"
exit 1
}
[[ -n "$sbt_dir" ]] || {
sbt_dir=~/.sbt/$(sbt_version)
addJava "-Dsbt.global.base=$sbt_dir"
echo "Using $sbt_dir as sbt dir, -sbt-dir to override."
}
# since sbt 0.7 doesn't understand iflast
(( ${#residual_args[@]} == 0 )) && residual_args=( "shell" )
# run sbt
execRunner "$java_cmd" \
$(get_mem_opts $sbt_mem) \
$(get_jvm_opts) \
${java_args[@]} \
-jar "$sbt_jar" \
"${sbt_commands[@]}" \
"${residual_args[@]}"

2
samples/Shell/sh.script! Executable file
View File

@@ -0,0 +1,2 @@
#!/bin/sh
echo "sh"

2
samples/Shell/zsh.script! Executable file
View File

@@ -0,0 +1,2 @@
#!/bin/zsh
echo "zsh"

1
samples/Text/mac.txt Normal file
View File

@@ -0,0 +1 @@
line 1

Some files were not shown because too many files have changed in this diff Show More