mirror of
https://github.com/KevinMidboe/linguist.git
synced 2025-10-29 17:50:22 +00:00
Merge branch 'master' into obj_cpp
Conflicts: lib/linguist/samples.json
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
before_install:
|
||||
- sudo apt-get install libicu-dev -y
|
||||
# Short-term fix addressing https://github.com/bundler/bundler/issues/2784
|
||||
- gem update --system 2.1.11
|
||||
rvm:
|
||||
- 1.8.7
|
||||
|
||||
@@ -6,12 +6,9 @@ We use this library at GitHub to detect blob languages, highlight code, ignore b
|
||||
|
||||
### Language detection
|
||||
|
||||
Linguist defines a list of all languages known to GitHub in a [yaml file](https://github.com/github/linguist/blob/master/lib/linguist/languages.yml). In order for a file to be highlighted, a language and lexer must be defined there.
|
||||
Linguist defines a list of all languages known to GitHub in a [yaml file](https://github.com/github/linguist/blob/master/lib/linguist/languages.yml). In order for a file to be highlighted, a language and a lexer must be defined there.
|
||||
|
||||
Most languages are detected by their file extension. This is the fastest and most common situation.
|
||||
|
||||
For disambiguating between files with common extensions, we first apply
|
||||
some common-sense heuristics to pick out obvious languages. After that, we use a
|
||||
Most languages are detected by their file extension. For disambiguating between files with common extensions, we first apply some common-sense heuristics to pick out obvious languages. After that, we use a
|
||||
[statistical
|
||||
classifier](https://github.com/github/linguist/blob/master/lib/linguist/classifier.rb).
|
||||
This process can help us tell the difference between, for example, `.h` files which could be either C, C++, or Obj-C.
|
||||
@@ -31,7 +28,7 @@ The actual syntax highlighting is handled by our Pygments wrapper, [pygments.rb]
|
||||
|
||||
### Stats
|
||||
|
||||
The Language stats bar that you see on every repository is built by aggregating the languages of each file in that repository. The top language in the graph determines the project's primary language. Collectively, these stats make up the [Top Languages](https://github.com/languages) page.
|
||||
The Language stats bar that you see on every repository is built by aggregating the languages of each file in that repository. The top language in the graph determines the project's primary language.
|
||||
|
||||
The repository stats API, accessed through `#languages`, can be used on a directory:
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Gem::Specification.new do |s|
|
||||
s.name = 'github-linguist'
|
||||
s.version = '2.10.9'
|
||||
s.version = '2.10.12'
|
||||
s.summary = "GitHub Language detection"
|
||||
s.description = 'We use this library at GitHub to detect blob languages, highlight code, ignore binary files, suppress generated files in diffs, and generate language breakdown graphs.'
|
||||
|
||||
|
||||
@@ -62,7 +62,8 @@ module Linguist
|
||||
generated_protocol_buffer? ||
|
||||
generated_jni_header? ||
|
||||
composer_lock? ||
|
||||
node_modules?
|
||||
node_modules? ||
|
||||
vcr_cassette?
|
||||
end
|
||||
|
||||
# Internal: Is the blob an XCode project file?
|
||||
@@ -222,20 +223,28 @@ module Linguist
|
||||
lines[1].include?("#include <jni.h>")
|
||||
end
|
||||
|
||||
# node_modules/ can contain large amounts of files, in general not meant
|
||||
# for humans in pull requests.
|
||||
# Internal: Is the blob part of node_modules/, which are not meant for humans in pull requests.
|
||||
#
|
||||
# Returns true or false.
|
||||
def node_modules?
|
||||
!!name.match(/node_modules\//)
|
||||
end
|
||||
|
||||
# the php composer tool generates a lock file to represent a specific dependency state.
|
||||
# In general not meant for humans in pull requests.
|
||||
# Internal: Is the blob a generated php composer lock file?
|
||||
#
|
||||
# Returns true or false.
|
||||
def composer_lock?
|
||||
!!name.match(/composer.lock/)
|
||||
end
|
||||
|
||||
# Is the blob a VCR Cassette file?
|
||||
#
|
||||
# Returns true or false
|
||||
def vcr_cassette?
|
||||
return false unless extname == '.yml'
|
||||
return false unless lines.count > 2
|
||||
# VCR Cassettes have "recorded_with: VCR" in the second last line.
|
||||
return lines[-2].include?("recorded_with: VCR")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -19,6 +19,15 @@ module Linguist
|
||||
if languages.all? { |l| ["Perl", "Prolog"].include?(l) }
|
||||
disambiguate_pl(data, languages)
|
||||
end
|
||||
if languages.all? { |l| ["ECL", "Prolog"].include?(l) }
|
||||
disambiguate_ecl(data, languages)
|
||||
end
|
||||
if languages.all? { |l| ["TypeScript", "XML"].include?(l) }
|
||||
disambiguate_ts(data, languages)
|
||||
end
|
||||
if languages.all? { |l| ["Common Lisp", "OpenCL"].include?(l) }
|
||||
disambiguate_cl(data, languages)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -40,6 +49,30 @@ module Linguist
|
||||
matches
|
||||
end
|
||||
|
||||
def self.disambiguate_ecl(data, languages)
|
||||
matches = []
|
||||
matches << Language["Prolog"] if data.include?(":-")
|
||||
matches << Language["ECL"] if data.include?(":=")
|
||||
matches
|
||||
end
|
||||
|
||||
def self.disambiguate_ts(data, languages)
|
||||
matches = []
|
||||
if (data.include?("</translation>"))
|
||||
matches << Language["XML"]
|
||||
else
|
||||
matches << Language["TypeScript"]
|
||||
end
|
||||
matches
|
||||
end
|
||||
|
||||
def self.disambiguate_cl(data, languages)
|
||||
matches = []
|
||||
matches << Language["Common Lisp"] if data.include?("(defun ")
|
||||
matches << Language["OpenCL"] if /\/\* |\/\/ |^\}/.match(data)
|
||||
matches
|
||||
end
|
||||
|
||||
def self.active?
|
||||
!!ACTIVE
|
||||
end
|
||||
|
||||
@@ -485,7 +485,7 @@ module Linguist
|
||||
#
|
||||
# Returns html String
|
||||
def colorize(text, options = {})
|
||||
lexer.highlight(text, options = {})
|
||||
lexer.highlight(text, options)
|
||||
end
|
||||
|
||||
# Public: Return name as String representation
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
# 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
|
||||
# interpreter - An Array of associated interpreters
|
||||
# interpreters - An Array of associated interpreters
|
||||
# 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
|
||||
@@ -53,6 +53,18 @@ ASP:
|
||||
- .aspx
|
||||
- .axd
|
||||
|
||||
ATS:
|
||||
type: programming
|
||||
color: "#1ac620"
|
||||
primary_extension: .dats
|
||||
lexer: OCaml
|
||||
aliases:
|
||||
- ats2
|
||||
extensions:
|
||||
- .atxt
|
||||
- .hats
|
||||
- .sats
|
||||
|
||||
ActionScript:
|
||||
type: programming
|
||||
lexer: ActionScript 3
|
||||
@@ -92,6 +104,8 @@ AppleScript:
|
||||
primary_extension: .applescript
|
||||
extensions:
|
||||
- .scpt
|
||||
interpreters:
|
||||
- osascript
|
||||
|
||||
Arc:
|
||||
type: programming
|
||||
@@ -115,6 +129,12 @@ AsciiDoc:
|
||||
- .adoc
|
||||
- .asc
|
||||
|
||||
AspectJ:
|
||||
type: programming
|
||||
lexer: AspectJ
|
||||
color: "#1957b0"
|
||||
primary_extension: .aj
|
||||
|
||||
Assembly:
|
||||
type: programming
|
||||
lexer: NASM
|
||||
@@ -214,6 +234,7 @@ C:
|
||||
color: "#555"
|
||||
primary_extension: .c
|
||||
extensions:
|
||||
- .cats
|
||||
- .w
|
||||
|
||||
C#:
|
||||
@@ -239,6 +260,7 @@ C++:
|
||||
extensions:
|
||||
- .C
|
||||
- .c++
|
||||
- .cc
|
||||
- .cxx
|
||||
- .H
|
||||
- .h++
|
||||
@@ -284,7 +306,7 @@ COBOL:
|
||||
|
||||
CSS:
|
||||
ace_mode: css
|
||||
color: "#1f085e"
|
||||
color: "#563d7c"
|
||||
primary_extension: .css
|
||||
|
||||
Ceylon:
|
||||
@@ -296,6 +318,16 @@ ChucK:
|
||||
lexer: Java
|
||||
primary_extension: .ck
|
||||
|
||||
Cirru:
|
||||
type: programming
|
||||
color: "#aaaaff"
|
||||
primary_extension: .cirru
|
||||
# ace_mode: cirru
|
||||
# lexer: Cirru
|
||||
lexer: Text only
|
||||
extensions:
|
||||
- .cr
|
||||
|
||||
Clean:
|
||||
type: programming
|
||||
color: "#3a81ad"
|
||||
@@ -316,6 +348,7 @@ Clojure:
|
||||
- .cljscm
|
||||
- .cljx
|
||||
- .hic
|
||||
- .cljs.hl
|
||||
filenames:
|
||||
- riemann.config
|
||||
|
||||
@@ -333,6 +366,8 @@ CoffeeScript:
|
||||
- .iced
|
||||
filenames:
|
||||
- Cakefile
|
||||
interpreters:
|
||||
- coffee
|
||||
|
||||
ColdFusion:
|
||||
type: programming
|
||||
@@ -388,7 +423,7 @@ Crystal:
|
||||
lexer: Ruby
|
||||
primary_extension: .cr
|
||||
ace_mode: ruby
|
||||
|
||||
|
||||
Cucumber:
|
||||
lexer: Gherkin
|
||||
primary_extension: .feature
|
||||
@@ -459,10 +494,19 @@ DCPU-16 ASM:
|
||||
Diff:
|
||||
primary_extension: .diff
|
||||
|
||||
Dogescript:
|
||||
type: programming
|
||||
lexer: Text only
|
||||
color: "#cca760"
|
||||
primary_extension: .djs
|
||||
|
||||
Dylan:
|
||||
type: programming
|
||||
color: "#3ebc27"
|
||||
primary_extension: .dylan
|
||||
extensions:
|
||||
- .intr
|
||||
- .lid
|
||||
|
||||
Ecere Projects:
|
||||
type: data
|
||||
@@ -478,6 +522,14 @@ ECL:
|
||||
extensions:
|
||||
- .eclxml
|
||||
|
||||
Eagle:
|
||||
type: markup
|
||||
color: "#3994bc"
|
||||
lexer: XML
|
||||
primary_extension: .sch
|
||||
extensions:
|
||||
- .brd
|
||||
|
||||
Eiffel:
|
||||
type: programming
|
||||
lexer: Text only
|
||||
@@ -528,6 +580,14 @@ F#:
|
||||
- .fsi
|
||||
- .fsx
|
||||
|
||||
FLUX:
|
||||
type: programming
|
||||
color: "#33CCFF"
|
||||
primary_extension: .fx
|
||||
lexer: Text only
|
||||
extensions:
|
||||
- .flux
|
||||
|
||||
FORTRAN:
|
||||
type: programming
|
||||
lexer: Fortran
|
||||
@@ -580,6 +640,17 @@ Forth:
|
||||
extensions:
|
||||
- .4th
|
||||
|
||||
Frege:
|
||||
type: programming
|
||||
color: "#00cafe"
|
||||
lexer: Haskell
|
||||
primary_extension: .fr
|
||||
|
||||
Game Maker Language:
|
||||
type: programming
|
||||
lexer: JavaScript
|
||||
primary_extension: .gml
|
||||
|
||||
GAS:
|
||||
type: programming
|
||||
group: Assembly
|
||||
@@ -627,6 +698,17 @@ Glyph:
|
||||
lexer: Tcl
|
||||
primary_extension: .glf
|
||||
|
||||
Gnuplot:
|
||||
type: programming
|
||||
color: "#f0a9f0"
|
||||
lexer: Gnuplot
|
||||
primary_extension: .gp
|
||||
extensions:
|
||||
- .gnu
|
||||
- .gnuplot
|
||||
- .plot
|
||||
- .plt
|
||||
|
||||
Go:
|
||||
type: programming
|
||||
color: "#a89b4d"
|
||||
@@ -653,6 +735,8 @@ Groovy:
|
||||
ace_mode: groovy
|
||||
color: "#e69f56"
|
||||
primary_extension: .groovy
|
||||
interpreters:
|
||||
- groovy
|
||||
|
||||
Groovy Server Pages:
|
||||
group: Groovy
|
||||
@@ -670,6 +754,7 @@ HTML:
|
||||
extensions:
|
||||
- .htm
|
||||
- .xhtml
|
||||
- .html.hl
|
||||
|
||||
HTML+Django:
|
||||
type: markup
|
||||
@@ -718,6 +803,12 @@ Handlebars:
|
||||
- .html.handlebars
|
||||
- .html.hbs
|
||||
|
||||
Harbour:
|
||||
type: programming
|
||||
lexer: Text only
|
||||
color: "#0e60e3"
|
||||
primary_extension: .hb
|
||||
|
||||
Haskell:
|
||||
type: programming
|
||||
color: "#29b544"
|
||||
@@ -733,6 +824,13 @@ Haxe:
|
||||
extensions:
|
||||
- .hxsl
|
||||
|
||||
Hy:
|
||||
type: programming
|
||||
lexer: Clojure
|
||||
ace_mode: clojure
|
||||
color: "#7891b1"
|
||||
primary_extension: .hy
|
||||
|
||||
IDL:
|
||||
type: programming
|
||||
lexer: Text only
|
||||
@@ -805,6 +903,13 @@ JSON5:
|
||||
lexer: JavaScript
|
||||
primary_extension: .json5
|
||||
|
||||
JSONLD:
|
||||
type: data
|
||||
group: JavaScript
|
||||
ace_mode: json
|
||||
lexer: JavaScript
|
||||
primary_extension: .jsonld
|
||||
|
||||
Jade:
|
||||
group: HTML
|
||||
type: markup
|
||||
@@ -827,7 +932,7 @@ Java Server Pages:
|
||||
JavaScript:
|
||||
type: programming
|
||||
ace_mode: javascript
|
||||
color: "#f15501"
|
||||
color: "#f7df1e"
|
||||
aliases:
|
||||
- js
|
||||
- node
|
||||
@@ -835,6 +940,7 @@ JavaScript:
|
||||
extensions:
|
||||
- ._js
|
||||
- .bones
|
||||
- .es6
|
||||
- .jake
|
||||
- .jsfl
|
||||
- .jsm
|
||||
@@ -846,6 +952,8 @@ JavaScript:
|
||||
- .ssjs
|
||||
filenames:
|
||||
- Jakefile
|
||||
interpreters:
|
||||
- node
|
||||
|
||||
Julia:
|
||||
type: programming
|
||||
@@ -992,6 +1100,18 @@ Markdown:
|
||||
- .mkdown
|
||||
- .ron
|
||||
|
||||
Mask:
|
||||
type: markup
|
||||
lexer: SCSS
|
||||
color: "#f97732"
|
||||
ace_mode: scss
|
||||
primary_extension: .mask
|
||||
|
||||
Mathematica:
|
||||
type: programming
|
||||
primary_extension: .mathematica
|
||||
lexer: Text only
|
||||
|
||||
Matlab:
|
||||
type: programming
|
||||
color: "#bb92ac"
|
||||
@@ -1099,6 +1219,7 @@ OCaml:
|
||||
primary_extension: .ml
|
||||
extensions:
|
||||
- .eliomi
|
||||
- .ml4
|
||||
- .mli
|
||||
- .mll
|
||||
- .mly
|
||||
@@ -1171,6 +1292,12 @@ Oxygene:
|
||||
color: "#5a63a3"
|
||||
primary_extension: .oxygene
|
||||
|
||||
PAWN:
|
||||
type: programming
|
||||
lexer: C++
|
||||
color: "#dbb284"
|
||||
primary_extension: .pwn
|
||||
|
||||
PHP:
|
||||
type: programming
|
||||
ace_mode: php
|
||||
@@ -1293,6 +1420,9 @@ Prolog:
|
||||
type: programming
|
||||
color: "#74283c"
|
||||
primary_extension: .prolog
|
||||
extensions:
|
||||
- .ecl
|
||||
- .pl
|
||||
|
||||
Protocol Buffer:
|
||||
type: markup
|
||||
@@ -1351,11 +1481,12 @@ R:
|
||||
type: programming
|
||||
color: "#198ce7"
|
||||
lexer: S
|
||||
aliases:
|
||||
aliases:
|
||||
- R
|
||||
primary_extension: .r
|
||||
extensions:
|
||||
- .R
|
||||
- .rsx
|
||||
filenames:
|
||||
- .Rprofile
|
||||
interpreters:
|
||||
@@ -1469,6 +1600,7 @@ Ruby:
|
||||
- Appraisals
|
||||
- Berksfile
|
||||
- Gemfile
|
||||
- Gemfile.lock
|
||||
- Guardfile
|
||||
- Podfile
|
||||
- Thorfile
|
||||
@@ -1520,6 +1652,7 @@ Scheme:
|
||||
color: "#1e4aec"
|
||||
primary_extension: .scm
|
||||
extensions:
|
||||
- .sld
|
||||
- .sls
|
||||
- .ss
|
||||
interpreters:
|
||||
@@ -1558,6 +1691,12 @@ Shell:
|
||||
filenames:
|
||||
- Dockerfile
|
||||
|
||||
Shen:
|
||||
type: programming
|
||||
color: "#120F14"
|
||||
lexer: Text only
|
||||
primary_extension: .shen
|
||||
|
||||
Slash:
|
||||
type: programming
|
||||
color: "#007eff"
|
||||
@@ -1597,6 +1736,15 @@ SuperCollider:
|
||||
lexer: Text only
|
||||
primary_extension: .scd
|
||||
|
||||
SystemVerilog:
|
||||
type: programming
|
||||
color: "#343761"
|
||||
lexer: systemverilog
|
||||
primary_extension: .sv
|
||||
extensions:
|
||||
- .svh
|
||||
- .vh
|
||||
|
||||
TOML:
|
||||
type: data
|
||||
primary_extension: .toml
|
||||
@@ -1612,6 +1760,7 @@ Tcl:
|
||||
primary_extension: .tcl
|
||||
extensions:
|
||||
- .adp
|
||||
- .tm
|
||||
|
||||
Tcsh:
|
||||
type: programming
|
||||
@@ -1631,6 +1780,7 @@ TeX:
|
||||
extensions:
|
||||
- .aux
|
||||
- .bib
|
||||
- .cls
|
||||
- .dtx
|
||||
- .ins
|
||||
- .ltx
|
||||
@@ -1773,6 +1923,7 @@ XML:
|
||||
- .kml
|
||||
- .launch
|
||||
- .mxml
|
||||
- .osm
|
||||
- .plist
|
||||
- .pluginspec
|
||||
- .ps1xml
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -10,7 +10,7 @@
|
||||
## Vendor Conventions ##
|
||||
|
||||
# Caches
|
||||
- cache/
|
||||
- (^|/)cache/
|
||||
|
||||
# Dependencies
|
||||
- ^[Dd]ependencies/
|
||||
@@ -36,6 +36,10 @@
|
||||
# Bootstrap minified css and js
|
||||
- (^|/)bootstrap([^.]*)(\.min)?\.(js|css)$
|
||||
|
||||
# Foundation css
|
||||
- foundation.min.css
|
||||
- foundation.css
|
||||
|
||||
# Vendored dependencies
|
||||
- thirdparty/
|
||||
- vendors?/
|
||||
@@ -43,6 +47,9 @@
|
||||
# Debian packaging
|
||||
- ^debian/
|
||||
|
||||
# Haxelib projects often contain a neko bytecode file named run.n
|
||||
- run.n$
|
||||
|
||||
## Commonly Bundled JavaScript frameworks ##
|
||||
|
||||
# jQuery
|
||||
@@ -59,6 +66,9 @@
|
||||
- (^|/)controls\.js$
|
||||
- (^|/)dragdrop\.js$
|
||||
|
||||
# Typescript definition files
|
||||
- (.*?)\.d\.ts$
|
||||
|
||||
# MooTools
|
||||
- (^|/)mootools([^.]*)\d+\.\d+.\d+([^.]*)\.js$
|
||||
|
||||
@@ -88,6 +98,9 @@
|
||||
# AngularJS
|
||||
- (^|/)angular([^.]*)(\.min)?\.js$
|
||||
|
||||
# React
|
||||
- (^|/)react(-[^.]*)?(\.min)?\.js$
|
||||
|
||||
## Python ##
|
||||
|
||||
# django
|
||||
@@ -107,6 +120,13 @@
|
||||
# Sparkle
|
||||
- (^|/)Sparkle/
|
||||
|
||||
## Groovy ##
|
||||
|
||||
# Gradle
|
||||
- (^|/)gradlew$
|
||||
- (^|/)gradlew\.bat$
|
||||
- (^|/)gradle/wrapper/
|
||||
|
||||
## .NET ##
|
||||
|
||||
# Visual Studio IntelliSense
|
||||
|
||||
110
samples/ATS/CoYonedaLemma.dats
Normal file
110
samples/ATS/CoYonedaLemma.dats
Normal file
@@ -0,0 +1,110 @@
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2014-01
|
||||
// CoYoneda Lemma:
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
#include
|
||||
"share/atspre_staload.hats"
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
staload
|
||||
"libats/ML/SATS/basis.sats"
|
||||
staload
|
||||
"libats/ML/SATS/list0.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload _ = "libats/ML/DATS/list0.dats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
sortdef ftype = type -> type
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
infixr (->) ->>
|
||||
typedef ->> (a:type, b:type) = a -<cloref1> b
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
typedef
|
||||
functor(F:ftype) =
|
||||
{a,b:type} (a ->> b) ->> F(a) ->> F(b)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
typedef
|
||||
list0 (a:type) = list0 (a)
|
||||
extern
|
||||
val functor_list0 : functor (list0)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
functor_list0{a,b}
|
||||
(f) = lam xs => list0_map<a><b> (xs, f)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
datatype
|
||||
CoYoneda
|
||||
(F:ftype, r:type) = {a:type} CoYoneda of (a ->> r, F(a))
|
||||
// end of [CoYoneda]
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
extern
|
||||
fun CoYoneda_phi
|
||||
: {F:ftype}functor(F) -> {r:type} (F (r) ->> CoYoneda (F, r))
|
||||
extern
|
||||
fun CoYoneda_psi
|
||||
: {F:ftype}functor(F) -> {r:type} (CoYoneda (F, r) ->> F (r))
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
CoYoneda_phi(ftor) = lam (fx) => CoYoneda (lam x => x, fx)
|
||||
implement
|
||||
CoYoneda_psi(ftor) = lam (CoYoneda(f, fx)) => ftor (f) (fx)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
datatype int0 = I of (int)
|
||||
datatype bool = True | False // boxed boolean
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun bool2string
|
||||
(x:bool): string =
|
||||
(
|
||||
case+ x of True() => "True" | False() => "False"
|
||||
)
|
||||
//
|
||||
implement
|
||||
fprint_val<bool> (out, x) = fprint (out, bool2string(x))
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
fun int2bool (i: int0): bool =
|
||||
let val+I(i) = i in if i > 0 then True else False end
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
val myintlist0 = g0ofg1($list{int0}((I)1, (I)0, (I)1, (I)0, (I)0))
|
||||
val myboolist0 = CoYoneda{list0,bool}{int0}(lam (i) => int2bool(i), myintlist0)
|
||||
val myboolist0 = CoYoneda_psi{list0}(functor_list0){bool}(myboolist0)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
val ((*void*)) = fprintln! (stdout_ref, "myboolist0 = ", myboolist0)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement main0 () = ()
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [CoYonedaLemma.dats] *)
|
||||
178
samples/ATS/DiningPhil2.dats
Normal file
178
samples/ATS/DiningPhil2.dats
Normal file
@@ -0,0 +1,178 @@
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2013-11
|
||||
//
|
||||
// Implementing a variant of
|
||||
// the problem of Dining Philosophers
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
#include
|
||||
"share/atspre_define.hats"
|
||||
#include
|
||||
"share/atspre_staload.hats"
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
staload
|
||||
UN = "prelude/SATS/unsafe.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload "libc/SATS/stdlib.sats"
|
||||
staload "libc/SATS/unistd.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload "{$LIBATSHWXI}/teaching/mythread/SATS/channel.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload _ = "libats/DATS/deqarray.dats"
|
||||
staload _ = "{$LIBATSHWXI}/teaching/mythread/DATS/channel.dats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload "./DiningPhil2.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement phil_left (n) = n
|
||||
implement phil_right (n) = (n+1) \nmod NPHIL
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
extern
|
||||
fun randsleep (n: intGte(1)): void
|
||||
//
|
||||
implement
|
||||
randsleep (n) =
|
||||
ignoret (sleep($UN.cast{uInt}(rand() mod n + 1)))
|
||||
// end of [randsleep]
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
phil_think (n) =
|
||||
{
|
||||
val () = println! ("phil_think(", n, ") starts")
|
||||
val () = randsleep (6)
|
||||
val () = println! ("phil_think(", n, ") finishes")
|
||||
}
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
phil_dine (n, lf, rf) =
|
||||
{
|
||||
val () = println! ("phil_dine(", n, ") starts")
|
||||
val () = randsleep (3)
|
||||
val () = println! ("phil_dine(", n, ") finishes")
|
||||
}
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
phil_loop (n) = let
|
||||
//
|
||||
val () = phil_think (n)
|
||||
//
|
||||
val nl = phil_left (n)
|
||||
val nr = phil_right (n)
|
||||
//
|
||||
val ch_lfork = fork_changet (nl)
|
||||
val ch_rfork = fork_changet (nr)
|
||||
//
|
||||
val lf = channel_takeout (ch_lfork)
|
||||
val () = println! ("phil_loop(", n, ") picks left fork")
|
||||
//
|
||||
val () = randsleep (2) // HX: try to actively induce deadlock
|
||||
//
|
||||
val rf = channel_takeout (ch_rfork)
|
||||
val () = println! ("phil_loop(", n, ") picks right fork")
|
||||
//
|
||||
val () = phil_dine (n, lf, rf)
|
||||
//
|
||||
val ch_forktray = forktray_changet ()
|
||||
val () = channel_insert (ch_forktray, lf)
|
||||
val () = channel_insert (ch_forktray, rf)
|
||||
//
|
||||
in
|
||||
phil_loop (n)
|
||||
end // end of [phil_loop]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
cleaner_wash (f) =
|
||||
{
|
||||
val f = fork_get_num (f)
|
||||
val () = println! ("cleaner_wash(", f, ") starts")
|
||||
val () = randsleep (1)
|
||||
val () = println! ("cleaner_wash(", f, ") finishes")
|
||||
}
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
cleaner_return (f) =
|
||||
{
|
||||
val n = fork_get_num (f)
|
||||
val ch = fork_changet (n)
|
||||
val () = channel_insert (ch, f)
|
||||
}
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
cleaner_loop () = let
|
||||
//
|
||||
val ch = forktray_changet ()
|
||||
val f0 = channel_takeout (ch)
|
||||
//
|
||||
val () = cleaner_wash (f0)
|
||||
val () = cleaner_return (f0)
|
||||
//
|
||||
in
|
||||
cleaner_loop ()
|
||||
end // end of [cleaner_loop]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
dynload "DiningPhil2.sats"
|
||||
dynload "DiningPhil2_fork.dats"
|
||||
dynload "DiningPhil2_thread.dats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
local
|
||||
//
|
||||
staload
|
||||
"{$LIBATSHWXI}/teaching/mythread/SATS/mythread.sats"
|
||||
//
|
||||
in (* in of [local] *)
|
||||
//
|
||||
val () = mythread_create_cloptr (llam () => phil_loop (0))
|
||||
val () = mythread_create_cloptr (llam () => phil_loop (1))
|
||||
val () = mythread_create_cloptr (llam () => phil_loop (2))
|
||||
val () = mythread_create_cloptr (llam () => phil_loop (3))
|
||||
val () = mythread_create_cloptr (llam () => phil_loop (4))
|
||||
//
|
||||
val () = mythread_create_cloptr (llam () => cleaner_loop ())
|
||||
//
|
||||
end // end of [local]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
main0 () =
|
||||
{
|
||||
//
|
||||
val () = println! ("DiningPhil2: starting")
|
||||
val ((*void*)) = while (true) ignoret (sleep(1))
|
||||
//
|
||||
} (* end of [main0] *)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [DiningPhil2.dats] *)
|
||||
71
samples/ATS/DiningPhil2.sats
Normal file
71
samples/ATS/DiningPhil2.sats
Normal file
@@ -0,0 +1,71 @@
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2013-11
|
||||
//
|
||||
// Implementing a variant of
|
||||
// the problem of Dining Philosophers
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
#include
|
||||
"share/atspre_define.hats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload "{$LIBATSHWXI}/teaching/mythread/SATS/channel.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
%{#
|
||||
#define NPHIL 5
|
||||
%} // end of [%{#]
|
||||
#define NPHIL 5
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
typedef nphil = natLt(NPHIL)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun phil_left (n: nphil): nphil
|
||||
fun phil_right (n: nphil): nphil
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun phil_loop (n: nphil): void
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
fun cleaner_loop ((*void*)): void
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
absvtype fork_vtype = ptr
|
||||
vtypedef fork = fork_vtype
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun fork_get_num (!fork): nphil
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun phil_dine
|
||||
(n: nphil, lf: !fork, rf: !fork): void
|
||||
// end of [phil_dine]
|
||||
|
||||
fun phil_think (n: nphil): void
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun cleaner_wash (f: !fork): void
|
||||
fun cleaner_return (f: fork): void
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun fork_changet (n: nphil): channel(fork)
|
||||
//
|
||||
fun forktray_changet ((*void*)): channel(fork)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [DiningPhil2.sats] *)
|
||||
89
samples/ATS/DiningPhil2_fork.dats
Normal file
89
samples/ATS/DiningPhil2_fork.dats
Normal file
@@ -0,0 +1,89 @@
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2013-11
|
||||
//
|
||||
// Implementing a variant of
|
||||
// the problem of Dining Philosophers
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
#include
|
||||
"share/atspre_define.hats"
|
||||
#include
|
||||
"share/atspre_staload.hats"
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
staload
|
||||
UN = "prelude/SATS/unsafe.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload "{$LIBATSHWXI}/teaching/mythread/SATS/channel.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload _ = "libats/DATS/deqarray.dats"
|
||||
staload _ = "{$LIBATSHWXI}/teaching/mythread/DATS/channel.dats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload "./DiningPhil2.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
datavtype fork = FORK of (nphil)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
assume fork_vtype = fork
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
fork_get_num (f) = let val FORK(n) = f in n end
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
local
|
||||
|
||||
val
|
||||
the_forkarray = let
|
||||
//
|
||||
typedef t = channel(fork)
|
||||
//
|
||||
implement
|
||||
array_tabulate$fopr<t>
|
||||
(n) = ch where
|
||||
{
|
||||
val n = $UN.cast{nphil}(n)
|
||||
val ch = channel_create_exn<fork> (i2sz(2))
|
||||
val () = channel_insert (ch, FORK (n))
|
||||
}
|
||||
//
|
||||
in
|
||||
arrayref_tabulate<t> (i2sz(NPHIL))
|
||||
end // end of [val]
|
||||
|
||||
in (* in of [local] *)
|
||||
|
||||
implement fork_changet (n) = the_forkarray[n]
|
||||
|
||||
end // end of [local]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
local
|
||||
|
||||
val the_forktray =
|
||||
channel_create_exn<fork> (i2sz(NPHIL+1))
|
||||
|
||||
in (* in of [local] *)
|
||||
|
||||
implement forktray_changet () = the_forktray
|
||||
|
||||
end // end of [local]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [DiningPhil2_fork.dats] *)
|
||||
43
samples/ATS/DiningPhil2_thread.dats
Normal file
43
samples/ATS/DiningPhil2_thread.dats
Normal file
@@ -0,0 +1,43 @@
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2013-11
|
||||
//
|
||||
// Implementing a variant of
|
||||
// the problem of Dining Philosophers
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
#include "share/atspre_define.hats"
|
||||
#include "share/atspre_staload.hats"
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
staload "{$LIBATSHWXI}/teaching/mythread/SATS/mythread.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
local
|
||||
//
|
||||
#include "{$LIBATSHWXI}/teaching/mythread/DATS/mythread.dats"
|
||||
//
|
||||
in (* in of [local] *)
|
||||
//
|
||||
// HX: it is intentionally left to be empty
|
||||
//
|
||||
end // end of [local]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
local
|
||||
//
|
||||
#include "{$LIBATSHWXI}/teaching/mythread/DATS/mythread_posix.dats"
|
||||
//
|
||||
in (* in of [local] *)
|
||||
//
|
||||
// HX: it is intentionally left to be empty
|
||||
//
|
||||
end // end of [local]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [DiningPhil2_thread.dats] *)
|
||||
178
samples/ATS/YonedaLemma.dats
Normal file
178
samples/ATS/YonedaLemma.dats
Normal file
@@ -0,0 +1,178 @@
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2014-01
|
||||
// Yoneda Lemma:
|
||||
// The hardest "trivial" theorem :)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
#include
|
||||
"share/atspre_staload.hats"
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
staload
|
||||
"libats/ML/SATS/basis.sats"
|
||||
staload
|
||||
"libats/ML/SATS/list0.sats"
|
||||
staload
|
||||
"libats/ML/SATS/option0.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload _ = "libats/ML/DATS/list0.dats"
|
||||
staload _ = "libats/ML/DATS/option0.dats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
sortdef ftype = type -> type
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
infixr (->) ->>
|
||||
typedef ->> (a:type, b:type) = a -<cloref1> b
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
typedef
|
||||
functor(F:ftype) =
|
||||
{a,b:type} (a ->> b) ->> F(a) ->> F(b)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
typedef
|
||||
list0 (a:type) = list0 (a)
|
||||
extern
|
||||
val functor_list0 : functor (list0)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
functor_list0{a,b}
|
||||
(f) = lam xs => list0_map<a><b> (xs, f)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
typedef
|
||||
option0 (a:type) = option0 (a)
|
||||
extern
|
||||
val functor_option0 : functor (option0)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
functor_option0{a,b}
|
||||
(f) = lam opt => option0_map<a><b> (opt, f)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
extern
|
||||
val functor_homres
|
||||
: {c:type} functor (lam(r:type) => c ->> r)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
functor_homres{c}{a,b} (f) = lam (r) => lam (x) => f (r(x))
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
extern
|
||||
fun Yoneda_phi : {F:ftype}functor(F) ->
|
||||
{a:type}F(a) ->> ({r:type}(a ->> r) ->> F(r))
|
||||
extern
|
||||
fun Yoneda_psi : {F:ftype}functor(F) ->
|
||||
{a:type}({r:type}(a ->> r) ->> F(r)) ->> F(a)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
implement
|
||||
Yoneda_phi
|
||||
(ftor) = lam(fx) => lam (m) => ftor(m)(fx)
|
||||
//
|
||||
implement
|
||||
Yoneda_psi (ftor) = lam(mf) => mf(lam x => x)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
(*
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2014-01-05:
|
||||
// Another version based on Natural Transformation
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
typedef
|
||||
natrans(F:ftype, G:ftype) = {x:type} (F(x) ->> G(x))
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
extern
|
||||
fun Yoneda_phi_nat : {F:ftype}functor(F) ->
|
||||
{a:type} F(a) ->> natrans(lam (r:type) => (a ->> r), F)
|
||||
extern
|
||||
fun Yoneda_psi_nat : {F:ftype}functor(F) ->
|
||||
{a:type} natrans(lam (r:type) => (a ->> r), F) ->> F(a)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
implement
|
||||
Yoneda_phi_nat
|
||||
(ftor) = lam(fx) => lam (m) => ftor(m)(fx)
|
||||
//
|
||||
implement
|
||||
Yoneda_psi_nat (ftor) = lam(mf) => mf(lam x => x)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
*)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
datatype bool = True | False // boxed boolean
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun bool2string
|
||||
(x:bool): string =
|
||||
(
|
||||
case+ x of True() => "True" | False() => "False"
|
||||
)
|
||||
//
|
||||
implement
|
||||
fprint_val<bool> (out, x) = fprint (out, bool2string(x))
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
val myboolist0 =
|
||||
$list_t{bool}(True, False, True, False, False)
|
||||
val myboolist0 = g0ofg1_list (myboolist0)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
extern
|
||||
val Yoneda_bool_list0 : {r:type} (bool ->> r) ->> list0(r)
|
||||
//
|
||||
implement
|
||||
Yoneda_bool_list0 =
|
||||
Yoneda_phi(functor_list0){bool}(myboolist0)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
val myboolist1 =
|
||||
Yoneda_psi(functor_list0){bool}(Yoneda_bool_list0)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
val () = fprintln! (stdout_ref, "myboolist0 = ", myboolist0)
|
||||
val () = fprintln! (stdout_ref, "myboolist1 = ", myboolist1)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement main0 () = ()
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [YonedaLemma.dats] *)
|
||||
187
samples/ATS/linset.hats
Normal file
187
samples/ATS/linset.hats
Normal file
@@ -0,0 +1,187 @@
|
||||
(***********************************************************************)
|
||||
(* *)
|
||||
(* Applied Type System *)
|
||||
(* *)
|
||||
(***********************************************************************)
|
||||
|
||||
(*
|
||||
** ATS/Postiats - Unleashing the Potential of Types!
|
||||
** Copyright (C) 2011-2013 Hongwei Xi, ATS Trustful Software, Inc.
|
||||
** All rights reserved
|
||||
**
|
||||
** ATS is free software; you can redistribute it and/or modify it under
|
||||
** the terms of the GNU GENERAL PUBLIC LICENSE (GPL) as published by the
|
||||
** Free Software Foundation; either version 3, or (at your option) any
|
||||
** later version.
|
||||
**
|
||||
** ATS is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||
** WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
** FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
** for more details.
|
||||
**
|
||||
** You should have received a copy of the GNU General Public License
|
||||
** along with ATS; see the file COPYING. If not, please write to the
|
||||
** Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
** 02110-1301, USA.
|
||||
*)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* Author: Hongwei Xi *)
|
||||
(* Authoremail: hwxi AT cs DOT bu DOT edu *)
|
||||
(* Start time: December, 2012 *)
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX: shared by linset_listord (* ordered list *)
|
||||
// HX: shared by linset_avltree (* AVL-tree-based *)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2013-02:
|
||||
// for sets of nonlinear elements
|
||||
//
|
||||
absvtype set_vtype (a:t@ype+) = ptr
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
vtypedef set (a:t0p) = set_vtype (a)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p}
|
||||
compare_elt_elt (x1: a, x2: a):<> int
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{} linset_nil{a:t0p} ():<> set(a)
|
||||
fun{} linset_make_nil{a:t0p} ():<> set(a)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p} linset_sing (x: a):<!wrt> set(a)
|
||||
fun{a:t0p} linset_make_sing (x: a):<!wrt> set(a)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p}
|
||||
linset_make_list (xs: List(INV(a))):<!wrt> set(a)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{}
|
||||
linset_is_nil {a:t0p} (xs: !set(INV(a))):<> bool
|
||||
fun{}
|
||||
linset_isnot_nil {a:t0p} (xs: !set(INV(a))):<> bool
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p} linset_size (!set(INV(a))): size_t
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p}
|
||||
linset_is_member (xs: !set(INV(a)), x0: a):<> bool
|
||||
fun{a:t0p}
|
||||
linset_isnot_member (xs: !set(INV(a)), x0: a):<> bool
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p}
|
||||
linset_copy (!set(INV(a))):<!wrt> set(a)
|
||||
fun{a:t0p}
|
||||
linset_free (xs: set(INV(a))):<!wrt> void
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun{a:t0p}
|
||||
linset_insert
|
||||
(xs: &set(INV(a)) >> _, x0: a):<!wrt> bool
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun{a:t0p}
|
||||
linset_takeout
|
||||
(
|
||||
&set(INV(a)) >> _, a, res: &(a?) >> opt(a, b)
|
||||
) :<!wrt> #[b:bool] bool(b) // endfun
|
||||
fun{a:t0p}
|
||||
linset_takeout_opt (&set(INV(a)) >> _, a):<!wrt> Option_vt(a)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun{a:t0p}
|
||||
linset_remove
|
||||
(xs: &set(INV(a)) >> _, x0: a):<!wrt> bool
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX: choosing an element in an unspecified manner
|
||||
//
|
||||
fun{a:t0p}
|
||||
linset_choose
|
||||
(
|
||||
xs: !set(INV(a)), x: &a? >> opt (a, b)
|
||||
) :<!wrt> #[b:bool] bool(b)
|
||||
//
|
||||
fun{a:t0p}
|
||||
linset_choose_opt (xs: !set(INV(a))):<!wrt> Option_vt(a)
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p}
|
||||
linset_takeoutmax
|
||||
(
|
||||
xs: &set(INV(a)) >> _, res: &a? >> opt(a, b)
|
||||
) :<!wrt> #[b:bool] bool (b)
|
||||
fun{a:t0p}
|
||||
linset_takeoutmax_opt (xs: &set(INV(a)) >> _):<!wrt> Option_vt(a)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p}
|
||||
linset_takeoutmin
|
||||
(
|
||||
xs: &set(INV(a)) >> _, res: &a? >> opt(a, b)
|
||||
) :<!wrt> #[b:bool] bool (b)
|
||||
fun{a:t0p}
|
||||
linset_takeoutmin_opt (xs: &set(INV(a)) >> _):<!wrt> Option_vt(a)
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun{}
|
||||
fprint_linset$sep (FILEref): void // ", "
|
||||
//
|
||||
fun{a:t0p}
|
||||
fprint_linset (out: FILEref, xs: !set(INV(a))): void
|
||||
//
|
||||
overload fprint with fprint_linset
|
||||
//
|
||||
(* ****** ****** *)
|
||||
//
|
||||
fun{
|
||||
a:t0p}{env:vt0p
|
||||
} linset_foreach$fwork
|
||||
(x: a, env: &(env) >> _): void
|
||||
//
|
||||
fun{a:t0p}
|
||||
linset_foreach (set: !set(INV(a))): void
|
||||
fun{
|
||||
a:t0p}{env:vt0p
|
||||
} linset_foreach_env
|
||||
(set: !set(INV(a)), env: &(env) >> _): void
|
||||
// end of [linset_foreach_env]
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p}
|
||||
linset_listize (xs: set(INV(a))): List0_vt (a)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
fun{a:t0p}
|
||||
linset_listize1 (xs: !set(INV(a))): List0_vt (a)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [linset.hats] *)
|
||||
504
samples/ATS/linset_listord.dats
Normal file
504
samples/ATS/linset_listord.dats
Normal file
@@ -0,0 +1,504 @@
|
||||
(***********************************************************************)
|
||||
(* *)
|
||||
(* Applied Type System *)
|
||||
(* *)
|
||||
(***********************************************************************)
|
||||
|
||||
(*
|
||||
** ATS/Postiats - Unleashing the Potential of Types!
|
||||
** Copyright (C) 2011-2013 Hongwei Xi, ATS Trustful Software, Inc.
|
||||
** All rights reserved
|
||||
**
|
||||
** ATS is free software; you can redistribute it and/or modify it under
|
||||
** the terms of the GNU GENERAL PUBLIC LICENSE (GPL) as published by the
|
||||
** Free Software Foundation; either version 3, or (at your option) any
|
||||
** later version.
|
||||
**
|
||||
** ATS is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||
** WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
** FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
** for more details.
|
||||
**
|
||||
** You should have received a copy of the GNU General Public License
|
||||
** along with ATS; see the file COPYING. If not, please write to the
|
||||
** Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
** 02110-1301, USA.
|
||||
*)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* Author: Hongwei Xi *)
|
||||
(* Authoremail: hwxi AT cs DOT bu DOT edu *)
|
||||
(* Start time: February, 2013 *)
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX-2013-08:
|
||||
// a set is represented as a sorted list in descending order;
|
||||
// note that descending order is chosen to faciliate set comparison
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
staload
|
||||
UN = "prelude/SATS/unsafe.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
staload "libats/SATS/linset_listord.sats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
#include "./SHARE/linset.hats" // code reuse
|
||||
#include "./SHARE/linset_node.hats" // code reuse
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
assume
|
||||
set_vtype (elt:t@ype) = List0_vt (elt)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{}
|
||||
linset_nil () = list_vt_nil ()
|
||||
implement{}
|
||||
linset_make_nil () = list_vt_nil ()
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
linset_sing
|
||||
(x) = list_vt_cons{a}(x, list_vt_nil)
|
||||
// end of [linset_sing]
|
||||
implement{a}
|
||||
linset_make_sing
|
||||
(x) = list_vt_cons{a}(x, list_vt_nil)
|
||||
// end of [linset_make_sing]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{}
|
||||
linset_is_nil (xs) = list_vt_is_nil (xs)
|
||||
implement{}
|
||||
linset_isnot_nil (xs) = list_vt_is_cons (xs)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{a}
|
||||
linset_size (xs) =
|
||||
let val n = list_vt_length(xs) in i2sz(n) end
|
||||
// end of [linset_size]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{a}
|
||||
linset_is_member
|
||||
(xs, x0) = let
|
||||
//
|
||||
fun aux
|
||||
{n:nat} .<n>.
|
||||
(
|
||||
xs: !list_vt (a, n)
|
||||
) :<> bool = let
|
||||
in
|
||||
//
|
||||
case+ xs of
|
||||
| list_vt_cons (x, xs) => let
|
||||
val sgn = compare_elt_elt<a> (x0, x) in
|
||||
if sgn > 0 then false else (if sgn < 0 then aux (xs) else true)
|
||||
end // end of [list_vt_cons]
|
||||
| list_vt_nil ((*void*)) => false
|
||||
//
|
||||
end // end of [aux]
|
||||
//
|
||||
in
|
||||
aux (xs)
|
||||
end // end of [linset_is_member]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{a}
|
||||
linset_copy (xs) = list_vt_copy<a> (xs)
|
||||
implement{a}
|
||||
linset_free (xs) = list_vt_free<a> (xs)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{a}
|
||||
linset_insert
|
||||
(xs, x0) = let
|
||||
//
|
||||
fun
|
||||
mynode_cons
|
||||
{n:nat} .<>.
|
||||
(
|
||||
nx: mynode1 (a), xs: list_vt (a, n)
|
||||
) : list_vt (a, n+1) = let
|
||||
//
|
||||
val xs1 =
|
||||
$UN.castvwtp0{List1_vt(a)}(nx)
|
||||
val+@list_vt_cons (_, xs2) = xs1
|
||||
prval () = $UN.cast2void (xs2); val () = (xs2 := xs)
|
||||
//
|
||||
in
|
||||
fold@ (xs1); xs1
|
||||
end // end of [mynode_cons]
|
||||
//
|
||||
fun ins
|
||||
{n:nat} .<n>. // tail-recursive
|
||||
(
|
||||
xs: &list_vt (a, n) >> list_vt (a, n1)
|
||||
) : #[n1:nat | n <= n1; n1 <= n+1] bool =
|
||||
(
|
||||
case+ xs of
|
||||
| @list_vt_cons
|
||||
(x, xs1) => let
|
||||
val sgn =
|
||||
compare_elt_elt<a> (x0, x)
|
||||
// end of [val]
|
||||
in
|
||||
if sgn > 0 then let
|
||||
prval () = fold@ (xs)
|
||||
val nx = mynode_make_elt<a> (x0)
|
||||
val ((*void*)) = xs := mynode_cons (nx, xs)
|
||||
in
|
||||
false
|
||||
end else if sgn < 0 then let
|
||||
val ans = ins (xs1)
|
||||
prval () = fold@ (xs)
|
||||
in
|
||||
ans
|
||||
end else let // [x0] is found
|
||||
prval () = fold@ (xs)
|
||||
in
|
||||
true (* [x0] in [xs] *)
|
||||
end (* end of [if] *)
|
||||
end // end of [list_vt_cons]
|
||||
| list_vt_nil () => let
|
||||
val nx = mynode_make_elt<a> (x0)
|
||||
val ((*void*)) = xs := mynode_cons (nx, xs)
|
||||
in
|
||||
false
|
||||
end // end of [list_vt_nil]
|
||||
) (* end of [ins] *)
|
||||
//
|
||||
in
|
||||
$effmask_all (ins (xs))
|
||||
end // end of [linset_insert]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(*
|
||||
//
|
||||
HX-2013-08:
|
||||
[linset_remove] moved up
|
||||
//
|
||||
implement{a}
|
||||
linset_remove
|
||||
(xs, x0) = let
|
||||
//
|
||||
fun rem
|
||||
{n:nat} .<n>. // tail-recursive
|
||||
(
|
||||
xs: &list_vt (a, n) >> list_vt (a, n1)
|
||||
) : #[n1:nat | n1 <= n; n <= n1+1] bool =
|
||||
(
|
||||
case+ xs of
|
||||
| @list_vt_cons
|
||||
(x, xs1) => let
|
||||
val sgn =
|
||||
compare_elt_elt<a> (x0, x)
|
||||
// end of [val]
|
||||
in
|
||||
if sgn > 0 then let
|
||||
prval () = fold@ (xs)
|
||||
in
|
||||
false
|
||||
end else if sgn < 0 then let
|
||||
val ans = rem (xs1)
|
||||
prval () = fold@ (xs)
|
||||
in
|
||||
ans
|
||||
end else let // x0 = x
|
||||
val xs1_ = xs1
|
||||
val ((*void*)) = free@{a}{0}(xs)
|
||||
val () = xs := xs1_
|
||||
in
|
||||
true // [x0] in [xs]
|
||||
end (* end of [if] *)
|
||||
end // end of [list_vt_cons]
|
||||
| list_vt_nil () => false
|
||||
) (* end of [rem] *)
|
||||
//
|
||||
in
|
||||
$effmask_all (rem (xs))
|
||||
end // end of [linset_remove]
|
||||
*)
|
||||
|
||||
(* ****** ****** *)
|
||||
(*
|
||||
** By Brandon Barker
|
||||
*)
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
linset_choose
|
||||
(xs, x0) = let
|
||||
in
|
||||
//
|
||||
case+ xs of
|
||||
| list_vt_cons
|
||||
(x, xs1) => let
|
||||
val () = x0 := x
|
||||
prval () = opt_some{a}(x0)
|
||||
in
|
||||
true
|
||||
end // end of [list_vt_cons]
|
||||
| list_vt_nil () => let
|
||||
prval () = opt_none{a}(x0)
|
||||
in
|
||||
false
|
||||
end // end of [list_vt_nil]
|
||||
//
|
||||
end // end of [linset_choose]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
{a}{env}
|
||||
linset_foreach_env (xs, env) = let
|
||||
//
|
||||
implement
|
||||
list_vt_foreach$fwork<a><env>
|
||||
(x, env) = linset_foreach$fwork<a><env> (x, env)
|
||||
//
|
||||
in
|
||||
list_vt_foreach_env<a><env> (xs, env)
|
||||
end // end of [linset_foreach_env]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{a}
|
||||
linset_listize (xs) = xs
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{a}
|
||||
linset_listize1 (xs) = list_vt_copy (xs)
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// HX: functions for processing mynodes
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{
|
||||
} mynode_null{a} () =
|
||||
$UN.castvwtp0{mynode(a,null)}(the_null_ptr)
|
||||
// end of [mynode_null]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
mynode_make_elt
|
||||
(x) = let
|
||||
//
|
||||
val nx = list_vt_cons{a}{0}(x, _ )
|
||||
//
|
||||
in
|
||||
$UN.castvwtp0{mynode1(a)}(nx)
|
||||
end // end of [mynode_make_elt]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement{
|
||||
} mynode_free
|
||||
{a}(nx) = () where {
|
||||
val nx =
|
||||
$UN.castvwtp0{List1_vt(a)}(nx)
|
||||
//
|
||||
val+~list_vt_cons (_, nx2) = nx
|
||||
//
|
||||
prval ((*void*)) = $UN.cast2void (nx2)
|
||||
//
|
||||
} (* end of [mynode_free] *)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
mynode_get_elt
|
||||
(nx) = (x) where {
|
||||
//
|
||||
val nx1 =
|
||||
$UN.castvwtp1{List1_vt(a)}(nx)
|
||||
//
|
||||
val+list_vt_cons (x, _) = nx1
|
||||
//
|
||||
prval ((*void*)) = $UN.cast2void (nx1)
|
||||
//
|
||||
} (* end of [mynode_get_elt] *)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
mynode_set_elt
|
||||
{l} (nx, x0) =
|
||||
{
|
||||
//
|
||||
val nx1 =
|
||||
$UN.castvwtp1{List1_vt(a)}(nx)
|
||||
//
|
||||
val+@list_vt_cons (x, _) = nx1
|
||||
//
|
||||
val () = x := x0
|
||||
//
|
||||
prval () = fold@ (nx1)
|
||||
prval () = $UN.cast2void (nx1)
|
||||
//
|
||||
prval () = __assert (nx) where
|
||||
{
|
||||
extern praxi __assert (nx: !mynode(a?, l) >> mynode (a, l)): void
|
||||
} (* end of [prval] *)
|
||||
//
|
||||
} (* end of [mynode_set_elt] *)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
mynode_getfree_elt
|
||||
(nx) = (x) where {
|
||||
//
|
||||
val nx =
|
||||
$UN.castvwtp0{List1_vt(a)}(nx)
|
||||
//
|
||||
val+~list_vt_cons (x, nx2) = nx
|
||||
//
|
||||
prval ((*void*)) = $UN.cast2void (nx2)
|
||||
//
|
||||
} (* end of [mynode_getfree_elt] *)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(*
|
||||
fun{a:t0p}
|
||||
linset_takeout_ngc
|
||||
(set: &set(INV(a)) >> _, x0: a):<!wrt> mynode0 (a)
|
||||
// end of [linset_takeout_ngc]
|
||||
*)
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
linset_takeout_ngc
|
||||
(set, x0) = let
|
||||
//
|
||||
fun takeout
|
||||
(
|
||||
xs: &List0_vt (a) >> _
|
||||
) : mynode0(a) = let
|
||||
in
|
||||
//
|
||||
case+ xs of
|
||||
| @list_vt_cons
|
||||
(x, xs1) => let
|
||||
prval pf_x = view@x
|
||||
prval pf_xs1 = view@xs1
|
||||
val sgn =
|
||||
compare_elt_elt<a> (x0, x)
|
||||
// end of [val]
|
||||
in
|
||||
if sgn > 0 then let
|
||||
prval () = fold@ (xs)
|
||||
in
|
||||
mynode_null{a}((*void*))
|
||||
end else if sgn < 0 then let
|
||||
val res = takeout (xs1)
|
||||
prval ((*void*)) = fold@ (xs)
|
||||
in
|
||||
res
|
||||
end else let // x0 = x
|
||||
val xs1_ = xs1
|
||||
val res = $UN.castvwtp0{mynode1(a)}((pf_x, pf_xs1 | xs))
|
||||
val () = xs := xs1_
|
||||
in
|
||||
res // [x0] in [xs]
|
||||
end (* end of [if] *)
|
||||
end // end of [list_vt_cons]
|
||||
| list_vt_nil () => mynode_null{a}((*void*))
|
||||
//
|
||||
end (* end of [takeout] *)
|
||||
//
|
||||
in
|
||||
$effmask_all (takeout (set))
|
||||
end // end of [linset_takeout_ngc]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
linset_takeoutmax_ngc
|
||||
(xs) = let
|
||||
in
|
||||
//
|
||||
case+ xs of
|
||||
| @list_vt_cons
|
||||
(x, xs1) => let
|
||||
prval pf_x = view@x
|
||||
prval pf_xs1 = view@xs1
|
||||
val xs_ = xs
|
||||
val () = xs := xs1
|
||||
in
|
||||
$UN.castvwtp0{mynode1(a)}((pf_x, pf_xs1 | xs_))
|
||||
end // end of [list_vt_cons]
|
||||
| @list_vt_nil () => let
|
||||
prval () = fold@ (xs)
|
||||
in
|
||||
mynode_null{a}((*void*))
|
||||
end // end of [list_vt_nil]
|
||||
//
|
||||
end // end of [linset_takeoutmax_ngc]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
implement
|
||||
{a}(*tmp*)
|
||||
linset_takeoutmin_ngc
|
||||
(xs) = let
|
||||
//
|
||||
fun unsnoc
|
||||
{n:pos} .<n>.
|
||||
(
|
||||
xs: &list_vt (a, n) >> list_vt (a, n-1)
|
||||
) :<!wrt> mynode1 (a) = let
|
||||
//
|
||||
val+@list_vt_cons (x, xs1) = xs
|
||||
//
|
||||
prval pf_x = view@x and pf_xs1 = view@xs1
|
||||
//
|
||||
in
|
||||
//
|
||||
case+ xs1 of
|
||||
| list_vt_cons _ =>
|
||||
let val res = unsnoc(xs1) in fold@xs; res end
|
||||
// end of [list_vt_cons]
|
||||
| list_vt_nil () => let
|
||||
val xs_ = xs
|
||||
val () = xs := list_vt_nil{a}()
|
||||
in
|
||||
$UN.castvwtp0{mynode1(a)}((pf_x, pf_xs1 | xs_))
|
||||
end // end of [list_vt_nil]
|
||||
//
|
||||
end // end of [unsnoc]
|
||||
//
|
||||
in
|
||||
//
|
||||
case+ xs of
|
||||
| list_vt_cons _ => unsnoc (xs)
|
||||
| list_vt_nil () => mynode_null{a}((*void*))
|
||||
//
|
||||
end // end of [linset_takeoutmin_ngc]
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [linset_listord.dats] *)
|
||||
51
samples/ATS/linset_listord.sats
Normal file
51
samples/ATS/linset_listord.sats
Normal file
@@ -0,0 +1,51 @@
|
||||
(***********************************************************************)
|
||||
(* *)
|
||||
(* Applied Type System *)
|
||||
(* *)
|
||||
(***********************************************************************)
|
||||
|
||||
(*
|
||||
** ATS/Postiats - Unleashing the Potential of Types!
|
||||
** Copyright (C) 2011-2013 Hongwei Xi, ATS Trustful Software, Inc.
|
||||
** All rights reserved
|
||||
**
|
||||
** ATS is free software; you can redistribute it and/or modify it under
|
||||
** the terms of the GNU GENERAL PUBLIC LICENSE (GPL) as published by the
|
||||
** Free Software Foundation; either version 3, or (at your option) any
|
||||
** later version.
|
||||
**
|
||||
** ATS is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||
** WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
** FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
** for more details.
|
||||
**
|
||||
** You should have received a copy of the GNU General Public License
|
||||
** along with ATS; see the file COPYING. If not, please write to the
|
||||
** Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
** 02110-1301, USA.
|
||||
*)
|
||||
|
||||
(* ****** ****** *)
|
||||
//
|
||||
// Author: Hongwei Xi
|
||||
// Authoremail: hwxiATcsDOTbuDOTedu
|
||||
// Time: October, 2010
|
||||
//
|
||||
(* ****** ****** *)
|
||||
|
||||
#define ATS_PACKNAME "ATSLIB.libats.linset_listord"
|
||||
#define ATS_STALOADFLAG 0 // no static loading at run-time
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
#include "./SHARE/linset.hats"
|
||||
#include "./SHARE/linset_node.hats"
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
castfn
|
||||
linset2list {a:t0p} (xs: set (INV(a))):<> List0_vt (a)
|
||||
|
||||
(* ****** ****** *)
|
||||
|
||||
(* end of [linset_listord.sats] *)
|
||||
215
samples/ATS/main.atxt
Normal file
215
samples/ATS/main.atxt
Normal file
@@ -0,0 +1,215 @@
|
||||
%{
|
||||
#include "./../ATEXT/atextfun.hats"
|
||||
%}
|
||||
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
|
||||
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
|
||||
<title>EFFECTIVATS-DiningPhil2</title>
|
||||
#patscode_style()
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h1>
|
||||
Effective ATS: Dining Philosophers
|
||||
</h1>
|
||||
|
||||
In this article, I present an implementation of a slight variant of the
|
||||
famous problem of 5-Dining-Philosophers by Dijkstra that makes simple but
|
||||
convincing use of linear types.
|
||||
|
||||
<h2>
|
||||
The Original Problem
|
||||
</h2>
|
||||
|
||||
There are five philosophers sitting around a table and there are also 5
|
||||
forks placed on the table such that each fork is located between the left
|
||||
hand of a philosopher and the right hand of another philosopher. Each
|
||||
philosopher does the following routine repeatedly: thinking and dining. In
|
||||
order to dine, a philosopher needs to first acquire two forks: one located
|
||||
on his left-hand side and the other on his right-hand side. After
|
||||
finishing dining, a philosopher puts the two acquired forks onto the table:
|
||||
one on his left-hand side and the other on his right-hand side.
|
||||
|
||||
<h2>
|
||||
A Variant of the Original Problem
|
||||
</h2>
|
||||
|
||||
The following twist is added to the original version:
|
||||
|
||||
<p>
|
||||
|
||||
After a fork is used, it becomes a "dirty" fork and needs to be put in a
|
||||
tray for dirty forks. There is a cleaner who cleans dirty forks and then
|
||||
puts them back on the table.
|
||||
|
||||
<h2>
|
||||
Channels for Communication
|
||||
</h2>
|
||||
|
||||
A channel is just a shared queue of fixed capacity. The following two
|
||||
functions are for inserting an element into and taking an element out of a
|
||||
given channel:
|
||||
|
||||
<pre
|
||||
class="patsyntax">
|
||||
#pats2xhtml_sats("\
|
||||
fun{a:vt0p} channel_insert (channel (a), a): void
|
||||
fun{a:vt0p} channel_takeout (chan: channel (a)): (a)
|
||||
")</pre>
|
||||
|
||||
If [channel_insert] is called on a channel that is full, then the caller is
|
||||
blocked until an element is taken out of the channel. If [channel_takeout]
|
||||
is called on a channel that is empty, then the caller is blocked until an
|
||||
element is inserted into the channel.
|
||||
|
||||
<h2>
|
||||
A Channel for Each Fork
|
||||
</h2>
|
||||
|
||||
Forks are resources given a linear type. Each fork is initially stored in a
|
||||
channel, which can be obtained by calling the following function:
|
||||
|
||||
<pre
|
||||
class="patsyntax">
|
||||
#pats2xhtml_sats("\
|
||||
fun fork_changet (n: nphil): channel(fork)
|
||||
")</pre>
|
||||
|
||||
where the type [nphil] is defined to be [natLt(5)] (for natural numbers
|
||||
less than 5). The channels for storing forks are chosen to be of capacity
|
||||
2. The reason that channels of capacity 2 are chosen to store at most one
|
||||
element (in each of them) is to guarantee that these channels can never be
|
||||
full (so that there is no attempt made to send signals to awake callers
|
||||
supposedly being blocked due to channels being full).
|
||||
|
||||
|
||||
<h2>
|
||||
A Channel for the Fork Tray
|
||||
</h2>
|
||||
|
||||
A tray for storing "dirty" forks is also a channel, which can be obtained
|
||||
by calling the following function:
|
||||
|
||||
<pre
|
||||
class="patsyntax">
|
||||
#pats2xhtml_sats("\
|
||||
fun forktray_changet ((*void*)): channel(fork)
|
||||
")</pre>
|
||||
|
||||
The capacity chosen for the channel is 6 (instead of 5) so that it can
|
||||
never become full (as there are only 5 forks in total).
|
||||
|
||||
<h2>
|
||||
Philosopher Loop
|
||||
</h2>
|
||||
|
||||
Each philosopher is implemented as a loop:
|
||||
|
||||
<pre
|
||||
class="patsyntax">
|
||||
#pats2xhtml_dats('\
|
||||
implement
|
||||
phil_loop (n) = let
|
||||
//
|
||||
val () = phil_think (n)
|
||||
//
|
||||
val nl = phil_left (n) // = n
|
||||
val nr = phil_right (n) // = (n+1) % 5
|
||||
//
|
||||
val ch_lfork = fork_changet (nl)
|
||||
val ch_rfork = fork_changet (nr)
|
||||
//
|
||||
val lf = channel_takeout (ch_lfork)
|
||||
val () = println! ("phil_loop(", n, ") picks left fork")
|
||||
//
|
||||
val () = randsleep (2) // sleep up to 2 seconds
|
||||
//
|
||||
val rf = channel_takeout (ch_rfork)
|
||||
val () = println! ("phil_loop(", n, ") picks right fork")
|
||||
//
|
||||
val () = phil_dine (n, lf, rf)
|
||||
//
|
||||
val ch_forktray = forktray_changet ()
|
||||
val () = channel_insert (ch_forktray, lf) // left fork to dirty tray
|
||||
val () = channel_insert (ch_forktray, rf) // right fork to dirty tray
|
||||
//
|
||||
in
|
||||
phil_loop (n)
|
||||
end // end of [phil_loop]
|
||||
')</pre>
|
||||
|
||||
It should be straighforward to follow the code for [phil_loop].
|
||||
|
||||
<h2>
|
||||
Fork Cleaner Loop
|
||||
</h2>
|
||||
|
||||
A cleaner is implemented as a loop:
|
||||
|
||||
<pre
|
||||
class="patsyntax">
|
||||
#pats2xhtml_dats('\
|
||||
implement
|
||||
cleaner_loop () = let
|
||||
//
|
||||
val ch = forktray_changet ()
|
||||
val f0 = channel_takeout (ch) // [f0] is dirty
|
||||
//
|
||||
val () = cleaner_wash (f0) // washes dirty [f0]
|
||||
val () = cleaner_return (f0) // puts back cleaned [f0]
|
||||
//
|
||||
in
|
||||
cleaner_loop ()
|
||||
end // end of [cleaner_loop]
|
||||
')</pre>
|
||||
|
||||
The function [cleaner_return] first finds out the number of a given fork
|
||||
and then uses the number to locate the channel for storing the fork. Its
|
||||
actual implementation is given as follows:
|
||||
|
||||
<pre
|
||||
class="patsyntax">
|
||||
#pats2xhtml_dats('\
|
||||
implement
|
||||
cleaner_return (f) =
|
||||
{
|
||||
val n = fork_get_num (f)
|
||||
val ch = fork_changet (n)
|
||||
val () = channel_insert (ch, f)
|
||||
}
|
||||
')</pre>
|
||||
|
||||
It should now be straighforward to follow the code for [cleaner_loop].
|
||||
|
||||
<h2>
|
||||
Testing
|
||||
</h2>
|
||||
|
||||
The entire code of this implementation is stored in the following files:
|
||||
|
||||
<pre>
|
||||
DiningPhil2.sats
|
||||
DiningPhil2.dats
|
||||
DiningPhil2_fork.dats
|
||||
DiningPhil2_thread.dats
|
||||
</pre>
|
||||
|
||||
There is also a Makefile available for compiling the ATS source code into
|
||||
an excutable for testing. One should be able to encounter a deadlock after
|
||||
running the simulation for a while.
|
||||
|
||||
<hr size="2">
|
||||
|
||||
This article is written by <a href="http://www.cs.bu.edu/~hwxi/">Hongwei Xi</a>.
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
%{
|
||||
implement main () = fprint_filsub (stdout_ref, "main_atxt.txt")
|
||||
%}
|
||||
41
samples/AspectJ/CacheAspect.aj
Normal file
41
samples/AspectJ/CacheAspect.aj
Normal file
@@ -0,0 +1,41 @@
|
||||
package com.blogspot.miguelinlas3.aspectj.cache;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
|
||||
import com.blogspot.miguelinlas3.aspectj.cache.marker.Cachable;
|
||||
|
||||
/**
|
||||
* This simple aspect simulates the behaviour of a very simple cache
|
||||
*
|
||||
* @author migue
|
||||
*
|
||||
*/
|
||||
public aspect CacheAspect {
|
||||
|
||||
public pointcut cache(Cachable cachable): execution(@Cachable * * (..)) && @annotation(cachable);
|
||||
|
||||
Object around(Cachable cachable): cache(cachable){
|
||||
|
||||
String evaluatedKey = this.evaluateKey(cachable.scriptKey(), thisJoinPoint);
|
||||
|
||||
if(cache.containsKey(evaluatedKey)){
|
||||
System.out.println("Cache hit for key " + evaluatedKey);
|
||||
return this.cache.get(evaluatedKey);
|
||||
}
|
||||
|
||||
System.out.println("Cache miss for key " + evaluatedKey);
|
||||
Object value = proceed(cachable);
|
||||
cache.put(evaluatedKey, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
protected String evaluateKey(String key, JoinPoint joinPoint) {
|
||||
// TODO add some smart staff to allow simple scripting in @Cachable annotation
|
||||
return key;
|
||||
}
|
||||
|
||||
protected Map<String, Object> cache = new WeakHashMap<String, Object>();
|
||||
}
|
||||
50
samples/AspectJ/OptimizeRecursionCache.aj
Normal file
50
samples/AspectJ/OptimizeRecursionCache.aj
Normal file
@@ -0,0 +1,50 @@
|
||||
package aspects.caching;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Cache aspect for optimize recursive functions.
|
||||
*
|
||||
* @author Migueli
|
||||
* @date 05/11/2013
|
||||
* @version 1.0
|
||||
*
|
||||
*/
|
||||
public abstract aspect OptimizeRecursionCache {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private Map _cache;
|
||||
|
||||
public OptimizeRecursionCache() {
|
||||
_cache = getCache();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
abstract public Map getCache();
|
||||
|
||||
abstract public pointcut operation(Object o);
|
||||
|
||||
pointcut topLevelOperation(Object o): operation(o) && !cflowbelow(operation(Object));
|
||||
|
||||
before(Object o) : topLevelOperation(o) {
|
||||
System.out.println("Seeking value for " + o);
|
||||
}
|
||||
|
||||
Object around(Object o) : operation(o) {
|
||||
Object cachedValue = _cache.get(o);
|
||||
if (cachedValue != null) {
|
||||
System.out.println("Found cached value for " + o + ": " + cachedValue);
|
||||
return cachedValue;
|
||||
}
|
||||
return proceed(o);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
after(Object o) returning(Object result) : topLevelOperation(o) {
|
||||
_cache.put(o, result);
|
||||
}
|
||||
|
||||
after(Object o) returning(Object result) : topLevelOperation(o) {
|
||||
System.out.println("cache size: " + _cache.size());
|
||||
}
|
||||
}
|
||||
102
samples/C/bootstrap.h
Normal file
102
samples/C/bootstrap.h
Normal file
@@ -0,0 +1,102 @@
|
||||
#ifndef BOOTSTRAP_H
|
||||
#define BOOTSTRAP_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include "cxrs.h"
|
||||
|
||||
/* If we're not using GNU C, elide __attribute__ */
|
||||
#ifndef __GNUC__
|
||||
# define __attribute__(x) /*NOTHING*/
|
||||
#endif
|
||||
|
||||
typedef struct object object;
|
||||
|
||||
object *true;
|
||||
object *false;
|
||||
object *eof;
|
||||
object *empty_list;
|
||||
object *global_enviroment;
|
||||
|
||||
enum obj_type {
|
||||
scm_bool,
|
||||
scm_empty_list,
|
||||
scm_eof,
|
||||
scm_char,
|
||||
scm_int,
|
||||
scm_pair,
|
||||
scm_symbol,
|
||||
scm_prim_fun,
|
||||
scm_lambda,
|
||||
scm_str,
|
||||
scm_file
|
||||
};
|
||||
|
||||
typedef object *(*prim_proc)(object *args);
|
||||
|
||||
object *read(FILE *in);
|
||||
object *eval(object *code, object *env);
|
||||
void print(FILE *out, object *obj, int display);
|
||||
|
||||
int check_type(enum obj_type type, object *obj, int err_on_false);
|
||||
|
||||
static inline int is_true(object *obj)
|
||||
{
|
||||
return obj != false;
|
||||
}
|
||||
|
||||
object *make_int(int value);
|
||||
int obj2int(object *i);
|
||||
|
||||
object *make_bool(int value);
|
||||
int obj2bool(object *b);
|
||||
|
||||
object *make_char(char c);
|
||||
char obj2char(object *ch);
|
||||
|
||||
object *make_str(char *str);
|
||||
char *obj2str(object *str);
|
||||
|
||||
object *cons(object *car, object *cdr);
|
||||
object *car(object *pair);
|
||||
object *cdr(object *pair);
|
||||
void set_car(object *pair, object *new);
|
||||
void set_cdr(object *pair, object *new);
|
||||
|
||||
object *make_symbol(char *name);
|
||||
char *sym2str(object *sym);
|
||||
object *get_symbol(char *name) __attribute__((pure));
|
||||
|
||||
object *make_prim_fun(prim_proc fun);
|
||||
prim_proc obj2prim_proc(object *proc);
|
||||
|
||||
object *make_lambda(object *args, object *code, object *env);
|
||||
object *lambda_code(object *lambda);
|
||||
object *lambda_args(object *lambda);
|
||||
|
||||
object *make_port(FILE *handle, int direction);
|
||||
int port_direction(object *port);
|
||||
FILE *port_handle(object *port);
|
||||
void set_port_handle_to_null(object *port);
|
||||
|
||||
/*both of these should never be called*/
|
||||
object *apply_proc(object *);
|
||||
object *eval_proc(object *);
|
||||
|
||||
|
||||
object *maybe_add_begin(object *code);
|
||||
|
||||
void init_enviroment(object *env);
|
||||
|
||||
|
||||
void eval_err(char *msg, object *code) __attribute__((noreturn));
|
||||
|
||||
void define_var(object *var, object *val, object *env);
|
||||
void set_var(object *var, object *val, object *env);
|
||||
object *get_var(object *var, object *env);
|
||||
|
||||
object *cond2nested_if(object *cond);
|
||||
object *let2lambda(object *let);
|
||||
object *and2nested_if(object *and);
|
||||
object *or2nested_if(object *or);
|
||||
|
||||
#endif /*include guard*/
|
||||
56
samples/C/dynarray.cats
Normal file
56
samples/C/dynarray.cats
Normal file
@@ -0,0 +1,56 @@
|
||||
/* ******************************************************************* */
|
||||
/* */
|
||||
/* Applied Type System */
|
||||
/* */
|
||||
/* ******************************************************************* */
|
||||
|
||||
/*
|
||||
** ATS/Postiats - Unleashing the Potential of Types!
|
||||
** Copyright (C) 2011-20?? Hongwei Xi, ATS Trustful Software, Inc.
|
||||
** All rights reserved
|
||||
**
|
||||
** ATS is free software; you can redistribute it and/or modify it under
|
||||
** the terms of the GNU GENERAL PUBLIC LICENSE (GPL) as published by the
|
||||
** Free Software Foundation; either version 3, or (at your option) any
|
||||
** later version.
|
||||
**
|
||||
** ATS is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||
** WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
** FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
** for more details.
|
||||
**
|
||||
** You should have received a copy of the GNU General Public License
|
||||
** along with ATS; see the file COPYING. If not, please write to the
|
||||
** Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
|
||||
** 02110-1301, USA.
|
||||
*/
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
/*
|
||||
(* Author: Hongwei Xi *)
|
||||
(* Authoremail: hwxi AT cs DOT bu DOT edu *)
|
||||
(* Start time: March, 2013 *)
|
||||
*/
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
#ifndef ATSHOME_LIBATS_DYNARRAY_CATS
|
||||
#define ATSHOME_LIBATS_DYNARRAY_CATS
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
#include <string.h>
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
#define atslib_dynarray_memcpy memcpy
|
||||
#define atslib_dynarray_memmove memmove
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
#endif // ifndef ATSHOME_LIBATS_DYNARRAY_CATS
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
/* end of [dynarray.cats] */
|
||||
47
samples/C/readline.cats
Normal file
47
samples/C/readline.cats
Normal file
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
** API in ATS for GNU-readline
|
||||
*/
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
/*
|
||||
** Permission to use, copy, modify, and distribute this software for any
|
||||
** purpose with or without fee is hereby granted, provided that the above
|
||||
** copyright notice and this permission notice appear in all copies.
|
||||
**
|
||||
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
** WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
** MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
** ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
** WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
** ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
** OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
#ifndef READLINE_READLINE_CATS
|
||||
#define READLINE_READLINE_CATS
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
#include <readline/readline.h>
|
||||
|
||||
/* ****** ****** */
|
||||
//
|
||||
#define \
|
||||
atscntrb_readline_rl_library_version() ((char*)rl_library_version)
|
||||
//
|
||||
#define atscntrb_readline_rl_readline_version() (rl_readline_version)
|
||||
//
|
||||
/* ****** ****** */
|
||||
|
||||
#define atscntrb_readline_readline readline
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
#endif // ifndef READLINE_READLINE_CATS
|
||||
|
||||
/* ****** ****** */
|
||||
|
||||
/* end of [readline.cats] */
|
||||
12
samples/Cirru/array.cirru
Normal file
12
samples/Cirru/array.cirru
Normal file
@@ -0,0 +1,12 @@
|
||||
|
||||
print $ array
|
||||
int 1
|
||||
string 2
|
||||
|
||||
print $ array
|
||||
int 1
|
||||
array
|
||||
int 2
|
||||
string 3
|
||||
array
|
||||
string 4
|
||||
7
samples/Cirru/block.cirru
Normal file
7
samples/Cirru/block.cirru
Normal file
@@ -0,0 +1,7 @@
|
||||
|
||||
set f $ block (a b c)
|
||||
print a b c
|
||||
|
||||
call f (int 1) (int 2) (int 3)
|
||||
|
||||
f (int 1) (int 2) (int 3)
|
||||
7
samples/Cirru/bool.cirru
Normal file
7
samples/Cirru/bool.cirru
Normal file
@@ -0,0 +1,7 @@
|
||||
|
||||
print $ bool true
|
||||
print $ bool false
|
||||
print $ bool yes
|
||||
print $ bool no
|
||||
print $ bool 1
|
||||
print $ bool 0
|
||||
14
samples/Cirru/map.cirru
Normal file
14
samples/Cirru/map.cirru
Normal file
@@ -0,0 +1,14 @@
|
||||
|
||||
print $ map
|
||||
a $ int 5
|
||||
b $ array (int 1) (int 2)
|
||||
c $ map
|
||||
int 1
|
||||
array (int 4)
|
||||
|
||||
set m $ map
|
||||
a $ int 1
|
||||
|
||||
set m b $ int 2
|
||||
|
||||
print m
|
||||
3
samples/Cirru/number.cirru
Normal file
3
samples/Cirru/number.cirru
Normal file
@@ -0,0 +1,3 @@
|
||||
|
||||
print $ int 1
|
||||
print $ float 1.2
|
||||
2
samples/Cirru/require.cirru
Normal file
2
samples/Cirru/require.cirru
Normal file
@@ -0,0 +1,2 @@
|
||||
|
||||
require ./stdio.cr
|
||||
23
samples/Cirru/scope.cirru
Normal file
23
samples/Cirru/scope.cirru
Normal file
@@ -0,0 +1,23 @@
|
||||
|
||||
set a (int 2)
|
||||
|
||||
print (self)
|
||||
|
||||
set c (child)
|
||||
|
||||
under c
|
||||
under parent
|
||||
print a
|
||||
|
||||
print $ get c a
|
||||
|
||||
set c x (int 3)
|
||||
print $ get c x
|
||||
|
||||
set just-print $ code
|
||||
print a
|
||||
|
||||
print just-print
|
||||
|
||||
eval (self) just-print
|
||||
eval just-print
|
||||
55
samples/Cirru/stdio.cirru
Normal file
55
samples/Cirru/stdio.cirru
Normal file
@@ -0,0 +1,55 @@
|
||||
|
||||
set a $ string 1
|
||||
print a
|
||||
|
||||
print (string 1)
|
||||
|
||||
print nothing
|
||||
|
||||
print
|
||||
map
|
||||
a (int 4)
|
||||
b $ map
|
||||
a $ int 5
|
||||
b $ int 6
|
||||
c $ map
|
||||
int 7
|
||||
|
||||
print
|
||||
array
|
||||
int 1
|
||||
int 2
|
||||
array
|
||||
int 3
|
||||
int 4
|
||||
|
||||
print
|
||||
array
|
||||
int 1
|
||||
map
|
||||
a $ int 2
|
||||
b $ array
|
||||
int 3
|
||||
|
||||
print
|
||||
int 1
|
||||
int 2
|
||||
|
||||
print $ code
|
||||
set a 1
|
||||
print (get a)
|
||||
print $ array
|
||||
int a
|
||||
array
|
||||
int a
|
||||
|
||||
set container (map)
|
||||
set container code $ code
|
||||
set a 1
|
||||
print (get a)
|
||||
print $ array
|
||||
int a
|
||||
array
|
||||
int a
|
||||
|
||||
print container
|
||||
3
samples/Cirru/string.cirru
Normal file
3
samples/Cirru/string.cirru
Normal file
@@ -0,0 +1,3 @@
|
||||
|
||||
print $ string a
|
||||
print $ string "a b"
|
||||
16
samples/Dogescript/example.djs
Normal file
16
samples/Dogescript/example.djs
Normal file
@@ -0,0 +1,16 @@
|
||||
quiet
|
||||
wow
|
||||
such language
|
||||
very syntax
|
||||
github recognized wow
|
||||
loud
|
||||
|
||||
such language much friendly
|
||||
rly friendly is true
|
||||
plz console.loge with 'such friend, very inclusive'
|
||||
but
|
||||
plz console.loge with 'no love for doge'
|
||||
wow
|
||||
wow
|
||||
|
||||
module.exports is language
|
||||
1396
samples/Eagle/Eagle.brd
Normal file
1396
samples/Eagle/Eagle.brd
Normal file
File diff suppressed because it is too large
Load Diff
3612
samples/Eagle/Eagle.sch
Normal file
3612
samples/Eagle/Eagle.sch
Normal file
File diff suppressed because it is too large
Load Diff
44
samples/Frege/CommandLineClock.fr
Normal file
44
samples/Frege/CommandLineClock.fr
Normal file
@@ -0,0 +1,44 @@
|
||||
{--
|
||||
This program displays the
|
||||
current time on stdandard output
|
||||
every other second.
|
||||
-}
|
||||
|
||||
module examples.CommandLineClock where
|
||||
|
||||
data Date = native java.util.Date where
|
||||
native new :: () -> IO (MutableIO Date) -- new Date()
|
||||
native toString :: Mutable s Date -> ST s String -- d.toString()
|
||||
|
||||
--- 'IO' action to give us the current time as 'String'
|
||||
current :: IO String
|
||||
current = do
|
||||
d <- Date.new ()
|
||||
d.toString
|
||||
|
||||
{-
|
||||
"java.lang.Thread.sleep" takes a "long" and
|
||||
returns nothing, but may throw an InterruptedException.
|
||||
This is without doubt an IO action.
|
||||
|
||||
public static void sleep(long millis)
|
||||
throws InterruptedException
|
||||
|
||||
Encoded in Frege:
|
||||
- argument type long Long
|
||||
- result void ()
|
||||
- does IO IO ()
|
||||
- throws ... throws ....
|
||||
|
||||
-}
|
||||
-- .... defined in frege.java.Lang
|
||||
-- native sleep java.lang.Thread.sleep :: Long -> IO () throws InterruptedException
|
||||
|
||||
|
||||
main args =
|
||||
forever do
|
||||
current >>= print
|
||||
print "\r"
|
||||
stdout.flush
|
||||
Thread.sleep 999
|
||||
|
||||
147
samples/Frege/Concurrent.fr
Normal file
147
samples/Frege/Concurrent.fr
Normal file
@@ -0,0 +1,147 @@
|
||||
module examples.Concurrent where
|
||||
|
||||
import System.Random
|
||||
import Java.Net (URL)
|
||||
import Control.Concurrent as C
|
||||
|
||||
main2 args = do
|
||||
m <- newEmptyMVar
|
||||
forkIO do
|
||||
m.put 'x'
|
||||
m.put 'y'
|
||||
m.put 'z'
|
||||
replicateM_ 3 do
|
||||
c <- m.take
|
||||
print "got: "
|
||||
println c
|
||||
|
||||
|
||||
example1 = do
|
||||
forkIO (replicateM_ 100000 (putChar 'a'))
|
||||
replicateM_ 100000 (putChar 'b')
|
||||
|
||||
example2 = do
|
||||
s <- getLine
|
||||
case s.long of
|
||||
Right n -> forkIO (setReminder n) >> example2
|
||||
Left _ -> println ("exiting ...")
|
||||
|
||||
setReminder :: Long -> IO ()
|
||||
setReminder n = do
|
||||
println ("Ok, I remind you in " ++ show n ++ " seconds")
|
||||
Thread.sleep (1000L*n)
|
||||
println (show n ++ " seconds is up!")
|
||||
|
||||
table = "table"
|
||||
|
||||
mainPhil _ = do
|
||||
[fork1,fork2,fork3,fork4,fork5] <- mapM MVar.new [1..5]
|
||||
forkIO (philosopher "Kant" fork5 fork1)
|
||||
forkIO (philosopher "Locke" fork1 fork2)
|
||||
forkIO (philosopher "Wittgenstein" fork2 fork3)
|
||||
forkIO (philosopher "Nozick" fork3 fork4)
|
||||
forkIO (philosopher "Mises" fork4 fork5)
|
||||
return ()
|
||||
|
||||
philosopher :: String -> MVar Int -> MVar Int -> IO ()
|
||||
philosopher me left right = do
|
||||
g <- Random.newStdGen
|
||||
let phil g = do
|
||||
let (tT,g1) = Random.randomR (60L, 120L) g
|
||||
(eT, g2) = Random.randomR (80L, 160L) g1
|
||||
thinkTime = 300L * tT
|
||||
eatTime = 300L * eT
|
||||
|
||||
println(me ++ " is going to the dining room and takes his seat.")
|
||||
fl <- left.take
|
||||
println (me ++ " takes up left fork (" ++ show fl ++ ")")
|
||||
rFork <- right.poll
|
||||
case rFork of
|
||||
Just fr -> do
|
||||
println (me ++ " takes up right fork. (" ++ show fr ++ ")")
|
||||
println (me ++ " is going to eat for " ++ show eatTime ++ "ms")
|
||||
Thread.sleep eatTime
|
||||
println (me ++ " finished eating.")
|
||||
right.put fr
|
||||
println (me ++ " took down right fork.")
|
||||
left.put fl
|
||||
println (me ++ " took down left fork.")
|
||||
table.notifyAll
|
||||
println(me ++ " is going to think for " ++ show thinkTime ++ "ms.")
|
||||
Thread.sleep thinkTime
|
||||
phil g2
|
||||
Nothing -> do
|
||||
println (me ++ " finds right fork is already in use.")
|
||||
left.put fl
|
||||
println (me ++ " took down left fork.")
|
||||
table.notifyAll
|
||||
println (me ++ " is going to the bar to await notifications from table.")
|
||||
table.wait
|
||||
println (me ++ " got notice that something changed at the table.")
|
||||
phil g2
|
||||
|
||||
inter :: InterruptedException -> IO ()
|
||||
inter _ = return ()
|
||||
|
||||
phil g `catch` inter
|
||||
|
||||
|
||||
getURL xx = do
|
||||
url <- URL.new xx
|
||||
con <- url.openConnection
|
||||
con.connect
|
||||
is <- con.getInputStream
|
||||
typ <- con.getContentType
|
||||
-- stderr.println ("content-type is " ++ show typ)
|
||||
ir <- InputStreamReader.new is (fromMaybe "UTF-8" (charset typ))
|
||||
`catch` unsupportedEncoding is
|
||||
br <- BufferedReader.new ir
|
||||
br.getLines
|
||||
where
|
||||
unsupportedEncoding :: InputStream -> UnsupportedEncodingException -> IO InputStreamReader
|
||||
unsupportedEncoding is x = do
|
||||
stderr.println x.catched
|
||||
InputStreamReader.new is "UTF-8"
|
||||
|
||||
charset ctyp = do
|
||||
typ <- ctyp
|
||||
case typ of
|
||||
m~´charset=(\S+)´ -> m.group 1
|
||||
_ -> Nothing
|
||||
|
||||
|
||||
type SomeException = Throwable
|
||||
|
||||
main ["dining"] = mainPhil []
|
||||
|
||||
main _ = do
|
||||
m1 <- MVar.newEmpty
|
||||
m2 <- MVar.newEmpty
|
||||
m3 <- MVar.newEmpty
|
||||
|
||||
forkIO do
|
||||
r <- (catchAll . getURL) "http://www.wikipedia.org/wiki/Haskell"
|
||||
m1.put r
|
||||
|
||||
forkIO do
|
||||
r <- (catchAll . getURL) "htto://www.wikipedia.org/wiki/Java"
|
||||
m2.put r
|
||||
|
||||
forkIO do
|
||||
r <- (catchAll . getURL) "http://www.wikipedia.org/wiki/Frege"
|
||||
m3.put r
|
||||
|
||||
r1 <- m1.take
|
||||
r2 <- m2.take
|
||||
r3 <- m3.take
|
||||
println (result r1, result r2, result r3)
|
||||
-- case r3 of
|
||||
-- Right ss -> mapM_ putStrLn ss
|
||||
-- Left _ -> return ()
|
||||
where
|
||||
result :: (SomeException|[String]) -> (String|Int)
|
||||
result (Left x) = Left x.getClass.getName
|
||||
result (Right y) = (Right . sum . map length) y
|
||||
-- mapM_ putStrLn r2
|
||||
|
||||
|
||||
561
samples/Frege/Sudoku.fr
Normal file
561
samples/Frege/Sudoku.fr
Normal file
@@ -0,0 +1,561 @@
|
||||
package examples.Sudoku where
|
||||
|
||||
import Data.TreeMap (Tree, keys)
|
||||
import Data.List as DL hiding (find, union)
|
||||
|
||||
|
||||
type Element = Int -- 1,2,3,4,5,6,7,8,9
|
||||
type Zelle = [Element] -- set of candidates
|
||||
type Position = Int -- 0..80
|
||||
type Feld = (Position, Zelle)
|
||||
type Brett = [Feld]
|
||||
|
||||
--- data type for assumptions and conclusions
|
||||
data Assumption =
|
||||
!ISNOT Position Element
|
||||
| !IS Position Element
|
||||
|
||||
|
||||
derive Eq Assumption
|
||||
derive Ord Assumption
|
||||
instance Show Assumption where
|
||||
show (IS p e) = pname p ++ "=" ++ e.show
|
||||
show (ISNOT p e) = pname p ++ "/" ++ e.show
|
||||
|
||||
showcs cs = joined " " (map Assumption.show cs)
|
||||
|
||||
elements :: [Element] -- all possible elements
|
||||
elements = [1 .. 9]
|
||||
|
||||
{-
|
||||
a b c d e f g h i
|
||||
0 1 2 | 3 4 5 | 6 7 8 1
|
||||
9 10 11 |12 13 14 |15 16 17 2
|
||||
18 19 20 |21 22 23 |24 25 26 3
|
||||
---------|---------|--------
|
||||
27 28 29 |30 31 32 |33 34 35 4
|
||||
36 37 38 |39 40 41 |42 43 44 5
|
||||
45 46 47 |48 49 50 |51 52 53 6
|
||||
---------|---------|--------
|
||||
54 55 56 |57 58 59 |60 61 62 7
|
||||
63 64 65 |66 67 68 |69 70 71 8
|
||||
72 73 74 |75 76 77 |78 79 80 9
|
||||
-}
|
||||
|
||||
positions :: [Position] -- all possible positions
|
||||
positions = [0..80]
|
||||
rowstarts :: [Position] -- all positions where a row is starting
|
||||
rowstarts = [0,9,18,27,36,45,54,63,72]
|
||||
colstarts :: [Position] -- all positions where a column is starting
|
||||
colstarts = [0,1,2,3,4,5,6,7,8]
|
||||
boxstarts :: [Position] -- all positions where a box is starting
|
||||
boxstarts = [0,3,6,27,30,33,54,57,60]
|
||||
boxmuster :: [Position] -- pattern for a box, by adding upper left position results in real box
|
||||
boxmuster = [0,1,2,9,10,11,18,19,20]
|
||||
|
||||
|
||||
--- extract field for position
|
||||
getf :: Brett -> Position -> Feld
|
||||
getf (f:fs) p
|
||||
| fst f == p = f
|
||||
| otherwise = getf fs p
|
||||
getf [] p = (p,[])
|
||||
|
||||
|
||||
--- extract cell for position
|
||||
getc :: Brett -> Position -> Zelle
|
||||
getc b p = snd (getf b p)
|
||||
|
||||
--- compute the list of all positions that belong to the same row as a given position
|
||||
row :: Position -> [Position]
|
||||
row p = [z..(z+8)] where z = (p `quot` 9) * 9
|
||||
|
||||
--- compute the list of all positions that belong to the same col as a given position
|
||||
col :: Position -> [Position]
|
||||
col p = map (c+) rowstarts where c = p `mod` 9
|
||||
|
||||
--- compute the list of all positions that belong to the same box as a given position
|
||||
box :: Position -> [Position]
|
||||
box p = map (z+) boxmuster where
|
||||
ri = p `div` 27 * 27 -- 0, 27 or 54, depending on row
|
||||
ci = p `mod` 9 -- column index 0..8, 0,1,2 is left, 3,4,5 is middle, 6,7,8 is right
|
||||
cs = ci `div` 3 * 3 -- 0, 3 or 6
|
||||
z = ri + cs
|
||||
|
||||
--- check if candidate set has exactly one member, i.e. field has been solved
|
||||
single :: Zelle -> Bool
|
||||
single [_] = true
|
||||
single _ = false
|
||||
|
||||
unsolved :: Zelle -> Bool
|
||||
unsolved [_] = false
|
||||
unsolved _ = true
|
||||
|
||||
-- list of rows, cols, boxes
|
||||
allrows = map row rowstarts
|
||||
allcols = map col colstarts
|
||||
allboxs = map box boxstarts
|
||||
allrcb = zip (repeat "row") allrows
|
||||
++ zip (repeat "col") allcols
|
||||
++ zip (repeat "box") allboxs
|
||||
|
||||
|
||||
containers :: [(Position -> [Position], String)]
|
||||
containers = [(row, "row"), (col, "col"), (box, "box")]
|
||||
|
||||
-- ----------------- PRINTING ------------------------------------
|
||||
-- printable coordinate of field, upper left is a1, lower right is i9
|
||||
pname p = packed [chr (ord 'a' + p `mod` 9), chr (ord '1' + p `div` 9)]
|
||||
|
||||
-- print board
|
||||
printb b = mapM_ p1line allrows >> println ""
|
||||
where
|
||||
p1line row = do
|
||||
print (joined "" (map pfld line))
|
||||
where line = map (getc b) row
|
||||
|
||||
-- print field (brief)
|
||||
-- ? = no candidate
|
||||
-- 5 = field is 5
|
||||
-- . = some candidates
|
||||
pfld [] = "?"
|
||||
pfld [x] = show x
|
||||
pfld zs = "0"
|
||||
|
||||
-- print initial/final board
|
||||
result msg b = do
|
||||
println ("Result: " ++ msg)
|
||||
print ("Board: ")
|
||||
printb b
|
||||
return b
|
||||
|
||||
res012 b = case concatMap (getc b) [0,1,2] of
|
||||
[a,b,c] -> a*100+b*10+c
|
||||
_ -> 9999999
|
||||
|
||||
-- -------------------------- BOARD ALTERATION ACTIONS ---------------------------------
|
||||
-- print a message about what is done to the board and return the new board
|
||||
turnoff1 :: Position -> Zelle -> Brett -> IO Brett
|
||||
turnoff1 i off b
|
||||
| single nc = do
|
||||
-- print (pname i)
|
||||
-- print ": set to "
|
||||
-- print (head nc)
|
||||
-- println " (naked single)"
|
||||
return newb
|
||||
| otherwise = return newb
|
||||
where
|
||||
cell = getc b i
|
||||
nc = filter (`notElem` off) cell
|
||||
newb = (i, nc) : [ f | f <- b, fst f != i ]
|
||||
|
||||
turnoff :: Int -> Zelle -> String -> Brett -> IO Brett
|
||||
turnoff i off msg b = do
|
||||
-- print (pname i)
|
||||
-- print ": set to "
|
||||
-- print nc
|
||||
-- print " by clearing "
|
||||
-- print off
|
||||
-- print " "
|
||||
-- println msg
|
||||
return newb
|
||||
where
|
||||
cell = getc b i
|
||||
nc = filter (`notElem` off) cell
|
||||
newb = (i, nc) : [ f | f <- b, fst f != i ]
|
||||
|
||||
turnoffh ps off msg b = foldM toh b ps
|
||||
where
|
||||
toh b p = turnoff p off msg b
|
||||
|
||||
setto :: Position -> Element -> String -> Brett -> IO Brett
|
||||
setto i n cname b = do
|
||||
-- print (pname i)
|
||||
-- print ": set to "
|
||||
-- print n
|
||||
-- print " (hidden single in "
|
||||
-- print cname
|
||||
-- println ")"
|
||||
return newb
|
||||
where
|
||||
nf = [n]
|
||||
newb = (i, nf) : [ f | f <- b, fst f != i ]
|
||||
|
||||
|
||||
-- ----------------------------- SOLVING STRATEGIES ---------------------------------------------
|
||||
-- reduce candidate sets that contains numbers already in same row, col or box
|
||||
-- This finds (and logs) NAKED SINGLEs in passing.
|
||||
reduce b = [ turnoff1 p sss | (p,cell) <- b, -- for each field
|
||||
unsolved cell, -- with more than 1 candidate
|
||||
-- single fields in containers that are candidates of that field
|
||||
sss = [ s | (rcb, _) <- containers, [s] <- map (getc b) (rcb p), s `elem` cell],
|
||||
sss != [] ] -- collect field index, elements to remove from candidate set
|
||||
|
||||
-- look for a number that appears in exactly 1 candidate set of a container
|
||||
-- this number can go in no other place (HIDDEN SINGLE)
|
||||
hiddenSingle b = [ setto i n cname | -- select index, number, containername
|
||||
(cname, rcb) <- allrcb, -- FOR rcb IN allrcb
|
||||
n <- elements, -- FOR n IN elements
|
||||
fs = filter (unsolved • snd) (map (getf b) rcb),
|
||||
occurs = filter ((n `elem`) • snd) fs,
|
||||
length occurs == 1,
|
||||
(i, _) <- occurs ]
|
||||
|
||||
-- look for NAKED PAIRS, TRIPLES, QUADS
|
||||
nakedPair n b = [ turnoff p t ("(naked tuple in " ++ nm ++ ")") | -- SELECT pos, tuple, name
|
||||
-- n <- [2,3,4], // FOR n IN [2,3,4]
|
||||
(nm, rcb) <- allrcb, -- FOR rcb IN containers
|
||||
fs = map (getf b) rcb, -- let fs = fields for rcb positions
|
||||
u = (fold union [] . filter unsolved . map snd) fs, -- let u = union of non single candidates
|
||||
t <- n `outof` u, -- FOR t IN n-tuples
|
||||
hit = (filter ((`subset` t) . snd) . filter (unsolved . snd)) fs,
|
||||
length hit == n,
|
||||
(p, cell) <- fs,
|
||||
p `notElem` map fst hit,
|
||||
any (`elem` cell) t
|
||||
]
|
||||
|
||||
-- look for HIDDEN PAIRS, TRIPLES or QUADS
|
||||
hiddenPair n b = [ turnoff p off ("(hidden " ++ show t ++ " in " ++ nm ++ ")") | -- SELECT pos, tuple, name
|
||||
-- n <- [2,3,4], // FOR n IN [2,3,4]
|
||||
(nm, rcb) <- allrcb, -- FOR rcb IN containers
|
||||
fs = map (getf b) rcb, -- let fs = fields for rcb positions
|
||||
u = (fold union [] . filter ((>1) . length) . map snd) fs, -- let u = union of non single candidates
|
||||
t <- n `outof` u, -- FOR t IN n-tuples
|
||||
hit = (filter (any ( `elem` t) . snd) . filter (unsolved . snd)) fs,
|
||||
length hit == n,
|
||||
off = (fold union [] . map snd) hit `minus` t,
|
||||
off != [],
|
||||
(p, cell) <- hit,
|
||||
! (cell `subset` t)
|
||||
]
|
||||
|
||||
a `subset` b = all (`elem` b) a
|
||||
a `union` b = uniq (sort (a ++ b))
|
||||
a `minus` b = filter (`notElem` b) a
|
||||
a `common` b = filter (`elem` b) a
|
||||
n `outof` as
|
||||
| length as < n = []
|
||||
| [] <- as = []
|
||||
| 1 >= n = map (:[]) as
|
||||
| (a:bs) <- as = map (a:) ((n-1) `outof` bs) ++ (n `outof` bs)
|
||||
| otherwise = undefined -- cannot happen because either as is empty or not
|
||||
|
||||
same f a b = b `elem` f a
|
||||
|
||||
intersectionlist = [(allboxs, row, "box/row intersection"), (allboxs, col, "box/col intersection"),
|
||||
(allrows ++ allcols, box, "line/box intersection")]
|
||||
intersections b = [
|
||||
turnoff pos [c] reason | -- SELECT position, candidate, reson
|
||||
(from, container, reason) <- intersectionlist,
|
||||
rcb <- from,
|
||||
fs = (filter (unsolved . snd) . map (getf b)) rcb, -- fs = fields in from with more than 1 candidate
|
||||
c <- (fold union [] • map snd) fs, -- FOR c IN union of candidates
|
||||
cpos = (map fst • filter ((c `elem`) • snd)) fs, -- cpos = positions where c occurs
|
||||
cpos != [], -- WHERE cpos is not empty
|
||||
all (same container (head cpos)) (tail cpos), -- WHERE all positions are in the intersection
|
||||
-- we can remove all occurences of c that are in container, but not in from
|
||||
(pos, cell) <- map (getf b) (container (head cpos)),
|
||||
c `elem` cell,
|
||||
pos `notElem` rcb ]
|
||||
|
||||
|
||||
-- look for an XY Wing
|
||||
-- - there exists a cell A with candidates X and Y
|
||||
-- - there exists a cell B with candidates X and Z that shares a container with A
|
||||
-- - there exists a cell C with candidates Y and Z that shares a container with A
|
||||
-- reasoning
|
||||
-- - if A is X, B will be Z
|
||||
-- - if A is Y, C will be Z
|
||||
-- - since A will indeed be X or Y -> B or C will be Z
|
||||
-- - thus, no cell that can see B and C can be Z
|
||||
xyWing board = [ turnoff p [z] ("xy wing " ++ pname b ++ " " ++ pname c ++ " because of " ++ pname a) |
|
||||
(a, [x,y]) <- board, -- there exists a cell a with candidates x and y
|
||||
rcba = map (getf board) (row a ++ col a ++ box a), -- rcba = all fields that share a container with a
|
||||
(b, [b1, b2]) <- rcba,
|
||||
b != a,
|
||||
b1 == x && b2 != y || b2 == x && b1 != y, -- there exists a cell B with candidates x and z
|
||||
z = if b1 == x then b2 else b1,
|
||||
(c, [c1, c2]) <- rcba,
|
||||
c != a, c!= b,
|
||||
c1 == y && c2 == z || c1 == z && c2 == y, -- there exists a cell C with candidates y and z
|
||||
ps = (uniq . sort) ((row b ++ col b ++ box b) `common` (row c ++ col c ++ box c)),
|
||||
-- remove z in ps
|
||||
(p, cs) <- map (getf board) ps,
|
||||
p != b, p != c,
|
||||
z `elem` cs ]
|
||||
|
||||
-- look for a N-Fish (2: X-Wing, 3: Swordfish, 4: Jellyfish)
|
||||
-- When all candidates for a particular digit in N rows are located
|
||||
-- in only N columns, we can eliminate all candidates from those N columns
|
||||
-- which are not located on those N rows
|
||||
fish n board = fish "row" allrows row col ++ fish "col" allcols col row where
|
||||
fishname 2 = "X-Wing"
|
||||
fishname 3 = "Swordfish"
|
||||
fishname 4 = "Jellyfish"
|
||||
fishname _ = "unknown fish"
|
||||
fish nm allrows row col = [ turnoff p [x] (fishname n ++ " in " ++ nm ++ " " ++ show (map (pname . head) rset)) |
|
||||
rset <- n `outof` allrows, -- take n rows (or cols)
|
||||
x <- elements, -- look for certain number
|
||||
rflds = map (filter ((>1) . length . snd) . map (getf board)) rset, -- unsolved fields in the rowset
|
||||
colss = (map (map (head . col . fst) . filter ((x `elem`) . snd)) rflds), -- where x occurs in candidates
|
||||
all ((>1) . length) colss, -- x must appear in at least 2 cols
|
||||
cols = fold union [] colss,
|
||||
length cols == n,
|
||||
cstart <- cols,
|
||||
(p, cell) <- map (getf board) (col cstart),
|
||||
x `elem` cell,
|
||||
all (p `notElem`) rset]
|
||||
|
||||
|
||||
-- compute immediate consequences of an assumption of the form (p `IS` e) or (p `ISNOT` e)
|
||||
conseq board (IS p e) = uniq (sort ([ p `ISNOT` x | x <- getc board p, x != e ] ++
|
||||
[ a `ISNOT` e |
|
||||
(a,cs) <- map (getf board) (row p ++ col p ++ box p),
|
||||
a != p,
|
||||
e `elem` cs
|
||||
]))
|
||||
conseq board (ISNOT p e) = uniq (sort ([ p `IS` x | cs = getc board p, length cs == 2, x <- cs, x != e ] ++
|
||||
[ a `IS` e |
|
||||
cp <- [row p, box p, col p],
|
||||
as = (filter ((e `elem`) . getc board) . filter (p!=)) cp,
|
||||
length as == 1,
|
||||
a = head as
|
||||
]))
|
||||
|
||||
-- check if two assumptions contradict each other
|
||||
contradicts (IS a x) (IS b y) = a==b && x!=y
|
||||
contradicts (IS a x) (ISNOT b y) = a==b && x==y
|
||||
contradicts (ISNOT a x) (IS b y) = a==b && x==y
|
||||
contradicts (ISNOT _ _) (ISNOT _ _) = false
|
||||
|
||||
-- get the Position of an Assumption
|
||||
aPos (IS p _) = p
|
||||
aPos (ISNOT p _) = p
|
||||
|
||||
-- get List of elements that must be turned off when assumption is true/false
|
||||
toClear board true (IS p x) = filter (x!=) (getc board p)
|
||||
toClear board false (IS p x) = [x]
|
||||
toClear board true (ISNOT p x) = [x]
|
||||
toClear board false (ISNOT p x) = filter (x!=) (getc board p)
|
||||
|
||||
|
||||
-- look for assumptions whose implications contradict themself
|
||||
chain board paths = [ solution a (head cs) (reverse cs) |
|
||||
(a, css) <- paths,
|
||||
cs <- take 1 [ cs | cs <- css, contradicts a (head cs) ]
|
||||
]
|
||||
where
|
||||
solution a c cs = turnoff (aPos a) (toClear board false a) reason where
|
||||
reason = "Assumption " ++ show a ++ " implies " ++ show c ++ "\n\t"
|
||||
++ showcs cs ++ "\n\t"
|
||||
++ "Therefore, " ++ show a ++ " must be false."
|
||||
|
||||
-- look for an assumption that yields to contradictory implications
|
||||
-- this assumption must be false
|
||||
chainContra board paths = [ solution a (reverse pro) (reverse contra) |
|
||||
(a, css) <- paths, -- FOR ALL assumptions "a" with list of conlusions "css"
|
||||
(pro, contra) <- take 1 [ (pro, contra) |
|
||||
pro <- (uniqBy (using head) . sortBy (comparing head)) css, -- FOR ALL conslusion chains "pro"
|
||||
c = head pro, -- LET "c" BE the final conclusion
|
||||
contra <- take 1 (filter ((contradicts c) . head) css) -- THE FIRST conclusion that contradicts c
|
||||
]
|
||||
]
|
||||
where
|
||||
solution a pro con = turnoff (aPos a) (toClear board false a) reason where
|
||||
reason = ("assumption " ++ show a ++ " leads to contradictory conclusions\n\t"
|
||||
++ showcs pro ++ "\n\t" ++ showcs con)
|
||||
|
||||
|
||||
|
||||
-- look for a common implication c of some assumptions ai, where at least 1 ai is true
|
||||
-- so that (a0 OR a1 OR a2 OR ...) IMPLIES c
|
||||
-- For all cells pi in same container that have x as candidate, we can construct (p0==x OR p1==x OR ... OR pi==x)
|
||||
-- For a cell p with candidates ci, we can construct (p==c0 OR p==c1)
|
||||
cellRegionChain board paths = [ solution b as (map head os) |
|
||||
as <- cellas ++ regionas, -- one of as must be true
|
||||
iss = filter ((`elem` as) . fst) paths, -- the implications for as
|
||||
(a, ass) <- take 1 iss, -- implications for first assumption
|
||||
fs <- (uniqBy (using head) . sortBy (comparing head)) ass,
|
||||
b = head fs, -- final conclusions of first assumption
|
||||
os = [fs] : map (take 1 . filter ((b==) . head) . snd) (tail iss), -- look for implications with same conclusion
|
||||
all ([]!=) os]
|
||||
where
|
||||
cellas = [ map (p `IS`) candidates | (p, candidates@(_:_:_)) <- board ]
|
||||
regionas = [ map (`IS` e) ps |
|
||||
region <- map (map (getf board)) (allrows ++ allcols ++ allboxs),
|
||||
e <- elements,
|
||||
ps = map fst (filter ((e `elem`) . snd) region),
|
||||
length ps > 1 ]
|
||||
solution b as oss = turnoff (aPos b) (toClear board true b) reason where
|
||||
reason = "all of the assumptions " ++ joined ", " (map show as) ++ " imply " ++ show b ++ "\n\t"
|
||||
++ joined "\n\t" (map (showcs . reverse) oss) ++ "\n\t"
|
||||
++ "One of them must be true, so " ++ show b ++ " must be true."
|
||||
|
||||
|
||||
{-
|
||||
Wir brauchen für einige Funktionen eine Datenstruktur wie
|
||||
[ (Assumption, [[Assumption]]) ]
|
||||
d.i. eine Liste von möglichen Annahmen samt aller Schlußketten.
|
||||
Idealerweise sollte die Schlußkette in umgekehrter Reihenfolge vorliegen,
|
||||
dann kann man einfach finden:
|
||||
- Annahmen, die zum Selbstwiderspruch führen.
|
||||
- alles, was aus einer bestimmten Annahme folgt (map (map head) [[a]])
|
||||
-...
|
||||
-}
|
||||
--- Liste aller Annahmen für ein bestimmtes Brett
|
||||
assumptions :: Brett -> [Assumption]
|
||||
assumptions board = [ a |
|
||||
(p, cs) <- board,
|
||||
!(single cs),
|
||||
a <- map (ISNOT p) cs ++ map (IS p) cs ]
|
||||
|
||||
consequences :: Brett -> [Assumption] -> [[Assumption]]
|
||||
consequences board as = map (conseq board) as
|
||||
|
||||
acstree :: Brett -> Tree Assumption [Assumption]
|
||||
acstree board = Tree.fromList (zip as cs)
|
||||
where
|
||||
as = assumptions board
|
||||
cs = consequences board as
|
||||
|
||||
-- bypass maybe on tree lookup
|
||||
find :: Tree Assumption [Assumption] -> Assumption -> [Assumption]
|
||||
find t a
|
||||
| Just cs <- t.lookup a = cs
|
||||
| otherwise = error ("no consequences for " ++ show a)
|
||||
|
||||
-- for performance resons, we confine ourselves to implication chains of length 20 per assumption
|
||||
mkPaths :: Tree Assumption [Assumption] -> [ (Assumption, [[Assumption]]) ]
|
||||
mkPaths acst = map impl (keys acst) -- {[a1], [a2], [a3] ]
|
||||
where
|
||||
-- [Assumption] -> [(a, [chains, ordered by length]
|
||||
impl a = (a, impls [[a]])
|
||||
impls ns = (take 1000 • concat • takeUntil null • iterate expandchain) ns
|
||||
-- expandchain :: [[Assumption]] -> [[Assumption]]
|
||||
expandchain css = [ (n:a:as) |
|
||||
(a : as) <- css, -- list of assumptions
|
||||
n <- find acst a, -- consequences of a
|
||||
n `notElem` as -- avoid loops
|
||||
]
|
||||
-- uni (a:as) = a : uni (filter ((head a !=) • head) as)
|
||||
-- uni [] = empty
|
||||
-- empty = []
|
||||
|
||||
|
||||
-- ------------------ SOLVE A SUDOKU --------------------------
|
||||
-- Apply all available strategies until nothing changes anymore
|
||||
-- Strategy functions are supposed to return a list of
|
||||
-- functions, which, when applied to a board, give a changed board.
|
||||
-- When a strategy does not find anything to alter,
|
||||
-- it returns [], and the next strategy can be tried.
|
||||
solve b
|
||||
| all (single . snd) b = result "Solved" b
|
||||
| any (([]==) . snd) b = result "not solvable" b
|
||||
| res@(_:_) <- reduce b = apply b res >>=solve -- compute smallest candidate sets
|
||||
-- comment "candidate sets are up to date" = ()
|
||||
| res@(_:_) <- hiddenSingle b = apply b res >>= solve -- find HIDDEN SINGLES
|
||||
-- comment "no more hidden singles" = ()
|
||||
| res@(_:_) <- intersections b = apply b res >>= solve -- find locked candidates
|
||||
-- comment "no more intersections" = ()
|
||||
| res@(_:_) <- nakedPair 2 b = apply b res >>= solve -- find NAKED PAIRS, TRIPLES or QUADRUPELS
|
||||
-- comment "no more naked pairs" = ()
|
||||
| res@(_:_) <- hiddenPair 2 b = apply b res >>= solve -- find HIDDEN PAIRS, TRIPLES or QUADRUPELS
|
||||
-- comment "no more hidden pairs" = ()
|
||||
-- res@(_:_) <- nakedPair 3 b = apply b res >>= solve // find NAKED PAIRS, TRIPLES or QUADRUPELS
|
||||
-- | comment "no more naked triples" = ()
|
||||
-- res@(_:_) <- hiddenPair 3 b = apply b res >>= solve // find HIDDEN PAIRS, TRIPLES or QUADRUPELS
|
||||
-- | comment "no more hidden triples" = ()
|
||||
-- res@(_:_) <- nakedPair 4 b = apply b res >>=solve // find NAKED PAIRS, TRIPLES or QUADRUPELS
|
||||
-- | comment "no more naked quadruples" = ()
|
||||
-- res@(_:_) <- hiddenPair 4 b = apply b res >>=solve // find HIDDEN PAIRS, TRIPLES or QUADRUPELS
|
||||
-- | comment "no more hidden quadruples" = ()
|
||||
| res@(_:_) <- xyWing b = apply b res >>=solve -- find XY WINGS
|
||||
-- comment "no more xy wings" = ()
|
||||
| res@(_:_) <- fish 2 b = apply b res >>=solve -- find 2-FISH
|
||||
-- comment "no more x-wings" = ()
|
||||
-- res@(_:_) <- fish 3 b = apply b res >>=solve // find 3-FISH
|
||||
-- | comment "no more swordfish" = ()
|
||||
-- res@(_:_) <- fish 4 b = apply b res >>=solve // find 4-FISH
|
||||
-- | comment "no more jellyfish" = ()
|
||||
-- | comment pcomment = ()
|
||||
| res@(_:_) <- chain b paths = apply b (take 9 res) >>= solve -- find forcing chains
|
||||
| res@(_:_) <- cellRegionChain b paths = apply b (take 9 res) >>= solve -- find common conclusion for true assumption
|
||||
| res@(_:_) <- chainContra b paths = apply b (take 9 res) >>= solve -- find assumptions that allow to infer both a and !a
|
||||
-- comment "consistent conclusions only" = ()
|
||||
|
||||
| otherwise = result "ambiguous" b
|
||||
where
|
||||
apply brd fs = foldM (\b\f -> f b) brd fs
|
||||
paths = mkPaths (acstree b)
|
||||
-- pcomment = show (length paths) ++ " assumptions with " ++ show (fold (+) 0 (map (length <~ snd) paths))
|
||||
-- ++ " implication chains"
|
||||
|
||||
-- comment com = do stderr << com << "\n" for false
|
||||
-- log com = do stderr << com << "\n" for true
|
||||
|
||||
--- turn a string into a row
|
||||
mkrow :: String -> [Zelle]
|
||||
mkrow s = mkrow1 xs
|
||||
where
|
||||
xs = s ++ "---------" -- make sure at least 9 elements
|
||||
mkrow1 xs = (take 9 • filter ([]!=) • map f • unpacked) xs
|
||||
f x | x >= '1' && x <= '9' = [ord x - ord '0']
|
||||
| x == ' ' = [] -- ignored
|
||||
| otherwise = elements
|
||||
|
||||
main ["-h"] = main []
|
||||
main ["-help"] = main []
|
||||
main [] = do
|
||||
mapM_ stderr.println [
|
||||
"usage: java Sudoku file ...",
|
||||
" java Sudoku position",
|
||||
"where position is a 81 char string consisting of digits",
|
||||
"One can get such a string by going to",
|
||||
"http://www.sudokuoftheday.com/pages/s-o-t-d.php",
|
||||
"Right click on the puzzle and open it in new tab",
|
||||
"Copy the 81 digits from the URL in the address field of your browser.",
|
||||
"",
|
||||
"There is also a file with hard sudokus in examples/top95.txt\n"]
|
||||
return ()
|
||||
|
||||
|
||||
main [s@#^[0-9\W]{81}$#] = solve board >> return ()
|
||||
where
|
||||
board = zip positions felder
|
||||
felder = decode s
|
||||
|
||||
main files = forM_ files sudoku
|
||||
where
|
||||
sudoku file = do
|
||||
br <- openReader file
|
||||
lines <- BufferedReader.getLines br
|
||||
bs <- process lines
|
||||
ss <- mapM (\b -> print "Puzzle: " >> printb b >> solve b) bs
|
||||
println ("Euler: " ++ show (sum (map res012 ss)))
|
||||
return ()
|
||||
|
||||
-- "--3-" => [1..9, 1..9, [3], 1..9]
|
||||
decode s = map candi (unpacked s) where
|
||||
candi c | c >= '1' && c <= '9' = [(ord c - ord '0')]
|
||||
| otherwise = elements
|
||||
process [] = return []
|
||||
process (s:ss)
|
||||
| length s == 81 = consider b1
|
||||
| length s == 9,
|
||||
length acht == 8,
|
||||
all ((9==) • length) acht = consider b2
|
||||
| otherwise = do
|
||||
stderr.println ("skipped line: " ++ s)
|
||||
process ss
|
||||
where
|
||||
acht = take 8 ss
|
||||
neun = fold (++) "" (s:acht)
|
||||
b1 = zip positions (decode s)
|
||||
b2 = zip positions (decode neun)
|
||||
consider b = do
|
||||
-- print "Puzzle: "
|
||||
-- printb b
|
||||
bs <- process ss
|
||||
return (b:bs)
|
||||
|
||||
79
samples/Frege/SwingExamples.fr
Normal file
79
samples/Frege/SwingExamples.fr
Normal file
@@ -0,0 +1,79 @@
|
||||
package examples.SwingExamples where
|
||||
|
||||
import Java.Awt (ActionListener)
|
||||
import Java.Swing
|
||||
|
||||
|
||||
main _ = do
|
||||
rs <- mapM Runnable.new [helloWorldGUI, buttonDemoGUI, celsiusConverterGUI]
|
||||
mapM_ invokeLater rs
|
||||
println "Hit enter to end ...."
|
||||
s <- getLine
|
||||
return ()
|
||||
|
||||
celsiusConverterGUI = do
|
||||
tempTextField <- JTextField.new()
|
||||
celsiusLabel <- JLabel.new ()
|
||||
convertButton <- JButton.new ()
|
||||
fahrenheitLabel <- JLabel.new ()
|
||||
frame <- JFrame.new ()
|
||||
frame.setDefaultCloseOperation JFrame.dispose_on_close
|
||||
frame.setTitle "Celsius Converter"
|
||||
celsiusLabel.setText "Celsius"
|
||||
convertButton.setText "Convert"
|
||||
let convertButtonActionPerformed _ = do
|
||||
celsius <- tempTextField.getText
|
||||
case celsius.double of
|
||||
Left _ -> fahrenheitLabel.setText ("not a valid number: " ++ celsius)
|
||||
Right c -> fahrenheitLabel.setText (show (c*1.8 + 32.0).long ++ " Fahrenheit")
|
||||
return ()
|
||||
ActionListener.new convertButtonActionPerformed >>= convertButton.addActionListener
|
||||
fahrenheitLabel.setText "Fahrenheit"
|
||||
contentPane <- frame.getContentPane
|
||||
layout <- GroupLayout.new contentPane
|
||||
contentPane.setLayout layout
|
||||
-- TODO continue
|
||||
-- http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/learn/CelsiusConverterProject/src/learn/CelsiusConverterGUI.java
|
||||
frame.pack
|
||||
frame.setVisible true
|
||||
|
||||
helloWorldGUI = do
|
||||
frame <- JFrame.new "Hello World Frege"
|
||||
frame.setDefaultCloseOperation(JFrame.dispose_on_close)
|
||||
label <- JLabel.new "Hello World!"
|
||||
cp <- frame.getContentPane
|
||||
cp.add label
|
||||
frame.pack
|
||||
frame.setVisible true
|
||||
|
||||
buttonDemoGUI = do
|
||||
frame <- JFrame.new "Button Demo"
|
||||
frame.setDefaultCloseOperation(JFrame.dispose_on_close)
|
||||
newContentPane <- JPanel.new ()
|
||||
b1::JButton <- JButton.new "Disable middle button"
|
||||
b1.setVerticalTextPosition SwingConstants.center
|
||||
b1.setHorizontalTextPosition SwingConstants.leading
|
||||
b2::JButton <- JButton.new "Middle button"
|
||||
b2.setVerticalTextPosition SwingConstants.center
|
||||
b2.setHorizontalTextPosition SwingConstants.leading
|
||||
b3::JButton <- JButton.new "Enable middle button"
|
||||
b3.setVerticalTextPosition SwingConstants.center
|
||||
b3.setHorizontalTextPosition SwingConstants.leading
|
||||
b3.setEnabled false
|
||||
let action1 _ = do
|
||||
b2.setEnabled false
|
||||
b1.setEnabled false
|
||||
b3.setEnabled true
|
||||
action3 _ = do
|
||||
b2.setEnabled true
|
||||
b1.setEnabled true
|
||||
b3.setEnabled false
|
||||
ActionListener.new action1 >>= b1.addActionListener
|
||||
ActionListener.new action3 >>= b3.addActionListener
|
||||
newContentPane.add b1
|
||||
newContentPane.add b2
|
||||
newContentPane.add b3
|
||||
newContentPane.setOpaque true
|
||||
frame.setContentPane newContentPane
|
||||
frame.pack
|
||||
frame.setVisible true
|
||||
642
samples/Game Maker Language/ClientBeginStep.gml
Normal file
642
samples/Game Maker Language/ClientBeginStep.gml
Normal file
@@ -0,0 +1,642 @@
|
||||
/*
|
||||
Originally from /Source/gg2/Scripts/Client/ClientBeginStep.gml in Gang Garrison 2
|
||||
|
||||
Copyright (C) 2008-2013 Faucet Software
|
||||
http://www.ganggarrison.com
|
||||
|
||||
This program is free software;
|
||||
you can redistribute it and/or modify it under the terms of the GNU General Public License
|
||||
as published by the Free Software Foundation; either version 3 of the License, or (at your option)
|
||||
any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License along with this program; if not,
|
||||
see <http://www.gnu.org/licenses>.
|
||||
|
||||
Additional permission under GNU GPL version 3 section 7
|
||||
If you modify this Program, or any covered work, by linking or combining it with the Game Maker runtime library,
|
||||
the 39dll library/extension, Hobbel's Download Manager DLL, or modified versions of these libraries,
|
||||
the licensors of this Program grant you additional permission to convey the resulting work.
|
||||
*/
|
||||
|
||||
// receive and interpret the server's message(s)
|
||||
var i, playerObject, playerID, player, otherPlayerID, otherPlayer, sameVersion, buffer, plugins, pluginsRequired, usePlugins;
|
||||
|
||||
if(tcp_eof(global.serverSocket)) {
|
||||
if(gotServerHello)
|
||||
show_message("You have been disconnected from the server.");
|
||||
else
|
||||
show_message("Unable to connect to the server.");
|
||||
instance_destroy();
|
||||
exit;
|
||||
}
|
||||
|
||||
if(room == DownloadRoom and keyboard_check(vk_escape))
|
||||
{
|
||||
instance_destroy();
|
||||
exit;
|
||||
}
|
||||
|
||||
if(downloadingMap)
|
||||
{
|
||||
while(tcp_receive(global.serverSocket, min(1024, downloadMapBytes-buffer_size(downloadMapBuffer))))
|
||||
{
|
||||
write_buffer(downloadMapBuffer, global.serverSocket);
|
||||
if(buffer_size(downloadMapBuffer) == downloadMapBytes)
|
||||
{
|
||||
write_buffer_to_file(downloadMapBuffer, "Maps/" + downloadMapName + ".png");
|
||||
downloadingMap = false;
|
||||
buffer_destroy(downloadMapBuffer);
|
||||
downloadMapBuffer = -1;
|
||||
exit;
|
||||
}
|
||||
}
|
||||
exit;
|
||||
}
|
||||
|
||||
roomchange = false;
|
||||
do {
|
||||
if(tcp_receive(global.serverSocket,1)) {
|
||||
switch(read_ubyte(global.serverSocket)) {
|
||||
case HELLO:
|
||||
gotServerHello = true;
|
||||
global.joinedServerName = receivestring(global.serverSocket, 1);
|
||||
downloadMapName = receivestring(global.serverSocket, 1);
|
||||
advertisedMapMd5 = receivestring(global.serverSocket, 1);
|
||||
receiveCompleteMessage(global.serverSocket, 1, global.tempBuffer);
|
||||
pluginsRequired = read_ubyte(global.tempBuffer);
|
||||
plugins = receivestring(global.serverSocket, 1);
|
||||
if(string_pos("/", downloadMapName) != 0 or string_pos("\", downloadMapName) != 0)
|
||||
{
|
||||
show_message("Server sent illegal map name: "+downloadMapName);
|
||||
instance_destroy();
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!noReloadPlugins && string_length(plugins))
|
||||
{
|
||||
usePlugins = pluginsRequired || !global.serverPluginsPrompt;
|
||||
if (global.serverPluginsPrompt)
|
||||
{
|
||||
var prompt;
|
||||
if (pluginsRequired)
|
||||
{
|
||||
prompt = show_question(
|
||||
"This server requires the following plugins to play on it: "
|
||||
+ string_replace_all(plugins, ",", "#")
|
||||
+ '#They are downloaded from the source: "'
|
||||
+ PLUGIN_SOURCE
|
||||
+ '"#The source states: "'
|
||||
+ PLUGIN_SOURCE_NOTICE
|
||||
+ '"#Do you wish to download them and continue connecting?'
|
||||
);
|
||||
if (!prompt)
|
||||
{
|
||||
instance_destroy();
|
||||
exit;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
prompt = show_question(
|
||||
"This server suggests the following optional plugins to play on it: "
|
||||
+ string_replace_all(plugins, ",", "#")
|
||||
+ '#They are downloaded from the source: "'
|
||||
+ PLUGIN_SOURCE
|
||||
+ '"#The source states: "'
|
||||
+ PLUGIN_SOURCE_NOTICE
|
||||
+ '"#Do you wish to download them and use them?'
|
||||
);
|
||||
if (prompt)
|
||||
{
|
||||
usePlugins = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (usePlugins)
|
||||
{
|
||||
if (!loadserverplugins(plugins))
|
||||
{
|
||||
show_message("Error ocurred loading server-sent plugins.");
|
||||
instance_destroy();
|
||||
exit;
|
||||
}
|
||||
global.serverPluginsInUse = true;
|
||||
}
|
||||
}
|
||||
noReloadPlugins = false;
|
||||
|
||||
if(advertisedMapMd5 != "")
|
||||
{
|
||||
var download;
|
||||
download = not file_exists("Maps/" + downloadMapName + ".png");
|
||||
if(!download and CustomMapGetMapMD5(downloadMapName) != advertisedMapMd5)
|
||||
{
|
||||
if(show_question("The server's copy of the map (" + downloadMapName + ") differs from ours.#Would you like to download this server's version of the map?"))
|
||||
download = true;
|
||||
else
|
||||
{
|
||||
instance_destroy();
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
if(download)
|
||||
{
|
||||
write_ubyte(global.serverSocket, DOWNLOAD_MAP);
|
||||
socket_send(global.serverSocket);
|
||||
receiveCompleteMessage(global.serverSocket,4,global.tempBuffer);
|
||||
downloadMapBytes = read_uint(global.tempBuffer);
|
||||
downloadMapBuffer = buffer_create();
|
||||
downloadingMap = true;
|
||||
roomchange=true;
|
||||
}
|
||||
}
|
||||
ClientPlayerJoin(global.serverSocket);
|
||||
if(global.rewardKey != "" and global.rewardId != "")
|
||||
{
|
||||
var rewardId;
|
||||
rewardId = string_copy(global.rewardId, 0, 255);
|
||||
write_ubyte(global.serverSocket, REWARD_REQUEST);
|
||||
write_ubyte(global.serverSocket, string_length(rewardId));
|
||||
write_string(global.serverSocket, rewardId);
|
||||
}
|
||||
if(global.queueJumping == true)
|
||||
{
|
||||
write_ubyte(global.serverSocket, CLIENT_SETTINGS);
|
||||
write_ubyte(global.serverSocket, global.queueJumping);
|
||||
}
|
||||
socket_send(global.serverSocket);
|
||||
break;
|
||||
|
||||
case JOIN_UPDATE:
|
||||
receiveCompleteMessage(global.serverSocket,2,global.tempBuffer);
|
||||
global.playerID = read_ubyte(global.tempBuffer);
|
||||
global.currentMapArea = read_ubyte(global.tempBuffer);
|
||||
break;
|
||||
|
||||
case FULL_UPDATE:
|
||||
deserializeState(FULL_UPDATE);
|
||||
break;
|
||||
|
||||
case QUICK_UPDATE:
|
||||
deserializeState(QUICK_UPDATE);
|
||||
break;
|
||||
|
||||
case CAPS_UPDATE:
|
||||
deserializeState(CAPS_UPDATE);
|
||||
break;
|
||||
|
||||
case INPUTSTATE:
|
||||
deserializeState(INPUTSTATE);
|
||||
break;
|
||||
|
||||
case PLAYER_JOIN:
|
||||
player = instance_create(0,0,Player);
|
||||
player.name = receivestring(global.serverSocket, 1);
|
||||
|
||||
ds_list_add(global.players, player);
|
||||
if(ds_list_size(global.players)-1 == global.playerID) {
|
||||
global.myself = player;
|
||||
instance_create(0,0,PlayerControl);
|
||||
}
|
||||
break;
|
||||
|
||||
case PLAYER_LEAVE:
|
||||
// Delete player from the game, adjust own ID accordingly
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
playerID = read_ubyte(global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, playerID);
|
||||
removePlayer(player);
|
||||
if(playerID < global.playerID) {
|
||||
global.playerID -= 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case PLAYER_DEATH:
|
||||
var causeOfDeath, assistantPlayerID, assistantPlayer;
|
||||
receiveCompleteMessage(global.serverSocket,4,global.tempBuffer);
|
||||
playerID = read_ubyte(global.tempBuffer);
|
||||
otherPlayerID = read_ubyte(global.tempBuffer);
|
||||
assistantPlayerID = read_ubyte(global.tempBuffer);
|
||||
causeOfDeath = read_ubyte(global.tempBuffer);
|
||||
|
||||
player = ds_list_find_value(global.players, playerID);
|
||||
|
||||
otherPlayer = noone;
|
||||
if(otherPlayerID != 255)
|
||||
otherPlayer = ds_list_find_value(global.players, otherPlayerID);
|
||||
|
||||
assistantPlayer = noone;
|
||||
if(assistantPlayerID != 255)
|
||||
assistantPlayer = ds_list_find_value(global.players, assistantPlayerID);
|
||||
|
||||
doEventPlayerDeath(player, otherPlayer, assistantPlayer, causeOfDeath);
|
||||
break;
|
||||
|
||||
case BALANCE:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
balanceplayer=read_ubyte(global.tempBuffer);
|
||||
if balanceplayer == 255 {
|
||||
if !instance_exists(Balancer) instance_create(x,y,Balancer);
|
||||
with(Balancer) notice=0;
|
||||
} else {
|
||||
player = ds_list_find_value(global.players, balanceplayer);
|
||||
if(player.object != -1) {
|
||||
with(player.object) {
|
||||
instance_destroy();
|
||||
}
|
||||
player.object = -1;
|
||||
}
|
||||
if(player.team==TEAM_RED) {
|
||||
player.team = TEAM_BLUE;
|
||||
} else {
|
||||
player.team = TEAM_RED;
|
||||
}
|
||||
if !instance_exists(Balancer) instance_create(x,y,Balancer);
|
||||
Balancer.name=player.name;
|
||||
with (Balancer) notice=1;
|
||||
}
|
||||
break;
|
||||
|
||||
case PLAYER_CHANGETEAM:
|
||||
receiveCompleteMessage(global.serverSocket,2,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
if(player.object != -1) {
|
||||
with(player.object) {
|
||||
instance_destroy();
|
||||
}
|
||||
player.object = -1;
|
||||
}
|
||||
player.team = read_ubyte(global.tempBuffer);
|
||||
break;
|
||||
|
||||
case PLAYER_CHANGECLASS:
|
||||
receiveCompleteMessage(global.serverSocket,2,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
if(player.object != -1) {
|
||||
with(player.object) {
|
||||
instance_destroy();
|
||||
}
|
||||
player.object = -1;
|
||||
}
|
||||
player.class = read_ubyte(global.tempBuffer);
|
||||
break;
|
||||
|
||||
case PLAYER_CHANGENAME:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
player.name = receivestring(global.serverSocket, 1);
|
||||
if player=global.myself {
|
||||
global.playerName=player.name
|
||||
}
|
||||
break;
|
||||
|
||||
case PLAYER_SPAWN:
|
||||
receiveCompleteMessage(global.serverSocket,3,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
doEventSpawn(player, read_ubyte(global.tempBuffer), read_ubyte(global.tempBuffer));
|
||||
break;
|
||||
|
||||
case CHAT_BUBBLE:
|
||||
var bubbleImage;
|
||||
receiveCompleteMessage(global.serverSocket,2,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
setChatBubble(player, read_ubyte(global.tempBuffer));
|
||||
break;
|
||||
|
||||
case BUILD_SENTRY:
|
||||
receiveCompleteMessage(global.serverSocket,6,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
buildSentry(player, read_ushort(global.tempBuffer)/5, read_ushort(global.tempBuffer)/5, read_byte(global.tempBuffer));
|
||||
break;
|
||||
|
||||
case DESTROY_SENTRY:
|
||||
receiveCompleteMessage(global.serverSocket,4,global.tempBuffer);
|
||||
playerID = read_ubyte(global.tempBuffer);
|
||||
otherPlayerID = read_ubyte(global.tempBuffer);
|
||||
assistantPlayerID = read_ubyte(global.tempBuffer);
|
||||
causeOfDeath = read_ubyte(global.tempBuffer);
|
||||
|
||||
player = ds_list_find_value(global.players, playerID);
|
||||
if(otherPlayerID == 255) {
|
||||
doEventDestruction(player, noone, noone, causeOfDeath);
|
||||
} else {
|
||||
otherPlayer = ds_list_find_value(global.players, otherPlayerID);
|
||||
if (assistantPlayerID == 255) {
|
||||
doEventDestruction(player, otherPlayer, noone, causeOfDeath);
|
||||
} else {
|
||||
assistantPlayer = ds_list_find_value(global.players, assistantPlayerID);
|
||||
doEventDestruction(player, otherPlayer, assistantPlayer, causeOfDeath);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case GRAB_INTEL:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
doEventGrabIntel(player);
|
||||
break;
|
||||
|
||||
case SCORE_INTEL:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
doEventScoreIntel(player);
|
||||
break;
|
||||
|
||||
case DROP_INTEL:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
doEventDropIntel(player);
|
||||
break;
|
||||
|
||||
case RETURN_INTEL:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
doEventReturnIntel(read_ubyte(global.tempBuffer));
|
||||
break;
|
||||
|
||||
case GENERATOR_DESTROY:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
team = read_ubyte(global.tempBuffer);
|
||||
doEventGeneratorDestroy(team);
|
||||
break;
|
||||
|
||||
case UBER_CHARGED:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
doEventUberReady(player);
|
||||
break;
|
||||
|
||||
case UBER:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
doEventUber(player);
|
||||
break;
|
||||
|
||||
case OMNOMNOMNOM:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
if(player.object != -1) {
|
||||
with(player.object) {
|
||||
omnomnomnom=true;
|
||||
if(hp < 200)
|
||||
{
|
||||
canEat = false;
|
||||
alarm[6] = eatCooldown; //10 second cooldown
|
||||
}
|
||||
if(player.team == TEAM_RED) {
|
||||
omnomnomnomindex=0;
|
||||
omnomnomnomend=31;
|
||||
} else if(player.team==TEAM_BLUE) {
|
||||
omnomnomnomindex=32;
|
||||
omnomnomnomend=63;
|
||||
}
|
||||
xscale=image_xscale;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case TOGGLE_ZOOM:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
if player.object != -1 {
|
||||
toggleZoom(player.object);
|
||||
}
|
||||
break;
|
||||
|
||||
case PASSWORD_REQUEST:
|
||||
if(!usePreviousPwd)
|
||||
global.clientPassword = get_string("Enter Password:", "");
|
||||
write_ubyte(global.serverSocket, string_length(global.clientPassword));
|
||||
write_string(global.serverSocket, global.clientPassword);
|
||||
socket_send(global.serverSocket);
|
||||
break;
|
||||
|
||||
case PASSWORD_WRONG:
|
||||
show_message("Incorrect Password.");
|
||||
instance_destroy();
|
||||
exit;
|
||||
|
||||
case INCOMPATIBLE_PROTOCOL:
|
||||
show_message("Incompatible server protocol version.");
|
||||
instance_destroy();
|
||||
exit;
|
||||
|
||||
case KICK:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
reason = read_ubyte(global.tempBuffer);
|
||||
if reason == KICK_NAME kickReason = "Name Exploit";
|
||||
else if reason == KICK_BAD_PLUGIN_PACKET kickReason = "Invalid plugin packet ID";
|
||||
else if reason == KICK_MULTI_CLIENT kickReason = "There are too many connections from your IP";
|
||||
else kickReason = "";
|
||||
show_message("You have been kicked from the server. "+kickReason+".");
|
||||
instance_destroy();
|
||||
exit;
|
||||
|
||||
case ARENA_STARTROUND:
|
||||
doEventArenaStartRound();
|
||||
break;
|
||||
|
||||
case ARENA_ENDROUND:
|
||||
with ArenaHUD clientArenaEndRound();
|
||||
break;
|
||||
|
||||
case ARENA_RESTART:
|
||||
doEventArenaRestart();
|
||||
break;
|
||||
|
||||
case UNLOCKCP:
|
||||
doEventUnlockCP();
|
||||
break;
|
||||
|
||||
case MAP_END:
|
||||
global.nextMap=receivestring(global.serverSocket, 1);
|
||||
receiveCompleteMessage(global.serverSocket,2,global.tempBuffer);
|
||||
global.winners=read_ubyte(global.tempBuffer);
|
||||
global.currentMapArea=read_ubyte(global.tempBuffer);
|
||||
global.mapchanging = true;
|
||||
if !instance_exists(ScoreTableController) instance_create(0,0,ScoreTableController);
|
||||
instance_create(0,0,WinBanner);
|
||||
break;
|
||||
|
||||
case CHANGE_MAP:
|
||||
roomchange=true;
|
||||
global.mapchanging = false;
|
||||
global.currentMap = receivestring(global.serverSocket, 1);
|
||||
global.currentMapMD5 = receivestring(global.serverSocket, 1);
|
||||
if(global.currentMapMD5 == "") { // if this is an internal map (signified by the lack of an md5)
|
||||
if(findInternalMapRoom(global.currentMap))
|
||||
room_goto_fix(findInternalMapRoom(global.currentMap));
|
||||
else
|
||||
{
|
||||
show_message("Error:#Server went to invalid internal map: " + global.currentMap + "#Exiting.");
|
||||
instance_destroy();
|
||||
exit;
|
||||
}
|
||||
} else { // it's an external map
|
||||
if(string_pos("/", global.currentMap) != 0 or string_pos("\", global.currentMap) != 0)
|
||||
{
|
||||
show_message("Server sent illegal map name: "+global.currentMap);
|
||||
instance_destroy();
|
||||
exit;
|
||||
}
|
||||
if(!file_exists("Maps/" + global.currentMap + ".png") or CustomMapGetMapMD5(global.currentMap) != global.currentMapMD5)
|
||||
{ // Reconnect to the server to download the map
|
||||
var oldReturnRoom;
|
||||
oldReturnRoom = returnRoom;
|
||||
returnRoom = DownloadRoom;
|
||||
if (global.serverPluginsInUse)
|
||||
noUnloadPlugins = true;
|
||||
event_perform(ev_destroy,0);
|
||||
ClientCreate();
|
||||
if (global.serverPluginsInUse)
|
||||
noReloadPlugins = true;
|
||||
returnRoom = oldReturnRoom;
|
||||
usePreviousPwd = true;
|
||||
exit;
|
||||
}
|
||||
room_goto_fix(CustomMapRoom);
|
||||
}
|
||||
|
||||
for(i=0; i<ds_list_size(global.players); i+=1) {
|
||||
player = ds_list_find_value(global.players, i);
|
||||
if global.currentMapArea == 1 {
|
||||
player.stats[KILLS] = 0;
|
||||
player.stats[DEATHS] = 0;
|
||||
player.stats[CAPS] = 0;
|
||||
player.stats[ASSISTS] = 0;
|
||||
player.stats[DESTRUCTION] = 0;
|
||||
player.stats[STABS] = 0;
|
||||
player.stats[HEALING] = 0;
|
||||
player.stats[DEFENSES] = 0;
|
||||
player.stats[INVULNS] = 0;
|
||||
player.stats[BONUS] = 0;
|
||||
player.stats[DOMINATIONS] = 0;
|
||||
player.stats[REVENGE] = 0;
|
||||
player.stats[POINTS] = 0;
|
||||
player.roundStats[KILLS] = 0;
|
||||
player.roundStats[DEATHS] = 0;
|
||||
player.roundStats[CAPS] = 0;
|
||||
player.roundStats[ASSISTS] = 0;
|
||||
player.roundStats[DESTRUCTION] = 0;
|
||||
player.roundStats[STABS] = 0;
|
||||
player.roundStats[HEALING] = 0;
|
||||
player.roundStats[DEFENSES] = 0;
|
||||
player.roundStats[INVULNS] = 0;
|
||||
player.roundStats[BONUS] = 0;
|
||||
player.roundStats[DOMINATIONS] = 0;
|
||||
player.roundStats[REVENGE] = 0;
|
||||
player.roundStats[POINTS] = 0;
|
||||
player.team = TEAM_SPECTATOR;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case SERVER_FULL:
|
||||
show_message("The server is full.");
|
||||
instance_destroy();
|
||||
exit;
|
||||
|
||||
case REWARD_CHALLENGE_CODE:
|
||||
var challengeData;
|
||||
receiveCompleteMessage(global.serverSocket,16,global.tempBuffer);
|
||||
challengeData = read_binstring(global.tempBuffer, buffer_size(global.tempBuffer));
|
||||
challengeData += socket_remote_ip(global.serverSocket);
|
||||
|
||||
write_ubyte(global.serverSocket, REWARD_CHALLENGE_RESPONSE);
|
||||
write_binstring(global.serverSocket, hmac_md5_bin(global.rewardKey, challengeData));
|
||||
socket_send(global.serverSocket);
|
||||
break;
|
||||
|
||||
case REWARD_UPDATE:
|
||||
receiveCompleteMessage(global.serverSocket,1,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
var rewardString;
|
||||
rewardString = receivestring(global.serverSocket, 2);
|
||||
doEventUpdateRewards(player, rewardString);
|
||||
break;
|
||||
|
||||
case MESSAGE_STRING:
|
||||
var message, notice;
|
||||
message = receivestring(global.serverSocket, 1);
|
||||
with NoticeO instance_destroy();
|
||||
notice = instance_create(0, 0, NoticeO);
|
||||
notice.notice = NOTICE_CUSTOM;
|
||||
notice.message = message;
|
||||
break;
|
||||
|
||||
case SENTRY_POSITION:
|
||||
receiveCompleteMessage(global.serverSocket,5,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
if(player.sentry)
|
||||
{
|
||||
player.sentry.x = read_ushort(global.tempBuffer) / 5;
|
||||
player.sentry.y = read_ushort(global.tempBuffer) / 5;
|
||||
player.sentry.xprevious = player.sentry.x;
|
||||
player.sentry.yprevious = player.sentry.y;
|
||||
player.sentry.vspeed = 0;
|
||||
}
|
||||
break;
|
||||
|
||||
case WEAPON_FIRE:
|
||||
receiveCompleteMessage(global.serverSocket,9,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
|
||||
if(player.object)
|
||||
{
|
||||
with(player.object)
|
||||
{
|
||||
x = read_ushort(global.tempBuffer)/5;
|
||||
y = read_ushort(global.tempBuffer)/5;
|
||||
hspeed = read_byte(global.tempBuffer)/8.5;
|
||||
vspeed = read_byte(global.tempBuffer)/8.5;
|
||||
xprevious = x;
|
||||
yprevious = y;
|
||||
}
|
||||
|
||||
doEventFireWeapon(player, read_ushort(global.tempBuffer));
|
||||
}
|
||||
break;
|
||||
|
||||
case PLUGIN_PACKET:
|
||||
var packetID, packetLen, buf, success;
|
||||
|
||||
// fetch full packet
|
||||
receiveCompleteMessage(global.serverSocket, 2, global.tempBuffer);
|
||||
packetLen = read_ushort(global.tempBuffer);
|
||||
receiveCompleteMessage(global.serverSocket, packetLen, global.tempBuffer);
|
||||
|
||||
packetID = read_ubyte(global.tempBuffer);
|
||||
|
||||
// get packet data
|
||||
buf = buffer_create();
|
||||
write_buffer_part(buf, global.tempBuffer, packetLen - 1);
|
||||
|
||||
// try to enqueue
|
||||
// give "noone" value for client since received from server
|
||||
success = _PluginPacketPush(packetID, buf, noone);
|
||||
|
||||
// if it returned false, packetID was invalid
|
||||
if (!success)
|
||||
{
|
||||
// clear up buffer
|
||||
buffer_destroy(buf);
|
||||
show_error("ERROR when reading plugin packet: no such plugin packet ID " + string(packetID), true);
|
||||
}
|
||||
break;
|
||||
|
||||
case CLIENT_SETTINGS:
|
||||
receiveCompleteMessage(global.serverSocket,2,global.tempBuffer);
|
||||
player = ds_list_find_value(global.players, read_ubyte(global.tempBuffer));
|
||||
player.queueJump = read_ubyte(global.tempBuffer);
|
||||
break;
|
||||
|
||||
default:
|
||||
promptRestartOrQuit("The Server sent unexpected data.");
|
||||
exit;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} until(roomchange);
|
||||
141
samples/Game Maker Language/Create.gml
Normal file
141
samples/Game Maker Language/Create.gml
Normal file
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
Originally from /Source/gg2/Objects/Updater.events/Create.xml in Gang Garrison 2
|
||||
|
||||
Copyright (C) 2008-2013 Faucet Software
|
||||
http://www.ganggarrison.com
|
||||
|
||||
This program is free software;
|
||||
you can redistribute it and/or modify it under the terms of the GNU General Public License
|
||||
as published by the Free Software Foundation; either version 3 of the License, or (at your option)
|
||||
any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License along with this program; if not,
|
||||
see <http://www.gnu.org/licenses>.
|
||||
|
||||
Additional permission under GNU GPL version 3 section 7
|
||||
If you modify this Program, or any covered work, by linking or combining it with the Game Maker runtime library,
|
||||
the 39dll library/extension, Hobbel's Download Manager DLL, or modified versions of these libraries,
|
||||
the licensors of this Program grant you additional permission to convey the resulting work.
|
||||
*/
|
||||
// Downloading code.
|
||||
|
||||
var downloadHandle, url, tmpfile, window_oldshowborder, window_oldfullscreen;
|
||||
timeLeft = 0;
|
||||
counter = 0;
|
||||
AudioControlPlaySong(-1, false);
|
||||
window_oldshowborder = window_get_showborder();
|
||||
window_oldfullscreen = window_get_fullscreen();
|
||||
window_set_fullscreen(false);
|
||||
window_set_showborder(false);
|
||||
|
||||
if(global.updaterBetaChannel)
|
||||
url = UPDATE_SOURCE_BETA;
|
||||
else
|
||||
url = UPDATE_SOURCE;
|
||||
|
||||
tmpfile = temp_directory + "\gg2update.zip";
|
||||
|
||||
downloadHandle = httpGet(url, -1);
|
||||
|
||||
while(!httpRequestStatus(downloadHandle))
|
||||
{ // while download isn't finished
|
||||
sleep(floor(1000/30)); // sleep for the equivalent of one frame
|
||||
io_handle(); // this prevents GameMaker from appearing locked-up
|
||||
httpRequestStep(downloadHandle);
|
||||
|
||||
// check if the user cancelled the download with the esc key
|
||||
if(keyboard_check(vk_escape))
|
||||
{
|
||||
httpRequestDestroy(downloadHandle);
|
||||
window_set_showborder(window_oldshowborder);
|
||||
window_set_fullscreen(window_oldfullscreen);
|
||||
room_goto_fix(Menu);
|
||||
exit;
|
||||
}
|
||||
|
||||
if(counter == 0 || counter mod 60 == 0)
|
||||
timer = random(359)+1;
|
||||
draw_sprite(UpdaterBackgroundS,0,0,0);
|
||||
draw_set_color(c_white);
|
||||
draw_set_halign(fa_left);
|
||||
draw_set_valign(fa_center);
|
||||
minutes=floor(timer/60);
|
||||
seconds=floor(timer-minutes*60);
|
||||
draw_text(x,y-20,string(minutes) + " minutes " + string(seconds) + " seconds Remaining...");
|
||||
counter+=1;
|
||||
var progress, size;
|
||||
progress = httpRequestResponseBodyProgress(downloadHandle);
|
||||
size = httpRequestResponseBodySize(downloadHandle);
|
||||
if (size != -1)
|
||||
{
|
||||
progressBar = floor((progress/size) * 20);
|
||||
offset = 3;
|
||||
for(i=0;i<progressBar;i+=1){
|
||||
draw_sprite(UpdaterProgressS,0,x+offset,y);
|
||||
offset+=12;
|
||||
}
|
||||
}
|
||||
screen_refresh();
|
||||
}
|
||||
// Errored
|
||||
if (httpRequestStatus(downloadHandle) == 2)
|
||||
{
|
||||
show_message("Downloading update failed!#" + httpRequestError(downloadHandle));
|
||||
httpRequestDestroy(downloadHandle);
|
||||
window_set_showborder(window_oldshowborder);
|
||||
window_set_fullscreen(window_oldfullscreen);
|
||||
room_goto_fix(Menu);
|
||||
exit;
|
||||
}
|
||||
// Request failed
|
||||
if (httpRequestStatusCode(downloadHandle) != 200)
|
||||
{
|
||||
show_message("Downloading update failed!#" + string(httpRequestStatusCode(downloadHandle)) + " " + httpRequestReasonPhrase(downloadHandle));
|
||||
httpRequestDestroy(downloadHandle);
|
||||
window_set_showborder(window_oldshowborder);
|
||||
window_set_fullscreen(window_oldfullscreen);
|
||||
room_goto_fix(Menu);
|
||||
exit;
|
||||
}
|
||||
|
||||
write_buffer_to_file(httpRequestResponseBody(downloadHandle), tmpfile);
|
||||
httpRequestDestroy(downloadHandle);
|
||||
|
||||
if(!file_exists(tmpfile))
|
||||
{
|
||||
window_set_showborder(window_oldshowborder);
|
||||
window_set_fullscreen(window_oldfullscreen);
|
||||
show_message("Error updating: Missing gg2update.zip in temp directory, download failed(?)");
|
||||
room_goto_fix(Menu);
|
||||
exit;
|
||||
}
|
||||
|
||||
// rename existing "Gang Garrison 2.exe" to avoid conflict when extracting
|
||||
if (file_exists("Gang Garrison 2.exe"))
|
||||
{
|
||||
var newName, n;
|
||||
n = 1;
|
||||
|
||||
// increment until unused name found
|
||||
do
|
||||
{
|
||||
newName = "gg2-old.delete.me." + string(n);
|
||||
n += 1;
|
||||
}
|
||||
until(!file_exists(newName));
|
||||
|
||||
file_rename("Gang Garrison 2.exe", newName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// let's extract the downloaded file now.
|
||||
extractzip(tmpfile, working_directory);
|
||||
|
||||
// run new version
|
||||
execute_program("Gang Garrison 2.exe", "", false);
|
||||
|
||||
// exit
|
||||
game_end();
|
||||
161
samples/Game Maker Language/Draw.gml
Normal file
161
samples/Game Maker Language/Draw.gml
Normal file
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
Originally from /Source/gg2/Objects/InGameElements/Character.events/Draw.xml in Gang Garrison 2
|
||||
|
||||
Copyright (C) 2008-2013 Faucet Software
|
||||
http://www.ganggarrison.com
|
||||
|
||||
This program is free software;
|
||||
you can redistribute it and/or modify it under the terms of the GNU General Public License
|
||||
as published by the Free Software Foundation; either version 3 of the License, or (at your option)
|
||||
any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License along with this program; if not,
|
||||
see <http://www.gnu.org/licenses>.
|
||||
|
||||
Additional permission under GNU GPL version 3 section 7
|
||||
If you modify this Program, or any covered work, by linking or combining it with the Game Maker runtime library,
|
||||
the 39dll library/extension, Hobbel's Download Manager DLL, or modified versions of these libraries,
|
||||
the licensors of this Program grant you additional permission to convey the resulting work.
|
||||
*/
|
||||
|
||||
xoffset = view_xview[0];
|
||||
yoffset = view_yview[0];
|
||||
xsize = view_wview[0];
|
||||
ysize = view_hview[0];
|
||||
|
||||
if (distance_to_point(xoffset+xsize/2,yoffset+ysize/2) > 800)
|
||||
exit;
|
||||
|
||||
var xr, yr;
|
||||
xr = round(x);
|
||||
yr = round(y);
|
||||
|
||||
image_alpha = cloakAlpha;
|
||||
|
||||
if (global.myself.team == team and canCloak)
|
||||
image_alpha = cloakAlpha/2 + 0.5;
|
||||
|
||||
if (invisible)
|
||||
exit;
|
||||
|
||||
if(stabbing)
|
||||
image_alpha -= power(currentWeapon.stab.alpha, 2);
|
||||
|
||||
if team == global.myself.team && (player != global.myself || global.showHealthBar == 1){
|
||||
draw_set_alpha(1);
|
||||
draw_healthbar(xr-10, yr-30, xr+10, yr-25,hp*100/maxHp,c_black,c_red,c_green,0,true,true);
|
||||
}
|
||||
if(distance_to_point(mouse_x, mouse_y)<25) {
|
||||
if cloak && team!=global.myself.team exit;
|
||||
draw_set_alpha(1);
|
||||
draw_set_halign(fa_center);
|
||||
draw_set_valign(fa_bottom);
|
||||
if(team==TEAM_RED) {
|
||||
draw_set_color(c_red);
|
||||
} else {
|
||||
draw_set_color(c_blue);
|
||||
}
|
||||
draw_text(xr, yr-35, player.name);
|
||||
|
||||
if(team == global.myself.team && global.showTeammateStats)
|
||||
{
|
||||
if(weapons[0] == Medigun)
|
||||
draw_text(xr,yr+50, "Superburst: " + string(currentWeapon.uberCharge/20) + "%");
|
||||
else if(weapons[0] == Shotgun)
|
||||
draw_text(xr,yr+50, "Nuts 'N' Bolts: " + string(nutsNBolts));
|
||||
else if(weapons[0] == Minegun)
|
||||
draw_text(xr,yr+50, "Lobbed Mines: " + string(currentWeapon.lobbed));
|
||||
}
|
||||
}
|
||||
|
||||
draw_set_alpha(1);
|
||||
if team == TEAM_RED ubercolour = c_red;
|
||||
if team == TEAM_BLUE ubercolour = c_blue;
|
||||
|
||||
var sprite, overlaySprite;
|
||||
if zoomed
|
||||
{
|
||||
if (team == TEAM_RED)
|
||||
sprite = SniperCrouchRedS;
|
||||
else
|
||||
sprite = SniperCrouchBlueS;
|
||||
overlaySprite = sniperCrouchOverlay;
|
||||
}
|
||||
else
|
||||
{
|
||||
sprite = sprite_index;
|
||||
overlaySprite = overlay;
|
||||
}
|
||||
|
||||
if (omnomnomnom)
|
||||
{
|
||||
draw_sprite_ext_overlay(omnomnomnomSprite,omnomnomnomOverlay,omnomnomnomindex,xr,yr,image_xscale,image_yscale,image_angle,c_white,1);
|
||||
if (ubered)
|
||||
draw_sprite_ext_overlay(omnomnomnomSprite,omnomnomnomOverlay,omnomnomnomindex,xr,yr,image_xscale,image_yscale,image_angle,ubercolour,0.7);
|
||||
}
|
||||
else if (taunting)
|
||||
{
|
||||
draw_sprite_ext_overlay(tauntsprite,tauntOverlay,tauntindex,xr,yr,image_xscale,image_yscale,image_angle,c_white,1);
|
||||
if (ubered)
|
||||
draw_sprite_ext_overlay(tauntsprite,tauntOverlay,tauntindex,xr,yr,image_xscale,image_yscale,image_angle,ubercolour,0.7);
|
||||
}
|
||||
else if (player.humiliated)
|
||||
draw_sprite_ext(humiliationPoses,floor(animationImage)+humiliationOffset,xr,yr,image_xscale,image_yscale,image_angle,c_white,image_alpha);
|
||||
else if (!taunting)
|
||||
{
|
||||
if (cloak)
|
||||
{
|
||||
if (!ubered)
|
||||
draw_sprite_ext(sprite,floor(animationImage+animationOffset),xr,yr,image_xscale,image_yscale,image_angle,c_white,image_alpha);
|
||||
else if (ubered)
|
||||
{
|
||||
draw_sprite_ext(sprite,floor(animationImage+animationOffset),xr,yr,image_xscale,image_yscale,image_angle,c_white,1);
|
||||
draw_sprite_ext(sprite,floor(animationImage+animationOffset),xr,yr,image_xscale,image_yscale,image_angle,ubercolour,0.7);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!ubered)
|
||||
draw_sprite_ext_overlay(sprite,overlaySprite,floor(animationImage+animationOffset),xr,yr,image_xscale,image_yscale,image_angle,c_white,image_alpha);
|
||||
else if (ubered)
|
||||
{
|
||||
draw_sprite_ext_overlay(sprite,overlaySprite,floor(animationImage+animationOffset),xr,yr,image_xscale,image_yscale,image_angle,c_white,1);
|
||||
draw_sprite_ext_overlay(sprite,overlaySprite,floor(animationImage+animationOffset),xr,yr,image_xscale,image_yscale,image_angle,ubercolour,0.7);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (burnDuration > 0 or burnIntensity > 0) {
|
||||
for(i = 0; i < numFlames * burnIntensity / maxIntensity; i += 1)
|
||||
{
|
||||
draw_sprite_ext(FlameS, alarm[5] + i + random(2), x + flameArray_x[i], y + flameArray_y[i], 1, 1, 0, c_white, burnDuration / maxDuration * 0.71 + 0.35);
|
||||
}
|
||||
}
|
||||
|
||||
// Copied from Lorgan's itemserver "angels" with slight modifications
|
||||
// All credit be upon him
|
||||
if (demon != -1)
|
||||
{
|
||||
demonX = median(x-40,demonX,x+40);
|
||||
demonY = median(y-40,demonY,y);
|
||||
demonOffset += demonDir;
|
||||
if (abs(demonOffset) > 15)
|
||||
demonDir *= -1;
|
||||
|
||||
var dir;
|
||||
if (demonX > x)
|
||||
dir = -1;
|
||||
else
|
||||
dir = 1;
|
||||
|
||||
if (demonFrame > sprite_get_number(demon))
|
||||
demonFrame = 0;
|
||||
|
||||
if (stabbing || ubered)
|
||||
draw_sprite_ext(demon,demonFrame+floor(animationImage)+7*player.team,demonX,demonY+demonOffset,dir*1,1,0,c_white,1);
|
||||
else
|
||||
draw_sprite_ext(demon,demonFrame+floor(animationImage)+7*player.team,demonX,demonY+demonOffset,dir*1,1,0,c_white,image_alpha);
|
||||
|
||||
demonFrame += 1;
|
||||
}
|
||||
80
samples/Game Maker Language/characterDrawEvent.gml
Normal file
80
samples/Game Maker Language/characterDrawEvent.gml
Normal file
@@ -0,0 +1,80 @@
|
||||
// Originally from /spelunky/Scripts/Platform Engine/characterDrawEvent.gml in the Spelunky Community Update Project
|
||||
|
||||
/**********************************************************************************
|
||||
Copyright (c) 2008, 2009 Derek Yu and Mossmouth, LLC
|
||||
|
||||
This file is part of Spelunky.
|
||||
|
||||
You can redistribute and/or modify Spelunky, including its source code, under
|
||||
the terms of the Spelunky User License.
|
||||
|
||||
Spelunky is distributed in the hope that it will be entertaining and useful,
|
||||
but WITHOUT WARRANTY. Please see the Spelunky User License for more details.
|
||||
|
||||
The Spelunky User License should be available in "Game Information", which
|
||||
can be found in the Resource Explorer, or as an external file called COPYING.
|
||||
If not, please obtain a new copy of Spelunky from <http://spelunkyworld.com/>
|
||||
|
||||
***********************************************************************************/
|
||||
|
||||
/*
|
||||
This event should be placed in the draw event of the platform character.
|
||||
*/
|
||||
//draws the sprite
|
||||
draw = true;
|
||||
if (facing == RIGHT) image_xscale = -1;
|
||||
else image_xscale = 1;
|
||||
|
||||
if (blinkToggle != 1)
|
||||
{
|
||||
if ((state == CLIMBING or (sprite_index == sPExit or sprite_index == sDamselExit or sprite_index == sTunnelExit)) and global.hasJetpack and not whipping)
|
||||
{
|
||||
draw_sprite_ext(sprite_index, -1, x, y, image_xscale, image_yscale, image_angle, image_blend, image_alpha);
|
||||
//draw_sprite(sprite_index,-1,x,y);
|
||||
draw_sprite(sJetpackBack,-1,x,y);
|
||||
draw = false;
|
||||
}
|
||||
else if (global.hasJetpack and facing == RIGHT) draw_sprite(sJetpackRight,-1,x-4,y-1);
|
||||
else if (global.hasJetpack) draw_sprite(sJetpackLeft,-1,x+4,y-1);
|
||||
if (draw)
|
||||
{
|
||||
if (redColor > 0) draw_sprite_ext(sprite_index, -1, x, y, image_xscale, image_yscale, image_angle, make_color_rgb(200 + redColor,0,0), image_alpha);
|
||||
else draw_sprite_ext(sprite_index, -1, x, y, image_xscale, image_yscale, image_angle, image_blend, image_alpha);
|
||||
}
|
||||
if (facing == RIGHT)
|
||||
{
|
||||
if (holdArrow == ARROW_NORM)
|
||||
{
|
||||
draw_sprite(sArrowRight, -1, x+4, y+1);
|
||||
}
|
||||
else if (holdArrow == ARROW_BOMB)
|
||||
{
|
||||
if (holdArrowToggle) draw_sprite(sBombArrowRight, 0, x+4, y+2);
|
||||
else draw_sprite(sBombArrowRight, 1, x+4, y+2);
|
||||
}
|
||||
}
|
||||
else if (facing == LEFT)
|
||||
{
|
||||
if (holdArrow == ARROW_NORM)
|
||||
{
|
||||
draw_sprite(sArrowLeft, -1, x-4, y+1);
|
||||
}
|
||||
else if (holdArrow == ARROW_BOMB)
|
||||
{
|
||||
if (holdArrowToggle) draw_sprite(sBombArrowLeft, 0, x-4, y+2);
|
||||
else draw_sprite(sBombArrowLeft, 1, x-4, y+2);
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
if canRun
|
||||
{
|
||||
xOffset=80
|
||||
if player=1
|
||||
yOffset=120
|
||||
else
|
||||
yOffset=143
|
||||
//draw the "flySpeed" bar, which shows how much speed the character has acquired while holding the "run" button
|
||||
//draw_healthbar(view_xview[0]+224+xOffset,view_yview[0]+432+yOffset,view_xview[0]+400+xOffset,view_yview[0]+450+yOffset,flySpeed,make_color_rgb(0,64,128),c_blue,c_aqua,0,1,1)
|
||||
}
|
||||
*/
|
||||
1050
samples/Game Maker Language/characterStepEvent.gml
Normal file
1050
samples/Game Maker Language/characterStepEvent.gml
Normal file
File diff suppressed because it is too large
Load Diff
251
samples/Game Maker Language/doEventPlayerDeath.gml
Normal file
251
samples/Game Maker Language/doEventPlayerDeath.gml
Normal file
@@ -0,0 +1,251 @@
|
||||
/*
|
||||
Originally from /Source/gg2/Scripts/Events/doEventPlayerDeath.gml in Gang Garrison 2
|
||||
|
||||
Copyright (C) 2008-2013 Faucet Software
|
||||
http://www.ganggarrison.com
|
||||
|
||||
This program is free software;
|
||||
you can redistribute it and/or modify it under the terms of the GNU General Public License
|
||||
as published by the Free Software Foundation; either version 3 of the License, or (at your option)
|
||||
any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License along with this program; if not,
|
||||
see <http://www.gnu.org/licenses>.
|
||||
|
||||
Additional permission under GNU GPL version 3 section 7
|
||||
If you modify this Program, or any covered work, by linking or combining it with the Game Maker runtime library,
|
||||
the 39dll library/extension, Hobbel's Download Manager DLL, or modified versions of these libraries,
|
||||
the licensors of this Program grant you additional permission to convey the resulting work.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Perform the "player death" event, i.e. change the appropriate scores,
|
||||
* destroy the character object to much splattering and so on.
|
||||
*
|
||||
* argument0: The player whose character died
|
||||
* argument1: The player who inflicted the fatal damage (or noone for unknown)
|
||||
* argument2: The player who assisted the kill (or noone for no assist)
|
||||
* argument3: The source of the fatal damage
|
||||
*/
|
||||
var victim, killer, assistant, damageSource;
|
||||
victim = argument0;
|
||||
killer = argument1;
|
||||
assistant = argument2;
|
||||
damageSource = argument3;
|
||||
|
||||
if(!instance_exists(killer))
|
||||
killer = noone;
|
||||
|
||||
if(!instance_exists(assistant))
|
||||
assistant = noone;
|
||||
|
||||
//*************************************
|
||||
//* Scoring and Kill log
|
||||
//*************************************
|
||||
|
||||
|
||||
recordKillInLog(victim, killer, assistant, damageSource);
|
||||
|
||||
victim.stats[DEATHS] += 1;
|
||||
if(killer)
|
||||
{
|
||||
if(damageSource == WEAPON_KNIFE || damageSource == WEAPON_BACKSTAB)
|
||||
{
|
||||
killer.stats[STABS] += 1;
|
||||
killer.roundStats[STABS] += 1;
|
||||
killer.stats[POINTS] += 1;
|
||||
killer.roundStats[POINTS] +=1;
|
||||
}
|
||||
|
||||
if (victim.object.currentWeapon.object_index == Medigun)
|
||||
{
|
||||
if (victim.object.currentWeapon.uberReady)
|
||||
{
|
||||
killer.stats[BONUS] += 1;
|
||||
killer.roundStats[BONUS] += 1;
|
||||
killer.stats[POINTS] += 1;
|
||||
killer.roundStats[POINTS] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (killer != victim)
|
||||
{
|
||||
killer.stats[KILLS] += 1;
|
||||
killer.roundStats[KILLS] += 1;
|
||||
killer.stats[POINTS] += 1;
|
||||
killer.roundStats[POINTS] += 1;
|
||||
if(victim.object.intel)
|
||||
{
|
||||
killer.stats[DEFENSES] += 1;
|
||||
killer.roundStats[DEFENSES] += 1;
|
||||
killer.stats[POINTS] += 1;
|
||||
killer.roundStats[POINTS] += 1;
|
||||
recordEventInLog(4, killer.team, killer.name, global.myself == killer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (assistant)
|
||||
{
|
||||
assistant.stats[ASSISTS] += 1;
|
||||
assistant.roundStats[ASSISTS] += 1;
|
||||
assistant.stats[POINTS] += .5;
|
||||
assistant.roundStats[POINTS] += .5;
|
||||
}
|
||||
|
||||
//SPEC
|
||||
if (victim == global.myself)
|
||||
instance_create(victim.object.x, victim.object.y, Spectator);
|
||||
|
||||
//*************************************
|
||||
//* Gibbing
|
||||
//*************************************
|
||||
var xoffset, yoffset, xsize, ysize;
|
||||
|
||||
xoffset = view_xview[0];
|
||||
yoffset = view_yview[0];
|
||||
xsize = view_wview[0];
|
||||
ysize = view_hview[0];
|
||||
|
||||
randomize();
|
||||
with(victim.object) {
|
||||
if((damageSource == WEAPON_ROCKETLAUNCHER
|
||||
or damageSource == WEAPON_MINEGUN or damageSource == FRAG_BOX
|
||||
or damageSource == WEAPON_REFLECTED_STICKY or damageSource == WEAPON_REFLECTED_ROCKET
|
||||
or damageSource == FINISHED_OFF_GIB or damageSource == GENERATOR_EXPLOSION)
|
||||
and (player.class != CLASS_QUOTE) and (global.gibLevel>1)
|
||||
and distance_to_point(xoffset+xsize/2,yoffset+ysize/2) < 900) {
|
||||
if (hasReward(victim, 'PumpkinGibs'))
|
||||
{
|
||||
repeat(global.gibLevel * 2) {
|
||||
createGib(x,y,PumpkinGib,hspeed,vspeed,random(145)-72, choose(0,1,1,2,2,3), false, true)
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
repeat(global.gibLevel) {
|
||||
createGib(x,y,Gib,hspeed,vspeed,random(145)-72, 0, false)
|
||||
}
|
||||
switch(player.team)
|
||||
{
|
||||
case TEAM_BLUE :
|
||||
repeat(global.gibLevel - 1) {
|
||||
createGib(x,y,BlueClump,hspeed,vspeed,random(145)-72, 0, false)
|
||||
}
|
||||
break;
|
||||
case TEAM_RED :
|
||||
repeat(global.gibLevel - 1) {
|
||||
createGib(x,y,RedClump,hspeed,vspeed,random(145)-72, 0, false)
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
repeat(global.gibLevel * 14) {
|
||||
var blood;
|
||||
blood = instance_create(x+random(23)-11,y+random(23)-11,BloodDrop);
|
||||
blood.hspeed=(random(21)-10);
|
||||
blood.vspeed=(random(21)-13);
|
||||
if (hasReward(victim, 'PumpkinGibs'))
|
||||
{
|
||||
blood.sprite_index = PumpkinJuiceS;
|
||||
}
|
||||
}
|
||||
if (!hasReward(victim, 'PumpkinGibs'))
|
||||
{
|
||||
//All Classes gib head, hands, and feet
|
||||
if(global.gibLevel > 2 || choose(0,1) == 1)
|
||||
createGib(x,y,Headgib,0,0,random(105)-52, player.class, false);
|
||||
repeat(global.gibLevel -1){
|
||||
//Medic has specially colored hands
|
||||
if (player.class == CLASS_MEDIC){
|
||||
if (player.team == TEAM_RED)
|
||||
createGib(x,y,Hand, hspeed, vspeed, random(105)-52 , 9, false);
|
||||
else
|
||||
createGib(x,y,Hand, hspeed, vspeed, random(105)-52 , 10, false);
|
||||
}else{
|
||||
createGib(x,y,Hand, hspeed, vspeed, random(105)-52 , player.class, false);
|
||||
}
|
||||
createGib(x,y,Feet,random(5)-2,random(3),random(13)-6 , player.class, true);
|
||||
}
|
||||
}
|
||||
|
||||
//Class specific gibs
|
||||
switch(player.class) {
|
||||
case CLASS_PYRO :
|
||||
if(global.gibLevel > 2 || choose(0,1) == 1)
|
||||
createGib(x,y,Accesory,hspeed,vspeed,random(105)-52, 4, false)
|
||||
break;
|
||||
case CLASS_SOLDIER :
|
||||
if(global.gibLevel > 2 || choose(0,1) == 1){
|
||||
switch(player.team) {
|
||||
case TEAM_BLUE :
|
||||
createGib(x,y,Accesory,hspeed,vspeed,random(105)-52, 2, false);
|
||||
break;
|
||||
case TEAM_RED :
|
||||
createGib(x,y,Accesory,hspeed,vspeed,random(105)-52, 1, false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case CLASS_ENGINEER :
|
||||
if(global.gibLevel > 2 || choose(0,1) == 1)
|
||||
createGib(x,y,Accesory,hspeed,vspeed,random(105)-52, 3, false)
|
||||
break;
|
||||
case CLASS_SNIPER :
|
||||
if(global.gibLevel > 2 || choose(0,1) == 1)
|
||||
createGib(x,y,Accesory,hspeed,vspeed,random(105)-52, 0, false)
|
||||
break;
|
||||
}
|
||||
playsound(x,y,Gibbing);
|
||||
} else {
|
||||
var deadbody;
|
||||
if player.class != CLASS_QUOTE playsound(x,y,choose(DeathSnd1, DeathSnd2));
|
||||
deadbody = instance_create(x,y-30,DeadGuy);
|
||||
// 'GS' reward - *G*olden *S*tatue
|
||||
if(hasReward(player, 'GS'))
|
||||
{
|
||||
deadbody.sprite_index = haxxyStatue;
|
||||
deadbody.image_index = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
deadbody.sprite_index = sprite_index;
|
||||
deadbody.image_index = CHARACTER_ANIMATION_DEAD;
|
||||
}
|
||||
deadbody.hspeed=hspeed;
|
||||
deadbody.vspeed=vspeed;
|
||||
if(hspeed>0) {
|
||||
deadbody.image_xscale = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (global.gg_birthday){
|
||||
myHat = instance_create(victim.object.x,victim.object.y,PartyHat);
|
||||
myHat.image_index = victim.team;
|
||||
}
|
||||
if (global.xmas){
|
||||
myHat = instance_create(victim.object.x,victim.object.y,XmasHat);
|
||||
myHat.image_index = victim.team;
|
||||
}
|
||||
|
||||
|
||||
with(victim.object) {
|
||||
instance_destroy();
|
||||
}
|
||||
|
||||
//*************************************
|
||||
//* Deathcam
|
||||
//*************************************
|
||||
if( global.killCam and victim == global.myself and killer and killer != victim and !(damageSource == KILL_BOX || damageSource == FRAG_BOX || damageSource == FINISHED_OFF || damageSource == FINISHED_OFF_GIB || damageSource == GENERATOR_EXPLOSION)) {
|
||||
instance_create(0,0,DeathCam);
|
||||
DeathCam.killedby=killer;
|
||||
DeathCam.name=killer.name;
|
||||
DeathCam.oldxview=view_xview[0];
|
||||
DeathCam.oldyview=view_yview[0];
|
||||
DeathCam.lastDamageSource=damageSource;
|
||||
DeathCam.team = global.myself.team;
|
||||
}
|
||||
1469
samples/Game Maker Language/faucet-http.gml
Normal file
1469
samples/Game Maker Language/faucet-http.gml
Normal file
File diff suppressed because it is too large
Load Diff
484
samples/Game Maker Language/game_init.gml
Normal file
484
samples/Game Maker Language/game_init.gml
Normal file
@@ -0,0 +1,484 @@
|
||||
/*
|
||||
Originally from /Source/gg2/Scripts/game_init.gml in Gang Garrison 2
|
||||
|
||||
Copyright (C) 2008-2013 Faucet Software
|
||||
http://www.ganggarrison.com
|
||||
|
||||
This program is free software;
|
||||
you can redistribute it and/or modify it under the terms of the GNU General Public License
|
||||
as published by the Free Software Foundation; either version 3 of the License, or (at your option)
|
||||
any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License along with this program; if not,
|
||||
see <http://www.gnu.org/licenses>.
|
||||
|
||||
Additional permission under GNU GPL version 3 section 7
|
||||
If you modify this Program, or any covered work, by linking or combining it with the Game Maker runtime library,
|
||||
the 39dll library/extension, Hobbel's Download Manager DLL, or modified versions of these libraries,
|
||||
the licensors of this Program grant you additional permission to convey the resulting work.
|
||||
*/
|
||||
|
||||
// Returns true if the game is successfully initialized, false if there was an error and we should quit.
|
||||
{
|
||||
instance_create(0,0,RoomChangeObserver);
|
||||
set_little_endian_global(true);
|
||||
if file_exists("game_errors.log") file_delete("game_errors.log");
|
||||
if file_exists("last_plugin.log") file_delete("last_plugin.log");
|
||||
|
||||
// Delete old left-over files created by the updater
|
||||
var backupFilename;
|
||||
backupFilename = file_find_first("gg2-old.delete.me.*", 0);
|
||||
while(backupFilename != "")
|
||||
{
|
||||
file_delete(backupFilename);
|
||||
backupFilename = file_find_next();
|
||||
}
|
||||
file_find_close();
|
||||
|
||||
var customMapRotationFile, restart;
|
||||
restart = false;
|
||||
|
||||
//import wav files for music
|
||||
global.MenuMusic=sound_add(choose("Music/menumusic1.wav","Music/menumusic2.wav","Music/menumusic3.wav","Music/menumusic4.wav","Music/menumusic5.wav","Music/menumusic6.wav"), 1, true);
|
||||
global.IngameMusic=sound_add("Music/ingamemusic.wav", 1, true);
|
||||
global.FaucetMusic=sound_add("Music/faucetmusic.wav", 1, true);
|
||||
if(global.MenuMusic != -1)
|
||||
sound_volume(global.MenuMusic, 0.8);
|
||||
if(global.IngameMusic != -1)
|
||||
sound_volume(global.IngameMusic, 0.8);
|
||||
if(global.FaucetMusic != -1)
|
||||
sound_volume(global.FaucetMusic, 0.8);
|
||||
|
||||
global.sendBuffer = buffer_create();
|
||||
global.tempBuffer = buffer_create();
|
||||
global.HudCheck = false;
|
||||
global.map_rotation = ds_list_create();
|
||||
|
||||
global.CustomMapCollisionSprite = -1;
|
||||
|
||||
window_set_region_scale(-1, false);
|
||||
|
||||
ini_open("gg2.ini");
|
||||
global.playerName = ini_read_string("Settings", "PlayerName", "Player");
|
||||
if string_count("#",global.playerName) > 0 global.playerName = "Player";
|
||||
global.playerName = string_copy(global.playerName, 0, min(string_length(global.playerName), MAX_PLAYERNAME_LENGTH));
|
||||
global.fullscreen = ini_read_real("Settings", "Fullscreen", 0);
|
||||
global.useLobbyServer = ini_read_real("Settings", "UseLobby", 1);
|
||||
global.hostingPort = ini_read_real("Settings", "HostingPort", 8190);
|
||||
global.music = ini_read_real("Settings", "Music", ini_read_real("Settings", "IngameMusic", MUSIC_BOTH));
|
||||
global.playerLimit = ini_read_real("Settings", "PlayerLimit", 10);
|
||||
//thy playerlimit shalt not exceed 48!
|
||||
if (global.playerLimit > 48)
|
||||
{
|
||||
if (global.dedicatedMode != 1)
|
||||
show_message("Warning: Player Limit cannot exceed 48. It has been set to 48");
|
||||
global.playerLimit = 48;
|
||||
ini_write_real("Settings", "PlayerLimit", 48);
|
||||
}
|
||||
global.multiClientLimit = ini_read_real("Settings", "MultiClientLimit", 3);
|
||||
global.particles = ini_read_real("Settings", "Particles", PARTICLES_NORMAL);
|
||||
global.gibLevel = ini_read_real("Settings", "Gib Level", 3);
|
||||
global.killCam = ini_read_real("Settings", "Kill Cam", 1);
|
||||
global.monitorSync = ini_read_real("Settings", "Monitor Sync", 0);
|
||||
if global.monitorSync == 1 set_synchronization(true);
|
||||
else set_synchronization(false);
|
||||
global.medicRadar = ini_read_real("Settings", "Healer Radar", 1);
|
||||
global.showHealer = ini_read_real("Settings", "Show Healer", 1);
|
||||
global.showHealing = ini_read_real("Settings", "Show Healing", 1);
|
||||
global.showHealthBar = ini_read_real("Settings", "Show Healthbar", 0);
|
||||
global.showTeammateStats = ini_read_real("Settings", "Show Extra Teammate Stats", 0);
|
||||
global.serverPluginsPrompt = ini_read_real("Settings", "ServerPluginsPrompt", 1);
|
||||
global.restartPrompt = ini_read_real("Settings", "RestartPrompt", 1);
|
||||
//user HUD settings
|
||||
global.timerPos=ini_read_real("Settings","Timer Position", 0)
|
||||
global.killLogPos=ini_read_real("Settings","Kill Log Position", 0)
|
||||
global.kothHudPos=ini_read_real("Settings","KoTH HUD Position", 0)
|
||||
global.clientPassword = "";
|
||||
// for admin menu
|
||||
customMapRotationFile = ini_read_string("Server", "MapRotation", "");
|
||||
global.shuffleRotation = ini_read_real("Server", "ShuffleRotation", 1);
|
||||
global.timeLimitMins = max(1, min(255, ini_read_real("Server", "Time Limit", 15)));
|
||||
global.serverPassword = ini_read_string("Server", "Password", "");
|
||||
global.mapRotationFile = customMapRotationFile;
|
||||
global.dedicatedMode = ini_read_real("Server", "Dedicated", 0);
|
||||
global.serverName = ini_read_string("Server", "ServerName", "My Server");
|
||||
global.welcomeMessage = ini_read_string("Server", "WelcomeMessage", "");
|
||||
global.caplimit = max(1, min(255, ini_read_real("Server", "CapLimit", 5)));
|
||||
global.caplimitBkup = global.caplimit;
|
||||
global.autobalance = ini_read_real("Server", "AutoBalance",1);
|
||||
global.Server_RespawntimeSec = ini_read_real("Server", "Respawn Time", 5);
|
||||
global.rewardKey = unhex(ini_read_string("Haxxy", "RewardKey", ""));
|
||||
global.rewardId = ini_read_string("Haxxy", "RewardId", "");
|
||||
global.mapdownloadLimitBps = ini_read_real("Server", "Total bandwidth limit for map downloads in bytes per second", 50000);
|
||||
global.updaterBetaChannel = ini_read_real("General", "UpdaterBetaChannel", isBetaVersion());
|
||||
global.attemptPortForward = ini_read_real("Server", "Attempt UPnP Forwarding", 0);
|
||||
global.serverPluginList = ini_read_string("Server", "ServerPluginList", "");
|
||||
global.serverPluginsRequired = ini_read_real("Server", "ServerPluginsRequired", 0);
|
||||
if (string_length(global.serverPluginList) > 254) {
|
||||
show_message("Error: Server plugin list cannot exceed 254 characters");
|
||||
return false;
|
||||
}
|
||||
var CrosshairFilename, CrosshairRemoveBG;
|
||||
CrosshairFilename = ini_read_string("Settings", "CrosshairFilename", "");
|
||||
CrosshairRemoveBG = ini_read_real("Settings", "CrosshairRemoveBG", 1);
|
||||
global.queueJumping = ini_read_real("Settings", "Queued Jumping", 0);
|
||||
|
||||
global.backgroundHash = ini_read_string("Background", "BackgroundHash", "default");
|
||||
global.backgroundTitle = ini_read_string("Background", "BackgroundTitle", "");
|
||||
global.backgroundURL = ini_read_string("Background", "BackgroundURL", "");
|
||||
global.backgroundShowVersion = ini_read_real("Background", "BackgroundShowVersion", true);
|
||||
|
||||
readClasslimitsFromIni();
|
||||
|
||||
global.currentMapArea=1;
|
||||
global.totalMapAreas=1;
|
||||
global.setupTimer=1800;
|
||||
global.joinedServerName="";
|
||||
global.serverPluginsInUse=false;
|
||||
// Create plugin packet maps
|
||||
global.pluginPacketBuffers = ds_map_create();
|
||||
global.pluginPacketPlayers = ds_map_create();
|
||||
|
||||
ini_write_string("Settings", "PlayerName", global.playerName);
|
||||
ini_write_real("Settings", "Fullscreen", global.fullscreen);
|
||||
ini_write_real("Settings", "UseLobby", global.useLobbyServer);
|
||||
ini_write_real("Settings", "HostingPort", global.hostingPort);
|
||||
ini_key_delete("Settings", "IngameMusic");
|
||||
ini_write_real("Settings", "Music", global.music);
|
||||
ini_write_real("Settings", "PlayerLimit", global.playerLimit);
|
||||
ini_write_real("Settings", "MultiClientLimit", global.multiClientLimit);
|
||||
ini_write_real("Settings", "Particles", global.particles);
|
||||
ini_write_real("Settings", "Gib Level", global.gibLevel);
|
||||
ini_write_real("Settings", "Kill Cam", global.killCam);
|
||||
ini_write_real("Settings", "Monitor Sync", global.monitorSync);
|
||||
ini_write_real("Settings", "Healer Radar", global.medicRadar);
|
||||
ini_write_real("Settings", "Show Healer", global.showHealer);
|
||||
ini_write_real("Settings", "Show Healing", global.showHealing);
|
||||
ini_write_real("Settings", "Show Healthbar", global.showHealthBar);
|
||||
ini_write_real("Settings", "Show Extra Teammate Stats", global.showTeammateStats);
|
||||
ini_write_real("Settings", "Timer Position", global.timerPos);
|
||||
ini_write_real("Settings", "Kill Log Position", global.killLogPos);
|
||||
ini_write_real("Settings", "KoTH HUD Position", global.kothHudPos);
|
||||
ini_write_real("Settings", "ServerPluginsPrompt", global.serverPluginsPrompt);
|
||||
ini_write_real("Settings", "RestartPrompt", global.restartPrompt);
|
||||
ini_write_string("Server", "MapRotation", customMapRotationFile);
|
||||
ini_write_real("Server", "ShuffleRotation", global.shuffleRotation);
|
||||
ini_write_real("Server", "Dedicated", global.dedicatedMode);
|
||||
ini_write_string("Server", "ServerName", global.serverName);
|
||||
ini_write_string("Server", "WelcomeMessage", global.welcomeMessage);
|
||||
ini_write_real("Server", "CapLimit", global.caplimit);
|
||||
ini_write_real("Server", "AutoBalance", global.autobalance);
|
||||
ini_write_real("Server", "Respawn Time", global.Server_RespawntimeSec);
|
||||
ini_write_real("Server", "Total bandwidth limit for map downloads in bytes per second", global.mapdownloadLimitBps);
|
||||
ini_write_real("Server", "Time Limit", global.timeLimitMins);
|
||||
ini_write_string("Server", "Password", global.serverPassword);
|
||||
ini_write_real("General", "UpdaterBetaChannel", global.updaterBetaChannel);
|
||||
ini_write_real("Server", "Attempt UPnP Forwarding", global.attemptPortForward);
|
||||
ini_write_string("Server", "ServerPluginList", global.serverPluginList);
|
||||
ini_write_real("Server", "ServerPluginsRequired", global.serverPluginsRequired);
|
||||
ini_write_string("Settings", "CrosshairFilename", CrosshairFilename);
|
||||
ini_write_real("Settings", "CrosshairRemoveBG", CrosshairRemoveBG);
|
||||
ini_write_real("Settings", "Queued Jumping", global.queueJumping);
|
||||
|
||||
ini_write_string("Background", "BackgroundHash", global.backgroundHash);
|
||||
ini_write_string("Background", "BackgroundTitle", global.backgroundTitle);
|
||||
ini_write_string("Background", "BackgroundURL", global.backgroundURL);
|
||||
ini_write_real("Background", "BackgroundShowVersion", global.backgroundShowVersion);
|
||||
|
||||
ini_write_real("Classlimits", "Scout", global.classlimits[CLASS_SCOUT])
|
||||
ini_write_real("Classlimits", "Pyro", global.classlimits[CLASS_PYRO])
|
||||
ini_write_real("Classlimits", "Soldier", global.classlimits[CLASS_SOLDIER])
|
||||
ini_write_real("Classlimits", "Heavy", global.classlimits[CLASS_HEAVY])
|
||||
ini_write_real("Classlimits", "Demoman", global.classlimits[CLASS_DEMOMAN])
|
||||
ini_write_real("Classlimits", "Medic", global.classlimits[CLASS_MEDIC])
|
||||
ini_write_real("Classlimits", "Engineer", global.classlimits[CLASS_ENGINEER])
|
||||
ini_write_real("Classlimits", "Spy", global.classlimits[CLASS_SPY])
|
||||
ini_write_real("Classlimits", "Sniper", global.classlimits[CLASS_SNIPER])
|
||||
ini_write_real("Classlimits", "Quote", global.classlimits[CLASS_QUOTE])
|
||||
|
||||
//screw the 0 index we will start with 1
|
||||
//map_truefort
|
||||
maps[1] = ini_read_real("Maps", "ctf_truefort", 1);
|
||||
//map_2dfort
|
||||
maps[2] = ini_read_real("Maps", "ctf_2dfort", 2);
|
||||
//map_conflict
|
||||
maps[3] = ini_read_real("Maps", "ctf_conflict", 3);
|
||||
//map_classicwell
|
||||
maps[4] = ini_read_real("Maps", "ctf_classicwell", 4);
|
||||
//map_waterway
|
||||
maps[5] = ini_read_real("Maps", "ctf_waterway", 5);
|
||||
//map_orange
|
||||
maps[6] = ini_read_real("Maps", "ctf_orange", 6);
|
||||
//map_dirtbowl
|
||||
maps[7] = ini_read_real("Maps", "cp_dirtbowl", 7);
|
||||
//map_egypt
|
||||
maps[8] = ini_read_real("Maps", "cp_egypt", 8);
|
||||
//arena_montane
|
||||
maps[9] = ini_read_real("Maps", "arena_montane", 9);
|
||||
//arena_lumberyard
|
||||
maps[10] = ini_read_real("Maps", "arena_lumberyard", 10);
|
||||
//gen_destroy
|
||||
maps[11] = ini_read_real("Maps", "gen_destroy", 11);
|
||||
//koth_valley
|
||||
maps[12] = ini_read_real("Maps", "koth_valley", 12);
|
||||
//koth_corinth
|
||||
maps[13] = ini_read_real("Maps", "koth_corinth", 13);
|
||||
//koth_harvest
|
||||
maps[14] = ini_read_real("Maps", "koth_harvest", 14);
|
||||
//dkoth_atalia
|
||||
maps[15] = ini_read_real("Maps", "dkoth_atalia", 15);
|
||||
//dkoth_sixties
|
||||
maps[16] = ini_read_real("Maps", "dkoth_sixties", 16);
|
||||
|
||||
//Server respawn time calculator. Converts each second to a frame. (read: multiply by 30 :hehe:)
|
||||
if (global.Server_RespawntimeSec == 0)
|
||||
{
|
||||
global.Server_Respawntime = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
global.Server_Respawntime = global.Server_RespawntimeSec * 30;
|
||||
}
|
||||
|
||||
// I have to include this, or the client'll complain about an unknown variable.
|
||||
global.mapchanging = false;
|
||||
|
||||
ini_write_real("Maps", "ctf_truefort", maps[1]);
|
||||
ini_write_real("Maps", "ctf_2dfort", maps[2]);
|
||||
ini_write_real("Maps", "ctf_conflict", maps[3]);
|
||||
ini_write_real("Maps", "ctf_classicwell", maps[4]);
|
||||
ini_write_real("Maps", "ctf_waterway", maps[5]);
|
||||
ini_write_real("Maps", "ctf_orange", maps[6]);
|
||||
ini_write_real("Maps", "cp_dirtbowl", maps[7]);
|
||||
ini_write_real("Maps", "cp_egypt", maps[8]);
|
||||
ini_write_real("Maps", "arena_montane", maps[9]);
|
||||
ini_write_real("Maps", "arena_lumberyard", maps[10]);
|
||||
ini_write_real("Maps", "gen_destroy", maps[11]);
|
||||
ini_write_real("Maps", "koth_valley", maps[12]);
|
||||
ini_write_real("Maps", "koth_corinth", maps[13]);
|
||||
ini_write_real("Maps", "koth_harvest", maps[14]);
|
||||
ini_write_real("Maps", "dkoth_atalia", maps[15]);
|
||||
ini_write_real("Maps", "dkoth_sixties", maps[16]);
|
||||
|
||||
ini_close();
|
||||
|
||||
// parse the protocol version UUID for later use
|
||||
global.protocolUuid = buffer_create();
|
||||
parseUuid(PROTOCOL_UUID, global.protocolUuid);
|
||||
|
||||
global.gg2lobbyId = buffer_create();
|
||||
parseUuid(GG2_LOBBY_UUID, global.gg2lobbyId);
|
||||
|
||||
// Create abbreviations array for rewards use
|
||||
initRewards()
|
||||
|
||||
var a, IPRaw, portRaw;
|
||||
doubleCheck=0;
|
||||
global.launchMap = "";
|
||||
|
||||
for(a = 1; a <= parameter_count(); a += 1)
|
||||
{
|
||||
if (parameter_string(a) == "-dedicated")
|
||||
{
|
||||
global.dedicatedMode = 1;
|
||||
}
|
||||
else if (parameter_string(a) == "-restart")
|
||||
{
|
||||
restart = true;
|
||||
}
|
||||
else if (parameter_string(a) == "-server")
|
||||
{
|
||||
IPRaw = parameter_string(a+1);
|
||||
if (doubleCheck == 1)
|
||||
{
|
||||
doubleCheck = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
doubleCheck = 1;
|
||||
}
|
||||
}
|
||||
else if (parameter_string(a) == "-port")
|
||||
{
|
||||
portRaw = parameter_string(a+1);
|
||||
if (doubleCheck == 1)
|
||||
{
|
||||
doubleCheck = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
doubleCheck = 1;
|
||||
}
|
||||
}
|
||||
else if (parameter_string(a) == "-map")
|
||||
{
|
||||
global.launchMap = parameter_string(a+1);
|
||||
global.dedicatedMode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (doubleCheck == 2)
|
||||
{
|
||||
global.serverPort = real(portRaw);
|
||||
global.serverIP = IPRaw;
|
||||
global.isHost = false;
|
||||
instance_create(0,0,Client);
|
||||
}
|
||||
|
||||
global.customMapdesginated = 0;
|
||||
|
||||
// if the user defined a valid map rotation file, then load from there
|
||||
|
||||
if(customMapRotationFile != "" && file_exists(customMapRotationFile) && global.launchMap == "") {
|
||||
global.customMapdesginated = 1;
|
||||
var fileHandle, i, mapname;
|
||||
fileHandle = file_text_open_read(customMapRotationFile);
|
||||
for(i = 1; !file_text_eof(fileHandle); i += 1) {
|
||||
mapname = file_text_read_string(fileHandle);
|
||||
// remove leading whitespace from the string
|
||||
while(string_char_at(mapname, 0) == " " || string_char_at(mapname, 0) == chr(9)) { // while it starts with a space or tab
|
||||
mapname = string_delete(mapname, 0, 1); // delete that space or tab
|
||||
}
|
||||
if(mapname != "" && string_char_at(mapname, 0) != "#") { // if it's not blank and it's not a comment (starting with #)
|
||||
ds_list_add(global.map_rotation, mapname);
|
||||
}
|
||||
file_text_readln(fileHandle);
|
||||
}
|
||||
file_text_close(fileHandle);
|
||||
}
|
||||
|
||||
else if (global.launchMap != "") && (global.dedicatedMode == 1)
|
||||
{
|
||||
ds_list_add(global.map_rotation, global.launchMap);
|
||||
}
|
||||
|
||||
else { // else load from the ini file Maps section
|
||||
//Set up the map rotation stuff
|
||||
var i, sort_list;
|
||||
sort_list = ds_list_create();
|
||||
for(i=1; i <= 16; i += 1) {
|
||||
if(maps[i] != 0) ds_list_add(sort_list, ((100*maps[i])+i));
|
||||
}
|
||||
ds_list_sort(sort_list, 1);
|
||||
|
||||
// translate the numbers back into the names they represent
|
||||
for(i=0; i < ds_list_size(sort_list); i += 1) {
|
||||
switch(ds_list_find_value(sort_list, i) mod 100) {
|
||||
case 1:
|
||||
ds_list_add(global.map_rotation, "ctf_truefort");
|
||||
break;
|
||||
case 2:
|
||||
ds_list_add(global.map_rotation, "ctf_2dfort");
|
||||
break;
|
||||
case 3:
|
||||
ds_list_add(global.map_rotation, "ctf_conflict");
|
||||
break;
|
||||
case 4:
|
||||
ds_list_add(global.map_rotation, "ctf_classicwell");
|
||||
break;
|
||||
case 5:
|
||||
ds_list_add(global.map_rotation, "ctf_waterway");
|
||||
break;
|
||||
case 6:
|
||||
ds_list_add(global.map_rotation, "ctf_orange");
|
||||
break;
|
||||
case 7:
|
||||
ds_list_add(global.map_rotation, "cp_dirtbowl");
|
||||
break;
|
||||
case 8:
|
||||
ds_list_add(global.map_rotation, "cp_egypt");
|
||||
break;
|
||||
case 9:
|
||||
ds_list_add(global.map_rotation, "arena_montane");
|
||||
break;
|
||||
case 10:
|
||||
ds_list_add(global.map_rotation, "arena_lumberyard");
|
||||
break;
|
||||
case 11:
|
||||
ds_list_add(global.map_rotation, "gen_destroy");
|
||||
break;
|
||||
case 12:
|
||||
ds_list_add(global.map_rotation, "koth_valley");
|
||||
break;
|
||||
case 13:
|
||||
ds_list_add(global.map_rotation, "koth_corinth");
|
||||
break;
|
||||
case 14:
|
||||
ds_list_add(global.map_rotation, "koth_harvest");
|
||||
break;
|
||||
case 15:
|
||||
ds_list_add(global.map_rotation, "dkoth_atalia");
|
||||
break;
|
||||
case 16:
|
||||
ds_list_add(global.map_rotation, "dkoth_sixties");
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
ds_list_destroy(sort_list);
|
||||
}
|
||||
|
||||
window_set_fullscreen(global.fullscreen);
|
||||
|
||||
global.gg2Font = font_add_sprite(gg2FontS,ord("!"),false,0);
|
||||
global.countFont = font_add_sprite(countFontS, ord("0"),false,2);
|
||||
draw_set_font(global.gg2Font);
|
||||
cursor_sprite = CrosshairS;
|
||||
|
||||
if(!directory_exists(working_directory + "\Maps")) directory_create(working_directory + "\Maps");
|
||||
|
||||
instance_create(0, 0, AudioControl);
|
||||
instance_create(0, 0, SSControl);
|
||||
|
||||
// custom dialog box graphics
|
||||
message_background(popupBackgroundB);
|
||||
message_button(popupButtonS);
|
||||
message_text_font("Century",9,c_white,1);
|
||||
message_button_font("Century",9,c_white,1);
|
||||
message_input_font("Century",9,c_white,0);
|
||||
|
||||
//Key Mapping
|
||||
ini_open("controls.gg2");
|
||||
global.jump = ini_read_real("Controls", "jump", ord("W"));
|
||||
global.down = ini_read_real("Controls", "down", ord("S"));
|
||||
global.left = ini_read_real("Controls", "left", ord("A"));
|
||||
global.right = ini_read_real("Controls", "right", ord("D"));
|
||||
global.attack = ini_read_real("Controls", "attack", MOUSE_LEFT);
|
||||
global.special = ini_read_real("Controls", "special", MOUSE_RIGHT);
|
||||
global.taunt = ini_read_real("Controls", "taunt", ord("F"));
|
||||
global.chat1 = ini_read_real("Controls", "chat1", ord("Z"));
|
||||
global.chat2 = ini_read_real("Controls", "chat2", ord("X"));
|
||||
global.chat3 = ini_read_real("Controls", "chat3", ord("C"));
|
||||
global.medic = ini_read_real("Controls", "medic", ord("E"));
|
||||
global.drop = ini_read_real("Controls", "drop", ord("B"));
|
||||
global.changeTeam = ini_read_real("Controls", "changeTeam", ord("N"));
|
||||
global.changeClass = ini_read_real("Controls", "changeClass", ord("M"));
|
||||
global.showScores = ini_read_real("Controls", "showScores", vk_shift);
|
||||
ini_close();
|
||||
|
||||
calculateMonthAndDay();
|
||||
|
||||
if(!directory_exists(working_directory + "\Plugins")) directory_create(working_directory + "\Plugins");
|
||||
loadplugins();
|
||||
|
||||
/* Windows 8 is known to crash GM when more than three (?) sounds play at once
|
||||
* We'll store the kernel version (Win8 is 6.2, Win7 is 6.1) and check it there.
|
||||
***/
|
||||
registry_set_root(1); // HKLM
|
||||
global.NTKernelVersion = real(registry_read_string_ext("\SOFTWARE\Microsoft\Windows NT\CurrentVersion\", "CurrentVersion")); // SIC
|
||||
|
||||
if (file_exists(CrosshairFilename))
|
||||
{
|
||||
sprite_replace(CrosshairS,CrosshairFilename,1,CrosshairRemoveBG,false,0,0);
|
||||
sprite_set_offset(CrosshairS,sprite_get_width(CrosshairS)/2,sprite_get_height(CrosshairS)/2);
|
||||
}
|
||||
if(global.dedicatedMode == 1) {
|
||||
AudioControlToggleMute();
|
||||
room_goto_fix(Menu);
|
||||
} else if(restart) {
|
||||
room_goto_fix(Menu);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
1861
samples/Game Maker Language/jsonion.gml
Normal file
1861
samples/Game Maker Language/jsonion.gml
Normal file
File diff suppressed because it is too large
Load Diff
1169
samples/Game Maker Language/jsonion_test.gml
Normal file
1169
samples/Game Maker Language/jsonion_test.gml
Normal file
File diff suppressed because it is too large
Load Diff
252
samples/Game Maker Language/loadserverplugins.gml
Normal file
252
samples/Game Maker Language/loadserverplugins.gml
Normal file
@@ -0,0 +1,252 @@
|
||||
/*
|
||||
Originally from /Source/gg2/Scripts/Plugins/loadserverplugins.gml in Gang Garrison 2
|
||||
|
||||
Copyright (C) 2008-2013 Faucet Software
|
||||
http://www.ganggarrison.com
|
||||
|
||||
This program is free software;
|
||||
you can redistribute it and/or modify it under the terms of the GNU General Public License
|
||||
as published by the Free Software Foundation; either version 3 of the License, or (at your option)
|
||||
any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License along with this program; if not,
|
||||
see <http://www.gnu.org/licenses>.
|
||||
|
||||
Additional permission under GNU GPL version 3 section 7
|
||||
If you modify this Program, or any covered work, by linking or combining it with the Game Maker runtime library,
|
||||
the 39dll library/extension, Hobbel's Download Manager DLL, or modified versions of these libraries,
|
||||
the licensors of this Program grant you additional permission to convey the resulting work.
|
||||
*/
|
||||
|
||||
// loads plugins from ganggarrison.com asked for by server
|
||||
// argument0 - comma separated plugin list (pluginname@md5hash)
|
||||
// returns true on success, false on failure
|
||||
var list, hashList, text, i, pluginname, pluginhash, realhash, url, handle, filesize, progress, tempfile, tempdir, failed, lastContact, isCached;
|
||||
|
||||
failed = false;
|
||||
list = ds_list_create();
|
||||
lastContact = 0;
|
||||
isCached = false;
|
||||
isDebug = false;
|
||||
hashList = ds_list_create();
|
||||
|
||||
// split plugin list string
|
||||
list = split(argument0, ',');
|
||||
|
||||
// Split hashes from plugin names
|
||||
for (i = 0; i < ds_list_size(list); i += 1)
|
||||
{
|
||||
text = ds_list_find_value(list, i);
|
||||
pluginname = string_copy(text, 0, string_pos("@", text) - 1);
|
||||
pluginhash = string_copy(text, string_pos("@", text) + 1, string_length(text) - string_pos("@", text));
|
||||
ds_list_replace(list, i, pluginname);
|
||||
ds_list_add(hashList, pluginhash);
|
||||
}
|
||||
|
||||
// Check plugin names and check for duplicates
|
||||
for (i = 0; i < ds_list_size(list); i += 1)
|
||||
{
|
||||
pluginname = ds_list_find_value(list, i);
|
||||
|
||||
// invalid plugin name
|
||||
if (!checkpluginname(pluginname))
|
||||
{
|
||||
show_message('Error loading server-sent plugins - invalid plugin name:#"' + pluginname + '"');
|
||||
return false;
|
||||
}
|
||||
// is duplicate
|
||||
else if (ds_list_find_index(list, pluginname) != i)
|
||||
{
|
||||
show_message('Error loading server-sent plugins - duplicate plugin:#"' + pluginname + '"');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Download plugins
|
||||
for (i = 0; i < ds_list_size(list); i += 1)
|
||||
{
|
||||
pluginname = ds_list_find_value(list, i);
|
||||
pluginhash = ds_list_find_value(hashList, i);
|
||||
isDebug = file_exists(working_directory + "\ServerPluginsDebug\" + pluginname + ".zip");
|
||||
isCached = file_exists(working_directory + "\ServerPluginsCache\" + pluginname + "@" + pluginhash);
|
||||
tempfile = temp_directory + "\" + pluginname + ".zip.tmp";
|
||||
tempdir = temp_directory + "\" + pluginname + ".tmp";
|
||||
|
||||
// check to see if we have a local copy for debugging
|
||||
if (isDebug)
|
||||
{
|
||||
file_copy(working_directory + "\ServerPluginsDebug\" + pluginname + ".zip", tempfile);
|
||||
// show warning
|
||||
if (global.isHost)
|
||||
{
|
||||
show_message(
|
||||
"Warning: server-sent plugin '"
|
||||
+ pluginname
|
||||
+ "' is being loaded from ServerPluginsDebug. Make sure clients have the same version, else they may be unable to connect."
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
show_message(
|
||||
"Warning: server-sent plugin '"
|
||||
+ pluginname
|
||||
+ "' is being loaded from ServerPluginsDebug. Make sure the server has the same version, else you may be unable to connect."
|
||||
);
|
||||
}
|
||||
}
|
||||
// otherwise, check if we have it cached
|
||||
else if (isCached)
|
||||
{
|
||||
file_copy(working_directory + "\ServerPluginsCache\" + pluginname + "@" + pluginhash, tempfile);
|
||||
}
|
||||
// otherwise, download as usual
|
||||
else
|
||||
{
|
||||
// construct the URL
|
||||
// http://www.ganggarrison.com/plugins/$PLUGINNAME$@$PLUGINHASH$.zip)
|
||||
url = PLUGIN_SOURCE + pluginname + "@" + pluginhash + ".zip";
|
||||
|
||||
// let's make the download handle
|
||||
handle = httpGet(url, -1);
|
||||
|
||||
// download it
|
||||
while (!httpRequestStatus(handle)) {
|
||||
// prevent game locking up
|
||||
io_handle();
|
||||
|
||||
httpRequestStep(handle);
|
||||
|
||||
if (!global.isHost) {
|
||||
// send ping if we haven't contacted server in 20 seconds
|
||||
// we need to do this to keep the connection open
|
||||
if (current_time-lastContact > 20000) {
|
||||
write_byte(global.serverSocket, PING);
|
||||
socket_send(global.serverSocket);
|
||||
lastContact = current_time;
|
||||
}
|
||||
}
|
||||
|
||||
// draw progress bar since they may be waiting a while
|
||||
filesize = httpRequestResponseBodySize(handle);
|
||||
progress = httpRequestResponseBodyProgress(handle);
|
||||
draw_background_ext(background_index[0], 0, 0, background_xscale[0], background_yscale[0], 0, c_white, 1);
|
||||
draw_set_color(c_white);
|
||||
draw_set_alpha(1);
|
||||
draw_set_halign(fa_left);
|
||||
draw_rectangle(50, 550, 300, 560, 2);
|
||||
draw_text(50, 530, "Downloading server-sent plugin " + string(i + 1) + "/" + string(ds_list_size(list)) + ' - "' + pluginname + '"');
|
||||
if (filesize != -1)
|
||||
draw_rectangle(50, 550, 50 + progress / filesize * 250, 560, 0);
|
||||
screen_refresh();
|
||||
}
|
||||
|
||||
// errored
|
||||
if (httpRequestStatus(handle) == 2)
|
||||
{
|
||||
show_message('Error loading server-sent plugins - download failed for "' + pluginname + '":#' + httpRequestError(handle));
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
|
||||
// request failed
|
||||
if (httpRequestStatusCode(handle) != 200)
|
||||
{
|
||||
show_message('Error loading server-sent plugins - download failed for "' + pluginname + '":#' + string(httpRequestStatusCode(handle)) + ' ' + httpRequestReasonPhrase(handle));
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
write_buffer_to_file(httpRequestResponseBody(handle), tempfile);
|
||||
if (!file_exists(tempfile))
|
||||
{
|
||||
show_message('Error loading server-sent plugins - download failed for "' + pluginname + '":# No such file?');
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
httpRequestDestroy(handle);
|
||||
}
|
||||
|
||||
// check file integrity
|
||||
realhash = GG2DLL_compute_MD5(tempfile);
|
||||
if (realhash != pluginhash)
|
||||
{
|
||||
show_message('Error loading server-sent plugins - integrity check failed (MD5 hash mismatch) for:#"' + pluginname + '"');
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
|
||||
// don't try to cache debug plugins
|
||||
if (!isDebug)
|
||||
{
|
||||
// add to cache if we don't already have it
|
||||
if (!file_exists(working_directory + "\ServerPluginsCache\" + pluginname + "@" + pluginhash))
|
||||
{
|
||||
// make sure directory exists
|
||||
if (!directory_exists(working_directory + "\ServerPluginsCache"))
|
||||
{
|
||||
directory_create(working_directory + "\ServerPluginsCache");
|
||||
}
|
||||
// store in cache
|
||||
file_copy(tempfile, working_directory + "\ServerPluginsCache\" + pluginname + "@" + pluginhash);
|
||||
}
|
||||
}
|
||||
|
||||
// let's get 7-zip to extract the files
|
||||
extractzip(tempfile, tempdir);
|
||||
|
||||
// if the directory doesn't exist, extracting presumably failed
|
||||
if (!directory_exists(tempdir))
|
||||
{
|
||||
show_message('Error loading server-sent plugins - extracting zip failed for:#"' + pluginname + '"');
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!failed)
|
||||
{
|
||||
// Execute plugins
|
||||
for (i = 0; i < ds_list_size(list); i += 1)
|
||||
{
|
||||
pluginname = ds_list_find_value(list, i);
|
||||
tempdir = temp_directory + "\" + pluginname + ".tmp";
|
||||
|
||||
// Debugging facility, so we know *which* plugin caused compile/execute error
|
||||
fp = file_text_open_write(working_directory + "\last_plugin.log");
|
||||
file_text_write_string(fp, pluginname);
|
||||
file_text_close(fp);
|
||||
|
||||
// packetID is (i), so make queues for it
|
||||
ds_map_add(global.pluginPacketBuffers, i, ds_queue_create());
|
||||
ds_map_add(global.pluginPacketPlayers, i, ds_queue_create());
|
||||
|
||||
// Execute plugin
|
||||
execute_file(
|
||||
// the plugin's main gml file must be in the root of the zip
|
||||
// it is called plugin.gml
|
||||
tempdir + "\plugin.gml",
|
||||
// the plugin needs to know where it is
|
||||
// so the temporary directory is passed as first argument
|
||||
tempdir,
|
||||
// the plugin needs to know its packetID
|
||||
// so it is passed as the second argument
|
||||
i
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete last plugin log
|
||||
file_delete(working_directory + "\last_plugin.log");
|
||||
|
||||
// Get rid of plugin list
|
||||
ds_list_destroy(list);
|
||||
|
||||
// Get rid of plugin hash list
|
||||
ds_list_destroy(hashList);
|
||||
|
||||
return !failed;
|
||||
384
samples/Game Maker Language/processClientCommands.gml
Normal file
384
samples/Game Maker Language/processClientCommands.gml
Normal file
@@ -0,0 +1,384 @@
|
||||
/*
|
||||
Originally from /Source/gg2/Scripts/GameServer/processClientCommands.gml in Gang Garrison 2
|
||||
|
||||
Copyright (C) 2008-2013 Faucet Software
|
||||
http://www.ganggarrison.com
|
||||
|
||||
This program is free software;
|
||||
you can redistribute it and/or modify it under the terms of the GNU General Public License
|
||||
as published by the Free Software Foundation; either version 3 of the License, or (at your option)
|
||||
any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License along with this program; if not,
|
||||
see <http://www.gnu.org/licenses>.
|
||||
|
||||
Additional permission under GNU GPL version 3 section 7
|
||||
If you modify this Program, or any covered work, by linking or combining it with the Game Maker runtime library,
|
||||
the 39dll library/extension, Hobbel's Download Manager DLL, or modified versions of these libraries,
|
||||
the licensors of this Program grant you additional permission to convey the resulting work.
|
||||
*/
|
||||
|
||||
var player, playerId, commandLimitRemaining;
|
||||
|
||||
player = argument0;
|
||||
playerId = argument1;
|
||||
|
||||
// To prevent players from flooding the server, limit the number of commands to process per step and player.
|
||||
commandLimitRemaining = 10;
|
||||
|
||||
with(player) {
|
||||
if(!variable_local_exists("commandReceiveState")) {
|
||||
// 0: waiting for command byte.
|
||||
// 1: waiting for command data length (1 byte)
|
||||
// 2: waiting for command data.
|
||||
commandReceiveState = 0;
|
||||
commandReceiveExpectedBytes = 1;
|
||||
commandReceiveCommand = 0;
|
||||
}
|
||||
}
|
||||
|
||||
while(commandLimitRemaining > 0) {
|
||||
var socket;
|
||||
socket = player.socket;
|
||||
if(!tcp_receive(socket, player.commandReceiveExpectedBytes)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
switch(player.commandReceiveState)
|
||||
{
|
||||
case 0:
|
||||
player.commandReceiveCommand = read_ubyte(socket);
|
||||
switch(commandBytes[player.commandReceiveCommand]) {
|
||||
case commandBytesInvalidCommand:
|
||||
// Invalid byte received. Wait for another command byte.
|
||||
break;
|
||||
|
||||
case commandBytesPrefixLength1:
|
||||
player.commandReceiveState = 1;
|
||||
player.commandReceiveExpectedBytes = 1;
|
||||
break;
|
||||
|
||||
case commandBytesPrefixLength2:
|
||||
player.commandReceiveState = 3;
|
||||
player.commandReceiveExpectedBytes = 2;
|
||||
break;
|
||||
|
||||
default:
|
||||
player.commandReceiveState = 2;
|
||||
player.commandReceiveExpectedBytes = commandBytes[player.commandReceiveCommand];
|
||||
break;
|
||||
}
|
||||
break;
|
||||
|
||||
case 1:
|
||||
player.commandReceiveState = 2;
|
||||
player.commandReceiveExpectedBytes = read_ubyte(socket);
|
||||
break;
|
||||
|
||||
case 3:
|
||||
player.commandReceiveState = 2;
|
||||
player.commandReceiveExpectedBytes = read_ushort(socket);
|
||||
break;
|
||||
|
||||
case 2:
|
||||
player.commandReceiveState = 0;
|
||||
player.commandReceiveExpectedBytes = 1;
|
||||
commandLimitRemaining -= 1;
|
||||
|
||||
switch(player.commandReceiveCommand)
|
||||
{
|
||||
case PLAYER_LEAVE:
|
||||
socket_destroy(player.socket);
|
||||
player.socket = -1;
|
||||
break;
|
||||
|
||||
case PLAYER_CHANGECLASS:
|
||||
var class;
|
||||
class = read_ubyte(socket);
|
||||
if(getCharacterObject(player.team, class) != -1)
|
||||
{
|
||||
if(player.object != -1)
|
||||
{
|
||||
with(player.object)
|
||||
{
|
||||
if (collision_point(x,y,SpawnRoom,0,0) < 0)
|
||||
{
|
||||
if (!instance_exists(lastDamageDealer) || lastDamageDealer == player)
|
||||
{
|
||||
sendEventPlayerDeath(player, player, noone, BID_FAREWELL);
|
||||
doEventPlayerDeath(player, player, noone, BID_FAREWELL);
|
||||
}
|
||||
else
|
||||
{
|
||||
var assistant;
|
||||
assistant = secondToLastDamageDealer;
|
||||
if (lastDamageDealer.object)
|
||||
if (lastDamageDealer.object.healer)
|
||||
assistant = lastDamageDealer.object.healer;
|
||||
sendEventPlayerDeath(player, lastDamageDealer, assistant, FINISHED_OFF);
|
||||
doEventPlayerDeath(player, lastDamageDealer, assistant, FINISHED_OFF);
|
||||
}
|
||||
}
|
||||
else
|
||||
instance_destroy();
|
||||
|
||||
}
|
||||
}
|
||||
else if(player.alarm[5]<=0)
|
||||
player.alarm[5] = 1;
|
||||
class = checkClasslimits(player, player.team, class);
|
||||
player.class = class;
|
||||
ServerPlayerChangeclass(playerId, player.class, global.sendBuffer);
|
||||
}
|
||||
break;
|
||||
|
||||
case PLAYER_CHANGETEAM:
|
||||
var newTeam, balance, redSuperiority;
|
||||
newTeam = read_ubyte(socket);
|
||||
|
||||
redSuperiority = 0 //calculate which team is bigger
|
||||
with(Player)
|
||||
{
|
||||
if(team == TEAM_RED)
|
||||
redSuperiority += 1;
|
||||
else if(team == TEAM_BLUE)
|
||||
redSuperiority -= 1;
|
||||
}
|
||||
if(redSuperiority > 0)
|
||||
balance = TEAM_RED;
|
||||
else if(redSuperiority < 0)
|
||||
balance = TEAM_BLUE;
|
||||
else
|
||||
balance = -1;
|
||||
|
||||
if(balance != newTeam)
|
||||
{
|
||||
if(getCharacterObject(newTeam, player.class) != -1 or newTeam==TEAM_SPECTATOR)
|
||||
{
|
||||
if(player.object != -1)
|
||||
{
|
||||
with(player.object)
|
||||
{
|
||||
if (!instance_exists(lastDamageDealer) || lastDamageDealer == player)
|
||||
{
|
||||
sendEventPlayerDeath(player, player, noone, BID_FAREWELL);
|
||||
doEventPlayerDeath(player, player, noone, BID_FAREWELL);
|
||||
}
|
||||
else
|
||||
{
|
||||
var assistant;
|
||||
assistant = secondToLastDamageDealer;
|
||||
if (lastDamageDealer.object)
|
||||
if (lastDamageDealer.object.healer)
|
||||
assistant = lastDamageDealer.object.healer;
|
||||
sendEventPlayerDeath(player, lastDamageDealer, assistant, FINISHED_OFF);
|
||||
doEventPlayerDeath(player, lastDamageDealer, assistant, FINISHED_OFF);
|
||||
}
|
||||
}
|
||||
player.alarm[5] = global.Server_Respawntime;
|
||||
}
|
||||
else if(player.alarm[5]<=0)
|
||||
player.alarm[5] = 1;
|
||||
var newClass;
|
||||
newClass = checkClasslimits(player, newTeam, player.class);
|
||||
if newClass != player.class
|
||||
{
|
||||
player.class = newClass;
|
||||
ServerPlayerChangeclass(playerId, player.class, global.sendBuffer);
|
||||
}
|
||||
player.team = newTeam;
|
||||
ServerPlayerChangeteam(playerId, player.team, global.sendBuffer);
|
||||
ServerBalanceTeams();
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case CHAT_BUBBLE:
|
||||
var bubbleImage;
|
||||
bubbleImage = read_ubyte(socket);
|
||||
if(global.aFirst) {
|
||||
bubbleImage = 0;
|
||||
}
|
||||
write_ubyte(global.sendBuffer, CHAT_BUBBLE);
|
||||
write_ubyte(global.sendBuffer, playerId);
|
||||
write_ubyte(global.sendBuffer, bubbleImage);
|
||||
|
||||
setChatBubble(player, bubbleImage);
|
||||
break;
|
||||
|
||||
case BUILD_SENTRY:
|
||||
if(player.object != -1)
|
||||
{
|
||||
if(player.class == CLASS_ENGINEER
|
||||
and collision_circle(player.object.x, player.object.y, 50, Sentry, false, true) < 0
|
||||
and player.object.nutsNBolts == 100
|
||||
and (collision_point(player.object.x,player.object.y,SpawnRoom,0,0) < 0)
|
||||
and !player.sentry
|
||||
and !player.object.onCabinet)
|
||||
{
|
||||
write_ubyte(global.sendBuffer, BUILD_SENTRY);
|
||||
write_ubyte(global.sendBuffer, playerId);
|
||||
write_ushort(global.serializeBuffer, round(player.object.x*5));
|
||||
write_ushort(global.serializeBuffer, round(player.object.y*5));
|
||||
write_byte(global.serializeBuffer, player.object.image_xscale);
|
||||
buildSentry(player, player.object.x, player.object.y, player.object.image_xscale);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DESTROY_SENTRY:
|
||||
with(player.sentry)
|
||||
instance_destroy();
|
||||
break;
|
||||
|
||||
case DROP_INTEL:
|
||||
if (player.object != -1)
|
||||
{
|
||||
if (player.object.intel)
|
||||
{
|
||||
sendEventDropIntel(player);
|
||||
doEventDropIntel(player);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case OMNOMNOMNOM:
|
||||
if(player.object != -1) {
|
||||
if(!player.humiliated
|
||||
and !player.object.taunting
|
||||
and !player.object.omnomnomnom
|
||||
and player.object.canEat
|
||||
and player.class==CLASS_HEAVY)
|
||||
{
|
||||
write_ubyte(global.sendBuffer, OMNOMNOMNOM);
|
||||
write_ubyte(global.sendBuffer, playerId);
|
||||
with(player.object)
|
||||
{
|
||||
omnomnomnom = true;
|
||||
if player.team == TEAM_RED {
|
||||
omnomnomnomindex=0;
|
||||
omnomnomnomend=31;
|
||||
} else if player.team==TEAM_BLUE {
|
||||
omnomnomnomindex=32;
|
||||
omnomnomnomend=63;
|
||||
}
|
||||
xscale=image_xscale;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case TOGGLE_ZOOM:
|
||||
if player.object != -1 {
|
||||
if player.class == CLASS_SNIPER {
|
||||
write_ubyte(global.sendBuffer, TOGGLE_ZOOM);
|
||||
write_ubyte(global.sendBuffer, playerId);
|
||||
toggleZoom(player.object);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case PLAYER_CHANGENAME:
|
||||
var nameLength;
|
||||
nameLength = socket_receivebuffer_size(socket);
|
||||
if(nameLength > MAX_PLAYERNAME_LENGTH)
|
||||
{
|
||||
write_ubyte(player.socket, KICK);
|
||||
write_ubyte(player.socket, KICK_NAME);
|
||||
socket_destroy(player.socket);
|
||||
player.socket = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
with(player)
|
||||
{
|
||||
if(variable_local_exists("lastNamechange"))
|
||||
if(current_time - lastNamechange < 1000)
|
||||
break;
|
||||
lastNamechange = current_time;
|
||||
name = read_string(socket, nameLength);
|
||||
if(string_count("#",name) > 0)
|
||||
{
|
||||
name = "I <3 Bacon";
|
||||
}
|
||||
write_ubyte(global.sendBuffer, PLAYER_CHANGENAME);
|
||||
write_ubyte(global.sendBuffer, playerId);
|
||||
write_ubyte(global.sendBuffer, string_length(name));
|
||||
write_string(global.sendBuffer, name);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case INPUTSTATE:
|
||||
if(player.object != -1)
|
||||
{
|
||||
with(player.object)
|
||||
{
|
||||
keyState = read_ubyte(socket);
|
||||
netAimDirection = read_ushort(socket);
|
||||
aimDirection = netAimDirection*360/65536;
|
||||
event_user(1);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case REWARD_REQUEST:
|
||||
player.rewardId = read_string(socket, socket_receivebuffer_size(socket));
|
||||
player.challenge = rewardCreateChallenge();
|
||||
|
||||
write_ubyte(socket, REWARD_CHALLENGE_CODE);
|
||||
write_binstring(socket, player.challenge);
|
||||
break;
|
||||
|
||||
case REWARD_CHALLENGE_RESPONSE:
|
||||
var answer, i, authbuffer;
|
||||
answer = read_binstring(socket, 16);
|
||||
|
||||
with(player)
|
||||
if(variable_local_exists("challenge") and variable_local_exists("rewardId"))
|
||||
rewardAuthStart(player, answer, challenge, true, rewardId);
|
||||
|
||||
break;
|
||||
|
||||
case PLUGIN_PACKET:
|
||||
var packetID, buf, success;
|
||||
|
||||
packetID = read_ubyte(socket);
|
||||
|
||||
// get packet data
|
||||
buf = buffer_create();
|
||||
write_buffer_part(buf, socket, socket_receivebuffer_size(socket));
|
||||
|
||||
// try to enqueue
|
||||
success = _PluginPacketPush(packetID, buf, player);
|
||||
|
||||
// if it returned false, packetID was invalid
|
||||
if (!success)
|
||||
{
|
||||
// clear up buffer
|
||||
buffer_destroy(buf);
|
||||
|
||||
// kick player
|
||||
write_ubyte(player.socket, KICK);
|
||||
write_ubyte(player.socket, KICK_BAD_PLUGIN_PACKET);
|
||||
socket_destroy(player.socket);
|
||||
player.socket = -1;
|
||||
}
|
||||
break;
|
||||
|
||||
case CLIENT_SETTINGS:
|
||||
var mirror;
|
||||
mirror = read_ubyte(player.socket);
|
||||
player.queueJump = mirror;
|
||||
|
||||
write_ubyte(global.sendBuffer, CLIENT_SETTINGS);
|
||||
write_ubyte(global.sendBuffer, playerId);
|
||||
write_ubyte(global.sendBuffer, mirror);
|
||||
break;
|
||||
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
298
samples/Game Maker Language/scrInitLevel.gml
Normal file
298
samples/Game Maker Language/scrInitLevel.gml
Normal file
@@ -0,0 +1,298 @@
|
||||
// Originally from /spelunky/Scripts/Level Generation/scrInitLevel.gml in the Spelunky Community Update Project
|
||||
|
||||
//
|
||||
// scrInitLevel()
|
||||
//
|
||||
// Calls scrLevelGen(), scrRoomGen*(), and scrEntityGen() to build level.
|
||||
//
|
||||
|
||||
/**********************************************************************************
|
||||
Copyright (c) 2008, 2009 Derek Yu and Mossmouth, LLC
|
||||
|
||||
This file is part of Spelunky.
|
||||
|
||||
You can redistribute and/or modify Spelunky, including its source code, under
|
||||
the terms of the Spelunky User License.
|
||||
|
||||
Spelunky is distributed in the hope that it will be entertaining and useful,
|
||||
but WITHOUT WARRANTY. Please see the Spelunky User License for more details.
|
||||
|
||||
The Spelunky User License should be available in "Game Information", which
|
||||
can be found in the Resource Explorer, or as an external file called COPYING.
|
||||
If not, please obtain a new copy of Spelunky from <http://spelunkyworld.com/>
|
||||
|
||||
***********************************************************************************/
|
||||
|
||||
global.levelType = 0;
|
||||
//global.currLevel = 16;
|
||||
if (global.currLevel > 4 and global.currLevel < 9) global.levelType = 1;
|
||||
if (global.currLevel > 8 and global.currLevel < 13) global.levelType = 2;
|
||||
if (global.currLevel > 12 and global.currLevel < 16) global.levelType = 3;
|
||||
if (global.currLevel == 16) global.levelType = 4;
|
||||
|
||||
if (global.currLevel <= 1 or
|
||||
global.currLevel == 5 or
|
||||
global.currLevel == 9 or
|
||||
global.currLevel == 13)
|
||||
{
|
||||
global.hadDarkLevel = false;
|
||||
}
|
||||
|
||||
// global.levelType = 3; // debug
|
||||
|
||||
// DEBUG MODE //
|
||||
/*
|
||||
if (global.currLevel == 2) global.levelType = 4;
|
||||
if (global.currLevel == 3) global.levelType = 2;
|
||||
if (global.currLevel == 4) global.levelType = 3;
|
||||
if (global.currLevel == 5) global.levelType = 4;
|
||||
*/
|
||||
|
||||
// global.levelType = 0;
|
||||
|
||||
global.startRoomX = 0;
|
||||
global.startRoomY = 0;
|
||||
global.endRoomX = 0;
|
||||
global.endRoomY = 0;
|
||||
oGame.levelGen = false;
|
||||
|
||||
// this is used to determine the path to the exit (generally no bombs required)
|
||||
for (i = 0; i < 4; i += 1)
|
||||
{
|
||||
for (j = 0; j < 4; j += 1)
|
||||
{
|
||||
global.roomPath[i,j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// side walls
|
||||
if (global.levelType == 4)
|
||||
k = 54;
|
||||
else if (global.levelType == 2)
|
||||
k = 38;
|
||||
else if (global.lake)
|
||||
k = 41;
|
||||
else
|
||||
k = 33;
|
||||
for (i = 0; i <= 42; i += 1)
|
||||
{
|
||||
for (j = 0; j <= k; j += 1)
|
||||
{
|
||||
if (not isLevel())
|
||||
{
|
||||
i = 999;
|
||||
j = 999;
|
||||
}
|
||||
else if (global.levelType == 2)
|
||||
{
|
||||
if (i*16 == 0 or
|
||||
i*16 == 656 or
|
||||
j*16 == 0)
|
||||
{
|
||||
obj = instance_create(i*16, j*16, oDark);
|
||||
obj.invincible = true;
|
||||
obj.sprite_index = sDark;
|
||||
}
|
||||
}
|
||||
else if (global.levelType == 4)
|
||||
{
|
||||
if (i*16 == 0 or
|
||||
i*16 == 656 or
|
||||
j*16 == 0)
|
||||
{
|
||||
obj = instance_create(i*16, j*16, oTemple);
|
||||
obj.invincible = true;
|
||||
if (not global.cityOfGold) obj.sprite_index = sTemple;
|
||||
}
|
||||
}
|
||||
else if (global.lake)
|
||||
{
|
||||
if (i*16 == 0 or
|
||||
i*16 == 656 or
|
||||
j*16 == 0 or
|
||||
j*16 >= 656)
|
||||
{
|
||||
obj = instance_create(i*16, j*16, oLush); obj.sprite_index = sLush;
|
||||
obj.invincible = true;
|
||||
}
|
||||
}
|
||||
else if (i*16 == 0 or
|
||||
i*16 == 656 or
|
||||
j*16 == 0 or
|
||||
j*16 >= 528)
|
||||
{
|
||||
if (global.levelType == 0) { obj = instance_create(i*16, j*16, oBrick); obj.sprite_index = sBrick; }
|
||||
else if (global.levelType == 1) { obj = instance_create(i*16, j*16, oLush); obj.sprite_index = sLush; }
|
||||
else { obj = instance_create(i*16, j*16, oTemple); if (not global.cityOfGold) obj.sprite_index = sTemple; }
|
||||
obj.invincible = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (global.levelType == 2)
|
||||
{
|
||||
for (i = 0; i <= 42; i += 1)
|
||||
{
|
||||
instance_create(i*16, 40*16, oDark);
|
||||
//instance_create(i*16, 35*16, oSpikes);
|
||||
}
|
||||
}
|
||||
|
||||
if (global.levelType == 3)
|
||||
{
|
||||
background_index = bgTemple;
|
||||
}
|
||||
|
||||
global.temp1 = global.gameStart;
|
||||
scrLevelGen();
|
||||
|
||||
global.cemetary = false;
|
||||
if (global.levelType == 1 and rand(1,global.probCemetary) == 1) global.cemetary = true;
|
||||
|
||||
with oRoom
|
||||
{
|
||||
if (global.levelType == 0) scrRoomGen();
|
||||
else if (global.levelType == 1)
|
||||
{
|
||||
if (global.blackMarket) scrRoomGenMarket();
|
||||
else scrRoomGen2();
|
||||
}
|
||||
else if (global.levelType == 2)
|
||||
{
|
||||
if (global.yetiLair) scrRoomGenYeti();
|
||||
else scrRoomGen3();
|
||||
}
|
||||
else if (global.levelType == 3) scrRoomGen4();
|
||||
else scrRoomGen5();
|
||||
}
|
||||
|
||||
global.darkLevel = false;
|
||||
//if (not global.hadDarkLevel and global.currLevel != 0 and global.levelType != 2 and global.currLevel != 16 and rand(1,1) == 1)
|
||||
if (not global.hadDarkLevel and not global.noDarkLevel and global.currLevel != 0 and global.currLevel != 1 and global.levelType != 2 and global.currLevel != 16 and rand(1,global.probDarkLevel) == 1)
|
||||
{
|
||||
global.darkLevel = true;
|
||||
global.hadDarkLevel = true;
|
||||
//instance_create(oPlayer1.x, oPlayer1.y, oFlare);
|
||||
}
|
||||
|
||||
if (global.blackMarket) global.darkLevel = false;
|
||||
|
||||
global.genUdjatEye = false;
|
||||
if (not global.madeUdjatEye)
|
||||
{
|
||||
if (global.currLevel == 2 and rand(1,3) == 1) global.genUdjatEye = true;
|
||||
else if (global.currLevel == 3 and rand(1,2) == 1) global.genUdjatEye = true;
|
||||
else if (global.currLevel == 4) global.genUdjatEye = true;
|
||||
}
|
||||
|
||||
global.genMarketEntrance = false;
|
||||
if (not global.madeMarketEntrance)
|
||||
{
|
||||
if (global.currLevel == 5 and rand(1,3) == 1) global.genMarketEntrance = true;
|
||||
else if (global.currLevel == 6 and rand(1,2) == 1) global.genMarketEntrance = true;
|
||||
else if (global.currLevel == 7) global.genMarketEntrance = true;
|
||||
}
|
||||
|
||||
////////////////////////////
|
||||
// ENTITY / TREASURES
|
||||
////////////////////////////
|
||||
global.temp2 = global.gameStart;
|
||||
if (not isRoom("rTutorial") and not isRoom("rLoadLevel")) scrEntityGen();
|
||||
|
||||
if (instance_exists(oEntrance) and not global.customLevel)
|
||||
{
|
||||
oPlayer1.x = oEntrance.x+8;
|
||||
oPlayer1.y = oEntrance.y+8;
|
||||
}
|
||||
|
||||
if (global.darkLevel or
|
||||
global.blackMarket or
|
||||
global.snakePit or
|
||||
global.cemetary or
|
||||
global.lake or
|
||||
global.yetiLair or
|
||||
global.alienCraft or
|
||||
global.sacrificePit or
|
||||
global.cityOfGold)
|
||||
{
|
||||
if (not isRoom("rLoadLevel"))
|
||||
{
|
||||
with oPlayer1 { alarm[0] = 10; }
|
||||
}
|
||||
}
|
||||
|
||||
if (global.levelType == 4) scrSetupWalls(864);
|
||||
else if (global.lake) scrSetupWalls(656);
|
||||
else scrSetupWalls(528);
|
||||
|
||||
// add background details
|
||||
if (global.graphicsHigh)
|
||||
{
|
||||
repeat(20)
|
||||
{
|
||||
// bg = instance_create(16*rand(1,42), 16*rand(1,33), oCaveBG);
|
||||
if (global.levelType == 1 and rand(1,3) < 3)
|
||||
tile_add(bgExtrasLush, 32*rand(0,1), 0, 32, 32, 16*rand(1,42), 16*rand(1,33), 10002);
|
||||
else if (global.levelType == 2 and rand(1,3) < 3)
|
||||
tile_add(bgExtrasIce, 32*rand(0,1), 0, 32, 32, 16*rand(1,42), 16*rand(1,33), 10002);
|
||||
else if (global.levelType == 3 and rand(1,3) < 3)
|
||||
tile_add(bgExtrasTemple, 32*rand(0,1), 0, 32, 32, 16*rand(1,42), 16*rand(1,33), 10002);
|
||||
else
|
||||
tile_add(bgExtras, 32*rand(0,1), 0, 32, 32, 16*rand(1,42), 16*rand(1,33), 10002);
|
||||
}
|
||||
}
|
||||
|
||||
oGame.levelGen = true;
|
||||
|
||||
// generate angry shopkeeper at exit if murderer or thief
|
||||
if ((global.murderer or global.thiefLevel > 0) and isRealLevel())
|
||||
{
|
||||
with oExit
|
||||
{
|
||||
if (type == "Exit")
|
||||
{
|
||||
obj = instance_create(x, y, oShopkeeper);
|
||||
obj.status = 4;
|
||||
}
|
||||
}
|
||||
// global.thiefLevel -= 1;
|
||||
}
|
||||
|
||||
with oTreasure
|
||||
{
|
||||
if (collision_point(x, y, oSolid, 0, 0))
|
||||
{
|
||||
obj = instance_place(x, y, oSolid);
|
||||
if (obj.invincible) instance_destroy();
|
||||
}
|
||||
}
|
||||
|
||||
with oWater
|
||||
{
|
||||
if (sprite_index == sWaterTop or sprite_index == sLavaTop)
|
||||
{
|
||||
scrCheckWaterTop();
|
||||
}
|
||||
/*
|
||||
obj = instance_place(x-16, y, oWater);
|
||||
if (instance_exists(obj))
|
||||
{
|
||||
if (obj.sprite_index == sWaterTop or obj.sprite_index == sLavaTop)
|
||||
{
|
||||
if (type == "Lava") sprite_index = sLavaTop;
|
||||
else sprite_index = sWaterTop;
|
||||
}
|
||||
}
|
||||
obj = instance_place(x+16, y, oWater);
|
||||
if (instance_exists(obj))
|
||||
{
|
||||
if (obj.sprite_index == sWaterTop or obj.sprite_index == sLavaTop)
|
||||
{
|
||||
if (type == "Lava") sprite_index = sLavaTop;
|
||||
else sprite_index = sWaterTop;
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
global.temp3 = global.gameStart;
|
||||
22
samples/Gnuplot/dashcolor.1.gnu
Normal file
22
samples/Gnuplot/dashcolor.1.gnu
Normal file
@@ -0,0 +1,22 @@
|
||||
# set terminal pngcairo background "#ffffff" fontscale 1.0 dashed size 640, 480
|
||||
# set output 'dashcolor.1.png'
|
||||
set label 1 "set style line 1 lt 2 lc rgb \"red\" lw 3" at -0.4, -0.25, 0 left norotate back textcolor rgb "red" nopoint offset character 0, 0, 0
|
||||
set label 2 "set style line 2 lt 2 lc rgb \"orange\" lw 2" at -0.4, -0.35, 0 left norotate back textcolor rgb "orange" nopoint offset character 0, 0, 0
|
||||
set label 3 "set style line 3 lt 2 lc rgb \"yellow\" lw 3" at -0.4, -0.45, 0 left norotate back textcolor rgb "yellow" nopoint offset character 0, 0, 0
|
||||
set label 4 "set style line 4 lt 2 lc rgb \"green\" lw 2" at -0.4, -0.55, 0 left norotate back textcolor rgb "green" nopoint offset character 0, 0, 0
|
||||
set label 5 "plot ... lt 1 lc 3 " at -0.4, -0.65, 0 left norotate back textcolor lt 3 nopoint offset character 0, 0, 0
|
||||
set label 6 "plot ... lt 3 lc 3 " at -0.4, -0.75, 0 left norotate back textcolor lt 3 nopoint offset character 0, 0, 0
|
||||
set label 7 "plot ... lt 5 lc 3 " at -0.4, -0.85, 0 left norotate back textcolor lt 3 nopoint offset character 0, 0, 0
|
||||
set style line 1 linetype 2 linecolor rgb "red" linewidth 3.000 pointtype 2 pointsize default pointinterval 0
|
||||
set style line 2 linetype 2 linecolor rgb "orange" linewidth 2.000 pointtype 2 pointsize default pointinterval 0
|
||||
set style line 3 linetype 2 linecolor rgb "yellow" linewidth 3.000 pointtype 2 pointsize default pointinterval 0
|
||||
set style line 4 linetype 2 linecolor rgb "green" linewidth 2.000 pointtype 2 pointsize default pointinterval 0
|
||||
set noxtics
|
||||
set noytics
|
||||
set title "Independent colors and dot/dash styles"
|
||||
set xlabel "You will only see dashed lines if your current terminal setting permits it"
|
||||
set xrange [ -0.500000 : 3.50000 ] noreverse nowriteback
|
||||
set yrange [ -1.00000 : 1.40000 ] noreverse nowriteback
|
||||
set bmargin 7
|
||||
unset colorbox
|
||||
plot cos(x) ls 1 title 'ls 1', cos(x-.2) ls 2 title 'ls 2', cos(x-.4) ls 3 title 'ls 3', cos(x-.6) ls 4 title 'ls 4', cos(x-.8) lt 1 lc 3 title 'lt 1 lc 3', cos(x-1.) lt 3 lc 3 title 'lt 3 lc 3', cos(x-1.2) lt 5 lc 3 title 'lt 5 lc 3'
|
||||
15
samples/Gnuplot/histograms.2.gnu
Normal file
15
samples/Gnuplot/histograms.2.gnu
Normal file
@@ -0,0 +1,15 @@
|
||||
# set terminal pngcairo transparent enhanced font "arial,10" fontscale 1.0 size 500, 350
|
||||
# set output 'histograms.2.png'
|
||||
set boxwidth 0.9 absolute
|
||||
set style fill solid 1.00 border lt -1
|
||||
set key inside right top vertical Right noreverse noenhanced autotitles nobox
|
||||
set style histogram clustered gap 1 title offset character 0, 0, 0
|
||||
set datafile missing '-'
|
||||
set style data histograms
|
||||
set xtics border in scale 0,0 nomirror rotate by -45 offset character 0, 0, 0 autojustify
|
||||
set xtics norangelimit font ",8"
|
||||
set xtics ()
|
||||
set title "US immigration from Northern Europe\nPlot selected data columns as histogram of clustered boxes"
|
||||
set yrange [ 0.00000 : 300000. ] noreverse nowriteback
|
||||
i = 22
|
||||
plot 'immigration.dat' using 6:xtic(1) ti col, '' u 12 ti col, '' u 13 ti col, '' u 14 ti col
|
||||
14
samples/Gnuplot/rates.gp
Normal file
14
samples/Gnuplot/rates.gp
Normal file
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env gnuplot
|
||||
|
||||
reset
|
||||
|
||||
set terminal png
|
||||
set output 'rates100.png'
|
||||
|
||||
set xlabel "A2A price"
|
||||
set ylabel "Response Rate"
|
||||
|
||||
#set xr [0:5]
|
||||
#set yr [0:6]
|
||||
|
||||
plot 'rates100.dat' pt 7 notitle
|
||||
40
samples/Gnuplot/surface1.16.gnu
Normal file
40
samples/Gnuplot/surface1.16.gnu
Normal file
@@ -0,0 +1,40 @@
|
||||
# set terminal pngcairo transparent enhanced font "arial,10" fontscale 1.0 size 500, 350
|
||||
# set output 'surface1.16.png'
|
||||
set dummy u,v
|
||||
set label 1 "increasing v" at 6, 0, -1 left norotate back nopoint offset character 0, 0, 0
|
||||
set label 2 "u=0" at 5, 6.5, -1 left norotate back nopoint offset character 0, 0, 0
|
||||
set label 3 "u=1" at 5, 6.5, 0.100248 left norotate back nopoint offset character 0, 0, 0
|
||||
set arrow 1 from 5, -5, -1.2 to 5, 5, -1.2 head back nofilled linetype -1 linewidth 1.000
|
||||
set arrow 2 from 5, 6, -1 to 5, 5, -1 head back nofilled linetype -1 linewidth 1.000
|
||||
set arrow 3 from 5, 6, 0.100248 to 5, 5, 0.100248 head back nofilled linetype -1 linewidth 1.000
|
||||
set parametric
|
||||
set view 70, 20, 1, 1
|
||||
set samples 51, 51
|
||||
set isosamples 2, 33
|
||||
set hidden3d back offset 1 trianglepattern 3 undefined 1 altdiagonal bentover
|
||||
set ztics -1.00000,0.25,1.00000 norangelimit
|
||||
set title "\"fence plot\" using separate parametric surfaces"
|
||||
set xlabel "X axis"
|
||||
set xlabel offset character -3, -2, 0 font "" textcolor lt -1 norotate
|
||||
set xrange [ -5.00000 : 5.00000 ] noreverse nowriteback
|
||||
set ylabel "Y axis"
|
||||
set ylabel offset character 3, -2, 0 font "" textcolor lt -1 rotate by -270
|
||||
set yrange [ -5.00000 : 5.00000 ] noreverse nowriteback
|
||||
set zlabel "Z axis"
|
||||
set zlabel offset character -5, 0, 0 font "" textcolor lt -1 norotate
|
||||
set zrange [ -1.00000 : 1.00000 ] noreverse nowriteback
|
||||
sinc(u,v) = sin(sqrt(u**2+v**2)) / sqrt(u**2+v**2)
|
||||
GPFUN_sinc = "sinc(u,v) = sin(sqrt(u**2+v**2)) / sqrt(u**2+v**2)"
|
||||
xx = 6.08888888888889
|
||||
dx = 1.10888888888889
|
||||
x0 = -5
|
||||
x1 = -3.89111111111111
|
||||
x2 = -2.78222222222222
|
||||
x3 = -1.67333333333333
|
||||
x4 = -0.564444444444444
|
||||
x5 = 0.544444444444445
|
||||
x6 = 1.65333333333333
|
||||
x7 = 2.76222222222222
|
||||
x8 = 3.87111111111111
|
||||
x9 = 4.98
|
||||
splot [u=0:1][v=-4.99:4.99] x0, v, (u<0.5) ? -1 : sinc(x0,v) notitle, x1, v, (u<0.5) ? -1 : sinc(x1,v) notitle, x2, v, (u<0.5) ? -1 : sinc(x2,v) notitle, x3, v, (u<0.5) ? -1 : sinc(x3,v) notitle, x4, v, (u<0.5) ? -1 : sinc(x4,v) notitle, x5, v, (u<0.5) ? -1 : sinc(x5,v) notitle, x6, v, (u<0.5) ? -1 : sinc(x6,v) notitle, x7, v, (u<0.5) ? -1 : sinc(x7,v) notitle, x8, v, (u<0.5) ? -1 : sinc(x8,v) notitle, x9, v, (u<0.5) ? -1 : sinc(x9,v) notitle
|
||||
46
samples/Gnuplot/surface1.17.gnu
Normal file
46
samples/Gnuplot/surface1.17.gnu
Normal file
@@ -0,0 +1,46 @@
|
||||
# set terminal pngcairo transparent enhanced font "arial,10" fontscale 1.0 size 500, 350
|
||||
# set output 'surface1.17.png'
|
||||
set dummy u,v
|
||||
set label 1 "increasing v" at 6, 0, -1 left norotate back nopoint offset character 0, 0, 0
|
||||
set label 2 "increasing u" at 0, -5, -1.5 left norotate back nopoint offset character 0, 0, 0
|
||||
set label 3 "floor(u)%3=0" at 5, 6.5, -1 left norotate back nopoint offset character 0, 0, 0
|
||||
set label 4 "floor(u)%3=1" at 5, 6.5, 0.100248 left norotate back nopoint offset character 0, 0, 0
|
||||
set arrow 1 from 5, -5, -1.2 to 5, 5, -1.2 head back nofilled linetype -1 linewidth 1.000
|
||||
set arrow 2 from -5, -5, -1.2 to 5, -5, -1.2 head back nofilled linetype -1 linewidth 1.000
|
||||
set arrow 3 from 5, 6, -1 to 5, 5, -1 head back nofilled linetype -1 linewidth 1.000
|
||||
set arrow 4 from 5, 6, 0.100248 to 5, 5, 0.100248 head back nofilled linetype -1 linewidth 1.000
|
||||
set parametric
|
||||
set view 70, 20, 1, 1
|
||||
set samples 51, 51
|
||||
set isosamples 30, 33
|
||||
set hidden3d back offset 1 trianglepattern 3 undefined 1 altdiagonal bentover
|
||||
set ztics -1.00000,0.25,1.00000 norangelimit
|
||||
set title "\"fence plot\" using single parametric surface with undefined points"
|
||||
set xlabel "X axis"
|
||||
set xlabel offset character -3, -2, 0 font "" textcolor lt -1 norotate
|
||||
set xrange [ -5.00000 : 5.00000 ] noreverse nowriteback
|
||||
set ylabel "Y axis"
|
||||
set ylabel offset character 3, -2, 0 font "" textcolor lt -1 rotate by -270
|
||||
set yrange [ -5.00000 : 5.00000 ] noreverse nowriteback
|
||||
set zlabel "Z axis"
|
||||
set zlabel offset character -5, 0, 0 font "" textcolor lt -1 norotate
|
||||
set zrange [ -1.00000 : 1.00000 ] noreverse nowriteback
|
||||
sinc(u,v) = sin(sqrt(u**2+v**2)) / sqrt(u**2+v**2)
|
||||
GPFUN_sinc = "sinc(u,v) = sin(sqrt(u**2+v**2)) / sqrt(u**2+v**2)"
|
||||
xx = 6.08888888888889
|
||||
dx = 1.11
|
||||
x0 = -5
|
||||
x1 = -3.89111111111111
|
||||
x2 = -2.78222222222222
|
||||
x3 = -1.67333333333333
|
||||
x4 = -0.564444444444444
|
||||
x5 = 0.544444444444445
|
||||
x6 = 1.65333333333333
|
||||
x7 = 2.76222222222222
|
||||
x8 = 3.87111111111111
|
||||
x9 = 4.98
|
||||
xmin = -4.99
|
||||
xmax = 5
|
||||
n = 10
|
||||
zbase = -1
|
||||
splot [u=.5:3*n-.5][v=-4.99:4.99] xmin+floor(u/3)*dx, v, ((floor(u)%3)==0) ? zbase : (((floor(u)%3)==1) ? sinc(xmin+u/3.*dx,v) : 1/0) notitle
|
||||
21
samples/Gnuplot/world2.1.gnu
Normal file
21
samples/Gnuplot/world2.1.gnu
Normal file
@@ -0,0 +1,21 @@
|
||||
# set terminal pngcairo transparent enhanced font "arial,10" fontscale 1.0 size 500, 350
|
||||
# set output 'world2.1.png'
|
||||
unset border
|
||||
set dummy u,v
|
||||
set angles degrees
|
||||
set parametric
|
||||
set view 60, 136, 1.22, 1.26
|
||||
set samples 64, 64
|
||||
set isosamples 13, 13
|
||||
set mapping spherical
|
||||
set noxtics
|
||||
set noytics
|
||||
set noztics
|
||||
set title "Labels colored by GeV plotted in spherical coordinate system"
|
||||
set urange [ -90.0000 : 90.0000 ] noreverse nowriteback
|
||||
set vrange [ 0.00000 : 360.000 ] noreverse nowriteback
|
||||
set cblabel "GeV"
|
||||
set cbrange [ 0.00000 : 8.00000 ] noreverse nowriteback
|
||||
set colorbox user
|
||||
set colorbox vertical origin screen 0.9, 0.2, 0 size screen 0.02, 0.75, 0 front bdefault
|
||||
splot cos(u)*cos(v),cos(u)*sin(v),sin(u) notitle with lines lt 5, 'world.dat' notitle with lines lt 2, 'srl.dat' using 3:2:(1):1:4 with labels notitle point pt 6 lw .1 left offset 1,0 font "Helvetica,7" tc pal
|
||||
9
samples/Hy/fibonacci.hy
Normal file
9
samples/Hy/fibonacci.hy
Normal file
@@ -0,0 +1,9 @@
|
||||
;; Fibonacci example in Hy.
|
||||
|
||||
(defn fib [n]
|
||||
(if (<= n 2) n
|
||||
(+ (fib (- n 1)) (fib (- n 2)))))
|
||||
|
||||
(if (= __name__ "__main__")
|
||||
(for [x [1 2 3 4 5 6 7 8]]
|
||||
(print (fib x))))
|
||||
13
samples/Hy/hello-world.hy
Normal file
13
samples/Hy/hello-world.hy
Normal file
@@ -0,0 +1,13 @@
|
||||
;; The concurrent.futures example in Hy.
|
||||
|
||||
(import [concurrent.futures [ThreadPoolExecutor as-completed]]
|
||||
[random [randint]]
|
||||
[sh [sleep]])
|
||||
|
||||
(defn task-to-do []
|
||||
(sleep (randint 1 5)))
|
||||
|
||||
(with-as (ThreadPoolExecutor 10) executor
|
||||
(setv jobs (list-comp (.submit executor task-to-do) (x (range 0 10))))
|
||||
(for (future (as-completed jobs))
|
||||
(.result future)))
|
||||
30
samples/JSONLD/sample.jsonld
Normal file
30
samples/JSONLD/sample.jsonld
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"@context": {
|
||||
"property": "http://example.com/vocab#property"
|
||||
},
|
||||
"@id": "../document-relative",
|
||||
"@type": "#document-relative",
|
||||
"property": {
|
||||
"@context": {
|
||||
"@base": "http://example.org/test/"
|
||||
},
|
||||
"@id": "../document-base-overwritten",
|
||||
"@type": "#document-base-overwritten",
|
||||
"property": [
|
||||
{
|
||||
"@context": null,
|
||||
"@id": "../document-relative",
|
||||
"@type": "#document-relative",
|
||||
"property": "context completely reset, drops property"
|
||||
},
|
||||
{
|
||||
"@context": {
|
||||
"@base": null
|
||||
},
|
||||
"@id": "../document-relative",
|
||||
"@type": "#document-relative",
|
||||
"property": "only @base is cleared"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
36
samples/M/Comment.m
Normal file
36
samples/M/Comment.m
Normal file
@@ -0,0 +1,36 @@
|
||||
Comment ;
|
||||
; this is a comment block
|
||||
; comments always start with a semicolon
|
||||
; the next line, while not a comment, is a legal blank line
|
||||
|
||||
;whitespace alone is a valid line in a routine
|
||||
;** Comments can have any graphic character, but no "control"
|
||||
;** characters
|
||||
|
||||
;graphic characters such as: !@#$%^&*()_+=-{}[]|\:"?/>.<,
|
||||
;the space character is considered a graphic character, even
|
||||
;though you can't see it.
|
||||
; ASCII characters whose numeric code is above 128 and below 32
|
||||
; are NOT allowed on a line in a routine.
|
||||
;; multiple semicolons are okay
|
||||
; a line that has a tag must have whitespace after the tag, bug
|
||||
; does not have to have a comment or a command on it
|
||||
Tag1
|
||||
;
|
||||
;Tags can start with % or an uppercase or lowercase alphabetic
|
||||
; or can be a series of numeric characters
|
||||
%HELO ;
|
||||
;
|
||||
0123 ;
|
||||
;
|
||||
%987 ;
|
||||
; the most common label is uppercase alphabetic
|
||||
LABEL ;
|
||||
;
|
||||
; Tags can be followed directly by an open parenthesis and a
|
||||
; formal list of variables, and a close parenthesis
|
||||
ANOTHER(X) ;
|
||||
;
|
||||
;Normally, a subroutine would be ended by a QUIT command, but we
|
||||
; are taking advantage of the rule that the END of routine is an
|
||||
; implicit QUIT
|
||||
61
samples/Mask/view.mask
Normal file
61
samples/Mask/view.mask
Normal file
@@ -0,0 +1,61 @@
|
||||
|
||||
// HTML Elements
|
||||
header {
|
||||
|
||||
img .logo src='/images/~[currentLogo].png' alt=logo;
|
||||
|
||||
h4 > 'Bar View'
|
||||
|
||||
if (currentUser) {
|
||||
|
||||
.account >
|
||||
a href='/acount' >
|
||||
'Hello, ~[currentUser.username]'
|
||||
}
|
||||
}
|
||||
|
||||
.view {
|
||||
ul {
|
||||
|
||||
// Iteration
|
||||
for ((user, index) of users) {
|
||||
|
||||
li.user data-id='~[user.id]' {
|
||||
|
||||
// interpolation
|
||||
.name > '~[ user.username ]'
|
||||
|
||||
// expression
|
||||
.count > '~[: user.level.toFixed(2) ]'
|
||||
|
||||
// util
|
||||
/* Localization sample
|
||||
* lastActivity: "Am {0:dd. MM} war der letzte Eintrag"
|
||||
*/
|
||||
.date > '~[ L: "lastActivity", user.date]'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Component
|
||||
:countdownComponent {
|
||||
input type = text >
|
||||
:dualbind value='number';
|
||||
|
||||
button x-signal='click: countdownStart' > 'Start';
|
||||
|
||||
h5 {
|
||||
'~[bind: number]'
|
||||
|
||||
:animation x-slot='countdownStart' {
|
||||
@model > 'transition | scale(0) > scale(1) | 500ms'
|
||||
@next > 'background-color | red > blue | 2s linear'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
footer > :bazCompo {
|
||||
|
||||
'Component generated at ~[: $u.format($c.date, "HH-mm") ]'
|
||||
}
|
||||
3
samples/Mathematica/Init.m
Normal file
3
samples/Mathematica/Init.m
Normal file
@@ -0,0 +1,3 @@
|
||||
(* Mathematica Init File *)
|
||||
|
||||
Get[ "Foobar`Foobar`"]
|
||||
17
samples/Mathematica/PacletInfo.m
Normal file
17
samples/Mathematica/PacletInfo.m
Normal file
@@ -0,0 +1,17 @@
|
||||
(* Paclet Info File *)
|
||||
|
||||
(* created 2014/02/07*)
|
||||
|
||||
Paclet[
|
||||
Name -> "Foobar",
|
||||
Version -> "0.0.1",
|
||||
MathematicaVersion -> "8+",
|
||||
Description -> "Example of an automatically generated PacletInfo file.",
|
||||
Creator -> "Chris Granade",
|
||||
Extensions ->
|
||||
{
|
||||
{"Documentation", Language -> "English", MainPage -> "Guides/Foobar"}
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
150
samples/Mathematica/Predicates.m
Normal file
150
samples/Mathematica/Predicates.m
Normal file
@@ -0,0 +1,150 @@
|
||||
(* ::Package:: *)
|
||||
|
||||
BeginPackage["Predicates`"];
|
||||
|
||||
|
||||
(* ::Title:: *)
|
||||
(*Predicates*)
|
||||
|
||||
|
||||
(* ::Section::Closed:: *)
|
||||
(*Fuzzy Logic*)
|
||||
|
||||
|
||||
(* ::Subsection:: *)
|
||||
(*Documentation*)
|
||||
|
||||
|
||||
PossiblyTrueQ::usage="Returns True if the argument is not definitely False.";
|
||||
PossiblyFalseQ::usage="Returns True if the argument is not definitely True.";
|
||||
PossiblyNonzeroQ::usage="Returns True if and only if its argument is not definitely zero.";
|
||||
|
||||
|
||||
(* ::Subsection:: *)
|
||||
(*Implimentation*)
|
||||
|
||||
|
||||
Begin["`Private`"];
|
||||
|
||||
|
||||
PossiblyTrueQ[expr_]:=\[Not]TrueQ[\[Not]expr]
|
||||
|
||||
|
||||
PossiblyFalseQ[expr_]:=\[Not]TrueQ[expr]
|
||||
|
||||
|
||||
End[];
|
||||
|
||||
|
||||
(* ::Section::Closed:: *)
|
||||
(*Numbers and Lists*)
|
||||
|
||||
|
||||
(* ::Subsection:: *)
|
||||
(*Documentation*)
|
||||
|
||||
|
||||
AnyQ::usage="Given a predicate and a list, retuns True if and only if that predicate is True for at least one element of the list.";
|
||||
AnyElementQ::usage="Returns True if cond matches any element of L.";
|
||||
AllQ::usage="Given a predicate and a list, retuns True if and only if that predicate is True for all elements of the list.";
|
||||
AllElementQ::usage="Returns True if cond matches any element of L.";
|
||||
|
||||
|
||||
AnyNonzeroQ::usage="Returns True if L is a list such that at least one element is definitely not zero.";
|
||||
AnyPossiblyNonzeroQ::usage="Returns True if expr is a list such that at least one element is not definitely zero.";
|
||||
|
||||
|
||||
RealQ::usage="Returns True if and only if the argument is a real number";
|
||||
PositiveQ::usage="Returns True if and only if the argument is a positive real number";
|
||||
NonnegativeQ::usage="Returns True if and only if the argument is a non-negative real number";
|
||||
PositiveIntegerQ::usage="Returns True if and only if the argument is a positive integer";
|
||||
NonnegativeIntegerQ::usage="Returns True if and only if the argument is a non-negative integer";
|
||||
|
||||
|
||||
IntegerListQ::usage="Returns True if and only if the input is a list of integers.";
|
||||
PositiveIntegerListQ::usage="Returns True if and only if the input is a list of positive integers.";
|
||||
NonnegativeIntegerListQ::usage="Returns True if and only if the input is a list of non-negative integers.";
|
||||
IntegerOrListQ::usage="Returns True if and only if the input is a list of integers or an integer.";
|
||||
PositiveIntegerOrListQ::usage="Returns True if and only if the input is a list of positive integers or a positive integer.";
|
||||
NonnegativeIntegerOrListQ::usage="Returns True if and only if the input is a list of positive integers or a positive integer.";
|
||||
|
||||
|
||||
SymbolQ::usage="Returns True if argument is an unassigned symbol.";
|
||||
SymbolOrNumberQ::usage="Returns True if argument is a number of has head 'Symbol'";
|
||||
|
||||
|
||||
(* ::Subsection:: *)
|
||||
(*Implimentation*)
|
||||
|
||||
|
||||
Begin["`Private`"];
|
||||
|
||||
|
||||
AnyQ[cond_, L_] := Fold[Or, False, cond /@ L]
|
||||
|
||||
|
||||
AnyElementQ[cond_,L_]:=AnyQ[cond,Flatten[L]]
|
||||
|
||||
|
||||
AllQ[cond_, L_] := Fold[And, True, cond /@ L]
|
||||
|
||||
|
||||
AllElementQ[cond_, L_] := Fold[And, True, cond /@ L]
|
||||
|
||||
|
||||
AnyNonzeroQ[L_]:=AnyElementQ[#!=0&,L]
|
||||
|
||||
|
||||
PossiblyNonzeroQ[expr_]:=PossiblyTrueQ[expr!=0]
|
||||
|
||||
|
||||
AnyPossiblyNonzeroQ[expr_]:=AnyElementQ[PossiblyNonzeroQ,expr]
|
||||
|
||||
|
||||
RealQ[n_]:=TrueQ[Im[n]==0];
|
||||
|
||||
|
||||
PositiveQ[n_]:=Positive[n];
|
||||
|
||||
|
||||
PositiveIntegerQ[n_]:=PositiveQ[n]\[And]IntegerQ[n];
|
||||
|
||||
|
||||
NonnegativeQ[n_]:=TrueQ[RealQ[n]&&n>=0];
|
||||
|
||||
|
||||
NonnegativeIntegerQ[n_]:=NonnegativeQ[n]\[And]IntegerQ[n];
|
||||
|
||||
|
||||
IntegerListQ[input_]:=ListQ[input]&&Not[MemberQ[IntegerQ/@input,False]];
|
||||
|
||||
|
||||
IntegerOrListQ[input_]:=IntegerListQ[input]||IntegerQ[input];
|
||||
|
||||
|
||||
PositiveIntegerListQ[input_]:=IntegerListQ[input]&&Not[MemberQ[Positive[input],False]];
|
||||
|
||||
|
||||
PositiveIntegerOrListQ[input_]:=PositiveIntegerListQ[input]||PositiveIntegerQ[input];
|
||||
|
||||
|
||||
NonnegativeIntegerListQ[input_]:=IntegerListQ[input]&&Not[MemberQ[NonnegativeIntegerQ[input],False]];
|
||||
|
||||
|
||||
NonnegativeIntegerOrListQ[input_]:=NonnegativeIntegerListQ[input]||NonnegativeIntegerQ[input];
|
||||
|
||||
|
||||
SymbolQ[a_]:=Head[a]===Symbol;
|
||||
|
||||
|
||||
SymbolOrNumberQ[a_]:=NumericQ[a]||Head[a]===Symbol;
|
||||
|
||||
|
||||
End[];
|
||||
|
||||
|
||||
(* ::Section:: *)
|
||||
(*Epilogue*)
|
||||
|
||||
|
||||
EndPackage[];
|
||||
520
samples/PAWN/grandlarc.pwn
Normal file
520
samples/PAWN/grandlarc.pwn
Normal file
@@ -0,0 +1,520 @@
|
||||
//----------------------------------------------------------
|
||||
//
|
||||
// GRAND LARCENY 1.0
|
||||
// A freeroam gamemode for SA-MP 0.3
|
||||
//
|
||||
//----------------------------------------------------------
|
||||
|
||||
#include <a_samp>
|
||||
#include <core>
|
||||
#include <float>
|
||||
#include "../include/gl_common.inc"
|
||||
#include "../include/gl_spawns.inc"
|
||||
|
||||
#pragma tabsize 0
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
#define COLOR_WHITE 0xFFFFFFFF
|
||||
#define COLOR_NORMAL_PLAYER 0xFFBB7777
|
||||
|
||||
#define CITY_LOS_SANTOS 0
|
||||
#define CITY_SAN_FIERRO 1
|
||||
#define CITY_LAS_VENTURAS 2
|
||||
|
||||
new total_vehicles_from_files=0;
|
||||
|
||||
// Class selection globals
|
||||
new gPlayerCitySelection[MAX_PLAYERS];
|
||||
new gPlayerHasCitySelected[MAX_PLAYERS];
|
||||
new gPlayerLastCitySelectionTick[MAX_PLAYERS];
|
||||
|
||||
new Text:txtClassSelHelper;
|
||||
new Text:txtLosSantos;
|
||||
new Text:txtSanFierro;
|
||||
new Text:txtLasVenturas;
|
||||
|
||||
new thisanimid=0;
|
||||
new lastanimid=0;
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
main()
|
||||
{
|
||||
print("\n---------------------------------------");
|
||||
print("Running Grand Larceny - by the SA-MP team\n");
|
||||
print("---------------------------------------\n");
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
public OnPlayerConnect(playerid)
|
||||
{
|
||||
GameTextForPlayer(playerid,"~w~Grand Larceny",3000,4);
|
||||
SendClientMessage(playerid,COLOR_WHITE,"Welcome to {88AA88}G{FFFFFF}rand {88AA88}L{FFFFFF}arceny");
|
||||
|
||||
// class selection init vars
|
||||
gPlayerCitySelection[playerid] = -1;
|
||||
gPlayerHasCitySelected[playerid] = 0;
|
||||
gPlayerLastCitySelectionTick[playerid] = GetTickCount();
|
||||
|
||||
//SetPlayerColor(playerid,COLOR_NORMAL_PLAYER);
|
||||
|
||||
//Kick(playerid);
|
||||
|
||||
/*
|
||||
Removes vending machines
|
||||
RemoveBuildingForPlayer(playerid, 1302, 0.0, 0.0, 0.0, 6000.0);
|
||||
RemoveBuildingForPlayer(playerid, 1209, 0.0, 0.0, 0.0, 6000.0);
|
||||
RemoveBuildingForPlayer(playerid, 955, 0.0, 0.0, 0.0, 6000.0);
|
||||
RemoveBuildingForPlayer(playerid, 1775, 0.0, 0.0, 0.0, 6000.0);
|
||||
RemoveBuildingForPlayer(playerid, 1776, 0.0, 0.0, 0.0, 6000.0);
|
||||
*/
|
||||
|
||||
/*
|
||||
new ClientVersion[32];
|
||||
GetPlayerVersion(playerid, ClientVersion, 32);
|
||||
printf("Player %d reports client version: %s", playerid, ClientVersion);*/
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
public OnPlayerSpawn(playerid)
|
||||
{
|
||||
if(IsPlayerNPC(playerid)) return 1;
|
||||
|
||||
new randSpawn = 0;
|
||||
|
||||
SetPlayerInterior(playerid,0);
|
||||
TogglePlayerClock(playerid,0);
|
||||
ResetPlayerMoney(playerid);
|
||||
GivePlayerMoney(playerid, 30000);
|
||||
|
||||
if(CITY_LOS_SANTOS == gPlayerCitySelection[playerid]) {
|
||||
randSpawn = random(sizeof(gRandomSpawns_LosSantos));
|
||||
SetPlayerPos(playerid,
|
||||
gRandomSpawns_LosSantos[randSpawn][0],
|
||||
gRandomSpawns_LosSantos[randSpawn][1],
|
||||
gRandomSpawns_LosSantos[randSpawn][2]);
|
||||
SetPlayerFacingAngle(playerid,gRandomSpawns_LosSantos[randSpawn][3]);
|
||||
}
|
||||
else if(CITY_SAN_FIERRO == gPlayerCitySelection[playerid]) {
|
||||
randSpawn = random(sizeof(gRandomSpawns_SanFierro));
|
||||
SetPlayerPos(playerid,
|
||||
gRandomSpawns_SanFierro[randSpawn][0],
|
||||
gRandomSpawns_SanFierro[randSpawn][1],
|
||||
gRandomSpawns_SanFierro[randSpawn][2]);
|
||||
SetPlayerFacingAngle(playerid,gRandomSpawns_SanFierro[randSpawn][3]);
|
||||
}
|
||||
else if(CITY_LAS_VENTURAS == gPlayerCitySelection[playerid]) {
|
||||
randSpawn = random(sizeof(gRandomSpawns_LasVenturas));
|
||||
SetPlayerPos(playerid,
|
||||
gRandomSpawns_LasVenturas[randSpawn][0],
|
||||
gRandomSpawns_LasVenturas[randSpawn][1],
|
||||
gRandomSpawns_LasVenturas[randSpawn][2]);
|
||||
SetPlayerFacingAngle(playerid,gRandomSpawns_LasVenturas[randSpawn][3]);
|
||||
}
|
||||
|
||||
//SetPlayerColor(playerid,COLOR_NORMAL_PLAYER);
|
||||
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_PISTOL,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_PISTOL_SILENCED,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_DESERT_EAGLE,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_SHOTGUN,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_SAWNOFF_SHOTGUN,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_SPAS12_SHOTGUN,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_MICRO_UZI,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_MP5,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_AK47,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_M4,200);
|
||||
SetPlayerSkillLevel(playerid,WEAPONSKILL_SNIPERRIFLE,200);
|
||||
|
||||
GivePlayerWeapon(playerid,WEAPON_COLT45,100);
|
||||
//GivePlayerWeapon(playerid,WEAPON_MP5,100);
|
||||
TogglePlayerClock(playerid, 0);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
public OnPlayerDeath(playerid, killerid, reason)
|
||||
{
|
||||
new playercash;
|
||||
|
||||
// if they ever return to class selection make them city
|
||||
// select again first
|
||||
gPlayerHasCitySelected[playerid] = 0;
|
||||
|
||||
if(killerid == INVALID_PLAYER_ID) {
|
||||
ResetPlayerMoney(playerid);
|
||||
} else {
|
||||
playercash = GetPlayerMoney(playerid);
|
||||
if(playercash > 0) {
|
||||
GivePlayerMoney(killerid, playercash);
|
||||
ResetPlayerMoney(playerid);
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
ClassSel_SetupCharSelection(playerid)
|
||||
{
|
||||
if(gPlayerCitySelection[playerid] == CITY_LOS_SANTOS) {
|
||||
SetPlayerInterior(playerid,11);
|
||||
SetPlayerPos(playerid,508.7362,-87.4335,998.9609);
|
||||
SetPlayerFacingAngle(playerid,0.0);
|
||||
SetPlayerCameraPos(playerid,508.7362,-83.4335,998.9609);
|
||||
SetPlayerCameraLookAt(playerid,508.7362,-87.4335,998.9609);
|
||||
}
|
||||
else if(gPlayerCitySelection[playerid] == CITY_SAN_FIERRO) {
|
||||
SetPlayerInterior(playerid,3);
|
||||
SetPlayerPos(playerid,-2673.8381,1399.7424,918.3516);
|
||||
SetPlayerFacingAngle(playerid,181.0);
|
||||
SetPlayerCameraPos(playerid,-2673.2776,1394.3859,918.3516);
|
||||
SetPlayerCameraLookAt(playerid,-2673.8381,1399.7424,918.3516);
|
||||
}
|
||||
else if(gPlayerCitySelection[playerid] == CITY_LAS_VENTURAS) {
|
||||
SetPlayerInterior(playerid,3);
|
||||
SetPlayerPos(playerid,349.0453,193.2271,1014.1797);
|
||||
SetPlayerFacingAngle(playerid,286.25);
|
||||
SetPlayerCameraPos(playerid,352.9164,194.5702,1014.1875);
|
||||
SetPlayerCameraLookAt(playerid,349.0453,193.2271,1014.1797);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
// Used to init textdraws of city names
|
||||
|
||||
ClassSel_InitCityNameText(Text:txtInit)
|
||||
{
|
||||
TextDrawUseBox(txtInit, 0);
|
||||
TextDrawLetterSize(txtInit,1.25,3.0);
|
||||
TextDrawFont(txtInit, 0);
|
||||
TextDrawSetShadow(txtInit,0);
|
||||
TextDrawSetOutline(txtInit,1);
|
||||
TextDrawColor(txtInit,0xEEEEEEFF);
|
||||
TextDrawBackgroundColor(txtClassSelHelper,0x000000FF);
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
ClassSel_InitTextDraws()
|
||||
{
|
||||
// Init our observer helper text display
|
||||
txtLosSantos = TextDrawCreate(10.0, 380.0, "Los Santos");
|
||||
ClassSel_InitCityNameText(txtLosSantos);
|
||||
txtSanFierro = TextDrawCreate(10.0, 380.0, "San Fierro");
|
||||
ClassSel_InitCityNameText(txtSanFierro);
|
||||
txtLasVenturas = TextDrawCreate(10.0, 380.0, "Las Venturas");
|
||||
ClassSel_InitCityNameText(txtLasVenturas);
|
||||
|
||||
// Init our observer helper text display
|
||||
txtClassSelHelper = TextDrawCreate(10.0, 415.0,
|
||||
" Press ~b~~k~~GO_LEFT~ ~w~or ~b~~k~~GO_RIGHT~ ~w~to switch cities.~n~ Press ~r~~k~~PED_FIREWEAPON~ ~w~to select.");
|
||||
TextDrawUseBox(txtClassSelHelper, 1);
|
||||
TextDrawBoxColor(txtClassSelHelper,0x222222BB);
|
||||
TextDrawLetterSize(txtClassSelHelper,0.3,1.0);
|
||||
TextDrawTextSize(txtClassSelHelper,400.0,40.0);
|
||||
TextDrawFont(txtClassSelHelper, 2);
|
||||
TextDrawSetShadow(txtClassSelHelper,0);
|
||||
TextDrawSetOutline(txtClassSelHelper,1);
|
||||
TextDrawBackgroundColor(txtClassSelHelper,0x000000FF);
|
||||
TextDrawColor(txtClassSelHelper,0xFFFFFFFF);
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
ClassSel_SetupSelectedCity(playerid)
|
||||
{
|
||||
if(gPlayerCitySelection[playerid] == -1) {
|
||||
gPlayerCitySelection[playerid] = CITY_LOS_SANTOS;
|
||||
}
|
||||
|
||||
if(gPlayerCitySelection[playerid] == CITY_LOS_SANTOS) {
|
||||
SetPlayerInterior(playerid,0);
|
||||
SetPlayerCameraPos(playerid,1630.6136,-2286.0298,110.0);
|
||||
SetPlayerCameraLookAt(playerid,1887.6034,-1682.1442,47.6167);
|
||||
|
||||
TextDrawShowForPlayer(playerid,txtLosSantos);
|
||||
TextDrawHideForPlayer(playerid,txtSanFierro);
|
||||
TextDrawHideForPlayer(playerid,txtLasVenturas);
|
||||
}
|
||||
else if(gPlayerCitySelection[playerid] == CITY_SAN_FIERRO) {
|
||||
SetPlayerInterior(playerid,0);
|
||||
SetPlayerCameraPos(playerid,-1300.8754,68.0546,129.4823);
|
||||
SetPlayerCameraLookAt(playerid,-1817.9412,769.3878,132.6589);
|
||||
|
||||
TextDrawHideForPlayer(playerid,txtLosSantos);
|
||||
TextDrawShowForPlayer(playerid,txtSanFierro);
|
||||
TextDrawHideForPlayer(playerid,txtLasVenturas);
|
||||
}
|
||||
else if(gPlayerCitySelection[playerid] == CITY_LAS_VENTURAS) {
|
||||
SetPlayerInterior(playerid,0);
|
||||
SetPlayerCameraPos(playerid,1310.6155,1675.9182,110.7390);
|
||||
SetPlayerCameraLookAt(playerid,2285.2944,1919.3756,68.2275);
|
||||
|
||||
TextDrawHideForPlayer(playerid,txtLosSantos);
|
||||
TextDrawHideForPlayer(playerid,txtSanFierro);
|
||||
TextDrawShowForPlayer(playerid,txtLasVenturas);
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
ClassSel_SwitchToNextCity(playerid)
|
||||
{
|
||||
gPlayerCitySelection[playerid]++;
|
||||
if(gPlayerCitySelection[playerid] > CITY_LAS_VENTURAS) {
|
||||
gPlayerCitySelection[playerid] = CITY_LOS_SANTOS;
|
||||
}
|
||||
PlayerPlaySound(playerid,1052,0.0,0.0,0.0);
|
||||
gPlayerLastCitySelectionTick[playerid] = GetTickCount();
|
||||
ClassSel_SetupSelectedCity(playerid);
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
ClassSel_SwitchToPreviousCity(playerid)
|
||||
{
|
||||
gPlayerCitySelection[playerid]--;
|
||||
if(gPlayerCitySelection[playerid] < CITY_LOS_SANTOS) {
|
||||
gPlayerCitySelection[playerid] = CITY_LAS_VENTURAS;
|
||||
}
|
||||
PlayerPlaySound(playerid,1053,0.0,0.0,0.0);
|
||||
gPlayerLastCitySelectionTick[playerid] = GetTickCount();
|
||||
ClassSel_SetupSelectedCity(playerid);
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
ClassSel_HandleCitySelection(playerid)
|
||||
{
|
||||
new Keys,ud,lr;
|
||||
GetPlayerKeys(playerid,Keys,ud,lr);
|
||||
|
||||
if(gPlayerCitySelection[playerid] == -1) {
|
||||
ClassSel_SwitchToNextCity(playerid);
|
||||
return;
|
||||
}
|
||||
|
||||
// only allow new selection every ~500 ms
|
||||
if( (GetTickCount() - gPlayerLastCitySelectionTick[playerid]) < 500 ) return;
|
||||
|
||||
if(Keys & KEY_FIRE) {
|
||||
gPlayerHasCitySelected[playerid] = 1;
|
||||
TextDrawHideForPlayer(playerid,txtClassSelHelper);
|
||||
TextDrawHideForPlayer(playerid,txtLosSantos);
|
||||
TextDrawHideForPlayer(playerid,txtSanFierro);
|
||||
TextDrawHideForPlayer(playerid,txtLasVenturas);
|
||||
TogglePlayerSpectating(playerid,0);
|
||||
return;
|
||||
}
|
||||
|
||||
if(lr > 0) {
|
||||
ClassSel_SwitchToNextCity(playerid);
|
||||
}
|
||||
else if(lr < 0) {
|
||||
ClassSel_SwitchToPreviousCity(playerid);
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
public OnPlayerRequestClass(playerid, classid)
|
||||
{
|
||||
if(IsPlayerNPC(playerid)) return 1;
|
||||
|
||||
if(gPlayerHasCitySelected[playerid]) {
|
||||
ClassSel_SetupCharSelection(playerid);
|
||||
return 1;
|
||||
} else {
|
||||
if(GetPlayerState(playerid) != PLAYER_STATE_SPECTATING) {
|
||||
TogglePlayerSpectating(playerid,1);
|
||||
TextDrawShowForPlayer(playerid, txtClassSelHelper);
|
||||
gPlayerCitySelection[playerid] = -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
public OnGameModeInit()
|
||||
{
|
||||
SetGameModeText("Grand Larceny");
|
||||
ShowPlayerMarkers(PLAYER_MARKERS_MODE_GLOBAL);
|
||||
ShowNameTags(1);
|
||||
SetNameTagDrawDistance(40.0);
|
||||
EnableStuntBonusForAll(0);
|
||||
DisableInteriorEnterExits();
|
||||
SetWeather(2);
|
||||
SetWorldTime(11);
|
||||
|
||||
//UsePlayerPedAnims();
|
||||
//ManualVehicleEngineAndLights();
|
||||
//LimitGlobalChatRadius(300.0);
|
||||
|
||||
ClassSel_InitTextDraws();
|
||||
|
||||
// Player Class
|
||||
AddPlayerClass(281,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(282,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(283,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(284,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(285,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(286,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(287,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(288,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(289,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(265,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(266,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(267,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(268,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(269,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(270,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(1,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(2,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(3,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(4,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(5,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(6,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(8,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(42,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(65,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
//AddPlayerClass(74,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(86,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(119,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(149,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(208,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(273,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(289,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
|
||||
AddPlayerClass(47,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(48,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(49,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(50,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(51,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(52,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(53,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(54,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(55,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(56,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(57,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(58,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(68,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(69,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(70,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(71,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(72,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(73,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(75,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(76,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(78,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(79,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(80,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(81,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(82,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(83,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(84,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(85,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(87,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(88,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(89,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(91,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(92,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(93,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(95,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(96,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(97,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(98,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
AddPlayerClass(99,1759.0189,-1898.1260,13.5622,266.4503,-1,-1,-1,-1,-1,-1);
|
||||
|
||||
// SPECIAL
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/trains.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/pilots.txt");
|
||||
|
||||
// LAS VENTURAS
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/lv_law.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/lv_airport.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/lv_gen.txt");
|
||||
|
||||
// SAN FIERRO
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/sf_law.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/sf_airport.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/sf_gen.txt");
|
||||
|
||||
// LOS SANTOS
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/ls_law.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/ls_airport.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/ls_gen_inner.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/ls_gen_outer.txt");
|
||||
|
||||
// OTHER AREAS
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/whetstone.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/bone.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/flint.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/tierra.txt");
|
||||
total_vehicles_from_files += LoadStaticVehiclesFromFile("vehicles/red_county.txt");
|
||||
|
||||
printf("Total vehicles from files: %d",total_vehicles_from_files);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
|
||||
public OnPlayerUpdate(playerid)
|
||||
{
|
||||
if(!IsPlayerConnected(playerid)) return 0;
|
||||
if(IsPlayerNPC(playerid)) return 1;
|
||||
|
||||
// changing cities by inputs
|
||||
if( !gPlayerHasCitySelected[playerid] &&
|
||||
GetPlayerState(playerid) == PLAYER_STATE_SPECTATING ) {
|
||||
ClassSel_HandleCitySelection(playerid);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// No weapons in interiors
|
||||
if(GetPlayerInterior(playerid) != 0 && GetPlayerWeapon(playerid) != 0) {
|
||||
SetPlayerArmedWeapon(playerid,0); // fists
|
||||
return 0; // no syncing until they change their weapon
|
||||
}
|
||||
|
||||
// Don't allow minigun
|
||||
if(GetPlayerWeapon(playerid) == WEAPON_MINIGUN) {
|
||||
Kick(playerid);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* No jetpacks allowed
|
||||
if(GetPlayerSpecialAction(playerid) == SPECIAL_ACTION_USEJETPACK) {
|
||||
Kick(playerid);
|
||||
return 0;
|
||||
}*/
|
||||
|
||||
/* For testing animations
|
||||
new msg[128+1];
|
||||
new animlib[32+1];
|
||||
new animname[32+1];
|
||||
|
||||
thisanimid = GetPlayerAnimationIndex(playerid);
|
||||
if(lastanimid != thisanimid)
|
||||
{
|
||||
GetAnimationName(thisanimid,animlib,32,animname,32);
|
||||
format(msg, 128, "anim(%d,%d): %s %s", lastanimid, thisanimid, animlib, animname);
|
||||
lastanimid = thisanimid;
|
||||
SendClientMessage(playerid, 0xFFFFFFFF, msg);
|
||||
}*/
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
90
samples/Prolog/or-constraint.ecl
Normal file
90
samples/Prolog/or-constraint.ecl
Normal file
@@ -0,0 +1,90 @@
|
||||
:- lib(ic).
|
||||
|
||||
/**
|
||||
* Question 1.11
|
||||
* vabs(?Val, ?AbsVal)
|
||||
*/
|
||||
vabs(Val, AbsVal):-
|
||||
AbsVal #> 0,
|
||||
(
|
||||
Val #= AbsVal
|
||||
;
|
||||
Val #= -AbsVal
|
||||
),
|
||||
labeling([Val, AbsVal]).
|
||||
|
||||
/**
|
||||
* vabsIC(?Val, ?AbsVal)
|
||||
*/
|
||||
vabsIC(Val, AbsVal):-
|
||||
AbsVal #> 0,
|
||||
Val #= AbsVal or Val #= -AbsVal,
|
||||
labeling([Val, AbsVal]).
|
||||
|
||||
/**
|
||||
* Question 1.12
|
||||
*/
|
||||
% X #:: -10..10, vabs(X, Y).
|
||||
% X #:: -10..10, vabsIC(X, Y).
|
||||
|
||||
/**
|
||||
* Question 1.13
|
||||
* faitListe(?ListVar, ?Taille, +Min, +Max)
|
||||
*/
|
||||
faitListe([], 0, _, _):-!.
|
||||
faitListe([First|Rest], Taille, Min, Max):-
|
||||
First #:: Min..Max,
|
||||
Taille1 #= Taille - 1,
|
||||
faitListe(Rest, Taille1, Min, Max).
|
||||
|
||||
/**
|
||||
* Question 1.14
|
||||
* suite(?ListVar)
|
||||
*/
|
||||
suite([Xi, Xi1, Xi2]):-
|
||||
checkRelation(Xi, Xi1, Xi2).
|
||||
suite([Xi, Xi1, Xi2|Rest]):-
|
||||
checkRelation(Xi, Xi1, Xi2),
|
||||
suite([Xi1, Xi2|Rest]).
|
||||
|
||||
/**
|
||||
* checkRelation(?Xi, ?Xi1, ?Xi2)
|
||||
*/
|
||||
checkRelation(Xi, Xi1, Xi2):-
|
||||
vabs(Xi1, VabsXi1),
|
||||
Xi2 #= VabsXi1 - Xi.
|
||||
|
||||
/**
|
||||
* Question 1.15
|
||||
* checkPeriode(+ListVar).
|
||||
*/
|
||||
% TODO Any better solution?
|
||||
checkPeriode(ListVar):-
|
||||
length(ListVar, Length),
|
||||
Length < 10.
|
||||
checkPeriode([X1, X2, X3, X4, X5, X6, X7, X8, X9, X10|Rest]):-
|
||||
X1 =:= X10,
|
||||
checkPeriode([X2, X3, X4, X5, X6, X7, X8, X9, X10|Rest]).
|
||||
% faitListe(ListVar, 18, -9, 9), suite(ListVar), checkPeriode(ListVar). => 99 solutions
|
||||
|
||||
|
||||
/**
|
||||
* Tests
|
||||
*/
|
||||
/*
|
||||
vabs(5, 5). => Yes
|
||||
vabs(5, -5). => No
|
||||
vabs(-5, 5). => Yes
|
||||
vabs(X, 5).
|
||||
vabs(X, AbsX).
|
||||
vabsIC(5, 5). => Yes
|
||||
vabsIC(5, -5). => No
|
||||
vabsIC(-5, 5). => Yes
|
||||
vabsIC(X, 5).
|
||||
vabsIC(X, AbsX).
|
||||
|
||||
faitListe(ListVar, 5, 1, 3). => 243 solutions
|
||||
faitListe([_, _, _, _, _], Taille, 1, 3). => Taille = 5 !!!!!!!!!!!!!!!!
|
||||
|
||||
faitListe(ListVar, 18, -9, 9), suite(ListVar). => 99 solutions
|
||||
*/
|
||||
5
samples/R/R-qgis-extension.rsx
Normal file
5
samples/R/R-qgis-extension.rsx
Normal file
@@ -0,0 +1,5 @@
|
||||
##polyg=vector
|
||||
##numpoints=number 10
|
||||
##output=output vector
|
||||
##[Example scripts]=group
|
||||
pts=spsample(polyg,numpoints,type="regular")
|
||||
7
samples/Scheme/basic.sld
Normal file
7
samples/Scheme/basic.sld
Normal file
@@ -0,0 +1,7 @@
|
||||
(define-library (libs basic)
|
||||
(export list2 x)
|
||||
(begin
|
||||
(define (list2 . objs) objs)
|
||||
(define x 'libs-basic)
|
||||
(define not-exported 'should-not-be-exported)
|
||||
))
|
||||
321
samples/Shen/graph.shen
Normal file
321
samples/Shen/graph.shen
Normal file
@@ -0,0 +1,321 @@
|
||||
\* graph.shen --- a library for graph definition and manipulation
|
||||
|
||||
Copyright (C) 2011, Eric Schulte
|
||||
|
||||
*** License:
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
- Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
- Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
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.
|
||||
|
||||
*** Commentary:
|
||||
|
||||
Graphs are represented as two dictionaries one for vertices and one
|
||||
for edges. It is important to note that the dictionary implementation
|
||||
used is able to accept arbitrary data structures as keys. This
|
||||
structure technically encodes hypergraphs (a generalization of graphs
|
||||
in which each edge may contain any number of vertices). Examples of a
|
||||
regular graph G and a hypergraph H with the corresponding data
|
||||
structure are given below.
|
||||
|
||||
|
||||
--G=<graph Vertices Edges>------------------------------------------------
|
||||
Vertices Edges
|
||||
---------- -------
|
||||
+----Graph G-----+ hash | key -> value hash | key -> value
|
||||
| | -----+------>-------- -----+-------->---------
|
||||
| a---b---c g | 1 | a -> [1] 1 | [a b] -> [1 2]
|
||||
| | | | 2 | b -> [1 2 3] 2 | [b c] -> [2 3]
|
||||
| d---e---f | 3 | c -> [2 4] 3 | [b d] -> [2 4]
|
||||
| | 4 | d -> [3 5] 4 | [c e] -> [3 5]
|
||||
+----------------+ 5 | e -> [4 5 6] 5 | [d e] -> [4 5]
|
||||
6 | f -> [6] 6 | [e f] -> [5 6]
|
||||
7 | g -> []
|
||||
|
||||
|
||||
--H=<graph Vertices Edges>------------------------------------------------
|
||||
Vertices Edges
|
||||
---------- -------
|
||||
hash | key -> value hash | key -> value
|
||||
+-- Hypergraph H----+ -----+------>-------- -----+-------->---------
|
||||
| | 1 | a -> [1] 1 | [a b [1 2
|
||||
| +------+ | 2 | b -> [1] | c d -> 3 4
|
||||
| +------+------+ | 3 | c -> [1] | e f] 5 6]
|
||||
| |a b c |d e f | | 4 | d -> [1 2] |
|
||||
| +------+------+ | 5 | e -> [1 2] 2 | [d e [4 5
|
||||
| |g h i | j | 6 | f -> [1 2] | f g -> 6 7
|
||||
| +------+ | 7 | g -> [2] | h i] 8 9]
|
||||
| | 8 | h -> [2]
|
||||
+-------------------+ 9 | i -> [2]
|
||||
10 | j -> []
|
||||
|
||||
|
||||
--G=<graph Vertices Edges>-------Graph with associated edge/vertex data---------
|
||||
Vertices Edges
|
||||
---------- -------
|
||||
+----Graph G-----+ hash | key -> value hash | key -> value
|
||||
| 4 6 7 | -----+------>-------- -----+-------->---------
|
||||
|0a---b---c g | 1 | a -> (@p 0 [1]) 1 | [a b] -> (@p 4 [1 2])
|
||||
| 1| 3| | 2 | b -> [1 2 3] 2 | [b c] -> (@p 6 [2 3])
|
||||
| d---e---f | 3 | c -> [2 4] 3 | [b d] -> (@p 1 [2 4])
|
||||
| 2 5 | 4 | d -> [3 5] 4 | [c e] -> (@p 3 [3 5])
|
||||
+----------------+ 5 | e -> [4 5 6] 5 | [d e] -> (@p 2 [4 5])
|
||||
6 | f -> [6] 6 | [e f] -> (@p 5 [5 6])
|
||||
7 | g -> (@p 7 [])
|
||||
|
||||
V = # of vertices
|
||||
E = # of edges
|
||||
M = # of vertex edge associations
|
||||
|
||||
size = size of all vertices + all vertices stored in Vertices dict
|
||||
M * sizeof(int) * 4 + indices into Vertices & Edge dicts
|
||||
V * sizeof(dict entry) + storage in the Vertex dict
|
||||
E * sizeof(dict entry) + storage in the Edge dict
|
||||
2 * sizeof(dict) the Vertices and Edge dicts
|
||||
|
||||
*** Code: *\
|
||||
(require dict)
|
||||
(require sequence)
|
||||
|
||||
(datatype graph
|
||||
Vertices : dictionary;
|
||||
Edges : dictoinary;
|
||||
===================
|
||||
(vector symbol Vertices Edges);)
|
||||
|
||||
(package graph- [graph graph? vertices edges add-vertex
|
||||
add-edge has-edge? has-vertex? edges-for
|
||||
neighbors connected-to connected? connected-components
|
||||
vertex-partition bipartite?
|
||||
\* included from the sequence library\ *\
|
||||
take drop take-while drop-while range flatten
|
||||
filter complement seperate zip indexed reduce
|
||||
mapcon partition partition-with unique frequencies
|
||||
shuffle pick remove-first interpose subset?
|
||||
cartesian-product
|
||||
\* included from the dict library\ *\
|
||||
dict? dict dict-> <-dict contents key? keys vals
|
||||
dictionary make-dict]
|
||||
|
||||
(define graph?
|
||||
X -> (= graph (<-address X 0)))
|
||||
|
||||
(define make-graph
|
||||
\* create a graph with specified sizes for the vertex dict and edge dict *\
|
||||
{number --> number --> graph}
|
||||
Vertsize Edgesize ->
|
||||
(let Graph (absvector 3)
|
||||
(do (address-> Graph 0 graph)
|
||||
(address-> Graph 1 (make-dict Vertsize))
|
||||
(address-> Graph 2 (make-dict Edgesize))
|
||||
Graph)))
|
||||
|
||||
(defmacro graph-macro
|
||||
\* return a graph taking optional sizes for the vertex and edge dicts *\
|
||||
[graph] -> [make-graph 1024 1024]
|
||||
[graph N] -> [make-graph N 1024]
|
||||
[graph N M] -> [make-graph N M])
|
||||
|
||||
(define vert-dict Graph -> (<-address Graph 1))
|
||||
|
||||
(define edge-dict Graph -> (<-address Graph 2))
|
||||
|
||||
(define vertices
|
||||
{graph --> (list A)}
|
||||
Graph -> (keys (vert-dict Graph)))
|
||||
|
||||
(define edges
|
||||
{graph --> (list (list A))}
|
||||
Graph -> (keys (edge-dict Graph)))
|
||||
|
||||
(define get-data
|
||||
Value V -> (if (tuple? Value)
|
||||
(fst Value)
|
||||
(error (make-string "no data for ~S~%" V))))
|
||||
|
||||
(define vertex-data
|
||||
Graph V -> (get-data (<-dict (vert-dict Graph) V) V))
|
||||
|
||||
(define edge-data
|
||||
Graph V -> (get-data (<-dict (edge-dict Graph) V) V))
|
||||
|
||||
(define resolve
|
||||
{(vector (list A)) --> (@p number number) --> A}
|
||||
Vector (@p Index Place) -> (nth (+ 1 Place) (<-vector Vector Index)))
|
||||
|
||||
(define resolve-vert
|
||||
{graph --> (@p number number) --> A}
|
||||
Graph Place -> (resolve (<-address (vert-dict Graph) 2) Place))
|
||||
|
||||
(define resolve-edge
|
||||
{graph --> (@p number number) --> A}
|
||||
Graph Place -> (resolve (<-address (edge-dict Graph) 2) Place))
|
||||
|
||||
(define edges-for
|
||||
{graph --> A --> (list (list A))}
|
||||
Graph Vert -> (let Val (trap-error (<-dict (vert-dict Graph) Vert) (/. E []))
|
||||
Edges (if (tuple? Val) (snd Val) Val)
|
||||
(map (lambda X (fst (resolve-edge Graph X))) Val)))
|
||||
|
||||
(define add-vertex-w-data
|
||||
\* add a vertex to a graph *\
|
||||
{graph --> A --> B --> A}
|
||||
G V Data -> (do (dict-> (vert-dict G) V (@p Data (edges-for G V))) V))
|
||||
|
||||
(define add-vertex-w/o-data
|
||||
\* add a vertex to a graph *\
|
||||
{graph --> A --> B --> A}
|
||||
G V -> (do (dict-> (vert-dict G) V (edges-for G V)) V))
|
||||
|
||||
(defmacro add-vertex-macro
|
||||
[add-vertex G V] -> [add-vertex-w/o-data G V]
|
||||
[add-vertex G V D] -> [add-vertex-w-data G V D])
|
||||
|
||||
(define update-vert
|
||||
\* in a dict, add an edge to a vertex's edge list *\
|
||||
{vector --> (@p number number) --> A --> number}
|
||||
Vs Edge V -> (let Store (<-address Vs 2)
|
||||
N (hash V (limit Store))
|
||||
VertLst (trap-error (<-vector Store N) (/. E []))
|
||||
Contents (trap-error (<-dict Vs V) (/. E []))
|
||||
(do (dict-> Vs V (if (tuple? Contents)
|
||||
(@p (fst Contents)
|
||||
(adjoin Edge (snd Contents)))
|
||||
(adjoin Edge Contents)))
|
||||
(@p N (length VertLst)))))
|
||||
|
||||
(define update-edges-vertices
|
||||
\* add an edge to a graph *\
|
||||
{graph --> (list A) --> (list A)}
|
||||
Graph Edge ->
|
||||
(let Store (<-address (edge-dict Graph) 2)
|
||||
EdgeID (hash Edge (limit Store))
|
||||
EdgeLst (trap-error (<-vector Store EdgeID) (/. E []))
|
||||
(map (update-vert (vert-dict Graph) (@p EdgeID (length EdgeLst))) Edge)))
|
||||
|
||||
(define add-edge-w-data
|
||||
G E D -> (do (dict-> (edge-dict G) E (@p D (update-edges-vertices G E))) E))
|
||||
|
||||
(define add-edge-w/o-data
|
||||
G E -> (do (dict-> (edge-dict G) E (update-edges-vertices G E)) E))
|
||||
|
||||
(defmacro add-edge-macro
|
||||
[add-edge G E] -> [add-edge-w/o-data G E]
|
||||
[add-edge G E V] -> [add-edge-w-data G E V])
|
||||
|
||||
(define has-edge?
|
||||
{graph --> (list A) --> boolean}
|
||||
Graph Edge -> (key? (edge-dict Graph) Edge))
|
||||
|
||||
(define has-vertex?
|
||||
{graph --> A --> boolean}
|
||||
Graph Vertex -> (key? (vert-dict Graph) Vertex))
|
||||
|
||||
(define neighbors
|
||||
\* Return the neighbors of a vertex *\
|
||||
{graph --> A --> (list A)}
|
||||
Graph Vert -> (unique (mapcon (remove-first Vert) (edges-for Graph Vert))))
|
||||
|
||||
(define connected-to-
|
||||
{graph --> (list A) --> (list A) --> (list A)}
|
||||
Graph [] Already -> Already
|
||||
Graph New Already ->
|
||||
(let Reachable (unique (mapcon (neighbors Graph) New))
|
||||
New (difference Reachable Already)
|
||||
(connected-to- Graph New (append New Already))))
|
||||
|
||||
(define connected-to
|
||||
\* return all vertices connected to the given vertex, including itself *\
|
||||
{graph --> A --> (list A)}
|
||||
Graph V -> (connected-to- Graph [V] [V]))
|
||||
|
||||
(define connected?
|
||||
\* return if a graph is fully connected *\
|
||||
{graph --> boolean}
|
||||
Graph -> (reduce (/. V Acc
|
||||
(and Acc
|
||||
(subset? (vertices Graph) (connected-to Graph V))))
|
||||
true (vertices Graph)))
|
||||
|
||||
(define connected-components-
|
||||
\* given a graph return a list of connected components *\
|
||||
{graph --> (list A) --> (list (list A)) --> (list graph)}
|
||||
Graph [] _ -> []
|
||||
Graph VS [] -> (map (/. V (let Component (graph 1 0)
|
||||
(do (add-vertex Component V) Component)))
|
||||
VS)
|
||||
Graph [V|VS] ES ->
|
||||
(let Con-verts (connected-to Graph V)
|
||||
Con-edges (filter (/. E (subset? E Con-verts)) ES)
|
||||
Component (graph (length Con-verts) (length Con-edges))
|
||||
(do (map (add-edge-w/o-data Component) Con-edges)
|
||||
(cons Component (connected-components- Graph
|
||||
(difference VS Con-verts)
|
||||
(difference ES Con-edges))))))
|
||||
|
||||
(define connected-components
|
||||
{graph --> (list graph)}
|
||||
Graph -> (connected-components- Graph (vertices Graph) (edges Graph)))
|
||||
|
||||
(define place-vertex
|
||||
\* given a graph, vertex and list of partitions, partition the vertex *\
|
||||
{graph --> A --> (list (list A)) --> (list (list A))}
|
||||
Graph V [] -> (if (element? V (neighbors Graph V))
|
||||
(simple-error
|
||||
(make-string "self-loop ~S, no vertex partition" V))
|
||||
[[V]])
|
||||
Graph V [C|CS] -> (let Neighbors (neighbors Graph V)
|
||||
(if (element? V Neighbors)
|
||||
(simple-error
|
||||
(make-string "self-loop ~S, no vertex partition" V))
|
||||
(if (empty? (intersection C Neighbors))
|
||||
[[V|C]|CS]
|
||||
[C|(place-vertex Graph V CS)]))))
|
||||
|
||||
(define vertex-partition
|
||||
\* partition the vertices of a graph *\
|
||||
{graph --> (list (list A))}
|
||||
Graph -> (reduce (place-vertex Graph) [] (vertices Graph)))
|
||||
|
||||
(define bipartite?
|
||||
\* check if a graph is bipartite *\
|
||||
{graph --> boolean}
|
||||
Graph -> (= 2 (length (vertex-partition Graph))))
|
||||
|
||||
)
|
||||
|
||||
\* simple tests
|
||||
|
||||
(set g (graph))
|
||||
(add-edge (value g) [chris patton])
|
||||
(add-edge (value g) [eric chris])
|
||||
(add-vertex (value g) nobody)
|
||||
(has-edge? (value g) [patton chris])
|
||||
(edges-for (value g) chris)
|
||||
(neighbors (value g) chris)
|
||||
(neighbors (value g) nobody)
|
||||
(connected-to (value g) chris)
|
||||
(connected? (value g))
|
||||
(connected-components (value g)) <- fail when package wrapper is used
|
||||
(map (function vertices) (connected-components (value g)))
|
||||
|
||||
*\
|
||||
102
samples/Shen/html.shen
Normal file
102
samples/Shen/html.shen
Normal file
@@ -0,0 +1,102 @@
|
||||
\* html.shen --- html generation functions for shen
|
||||
|
||||
Copyright (C) 2011, Eric Schulte
|
||||
|
||||
*** License:
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
- Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
- Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
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.
|
||||
|
||||
*** Commentary:
|
||||
|
||||
The standard lisp-to-html conversion tool suite. Follows some of
|
||||
the convertions of Clojure's hiccup.
|
||||
|
||||
an example...
|
||||
|
||||
(8-) (html [ul#todo1.tasks.stuff [: [title "today"]]
|
||||
(map (lambda Str [li Str]) ["get milk" "dishes"])])
|
||||
"<ul class='tasks stuff' id='todo1' title='today'>
|
||||
<li>get milk</li><li>dishes</li></ul>"
|
||||
|
||||
*** Code: *\
|
||||
(trap-error
|
||||
(require string)
|
||||
(/. E (load "../string/string.shen")))
|
||||
|
||||
(package string- [html
|
||||
\* symbols included from string *\
|
||||
takestr dropstr substr length-str index-str
|
||||
reverse-str starts-with substr? replace-str
|
||||
join split trim-left trim-right chomp trim]
|
||||
|
||||
(define to-str
|
||||
\* return argument as a string, if already a string do not change *\
|
||||
X -> X where (string? X)
|
||||
X -> (str X))
|
||||
|
||||
(define gassoc
|
||||
X Y -> (hd (tl (assoc X Y))))
|
||||
|
||||
(define dassoc
|
||||
X Y -> (remove (assoc X Y) Y))
|
||||
|
||||
(define passoc
|
||||
[] Y -> Y
|
||||
[X XV] Y -> (let Orig (gassoc X Y)
|
||||
New (if (cons? Orig) [XV|Orig] XV)
|
||||
[[X New]|(dassoc X Y)]))
|
||||
|
||||
(define html
|
||||
X -> X where (string? X)
|
||||
[Tag [: |Attrs] |Body] ->
|
||||
(let Tag-comps (css-parse-symbol Tag)
|
||||
Tag (gassoc tag Tag-comps)
|
||||
New-attrs (passoc (assoc class Tag-comps)
|
||||
(passoc (assoc id Tag-comps) Attrs))
|
||||
(@s (make-string "<~S" Tag) (attributes New-attrs) ">"
|
||||
(html Body)
|
||||
(make-string "</~S>" Tag))) where (symbol? Tag)
|
||||
[Tag|Body] -> (html [Tag [:] Body]) where (symbol? Tag)
|
||||
[H|HS] -> (@s (html H) (html HS))
|
||||
[] -> "")
|
||||
|
||||
(define css-parse-symbol
|
||||
{symbol --> [[symbol A]]}
|
||||
Symbol -> (let String (str Symbol)
|
||||
Class-split (split (str .) String)
|
||||
Class (map (function intern) (tl Class-split))
|
||||
Id-split (split (str #) (hd Class-split))
|
||||
Tag (hd Id-split)
|
||||
Id (tl Id-split)
|
||||
((if (= [] Id) (/. X X) (cons [id (intern (hd Id))]))
|
||||
((if (= [] Class) (/. X X) (cons [class Class]))
|
||||
[[tag (intern Tag)]]))))
|
||||
|
||||
(define attributes
|
||||
[] -> ""
|
||||
[[K V]|AS] -> (@s " " (to-str K) "='"
|
||||
(if (cons? V) (join " " (map (function str) V)) (to-str V))
|
||||
"'" (attributes AS)))
|
||||
|
||||
)
|
||||
39
samples/Shen/json.shen
Normal file
39
samples/Shen/json.shen
Normal file
@@ -0,0 +1,39 @@
|
||||
(load "grammar.shen")
|
||||
|
||||
\*
|
||||
|
||||
JSON Lexer
|
||||
|
||||
1. Read a stream of characters
|
||||
2. Whitespace characters not in strings should be discarded.
|
||||
3. Whitespace characters in strings should be preserved
|
||||
4. Strings can contain escaped double quotes. e.g. "\""
|
||||
|
||||
*\
|
||||
|
||||
(define whitespacep
|
||||
\* e.g. ASCII 32 == #\Space. *\
|
||||
\* All the others are whitespace characters from an ASCII table. *\
|
||||
Char -> (member Char ["c#9;" "c#10;" "c#11;" "c#12;" "c#13;" "c#32;"]))
|
||||
|
||||
(define replace-whitespace
|
||||
"" -> ""
|
||||
(@s Whitespace Suffix) -> (@s "" (replace-whitespace Suffix)) where (whitespacep Whitespace)
|
||||
(@s Prefix Suffix) -> (@s Prefix (replace-whitespace Suffix)))
|
||||
|
||||
(define fetch-until-unescaped-doublequote
|
||||
[] -> []
|
||||
["\" "c#34;" | Chars] -> ["\" "c#34;" | (fetch-until-unescaped-doublequote Chars)]
|
||||
["c#34;" | Chars] -> []
|
||||
[Char | Chars] -> [Char | (fetch-until-unescaped-doublequote Chars)])
|
||||
|
||||
\* (define strip-whitespace-chars *\
|
||||
\* [] -> [] *\
|
||||
\* ["c#34;" | Chars] -> ["c#34;" | ( *\
|
||||
\* [WhitespaceChar | Chars] -> (strip-whitespace-chars Chars) where (whitespace? WhitespaceChar) *\
|
||||
\* [Char | Chars] -> [Char | (strip-whitespace-chars Chars)]) *\
|
||||
|
||||
(define tokenise
|
||||
JSONString ->
|
||||
(let CharList (explode JSONString)
|
||||
CharList))
|
||||
216
samples/SystemVerilog/endpoint_phy_wrapper.svh
Normal file
216
samples/SystemVerilog/endpoint_phy_wrapper.svh
Normal file
@@ -0,0 +1,216 @@
|
||||
module endpoint_phy_wrapper
|
||||
(
|
||||
input clk_sys_i,
|
||||
input clk_ref_i,
|
||||
input clk_rx_i,
|
||||
input rst_n_i,
|
||||
|
||||
IWishboneMaster.master src,
|
||||
IWishboneSlave.slave snk,
|
||||
IWishboneMaster.master sys,
|
||||
|
||||
output [9:0] td_o,
|
||||
input [9:0] rd_i,
|
||||
|
||||
output txn_o,
|
||||
output txp_o,
|
||||
|
||||
input rxn_i,
|
||||
input rxp_i
|
||||
);
|
||||
|
||||
wire rx_clock;
|
||||
|
||||
parameter g_phy_type = "GTP";
|
||||
|
||||
wire[15:0] gtx_data;
|
||||
wire [1:0]gtx_k;
|
||||
wire gtx_disparity;
|
||||
wire gtx_enc_error;
|
||||
wire [15:0] grx_data;
|
||||
wire grx_clk;
|
||||
wire [1:0]grx_k;
|
||||
wire grx_enc_error;
|
||||
wire [3:0] grx_bitslide;
|
||||
wire gtp_rst;
|
||||
wire tx_clock;
|
||||
|
||||
generate
|
||||
if(g_phy_type == "TBI") begin
|
||||
|
||||
assign rx_clock = clk_ref_i;
|
||||
assign tx_clock = clk_rx_i;
|
||||
|
||||
|
||||
wr_tbi_phy U_Phy
|
||||
(
|
||||
.serdes_rst_i (gtp_rst),
|
||||
.serdes_loopen_i(1'b0),
|
||||
.serdes_prbsen_i(1'b0),
|
||||
.serdes_enable_i(1'b1),
|
||||
.serdes_syncen_i(1'b1),
|
||||
|
||||
.serdes_tx_data_i (gtx_data[7:0]),
|
||||
.serdes_tx_k_i (gtx_k[0]),
|
||||
.serdes_tx_disparity_o (gtx_disparity),
|
||||
.serdes_tx_enc_err_o (gtx_enc_error),
|
||||
|
||||
.serdes_rx_data_o (grx_data[7:0]),
|
||||
.serdes_rx_k_o (grx_k[0]),
|
||||
.serdes_rx_enc_err_o (grx_enc_error),
|
||||
.serdes_rx_bitslide_o (grx_bitslide),
|
||||
|
||||
|
||||
.tbi_refclk_i (clk_ref_i),
|
||||
.tbi_rbclk_i (clk_rx_i),
|
||||
|
||||
.tbi_td_o (td_o),
|
||||
.tbi_rd_i (rd_i),
|
||||
.tbi_syncen_o (),
|
||||
.tbi_loopen_o (),
|
||||
.tbi_prbsen_o (),
|
||||
.tbi_enable_o ()
|
||||
);
|
||||
|
||||
end else if (g_phy_type == "GTX") begin // if (g_phy_type == "TBI")
|
||||
wr_gtx_phy_virtex6
|
||||
#(
|
||||
.g_simulation(1)
|
||||
) U_PHY
|
||||
(
|
||||
.clk_ref_i(clk_ref_i),
|
||||
|
||||
.tx_clk_o (tx_clock),
|
||||
.tx_data_i (gtx_data),
|
||||
.tx_k_i (gtx_k),
|
||||
.tx_disparity_o (gtx_disparity),
|
||||
.tx_enc_err_o(gtx_enc_error),
|
||||
.rx_rbclk_o (rx_clock),
|
||||
.rx_data_o (grx_data),
|
||||
.rx_k_o (grx_k),
|
||||
.rx_enc_err_o (grx_enc_error),
|
||||
.rx_bitslide_o (),
|
||||
|
||||
.rst_i (!rst_n_i),
|
||||
.loopen_i (1'b0),
|
||||
|
||||
.pad_txn_o (txn_o),
|
||||
.pad_txp_o (txp_o),
|
||||
|
||||
.pad_rxn_i (rxn_i),
|
||||
.pad_rxp_i (rxp_i)
|
||||
);
|
||||
|
||||
end else if (g_phy_type == "GTP") begin // if (g_phy_type == "TBI")
|
||||
assign #1 tx_clock = clk_ref_i;
|
||||
|
||||
wr_gtp_phy_spartan6
|
||||
#(
|
||||
.g_simulation(1)
|
||||
) U_PHY
|
||||
(
|
||||
.gtp_clk_i(clk_ref_i),
|
||||
.ch0_ref_clk_i(clk_ref_i),
|
||||
|
||||
.ch0_tx_data_i (gtx_data[7:0]),
|
||||
.ch0_tx_k_i (gtx_k[0]),
|
||||
.ch0_tx_disparity_o (gtx_disparity),
|
||||
.ch0_tx_enc_err_o(gtx_enc_error),
|
||||
.ch0_rx_rbclk_o (rx_clock),
|
||||
.ch0_rx_data_o (grx_data[7:0]),
|
||||
.ch0_rx_k_o (grx_k[0]),
|
||||
.ch0_rx_enc_err_o (grx_enc_error),
|
||||
.ch0_rx_bitslide_o (),
|
||||
|
||||
.ch0_rst_i (!rst_n_i),
|
||||
.ch0_loopen_i (1'b0),
|
||||
|
||||
.pad_txn0_o (txn_o),
|
||||
.pad_txp0_o (txp_o),
|
||||
|
||||
.pad_rxn0_i (rxn_i),
|
||||
.pad_rxp0_i (rxp_i)
|
||||
);
|
||||
|
||||
end // else: !if(g_phy_type == "TBI")
|
||||
endgenerate
|
||||
|
||||
wr_endpoint
|
||||
#(
|
||||
.g_simulation (1),
|
||||
.g_pcs_16bit(g_phy_type == "GTX" ? 1: 0),
|
||||
.g_rx_buffer_size (1024),
|
||||
.g_with_rx_buffer(0),
|
||||
.g_with_timestamper (1),
|
||||
.g_with_dmtd (0),
|
||||
.g_with_dpi_classifier (1),
|
||||
.g_with_vlans (0),
|
||||
.g_with_rtu (0)
|
||||
) DUT (
|
||||
.clk_ref_i (clk_ref_i),
|
||||
.clk_sys_i (clk_sys_i),
|
||||
.clk_dmtd_i (clk_ref_i),
|
||||
.rst_n_i (rst_n_i),
|
||||
.pps_csync_p1_i (1'b0),
|
||||
|
||||
.phy_rst_o (),
|
||||
.phy_loopen_o (),
|
||||
.phy_enable_o (),
|
||||
.phy_syncen_o (),
|
||||
|
||||
.phy_ref_clk_i (tx_clock),
|
||||
.phy_tx_data_o (gtx_data),
|
||||
.phy_tx_k_o (gtx_k),
|
||||
.phy_tx_disparity_i (gtx_disparity),
|
||||
.phy_tx_enc_err_i (gtx_enc_error),
|
||||
|
||||
.phy_rx_data_i (grx_data),
|
||||
.phy_rx_clk_i (rx_clock),
|
||||
.phy_rx_k_i (grx_k),
|
||||
.phy_rx_enc_err_i (grx_enc_error),
|
||||
.phy_rx_bitslide_i (5'b0),
|
||||
|
||||
.src_dat_o (snk.dat_i),
|
||||
.src_adr_o (snk.adr),
|
||||
.src_sel_o (snk.sel),
|
||||
.src_cyc_o (snk.cyc),
|
||||
.src_stb_o (snk.stb),
|
||||
.src_we_o (snk.we),
|
||||
.src_stall_i (snk.stall),
|
||||
.src_ack_i (snk.ack),
|
||||
.src_err_i(1'b0),
|
||||
|
||||
.snk_dat_i (src.dat_o[15:0]),
|
||||
.snk_adr_i (src.adr[1:0]),
|
||||
.snk_sel_i (src.sel[1:0]),
|
||||
.snk_cyc_i (src.cyc),
|
||||
.snk_stb_i (src.stb),
|
||||
.snk_we_i (src.we),
|
||||
.snk_stall_o (src.stall),
|
||||
.snk_ack_o (src.ack),
|
||||
.snk_err_o (src.err),
|
||||
.snk_rty_o (src.rty),
|
||||
|
||||
.txtsu_ack_i (1'b1),
|
||||
|
||||
.rtu_full_i (1'b0),
|
||||
.rtu_almost_full_i (1'b0),
|
||||
.rtu_rq_strobe_p1_o (),
|
||||
.rtu_rq_smac_o (),
|
||||
.rtu_rq_dmac_o (),
|
||||
.rtu_rq_vid_o (),
|
||||
.rtu_rq_has_vid_o (),
|
||||
.rtu_rq_prio_o (),
|
||||
.rtu_rq_has_prio_o (),
|
||||
|
||||
.wb_cyc_i(sys.cyc),
|
||||
.wb_stb_i (sys.stb),
|
||||
.wb_we_i (sys.we),
|
||||
.wb_sel_i(sys.sel),
|
||||
.wb_adr_i(sys.adr[7:0]),
|
||||
.wb_dat_i(sys.dat_o),
|
||||
.wb_dat_o(sys.dat_i),
|
||||
.wb_ack_o (sys.ack)
|
||||
);
|
||||
|
||||
endmodule // endpoint_phy_wrapper
|
||||
7
samples/SystemVerilog/fifo.sv
Normal file
7
samples/SystemVerilog/fifo.sv
Normal file
@@ -0,0 +1,7 @@
|
||||
module fifo (
|
||||
input clk_50,
|
||||
input clk_2,
|
||||
input reset_n,
|
||||
output [7:0] data_out,
|
||||
output empty
|
||||
);
|
||||
18
samples/SystemVerilog/priority_encoder.sv
Normal file
18
samples/SystemVerilog/priority_encoder.sv
Normal file
@@ -0,0 +1,18 @@
|
||||
// http://hdlsnippets.com/parameterized_priority_encoder
|
||||
module priority_encoder #(parameter INPUT_WIDTH=8,OUTPUT_WIDTH=3)
|
||||
(
|
||||
input logic [INPUT_WIDTH-1:0] input_data,
|
||||
output logic [OUTPUT_WIDTH-1:0] output_data
|
||||
);
|
||||
|
||||
int ii;
|
||||
|
||||
always_comb
|
||||
begin
|
||||
output_data = 'b0;
|
||||
for(ii=0;ii<INPUT_WIDTH;ii++)
|
||||
if (input_data[ii])
|
||||
output_data = ii[OUTPUT_WIDTH-1:0];
|
||||
end
|
||||
|
||||
endmodule
|
||||
8
samples/SystemVerilog/util.vh
Normal file
8
samples/SystemVerilog/util.vh
Normal file
@@ -0,0 +1,8 @@
|
||||
function integer log2;
|
||||
input integer x;
|
||||
begin
|
||||
x = x-1;
|
||||
for (log2 = 0; x > 0; log2 = log2 + 1)
|
||||
x = x >> 1;
|
||||
end
|
||||
endfunction
|
||||
201
samples/Tcl/stream-0.1.tm
Normal file
201
samples/Tcl/stream-0.1.tm
Normal file
@@ -0,0 +1,201 @@
|
||||
# A stream ensemble
|
||||
#
|
||||
# Copyright (c) 2013 Lawrence Woodman <lwoodman@vlifesystems.com>
|
||||
#
|
||||
# Licensed under an MIT licence. Please see LICENCE.md for details.
|
||||
#
|
||||
|
||||
package require Tcl 8.5
|
||||
|
||||
namespace eval stream {
|
||||
namespace export {[a-z]*}
|
||||
namespace ensemble create
|
||||
}
|
||||
|
||||
proc stream::create {first restCmdPrefix} {
|
||||
return [list $first $restCmdPrefix]
|
||||
}
|
||||
|
||||
proc stream::first {stream} {
|
||||
lassign $stream first
|
||||
return $first
|
||||
}
|
||||
|
||||
proc stream::foldl {cmdPrefix initialValue args} {
|
||||
set numStreams [llength $args]
|
||||
if {$numStreams == 1} {
|
||||
FoldlSingleStream $cmdPrefix $initialValue [lindex $args 0]
|
||||
} elseif {$numStreams > 1} {
|
||||
FoldlMultiStream $cmdPrefix $initialValue $args
|
||||
} else {
|
||||
Usage "stream foldl cmdPrefix initalValue stream ?stream ..?"
|
||||
}
|
||||
}
|
||||
|
||||
proc stream::foreach {args} {
|
||||
set numArgs [llength $args]
|
||||
if {$numArgs == 3} {
|
||||
lassign $args varName stream body
|
||||
ForeachSingleStream $varName $stream $body
|
||||
} elseif {($numArgs > 3) && (($numArgs % 2) == 1)} {
|
||||
set body [lindex $args end]
|
||||
set items [lrange $args 0 end-1]
|
||||
ForeachMultiStream $items $body
|
||||
} else {
|
||||
Usage "stream foreach varName stream ?varName stream ..? body"
|
||||
}
|
||||
}
|
||||
|
||||
proc stream::fromList {_list {index 0}} {
|
||||
if {$index >= [llength $_list]} {return {}}
|
||||
create [lindex $_list $index] [list fromList $_list [expr {$index + 1}]]
|
||||
}
|
||||
|
||||
proc stream::isEmpty {stream} {
|
||||
expr {[llength $stream] == 0}
|
||||
}
|
||||
|
||||
proc stream::map {cmdPrefix args} {
|
||||
set numArgs [llength $args]
|
||||
if {$numArgs == 1} {
|
||||
MapSingleStream $cmdPrefix [lindex $args 0]
|
||||
} elseif {$numArgs > 1} {
|
||||
MapMultiStream $cmdPrefix $args
|
||||
} else {
|
||||
Usage "stream map cmdPrefix stream ?stream ..?"
|
||||
}
|
||||
}
|
||||
|
||||
proc stream::rest {stream} {
|
||||
set rest [lindex $stream 1]
|
||||
{*}$rest
|
||||
}
|
||||
|
||||
# Note: This will work through the elements of the stream until it finds
|
||||
# the first element that is matched by the cmdPrefix predicate.
|
||||
proc stream::select {cmdPrefix stream} {
|
||||
while {![isEmpty $stream]} {
|
||||
lassign $stream first rest
|
||||
if {[{*}$cmdPrefix $first]} {
|
||||
return [create $first [list select $cmdPrefix [{*}$rest]]]
|
||||
} else {
|
||||
set stream [{*}$rest]
|
||||
}
|
||||
}
|
||||
return $stream
|
||||
}
|
||||
|
||||
proc stream::take {num stream} {
|
||||
if {[isEmpty $stream] || $num <= 0} {
|
||||
return [::list]
|
||||
} else {
|
||||
lassign $stream first rest
|
||||
create $first [list take [expr {$num - 1}] [{*}$rest]]
|
||||
}
|
||||
}
|
||||
|
||||
proc stream::toList {stream} {
|
||||
set res [::list]
|
||||
while {![isEmpty $stream]} {
|
||||
lassign $stream first rest
|
||||
lappend res $first
|
||||
set stream [{*}$rest]
|
||||
}
|
||||
return $res
|
||||
}
|
||||
|
||||
|
||||
#################################
|
||||
# Internal
|
||||
#################################
|
||||
|
||||
proc stream::FoldlSingleStream {cmdPrefix initialValue stream} {
|
||||
set acc $initialValue
|
||||
while {![isEmpty $stream]} {
|
||||
lassign $stream first rest
|
||||
set acc [{*}$cmdPrefix $acc $first]
|
||||
set stream [{*}$rest]
|
||||
}
|
||||
return $acc
|
||||
}
|
||||
|
||||
proc stream::FoldlMultiStream {cmdPrefix initialValue streams} {
|
||||
set acc $initialValue
|
||||
|
||||
while 1 {
|
||||
set firsts [::list]
|
||||
set restStreams [::list]
|
||||
::foreach stream $streams {
|
||||
if {[isEmpty $stream]} {
|
||||
return $acc
|
||||
}
|
||||
lassign $stream first rest
|
||||
lappend firsts $first
|
||||
lappend restStreams [{*}$rest]
|
||||
}
|
||||
set acc [{*}$cmdPrefix $acc {*}$firsts]
|
||||
set streams $restStreams
|
||||
}
|
||||
return $acc
|
||||
}
|
||||
|
||||
proc stream::ForeachSingleStream {varName stream body} {
|
||||
set res {}
|
||||
while {![isEmpty $stream]} {
|
||||
lassign $stream first rest
|
||||
uplevel 2 [list set $varName $first]
|
||||
set stream [{*}$rest]
|
||||
set res [uplevel 2 $body]
|
||||
}
|
||||
return $res
|
||||
}
|
||||
|
||||
proc stream::ForeachMultiStream {items body} {
|
||||
set res {}
|
||||
|
||||
while 1 {
|
||||
set nextItems [::list]
|
||||
::foreach {varName stream} $items {
|
||||
if {[isEmpty $stream]} {
|
||||
return $res
|
||||
}
|
||||
lassign $stream first rest
|
||||
uplevel 2 [list set $varName $first]
|
||||
lappend nextItems $varName
|
||||
lappend nextItems [{*}$rest]
|
||||
}
|
||||
set res [uplevel 2 $body]
|
||||
set items $nextItems
|
||||
}
|
||||
|
||||
return $res
|
||||
}
|
||||
|
||||
proc stream::MapSingleStream {cmdPrefix stream} {
|
||||
if {[isEmpty $stream]} {
|
||||
return $stream
|
||||
}
|
||||
lassign $stream first rest
|
||||
create [{*}$cmdPrefix $first] [list MapSingleStream $cmdPrefix [{*}$rest]]
|
||||
}
|
||||
|
||||
proc stream::MapMultiStream {cmdPrefix streams} {
|
||||
set firsts [::list]
|
||||
set restStreams [::list]
|
||||
|
||||
::foreach stream $streams {
|
||||
if {[isEmpty $stream]} {
|
||||
return $stream
|
||||
}
|
||||
lassign $stream first rest
|
||||
lappend firsts $first
|
||||
lappend restStreams [{*}$rest]
|
||||
}
|
||||
|
||||
return [create [{*}$cmdPrefix {*}$firsts] \
|
||||
[list MapMultiStream $cmdPrefix $restStreams]]
|
||||
}
|
||||
|
||||
proc stream::Usage {msg} {
|
||||
return -code error -level 2 "wrong # args: should be \"$msg\""
|
||||
}
|
||||
76
samples/Tcl/xdgbasedir-0.3.tm
Normal file
76
samples/Tcl/xdgbasedir-0.3.tm
Normal file
@@ -0,0 +1,76 @@
|
||||
# XDG Base Directory Specification handling
|
||||
#
|
||||
# Copyright (C) 2013 Lawrence Woodman
|
||||
#
|
||||
# Licensed under an MIT licence. Please see LICENCE.md for details.
|
||||
#
|
||||
# For XDG Base Directory Specification
|
||||
# http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
||||
#
|
||||
package require Tcl 8.5
|
||||
|
||||
namespace eval XDG {
|
||||
variable DEFAULTS ""
|
||||
namespace export DATA_HOME CONFIG_HOME CACHE_HOME
|
||||
namespace export RUNTIME_DIR DATA_DIRS CONFIG_DIRS
|
||||
}
|
||||
|
||||
proc XDG::SetDefaults {} {
|
||||
variable DEFAULTS
|
||||
if {$DEFAULTS ne ""} return
|
||||
set DEFAULTS [list \
|
||||
DATA_HOME [file join $::env(HOME) .local share] \
|
||||
CONFIG_HOME [file join $::env(HOME) .config] \
|
||||
CACHE_HOME [file join $::env(HOME) .cache] \
|
||||
DATA_DIRS [list [file join /usr local share] [file join /usr share]] \
|
||||
CONFIG_DIRS [list [file join /etc xdg ]]
|
||||
]
|
||||
}
|
||||
|
||||
proc XDG::XDGVarSet {var} {
|
||||
expr {[info exists ::env(XDG_$var)] && $::env(XDG_$var) ne ""}
|
||||
}
|
||||
|
||||
proc XDG::Dir {var {subdir ""} } {
|
||||
variable DEFAULTS
|
||||
SetDefaults
|
||||
set dir [dict get $DEFAULTS $var]
|
||||
|
||||
if {[XDGVarSet $var]} {
|
||||
set dir $::env(XDG_$var)
|
||||
}
|
||||
|
||||
return [file join $dir $subdir]
|
||||
}
|
||||
|
||||
proc XDG::Dirs {var {subdir ""} } {
|
||||
variable DEFAULTS
|
||||
SetDefaults
|
||||
set rawDirs [dict get $DEFAULTS $var]
|
||||
|
||||
if {[XDGVarSet $var]} {
|
||||
set rawDirs [split $::env(XDG_$var) ":"]
|
||||
}
|
||||
|
||||
set outDirs {}
|
||||
foreach dir $rawDirs {
|
||||
lappend outDirs [file join $dir $subdir]
|
||||
}
|
||||
return $outDirs
|
||||
}
|
||||
|
||||
# The remaining procs reference the environmental variables XDG_
|
||||
# followed by the proc name.
|
||||
proc XDG::DATA_HOME {{subdir ""}} {Dir DATA_HOME $subdir}
|
||||
proc XDG::CONFIG_HOME {{subdir ""}} {Dir CONFIG_HOME $subdir}
|
||||
proc XDG::CACHE_HOME {{subdir ""}} {Dir CACHE_HOME $subdir}
|
||||
|
||||
proc XDG::RUNTIME_DIR {{subdir ""}} {
|
||||
if {![XDGVarSet RUNTIME_DIR]} { return {} }
|
||||
return [file join $::env(XDG_RUNTIME_DIR) $subdir]
|
||||
}
|
||||
|
||||
# The following procs returning the directories as a list with the most
|
||||
# important first.
|
||||
proc XDG::DATA_DIRS {{subdir ""}} {Dirs DATA_DIRS $subdir}
|
||||
proc XDG::CONFIG_DIRS {{subdir ""}} {Dirs CONFIG_DIRS $subdir}
|
||||
380
samples/TeX/problemset.cls
Normal file
380
samples/TeX/problemset.cls
Normal file
@@ -0,0 +1,380 @@
|
||||
% =====================================
|
||||
% problemset Document Style
|
||||
% For Problem Sets
|
||||
%
|
||||
% Options:
|
||||
% final hides to-dos
|
||||
% worksheet hides solutions and places each problem on separate page
|
||||
% expand places each problem on a separate page
|
||||
% =====================================
|
||||
|
||||
\ProvidesClass{problemset}
|
||||
\DeclareOption*{\PassOptionsToClass{final}{article}}
|
||||
\DeclareOption{worksheet}{\providecommand{\@solutionvis}{0}}
|
||||
\DeclareOption{expand}{\providecommand{\@expand}{1}}
|
||||
\ProcessOptions\relax
|
||||
|
||||
% ================== Packages and Document Options ==================
|
||||
\LoadClass[10pt,letterpaper]{article}
|
||||
\RequirePackage[%
|
||||
top=0.85in,
|
||||
bottom=1in,
|
||||
left=1in,
|
||||
right=1in
|
||||
]{geometry}
|
||||
\RequirePackage{pgfkeys} % For mathtable environment.
|
||||
\RequirePackage{tabularx} % For pset heading
|
||||
\RequirePackage{float} % Used for floats (tables, figures, etc.)
|
||||
\RequirePackage{graphicx} % Used for inserting images.
|
||||
\RequirePackage{enumerate} % Used for the enumerate environment.
|
||||
\RequirePackage{mathtools} % Required. Loads amsmath.
|
||||
\RequirePackage{amsthm} % Required. Used for theorem environments.
|
||||
\RequirePackage{amssymb} % Required.
|
||||
\RequirePackage{booktabs} % Required. Used for mathtable environment.
|
||||
\RequirePackage{esdiff} % For derivatives and partial derivatives
|
||||
\RequirePackage{mathtools} % Optional. Used for \shortintertext.
|
||||
\RequirePackage{fancyhdr} % Required. For customizing headers/footers.
|
||||
\RequirePackage{lastpage} % Required. For page count in header/footer.
|
||||
\RequirePackage{xcolor} % Required. For setting the color of hyperlinks
|
||||
\RequirePackage[%
|
||||
obeyFinal, % Disable todos by setting [final] option for class
|
||||
color=@todoclr,
|
||||
linecolor=red
|
||||
]{todonotes} % For keeping track of to-dos.
|
||||
\RequirePackage[%
|
||||
colorlinks=true,
|
||||
linkcolor=navy,
|
||||
urlcolor=black
|
||||
]{hyperref} % For following urls and references in a document.
|
||||
\RequirePackage{url} % Enables urls with the \url tag
|
||||
\RequirePackage[all]{hypcap}
|
||||
% hypcap: Links go to object instead of caption. [Keep as last package]
|
||||
|
||||
% ================== Appearance Settings ==================
|
||||
\definecolor{@todoclr}{gray}{0.80} % For To-Dos. 50% brightness
|
||||
\definecolor{navy}{RGB}{0,0,150} % For coloring hyperlinks
|
||||
\setlength{\parskip}{1.5ex} % Sets space between paragraphs.
|
||||
\setlength{\parindent}{0pt} % Indent for first line of new paragraphs.
|
||||
|
||||
% Smaller verbatim type size
|
||||
\let\VERBATIM\verbatim
|
||||
\def\verbatim{%
|
||||
\def\verbatim@font{\small\ttfamily}%
|
||||
\VERBATIM}
|
||||
|
||||
% ============= Caption Modifications =============
|
||||
\usepackage[small]{caption}
|
||||
\usepackage[footnotesize]{subcaption}
|
||||
% For no visible number, use: \caption*{Unnumbered figure caption.}
|
||||
\captionsetup[table]{labelformat=simple, labelsep=period, labelfont=bf}
|
||||
\captionsetup[figure]{labelformat=simple, labelsep=period, labelfont=bf}
|
||||
\captionsetup[subtable]{labelformat=parens, labelsep=space, labelfont=bf}
|
||||
\captionsetup[subfigure]{labelformat=simple, labelsep=period, labelfont=bf}
|
||||
|
||||
% ================== Booleans ==================
|
||||
\def\TRUE{1}
|
||||
\def\FALSE{0}
|
||||
\def\SHOW{1}
|
||||
\def\HIDE{0}
|
||||
|
||||
% ============= Gets Document Info, Generates Heading =============
|
||||
\providecommand{\heading}[5][]{
|
||||
\thispagestyle{empty}
|
||||
\listoftodos
|
||||
\clearpage
|
||||
\pagenumbering{arabic}
|
||||
%
|
||||
\providecommand{\shortname}{#1}
|
||||
\providecommand{\authorname}{#2}
|
||||
\providecommand{\coursename}{#3}
|
||||
\providecommand{\assignment}{#4}
|
||||
\providecommand{\duedate}{#5}
|
||||
\begin{minipage}{0.5\textwidth}
|
||||
\begin{flushleft}
|
||||
\hypertarget{@assignment}{
|
||||
\textbf{\assignment}
|
||||
}\\
|
||||
\authorname
|
||||
\end{flushleft}
|
||||
\end{minipage}
|
||||
\begin{minipage}{0.5\textwidth}
|
||||
\begin{flushright}
|
||||
\coursename\\
|
||||
\duedate\\
|
||||
\end{flushright}
|
||||
\end{minipage}
|
||||
\thispagestyle{empty}
|
||||
}
|
||||
|
||||
% ============= Headers and Footers =============
|
||||
\renewcommand{\headrulewidth}{0pt}
|
||||
\renewcommand{\footrulewidth}{0.5pt}
|
||||
\pagestyle{fancyplain}
|
||||
\fancyhf{}
|
||||
\lfoot{%
|
||||
\fancyplain{}{%
|
||||
\hyperlink{@assignment}{%
|
||||
\small{%
|
||||
\color{black}{%
|
||||
\assignment
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
\cfoot{%
|
||||
\fancyplain{}{%
|
||||
\small{%
|
||||
\coursename
|
||||
}
|
||||
}
|
||||
}
|
||||
\rfoot{%
|
||||
\fancyplain{}{%
|
||||
\small{\shortname~\thepage~of~\pageref{LastPage}}
|
||||
}
|
||||
}
|
||||
|
||||
% ============= Problem Command =============
|
||||
% INPUT: Points for question [#1] (Optional)
|
||||
\newcounter{theproblem} % Problem counter for environment
|
||||
|
||||
\providecommand{\problem}[1][]{%
|
||||
\addtocounter{theproblem}{1}%
|
||||
\setcounter{table}{0}%
|
||||
\setcounter{figure}{0}%
|
||||
\setcounter{equation}{0}%
|
||||
\noindent%
|
||||
\textbf{%
|
||||
Problem~\arabic{theproblem}.}~\textit{\small{#1}}
|
||||
|
||||
}
|
||||
|
||||
% ============= QED, Page Breaks After QED? =============
|
||||
\providecommand{\@expand}{\HIDE} % Default is to omit pagebreaks after the solution
|
||||
\providecommand{\qqed}{\hfill\rule{2mm}{2mm}\ifnum\@expand=\SHOW\\\pagebreak\fi}
|
||||
|
||||
|
||||
% ============= Solution Command =============
|
||||
\providecommand{\@solutionvis}{1} % Default setting is to show solutions.
|
||||
\providecommand{\solution}[2][\@solutionvis]{
|
||||
\vspace{0.5em}\noindent\textbf{Solution.}
|
||||
\ifnum#1=\SHOW%
|
||||
#2
|
||||
|
||||
\hfill\qqed\vspace{0.1em}
|
||||
\else%
|
||||
\pagebreak%
|
||||
\fi
|
||||
}
|
||||
|
||||
% ============= Chapter, Section, Item Commands =============
|
||||
\providecommand{\chap}[2][0]{
|
||||
\ifnum#1=0%
|
||||
\else%
|
||||
\setcounter{section}{#1}%
|
||||
\addtocounter{section}{-1}%
|
||||
\fi%
|
||||
\vspace{-1.75em}%
|
||||
\section{#2}
|
||||
}
|
||||
|
||||
\providecommand{\sect}[2][0]{
|
||||
\ifnum#1=0%
|
||||
\else%
|
||||
\setcounter{subsection}{#1}%
|
||||
\addtocounter{subsection}{-1}%
|
||||
\fi%
|
||||
\vspace{-0.5em}%
|
||||
\subsection{#2}
|
||||
}
|
||||
|
||||
\providecommand{\subsect}[1]{\noindent\textbf{#1.}}
|
||||
|
||||
% ============= Insert Non-Float Image =============
|
||||
\providecommand{\insertgraphic}[2][0.5\textwidth]{
|
||||
\vspace{-1em}
|
||||
\begin{center}
|
||||
\includegraphics[width=#1]{#2}
|
||||
\end{center}
|
||||
\vspace{-1em}
|
||||
}
|
||||
|
||||
|
||||
|
||||
% ============= Object Numbering by Problem =============
|
||||
\renewcommand{\thetable}{\arabic{theproblem}.\arabic{table}}
|
||||
\renewcommand{\thefigure}{\arabic{theproblem}.\arabic{figure}}
|
||||
\renewcommand{\theequation}{\arabic{theproblem}.\arabic{equation}}
|
||||
|
||||
|
||||
% ============= Formula Environment =============
|
||||
\newcounter{formula}
|
||||
\newenvironment{formula}[1][Formula \arabic{formula}]
|
||||
{
|
||||
\addtocounter{formula}{1}
|
||||
\begin{displaymath}
|
||||
\tag*{\parbox{5em}{\textbf{\small{#1}}}}
|
||||
}{
|
||||
\end{displaymath}\\
|
||||
}
|
||||
|
||||
% ============= Math Table =============
|
||||
\newif\ifcaption
|
||||
\pgfkeys
|
||||
{
|
||||
/mypkg/title/.store in=\Caption,% Any value assigned to title will be stored in \Caption
|
||||
/mypkg/title= , % Initialize so \Caption exists
|
||||
/mypkg/label/.store in=\Label, % Any value assigned to label will be stored in \Label
|
||||
/mypkg/label= , % Initialize so \Label exists
|
||||
/mypkg/caption/.is if=caption, % Declare a boolean, defaults to false
|
||||
}
|
||||
\newenvironment{mathtable}[2][]{
|
||||
\pgfkeys{/mypkg/.cd, #1}%
|
||||
\vspace{-1em}%
|
||||
\begin{table}[ht!]%
|
||||
\small \begin{center}%
|
||||
\begin{displaymath}%
|
||||
\begin{array}{#2}%
|
||||
\toprule
|
||||
}{
|
||||
\bottomrule
|
||||
\end{array}%
|
||||
\end{displaymath}%
|
||||
\ifcaption%
|
||||
\vspace{-1em}\caption{\Caption}\label{\Label}%
|
||||
\fi%
|
||||
\end{center}%
|
||||
\end{table}%
|
||||
\vspace{-1em}%
|
||||
}
|
||||
|
||||
|
||||
% ============= Double-line Column-Heading for table =============
|
||||
\providecommand{\double}[2]{%
|
||||
\multicolumn{1}{c}{%
|
||||
\genfrac{}{}{0pt}{}{\text{#1}}{\text{#2}}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
% ============= Theorem-Style Environments =============
|
||||
\theoremstyle{plain} % Bold label, italic letters
|
||||
\newtheorem{thm}{Theorem}[section] % Numbered by section
|
||||
\newtheorem{lma}[thm]{Lemma}
|
||||
\newtheorem{crl}[thm]{Corollary}
|
||||
\newtheorem{prp}[thm]{Proposition}
|
||||
\newtheorem{cnj}[thm]{Conjecture}
|
||||
\newtheorem{alg}[thm]{Algorithm}
|
||||
|
||||
% Associated environments (for numbered theorem environments)
|
||||
\newenvironment{theorem}[2][]{\begin{thm}[#1]\label{#2}}{\end{thm}}
|
||||
\newenvironment{lemma}[2][]{\begin{lma}[#1]\label{#2}}{\end{lma}}
|
||||
\newenvironment{corollary}[2][]{\begin{crl}[#1]\label{#2}}{\end{thm}}
|
||||
\newenvironment{proposition}[2][]{\begin{prp}[#1]\label{#2}}{\end{crl}}
|
||||
\newenvironment{conjecture}[2][]{\begin{cnj}[#1]\label{#2}}{\end{cnj}}
|
||||
\newenvironment{algorithm}[2][]{\begin{alg}[#1]\label{#2}}{\end{alg}}
|
||||
|
||||
\theoremstyle{remark} % Italic label, roman letters
|
||||
\newtheorem{rmk}{Remark}[section] % Numbered by section. Remarks are used to expand on and integrate material.
|
||||
\newtheorem*{note}{Note} % Un-numbered. Notes are used to comment on specific elements of the material.
|
||||
\newtheorem*{caveat}{Caveat} % Un-numbered. Caveats are used to guide the reader away from a common error.
|
||||
\newtheorem*{warning}{Warning} % Un-numbered. Warnings are used to guide away from especially egregious errors.
|
||||
|
||||
\theoremstyle{definition} % Bold label, roman letters
|
||||
\newtheorem{dfn}{Definition}[section] % Numbered by section. Definitions of concepts and terms.
|
||||
\newtheorem{exm}{Example}[section] % Numbered by section. Illustrative examples.
|
||||
\newtheorem{smm}{Summary}[subsection] % Numbered by subsection. For section summaries.
|
||||
\newtheorem*{question}{Question} % Un-numbered. For questions to motivate further analysis.
|
||||
\newtheorem*{speculation}{Speculation} % Un-numbered. For questions that arise but will not be immediately answered.
|
||||
|
||||
% Associated environments (for numbered theorem environments)
|
||||
\newenvironment{remark}[2][]{\begin{rmk}[#1]\label{#2}}{\end{rmk}}
|
||||
\newenvironment{definition}[2][]{\begin{dfn}[#1]\label{#2}}{\end{dfn}}
|
||||
\newenvironment{example}[2][]{\begin{exm}[#1]\label{#2}}{\end{exm}}
|
||||
\newenvironment{summary}[2][]{\begin{smm}[#1]\label{#2}}{\end{smm}}
|
||||
|
||||
|
||||
% ============= Greek Letters =============
|
||||
\renewcommand{\a}{\ensuremath{\alpha}}
|
||||
\renewcommand{\b}{\ensuremath{\beta}}
|
||||
\renewcommand{\c}{\ensuremath{\gamma}}
|
||||
\newcommand{\ch}{\ensuremath{\chi}}
|
||||
\renewcommand{\d}{\ensuremath{\delta}}
|
||||
\newcommand{\ep}{\ensuremath{\epsilon}}
|
||||
\newcommand{\et}{\ensuremath{\eta}}
|
||||
\newcommand{\ve}{\ensuremath{\varepsilon}}
|
||||
\renewcommand{\r}{\ensuremath{\rho}}
|
||||
\newcommand{\s}{\ensuremath{\sigma}}
|
||||
\renewcommand{\t}{\ensuremath{\tau}}
|
||||
\newcommand{\f}{\ensuremath{\psi}}
|
||||
\newcommand{\w}{\ensuremath{\omega}}
|
||||
\newcommand{\h}{\ensuremath{\phi}}
|
||||
\newcommand{\m}{\ensuremath{\mu}}
|
||||
\renewcommand{\l}{\ensuremath{\lambda}}
|
||||
\renewcommand{\k}{\ensuremath{\kappa}}
|
||||
\renewcommand{\v}{\ensuremath{\nu}}
|
||||
\renewcommand{\i}{\ensuremath{\iota}}
|
||||
\renewcommand{\o}{\ensuremath{\theta}}
|
||||
\newcommand{\z}{\ensuremath{\zeta}}
|
||||
|
||||
% ============= Mathematical Symbols =============
|
||||
\providecommand{\NN}{\ensuremath{\mathbb{N}}}
|
||||
\providecommand{\ZZ}{\ensuremath{\mathbb{Z}}}
|
||||
\providecommand{\QQ}{\ensuremath{\mathbb{Q}}}
|
||||
\providecommand{\RR}{\ensuremath{\mathbb{R}}}
|
||||
\providecommand{\CC}{\ensuremath{\mathbb{C}}}
|
||||
\providecommand{\pd}{\partial} % 'dee' symbol for partial derivatives
|
||||
\providecommand{\dd}{\mathrm{d}} % 'dee' symbol for ordinary derivatives
|
||||
\providecommand{\x}{\times}
|
||||
\providecommand{\n}{\scalebox{0.6}[1.0]{\ensuremath{-}}}
|
||||
|
||||
|
||||
|
||||
% ============= Mathematical Macros =============
|
||||
\providecommand{\Sum}[3][n]{\ensuremath{\sum_{{#1}={#2}}^{#3}}} % Sum from [n]={1}to{2}. \Sum{1}{10}
|
||||
\providecommand{\infsum}[2][n]{\ensuremath{\sum_{{#1}={#2}}^\infty}} % Infinite sum from [n]={1} \infsum{1}
|
||||
\providecommand{\Int}[4][x]{\ensuremath{\int_{#3}^{#4}\!{#2}\,\mathrm{d}{#1}}} % Integrate {1} from {2} to {3} with respect to [x]
|
||||
\providecommand{\Lim}[3][\infty]{\ensuremath{\displaystyle \lim_{{#2}\to{#1}}\!\!{#3}}} % Take the limit from {1} to [infinity] of {3} \Lim{x}{f(x)}
|
||||
\providecommand{\Frac}[2]{\ensuremath{\,^{#1}\!/\!_{#2}}} % Slanted fraction with proper spacing. Usefule for in-line display of fractions.
|
||||
\providecommand{\eval}[3]{\ensuremath{\left[ #1 \right \vert_{#2}^{#3}}}
|
||||
\renewcommand{\L}{\left} % for left-hand right-sizing
|
||||
\providecommand{\R}{\right} % for right-hand right-sizing
|
||||
\providecommand{\D}{\diff} % for writing derivatives
|
||||
\providecommand{\PD}{\diffp} % for writing partial derivatives
|
||||
\providecommand{\full}{\displaystyle} % Forces display style in math mode
|
||||
\providecommand{\Deg}{\ensuremath{^\circ}} % for adding a degree symbol, even if not in math mode
|
||||
\providecommand{\abs}[1]{\left\vert #1 \right\vert} % Absolute Value
|
||||
\providecommand{\norm}[1]{\left \Vert #1 \right \Vert} % Norm (vector magnitude)
|
||||
\providecommand{\e}[1]{\ensuremath{\times 10^{#1}}} % Scientific Notation with times symbol
|
||||
\providecommand{\E}[1]{\ensuremath{10^{#1}}} % Scientific Notation
|
||||
\renewcommand{\u}[1]{\text{ #1}} % For inserting units in Roman text
|
||||
\providecommand{\mc}{\text{,}\hspace{1em}} % For inserting comma and space into math mode
|
||||
\providecommand{\mtxt}[2][]{#1\hspace{0.5em}\text{#2}\hspace{0.5em}} % For insterting text into math mode with space on either side. Option for preceding punctuation.
|
||||
|
||||
% ============= Probability and Statistics =============
|
||||
\providecommand{\prob}[1]{\ensuremath{P\!\left(#1\right)} }
|
||||
\providecommand{\cndprb}[2]{\ensuremath{P\!\left(#1 \left\vert #2 \right. \right)} }
|
||||
\providecommand{\cov}[1]{\ensuremath{\text{Cov}\!\left(#1\right)} }
|
||||
\providecommand{\ex}[1]{\ensuremath{E\!\left[#1\right]} }
|
||||
|
||||
% ============= Linear Algebra =============
|
||||
|
||||
% Column vectors
|
||||
\providecommand{\twovector}[3][r]{\left(\begin{array}{#1} #2 \\ #3\end{array}\right)}
|
||||
\providecommand{\threevector}[4][r]{\left(\begin{array}{#1} #2 \\ #3 \\ #4\end{array}\right)}
|
||||
\providecommand{\fourvector}[5][r]{\left(\begin{array}{#1} #2 \\ #3 \\ #4 \\ #5 \end{array}\right)}
|
||||
|
||||
% ============= Vector Calculus =============
|
||||
% ------------- Susan Lea's notation ---------------
|
||||
\providecommand{\vecs}[1]{\ensuremath{\vec{\bm{#1}}} } % bolded symbol, arrow
|
||||
\providecommand{\vect}[1]{\ensuremath{\vec{\textbf{#1}}} } % bolded text, arrow
|
||||
\providecommand{\unitvecs}[1]{\bm{\hat{#1}}}
|
||||
\providecommand{\unitvect}[1]{\hat{\textbf{#1}}}
|
||||
\providecommand{\Div}[1]{\vecs{\del} \cdot \vect{#1}}
|
||||
\providecommand{\Curl}[1]{\vecs{\del} \times \vect{#1}}
|
||||
\providecommand{\Grad}{\vecs{\del}}
|
||||
|
||||
|
||||
|
||||
|
||||
47
samples/XML/pt_BR.xml
Normal file
47
samples/XML/pt_BR.xml
Normal file
@@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!DOCTYPE TS>
|
||||
<TS version="2.0" language="pt_BR">
|
||||
<context>
|
||||
<name>MainWindow</name>
|
||||
<message>
|
||||
<location filename="../forms/mainwindow.ui" line="22"/>
|
||||
<source>United Kingdom</source>
|
||||
<translation>Reino Unido</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../forms/mainwindow.ui" line="38"/>
|
||||
<source>God save the Queen</source>
|
||||
<translation>Deus salve a Rainha</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="46"/>
|
||||
<source>England</source>
|
||||
<translation>Inglaterra</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="47"/>
|
||||
<source>Wales</source>
|
||||
<translation>Gales</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="48"/>
|
||||
<source>Scotland</source>
|
||||
<translation>Escócia</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="49"/>
|
||||
<source>Northern Ireland</source>
|
||||
<translation>Irlanda Norte</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="51"/>
|
||||
<source>Portuguese</source>
|
||||
<translation>Português</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="52"/>
|
||||
<source>English</source>
|
||||
<translation>Inglês</translation>
|
||||
</message>
|
||||
</context>
|
||||
</TS>
|
||||
20
samples/YAML/vcr_cassette.yml
Normal file
20
samples/YAML/vcr_cassette.yml
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
http_interactions:
|
||||
- request:
|
||||
method: get
|
||||
uri: http://example.com/
|
||||
body: ''
|
||||
headers: {}
|
||||
response:
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
headers:
|
||||
Content-Type:
|
||||
- text/html;charset=utf-8
|
||||
Content-Length:
|
||||
- '26'
|
||||
body: This is the response body
|
||||
http_version: '1.1'
|
||||
recorded_at: Tue, 01 Nov 2011 04:58:44 GMT
|
||||
recorded_with: VCR 2.0.0
|
||||
@@ -211,6 +211,9 @@ class TestBlob < Test::Unit::TestCase
|
||||
assert !blob("CSS/bootstrap.css").generated?
|
||||
assert blob("CSS/bootstrap.min.css").generated?
|
||||
|
||||
# Generated VCR
|
||||
assert blob("YAML/vcr_cassette.yml").generated?
|
||||
|
||||
assert Linguist::Generated.generated?("node_modules/grunt/lib/grunt.js", nil)
|
||||
end
|
||||
|
||||
@@ -343,6 +346,14 @@ class TestBlob < Test::Unit::TestCase
|
||||
|
||||
# Vagrant
|
||||
assert blob("Vagrantfile").vendored?
|
||||
|
||||
# Gradle
|
||||
assert blob("gradlew").vendored?
|
||||
assert blob("gradlew.bat").vendored?
|
||||
assert blob("gradle/wrapper/gradle-wrapper.properties").vendored?
|
||||
assert blob("subproject/gradlew").vendored?
|
||||
assert blob("subproject/gradlew.bat").vendored?
|
||||
assert blob("subproject/gradle/wrapper/gradle-wrapper.properties").vendored?
|
||||
end
|
||||
|
||||
def test_language
|
||||
|
||||
@@ -15,14 +15,14 @@ class TestHeuristcs < Test::Unit::TestCase
|
||||
File.read(File.join(samples_path, name))
|
||||
end
|
||||
|
||||
# Only calling out '.h' filenames as these are the ones causing issues
|
||||
def all_h_fixtures(language_name)
|
||||
Dir.glob("#{samples_path}/#{language_name}/*.h")
|
||||
def all_fixtures(language_name, file="*")
|
||||
Dir.glob("#{samples_path}/#{language_name}/#{file}")
|
||||
end
|
||||
|
||||
def test_obj_c_by_heuristics
|
||||
languages = ["C++", "Objective-C"]
|
||||
all_h_fixtures("Objective-C").each do |fixture|
|
||||
# Only calling out '.h' filenames as these are the ones causing issues
|
||||
all_fixtures("Objective-C", "*.h").each do |fixture|
|
||||
results = Heuristics.disambiguate_c(fixture("Objective-C/#{File.basename(fixture)}"), languages)
|
||||
assert_equal Language["Objective-C"], results.first
|
||||
end
|
||||
@@ -50,4 +50,38 @@ class TestHeuristcs < Test::Unit::TestCase
|
||||
results = Heuristics.disambiguate_pl(fixture("Perl/perl-test.t"), languages)
|
||||
assert_equal Language["Perl"], results.first
|
||||
end
|
||||
|
||||
def test_ecl_prolog_by_heuristics
|
||||
languages = ["ECL", "Prolog"]
|
||||
results = Heuristics.disambiguate_ecl(fixture("Prolog/or-constraint.ecl"), languages)
|
||||
assert_equal Language["Prolog"], results.first
|
||||
end
|
||||
|
||||
def test_ecl_ecl_by_heuristics
|
||||
languages = ["ECL", "Prolog"]
|
||||
results = Heuristics.disambiguate_ecl(fixture("ECL/sample.ecl"), languages)
|
||||
assert_equal Language["ECL"], results.first
|
||||
end
|
||||
|
||||
def test_ts_typescript_by_heuristics
|
||||
languages = ["TypeScript", "XML"]
|
||||
results = Heuristics.disambiguate_ts(fixture("TypeScript/classes.ts"), languages)
|
||||
assert_equal Language["TypeScript"], results.first
|
||||
end
|
||||
|
||||
def test_ts_xml_by_heuristics
|
||||
languages = ["TypeScript", "XML"]
|
||||
results = Heuristics.disambiguate_ts(fixture("XML/pt_BR.xml"), languages)
|
||||
assert_equal Language["XML"], results.first
|
||||
end
|
||||
|
||||
def test_cl_by_heuristics
|
||||
languages = ["Common Lisp", "OpenCL"]
|
||||
languages.each do |language|
|
||||
all_fixtures(language).each do |fixture|
|
||||
results = Heuristics.disambiguate_cl(fixture("#{language}/#{File.basename(fixture)}"), languages)
|
||||
assert_equal Language[language], results.first
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -10,6 +10,7 @@ class TestLanguage < Test::Unit::TestCase
|
||||
|
||||
def test_lexer
|
||||
assert_equal Lexer['ActionScript 3'], Language['ActionScript'].lexer
|
||||
assert_equal Lexer['AspectJ'], Language['AspectJ'].lexer
|
||||
assert_equal Lexer['Bash'], Language['Gentoo Ebuild'].lexer
|
||||
assert_equal Lexer['Bash'], Language['Gentoo Eclass'].lexer
|
||||
assert_equal Lexer['Bash'], Language['Shell'].lexer
|
||||
@@ -322,7 +323,7 @@ class TestLanguage < Test::Unit::TestCase
|
||||
def test_color
|
||||
assert_equal '#701516', Language['Ruby'].color
|
||||
assert_equal '#3581ba', Language['Python'].color
|
||||
assert_equal '#f15501', Language['JavaScript'].color
|
||||
assert_equal '#f7df1e', Language['JavaScript'].color
|
||||
assert_equal '#31859c', Language['TypeScript'].color
|
||||
end
|
||||
|
||||
@@ -385,6 +386,15 @@ class TestLanguage < Test::Unit::TestCase
|
||||
<div class="highlight"><pre><span class="k">def</span> <span class="nf">foo</span>
|
||||
<span class="s1">'foo'</span>
|
||||
<span class="k">end</span>
|
||||
</pre></div>
|
||||
HTML
|
||||
end
|
||||
|
||||
def test_colorize_with_options
|
||||
assert_equal <<-HTML.chomp, Language['Ruby'].colorize("def foo\n 'foo'\nend\n", :options => { :cssclass => "highlight highlight-ruby" })
|
||||
<div class="highlight highlight-ruby"><pre><span class="k">def</span> <span class="nf">foo</span>
|
||||
<span class="s1">'foo'</span>
|
||||
<span class="k">end</span>
|
||||
</pre></div>
|
||||
HTML
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user