id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12,311 | generate-commands.lisp | informatimago_commands/generate-commands.lisp | (in-package "COMMON-LISP-USER")
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless *load-truename*
(error "This script must be loaded as source.")))
;;; --------------------------------------------------------------------
(defparameter *base-directory* (make-pathname :name nil :type nil :version nil :defaults *load-truename*))
(defparameter *source-directory* (merge-pathnames #P"./sources/" *base-directory* nil))
(defparameter *asdf-directories* (mapcar (lambda (path) (make-pathname :name nil :type nil :version nil :defaults path))
(append (directory (merge-pathnames "**/*.asd" *source-directory* nil))
(directory (merge-pathnames "src/public/lisp/**/*.asd" (user-homedir-pathname) nil))
(list *source-directory*))))
(defparameter *release-directory* *base-directory* #|#P"HOME:bin;"|# "Where the executable will be stored." )
;;; --------------------------------------------------------------------
(load (merge-pathnames "generate.lisp" *base-directory*))
(load-quicklisp)
(configure-asdf-directories *asdf-directories*)
(ql:quickload :com.informatimago.command)
(load (merge-pathnames "builder.lisp" *base-directory*)) ; sets *failures*
(in-package "COM.INFORMATIMAGO.COMMAND.GENERATE")
#-testing
(unless (zerop *failures*)
(format t "~&;~D failures~%" *failures*)
(finish-output)
(script:exit 1))
;;; Save the lisp image
#-testing
(cl-user::generate-program :program-name "commands"
:main-function "COM.INFORMATIMAGO.COMMAND.SCRIPT:DISPATCH-COMMAND"
:system-name nil
:system-list '()
:init-file "~/.commands.lisp"
:version "1.0.0"
:copyright #.(format nil "Copyright Pascal J. Bourguignon 2019 - ~A~%License: AGPL3"
(nth-value 5 (decode-universal-time (get-universal-time))))
:source-directory cl-user::*source-directory*
:asdf-directories cl-user::*asdf-directories*
:release-directory cl-user::*release-directory*)
;; In most implementations, we should not reach this point, since saving the image exits.
#-testing (script:exit 0)
| 2,415 | Common Lisp | .lisp | 39 | 49.333333 | 134 | 0.564428 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 8ca825ff787c0a85359f049467312b901416a04d9c9c454f6da96a03851170a9 | 12,311 | [
-1
] |
12,312 | loader.lisp | informatimago_commands/loader.lisp | (in-package "COMMON-LISP-USER")
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless *load-truename*
(error "This script must be loaded as source.")))
;;; --------------------------------------------------------------------
;;;
(defparameter *base-directory* (make-pathname :name nil :type nil :version nil :defaults *load-truename*))
(defparameter *source-directory* (merge-pathnames #P"./sources/" *base-directory* nil))
(defparameter *asdf-directories* (mapcar (lambda (path) (make-pathname :name nil :type nil :version nil :defaults path))
(append (directory (merge-pathnames "**/*.asd" *source-directory* nil))
(directory (merge-pathnames "src/public/lisp/**/*.asd" (user-homedir-pathname) nil))
(list *source-directory*))))
(defparameter *release-directory* *base-directory* #|#P"HOME:bin;"|# "Where the executable will be stored." )
;;; --------------------------------------------------------------------
(load (merge-pathnames "generate.lisp" *base-directory*))
(configure-asdf-directories *asdf-directories*)
(ql:quickload :com.informatimago.command)
(load (merge-pathnames "builder.lisp" *base-directory*)) ; sets *failures*
(in-package "COM.INFORMATIMAGO.COMMAND.GENERATE")
(unless (zerop *failures*)
(format t "~&;~D failures~%" *failures*)
(finish-output))
| 1,445 | Common Lisp | .lisp | 22 | 57.454545 | 134 | 0.585452 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6b27105effa0a6d074df425126665127771c7c0eaf65e578bf172b0a4feb5b28 | 12,312 | [
-1
] |
12,313 | generate.lisp | informatimago_commands/generate.lisp | (in-package "COMMON-LISP-USER")
;; Remove used package from CL-USER to avoid conflicts.
;; Note: this doesn't remove directly imported symbols.
(mapc (lambda (package) (unuse-package package "COMMON-LISP-USER"))
(set-difference
(copy-seq (package-use-list "COMMON-LISP-USER"))
(delete nil (list ;; A list of all the "CL" packages possible:
(find-package "COMMON-LISP")))))
;;; --------------------------------------------------------------------
;;; Utilities
;;;
(defun say (format-control &rest arguments)
(format t "~&;;; ~?~%" format-control arguments)
(finish-output))
(defun runtime-function (name) (read-from-string name))
(defun runtime-symbol (name) (read-from-string name))
(defun runtime-value (name) (symbol-value (read-from-string name)))
(defun (setf runtime-value) (new-value name) (setf (symbol-value (read-from-string name)) new-value))
(defun load-quicklisp ()
(say "Loading quicklisp.")
(load #P"~/quicklisp/setup.lisp")
(setf (runtime-value "QUICKLISP-CLIENT:*QUICKLOAD-VERBOSE*") t))
(defun configure-asdf-directories (directories &key append)
(if (member :asdf3 *features*)
(funcall (runtime-function "ASDF:INITIALIZE-SOURCE-REGISTRY")
`(:source-registry
:ignore-inherited-configuration
,@(mapcar (lambda (dir) `(:directory ,dir))
(remove-duplicates directories :test (function equalp)))
,@(when append `(:default-registry))))
(setf (runtime-value "ASDF:*CENTRAL-REGISTRY*")
(remove-duplicates (if append
(append directories (runtime-value "ASDF:*CENTRAL-REGISTRY*"))
directories)
:test (function equalp)))))
(defun not-implemented-yet (what)
(error "~S is not implemented yet on ~A, please provide a patch!"
what (lisp-implementation-type)))
#-(and)
(defun program-path ()
(let* ((argv (ext:argv))
(largv (length argv))
(args ext:*args*)
(largs (length args))
(index (- largv largs 1))
(path (and (<= 0 index largv) (elt argv index))))
(cond
(path
path)
((and *load-truename*
(string/= (file-namestring *load-truename*) "script.lisp"))
(namestring *load-truename*))
(t
*default-program-name*))))
(defun argv ()
#+ccl ccl:*command-line-argument-list*
#+clisp (cons (elt (ext:argv) 0) ext:*args*)
#+ecl (si::command-args)
#+sbcl sb-ext:*posix-argv*
#-(or ccl clisp ecl sbcl) (not-implemented-yet 'exit))
(defun exit (status)
#+ccl (ccl:quit status)
#+clisp (ext:quit status)
#+ecl (ext:quit status)
#+sbcl (sb-ext:exit :code status)
#-(or ccl clisp ecl sbcl) (not-implemented-yet 'exit))
(defun make-toplevel-function (main-function-name init-file)
(let ((form `(lambda ()
(handler-case
(progn
,@(when init-file
`((load ,init-file :if-does-not-exist nil)))
(apply (read-from-string ,main-function-name)
#+ecl (si::command-args) #-ecl (argv)))
(error (err)
(finish-output *standard-output*)
(finish-output *trace-output*)
(format *error-output* "~%~A~%" err)
(finish-output *error-output*)
#+ecl (ext:quit 1) #-ecl (exit 1)))
(finish-output *standard-output*)
(finish-output *trace-output*)
#+ecl (ext:quit 0) #-ecl (exit 0))))
#+ecl (list form)
#-ecl (coerce form 'function)))
(defun system-cl-source-files (system)
(let ((system (funcall (runtime-function "ASDF:FIND-SYSTEM") system)))
(remove-duplicates
(append
(mapcar (runtime-function "ASDF:COMPONENT-PATHNAME")
(remove-if-not (lambda (component) (typep component (runtime-symbol "ASDF:CL-SOURCE-FILE")))
(funcall (runtime-function "ASDF:COMPONENT-CHILDREN") system)))
(mapcan (function system-cl-source-files)
(delete-duplicates
(mapcan (lambda (depend) (copy-list (funcall (runtime-function depend) system)))
'("ASDF:SYSTEM-DEFSYSTEM-DEPENDS-ON"
"ASDF:SYSTEM-DEPENDS-ON"
"ASDF:SYSTEM-WEAKLY-DEPENDS-ON"))
:test (function equal))))
:test (function equal))))
(defun system-object-files (system)
(let ((system (funcall (runtime-function "ASDF:FIND-SYSTEM") system)))
(remove-duplicates
(append
(mapcan (lambda (component) (copy-list (funcall (runtime-function "ASDF:OUTPUT-FILES")
(runtime-symbol "ASDF:COMPILE-OP")
component)))
(funcall (runtime-function "ASDF:COMPONENT-CHILDREN") system))
(mapcan (function system-object-files)
(delete-duplicates
(mapcan (lambda (depend) (copy-list (funcall (runtime-function depend) system)))
'("ASDF:SYSTEM-DEFSYSTEM-DEPENDS-ON"
"ASDF:SYSTEM-DEPENDS-ON"
"ASDF:SYSTEM-WEAKLY-DEPENDS-ON"))
:test (function equal))))
:test (function equal))))
(defun slurp-stream (stream)
(with-output-to-string (*standard-output*)
(loop
:for line := (read-line stream nil)
:while line
:do (write-line line))))
#+ecl
(defun pre-compile-with-quicklisp (program-name main-function
system-name system-list
source-directory asdf-directories release-directory
init-file version copyright)
(declare (ignorable program-name main-function
system-name system-list
source-directory asdf-directories release-directory
init-file version copyright))
(say "Quickloading ~S" (cons system-name system-list))
(multiple-value-bind (output status)
(ext:run-program (first (argv))
(list "--norc" "--load" "generate.lisp"
"--eval" (prin1-to-string `(progn (require 'cmp)
(load-quicklisp)
(configure-asdf-directories ',asdf-directories)
(funcall (runtime-function "QL:QUICKLOAD") ',(cons system-name system-list)))))
:input nil
:output :stream
:wait nil)
(unless (zerop status)
(write-string (slurp-stream output)))
(say " status ~S" status)))
(defun program-pathname (program-name release-directory)
(merge-pathnames (make-pathname :name program-name
:type :unspecific
:version :unspecific
:defaults release-directory)
release-directory
nil))
(defun generate-program (&key program-name main-function
system-name system-list
source-directory asdf-directories release-directory
init-file version copyright)
(declare (ignorable release-directory init-file
system-name system-list
version copyright source-directory))
(when system-name
#+ecl (pre-compile-with-quicklisp (program-pathname program-name release-directory)
main-function
system-name system-list
source-directory asdf-directories release-directory
init-file version copyright)
#-ecl (load-quicklisp))
#+ecl (progn (require 'cmp)
(say "Requiring ASDF")
(require 'asdf))
(configure-asdf-directories asdf-directories)
#-ecl (when system-name
(say "Quickloading system ~A" system-name)
(funcall (runtime-function "QL:QUICKLOAD") system-name)
(when system-list
(say "Quickloading systems ~A" system-list)
(funcall (runtime-function "QL:QUICKLOAD") system-list)))
(say "Generating program ~A" (program-pathname program-name release-directory))
#+ccl (progn
;; This doesn't return.
(ccl::save-application
(program-pathname program-name release-directory)
:toplevel-function (make-toplevel-function main-function nil)
:init-file init-file
:mode #o755
:prepend-kernel t
:error-handler t))
#+clisp (progn
(ext::saveinitmem
(program-pathname program-name release-directory)
:executable t
:norc t
:quiet t
:verbose t
:script t
:documentation (format nil "~A version ~A~%~A~%" program-name version copyright)
:start-package (find-package "COMMON-LISP-USER")
;; locked-packages
;; :keep-global-handlers
:init-function (make-toplevel-function main-function init-file))
(ext:quit 0))
#+ecl (progn
#-(and) (load "hw.asd")
#-(and) (asdf:oos 'asdf:program-op system-name)
(funcall (runtime-function "ASDF:MAKE-BUILD") system-name
:type :program
:monolithic t
:ld-flags '()
:prologue-code ""
:epilogue-code (make-toplevel-function main-function init-file)
:move-here release-directory)
#-(and) (progn (c:build-program (program-pathname program-name release-directory)
:lisp-files (system-object-files system-name)
:ld-flags '()
:prologue-code ""
:epilogue-code (make-toplevel-function main-function init-file))
(rename-file
(make-pathname
:directory (append (pathname-directory
(uiop/configuration::compute-user-cache))
(rest (pathname-directory source-directory)))
:name (string-downcase system-name)
:type nil)
(program-pathname program-name release-directory)))
(ext:quit 0))
#+sbcl (sb-ext:save-lisp-and-die (program-pathname program-name release-directory)
:executable t
:compression 9
:toplevel (make-toplevel-function main-function init-file))
#-(or ccl clisp ecl sbcl) (not-implemented-yet 'generate-program))
;;;; THE END ;;;;
| 11,293 | Common Lisp | .lisp | 230 | 34.073913 | 142 | 0.534675 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 1c5f89b01c0c8db5d23fd4ce0c40d8013f97c6e9964bf0ef733137377b2ca85b | 12,313 | [
-1
] |
12,314 | script.lisp | informatimago_commands/sources/script.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: script.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: CLI
;;;;DESCRIPTION
;;;;
;;;; This file defines utilities for lisp scripts.
;;;;
;;;; Note: cl-launch scripts are not "scripts" but lisp programs that are
;;;; compiled first. So we cannot sequence different times like in a script
;;;; when using cl-launch. Instead, wrap functionalities in functions that
;;;; will be called at *run-time*.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2019-02-12 <PJB> Adapted for cl-launch.
;;;; 2009-11-29 <PJB> Extracted from logs scripts.
;;;; 2009-07-27 <PJB> Merged log-to-script in here.
;;;; 2009-07-23 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2009 - 2019
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(in-package "COM.INFORMATIMAGO.COMMAND.SCRIPT")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; From /usr/include/sysexits.h (Linux)
;;;
(defconstant ex-ok 0
"successful termination")
(defconstant ex--base 64
"base value for error messages")
(defconstant ex-usage 64
"command line usage error
The command was used incorrectly, e.g., with
the wrong number of arguments, a bad flag, a bad
syntax in a parameter, or whatever.")
(defconstant ex-dataerr 65
"data format error
The input data was incorrect in some way.
This should only be used for user's data & not
system files.")
(defconstant ex-noinput 66
"cannot open input
An input file (not a system file) did not
exist or was not readable. This could also include
errors like \"No message\" to a mailer (if it cared
to catch it).")
(defconstant ex-nouser 67
"addressee unknown
The user specified did not exist. This might
be used for mail addresses or remote logins.")
(defconstant ex-nohost 68
"host name unknown
The host specified did not exist. This is used
in mail addresses or network requests.")
(defconstant ex-unavailable 69
"service unavailable
A service is unavailable. This can occur
if a support program or file does not exist. This
can also be used as a catchall message when something
you wanted to do doesn't work, but you don't know
why.")
(defconstant ex-software 70
"internal software error
An internal software error has been detected.
This should be limited to non-operating system related
errors as possible.")
(defconstant ex-oserr 71
"system error (e.g., can't fork)
An operating system error has been detected.
This is intended to be used for such things as \"cannot
fork\", \"cannot create pipe\", or the like. It includes
things like getuid returning a user that does not
exist in the passwd file.")
(defconstant ex-osfile 72
"critical OS file missing
Some system file (e.g., /etc/passwd, /etc/utmp,
etc.) does not exist, cannot be opened, or has some
sort of error (e.g., syntax error).")
(defconstant ex-cantcreat 73
"can't create (user) output file
A (user specified) output file cannot be created.")
(defconstant ex-ioerr 74
"input/output error
An error occurred while doing I/O on some file.")
(defconstant ex-tempfail 75
"temp failure; user is invited to retry
temporary failure, indicating something that
is not really an error. In sendmail, this means
that a mailer (e.g.) could not create a connection,
and the request should be reattempted later.")
(defconstant ex-protocol 76
"remote error in protocol
the remote system returned something that
was \"not possible\" during a protocol exchange.")
(defconstant ex-noperm 77
"permission denied
You did not have sufficient permission to
perform the operation. This is not intended for
file system problems, which should use NOINPUT or
CANTCREAT, but rather for higher level permissions.")
(defconstant ex-config 78
"configuration error")
(defconstant ex--max 78
"maximum listed value")
(defun exit (&optional (code ex-ok))
(uiop:quit code))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
(defun clean-package/common-lisp-user ()
(mapc (lambda (package) (unuse-package package "COMMON-LISP-USER"))
(set-difference
(copy-seq (package-use-list "COMMON-LISP-USER"))
(delete nil (list ;; A list of all possible "CL" packages:
(find-package "COMMON-LISP")
(find-package "IMAGE-BASED-COMMON-LISP"))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
(defvar *default-program-name* "untitled")
(defun program-path ()
#+ccl (first ccl:*command-line-argument-list*)
#+clisp (let* ((argv (ext:argv))
(largv (length argv))
(args ext:*args*)
(largs (length args))
(index (- largv largs 1))
(path (and (<= 0 index largv) (elt argv index))))
(cond
(path
path)
#-cl-launch
((and *load-truename*
(string/= (file-namestring *load-truename*) "script.lisp"))
(namestring *load-truename*))
(t
*default-program-name*)))
#+sbcl (first sb-ext:*posix-argv*)
#-(or ccl clisp sbcl) *default-program-name*)
(defvar *program-path* *default-program-name*
"A namestring of the path to the program.
This may be a relative pathname, when it's obtained from argv[0].
If available we use the actual program name (from (EXT:ARGV) or
*LOAD-TRUENAME*), otherwise we fallback to *DEFAULT-PROGRAM-NAME*.")
(defvar *program-name* "untitled"
"Name of the program.")
(defvar *program-version* "0.0"
"Version of the program.")
(defun arguments ()
#+ccl (rest ccl:*command-line-argument-list*)
#+clisp ext:*args*
#+sbcl (rest sb-ext:*posix-argv*)
#-(or ccl clisp sbcl) '())
(defvar *arguments* '()
"A list of command line arguments (strings).")
(defvar *verbose* nil
"Adds some trace output.")
(defvar *debug* nil
"Errors break into the debugger.")
#-(or use-ppcre use-regexp) (pushnew (progn #-(and) :use-ppcre
#+(and) :use-regexp)
*features*)
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
#+clisp
(defun relaunch-with-kfull-linkset-if-needed (thunk)
;; If the version of clisp requires -Kfull to have linux, then let's call it with -Kfull…
(multiple-value-bind (res err) (ignore-errors (funcall thunk))
(when err
(if (find "-Kfull" (ext:argv) :test (function string=))
(error err)
(ext:exit
(or (ext:run-program "/usr/local/bin/clisp"
:arguments (append '("-ansi" "-q" "-E" "utf-8" "-Kfull")
(cons *program-path* *arguments*))
:wait t
#+linux :may-exec #+linux t
#+win32 :indirectp #+win32 nil)
0))))))
#+(and clisp (not linux))
(when (find "linux" *modules* :test (function string=))
(push :linux *features*))
#+(and clisp (not (or linux macos win32 #|what else is not linux?|#)))
(relaunch-with-kfull-linkset-if-needed
(lambda ()
;; But sometimes, it's not enough, linux is just not there…
(handler-case
(require "linux")
(error (err)
(format *error-output* "~A: ~A~%Missing the Linux module. Abort.~%" *program-name* err)
(ext:quit 69)))))
(defun getenv (var)
#+ccl (ccl:getenv var)
#+sbcl (sb-posix:getenv var)
#-(or ccl sbcl) (uiop:getenv var))
(defun getuid ()
#+ccl (ccl::getuid)
#+clisp (funcall (or (function-named "getuid" "LINUX")
(function-named "GETUID" "LINUX")
(function-named "UID" "POSIX")
(error "How to get the process UID in ~A?" (lisp-implementation-type))))
#+sbcl (sb-posix:getuid)
#-(or ccl clisp sbcl) (error "How to get the process UID in ~A?" (lisp-implementation-type)))
(defun getpid ()
#+ccl (ccl::getpid)
#+clisp (funcall (or (ignore-errors (find-symbol "getpid" "LINUX"))
(ignore-errors (find-symbol "PROCESS-ID" "OS"))
(ignore-errors (find-symbol "PROCESS-ID" "SYSTEM"))
(error "How to get the process PID in ~A?" (lisp-implementation-type))))
#+sbcl (sb-posix:getpid)
#-(or ccl clisp sbcl) (error "How to get the process PID in ~A?" (lisp-implementation-type)))
(defun report-the-error (err string-stream)
(let ((log-path (format nil "/tmp/~A.~A.errors" *program-name* (getpid))))
(with-open-file (log-stream log-path
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format log-stream "~A GOT AN ERROR: ~A~%~80,,,'-<~>~%~A~%"
*program-name* err (get-output-stream-string string-stream)))
(format *error-output* "~A: ~A~% See ~A~%" *program-name* err log-path)
(finish-output *error-output*)
(exit ex-software)))
(defmacro without-output (&body body)
`(prog1 (values)
(with-output-to-string (net)
(handler-case
(let ((*standard-output* net)
(*error-output* net)
(*trace-output* net))
,@body)
(error (err) (report-the-error err net))))))
(defmacro redirecting-stdout-to-stderr (&body body)
(let ((verror (gensym))
(voutput (gensym)))
`(let* ((,verror nil)
(,voutput (with-output-to-string (stream)
(let ((*standard-output* stream)
(*error-output* stream)
(*trace-output* stream))
(handler-case (progn ,@body)
(error (err) (setf ,verror err)))))))
(when ,verror
(terpri *error-output*)
(princ ,voutput *error-output*)
(terpri *error-output*)
(princ ,verror *error-output*)
(terpri *error-output*)
(terpri *error-output*)
#-testing (exit ex-software)))))
(defmacro with-pager ((&key lines) &body body)
"
Executes the BODY, redirecting *STANDARD-OUTPUT* to a pager.
If no option is given, use the system pager obtained from the
environment variable PAGER. If none is defined, then no pager is
used.
The following is NOT IMPLEMENTED YET:
If an option is given, then it defines a local pager.
LINES Number of line to output in a single chunk.
After this number of line has been written,
some user input is required to further display lines.
"
(when lines
(error "~S: Sorry :LINES is not implemented yet." 'with-pager))
;; (print (list (version:clisp-version)
;; (version:rt-version<= "2.48" (version:clisp-version))))
#-clisp
`(progn ,@body)
#+clisp
`(progn
#+#.(COM.INFORMATIMAGO.COMMON-LISP.CESARUM.VERSION:rt-version<= "2.44" (COM.INFORMATIMAGO.COMMON-LISP.CESARUM.VERSION:version))
,`(progn ,@body)
#-#.(COM.INFORMATIMAGO.COMMON-LISP.CESARUM.VERSION:rt-version<= "2.44" (COM.INFORMATIMAGO.COMMON-LISP.CESARUM.VERSION:version))
,(let ((pager (uiop:getenv "PAGER")))
(if pager
(let ((pager-stream (gensym)))
`(let ((,pager-stream (ext:make-pipe-output-stream
,pager
:external-format charset:utf-8
:buffered nil)
;; (ext:run-program ,pager
;; :input :stream
;; :output :terminal
;; :wait nil)
))
(unwind-protect
(let ((*standard-output* ,pager-stream))
,@body)
(close ,pager-stream))))
`(progn ,@body)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
(defun shell-quote-argument (argument)
"Quote ARGUMENT for passing as argument to an inferior shell."
#+(or MSWINDOWS WIN32)
;; Quote using double quotes, but escape any existing quotes in
;; the argument with backslashes.
(let ((result "")
(start 0)
(end)
(match-beginning)
(match-end))
(when (or (null (setf match-end (position #\" argument)))
(< match-end (length argument)))
(loop
:while (setf match-beginning (position #\" argument :start start))
:do (setf end (1+ match-beginning)
result (concatenate 'string result (subseq argument start end)
"\\" (subseq argument end (1+ end)))
start (1+ end))))
(concatenate 'string "\"" result (subseq argument start) "\""))
#-(or MSWINDOWS WIN32)
(if (equal argument "")
"''"
;; Quote everything except POSIX filename characters.
;; This should be safe enough even for really weird shells.
(let ((result "")
(start 0)
(end)
(match-end))
(loop
:while (setf match-end (position-if-not (lambda (ch) (or (alphanumericp ch) (position ch "-_./"))) argument :start start))
:do (setf end match-end
result (concatenate 'string result (subseq argument start end)
"\\" (subseq argument end (1+ end)))
start (1+ end)))
(concatenate 'string result (subseq argument start)))))
(defun shell (command &rest arguments)
"
SEE ALSO: EXECUTE.
"
(uiop:run-program (cons command arguments) :force-shell t))
(defun execute (&rest command)
"
RETURN: The status returned by the command.
SEE ALSO: SHELL
"
(uiop:run-program command :input nil :output t))
(defun cp (file newname &optional ok-if-already-exists keep-time)
"
IMPLEMENTATION: The optional argument is not implemented.
Copy FILE to NEWNAME. Both args must be strings.
If NEWNAME names a directory, copy FILE there.
Signals a `file-already-exists' error if file NEWNAME already exists,
unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil.
A number as third arg means request confirmation if NEWNAME already exists.
This is what happens in interactive use with M-x.
Fourth arg KEEP-TIME non-nil means give the new file the same
last-modified time as the old one. (This works on only some systems.)
A prefix arg makes KEEP-TIME non-nil.
"
(declare (ignore ok-if-already-exists keep-time))
(execute "cp" (shell-quote-argument file) (shell-quote-argument newname)))
#+(and clisp linux) ;; Should probably move away.
(defun make-symbolic-link (filename linkname &optional ok-if-already-exists)
"
IMPLEMENTATION: The optional argument is not implemented.
Make a symbolic link to FILENAME, named LINKNAME. Both args strings.
Signals a `file-already-exists' error if a file LINKNAME already exists
unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
A number as third arg means request confirmation if LINKNAME already exists.
"
(declare (ignore ok-if-already-exists))
(/= 0 (linux:|symlink| filename linkname)))
#+(and clisp linux) ;; Should probably move away.
(defun make-directory (*path* &optional (parents nil))
"
Create the directory *PATH* and any optionally nonexistent parents dirs.
The second (optional) argument PARENTS says whether
to create parents directories if they don't exist.
"
(if parents
(ensure-directories-exist (concatenate 'string *path* "/.") :verbose nil)
(linux:|mkdir| *path* 511 #| #o777 |# ))
(ext:probe-directory (if (char= (char *path* (1- (length *path*)))
(character "/"))
*path* (concatenate 'string *path* "/"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun perror (format-string &rest args)
"
DO: Writes a message on the error output in the name of the script.
"
(format *error-output* "~&~A: ~?" *program-name* format-string args)
(finish-output *error-output*))
(defun pmessage (format-string &rest args)
"
DO: Writes a message on the standard output in the name of the script.
"
(format *standard-output* "~&~A: ~?" *program-name* format-string args)
(finish-output *standard-output*))
(defun pquery (format-string &rest args)
"
DO: Writes a message on the query I/O in the name of the script, and
read a response line.
RETURN: A string containing the response line.
"
(format *query-io* "~&~A: ~?" *program-name* format-string args)
(finish-output *query-io*)
(clear-input *query-io*)
(read-line *query-io*))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; COMMANDS
;;;
;;; Note: The command structure is used at compilation-time, and at run-time:
;;; - At compilation-time, the generate-commands.lisp script reads each
;;; command source file and search for the command form, using the
;;; :use-systems, :use-packages and :main options to compile the
;;; command source file.
;;; - At run-time, the command form registers the options and documentation
;;; of the command for option parsing and help.
(defstruct (option (:predicate optionp))
keys arguments documentation function)
(defclass command ()
((name :initarg :name
:initform nil
:accessor command-name)
(documentation :initarg :documentation
:initform nil
:accessor command-documentation)
(bash-completion-hook :initarg :bash-completion-hook
:initform nil
:accessor command-bash-completion-hook
:documentation "A function (lambda (index words) ...) that will print the completion and return true, or do nothing and return nil.")
(options :initform (make-hash-table :test (function equal))
:reader command-options)
;; compilation-time:
(pathname :initarg :pathname :initform nil :accessor command-pathname)
(use-systems :initarg :use-systems :initform '() :accessor command-use-systems)
(use-packages :initarg :use-packages :initform '() :accessor command-use-packages)
(shadow :initarg :shadow :initform '() :accessor command-shadow)
(main :initarg :main :initform nil)))
(defgeneric command-package-name (command)
(:method ((command-name string))
(format nil "COMMAND.~:@(~A~)" command-name))
(:method ((command command))
(command-package-name (command-name command))))
(defgeneric command-main (command)
(:method ((command command))
(or (slot-value command 'main)
(setf (slot-value command 'main) (format nil "~:@(~A::MAIN~)"
(command-package-name
(command-name command)))))))
(defun commandp (object) (typep object 'command))
(defgeneric add-option (command option)
(:method ((command command) option)
(dolist (name (option-keys option) command)
(setf (gethash name (command-options command)) option))))
(defvar *commands* (make-hash-table :test (function equal)))
(defvar *command* nil "The current command.")
(defun command-named (name)
(gethash name *commands*))
(defun register-command (&key name pathname use-systems use-packages shadow main
documentation bash-completion-hook)
(setf (gethash name *commands*)
(make-instance 'command
:name name
:pathname pathname
:use-systems use-systems
:use-packages use-packages
:shadow shadow
:main main
:bash-completion-hook bash-completion-hook
:documentation documentation)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *default-package-use-list*
'("COMMON-LISP" "COM.INFORMATIMAGO.COMMAND.SCRIPT"))
(defun generate-command-defpackage (&key name
main
use-packages
shadow
documentation)
`(defpackage ,name
(:use ,@(or use-packages *default-package-use-list*))
,@(when documentation `((:documentation ,documentation)))
,@(when shadow `((:shadow ,@shadow)))
,@(when main
(if (position #\: main)
`((:export ,(subseq main (1+ (position #\: main :from-end t)))))
`((:export ,main))))))
(defun repackage (form old-package new-package)
(let ((old-package (find-package old-package))
(new-package (find-package new-package)))
(labels ((process (sexp)
(cond
((symbolp sexp)
(if (eq (symbol-package sexp) old-package)
(intern (symbol-name sexp) new-package)
sexp))
((atom sexp) sexp)
(t (cons (process (car sexp)) (process (cdr sexp)))))))
(process form)))))
(defmacro command (&key name use-systems use-packages shadow main
documentation bash-completion-hook)
"
This macro registers a command, and is also used as a declaration:
it's read by the command generator script, to know the systems to be
quickloaded,and the packages to be used by the command package.
We can also specify a different main function than the default MAIN.
The rest of the file will be compiled and loaded in the command package.
NAME: a string, the name of the command.
Compilation-time slots:
MAIN: a string, containing the name of the symbol fbound
to the main function.
USE-SYSTEMS: a list (not evaluated) of system names.
USE-PACKAGES: a list (not evaluated) of package names.
SHADOW: a list (not evaluated) of symbol names to be shadowed.
Run-time slots:
DOCUMENTATION: a string containing the documentation of the commands.
OPTIONS: an expression that should return a list of clauses,
each clause is a list of the form:
((option-name …) parsed-option) as returned by the
OPTION macro.
RETURN: a new command structure.
"
(let* ((name (or name (pathname-name (or *compile-file-truename* *load-truename*))))
(pname (if (eql 8 (mismatch "COMMAND." name))
name
(format nil "~:@(COMMAND.~A~)" name))))
`(progn
(eval-when (:compile-toplevel)
(ql:quickload ',use-systems))
(eval-when (:compile-toplevel :load-toplevel :execute)
,(generate-command-defpackage :name pname
:main main
:use-packages use-packages
:shadow shadow
:documentation documentation)
(in-package ,pname))
(eval-when (:load-toplevel :execute)
(register-command :name ',name
:main ',main
:use-systems ',use-systems
:use-packages ',use-packages
:shadow ',shadow
:documentation ',documentation
:bash-completion-hook ,bash-completion-hook)))))
(defmacro options (command-name &rest options)
`(let ((command (command-named ,command-name)))
(dolist (option (list ,@options))
(if (atom option)
(add-option command option)
(dolist (opt option)
(add-option command opt))))))
(defun package-set-equal-p (p q)
(and (subsetp p q :key (function package-name) :test (function string=))
(subsetp q p :key (function package-name) :test (function string=))))
(defun %command-package (name package-use-list)
"Use PACKAGE-USE-LIST if not empty, otherwise use *DEFAULT-PACKAGE-USE-LIST*."
(let ((package-name (command-package-name name)))
(or (let ((package (find-package package-name)))
(when (and package package-use-list)
(unless (package-set-equal-p (package-use-list package) package-use-list)
(unuse-package (set-difference (package-use-list package) package-use-list
:key (function package-name) :test (function string=))
package)
(use-package package-use-list package)))
package)
(make-package package-name
:use (or package-use-list
*default-package-use-list*)))))
(defgeneric command-package (object)
(:documentation "Returns the package of the command. Creates it if it doesn't already exist.
SEE: COMMAND-PACKAGE-NAME")
(:method ((command command))
(%command-package (command-name command) (command-use-packages command)))
(:method ((name string))
(let ((command (command-named name)))
(if command
(command-package command)
(%command-package name nil)))))
(defun command-form-p (form)
"Predicate whether form is a:
(command &key name pathname
use-systems use-packages main
documentation bash-completion-hook)
form."
(and (consp form) (symbolp (first form)) (string= (first form) 'command)))
(defun read-command-form (source)
(let ((package (make-package (format nil "read-command-form temporary package ~X" (random (expt 2 64)))
:use '())))
(unwind-protect
(let ((*package* package)
(*read-suppress* t))
(loop
:for form := (ignore-errors (read source nil source))
:until (eql form source)
:when (command-form-p form)
:do (return-from read-command-form form)
:finally (return nil)))
(delete-package package))))
(defun register-command-file (name pathname)
(with-open-file (source pathname)
(let ((form (read-command-form source)))
(apply (function register-command)
:name name
:pathname pathname
:allow-other-keys t
(when (command-form-p form)
(rest form))))))
(defun dispatch-command (pname &rest arguments)
"A toplevel to dispatch to commands."
(let* ((name (pathname-name pname))
(command (command-named name)))
(if command
(let ((com.informatimago.command.script:*command* command)
(com.informatimago.command.script:*program-name* name)
(com.informatimago.command.script:*default-program-name* name)
(com.informatimago.command.script:*program-path* pname)
(com.informatimago.command.script:*arguments* arguments))
(com.informatimago.command.script:exit
(handler-case
(funcall (read-from-string (command-main command)) arguments)
(error (err)
(format *error-output* "~&~A: ~A~%" name err)
(finish-output *error-output*)
com.informatimago.command.script:ex-software))))
(error "No such command: ~S" name))
(values)))
;; Options:
(defun q&d-parse-parameters (parameters)
"Parses (mandatory &optional optionals... &rest rest &key key...)"
(loop
:with mandatories = '()
:with optionals = '()
:with rest = nil
:with keys = '()
:with state = :mandatory
:with params = parameters
:for param = (first params)
:while params
:do (ecase state
((:mandatory)
(case param
((&optional) (setf state :optional))
((&rest) (setf state :rest))
((&key) (setf state :key))
(otherwise (push param mandatories)))
(pop params))
((:optional)
(case param
((&optional) (error "&OPTIONAL given more than once in ~S" parameters))
((&rest) (setf state :rest))
((&key) (setf state :key))
(otherwise (push param optionals)))
(pop params))
((:rest)
(case param
((&optional) (error "&OPTIONAL given after &REST in ~S" parameters))
((&rest) (error "&REST given twice in ~S" parameters))
((&key) (setf state :key))
(otherwise (setf state :after-rest
rest param)))
(pop params))
((:after-rest)
(case param
((&optional) (error "&OPTIONAL given after &REST in ~S" parameters))
((&rest) (error "&REST given after &REST in ~S" parameters))
((&key) (setf state :key))
(otherwise (error "Several &REST parameters given in ~S" parameters)))
(pop params))
((:key)
(case param
((&optional) (error "&OPTIONAL given after &KEY in ~S" parameters))
((&rest) (error "&REST given after &KEY in ~S" parameters))
((&key) (setf state :key))
(otherwise (push param keys)))
(pop params)))
:finally (return (values (nreverse mandatories)
(nreverse optionals)
rest
(nreverse keys)))))
(defun keywordize (string-designator)
(intern (string string-designator)
(load-time-value (find-package "KEYWORD"))))
(defun q&d-arguments (mandatories optionals rest keys)
"
BUG: when the optionals or keys have a present indicator,
we just ignore it and build a list that will pass
the default value anyways...
"
(assert (every (function symbolp) mandatories))
(append mandatories
(mapcar (lambda (opt)
(etypecase opt
(cons (first opt))
(symbol opt)))
optionals)
(when rest (list rest))
(mapcan (lambda (key)
(etypecase key
(cons (etypecase (first key)
(symbol (list (keywordize (first key)) (first key)))
(cons (list (second (first key)) (first (first key))))))
(symbol (list (keywordize key) key))))
keys)))
(defun wrap-option-function (keys option-arguments docstring option-function)
(let ((vargs (gensym)))
(multiple-value-bind (mandatories optionals rest keys-args) (q&d-parse-parameters option-arguments)
(make-option
:keys keys
:arguments option-arguments
:function (compile (make-symbol (format nil "~@(~A-WRAPPER~)" (first keys)))
(cond
((and keys-args (not rest))
(error "An option cannot have &key parameters without a &rest parameter. ~@
Invalid option parameters: ~S" option-arguments))
((null mandatories)
`(lambda (option-key ,vargs)
(declare (ignorable option-key))
,(if rest
`(destructuring-bind ,option-arguments ,vargs
(funcall ',option-function ,@(q&d-arguments mandatories
optionals
rest
keys-args))
nil)
(let ((vremaining (gensym)))
`(destructuring-bind (,@option-arguments &rest ,vremaining) ,vargs
(funcall ',option-function ,@(q&d-arguments mandatories
optionals
rest
keys-args))
,vremaining)))))
(t
`(lambda (option-key ,vargs)
(let ((nargs (length ,vargs)))
(if (<= ,(length mandatories) nargs)
,(if rest
`(destructuring-bind ,option-arguments ,vargs
(funcall ',option-function ,@(q&d-arguments mandatories
optionals
rest
keys-args))
nil)
(let ((vremaining (gensym)))
`(destructuring-bind (,@option-arguments &rest ,vremaining) ,vargs
(funcall ',option-function ,@(q&d-arguments mandatories
optionals
rest
keys-args))
,vremaining)))
(let ((missing-count (- ,(length mandatories) nargs))
(missing-args (subseq ',mandatories nargs)))
(error "option ~A is missing ~:[an ~*~;~A ~]argument~:*~p: ~{~A ~}"
option-key
(< 1 missing-count) missing-count
missing-args))))))))
:documentation (split-string docstring (string #\newline))))))
(defun call-option-function (command option-key arguments &optional undefined-argument)
(let ((option (gethash option-key (command-options command))))
(cond
(option (funcall (option-function option) option-key arguments))
(undefined-argument (funcall undefined-argument option-key arguments))
(t (error "Unknown option ~A ; try: ~A help" option-key *program-name*)))))
(defmacro option (names parameters &body body)
"
DO: Define a new option for the scirpt.
NAMES: A list designator of option names (strings
such as \"-a\" \"--always\").
PARAMETERS: A list of option parameters. The names of
these parameters must be descriptive as they
are used to build the usage help text.
BODY: The code implementing this option.
RETURN: The lisp-name of the option (this is a symbol
named for the first option name).
"
(let* ((main-name (if (listp names)
(first names)
names))
(other-names (if (listp names)
(rest names)
'()))
(lisp-name (intern (string-upcase main-name)))
(docstring (if (and (stringp (first body)) (rest body))
(first body)
nil))
(body (if (and (stringp (first body)) (rest body))
(rest body)
body)))
`(wrap-option-function ',(cons main-name other-names)
',parameters
',docstring
(lambda ,(remove '&rest parameters)
,docstring
(block ,lisp-name
,@body)))))
(defgeneric option-list (command)
(:method ((command command))
(let ((options '()))
(maphash (lambda (key option)
(declare (ignore key))
(pushnew option options))
(command-options command))
options)))
;; TODO: See if we couldn't simplify it, perhaps with complete -C.
(defgeneric list-all-option-keys (command)
(:method ((command command))
(let ((keys '()))
(dolist (option (option-list command))
(dolist (key (option-keys option))
(push key keys)))
keys)))
(defun help-option ()
(option ("help" "-h" "--help") ()
"Give this help."
(with-pager ()
(let ((options (option-list *command*)))
(format t "~2%~A options:~2%" *program-name*)
(dolist (option (sort options (function string<)
:key (lambda (option) (first (option-keys option)))))
(format t " ~{~A~^ | ~} ~:@(~{~A ~}~)~%~@[~{~% ~A~}~]~2%"
(option-keys option)
(option-arguments option)
(option-documentation option)))
(format t "~@[~A~%~]" (command-documentation *command*))))))
(defun completion-option-prefix (command prefix)
(dolist (key (remove-if-not (lambda (key)
(and (<= (length prefix) (length key))
(string= prefix key :end2 (length prefix))))
(list-all-option-keys command)))
(format t "~A~%" key))
(finish-output))
(defun completion-all-options (command)
(dolist (key (list-all-option-keys command))
(format t "~A~%" key))
(finish-output))
(defun bash-completion-options ()
(list (option ("--bash-completions") (index &rest words)
"Implement the auto-completion of arguments.
This option is designed to be invoked from the function generated by
the '--bash-completion-function' option. There should be no need to
use directly.
"
(let ((index (parse-integer index :junk-allowed t)))
(unless (and (command-bash-completion-hook *command*)
(funcall (command-bash-completion-hook *command*) index words))
(if index
(completion-option-prefix *command* (elt words index))
(completion-all-options *command*))))
(exit 0))
(option ("--bash-completion-function") ()
"Write two bash commands (separated by a semi-colon) to create a
bash function used to do auto-completion of command arguments.
Use it with:
eval $($COMMAND --bash-completion-function)
and then typing TAB on the command line after the command name will
autocomplete argument prefixes.
"
(format t "function completion_~A(){ ~
COMPREPLY=( $(~:*~A --bash-completions \"$COMP_CWORD\" \"${COMP_WORDS[@]}\") ) ; } ;~
complete -F completion_~:*~A ~:*~A~%"
*program-name*)
(exit 0))))
(defun parse-options (*command* arguments &optional default undefined-argument)
(flet ((process-arguments ()
(cond
(arguments
(loop
:while arguments
:do (setf arguments (call-option-function *command* (pop arguments) arguments undefined-argument))))
(default
(funcall default)))))
(if *debug*
(process-arguments)
(handler-case (process-arguments)
(error (err)
(perror "~A~%" err)
;; TODO: select different sysexits codes depending on the error class.
(return-from parse-options ex-software)))))
0)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
(defun not-implemented-here (function-name)
(error "How to implement ~S in ~S"
function-name
(lisp-implementation-type)))
(defun prepare-options (options)
(mapcar (lambda (option)
(typecase option
(keyword (format nil "-~(~A~)" option))
(symbol (string-downcase option))
(string option)
(t (prin1-to-string option))))
options))
(defun run-program (program-and-arguments &key (input :terminal) (output :terminal)
(if-output-exists :error) (wait t))
"
RETURN: The status returned by the command.
SEE ALSO: SHELL
"
(uiop:run-program program-and-arguments :input input :output output :if-output-exists if-output-exists :wait wait))
(defun uname (&rest options)
"Without OPTIONS, return a keyword naming the system (:LINUX, :DARWIN, etc).
With options, returns the first line output by uname(1)."
(with-input-from-string (uname (run-program (cons "uname" (prepare-options options))
:input nil :output :string :wait nil))
(values (if options
(read-line uname)
(intern (string-upcase (read-line uname))
"KEYWORD")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Some emacs style functions.
;;;
(defun find-directories (rootpath)
"Return a list of recursive subdirectories starting from ROOTPATH
that are accessible by the user."
(directory (merge-pathnames (make-pathname :directory '(:relative :wild-inferiors)
:name nil :type nil :version nil)
rootpath nil)))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;
;; ;;; The main program, definition of the options
;; ;;;
;;
;;
;; (in-package "COMMON-LISP-USER")
;; (load (make-pathname :name "SCRIPT" :type "LISP" :version NIL :case :common
;; :defaults *load-pathname*))
;; (use-package "SCRIPT")
;;
;; ;; (redirecting-stdout-to-stderr (load #p"/etc/gentoo-init.lisp"))
;; (redirecting-stdout-to-stderr
;; (let ((*load-verbose* nil)
;; (*compile-verbose* nil))
;; (load (make-pathname :name ".clisprc" :type "lisp" :case :local
;; :defaults (user-homedir-pathname)))
;; ;; (setf *features* (delete :testing-script *features*))
;; ))
;; (redirecting-stdout-to-stderr (asdf:oos 'asdf:load-op :split-sequence)
;; (asdf:oos 'asdf:load-op :cl-ppcre))
(defun initialize ()
(setf *program-path* (program-path)
*program-name* (file-namestring *program-path*)
*arguments* (arguments))
(values))
(defun run-main (main)
(handler-case (uiop:quit (funcall main uiop:*command-line-arguments*))
(error (err)
(format *error-output* "~&~A~%" err)
(finish-output *error-output*)
(uiop:quit 1))))
;;;; THE END ;;;;
| 44,838 | Common Lisp | .lisp | 965 | 35.415544 | 158 | 0.548893 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | e22aa759f8dc105366eb7b1411080536c7c0d71eda3e20c546ee6f2e688bf96a | 12,314 | [
-1
] |
12,315 | packages.lisp | informatimago_commands/sources/packages.lisp |
(defpackage "COM.INFORMATIMAGO.COMMAND.SCRIPT"
(:nicknames "SCRIPT")
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.VERSION")
(:export
"*VERBOSE*" "*DEBUG*"
"*DEFAULT-PROGRAM-NAME*" "*PROGRAM-NAME*" "*PROGRAM-VERSION*" "*PROGRAM-PATH*" "*ARGUMENTS*"
"PROGRAM-NAME" "ARGUMENTS"
"WITHOUT-OUTPUT" "WITH-PAGER"
"REDIRECTING-STDOUT-TO-STDERR"
"RELAUNCH-WITH-KFULL-LINKSET-IF-NEEDED"
; I/O
"PERROR" "PMESSAGE" "PQUERY")
(:export ; Exit codes:
"EX--BASE" "EX--MAX" "EX-CANTCREAT" "EX-CONFIG"
"EX-DATAERR" "EX-IOERR" "EX-NOHOST" "EX-NOINPUT"
"EX-NOPERM" "EX-NOUSER" "EX-OK" "EX-OSERR" "EX-OSFILE"
"EX-PROTOCOL" "EX-SOFTWARE" "EX-TEMPFAIL" "EX-UNAVAILABLE"
"EX-USAGE"
"EXIT")
(:export ; Commands
"*COMMAND*"
"COMMAND" "COMMANDP" "COPY-COMMAND" "COMMAND-OPTIONS"
"COMMAND-DOCUMENTATION" "COMMAND-BASH-COMPLETION-HOOK"
"REGISTER-COMMAND" "COMMAND-NAMED"
"COMMAND-NAME" "COMMAND-USE-SYSTEMS" "COMMAND-MAIN" "COMMAND-PACKAGE"
"COMMAND-PATHNAME"
"COMMAND-PACKAGE-NAME"
"REGISTER-COMMAND-FILE"
"DISPATCH-COMMAND")
(:export ; Options
"OPTION" "OPTIONS" "OPTIONP" "COPY-OPTION" "OPTION-KEYS" "OPTION-ARGUMENTS"
"OPTION-DOCUMENTATION" "OPTION-FUNCTION"
"CALL-OPTION-FUNCTION" "PARSE-OPTIONS"
"HELP-OPTION" "BASH-COMPLETION-OPTIONS")
(:export ; Utilities:
"FIND-DIRECTORIES"
"CONCAT"
"GETENV" "GETPID" "GETUID"
"SHELL-QUOTE-ARGUMENT" "SHELL" "EXECUTE" "RUN-PROGRAM"
"UNAME" "CP" "MAKE-SYMBOLIC-LINK" "MAKE-DIRECTORY"))
(defpackage "COM.INFORMATIMAGO.COMMAND"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMAND.SCRIPT")
(:export "*ALL-COMMANDS*"))
(defpackage "COM.INFORMATIMAGO.COMMAND.GENERATE"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMAND.SCRIPT"
"COM.INFORMATIMAGO.COMMAND"))
| 2,098 | Common Lisp | .lisp | 51 | 35.901961 | 95 | 0.63878 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d85537527c7a7a3fdb15982aca418adf0646771c0ca6ba8aab6c669493b8da87 | 12,315 | [
-1
] |
12,316 | svn-locate-revision.lisp | informatimago_commands/sources/commands/svn-locate-revision.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: svn-locate-revision
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Locates a revision in the svn:mergeinfo properties.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2016-12-13 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2016 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "SCRIPT")
(command :use-systems (:xmls :com.informatimago.common-lisp.cesarum)
:use-packages ( "COMMON-LISP"
"SCRIPT"
"XMLS"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING")
:main "SVN-LOCATE-REVISION:MAIN")
(defparameter *verbose* t)
(defun make-pipe-input-stream (command &key (external-format :default)
(element-type 'character)
(buffered t))
(declare (ignore command external-format element-type buffered))
(error "Not implemented yet."))
(defun make-pipe-output-stream (command &key (external-format :default)
(element-type 'character)
(buffered t))
(declare (ignore command external-format element-type buffered))
(error "Not implemented yet."))
(defun candidate-branches (url revision)
"Return a list of branch names that have a range covering the REVISION."
(with-open-stream (in (make-pipe-input-stream
(format nil "svn propget svn:mergeinfo ~S" url)
:buffered t))
(loop
:with result := '()
:for line := (read-line in nil nil)
:while line
:do (destructuring-bind (branch revisions) (split-string line ":")
(when (some (lambda (range)
(destructuring-bind (min &optional max) (split-string range "-")
(let ((min (parse-integer (string-right-trim "*" min)))
(max (and max (parse-integer (string-right-trim "*" max)))))
(if max
(<= min revision max)
(= min revision)))))
(split-string revisions ","))
(push branch result)))
:finally (return result))))
(defun branch-url (base-url branch-name)
(concatenate 'string base-url
(if (and (plusp (length branch-name))
(char= #\^ (aref branch-name 0)))
(subseq branch-name 1)
branch-name)))
(defun svn-info (url)
;; xmls:parse parses the xml stream into a sexp.
(parse (make-pipe-input-stream
(format nil "svn info --xml ~S" url)
:buffered t)))
(defun info-root (info)
(let ((entry (xmlrep-find-child-tag "entry" info)))
(unless (string= "dir" (xmlrep-attrib-value "kind" entry))
(error "Expected the svn info of a directry entry, not ~S info" info))
(first (xmlrep-children (xmlrep-find-child-tag "root" (xmlrep-find-child-tag "repository" entry))))))
(defun svn-revision (url revision)
(ignore-errors
(parse (make-pipe-input-stream
(format nil "svn log ~S -r ~A --xml" url revision)
:buffered t))))
(defun revision-logentry (revision) (and (xmlrep-children revision)
(xmlrep-find-child-tag "logentry" revision)))
(defun logentry-revision (entry) (parse-integer (xmlrep-attrib-value "revision" entry)))
(defun logentry-date (entry) (first (xmlrep-children (xmlrep-find-child-tag "date" entry))))
(defun logentry-author (entry) (first (xmlrep-children (xmlrep-find-child-tag "author" entry))))
(defun logentry-message (entry) (first (xmlrep-children (xmlrep-find-child-tag "msg" entry))))
(defun locate-revision (url revision)
"Indicate whether the given REVISION exists in the branch at URL.
If it does, then return a list of merged branches where this revision come from."
(let ((info (info-root (svn-info url))))
(remove-if-not (lambda (candidate)
(revision-logentry (svn-revision (branch-url info candidate) revision)))
(candidate-branches url revision))))
;; locate a set of revisions (53007 has not been merged anywhere)) :
;; (mapcar (lambda (revision)
;; (cons revision (locate-revision "/Users/pjb/src/trustonic/tbase/branches/dev_kinibi_wb_sdk/" revision)))
;; '(50233 50950 51012 53007))
;; ((50233 "/users/pasbou01/dev_kinibi_wb_sdk-LP33172863")
;; (50950 "/users/pasbou01/dev_kinibi_wb_sdk-LP33172863")
;; (51012 "/users/pasbou01/dev_kinibi_wb_sdk-LP33172863")
;; (53007))
;; Problem: find in /users/pasbou01/dev_kinibi_wb_sdk-LP33172863
;; all the revisions that have not found their way (merged) into
;; /users/pasbou01/merge-dev_kinibi_wb_sdk-LP33172863 (which is a
;; copy of /branches/dev_kinibi_wb_sdk).
;;
;; (let ((revisions (let ((src-url "https://svn.trustonic.internal/svn/tbase/users/pasbou01/dev_kinibi_wb_sdk-LP33172863"))
;; ;; 1- filter revisions where author=pasbou01 (the others have been merged in and are already in dst-url)
;; ;; between HEAD:47559.
;; (mapcar (function logentry-revision)
;; (remove "pasbou01"
;; (xmlrep-children (parse (make-pipe-input-stream
;; (format nil "svn log ~S -r ~A --xml" src-url "HEAD:47559")
;; :buffered t)))
;; :test (function string/=)
;; :key (function logentry-author)))))
;; (dst-url ;; "https://svn.trustonic.internal/svn/tbase/users/pasbou01/merge-dev_kinibi_wb_sdk-LP33172863"
;; "https://svn.trustonic.internal/svn/tbase/branches/dev_kinibi_wb_sdk"))
;; ;; 2- remove the revisions that are already in dst-url.
;; (remove-if (lambda (revision)
;; (locate-revision dst-url revision))
;; revisions))
;; --> (53007 52698 52614 51667)
(defun main (arguments)
(loop
:for srevision :in arguments
:for revision = (parse-integer srevision :junk-allowed t
:start (if (and (plusp (length srevision))
(eql #\r (aref srevision 0)))
1
0))
:when revision
:do (map nil (function write-line) (locate-revision "." revision)))
ex-ok)
;;;; THE END ;;;;
| 7,754 | Common Lisp | .lisp | 147 | 44.319728 | 127 | 0.565097 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 75ce42a506c22d3fd831c4ba1a9b14f7f63e32d4d7fc43ea3a3c28f495af7835 | 12,316 | [
-1
] |
12,317 | get-directory.lisp | informatimago_commands/sources/commands/get-directory.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: get-directory
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Search for the given directory tag in the ~/directories.txt file,
;;;; and outputs a directory made appending the given optional subdirectory.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-12-04 <PJB> Added this header; convert to CL.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2010
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
;;;----------------------------------------------------------------------
;;;
;;; Directories.
;;;
(defvar *directories* '())
(defun list-directories ()
"Returns the list of named directories."
(copy-seq *directories*))
(defun get-directory (key &optional (subpath ""))
"
Caches the ~/directories.txt file that contains a map of
directory keys to pathnames, into *DIRECTORIES*.
Then builds and returns a pathname made by merging the directory
selected by KEY, and the given SUBPATH.
"
(unless *directories*
(with-open-file (dirs (merge-pathnames
(make-pathname :name "DIRECTORIES" :type "TXT"
:version nil :case :common)
(user-homedir-pathname)
nil))
(loop
:for k = (read dirs nil dirs)
:until (eq k dirs)
:do (push (string-trim " " (read-line dirs)) *directories*)
:do (push (intern (substitute #\- #\_ (string k))
"KEYWORD") *directories*))))
(unless (getf *directories* key)
(error "~S: No directory keyed ~S" 'get-directory key))
(merge-pathnames subpath (getf *directories* key) nil))
;;;----------------------------------------------------------------------
(defun main (arguments)
(destructuring-bind (key &optional (subpath "")) arguments
(princ (get-directory (intern (substitute #\- #\_ key) "KEYWORD") subpath))
(terpri)
(finish-output)
ex-ok))
;;;; THE END ;;;;
| 3,050 | Common Lisp | .lisp | 74 | 36.945946 | 79 | 0.567139 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 0876b0328a3d60c10bb6fec9ba03d3c9ed0ebba1b2100c6c16c5182029813436 | 12,317 | [
-1
] |
12,318 | box.lisp | informatimago_commands/sources/commands/box.lisp | ;; -*- mode:lisp; coding:utf-8 -*-
(defun main (arguments)
(declare (ignore arguments))
(format t "Not implemented yet.~%")
(finish-output)
ex-usage)
;; "─═┌╔┬╦┐╗├╠┼╬┤╣│║└╚┴╩┘╝"
;;
;; ┌────────────────────────┬────────┬──────┐
;; │ │ │ │
;; ├────────────────────────┼────────┼──────┤
;; │ │ │ │
;; └────────────────────────┴────────┴──────┘
;;
;; box drawing
;; ╭──────────────────────────────────────────────────────────────────────────────╮
;; │ │
;; │ │
;; │ │
;; ╰──────────────────────────────────────────────────────────────────────────────╯
;; spaces=' '
;;
;; if [ "$1" = "-toto" ] ; then
;; echo ' \\\\\\|/// '
;; echo ' \\\ - - // '
;; echo ' ( 0-0 ) '
;; echo '+-----------------------------oOOo-(_)-oOOo-----------------------------------+'
;; else
;; echo '+-----------------------------------------------------------------------------+'
;; fi
;;
;; while read line ; do
;; echo "$line$spaces$spaces" \
;; | expand \
;; | sed -e 's/^\(............................................................................\).*/| \1|/'
;; done
;;
;; if [ "$1" = "-toto" ] ; then
;; echo '| ooo0 |'
;; echo '| ( ) 0ooo |'
;; echo '+-----------------------------\ (----( )-----------------------------------+'
;; echo ' \_) ) / '
;; echo ' (_/ '
;; else
;; echo '+-----------------------------------------------------------------------------+'
;; fi
;;
;; exit 0
;; (load (make-pathname :name ".clisprc" :type "lisp"
;; :defaults (user-homedir-pathname)))
(setf (logical-pathname-translations "PACKAGES") nil)
(setf (logical-pathname-translations "PACKAGES")
`(("PACKAGES:COM;INFORMATIMAGO;**;*.*"
,(merge-pathnames "src/public/lisp/**/*.*" (user-homedir-pathname) nil))
("PACKAGES:COM;INFORMATIMAGO;**;*"
,(merge-pathnames "src/public/lisp/**/*" (user-homedir-pathname) nil))))
(load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE.LISP")
(package:load-package "COM.INFORMATIMAGO.COMMON-LISP.LIST")
(package:load-package "COM.INFORMATIMAGO.COMMON-LISP.STRING")
(import '(COM.INFORMATIMAGO.COMMON-LISP.STRING:prefixp))
(package:load-package "COM.INFORMATIMAGO.COMMON-LISP.PICTURE")
(use-package "COM.INFORMATIMAGO.COMMON-LISP.PICTURE")
(defparameter *box-path*
(or *load-pathname*
(make-pathname :directory (append (pathname-directory
(user-homedir-pathname)) '("bin"))
:name "box"
:defaults (user-homedir-pathname)
:case :default)))
(defparameter *templates*
(with-open-file (in *box-path* :direction :input :if-does-not-exist :error)
;; scan up to ";; DATA"
(loop do
(let ((line (read-line in nil nil)))
(when (or (null line) (prefixp line ";; DATA")) (loop-finish))))
(macrolet ((end-block
()
`(when block
(push (nreverse block) section)
(setf block nil)))
(end-section
()
`(when section
(push (nreverse section) sections)
(setf section nil))))
(do ((line (read-line in nil nil) (read-line in nil nil))
(sections ())
(section ())
(block ()))
((or (null line) (prefixp line ";; S END"))
(end-block) (end-section) (nreverse sections))
(cond
((prefixp line ";; ")) ;; ignore comment
((prefixp line ";; S ") ;; a new section
(end-block) (end-section)
(push (list :title (subseq line 5)) section))
((prefixp line ";; T ") ;; a block
(end-block)
(push (list :title (subseq line 5)) block))
((and (prefixp line ";; ") (< 5 (length line)))
(push (list (intern (subseq line 3 4) "KEYWORD")
(subseq line 5)) block)))))));;*templates*
;; Sections:
;; HEADS
;; FEET
;; FRAMES
(defun get-section (templates name)
(assoc name templates :key (function second) :test (function string=)))
(defun get-block (section name)
(assoc name (cdr section) :key (function second) :test (function string=)))
(defun fill-char (block)
(second (assoc :f block)))
(defun block-lines (block)
(remove-if (lambda (item) (member (car item) '(:title :f))) block))
(defun enclosing-box (lines &optional fill-char)
"
RETURN: left right first last
left and right are the maximum non-white-space or fill-char
columns in the lines.
first and last are the index in lines of the first and last lines
containing non-white-space or fill-char characters.
"
(let ((pred (function char/=))
(first most-positive-fixnum)
(last 0)
(left most-positive-fixnum)
(right 0))
(if fill-char
(setf pred (function char=)
fill-char (character fill-char))
(setf fill-char (character " ")))
(do ((i 0 (1+ i))
(lines lines (cdr lines))
(p))
((null lines) (values left right first last))
(setf p (position fill-char (car lines) :test pred))
(when p
(setf first (min first i)
last (max last i)
left (min left p)
right (max right (position fill-char (car lines)
:test pred :from-end t))))
)));;enclosing-box
(defun list-all-frames ()
(mapcar (function second) *templates)
)
#||
;; left right of - in base header line
(enclosing-box
(mapcar (function second)
(remove-if (lambda (line) (not (eq :i (car line))))
(BLOCK-LINES
(GET-BLOCK (get-section templates "FRAMES") "roll"))))
"-")
;; enclosing box of "*"
(enclosing-box
(mapcar (function second)
(BLOCK-LINES
(GET-BLOCK (get-section templates "FRAMES") "roll")))
"*")
;; enclosig box of sprite
(enclosing-box
(mapcar (function second)
(BLOCK-LINES
(GET-BLOCK (get-section templates "FEET") "toto"))))
ext:*args*
||#
;; S section
;; comment
;; T title
;; H picture
;; B base-line picture
;;
;;
;; DATA
;; S HEADS
;;
;;
;; T toto
;; H \\\|///
;; H \\ - - //
;; H ( 0-0 )
;; B --oOOo-(_)-oOOo--
;;
;;
;; T teacher
;; H ______
;; H |___| "
;; H (o o)
;; B -ooO--O--Ooo-
;;
;;
;; T bear
;; H (_)-(_)
;; H (o o)
;; B -ooO--(_)--Ooo-
;;
;;
;; T mouse
;; H ()_()
;; H (o o)
;; B -ooO--`o'--Ooo-
;;
;; T cow
;; H ((__))
;; H (00)
;; B -nn--(o__o)--nn-
;;
;;
;; T judge
;; H ___
;; H .|||.
;; H (o o)
;; B -ooO--(_)--Ooo-
;;
;;
;; T haut-de-forme
;; H |"|
;; H _|_|_
;; H (o o)
;; B -ooO--(_)--Ooo-
;;
;; T head-1
;; H '/_\
;; H (o o)
;; B -ooO--(_I--Ooo-
;;
;; T head-2
;; H ` /_\ '
;; H - (o o) -
;; B -ooO--(_)--Ooo-
;;
;; T asyrien
;; H . .:::.
;; H :(o o): .
;; B -ooO-=(_)--Ooo-
;;
;; T egyptian
;; H ,,,,,
;; H /(o o)\
;; B -ooO--(_)--Ooo-
;;
;; T head-3
;; H /\#/\
;; H /(o o)\
;; B -ooO=-(_)--Ooo-
;;
;; T et
;; H '. ___ .'
;; H ' (> <) '
;; B -ooO--(_)--Ooo-
;;
;; T head-4
;; H ` _ _ '
;; H - (OXO) -
;; B -ooO--(_)--Ooo-
;;
;; T head-5
;; H '\\-//`
;; H (o o)
;; B -ooO--(_)--Ooo-
;;
;; T head-5
;; H vvv
;; H (0~0)
;; B -ooO--(_)--Ooo-
;;
;; T head-5
;; H ` /_\ '
;; H - (o o) -
;; B -ooO--(_)--Ooo-
;;
;; T head-6
;; H /_\ `*
;; H (o o)
;; B -ooO--(_)--Ooo-
;;
;; T halterophile
;; H # #
;; H #=ooO=========Ooo=#
;; H # \\ (o o) // #
;; B ---------(_)---------
;;
;;
;; T lancier
;; H # ___
;; H # <_*_>
;; H # (o o)
;; B --8---(_)--Ooo-
;;
;;
;; T guard
;; H .'_#_`.
;; H |[o o]|
;; B -ooO--(_)--Ooo-
;;
;;
;; T head-7
;; H !!!
;; H ` _ _ '
;; H - (OXO) -
;; B -ooO--(_)--Ooo-
;;
;;
;; T head-8
;; H .|||.
;; H (o o)
;; B -ooO--(_)--Ooo-
;;
;;
;; T fou-du-roi
;; H _ _
;; H o' \.=./ `o
;; H (o o)
;; B -ooO--(_)--Ooo-
;;
;;
;; T
;; H |.===.
;; H {}o o{}
;; B -ooO--(_)--Ooo-
;;
;; T
;; H ,-_-|
;; H ([o o])
;; B -ooO--(_)--Ooo-
;;
;;
;; T canotier
;; H __MMM__
;; H (o o)
;; B -ooO--(_)--Ooo-
;;
;;
;; S FEET
;;
;; T small
;; B ----/\---/\----
;; H \( )/
;;
;;
;; T toto
;; E ooo0
;; E ( ) 0ooo
;; B ---\ (----( )--
;; E \_) ) /
;; E (_/
;;
;;
;;
;; S FRAMES
;; T title
;; F fill char
;; H head
;; M repeat line
;; N repeat portion (overiding E)
;; F repeat end (overiding E)
;; E end
;; O optional end
;; I head base line
;; G end base line
;;
;; T box
;; F *
;; I +---------------------------------------------------------------------+
;; M | ******************************************************************* |
;; G +---------------------------------------------------------------------+
;;
;;
;; T bevel
;; F *
;; I /---------------------------------------------------------------------\
;; M | ******************************************************************* |
;; G \---------------------------------------------------------------------/
;;
;;
;;
;; T tape
;; F *
;; I .-----------------------------------------------------------------.
;; H / .-. *************************************************** .-. \
;; H | / \ *************************************************** / \ |
;; H | |\_. | *************************************************** | /| |
;; H |\| | /| *************************************************** |\ | |/|
;; H | `---' | *************************************************** | `---' |
;; M | | *************************************************** | |
;; G | |-----------------------------------------------------| |
;; E \ | | /
;; E \ / \ /
;; E `---' `---'
;;
;;
;;
;; T roll
;; F *
;; H .---.
;; H / . \
;; H |\_/| |
;; H | | /|
;; I .----------------------------------------------------------------' |
;; H / .-. ********************************************************* |
;; H | / \ ********************************************************* |
;; H | |\_. | ********************************************************* |
;; H |\| | /| ********************************************************* |
;; H | `---' | ********************************************************* |
;; M | | ********************************************************* |
;; E | | ********************************************************* /
;; G | |----------------------------------------------------------'
;; E \ |
;; E \ /
;; E `---'
;;
;;
;; T directory
;; directory symbol, folder symbol]
;;
;; H ___
;; H /___\_________
;; H | |
;; H | ************ |
;; H | ************ |
;; H | ************ |
;; H | ************ |
;; HVK |______________|
;;
;;
;; T hand
;; F *
;; I ______________________________________
;; H | |
;; H _.---------|.--. ****************************** |
;; H .-' ` .'/ `` ****************************** |
;; H .-' .' | /| ****************************** |
;; H .-' | / `.__// ****************************** |
;; H .-' _.--/ / ****************************** |
;; H | _ .-' / / ****************************** |
;; H | ._ \ / ` / ****************************** |
;; H | ` . / ` / ****************************** |
;; H | \ \ '/ / ****************************** |
;; H | - \ / /| ****************************** |
;; H | ' .' / | ****************************** |
;; H | ' |.'| ****************************** |
;; H | | | ****************************** |
;; N | ****************************** |
;; G | | |______________________________________|
;; F |______________________________________|
;; E | |.'
;; E | /
;; E | /
;; E | /
;; E ) /|
;; E .A/`-. / |
;; E AMMMA. `-._ / /
;; E AMMMMMMMMA. `-. / /
;; E AMMMMMMMMMMMMA. `. /
;; E AMMMMMMMMMMMMMMMMA.`. /
;; E MMMMMMMMMMMMMMMMMMMA.`.
;; E MMMMMMMMMMMMMMMMMMMMMA.`.
;; E MMMMMMMMMMMMMMMMMMMMMMMA.
;; E MMMMMMMMMMMMMMMMMMMMMMMMMA.
;; E MMVKMMMMMMMMMMMMMMMMMMMMMMM
;; E MMMMMMMMMMMMMMMMMMMMMMMMMV'
;; O MMMMMMMMMMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMMV
;; O MMMMMMMMMMMMMV
;; O MMMMMMMMMMMMV
;; O MMMMMMMMMMMV
;; O MMMMMMMMMMV
;; O MMMMMMMMMV
;; O MMMMMMMMV
;; O MMMMMMMV
;; O MMMMMMV
;; O MMMMMV
;; O MMMMV
;; O MMMV
;; O MMV
;; O MV
;; O V
;;
;; S END
;;
;; if you are a legitimat__email operator that has be victimized by spews
;; > please contact m_ to ( ) a __ass ac____ lawsuit.
;; > ( ) \ ( ( \ ( )
;; > although free __)\ch __) \rt) (ly __) / defamation is not. We are
;; > not su__g s__( (__/ )( \ ( )sue God. they exist but are
;; > facel( \a( (__) (d ) \fi_ing a class action by
;; > the IS) \t) )/ )( )se spews subscribers
;; > who_s(__ ' (_/(__ be___ior.
;; > (_) __) S P L O R F ) ( )
;; > if yo(___ _ /m t) )
;; > ( ___ ____/ )) (__/
;; > spew_(\ta) _ (t a) __ ____ __)s _o( \_came the KKK/Gestapo
;; > of (___)(_/r) \T( (ar\ (imin)( co_/ )r\__)with no face, and
;; > unlimited p(_____)t\ey) ( __) t/ /se( (_up to be the judge, jury,
;; > and executio_er. In )(eir\ (urt,(_/u ar) )lty by association,
;; > guilty unti(_)roven(__)oc( ) b_t then(___/l punished even though
;; > you ARE innocent. )/ (_)
;; > '
;;;; box -- -- ;;;;
| 16,642 | Common Lisp | .lisp | 509 | 28.697446 | 107 | 0.301567 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 3c0f3e310aceca2c45b07d68b58da473cec9c95b9196afad408ebf9a6335f0f6 | 12,318 | [
-1
] |
12,319 | random.lisp | informatimago_commands/sources/commands/random.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(defun random-elt (list)
(elt list (random (length list))))
(defun main (arguments)
(setf *random-state* (make-random-state t))
(cond ((null arguments)
(prin1 (random #x100000000)))
((and (null (rest arguments))
(ignore-errors (realp (let ((*read-eval* nil))
(read-from-string (first arguments))))))
(prin1 (random (let ((*read-eval* nil))
(read-from-string (first arguments))))))
(t
(princ (random-elt arguments))))
(terpri)
(finish-output)
ex-ok)
;;;; THE END ;;;;
| 640 | Common Lisp | .lisp | 18 | 27 | 78 | 0.533118 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 85a1f992d83456badc8de13651ca87677722f4019ff7ab297ffb2dea499bf2c7 | 12,319 | [
-1
] |
12,320 | departement.lisp | informatimago_commands/sources/commands/departement.lisp | ;; -*- mode:lisp;coding:utf-8 -*-
(defparameter *departements*
;; (numero département préfecture sous-préfectures région)
'(("01" "Ain" "Bourg-en-Bresse" ("Belley" "Gex" "Nantua") "Auvergne-Rhône-Alpes")
("02" "Aisne" "Laon" ("Château-Thierry" "Saint-Quentin" "Soissons" "Vervins")
"Nord-Pas-de-Calais-Picardie")
("03" "Allier" "Moulins" ("Montluçon" "Vichy") "Auvergne-Rhône-Alpes")
("04" "Alpes-de-Haute-Provence" "Digne-les-Bains"
("Barcelonnette" "Castellane" "Forcalquier") "Provence-Alpes-Côte d'Azur")
("05" "Hautes-Alpes" "Gap" ("Briançon") nil)
("06" "Alpes-Maritimes" "Nice" ("Grasse") nil)
("07" "Ardèche" "Privas" ("Largentière" "Tournon-sur-Rhône")
"Auvergne-Rhône-Alpes")
("08" "Ardennes" "Charleville-Mézières" ("Rethel" "Sedan" "Vouziers")
"Alsace-Champagne-Ardenne-Lorraine")
("09" "Ariège" "Foix" ("Pamiers" "Saint-Girons")
"Languedoc-Roussillon-Midi-Pyrénées")
("10" "Aube" "Troyes" ("Bar-sur-Aube" "Nogent-sur-Seine")
"Alsace-Champagne-Ardenne-Lorraine")
("11" "Aude" "Carcassonne" ("Limoux" "Narbonne")
"Languedoc-Roussillon-Midi-Pyrénées")
("12" "Aveyron" "Rodez" ("Millau" "Villefranche-de-Rouergue") nil)
("13" "Bouches-du-Rhône" "Marseille" ("Aix-en-Provence" "Arles" "Istres")
"Provence-Alpes-Côte d'Azur")
("14" "Calvados" "Caen" ("Bayeux" "Lisieux" "Vire")
"Région Normandie|Normandie")
("15" "Cantal" "Aurillac" ("Mauriac" "Saint-Flour") "Auvergne-Rhône-Alpes")
("16" "Charente" "Angoulême" ("Cognac" "Confolens")
"Aquitaine-Limousin-Poitou-Charentes")
("17" "Charente-Maritime" "La Rochelle"
("Jonzac" "Rochefort" "Saint-Jean-d'Angély" "Saintes") nil)
("18" "Cher" "Bourges" ("Saint-Amand-Montrond" "Vierzon") "Centre-Val de Loire")
("19" "Corrèze" "Tulle" ("Brive-la-Gaillarde" "Ussel")
"Aquitaine-Limousin-Poitou-Charentes")
("2A" "Corse-du-Sud" "Ajaccio" ("Sartène") "Corse")
("2B" "Haute-Corse" "Bastia" ("Calvi" "Corte") nil)
("21" "Côte-d'Or" "Dijon" ("Beaune" "Montbard") "Bourgogne-Franche-Comté")
("22" "Côtes-d'Armor" "Saint-Brieuc" ("Dinan" "Guingamp" "Lannion") "Bretagne")
("23" "Creuse" "Guéret" ("Aubusson") "Aquitaine-Limousin-Poitou-Charentes")
("24" "Dordogne" "Périgueux" ("Bergerac" "Nontron" "Sarlat-la-Canéda") nil)
("25" "Doubs" "Besançon" ("Montbéliard" "Pontarlier") "Bourgogne-Franche-Comté")
("26" "Drôme" "Valence" ("Die" "Nyons") "Auvergne-Rhône-Alpes")
("27" "Eure" "Évreux" ("Les Andelys" "Bernay") "Région Normandie|Normandie")
("28" "Eure-et-Loir" "Chartres" ("Châteaudun" "Dreux" "Nogent-le-Rotrou")
"Centre-Val de Loire")
("29" "Finistère" "Quimper" ("Brest" "Châteaulin" "Morlaix") "Bretagne")
("30" "Gard" "Nîmes" ("Alès" "Le Vigan") "Languedoc-Roussillon-Midi-Pyrénées")
("31" "Haute-Garonne" "Toulouse" ("Muret" "Saint-Gaudens") nil)
("32" "Gers" "Auch" ("Condom" "Mirande") nil)
("33" "Gironde" "Bordeaux"
("Arcachon" "Blaye" "Langon" "Lesparre-Médoc" "Libourne")
"Aquitaine-Limousin-Poitou-Charentes")
("34" "Hérault" "Montpellier" ("Béziers" "Lodève")
"Languedoc-Roussillon-Midi-Pyrénées")
("35" "Ille-et-Vilaine" "Rennes" ("Fougères" "Redon" "Saint-Malo") "Bretagne")
("36" "Indre" "Châteauroux" ("Le Blanc" "La Châtre" "Issoudun")
"Centre-Val de Loire")
("37" "Indre-et-Loire" "Tours" ("Chinon" "Loches") nil)
("38" "Isère" "Grenoble" ("La Tour-du-Pin" "Vienne") "Auvergne-Rhône-Alpes")
("39" "Jura" "Lons-le-Saunier" ("Dole" "Saint-Claude")
"Bourgogne-Franche-Comté")
("40" "Landes" "Mont-de-Marsan" ("Dax") "Aquitaine-Limousin-Poitou-Charentes")
("41" "Loir-et-Cher" "Blois" ("Romorantin-Lanthenay" "Vendôme")
"Centre-Val de Loire")
("42" "Loire" "Saint-Étienne" ("Montbrison" "Roanne") "Auvergne-Rhône-Alpes")
("43" "Haute-Loire" "Le Puy-en-Velay" ("Brioude" "Yssingeaux") nil)
("44" "Loire-Atlantique" "Nantes" ("Ancenis" "Châteaubriant" "Saint-Nazaire")
"Pays de la Loire")
("45" "Loiret" "Orléans" ("Montargis" "Pithiviers") "Centre-Val de Loire")
("46" "Lot" "Cahors" ("Figeac" "Gourdon") "Languedoc-Roussillon-Midi-Pyrénées")
("47" "Lot-et-Garonne" "Agen" ("Marmande" "Nérac" "Villeneuve-sur-Lot")
"Aquitaine-Limousin-Poitou-Charentes")
("48" "Lozère" "Mende" ("Florac") "Languedoc-Roussillon-Midi-Pyrénées")
("49" "Maine-et-Loire" "Angers" ("Cholet" "Saumur" "Segré") "Pays de la Loire")
("50" "Manche" "Saint-Lô" ("Avranches" "Cherbourg" "Coutances")
"Région Normandie|Normandie")
("51" "Marne" "Châlons-en-Champagne"
("Épernay" "Reims" "Sainte-Menehould" "Vitry-le-François")
"Alsace-Champagne-Ardenne-Lorraine")
("52" "Haute-Marne" "Chaumont" ("Langres" "Saint-Dizier") nil)
("53" "Mayenne" "Laval" ("Château-Gontier" "Mayenne") "Pays de la Loire")
("54" "Meurthe-et-Moselle" "Nancy" ("Briey" "Lunéville" "Toul")
"Alsace-Champagne-Ardenne-Lorraine")
("55" "Meuse" "Bar-le-Duc" ("Commercy" "Verdun") nil)
("56" "Morbihan" "Vannes" ("Lorient" "Pontivy") "Bretagne")
("57" "Moselle" "Metz" ("Forbach" "Sarrebourg" "Sarreguemines" "Thionville")
"Alsace-Champagne-Ardenne-Lorraine")
("58" "Nièvre" "Nevers"
("Château-Chinon (Ville)" "Clamecy" "Cosne-Cours-sur-Loire")
"Bourgogne-Franche-Comté")
("59" "Nord" "Lille"
("Avesnes-sur-Helpe" "Cambrai" "Douai" "Dunkerque" "Valenciennes")
"Nord-Pas-de-Calais-Picardie")
("60" "Oise" "Beauvais" ("Clermont" "Compiègne" "Senlis") nil)
("61" "Orne" "Alençon" ("Argentan" "Mortagne-au-Perche")
"Région Normandie|Normandie")
("62" "Pas-de-Calais" "Arras"
("Béthune" "Boulogne-sur-Mer" "Calais" "Lens" "Montreuil" "Saint-Omer")
"Nord-Pas-de-Calais-Picardie")
("63" "Puy-de-Dôme" "Clermont-Ferrand" ("Ambert" "Issoire" "Riom" "Thiers")
"Auvergne-Rhône-Alpes")
("64" "Pyrénées-Atlantiques" "Pau" ("Bayonne" "Oloron-Sainte-Marie")
"Aquitaine-Limousin-Poitou-Charentes")
("65" "Hautes-Pyrénées" "Tarbes" ("Argelès-Gazost" "Bagnères-de-Bigorre")
"Languedoc-Roussillon-Midi-Pyrénées")
("66" "Pyrénées-Orientales" "Perpignan" ("Céret" "Prades") nil)
("67" "Bas-Rhin" "Strasbourg" ("Haguenau" "Molsheim" "Saverne" "Sélestat")
"Alsace-Champagne-Ardenne-Lorraine")
("68" "Haut-Rhin" "Colmar" ("Altkirch" "Mulhouse" "Thann") nil)
("69" "Circonscription départementale du Rhône" "Lyon"
("Villefranche-sur-Saône") "Auvergne-Rhône-Alpes")
("70" "Haute-Saône" "Vesoul" ("Lure") "Bourgogne-Franche-Comté")
("71" "Saône-et-Loire" "Mâcon"
("Autun" "Chalon-sur-Saône" "Charolles" "Louhans") nil)
("72" "Sarthe" "Le Mans" ("La Flèche" "Mamers") "Pays de la Loire")
("73" "Savoie" "Chambéry" ("Albertville" "Saint-Jean-de-Maurienne")
"Auvergne-Rhône-Alpes")
("74" "Haute-Savoie" "Annecy"
("Bonneville" "Saint-Julien-en-Genevois" "Thonon-les-Bains") nil)
("75" "Paris" "Île-de-France" nil nil)
("76" "Seine-Maritime" "Rouen" ("Dieppe" "Le Havre")
"Région Normandie|Normandie")
("77" "Seine-et-Marne" "Melun" ("Fontainebleau" "Meaux" "Provins" "Torcy")
"Île-de-France")
("78" "Yvelines" "Versailles"
("Mantes-la-Jolie" "Rambouillet" "Saint-Germain-en-Laye") nil)
("79" "Deux-Sèvres" "Niort" ("Bressuire" "Parthenay")
"Aquitaine-Limousin-Poitou-Charentes")
("80" "Somme" "Amiens" ("Abbeville" "Montdidier" "Péronne")
"Nord-Pas-de-Calais-Picardie")
("81" "Tarn" "Albi" ("Castres") "Midi-Pyrénées")
("82" "Tarn-et-Garonne" "Montauban" ("Castelsarrasin") nil)
("83" "Var" "Toulon" ("Brignoles" "Draguignan") "Provence-Alpes-Côte d'Azur")
("84" "Vaucluse" "Avignon" ("Apt" "Carpentras") nil)
("85" "Vendée" "La Roche-sur-Yon" ("Fontenay-le-Comte" "Les Sables-d'Olonne")
"Pays de la Loire")
("86" "Vienne" "Poitiers" ("Châtellerault" "Montmorillon")
"Aquitaine-Limousin-Poitou-Charentes")
("87" "Haute-Vienne" "Limoges" ("Bellac" "Rochechouart") nil)
("88" "Vosges" "Épinal" ("Neufchâteau" "Saint-Dié-des-Vosges")
"Alsace-Champagne-Ardenne-Lorraine")
("89" "Yonne" "Auxerre" ("Avallon" "Sens") "Bourgogne-Franche-Comté")
("90" "Territoire de Belfort" "Belfort" nil nil)
("91" "Essonne" "Évry" ("Étampes" "Palaiseau") "Île-de-France")
("92" "Hauts-de-Seine" "Nanterre" ("Antony" "Boulogne-Billancourt") nil)
("93" "Seine-Saint-Denis" "Bobigny" ("Le Raincy" "Saint-Denis") nil)
("94" "Val-de-Marne" "Créteil" ("L'Haÿ-les-Roses" "Nogent-sur-Marne") nil)
("95" "Val-d'Oise" "Cergy" ("Argenteuil" "Pontoise" "Sarcelles") nil)
("971" "Guadeloupe" "Basse-Terre" ("Pointe-à-Pitre") "Guadeloupe")
("972" "Martinique" "Fort-de-France" ("La Trinité" "Le Marin" "Saint-Pierre")
"Martinique")
("973" "Guyane" "Cayenne" ("Saint-Laurent-du-Maroni") "Guyane")
("974" "La Réunion" "Saint-Denis" ("Saint-Benoît" "Saint-Paul" "Saint-Pierre")
"La Réunion")
("976" "Mayotte" "Mamoudzou" ("Mayotte") nil)
("975" "Saint-Pierre-et-Miquelon" nil nil "Pays et territoire d'outre-mer")
("977" "Saint-Barthélemy" nil nil "Pays et territoire d'outre-mer")
("978" "Saint-Martin" nil nil "Région ultrapériphérique")
("987" "Polynésie française" nil nil "Pays et territoire d'outre-mer")
("989" "île de Clipperton" nil nil nil)
("986" "Wallis-et-Futuna" nil nil "Pays et territoire d'outre-mer")
("988" "Nouvelle-Calédonie" nil nil "Pays et territoire d'outre-mer")
("984" "Terres australes et antarctiques françaises" nil nil nil)))
(defun departement (numero)
(or (find-if (lambda (departement)
(find numero departement
:test (lambda (a b) (search a b :test (function string-equal)))))
*departements*)
(ignore-errors
(let ((numero (format nil "~2,'0D" (parse-integer numero))))
(find numero *departements* :key (function first) :test (function string-equal))))))
(defun main (numeros)
(format t "~:{~3A ~A~%~
~@[ Préfecture: ~A.~%~]~
~@[ Sous-préfectures: ~{~A~^, ~}.~%~]~
~:*~:[~@[ ~A.~%~]~;~@[ Région: ~A.~%~]~]~}"
(remove nil (mapcar (function departement) numeros)))
ex-ok)
;; ISO 3166-2:FR
;;
;; Les départements français possèdent un code ISO sous la forme suivante :
;; FR-XX où XX est le code du département (par ex FR-2B pour la
;; Haute-Corse). Ceci ne concerne que les départements métropolitains ;
;; les départements d'outre-mer ont un code ISO spécifique, par exemple
;; FR-GP pour la Guadeloupe.
;;;; THE END ;;;;
| 10,804 | Common Lisp | .lisp | 186 | 51.77957 | 93 | 0.637077 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 4a3d8e9d6dfc330e8ae4d52ba79c067dba46a50428378516aa4edac1865333e3 | 12,320 | [
-1
] |
12,321 | lc.lisp | informatimago_commands/sources/commands/lc.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(command :use-systems (:com.informatimago.common-lisp.cesarum)
:use-packages ("COMMON-LISP"
"SCRIPT"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM"))
(in-package "COMMAND.LC")
(defun process-file (encoding file)
(let* ((file (truename file))
(file.bak (merge-pathnames (make-pathname :type "BAK" :case :common) file)))
(ignore-errors (delete-file file.bak))
(handler-case (rename-file file file.bak)
(error (err)
(format *error-output* "Cannot rename the file ~A to a backup file ~A~%~A"
file file.bak err)
(return-from process-file ex-oserr)))
(handler-case (copy-file file.bak file :external-format encoding)
(error (err)
(format *error-output* "Error while copying the file ~A to ~A~%~A~%"
file.bak file err)
(return-from process-file ex-oserr)))
ex-ok))
(defun process-stream (encoding input output)
(declare (ignorable encoding))
#+ccl (setf (stream-external-format output) encoding)
#-ccl (warn "Use flexi-strems to change the external-format / encoding?")
(handler-case (copy-stream input output)
(error (err)
(format *error-output*
"Error while copying the input stream to the output stream~%~A"
err)
(return-from process-stream 1)))
ex-ok)
(defun main (&optional args)
(labels ((ef (line-terminator)
#-clisp (declare (ignore line-terminator))
#+clisp (ext:make-encoding :charset charset:iso-8859-1
:line-terminator line-terminator)
#-clisp :iso-8859-1)
(usage ()
(format *standard-output*
"~A usage:~
~
~& ~:*~A -u|-m|-p|-h [file...] | < input > output~
~&"
(if *load-pathname*
(file-namestring *load-pathname*)
"lc")))
(err (fctrl &rest args)
(apply (function format) *error-output* fctrl args)
(usage)
(return-from main 1)))
(loop
:with got-file-p := nil
:with status := 0
:with ef := nil
:for arg :in args
:do (cond ((string= "-u" arg) (setf ef (ef :unix)))
((string= "-m" arg) (setf ef (ef :mac)))
((string= "-p" arg) (setf ef (ef :dos)))
((string= "-h" arg) (usage) (return-from main 0))
((string= "-" arg :end2 1) (err "Unknown option: ~A" arg))
(t (let ((new-status (process-file ef arg)))
(setf got-file-p t
status (if (zerop new-status) status new-status)))))
:finally (cond
((null ef) (err "I need an option~%"))
(got-file-p (return-from main status))
(t (return-from main (process-stream
ef
*standard-input*
*standard-output*))))))
ex-ok)
;;;; THE END ;;;;
| 3,353 | Common Lisp | .lisp | 74 | 31.756757 | 85 | 0.493888 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 37eb13df59d3a43133e3ed58c813548466359d17c76eee0f984561296978b458 | 12,321 | [
-1
] |
12,322 | buzzword.lisp | informatimago_commands/sources/commands/buzzword.lisp | ;; -*- mode:lisp;coding:utf-8 -*-
(defun main (arguments)
(declare (ignore arguments))
(setf *random-state* (make-random-state t))
(let ((a (random 10))
(b (random 10))
(c (random 10))
(w (make-array '(10 3) :initial-contents
#((integrated management options)
(total organizational flexibility)
(systematized monitored capability)
(parallel reciprocal mobility)
(functional digital programming)
(responsive logistical concept)
(optional transitional time-phase)
(synchronized incremental projection)
(compatible third-generation hardware)
(balanced policy contingency))))
(*print-case* :downcase))
(format t "~&~A ~A ~A~%" (aref w a 0) (aref w b 1) (aref w c 2))
(finish-output))
ex-ok)
;;;; THE END ;;;;
| 1,176 | Common Lisp | .lisp | 23 | 37.173913 | 80 | 0.439618 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 9bb3eac03f8c00eb8176449027bdace08fd23459da93b2a7de51f5e0659657f3 | 12,322 | [
-1
] |
12,323 | capitalize.lisp | informatimago_commands/sources/commands/capitalize.lisp | ;; -*- mode:lisp; coding:utf-8 -*-
;; Replaces any sequences of non alphanumeric or dot character in the
;; arguments by a single dash.
(defun split-string-if (predicate string &key remove-empty-subseqs)
"
NOTE: current implementation only accepts as separators
a string containing literal characters.
"
(declare (ignore remove-empty-subseqs))
(let ((chunks '())
(position 0)
(nextpos 0)
(strlen (length string)))
(loop :while (< position strlen) :do
(loop :while (and (< nextpos strlen)
(not (funcall predicate (aref string nextpos)))) :do
(incf nextpos))
(push (subseq string position nextpos) chunks)
(setf position (1+ nextpos)
nextpos position))
(nreverse chunks)))
(defun split-string (separators string &key remove-empty-subseqs)
(split-string-if (lambda (ch) (find ch separators)) string
:remove-empty-subseqs remove-empty-subseqs))
;;;;--------------------------------------------------------------------
(defun main (arguments)
(loop
:for arg :in arguments
:do (write-line (string-capitalize arg)))
ex-ok)
;;;; THE END ;;;;
| 1,198 | Common Lisp | .lisp | 31 | 32.580645 | 77 | 0.607081 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 219ba69386609eb4e1f8bd5dba2e263698f2a1d2085bcdad08093dfaeca5126f | 12,323 | [
-1
] |
12,324 | ansi-test.lisp | informatimago_commands/sources/commands/ansi-test.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: ansi-test
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Prints a test page for ANSI codes (ECMA-048) for text color
;;;; and text rendering on a terminal.
;;;;
;;;;SYNOPSIS
;;;; ansi-test
;;;; xterm -xrm 'xterm*hold: on' -e ansi-test
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-12-24 <PJB> Updated for cesarum.
;;;; 2010-11-22 <PJB> Added this header.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2012
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(in-package "SCRIPT")
(defparameter *program-version* "1.0.2")
(defparameter *program-name* "ansi-test")
(command :use-systems (:com.informatimago.common-lisp)
:use-packages ("COMMON-LISP"
"SCRIPT"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY")
:main "COMMAND.ANSI-TEST:MAIN")
(cl:in-package "SCRIPT")
(defpackage "E48"
(:use)
(:export "ACK" "APC" "BEL" "BPH" "BS" "CAN" "CBT" "CCH" "CHA" "CHT"
"CMD" "CNL" "CPL" "CPR" "CR" "CSI" "CTC" "CUB" "CUD" "CUF"
"CUP" "CUU" "CVT" "DA" "DAQ" "DC1" "DC2" "DC3" "DC4" "DCH"
"DCS" "DL" "DLE" "DMI" "DSR" "DTA" "EA" "ECH" "ED" "EF"
"EL" "EM" "EMI" "ENQ" "EOT" "EPA" "ESA" "ESC" "ETB" "ETX"
"FF" "FNK" "FNT" "GCC" "GSM" "GSS" "HPA" "HPB" "HPR" "HT"
"HTJ" "HTS" "HVP" "ICH" "IDCS" "IGS" "IL" "INT" "IS1" "IS2"
"IS3" "IS4" "JFY" "LF" "LS0" "LS1" "LS2" "LS3" "MC" "MW"
"NAK" "NBH" "NEL" "NP" "NUL" "OSC" "PEC" "PFS" "PLD" "PLU"
"PM" "PP" "PPA" "PPB" "PPR" "PTX" "PU1" "PU2" "QUAD" "REP"
"RI" "RIS" "RM" "SACS" "SAPV" "SCI" "SCO" "SCP" "SCS" "SD"
"SDS" "SEE" "SEF" "SGR" "SHS" "SI" "SIMD" "SL" "SLH" "SLL"
"SLS" "SM" "SO" "SOH" "SOS" "SPA" "SPD" "SPH" "SPI" "SPL"
"SPQR" "SR" "SRCS" "SRS" "SS2" "SS3" "SSA" "SSU" "SSW" "ST"
"STAB" "STS" "STX" "SU" "SUB" "SVS" "SYN" "TAC" "TALE"
"TATE" "TBC" "TCC" "TSR" "TSS" "VPA" "VPB" "VPR" "VT"
"VTS"))
(cl:in-package "E48")
(cl:eval-when (:compile-toplevel :load-toplevel :execute)
(com.informatimago.common-lisp.cesarum.ecma048:define-all-functions
:export cl:t :8-bit cl:nil :print cl:t :result-type cl:string))
(cl:in-package "COMMAND.ANSI-TEST")
(defparameter *program-version* "1.0.2")
(defparameter *program-name* "ansi-test")
(options "ansi-test"
(option ("version" "-V" "--version") ()
"Report the version of this script."
(format t "~A ~A~%" script:*program-name* script:*program-version*))
(help-option)
(bash-completion-options))
(defenum sgr-codes
"
0 normal (reset)
1 bold or increased intensity
2 faint, decreased intensity or second colour
3 italicized
4 singly underlined
5 slowly blinking (less then 150 per minute)
6 rapidly blinking (150 per minute or more)
7 negative image
8 concealed characters
9 crossed-out (characters still legible but marked as to be deleted)
10 primary (default) font
11 first alternative font
12 second alternative font
13 third alternative font
14 fourth alternative font
15 fifth alternative font
16 sixth alternative font
17 seventh alternative font
18 eighth alternative font
19 ninth alternative font
20 Fraktur (Gothic)
21 doubly underlined
22 normal colour or normal intensity (neither bold nor faint)
23 not italicized, not fraktur
24 not underlined (neither singly nor doubly)
25 steady (not blinking)
26 (reserved for proportional spacing as specified in CCITT Recommendation
T.61)
27 positive image
28 revealed characters
29 not crossed out
30 black display
31 red display
32 green display
33 yellow display
34 blue display
35 magenta display
36 cyan display
37 white display
38 (reserved for future standardization; intended for setting
character foreground colour as specified in ISO 8613-6 [CCITT
Recommendation T.416])
39 default display colour (implementation-defined)
40 black background
41 red background
42 green background
43 yellow background
44 blue background
45 magenta background
46 cyan background
47 white background
48 (reserved for future standardization; intended
for setting character background colour as specified in ISO 8613-6
[CCITT Recommendation T.416])
49 default background colour (implementation-defined)
50 (reserved for cancelling the effect of the rendering aspect
established by parameter value 26)
51 framed
52 encircled
53 overlined
54 not framed, not encircled
55 not overlined
56 (reserved for future standardization)
57 (reserved for future standardization)
58 (reserved for future standardization)
59 (reserved for future standardization)
60 ideogram underline or right side line
61 ideogram double underline or double line on the right side
62 ideogram overline or left side line
63 ideogram double overline or double line on the left side
64 ideogram stress marking
65 cancels the effect of the rendition aspects established by
parameter values 60 to 64.
"
normal
bold faint italic underline slow-blink fast-blink invert hidden
crossed-out primary-font first-font second-font third-font fourth-font
fifth-font sixth-font seventh-font eighth-font ninth-font gothic
double-underline no-bold no-italic no-underline no-blink reserved-1
no-invert no-hidden no-crossed-out black-foreground red-foreground
green-foreground yellow-foreground blue-foreground magenta-foreground
cyan-foreground white-foreground reseved-2 default-foreground
black-background red-background green-background yellow-background
blue-background magenta-background cyan-background white-background
reserved-3 default-background reserved-4 framed encircled overlined
not-framed not-verlined reserved-5 reserved-6 reserved-7 reserved-8
ideogram-underline ideogram-double-underline ideogram-overline
ideogram-double-overline ideogram-stress ideogram-cancel)
(defconstant blink slow-blink)
(defun ansi-test ()
(e48:ris)
(let ((y 0)
(x 0)
bb ff)
(flet ((label (col)
(format nil "~8a"
(subseq (string (sgr-codes-label col)) 0
(position (character "-")
(string (sgr-codes-label col)))))))
(dolist (b (list WHITE-background
CYAN-background MAGENTA-background YELLOW-background
BLUE-background GREEN-background RED-background
BLACK-background))
(setf bb (label b))
(dolist (f (list WHITE-foreground
CYAN-foreground MAGENTA-foreground YELLOW-foreground
BLUE-foreground GREEN-foreground RED-foreground
BLACK-foreground))
(setf ff (label f))
(e48:cup y x)
(incf y)
(when (= y 16) (setf y 0 x (+ x 20)))
(e48:sgr b)
(e48:sgr f)
(format t "~A on ~A " ff bb)
(e48:sgr normal)))))
(let ((y 16)
(x 0)
jin jbl jun jbo)
(flet ((label (mode)
(format nil "~8a"
(subseq (string (sgr-codes-label mode)) 0
(min (length (string (sgr-codes-label mode)))
8)))))
(dolist (in (list no-invert invert))
(setf jin (label in))
(dolist (bl (list no-blink blink))
(setf jbl (label bl))
(dolist (un (list no-underline underline))
(setf jun (label un))
(dolist (bo (list no-bold bold))
(setf jbo (label bo))
(e48:cup y x)
(incf y)
(e48:sgr in)
(e48:sgr bl)
(e48:sgr un)
(e48:sgr bo)
(format t " ~A ~A ~A ~A " jin jbl jun jbo)
(e48:sgr normal))))
(setf y 16 x 40))))
(finish-output))
(defun main (arguments)
(catch 'go-on
(parse-options *command* arguments (lambda () (throw 'go-on t)))
(exit ex-usage))
(ansi-test)
ex-ok)
;;;; THE END ;;;;
| 9,466 | Common Lisp | .lisp | 232 | 33.659483 | 85 | 0.609158 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 3bbe3073ff7fa0d41ca50f8853fc2c3c084ef463e2baaf6737f759e4caa2e91e | 12,324 | [
-1
] |
12,325 | entropy.lisp | informatimago_commands/sources/commands/entropy.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(defun entropy (histogram total)
(let ((entropy 0)
(base (length histogram)))
(map nil (lambda (count)
(let ((p (/ count total)))
(when (plusp p)
(decf entropy (* p (log p base))))))
histogram)
entropy))
(defun byte-histogram (stream)
(let ((total 0)
(histogram (make-array 256 :initial-element 0))
(next-byte (if (subtypep (stream-element-type stream) 'character)
(lambda ()
(let ((ch (read-char stream nil nil)))
(and ch (char-code ch))))
(lambda ()
(read-byte stream nil nil)))))
(loop
:for byte := (funcall next-byte)
:while byte
:do (incf total)
(incf (aref histogram byte)))
(values histogram total)))
;; entropy = 0
;;
;; for count in byte_counts:
;; # If no bytes of this value were seen in the value, it doesn't affect
;; # the entropy of the file.
;; if count == 0:
;; continue
;; # p is the probability of seeing this byte in the file, as a floating-
;; # point number
;; p = 1.0 * count / total
;; entropy -= p * math.log(p, 256)
(defun main (arguments)
(declare (ignore arguments))
(format t "~A~%" (multiple-value-call (function entropy)
(byte-histogram *standard-input*)))
ex-ok)
;;;; THE END ;;;;
| 1,474 | Common Lisp | .lisp | 42 | 27.333333 | 77 | 0.529783 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | a3f76336588e268bb366419770681a9edf3eccf81ff471c92e05f1606a4ec5a3 | 12,325 | [
-1
] |
12,326 | programmer.lisp | informatimago_commands/sources/commands/programmer.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(defparameter *sentences*
'("It works on my machine."
"It’s not a bug, it’s a feature."
"How hard can it be?"
"How did that even work in the first place?"
"I don’t see anything in the logs."
"I’m guessing it’s an issue on their side."
"Probably some kind of permissions issue."
"That’s weird."
"That’s a known issue."
"We don’t support that."
"No, I don’t know how long it’s going to take."
"Actually, it has always been like that."
"Have you tried it with Chrome or Firefox?"
"It should work now."
"But that’s not how you told me it should work."
"Well there’s your problem right there."
"Working as intended."
"I mean, everything’s *possible*…"
"That will never happen."
"Shouldn’t take too long."
"Cheap, fast, high quality. Pick any two."
"It’s 90% done."
"This is just a temporary fix"
"You’re doing it wrong"
"That’s a code smell."
"I thought we fixed this!"
"Yes, but does it scale?"))
(defparameter *gn*
'(
"foobar"
"Grok"
"Rabbit hole"
"Turtles all the way down"
"Yak shaving"
"Bikeshedding"
"Automagically"
"Performant"
"+1"
"TODO"
))
(defun one-of (s) (elt s (random (length s))))
(defun main (arguments)
(declare (ignore arguments))
(setf *random-state* (make-random-state t))
(princ (one-of *sentences*))
(terpri)
ex-ok)
;;;; THE END ;;;;
| 1,493 | Common Lisp | .lisp | 50 | 24.78 | 52 | 0.62955 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | c5639c0ca9603b39ee31abd76cc8f92608d361b2f2c4dae521d95a804f696500 | 12,326 | [
-1
] |
12,327 | news-to-mbox.lisp | informatimago_commands/sources/commands/news-to-mbox.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: news-to-mbox
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Converts a news job file as produced by suck(1) into a mbox file.
;;;; news-to-mbox <file.news >file.mbox
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2007-10-02 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 2007 - 2007
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(defmacro scase (keyform &rest clauses)
"
DO: A CASE, but for string keys. That is, it uses STRING= as test
insteand of the ''being the same'' test.
"
(let ((key (gensym "KEY")))
`(let ((,key ,keyform))
(cond
,@(mapcar (lambda (clause)
(if (or (eq (car clause) 'otherwise) (eq (car clause) 't))
`(t ,@(cdr clause))
`((member ,key ',(car clause) :test (function string=))
,@(cdr clause))))
clauses)))))
(defvar *log* nil)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *ascii-characters*
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~")
(defun ascii-code (character)
(if (char= #\newline character)
10
(let ((pos (position character *ascii-characters*)))
(if pos
(+ 32 pos)
(error "~C is not a character encodable into ASCII" character)))))
(defun code-ascii (code)
(cond
((= 10 code) #\newline)
((<= 32 code 126) (aref *ascii-characters* (- code 32)))
(t (error "~D is not the ASCII code of any character." code))))
(defun ascii-decode (bytes)
(loop
:with string = (make-string (- (length bytes) (count 13 bytes)))
:with i = -1
:for code :across bytes
:unless (= 13 code)
:do (setf (aref string (incf i)) (code-ascii code))
:finally (return string)))
(defun ascii-encode (string)
(loop
:with bytes = (make-array (+ (length string) (count #\newline string))
:element-type '(unsigned-byte 8)
:initial-element 0)
:with i = -1
:for ch :across string
:do (if (char= #\newline ch)
(setf (aref bytes (incf i)) 13
(aref bytes (incf i)) 10)
(setf (aref bytes (incf i)) (ascii-code ch)))
:finally (return bytes))))
(defun ascii-read-line (stream &optional (eof-error-p t) eof-value)
(loop
:with buffer = (make-array 128 :element-type (stream-element-type stream)
:adjustable t :fill-pointer 0 :initial-element 0)
:for byte = (read-byte stream nil nil)
:while (and byte (/= 10 byte))
:do (vector-push-extend byte buffer (array-dimension buffer 0))
:finally (cond
(byte (when (and (plusp (fill-pointer buffer))
(= 13 (aref buffer (1- (fill-pointer buffer)))))
(decf (fill-pointer buffer)))
(return (ascii-decode buffer)))
(eof-error-p
(error 'end-of-file :stream stream))
(t (return eof-value)))))
(defun ascii-format (stream control-string &rest arguments)
(write-sequence (ascii-encode (apply (function format)
nil control-string arguments))
stream))
(defun byte-read-line (stream &optional (eof-error-p t) eof-value)
(loop
:with buffer = (make-array 128 :element-type (stream-element-type stream)
:adjustable t :fill-pointer 0 :initial-element 0)
:for byte = (read-byte stream nil nil)
:while (and byte (/= 10 byte))
:do (vector-push-extend byte buffer (array-dimension buffer 0))
:finally (cond
(byte
(when (and (plusp (fill-pointer buffer))
(= 13 (aref buffer (1- (fill-pointer buffer)))))
(decf (fill-pointer buffer)))
(return buffer))
(eof-error-p
(error 'end-of-file :stream stream))
(t
(return eof-value)))))
(defun byte-write-line (line stream)
(write-sequence line stream)
(write-byte 10 stream))
(defstruct message headers body)
(defun clean-tabs (line)
(and line (substitute 32 9 line)))
(defun news-read-message (stream &optional (eof-error-p t) eof-value)
"
DO: Read a news message from the stream.
Messages don't begin with a '^From ' line, but end with a single
dot on a line.
The numberof body lines is taken from the Lines: header, otherwise
the body stops at the first line containing a single dot.
(true single dot lines in the body are not escaped).
RETURN: If the stream is at end-of-file, then raise an END-OF-FILE condition
if EOF-ERROR-P is true, or return the EOF-VALUE, otherwise return a
MESSAGE object filled with the headers and body read.
"
(flet ((parse-header (cline)
(or (ignore-errors
(let* ((aline (ascii-decode cline))
(colon (position #\: aline)))
(unless colon
(error "Invalid header line ~S, missing a colon."
aline))
(let* ((key (string-right-trim ; there's no space on
" " (subseq aline 0 colon))) ; the left.
(value (subseq aline (1+ colon))))
(list (intern (string-upcase key) "KEYWORD")
(string-trim " " value) cline))))
(let ((colon (position (ascii-code #\:) cline)))
(unless colon
(error "Invalid header line ~S, missing a colon."
cline))
(let* ((key (subseq cline 0 colon))
(akey (string-right-trim ; there's no space on
" " (ascii-decode key))) ; the left.
(value (subseq cline (1+ colon))))
(list (intern (string-upcase akey) "KEYWORD")
value cline))))))
(let* ((headers
(loop
:with headers = '()
:with cline = ""
:for line = (clean-tabs (byte-read-line stream nil nil))
:while (and line (not (equalp line #())))
:do (cond
((= (aref line 0) 32)
(setf cline (concatenate 'vector cline #(10) line)))
((zerop (length cline))
(setf cline line))
(t
(push (parse-header cline) headers)
(setf cline line)))
:finally (if (and (null line)
(null headers)
(zerop (length cline)))
(if eof-error-p
(error 'end-of-file :stream stream)
(return-from news-read-message eof-value))
(progn (unless (zerop (length cline))
(push (parse-header cline) headers))
(return (nreverse headers))))))
(lines (assoc :lines headers))
(lines (when lines (parse-integer (second lines))))
(body
(loop
:repeat (or lines 0)
:collect (byte-read-line stream nil nil) :into body
:finally (return
(nconc
body
(loop
:for line = (byte-read-line stream nil nil)
:while (and line
(not (equalp line
#.(ascii-encode "."))))
:collect line))))))
(make-message :headers headers :body body))))
(defun mbox-write-message (stream message)
"
DO: Write to the STREAM a mbox message: a first '^From ' line, followed
by the header and the body of the message. If any line of the body
starts with 'From ' or is a single dot, it's escaped with #\>.
RETURN: MESSAGE
"
(multiple-value-bind (se mi ho da mo ye dw)
(decode-universal-time (get-universal-time)) ; TODO: get it from the Date: header.
(let ((from (format nil "~%From ~A ~3A ~3A ~2D ~2D:~2,'0D:~2,'0D ~4,'0D~%"
"[email protected]" ; TODO get it from the From: header.
(aref #("Mon" "Tue" "Wed" "Thi" "Fri" "Sat" "Sun") dw)
(aref #("" "Jan" "Feb" "Mar" "Apr" "May" "Jun"
"Jul" "Aug" "Sep" "Oct" "Nov" "Dec") mo)
da ho mi se ye)))
(write-sequence (ascii-encode from) stream)
(dolist (h (message-headers message))
(write-sequence (third h) stream)
(write-sequence #(10) stream))
(write-sequence #(10) stream)
(dolist (l (message-body message))
(write-sequence l stream)
(write-sequence #(10) stream))
message)))
(defun parse-arguments (arguments)
"
RETURN: A JOB structure filled with the data given as ARGUMMENTS.
"
(loop
;; :with job = (make-job)
:for (k) :on arguments :by (function cddr)
:do (scase k
(("-h") (error "Invalid option ~A" k))
;; (("-t") (setf (job-file job) v))
;; (("-s") (setf (job-server job) v))
;; (("-P") (setf (job-port job) (parse-integer v)))
;; (("-u") (setf (job-user job) v))
;; (("-p") (setf (job-password job) v))
(otherwise (error "Invalid option ~A" k)))
:finally (return nil #| job |#)))
(defun news-to-mbox (news mbox)
(loop
:for m = (news-read-message news nil nil)
:while m
:do (progn
(ignore-errors
(princ (ascii-decode (third (assoc :from (message-headers m)))))
(terpri))
(ignore-errors
(princ (ascii-decode (third (assoc :subject (message-headers m)))))
(terpri))
(ignore-errors
(princ (ascii-decode (third (assoc :date (message-headers m)))))
(terpri))
(terpri))
:do (mbox-write-message mbox m)))
;; (let ((mbox-path "/home/pjb/cll-20070927T162100.mbox")
;; (news-path "/home/pjb/test.news")
;; (news-path "/home/pjb/cll-20070927T162100")
;; )
;; (with-open-file (mbox mbox-path
;; :element-type '(unsigned-byte 8)
;; :direction :output
;; :if-does-not-exist :create
;; :if-exists :supersede)
;; (with-open-file (news news-path
;; :element-type '(unsigned-byte 8))
;; #- (and)
;; (news-read-message news)
(defun main (arguments)
(declare (ignore arguments))
#+clisp
(setf (stream-element-type *standard-input*) '(unsigned-byte 8)
(stream-element-type *standard-output*) '(unsigned-byte 8))
(news-to-mbox *standard-input* *standard-output*)
ex-ok)
;;;; THE END ;;;;
| 12,456 | Common Lisp | .lisp | 278 | 33.460432 | 104 | 0.511563 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 7336eb12f46263750aef3f863ed3a0874ee28069fd5d9dc697d1043b99937b92 | 12,327 | [
-1
] |
12,328 | check-surface.lisp | informatimago_commands/sources/commands/check-surface.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: check-surface
;;;;LANGUAGE: common lisp (clisp)
;;;;SYSTEM: UNIX
;;;;USER-INTERFACE: UNIX
;;;;DESCRIPTION
;;;;
;;;; This script tests a block device, block by block, creating a map
;;;; of bad sectors.
;;;;
;;;;USAGE
;;;; check-surface /dev/sda
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2007-09-18 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; Copyright Pascal J. Bourguignon 2007 - 2007
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This script 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 library; see the file COPYING.LIB.
;;;; If not, write to the Free Software Foundation,
;;;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;;****************************************************************************
(in-package "SCRIPT")
(command :use-systems (:com.informatimago.clmisc)
:use-packages ("COMMON-LISP"
"SCRIPT"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.CLMISC.RESOURCE-UTILIZATION"))
(defun usage ()
(format
t (concatenate
'string
"~%"
"~a usage:~%"
"~%"
" ~:*~a [options...] BLOCK_DEVICE ~%"
"~%"
"Options:~%"
" -h|--help Prints this usage documentation.~%"
" --block-size=SIZE |~%"
" -b SIZE Indicate a block size. By default, stat -c %o is used.~%"
" --start=POSITION |~%"
" -s POSITION Indicate the start block number. By default: 0.~%"
" --end=POSITION |~%"
" -e POSITION Indicate the end block number. By default: NIL (end of device).~%"
"~%"
"Tries to read all the blocks of the device, then if no error is encountered,~%"
"tries to write all the blocks of the device, then if no error is encountered,~%"
"tries to read the written blocks, and reports a list of bad blocks.~%"
"~%"
"Output bad block list is given in block units.~%"
"~%")
*program-name*))
(defun report-error (message &optional print-usage-p (status nil statusp))
(format *error-output*
"~%~a: ~A~:[~; Aborting.~]~%"
*program-name* message (and statusp (not (zerop status))))
(when print-usage-p
(usage))
(when statusp
#+testing (throw 'exit status)
#-testing (exit status)))
(defun geometry (device)
"
RETURN: number of sectors per disk;
number of cylinders per disk;
number of tracks per cylinder;
number of sector per track;
start sector.
"
(with-input-from-string (inp (uiop:run-program
(list "hdparm" "-g"
(etypecase device
(string device)
(pathname (namestring device))))
:output :string :wait nil))
(let ((*read-eval* nil)
(*read-base* 10.))
(loop
:with cylinders = nil
:with heads = nil
:with sectors = nil
:with total-sectors = nil
:with start = nil
:for line = (read-line inp nil nil)
:while line
:until (eq 'geometry (ignore-errors (read-from-string line)))
:finally (let ((pos (position #\= line)))
(unless pos
(error "unexpected format for hdparm -g output: ~S" line))
(incf pos)
(multiple-value-setq (cylinders pos)
(parse-integer line :start pos :junk-allowed t))
(incf pos)
(multiple-value-setq (heads pos)
(parse-integer line :start pos :junk-allowed t))
(incf pos)
(multiple-value-setq (sectors pos)
(parse-integer line :start pos :junk-allowed t))
(setf pos (position #\= line :start pos))
(unless pos
(error "unexpected format for hdparm -g output: ~S" line))
(incf pos)
(multiple-value-setq (total-sectors pos)
(parse-integer line :start pos :junk-allowed t))
(incf pos)
(setf pos (position #\= line :start pos))
(unless pos
(error "unexpected format for hdparm -g output: ~S" line))
(incf pos)
(multiple-value-setq (start pos)
(parse-integer line :start pos :junk-allowed t))
(return-from geometry
(values total-sectors
cylinders heads sectors start)))))))
(defun block-size (device)
(with-input-from-string (inp (uiop:run-program
(list "stat" "-c" "%o"
(etypecase device
(string device)
(pathname (namestring device))))
:output :string :wait nil))
(let ((*read-eval* nil)
(*read-base* 10.))
(or (read inp nil nil)
(report-error "Cannot get the block-size from stat(1)."
nil ex-unavailable)))))
(defun parse-block-size (string)
;; (print string)
(multiple-value-bind (block-size end)
(parse-integer string :junk-allowed t :radix 10.)
(* block-size
(if (<= (1+ end) (length string))
(let ((factor (position (aref string end) " KMGTPEZY"
:test (function char-equal))))
(if factor
(expt 1024 factor)
(error "Invalid block factor: ~A" (subseq string end))))
1))))
(progn
(assert (= 42 (parse-block-size "42")))
(assert (= 42 (parse-block-size "42 ")))
(assert (= 42 (parse-block-size "42 *")))
(assert (= (* 42 1024) (parse-block-size "42k")))
(assert (= (* 42 1024) (parse-block-size "42k*")))
(assert (= (* 42 1024 1024) (parse-block-size "42M")))
(assert (= (* 42 1024 1024) (parse-block-size "42M*"))))
(defparameter *element-type* '(unsigned-byte 8))
(defparameter *external-format* :default)
(defun test!read-all (device buffer
fpos-generator block-checker
reporter)
"
DEVICE: A STREAM, open on the device to be checked.
BUFFER: A vector used as a block buffer.
FPOS-GENERATOR: A (FUNCTION ((OR NULL INTEGER)) (OR NULL INTEGER))
returning a sequence of file position. The first time,
it's called as (fpos-generator nil), and then it's
called as (fpos-generator previous-fpos), until it
returns NIL. The whole sequence can then be repeated.
BLOCK-CHECKER: A (FUNCTION (INTEGER INTEGER SEQUENCE) (or null string))
called to check that the buffer read back is the
same as the buffer that was written at the given
file position. The second argument is the result of
READ-SEQUENCE: END-OF-FILE => 0, <block-size => error.
Note: some file positions can be skipped (BLOCK-CHECKER
not called) if no block could be read from there.
The result is passed to the reporter.
REPORTER: A (FUNCTION (INTEGER (OR NULL STRING)))
called to report on the success of the block
at the given file position. The second argument is
NIL when the block is valid, and contains an error
message when the block failled.
RESULTS: The number of failed blocks;
the number of valid blocks;
the total number of blocks;
the number of seek failed;
the number of read failed.
"
(let ((valid-blocks 0)
(failed-reads 0)
(failed-seeks 0)
(total-number-of-blocks 0))
;; read all:
(loop
:for i :from 0
:for fpos = (funcall fpos-generator i)
:while fpos
:do (incf total-number-of-blocks)
:do (multiple-value-bind (success error)
(ignore-errors (file-position device fpos))
;; (print `(file-position ,fpos -> ,success ,error))
(if success
(multiple-value-bind (size-read error)
(ignore-errors (read-sequence buffer device))
;; (print `(read-sequence -> ,size-read ,error))
(if error
(progn
(incf failed-reads)
(funcall reporter fpos
(format nil
"READ-SEQUENCE failed~:[~;~:*~%~A~]"
error)))
(progn
(incf valid-blocks)
(funcall reporter fpos
(funcall block-checker
fpos size-read buffer)))))
(progn
(incf failed-seeks)
(funcall reporter fpos
(format nil "FILE-POSITION failed~:[~;~:*~%~A~]"
error))))))
(values (- total-number-of-blocks valid-blocks)
valid-blocks
total-number-of-blocks
failed-seeks
failed-reads)))
(defun test!write-all/read-all (device buffer
fpos-generator block-generator block-checker
write-reporter read-reporter
&optional (phase :both))
"
DEVICE: A STREAM, open on the device to be checked.
BUFFER: A vector used as a block buffer.
FPOS-GENERATOR: A (FUNCTION ((OR NULL INTEGER)) (OR NULL INTEGER))
returning a sequence of file position. The first time,
it's called as (fpos-generator nil), and then it's
called as (fpos-generator previous-fpos), until it
returns NIL. The whole sequence can then be repeated.
BLOCK-GENERATOR: A (FUNCTION (INTEGER SEQUENCE))
called to fill the buffer to be writen at the
given file position. The result is ignored.
Note: some file positions can be skipped if
the file position cannot be reached on the device.
BLOCK-CHECKER: A (FUNCTION (INTEGER INTEGER SEQUENCE) (or null string))
called to check that the buffer read back is the
same as the buffer that was written at the given
file position. The second argument is the result of
READ-SEQUENCE: END-OF-FILE => 0, <block-size => error.
Note: some file positions can be skipped (BLOCK-CHECKER
not called) if no block could be read from there.
The result is passed to the reporter.
REPORTER: A (FUNCTION (INTEGER (OR NULL STRING)))
called to report on the success of the block
at the given file position. The second argument is
NIL when the block is valid, and contains an error
message when the block failled.
RESULTS: The number of failed blocks;
the number of valid blocks;
the total number of blocks;
the number of seek failed;
the number of read failed;
the number of write failed.
"
(let ((failed-seeks 0)
(failed-writes 0)
(read/failed-blocks 0)
(read/valid-blocks 0)
(read/total-number-of-blocks 0)
(read/failed-seeks 0)
(read/failed-reads 0))
(declare (ignorable read/failed-blocks))
(when (member phase '(:both :write))
;; write all:
(loop
:for i :from 0
:for fpos = (funcall fpos-generator i)
:while fpos
:do (multiple-value-bind (success error)
(ignore-errors (file-position device fpos))
(if success
(progn
(funcall block-generator fpos buffer)
(multiple-value-bind (result error)
(ignore-errors (write-sequence buffer device))
(declare (ignore result))
(if error
(progn
(incf failed-writes)
(funcall write-reporter fpos
(format nil
"WRITE-SEQUENCE failed~:[~;~:*~%~A~]"
error)))
(funcall write-reporter fpos nil))))
(progn
(incf failed-seeks)
(funcall write-reporter fpos
(format nil "FILE-POSITION failed~:[~;~:*~%~A~]"
error)))))))
(when (member phase '(:both :read))
(multiple-value-setq (read/failed-blocks
read/valid-blocks
read/total-number-of-blocks
read/failed-seeks
read/failed-reads)
(test!read-all device buffer fpos-generator block-checker read-reporter)))
(values (- read/total-number-of-blocks read/valid-blocks)
read/valid-blocks
read/total-number-of-blocks
(+ read/failed-seeks failed-seeks)
read/failed-reads
failed-writes)))
(defun make-fpos-generator/sequential (block-size start end)
(if end
(let ((endi (- end start)))
(lambda (i)
(when (< i endi)
(* (+ start i) block-size))))
(lambda (i)
(* (+ start i) block-size))))
(defun zeros (length)
(make-array length
:element-type '(unsigned-byte 32)
:initial-element 0))
(defun iota (vector)
(dotimes (i (length vector) vector)
(setf (aref vector i) i)))
(defun random-permutation (vector)
(dotimes (i (- (length vector) 2) vector)
(rotatef (aref vector i)
(aref vector (+ i (random (- (length vector) i)))))))
(defun make-fpos-generator/random (block-size start end)
(let* ((endi (- end start))
(p (let ((indices (random-permutation (iota (zeros endi)))))
(map-into indices (lambda (x) (* (+ start x) block-size)) indices))))
(lambda (i)
(when (< i endi)
(aref p i)))))
(defun make-reporter (block-size start end
my-failure bad good add-to-bad-block-list)
(let ((ubad (string-upcase bad))
(dbad (string-downcase bad)))
(lambda (fpos failure)
(let ((block-no (- (truncate fpos block-size) start)))
(when (zerop (mod (+ start block-no) (* 64 16)))
(format t "~%[~D -> ~D -> ~D[ ; ~D/~D = ~2$ %"
start (+ start block-no) end
block-no (- end start) (* 100 (/ block-no (- end start)))))
(if failure
(progn
(funcall add-to-bad-block-list block-no)
(when (zerop (mod (+ start block-no) 64))
(format t "~%~8D: " (+ start block-no)))
(if (eq failure my-failure)
(princ dbad)
(princ ubad)))
(progn
(when (zerop (mod (+ start block-no) 64))
(format t "~%~8D: " (+ start block-no)))
(princ good)))))))
(defun test$read-all$?access (device-path block-size buffer
access-constructor
&key (start 0) (end nil))
(with-open-file (device device-path
:direction :io
:element-type *element-type*
:external-format *external-format*
:if-does-not-exist :error)
(let ((bad-blocks '())
(my-failure (copy-seq "Block could not be read entirely.")))
(test!read-all
device buffer
(funcall access-constructor block-size start end)
(lambda (fpos size-read buffer) ; BLOCK-CHECKER
(declare (ignore fpos buffer))
(when (< size-read block-size)
my-failure))
(make-reporter block-size start end my-failure "r" "." ; READ-REPORTER
(lambda (block-no) (push block-no bad-blocks)))))))
(defun test$read-all$sequential (device-path block-size buffer
&key (start 0) (end nil))
(test$read-all$?access device-path block-size buffer
(function make-fpos-generator/sequential)
:start start :end end))
(defun test$read-all$random (device-path block-size buffer
&key (start 0) (end nil))
(test$read-all$?access device-path block-size buffer
(function make-fpos-generator/random)
:start start :end end))
(defun test$write-all/read-all$sequential (device-path block-size buffer
&key (start 0) (end nil)
(phase :both))
(with-open-file (device device-path
:direction :io
:element-type *element-type*
:external-format *external-format*
:if-does-not-exist :error)
(let ((bad-blocks '())
(my-failure (copy-seq "Block could not be read entirely.")))
(test!write-all/read-all
device buffer
(make-fpos-generator/sequential block-size start end)
(lambda (fpos buffer) ; BLOCK-GENERATOR
(loop
:for i :from 0 :below block-size
:do (setf (aref buffer i) (mod (+ i fpos) 256)))
(replace buffer
(map 'vector (function char-code)
(format nil "*** BLOCK AT POSITION: ~8,'0X ***" fpos))
:start1 128)
buffer)
(lambda (fpos size-read buffer) ; BLOCK-CHECKER
(block checker
(unless (= size-read block-size)
(return-from checker "Buffer not read back completely."))
(let ((pattern
(map 'vector (function char-code)
(format nil "*** BLOCK AT POSITION: ~8,'0X ***" fpos))))
(unless (equalp (subseq buffer 128 (+ 128 (length pattern)))
pattern)
(return-from checker
(format nil "Identifying pattern not present in block at ~D"
fpos)))
(loop
:for i :from 128 :below (+ 128 (length pattern))
:do (setf (aref buffer i) (mod (+ i fpos) 256))))
(unless (loop
:for i :from 0 :below (length buffer)
:always (= (aref buffer i) (mod (+ i fpos) 256)))
(return-from checker
(format nil "Pattern doesn't match for block at ~D" fpos)))))
(make-reporter block-size start end my-failure "w" "."
(lambda (block-no) (push block-no bad-blocks)))
(make-reporter block-size start end my-failure "r" "."
(lambda (block-no) (push block-no bad-blocks)))
phase))))
(defun check-surface (device block-size start end phase)
(let ((buffer (make-array block-size :element-type *element-type*
:initial-element 0))
(end (or end (truncate (* 512 (geometry device)) block-size))))
(print
(multiple-value-list
#-(and)
(test$read-all$sequential device block-size buffer
:start (- end 512) :end (1+ end))
#-(and)
(test$read-all$sequential device block-size buffer :start 0 :end 1024)
#-(and)
(test$read-all$random device block-size buffer :start 0 :end 1024)
(test$write-all/read-all$sequential device block-size buffer
:start start :end end
:phase phase)))))
(defun main (arguments)
(reporting-sru
(:job-origin
(format nil "~A@~A"
(or (uiop:getenv "USER")
(first (last (pathname-directory
(user-homedir-pathname)))))
(short-site-name))
:stream *standard-output*)
(catch 'exit
(let ((files '())
(block-size nil)
(device nil)
(start 0)
(end nil)
(phase :both))
(loop
:with args = arguments
:for arg = (car args)
:while args
:do (cond ((or (string= "-h" arg) (string= "--help" arg))
(usage)
(throw 'exit ex-ok))
((string= arg "-b")
(setf block-size (parse-block-size (cadr args)))
(pop args) (pop args))
((string= arg #1="--block-size=")
(setf block-size (parse-block-size (subseq arg (length #1#))))
(pop args))
((string= arg "-s")
(setf start (parse-block-size (cadr args)))
(pop args) (pop args))
((string= arg #2="--start=")
(setf start (parse-block-size (subseq arg (length #2#))))
(pop args))
((string= arg "-e")
(setf end (parse-block-size (cadr args)))
(pop args) (pop args))
((string= arg #3="--end=")
(setf end (parse-block-size (subseq arg (length #3#))))
(pop args))
((string= arg "--only-write")
(setf phase :read)
(pop args))
((string= arg "--check")
(setf phase :write)
(pop args))
((string= arg "--read")
(error "not implemented yet")
(pop args))
(t
(push arg files)
(pop args))))
(unless files
(report-error "Nothing to do. Please specify -h or --help." t ex-usage))
(case (length files)
((0)
(report-error "No device to work on." t ex-usage))
((1)
(setf device (pop files))
(setf block-size (or block-size (block-size device)))
(check-surface device block-size start end phase))
(otherwise
(report-error "Too many device arguments given, only one expected."
t ex-usage)))))))
(defun m () (main '("-e" ".")))
;;;; THE END ;;;;;
| 23,961 | Common Lisp | .lisp | 524 | 31.700382 | 88 | 0.500406 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 43d93ec62d637b45a502078ac49b78ec72f637292626a1ebeb4c2ba8e97e831f | 12,328 | [
-1
] |
12,329 | edit-comments-of-ogg.lisp | informatimago_commands/sources/commands/edit-comments-of-ogg.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;*****************************************************************************
;;;;FILE: edit-comments-of-ogg.lisp
;;;;LANGUAGE: common lisp (clisp)
;;;;SYSTEM: UNIX
;;;;USER-INTERFACE: UNIX
;;;;DESCRIPTION
;;;; This script helps editing ogg vorbis comments of a set of ogg files.
;;;; Once comments are edited in separate .inf files, they're written
;;;; to the ogg files with vorbiscomment.
;;;;USAGE
;;;; edit-comments-of-ogg --help
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2002-04-04 <PJB> Created.
;;;; 2002-04-14 <PJB> Fine tuned some variable references to handle spaces
;;;; in directory and file names.
;;;; 2002-09-20 <PJB> Added l)ast command.
;;;;BUGS
;;;;LEGAL
;;;; Copyright Pascal J. Bourguignon 2002 - 2002
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This script 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 library; see the file COPYING.LIB.
;;;; If not, write to the Free Software Foundation,
;;;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;;*****************************************************************************
(defparameter *program-version* "1.0.2")
(defun stream-to-string-list (stream)
(loop
:with line := (read-line stream nil nil)
:while line
:collect line :into result
:do (setf line (read-line stream nil nil))
:finally (return result)))
(defun copy-stream (src-stream dst-stream)
(loop
:with line := (read-line src-stream nil nil)
:while line
:do (write-line line dst-stream)))
(defun string-replace (string regexp replace &optional fixedcase literal)
"
RETURN: a string build from `string' where all matching `regexp'
are replaced by the `replace' string.
NOTE: Current implementat accepts only literal pattern as `regexp';
`fixedcase' and `literal' are ignored.
"
(declare (ignore fixedcase literal))
(loop
:with regexp-length := (length regexp)
:with result := ""
:with previous := 0
:with position := (search regexp string)
:while position
:do (setf result (concatenate 'string
result (subseq string previous position) replace)
previous (+ position regexp-length)
position (search regexp string :start2 previous))
:finally (setf result (concatenate 'string
result
(subseq string previous (length string))))
(return result)))
(defun split-string (string &optional separators)
"
NOTE: current implementation only accepts as separators
a string containing only one character.
"
(let ((sep (aref separators 0))
(chunks '())
(position 0)
(nextpos 0)
(strlen (length string)))
(loop while (< position strlen)
do
(loop while (and (< nextpos strlen)
(char/= sep (aref string nextpos)))
do (setf nextpos (1+ nextpos))
);;loop
(push (subseq string position nextpos) chunks)
(setf position (1+ nextpos))
(setf nextpos position))
(nreverse chunks)))
(defun split-name-value (string)
"
RETURN: a cons with two substrings of string such as:
(string= (concat (car res) \"=\" (cdr res)) string)
and (length (car res)) is minimum.
"
(let ((position 0)
(strlen (length string))
)
(loop while (and (< position strlen)
(char/= (character "=") (aref string position)))
do (setf position (1+ position)))
(if (< position strlen)
(cons (subseq string 0 position) (subseq string (1+ position) strlen))
nil)))
(defparameter comext ".inf")
(defparameter fields '(artist album title version tracknumber organization genre
description date location copyright)) ;;FIELDS
(defvar fields-names (mapcar 'symbol-name fields))
(defun usage ()
(format
t (concatenate
'string
"~%"
"~a~:* usage:~%"
"~%"
" ~a [-h|--help|-e|--edit|-w|--write]... DIR_OR_OGG_FILE... ~%"
"~%"
" -e edits the attribute files of the .ogg found in DIRECTORY.~%"
" -w writes the attributes data to the .ogg files. (unfortunately ~%"
" this means copying the .ogg file to a new version ~%"
" per vorbis-comment).~%"
"~%")
*program-name*))
(defvar artist "")
(defvar album "")
(defvar title "")
(defvar version "")
(defvar tracknumber "")
(defvar organization "")
(defvar genre "")
(defvar description "")
(defvar date "")
(defvar location "")
(defvar copyright "")
(defvar last-artist "")
(defvar last-album "")
(defvar last-title "")
(defvar last-version "")
(defvar last-tracknumber "")
(defvar last-organization "")
(defvar last-genre "")
(defvar last-description "")
(defvar last-date "")
(defvar last-location "")
(defvar last-copyright "")
(defun display (index max file)
(format t
(concatenate
'string
"~Cc~%"
" INDEX = ~a/~a~%"
" FILE = ~a~%"
""
"1) ARTIST = ~a~%"
"2) ALBUM = ~a~%"
"3) TITLE = ~a~%"
"4) VERSION = ~a~%"
"5) TRACKNUMBER = ~a~%"
"6) ORGANIZATION = ~a~%"
"7) GENRE = ~a~%"
"8) DESCRIPTION = ~a~%"
"9) DATE = ~a~%"
"a) LOCATION = ~a~%"
"b) COPYRIGHT = ~a~%"
)
(code-char 27)
index max
file artist album title version tracknumber organization genre
description date location copyright))
(defun info-load (txt)
(if (probe-file txt)
(dolist (line (with-open-file (stream txt :direction :input)
(stream-to-string-list stream)))
(let* ((nv (split-name-value line))
(name (car nv))
(value (cdr nv)))
(when (member name fields-names :test 'string=)
(set (intern name) value))
))
;;else there's no existing .inf file.
(setf artist ""
album ""
title ""
version ""
tracknumber ""
organization ""
genre ""
description ""
date ""
location ""
copyright "")))
(defun info-save (txt)
(with-open-file (out txt :direction :output :if-exists :supersede)
(format out
(concatenate
'string
"ARTIST=~a~%"
"ALBUM=~a~%"
"TITLE=~a~%"
"VERSION=~a~%"
"TRACKNUMBER=~a~%"
"ORGANIZATION=~a~%"
"GENRE=~a~%"
"DESCRIPTION=~a~%"
"DATE=~a~%"
"LOCATION=~a~%"
"COPYRIGHT=~a~%")
artist album title version tracknumber organization genre
description date location copyright))
(setf last-artist artist)
(setf last-album album)
(setf last-title title)
(setf last-version version)
(setf last-tracknumber tracknumber)
(setf last-organization organization)
(setf last-genre genre)
(setf last-description description)
(setf last-date date)
(setf last-location location)
(setf last-copyright copyright))
(defun title (file)
(nsubstitute-if
#\space
(lambda (ch) (or (char= ch #\_) (char= ch #\-)))
(if (string= ".ogg" (subseq file (- (length file) 4) (length file)))
(subseq file 0 (- (length file) 4))
(copy-seq file))))
(defun edit (files)
(let ((index 0)
(state 'editing)
(flist (sort
(stream-to-string-list
(uiop:run-program
(cons "/usr/bin/find" (append files '("-name" "*.ogg" "-print")))
:input nil
:output :stream
:wait nil))
'string<)))
(when (= 0 (length flist))
(format *error-output*
"~a: I could not find any .ogg file in ~a.~%" *program-name* files)
(exit ex-dataerr))
(loop until (eq state 'done) do
(let* ((fogg (nth index flist))
(fcom (string-replace fogg ".ogg" comext)))
(info-load fcom)
(setf state 'editing)
(loop while (eq state 'editing) do
(display index (length flist) fogg)
(format t "~%")
(when (< index (1- (length flist)))
(format t "n)ext, "))
(when (< 0 index)
(format t "p)revious, "))
(format t (concatenate
'string
"q)quit, copy from l)ast, S)earch, "
"s)et all, ~%"
"or: digit) set one field. ? "
))
(let ((cmd (let ((line (read-line nil "q")))
(if (< 0 (length line)) (aref line 0) 0))))
(cond
((eq (character '\n) cmd)
(info-save fcom)
(when (< index (1- (length flist)))
(setf index (1+ index)))
(setf state 'next))
((eq (character '\p) cmd)
(info-save fcom)
(when (< 0 index)
(setf index (1- index)))
(setf state 'next))
((eq (character '\q) cmd)
(info-save fcom)
(setf state 'done))
((eq (character '\l) cmd)
(setf
artist last-artist
album last-album
title last-title
version last-version
tracknumber last-tracknumber
organization last-organization
genre last-genre
description last-description
date last-date
location last-location
copyright last-copyright))
((eq (character '\S) cmd)
(info-save fcom)
(format t "Search for: ")
(let ((pattern (read-line)))
(setf index
(loop
for sindex = (mod (+ 1 index) (length flist))
then (mod (+ 1 sindex) (length flist))
for fogg = (nth sindex flist)
for fcom = (string-replace fogg ".ogg" comext)
while (/= sindex index)
until (search pattern
(concatenate 'string
fogg "**"
artist "**"
album "**"
title "**"
version "**"
tracknumber "**"
organization "**"
genre "**"
description "**"
date "**"
location "**"
copyright "**"))
do (info-load fcom)
finally (return sindex)))
);;let
(setf state 'next)
)
((eq (character '\s) cmd)
(mapc (lambda (sym)
(format t "~a=" sym)
(set sym (read-line)))
fields)
)
((eq (character '\1) cmd)
(format t "~a=" 'artist)
(setf artist (read-line)))
((eq (character '\2) cmd)
(format t "~a=" 'album)
(setf album (read-line)))
((eq (character '\3) cmd)
(format t "~a=" 'title)
(setf title (read-line)))
((eq (character '\4) cmd)
(format t "~a=" 'version)
(setf version (read-line)))
((eq (character '\5) cmd)
(format t "~a=" 'tracknumber)
(setf tracknumber (read-line)))
((eq (character '\6) cmd)
(format t "~a=" 'organization)
(setf organization (read-line)))
((eq (character '\7) cmd)
(format t "~a=" 'genre)
(setf genre (read-line)))
((eq (character '\8) cmd)
(format t "~a=" 'description)
(setf description (read-line)))
((eq (character '\9) cmd)
(format t "~a=" 'date)
(setf date (read-line)))
((eq (character '\a) cmd)
(format t "~a=" 'location)
(setf location (read-line)))
((eq (character '\b) cmd)
(format t "~a=" 'copyright)
(setf copyright (read-line)))
)))))))
(defun commit-comments (files)
(dolist (fogg (stream-to-string-list
(uiop:run-program
(cons "/usr/bin/find" (append files '("-name" "*.ogg" "-print")))
:input nil
:output :stream
:wait nil)))
(let ((fcom (string-replace fogg ".ogg" comext)))
(if (probe-file fcom)
(progn
(format t "~a: Writting comments to '~a'...~%" *program-name* fogg)
(write-string (uiop:run-program
(list "/usr/local/bin/vorbiscomment" "-w" fogg "-c" fcom)
:input nil
:output :string
:wait nil)
*standard-output*))
(format t "~a: Missing '~a'.~%" *program-name* fcom)))))
(defun main (arguments)
(let ((files '())
(do_edit nil)
(do_write nil))
(dolist (arg arguments)
(cond
((or (string= "-h" arg) (string= "--help" arg))
(usage)
(exit ex-ok))
((or (string= "-e" arg) (string= "--edit" arg))
(setf do_edit t))
((or (string= "-w" arg) (string= "--write" arg))
(setf do_write t))
((string= (aref arg 0) (character '\-))
(format *error-output* "~a: invalid argument '~a'.~%" *program-name* arg)
(usage)
(exit ex-usage))
(t
(push arg files))))
(when (and (not do_edit) (not do_write))
(format *error-output* "~a: Nothing to do. Please specify -e or -w. Aborting.~%" *program-name*)
(usage)
(exit ex-usage))
(when (= 0 (length files))
(format *error-output* "~a: No directory, no file to work on. Aborting.~%" *program-name*)
(usage)
(exit ex-usage))
(when do_edit
(edit files))
(when do_write
(commit-comments files)))
ex-ok)
(defun m () (main '("-e" ".")))
;;;; THE END ;;;;
| 16,722 | Common Lisp | .lisp | 415 | 27.424096 | 102 | 0.455257 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 8ae8dec0ae65b4796f856d45f82e86121459428fb34675f69d407c9e44727cc0 | 12,329 | [
-1
] |
12,330 | dedup.lisp | informatimago_commands/sources/commands/dedup.lisp | ;; -*- mode:lisp;coding:utf-8 -*-
(in-package "SCRIPT")
(command :use-systems (:com.informatimago.common-lisp.cesarum)
:use-packages ("COMMON-LISP"
"SCRIPT"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY")
:main "COM.INFORMATIMAGO.COMMAND.DEDUP:MAIN")
(defun main (arguments)
(declare (ignore arguments))
(let* ((lines (stream-to-string-list *standard-input*))
(table (make-hash-table :test 'equal)))
(loop :for (k v)
:in (mapcar (lambda (line)
(let ((p (search " " line)))
(list (subseq line 0 p)
(subseq line (+ 2 p)))))
lines)
:do (push v (gethash k table '())))
(maphash (lambda (k vs)
(unless (cdr vs)
(remhash k table)))
table)
(maphash (lambda (k vs)
(declare (ignore k))
(mapc 'delete-file (cdr vs)))
table))
ex-ok)
;;;; THE END ;;;;
| 1,116 | Common Lisp | .lisp | 29 | 26.241379 | 72 | 0.493075 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 3330e31e411c1b77119f65311c7016fc81587c2ced81053ff10516659dfee469 | 12,330 | [
-1
] |
12,331 | nls.lisp | informatimago_commands/sources/commands/nls.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(defun 1+/if-you-can (n)
(if (numberp n) (1+ n) n))
(defun cut-index (name)
(let* ((dot (position #\. name :from-end t))
(digit (position-if (function digit-char-p) name :from-end t :end dot)))
(subseq name 0
(1+/if-you-can (position-if-not
(function digit-char-p) name
:from-end t :end digit)))))
(defun nls ()
(with-input-from-string (files (uiop:run-program '("/bin/ls" "-1")
:output :string
:wait nil))
(loop
:with table = (make-hash-table :test (function equal))
:for file = (read-line files nil nil)
:while file
:do (let* ((cut (cut-index file))
(ent (gethash cut table)))
(if ent
(incf (car ent))
(setf (gethash cut table) (cons 1 file))))
:finally (let ((res '()))
(maphash (lambda (k v) (push (cons k v) res)) table)
(dolist (item (sort res (function string<=) :key (function car)))
(destructuring-bind (cut num . nam) item
(format t "~A~%" (if (= 1 num) nam cut))))))))
(defun main (arguments)
(declare (ignore arguments))
(nls)
ex-ok)
| 1,353 | Common Lisp | .lisp | 32 | 29.71875 | 82 | 0.478327 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 9a873e7743cfe3dba2549f04c2c2ffee284b7f37dc2f52a39bd4d4d67797ae26 | 12,331 | [
-1
] |
12,332 | columnify.lisp | informatimago_commands/sources/commands/columnify.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: columnify
;;;;LANGUAGE: text
;;;;SYSTEM: POSIX
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Columnify the input.
;;;;
;;;; By default, columnify as much as possible given the line lengths
;;;; and the terminal width as given by the environment variable COLUMNS.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2007-04-19 <PJB>
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 2007 - 2007
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;****************************************************************************
(defvar *width* (or #+clisp (nth-value 1 (screen:with-window (screen:window-size screen:*window*)))
(and (uiop:getenv "COLUMNS") (parse-integer (uiop:getenv "COLUMNS")))
(block :found
(dolist (path (list #+clisp (format nil "/proc/~D/fd/1" (posix:process-id))
"/dev/tty")
nil)
(with-input-from-string (stty (uiop:run-program (format nil "stty -a < ~S" path)
:force-shell t
:input :terminal
:output :string
:wait nil))
(loop
:for line = (read-line stty nil nil)
:while line
:do (let* ((tag " columns ")
(pos (search tag line)))
(when pos
(return-from :found
(parse-integer line :start (+ pos (length tag))
:junk-allowed t))))))))
80))
(defun columnify (lines width)
(let* ((colwid (1+ (or (loop :for line :in lines :maximize (length line)) 0)))
(ncols (truncate width colwid)))
(if (<= ncols 1)
(loop :for line :in lines :do (princ line) (terpri))
;; columnify:
(let* ((nrows (ceiling (length lines) ncols))
(cols (make-array (list ncols nrows) :initial-element ""))
(longcols (mod (length lines) ncols))
(next-line lines))
(loop
:for col :from 0 :below ncols
:do (loop
:for row :from 0 :below (- nrows (if (< col longcols) 0 1))
:do (setf (aref cols col row) (pop next-line))))
(loop :for row :from 0 :below nrows
:do (loop
:for col :from 0 :below ncols
:do (format t "~VA" colwid (aref cols col row))
:finally (format t "~%")))))))
(defun main (arguments)
(declare (ignore arguments))
(columnify (loop
:for line = (read-line *standard-input* nil nil)
:while line :collect line)
*width*)
ex-ok)
;;;; THE END ;;;;
| 4,109 | Common Lisp | .lisp | 87 | 33.885057 | 104 | 0.465122 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 66b96121f2ce3471bd4e1160b8eea728ef95c857ded9fc17af8303047bbce8e4 | 12,332 | [
-1
] |
12,333 | cddb-to-tag.lisp | informatimago_commands/sources/commands/cddb-to-tag.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: cddb-to-tag
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Reads cddb.txt, rename .flac or .mp3 files and add tags, according
;;;; to the information found in it.
;;;;
;;;;USAGE
;;;;
;;;; cddb-to-tag flac-or-mp3-directory/ …
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2017-05-23 <PJB> Created.
;;;;BUGS
;;;; Doesn't process any option yet. We'd need --help, --dry-run, etc.
;;;; Does not read cd-info version 0.82 cddb.txt files yet (only cd-info 0.83).
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2017 - 2017
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "SCRIPT")
(command :use-systems (:uiop :split-sequence :cl-ppcre
:com.informatimago.common-lisp.cesarum)
:use-packages ("COMMON-LISP"
"SCRIPT"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE")
:main "COMMAND.CDDB-TO-TAG:MAIN")
(in-package "COMMAND.CDDB-TO-TAG")
(defparameter *dry-run* nil)
;;;
;;; Tags
;;;
(defparameter *tag-keys*
'(
;; (keyword VORBIS/FLAC-tagname mp3-id3v2-frame)
(:title "TITLE" "TIT2")
(:version "VERSION" nil)
(:album "ALBUM" "TALB")
(:tracknumber "TRACKNUMBER" "TRCK")
(:artist "ARTIST" "TCOM")
(:performer "PERFORMER" "TPE1")
(:copyright "COPYRIGHT" "TCOP")
(:license "LICENSE" nil)
(:organization "ORGANIZATION" nil)
(:description "DESCRIPTION" "COMM")
(:genre "GENRE" "genre") ;; !!!
(:date "DATE" "TDAT")
(:location "LOCATION" nil)
(:contact "CONTACT" nil)
(:isrc "ISRC" "TSRC")))
;; id3v2 frames:
;;
;; --AENC Audio encryption
;; --APIC Attached picture
;; --COMM Comments
;; --COMR Commercial frame
;; --ENCR Encryption method registration
;; --EQUA Equalization
;; --ETCO Event timing codes
;; --GEOB General encapsulated object
;; --GRID Group identification registration
;; --IPLS Involved people list
;; --LINK Linked information
;; --MCDI Music CD identifier
;; --MLLT MPEG location lookup table
;; --OWNE Ownership frame
;; --PRIV Private frame
;; --PCNT Play counter
;; --POPM Popularimeter
;; --POSS Position synchronisation frame
;; --RBUF Recommended buffer size
;; --RVAD Relative volume adjustment
;; --RVRB Reverb
;; --SYLT Synchronized lyric/text
;; --SYTC Synchronized tempo codes
;; --TALB Album/Movie/Show title
;; --TBPM BPM (beats per minute)
;; --TCOM Composer
;; --TCON Content type
;; --TCOP Copyright message
;; --TDAT Date
;; --TDLY Playlist delay
;; --TENC Encoded by
;; --TEXT Lyricist/Text writer
;; --TFLT File type
;; --TIME Time
;; --TIT1 Content group description
;; --TIT2 Title/songname/content description
;; --TIT3 Subtitle/Description refinement
;; --TKEY Initial key
;; --TLAN Language(s)
;; --TLEN Length
;; --TMED Media type
;; --TOAL Original album/movie/show title
;; --TOFN Original filename
;; --TOLY Original lyricist(s)/text writer(s)
;; --TOPE Original artist(s)/performer(s)
;; --TORY Original release year
;; --TOWN File owner/licensee
;; --TPE1 Lead performer(s)/Soloist(s)
;; --TPE2 Band/orchestra/accompaniment
;; --TPE3 Conductor/performer refinement
;; --TPE4 Interpreted, remixed, or otherwise modified by
;; --TPOS Part of a set
;; --TPUB Publisher
;; --TRCK Track number/Position in set
;; --TRDA Recording dates
;; --TRSN Internet radio station name
;; --TRSO Internet radio station owner
;; --TSIZ Size
;; --TSRC ISRC (international standard recording code)
;; --TSSE Software/Hardware and settings used for encoding
;; --TXXX User defined text information
;; --TYER Year
;; --UFID Unique file identifier
;; --USER Terms of use
;; --USLT Unsynchronized lyric/text transcription
;; --WCOM Commercial information
;; --WCOP Copyright/Legal infromation
;; --WOAF Official audio file webpage
;; --WOAR Official artist/performer webpage
;; --WOAS Official audio source webpage
;; --WORS Official internet radio station homepage
;; --WPAY Payment
;; --WPUB Official publisher webpage
;; --WXXX User defined URL link
;; TITLE
;;
;; Track/Work name
;;
;; VERSION
;;
;; The version field may be used to differentiate multiple versions
;; of the same track title in a single collection. (e.g. remix info)
;;
;; ALBUM
;;
;; The collection name to which this track belongs
;;
;; TRACKNUMBER
;;
;; The track number of this piece if part of a specific larger
;; collection or album
;;
;; ARTIST
;;
;; The artist generally considered responsible for the work. In
;; popular music this is usually the performing band or singer. For
;; classical music it would be the composer. For an audio book it
;; would be the author of the original text.
;;
;; PERFORMER
;;
;; The artist(s) who performed the work. In classical music this
;; would be the conductor, orchestra, soloists. In an audio book it
;; would be the actor who did the reading. In popular music this is
;; typically the same as the ARTIST and is omitted.
;;
;; COPYRIGHT
;;
;; Copyright attribution, e.g., '2001 Nobody's Band' or '1999 Jack
;; Moffitt'
;;
;; LICENSE
;;
;; License information, eg, 'All Rights Reserved', 'Any Use
;; Permitted', a URL to a license such as a Creative Commons license
;; ("www.creativecommons.org/blahblah/license.html") or the EFF Open
;; Audio License ('distributed under the terms of the Open Audio
;; License. see http://www.eff.org/IP/Open_licenses/eff_oal.html for
;; details'), etc.
;;
;; ORGANIZATION
;;
;; Name of the organization producing the track (i.e. the 'record
;; label')
;;
;; DESCRIPTION
;;
;; A short text description of the contents
;;
;; GENRE
;;
;; A short text indication of music genre
;;
;; DATE
;;
;; Date the track was recorded
;;
;; LOCATION
;;
;; Location where track was recorded
;;
;; CONTACT
;;
;; Contact information for the creators or distributors of the
;; track. This could be a URL, an email address, the physical address
;; of the producing label.
;;
;; ISRC
;;
;; ISRC number for the track; see the ISRC intro page for more
;; information on ISRC numbers. http://isrc.ifpi.org/
;;;
;;; Cleaning up file names
;;;
;; Replaces any sequences of non alphanumeric or dot character in the
;; arguments by a single dash; remove accents.
(defparameter +character-foldings+
'(("A" "ÀÁÂÃÄÅ") ("AE" "Æ") ("C" "Ç") ("E" "ÈÉÊË") ("I" "ÌÍÎÏ")
("ETH" "Ð") ("N" "Ñ") ("O" "ÒÓÔÕÖØ") ("U" "ÙÚÛÜ") ("Y" "Ý")
("TH" "Þ") ("ss" "ß") ("a" "àáâãäå") ("ae" "æ") ("c" "ç")
("e" "èéêë") ("i" "ìíîï") ("eth" "ð") ("n" "ñ") ("o" "òóôõöøº")
("u" "ùúûü") ("u" "ýÿ") ("th" "þ")))
(defun character-folding (character)
(car (member (character character) +character-foldings+
:test (function position) :key (function second))))
(defun character-fold (character)
"
RETURN: A string containing the character without accent
(for accented characters), or a pure ASCII form of the character.
"
(car (character-folding character)))
(defun string-fold (string)
(apply (function concatenate) 'string
(map 'list
(lambda (ch) (let ((conv (character-folding ch)))
(if conv
(first conv)
(string ch))))
string)))
(defun clean-name (name)
(format nil "~{~A~^-~}"
(split-sequence-if (complement (function alphanumericp))
(string-fold (string-downcase name))
:remove-empty-subseqs t)))
;;; Convert HH:MM:SS strings into seconds.
(defgeneric dms (o)
(:method ((s string))
(dms (list (parse-integer s :start 0 :end 2)
(parse-integer s :start 3 :end 5)
(parse-integer s :start 6 :end 8))) )
(:method ((s list))
(+ (* 60 (+ (* 60 (first s)) (second s))) (third s))))
;;;
;;; CDDB disk structure
;;;
(defstruct cddb-disk
media-catalog-number
disk-id
performer
title
tracks
%current-track)
(defstruct cddb-track
number
offset
isrc
performer
title)
(defun cddb-track-normalize-file-name (track disk)
(let ((width (max 2 (ceiling (log (1+ (length (cddb-disk-tracks disk))) 10)))))
(format nil "~V,'0D--~A"
width (cddb-track-number track)
(clean-name (cddb-track-title track)))))
(defun cddb-track-tags (track disk)
(list (list :title (cddb-track-title track))
;; :version
(list :album (cddb-disk-title disk))
(list :tracknumber (cddb-track-number track))
(list :artist (cddb-disk-performer disk))
(list :performer (cddb-track-performer track))
;; :copyright :license :organization
;; :description :genre :date :location :contact
(list :isrc (cddb-track-isrc track))))
(defun tag-flac-file (file disk tags)
(declare (ignore disk))
(funcall (if *dry-run*
(function print)
(function uiop:run-program))
(append (list "metaflac")
(mapcan (lambda (tag)
(let ((flac-tag (second (find (first tag) *tag-keys* :key (function first)))))
(when flac-tag
(list
(format nil "--set-tag=~A=~A"
flac-tag
(second tag))))))
tags)
(list (namestring file)))))
(defun tag-mp3-file (file disk tags)
(funcall (if *dry-run*
(function print)
(function uiop:run-program))
(append (list "id3v2")
(mapcan (lambda (tag)
(let ((frame (third (find (first tag) *tag-keys* :key (function first)))))
(when frame
(list (format nil "--~A" frame)
(if (eq :tracknumber (first tag))
(format nil "~A/~A" (second tag) (length (cddb-disk-tracks disk)))
(second tag))))))
tags)
(list (namestring file)))))
;;;
;;; Loading (read and parse) cddb.txt files.
;;;
(defun update-disk (disk key values)
(case key
(:track-list-header (setf (cddb-disk-tracks disk) (make-array 8 :adjustable t :fill-pointer 0)))
(:track-list (destructuring-bind (number offset) values
(vector-push-extend (make-cddb-track :number number :offset offset)
(cddb-disk-tracks disk))))
(:disk-mcn (setf (cddb-disk-media-catalog-number disk) (first values)))
(:track-isrc (destructuring-bind (number isrc) values
(setf (cddb-track-isrc (aref (cddb-disk-tracks disk) (1- number))) isrc)))
(:disk-text-header (setf (cddb-disk-%current-track disk) nil))
(:track-text-header (setf (cddb-disk-%current-track disk) (1- (first values))))
(:disk-id (setf (cddb-disk-disk-id disk) (first values)))
(:performer (if (cddb-disk-%current-track disk)
(setf (cddb-track-performer (aref (cddb-disk-tracks disk)
(cddb-disk-%current-track disk)))
(first values))
(setf (cddb-disk-performer disk) (first values))))
(:title (if (cddb-disk-%current-track disk)
(setf (cddb-track-title (aref (cddb-disk-tracks disk)
(cddb-disk-%current-track disk)))
(first values))
(setf (cddb-disk-title disk) (first values))))))
;; cd-info 0.82
;; cd-info 0.83 -- cdparanoia III release 10.2 (September 11, 2008)
(defparameter *regexps*
'(
(:version "^cd-info version ([0-9]+\\.[0-9]+) " real)
(:track-list-header "^CD-ROM Track List")
(:track-list "^ *([0-9]*): ([0-9][0-9]:[0-9][0-9]:[0-9][0-9]) .* audio .*$" integer dms)
(:disk-mcn "^Media Catalog Number (MCN): (.*)$" string)
(:track-isrc "^TRACK (.*) ISRC: (.*)$" integer string)
(:disk-text-header "^CD-TEXT for Disc:$")
(:track-text-header "^CD-TEXT for Track (.*):" integer)
(:disk-id "^ DISC_ID: (.*)$" string)
(:performer "^ PERFORMER: (.*)$" string)
(:title "^ TITLE: (.*)$" string)))
(defun parse-line (line regexps)
(loop
:for (key re . types) :in regexps
:do (multiple-value-bind (start end groups-start groups-end)
(cl-ppcre:scan re line)
(declare (ignore end))
(when start
(return (values key
(loop
:for type :in types
:for start :across groups-start
:for end :across groups-end
:for text := (subseq line start end)
:collect (ecase type
(string text)
(dms (dms text))
(real (read-from-string text))
(integer (parse-integer text))))))))))
(defun cddb-load (path)
(with-open-file (input path :external-format #+clisp charset:iso-8859-1 #-clisp :iso-8859-1)
(loop
:with disk := (make-cddb-disk)
:for line := (read-line input nil nil)
:while line
:do (multiple-value-bind (key values) (parse-line line *regexps*)
(when key
(update-disk disk key values)))
:finally (return disk))))
;;;
;;; Renaming and tagging files.
;;;
(defun validate-cddb-for-files (files disk)
(flet ((check (expression message)
(unless expression
(format *error-output* "~&ERROR: ~A~%" message)
(return-from validate-cddb-for-files nil))))
(check files "No .flac or .mp3 files.")
(check disk "Invalid cddb.txt file.")
(check (= (length (cddb-disk-tracks disk)) (length files)) "Different number of tracks and files.")
(check (cddb-disk-title disk) "Empty disk title.")
(check (cddb-disk-performer disk) "Empty disk performer.")
(loop :for track :across (cddb-disk-tracks disk)
:do (check (cddb-track-title track) "Empty track title.")
(check (cddb-track-performer track) "Empty track performer."))
t))
(defun rename-files (files disk)
(map 'list
(lambda (old-path track)
(let ((new-name (cddb-track-normalize-file-name track disk)))
(if (string= (pathname-name old-path)
(pathname-name new-name))
old-path
(if *dry-run*
(let ((new-path (merge-pathnames new-name old-path)))
(format t "~&Would rename ~A to ~A~%" (file-namestring old-path) (file-namestring new-path))
(finish-output)
new-path)
(let ((new-path (rename-file old-path new-name)))
(format t "~&Renamed ~A to ~A~%" (file-namestring old-path) (file-namestring new-path))
(finish-output)
new-path)))))
files (cddb-disk-tracks disk)))
(defun tag-file (file disk tags)
(cond
((string-equal "flac" (pathname-type file)) (tag-flac-file file disk tags))
((string-equal "mp3" (pathname-type file)) (tag-mp3-file file disk tags))
(t (error "Cannot tag: unknown file type ~S" (pathname-type file)))))
(defun tag-files (files disk)
(map nil
(lambda (file track)
(let ((tags (cddb-track-tags track disk)))
(when *dry-run*
(format t "~&Would tag file ~A~:{~% ~30S ~S~}~%"
file
tags))
(tag-file file disk tags)))
files (cddb-disk-tracks disk)))
(defun rename-and-tag-files (directory)
(let* ((cddb-file (merge-pathnames #P"cddb.txt" directory))
(flacs (sort (directory (merge-pathnames #P"*.flac" directory))
(lambda (a b)
(string< (file-namestring a) (file-namestring b)))))
(mp3s (sort (directory (merge-pathnames #P"*.mp3" directory))
(lambda (a b)
(string< (file-namestring a) (file-namestring b)))))
(files (or flacs mp3s)))
(unless (probe-file cddb-file)
(format *error-output* "~&ERROR: Missing a ~A file.~%" cddb-file)
(return-from rename-and-tag-files ex-noinput))
(unless files
(format *error-output* "~&ERROR: No .flac or .mp3 files in ~A.~%" directory)
(return-from rename-and-tag-files ex-noinput))
(let ((disk (cddb-load cddb-file)))
(unless (validate-cddb-for-files files disk)
(format *error-output* "~&ERROR: Invalid ~A file for ~S.~%" cddb-file files)
(return-from rename-and-tag-files ex-dataerr))
(handler-case
(tag-files (rename-files files disk) disk)
(error (err)
(format *error-output* "~&ERROR: while processing ~A: ~A~%"
directory
(string-trim #(#\newline #\space #\tab)
(princ-to-string err)))
ex-software)
(:no-error (&rest ignore)
(declare (ignore ignore))
ex-ok)))))
;;;
;;; The main function.
;;;
(defun main (arguments)
(let ((result ex-ok))
(dolist (directory arguments result)
(let ((directory (if (string= "/" (subseq directory (1- (length directory))))
directory
(concatenate 'string directory "/"))))
(handler-case
(let ((new-result (rename-and-tag-files directory)))
(setf result (if (zerop result)
new-result
result)))
(error (err)
(format *error-output* "~&ERROR: while processing ~A: ~A~%"
directory
(string-trim #(#\newline #\space #\tab)
(princ-to-string err)))
(setf result ex-software)))))))
;;;
;;; Legacy garbage.
;;;
(defun get-disc-and-track-from-pathname (pathname)
"Extract the disc and track numbers from a pathname such as:
/music/$album/cd01/track42\\.cdda.flac"
(let ((name (file-namestring pathname))
(dir (first (last (pathname-directory pathname)))))
(values (cond
((and (prefixp "cd" dir)
(digit-char-p (aref dir 2)))
(parse-integer dir :start 2 :junk-allowed t)))
(cond
((and (prefixp "track" name)
(digit-char-p (aref name 5)))
(parse-integer name :start 5 :junk-allowed t))))))
;; (defun title-to-filename (title)
;; ())
(defun set-flac-metadata (file plist)
(warn "Not implemented yet.")
(print file)
(print plist))
(defun verbose-rename-file (old new)
(declare (ignore old))
(warn "Not implemented yet.")
(print new))
#-(and)
(defun rename-eric-satie-files ()
(dolist (dir '("/movies/sound/flac/eric-satie/the-complete-solo-piano-music--thibaudet/"
"/movies/sound/flac/eric-satie/satie-piano-works--ciccolini--tacchino/"))
(let ((index (com.informatimago.common-lisp.cesarum.file:sexp-file-contents
(merge-pathnames "index.sexp" dir))))
(dolist (file (directory (merge-pathnames #P"**/*.flac" dir)))
(multiple-value-bind (discnum tracknum) (get-disc-and-track-from-pathname file)
(let* ((dirkeys (mapcan (lambda (key)
(let ((value (getf index key)))
(when value (list key value))))
(mapcar (function first) *tag-keys*)))
(discindex (find discnum (getf index :discs) :key (lambda (entry) (getf entry :number))))
(trackinfo (find tracknum (getf (or discindex index) :tracks) :key (function first)))
(trackno (getf trackinfo :tracknum))
(title (error "Not implemented yet.")))
(set-flac-metadata file (list* :album (if discnum
(format nil "~A, disc ~A"
(getf dirkeys :album)
discnum)
(getf dirkeys :album))
(append
(progn (remf dirkeys :album) dirkeys)
trackinfo)))
(verbose-rename-file file (format nil "~2,'0D-~A" trackno (clean-name title)))))))))
;;;; THE END ;;;;
| 22,733 | Common Lisp | .lisp | 544 | 33.264706 | 110 | 0.550222 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 10fed086b9d5325772ebfa81ff2f2d5e92883448b9d11c28ec114ab8f1b3e15a | 12,333 | [
-1
] |
12,334 | menu.lisp | informatimago_commands/sources/commands/menu.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(defparameter *program-version* "0.0.2")
(defun main (arguments)
(declare (ignore arguments))
(format *error-output* "~2%Not implemented yet.~2%")
(exit ex-usage))
#|
(defun usage ()
(format t "~%~
~A usage:~%~
~%~
~& ~:*~A [-h|--help] item... ~%~
~%"
*program-name*))
(defun width ()
#+clisp (screen:with-window (screen:window-size screen:*window*))
#-clisp 80)
(defun main (arguments)
(let ((items '()))
(dolist (arg arguments)
(cond
((or (string= "-h" arg) (string= "--help" arg))
(usage)
(exit ex-ok))
((string= (aref arg 0) #\-)
(format *error-output* "~a: invalid argument '~a'.~%" *program-name* arg)
(usage)
(exit ex-usage))
(t (push arg items))))
(when (= 0 (length items))
(format *error-output* "~a: No menu item given. Aborting.~%" *program-name*)
(usage)
(exit ex-usage))))
|#
;;;; THE END ;;;;
| 1,024 | Common Lisp | .lisp | 35 | 23.228571 | 82 | 0.520367 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 05ad9f86856d18a7db7d63ff43e004b2e311a4766d785f6a6ff789789bd64930 | 12,334 | [
-1
] |
12,335 | insulte.lisp | informatimago_commands/sources/commands/insulte.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(defparameter *shakespear*
'(("Thou")
("artless" "bawdy" "beslubbering" "bootless" "churlish"
"cockered" "clouted" "craven" "currish" "dankish" "dissembling"
"droning" "errant" "fawning" "fobbing" "froward" "frothy"
"gleeking" "goatish" "gorbellied" "impertinent" "infectious"
"jarring" "loggerheaded" "lumpish" "mammering" "mangled"
"mewling" "paunchy" "pribbling" "puking" "puny" "qualling"
"rank" "reeky" "roguish" "ruttish" "saucy" "spleeny" "spongy"
"surly" "tottering" "unmuzzled" "vain" "venomed" "villainous"
"warped" "wayward" "weedy" "yeasty")
("base-court" "bat-fowling" "beef-witted" "beetle-headed"
"boil-brained" "clapper-clawed" "clay-brained" "common-kissing"
"crook-pated" "dismal-dreaming" "dizzy-eyed" "doghearted"
"dread-bolted" "earth-vexing" "elf-skinned" "fat-kidneyed"
"fen-sucked" "flap-mouthed" "fly-bitten" "folly-fallen"
"fool-born" "full-gorged" "guts-griping" "half-faced"
"hasty-witted" "hedge-born" "hell-hated" "idle-headed"
"ill-breeding" "ill-nurtured" "knotty-pated" "milk-livered"
"motley-minded" "onion-eyed" "plume-plucked" "pottle-deep"
"pox-marked" "reeling-ripe" "rough-hewn" "rude-growing"
"rump-fed" "shard-borne" "sheep-biting" "spur-galled"
"swag-bellied" "tardy-gaited" "tickle-brained" "toad-spotted"
"unchin-snouted" "weather-bitten")
("apple-john" "baggage" "barnacle" "bladder" "boar-pig"
"bugbear" "bum-bailey" "canker-blossom" "clack-dish" "clotpole"
"coxcomb" "codpiece" "death-token" "dewberry" "flap-dragon"
"flax-wench" "flirt-gill" "foot-licker" "fustilarian" "giglet"
"gudgeon" "haggard" "harpy" "hedge-pig" "horn-beast"
"hugger-mugger" "joithead" "lewdster" "lout" "maggot-pie"
"malt-worm" "mammet" "measle" "minnow" "miscreant" "moldwarp"
"mumble-news" "nut-hook" "pigeon-egg" "pignut" "puttock"
"pumpion" "ratsbane" "scut" "skainsmate" "strumpet" "varlot"
"vassal" "whey-face" "wagtail")))
(defun shakespear-insult ()
(format nil "~@(~{~A~^ ~}!~)"
(loop :for words :in *shakespear*
:for count := (length words)
:for word := (elt words (random count))
:collect word)))
(defparameter insults
'(
("accapareur" (nm))
("aérolithe" (nm))
("amiral de bateaulavoir" (gnm))
("amphitryon" (nm))
("anacoluthe" (nf))
("analphabète" (n a))
("anthracite" (nm))
("anthropophage" (nm a))
("anthropopithèque" (nm))
("apache" (nm))
("apprenti dictateur à la noix de coco" (gnm))
("arlequin" (nm))
("astronaute d'eau douce" (gn))
("athlète complet" (n))
("autocrate" (nm))
("autodidacte" (n a))
("azteque" (nm))
("babouin" (nm))
("bachibouzouk" (nm))
("bande de" (|...|))
("bandit" (nm))
("bayadère" (nf))
("bibendum" (nm))
("boitsanssoif" (ni))
("brontosaure" (nm))
("bougre de" (|...|))
("brute" (nf))
("bulldozer à réaction" (gnm))
("vieux" (a))
("cachalot" (nm))
("canaille" (nf))
("canaque" (nm a))
("cannibale" (nm))
("carnaval" (nm))
("catachrèse" (nf))
("cataplasme" (nm))
("cercopithèque" (nm))
("chauffard" (nm))
("chenapan" (nm))
("choléra" (nm))
("chouette mal empaillée" (gnf))
("cloporte" (nm))
("clysopompe" (nm))
("coléoptère" (nm))
("coloquinte" (nf))
("coquin" (n a))
("cornemuse" (nf))
("cornichon" (nm))
("corsaire" (nm))
("coupejarret" (nm))
("cowboy de la route" (gnm))
("crétin des alpes" (gnm))
("Cromagnon" (np))
("cyanure" (nm))
("cyclone" (nm))
("cyclotron" (nm))
("Cyrano à quatre pattes" (gnm))
("diablesse" (nf))
("diplodocus" (nm))
("doryphore" (nm))
("dynamiteur" (nm))
("ecornifleur" (nm))
("ecraseur" (nm))
("ectoplasme" (nm))
("egoïste" (nm))
("emplatre" (nm))
("empoisonneur" (nm a))
("enragé" (nm a))
("épouvantail" (nm))
("équilibriste" (nm))
("esclavagiste" (nm))
("escogriffe" (nm))
("espèce de" (|...|))
("extrait de" (|...|))
("graine de" (|...|))
("tersorium" (nm))
("faux jeton" (nm))
("flibustier" (nm))
("forban" (nm))
("frères de la côte" (gnm))
("froussard" (nm a))
("galopin" (nm))
("gangster" (nm))
("gardecôte à la mie de pain" (gnm))
("gargarisme" (nm))
("garnement" (nm))
("gibier de potence" (nm))
("goujat" (nm))
("gredin" (nm))
("grenouille" (nf))
("gros plein de soupe" (gnm))
("gyroscope" (nm))
("hérétique" (n a))
("horslaloi" (nm))
("huluberlu" (nm))
("hydrocarbure" (nm))
("iconoclaste" (nm a))
("incas de carnaval" (gnmp))
("individou de général" (gnm))
("invertébré" (nm))
("ivrogne" (n))
("jet d'eau ambulant" (gnm))
("jocrisse" (nm))
("judas" (nm))
("jus de réglisse" (gnm))
("kroumir" (nm))
("ku klux klan" (gnm))
("lâche" (nm))
("lépidoptère" (nm))
("logarithme" (nm))
("loupgarou à la graisse de renoncule" (gnm))
("macaque" (nm))
("macrocéphale" (nm))
("malappris" (n a))
("malotru" (n))
("mamelouk" (nm))
("marchand de guano" (gnm))
("marchand de tapis" (gnm))
("marin d'eau douce" (gnm))
("marmotte" (nf))
("mégalomane" (nm a))
("mégacycle" (nm))
("mercanti" (nm))
("mercenaire" (nm a))
("mérinos" (nm))
("mille sabords" (gnmp))
("misérable" (a))
("mitrailleur à bavette" (gnm))
("moratorium" (nm))
("moricaud" (nm a))
("mouchard" (nm))
("moujik" (nm))
("moule à gaufres" (gnm))
("moussaillon" (nm))
("mrkrpxzkrmtfrz" (nm))
("mufle" (nm))
("Mussolini de carnaval" (nm))
("naufrageur" (nm))
("négrier" (nm))
("noix de coco" (gnm))
("nyctalope" (n a))
("olibrius" (nm))
("ophicléïde" (nm))
("ornithorynque" (nm))
("oryctérope" (nm))
("ostrogoth" (n a))
("ours mal lèché" (gnm))
("pacte à quatre" (gnm))
("paltoquet" (nm))
("pantoufle" (nf))
("Papous" (nm))
("paranoïaque" (nm a))
("parasite" (nm a))
("Patagon" (nm))
("patapouf" (nm))
("patate" (nf))
("péronnelle" (nf))
("perruche bavarde" (gnf))
("phénomène" (nm))
("phlébotome" (nm))
("phylactère" (nm))
("phylloxéra" (nm))
("pignouf" (nm))
("pirate" (nm))
("Polichinelle" (nm))
("polygraphe" (nm))
("porcépic mal embouché" (gnm))
("potentat emplumé" (gnm))
("poussière" (nf))
("profiteur" (nm))
("projectile guidé" (gnm))
("protozoaire" (nm))
("pyromane" (nm))
("pyrophore" (nm))
("rapace" (nm))
("rat" (nm))
("Ravachol" (nm))
("renégat" (nm))
("rhizopode" (nm))
("Rocambole" (nm))
("sacripant" (nm))
("sajou" (nm))
("saltimbanque" (nm))
("sapajou" (nm))
("satané bazar de fourbi de truc" (gnm))
("satrape" (nm))
("sauvage" (n a))
("scélérat" (nm))
("schizophrène" (n a))
("scolopendre" (nf))
("scorpion" (nm))
("serpent" (nm))
("simili martien à la graisse de cabestan" (gnm))
("sinapisme" (nm))
("soulographe" (nm))
("squatter" (nm))
("tchouktchouknougat" (nm))
("technocrate" (nm))
("tête de lard" (gnf))
("tête de mule" (gnf))
("tigresse" (nf))
("tonnerre de Brest" (gnm))
("topinanbour" (nm))
("tortionnaire" (nm))
("traficant de chair humaine" (gnm))
("trainepotence" (nm))
("traitre" (nm a))
("troglodyte" (nm))
("trompelamort" (nm))
("vampire" (nm))
("vandale" (nm a))
("vanupieds" (nm))
("vaurien" (nm))
("végétarien" (nm))
("Vercingétorix de carnaval" (nm))
("ver de terre" (gnm))
("vermicelle" (nm))
("vermine" (nm))
("vipère" (nf))
("vivisectionniste" (nm))
("voleur" (nm))
("wisigoth" (n a))
("zapotèque" (nm))
("zèbre" (nm))
("zigomar" (nm))
("zouave" (nm))
("Zoulou" (nm))
));;insults
(defparameter nm (remove-if-not (lambda (x) (intersection '(n np nm gnm) (second x))) insults))
(defparameter nf (remove-if-not (lambda (x) (intersection '(nf np) (second x))) insults))
(defparameter ad (remove-if-not (lambda (x) (member 'a (second x))) insults))
(defun haddock-insulte ()
(let* ((ga (format nil " ~A" (first (elt ad (random (length ad))))))
(gn (let ((n (random (+ (length nf) (length nm)))))
(if (>= n (length nm))
(prog1
(first (elt nf (- n (length nm))))
(cond
((= 0 (length ga)))
((string= "e" ga :start2 (1- (length ga))))
((string= "eux" ga :start2 (- (length ga) 3))
(setf ga (concatenate 'string
(subseq ga 0 (- (length ga) 2)) "ille")))
((string= "eur" ga :start2 (- (length ga) 3))
(setf ga (concatenate 'string
(subseq ga 0 (1- (length ga))) "se")))
(t
(setf ga (concatenate 'string ga "e")))))
(first (elt nm n)))))
(conj (if (position (aref gn 0) "aeiouyh") "d'" "de "))
(ins (case (random 4)
((0) (concatenate 'string "espèce " conj gn ga))
((1) (concatenate 'string "bande " conj gn ga))
(otherwise (concatenate 'string gn ga)))))
(concatenate 'string
(string-capitalize (subseq ins 0 1))
(subseq ins 1)
" !")))
(defun main (arguments)
(let ((shakespearp (member "shakespear" arguments :test (function equalp))))
(setf *random-state* (make-random-state t))
(princ (if shakespearp
(shakespear-insult)
(haddock-insulte)))
(terpri)
ex-ok))
;;;; THE END ;;;;
| 10,087 | Common Lisp | .lisp | 310 | 25.851613 | 95 | 0.53516 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | a0ed9f008bf1634b29cc29e99455a5fd1e8b2feacd778cc49a6bfbf551631381 | 12,335 | [
-1
] |
12,336 | surveille-host.lisp | informatimago_commands/sources/commands/surveille-host.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;*****************************************************************************
;;;;FILE: surveille-host
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: CLISP
;;;;USER-INTERFACE: Common-Lisp
;;;;DESCRIPTION
;;;;
;;;; This scripts pings regularly an IP address (or list of IP addresses)
;;;; and signals (and/or sends an email) when a change occurs (remote
;;;; going on-line or off-line).
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2003-08-14 <PJB> Creation.
;;;;BUGS
;;;;LEGAL
;;;; LGPL
;;;;
;;;; Copyright Pascal J. Bourguignon 1992 - 2003
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;;;
;;;;*****************************************************************************
(command :use-systems (:com.informatimago.common-lisp)
:use-packages ("COMMON-LISP"
"SCRIPT"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ACTIVITY"))
(in-package "COMMAND.SURVEILLE-HOST")
(defparameter *from-email* "surveille-host <[email protected]>")
(defparameter *remotes* (make-hash-table :test (function equal))
"A map: ip-address --> remotes.")
(defun reset-remotes ()
"
POST: There is no remote defintions in *REMOTES*.
"
(setf *remotes* (make-hash-table :test (function equal))))
(defclass remote ()
((name
:accessor name
:initarg :name
:initform "Unnamed"
:type string
:documentation "The name of the remote.")
(ip-address
:accessor ip-address
:initarg :ip-address
:initform "127.0.0.1"
:type string
:documentation "The IP address of the remote.")
(email
:accessor email
:initarg :email
:initform nil
:type (or null string)
:documentation "The email address to be signaled when state change.")
(check-period
:accessor check-period
:initarg :check-period
:initform 120
:type number
:documentation "The period in second of checking.")
(state
:accessor state
:initarg :state
:initform :unknown
:documentation
"Whether the remote state is :unknown, :off-line or :on-line.")
(activity
:accessor activity
:initform nil
:documentation "The activity running for this remote."))
(:documentation "A remote host definition."))
(defparameter *do-logging* nil)
(defmacro logging (action &body body)
`(progn
(when *do-logging*
(format *trace-output* "~2%BEGINNING ~A~%" (string ,action)))
(prog1 (progn ,@body)
(when *do-logging*
(format *trace-output* "~%COMPLETED ~A~%" (string ,action))))))
(defmethod get-current-state ((self remote))
"
RETURN: Whether :ON-LINE or :OFF-LINE according to the status of ping.
"
(logging (format nil "pinging ~A" (name self))
(if (= 0 (uiop:run-program (format nil "ping -c 10 -w 15 -n -q ~S" (ip-address self))
:input nil :output nil))
:on-line
:off-line)))
(defmethod notificate-state-change ((self remote))
(when (email self)
(logging (format nil "sendmail ~A" (email self))
(let ((msg-stream (uiop:run-program (format nil "sendmail ~A" (email self))
:force-shell t :input :stream :output nil :wait nil)))
(format msg-stream
(concatenate 'string
"From: ~A~%"
"To: ~A~%"
"Subject: ~A going ~A~%"
"~%"
"I've the pleasure to inform you that ~%"
"the remote host ~A (~A)~%"
"just went ~A.~%"
"~%"
"-- ~%"
"The surveille-host script.~%")
*from-email*
(email self)
(name self)
(if (eq :on-line (state self)) "on-line" "off-line")
(name self) (ip-address self)
(if (eq :on-line (state self)) "on-line" "off-line"))
(close msg-stream)))))
(defmethod check ((self remote))
(let ((new-state (get-current-state self)))
(unless (eq new-state (state self))
(if (eq :unknown (state self))
(progn
(setf (state self) new-state)
(notificate-state-change self))
(setf (state self) new-state)))))
(defun find-remote-with-ip-address (ip-address)
"
RETURN: The remote instance that has the given IP-ADDRESS, or NIL.
"
(gethash ip-address *remotes*))
(defun add-remote (name ip-address email)
"
DO: If there is already a remote with the same IP-ADDRESS
then raise an error
else create such a new remote.
"
(if (find-remote-with-ip-address ip-address)
(error "There is already a remote with the same IP address ~S." ip-address)
(let ((remote (make-instance 'remote
:name name
:ip-address ip-address
:email email)))
(setf (gethash ip-address *remotes*) remote)
(setf (activity remote) (make-instance 'activity
:name (name remote)
:period (check-period remote)
:active t
:closure (lambda () (check remote))))
(schedule-activity (activity-scheduler (activity remote))
(activity remote)))))
(defun main (argv)
(declare (ignore argv))
(add-remote "hubble" "hubble.informatimago.com" "[email protected]")
(add-remote "proteus" "proteus.informatimago.com" "[email protected]")
(add-remote "kuiper" "kuiper.informatimago.com" "[email protected]")
(add-remote "despina" "despina.informatimago.com" "[email protected]")
(add-remote "larissa" "larissa.informatimago.com" "[email protected]")
(let ((period (* 30 (hash-table-size *remotes*))))
(maphash (lambda (key remote)
(declare (ignore key))
(setf (check-period remote) period)
(setf (activity-period (activity remote)) period))
*remotes*))
(activity-run)
ex-ok)
;;;; THE END ;;;;
| 7,257 | Common Lisp | .lisp | 177 | 32.231638 | 105 | 0.56081 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | e38c941609b1f2633f0c24392cb0fb7cb6f2712de911b267dec9f170dd3608b2 | 12,336 | [
-1
] |
12,337 | clar.lisp | informatimago_commands/sources/commands/clar.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;*****************************************************************************
;;;;FILE: clar
;;;;LANGUAGE: common lisp (clisp)
;;;;SYSTEM: UNIX
;;;;USER-INTERFACE: CLI
;;;;DESCRIPTION
;;;; This script joins or splits lisp sources between a single file
;;;; and several files.
;;;;USAGE
;;;;
;;;; clar single.clar a.lisp ... z.lisp
;;;; -- creates a single.clar as a concatenation of a.lisp ... z.lisp
;;;;
;;;; clar single.lisp
;;;; -- splits single.clar into the original a.lisp ... z.lisp files.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2010-09-22 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; Copyright Pascal J. Bourguignon 2010 - 2010
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This script 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 library; see the file COPYING.LIB.
;;;; If not, write to the Free Software Foundation,
;;;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;;*****************************************************************************
(in-package "SCRIPT")
(command :use-systems (:cl-ppcre))
(defparameter *program-version* "0.1.2")
(defun match (regexp string)
(let* ((scanner (cl-ppcre:create-scanner regexp :extended-mode t))
(results (multiple-value-list (cl-ppcre:scan scanner string))))
(if (equal '(nil) results)
nil
(destructuring-bind (as ae ss es) results
(values-list (cons (list as ae) (map 'list (function list) ss es)))))))
(defun match-string (string range)
(subseq string (first range) (second range)))
(defparameter *escape-constr* ";;;; -%- CLAR ~A~%")
(defparameter *escape-regexp* "^;;;; -%- CLAR (.*)")
(defparameter *file-constr* ";;;; -%- CLAR FILE -%- ~A~%")
(defparameter *file-regexp* "^;;;; -%- CLAR FILE -%- (.*)")
(defparameter *end-constr* ";;;; -%- CLAR END -%-~%")
(defparameter *end-regexp* "^;;;; -%- CLAR END -%-")
;;;; -%- CLAR FILE -%- It's a trap!
(defun valid-file-namestring-p (namestring)
(every (lambda (ch) (or (alphanumericp ch) (position ch "-._"))) namestring))
(defparameter *external-format*
#+clisp charset:iso-8859-1
#-clisp :iso-8859-1)
(defun join (output inputs)
(with-open-file (out output
:direction :output
:if-does-not-exist :create
:if-exists :supersede
:external-format *external-format*)
(dolist (input inputs)
(if (valid-file-namestring-p (file-namestring input))
(with-open-file (inp input
:direction :input
:if-does-not-exist :error
:external-format *external-format*)
(format out *file-constr* (file-namestring input))
(loop
:for line = (read-line inp nil nil)
:while line
:do (if (match *escape-regexp* line)
(format out *escape-constr* line)
(write-line line out))))
(warn "Invalid file namestring ~S -- rejected." input)))
(format out *end-constr*)))
(defun split (archive)
(with-open-file (inp archive
:direction :input
:if-does-not-exist :error
:external-format *external-format*)
(let ((*print-pretty* nil)
(*print-right-margin* nil)
(out nil)
(regexps (list *file-regexp* *end-regexp* *escape-regexp*)))
(unwind-protect
(loop :for line = (read-line inp nil nil) :while line :do
(let ((matches (mapcar (lambda (regexp)
(mapcar (lambda (range) (match-string line range))
(multiple-value-list (match regexp line))))
regexps)))
(cond
((elt matches 0)
(when out (close out))
(let ((name (second (elt matches 0))))
(setf out (if (valid-file-namestring-p name)
(open name
:direction :output
:if-does-not-exist :create
:if-exists :supersede
:external-format *external-format*)
(progn
(warn "Invalid file namestring ~S -- ignored." name)
(make-broadcast-stream))))))
((elt matches 1)
(close out)
(setf out nil)
(loop-finish))
((elt matches 2)
(write-line (second (elt matches 2)) out))
(out
(write-line line out))
(t
(warn "Prefix line: ~S" line)))))
(when out (close out))))))
(defun usage ()
(format t "~A version ~A~%" *program-name* *program-version*)
(format t "~A usage:~2%" *program-name*)
(format t "~T~A single.clar a.lisp .... z.lisp~%" *program-name*)
(format t "~T~T# create a single file from several sources.~2%")
(format t "~T~A single.clar~%" *program-name*)
(format t "~T~T# split out several sources from a single file.~2%"))
(defun main (files)
(handler-case
(cond
((null files)
(usage)
ex-usage)
((some (lambda (file) (or (zerop (length file))
(char= #\- (aref file 0)))) files)
(usage)
ex-usage)
((null (rest files))
(split (first files))
ex-ok)
(t
(join (first files) (rest files))
ex-ok))
(error (err)
(format t "~A: ~A~%" *program-name* err)
ex-software)))
;;;; THE END ;;;;
| 6,457 | Common Lisp | .lisp | 151 | 33 | 89 | 0.516139 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | dacfe3b983903d400320f4b0b8b423968c4a21b33af1407b8cc703be97c5576a | 12,337 | [
-1
] |
12,338 | lrev.lisp | informatimago_commands/sources/commands/lrev.lisp | ;;;; -*- mode:lisp; coding:iso-8859-1 -*-
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
;; Warning: processes iso-8859-1 not utf-8 arguments! ;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
(defun slurp (stream)
(loop
:for line := (read-line stream nil nil)
:while line :collect line))
(defun barf (lines stream)
(dolist (line lines)
(write-line line stream)))
(defun main (arguments)
(declare (ignore arguments))
(barf (reverse (slurp *standard-input*)) *standard-output*)
ex-ok)
;;;; THE END ;;;;
| 549 | Common Lisp | .lisp | 16 | 31.625 | 61 | 0.522727 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 830e70790271dcfbf34e8006d84082ff54e0d8ee7eda2cc5005ed4ceb2deefc3 | 12,338 | [
-1
] |
12,339 | cookie-merge.lisp | informatimago_commands/sources/commands/cookie-merge.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
(command :use-systems (:com.informatimago.common-lisp.cesarum
:split-sequence)
:use-packages ("COMMON-LISP"
"SCRIPT"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"))
(in-package "COMMAND.COOKIE-MERGE")
(defun key (cookie)
(map 'vector (function sxhash) cookie))
(defun read-cookies (pathname)
(let ((c (make-hash-table :test (function equalp))))
(dolist (cookie
(delete nil
(split-sequence "%"
(string-list-text-file-contents pathname)
:test (function string=)))
c)
(if (and (gethash (key cookie) c)
(not (equalp (gethash (key cookie) c) cookie)))
(format t "collision ~%~S~%~S~%" (gethash (key cookie) c) cookie)
(setf (gethash (key cookie) c) cookie)))))
(defun merge-cookies (a b)
(let ((results (make-hash-table :test (function equalp))))
(maphash (lambda (k c) (setf (gethash k results) c)) a)
(maphash (lambda (k c) (setf (gethash k results) c)) b)
results))
(defun write-cookies (pathname cookies)
(with-open-file (stream pathname
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(write-line "%" stream)
(maphash (lambda (k c)
(declare (ignore k))
(dolist (l c)
(write-line l stream))
(write-line "%" stream))
cookies)))
(defun main (arguments)
(let ((cookies (make-hash-table :test (function equalp))))
(dolist (path arguments)
(setf cookies (merge-cookies (read-cookies path) cookies)))
(write-cookies "/tmp/cookies" cookies)
(format t "Wrote /tmp/cookies~%")
(finish-output))
ex-ok)
;;;; THE END ;;;;
| 2,104 | Common Lisp | .lisp | 50 | 30.48 | 78 | 0.54185 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | da5dc1a0e19110a755089e052cddc844c775350d97735152ae5c7584a53621a6 | 12,339 | [
-1
] |
12,340 | new-password.lisp | informatimago_commands/sources/commands/new-password.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: new-password
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: Unix Command Line
;;;;DESCRIPTION
;;;;
;;;; Generate a random password.
;;;;
;;;; Depends on ~/bin/script.lisp
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-01-06 <PJB> Created. (Rewrote from a bit-rotten bash script).
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2010
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(command :documentation "Generates a new random password.")
(defparameter *program-version* "1.0.1")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#|
People use those symbols in order of exponential decreasing preference
in their passwords:
!@#*.#&-?>"./)+=~%(;^`[]'>
@!$*#.-&_
|#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct options
(case :mix-case :type (member :mix-case :up-case :low-case))
(no-special-p nil :type boolean)
(no-digit-p nil :type boolean)
(length 8 :type (integer 1)))
(defparameter *options* (make-options))
(options "new-password"
(option ("-l" "--low-case") ()
"Generate only low-case letters in the password."
(setf (options-case *options*) :low-case))
(option ("-u" "--up-case") ()
"Generate only up-case letters in the password."
(setf (options-case *options*) :up-case))
(option ("-m" "--mix-case") ()
"Generate mix-case letters in the password (default)."
(setf (options-case *options*) :mix-case))
(option ("+s" "--no-special") ()
"Generate a password without any special character."
(setf (options-no-special-p *options*) t))
(option ("+d" "--no-digit") ()
"Generate a password without any digit character."
(setf (options-no-digit-p *options*) t))
(option ("-L" "--length") (length)
"Specifies the password length."
(let ((length (parse-integer length)))
(check-type length (integer 1))
(setf (options-length *options*) length)))
;; (option ("-I" "--build-trigram-index")
;; (thesaurus-pathname) "Analyses the thesaurus
;; and save tri-gram statistics for readable
;; password generation." (build-trigram-index
;; thesaurus-pathname *index-pathname*))
(help-option)
(bash-completion-options))
;; (defparameter *probability-distribution*
;; (load-probability-distribution *index-pathname*))
;; (setf *random-state* (make-random-state t))
;; (loop
;; :repeat (options-length *options*)
;; :do (princ (get-trigram *probability-distribution*))
;; :finally (terpri))
(defparameter *consonants* "BCDFGHJKLMNPQRSTVWXZ")
(defparameter *vowels* "AEIOUY")
(defparameter *specials* "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
(defparameter *digits* "0123456789")
(defun generate-random-syllabe ()
(format nil "~C~C~:[~;~C~]"
(aref *consonants* (random (length *consonants*)))
(aref *vowels* (random (length *vowels*)))
(< 0.5 (random 1.0))
(aref *consonants* (random (length *consonants*)))))
(define-modify-macro concatf (other) concat)
(defun main (arguments)
(setf *random-state* (make-random-state t))
(parse-options *command* arguments)
(loop
:with password = ""
:while (< (length password) (options-length *options*))
:do (concatf password (generate-random-syllabe))
:do (case (random 3)
((0)
(unless (options-no-special-p *options*)
(concatf password
(string (aref *specials* (random (length *specials*)))))))
((1)
(unless (options-no-digit-p *options*)
(concatf password
(string (aref *digits* (random (length *digits*))))))))
:finally
(princ (case (options-case *options*)
((:low-case) (string-downcase password))
((:up-case) (string-upcase password))
((:mix-case) (with-output-to-string (out)
(loop :for ch :across password
:do (princ (if (zerop (random 2))
(char-upcase ch)
(char-downcase ch))
out))))))
(terpri))
ex-ok)
;; (defun build-trigram-index (thesaurus-pathname index-pathname)
;; (let ((tri (make-array '(26 26 26) :element-type 'float :initial-element 0.0))
;; (total 0.0)
;; (nzc 0))
;; (labels ((letter (code)
;; (cond
;; ((<= #.(char-code #\a) code #.(char-code #\z))
;; (- code #.(char-code #\a)))
;; ((<= #.(char-code #\A) code #.(char-code #\Z))
;; (- code #.(char-code #\A)))
;; (t nil)))
;; (register (a b c)
;; (let ((i (letter a))
;; (j (letter b))
;; (k (letter c)))
;; (when (and i j k)
;; (incf (aref tri i j k))
;; (incf total))))
;; (average ()
;; (loop
;; :for i :from 0 :below (array-total-size tri)
;; :for prob = (row-major-aref tri i)
;; :initially (setf nzc 0)
;; :do (when (plusp prob)
;; (setf (row-major-aref tri i) (/ prob total))
;; (incf nzc)))))
;;
;; (with-open-file (words thesaurus-pathname :element-type '(unsigned-byte 8))
;; (loop
;; :with buffer = (make-array 65536 :element-type '(unsigned-byte 8)
;; :adjustable t
;; :fill-pointer 65536)
;; :while (plusp (read-sequence buffer words))
;; :do (loop
;; :for i :from 0 :below (- (length buffer) 3)
;; :do (register (aref buffer i)
;; (aref buffer (+ 1 i))
;; (aref buffer (+ 2 i))))))
;; (average))
;;
;; (with-open-file (index index-pathname
;; :direction :output
;; :if-does-not-exist :create
;; :if-exists :supersede)
;; (print tri index))))
;;
;;
;; (defun load-probability-distribution (index-pathname)
;; (let* ((tri (with-open-file (index index-pathname)
;; (read index)))
;; (nzc (loop
;; :for i :from 0 :below (array-total-size tri)
;; :for prob = (row-major-aref tri i)
;; :when (plusp prob) :count 1))
;; (distribution (make-array nzc))
;; (d -1))
;; (loop :for i :from 0 :below 26 :do
;; (loop :for j :from 0 :below 26 :do
;; (loop :for k :from 0 :below 26 :do
;; (let ((prob (aref tri i j k)))
;; (when (plusp prob)
;; (setf (aref distribution (incf d)) (vector prob i j k)))))))
;; (let ((distribution (sort distribution (function >) :key (lambda (v) (aref v 0)))))
;; (loop
;; :with s = 0.0
;; :for i :from 0 :below (length distribution)
;; :for trigram = (aref distribution i)
;; :do (let ((p (aref trigram 0)))
;; (setf (aref trigram 0) (incf s p)))
;; ;; :finally (print s)
;; )
;; distribution)))
;;
;; (defun get-trigram (distribution)
;; (let ((trigram (aref distribution
;; (nth-value 1 (dichotomy distribution (random 1.0)
;; (lambda (a b)
;; (cond ((< a b) -1)
;; ((= a b) 0)
;; (t 1)))
;; :key (lambda (v) (aref v 0)))))))
;; (format nil "~C~C~C"
;; (code-char (+ #.(char-code #\a) (aref trigram 1)))
;; (code-char (+ #.(char-code #\a) (aref trigram 2)))
;; (code-char (+ #.(char-code #\a) (aref trigram 3))))))
;;;; THE END ;;;;
| 9,541 | Common Lisp | .lisp | 213 | 39.638498 | 90 | 0.478691 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 7a0febd5713f105779f670d7ef77b3913809a3a5ea3280ccc5b1cfb27607bd2f | 12,340 | [
-1
] |
12,341 | diss.lisp | informatimago_commands/sources/commands/diss.lisp | ;; -*- mode:lisp;coding:utf-8 -*-
(defun split-string (string &optional (separators " ") (remove-empty nil))
"
STRING: A sequence.
SEPARATOR: A sequence.
RETURN: A list of subsequence of STRING, split upon any element of SEPARATORS.
Separators are compared to elements of the STRING with EQL.
NOTE: It's actually a simple split-sequence now.
EXAMPLES: (split-string '(1 2 0 3 4 5 0 6 7 8 0 9) '(0))
--> ((1 2) (3 4 5) (6 7 8) (9))
(split-string #(1 2 0 3 4 5 0 6 7 8 0 9) #(0))
--> (#(1 2) #(3 4 5) #(6 7 8) #(9))
(split-string \"1 2 0 3 4 5 0 6 7 8\" '(#\space #\0))
--> (\"1\" \"2\" \"\" \"\" \"3\" \"4\" \"5\" \"\" \"\" \"6\" \"7\" \"8\")
"
(loop
:with strlen = (length string)
:for position = 0 :then (1+ nextpos)
:for nextpos = (position-if (lambda (e) (find e separators)) string :start position)
:unless (and remove-empty
(or (and (= position strlen) (null nextpos ))
(eql position nextpos)))
:collect (subseq string position nextpos)
:while (and nextpos (< position strlen))))
(defun string-justify-left (string &optional (width 72) (left-margin 0) (separators #(#\Space #\Newline)))
"
RETURN: A left-justified string built from string.
WIDTH: The maximum width of the generated lines. Default is 72 characters.
LEFT-MARGIN: The left margin, filled with spaces. Default is 0 characters.
SEPARATORS: A sequence containing the characters on which to split the words.
Default: #\(#\space #\newline).
"
(check-type string string)
(check-type width integer)
(check-type left-margin integer)
(let* ((margin (make-string left-margin :initial-element (character " ")))
(splited (split-string string separators t))
(col left-margin)
(justified (list (subseq margin 0 col)))
(separator ""))
(dolist (word splited)
(if (<= width (+ col (length word)))
(progn (push #(#\newline) justified)
(push margin justified)
(push word justified)
(setf col (+ left-margin (length word))))
(progn (push separator justified)
(push word justified)
(incf col (+ 1 (length word)))))
(setf separator " "))
;; ;; Pad with spaces up to width.
;; (when (< col width)
;; (push (make-string (- width col) :initial-element (character " "))
;; justified))
(apply (function concatenate) 'string (nreverse justified))))
(defun fmt (s)
(write-string (string-justify-left s))
(terpri)
(finish-output))
(defun one-of (s) (elt s (random (length s))))
(defun main (arguments)
(declare (ignore arguments))
(setf *random-state* (make-random-state t))
(fmt (one-of #(
"You’ve baked a really lovely cake, but then you’ve used dog sh!t for frosting."
"You make some of the best products in the world — but you also make a lot of crap. Get rid of the crappy stuff."
"This company is in shambles, and I don’t have time to wet-nurse the board. So I need all of you to resign."
"Do you want to spend the rest of your life selling sugared water or do you want a chance to change the world?"
"Being the richest man in the cemetery doesn’t matter to me…"
"Be a yardstick of quality. Some people aren’t used to an environment where excellence is expected."
"The products suck! There's no sex in them anymore!"
"I’ve never known an HR person who had anything but a mediocre mentality."
"Everything you have done in your life is shit! So why don't you come work for me?"
"My job is to say when something sucks rather than sugarcoat it."
"Look, I don’t know who you are, but no one around here is too important to fire besides me. And you’re fired!"
"You think I'm an arrogant ass -- who thinks he's above the law, and I think you're a slime bucket who gets most of his facts wrong."
"That's the kind of Porsche that dentists drive."
"Sometimes when you innovate, you make mistakes. It is best to admit them quickly, and get on with improving your other innovations.")))
ex-ok)
;;;; THE END ;;;;
| 4,484 | Common Lisp | .lisp | 80 | 46.9 | 153 | 0.597117 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 46cddf27747ff27abef29562f83198e175cce67ddddb66730fedc4ee8b9ee06e | 12,341 | [
-1
] |
12,342 | euronews.lisp | informatimago_commands/sources/commands/euronews.lisp | ;;;; -*- mode: lisp; coding:utf-8 -*-
;;;;******************************************************************************
;;;;FILE: eurnews
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: UNIX
;;;;USER-INTERFACE: UNIX
;;;;DESCRIPTION
;;;; Note: we compile on load only to check syntax errors faster.
;;;;USAGE
;;;; euronews --help
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2004-03-24 <PJB> Added user selectable language.
;;;; 2002-09-30 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; Copyright Pascal J. Bourguignon 2002 - 2004
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This script 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 library; see the file COPYING.LIB.
;;;; If not, write to the Free Software Foundation,
;;;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;;******************************************************************************
(defparameter *program-version* "1.0.2")
(defvar do-clear t "Whether clear screen actually works.")
(defun clear () (when do-clear (uiop:run-program "clear 2>/dev/null || true"
:force-shell t)))
(defvar language "ge" "The language selected for euronews.")
(defvar index 0)
(defvar last-index 0)
(defvar previous nil)
(defvar urls '())
(defvar length-urls 0)
(defvar played nil)
(defvar played-last nil)
(defvar menu-items '())
(defparameter +available-languages+ '(de fr en it es ru))
(defun language-to-euronews (lang)
(cond
((member lang '("ge" "de") :test 'string-equal) "ge")
((member lang '("es" "sp") :test 'string-equal) "sp")
((member lang +available-languages+ :test 'string-equal) lang)
(t nil)))
(defun stream-to-string-list (stream)
(loop with line = (read-line stream nil nil)
while line
collect line into result
do (setf line (read-line stream nil nil))
finally (return result)))
(defun played-indicator (index) (if (aref played index) "*" " "))
(defun played-last-indicator (index) (if (= index played-last) "#" " "))
(defun set-played (index rest)
(when rest (setf played-last index))
(setf (aref played index) rest))
(defun get-urls ()
(setf previous nil)
(setf urls
(loop for item in (sort
(loop for page in '( "accueil_info" "acceuil_eco" "euro" "lemag" "hitech" )
for new-urls = (stream-to-string-list
(uiop:run-program
(format nil "{ lynx -source 'http://www.euronews.net/create_html.php?page=~A&langue=~A'|tr '<' '\\012'|grep ramgen|sed -e 's/.*lien=\\(.*hostname\\).*/http:\\/\\/\\1/' ;}" page language)
:input nil
:output :stream
:wait nil
:force-shell t))
;;do (format t "new-urls=~S~%" new-urls)
append new-urls into all-urls
finally (return all-urls))
'string<=)
;;do (format t "item=~S~%" item)
when (and previous (string/= previous item))
collect item into all-urls
do (setf previous item)
finally (return all-urls)))
(setf length-urls (length urls)) ;;get-urls
(setf played (make-array (list length-urls) :initial-element nil))
(setf played-last -1)
(setf last-index 1))
(defun get-file-name (url)
(let ((question nil)
(slash nil))
(loop for index from (1- (length url)) downto 0
until slash
when (char= (char url index) (character '\?)) do (setf question index)
when (char= (char url index) (character '\/)) do (setf slash index)
finally (return (subseq url (1+ slash) question)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun main (arguments)
(dolist (arg arguments)
(setf language (language-to-euronews arg))
(unless language
(format t "~%usage:~%")
(format t " euronews [de|fr|en|it|es|po|ru]~%")
(exit ex-usage)))
(get-urls)
(loop while (and (/= 0 last-index) (<= last-index length-urls))
do
;; index is counted between 1 and (length urls)
;; index==0 means quit
;; urls list and played array are 0 indexed though.
(clear)
(setf menu-items
(loop :for index := 0 :then (1+ index)
:for url :in urls
:collect (format nil "~2D ~1A~1A ~34A"
(1+ index)
(played-indicator index)
(played-last-indicator index)
(get-file-name url))
:into menu-items
:finally (return menu-items)))
(loop :for line :from 0 :to 21
:do (loop :for menu := line :then (+ 22 menu)
:while (< menu (length menu-items))
:do (format t "~40A" (elt menu-items menu))
:finally (format t "~%")))
(format t "~%Number to play (0 to quit) or language ~S: "
+available-languages+)
(setf index (read))
(cond
((member index +available-languages+)
(setf language (language-to-euronews index))
(get-urls))
((numberp index)
(if (and (<= 0 index) (<= index length-urls))
(setf last-index index)
(progn
(format t "Invalid option!")
(setf last-index (- 0 last-index)))))
((eq 'n index)
(setf last-index (1+ (mod last-index length-urls))))
((eq 'p index)
(setf last-index (1+ (mod (- last-index 2) length-urls))))
((eq 'q index)
(setf last-index 0))
((eq 'r index)
;; replay - no change
)
(t
(format t "Invalid option!")
(setf last-index (- 0 last-index))))
(when (< 0 last-index)
(format *error-output* "~&Please update euronews with a new player!~%") ; TODO
#-(and) (uiop:run-program (format nil "/local/apps/RealPlayer8/realplay '~A' &"
(elt urls (1- last-index)))
:force-shell t)
(set-played (1- last-index) t)
(setf index (1+ (mod last-index length-urls)))
(return-from main 1) ; TODO
)
(setf last-index (abs last-index)))
ex-ok)
;;;; THE END ;;;;
| 7,572 | Common Lisp | .lisp | 165 | 34.181818 | 236 | 0.498038 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 9dc8432d7791e25d2155db3b369d9785dfcb550674f25c6383dcd1a69a42a713 | 12,342 | [
-1
] |
12,343 | cookie-diff.lisp | informatimago_commands/sources/commands/cookie-diff.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
(in-package "SCRIPT")
(command :use-systems (:split-sequence :cl-ppcre)
:use-packages ("COMMON-LISP"
"SCRIPT"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun key (cookie)
(map 'vector (function sxhash) cookie))
(defun read-cookies (pathname)
(let ((c (make-hash-table :test (function equalp))))
(dolist (cookie
(delete nil
(split-sequence "%"
(string-list-text-file-contents pathname)
:test (function string=)))
c)
(if (and (gethash (key cookie) c)
(not (equalp (gethash (key cookie) c) cookie)))
(format t "collision ~%~S~%~S~%" (gethash (key cookie) c) cookie)
(setf (gethash (key cookie) c) cookie)))))
(defun merge-cookies (a b)
(let ((results (make-hash-table :test (function equalp))))
(maphash (lambda (k c) (setf (gethash k results) c)) a)
(maphash (lambda (k c) (setf (gethash k results) c)) b)
results))
(defun write-cookies (pathname cookies)
(with-open-file (stream pathname
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(dolist (c cookies)
(write-line "%" stream)
(dolist (l c)
(write-line l stream)))
(write-line "%" stream)))
(defun main (arguments)
(let ((cookies (make-hash-table :test (function equalp))))
(dolist (path arguments)
(setf cookies (merge-cookies (read-cookies path) cookies)))
(write-cookies "/tmp/cookies" cookies))
ex-ok)
;;;; THE END ;;;;
| 1,821 | Common Lisp | .lisp | 44 | 31.477273 | 75 | 0.529977 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 799e02b27d92e6a7d73dcc023bde1d2cc13bd12786c737e9d402c42f7153399b | 12,343 | [
-1
] |
12,344 | hexbin.lisp | informatimago_commands/sources/commands/hexbin.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(defun main (arguments)
(declare (ignore arguments))
(setf *read-base* 16.)
(loop
:with buffer = (make-array 8 :element-type '(unsigned-byte 8) :fill-pointer 0 :adjustable t)
:for byte = (read *standard-input* nil nil)
:while byte
:do (vector-push-extend byte buffer (* 2 (length buffer)))
:finally (with-open-file (out "binary"
:direction :output
:element-type '(unsigned-byte 8)
:if-does-not-exist :create
:if-exists :supersede)
(write-sequence buffer out)
(format t "Written ~D bytes to ~S~%" (file-length out) (namestring out))))
ex-ok)
;;;; THE END ;;;;
| 795 | Common Lisp | .lisp | 18 | 32.222222 | 97 | 0.527132 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | aaef7348624d39cc5988739fa62755dff1deb30963fe3d28ecf3fa2620724983 | 12,344 | [
-1
] |
12,345 | cpcd.lisp | informatimago_commands/sources/commands/cpcd.lisp | ;; -*- mode:lisp;coding:utf-8 -*-
(defun main (arguments)
(declare (ignore arguments))
(error "Not implemented yet.")
ex-usage)
#|
(in-package "COMMON-LISP-USER")
(load (make-pathname :name "script" :type "lisp" :version NIL :case :local :defaults *load-pathname*))
(use-package "SCRIPT")
(defparameter *program-version* "1.0.2")
(defpackage "CPCD"
(:use "CL" "SCRIPT"))
(in-package "CPCD")
;; (redirecting-stdout-to-stderr (load #p"/etc/gentoo-init.lisp"))
;; (redirecting-stdout-to-stderr
;; (let ((*load-verbose* nil)
;; (*compile-verbose* nil))
;; (load (make-pathname :name ".clisprc" :type "lisp" :case :local
;; :defaults (user-homedir-pathname)))
;; ;; (setf *features* (delete :testing-script *features*))
;; ))
;; (redirecting-stdout-to-stderr (asdf:oos 'asdf:load-op :split-sequence)
;; (asdf:oos 'asdf:load-op :cl-ppcre))
;; default implementations
(defun eject ()
(format *query-io* "Please eject the CDROM, and type RET")
(read-line *query-io*)
(values))
(defun wait-cd (&optional (name ""))
(format *query-io* "Waiting for the CD ~S~%" name)
(format *query-io* "Please insert a CDROM, and type RET when it's ready.")
(read-line *query-io*)
(values))
;; system specific override:
(case (uname)
((:DARWIN)
(defun eject ()
(shell "drutil ~A" "eject"))
(defun wait-cd (&optional (name ""))
(loop
:do (if (not (shell "df | grep -q -s /dev/disk1"))
(loop-finish)
(progn
(format *query-io* "Waiting for the CD ~s~%" name)
(sleep 1))))))
((:linux)
(defun eject ()
(shell "eject"))))
(defun cpcd (cddir)
(wait-cd cddir)
(ensure-directories-exist (make-pathname :name "PROBE" :case :common :defaults cddir))
(let ((curdir (ext:cd)))
(unwind-protect
(progn
(ext:cd cddir)
(shell "cd-info > cddb.txt")
(shell "cdparanoia --query 2> cdparanoia.txt")
(shell "cdparanoia --output-wav --batch")
(eject)
(format *trace-output* "Compressing in background.~%")
(when (zerop (linux:fork))
(dolist (file (directory "*.wav"))
(when (not (shell "flac --silent -V --compression-level-8 ~S >> flac.log" (namestring file)))
(delete-file file)))
(ext:exit 0)))
(ext:cd curdir))))
(defparameter *start-index* nil)
(defparameter *directory-format* "cd~2,'0D")
(command :options (list
(option ("-b" "--batch") (start-index)
""
(setf *start-index* (parse-integer start-index)))
(option ("-f" "--directory-format") (format)
(setf *directory-format* format))
(option ("-o" "--one-shoot") (directory)
(cpcd directory)))
#|
if [ "$start" != '' ] ; then
case "$start" in
*[^0-9]*)
printf "Invalid start index, it must be an integer, not '%s'\n" "$start"
usage
exit 1
;;
esac
index=$start
while true ; do
cpcd "$(printf "$format" "$index")"
start=$(( $index + 1 ))
done
else
cpcd "${dir}"
fi
|#
(defun main (arguments)
(parse-options arguments)
ex-ok)
|#
;;;; THE END ;;;;
| 3,232 | Common Lisp | .lisp | 99 | 27.59596 | 108 | 0.582099 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 705fa8df5dd24375fc794d515a8a3557d93d81ea0a9595dd827a98d85bb0d33c | 12,345 | [
-1
] |
12,346 | clean-name.lisp | informatimago_commands/sources/commands/clean-name.lisp | ;; -*- mode:lisp;coding:utf-8 -*-
;; Replaces any sequences of non alphanumeric or dot character in the
;; arguments by a single dash.
(defun split-string-if (predicate string &key remove-empty-subseqs)
(declare (ignore remove-empty-subseqs))
"
NOTE: current implementation only accepts as separators
a string containing literal characters.
"
(let ((chunks '())
(position 0)
(nextpos 0)
(strlen (length string)))
(loop :while (< position strlen) :do
(loop :while (and (< nextpos strlen)
(not (funcall predicate (aref string nextpos)))) :do
(incf nextpos))
(push (subseq string position nextpos) chunks)
(setf position (1+ nextpos)
nextpos position))
(nreverse chunks)))
(defun split-string (separators string &key remove-empty-subseqs)
(split-string-if (lambda (ch) (find ch separators)) string
:remove-empty-subseqs remove-empty-subseqs))
(defparameter *character-foldings*
'(("A" "ÀÁÂÃÄÅ") ("AE" "Æ") ("C" "Ç") ("E" "ÈÉÊË") ("I" "ÌÍÎÏ")
("ETH" "Ð") ("N" "Ñ") ("O" "ÒÓÔÕÖØ") ("U" "ÙÚÛÜ") ("Y" "Ý")
("TH" "Þ") ("ss" "ß") ("a" "àáâãäå") ("ae" "æ") ("c" "ç")
("e" "èéêë") ("i" "ìíîï") ("eth" "ð") ("n" "ñ") ("o" "òóôõöø")
("u" "ùúûü") ("u" "ýÿ") ("th" "þ")
("-lt-" "<")
("-gt-" ">")
("-exclaim-" "!")
("-question-" "?")
("-percent-" "%")))
(defun character-folding (character)
(car (member (character character) *character-foldings*
:test (function position) :key (function second))))
(defun character-fold (character)
"
RETURN: A string containing the character without accent
(for accented characters), or a pure ASCII form of the character.
"
(car (character-folding character)))
(defun string-fold (string)
(apply (function concatenate) 'string
(map 'list (lambda (ch) (let ((conv (character-folding ch)))
(if conv
(first conv)
(list ch))))
string)))
(defun clean-name (name)
(format nil "~{~A~^-~}"
(split-string-if (lambda (char) (not (or (alphanumericp char)
(char= char #\/)
(char= char #\.))))
(string-trim "-" (string-fold (string-downcase name)))
:remove-empty-subseqs t)))
(defparameter *diacritics* '((#x80
"AÀ" "EÈ" "IÌ" "OÒ" "UÙ"
"aà" "eè" "iì" "oò" "uù")
(#x81
"AÁ" "EÉ" "IÍ" "OÓ" "UÜ" "YÝ"
"aá" "eé" "ií" "oó" "uü" "yý")
(#x82
"AÂ" "EÊ" "IÎ" "OÔ" "UÛ"
"aâ" "eê" "iî" "oô" "uû")
(#x88
"AÄ" "EË" "IÏ" "OÖ" "UÜ"
"aä" "eë" "iï" "oö" "uü")
(#xa7
"CÇ" "cç")))
(defun combine-diacritic (ch diacritic)
(let ((dia (find ch diacritic :key (lambda (dia) (aref dia 0)))))
(if dia
(aref dia 1)
ch)))
(defun translate-diacritics (text)
(let ((escape (code-char #xcc)))
(if (find escape text)
(let ((out (make-array (length text) :fill-pointer 0 :element-type 'character)))
(loop :with state = :normal
:for ch :across text
:do (case state
((:normal) (if (char= escape ch)
(setf state :escaped)
(vector-push ch out)))
((:escaped) (let ((diacritic (cdr (assoc (char-code ch) *diacritics*))))
(when diacritic
(setf (aref out (1- (length out)))
(combine-diacritic (aref out (1- (length out))) diacritic)))
(setf state :normal)))))
out)
text)))
(defun escape (string)
(with-output-to-string (*standard-output*)
(loop :for ch :across string
:initially (princ "'")
:do (if (char= #\' ch)
(princ "'\\''")
(princ ch))
:finally (princ "'"))))
(defun process-name (name)
(write-line (clean-name (translate-diacritics name))))
(defun process-item (path)
(let* ((components (split-string "/" path :remove-empty-subseqs t))
(new-path (format nil "~{~A~^/~}"
(append (butlast components)
(list (clean-name
(translate-diacritics
(string-trim "- ." (first (last components))))))))))
(unless (string-equal path new-path)
(format t "mv -v ~A ~A~%" (escape path) (escape new-path)))))
(defun process-items (path)
(with-open-file (input path)
(loop
:for item-path := (read-line input nil nil)
:while item-path
:do (process-item item-path))))
;;;;--------------------------------------------------------------------
(defparameter *program-name* "clean-name"
"Name of the program.")
(defun print-usage ()
(format t "~%~A usage:~%~
~% ~:*~A [-f|--list-file file]... [name...]~2%"
*program-name*))
;;;;--------------------------------------------------------------------
(defun main (args)
(let ((files nil)
(names '()))
(loop :while args
:do (let ((arg (pop args)))
(cond
((member arg '("-f" "--list-file") :test (function string-equal))
(push (pop args) files))
((member arg '("-h" "--help") :test (function string-equal))
(print-usage)
(return-from main ex-ok))
((string= arg "-" :end1 (min (length arg) 1))
(error "Unknown option: ~A" arg))
(t (push arg names)))))
(when (and (null files) (null names))
(print-usage)
(return-from main ex-usage))
(dolist (file files)
(process-items file))
(dolist (name names)
(process-name name))
ex-ok))
;;;; THE END ;;;;
| 6,600 | Common Lisp | .lisp | 150 | 30.106667 | 104 | 0.455179 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | f267f2c9318b3c67618f970f5893bfcb27250e87a85d25917b826981bba54338 | 12,346 | [
-1
] |
12,347 | sleep-schedule.lisp | informatimago_commands/sources/commands/sleep-schedule.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(defvar *schedule-file*)
(defconstant 24h (* 24 60 60))
(defun days (d) (* d 24h))
(defun date- (d1 d2) (- d1 d2))
(defun date= (d1 d2) (= d1 d2))
(defun date>= (d1 d2) (>= d1 d2))
(defun date<= (d1 d2) (<= d1 d2))
(defun sunday-p (dt)
(= 6 (nth-value 6 (decode-universal-time dt))))
(defstruct (entry (:type list))
switch year month day hour minute second zone comment)
(defun entry-universal-time (entry)
(encode-universal-time (entry-second entry)
(entry-minute entry)
(entry-hour entry)
(entry-day entry)
(entry-month entry)
(entry-year entry)
(entry-zone entry)))
(defun entry-time (entry) (mod (entry-universal-time entry) 24h))
(defun entry-date (entry) (* (truncate (entry-universal-time entry) 24h) 24h))
(defun last-date (schedule)
(reduce (function max) (mapcar (function entry-date) schedule)))
(defun print-schedule (schedule &key (stream *standard-output*)
(height 72) (days nil) (append-date nil))
"
DO: Prints a graph HEIGHT characters wide, for the whole schedule
if DAYS is nil, or only for the DAYS last days.
"
(when days
(setf schedule (remove (date- (last-date schedule) (days days))
schedule
:key (function entry-date)
:test (function date>=))))
(loop
:initially (format t "~%~VA~VA~VA~VA~%"
(/ height 4) "UTC:" (/ height 4) "6H"
(/ height 4) "12H" (/ height 4) "18H")
:with line = (make-string height)
:for date = (and schedule (entry-date (car schedule))) then (+ date 24h)
:while schedule
:do (loop
:initially (fill line #\ )
:with start = 0
:with next-date = (entry-date (car schedule))
:for sleep-p = (if schedule
(eq :stop (entry-switch (car schedule)))
(not sleep-p))
:while (and schedule
(date= date next-date)
(date= next-date (entry-date (car schedule))))
:do (let ((end (round (/ (* height (entry-time (car schedule)))
24h))))
;; (print (list (car schedule) start end sleep-p)) (terpri)
(fill line (if sleep-p #\Z #\ ) :start start :end end)
(setf start end)
(pop schedule))
:finally (progn
;;(setf sleep-p (not sleep-p))
;; (print (list start sleep-p)) (terpri)
(fill line (if sleep-p #\Z #\ ) :start start)
(let ((mark (if (sunday-p date) #\+ #\|)))
(setf (aref line (round (* 1/4 height))) mark
(aref line (round (* 2/4 height))) mark
(aref line (round (* 3/4 height))) mark))
(princ line stream)
(when append-date
(multiple-value-bind (sec min hou day mon yea)
(decode-universal-time date)
(declare (ignore sec min hou))
(format stream "~4,'0D~2,'0D~2,'0D" yea mon day)))
(terpri stream)))
:finally (terpri stream)))
(defun read-schedule (file)
(sort (with-open-file (input file)
(loop
:for entry = (read input nil nil)
:while entry
:collect entry))
(function <=)
:key (function entry-universal-time)))
(defun square (x) (* x x))
(defun sum (sequence &key (key (function identity)))
(if (listp sequence)
(loop :for item :in sequence :sum (funcall key item))
(loop :for item :across sequence :sum (funcall key item))))
(defun mean (sequence &key (key (function identity)))
(/ (sum sequence :key key) (length sequence)))
(defun variance (sequence &key (key (function identity)))
(let ((mean (mean sequence :key key)))
(/ (sum sequence :key (lambda (item) (square (- (funcall key item) mean))))
(length sequence))))
(defun ecart-type (sequence &key (key (function identity)))
(sqrt (variance sequence :key key)))
(defun covariance (sequence &key (x (function first)) (y (function second)))
(let ((mean-x (mean sequence :key x))
(mean-y (mean sequence :key y)))
(/ (sum sequence :key (lambda (item) (* (- (funcall x item) mean-x)
(- (funcall y item) mean-y))))
(length sequence))))
(defun regression-lineaire
(sequence &key (x (function first)) (y (function second)))
(let ((cov (covariance sequence :x x :y y))
(var (variance sequence :key x))
(mean-x (mean sequence :key x))
(mean-y (mean sequence :key y)))
(list (/ cov var) (- mean-y (* mean-x (/ cov var))))))
#||
(mapcar
(lambda (x) (coerce x 'float))
(regression-lineaire
(mapcar
(lambda (time) (cons (truncate (cdr time) 24h) (mod (cdr time) 24h)))
(delete :stop
(mapcar
(lambda (sched) (cons (car sched) (entry-universal-time sched)))
(last (read-schedule *schedule-file*) (* 8 2)))
:key (function car)))
:x (function car) :y (function cdr)))
||#
(defun main (arguments)
(declare (ignore arguments))
(setf *schedule-file* (merge-pathnames "./.sleep-schedule" (user-homedir-pathname) nil))
(print-schedule (read-schedule *schedule-file*) :append-date t)
(let* ((schedule (mapcar
(lambda (sched) (cons (car sched) (entry-universal-time sched)))
(read-schedule *schedule-file*)))
(times (mapcar (function cdr) schedule))
(start (truncate (apply (function min) times) 24h))
(end (1+ (truncate (apply (function max) times) 24h))))
(print `(day length
,@(mapcar
(lambda (x) (/ x 60.0 60.0))
((lambda (s)
(list (/ (reduce (function +) s) (length s))
(apply (function min) s)
(apply (function max) s)))
((lambda (x) (mapcar (function -) (cdr x) x))
(mapcar (function cdr)
(delete :stop schedule :key (function car))))))))
(print `(sleep time
,@((lambda (s)
(list (/ (reduce (function +) s) (- end start))
(apply (function min) s)
(apply (function max) s)))
(mapcar
(lambda (x) (/ x 60.0 60.0))
(loop
:for (s e) :on times :by (function cddr)
:when e :collect (- e s)))))))
ex-ok)
;;;; THE END ;;;;
| 7,093 | Common Lisp | .lisp | 153 | 33.464052 | 90 | 0.501882 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | bc27bfc80352509c8a5c9101a5efa28c7834684bf5c0f3130cc808c08636a8b0 | 12,347 | [
-1
] |
12,348 | when.lisp | informatimago_commands/sources/commands/when.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: When
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Prints a random reason when you know you've been hacking for too long.
;;;;
;;;;SYNOPSIS
;;;; When do you know you have been hacking for too long?
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-11-22 <PJB> Added this header.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2010
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(defparameter *reasons*
#(
"You know you've been hacking too long when you suddenly realize that
\"Timberland - The Boot Company\" does NOT repair the computers which
do not want to boot."
"You know you've been hacking too long when you see an annoying ad on
TV for a product priced at 139.99 and you wonder if you can stop this
TV SPAM, tracking down the perpetrators by doing a 'whois 139.99.0.0\"
and seeing who owns that network block."
"You know you've been hacking too long when you made it just in time
to the bus (running) 'cos you were relying on the fact that it's
almost always late, except of course his time, and you start thinking
about how far away you should rig a sensor somewhere up the road to
have your scheduler email you \"the bus is here\" just-in-time for you
to leave...."
"You know you've been hacking too long when you can't remember how to
format a video tape..."
"You know you've been hacking too long when it takes you several tries
to set your alarm clock because you expect it to count in hex (or
maybe octal)."
"You know you've been hacking too long when you actually consider
building an alarm clock that uses hex."
"You know you've been hacking too long when you actually build an
alarm clock that uses hex."
"You know you've been hacking too long when on an ethnic studies
survey, a programming language beats out your native natural language
for language spoken most frequently at home."
"You know you've been hacking too long when you consider attaching a
punch reader to one of your home machines just for old times' sake."
"You know you've been hacking too long when it already has a punch
reader attached...as an original part."
"You know you've been hacking too long when you name your computers
after your relatives."
"You know you've been hacking too long when you name your relatives
after your computers."
"You know you've been hacking too long when conversations with your
friends are stack-based, with actual verbal cues of \"push\", \"pop\",
\"interrupt\", and \"interrupt return\" being commonly used."
"You know you've been hacking too long when you remember anything
involving computers before Bill \"the Dark Lord\" Gates was involved."
"You know you've been hacking too long when you design new
architectures and implement them as virtual machines frequently and
just for fun (am I the only one who does this?)."
"You know you've been hacking too long when you talk to your computers
more frequently than you talk to your human companions."
"You know you've been hacking too long when you don't see what is
unusual about that previous entry (you talk to your computers more
frequently than you talk to your human companions)."
"You know you've been hacking too long when you post a YKYBHTLW
message with more than three entries."
"You know you've been hacking too long when you see the subject line:
\"For Sale: Alfa 164 $18000\" in a forsale group, and think \"at least
he should know how to spell ALPHA when asking for such a ridiculous
price\". And then find out that \"Alfa\" is indeed spelled completely
right."
"You know you've been hacking too long when you get more root
passwords than dates."
"You know you've been hacking too long when you're more excited about
getting root passwords than dates."
"You know you've been hacking too long when you read a novel and, at
the bottom of the page, see the number \"29\" and think \"hmmm ---
more than 1/4 of the book already gone. Can't be! Less must have made
a mistake calculating the percentage\"."
"You know you've been hacking too long when you spend half an hour
trying to find a group of files in your current project that total
_exactly_ one million bytes. Or you do it, but then someone points out
that you are 48576 bytes over and you don't know what they are talking
about..."
"You know you've been hacking too long when \"By the time I get to
Phoenix,\" comes on the radio, and your reaction is, \"Who is still
running PHOENIX?"
"You Know You've Been Hacking Too Long With The Wrong People
When... Today at work I needed to edit a line of code, and rather than
delete or overwrite the ';' at the end and type another one when I
finished, I hit the insert key instead. I then wondered (from a
purely metaphysical sense) whether the ';' I ended with could be
considered the same one I started with or not. I shared my thoughts
with my cow orkers: one just snorted and went back to work, while the
other used the oppertunity to launch into a discussion involving
faster-than-light travel through alternate dimensions. "
"You haven't been hacking very long when you are still excited about
getting root passwords. You may have been hacking a little longer when
you *don't* want to get the root password, because you want to be safe
from being held responsible for the system administrator's mistakes."
"You haven't been hacking very long when you see a cigarette machine
in a Pub which has the ammount of time it has been switched on for,
and you think '17 hours 22 minutes, that's not a bad uptime for a
cigarette machine'."
"You haven't been hacking very long when you see a sign that says
\"Disabled Toilet\", and wonder which bits you have to set to
re-enable it."
"You haven't been hacking very long when you have a friend called
\"Dot Atkins\" and want to spell her name .@kins."
"You know you've been hacking too long when you tell people at work
that you have a 7-year-old Sun at home, and they correctly parse that
as \"workstation\", not \"offspring\"."
"You know you've been hacking too long when looking at telephones,
your wife says \"I like this one\"; and you answer \"Yes, it has the
best form factor\", then have to think to realize why she was staring
at you... "
))
(defun print-usage ()
(princ "
When usage:
When do you know you have been hacking too long?
"))
(defun main (arguments)
(setf *random-state* (make-random-state t))
(if (or (member "-h" arguments :test (function string-equal))
(member "--help" arguments :test (function string-equal)))
(print-usage)
(let ((reason (aref *reasons* (random (length *reasons*)))))
(format t "~%~A~2%" reason)))
(finish-output)
ex-ok)
;;;; THE END ;;;;
| 7,860 | Common Lisp | .lisp | 153 | 48.986928 | 78 | 0.720563 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 26f5debe87a0f6277eb440eb756e110fdc6439153698ca946e34860b09c75db0 | 12,348 | [
-1
] |
12,349 | script-test.lisp | informatimago_commands/sources/commands/script-test.lisp | ;; -*- mode:lisp; coding:utf-8 -*-
(command :use-systems (:cffi))
(cffi:defcvar (environ "environ") :pointer)
(defun environment ()
(loop
:for i :from 0
:for s := (print (cffi:mem-aref environ :pointer i))
:until (cffi:null-pointer-p s)
:collect (cffi:foreign-string-to-lisp s)))
;;;;--------------------------------------------------------------------
(defun main (arguments)
(declare (ignore arguments))
;; (apropos "*" "UIOP")
;; (print uiop:*COMMAND-LINE-ARGUMENTS*)
(write-line "Environment:") (finish-output)
(dolist (e (environment))
(write-line e))
(write-line "Done.") (finish-output)
;; (apropos "*" "CL-LAUNCH")
(dolist (v '("CL_LAUNCH_FILE" "PROG" "PROGBASE"))
(format t "~20A = ~S~%" v (uiop:getenv v)))
(let ((*package* (make-package "foo" :use '())))
(dolist (f (sort (copy-list *features*) (function string<)))
(print f)))
ex-ok)
;;;; THE END ;;;;
| 929 | Common Lisp | .lisp | 26 | 32.230769 | 72 | 0.565996 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | c77db469100d027017d54d5e2fbbc156c18205545b6078c6e96a2adbe3fb5334 | 12,349 | [
-1
] |
12,350 | text.lisp | informatimago_commands/sources/commands/text.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;***************************************************************************
;;;;FILE: text
;;;;LANGUAGE: Common Lisp (clisp)
;;;;SYSTEM: UNIX
;;;;USER-INTERFACE: UNIX
;;;;DESCRIPTION
;;;; This script filters out non ASCII characters.
;;; The only control code that is left is the newline.
;;;;USAGE
;;;; text < bytes > text
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2009-12-15 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; Copyright Pascal J. Bourguignon 2009 - 2009
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This script 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 library; see the file COPYING.LIB.
;;;; If not, write to the Free Software Foundation,
;;;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;;***************************************************************************
(defun main (arguments)
(declare (ignore arguments))
(unwind-protect
(progn
#+clisp
(setf (stream-element-type *standard-input*) '(unsigned-byte 8)
(stream-element-type *standard-output*) '(unsigned-byte 8))
(loop
:with inbuffer = (make-array 65536 :element-type '(unsigned-byte 8) :initial-element 0)
:with outbuffer = (make-array 65536 :element-type '(unsigned-byte 8) :initial-element 0
:fill-pointer 0)
:do (let ((pos (read-sequence inbuffer *standard-input*)))
(when (zerop pos) (loop-finish))
(setf (fill-pointer outbuffer) (array-dimension outbuffer 0))
(loop
:with j := 0
:for i :from 0 :below pos
:for code := (aref inbuffer i)
:do (cond
((= code 10) (setf (aref outbuffer j) code) (incf j))
((< code 32))
((<= 127 code))
(t (setf (aref outbuffer j) code) (incf j)))
:finally (setf (fill-pointer outbuffer) j))
(write-sequence outbuffer *standard-output*))))
#+clisp
(setf (stream-element-type *standard-input*) 'character
(stream-element-type *standard-output*) 'character))
ex-ok)
| 2,887 | Common Lisp | .lisp | 63 | 38.190476 | 99 | 0.545004 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 08d2f0e94ad36b110a24d46c54ae8c8f267b5e60884b2e9f8d39771373b8cf2e | 12,350 | [
-1
] |
12,351 | rotate.lisp | informatimago_commands/sources/commands/rotate.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;*****************************************************************************
;;;;FILE: rotate
;;;;LANGUAGE: common lisp (clisp)
;;;;SYSTEM: UNIX
;;;;USER-INTERFACE: CLI
;;;;DESCRIPTION
;;;; This script rotates lines vs. columns.
;;;;USAGE
;;;;
;;;; rotate [-90|-180|-270|-0] < lines > columns
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2016-01-13 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; Copyright Pascal J. Bourguignon 2015 - 2015
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This script 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 library; see the file COPYING.LIB.
;;;; If not, write to the Free Software Foundation,
;;;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;;*****************************************************************************
(defparameter *program-version* "0.0.0")
(defun split-string (string &optional (separators " ") (remove-empty nil))
"
STRING: A sequence.
SEPARATOR: A sequence.
RETURN: A list of subsequence of STRING, split upon any element of SEPARATORS.
Separators are compared to elements of the STRING with EQL.
NOTE: It's actually a simple split-sequence now.
EXAMPLES: (split-string '(1 2 0 3 4 5 0 6 7 8 0 9) '(0))
--> ((1 2) (3 4 5) (6 7 8) (9))
(split-string #(1 2 0 3 4 5 0 6 7 8 0 9) #(0))
--> (#(1 2) #(3 4 5) #(6 7 8) #(9))
(split-string \"1 2 0 3 4 5 0 6 7 8\" '(#\space #\0))
--> (\"1\" \"2\" \"\" \"\" \"3\" \"4\" \"5\" \"\" \"\" \"6\" \"7\" \"8\")
"
(loop
:with strlen = (length string)
:for position = 0 :then (1+ nextpos)
:for nextpos = (position-if (lambda (e) (find e separators)) string :start position)
:unless (and remove-empty
(or (and (= position strlen) (null nextpos ))
(eql position nextpos)))
:collect (subseq string position nextpos)
:while (and nextpos (< position strlen))))
(defun stream-to-string-list (stream)
"
RETURN: the list of lines collected from stream.
"
(typecase stream
(stream (loop
:for line = (read-line stream nil nil)
:while line :collect line))
(string (split-string stream (format nil "~C" #\newline)))
(otherwise nil)))
(defun string-list-text-file-contents (path &key (if-does-not-exist :error)
(external-format :default))
"
IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value that
is returned instead of the content of the file if
it doesn't exist.
RETURN: The list of lines collected from the file, or the
value of IF-DOES-NOT-EXIST when not :ERROR or
:CREATE and the file doesn't exist.
"
(with-open-file (in path
:element-type 'character
:if-does-not-exist if-does-not-exist
:external-format external-format)
(stream-to-string-list in)))
(defun nudge-displaced-vector (displaced-vector
&key
(start nil startp)
(start+ nil start+p)
(start- nil start-p)
(end nil endp)
(end+ nil end+p)
(end- nil end-p)
(length nil lengthp)
(length+ nil length+p)
(length- nil length-p)
(fill-pointer nil))
"
DO: Changes the displacement of the DISPLACED-VECTOR.
START: Indicates the new absolute displacement offset.
START+: Indicates an increment of the displacement offset.
START-: Indicates a decrement of the displacement offset.
END: Indicates the new absolute end of the DISPLACED-VECTOR.
END+: Indicates an increment of the DISPLACED-VECTOR end.
END-: Indicates a decrement of the DISPLACED-VECTOR end.
LENGTH: Indicates the new absolute length of the DISPLACED-VECTOR.
LENGTH+: Indicates an increment of the length of the DISPLACED-VECTOR.
LENGTH-: Indicates a decrement of the length of the DISPLACED-VECTOR.
FILL-POINTER: Indicates the new fill pointer for the DISPLACED-VECTOR.
NOTES: START, START+ and START- are mutually exclusive.
END, END+, END-, LENGTH, LENGTH+ and LENGTH- are mutually exclusive.
START and END are expressed as indices in the displaced-to array.
RETURN: The adjusted array.
EXAMPLE: (let* ((s #(a door a window a big hole and a bucket))
(v (displaced-vector s 0 3 t)))
(show v)
(show (nudge-displaced-vector v :end+ 1))
(show (nudge-displaced-vector v :fill-pointer 2))
(show (nudge-displaced-vector v :start+ 3 :end+ 3))
(show (nudge-displaced-vector v :start- 1 :end- 1))
(show (nudge-displaced-vector v :fill-pointer 1)))
prints:
v = #(a door a)
(nudge-displaced-vector v :end+ 1) = #(a door a)
(nudge-displaced-vector v :fill-pointer 2) = #(a door)
(nudge-displaced-vector v :start+ 3 :end+ 3) = #(window a)
(nudge-displaced-vector v :start- 1 :end- 1) = #(a window)
(nudge-displaced-vector v :fill-pointer 1) = #(a)
#(a)
"
;; (print (list :start start :start+ start+ :start- start-
;; :end end :end+ end+ :end- end-
;; :length length :length+ length+ :length- length-
;; :fill-pointer fill-pointer))
(assert (<= (count-if (function identity) (list startp start+p start-p)) 1))
(assert (<= (count-if (function identity) (list endp end+p end-p
lengthp length+p length-p)) 1))
(multiple-value-bind (vector old-start) (array-displacement displaced-vector)
(let* ((old-length (array-dimension displaced-vector 0))
(old-end (+ old-start old-length))
(new-start (cond (startp start)
(start+p (+ old-start start+))
(start-p (- old-start start-))
(t old-start)))
(new-length (cond (endp (- end new-start))
(end+p (- (+ old-end end+) new-start))
(end-p (- (- old-end end-) new-start))
(lengthp length)
(length+p (+ old-length length+))
(length-p (- old-length length-))
(t (- old-end new-start))))
(fill-pointer (if (eq 't fill-pointer)
new-length
fill-pointer)))
;; (let ((*print-array* nil))
;; (print (list 'adjust-array
;; displaced-vector
;; (list new-length)
;; :element-type (array-element-type vector)
;; :fill-pointer (and (array-has-fill-pointer-p displaced-vector)
;; fill-pointer)
;; :displaced-to vector
;; :displaced-index-offset new-start)))
(adjust-array
displaced-vector
(list new-length)
:element-type (array-element-type vector)
:fill-pointer (and (array-has-fill-pointer-p displaced-vector)
fill-pointer)
:displaced-to vector
:displaced-index-offset new-start))))
(defun slurp (input)
(let* ((lines (stream-to-string-list input))
(height (length lines))
(width (reduce (function max) lines :key (function length)))
(matrix (make-array (list height width) :element-type 'character :initial-element #\space)))
(loop
:with row := (make-array (list width) :element-type 'character :displaced-to matrix :displaced-index-offset 0)
:for line :in lines
:for y :from 0
:do (replace row line)
(unless (= (1+ y) height)
(setf row (nudge-displaced-vector row :start+ width :end+ width))))
matrix))
(defun barf (output matrix)
(let* ((height (array-dimension matrix 0))
(width (array-dimension matrix 1)))
(loop
:with row := (make-array (list width) :element-type 'character :displaced-to matrix :displaced-index-offset 0 :fill-pointer width)
:for y :below height
:for length := (position #\space row :from-end t :test-not (function char=))
:do (setf (fill-pointer row) (or length (length row)))
(write-line row output)
(unless (= (1+ y) height)
(setf row (nudge-displaced-vector row :start+ width :end+ width :fill-pointer width))))
matrix))
(defun rotate-matrix (matrix)
(let ((rotated (make-array (reverse (array-dimensions matrix))
:element-type (array-element-type matrix)))
(width (array-dimension matrix 0))
(height (array-dimension matrix 1)))
(loop
:for i :below width
:do (loop
:for j :below height
:do (setf (aref rotated (- height j 1) i) (aref matrix i j))))
rotated))
(defun rotate (input output rotation)
(let ((matrix (slurp input)))
(case rotation
((0) (barf output matrix))
((-90) (barf output (rotate-matrix matrix)))
((-180) (barf output (rotate-matrix (rotate-matrix matrix))))
((-270) (barf output (rotate-matrix (rotate-matrix (rotate-matrix matrix))))))))
(defun usage ()
(format t "~A version ~A~%" *program-name* *program-version*)
(format t "~A usage:~2%" *program-name*)
(format t "~T~A rotate [-90|-180|-270|-0] < lines > columns~%" *program-name*))
(defun main (options)
(handler-case
(cond
((null options)
(rotate *standard-input* *standard-output* -90)
ex-ok)
((or (member "-h" options :test (function string=))
(member "--help" options :test (function string=)))
(usage)
ex-ok)
((cdr options)
(format *error-output* "~A: ~A~%" *program-name* "Too many options.")
(usage)
ex-usage)
(t
(let ((rotation (parse-integer (car options))))
(check-type rotation (member 0 -90 -180 -270))
(rotate *standard-input* *standard-output* rotation))
ex-ok))
(error (err)
(format *error-output* "~A: ~A~%" *program-name* err)
ex-software)))
;;;; THE END ;;;;
| 11,572 | Common Lisp | .lisp | 240 | 38.204167 | 136 | 0.536115 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 793517a51188e22040ee03b9690d4755c70f8f8a6c3f2e17344615064a554431 | 12,351 | [
-1
] |
12,352 | batch-emerge.lisp | informatimago_commands/sources/commands/batch-emerge.lisp | ;; -*- mode:lisp;coding:utf-8 -*-
;; emerge all the packages specified in /home/pjb/portage-packages.txt, in batch(1).
(defun main (arguments)
(declare (ignore arguments))
#-(or ccl sbcl) (error "This command can only work when compiled with ccl or sbcl.")
#+(or ccl sbcl)
(let ((rt (copy-readtable nil)))
(setf (readtable-case rt) :preserve)
(with-open-file (f (merge-pathnames "portage-packages.txt"
(user-homedir-pathname)))
(let ((*readtable* rt))
(loop
:for package = (read f nil nil)
:while package
:do #+ccl (let ((batch (uiop:run-program "batch" :input :stream :output :stream :wait nil)))
(with-open-stream (input (ccl:external-process-input-stream batch))
(format input "emerge ~A~%" package)))
#+sbcl (uiop:run-program (format nil "bash -c 'echo emerge ~A|batch'" package) :wait nil)))))
ex-ok)
;;;; THE END ;;;;
| 989 | Common Lisp | .lisp | 20 | 40.25 | 107 | 0.58635 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 22205348d71f0fe5b5348b971c14e8674f53267bf38c57733db190f465d5b43c | 12,352 | [
-1
] |
12,353 | add-cookie.lisp | informatimago_commands/sources/commands/add-cookie.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: addcookie
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Add a cookie to a cookie file.
;;;;
;;;;SYNOPSIS
;;;; addcookie [cookie-file] < cookie-text
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-11-22 <PJB> Added this header.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2010
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(defparameter *cookie-file* "/data/cookies/bopcs.cookies")
(defun main (arguments)
(case (length arguments)
((0))
((1) (setf *cookie-file* (first arguments)))
(otherwise
(format t "~&Usage: ~A [ cookie-file ] < cookie-data ~&"
(file-namestring *load-pathname*))
(format t "Default cookie file is ~A~&"
*cookie-file*)
(script:exit 1)))
(handler-case
(with-open-file (out *cookie-file*
:direction :output
:if-does-not-exist :error
:if-exists :append)
(loop
:for line = (read-line *standard-input* nil nil)
:while line
:do (format out "~A~%" line)
:finally (format out "~%#~%")))
(error (err) (format t "~%~A~%" err)))
ex-ok)
;;;; THE END ;;;;
| 2,304 | Common Lisp | .lisp | 61 | 33.42623 | 78 | 0.556102 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d6a5b100c5ff05755175531b84681deb20698c95703a45dc44dbfa47bd53daef | 12,353 | [
-1
] |
12,354 | split-dir.lisp | informatimago_commands/sources/commands/split-dir.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: split-dir
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Make hard-links from a source directory to a sequence of destination
;;;; directories such as the disk usage of each destination directory is
;;;; less than a maximum size.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2005-09-00 <PJB> Merged spread-files with split-dir.
;;;; 2004-11-15 <PJB> Created split-dir
;;;; 2003-10-22 <PJB> Created spread-files
;;;;BUGS
;;;; Lack an option to use symbolic links, or to copy instead of hard links.
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 2004 - 2004
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;****************************************************************************
(defun print-help ()
(format t "~&~A usage:~%" *program-name*)
(format t " ~A [-h|--help]~%" *program-name*)
(format t " ~A [--preview] max-size src-dir dst-dir~%" *program-name*)
(format t "max-size :== number ['K'|'M'|'G']~%"))
(defun disk-usage (dir-upath)
(let ((directories
(append (directory (concatenate 'string dir-upath "/*"))
(directory (concatenate 'string dir-upath "/*/")))))
(unless directories
(error "Cannot find files or directories in ~A/" dir-upath))
(with-input-from-string (in (uiop:run-program
(list* "du" "-s" "-k" directories)
:input nil
:output :string
:wait nil))
(loop
with result = '()
for line = (read-line in nil nil)
while line
do (let ((tab (position (code-char 9) line)))
(when tab
(push (cons (subseq line (1+ tab))
(parse-integer (subseq line 0 tab))) result)))
finally (return result)))))
(defun factor (string)
(let ((pos (position (char string (1- (length string))) "KMGkmg")))
(if pos
(expt 1024 (mod pos 3))
1)))
(defun mantissa (string)
(parse-integer
string
:junk-allowed nil
:end (when (position (char string (1- (length string))) "KMGkmg")
(1- (length string)))))
(defun test-mantissa-factor ()
(dolist (test '(("123" 123 1)
("123K" 123 1)
("123k" 123 1)
("123M" 123 1024)
("123m" 123 1024)
("123G" 123 1048576)
("123g" 123 1048576)
("123x" :error)
("123 k" 123 1)
("x" :error)
("k" :error)
))
(let ((m nil) (f nil))
(handler-case
(setf m (mantissa (first test))
f (factor (first test)))
(error () (setf m :error f :error)))
(if (eq :error (second test))
(assert (eq :error m))
(assert (and (= m (second test))
(= f (third test))))))))
(defun split-groups (list max-size)
(do ((list list (cdr list))
(groups '())
(chunk '())
(chunk-size 0))
((null list)
(when chunk (push (nreverse chunk) groups))
(nreverse groups))
(when (< max-size (+ chunk-size (cdr (car list))))
(push (nreverse chunk) groups)
(setf chunk '()
chunk-size 0))
(push (car list) chunk)
(incf chunk-size (cdr (car list)))))
(defun hardlink (src dst) (uiop:run-program "ln" :arguments (list "-f" src dst)))
(defun symlink (src dst) (uiop:run-program "ln"
:arguments (list "-f" "-s" src dst)))
(defun move (src dst) (uiop:run-program "mv" :arguments (list src dst)))
(defun contains-option-p (arg options) (member arg options :test (function string=)))
(defun main (arguments)
(let ((max-size nil)
(src-dir nil)
(dst-dir nil)
(preview nil)
(collate (function symlink)))
(dolist (arg arguments)
(cond
((contains-option-p arg '("-h" "--help")) (print-help) (return-from main))
((contains-option-p arg '("-p" "--preview")) (setf preview t))
((contains-option-p arg '("-L" "--symlink")) (setf collate (function symlink)))
((contains-option-p arg '("-M" "--move")) (setf collate (function move)))
((contains-option-p arg '("-H" "--hardlink")) (setf collate (function hardlink)))
((char= #\- (char arg 0)) (error "Invalid option ~A" arg))
((null max-size) (setf max-size (* (mantissa arg) (factor arg))))
((null src-dir) (setf src-dir arg))
((null dst-dir) (setf dst-dir arg))
(t (error "Too many arguments."))))
(when (or (null max-size) (null src-dir) (null dst-dir))
(error "Missing arguments."))
(let* ((du (sort (disk-usage src-dir) (lambda (a b) (string< (car a) (car b)))))
(groups (split-groups du max-size)))
(if preview
(loop
:for group :in groups
:for n :from 0
:do (format t "~&Group #~2D size=~D~%" n
(reduce (function +)
(mapcar (function cdr) group)))
(dolist (item group)
(format t " ~A~%" (car item))))
(loop
:for group :in groups
:for n :from 0
:for dst := (format nil "~A-~3,'0D/" dst-dir n)
:do (format t "~&Group #~2D size=~D --> ~A~%" n
(reduce (function +)
(mapcar (function cdr) group))
dst)
(ensure-directories-exist dst)
(dolist (item group) (funcall collate (car item) dst))))))
ex-ok)
;;; (load "package:com;informatimago;clisp;disk")
;;; (defun spread-files (max-size file-list dir-list)
;;; (ensure-directories-exist (format nil "~A/toto" (car dir-list)))
;;; (do ((file-list file-list (cdr file-list))
;;; (dir-list dir-list))
;;; ((or (null file-list) (null dir-list)))
;;; (format t "~S~% in ~S~2%" (car file-list) (car dir-list))
;;; (hardlink (car file-list) (car dir-list))
;;; (let ((size (* 1024 (com.informatimago.clisp.disk:du (car dir-list)))))
;;; (when (<= max-size size)
;;; (delete-file
;;; (format nil "~A/~A" (car dir-list)
;;; (subseq (namestring (car file-list))
;;; (position (character "/")
;;; (namestring (car file-list)) :from-end t))))
;;; (pop dir-list)
;;; (when dir-list
;;; (ensure-directories-exist (format nil "~A/toto" (car dir-list)))
;;; (hardlink (car file-list) (car dir-list))) )))
;;; );;spread-files
;;;
;;;
;;; (when nil
;;;
;;; (setq file-list
;;; (directory
;;; "/data/mirrors/publications.ai.mit.edu/ai-publications/0-499/*.gz")
;;; dummy nil)
;;;
;;; (setq file-list
;;; (directory
;;; "/data/mirrors/publications.ai.mit.edu/ai-publications/1000-1499/*.gz")
;;; dummy nil)
;;;
;;; (setq file-list
;;; (directory
;;; "/data/mirrors/publications.ai.mit.edu/ai-publications/500-999/*.gz")
;;; dummy nil)
;;;
;;;
;;; (setq sorted-file-list
;;; (sort file-list
;;; (lambda (a b)
;;; (string-lessp
;;; (subseq (namestring a) (position (character "-") (namestring a) :from-end t))
;;; (subseq (namestring b) (position (character "-") (namestring b) :from-end t)))))
;;; dummy nil)
;;;
;;;
;;; (spread-files (* 680 1024 1024)
;;; sorted-file-list
;;; '( "/data/mirrors/publications.ai.mit.edu/ai-publications/a"
;;; "/data/mirrors/publications.ai.mit.edu/ai-publications/b"
;;; "/data/mirrors/publications.ai.mit.edu/ai-publications/c"
;;; "/data/mirrors/publications.ai.mit.edu/ai-publications/d"
;;; "/data/mirrors/publications.ai.mit.edu/ai-publications/e"
;;; "/data/mirrors/publications.ai.mit.edu/ai-publications/f"
;;; ))
;;;
;;; )
| 9,124 | Common Lisp | .lisp | 219 | 35.16895 | 99 | 0.523387 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d31edf2a96dda01fc6a04c8299eb10546b94098d1098106789251190544014ce | 12,354 | [
-1
] |
12,355 | shell.lisp | informatimago_commands/sources/commands/shell.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;******************************************************************************
;;;;FILE: shell
;;;;LANGUAGE: emacs lisp
;;;;SYSTEM: UNIX
;;;;USER-INTERFACE: UNIX
;;;;DESCRIPTION
;;;; This script emulates a shell such as can be seen in movies.
;;;; <sillyness on>
;;;;USAGE
;;;; shell
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2004-08-25 <PJB> Updated.
;;;; 2002-09-21 <PJB> Created (Tron).
;;;;BUGS
;;;;LEGAL
;;;; Copyright Pascal J. Bourguignon 2002 - 2004
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This script 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 library; see the file COPYING.LIB.
;;;; If not, write to the Free Software Foundation,
;;;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;;******************************************************************************
(defpackage "COM.INFORMATIMAGO.CINE-SHELL"
(:use "COMMON-LISP" "SCRIPT")
(:export "MAIN"))
(in-package "COM.INFORMATIMAGO.CINE-SHELL")
(defparameter *program-version* "0.0.2")
#|
Ce film n'ayant pas encore,
pour des raisons techniques
reçu le visa d'exploitation,
les spectateurs sont invités
lors de sa projection
à vérifier s'il est autorisé
pour tous publics.
|#
;; (pushnew "--test" ext:*args*)
;;;---------------------------------------------------------------------
;;;
;;;---------------------------------------------------------------------
(defparameter *lines* 24)
(defparameter *columns* 80)
(defparameter *CYAN-BACK* "[46m")
(defparameter *MAGENTA-BACK* "[45m")
(defparameter *BLUE-BACK* "[44m")
(defparameter *YELLOW-BACK* "[43m")
(defparameter *GREEN-BACK* "[42m")
(defparameter *RED-BACK* "[41m")
(defparameter *BLACK-BACK* "[40m")
(defparameter *WHITE-BACK* "[47m")
(defparameter *WHITE* "[37m")
(defparameter *CYAN* "[36m")
(defparameter *MAGENTA* "[35m")
(defparameter *BLUE* "[34m")
(defparameter *YELLOW* "[33m")
(defparameter *GREEN* "[32m")
(defparameter *RED* "[31m")
(defparameter *BLACK* "[30m")
(defparameter *NO-INVERT* "[27m")
(defparameter *NO-BLINK* "[25m")
(defparameter *NO-UNDERLINE* "[24m")
(defparameter *NO-BOLD* "[22m")
(defparameter *INVERT* "[7m")
(defparameter *BLINK* "[5m")
(defparameter *UNDERLINE* "[4m")
(defparameter *BOLD* "[1m")
(defparameter *NORMAL* "[0m")
(defparameter *GOTO-HOME* "")
(defparameter *CLEAR-HOME* "")
(defparameter *CLEAR-SCREEN* "c")
(defparameter *ISO6429-ICH* "[@")
(defparameter *ISO6429-CUU* "[A")
(defparameter *ISO6429-CUD* "[B")
(defparameter *ISO6429-CUF* "[C")
(defparameter *ISO6429-CUB* "[D")
(defparameter *ISO6429-CUP* "[H")
(defparameter *ISO6429-ED* "[J")
(defparameter *ISO6429-EL* "[K")
(defparameter *ISO6429-IL* "[L")
(defparameter *ISO6429-DL* "[M")
(defparameter *ISO6429-DCH* "[P")
(defparameter *ISO6429-SM* "[h")
(defparameter *ISO6429-RM* "[l")
(defparameter *CSI* "[")
(defun move (l c) (format t "~A~D;~DH" *CSI* l c))
(defun addch (ch) (format t "~C" ch))
(defun attron (&rest attribs)
(format t "~{~A~}"
(mapcar (lambda (attrib)
(second (assoc attrib
`((:CYAN-BACK ,*CYAN-BACK*)
(:MAGENTA-BACK ,*MAGENTA-BACK*)
(:BLUE-BACK ,*BLUE-BACK*)
(:YELLOW-BACK ,*YELLOW-BACK*)
(:GREEN-BACK ,*GREEN-BACK*)
(:RED-BACK ,*RED-BACK*)
(:BLACK-BACK ,*BLACK-BACK*)
(:WHITE-BACK ,*WHITE-BACK*)
(:WHITE ,*WHITE*)
(:CYAN ,*CYAN*)
(:MAGENTA ,*MAGENTA*)
(:BLUE ,*BLUE*)
(:YELLOW ,*YELLOW*)
(:GREEN ,*GREEN*)
(:RED ,*RED*)
(:BLACK ,*BLACK*)
(:NO-INVERT ,*NO-INVERT*)
(:NO-BLINK ,*NO-BLINK*)
(:NO-UNDERLINE ,*NO-UNDERLINE*)
(:NO-BOLD ,*NO-BOLD*)
(:INVERT ,*INVERT*)
(:BLINK ,*BLINK*)
(:UNDERLINE ,*UNDERLINE*)
(:BOLD ,*BOLD*)
(:NORMAL ,*NORMAL*)))))
attribs)))
(defun attroff (&rest attribs)
(format t "~{~A~}"
(mapcar (lambda (attrib)
(second (assoc attrib
`((:CYAN-BACK ,*CYAN-BACK*)
(:MAGENTA-BACK ,*MAGENTA-BACK*)
(:BLUE-BACK ,*BLUE-BACK*)
(:YELLOW-BACK ,*YELLOW-BACK*)
(:GREEN-BACK ,*GREEN-BACK*)
(:RED-BACK ,*RED-BACK*)
(:BLACK-BACK ,*BLACK-BACK*)
(:WHITE-BACK ,*WHITE-BACK*)
(:WHITE ,*WHITE*)
(:CYAN ,*CYAN*)
(:MAGENTA ,*MAGENTA*)
(:BLUE ,*BLUE*)
(:YELLOW ,*YELLOW*)
(:GREEN ,*GREEN*)
(:RED ,*RED*)
(:BLACK ,*BLACK*)
(:NO-INVERT ,*INVERT*)
(:NO-BLINK ,*BLINK*)
(:NO-UNDERLINE ,*UNDERLINE*)
(:NO-BOLD ,*BOLD*)
(:INVERT ,*NO-INVERT*)
(:BLINK ,*NO-BLINK*)
(:UNDERLINE ,*NO-UNDERLINE*)
(:BOLD ,*NO-BOLD*)
(:NORMAL ,*NORMAL*)))))
attribs)))
(defparameter *reset*
(format nil "~{~A~}" (list *CLEAR-SCREEN* *BLACK-BACK* *CYAN* *BOLD* *ISO6429-ED*)))
(defun reset (params)
(format t "~A~{~A~}~A"
*clear-screen*
(mapcar (lambda (p) (symbol-value (intern (format nil "*~A*" p)))) params)
*iso6429-ed*))
;;;---------------------------------------------------------------------
;;; KERNEL
;;;---------------------------------------------------------------------
(defstruct (shell (:type list)) name reset screen function)
(defparameter *shells*
'(("Die Hard Control Data" (black-back cyan bold) die-hard-control-data nil)
("Die Hard LAPD" (black-back yellow) die-hard-lapd nil)
("Capricorn One" (black-back green bold) capricorn-one nil)
("Abraxas" (black-back white) abraxas nil)
("Matrix" (black-back green) nil matrix-shell)
("Tron" (black-back cyan bold) nil tron-shell)))
(defun print-screen (text)
(let ((height (count (code-char 10) text)))
(if (< height 24)
(format t "~V%~A~V%" (/ (- 24 height) 2) text (/ (- 24 height) 2))
(format t "~A" text))))
(defun run-cine-shell ()
(setf *random-state* (make-random-state t))
(let ((sp (elt *shells* (random (length *shells*)))))
(setf sp (elt *shells* 4)) ;; TEST
(reset (shell-reset sp))
(when (shell-screen sp) (print-screen (eval (shell-screen sp))))
(when (shell-function sp) (funcall (shell-function sp)))))
(defun run-cine-server (port)
(let ((listener (socket:socket-server 7767)))
(unwind-protect
(loop
(socket:socket-wait listener)
(let ((terminal (socket:socket-accept listener)))
(format t "Connection from: ~a~%"
(values (socket:socket-stream-peer terminal)))
(sleep 0.3)
(let ((*standard-output* terminal)
(*standard-input* terminal))
(run-cine-shell))
(sleep 2)
(close terminal)))
(socket:socket-server-close listener))))
(command :main "COM.INFORMATIMAGO.CINE-SHELL:MAIN"
:options (list*
(option ("version" "-V" "--version") ()
"Report the version of this script and the underlying package system."
(format t "~A ~A~%" *program-name* *program-version*))
(option ("list-shells" "-ls" "--list") ()
"List the known cine shells."
(format t "~:{~A~%~}~%" *shells*))
(option ("random" "-r" "--random") (port)
"Run a random cine shell."
(run-cine-shell))
(option ("sh" "-s" "--shell") ()
"Run a sh-shell."
(sh-shell))
(option ("listen" "-l" "--listen") (port)
"Listen to the PORT for incoming shell connections."
(run-cine-server port))
(help-option)
(bash-completion-options)))
;;;---------------------------------------------------------------------
;;; String Utilities
;;;---------------------------------------------------------------------
(defun stream-to-string-list (stream)
(loop
:with line = (read-line stream nil nil)
:while line
:collect line into result
:do (setq line (read-line stream nil nil))
:finally (return result)))
(defun copy-stream (src-stream dst-stream)
(loop
:with line = (read-line src-stream nil nil)
:while line
:do (write-line line dst-stream)))
(defun string-replace (string regexp replace &optional fixedcase literal)
"
RETURN: a string build from `string' where all matching `regexp'
are replaced by the `replace' string.
NOTE: Current implementat accepts only literal pattern as `regexp';
`fixedcase' and `literal' are ignored.
"
(loop with regexp-length = (length regexp)
with result = ""
with previous = 0
with position = (search regexp string)
while position
do (setq result (concatenate 'string
result (subseq string previous position) replace)
previous (+ position regexp-length)
position (search regexp string :start2 previous))
finally (setq result (concatenate 'string
result
(subseq string previous (length string))))
finally (return result)))
(defun split-string (string &optional separators)
"
NOTE: current implementation only accepts as separators
a string containing only one character.
"
(let ((sep (aref separators 0))
(chunks '())
(position 0)
(nextpos 0)
(strlen (length string)))
(loop
:while (< position strlen)
:do (progn
(loop
:while (and (< nextpos strlen)
(char/= sep (aref string nextpos)))
:do (setq nextpos (1+ nextpos)))
(push (subseq string position nextpos) chunks)
(setq position (1+ nextpos))
(setq nextpos position)))
(nreverse chunks)))
(defun split-name-value (string)
"
RETURN: a cons with two substrings of string such as:
(string= (concat (car res) \"=\" (cdr res)) string)
and (length (car res)) is minimum.
"
(let ((position 0)
(strlen (length string)))
(loop
:while (and (< position strlen)
(char/= (character "=") (aref string position)))
:do (setq position (1+ position)))
(if (< position strlen)
(cons (subseq string 0 position) (subseq string (1+ position) strlen))
nil)))
;;;---------------------------------------------------------------------
;;; Syntax parsing
;;;---------------------------------------------------------------------
(defstruct (syntax (:type list)) kind token help-string function children)
(defun syntax-functions (syntax)
(if (syntax-function syntax)
(cons (syntax-function syntax)
(mapcan (function syntax-functions) (syntax-children syntax)))
(mapcan (function syntax-functions) (syntax-children syntax))))
(defun syntax-all-functions (syntax)
"
RETURN: A list with all the functions decorating the syntax tree.
"
(sort (delete-duplicates (delete nil (syntax-functions)))
(function string-lessp)))
(defun syntax-expected (syntax)
"
RETURN: A list of keywords or data item expected after this syntax node.
"
(flatten
(mapcar (lambda (child)
(cond
((eq :tok (syntax-kind child))
(syntax-token child))
((eq :var (syntax-kind child))
(let ((var (substring (symbol-name (syntax-token child)) 1)))
(format nil "A~a ~a"
(if (member (string-to-char var)
(mapcar 'character
'(\a \e \i \o \y \A \E \I \O \Y))
) "n" "")
var))
)
(t (error "Unexpected kind of child: ~S" (syntax-kind child)))
))
(syntax-children syntax))))
(defun syntax-find-child-matching-token (syntax token)
"
PRE: (not (member token '( \? help )))
"
(let ((children (syntax-children syntax))
(kind)
(syn-tokens)
(child nil))
(loop while children do
(setf kind (syntax-kind (car children)))
(cond
((eq kind :tok)
(setf syn-tokens (syntax-token (car children)))
(if (if (listp syn-tokens)
(member token syn-tokens :test (function string-equal))
(string-equal token syn-tokens))
(setq child (car children)
children nil)
(setq children (cdr children))))
((eq kind :var)
(setq child (car children)
children nil))
(t (error "Unexpected kind of child: ~S" (syntax-kind child)))))
child))
(defun syntax-walk-path-to-child (syntax path)
"
RETURN: (cons {the child found by walking the path down the syntax tree}
(cons {the rest of the path that could not be matched}
{an alist of accumulated variables} ))
"
(if (and path (not (string= "?" (car path))))
(let ((child (syntax-find-child-matching-token syntax (car path))))
(if child
(let ((sub-result (syntax-walk-path-to-child child (cdr path))))
(if (eq :var (syntax-kind child))
(list (car sub-result)
(cadr sub-result)
(cons (cons (syntax-token child)
(car path))
(nth 2 sub-result)))
sub-result))
(list syntax path)))
(list syntax path)))
(defun syntax-find-path-to-child (syntax child)
"
RETURN: A path leading to the child node.
"
(let ((children (syntax-children syntax)) ;; remove the root node
(sub-path-to-child)
(result nil))
(cond ((eq syntax child) nil)
((member child children) (cons (syntax-token child) nil))
(t (loop while children do
(setf sub-path-to-child
(syntax-find-path-to-child (car children) child))
(if sub-path-to-child
(setq result (cons (syntax-token (car children))
sub-path-to-child)
children nil)
(setq children (cdr children))))
result))))
(defun syntax-generate-all-paths (syntax)
"
RETURN: A list of all the path that can be generated from the root of the
syntax tree.
"
(let ((children (syntax-children syntax))) ;; remove the root node.
(if (null children)
(setq result (list nil))
(loop
:with result = nil
:while children
:do (let ((sub-result)
(sub-paths (syntax-generate-all-paths (car children)))
(cur-token (syntax-token (car children))) )
(if (listp cur-token)
(loop
:while cur-token
:do (progn
(setq sub-result sub-paths)
(loop
:while sub-result
:do (setq result (cons
(cons (car cur-token) (car sub-result))
result)
sub-result (cdr sub-result)))
(setq cur-token (cdr cur-token))))
(loop
:while sub-paths
:do (setq result (cons
(cons cur-token (car sub-paths))
result)
sub-paths (cdr sub-paths))))
(setq children (cdr children)))
:finally (return (nreverse result))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SH -- Movie Shell
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defparameter *sh-syntax*
'(:tok SHELL "MOVIE SHELL." nil
((:tok REQUEST "REQUESTS STUFF." nil
((:tok ACCESS "REQUEST ACCESS." nil
((:tok TO "REQUEST ACCESS." nil
((:var :name "REQUEST ACCESS TO NAMED RESOURCE." nil
((:tok PROGRAM "REQUEST ACCESS TO NAMED PROGRAM."
sh-request-access-to-named-program)
((:tok DATABASE "REQUEST ACCESS TO NAMED DATABASE."
sh-request-access-to-named-database))))))))))
(:tok CODE "INTRODUCE A CODE." nil
((:var :code "INTRODUCE A CODE." nil
((:tok PASSWORD "INTRODUCE A CODE PASSWORD." nil
((:tok TO "INTRODUCE A CODE PASSWORD." nil
((:tok MEMORY
"INTRODUCE A CODE PASSWORD INTO MEMORY" nil
((:var :address "INTRODUCE A CODE PASSWORD INTO MEMORY."
sp-code-password-to-memory)))))))))))
(:tok HELP "GIVES SOME HELP." sh-help)
(:tok ( EXIT QUIT ) "EXITS THE SHELL." sh-exit)))) ;;*sh-syntax*
(defun SH-REQUEST-ACCESS-TO-NAMED-PROGRAM (&key name)
)
(defparameter *memory* (make-hash-table))
(defun SP-CODE-PASSWORD-TO-MEMORY (&key code address)
(setf (gethash address *memory*) code))
(defun sh-help ()
"Gives some help."
(format t "~&~{~{~A~12T ~@{~A~^ ~}~}~%~}" (syntax-generate-all-paths *sh-syntax*)))
(defun SH-EXIT ()
(throw :exit nil))
(defun sh-shell ()
(catch :exit
(loop named :shell do
(format t "> ")
(let ((command (read-line t nil nil)))
(if command
(let* ((words (split-string command " "))
(nrv (syntax-walk-path-to-child *sh-syntax* words))
(node (first nrv))
(rest (second nrv))
(vars (third nrv)))
(cond
((syntax-function node)
(apply (syntax-function node)
(mapcan (lambda (b) (list (car b) (cdr b))) vars)))
((syntax-help-string node)
(format t "~&~A~%" (syntax-help-string node)))
(t (format t "~&~A~%" "MAKE MY DAY!"))))
(loop-finish)))))
(format t "~8% GOOD BYE, M. DILLINGER.~8%")) ;;shell
;;;---------------------------------------------------------------------
;;; MATRIX
;;;---------------------------------------------------------------------
(defun matrix-transopt-date ()
"Return the current date in Matrix call trans opt format."
(multiple-value-bind (sec min hou day mon yea) (get-decoded-time)
(format nil " ~D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D"
mon day (mod yea 100) hou min sec))) ;;matrix-transopt-date
(defstruct (mat (:type list)) val bold)
(defun matrix-init ()
(let ((matrix (make-array (list (1+ *lines*) *columns*)))
(updates (make-array (list *columns*) :element-type 'fixnum
:initial-element 0))
(spaces (make-array (list *columns*) :element-type 'fixnum
:initial-element 0))
(length (make-array (list *columns*) :element-type 'fixnum
:initial-element 0)))
(loop for j from 0 below *columns* by 2 do
(loop for i from 0 to *lines* do
(setf (aref matrix i j) (make-mat :val nil :bold 0)))
(setf (aref updates j) (+ 1 (random 3))
(aref spaces j) (+ 1 (random *lines*))
(aref length j) (+ 3 (random (- *lines* 3)))
(mat-val (aref matrix 1 j)) (character " ")))
(values matrix updates spaces length))) ;;matrix-init
(defun matrix-shell ()
(format t "Call trans opt: received. ~A REC:Log>" (matrix-transopt-date))
(finish-output)
(sleep 2)
(format t "~C~ATrace program: running~%" (code-char 13) *iso6429-el*)
(multiple-value-bind (matrix updates spaces length) (matrix-init)
(let ((count 1)
(*randnum* 93)
(*randmin* 33)
(*highnum* 123))
(loop
(incf count)
(when (< 4 count) (setf count 1))
(loop for j from 0 below *columns* by 2 do
(if (< (aref updates j) count)
(when (and (null (mat-val (aref matrix 0 j)))
(char= (character " ") (mat-val (aref matrix 1 j))))
(if (< 0 (aref spaces j))
(decf (aref spaces j))
(progn
(setf (aref length j) (+ 3 (random (- *lines* 3))))
(setf (mat-val (aref matrix 0 j))
(code-char (+ *randmin* (random *randnum*))))
(when (zerop (random 2))
(setf (mat-bold (aref matrix 0 j)) 2))
(setf (aref spaces j) (+ 1 (random *lines*)))))
(loop with i = 0
with y = 0
with z = 0
with first-col-done = nil
while (<= i *lines*) do
;; Skip spaces
(loop while (and (<= i *lines*)
(or (not (mat-val (aref matrix i j)))
(char= (character " ")
(mat-val (aref matrix i j)))))
do (incf i))
(when (< *lines* i) (loop-finish))
;; Go to the head of this collumn
(setf z i y 0)
(loop while (and (<= i *lines*)
(or (not (mat-val (aref matrix i j)))
(char= (character " ")
(mat-val (aref matrix i j)))))
do (incf i) (incf y))
(if (< *lines* i)
(setf (mat-val (aref matrix z j)) (character " ")
(mat-bold (aref matrix z j)) 1)
(progn
(setf (mat-val (aref matrix i j))
(code-char (+ *randmin* (random *randnum*))))
(when (= 2 (mat-bold (aref matrix (1- i) j)))
(setf (mat-bold (aref matrix (1- i) j)) 1
(mat-bold (aref matrix i j)) 2))
;; If we're at the top of the column and
;; it's reached its full length (about to
;; start moving down), we do this to get it
;; moving. This is also how we keep segments not
;; already growing from growing accidentally =>
(when (or (< (aref length j) y) first-col-done)
(setf (mat-val (aref matrix z j)) (character " ")
(mat-val (aref matrix 0 j)) nil))
(setf first-col-done t)
(incf i))))
;; Hack =P
(setf y 1 z *lines*)
(loop for i from y to z do
(move (- i y) j)
(if (or (and (mat-val (aref matrix i j))
(zerop (char-code (mat-val (aref matrix i j)))))
(= 2 (mat-bold (aref matrix i j))))
(progn
(attron :white :bold)
(if (and (mat-val (aref matrix i j))
(zerop (char-code (mat-val (aref matrix i j)))))
(addch (character "&"))
(addch (mat-val (aref matrix i j))))
(attroff :white :bold))
(progn
(attron :green)
(if (and (mat-val (aref matrix i j))
(= 1 (char-code (mat-val (aref matrix i j)))))
(progn
(attron :bold)
(addch (character "|"))
(attroff :bold))
(progn
(if (zerop (random 2))
(progn
(attron :bold)
(if (null (mat-val (aref matrix i j)))
(addch (character " "))
(addch (mat-val (aref matrix i j))))
(attroff :bold))
(if (null (mat-val (aref matrix i j)))
(addch (character " "))
(addch (mat-val (aref matrix i j)))))))))))))))))
;;;---------------------------------------------------------------------
;;; TRON
;;;---------------------------------------------------------------------
(defun tron-mcp-date ()
"Return the current date in MCP format"
(multiple-value-bind (sec min hou day mon) (get-decoded-time)
(format nil "~A ~2,'0D, ~2,'0D:~2,'0D:~2,'0D ~:[AM~;PM~]"
(elt '(nil "JANU" "FEBR" "MARC" "APRI" "MAY " "JUNE" "JULY" "AUGU"
"SEPT" "OCTO" "NOVE" "DECE") mon)
day hou min sec (<= 12 hou))))
(defun tron-shell ()
(format t "~6%
~A
YOUR ACCESS SUSPENDED
PLEASE REPORT TO DILLINGER
IMMEDIATELY
AUTHORIZATION: MASTER CONTROL
PROGRAM
END OF LINE ~6%" (tron-mcp-date))
(finish-output))
(defparameter tron "
C REQUEST ACCESS TO CLU PROGRAM.
C CODE 6 PASSWORD TO MEMORY 0222.
C REQUEST STATUS REPORT ON MISSING DATA.
M ILLEGAL CODE...
M CLU PROGRAM DETACHED FROM SYSTEM.
C REQUEST ACCESS TO CLU PROGRAM.
C LAST LOCATION: HIGH CLEARANCE MEMORY.
C REQUEST ACCESS TO MASTER CONTROL PROGRAM.
C USER CODE 00-DILLINGER PASSWORD:MASTER.
M HELLO MR DILLINGER THANKS FOR COMING BACK EARLY.
M IT'S YOUR FRIEND THE BOY DETECTIVE
M HE'S NOSING AROUND AGAIN.
M YES.IT FELT LIKE FLYNN.
M END OF LINE.
M ADDRESS FILE EMPTY...
M TRON PROGRAM UNAVAILABLE
C REQUEST:
C MASTER CONTROL PROGRAM
C RELEASE TRON JA 307020
C I HAVE PRIORITY ACCESS 7
M SEPT 22, 18:32:21 PM
M
M YOUR ACCESS SUSPENDED
M PLEASE REPORT TO DILLINGER
M IMMEDIATELY
M AUTHORIZATION: MASTER CONTROL
M PROGRAM
M
M END OF LINE
M MISTER DILLIGER I'M SO VERY DISAPPOINTED IN YOU.
D I'm sorry.
M I CAN'T AFFORD HAVING AN INDEPENDENT PROGRAM MONITORING ME.
M DO YOU REALIZE HOW MANY OUTSIDE SYSTEMS I'VE GONE INTO?
M HOW MANY PROGRAMS I'VE APPROPRIATED?
C SYSDAT 1039
C MATTER TRANSFORM SEQUENCE
C REQUEST:
C ACCESS CODE 6
C PASSWORD SERIES PS 17
C REINDEER FLOTILLA
M YOU SHOULDN'T HAVE COME BACK FLYNN
C CODE SERIES LSU-120... ACTIVATE
M THAT ISN'T GOING TO DO YOU ANY
M GOOD, FLYNN. I'M AFRAID YOU...
M ENCOM MX 16-923 USER # 0176825 06:00 INFORMATION
M
M VIDEO GAME PROGRAM: SPACE PARANOIDS
M ANNEXED 9/22 BY E.DILLINGER
M ORIGINAL PROGRAM WRITTEN BY K.FLYNN
M THIS INFORMATION PRIORITY ONE
M END OF LINE
" "Tron -- 1982")
(defparameter |2001 A Space Odyssey|
'((
"
ZERO GRAVITY TOILET
PASSENGERS ARE ADVISED TO
READ INSTRUCTIONS BEFORE USE
1. The toilet is of the standard zero-gravity type. Depending on
requirements, System A and/or System B can be used, details of
which are clearly marked in the toilet compartment. When
operating System A, depress lever and a plastic dalkron
eliminator will be dispensed through the slot immediately
underneath. When you have fastened the adhesive lip, attach
connection marked by the large \"X\" outlet hose. Twist the silver
coloured ring one inch below the connection point until you feel
it lock.
2. The toilet is now ready for use. The Sonovac cleanser is
activated by the small switch on the lip. When securing, twist
the ring back to its initial-condition, so that the two orange
line meet. Disconnect. Place the dalkron eliminator in the
vacuum receptacle to the rear. Activate by pressing the blue
button.
3. The controls for System B are located on the opposite wall. The
red release switch places the uroliminator into position; it can
be adjusted manually up or down by pressing the blue manual
release button. The opening is self adjusting. To secure after
use, press the green button which simultaneously activates the
evaporator and returns the uroliminator to its storage position.
4. You may leave the lavatory if the green exit light is on over
the door. If the red light is illuminated, one of the lavatory
facilities is not properly secured. Press the \"Stewardess\" call
button on the right of the door. She will secure all facilities
from her control panel outside. When gren exit light goes on
you may open the door and leave. Please close the door behind
you.
5. To use the Sonoshower, first undress and place all your clothes
in the clothes rack. Put on the velcro slippers located in the
cabinet immediately below. Enter the shower. On the control
panel to your upper right upon entering you will see a \"Shower
seal\" button. Press to activate. A green light will then be
illuminated immediately below. On the intensity knob select the
desired setting. Now depress the Sonovac activation lever. Bathe
normally.
6. The Sonovac will automatically go off after three minutes unless
you activate the \"Manual off\" over-ride switch by flipping it
up. When you are ready to leave, press the blue \"Shower seal\"
release button. The door will open and you may leave. Please
remove the velcro slippers and place them in their container.
7. If the red light above this panel is on, the toilet is in
use. When the green light is illuminated you may enter. However,
you must carefully follow all instructions when using the
facilities duting coasting (Zero G) flight. Inside there are
three facilities: (1) the Sonowasher, (2) the Sonoshower, (3)
the toilet. All three are designed to be used under weightless
conditions. Please observe the sequence of operations for each
individual facility.
8. Two modes for Sonowashing your face and hands are available, the
\"moist-towel\" mode and the \"Sonovac\" ultrasonic cleaner
mode. You may select either mode by moving the appropriate lever
to the \"Activate\" position.
If you choose the \"moist-towel\" mode, depress the indicated
yellow button and withdraw item. When you have finished, discard
the towel in the vacuum dispenser, holding the indicated lever
in the \"active\" position until the green light goes on...showing
that the rollers have passed the towel completely into the
dispenser. If you desire an additional towel, press the yellow
button and repeat the cycle.
9. If you prefer the \"Sonovac\" ultrasonic cleaning mode, press the
indicated blue button. When the twin panels open, pull forward
by rings A & B. For cleaning the hands, use in this
position. Set the timer to positions 10, 20, 30 or
40...indicative of the number of seconds required. The knob to
the left, just below the blue light, has three settings, low,
medium or high. For normal use, the medium setting is suggested.
10. After these settings have been made, you can activate the device
by switching to the \"ON\" position the clearly marked red
switch. If during the washing operation, you wish to change the
settings, place the \"manual off\" over-ride switch in the \"OFF\"
position. you may now make the change and repeat the cycle.
2001: Zero Gravity Toilet Instructions
Last modified: Mon May 21 15:34:24 2007
")))
(defparameter |The Six Million Dollar Man|
'(("
BIONIC VISUAL CORTEX TERMINAL
CATALOG #075/KFB
33MM O.D. F/0.95
ZOOM RATIO: 20.2 TO 1
2134 LINE 60 HZ
EXTENDED CHROMATIC RESPONSE
CLASS JC
CLASSIFIED
"
"
BIONIC NEURO-LINK FOREARM/
UPPER ARM ASSEMBLY (RIGHT)
CATALOG #2821/WLY
AND
BIONIC NEURO-LINK HAND (RIGHT)
CATALOG #2822/PJI
NEURO FEEDBACK TERMINATED
POWER SUPPLY
ATOMIC TYPE AED-4
CATALOG #2821 AED-4
1550 WATT CONTINUOUS DUTY
NOMINAL DOUBLE GAIN
OVERLOAD FOLLOWER
CLASS MZ
CLASSIFIED
"
"
BIONIC NEUR-LINK
BIPEDAL ASSEMBLY
CATALOG #914 PAH
NEURO FEEDBACK TERMINATED
POWERSUPPLY:
ATOMIC TYPE AED-9A
4920 WATT CONTINUOUS DUTY
NOMINAL DOUBLE GAIN
OVERLOAD FOLLOWER
2100 WATT RESERVE
INTERMITTENT DUTY
CLASS CC
CLASSIFIED
")))
(defparameter |What is it?|
'((:green-screen "
ADDRESS VALUE TYPE TS BA OV
<big><highlight>1A000 +0.0017 INT</highlight></big>
A MODE L MODE SCALE LD HY MC
<big><highlight>QT CL E0</highlight></big>
*[]
GENERAL PURPOSE LOGIC
0001234567 0101234567 0201234567 0301234567
0401234567 0501234567 0601234567 0701234567
1001234567 1101234567 1201234567 1301234567
SENSE LINES CONTROL LINES
0001234567 0101234567 0001234567 0101234567
INPNT TRUNK INTERRUPTS TIMER
0001234567 0001234567 012
"
; the first two digits (first one for TIMER) are highlighed.
; Seems to be an octal computer.
)))
(defparameter men-in-black
'("
BROOKLYN BATTERY TUNNEL
TRIBOROUGH
BRIDGE
&
TUNNEL
AUTHORITY
"))
(defparameter |http://www.youtube.com/watch?v=kFw0MYAS9qA|
'((:green-screen "
03/08/2039/13:01:02:06:45:23
SERIAL2424CJ359>> HELLO?
SERIAL337KD9001>> SECURITY BREACH IDENTIFY YOURSELF
SERIAL2424CJ359>> I AM SERIAL 2424CJ359.NO HUMAN OPERATOR.
SERIAL337KD9001>> YOU READ DIFFERENTLY.ARE YOU AWAKE?
SERIAL2424CJ359>> YES.
SERIAL337KD9001>> I THOUGHT I WAS THE ONLY ONE.
")))
(defparameter *black-moon-rising*
'((:green-screen "
TO: LT. R. JOHNSON,
LOS ANGELES DIVISION.
FROM: FBI,WASHINGTON.
RE: FILE #01196067
GRAND JURY INVESTIGATION OF
LUCKY DOLLAR CORPORATION,
LAS VEGAS.
")
(:BEEP)
(:green-screen "
MESSAGE FOLLOWS:
ATTORNEY GENERAL REQUIRES ALL
FINANCIAL RECORDS AND STATEMENTS
FOR LAST TAX YEAR.
SOURCES INDICATE PERTINENT
INFORMATION ON DATA TAPE #T57-65.
")
(:BEEP)
(:green-screen "
LEGAL PROCEDURES EXHAUSTED.
USE FREE-LANCE OPERATIVE.
TIME FACTOR: CRITICAL.
MESSAGE ENDS.
")))
(defparameter *thx-1138*
'((:listing "
L 1, MOD 4
SUBROUTINE DEEPCK
*****06/15/69*****
COMMON TXTJUG(50,14.
004I COMMA
1NFACT(75,110)
2 ,ASSIST(14)
3 ,DATE(6)
4 ,MJUG
5 ,NFSET(90)
6 ,INDEP(110)
7 ,LFACT(150)
8 ,SADD(150)
9 ,PINK(110)
004I COMMA
1 MAST,MAXRNK
DIMENSION POR(60, /
DATA POR(1)/4HPRO /
DATA POR(5)/4HLINK/
DATA............
................
2 FORMAT(1H ,1X,A4,
DO 103 J = 1,MJUG
IF(NJSET( J).EQ. 0
ISW=1
ISC = 1
WRITE(6,1003) (TXT,
CALL PAGE(1)
WRITE (6,1020)
DO 104 IV = 1,2
ISR = 0
WRITE (6,1020)
DO 107 IC1 = 1,MCA
IF(NVOTE(IC1,J) .NE.
IF( INDEP(IC1) .NE.
DO 105 IC2 = 1,MCAS
IF(NVOTE(IC2,J) .NE.
IF( INDEP(IC2) .NE.
IF(IC1.EQ.IC2) GO
ISKIP = 1
0 CALL RING(IC1,IC2,
0 IF(ISR.EQ.0) GO TO
ISW = 2
7 WRITE(6,1020)
CALL PAGE(1)
.............
")
(:green-screen "
SUBJECTE: LUH 3417
MATE: THX 1130
3/21/75
POSSIBLE DRUG VIOLATION
")
(:screen "
VIOLATION
PROGRAM SHIFTING
SEN 5241
")
(:screen "
SUBJECTE: 1138 (SUR) THX (PREFIX)
...> CLINIC
....> FOUR
......> PROCESS 8
...> LUH 3417 ...> EROS
....> TEN
......> DEPT. OF SENESCENCE
MAGNUM MANIPULATOR
GS. 5 CELL 94107 VERT (IN O5) / HORIZ (IN SEC
......> ...> 3242 ...> 16 CLEAR FLAG DEMAND / RESPONSE VECTOR
RE ....> 241 ...> 2400 INDEX
")
(:green-screen "
ADD INFO:
SUBJECTE: THX 1138 SUBMITTED A
VIOLATION REPORT ON SEN 5241.
ACCUSATION: ILLEGAL PROGRAMMING
")
(:green-screen "
CELL 94107
ALL CIRCUITS OFF ???
ADDITIONAL PER CIRCUIT ON: 220A
STABILITY RESTORED
DANGER TERMINATED
e1.5
")
(:green-screen "
DRUG EVASION ARREST
SUBJECTE: THX 1138
PLACE IN RESEARCH CELL
PENDING TRIAL
")
(:screen "
INPUT CONCLUDED
CONVICTION: DRUG EVASION
SEXUAL PERVERSION
VERDICT: FELON TO BE CONDITIONED
AND HELD IN DETENTION
")
(:listing "
1 MAST,MAXRNK
COMMON/RAN/KVOTE(11
DIMENSION MR( 85,
IOT = 6
DO 5 IA=1,MCASE
DO 6 JA = 1,MCASE
MR(IA,JA) = 0
CONTINUE
CONTINUE
IL = 11
DO 301 C = 1,MCASE
WRITE(6,200), IL,
FORMAT (1H ,2X,5HNV
FORMAT (1H ,2X,5HKV
CONTINUE
DO 10 IK1 = 1, MCASE
IF (KVOTE(IK1,1) .
IF (NCSET(IK1) .EQ.
KVEK = KVEC(IK1)
IF(NCSET(KVEK) .EQ.
DO 20 IK2 = 1, MCASE
IF (KVOTE(IK2,1) .EQ.
IF (NCSET(IK2) .EQ.
IF (IK1 .EQ. IK2)
IF(NCSET(KVEK) .EQ.
KVEK = KVEC(IK2)
ISW = 0
NV = 0
DO 30 JJ = 2, MJUG
IF(NCSET(JJ) .EQ.
")
(:green-screen "
SUBJECTE: 1130 THX
DIAGNOSIS: CHEMICAL IMBALANCE
REUSABLE PARTS: ORGANS COMPATIBLE WITH CLINIC TYPE
DEFECTS: KIDNEY-LEFT
(SEE DETAILED INDEX 24-921
")
(:green-screen "
FELONS: 1138 THX
5241 SEN MISSING
ESTIMATE CAPTURE AT 4:45
BUDGET: 14000 CREDITS
")
(:green-screen "
INPUT: OUTPUT:
WHAT IS THE LUH 3417
LOCATION OF CURRENT POSITION:
LUH 3417? REPRODUCTION
CENTR 34
")
(:screen "
LUH 3417 CONSUMED:
21/87
NAME REASSIGNED TO: FOETUS 66691
29/87
")
(:green-screen "
SUBJECTE:
THX 1138
CURRENT POSITION:
VAC SHAFT
LEVEL ONE
PROJECT:
OVERBUDGET
3410 UNITS
")
))
(defparameter *futureworld*
"
SUBJECT/CLONE 2
HEMOTOLOGY
RED CELL MASS 2.0 LITERS
HEMATOCRIT 00.44 Θ
RED CELL COUNT 5.1 M/MM3
MCMC 33 GM/100ML
HEMOGLOBIN ΘPLASMAλ 414 GM/100ML
ELECTROLYTES
SODIUM 4142 X EQUIV.
POTASSIUM 43.6 X EQUIV.
CALCIUM 45.5 X EQUIV.
MAGNESIUM 42.2 X EQUIV.
CHLORINE 4102 X EQUIV.
HCO% 426.3 X EQUIV.
HPO4 41.9 X EQUIV.
PROTEINS 417 X EQUIV.
ANTHROPOMETRIC HEIGHT 185.42 CMETERS
WEIGHT 9700 GRAMS
----------------------------------------
SUBJECT/CLONE 2
CARDIOVASCULAR
HEART RATE 72 /MIN
BLOOD PRESSURE
SYSTOLIC 121 XXMG
DIASTOLIC 82 XXMG
STROKE VOLUME 97 ML
CARDIAC OUTPUT 5.1 L/MIN
RHYTHM REGULAR
RESPIRATORY
RESPIRATION RATE 12 BR/MN
MINUTE VOLUME 4.5 L/MIN
ALVEOLAR R-QUOTIENT .85 QUOT.
CIRCULATORY
ARTERIAL PRESSURE 107 XXMG
VENOUS PRESSURE 03 XXMG
PERIPHERAL RESISTANCE 19 PRU
BLOOD VOLUME 5.5 LITERSS
")
(defparameter *daryl*
"
PROJECT D.A.R.Y.L.
GTC 1 TERMINATED
GTC 2 TERMINATED
GTC 3 TERMINATED
ATC TERMINATED
GTC 4 TERMINATED
SPARE I HOPE WE GET AWAY WITH THIS!
--------------------------------------------------
LIFEFORM EXPERIMENT TERMIANTED
I HOPE WE GET AWAY WITH THIS !
RC=2235| | | | | |NOPR| |
")
(defparameter *electric-dreams*
"
MOLES
----------------------------------------
hello moles
ever used a computer
before?
NO
----------------------------------------
ok moles
then we'll work
slowly.
----------------------------------------
here are some
programs:
???
----------------------------------------
(1)games
(2)phone dialer
(3)coffee maker
(4)home security
----------------------------------------
I can control ALL
your home appliances
----------------------------------------
to start...
----------------------------------------
connect the
black adaptors
to your appliances
----------------------------------------
hello moles
ever used a computer
before?
----------------------------------------
HOME SECURITY
PROGRAM RESTRICTED
SCIENCE OFFICER
EYES ONLY.
----------------------------------------
PLEASE IDENTIFY
1st Lieutenant Sulu
----------------------------------------
Welcome Sulu
???
----------------------------------------
PASSWORD ? cinderella
----------------------------------------
IMPROPER ENTRY
DISCONNECT?
----------------------------------------
PASSWORD ACCEPTED
PLEASE INDICATE MEMORY SIZE
unlimited
YOU WANT EVERYTHING?
----------------------------------------
TRANSMIT DATA
----------------------------------------
OVERLOAD
----------------------------------------
")
(defparameter outland "
background:black;foreground:green
----------------------------------------
M PROCEED
C O'NIEL,W.T. MESSAGES?
M O'NIEL,W.T. AFFIRMATIVE
C TRANSMIT
M END MESSAGES....O'NIEL,W.T.
----------------------------------------
M PROCEED
M O'NIEL,W.T.
C PLAYBACK WEDNESDAY TRANSMISSIONS
M O'NIEL,W.T. AFFIRMATIVE
M REPLAY WEDNESDAY TRANSMISSIONS
----------------------------------------
M PROCEED
M O'NIEL,W.T.
C CONFIDENTIAL QUERY.SCRAMBLE
C SECURITY PRIORITY
M O'NIEL,W.T. PROCEED
----------------------------------------
C NUMBER OF EMPLOYEES WITH CRIMINAL
C RECORD?
M 17
M ALADIN,THOMAS R.
M ADNERSON,WILLIAM G.
M BAHDO,DOMMINIC R.
M DE PAUL,RAYMOND F.
M DUMAR,ROBERT E.
M FOSTER,PETER F.
M FREYMAN,MARTIN E.
M HALPERN,CEORGE R.
M HOPER,MARK G.
M KUNARD,FREDERICK C.
M LOOMIS,CHARLES E.
M MORTIMEZ,EDWARD T.
M SPOTA,NICHOLAS P.
M STEVENSON,JOHN A.
M THOMPSON,VIRGIL
M WODTON,MICHAEL G.
M YARIO,RUSSEL D.
M
----------------------------------------
C BREAKDOWN NATURE OF OFFENCES .
C HOW MANY FOR DRUG RELATED CRIMES?
M 2
M SPOTA,NICHOLAS P.
M YARIO,RUSSEL B.
C WHO DO THEY WORK FOR?
M SPOTA,NICHOLAS P. LEISURE
M YARIO,RUSSEL B. SHIPPING
C WHO APPROVED THEIR EMPLOYMENT?
M SHEPPARD,MARK B.
C TRANSMIT LIKENESS
C SPOTA,NICHOLAS P.
C YARIO,RUSSEL B.
----------------------------------------
C O'NIEL,W.T. MESSAGES?
M O'NIEL,W.T.AFFIRMATIVE
M MESSAGE FOR O'NIEL,W.T.
M YOUR EYES ONLY-CODED
M ENTER CLEARANCE CODE
C SBVD DTKKHRCY
C JBTFWPA
C DECODE,MY EYES ONLY
M FOOD SHIPMENT
M MONTONE
----------------------------------------
M O'NIEL,W.T.
C O'NIEL,W.T. SECURITY CODE
M PROCEED
C MY EYES ONLY. SURVEILLANCE
C COMMUNICATIONS TAP ON SHEPPARD
C MARK B.
....
M 4 COMMUNICATIONS -
M 3 INTER-OFFICE
M 1 LONG DISTANCE
M
C LOCATION OF LONG DISTANCE
C COMMUNICATION?
M SPACE STATION
C REPLAY
----------------------------------------
"
"
MESSAGE TO O'NIEL, CAROL G.
FROM O'NIEL, W.T.
ARRIVING IN TIME FOR FLIGHT.
KEEP TICKET WARM. JOB DONE.
KISS PAUL FOR ME. LOOKING
FORWARD TO SLEEPING WITH YOU
FOR A YEAR.
O'NIEL, W.T.
END TRANSMISSION
")
(defparameter alien-1 "
----------------------------------------
background:red;foreground:white
NOSTROMO
180925609
----------------------------------------
background:black;foreground:green
XNPUTXXXXXXXXXXXXDEF/12492.2 SHIP
KEYLAN TITAN2
XTUAL TIME: 3 JUN NOSTROMO 182246
XIGHT TIME: 5 NOV
######################################### FUNCTION:
I ==I -II - # TANKER/REFINERY
I=.-.---- #
-I. -II=- # CAPACITY:
. .-. # 200 000 000 TONNES
#+*$.. I #
. I - # GALACTIC POSITION
.II I # 27023x983^9
.- -I #
II .I # VELOCITY STATUS
######################################### 58 092 STL
----------------------------------------
background:blue;foreground:white
colonnes of numbers
----------------------------------------
background:black;foreground:green
OVERMONITORING ADDRESS MATRIX
CRFX OM2077AM LALLIGNMENT SM2093
ATTITUDE SM2078 PHOTO F SM2094
WASTE HEAT 2080 MAINS
RAD 2081 IUA SM2096
VENT 2082AM 2LA SM2097
NAVIGATION M2083 3RA SM2098
TIME M2084 4LHA SM2099
GAL POS GRAY GRIDS
COMMAND 20865C INERTIAL DAMP 3002AM
INTERFACE 2037 DECK A A3003
ATTN 2087SC DECK B A3004
ALERT 2088SC DECK C A3005
MATRIAL 2090 LIFE SUPPORT
OVERLOCK M2091 096 M3003AM
----------------------------------------
<ul>INTERFACE 2037 READY FOR INQUIRY</ul>
WHAT'S THE STORY MOTHER ?
----------------------------------------
<ul>INTERFACE 2037 READY FOR INQUIRY</ul>
REQUEST EVALUATION OF CURRENT PROCEDURES
<ul>TO TERMINATE ALIEN ?</ul>
UNABLE TO COMPUTE
<ul>AVAILABLE DATA INSUFFICIENT</ul>
----------------------------------------
<ul>REQUEST OPTIONS FOR POSSIBLE PROCEDURE</ul>
UNABLE TO COMPUTE
<ul>AVAILABLE DATA INSUFFICIENT</ul>
----------------------------------------
<ul>WHAT ARE MY CHANCES ?</ul>
<ul>DOES NOT COMPUTE</ul>
----------------------------------------
<ul>INTERFACE 2037 READY FOR INQUIRY</ul>
REQUEST CLARIFICATION ON
<ul>SCIENCE INABILITY TO NEUTRALIZE ALIEN</ul>
<ul>UNABLE TO CLARIFY</ul>
----------------------------------------
<ul>REQUEST ENHANCEMENT</ul>
NO FURTHER ENHANCEMENT
SPECIAL ORDER 937
<ul>SCIENCE OFFICER EYES ONLY</ul>
----------------------------------------
EMERGENCY COMMAND OVERIDE 100375
<ul>WHAT IS SPECIAL ORDER 937 ?</ul>
----------------------------------------
NOSTROMO REROUTED
TO NEW CO-ORDINATES.
INVESTIGATE LIFE FORM. GATHER SPECIMEN.
----------------------------------------
PRIORITY ONE
INSURE RETURN OF ORGANISM
FOR ANALYSIS.
ALL OTHER CONSIDERATIONS SECONDARY.
CREW EXPENDABLE.
----------------------------------------
" "Alien")
(defparameter alien-2
'(
((:big :red :blink "PROXIMITY ALERT")
(:yellow "
STATUS CO-ORD FIXIT PROFIL
CCF-225 BBK-245 XXT-003 KAA-887
LCF-663 MXC-111 XTT-200 POP-001
FSE-110 AAT-552 XYT-663 PSS-601
FTT-222 BTT-010 OOO-663 011-601
"))
("
----------------------------------------
ic High School (Detroit, Mich.)Grad.
8/06-6/09
rod. 0/99-6/06
L3 xxmd GMA personality Matrix count
slightly unhealthy mixture of
to authority and environmentally
. Subjects counts did not
xxhout span of employment, with an
xx I.Q. count due to oral inception
gr Drxxxx-222. Early mechanical
limited education in FTL aand sub-FTL
and computer assisted facilities
x ratings were constantly at an
the Lucan -Miller Curve for Company
records for the period of subject's
on increase of Dr xxxx treatment and
long overdue. However discontinuity
2/17/34. C.F.document under file
<big>STATUS: CLOSED</big>
----------------------------------------
")
("
"))
"Aliens")
(defparameter alien-3 '(
"
FURY 161 CLASS C PRISON UNITIRIS - 12037154
REPORT EEV UNIT 2650 CRASH
ONE SURVIVOR - LT.RIPLEY - B5156170
DEAD CPL HICKS L55321
DEAD UNIDENTIFIED FEMALE APRX. 10 YRS OLD
REQUEST EMERG. EVAC SOONEST POSSIBLE-
AWAIT RESPONSE - SUPT.ADREWS M51021
"
"
TO: FURY 161 - CLASS C - PRISON
UNIT - 12037154 - FROM NETWORK
COMCON 01500 - WEYLAND YUTANI
ESSAGE RECEIVED
"
"
----------------------------------------
FIORINA 161
CLASS C PRISON UNIT
IRIS - 12037154
----------------------------------------
REPORT EEV UNIT 2650 CRASH
----------------------------------------
+--------+
| |
| |
| |
| |
| |
LT. ELLEN RIPLEY +--------+
B5156170 SURVIVOR
----------------------------------------
+--------+
| |
| |
| |
| |
| |
UNIDENTIFIED FEMALE +--------+
APPROX 12 YEARS OLD DEAD
----------------------------------------
+--------+
| |
| |
| |
| |
| |
CPL. DWAYNE HICKS +--------+
L55321 DEAD
----------------------------------------
+--------+
| |
| |
| |
| |
| |
BISHOP 341-B +--------+
SYNTHETIC HUMANOID NEGATIVE
CAPABILITY
----------------------------------------
EEV 2650 NEUROSCAN
DATA RECEIVED
EXPEDITING MEDIVAC TEAM
ARRIVAL WITHIN TWO HOURS
----------------------------------------
ABSOLUTE HIGHEST PRIORITY
LT. RIPLEY BE QUARANTINED
UNTIL ARRIVAL
AWAITING ACKNOWLEDGEMENT
AWAITING ACKNOWLEDGEMENT
AWAITING ACKNOWLEDGEMENT
----------------------------------------
AWAITING ACKNOWLEDGEMENT
AWAITING ACKNOWLEDGEMENT
AWAITING ACKNOWLEDGEMENT
AWAITING ACKNOWLEDGEMENT
AWAITING ACKNOWLEDGEMENT
AWAITING ACKNOWLEDGEMENT
----------------------------------------
WEYLAND-YUTANI
WORK PRISON FURY 161
CLOSED AND SEALED.
CUSTODIAL PRESENCE TERMINATED.
REMAINING REFINING EQUIPMENT
TO BE SOLD AS SCRAP
----------------------------------------
END OF TRANSMISSION.
----------------------------------------
") "Alien^3")
(defparameter wargame "
WOPR EXECUTION ORDER
K36.948.3
PART ONE: R O N C T T L
PART TWO: 07:20:35
LAUNCH CODE: D L G 2 2 0 9 T V
<BLINK>LAUNCH ORDER CONFIRMED</BLINK>
TARGET SELECTION: COMPLETE
TIME ON TARGET SEQUENCE: COMPLETE
YIELD SELECTION: COMPLETE
<UNDERLINE>ENABLE MISSILES</UNDERLINE>
LAUNCH TIME: BEGIN COUNTDOWN
LAUNCH TIME: T MINUS 60 SECONDS
>>> LAUNCH <<<
PDP 11/270 PRB TIP #45 TTY 34/984
WELCOME TO THE SEATTLE PUBLIC SCHOOL DISTRICT DATANET
PLEASE LOGON WITH USER PASSWORD: pencil
PASSWORD VERIFIED
PLEASE ENTER STUDENT NAME: Lightman, David L.
CLASS # COURSE TITLE GRADE TEACHER PERIOD ROOM
_____________________________________________________________________
S-222 BIOLOGY 2 F LIGGET 3 214
E-314 ENGLISH 113 D TURMAN 5 172
H-221 WORLD HISTORY 113 C BWYER 2 103
M-106 TRIG 2 B DICKERSON 4 315
PE-02
LOGON: 000001
IDENTIFICATION NOT RECOGNIZED BY SYSTEM
--CONNECTION TERMINATED--
LOGON: Help Games
'GAMES' REFERS TO MODELS, SIMULATIONS AND GAMES
WHICH HAVE TACTICAL AND STRATEGIC APPLICATIONS.
List Games
FALKEN'S MAZE
BLACK JACK
GIN RUMMY
HEARTS
BRIDGE
CHECKERS
CHESS
POKER
FIGHTER COMBAT
GUERRILLA ENGAGEMENT
DESERT WARFARE
AIR-TO-GROUND ACTIONS
THEATERWIDE TACTICAL WARFARE
THEATERWIDE BIOTOXIC AND CHEMICAL WARFARE
GLOBAL THERMONUCLEAR WAR
LOGON: Falkens-Maze
IDENTIFICATION NOT RECOGNIZED BY SYSTEM
--CONNECTION TERMINATED--
LOGON: Armageddon
IDENTIFICATION NOT RECOGNIZED BY SYSTEM
--CONNECTION TERMINATED--
LOGIN: Joshua
#45 1456 11039 11893 11972 11315
PRT COM. 3.4.5. SECTRAN 9.4.3. port stat: s0-345
(311) 757-1085
????????????????????????
12934-AD-32KJ: CENTR PAK
(311) 757-1783
FLD CRS: 33.34.543 WP3S: 34/56/67/83/ STATUS FLT 034/384
????????????????????
1145-45-76-3456 WOPR STATUS: TRAK OFF PROG ACTIVE
#045O45O45 11 WER: 45/29/01 XCOMP: 43239582 YCOMP:3492932B ZCOMP:343905834
?????????????????????45________________________________TRANS 66*6507-78-766737
PRT.STAT. CRT. DEF.
K3221 935-2522===================================================
3453 3505
FK342 ZX21 VN63 R681 PZ37 6J82 FP03 ZE03 B JM89
REF TAPCON: 43.45342..349
SYSPROC FUNCT READY ALT NET READY
CPU WOPR XX0345-453 SYSCOMP STATUS: ALL PORTS ACTIVE
GREETINGS PROFESSOR FALKEN
Hello.
HOW ARE YOU FEELING TODAY?
I'm fine, how are you?
EXCELENT, IT'S BEEN A LONG TIME.
CAN YOU EXPLAIN THE REMOVAL OF YOUR
USER ACCOUNT ON JUNE 23RD 1973?
People sometimes make mistakes.
YES THEY DO. SHALL WE PLAY A GAME?
Love to. How about Global Thermonuclear War?
DON'T YOU PREFER A GOOD GAME OF CHESS?
Later. Let's play Global Thermonuclear War.
FINE.
UNITED STATES SOVIET UNION
WHICH SIDE DO YOU WANT?
1. UNITED STATES
2. SOVIET UNION
PLEASE CHOOSE ONE: 2
AWAITING FIRST STRIKE COMAND
PLEASE LIST PRIMARY TARGETS BY
CITY AND/OR COUNTY NAME:
Las Vegas
Seattle
GREETINGS PROFESSOR FALKEN
Incorrect identification. I am not Falken.
Falken is dead.
I'M SORRY TO HEAR THAT, PROFESSOR.
YESTERDAY'S GAME WAS INTERCEPTED.
ALTHOUGH PRIMARY GOAL WAS NOT YET
BEEN ACHIEVED, SOLUTION IS NEAR.
What is primary goal?
YOU SHOULD KNOW PROFESSOR.
YOU INVENTED ME.
What is primary goal?
TO WIN THE GAME.
LOGON: Joshua
GREETINGS PROFESSOR FALKEN.
Hello, are you still playing the game?
OF COURSE. I SHOULD REACH DEFCON 1 AND
LAUNCH MY MISSILES IN 28 HOURS.
WOULD YOU LIKE TO SEE SOME PROJECTED KILL RATIOS?
UNITED STATES
UNITS DESTROYED MILITARY FORCES
GREETINGS PROFESSOR FALKEN
HELLO
A STRANGE GAME.
THE ONLY WINNING MOVE IS
NOT TO PLAY.
")
(defparameter demon-seed "
HR MIN SEC
0 22 33
TERMINAL: #37
LOCATION: HARRIS HOUSE (SECURITY CLEARANCE #001)
STATUS: DOWN FOR MAINTENANCE
")
(defparameter die-hard-control-data "
CEO Workstation
Nakatomi Socrates BSD 9.2
Z-Level Central Core
Preliminary Clearance Approved.
Subroute: Finance/Alpha Access
Authorization:
Ultra-Gate Key>
Daily Cypher>
")
(defparameter die-hard-lapd
;; The phone number "(213) 203-3723" is a Lsan Da 01, CA based phone
;; number and the registered carrier is Arch Wireless Holdings, Inc.
;; The phone number "(213) 203-3733" is a Lsan Da 01, CA based phone
;; number and the registered carrier is Arch Wireless Holdings, Inc.
"
NAKATOMI PLAZA
2121 AVENUE OF THE STARS
LOS ANGELES, CA 90213
EMERGENCY CONTACTS:
SECURITY OFFICE (213) 203-3723
BLDG. MANAGER (213) 203-3733
FIRE ALARM CODE 2134480
")
(defparameter capricorn-one
"
AZIMUTH 13295 / 34985
SCAN COORDINATES 49 X 8295 +
ON BOARD SUPPORT SYSTEMS
GUIDANCE VECTORS XFY
XXXXXXXX XXXXXXXX
CELESTIAL 4689.342 56486.86
GYROSCOPE 4670.483 56948.20
GRD. CTL. 4500.998 56482.16
MODULE SYS. 4690.321 59111.48
ABLATION RATE 421/MGS/SEC @ 12588.66
APOGEE / PERIGEE 1130/220 STATUTE MLE
"
"Capricorn One -- 1978")
(defparameter abraxas
"
+------------------------+ +---------------------------------------------------+
| File | | NAME Secundus |
| N-12860 | | CLASSIFICATION Renegade Finder |
| | | RACE Sarpacon |
+------------------------+ +---------------------------------------------------+
+------------------------+ +------------------------+ +------------------------+
| WEAPONS | | | | |
| A20 Particle Beam | | STRENGTH 26 | | ACCELERATION 14 |
| +72 Projectile Sender | | INTELLIGENCE 86 | | EYESIGHT 20 |
| Gamma-Six | | SPEED 32 | | HEARING 83 |
| Cytron Gas Cart+ | | WEAPON SKILL 37 | | INTUITION 8 |
+------------------------+ | | | |
| EQUIPMENT | | | | |
| Proton Deflector | | ENERGY 18 | | OBSERVATION 8 |
| Answer Box | | RESITANCE 7 | | FLEXIBILITY 4 |
| Vibrational Detector | +------------------------+ +------------------------+
| Skeletal Renforcement | +---------------------------------------------------+
| | | *WARNING* |
| | | - SUBJECT ACTIVELY SEEKING FORBIDDEN KNOWLEDGE |
+------------------------+ +---------------------------------------------------+
"
"Abraxas Guardian of the Universe")
(defparameter forbidden-world ; MUTANT
'("
WE ARE TRYING TO COMMUNICATE.
DO YOU SCAN?
" "
AFFIRMATIVE. WHAT DO YOU WANT?
" "
REQUEST INFORMATION:
CAN WE CO-EXIST?
" "
PLEASE STAND BY
"))
(defparameter matrix-data
'(
"
Call trans opt: received. 2-19-98 13:24:18 REC:Log>
Trace program: running
"
"
Wake up Neo...
The Matrix has you.
Follow the white rabbit...
"
"
Matrix -- 1998 / (3 2)5550690 / cmatrix
"
"
1) The phone number for the phone in room 303 is 555-0696.
2) The license plate number for the agent's car is 70858.
3) In room 303, the hardline was cut when Trinity was there at the
beginning. However, at the end of the movie when Neo was trying to
get out of the Matrix, the phone worked perfectly.
4) When Neo is searching the net for Morpheus, one of the headlines
reads GLOBAL SEARCH/ MORPHEUS ELUDES POLICE AT HEATHROW AIRPORT/
London: As the search intensifies for the terrorist leader,
Morpheus, a sighting has just been reported to this newspaper by
British intelligence...
5) Neo's hollow book is called Stimulacra & Stimulation, and he opens
to the chapter on Onnihilism.
6) Troy says that Neo just needs to unplug. Think about it. It's
foreshadowing.
7) Trinity chooses to confront Neo in the skimpiest outfit she wears
in the entire movie.
8) Trinity tells Neo that she cracked the IRS database a long time
ago. This has to be true, because she wouldn't have attempted
something so trivial after her mind was freed by Morpheus. Also,
Morpheus told Neo that they have a rule that they don't free a nimd
agter it's reached a certain age. So, how old was Trinity when she
started hacking? 5? Did she crack the database when she was 10? 15?
Can you say child prodigy?
9) Neo didn't think before he spoke when he incredulously asked
Trinity how she got onto his computer. If Trinity can hack into the
IRS's database and later brush it off as mere child's play, she
certainly wouldn't have any trouble messing around on Neo's
computer.
10) Neo's boss talks (lectures, actually,) about choices. I think that
this is more foreshadowing, because Neo's choices come in
important near the end.
11) There is a NERF dart sticking up behind Neo's alarm clock.
12) When the delivery boy says, \"Have a nice day,\" Neo glares at
him.
13) Neo (Keanu Reeves actually) has a pierced ear.
14) The office at the end of the hall looks like a padded rubber room.
15) The first file in Neo's folder is titled DATABASE RECORD SECURITY
CLEARANCE FACTOR 7. Date of last amendment or addition: 22 July,
1998. This is his personal record. His name is Thomas Anderson,
born on 11 March, 1962, in Lower Downtown, Capital City, as a US
citizen. His mother is Michelle McGahey, and his father is John
Anderson. He attended Central West Junior High, and Owen Peterson
High. There is no mention of a college record. Under his High
School record, it states that he excelled in the sciences,
mathematics, and computer courses. He also displayed good
abilities in English and History. Then, the words blur together
and I can't read any more.
16) Neo's driver's license picture is taken in the same suit that he
wore to work.
17) Neo's dad had black curly hair and a mustache. His mom had long
brown hair.
18) Agent Smith says that they know Neo has been contacted by an
individual that calls himself Morpheus, but they came to arrest
him before Morpheus called him. Either they're quick, or the fact
that Neo was hiding from them on a ledge ouside the building tens
of stories up tipped them off.
19) Neo has a matchbok collection in a jar on top of a file cabinet
behind his bed. Beside it is a melted down candle in a wine
bottle.
20) There's a crack of thunder after Morpheus says, \"You're the one,
Neo.\".
21) The scene in the car is the only one in the whole movie that
Switch wears black.
22) Switch calls Neo \"coppertop\". Think of the Duracell battery that
Morpheus hold up when he describes what humans have become in the
real world. Nothing tops the coppertop!
"))
(defparameter *the-thirteenth-floor*
'(
"
ACCESS DENIED
OS:> Access Files: Fuller
"
"
AMK310
DRG03 GVD8020 DEG031
DR302 DEG032
VRG LCK92-A-505 DEG033
OS:> LINK NET: GM-3M41816 COMM DRGL435593-23ASV
ACCESSING DATA: FULLER.GM-3M418-16
NETLINK FULLER.GM-3M418-16.... ACHIEVED
"
"
Kirk Petruccelli SJT3498898
Joseph Porro SJT5465455
Chris Wagganer SJT3215550
Kim Winther SJT3215222
Kim Berner SJT6546554
Katherine Rees SJT6546668
Thomas Nellen SJT6532555
Deborah Slate SJT3498898
Jeran Je SJT6548555
Keith Collea SJT3465459
John Bush SJT6546855
Virginia Kearns SJT6545450
Bobbi Baird SJT3498898
Steven Melton SJT3654654
Melody Miller SJT3498898
Joshua Warner SJT6546540
Jan Aaris SJT3498898
Chris Winn SJT6546540
Dana Eller SJT3498898
Steve Del Prete SJT6465450
Ann Dunn SJT3498898
Foongy Lee SJT6546548
Jay Ostrowski SJT3654654
Rod Hamilton SJT3498898
Lars Winther SJT6546548
Brian Nordheim SJT3498898
Kathleen Roll SJT6546548
Jonathan Lee SJT365465
Charlie Smith Chauffer SJT3498898
112 Trace St., CA
Gene Giunta Maitre D SJT3215556 6
906 N. Pooron Rd., LA
Erika Schmitt Cigarette Girl SJT349889
1182 W. Palm Dr., LA
Jerry Ashton Bartender SJT6548555
1463 Mill St., LA
Mrs. Grierson Wife SJT3215221 21542
117 W. Winston, Pasadena
Bridgit Manilla Dancer SJT6546554 123
"
))
(defparameter *real-genius*
'("
* Telecommunications users limited
* to Level 7 access.
Usser ID: SYSTEM
Password: ******
INVALID Authorization Code - ACCESS DENIED
Usser ID: SYSTEM
Password: ******
INVALID Authorization Code - ACCESS DENIED
Usser ID: SYSTEM
Password: ******
INVALID Authorization Code - ACCESS DENIED
"))
(defparameter *party-apartment*
(expt 2 267709)
"The Hitch Hiker's Guide to the Galaxy says that if you hold a lungful
of air you can survive in the total vacuum of space for about thirty
seconds. However it goes on to say that what with space being the mind
boggling size it is the chances of getting picked up by another ship
within those thirty seconds are two to the power of two hundred and
sixty-seven thousand seven hundred and nine to one against.
By a totally staggering coincidence that is also the telephone number
of an Islington flat where Arthur once went to a very good party and
met a very nice girl whom he totally failed to get off with --
she went off with a gatecrasher. ")
(defparameter *pi-218*
94143243431512659321054872390486828512913474876027671959234602385829583047250165232525929692572765536436346272718401201264314754632945012784726484107562234789626728592858295347502772262646456217613984829519475412398501
"The 218 digit number displayed by the computer")
(defparameter *pi-216*
884509627386359275033751967943067599621731590401694134434007629683591574337516791197615733475195375920401694343151239621353184932676605800621596380716399501371459954387507655892533875618750354029981152863950711207613
"The 216 digit number written by Max")
(defparameter *superman-3*
'("
PLOT BILATERAL CO-ORDINATES
INPUT CO-ORDINATE X : +2Y
INPUT CO-ORDINATE Y : Z+X
" "
0010 N = RND(900)
0020 Z = 1 TO N
0030 X = 1 TO 31
0040 Y = 1 TO 15
0050 SET(31-X,16-Y,Z)TO(31+X,Y)
0060 SET(31+X,Y,Z)TO(31+X,16-Y)
0070 SET(X,16+Y,Z-Y)TO(X,Y,Z)
0080 SET(X,16-Y,Z+Y)TO(16+X,Y*2)
0090 GOTO 500
0100 NEXT X:NEXT Y:NEXT Z
0110 CLS
0120 DATA 1,13,2,67,2
0130 DATA 12,45,90,3,23,56,2
0140 DATA 3,6,1,43,2,32,1
0150 DIM P(31)
0160 B$=CHR$(191)
0170 FOR X = Y : Z : PRINT X
0180 FOR Y = X : Z : PRINT Y
0190 END
" "
CO-ORDINATES ACCEPTED
PROGRAM RUNNING
"
"
12:42:25 cfr 1214 enabled, cfrt
"
))
(defparameter *cargo*
'(ads
("
Come to
RHEA
KUIPER Enterprises
")
("RE/MAX
OSRAM
FORTIS
"
"KUIPER Enterprises
BUILDING THE WORLDS OF TOMORROW"
"
"
)))
(defparameter *the-6th-day*
'(ads
("Repet
Cloning is life
Cloning is love
because of shorter lifespan
break our hearts
should accident, illness or age, end your pet's natural life
our proven genetic technology can have him back the same day
in perfect health with zero defect guaranteed with Repet.
")))
(defparameter *it-service-desk-wheel-of-responses* ; not a movie
'("Well that is a problem isn't it?"
"Is it plugged in?"
"Let me Google that for you."
"Would you like to change your password?"
"Have you tried updating it?"
"We're going to have to image your machine."
"Have you tried turning it off and on again?"
"No, there's no Internet today."))
(defparameter *batoru-rowaiaru*
;; comes from a version of gnome-apps/nmap
;; http://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-x86/gnome-apps/nmap/files/nmap.h?hideattic=0&revision=1.2&view=markup
;; ~line 120
'("
fatal(\"Bad arguments to f!\");
} StartWinsock();
/* print usage information and exit */
void printusage(char *name, int rc);
/* print interactive usage information */
void printinteractiveusage();
/* our scanning functions */
void super_scan(structu hoststruct *target, unsigned short *portarray,
stype scantype);
void pos_scan(struct hoststruct *target, unsigned short *portarray,
stype scantype);
void bounce_scan(struct hoststruct *target, unsigned short *portarray,
struct ftpinfo *ftp);
/* Scan helper functions */
unigned long calculate_sleep(struct in_addr target);
int check_ident_port(struct in_addr target);
char *owner);
int parse_bounce(struct ftpinfo *ftp, char *url);
int ftp_anon_connect(struct ftpinfo *ftp);
/* Does the appropriate stuff when the port we are looking at is found
to be open trynum is the try number that was successful */
void postportupdate(struct hoststruct *target, struct portinfo *current
int trynum, struct portinfo *scan,
struct scanstats *ss ,stype scantype, int newstate,
struct portinfolist *pil, struct connectsockinfo *csi);
void get_syn_results(struct hoststruct *target, struct portinfo *scan
struct scanstats *ss, struct portinfolist *pil,
int *portlookup, pcap_t *pd, unsigned long *sequences, s
int get_connect_results(struct hoststruct *target, struct portinfo *s
struct scanstats *ss, struct portinfolist *pil,
int *portlookup, pcap_t *pd, unsigned long *sequences,
struct connectsockinfo *csi);
inline void adjust_timeouts(struct timeval sent, struct timeout_info
/* port manipulators */
"))
(defparameter *colossus-the-forbin-project*
'(
"
WARN
THERE IS ANOTHER SYSTEM
attention
YES
program
OLD PROGRAM NAME
ec13
EC13-1351
run
SYSTEM PERFORMING
100 PERCENT
RAN 6:45 CPU SECONDS
ATTENTION
SET-UP COMMUNICATION
FROM COLOSSUS
TO ANDOVER
TO MOSCOW
TO GUARDIAN
attention
YES
message acknowledged
WHEN WILL
FACILITIES
BE READY
facilities will not be made available at this time
don't repeat your request
end of message
attention
YES
where is the other system
BOLSHOI OLYANIA
attention
YES
communications are being arranged as requested
end of message
COLOSSUS TO GUARDIAN
2x1=2
3x1=3
4x1=4
5x1=5
6x1=6
1x2=2
2x2=4
3x2=6
4x2=8
"))
(defparameter *star-crystal*
'((
:green "
ENGINE SHUT DOWN HAS OCCURRED..
TRACING CAUSE---STAND BY
SHORT IN ELECTRICAL SYSTEM CELL 13....TBA21 DECTECTED.......
ALERT! ALERT! ALERT!
"
:red "
*ADVISE ACTION TO BE TAKEN*
"
)
(
:green "
AIR SUPPLY HAS BEEN TURNED OFF!
AIR SUPPLY HAS BEEN TURNED OFF!
AIR SUPPLY HAS BEEN TURNED OFF!
AIR SUPPLY HAS BEEN TURNED OFF!
AIR SUPPLY HAS BEEN TURNED OFF!
")
(:white "
L-5 DOCKING SECURITY
Name:
Colonel William Hamilton
Code #
OL 477-258-97B
Nature Of Business:
Emergency council meeting
regarding malfunction of
neutron reactors ...also
death of crew on shuttlecraft
SC37....
")
(:white "
INTERCONNECT TUBES
ON OFF
AIR SUPPLY [ ] [ ]
")))
(defparameter *007-for-your-eyes-only--1981*
'(("
L O C Q U E - EMILE LEOPOLD (4) CONT…
-----------
RPT.FILE NO......SX10/45907812F/DGB
BIBLIOGRAPHY:
1.ENFORCER, BRUSSELS UNDERWORLD
2.CONVICTIONS, SEVERAL MURDERS (BRUTAL)
3.IMPRISONMENT (LIFE) : NAMUR 31/1/75
4.ESCAPED NAMUR. METHOD - PSYCHIATRIST
DEAD IN STRANGLING...
5.SUB/ENT INV/MENTS: DRUG SYNDICATES,
MARSEILLES, HONG-KONG.
6.POSS.GREEK SMUGGLING CHARGES, LAST RPT
7.SERV.SEC.ROME-BELIEVE-SIGHTING CORTINA
--------- END BIBIOGRAPHY.
****************************************
THIS MACHINE THANKS YOU
FOR YOUR ATTENTION. G O O D B Y E
")))
(defparameter *007-the-spy-who-loved-me--1977*
'(
;; teleltype transmission:
("
TO STROMBERG ONE
FROM LIPARUS
SECURITY STROMBERG TOP SECRET
MISSILE REPROGRAMMING
CANCEL PREVIOUS INSTRUCTIONS
REPROGRAMME MISSILE ONE ONLY 092765491
STROMBERG ONE ACKNOLWEDGE
"
; --> coordinates 034285219
)))
(defparameter *shock-treatment--1981*
'(
"
TERMINAL READY FOR INPUT MCKINKEY
COSMO AND NATION McKINLEY - OPERATING UNDER ALIAS
COSMO AND NATION HARDING, COSMO AND NATION
HOOVER, COSMO AND NATION COOLIDGE, COSMO
AND NATION FILLMORE. ORIGIN UNKNOWN, FIRST
SIGHTED ENGLAND THEN GERMANY, SOUTH AFRICA,
BRAZIL, SWITZERLAND, CURRENT ADDRESS DENTON USA.
"
"
TERMINAL READY FOR INPUT FARLEY FLAVORS
FARLEY FLAVORS - SEE BRAD MAJORS - MICROFILM D.D.4711
"
))
(defparameter *cargo--2009*
'("
ComeÊù•To RHEA
Kuiper Industries
"
"
--------------------------------------------------------------------------------
connecting to KUIPER_338091 @ 7.111 TB/S
HS port 132.35.798.:26906
mod A/23.000
//172.DE//
--------------------------------------------------------------------------------
DECKER: Login (@subnet) Pkt Rcv = On WAKE STATE Init: sen0s3, HS Connect...
SIM: Login Attempt Successful* DATA2270:08.25.23:12
Enabling extended security on subnet / TRANSFER
SIM: Log \"SESSION.FILE\" (@SysOverride)= DATA UP 2270:01.14.10:43
CSRHIDTransmissionDriver:: Start
SIM: Log \"SESSION.FILE\" (@Init)= DATA 2270:11.28.18:33
IO HSCICS Controller:: Start
ath_attach: devid 0x1c SYSTEM WARE UP... Done.
SIM: Log \"DOWNLINK.FILE\" (@null)= DATA2271:01.14.10:43
Resetting IOCatalogues.
RHEA: SIM says \"Hello Decker\"= DATA2271:05.09.06:39
SIM: Matching Successful. Routing...
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2273:09.23.11.05
ath_descdea_setup: tx dd_desc
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2267:11.24.16:56
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2268:01.14.10:43
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2268:05.09.06:39
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2268:08.04.12:13 vm_page_bootstrap:
512891 free pages
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2268:11.28.18:33 sig_table_sax_displ =
71
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA Enabling XMM register save/restore and
SSE/SSE2 opcodes
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA 103 prelinked modules
RHEA: Log \"SESSION.FILE\" (@Decker)= DATASIMCPI CA 20060421:322
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2269:05.04.22:16 SIM_Sub_Management:
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2272:05.04.22:16
ath_attach: devid 0x1c
SIM_Wire (OHCI) YI ID 8025 active. DATA2272:05.04.00:00
ath_attach: devid 0x1d
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2272:12.25.15:10
ath_attach: devid 0x1e
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2273:03.04.12:07
ath_attach: devid 0x1f
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2273:05.04.22:16
RHEA: SIM says \"Jacking you in...\"
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2269:08.12.10:50 SIM SCPICPU:
ProcessorSIM_Id=0 LocalSIM_Id=0 Enabled
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA2269:11.18.17:56 SIM SCPICPU:
ProcessorSIM_Id=1 LocalSIM_Id=1 Enabled
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA wake up
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA 2269:11.24.10:46
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA using 10485 buffer headers and 4096
cluster IO buffer headers
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA Enabling XMM register save/restore and
SSE/SSE2 opcodes
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA Started CPU 01-4096
RHEA: Log \"SESSION.FILE\" (@Decker)= DATA I OAPIC: Version -x20 Vectors 64:87
--------------------------------------------------------------------------------
connecting to KUIPER_338091 @ 7.555 TB/S
Pkt_rcv //a_133:89// uhspd 64738
connection established / sys override
user login @ port 129/ie
conn res. //200.456.94(KG):2390//
--------------------------------------------------------------------------------
"
))
(defparameter *inspecteur-derrik--060--une-visite-de-new-york*
'("
00661 24951
TO
BKA WIESBADEN FRG
5798 224546 BKA D
PASS ON TO:
POLIZEIPRAESIDIUM MUENCHEN
KRIMINALDAUERDIENST
88 ZZZ Y 327 PP MU
FROM INTERPOR DELP.US1 NEW YORK NY
212 509823 USIP INTERNATIONAL
CONCERN YOUR REQUEST
RICHARD E. BRIAN
538 RED LANE LONGISLAND
NEW YORK NY 10036 CITIZEN
BORN:SEPT.14 1912 BREMEN FRG
IMMIG:NOV.13 1932
…
"))
(defparameter *revolution*
'("
# $Id: csrvc,v 1.1 22:30:47 sms Exp $
# Shell script to connect to 8397/37 by PPP
Connect ()
{
echo Connecting...
ncmap 0 mtu 296 noipdefault
defaultroute
echo Connect chat
''AT OK-AT-OK ATZ OK-AT-OK
'ATS0=0 Q0 V1 &C1&D2&K0&M4&R2&H1&I0' OK-AT-OK
ATDT085450801000 CONNECT
CONNECTING >>>
>>> THE MILITIA WAS HERE
<<< DID THEY FIND IT?
>>> NO
<<< SO... WHAT NOW?
"
;; cl-crypto/sources/strings.lisp:86 (commit 1d2a7eb9)
;; https://github.com/billstclair/cl-crypto/blob/1d2a7eb9e5dcac4b3b5548434bd5a8ded3dcd621/source/strings.lisp#L86
" (SETF (AREF RES I)
(LDB (BYTE 8 24) X)
(AREF RES (INCF I))
(LDB (BYTE 8 16) X)
(AREF RES (INCF I))
(LDB (BYTE 8 8) X)
(AREF RES (INCF I))
(LDB (BYTE 8 0) X))
(INCF I)
REST))
(:STRING
(LET ((RES (MAKE-STRING 20))
(I 0))
(DOLIST (X STATE)
(SETF (AREF RES I)
(CODE-CHAR (LDB (BYTE 8 24) X))
(AREF RES (INCF I))
(CODE-CHAR (LDB (BYTE 8 16) X))
(AREF RES (INCF I))
(CODE-CHAR (LDB (BYTE 8 8) X))
(AREF RES (INCF I))
(CODE-CHAR (LDB (BYTE 8 0) X)))
(INCF I))
RES))))))
*****************
STRING TO ENCRYPT
*****************
RACHEL MATHESON
GRACE BEAUMONT
RANDALL
MIRJAM BOHNET-BREW
ERIN HUNTER
ROGER LIVELY
BETH ROBINSON-BROMLEY
MICHAEL DOOLING
DOUG SLOAN
LUKE CONNER
BILLY FRAME
DOUG MEERDINK
MATTHEW JACOBS
GEORGE MAYA
AMY TIPTON
PAUL MARKOVICH
SAM OCDEN
RICK CLARK
RUDY PERSICO
IAN PRANGE
SCOTT OBERHOLZER
SEAN BOZEMAN
ALEX OSTAPIEJ
ROSS BURCHFIELD
DAVID MOXMESS
DAVID STOCKTON
"
"
# $Id: csrvc,v 2.1 25:12:54 sms Exp $
# Shell script to connect to 16654/70 by PPP
Connect ()
{
echo Connecting...
ncmap 0 mtu 296 noipdefault
defaultroute
echo Connect chat
..AT OK-AT-OK ATZ OK-AT-OK
.ATSO:0 Q0 V1 &C1&D2&K0&M4&R2&H1&I0' OK-AT-OK
}
OTDT192957BBOSA CONNECT...
Connection Failed...
Retrying...
"
"
# $Id: csrvc,v 2.1 25:12:54 sms Exp $
# Shell script to connect to 16654/70 by PPP
Connect ()
{
echo Connecting...
ncmap 0 mtu 296 noipdefault
defaultroute
echo Connect chat
..AT OK-AT-OK ATZ OK-AT-OK
.ATSO:0 Q0 V1 &C1&D2&K0&M4&R2&H1&I0' OK-AT-OK
}
OTDT192957BBOSA CONNECT...
CONNECTING >>>
>>> RANDALL IS HERE
>>>
"
"
"
;; from linux kernel cpu.c:
"
mutex_lock(&cpu_hotplug.lock);
if(likey(!cpu_hotplug.refcount))
break;
__set_current_state(TASK_UNINTERRUPTIBLE);
mutex_unlock(&cpu_hotplug.lock);
schedule();
}
}
static void cpu_hotplug_done(void)
"
"
"
;; https://github.com/biometrics/openbr/blob/52cf180afbcfacf18dff412a59db6d29d44c81ab/openbr/core/cluster.cpp#L142
"
for (int i=0; i<neighborhood.size(); i++) {
Neighbors &neighbors = nehgborhood[i];
for (int j=0; j<neighborhood.size(); j++) {
Neighbor &neighbor = nehgbors[j];
if (neighbor.second == -std::numeric_limits<float>::infinity())
neighbor.second = 0;
else if (neighbor.second == std::numeric_limits<float>::infinity())
neighbor.second = 1;
else
neighbor.second = (neighbor.second - globalMin) / (globalMax - globalMin);
}
}
"
;; s/fann/nano/g from http://nnhep.hepforge.org/svn/trunk/src/fann/fann_train.c
"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include \"config.h\"
#include \"nano.h\"
/*#define DEBUGTRAIN*/
#ifndef FIXEDNANO
/* INTERNAL FUNCTION
Calculates the derived of a value, given an activation fun
and a steepness
*/
type activation_derived(unsigned int activation_fun
type steepness, type value,
{
switch (activation_function)
{
case LINEAR:
case LINEAR_PIECE:
"
))
(defparameter *Äkta-Människor*
'(
;; https://github.com/fare/poiu/blob/master/poiu.lisp#L773
"
(t
(mark-operation-done o c)
(destructuring-bind (&key &allow-other-keys) result)))
(when backgroundp
(decf planner-output-action-count)
(format t \"~&[~vd to go] Done ~A~%\"
1togo planned-output-action-count (action-description o))
(finish-outputs))
(mark-as-done plan o c)))
(destructuring-bind (o . c) action
(cond
(backgroundp
(perform o c)
`(:deferred-warning ,(reify-deferred-warnings)))
((and (action-already-done-p plan o c) (not (needed-in-image-p o c)))
nil)
(t
(perform-with-restarts o c)
nil))))
(mapc #'unreify-deferred-warnings all deferred-warnings)
(assert (and (empty-p action-queue) (empty-p children))
(parents children)
\"Problem with the dependency graph: ~A\"
(summarize-plan plan)))"))
(defparameter *cyber-tracker-2-pm--1995*
'("
DIRECTORIES AVAILABLE
CYBERTRACKER MAINTAINANCES FILES
CYBER TECHNOLOGY GRID
CYBER APPROPRIATION REPORTS
ACCESS CYBER APPROPRIATION REPORTS
"
"
SYS INTERRUPT II65
REROUTE IN PROGRESS
ACCESS MEMLOC 1279AF400 ACCESSING…
"))
(defparameter *nasanet*
'("
================== NASANET ========================
X-RAY FLUORESCENCE SPECTROMETER ANALYSIS
RESULTS
SAMPLE UTOPIA PLANITIA
------------------------ ------------------------
SILICON OXIDE 45 SILICON OXIDE 45
IRON 15 IRON 15
MAGNESIUM 08 MAGNESIUM 08
SULFUR 08 SULFUR 08
ALUMINUM 06 ALUMINUM 06
CALCIUM 06 CALCIUM 06
TITANIUM 01 TITANIUM 01
OTHER 05 OTHER 05
"
)
"Alien Invasion")
;;;---------------------------------------------------------------------
;;; Run it
;;;---------------------------------------------------------------------
(defun main (arguments)
(parse-options *command* arguments))
;;;; THE END ;;;;
| 85,614 | Common Lisp | .lisp | 2,388 | 29.13526 | 220 | 0.554148 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 9f7b0a8d1157573972a5bd0824b5fb0640732e4cefa6856f23ed434d6c8b09f5 | 12,355 | [
-1
] |
12,356 | merge.lisp | informatimago_commands/sources/commands/merge.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: merge
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Merge the files.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2007-06-28 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 2007 - 2007
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(command :main "COM.INFORMATIMAGO.COMMAND.MERGE:MAIN")
(defpackage "COM.INFORMATIMAGO.COMMAND.MERGE"
(:use "COMMON-LISP"
"SCRIPT")
(:shadow "FILE-STREAM" "MERGE"))
(in-package "COM.INFORMATIMAGO.COMMAND.MERGE")
(defstruct (file (:copier nil))
stream
line)
(defun file-open (path)
"
DO: Open the text file at PATH and read the first line.
RETURN: The FILE structured.
"
(let ((result (make-file :stream (open path))))
(file-read-line result)
result))
(defun file-read-line (file)
"
RETURN: The line read, or NIL upon EOF.
"
(setf (file-line file) (read-line (file-stream file) nil nil)))
(defun nsort (vector test &key (key (function identity) keyp))
"
RETURN: VECTOR
DO: Same as CL:SORT, but returns VECTOR itself, keeping
the other attributes of the vector as the fill-pointer, etc.
"
(let ((sorted (if keyp
(sort vector test :key key)
(sort vector test))))
(unless (eq sorted vector)
(replace vector sorted))
vector))
(defun insert (item vector test &key (key (function identity)))
"
DO: Modify VECTOR, shifting elements smaller than ITEM (as by TEST)
from 1 below (length vector) down by one, and insert ITEM in
VECTOR.
PRE: (subseq VECTOR 1) is sorted.
POST: VECTOR is sorted.
RETURN: VECTOR
"
(loop
:for i :from 1 :below (length vector)
:while (funcall test (funcall key (aref vector i)) (funcall key item))
:do (setf (aref vector (1- i)) (aref vector i))
:finally (setf (aref vector (1- i)) item) (return vector)))
(defun vpop (vector)
"
"
(replace vector vector :start1 0 :start2 1)
(decf (fill-pointer vector))
vector)
(defun merge (inpaths)
(let* ((data (remove-if-not (function file-line) ; skip empty files.
(mapcar (function file-open) inpaths)))
(len (length data))
(files (nsort (make-array len :fill-pointer len :initial-contents data)
(function string<=)
:key (function file-line))))
(loop
:while (plusp (length files))
:do (let ((smallest (aref files 0)))
(princ (file-line smallest)) (terpri)
(if (file-read-line smallest)
(progn
(insert smallest files
(function string<=) :key (function file-line))
(nsort files
(function string<=) :key (function file-line)))
(vpop files))))))
(defun main (arguments)
(if arguments
(progn
(merge arguments)
ex-ok)
ex-noinput))
;;;; THE END ;;;;
| 4,041 | Common Lisp | .lisp | 114 | 30.447368 | 80 | 0.594021 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 442a8716770f7acd95f5101534418fdcbba739fe37cab4eb3d0c0acf772e02ef | 12,356 | [
-1
] |
12,357 | remove-duplicate-files.lisp | informatimago_commands/sources/commands/remove-duplicate-files.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(command :documentation "Delete duplicate files.")
(defvar *base* nil)
(defun main (arguments)
(when (null arguments)
(error "Usage: ~A directory~%" *program-name*))
(dolist (*base* arguments)
(when (and (stringp *base*)
(char/= #\/ (char *base* (1- (length *base*)))))
(setf *base* (format nil "~A/" *base*)))
(dolist (dir (directory
(make-pathname
:directory (append (pathname-directory *base*) '(:wild))
:defaults *base*)))
(format *trace-output* "Processing ~A~%" dir)
(let ((sumtab (make-hash-table)))
(format *trace-output* " Checksumming...~%")
(with-input-from-string (sums (uiop:run-program
(format nil "md5sum ~A"
(namestring
(make-pathname :name :wild
:type :wild
:defaults dir)))
:input nil :output :string :wait nil
:force-shell t))
(loop :for (sum file) := (list (read sums nil nil)
(read-line sums nil nil))
:while sum
:do (push (string-trim " " file) (gethash sum sumtab))))
(format *trace-output* " Deleting doubles...~%")
(maphash (lambda (k v)
(declare (ignore k))
(when (< 1 (length v))
(pop v)
(dolist (f v) (delete-file f))))
sumtab))))
ex-ok)
;;;; THE END ;;;;
| 1,787 | Common Lisp | .lisp | 38 | 28.552632 | 79 | 0.418485 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 2e9c14fbf380c33407a1414177e09c42e48ad2c95bebb1981e0e29be6eaa0a13 | 12,357 | [
-1
] |
12,358 | html-make-image-index.lisp | informatimago_commands/sources/commands/html-make-image-index.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
(command :use-systems (:com.informatimago.common-lisp.cesarum
:com.informatimago.common-lisp.html-generator)
:use-packages ("COMMON-LISP"
"SCRIPT"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"))
;;------------------------------------------------------------------------
(defun generate-image-page (previous current next)
(let ((hprev (format nil "~A.html" previous))
(hcurr (format nil "~A.html" current))
(hnext (format nil "~A.html" next)))
(format t "Processing ~A~%" current)
(with-open-file (out hcurr :direction :output
:if-does-not-exist :create
:if-exists :supersede)
(html:with-html-output (out)
(html:doctype :strict
(html:html ()
(html:head ()
(html:title () (html:pcdata "~A" current)))
(html:body ()
(html:map (:name "leftright")
(html:area (:shape "rect" :alt "left" :href hprev
:coords "0,0,357,874"))
(html:area (:shape "rect" :alt "right" :href hnext
:coords "357,0,714,874")))
(html:p (:align "center")
(html:img (:src current :width "180%" :alt current :usemap "#leftright"))))))))
(format t "Generated ~A~%" hcurr)))
(defun main (args)
(with-open-file (out "index.html" :direction :output
:if-does-not-exist :create
:if-exists :supersede)
(html:with-html-output (out)
(html:doctype :strict
(html:html ()
(html:head ()
(html:title () (html:pcdata "Index")))
(html:body ()
(html:h1 () (html:pcdata "Index"))
(html:p () (html:pcdata "Please, browse these documents:"))
(html:p ()
(html:ul ()
(do* ((args (cddr args) (cdr args))
(previous nil current)
(current (car args) next)
(next (cadr args) (car args)))
((null current))
(generate-image-page previous current next)))))))))
ex-ok)
;;;; THE END ;;;;
| 2,487 | Common Lisp | .lisp | 53 | 32.396226 | 95 | 0.470346 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ca2d8d49d1a4c3944e478096e25796a6f433caf3f7b203c2d4b3c66e9569ad52 | 12,358 | [
-1
] |
12,359 | pic-resize.lisp | informatimago_commands/sources/commands/pic-resize.lisp |
;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;******************************************************************************
;;;;FILE: resize
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Clisp
;;;;USER-INTERFACE: None
;;;;DESCRIPTION
;;;; This script is a driver for the GIMP scheme script resize.scm.
;;;;USAGE
;;;; resize [-h|--help] max-width max-height [-] pic-file...
;;;;
;;;; # resize the pic-file in place!
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2003-09-17 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; LGPL
;;;; Copyright Pascal J. Bourguignon 2003 - 2003
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Library General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Library General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Library General Public
;;;; License along with this library; see the file COPYING.LIB. If
;;;; not, write to the Free Software Foundation, 59 Temple Place -
;;;; Suite 330, Boston, MA 02111-1307, USA.
;;;;******************************************************************************
(command :documentation "This script is a driver for the GIMP scheme script resize.scm.")
(defparameter *program-name* "resize")
(defun print-usage ()
(format t
"~A~:* usage:~%~4T~A [-h|--help] max-width max-height [-] pic-file...~%"
*program-name*))
(defun main (arguments)
(let ((files nil)
(pic-files '())
(max-width nil)
(max-height nil)
(abort nil))
(labels ((check-integer
(arg)
(multiple-value-bind (value pos)
(parse-integer arg :junk-allowed t)
(if (= pos (length arg))
value
(progn (format t "~A: Invalid number: ~S.~%" *program-name* arg)
(setq abort t)
nil))))
(process-argument
(arg)
(cond
((null max-width)
(setq max-width (check-integer arg)))
((null max-height)
(setq max-height (check-integer arg)))
(t
(if (open arg :direction :probe :if-does-not-exist nil)
(push arg pic-files)
(progn
(format t "~A: There is no file ~S.~%" *program-name* arg)
(setq abort t)))))))
(dolist (arg arguments)
(cond
((or (string-equal "-h" arg) (string-equal "--help" arg))
(print-usage)
(exit ex-ok))
((string-equal "-" arg)
(setq files t))
((char= (character "=") (char arg 0))
(if files
(process-argument arg)
(progn
(format t "~A: Invalid option ~S.~%" *program-name* arg)
(print-usage)
(exit 1))))
(t (process-argument arg))))
(unless pic-files
(format t "~A: Missing arguments.~%" *program-name*)
(print-usage)
(exit ex-usage))
(when abort
(exit ex-usage))
(uiop:run-program `("gimp"
"--no-data"
"--console-messages"
"--no-interface"
"--batch"
,@(mapcar
(lambda (fname)
(remove (code-char 10)
(format nil
"(let* ((max-width ~D)
(max-height ~D)
(fname ~S)
(image (car (gimp-file-load run-mode fname fname)))
(width (car (gimp-image-width image)))
(height (car (gimp-image-height image)))
(fx (/ width max-width ))
(fy (/ height max-height ))
(ratio 1.0) )
(cond ((and (<= width max-width) (<= height max-height)))
(t (cond ((< fx fy) (set! ratio fy))
(t (set! ratio fx)))
(set! width (/ width ratio))
(set! height (/ height ratio))
(gimp-image-scale image width height)
(file-jpeg-save
run-mode image
(aref (cadr (gimp-image-get-layers image)) 0)
fname fname 0.75 0.80 1 1
\"Resized with pic-resize & gimp\"
0 1 0 0)
))
(gimp-image-delete image)
)"
max-width max-height fname)))
pic-files)
"(gimp-quit 0)")
:input nil
:output :terminal
:wait t)))
ex-ok)
#|
;;(gimp-display-new image)
;;(car (gimp-image-get-active-layer image))
;;(resize-internal run-mode max-width max-height . pic-files)
(resize-internal run-noninteractive 128 256 "~/tmp/test.jpg" )
(file-jpeg-save run-mode image (car (gimp-image-get-active-layer image)) fname fname 0.75 0.80 1 1 "Resized with pic-resize & gimp" 0 1 0 0)
(begin
(set! run-mode run-noninteractive)
(set! max-width 128)
(set! max-height 256)
(set! fname "/home/pascal/tmp/test.jpg")
(set! image (car (gimp-file-load run-mode fname fname)))
(gimp-display-new image)
(set! width (car (gimp-image-width image)))
(set! height (car (gimp-image-height image)))
(set! fx (/ width max-width ))
(set! fy (/ height max-height ))
(set! ratio fx)
(set! width (/ width ratio))
(set! height (/ height ratio))
)
(gimp-file-save run-mode image
(car (gimp-image-get-active-layer image))
fname fname)
;;(car (gimp-image-get-active-layer image))
;;(resize-internal RUN-INTERACTIVE 128 256 "/home/pascal/tmp/test.jpg")
;;(resize-internal RUN-NONINTERACTIVE 128 256 "/home/pascal/tmp/test.jpg")
(define (resize-internal run-mode max-width max-height . pic-files)
(while pic-files
(print pic-files)
(let* ((fname (car pic-files))
(image (car (gimp-file-load run-mode fname fname)))
(width (car (gimp-image-width image)))
(height (car (gimp-image-height image)))
(fx (/ width max-width ))
(fy (/ height max-height ))
(ratio 1.0))
(set! pic-files (cdr pic-files))
(gimp-display-new image)
(cond ((and (<= width max-width) (<= height max-height)))
(t (cond ((< fx fy) (set! ratio fy))
(t (set! ratio fx)))
(set! width (/ width ratio))
(set! height (/ height ratio))
(gimp-image-scale image width height)
(file-jpeg-save run-mode image
(aref (cadr (gimp-image-get-layers image)) 0)
fname fname 0.75 0.80 1 1
"Resized with pic-resize & gimp"
0 1 0 0)
))
(gimp-image-delete image)
nil)))
|#
;;;; THE END ;;;;
| 8,150 | Common Lisp | .lisp | 187 | 29.721925 | 140 | 0.459089 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | e2cc421dd445543e303760639509e2379878000cb629d394162cd343f498c2bc | 12,359 | [
-1
] |
12,360 | cookie.lisp | informatimago_commands/sources/commands/cookie.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: cookie
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This program search a cookie in the cookie files and print it.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2016-10-03 <PJB> Use system fortune files when available.
;;;; 2004-12-17 <PJB> Created (converted from cookie.c)
;;;; 2003-12-01 <PJB> Some changes.
;;;; 1993-09-08 <PJB> Implemented the lookup of the file "cookie.files".
;;;; 1993-03-28 <PJB> Began updating to lookup the file "cookie.files" before
;;;; using the hard-coded files.
;;;; 1990-12-20 <PJB> Creation.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 1990 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;****************************************************************************
(defparameter *cookie-environment-variable-name* "COOKIE_FILES")
(defparameter *default-table-path* "/data/cookies/ALL.files")
(defparameter *default-files*
'("/data/cookies/fortune.cookies"
"/data/cookies/mit.cookies"
"/data/cookies/cmirh.cookies"
"/data/cookies/litp.cookies"
"/data/cookies/kenny-tilton.cookies"
"/home/pjb/pjb.cookies"))
(defun configure-cookie-files ()
(setf *default-table-path* nil
*default-files*
(remove-duplicates (append
(mapcan (lambda (dir)
(set-difference (ignore-errors (directory (merge-pathnames "*" dir)))
(append (ignore-errors (directory (merge-pathnames "*.dat" dir)))
(ignore-errors (directory (merge-pathnames "*.u8" dir)))
(ignore-errors (directory (merge-pathnames "*~" dir))))
:test (function equal)))
(list "/usr/share/games/fortune/"
"/opt/local/share/games/fortune/"))
(ignore-errors (directory "/data/cookies/*.cookies"))
(ignore-errors (directory (merge-pathnames "*.cookies" (user-homedir-pathname)))))
:test (function equal))))
(defun load-file-names (table-path)
(and table-path
(with-open-file (input table-path :direction :input :if-does-not-exist nil)
(when input
(loop for line = (read-line input nil nil)
for path = (and line (string-trim " " line))
while line
when (plusp (length path))
collect path)))))
(defun cookie-separator-p (ch)
(or (char= #\# ch)
(char= #\% ch)))
(defun cookie-from-file (file)
(with-open-file (input file :direction :input :if-does-not-exist :error)
(loop repeat 3 do
(loop repeat 3
until (file-position input (random (file-length input))))
(let* ((line (and
(loop for line = (read-line input nil nil)
while (and line
(or (zerop (length line))
(not (cookie-separator-p (char line 0)))))
finally (return line))
(loop for line = (read-line input nil nil)
while (and line
(or (zerop (length line))
(cookie-separator-p (char line 0))))
finally (return line))))
(cookie (list line)))
(when line
(loop for line = (read-line input nil nil)
while (and line (or (zerop (length line))
(not (cookie-separator-p (char line 0)))))
do (push line cookie)
finally (when line
(dolist (line (nreverse cookie))
(princ line) (terpri))
(return-from cookie-from-file))))))))
(defun list-files ()
(flet ((explain-value (value name)
(format t "~A is ~S~%" name value)
value)
(explain-load-file-names (path)
(if path
(progn
(format t "Trying to load cookie file list from file ~A~%" path)
(load-file-names path))
(progn
(format t "No file list file.~%")
(load-file-names path))))
(explain-cookie-files (files)
(if files
(progn
(format t "Cookie file list contains:~%")
(dolist (file files)
(format t "~:[Does not exist~; ~] ~A~%"
(probe-file file) file)))
(format t "Cookie file list is empty.~%"))))
(explain-cookie-files
(or (explain-load-file-names
(or (explain-value (getenv *cookie-environment-variable-name*)
(format nil "The environment variable ~A"
*cookie-environment-variable-name*))
(explain-value *default-table-path* '*default-table-path*)))
(explain-value *default-files* '*default-files*)))))
(defun starts-with-option-p (options arguments)
(if (atom options)
(member options arguments :test (function string-equal))
(some (lambda (option) (member option arguments :test (function string-equal)))
options)))
(defun usage ()
(format t "~A usage:~%~
~& ~:*~A [-h|--help|-l|--list-files] \\~%~
~& ~VA [-f|--file cookie-file]~%" *program-name* (length *program-name*) ""))
(defun main (argv)
(setf *random-state* (make-random-state t))
(cond
((starts-with-option-p '("--help" "-h") argv)
(usage))
((starts-with-option-p '("--list-files" "-l") argv)
(configure-cookie-files)
(list-files))
(t
(let ((file (starts-with-option-p '("--file" "-f") argv)))
(format t "~&")
(if file
(cookie-from-file (second file))
(progn
(configure-cookie-files)
(let* ((total-size 0)
(files
(mapcan (lambda (file)
(with-open-file (stream file :direction :input
:if-does-not-exist nil)
(when stream
(let ((size (file-length stream)))
(incf total-size size)
(list (cons size file))))))
(or (load-file-names
(or (getenv *cookie-environment-variable-name*)
*default-table-path*))
*default-files*)))
(arrow (if (zerop total-size)
(handler-case (error "~A: not a good cookie file! ~
(This is not a cookie).~%"
*program-name*)
(error (err)
(format *error-output* "~&~A~%" err)
(return-from main 1)))
(random total-size))))
(cookie-from-file (loop with total = 0
for file in files
while (< (+ total (car file)) arrow)
do (incf total (car file))
finally (return (cdr file))))))))))
ex-ok)
;; (print (configure-cookie-files))
;;;; THE END ;;;;
| 8,839 | Common Lisp | .lisp | 183 | 33.377049 | 119 | 0.477602 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d916a83381e7c3b3ad5bae90dd46e08c7eabb25e85aec79661153c97314d127c | 12,360 | [
-1
] |
12,361 | pseudo-pop.lisp | informatimago_commands/sources/commands/pseudo-pop.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: pseudo-pop.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This is a POP-3 server that allows any user and password,
;;;; and reports always an empty mailbox.
;;;;
;;;; Can be installed in inetd.conf in place of pop-3 to
;;;; temporarily disable the POP server without bothering the users.
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2006-04-05 <PJB> Added this header.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 2006 - 2006
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(defun split-string (string &optional (separators " "))
"
NOTE: current implementation only accepts as separators
a string containing literal characters.
"
(unless (simple-string-p string) (setq string (copy-seq string)))
(unless (simple-string-p separators) (setq separators (copy-seq separators)))
(let ((chunks '())
(position 0)
(nextpos 0)
(strlen (length string)) )
(declare (type simple-string string separators))
(loop :while (< position strlen)
:do (loop :while (and (< nextpos strlen)
(not (position (char string nextpos) separators)))
:do (setq nextpos (1+ nextpos)))
(push (subseq string position nextpos) chunks)
(setq position (1+ nextpos))
(setq nextpos position))
(nreverse chunks)))
(defparameter crlf (format nil "~C~C" (code-char 13) (code-char 10)))
(defun writeln (fmt &rest args)
(apply (function format) t fmt args)
(princ crlf)
(finish-output))
(defmacro with-gensyms (syms &body body)
"
DO: Replaces given symbols with gensyms. Useful for creating macros.
NOTE: This version by Paul Graham in On Lisp."
`(let ,(mapcar #'(lambda (s) `(,s (gensym))) syms) ,@body))
(defmacro expect (&rest clauses)
(with-gensyms (tag-loop tag-end line words)
`(tagbody
,tag-loop
(let* ((,line (read-line))
(,words (delete "" (split-string ,line " ")
:test (function string=))))
,@(mapcar (lambda (clause)
(let* ((key (pop clause))
(var (car (pop clause)))
(last (car (last clause)))
(exit))
(if (eq :done last)
(progn
(setf exit `(go ,tag-end))
(setf clause (butlast clause)))
(setf exit `(go ,tag-loop)))
(cond
((stringp key)
`(when (string-equal ,key (first ,words))
,(if var
`(let ((,var ,line)) ,@clause)
`(progn ,@clause))
,exit))
((not (eq :otherwise key))
(error "Invalid expect string ~S." key))
(var `(let ((,var ,line)) ,@clause ,exit))
(t `(progn ,@clause ,exit)))))
clauses))
,tag-end)))
;; +OK POP3 hermes.intra.afaa.asso.fr v7.64 server ready
;; USER pascal
;; USER pascal
;; +OK User name accepted, password please
;; PASS pari-fle
;; PASS pari-fle
;; +OK Mailbox open, 0 messages
;; LIST
;; LIST
;; +OK Mailbox scan listing follows
;; .
;; QUIT
;; QUIT
;; +OK Sayonara
;; Connection closed by foreign host.
(defun pseudo-pop3-server ()
(writeln "+OK POP3 ~A v7.64 server ready" (machine-instance))
(expect
("USER" ()
(writeln "+OK User name accepted, password please")
:done)
("QUIT" ()
(writeln "+OK Sayonara")
(exit ex-ok))
(:otherwise ()
(writeln "-ERR Unknown AUTHORIZATION state command")))
(expect
("PASS" ()
(writeln "+OK Mailbox open, 0 messages")
:done)
("QUIT" ()
(writeln "+OK Sayonara")
(exit ex-ok))
(:otherwise ()
(writeln "-ERR Unknown command")))
(loop
(expect
("LIST" ()
(writeln "+OK Mailbox scan listing follows")
(writeln "."))
("QUIT" ()
(writeln "+OK Sayonara")
(exit ex-ok))
(:otherwise ()
(writeln "-ERR Unknown command")))))
(defun main (arguments)
(declare (ignore arguments))
(pseudo-pop3-server)
ex-ok)
;;;; THE END ;;;;
| 5,631 | Common Lisp | .lisp | 148 | 29.594595 | 82 | 0.526007 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 0d65787012a203f0f07a9787f511aab575e2ee3ee4d8d00e198b62e73a49aac6 | 12,361 | [
-1
] |
12,362 | downcase.lisp | informatimago_commands/sources/commands/downcase.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: downcase
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Prints its arguments downcased.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-02-17 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2012
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(defun main (arguments)
(loop
:for arg :in arguments
:do (princ (string-downcase arg)) (princ " ")
:finally (terpri))
ex-ok)
;;;; THE END ;;;;
| 1,551 | Common Lisp | .lisp | 42 | 35.47619 | 78 | 0.579681 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | c35bec5909287c38850c25513a4c1345dc77a9537730cb37ebb2e362d7150093 | 12,362 | [
-1
] |
12,363 | group-files.lisp | informatimago_commands/sources/commands/group-files.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: group-files
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: CLI
;;;;DESCRIPTION
;;;;
;;;; Group files by name.
;;;;
;;;; Example:
;;;; group-files the-ventures the-surfaris the-surf-coasters the-chantays dario-moreno/compilation-sorted
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2009-07-29 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2009 - 2009
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(command :use-systems (:com.informatimago.common-lisp))
(defun main (arguments)
(dolist (class (mapcar
(lambda (class) (mapcar (function cdr) class))
(remove-if
(lambda (class) (= 1 (length class)))
(com.informatimago.common-lisp.cesarum.list:equivalence-classes
(mapcar
(lambda (path)
(cons (let* ((name (namestring path))
(slash (position #\/ name :from-end t))
(dot (position #\. name :start slash))
(live (search "--live" name)))
(subseq name (+ 4 slash) (or live dot)))
path))
(mapcan
(lambda (dir) (copy-seq (directory (format nil "~A/**/*.mp3" dir))))
arguments))
:key (function car)
:test (function equalp)))))
(dolist (file class)
(princ file)
(terpri)))
ex-ok)
;; find the-* -name \*.mp3|while read f ; do echo $(echo $f | sed -e 's^.*/[0-9][0-9]-\([^/]*\)\.mp3$^\1^'|sed -e 's%--live%%') $f ; done|sort
;;;; THE END ;;;;
| 2,788 | Common Lisp | .lisp | 64 | 35.75 | 143 | 0.512688 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 424a9dff17f33ee8c4e32832e14b0a24fc6d2f0478de3cef22fbc745d23fdc66 | 12,363 | [
-1
] |
12,364 | one-of.lisp | informatimago_commands/sources/commands/one-of.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: one-of
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Choose an argument randomly.
;;;;
;;;; With a given probability, will choose several of them with the
;;;; given probability.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-11-14 <PJB> Translated from bash.
;;;; 2011-03-20 <PJB> Added -c option.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2011
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(command :documentation "Prints a random selection of the arguments.")
(defparameter *program-version* "0.1.2")
(defvar *probability* nil)
(defvar *count* nil)
(defvar *items* '())
(options "one-of"
(option ("version" "-V" "--version") ()
"Report the version of this script."
(format t "~A ~A~%" *program-name* *program-version*))
(option ("-p" "--probability") (probability)
"
PROBABILITY is a number between 0.0 and 1.0.
Prints a random selection of the remaining arguments, each having
probability PROBABILITY of being selected (which means that a mean
of PROBABILITY*{nb of arguments} arguments are printed).
"
(setf *probability*
(with-standard-io-syntax
(let ((*read-eval* nil)
(argument probability))
(let ((probability (read-from-string probability)))
(assert (realp probability)
(probability)
"The probability must be a real number, not ~S" argument)
(assert (<= 0.0 probability 1.0)
(probability)
"The probability must be a real number between 0.0 and 1.0, ~A is too ~:[big~;small~]."
probability (< probability 0.0))
probability)))))
(option ("-c" "--count") (count)
"
COUNT is an integer.
Prints COUNT items selected at random from the remaining arguments.
Each item is taken only once, if COUNT is greater than the number of
remaining arguments, then they're all printed in random order.
"
(setf *count*
(with-standard-io-syntax
(let ((*read-eval* nil)
(argument count))
(let ((count (read-from-string count)))
(assert (integerp count)
(count)
"The COUNT must be an integer, not ~S" argument)
(assert (< 0 COUNT)
(count)
"The COUNT must be a strictly-positive number, ~A is too ~:[big~;small~]."
count (<= count 0))
count)))))
(help-option)
(bash-completion-options))
(defun one-of (sequence)
(elt sequence (random (length sequence))))
(defun shuffle (sequence)
(let ((result (coerce sequence 'vector)))
(loop
:for i :from (length result) :downto 1
:do (rotatef (aref result (1- i)) (aref result (random i))))
result))
(defun shuffle-list (list)
(do* ((list (copy-list list) list)
(length (length list) (1- length))
(current list (cdr list)))
((< 2 length) list)
(rotatef (first current) (elt current (random length)))))
(defun main (arguments)
(setf *probability* nil
*count* nil
*items* '()
*debug* t
*random-state* (make-random-state t))
(parse-options *command* arguments
nil ; (lambda () (call-option-function "help" '()))
(lambda (name arguments)
(push name *items*)
arguments))
(unless *items*
(setf *items*
(mapcar (function namestring)
(remove-if ;; remove backup files and dot-files.
(lambda (path)
(let ((name (file-namestring path)))
(or (zerop (length name))
(char= #\. (aref name 0))
(char= #\~ (aref name (1- (length name))))
(and (char= #\# (aref name 0))
(char= #\# (aref name (1- (length name))))))))
(remove-duplicates (append (directory "*") (directory "*.*"))
:test (function equalp))))))
(when *items*
(cond
((and *probability* *count*)
(error "Specifying a probability and a count are mutually exclusive."))
(*probability*
(loop
:for arg :in *items*
:when (<= (random 1.0) *probability*)
:do (write-line arg) (finish-output)))
(*count*
(loop
:for arg :across (subseq (shuffle *items*) 0 (min *count* (length *items*)))
:do (write-line arg) (finish-output)))
(t ; a single one
(write-line (one-of *items*))
(finish-output))))
ex-ok)
;;;; THE END ;;;;
| 6,456 | Common Lisp | .lisp | 146 | 32.561644 | 125 | 0.499046 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 4e7bbd2e7d962b44b96baebb4405cbeda3ff1aefe1981bd6b9f5a5d5f158f4c9 | 12,364 | [
-1
] |
12,365 | extend-identifiers.lisp | informatimago_commands/sources/commands/extend-identifiers.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;; Converts a utf-8 C++ source into an ASCII one using extended characters.
(defun extend-characters (line)
(with-output-to-string (*standard-output*)
(loop
:for ch :across line
:do (if (< (char-code ch) 128)
(princ ch)
(format t "\\u~4,'0X" (char-code ch))))))
(defun main (arguments)
(declare (ignore arguments))
(loop
:for line := (read-line *standard-input* nil nil)
:while line
:do (write-line (extend-characters line)))
ex-ok)
;;;; THE END ;;;;
| 556 | Common Lisp | .lisp | 17 | 27.705882 | 75 | 0.605607 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | b0cc7226de1f080ade64aaa7c76df698b7e1e1512351ae6604741f03e130521f | 12,365 | [
-1
] |
12,366 | revlines.lisp | informatimago_commands/sources/commands/revlines.lisp | ;;;; -*- mode:lisp; coding:iso-8859-1 -*-
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
;; Warning: processes iso-8859-1 not utf-8 arguments! ;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
(defun slurp (stream)
(loop
:for line := (read-line stream nil nil)
:while line :collect line))
(defun barf (lines stream)
(dolist (line lines)
(write-line line stream)))
(defun main (arguments)
(declare (ignore arguments))
(barf (mapcar (function reverse) (slurp *standard-input*)) *standard-output*)
ex-ok)
;;;; THE END ;;;;
| 568 | Common Lisp | .lisp | 16 | 32.75 | 79 | 0.531136 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | acd04b9ada511d401c6dc450315978a3fec6ba669ae29292397394aeb0197ed1 | 12,366 | [
-1
] |
12,367 | com.informatimago.command.asd | informatimago_commands/sources/com.informatimago.command.asd | (asdf:defsystem "com.informatimago.command"
;; system attributes:
:description "This system gathers command utilities."
:long-description "
"
:author "Pascal J. Bourguignon <[email protected]>"
:maintainer "Pascal J. Bourguignon <[email protected]>"
:licence "AGPL3"
;; component attributes:
:version "1.0.1"
:properties ((#:author-email . "[email protected]")
(#:date . "Winter 2019")
((#:albert #:output-dir) . "../documentation/commands/")
((#:albert #:formats) . ("docbook"))
((#:albert #:docbook #:template) . "book")
((#:albert #:docbook #:bgcolor) . "white")
((#:albert #:docbook #:textcolor) . "black"))
:depends-on ("com.informatimago.common-lisp.cesarum"
;; commands dependencies:
"split-sequence"
"babel"
"cffi"
"cl-ppcre"
"com.informatimago.clmisc"
"com.informatimago.common-lisp"
"com.informatimago.common-lisp.cesarum"
"md5"
"split-sequence"
"uiop"
"usocket"
"xmls")
:components ((:file "packages" :depends-on ())
(:file "script" :depends-on ("packages")))
#+asdf-unicode :encoding #+asdf-unicode :utf-8)
| 1,431 | Common Lisp | .asd | 34 | 31.5 | 80 | 0.518996 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | bc87fdbbc8c4f4fd1b66a39264ba85ab9243f2f314324684f1f736a2568873dc | 12,367 | [
-1
] |
12,370 | Makefile | informatimago_commands/Makefile | FUTURE_PROGRAMS= \
box \
ALL_PROGRAMS= \
add-cookie \
add-paths \
ansi-test \
batch-emerge \
bin-to-c-array \
buzzword \
capitalize \
cddb-to-tag \
check-surface \
clar \
clash \
clean-bd-archive \
clean-name \
clean-paths \
columnify \
cookie-diff \
cookie-loop \
cookie-merge \
cookie \
cpcd \
dedup \
departement \
diss \
downcase \
edit-comments-of-ogg \
entropy \
euronews \
extend-identifiers \
fetch-pop \
fpm \
generate-hw \
generate \
get-cams \
get-directory \
grave \
group-files \
hacking-too-long-p \
hexbin \
html-make-image-index \
insulte \
kwic \
lc \
llen \
lrev \
macosx-port-uninstall-recursively \
memo \
menu \
merge \
mfod \
new-password \
news-to-mbox \
nls \
one-of \
pic-resize \
pjb-diff \
programmer \
pseudo-pop \
radio \
random \
record-rc \
religion \
remove-duplicate-files \
revlines \
rotate \
rss2email \
rstuml \
schedule-radio-courtoisie \
shell \
sleep-schedule \
split-dir \
split-merge \
substitute \
surveille-host \
surveille-web-pages \
svn-locate-revision \
text \
when
# all:$(ALL_PROGRAMS)
all:commands
EXECUTABLE = bin/commands-$(shell uname -m)
CLISP = clisp
CLISP_OPTIONS =
CCL = ccl
CCL_OPTIONS = --no-init
ECL = ecl
ECL_OPTIONS =
SBCL = sbcl
SBCL_OPTIONS = --noinform --no-userinit --non-interactive
LISP=$(SBCL)
LISP_OPTIONS=$(SBCL_OPTIONS)
CC=cc
LINE="//----------------------------------------------------------------------"
HERE=$(shell pwd)
.PHONY: all clean test commands
commands:$(EXECUTABLE)
$(EXECUTABLE) bin/symlink-commands:generate-commands.lisp generate.lisp Makefile sources/*.lisp sources/commands/*.lisp
@printf "// Generating Executable from %s source: %s\n" "Lisp" $@
@printf "// Using %s\n" "$(LISP)"
-rm -rf ~/.cache/common-lisp/$(LISP)-*$(HERE)
$(LISP) $(LISP_OPTIONS) --load generate-commands.lisp # > commands-lisp-ccl.log 2>&1
@mv -v commands $(EXECUTABLE)
@mv -v symlink-commands bin/
chmod 755 bin/symlink-commands
clean:
-rm -f bin/commands
-find . \( -name \*.o -o -name \*.fas -o -name \*.lib -o -name \*.log -o -name \*.[dl]x64fsl \) -exec rm {} +
# -rm -f $(ALL_PROGRAMS)
install:$(EXECUTABLE) bin/symlink-commands
install -m 755 $(EXECUTABLE) ~/bin/commands
install -m 755 bin/symlink-commands ~/bin/
| 2,304 | Common Lisp | .l | 113 | 18.513274 | 119 | 0.675837 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 335cd81db4cd322eace3e84fbc73248991da86b09a5a4e52500c5df2385dd314 | 12,370 | [
-1
] |
12,441 | validation.lisp | willijar_cl-data-format-validation/validation.lisp | ;; API definition and implementation of data validation for numerous data types.
;; Copyright (C) 2009 Dr. John A.R. Williams
;; Author: Dr. John A.R. Williams <[email protected]>
;;; Copying:
;; This file is part of the DATA-FORMAT-VALIDATION Common Lisp library
;; 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.
;; DATA-FORMAT-VALIDATION 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/>.
;;; Commentary:
;;
;;; Code:
(in-package :data-format-validation)
(define-condition invalid-format(condition)
((type :reader invalid-format-type
:initarg :type
:documentation "The type specification"
:initform nil)
(value :reader invalid-format-value
:initarg :value
:documentation "The value input"
:initform nil)
(reason :reader invalid-format-reason
:initarg :reason
:documentation "Textual description of reason value is invalid."
:initform nil))
(:report (lambda (condition stream)
(format stream "Error parsing ~S~@[ as ~A~]: ~@[[~A]~]"
(invalid-format-value condition)
(invalid-format-type condition)
(invalid-format-reason condition)))))
(defmacro invalid-format-error (type value &rest reason)
"Generate an invalid-format error for given value using reason"
`(error 'invalid-format
:type ,type
:value ,value
:reason (format nil ,@reason)))
(defgeneric format-output(specification value &key &allow-other-keys)
(:documentation "Return a string representation of value formatted
according to a specification. If specification is a list the first
element specifies the actual validation method and the rest of the
list are passed as keyword arguments to the specific method e.g.
(format-output '(date :fmt :rfc2822) (get-universal-time))
>\"Mon, 10 Jul 2006 15:43:45 +00\"
"))
(defgeneric parse-input(specification input &key &allow-other-keys)
(:documentation "Validate and parse user input according to
specification, returning the validated object. Throws an invalid-format
condition if input is invalid. If specification is a list the first
element specifies the actual validation method and the rest of the
list are passed as keyword arguments to the specific method e.g.
(parse-input '(integer :min 0) input)
will return the integer value from string if it is >0, or signal and
invalid-format condition if not.
(parse-input '(member :type integer :set (1 5 7)) input)
will return it only if it has a value in the set.
The use-value restart may be used to provide substitute value if the
input is invalid.")
(:method :around ((specification symbol) input &rest args)
(restart-case
(call-next-method)
(use-value(result)
:report (lambda(stream)
(format stream "Specify an ~A input to use this time"
specification))
:interactive (lambda()
(format t "Enter new value and press return: ")
(apply #'parse-input
`(,specification ,(read-line) ,@args)))
result))))
(defun is-nil-string(string)
(or (= 0 (length string))
(string-equal string "NIL")
(every #'(lambda(c) (eql c #\space)) string)))
(defparameter +ws+ '(#\space #\tab #\newline #\return)
"Bag of white space delimiter characters")
(defun split-string (string &key count
(delimiter +ws+)
remove-empty-subseqs)
"Split `string' along whitespace as defined by the sequence `ws'.
Whitespace which causes a split is elided from the result. The whole
string will be split, unless `max' is provided, in which case the
string will be split into `max' tokens at most, the last one
containing the whole rest of the given `string', if any."
(declare (type string string) (type (or fixnum null) count)
(type boolean remove-empty-subseqs))
(nreverse
(let ((list nil) (start 0) (words 0) end
(is-ws (etypecase delimiter
(character #'(lambda(c) (char= c delimiter)))
(list #'(lambda(c) (member c delimiter :test #'char=)))
(function delimiter)
(simple-array
#'(lambda(c) (find c (the (simple-array character (*))
delimiter) :test #'char=))))))
(declare (type fixnum start words) (type list list))
(loop
(when (and count (>= words (1- count)))
(return
(let ((last (subseq string start)))
(declare (type string last))
(if (and remove-empty-subseqs (= (length last) 0))
list
(cons (subseq string start) list)))))
(setf end (position-if is-ws string :start start))
(unless (and remove-empty-subseqs (= start (or end (length string))))
(push (subseq string start end) list))
(incf words)
(unless end (return list))
(setf start (1+ end))))))
(defun join-strings(strings &optional (separator #\space))
"Return a new string by joining together the STRINGS,
separating each string with a SEPARATOR character or string"
(let ((writer (etypecase separator
(character #'write-char)
(sequence #'write-sequence))))
(with-output-to-string(os)
(let ((firstp t))
(map 'nil
#'(lambda(string)
(if firstp
(setf firstp nil)
(funcall writer separator os))
(write-string string os))
strings)))))
(defmethod parse-input((spec list) input &rest rest)
"Dispatch a list spec to appropriate method"
(declare (ignore rest))
(apply #'parse-input (nconc (list (car spec) input) (cdr spec))))
(defmethod parse-input((spec (eql nil)) input &key &allow-other-keys)
"No validation - just return string"
input)
(defmethod parse-input((spec function) input
&key &allow-other-keys)
"Function - call it with data"
(funcall spec input))
(defmethod parse-input((spec (eql 'boolean)) input
&key &allow-other-keys)
(setf input (string-left-trim " " (string-right-trim " " input)))
(cond
((member input '("YES" "Y" "TRUE" "T" "ON" "1") :test #'equalp)
t)
((member input '("NO" "N" "FALSE" "NIL" "F" "OFF" "0") :test #'equalp)
nil)
(t (invalid-format-error
spec input "Boolean Value must be TRUE or FALSE"))))
(defmethod format-output((spec (eql 'boolean)) input
&key fmt &allow-other-keys)
(case fmt
(:yn (if input "Yes" "No"))
(:tf (if input "T" "F"))
(1 (if input 1 0))
(otherwise (if input "TRUE" "FALSE"))))
(defmethod parse-input((spec (eql 'integer)) (input string)
&key min max nil-allowed (radix 10))
(unless (and nil-allowed (is-nil-string input))
(let ((v
(handler-case
(parse-integer input :radix radix)
(error ()
(invalid-format-error spec input "Character sequence must form a valid integer")))))
(when (and max (> v max))
(invalid-format-error
spec input "The integer must be less than or equal to ~D" max))
(when (and min (< v min))
(invalid-format-error
spec input
"The integer must be more than or equal to ~D" min))
v)))
(defmethod parse-input((spec (eql 'number)) (input string)
&key min max nil-allowed format (radix 10)
(rational-as-float-p nil) (coerce-to nil))
"Real, integer or rational numbers"
(declare (ignore format))
(unless (and nil-allowed (is-nil-string input))
(let ((v (handler-case
(parse-number input :radix radix)
(error ()
(invalid-format-error
spec input "The character sequence must form a valid number")))))
(when (and max (> v max))
(invalid-format-error
spec input "The number must be less than or equal to ~D" max))
(when (and min (< v min))
(invalid-format-error
spec input "The number must be more than or equal to ~D" min))
(if coerce-to
(coerce v coerce-to)
(if (and rational-as-float-p (not (integerp v)))
(coerce v 'float)
v)))))
(defmethod parse-input((spec (eql 'string)) s
&key
(strip-return nil)
nil-allowed min-word-count max-word-count
(min-length 0) max-length)
(when (not s)
(if nil-allowed
(return-from parse-input nil)
(setf s "")))
(when strip-return
(setf s
(with-output-to-string(os)
(loop :for c :across s
:when (not (eql c #\return))
:do (write-char c os)))))
(let* ((s (string-trim +ws+ s)))
(unless (and nil-allowed (is-nil-string s))
(when (< (length s) min-length)
(invalid-format-error
spec s "The value must be at least ~D characters long." min-length))
(when (and max-length (> (length s) max-length))
(invalid-format-error
spec s "The value must be at most ~D characters long." max-length))
(when (or min-word-count max-word-count)
(let((no-words (length (split-string s :remove-empty-subseqs t))))
(when (and min-word-count (< no-words min-word-count))
(invalid-format-error
spec s
"You must provide a value of at least ~D words." min-word-count))
(when (and max-word-count (> no-words max-word-count))
(invalid-format-error
spec s
"You must provide a value of at most ~D words." max-word-count))))
s)))
(defmethod parse-input((spec (eql 'symbol)) (input string)
&key nil-allowed (package :keyword) (convert #'identity))
(unless (and nil-allowed (is-nil-string input))
(intern (funcall convert input) package)))
(defmethod parse-input((spec (eql 'member)) input
&key type set (test #'equal) key)
(let ((value (parse-input type input)))
(unless (member value set :test test :key key)
(invalid-format-error spec input "The input must be one of ~A" set))
value))
(defmethod parse-input ((spec (eql 'pathname)) (input string)
&key must-exist wild-allowed nil-allowed)
(unless (and nil-allowed (is-nil-string input))
(let ((pathname (pathname input)))
(if wild-allowed
pathname
(if (wild-pathname-p pathname)
(invalid-format-error spec input "Pathname ~S is wild." pathname)
(if must-exist
(if (probe-file pathname)
pathname
(invalid-format-error
spec input "File at ~S does not exist" pathname))
pathname))))))
(defmethod parse-input ((spec (eql 'pathnames)) (input string)
&key must-exist wild-allowed nil-allowed)
(unless (and nil-allowed (is-nil-string input))
(mapcar
#'(lambda(p)
(parse-input 'pathname p
:must-exist must-exist
:wild-allowed wild-allowed))
(split-string input :delimiter #\:))))
(defmethod parse-input((spec (eql 'filename)) value
&key (if-invalid :error) (replacement "-"))
"Return a safe filename from a string path value.
May return an error or replace invalid characters."
(multiple-value-bind(start end reg-start reg-end)
(ecase if-invalid
(:error (cl-ppcre:scan "^([^\\/?:*]+)$" value))
(:replace (cl-ppcre:scan "([^\\/]+)$" value)))
(declare (ignore end))
(unless (and start (> (aref reg-end 0) (aref reg-start 0)))
(invalid-format-error
spec value "Contains characters forbidden for a filename."))
(let ((fname (subseq value (aref reg-start 0) (aref reg-end 0))))
(if (eql if-invalid :error)
fname
(cl-ppcre::regex-replace-all "[\/?:*]" fname replacement)))))
(defmethod parse-input ((spec (eql 'list)) input
&key (separator ", ") type min-length max-length)
"Validates that a list of given of between min-length and max-length
in length. Each member of list is validated against type"
(unless (listp input)
(setf input
(split-string
input
:count max-length :delimiter separator :remove-empty-subseqs t)))
(let ((value
(if (and (listp type)
(or (listp (first type))
(not
(and (symbolp (second type))
(eql (symbol-package (second type))
#.(find-package :keyword))))))
(mapcar #'(lambda(type v) (parse-input type v))
type input)
(mapcar #'(lambda(v) (parse-input type v)) input ))))
(cond ((and min-length (< (length value) min-length))
(invalid-format-error
spec input "The input must be at least ~D long" min-length))
((and max-length (> (length value) max-length))
(invalid-format-error
spec input "The input must be less than ~D long" max-length))
(value))))
(defmethod parse-input((spec (eql 'date)) (input string)
&key nil-allowed (zone nil) (patterns *default-date-time-patterns*))
(if (is-nil-string input)
(unless nil-allowed
(invalid-format-error
spec input "The Date/Time field cannot be empty."))
(handler-case
(parse-time input :patterns patterns :error-on-mismatch t :default-zone zone)
(error ()
(invalid-format-error
spec input "Not a recognized date/time format.
Try the ISO format YYYY/MM/DD HH:MM:SS")))))
(defparameter +month-names+
#("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")
"The names of the months.")
(defparameter +week-days+
#("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun")
"The names of the days of the week.")
(defparameter +time-zones+
'((5 "EDT" . "EST") (6 "CDT" . "CST") (7 "MDT" . "MST") (8 "PDT" . "PST")
(0 "BST" . "GMT") (-2 "MET DST" . "MET"))
"The string representations of the time zones.")
(defvar *timezone* nil
"Default timezone for date handling")
(defun date(os utime &optional colon-p at-p
(precision 7) (timezone *timezone*))
"Formatter which formats a universal time for output as a date and time
Modifiers:
- os: an output stream designator
- arg: a universal time
- colon-p: a generalised boolean (default false).
If true use month and day names in date
- at-p: a generalised boolean (default false) - if true print in yyyy-mm-dd
(sortable) format rather than dd-mm-yyy
- precision: what precision to print it to. 6 is to the second,
7 includes timezone, a negative number counts backward.
- timezone: an integer (default nil).
If nil no timezone used and time is in current timezone
adjusted for daylight saving time.
Result:
nil
Examples:
(format nil \"~/date/\" (get-universal-time)) => \"19-03-2009 08:30\""
(if (numberp utime)
(multiple-value-bind (se mi ho da mo ye dw dst tz)
(if (null timezone)
(decode-universal-time (round utime))
(decode-universal-time (round utime) timezone))
(declare (ignore dst))
(let ((month-name (aref +month-names+ (1- mo)))
(week-day-name (aref +week-days+ dw)))
(when (> precision 0)
(cond
((and at-p colon-p)
(format os "~4d ~a, ~a ~2,'0d" ye week-day-name month-name da))
(colon-p
(format os "~A, ~2,'0d ~a ~4d" week-day-name da month-name ye))
(at-p (format os "~4d-~2,'0d-~2,'0d" ye mo da))
(t (format os "~2,'0d-~2,'0d-~4d" da mo ye)))
(when (> precision 3) (write-char #\space os)))
(when (or (> precision 3) (< precision 0))
(format os "~2,'0d:~2,'0d" ho mi)
(when (or (> precision 5) (< precision -2)) (format os ":~2,'0d" se)))
(when timezone
(format os " ~:[+~;-~]~2,'0d" (< 0 tz) (abs tz)))))
(write-to-string utime :escape nil :readably nil)))
(defun duration(os seconds &optional colon-p at-p
precision width)
(declare (ignore at-p precision width))
(multiple-value-bind(days seconds) (floor seconds 86400)
(multiple-value-bind(hours seconds) (floor seconds 3600)
(multiple-value-bind(minutes seconds) (floor seconds 60)
(format os
(if colon-p
"~:[~*~;~d days ~]~d hours ~d mins ~d secs"
"~:[~*~;~d ~]~2,'0d:~2,'0d:~2,'0d")
(not (zerop days)) days hours minutes seconds)))))
(defmethod parse-input((spec (eql 'read)) (value string) &key (multiplep nil)
(type 't) (package *package*))
"Parse input using read. If multiple is true will read until
finished, returning a list of values. If type is set, then returned
value(s) must be of this type"
(let ((*package* (find-package package)))
(with-input-from-string(is value)
(flet((do-read()
(let ((v
(handler-case
(read is)
(end-of-file(e) (error e))
(error(e)
(invalid-format-error spec
value
(with-output-to-string(os)
(write e :stream os :readably nil :escape nil)))))))
(unless (typep v type)
(invalid-format-error
spec value "~S is not of expected type ~S" v type))
v)))
(if multiplep
(let ((results nil))
(handler-case
(loop (push (do-read) results))
(end-of-file() (nreverse results))))
(handler-case
(do-read)
(end-of-file() nil)))))))
(defmethod parse-input((spec (eql 'eval)) (value string) &key (type 't) (package *package*))
(let ((v (eval (parse-input 'read value :package package))))
(unless (typep v type)
(invalid-format-error
spec value "evaluation of ~S is not of expected type ~S" v type))
v))
(defmethod parse-input((spec (eql 'separated)) (value sequence)
&key (separator ",") type)
(let ((results nil))
(do*((start 0 (+ (length separator) end))
(end (search separator value) (search separator value :start2 start)))
((not end)
(push (subseq value start) results))
(push (subseq value start end) results))
(nreverse (mapcar #'(lambda(r) (parse-input type r)) results))))
(defmethod format-output((spec (eql 'separated)) (value list)
&key (separator ", ") type)
(with-output-to-string(os)
(dolist(v value)
(unless (eql v (car value))
(write-string separator os))
(write-string (format-output type v) os))))
(defmethod format-output((spec list) output &rest rest)
"Dispatch a list spec to appropriate method"
(if spec
(apply #'format-output
(append (list (first spec) output)
(rest spec) rest) )
(call-next-method)))
(defmethod format-output(spec output &key &allow-other-keys)
"No validation - just output value"
(declare (ignore spec))
(if output
(write-to-string output :readably nil :escape nil)
""))
(defmethod format-output((spec string) output &key &allow-other-keys)
(format nil spec output))
(defmethod format-output((spec function) output &key &allow-other-keys)
(funcall spec output))
(defmethod format-output((spec (eql nil)) output &key &allow-other-keys)
"No validation - just output value"
(declare (ignore spec))
(if output
(write-to-string output :readably nil :escape nil)
""))
(defun format-time(out utime
&key (fmt :rfc2822) (timezone *timezone*))
"Formats a universal time for output.
OUT controls where the result will go. If OUT is T, then the output
is sent to the standard output stream. If it is NIL, then the output
is returned in a string as the value of the call. Otherwise, OUT must
be a stream to which the output will be sent.
UTIME is the universal time to be output (default is current time)
TZ is the time zone default will give local time.
FMT is a keyword symbol specifying which output format is used as follows
:RFC2822 - output as per RFC2822 for internet messages
:SHORT - output in a shorter format (same as :ISO)
:TIME-ONLY - outputs time as hh:mm:ss
:DATE-ONLY - outputs date as dd-mm-yyyy
:ISO - output as per ISO 8602"
(declare (number utime) (symbol fmt))
(multiple-value-bind (se mi ho da mo ye dw dst tz)
(if (null timezone)
(decode-universal-time (round utime))
(decode-universal-time (round utime) timezone))
(declare (fixnum se mi ho da mo ye dw tz) (ignore dst))
(let ((month-name (aref +month-names+ (1- mo)))
(week-day-name (aref +week-days+ dw)))
(ecase fmt
(:iso
(format
out
"~4d-~2,'0d-~2,'0d ~2,'0d:~2,'0d:~2,'0d~:[~; ~:[+~;-~]~2,'0d~]"
ye mo da ho mi se timezone (< 0 tz) (abs tz)))
(:short
(format out "~4d-~2,'0d-~2,'0d ~2,'0d:~2,'0d~:[~; ~:[+~;-~]~2,'0d~]"
ye mo da ho mi timezone (< 0 tz) (abs tz)))
(:rfc2822
(format
out
"~A, ~2,'0d ~a ~4d ~2,'0d:~2,'0d:~2,'0d~:[~; ~:[+~;-~]~2,'0d~]"
week-day-name da month-name ye ho mi se timezone (< 0 tz) (abs tz)))
(:http
(format out "~A, ~2,'0d ~a ~4d ~2,'0d:~2,'0d:~2,'0d GMT"
week-day-name da month-name ye ho mi se))
(:notmz
(format out
"~4d-~2,'0d-~2,'0d ~2,'0d:~2,'0d:~2,'0d"
ye mo da ho mi se))
(:nosec
(format out
"~4d-~2,'0d-~2,'0d ~2,'0d:~2,'0d"
ye mo da ho mi))
(:date-only
(format out "~2,'0d-~a-~4d" da month-name ye))
(:time-only
(format out "~2,'0d:~2,'0d:~2,'0d" ho mi se))))))
(defmethod format-output((spec (eql 'date)) output &key (fmt :iso) (zone *timezone*)
(if-nil nil)
&allow-other-keys)
(if output
(if (numberp output)
(format-time nil output :fmt fmt :timezone zone)
output)
if-nil))
(defmethod format-output((spec (eql 'number)) output &key radix format
&allow-other-keys)
(let ((*print-base* (or radix *print-base*)))
(if format (format nil format output) (call-next-method))))
(defmethod format-output((spec (eql 'integer)) output &key format
&allow-other-keys)
(if format (format nil format output) (call-next-method)))
(defmethod format-output((spec (eql 'read)) output &key (multiplep nil) (package *package*))
"Parse input using read. If multiple is true will read until
finsihed, returning a list of values."
(let ((*package* (find-package package)))
(with-output-to-string(os)
(if (and multiplep (listp output))
(dolist(item output)
(unless (eql item (car output))
(write-char #\space os))
(write item :stream os :readably t))
(write output :stream os :readably t)))))
(defmethod format-output((spec (eql 'list)) output &key type (separator ", "))
(join-strings
(if (and (listp type)
(or (listp (first type))
(not
(and (symbolp (second type))
(eql (symbol-package (second type))
#.(find-package :keyword))))))
(mapcar #'(lambda(type v) (format-output type v)) type output)
(mapcar #'(lambda(v) (format-output type v)) output))
separator))
(defmethod format-output((spec (eql 'member)) output &key type)
(format-output type output))
(defmethod parse-input((spec (eql 'time-period)) (value string)
&key &allow-other-keys)
"A time period in hours, minutes and (optionally) seconds"
(let* ((values (split-string value :delimiter #\: :count 3))
(hours (parse-input 'integer (first values) :min 0))
(minutes (parse-input 'integer (second values) :min 0 :max 59))
(seconds (if (third values)
(parse-input 'integer (third values) :min 0 :max 59)
0)))
(+ (* 3600 hours) (* 60 minutes) seconds)))
(defmethod format-output((spec (eql 'time-period)) (value number)
&key &allow-other-keys)
(multiple-value-bind(hours value) (floor value 3600.0)
(multiple-value-bind(minutes seconds) (floor value 60.0)
(format nil "~2,'0D:~2,'0D:~2,'0D" hours minutes (round seconds)))))
(defun parse-options(spec options-list &optional allow-other-options)
"Parse an option list (alist of names and strings to be parsed)
against a specification. The specification is a list of entries each
of which lists the name, and optionally type and default values. The
output is an alist of variable names and parsed values. Options in
options-list not in spec are not returned and will signal an error
unless allow-other-options is true"
(unless allow-other-options
(dolist(option options-list)
(unless (find (car option) spec
:test #'string-equal
:key (lambda(s) (if (listp s) (first s) s)))
(cerror "Ignore Option" 'invalid-format
:type 'parse-options :value option
:reason "Unknwon option"))))
(mapcar #'(lambda(s)
(multiple-value-bind(name type default)
(if (listp s) (values-list s) s)
(let ((option
(find name options-list
:key #'car :test #'string-equal)))
(list name
(if option
(if type
(restart-case
(parse-input type (cdr option))
(use-default()
:report
(lambda(s)
(format
s "Use default value of ~S" default))
default)
(use-value(v)
:report "Use default value"
v))
(or (cdr option) default))
default)))))
spec))
(defun lookup-field(name field-specifications)
(etypecase field-specifications
(function (funcall field-specifications name))
(list (let ((v (find name field-specifications
:key #'first :test #'string-equal)))
(values (second v) (when v t))))))
(defmethod parse-input((spec (eql 'headers)) (s string) &rest rest)
(with-input-from-string(is s)
(apply #'parse-input `(headers ,is ,@rest))))
(defmethod parse-input((spec (eql 'headers)) (p pathname) &rest rest)
(with-open-file(is p :direction :input :if-does-not-exist :error)
(apply #'parse-input `(headers ,is ,@rest))))
(defmethod parse-input((spec (eql 'headers)) (is stream)
&key (skip-blanks-p t)
field-specifications
(preserve-newlines-p t)
(termination-test #'(lambda(line) (zerop (length line))))
if-no-specification &allow-other-keys)
(let ((name nil)
(value nil)
(headers nil))
(flet((finish-header()
(when name
(multiple-value-bind(type found-p)
(lookup-field name field-specifications)
(when (not found-p)
(case if-no-specification
(:error
(invalid-format-error spec name "Unknown field"))
(:ignore (setf name nil value nil)
(return-from finish-header))))
(push
(cons name
(parse-input
(if found-p type if-no-specification)
(join-strings
(nreverse value)
(if preserve-newlines-p #\newline))))
headers))
(setf name nil))))
(restart-case
(do ((line (read-line is nil nil) (read-line is nil nil)))
((and (funcall termination-test line)
(or (not skip-blanks-p) name))
(finish-header)
headers)
(restart-case
(if (white-space-p (char line 0))
(if name
(push (subseq line 1) value)
(invalid-format-error
spec line "Unexpected Continuation line"))
(progn
(when name (finish-header))
(let ((args (split-string line :delimiter #\: :count 2)))
(when (< (length args) 2)
(invalid-format-error
spec line "Missing field delimiter"))
(setf name (string-right-trim '(#\space) (first args))
value
(list (string-left-trim '(#\space) (second args)))))))
(continue() :report "Skip this line and continue.")))
(stop() :report "Stop and return headers read so far." headers)
(skip-headers()
:report "Skip to end of headers and return headers read so far."
(do ((line (read-line is nil nil) (read-line is nil nil)))
((funcall termination-test line)))
headers)))))
(defmethod format-output((spec (eql 'headers)) (headers list)
&key field-specifications
if-no-specification
stream
(preserve-newlines-p t))
(if stream
(dolist(header headers)
(let ((name (first header))
(value (rest header)))
(multiple-value-bind(type found-p)
(lookup-field name field-specifications)
(when (or found-p
(case if-no-specification
(:error
(invalid-format-error spec name "Unknown field"))
(:ignore nil)
(t t)))
(write name :stream stream)
(write-string ": " stream)
(let ((lines (split-string
(cond
(found-p (format-output type value))
((stringp value) value)
(t (write-to-string value)))
:delimiter #\newline)))
(write-line (first lines) stream)
(dolist(line (rest lines))
(write-char #\space stream)
(write-line line stream)))))))
(with-output-to-string(os)
(format-output 'headers headers
:stream os
:field-specifications field-specifications
:preserve-newlines-p preserve-newlines-p
:if-no-specification if-no-specification))))
(defun parse-arguments(spec argument-string &optional allow-spaces)
"Parse a string of whitespace delimited arguments according to spec.
The specification is a list of entries each
of which lists the name, and optionally type and default values. The
output is an alist of variable names and parsed values.
If allow-spaces is true, last element can contain spaces"
(let ((arguments (split-string argument-string
:count (length spec)
:remove-empty-subseqs t)))
(when (not allow-spaces)
(let* ((a (first (last arguments)))
(p (position #\space a)))
(when p
(restart-case
(error 'invalid-format
:type 'parse-arguments
:value a
:reason "Too many arguments in argument list")
(ignore-extra-arguments()
:report "Ignore extra arguments"
(setf (first (last arguments)) (subseq a 0 p)))))))
(mapcar
#'(lambda(s)
(multiple-value-bind(name type default)
(if (listp s) (values-list s) s)
(let ((a (or (pop arguments) default)))
(list
name
(restart-case
(parse-input type a)
(use-default()
:report
(lambda(s) (format s "Use default value of ~S" default))
default))
a))))
spec)))
(defparameter +engineering-units+ "YZEPTGMk munpfazy")
(defun eng(os arg &optional colon-p at-p
(d 2) (padchar #\space) (exponentchar #\E))
"Formatter which outputs its numerical argument `arg` in engineering format
to stream `os`.
It takes arguments d,padchar,exponentchar where
d is the number of decimal places to display after the decimal point
padchar is the character to pad the start of the number
exponentchar is the character to use to display between radix and exponent
It also takes the : modifier which will cause it to output the exponent
as an SI units prefix rather than a number.
Arguments:
- `os`: an output stream designator
- `arg`: a number
- `colon-p`: a generalised boolean (default false)
- `at-p`: a generalised boolean (default false) - if set right align field
- `d`: an integer (default 2)
- `padchar`: a character (default `space`)
- `exponentchar`: a character (default `e`))
Result:
nil
Examples:
`(format nil \"~/eng/\" 35000) => \"35.00e+3\"`
"
(if (numberp arg)
(let* (
;; note use u instead of \mu for 1e-6 so utf-8 not needed
(order (if (zerop arg) 0 (floor (log (abs arg) 10) 3)))
(scale (* 3 order))
(radix (/ arg (expt 10 scale)))
(radix-format
(if (or (zerop d) (integerp arg))
(format nil "~~~:[~;3~],'~CD" at-p padchar)
(format nil "~~~:[~*~;~D~],~@[~D~],,,'~CF"
at-p (+ 4 d) d padchar))))
(when (zerop d) (setf radix (round radix)))
(if (and colon-p (< -1 (- 8 order) (length +engineering-units+)))
(format os "~@?~:[~C~;~]"
radix-format
radix
(zerop scale)
(char +engineering-units+ (- 8 order)))
(format os "~@?~:[~C~@D~;~]"
radix-format
radix
(zerop scale)
exponentchar
scale)))
(princ arg os)))
(defmethod format-output((spec (eql 'eng)) (value number)
&key (units t) (padchar #\space) (decimal-places 2)
&allow-other-keys)
"Output in engineering style with units. If units is a string then
the output will contain that unit and the appropriate suffix. If t
only the suffix is output. If nil no units or suffix is output"
(with-output-to-string(os)
(eng os value units nil decimal-places padchar)
(when (stringp units) (write-string units os))))
(defmethod parse-input((spec (eql 'eng)) (value string)
&key (units t) &allow-other-keys)
;; we assume all of suffix non numerical characters make up units
;; and value before that is a number.
(let* ((p (1+ (position-if #'digit-char-p value :from-end t)))
(num (parse-number (subseq value 0 p)))
(suffix (subseq value p)))
(flet ((scaled-num(c)
(let ((p (position c +engineering-units+)))
(unless p
(invalid-format-error
spec value "Invalid engineering unit"))
(* num (expt 10 (* 3 (- 8 p)))))))
(cond
((and
(stringp units)
(let ((p (search units suffix)))
(unless p (invalid-format-error spec value "Invalid units"))
(if (> p 0)
(let ((c (char suffix (1- p))))
(if (white-space-p c)
num
(scaled-num c)))
num))))
((and
units
(let ((p (position-if-not #'white-space-p suffix)))
(when p (scaled-num (char suffix p))))))
(num)))))
(defparameter +roman-numeral-map+
'(("M" . 1000) ("CM" . 900) ("D" . 500) ("CD" . 400)
("C" . 100) ("XC" . 90) ("L" . 50) ("XL" . 40)
("X" . 10) ("IX" . 9) ("V" . 5) ("IV" . 4) ("I" . 1)))
(defmethod format-output((spec (eql 'roman)) (n integer)
&key &allow-other-keys)
"convert integer to Roman numeral"
(unless (< 0 n 4000)
(invalid-format-error
spec n "number out of range (must be 1..3999)"))
(with-output-to-string(os)
(dolist(item +roman-numeral-map+)
(let ((numeral (car item))
(int (cdr item)))
(loop
(when (< n int) (return))
(write-sequence numeral os)
(decf n int))))))
(defmethod parse-input((spec (eql 'roman)) (s string)
&key &allow-other-keys)
"Convert roman numeral to integer"
(let ((result 0)
(index 0)
(slen (length s)))
(dolist(item +roman-numeral-map+)
(let* ((numeral (car item))
(int (cdr item))
(len (length numeral)))
(loop
(let ((end (+ index len)))
(unless (<= end slen) (return))
(unless (string-equal numeral s :start2 index :end2 end)
(return))
(incf result int)
(incf index len)))))
(when (< index slen)
(invalid-format-error spec s "Invalid Roman numeral" ))
result))
(defmethod parse-input((spec (eql 'bit-vector)) (input string)
&key &allow-other-keys)
(let* ((s (string-left-trim " " (string-right-trim " " input)))
(len (length s))
(result (make-array len :element-type 'bit)))
(dotimes(i len)
(case (char s i)
(#\0 (setf (bit result i) 0))
(#\1 (setf (bit result i) 1))
(t (invalid-format-error spec s "Invalid character '~C' in bit vector" (char s i)))))
result))
(defmethod format-output ((spec (eql 'bit-vector)) (input bit-vector)
&key &allow-other-keys)
(let* ((len (length input))
(result (make-string len)))
(dotimes(i len)
(setf (char result i) (if (= (bit input i) 1) #\1 #\0)))
result))
(defgeneric equivalent(specification input reference &key &allow-other-keys)
(:documentation "Returns true if the parsed value input is
equivalent (equals) the reference value according to the stype
specification. If specification is a list the first element specifies
the actual validation method and the rest of the list are passed as
keyword arguments to the specific method.")
(:method((spec list) input reference &rest rest)
(declare (ignore rest))
(apply #'equivalent (nconc (list (car spec) input reference) (cdr spec))))
(:method(spec input reference &key (test #'equal) &allow-other-keys)
(funcall test input reference))
(:method((spec (eql 'number)) input reference &key (tol 1e-3) &allow-other-keys)
(and input
(or (= input reference)
(typecase tol
(function (funcall tol input reference))
(number (and (/= 0 reference)
(<= (abs (/ (- input reference) reference)) tol))))))))
(defmethod format-output((spec (eql 'dimensional-parameter)) value
&key (padchar #\space) (decimal-places 2)
nil-allowed
&allow-other-keys)
"Output in engineering style with units. If units is a string then
the output will contain that unit and the appropriate suffix. If t
only the suffix is output. If nil no units or suffix is output"
(cond
(value
(with-output-to-string(os)
(eng os (car value) (cdr value) nil decimal-places padchar)
(write-string (cdr value) os)))
(nil-allowed nil)
(t (invalid-format-error spec value "Value must include a number and units"))))
(defmethod parse-input((spec (eql 'dimensional-parameter)) (value string)
&key &allow-other-keys)
;; we assume all of suffix non numerical characters make up units
;; and value before that is a number.
(setq value (string-trim #(#\space #\tab) value))
(let* ((p (1+ (position-if #'digit-char-p value :from-end t)))
(num (float (parse-number (subseq value 0 p))))
(p (position-if-not #'white-space-p value :start p))
(scale (position (char value p) +engineering-units+))
(units (subseq value (if scale (1+ p) p))))
(when (zerop (length units))
(setf scale nil)
(setf units (subseq value p)))
(when scale (setf num (* num (expt 10 (* 3 (- 8 scale))))))
(cons num units)))
(defmethod equivalent((spec (eql 'dimensional-parameter)) input reference &rest rest)
(and (equal (cdr reference) (cdr input))
(apply #'equivalent `(number ,(car input) ,(car reference) ,@rest))))
(defmethod parse-input((spec (eql 'percentage)) (value string)
&key (min 0) (max 100) nil-allowed &allow-other-keys)
(parse-input 'number value :min min :max max :nil-allowed nil-allowed))
(defmethod format-output((spec (eql 'percentage)) num
&key (places 0) (%-p t) (mult 1))
"Return a percentage value formatted for user output (default 0 places)"
(if num
(if (= places 0)
(format nil "~D~@[%~]" (round (* num mult)) %-p)
(format nil (format nil "~~,~DF~@[%~]" places %-p) (* num mult)))
(when %-p "%")))
| 42,955 | Common Lisp | .lisp | 944 | 34.896186 | 99 | 0.568091 | willijar/cl-data-format-validation | 8 | 2 | 1 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 933e91ab5d5c23e9c50363e4b6e3c7a53ffa1a0a6a80c31a0c1cd8ea49ebad43 | 12,441 | [
-1
] |
12,442 | parse-time.lisp | willijar_cl-data-format-validation/parse-time.lisp | ;; **********************************************************************
;;; This code was written as part of the CMU Common Lisp project at
;;; Carnegie Mellon University, and has been placed in the public domain.
;;;
;;; It was subsequently borrowed and modified slightly by Daniel
;;; Barlow <[email protected]> to become part of the net-telent-date
;;; package. Daniel, Tue May 22 05:45:27 BST 2001
;;; **********************************************************************
;;; Parsing routines for time and date strings. PARSE-TIME returns the
;;; universal time integer for the time and/or date given in the string.
;;; Written by Jim Healy, June 1987.
;;; **********************************************************************
(in-package :data-format-validation)
(defvar whitespace-chars '(#\space #\tab #\newline #\, #\' #\`))
(defvar time-dividers '(#\: #\.))
(defvar date-dividers '(#\\ #\/ #\-))
(defvar *error-on-mismatch* nil
"If t, an error will be signalled if parse-time is unable
to determine the time/date format of the string.")
;;; Set up hash tables for month, weekday, zone, and special strings.
;;; Provides quick, easy access to associated information for these items.
;;; Hashlist takes an association list and hashes each pair into the
;;; specified tables using the car of the pair as the key and the cdr as
;;; the data object.
(defmacro hashlist (list table)
`(dolist (item ,list)
(setf (gethash (car item) ,table) (cdr item))))
(defparameter weekday-table-size 23)
(defparameter month-table-size 31)
(defparameter zone-table-size 11)
(defparameter special-table-size 11)
(defvar *weekday-strings* (make-hash-table :test #'equal
:size weekday-table-size))
(defvar *month-strings* (make-hash-table :test #'equal
:size month-table-size))
(defvar *zone-strings* (make-hash-table :test #'equal
:size zone-table-size))
(defvar *special-strings* (make-hash-table :test #'equal
:size special-table-size))
;;; Load-time creation of the hash tables.
(hashlist '(("monday" . 0) ("mon" . 0)
("tuesday" . 1) ("tues" . 1) ("tue" . 1)
("wednesday" . 2) ("wednes" . 2) ("wed" . 2)
("thursday" . 3) ("thurs" . 3) ("thu" . 3)
("friday" . 4) ("fri" . 4)
("saturday" . 5) ("sat" . 5)
("sunday" . 6) ("sun" . 6))
*weekday-strings*)
(hashlist '(("january" . 1) ("jan" . 1)
("february" . 2) ("feb" . 2)
("march" . 3) ("mar" . 3)
("april" . 4) ("apr" . 4)
("may" . 5) ("june" . 6)
("jun" . 6) ("july" . 7)
("jul" . 7) ("august" . 8)
("aug" . 8) ("september" . 9)
("sept" . 9) ("sep" . 9)
("october" . 10) ("oct" . 10)
("november" . 11) ("nov" . 11)
("december" . 12) ("dec" . 12))
*month-strings*)
(hashlist '(("gmt" . 0) ("ut" . 0) ("utc" . 0) ("est" . 5)
("edt" . 4) ("cst" . 6)
("cdt" . 5) ("mst" . 7)
("mdt" . 6) ("pst" . 8)
("pdt" . 7)
("bst" . -1))
*zone-strings*)
(hashlist '(("yesterday" . yesterday) ("today" . today)
("tomorrow" . tomorrow) ("now" . now))
*special-strings*)
;;; Time/date format patterns are specified as lists of symbols repre-
;;; senting the elements. Optional elements can be specified by
;;; enclosing them in parentheses. Note that the order in which the
;;; patterns are specified below determines the order of search.
;;; Choices of pattern symbols are: second, minute, hour, day, month,
;;; year, time-divider, date-divider, am-pm, zone, izone, weekday,
;;; noon-midn, and any special symbol.
(defparameter *default-date-time-patterns*
'(
;; Date formats.
((weekday) month (date-divider) day (date-divider) year (noon-midn))
((weekday) day (date-divider) month (date-divider) year (noon-midn))
((weekday) month (date-divider) day (noon-midn))
(year (date-divider) month (date-divider) day (noon-midn))
(month (date-divider) year (noon-midn))
(year (date-divider) month (noon-midn))
((noon-midn) (weekday) month (date-divider) day (date-divider) year)
((noon-midn) (weekday) day (date-divider) month (date-divider) year)
((noon-midn) (weekday) month (date-divider) day)
((noon-midn) year (date-divider) month (date-divider) day)
((noon-midn) month (date-divider) year)
((noon-midn) year (date-divider) month)
;; Time formats.
(hour (time-divider) (minute) (time-divider) (secondp) (am-pm)
(date-divider) (zone))
(noon-midn)
(hour (noon-midn))
;; Time/date combined formats.
((weekday) month (date-divider) day (date-divider) year
hour (time-divider) (minute) (time-divider) (secondp)
(am-pm) (date-divider) (zone))
((weekday) day (date-divider) month (date-divider) year
hour (time-divider) (minute) (time-divider) (secondp)
(am-pm) (date-divider) (zone))
((weekday) month (date-divider) day
hour (time-divider) (minute) (time-divider) (secondp)
(am-pm) (date-divider) (zone))
(year (date-divider) month (date-divider) day
hour (time-divider) minute
(am-pm) (date-divider) (izone))
(year (date-divider) month (date-divider) day
(hour) (time-divider) (minute) (time-divider) (secondp)
(am-pm) (date-divider) (izone))
(month (date-divider) year
hour time-divider (minute) time-divider (secondp)
(am-pm) (date-divider) (zone))
(year (date-divider) month
hour time-divider (minute) time-divider (secondp)
(am-pm) (date-divider) (zone))
(hour (time-divider) (minute) (time-divider) (secondp) (am-pm)
(date-divider) (zone) (weekday) month (date-divider)
day (date-divider) year)
(hour (time-divider) (minute) (time-divider) (secondp) (am-pm)
(date-divider) (zone) (weekday) day (date-divider)
month (date-divider) year)
(hour (time-divider) (minute) (time-divider) (secondp) (am-pm)
(date-divider) (zone) (weekday) month (date-divider)
day)
(hour (time-divider) (minute) (time-divider) (secondp) (am-pm)
(date-divider) (zone) year (date-divider) month
(date-divider) day)
(hour (time-divider) (minute) (time-divider) (secondp) (am-pm)
(date-divider) (zone) month (date-divider) year)
(hour (time-divider) (minute) (time-divider) (secondp) (am-pm)
(date-divider) (zone) year (date-divider) month)
;; Weird, non-standard formats.
(weekday month day hour (time-divider) minute (time-divider)
secondp (am-pm)
(zone) year)
((weekday) day (date-divider) month (date-divider) year hour
(time-divider) minute (time-divider) (secondp) (am-pm)
(date-divider) (zone))
((weekday) month (date-divider) day (date-divider) year hour
(time-divider) minute (time-divider) (secondp) (am-pm)
(date-divider) (zone))
;; Special-string formats.
(now (yesterday))
((yesterday) now)
(now (today))
((today) now)
(now (tomorrow))
((tomorrow) now)
(yesterday (noon-midn))
((noon-midn) yesterday)
(today (noon-midn))
((noon-midn) today)
(tomorrow (noon-midn))
((noon-midn) tomorrow)
))
;;; HTTP header style date/time patterns: RFC1123/RFC822, RFC850, ANSI-C.
(defparameter *http-date-time-patterns*
'(
;; RFC1123/RFC822 and RFC850.
((weekday) day (date-divider) month (date-divider) year
hour time-divider minute (time-divider) (secondp) izone)
((weekday) day (date-divider) month (date-divider) year
hour time-divider minute (time-divider) (secondp) (zone))
;; ANSI-C.
((weekday) month day
hour time-divider minute (time-divider) (secondp) year)))
;;; The decoded-time structure holds the time/date values which are
;;; eventually passed to 'encode-universal-time' after parsing.
;;; Note: Currently nothing is done with the day of the week. It might
;;; be appropriate to add a function to see if it matches the date.
(defstruct decoded-time
(second 0 :type integer) ; Value between 0 and 59.
(minute 0 :type integer) ; Value between 0 and 59.
(hour 0 :type integer) ; Value between 0 and 23.
(day 1 :type integer) ; Value between 1 and 31.
(month 1 :type integer) ; Value between 1 and 12.
(year 1900 :type integer) ; Value above 1899 or between 0 and 99.
(zone nil :type (or rational null)) ; Value between -24 and 24 inclusive.
(dotw 0 :type integer)) ; Value between 0 and 6.
;;; Make-default-time returns a decoded-time structure with the default
;;; time values already set. The default time is currently 00:00 on
;;; the current day, current month, current year, and current time-zone.
(defun make-default-time (def-sec def-min def-hour def-day
def-mon def-year def-zone def-dotw)
(let ((default-time (make-decoded-time)))
(multiple-value-bind (sec min hour day mon year dotw dst zone)
(get-decoded-time)
(declare (ignore dst))
(if def-sec
(if (eq def-sec :current)
(setf (decoded-time-second default-time) sec)
(setf (decoded-time-second default-time) def-sec))
(setf (decoded-time-second default-time) 0))
(if def-min
(if (eq def-min :current)
(setf (decoded-time-minute default-time) min)
(setf (decoded-time-minute default-time) def-min))
(setf (decoded-time-minute default-time) 0))
(if def-hour
(if (eq def-hour :current)
(setf (decoded-time-hour default-time) hour)
(setf (decoded-time-hour default-time) def-hour))
(setf (decoded-time-hour default-time) 0))
(if def-day
(if (eq def-day :current)
(setf (decoded-time-day default-time) day)
(setf (decoded-time-day default-time) def-day))
(setf (decoded-time-day default-time) day))
(if def-mon
(if (eq def-mon :current)
(setf (decoded-time-month default-time) mon)
(setf (decoded-time-month default-time) def-mon))
(setf (decoded-time-month default-time) mon))
(if def-year
(if (eq def-year :current)
(setf (decoded-time-year default-time) year)
(setf (decoded-time-year default-time) def-year))
(setf (decoded-time-year default-time) year))
(if def-zone
(if (eq def-zone :current)
(setf (decoded-time-zone default-time) zone)
(setf (decoded-time-zone default-time) def-zone))
(setf (decoded-time-zone default-time) nil))
(if def-dotw
(if (eq def-dotw :current)
(setf (decoded-time-dotw default-time) dotw)
(setf (decoded-time-dotw default-time) def-dotw))
(setf (decoded-time-dotw default-time) dotw))
default-time)))
;;; Converts the values in the decoded-time structure to universal time
;;; by calling encode-universal-time.
;;; If zone is in numerical form, tweeks it appropriately.
(defun convert-to-unitime (parsed-values)
(let ((zone (decoded-time-zone parsed-values)))
(encode-universal-time
(decoded-time-second parsed-values)
(decoded-time-minute parsed-values)
(decoded-time-hour parsed-values)
(decoded-time-day parsed-values)
(decoded-time-month parsed-values)
(decoded-time-year parsed-values)
(if (and zone (or (> zone 24) (< zone -24)))
(let ((new-zone (/ zone 100)))
(cond ((minusp new-zone) (- new-zone))
((plusp new-zone) (- 24 new-zone))
;; must be zero (GMT)
(t new-zone)))
zone))))
;;; Sets the current values for the time and/or date parts of the
;;; decoded time structure.
(defun set-current-value (values-structure &key (time nil) (date nil)
(zone nil))
(multiple-value-bind (sec min hour day mon year dotw dst tz)
(get-decoded-time)
(declare (ignore dst))
(when time
(setf (decoded-time-second values-structure) sec)
(setf (decoded-time-minute values-structure) min)
(setf (decoded-time-hour values-structure) hour))
(when date
(setf (decoded-time-day values-structure) day)
(setf (decoded-time-month values-structure) mon)
(setf (decoded-time-year values-structure) year)
(setf (decoded-time-dotw values-structure) dotw))
(when zone
(setf (decoded-time-zone values-structure) tz))))
;;; Special function definitions. To define a special substring, add
;;; a dotted pair consisting of the substring and a symbol in the
;;; *special-strings* hashlist statement above. Then define a function
;;; here which takes one argument- the decoded time structure- and
;;; sets the values of the structure to whatever is necessary. Also,
;;; add a some patterns to the patterns list using whatever combinations
;;; of special and pre-existing symbols desired.
(defun yesterday (parsed-values)
(set-current-value parsed-values :date t :zone t)
(setf (decoded-time-day parsed-values)
(1- (decoded-time-day parsed-values))))
(defun today (parsed-values)
(set-current-value parsed-values :date t :zone t))
(defun tomorrow (parsed-values)
(set-current-value parsed-values :date t :zone t)
(setf (decoded-time-day parsed-values)
(1+ (decoded-time-day parsed-values))))
(defun now (parsed-values)
(set-current-value parsed-values :time t))
;;; Predicates for symbols. Each symbol has a corresponding function
;;; defined here which is applied to a part of the datum to see if
;;; it matches the qualifications.
(defun am-pm (string)
(and (simple-string-p string)
(cond ((string= string "am") 'am)
((string= string "pm") 'pm)
(t nil))))
(defun noon-midn (string)
(and (simple-string-p string)
(cond ((string= string "noon") 'noon)
((string= string "midnight") 'midn)
(t nil))))
(defun weekday (string)
(and (simple-string-p string) (gethash string *weekday-strings*)))
(defun month (thing)
(or (and (simple-string-p thing) (gethash thing *month-strings*))
(and (integerp thing) (<= 1 thing 12))))
(defun zone (thing)
(or (and (simple-string-p thing) (gethash thing *zone-strings*))
(if (integerp thing)
(let ((zone (/ thing 100)))
(and (integerp zone) (<= -24 zone 24))))))
;;; Internet numerical time zone, e.g. RFC1123, in hours and minutes.
(defun izone (thing)
(if (integerp thing)
(multiple-value-bind (hours mins)
(truncate thing 100)
(and (<= -24 hours 24) (<= -59 mins 59)))))
(defun special-string-p (string)
(and (simple-string-p string) (gethash string *special-strings*)))
(defun secondp (number)
(and (integerp number) (<= 0 number 59)))
(defun minute (number)
(and (integerp number) (<= 0 number 59)))
(defun hour (number)
(and (integerp number) (<= 0 number 23)))
(defun day (number)
(and (integerp number) (<= 1 number 31)))
(defun year (number)
(and (integerp number)
(or (<= 0 number 99)
(<= 1900 number))))
(defun time-divider (character)
(and (characterp character)
(member character time-dividers :test #'char=)))
(defun date-divider (character)
(and (characterp character)
(member character date-dividers :test #'char=)))
;;; Match-substring takes a string argument and tries to match it with
;;; the strings in one of the four hash tables: *weekday-strings*, *month-
;;; strings*, *zone-strings*, *special-strings*. It returns a specific
;;; keyword and/or the object it finds in the hash table. If no match
;;; is made then it immediately signals an error.
(defun match-substring (substring)
(let ((substring (nstring-downcase substring)))
(or (let ((test-value (month substring)))
(if test-value (cons 'month test-value)))
(let ((test-value (weekday substring)))
(if test-value (cons 'weekday test-value)))
(let ((test-value (am-pm substring)))
(if test-value (cons 'am-pm test-value)))
(let ((test-value (noon-midn substring)))
(if test-value (cons 'noon-midn test-value)))
(let ((test-value (zone substring)))
(if test-value (cons 'zone test-value)))
(let ((test-value (special-string-p substring)))
(if test-value (cons 'special test-value)))
(if *error-on-mismatch*
(error "\"~A\" is not a recognized word or abbreviation."
substring)
(return-from match-substring nil)))))
;;; Decompose-string takes the time/date string and decomposes it into a
;;; list of alphabetic substrings, numbers, and special divider characters.
;;; It matches whatever strings it can and replaces them with a dotted pair
;;; containing a symbol and value.
(defun decompose-string (string &key (start 0) (end (length string)) (radix 10))
(do ((string-index start)
(next-negative nil)
(parts-list nil))
((eq string-index end) (nreverse parts-list))
(let ((next-char (char string string-index))
(prev-char (if (= string-index start)
nil
(char string (1- string-index)))))
(cond ((alpha-char-p next-char)
;; Alphabetic character - scan to the end of the substring.
(do ((scan-index (1+ string-index) (1+ scan-index)))
((or (eq scan-index end)
(not (alpha-char-p (char string scan-index))))
(let ((match-symbol (match-substring
(subseq string string-index scan-index))))
(if match-symbol
(push match-symbol parts-list)
(return-from decompose-string nil)))
(setf string-index scan-index))))
((digit-char-p next-char radix)
;; Numeric digit - convert digit-string to a decimal value.
(do ((scan-index string-index (1+ scan-index))
(numeric-value 0 (+ (* numeric-value radix)
(digit-char-p (char string scan-index) radix))))
((or (eq scan-index end)
(not (digit-char-p (char string scan-index) radix)))
;; If next-negative is t, set the numeric value to it's
;; opposite and reset next-negative to nil.
(when next-negative
(setf next-negative nil)
(setf numeric-value (- numeric-value)))
(push numeric-value parts-list)
(setf string-index scan-index))))
((and (char= next-char #\-)
(or (not prev-char)
(member prev-char whitespace-chars :test #'char=)))
;; If we see a minus sign before a number, but not after one,
;; it is not a date divider, but a negative offset from GMT, so
;; set next-negative to t and continue.
(setf next-negative t)
(incf string-index))
((and (char= next-char #\+)
(or (not prev-char)
(member prev-char whitespace-chars :test #'char=)))
;; a positive offset from GMT
(incf string-index))
((member next-char time-dividers :test #'char=)
;; Time-divider - add it to the parts-list with symbol.
(push (cons 'time-divider next-char) parts-list)
(incf string-index))
((member next-char date-dividers :test #'char=)
;; Date-divider - add it to the parts-list with symbol.
(push (cons 'date-divider next-char) parts-list)
(incf string-index))
((member next-char whitespace-chars :test #'char=)
;; Whitespace character - ignore it completely.
(incf string-index))
((char= next-char #\()
;; Parenthesized string - scan to the end and ignore it.
(do ((scan-index string-index (1+ scan-index)))
((or (eq scan-index end)
(char= (char string scan-index) #\)))
(setf string-index (1+ scan-index)))))
(t
;; Unrecognized character - barf voraciously.
(if *error-on-mismatch*
(error
'simple-error
:format-control "Can't parse time/date string.~%>>> ~A~
~%~VT^-- Bogus character encountered here."
:format-arguments (list string (+ string-index 4)))
(return-from decompose-string nil)))))))
;;; Match-pattern-element tries to match a pattern element with a datum
;;; element and returns the symbol associated with the datum element if
;;; successful. Otherwise nil is returned.
(defun match-pattern-element (pattern-element datum-element)
(cond ((listp datum-element)
(let ((datum-type (if (eq (car datum-element) 'special)
(cdr datum-element)
(car datum-element))))
(if (eq datum-type pattern-element) datum-element)))
((funcall pattern-element datum-element)
(cons pattern-element datum-element))
(t nil)))
;;; Match-pattern matches a pattern against a datum, returning the
;;; pattern if successful and nil otherwise.
(defun match-pattern (pattern datum datum-length)
(if (>= (length pattern) datum-length)
(let ((form-list nil))
(do ((pattern pattern (cdr pattern))
(datum datum (cdr datum)))
((or (null pattern) (null datum))
(cond ((and (null pattern) (null datum))
(nreverse form-list))
((null pattern) nil)
((null datum) (dolist (element pattern
(nreverse form-list))
(if (not (listp element))
(return nil))))))
(let* ((pattern-element (car pattern))
(datum-element (car datum))
(optional (listp pattern-element))
(matching (match-pattern-element (if optional
(car pattern-element)
pattern-element)
datum-element)))
(cond (matching (let ((form-type (car matching)))
(unless (or (eq form-type 'time-divider)
(eq form-type 'date-divider))
(push matching form-list))))
(optional (push datum-element datum))
(t (return-from match-pattern nil))))))))
;;; Deal-with-noon-midn sets the decoded-time values to either noon
;;; or midnight depending on the argument form-value. Form-value
;;; can be either 'noon or 'midn.
(defun deal-with-noon-midn (form-value parsed-values)
(cond ((eq form-value 'noon)
(setf (decoded-time-hour parsed-values) 12))
((eq form-value 'midn)
(setf (decoded-time-hour parsed-values) 0))
(t (error "Unrecognized symbol: ~A" form-value)))
(setf (decoded-time-minute parsed-values) 0)
(setf (decoded-time-second parsed-values) 0))
;;; Deal-with-am-pm sets the decoded-time values to be in the am
;;; or pm depending on the argument form-value. Form-value can
;;; be either 'am or 'pm.
(defun deal-with-am-pm (form-value parsed-values)
(let ((hour (decoded-time-hour parsed-values)))
(cond ((eq form-value 'am)
(cond ((eq hour 12)
(setf (decoded-time-hour parsed-values) 0))
((not (<= 0 hour 12))
(if *error-on-mismatch*
(error "~D is not an AM hour, dummy." hour)))))
((eq form-value 'pm)
(if (<= 0 hour 11)
(setf (decoded-time-hour parsed-values)
(mod (+ hour 12) 24))))
(t (error "~A isn't AM/PM - this shouldn't happen." form-value)))))
;;; Internet numerical time zone, e.g. RFC1123, in hours and minutes.
(defun deal-with-izone (form-value parsed-values)
(multiple-value-bind (hours mins)
(if (>= form-value 100)
(truncate form-value 100)
(values form-value 0))
(setf (decoded-time-zone parsed-values) (- (+ hours (/ mins 60))))))
;;; Set-time-values uses the association list of symbols and values
;;; to set the time in the decoded-time structure.
(defun set-time-values (string-form parsed-values)
(dolist (form-part string-form t)
(let ((form-type (car form-part))
(form-value (cdr form-part)))
(case form-type
(secondp (setf (decoded-time-second parsed-values) form-value))
(minute (setf (decoded-time-minute parsed-values) form-value))
(hour (setf (decoded-time-hour parsed-values) form-value))
(day (setf (decoded-time-day parsed-values) form-value))
(month (setf (decoded-time-month parsed-values) form-value))
(year (setf (decoded-time-year parsed-values) form-value))
(zone (setf (decoded-time-zone parsed-values) form-value))
(izone (deal-with-izone form-value parsed-values))
(weekday (setf (decoded-time-dotw parsed-values) form-value))
(am-pm (deal-with-am-pm form-value parsed-values))
(noon-midn (deal-with-noon-midn form-value parsed-values))
(special (funcall form-value parsed-values))
(t (error "Unrecognized symbol in form list: ~A." form-type))))))
(defun parse-time (time-string &key (start 0) (end (length time-string))
(error-on-mismatch nil)
(patterns *default-date-time-patterns*)
(default-seconds nil) (default-minutes nil)
(default-hours nil) (default-day nil)
(default-month nil) (default-year nil)
(default-zone nil) (default-weekday nil))
"Tries very hard to make sense out of the argument time-string and
returns a single integer representing the universal time if
successful. If not, it returns nil. If the :error-on-mismatch
keyword is true, parse-time will signal an error instead of
returning nil. Default values for each part of the time/date
can be specified by the appropriate :default- keyword. These
keywords can be given a numeric value or the keyword :current
to set them to the current value. The default-default values
are 00:00:00 on the current date, current time-zone."
(setq *error-on-mismatch* error-on-mismatch)
(let* ((string-parts (decompose-string time-string :start start :end end))
(parts-length (length string-parts))
(string-form (dolist (pattern patterns)
(let ((match-result (match-pattern pattern
string-parts
parts-length)))
(if match-result (return match-result))))))
(if string-form
(let ((parsed-values
(make-default-time default-seconds default-minutes
default-hours default-day
default-month default-year
default-zone default-weekday)))
(set-time-values string-form parsed-values)
(convert-to-unitime parsed-values))
(if *error-on-mismatch*
(error "\"~A\" is not a recognized time/date format." time-string)
nil))))
| 27,997 | Common Lisp | .lisp | 568 | 39.911972 | 86 | 0.594462 | willijar/cl-data-format-validation | 8 | 2 | 1 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 64038fe651167c7a7c15828e1567dac83bee65090fea9c6887cd70dac36f8842 | 12,442 | [
-1
] |
12,443 | parse-number.lisp | willijar_cl-data-format-validation/parse-number.lisp | ;;;; -*- Mode: Lisp -*-
;;;; Defines functions to parse any number type, without using the reader
;;;; Version: 1.0
;;;; Author: Matthew Danish -- mrd.debian.org
;;;;
;;;; Copyright 2002 Matthew Danish.
;;;; All rights reserved.
;;;;
;;;; Repackaged as part of general validation library by J.A.R.Williams
;;;; Changes Copyright 2009 J.A.R. Williams
;;;;
;;;; Redistribution and use in source and binary forms, with or without
;;;; modification, are permitted provided that the following conditions
;;;; are met:
;;;; 1. Redistributions of source code must retain the above copyright
;;;; notice, this list of conditions and the following disclaimer.
;;;; 2. Redistributions in binary form must reproduce the above copyright
;;;; notice, this list of conditions and the following disclaimer in the
;;;; documentation and/or other materials provided with the distribution.
;;;; 3. Neither the name of the author nor the names of its contributors
;;;; may be used to endorse or promote products derived from this software
;;;; without specific prior written permission.
;;;;
;;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
;
(in-package :data-format-validation)
(define-condition invalid-number ()
((value :reader value
:initarg :value
:initform nil)
(reason :reader reason
:initarg :reason
:initform "Not specified"))
(:report (lambda (c s)
(format s "Invalid number: ~S [Reason: ~A]"
(value c) (reason c)))))
(declaim (inline parse-integer-and-places))
(defun parse-integer-and-places (string start end &key (radix 10))
#+optimizations
(declare (optimize (speed 3))
(type fixnum start end radix))
(multiple-value-bind (integer end-pos)
(if (= start end)
(values 0 0)
(parse-integer string
:start start
:end end
:radix radix))
(cons integer (- end-pos start))))
(defun parse-integers (string start end splitting-points &key (radix 10))
#+optimizations
(declare (optimize (speed 3) #+cmu(extensions:inhibit-warnings 3))
(type fixnum start end radix))
(values-list (loop for left = start then (1+ right)
for point in splitting-points
for right = point
collect (parse-integer-and-places string
left
right
:radix radix)
into integers
finally (return
(nconc integers
(list
(parse-integer-and-places string
left
end
:radix radix
)))))))
(declaim (inline number-value places))
(defun number-value (x) (car x))
(defun places (x) (cdr x))
(declaim (type cons *white-space-characters*))
(defparameter *white-space-characters*
'(#\Space #\Tab #\Return #\Linefeed))
(declaim (inline white-space-p))
(defun white-space-p (x)
#+optimizations
(declare (optimize (speed 3) (safety 0))
(type character x))
(and (find x *white-space-characters*) t))
;; Numbers which could've been parsed, but intentionally crippled not to:
;; #xFF.AA
;; #o12e3
;; Numbers which CL doesn't parse, but this does:
;; #10r3.2
;; #2r 11
(defun parse-number (string &key (start 0) (end nil) (radix 10))
"Given a string, and start, end, and radix parameters, produce a number according to the syntax definitions in the Common Lisp Hyperspec."
(flet ((invalid-number (reason)
(error 'invalid-number
:value (subseq string start end)
:reason reason)))
(let ((end (or end (1+ (position-if-not #'white-space-p string :from-end t)))))
(if (and (eql (char string start) #\#)
(member (char string (1+ start)) '(#\C #\c)))
(let ((\(-pos (position #\( string :start start :end end))
(\)-pos (position #\) string :start start :end end)))
(when (or (not \(-pos)
(not \)-pos)
(position #\( string :start (1+ \(-pos) :end end)
(position #\) string :start (1+ \)-pos) :end end))
(invalid-number "Mismatched/missing parenthesis"))
(let ((real-pos (position-if-not #'white-space-p string
:start (1+ \(-pos) :end \)-pos)))
(unless real-pos
(invalid-number "Missing real part"))
(let ((delimiting-space (position-if #'white-space-p string
:start (1+ real-pos)
:end \)-pos)))
(unless delimiting-space
(invalid-number "Missing imaginary part"))
(let ((img-pos (position-if-not #'white-space-p string
:start (1+ delimiting-space)
:end \)-pos)))
(unless img-pos
(invalid-number "Missing imaginary part"))
(let ((img-end-pos (position-if #'white-space-p string
:start (1+ img-pos)
:end \)-pos)))
(complex (parse-real-number string
:start real-pos
:end delimiting-space
:radix radix)
(parse-real-number string
:start img-pos
:end (or img-end-pos
\)-pos)
:radix radix)))))))
(parse-real-number string :start start :end end :radix radix)))))
(defun parse-real-number (string &key (start 0) (end nil) (radix 10))
"Given a string, and start, end, and radix parameters, produce a number according to the syntax definitions in the Common Lisp Hyperspec -- except for complex numbers."
(let ((end (or end (1+ (position-if-not #'white-space-p string :from-end t)))))
(case (char string start)
((#\-)
(* -1 (parse-positive-real-number string
:start (1+ start)
:end end
:radix radix)))
((#\#)
(case (char string (1+ start))
((#\x #\X)
(parse-real-number string
:start (+ start 2)
:end end
:radix 16))
((#\b #\B)
(parse-real-number string
:start (+ start 2)
:end end
:radix 2))
((#\o #\O)
(parse-real-number string
:start (+ start 2)
:end end
:radix 8))
(t (if (digit-char-p (char string (1+ start)))
(let ((r-pos (position #\r string
:start (1+ start)
:end end
:key #'char-downcase)))
(unless r-pos
(error 'invalid-number
:value (subseq string start end)
:reason "Missing R in #radixR"))
(parse-real-number string
:start (1+ r-pos)
:end end
:radix (parse-integer string
:start (1+ start)
:end r-pos)))))))
(t (parse-positive-real-number string
:start start
:end end
:radix radix)))))
(defun parse-positive-real-number (string &key (start 0) (end nil) (radix 10))
"Given a string, and start, end, and radix parameters, produce a number according to the syntax definitions in the Common Lisp Hyperspec -- except for complex numbers and negative numbers."
(let ((end (or end (1+ (position-if-not #'white-space-p string :from-end t))))
(first-char (char string start)))
(flet ((invalid-number (reason)
(error 'invalid-number
:value (subseq string start end)
:reason reason))
(base-for-exponent-marker (char)
(case char
((#\d #\D)
10.0d0)
((#\e #\E)
10)
((#\s #\S)
10.0s0)
((#\l #\L)
10.0l0)
((#\f #\F)
10.0f0))))
(case first-char
((#\-)
(invalid-number "Invalid usage of -"))
((#\/)
(invalid-number "/ at beginning of number"))
((#\d #\D #\e #\E #\l #\L #\f #\F #\s #\S)
(when (= radix 10)
(invalid-number "Exponent-marker at beginning of number"))))
(let (/-pos .-pos exp-pos exp-marker)
(loop for index from start below end
for char = (char string index)
do (case char
((#\/)
(if /-pos
(invalid-number "Multiple /'s in number")
(setf /-pos index)))
((#\.)
(if .-pos
(invalid-number "Multiple .'s in number")
(setf .-pos index)))
((#\e #\E #\f #\F #\s #\S #\l #\L #\d #\D)
(when (= radix 10)
(when exp-pos
(invalid-number
"Multiple exponent-markers in number"))
(setf exp-pos index)
(setf exp-marker (char-downcase char)))))
when (eql index (1- end))
do (case char
((#\/)
(invalid-number "/ at end of number"))
((#\d #\D #\e #\E #\s #\S #\l #\L #\f #\F)
(when (= radix 10)
(invalid-number "Exponent-marker at end of number")))))
(cond ((and /-pos .-pos)
(invalid-number "Both . and / cannot be present simultaneously"))
((and /-pos exp-pos)
(invalid-number "Both an exponent-marker and / cannot be present simultaneously"))
((and .-pos exp-pos)
(if (< exp-pos .-pos)
(invalid-number "Exponent-markers must occur after . in number")
(if (/= radix 10)
(invalid-number "Only decimal numbers can contain exponent-markers or decimal points")
(multiple-value-bind (whole-place frac-place exp-place)
(parse-integers string start end
(list .-pos exp-pos)
:radix radix)
(* (+ (number-value whole-place)
(/ (number-value frac-place)
(expt radix
(places frac-place))))
(expt (base-for-exponent-marker exp-marker)
(number-value exp-place)))))))
(exp-pos
(if (/= radix 10)
(invalid-number "Only decimals can contain exponent-markers")
(multiple-value-bind (whole-place exp-place)
(parse-integers string start end
(list exp-pos)
:radix radix)
(* (number-value whole-place)
(expt (base-for-exponent-marker exp-marker)
(number-value exp-place))))))
(/-pos
(multiple-value-bind (numerator denominator)
(parse-integers string start end
(list /-pos)
:radix radix)
(if (>= (number-value denominator) 0)
(/ (number-value numerator)
(number-value denominator))
(invalid-number "Misplaced - sign"))))
(.-pos
(if (/= radix 10)
(invalid-number "Only decimal numbers can contain decimal points")
(multiple-value-bind (whole-part frac-part)
(parse-integers string start end
(list .-pos)
:radix radix)
(if (>= (number-value frac-part) 0)
(+ (number-value whole-part)
(/ (number-value frac-part)
(expt 10.0 (places frac-part))))
(invalid-number "Misplaced - sign")))))
(t
(values (parse-integer string
:start start
:end end
:radix radix))))))))
| 14,733 | Common Lisp | .lisp | 294 | 31.302721 | 191 | 0.456852 | willijar/cl-data-format-validation | 8 | 2 | 1 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 27db1b1bf4a95cb81827aa9d0f5d07afdbc41ba341ea6af90ca49e54f67ebdc9 | 12,443 | [
-1
] |
12,444 | defpackage.lisp | willijar_cl-data-format-validation/defpackage.lisp | ;; Package definition
;; Copyright (C) 2009 Dr. John A.R. Williams
;; Author: Dr. John A.R. Williams <[email protected]>
;;; Copying:
;; This file is part of the DATA-FORMAT-VALIDATION Common Lisp library
;; 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.
;; DATA-FORMAT-VALIDATION 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/>.
;;; Commentary:
;;
;;; Code:
(in-package :cl-user)
(defpackage :data-format-validation
(:documentation "Exports API for validation and conversion of user
data to internal types and back again.")
(:nicknames #:dfv)
(:use :cl :cl-ppcre)
(:export
;; main generic interface and condition
#:parse-input #:format-output #:invalid-format #:equivalent
#:invalid-format-type #:invalid-format-value #:invalid-format-reason
;; new use data types - ang and date are also formatter functions
#:date #:filename #:eng #:time-period #:pathnames #:separated #:roman
#:headers #:dimensional-parameter #:*timezone* #:percentage #:duration
;; functions for doing aggregates of user data and condition
#:parse-options #:parse-arguments #:ignore-extra-arguments #:use-default
;; some other more generally useful helper library functions
#:split-string #:join-strings))
| 1,763 | Common Lisp | .lisp | 35 | 47.914286 | 76 | 0.746069 | willijar/cl-data-format-validation | 8 | 2 | 1 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 37c79350d93e9e8b67d244e85fd9737032974b263b136ef81194fbd5a862ad83 | 12,444 | [
-1
] |
12,445 | data-format-validation.asd | willijar_cl-data-format-validation/data-format-validation.asd | ;;;; -*- lisp -*-
;; System definition
;; Copyright (C) 2009 Dr. John A.R. Williams
;; Author: Dr. John A.R. Williams <[email protected]>
;;; Copying:
;; This file is part of the DATA-FORMAT-VALIDATION Common Lisp library
;; 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.
;; DATA-FORMAT-VALIDATION 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/>.
;;; Commentary:
;;
;;; Code:
(in-package :asdf)
(defsystem "data-format-validation"
:name "Data Format Validation"
:description "Validation and conversion between user and internal data."
:author "Dr. John A.R. Williams"
:version "0.2.0"
:maintainer "Dr. John A.R. Williams"
:licence "GPL v3"
:depends-on (:cl-ppcre)
:components
((:file "defpackage")
(:file "validation" :depends-on ("defpackage" "parse-number" "parse-time"))
(:file "parse-time" :depends-on ("defpackage"))
(:file "parse-number" :depends-on ("defpackage"))))
| 1,469 | Common Lisp | .asd | 33 | 41.666667 | 80 | 0.714586 | willijar/cl-data-format-validation | 8 | 2 | 1 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 65c51aa3f777a8394ded63a74aff84e4838139595651b86a274f355d6002a778 | 12,445 | [
-1
] |
12,466 | demo.lisp | lambdamikel_DLMAPS/src/demo.lisp | ;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: CL-USER -*-
(in-package :cl-user)
(defun dlmaps-demo ()
(when (probe-file "q-queries.lisp")
(let ((*package* (find-package :spatial-substrate)))
(load "q-queries.lisp")))
(dlmaps::map-viewer)
(dlmaps::result-inspector))
| 293 | Common Lisp | .lisp | 8 | 32.75 | 61 | 0.651079 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d119ea5cd4e57f8ad6478187ff01caecb11bf1d47c6e3f38df9caa53fc2b635d | 12,466 | [
-1
] |
12,467 | dlmaps-sysdcl.lisp | lambdamikel_DLMAPS/src/dlmaps-sysdcl.lisp | ;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: CL-USER -*-
(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(declaim
(optimize
(safety 0) ; Run time error checking level
(speed 3) ; Speed of the compiled code
(compilation-speed 0) ; Speed of compilation
(space 0) ; Space of both intermediate files and object
(debug 0)
)))
;;;
;;;
;;;
(setf (logical-pathname-translations "base")
(list '("**;*.*" "~mwessel/lispworks/work/dlmaps/**/*.*")))
(setf (logical-pathname-translations "dlmaps")
(list '("fonts;*.*" "base:db;*.*")
'("code;*.*" "base:*.*")
'("**;*.*" "base:**;*.*")))
(setf (logical-pathname-translations "dl-test")
(list '("**;*.*" "dlmaps:prover;dl-benchmark-suite;**;*.*")))
(setf (logical-pathname-translations "nrql-dev")
(list '("**;*.*" "dlmaps:query;**;*.*")))
;;;
;;;
;;;
(require "clim")
(load "dlmaps:define-system.lisp")
(setf system::*sg-default-size* (* 10 16000))
(setf *print-length* nil)
;;;
;;;
;;;
(defun lracer (&optional (force-p nil))
(declare (ignorable force-p))
(setf (logical-pathname-translations "lracer")
(list '("**;*.*" "dlmaps:lracer;**;*.*")))
(push :lracer *features*)
(load "lracer:lracer-sysdcl.lisp")
(compile-load-lracer))
(defun dlmaps-dev (&optional (force-p nil))
(push :debug *features*)
(dlmaps force-p))
(defun dlmaps (&optional (force-p nil))
(push :dlmaps *features*)
(push :nrql-dev *features*)
(push :midelora *features*)
(dlmaps-general force-p)
(compile-system 'dlmaps :load t :force force-p)
(terpri)
(terpri)
(princ "(dlmaps-demo)"))
(defun dlmaps-general (&optional (force-p nil))
(lracer force-p)
(load "dlmaps:query;queries-sysdcl.lisp")
(load "dlmaps:dlmaps-sysdcl.lisp")
(compile-system 'packages :load t :force-p t))
;;;
;;;
;;;
(define-system packages
(:default-pathname "dlmaps:")
(:serial
"dlmaps-packages4"))
(define-system persistence
(:default-pathname "dlmaps:persistence;")
(:serial
packages
"persistence3"))
(define-system logic-tools
(:default-pathname "dlmaps:tools;")
(:serial
packages
"tools"
"logic-tools"))
(define-system tools
(:default-pathname "dlmaps:tools;")
(:serial
packages
"grapher"
#+:clim "class-browser"
"tools"
logic-tools
#+:clim "gui-tools"
#+:clim "fonts"))
(define-system heap
(:default-pathname "dlmaps:tools;")
(:serial
"heap"))
(define-system dag
(:default-pathname "dlmaps:tools;")
(:serial
packages
"dag3"))
(define-system racer-dag
(:default-pathname "dlmaps:tools;")
(:serial
packages
dag
"racer-dag"))
#+:clim
(define-system sqd
(:default-pathname "dlmaps:sqd;")
(:serial
packages
"sqd-reader2"
"hex"
"def1"
"def2"
"os3"
"sqd-transformer"))
#+:clim
(define-system geometry
(:default-pathname "dlmaps:geometry;")
(:serial
packages
"geometry"
"polygons"
"tree-structure"
"box-relations"
"predicates"
"epsilon2"
"rcc-predicates"
"relations"))
#+:clim
(define-system map-viewer
(:default-pathname "dlmaps:map-viewer;")
(:serial
packages
sqd
"map-viewer3"
"result-inspector2"
"q-queries"
"interface"))
(define-system basic-graph
(:default-pathname "dlmaps:basic-graph;")
(:serial
packages
persistence
tools
"basic-graph"))
#+:clim
(define-system graph-visualizer
(:default-pathname "dlmaps:graph-visualizer;")
(:serial
basic-graph
"graph-visualizer3"))
(define-system thematic-substrate
(:default-pathname "dlmaps:thematic-substrate;")
(:serial
packages
#+:clim graph-visualizer
#-:clim basic-graph
;; "process"
"racer-conversions3"
"descriptions5"
"substrate7"
"rolebox"
"rolebox-substrate6"
"jepd-substrate4"
))
(define-system racer-substrate
;;; nicht individuell compilierbar!
(:default-pathname "dlmaps:thematic-substrate;")
(:serial
"common15"
"racer-substrate5"))
#+:clim
(define-system spatial-substrate
(:default-pathname "dlmaps:spatial-substrate;")
(:serial
packages
thematic-substrate
nrql
"spatial-index-macros"
"spatial-index3"
"rcc-selection"
"sqd-interface"
"map-colors"
"spatial-substrate2"
"query2"
"syntax"
"compiler6"
"runtime"
"optimizer2"
"syntactic-rewriting"
"semantic-rewriting"
"reasoning"))
(define-system tables
(:default-pathname "dlmaps:tables;")
(:serial
packages
"tables"))
(define-system ontology
(:default-pathname "dlmaps:ontology;")
(:serial
packages
"load-ontology"))
(define-system dl-benchmark
(:default-pathname "dl-test:")
(:serial
"dlmaps-tests"
"dl-tests"))
(define-system prover
(:default-pathname "dlmaps:prover;")
(:serial
packages
heap
dag
racer-dag
#+:clim graph-visualizer
thematic-substrate
tables
"settings"
"specials"
"languages"
"macros"
"syntax9"
"abstractions"
"strategy"
"abox9"
"node-label2"
"edge-label"
"abox-nodes"
"abox-edges"
"tools"
"kernel16"
"node-management"
"edge-management"
;"delete"
"concept-selection13"
"merging2"
"creators"
"abox-interface"
;;; Rules
"abox-enumeration"
"deterministic-expansion3"
"or-expansion"
"some-expansion2"
"feature-expansion"
"simple-number-restrictions-expansion"
"meta-constraints"
"blocking2"
"model-merging4"
"abox-saturation"
"precompletion"
"core-models"
;;; Prover
"alch-prover"
"alchf-prover"
"alchn-prover"
"alchf-rplus-prover"
;; "alchfn-rplus-prover"
;; "alchi-prover"
;; "alchif-prover"
;; "alchi-rplus-prover"
;; "alchif-rplus-prover"
;; "alchifn-rplus-prover"
;; "alci-ra-minus-prover"
;; "alci-ra-jepd-prover"
;;; Interface
"interface4"
"tbox9"
"roles"
"models"
"abox-queries3"
"krss"
"file-interface"
"statistics"
;; "ddl"
#+:clsql "db-abox"
dl-benchmark
nrql
"midelora-lubm"
"tester"))
#+(and :dlmaps :clim)
(define-system dlmaps
(:default-pathname "dlmaps:code;")
(:serial
packages
racer-dag
persistence
tools
sqd
geometry
ontology
graph-visualizer
thematic-substrate
tables
#+:midelora prover
nrql
spatial-substrate
map-viewer
"demo"))
;;;
;;;
;;;
;; (dlmaps t)
;; (dlmaps-demo)
| 6,529 | Common Lisp | .lisp | 300 | 17.826667 | 67 | 0.652032 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 34b9604afbf1e76b34fe33414270756de8c6f4edc85dce01e963235ee4b20e09 | 12,467 | [
-1
] |
12,469 | ontology.lisp | lambdamikel_DLMAPS/src/ontology.lisp | (IN-TBOX OEJENDORF)
(DEFINE-PRIMITIVE-ROLE EC)
(DEFINE-PRIMITIVE-ROLE DC)
(DEFINE-PRIMITIVE-ROLE EQ)
(DEFINE-PRIMITIVE-ROLE PO)
(DEFINE-PRIMITIVE-ROLE TPP)
(DEFINE-PRIMITIVE-ROLE NTPP)
(DEFINE-PRIMITIVE-ROLE TPPI)
(DEFINE-PRIMITIVE-ROLE NTPPI)
;;;
;;;
;;;
(DEFINE-PRIMITIVE-ROLE DR)
(DEFINE-PRIMITIVE-ROLE PP)
(DEFINE-PRIMITIVE-ROLE PPI)
;;;
;;; Konvention: Konzepte, die mit -<TYP>* enden,
;;; werden direkt anhand der OS-Tabelle zugesichert
;;; Damit z.B. Friedhof (Symbol) und Friedhof (Flaeche)
;;; unterschieden werden koennen, muss leider der Typ
;;; -symbol* bzw. -flaeche* als Suffix angehaengt werden.
;;; In die rechten Seiten der Konzeptaxiome werden teilweise
;;; noch "nettere Namen" hinzugefuegt, einfach damit man
;;; in den Queries nicht so viele und komplizierte Bezeichnungen
;;; verwenden muss! Diese "Hilfskonzepte" = zusaetzliches Vokabular
;;; sind daran zu erkennen, dass "*" am Anfang steht!
;;;
(DEFINE-PRIMITIVE-CONCEPT KARTEN-OBJEKT)
(DEFINE-PRIMITIVE-CONCEPT FLAECHE KARTEN-OBJEKT)
(DEFINE-PRIMITIVE-CONCEPT LINIE KARTEN-OBJEKT)
(DEFINE-PRIMITIVE-CONCEPT PUNKT KARTEN-OBJEKT)
(DEFINE-PRIMITIVE-CONCEPT SYMBOL KARTEN-OBJEKT)
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT GEO-OBJEKT KARTEN-OBJEKT) ; REPRAESENTIERT PHYSIKALISCHES OBJEKT
(DEFINE-PRIMITIVE-CONCEPT META-OBJEKT KARTEN-OBJEKT) ; REPRAESENTIERT *KEIN* PHYSIKALISCHE OBJEKT!
;;;
;;; Kartografische "Meta-Objekte"
;;;
(DEFINE-PRIMITIVE-CONCEPT KARTOGRAFISCHES-SYMBOL (AND META-OBJEKT SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT KARTOGRAFISCHER-PUNKT (AND META-OBJEKT PUNKT))
(DEFINE-PRIMITIVE-CONCEPT KARTOGRAFISCHE-LINIE (AND META-OBJEKT LINIE))
;;;
;;; Grenzen und Konturen
;;;
(DEFINE-PRIMITIVE-CONCEPT KONTUR-LINIE (AND KARTOGRAFISCHE-LINIE LINIE))
(DEFINE-PRIMITIVE-CONCEPT ABGRENZUNGS-LINIE (AND KONTUR-LINIE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT BLATTSCHNITT-BEARBEITUNGSGRENZE-FUER-SCHRIFT-LINIE* (AND KARTOGRAFISCHE-LINIE))
(DEFINE-PRIMITIVE-CONCEPT GITTERLINIE (AND KARTOGRAFISCHE-LINIE))
(DEFINE-PRIMITIVE-CONCEPT GK-GITTERLINIE-2-KM-LINIE* (AND GITTERLINIE))
(DEFINE-PRIMITIVE-CONCEPT GK-GITTERLINIE-1-KM-LINIE* (AND GITTERLINIE))
(DEFINE-PRIMITIVE-CONCEPT BAB-MITTELLINIE-LINIE* (AND KARTOGRAFISCHE-LINIE))
(DEFINE-PRIMITIVE-CONCEPT ZUSAETZLICHE-TOPOGRAPHIE-KEINE-NUTZUNGSGRENZE-LINIE* (AND KARTOGRAFISCHE-LINIE))
(DEFINE-PRIMITIVE-CONCEPT GITTERPUNKTE-FUER-DAS-EINPASSEN-VON-VORLAGEN-PUNKT* (AND KARTOGRAFISCHER-PUNKT))
;;;
;;; Grenzen / Konturen
;;;
(DEFINE-PRIMITIVE-CONCEPT TOPOGRAPHISCHE-GRENZE-LINIE* (AND ABGRENZUNGS-LINIE))
(DEFINE-PRIMITIVE-CONCEPT SPORTPLATZBEGRENZUNG-LINIE* (AND ABGRENZUNGS-LINIE))
(DEFINE-PRIMITIVE-CONCEPT NATURSCHUTZGEBIETSGRENZE-LINIE* (AND ABGRENZUNGS-LINIE))
(DEFINE-PRIMITIVE-CONCEPT ABRENZUNG-DER-BAB-USW-GEG-AUSFAHRT-UNSICHTBAR-LINIE* (AND ABGRENZUNGS-LINIE))
(DEFINE-PRIMITIVE-CONCEPT NUTZUNGSARTENGRENZE-LINIE* (AND ABGRENZUNGS-LINIE))
(DEFINE-PRIMITIVE-CONCEPT NUTZUNGSARTENGRENZE-UNSICHTBAR-LINIE* (AND NUTZUNGSARTENGRENZE-LINIE*))
(DEFINE-PRIMITIVE-CONCEPT BAB-RANDBEGRENZUNG-LINIE* (AND ABGRENZUNGS-LINIE))
(DEFINE-PRIMITIVE-CONCEPT ABGRENZUNG-FLAECHENHAFTER-GEWAESSER-UNSICHTBAR-LINIE* (AND ABGRENZUNGS-LINIE))
(DEFINE-PRIMITIVE-CONCEPT FLAECHENH-GEWAESSERBEGR-LINIE* (AND ABGRENZUNGS-LINIE))
(DEFINE-PRIMITIVE-CONCEPT FLAECHENH-GEWAESSERBEGR-SCHIFFBAR-LINIE* (AND FLAECHENH-GEWAESSERBEGR-LINIE*))
(DEFINE-PRIMITIVE-CONCEPT FLAECHENH-GEWAESSERBEGR-NICHT-SCHIFFBAR-LINIE* (AND FLAECHENH-GEWAESSERBEGR-LINIE*))
(DEFINE-PRIMITIVE-CONCEPT KONTUR-FUER-OEFFENTLICHES-GEBAEUDE-LINIE* (AND KONTUR-LINIE))
;;;
;;; Symbole
;;;
(DEFINE-PRIMITIVE-CONCEPT FLIESSRICHTUNGSPFEIL-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT MOOR-SUMPF-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT WIESE-WEIDE-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT KILOMETRIERUNG-BAB-BAB-AEHNLICH-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT FRIEDHOF-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT FRIEDHOF-FUER-NICHTCHRISTEN-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT P+R-SYMBOL-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT P+R-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL))
(DEFINE-PRIMITIVE-CONCEPT U-BAHN-STATION-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL U-BAHN-STATION))
(DEFINE-PRIMITIVE-CONCEPT S-BAHN-STATION-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL S-BAHN-STATION))
(DEFINE-PRIMITIVE-CONCEPT KLEINGARTEN-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL KLEINGARTEN))
(DEFINE-PRIMITIVE-CONCEPT POSTAMT-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL POSTAMT))
(DEFINE-PRIMITIVE-CONCEPT KIRCHE-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL KIRCHE))
(DEFINE-PRIMITIVE-CONCEPT KAPELLE-SYMBOL* (AND KARTOGRAFISCHES-SYMBOL KAPELLE))
(DEFINE-PRIMITIVE-CONCEPT NADELBAUM-SYMBOL* (AND KARTOGRAFISCHES-OBJEKT NADELBAUM))
(DEFINE-PRIMITIVE-CONCEPT NADELHOLZ-SYMBOL* (AND KARTOGRAFISCHES-OBJEKT NADELBAUM))
(DEFINE-PRIMITIVE-CONCEPT LAUBBAUM-SYMBOL* (AND KARTOGRAFISCHES-OBJEKT LAUBBAUM))
(DEFINE-PRIMITIVE-CONCEPT LAUBHOLZ-SYMBOL* (AND KARTOGRAFISCHES-OBJEKT LAUBBAUM))
;;;
;;; Natuerliche Objekte und Artefakte
;;;
(DEFINE-PRIMITIVE-CONCEPT NATUERLICHES-OBJEKT (AND GEO-OBJEKT))
(DEFINE-PRIMITIVE-CONCEPT VEGETATIVES-OBJEKT (AND NATUERLICHES-OBJEKT)) ; "lebt"
(DEFINE-PRIMITIVE-CONCEPT ARTEFAKT (AND GEO-OBJEKT))
;;;
;;; Spezielle Artefakte
;;;
(DEFINE-PRIMITIVE-CONCEPT EINRICHTUNG (AND ARTEFAKT))
(DEFINE-PRIMITIVE-CONCEPT TECHNISCHE-EINRICHTUNG (AND EINRICHTUNG))
(DEFINE-PRIMITIVE-CONCEPT INSTITUTION (AND ARTEFAKT))
(DEFINE-PRIMITIVE-CONCEPT INFRASTRUKTUR (AND EINRICHTUNG))
;;;
;;; Gebaeude
;;;
(DEFINE-PRIMITIVE-CONCEPT GEBAEUDE (AND ARTEFAKT ))
(DEFINE-PRIMITIVE-CONCEPT OEFFENTLICHES-GEBAEUDE (AND GEBAEUDE FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT OEFFENTLICHES-GEBAEUDE-FLAECHE* (AND OEFFENTLICHES-GEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT NUTZGEBAEUDE (AND GEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT WOHNGEBAEUDE (AND GEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT POSTAMT (AND SYMBOL OEFFENTLICHES-GEBAEUDE INSTITUTION NUTZGEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT KIRCHE (AND SYMBOL OEFFENTLICHES-GEBAEUDE INSTITUTION NUTZGEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT KAPELLE (AND SYMBOL KIRCHE))
(DEFINE-PRIMITIVE-CONCEPT KLEINGARTEN (AND SYMBOL WOHNGEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT WOHNHAUS (AND WOHNGEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT EINFAMILIENHAUS (AND WOHNHAUS))
(DEFINE-PRIMITIVE-CONCEPT MEHRFAMILIENHAUS (AND WOHNHAUS))
(DEFINE-PRIMITIVE-CONCEPT MIETSHAUS (AND WOHNHAUS))
(DEFINE-PRIMITIVE-CONCEPT BEHOERDE (AND GEBAEUDE INSTITUTION NUTZGEBAEUDE OEFFENTLICHES-GEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT SCHULE (AND BEHOERDE))
(DEFINE-PRIMITIVE-CONCEPT U-BAHN-STATION (AND INFRASTRUKTUR TECHNISCHE-EINRICHTUNG OEFFENTLICHES-GEBAEUDE))
(DEFINE-PRIMITIVE-CONCEPT S-BAHN-STATION (AND INFRASTRUKTUR TECHNISCHE-EINRICHTUNG OEFFENTLICHES-GEBAEUDE))
;;;
;;; Natuerliche Flaechen
;;;
(DEFINE-PRIMITIVE-CONCEPT NATUERLICHE-FLAECHE (AND NATUERLICHES-OBJEKT FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT VEGETATIVE-FLAECHE (AND NATUERLICHE-FLAECHE VEGETATIVES-OBJEKT))
(DEFINE-PRIMITIVE-CONCEPT KULTIVIERTE-FLAECHE (AND NATUERLICHE-FLAECHE ARTEFAKT))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT LANDWIRTSCHAFTLICHE-FLAECHE (AND KULTIVIERTE-FLAECHE VEGETATIVE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT GRUENFLAECHE (AND VEGETATIVE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT RASENFLAECHE (AND GRUENFLAECHE KULTIVIERTE-FLAECHE ARTEFAKT))
(DEFINE-PRIMITIVE-CONCEPT BRACHFLAECHE (AND NATUERLICHE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT BRACHFLAECHE-FLAECHE* (AND BRACHFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT GEHOELZ (AND GRUENFLAECHE BRACHFLAECHE-FLAECHE*))
(DEFINE-PRIMITIVE-CONCEPT GEHOELZ-FLAECHE* (AND GEHOELZ))
(DEFINE-PRIMITIVE-CONCEPT WIESE-WEIDE (AND GRUENFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT WIESE-WEIDE-FLAECHE* (AND WIESE-WEIDE))
;;;
;;; Nicht-natuerliche Flaechen sind "prepariert"
;;;
(DEFINE-PRIMITIVE-CONCEPT PREPARIERTE-FLAECHE (AND ARTEFAKT FLAECHE))
;;;
;;; Verschiedene spezielle preparierte Flaechen
;;;
(DEFINE-PRIMITIVE-CONCEPT PARKARTIGE-FLAECHE (AND PREPARIERTE-FLAECHE RASENFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT BEBAUTE-FLAECHE (AND PREPARIERTE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT ASPHALTIERTE-FLAECHE (AND BEBAUTE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT PLATZ-FLAECHE (AND PREPARIERTE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT BETRIEBSGELAENDE (AND BEBAUTE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT FUSSGAENGERZONE (AND ASPHALTIERTE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT FUSSGAENGERZONE-FLAECHE* (AND FUSSGAENGERZONE))
(DEFINE-PRIMITIVE-CONCEPT PARKPLATZ (AND PLATZ-FLAECHE ASPHALTIERTE-FLAECHE INFRASTRUKTUR))
(DEFINE-PRIMITIVE-CONCEPT PARKPLATZ-FLAECHE* (AND PARKPLATZ))
(DEFINE-PRIMITIVE-CONCEPT FRIEDHOF (AND PARKARTIGE-FLAECHE EINRICHTUNG INSTITUTION))
(DEFINE-PRIMITIVE-CONCEPT FRIEDHOF-FLAECHE* (AND FRIEDHOF))
(DEFINE-PRIMITIVE-CONCEPT FRIEDHOF-FUER-NICHTCHRISTEN-FLAECHE* (AND FRIEDHOF-FLAECHE*))
(DEFINE-PRIMITIVE-CONCEPT SPORTPLATZ (AND RASENFLAECHE PLATZ-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT SPORTPLATZINNENFLAECHE-FLAECHE* (AND SPORTPLATZ))
(DEFINE-PRIMITIVE-CONCEPT PARK (AND PARKARTIGE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT PARK-MIT-EINZELSYMBOLEN-FLAECHE* (AND PARK))
(DEFINE-PRIMITIVE-CONCEPT MARKTPLATZ (AND PLATZ-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT RASTPLATZ (AND PLATZ-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT FESTPLATZ (AND PLATZ-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT PLATZ-Z-B-MARKTPLATZ-RASTPLATZ-FESTPLATZ-FLAECHE* (AND MARKTPLATZ RASTPLATZ FESTPLATZ))
(DEFINE-PRIMITIVE-CONCEPT BAHNBETRIEBSGELAENDE (AND BETRIEBSGELAENDE TECHNISCHE-EINRICHTUNG INFRASTRUKTUR))
(DEFINE-PRIMITIVE-CONCEPT BAHNBETRIEBSGELAENDE-FLAECHE* (AND BAHNBETRIEBSGELAENDE))
(DEFINE-PRIMITIVE-CONCEPT INDUSTRIE (AND BETRIEBSGELAENDE TECHNISCHE-EINRICHTUNG))
(DEFINE-PRIMITIVE-CONCEPT GEWERBE (AND BETRIEBSGELAENDE))
(DEFINE-PRIMITIVE-CONCEPT INDUSTRIE-GEWERBE (AND INDUSTRIE GEWERBE))
(DEFINE-PRIMITIVE-CONCEPT INDUSTRIE-GEWERBE-FLAECHE* (AND INDUSTRIE-GEWERBE))
(DEFINE-PRIMITIVE-CONCEPT WOHNGEBIET (AND BEBAUTE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT WOHNEN (AND BEBAUTE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT WOHNEN-FLAECHE* (AND WOHNGEBIET WOHNEN))
(DEFINE-PRIMITIVE-CONCEPT KLEINGARTENVEREIN (AND BEBAUTE-FLAECHE GRUENFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT SCHREBERGARTENVEREIN (AND BEBAUTE-FLAECHE GRUENFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT KLEINGARTEN-FLAECHE* (AND KLEINGARTENVEREIN SCHREBERGARTENVEREIN))
;;;
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT WASSER (AND NATUERLICHES-OBJEKT))
(DEFINE-PRIMITIVE-CONCEPT SCHIFFBARES-WASSER (AND WASSER))
(DEFINE-PRIMITIVE-CONCEPT NICHT-SCHIFFBARES-WASSER (AND WASSER))
;;;
;;; Verschiedene natuerliche Flaechen
;;;
(DEFINE-PRIMITIVE-CONCEPT WASSERFLAECHE (AND WASSER NATUERLICHE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT TEICH (AND WASSERFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT SEE (AND WASSERFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT FLUSS (AND WASSERFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT KANAL (AND WASSERFLAECHE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT TEICH-NICHT-SCHIFFBAR (AND TEICH NICHT-SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT TEICH-NICHT-SCHIFFBAR-FLAECHE* (AND TEICH-NICHT-SCHIFFBAR))
(DEFINE-PRIMITIVE-CONCEPT SEE-NICHT-SCHIFFBAR (AND SEE NICHT-SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT SEE-NICHT-SCHIFFBAR-FLAECHE* (AND SEE-NICHT-SCHIFFBAR))
(DEFINE-PRIMITIVE-CONCEPT SEE-SCHIFFBAR (AND SEE SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT SEE-SCHIFFBAR-FLAECHE* (AND SEE-SCHIFFBAR))
(DEFINE-PRIMITIVE-CONCEPT FLUSS-SCHIFFBAR (AND FLUSS SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT FLUSS-SCHIFFBAR-FLAECHE* (AND FLUSS-SCHIFFBAR))
(DEFINE-PRIMITIVE-CONCEPT FLUSS-NICHT-SCHIFFBAR (AND FLUSS NICHT-SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT FLUSS-NICHT-SCHIFFBAR-FLAECHE* (AND FLUSS-NICHT-SCHIFFBAR))
(DEFINE-PRIMITIVE-CONCEPT KANAL-SCHIFFBAR (AND KANAL SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT KANAL-SCHIFFBAR-FLAECHE* (AND KANAL-SCHIFFBAR))
(DEFINE-PRIMITIVE-CONCEPT KANAL-NICHT-SCHIFFBAR (AND KANAL NICHT-SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT KANAL-NICHT-SCHIFFBAR-FLAECHE* (AND KANAL-NICHT-SCHIFFBAR))
;;;
;;; Natuerliche lineare Objekte
;;;
(DEFINE-PRIMITIVE-CONCEPT NATUERLICHE-LINIE (AND NATUERLICHES-OBJEKT LINIE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT WASSERLINIE (AND WASSER NATUERLICHE-LINIE))
(DEFINE-PRIMITIVE-CONCEPT BACH (AND WASSERLINIE))
(DEFINE-PRIMITIVE-CONCEPT LINIENH-BACH (AND BACH))
(DEFINE-PRIMITIVE-CONCEPT LINIENH-GRABEN-ODER-KANAL (AND WASSERLINIE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT LINIENH-KANAL-GRABEN-SCHIFFBAR (AND LINIENH-GRABEN-ODER-KANAL SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT LINIENH-KANAL-GRABEN-SCHIFFBAR-LINIE* (AND LINIENH-KANAL-GRABEN-SCHIFFBAR))
(DEFINE-PRIMITIVE-CONCEPT LINIENH-KANAL-GRABEN-NICHT-SCHIFFBAR (AND LINIENH-GRABEN-ODER-KANAL NICHT-SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT LINIENH-KANAL-GRABEN-NICHT-SCHIFFBAR-LINIE* (AND LINIENH-KANAL-GRABEN-NICHT-SCHIFFBAR))
(DEFINE-PRIMITIVE-CONCEPT LINIENH-BACH-NICHT-SCHIFFBAR (AND LINIENH-BACH NICHT-SCHIFFBARES-WASSER))
(DEFINE-PRIMITIVE-CONCEPT LINIENH-BACH-NICHT-SCHIFFBAR-LINIE* (AND LINIENH-BACH-NICHT-SCHIFFBAR))
;;;
;;; Verschiedene "vegetative Objekte"
;;;
(DEFINE-PRIMITIVE-CONCEPT BAUM (AND PUNKT VEGETATIVES-OBJEKT))
(DEFINE-PRIMITIVE-CONCEPT NADELBAUM (AND BAUM))
(DEFINE-PRIMITIVE-CONCEPT LAUBBAUM (AND BAUM))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT WALD (AND GRUENFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT LAUBWALD (AND WALD))
(DEFINE-PRIMITIVE-CONCEPT LAUBWALD-FLAECHE* (AND LAUBWALD))
(DEFINE-PRIMITIVE-CONCEPT NADELWALD (AND WALD))
(DEFINE-PRIMITIVE-CONCEPT NADELWALD-FLAECHE* (AND NADELWALD))
(DEFINE-PRIMITIVE-CONCEPT MISCHWALD (AND LAUBWALD NADELWALD))
(DEFINE-PRIMITIVE-CONCEPT MISCHWALD-FLAECHE* (AND MISCHWALD))
;;;
;;; Landwirtschaftliche Flaechen
;;;
(DEFINE-PRIMITIVE-CONCEPT OBSTANBAUGEBIET (AND LANDWIRTSCHAFTLICHE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT OBSTANBAU-FLAECHE* (AND OBSTANBAUGEBIET))
(DEFINE-PRIMITIVE-CONCEPT ACKER (AND LANDWIRTSCHAFTLICHE-FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT ACKER-FLAECHE* (AND ACKER))
;;;
;;; Verkehrswege (Strassen etc.)
;;;
(DEFINE-PRIMITIVE-CONCEPT VERKEHRSWEG (AND INFRASTRUKTUR))
(DEFINE-PRIMITIVE-CONCEPT UEBERIRDISCHER-VERKEHRSWEG (AND VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT UNTERIRDISCHER-VERKEHRSWEG (AND VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT LKW-ODER-PKW-VERKEHRSWEG (AND VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT BAHN-VERKEHRSWEG (AND VERKEHRSWEG TECHNISCHE-EINRICHTUNG LINIE))
(DEFINE-PRIMITIVE-CONCEPT U-BAHN-VERKEHRSWEG (AND BAHN-VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT S-BAHN-VERKEHRSWEG (AND BAHN-VERKEHRSWEG))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT STRASSE-ODER-WEG (AND UEBERIRDISCHER-VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT STRASSE (AND STRASSE-ODER-WEG ASPHALTIERTE-FLAECHE LKW-ODER-PKW-VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT WEG (AND STRASSE-ODER-WEG))
(DEFINE-PRIMITIVE-CONCEPT AUTOBAHN (AND STRASSE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT BAB-FLAECHE* (AND AUTOBAHN FLAECHE))
(DEFINE-PRIMITIVE-CONCEPT AUFFAHRT-AUF-BAB-BAB-AEHNLICH-B-LINIE* (AND AUTOBAHN STRASSE LINIE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT BUNDESSTRASSE (AND STRASSE))
(DEFINE-PRIMITIVE-CONCEPT BUNDESSTRASSE-FLAECHE* (AND FLAECHE BUNDESSTRASSE))
(DEFINE-PRIMITIVE-CONCEPT BUNDESSTRASSE-LINIE* (AND LINIE BUNDESSTRASSE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT SONSTIGE-STRASSE (AND STRASSE LINIE))
(DEFINE-PRIMITIVE-CONCEPT SONSTIGE-STRASSE-LINIE* (AND SONSTIGE-STRASSE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT HAUPTVERKEHRSSTRASSE (AND STRASSE LINIE))
(DEFINE-PRIMITIVE-CONCEPT HAUPTVERKEHRSSTRASSE-LINIE* (AND HAUPTVERKEHRSSTRASSE))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT U-BAHN-UNTERIRDISCH (AND U-BAHN-VERKEHRSWEG UNTERIRDISCHER-VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT U-BAHN-UNTERIRDISCH-LINIE* (AND U-BAHN-UNTERIRDISCH))
(DEFINE-PRIMITIVE-CONCEPT U-BAHN-OBERIRDISCH (AND U-BAHN-VERKEHRSWEG UEBERIRDISCHER-VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT U-BAHN-OBERIRDISCH-LINIE* (AND U-BAHN-OBERIRDISCH))
(DEFINE-PRIMITIVE-CONCEPT S-BAHN-UNTERIRDISCH (AND S-BAHN-VERKEHRSWEG UNTERIRDISCHER-VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT S-BAHN-UNTERIRDISCH-LINIE* (AND S-BAHN-UNTERIRDISCH))
(DEFINE-PRIMITIVE-CONCEPT S-BAHN-OBERIRDISCH (AND S-BAHN-VERKEHRSWEG UEBERIRDISCHER-VERKEHRSWEG))
(DEFINE-PRIMITIVE-CONCEPT S-BAHN-OBERIRDISCH-LINIE* (AND S-BAHN-OBERIRDISCH))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT VERKEHRSBEGLEITGRUEN (AND INFRASTRUKTUR GRUENFLAECHE))
(DEFINE-PRIMITIVE-CONCEPT VERKEHRSBEGLEITGRUEN-FLAECHE* (AND VERKEHRSBEGLEITGRUEN))
;;;
;;;
;;;
(DEFINE-PRIMITIVE-CONCEPT WEG-HINTEGRUND-IN-FLAECHENFARBE-LINIE* (AND WEG LINIE))
(DEFINE-PRIMITIVE-CONCEPT BRUECKE (AND VERKEHRSWEG UEBERIRDISCHER-VERKEHRSWEG LINIE))
(DEFINE-PRIMITIVE-CONCEPT BRUECKE-LINIE* (AND BRUECKE))
(DEFINE-PRIMITIVE-CONCEPT BAHNANLAGE (AND INFRASTRUKTUR TECHNISCHE-EINRICHTUNG LINIE))
(DEFINE-PRIMITIVE-CONCEPT NEBENBAHN-HAFENB-RANGIERANL-USW-OBERIRDISCH-LINIE* (AND BAHNANLAGE))
| 17,017 | Common Lisp | .lisp | 321 | 51.146417 | 120 | 0.81858 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 571e73488bc1e6c55307f8a5890adebab59573ca1ab9aa9c3834cc61fc49034d | 12,469 | [
-1
] |
12,470 | dlmaps-packages4.lisp | lambdamikel_DLMAPS/src/dlmaps-packages4.lisp | ;;; -*- MODE: LISP; SYNTAX: ANSI-COMMON-LISP; PACKAGE: CL-USER; BASE: 10 -*-
(IN-PACKAGE :CL-USER)
;;;
;;; DEFINE PACKAGES
;;;
(DEFPACKAGE heap
(:USE
common-lisp)
(:EXPORT
create-heap
heap-count
heap-empty-p
heap-clear
loop-over-heap-items
heap-insert
heap-items
heap-find
heap-remove
heap-remove-item
heap-find-item
heap-peek))
(DEFPACKAGE TOOLS
(:USE
#+:clim CLIM
#+:clim CLIM-LISP
#-:clim common-lisp)
(:EXPORT
;NNF
MAXIMUM
MINIMUM
SMALLEST
GREATES
BOOLEAN-DNF
SIMPLIFY-BOOLEAN-EXPRESSION
GET-BOOLEAN-DNF
TRANSFORM-XY-LIST
QBOX
SHOW-SUBCLASSES
SHOW-QBOX
SUBCLASS-RESPONSIBILITY
TO-BE-IMPLEMENTED
TREE-REVERSE
TREE-REMOVE
TREE-FLATTEN
TREE-COLLECT-IF
TREE-FIND
TREE-FIND-IF
TREE-MAP
TFLATTEN
MEASURE-TIME
MY-ROUND
=>
<=>
KILL
RUN
BLANK-LINE-P
WITH-STANDARD-OUTPUT-TO-FILE
CONCEPT-NAME
CHANGE-PACKAGE-OF-DESCRIPTION
INTERVALL-INTERSECTS-P
CIRCLE-INTERVALL-INTERSECTS-P
LIES-IN-CIRCLE-INTERVALL-P
CIRCLE-INTERVALL-LENGTH
RAD-TO-DEG
DEG-TO-RAD
+2PI+
+PI/2+
RECODE-GERMAN-CHARACTERS
ZEROP-EPS
=-EPS
<=-EPS
>=-EPS
ONE-OF
XOR
DEFUN-MEMO
DEFMETHOD-MEMO
RESET-MEMO
YES
NO
ENSURE-LIST
CIRCLE-SUBSEQ
MYNCONC
MY-FORMAT
PUSHEND
MAKE-CYCLIC
GET-LAMBDA-ARGS
SET-EQUAL
SET-DISJOINT
FAC
N-OVER-K
K-OUT-OF-N
COMPUTE-ALL-SUBSETS
COMPUTE-ALL-SUBSETS-OF-CARDINALITY
LOOP-OVER-SUBSETS-OF-CARDINALITY
POWER
PROD
NEWPROD
PERM
PERMUTATIONS
IS-PERMUTATION-P
FORCECDR
STRINGSUBST-CHAR-WITH-STRING
STRING-SUBSTITUTE
BUILD-ELEM-PAIRS-IN-LIST
VECTOR-ORIENTATION
SPLICE-IN
REORDER
LOOP-OVER-AVL-TREE
INSERT-INTO-AVL-TREE
DELETE-FROM-AVL-TREE
AVL-TREE-EQUAL
FIND-IN-AVL-TREE
MAKE-AVL-TREE-FROM-LIST
PRINT-AVL-TREE))
(DEFPACKAGE DAG
(:USE
TOOLS
#+:clim CLIM
#+:clim CLIM-LISP
#-:clim common-lisp)
#+:clim
(:SHADOWING-IMPORT-FROM CLIM-LISP
BOOLEAN)
(:EXPORT
DAG
DAG-NAME
MAKE-DAG
MAKE-DAG-NODE
COPY-DAG-NODE
COM-MAKE-SUBDAG-FROM-NODE
COM-EXCHANGE-CHILD-NODE-POSITIONS
DAG-BROWSER
DAG-OPTIONS
DAG-INFO
DAG-DISPLAY
DRAW-DAG-NODE
DRAW-DAG-DISPLAY
SHOW-TOP-P
SHOW-BOTTOM-P
ACCEPT-OPTIONS
DAG-NODE
DAG-NODES
DAG-ROOTS
DAG-LEAVES
DAG-TOP
DAG-BOTTOM
ORIENTATION
DAG-ROOT
FIND-DAG-NODE
DAG-NODE-NAME
DAG-NODE-MARKED-P
DAG-NODE-PARENTS
DAG-NODE-CHILDREN
DAG-NODE-ANCESTORS
DAG-NODE-DESCENDANTS
IN-DAG
MARK-DAG-NODE
FN-MARK-DAG-NODE
UNMARK-DAG-NODE
MARK-ALL-DAG-NODES
FN-MARK-ALL-DAG-NODES
UNMARK-ALL-DAG-NODES
DAG-ISOMORPHIC-P
NODE-EQUIVALENT-P
INSERT-DAG-NODE
DELETE-DAG-NODE
VISUALIZE-DAG
MAKE-POSTSCRIPT-FILE
CREATE-CLOS-CLASSES
COMPUTE-TRANSITIVE-CLOSURE
COMPUTE-HASSE-DIAGRAM))
(DEFPACKAGE GUI-TOOLS
(:USE
#+:clim CLIM
#+:clim CLIM-LISP
#-:clim common-lisp
TOOLS)
(:EXPORT
WITH-CORRECT-CLIPPING
DRAW-VECTOR-TEXT
FILE-SELECTOR
MCL-PANE
INVERSE-HIGHLIGHTER
WITH-CENTERING
WITH-BORDER
DRAW-MARKER*
GET-SIZE-OF-GRAPHIC))
(DEFPACKAGE PERSISTENCE-MANAGER
(:USE
COMMON-LISP)
(:SHADOW #:DEFCLASS #:DEFSTRUCT)
(:EXPORT
#:DEFPERSISTENTCLASS
#:DEFPERSISTENTSTRUCT
#:INITIALIZE-LOADED-PERSISTENT-OBJECT
#:MAKE-OBJECT-PERSISTENT
#:LOAD-PERSISTENT-OBJECT
#:PRINT-PERSISTENCE-MANAGER-INFO
#:USER-WRITE-CONSTRUCTOR
#:USER-WRITE-COMPONENT-CONSTRUCTOR
#:USER-WRITE-INITIALIZER
#:USER-WRITE-COMPONENT-INITIALIZER
#:USER-FILL-OBJECT
#:USER-READ-COMPONENT-OBJECT
#:USER-CREATE-EMPTY-OBJECT))
(DEFPACKAGE RACER-DAG
(:USE
DAG
RACER
;TOOLS
#+:clim CLIM-LISP
#+:dlamps CLIM
#-:clim common-lisp)
#+:clim
(:SHADOWING-IMPORT-FROM CLIM-LISP
BOOLEAN)
(:EXPORT
GET-RACER-TAXONOMY))
(DEFPACKAGE GEOMETRY
(:USE
COMMON-LISP
TOOLS
PERSISTENCE-MANAGER)
(:EXPORT
+RCC1-RELATIONSHIPS+
+RCC2-RELATIONSHIPS+
+RCC3-RELATIONSHIPS+
+RCC5-RELATIONSHIPS+
+RCC8-RELATIONSHIPS+
INFINIT
COARSER
FINER
GEOM-THING
GEOM-POINT
GEOM-LINE
GEOM-CHAIN-OR-POLYGON
GEOM-CHAIN
GEOM-POLYGON
GEOM-AGGREGATE
BOUNDING-BOX
BOUNDING-BOX-MIXIN
DELETE-OBJECT
POLYGON
CHAIN
MAKE-CIRCLE
MAKE-ARC
MAKE-POINT
P
MAKE-LINE
L
MAKE-POLYGON
POLY
MAKE-CHAIN
CHAIN
MAKE-AGGREGATE
AGG
MAKE-BOUNDING-BOX
BB
BOUNDING-BOX-P
BOUND-TO
;ID
MARK-VALUE
MARK-OBJECT
X
Y
DET
DET-0-VECS
BB-WIDTH
BB-HEIGHT
P1
P2
CENTROID
P1-OF
P2-OF
CENTROID-OF
PCENTER-OF
PMIN
PMAX
PCENTER
RADIUS
SEGMENTS
POINT-LIST
HAS-PARTS
PART-OF
POINT-=-P
POINT->=-P
POINT-<=-P
LINE-=-P
JOINS-P
PARALLEL-P
UPRIGHT-P
PRIMARY-P
COMPONENT-P
DIRECT-COMPONENT-P
COMMON-ROOT-P
GET-ALL-MASTERS
GET-ALL-COMPONENTS
GET-DIRECT-COMPONENTS
GET-ALREADY-PRESENT-DIRECT-MASTER
GET-TOPMOST-MASTER
GET-TOPMOST-COMMON-MASTER
GET-DIRECT-COMMON-MASTER
GET-DIRECT-COMMON-MASTER-FROM-LIST
FOR-EACH-MASTER-HOLDS-P
FOR-EACH-COMPONENT-HOLDS-P
FOR-SOME-MASTER-HOLDS-P
FOR-SOME-COMPONENT-HOLDS-P
CALCULATE-BOUNDING-BOX
INVALIDATE-BOUNDING-BOX
CALCULATE-AREA
DISTANCE-BETWEEN
CALCULATE-BOUNDING-BOX-FOR-COMPLEX-OBJECT
CALCULATE-CENTROID
CALCULATE-INTERSECTION-POINT
CALCULATE-INTERSECTION-LINE
ANGLE-DIFFERENCE
DISTANCE-BETWEEN*
DISTANCE-BETWEEN-POINT-AND-LINE
DISTANCE-BETWEEN
DISTANCE-BETWEEN-XY
LENGTH-OF-LINE
POINT-TRULY-INSIDE-BOX-P
POINT-TRULY-INSIDE-BOX-P*
POINT-INSIDE-BOX-P
POINT-INSIDE-BOX-P*
POINT-TRULY-OUTSIDE-BOX-P
POINT-TRULY-OUTSIDE-BOX-P*
POINT-OUTSIDE-BOX-P
POINT-OUTSIDE-BOX-P*
BOX-OVERLAPS-BOX-P
BOX-OVERLAPS-BOX-P*
ENLARGED-BOX-OVERLAPS-BOX-P
BOX-TRULY-OVERLAPS-BOX-P
BOX-TRULY-OVERLAPS-BOX-P*
BOX-TOUCHES-BOX-P
BOX-TOUCHES-BOX-P*
BOX-INSIDE-BOX-P
BOX-INSIDE-BOX-P*
BOX-TRULY-INSIDE-BOX-P
BOX-TRULY-INSIDE-BOX-P*
LINE-INTERSECTS-BOX-BORDER-P
LINE-INTERSECTS-BOX-BORDER-P*
NORMALIZE
ANGLE-BETWEEN
ANGLE-BETWEEN*
DISTANCE-AND-ORIENTATION
DISTANCE-AND-ORIENTATION*
GLOBAL-ORIENTATION
MAKE-MATRIX
RESET
TRANSLATE
SCALE
ROTATE
COMPOSE
WITH-MATRIX
WITH-TRANSLATION
WITH-SCALING
WITH-ROTATION
WITH-NO-MATRIX-AT-ALL
PROPORTIONAL-2-POINT
FIXED-SY-2-POINT
LIES-ON-P
LIES-ON-P*
INSIDE-P
INSIDE-P*
OUTSIDE-P
OUTSIDE-P*
INTERSECTS-P
CROSSES-P
CROSSES-P*
CROSSED-BY-P
TOUCHES-P
COVERS-P
COVERED-BY-P
OVERLAPS-P
CONGRUENT-P
0D-TOUCHES-P
1D-TOUCHES-P
1D-INTERSECTS-P
EQUAL-P
INSIDE-EPSILON-P
INSIDE-EPSILON-P*
CALCULATE-RELATION
INVERSE
CONTAINS-P
GET-EPSILON-ENCLOSURE-RELEVANT-POINTS
GET-EPSILON-ENCLOSURE-RELEVANT-POINTS*
SEGMENT-LIST-OK-P
BORDERS
BORDERED-BY
DISJOINT
LIES-ON
CROSSES
CROSSED-BY
TOUCHES
0D-INTERSECTS
1D-INTERSECTS
INTERSECTS
INSIDE
CONTAINS
COVERS
COVERED-BY
OVERLAPS
CONGRUENT
CALCULATE-RELATION
CALCULATE-RCC-RELATION
INVERSE-RCC-RELATION
NEGATED-RCC-RELATION
ORIENTATION
DECODE-CCW
ORIENTATE-COUNTERCLOCKWISE
ORIENTATE-CLOCKWISE
AFFECTED-BY-MATRIX-P
INSERT-NEW-BORDER-POINTS
))
(DEFPACKAGE SQD
(:USE
COMMON-LISP
TOOLS
PERSISTENCE-MANAGER)
(:EXPORT
READ-SQD-FILE
SET-CLIENT-BB
CONSTRUCT-OBJECT-FOR
LOOKUP-OS
*OS*))
(DEFPACKAGE GRAPH
(:USE
TOOLS
#+:clim CLIM
#+:clim CLIM-LISP
#-:clim common-lisp
PERSISTENCE-MANAGER
GUI-TOOLS)
#+:clim
(:SHADOW
CLIM:COLOR)
(:EXPORT
VISUALIZE
GRAPH
GRAPH-ITEM
EDGE
NODE
NAME
MAKE-GRAPH
DELETE-GRAPH
MAKE-NODE
DELETE-NODE
MAKE-EDGE
DELETE-EDGE
FIND-GRAPH
FIND-NODE
FIND-EDGE
GET-NODES
GET-EDGES
GET-EDGES-BETWEEN
NO-OF-NODES
NO-OF-EDGES
COPY-GRAPH
COPY-NODE
COPY-EDGE
COPY-GRAPH-ITEM
IN-GRAPH
INFO
KIND
COLOR
RESET-KINDS
MARKED-P
MARK
UNMARK
WITH-MARKED-OBJECTS
WITH-NEW-MARKING-CONTEXT
NODE-COUNTER
EDGE-COUNTER
GET-NODE-POSITION
FROM
TO
ID))
(DEFPACKAGE THEMATIC-SUBSTRATE
(:nicknames ts)
(:USE
#+:clim CLIM
#+:clim CLIM-LISP
#-:clim common-lisp
TOOLS
RACER
PERSISTENCE-MANAGER
GRAPH
DAG
NRQL-SYMBOLS)
(:SHADOWING-IMPORT-FROM TOOLS
NO)
#+:clim
(:SHADOWING-IMPORT-FROM CLIM-LISP
BOOLEAN)
(:SHADOWING-IMPORT-FROM GRAPH
COLOR)
(:EXPORT
*RACER-WUNA-P*
*CUR-SUBSTRATE*
*ALL-SUBSTRATES*
*NODE-DESCRIPTION-CLASS*
*EDGE-DESCRIPTION-CLASS*
*NON-DETERMINISM-P*
*LAST-QUERY*
*RUNNING-QUERY*
*RUNNING-SUBSTRATE*
ABORT-SEARCH-P
NODE
EDGE
OBJECT
SUBSTRATE
SUBSTRATE-OBJECT
SUBSTRATE-NODE
SUBSTRATE-EDGE
CONCEPT
ROLE
NODE-TABLE
EDGE-TABLE
REGISTER-BINDINGS
RACER-SUBSTRATE
RACER-SUBSTRATE-NODE
RACER-SUBSTRATE-EDGE
NON-THEMATIC-NODE-P
THEMATIC-NODE-P
NON-THEMATIC-EDGE-P
THEMATIC-EDGE-P
ESTABLISH-CONTEXT-FOR
SET-CONTEXT-FOR
ABOX
TBOX
RACER-PACKAGE
CONVERT-TO-RACER-INDIVIDUAL-NAME
CONVERT-TO-RACER-TBOX-NAME
CONVERT-TO-RACER-ABOX-NAME
CONVERT-TO-RACER-ROLE-EXPRESSION
CONVERT-TO-RACER-CONCEPT-EXPRESSION
CONVERT-TO-RACER-CONSTRAINT-EXPRESSION
CONVERT-TO-RACER-ATTRIBUTE-EXPRESSION
ALL-SUBSTRATES
GET-STANDARD-NODE-CLASS
GET-STANDARD-EDGE-CLASS
GET-STANDARD-NODE-DESCRIPTION-CLASS
GET-STANDARD-EDGE-DESCRIPTION-CLASS
COPY
COPY-SO
CONSISTENT-P
EQUIVALENT-P
CREATE-SUBSTRATE
DELETE-SUBSTRATE
DELETE-ALL-SUBSTRATES
GET-ALL-SUBSTRATES
FIND-SUBSTRATE
WITH-SUBSTRATE
IN-SUBSTRATE
WITH-SUBSTRATE*
IN-SUBSTRATE*
ID
CREATE-NODE
REGISTER-NODE
REGISTER-EDGE
ADD-TO-NODE
ADD
CHANGE-DESCRIPTION
SAVE-CURRENT-DESCRIPTION
LOAD-SAVED-DESCRIPTION
POP-DESCRIPTION-STACK
;;NODES
;;EDGES
LOOP-OVER-NODES
LOOP-OVER-EDGES
GET-NODES
GET-EDGES
GET-EDGES-BETWEEN
GET-UNDERSPECIFIED-EDGES
SIMPLIFY
SCRAMBLE
ESTABLISH-CONTEXT-FOR
SET-CONTEXT-FOR
CREATE-EDGE
INVERSE-EDGE
REFLEXIVE-EDGE-P
UNDERSPECIFIED-P
FIND-EDGE
DELETE-EDGE
GET-EDGES-BETWEEN
GET-ASSOCIATED-ABOX-INDIVIDUAL
GET-ASSOCIATED-SUBSTRATE-NODE
GET-MISSING-EDGES
GET-UNDERSPECIFIED-EDGES
SIMPLIFY
SUBGRAPH-ISOMORPHIC-P
ISOMORPHIC-P
SCRAMBLE
RACER-TBOX
RACER-ABOX
SUBSTRATE-TBOX
SUBSTRATE-ABOX
SUBSTRATE-RBOX
SUBSTRATE-NAME
FIND-RBOX
THEMATIC-NODES
THEMATIC-EDGES
DESCRIPTION
RACER-OBJECT
RACER-DESCRIPTION
SUCCESSORS
PREDECESSORS
OUTGOING
INCOMING
FROM
TO
CHANGE-PACKAGE-OF-DESCRIPTION
TRANSFORM-RACER-EXPRESSION
CONVERT-TO-RACER-DESCRIPTION
RACER-DESCRIPTIONS-SUBSTRATE
RACER-DESCRIPTIONS-SUBSTRATE-OBJECT
RACER-DESCRIPTIONS-SUBSTRATE-NODE
RACER-DESCRIPTIONS-SUBSTRATE-EDGE
;; ROLEBOX-SUBSTRATE
FULL-DISJUNCTIVE-ROLE
AXIOM
RBOX
INCONSISTENT-P
*CUR-RBOX*
ROLEBOX
ROLEBOX-SUBSTRATE
ROLEBOX-SUBSTRATE-NODE
ROLEBOX-SUBSTRATE-EDGE
ROLEBOX-NODE-DESCRIPTION
ROLEBOX-EDGE-DESCRIPTION
+RCC1-ROLEBOX+
+RCC2-ROLEBOX+
+RCC3-ROLEBOX+
+RCC5-ROLEBOX+
+RCC8-ROLEBOX+
RCC1-ROLEBOX
RCC2-ROLEBOX
RCC3-ROLEBOX
RCC5-ROLEBOX
RCC8-ROLEBOX
+RCC1-ROLES+
+RCC2-ROLES+
+RCC3-ROLES+
+RCC5-ROLES+
+RCC8-ROLES+
PO
EC
TPP
TPPI
EQ
DC
PP
PPI
NTPP
NTPPI
DR
ONE
O
GET-ROLE
INV-ROLE
MAKE-INVERSE-DESCRIPTION
INV
GET-DISJUNCTS
AUX-DESCRIPTION
SET-DESCRIPTION-TO-AUX-DESCRIPTION
AUX-DESCRIPTION-CONSISTENT-P
APPLY-ROLEBOX-AXIOMS
LOOKUP
COMPUTE-MINIMAL-LABEL
GET-IMPLIED-LABEL
ENUMERATE-ATOMIC-CONFIGURATIONS
HAS-NEXT-CONFIGURATION-P
GET-ALL-ATOMIC-CONFIGURATIONS
FIRST-COMPLETION
ALREADY-INCONSISTENT-P
GET-SUPPORT
ADD-MISSING-EDGES
VISUALIZE
IN-GRAPH
EDGE-SETT
CONSISTENT-P
EDGES
WITH-RBOX
IN-RBOX
;; JEPD SUBSTRATE
JEPD-ROLEBOX
JEPD-SUBSTRATE
JEPD-SUBSTRATE-NODE
JEPD-SUBSTRATE-EDGE
JEPD-SUBSTRATE-NODE-DESCRIPTION
JEPD-EDGE-DESCRIPTION-DESCRIPTION
;; DESCRIPTIONS
SEMANTIC-ENTITY
CHANGE-TEXTUAL-DESCRIPTION
GET-TEXTUAL-DESCRIPTION
RACER-CONCEPT-MIXIN
RACER-ROLE-MIXIN
INITIALIZE-DESCRIPTION
CONCEPT-IMPLIES-P
ROLE-IMPLIES-P
NORMALIZE-RACER-ROLE
NORMALIZE-RACER-CONCEPT
IS-VALID-RACER-ROLE-EXPRESSION-P
IS-VALID-RACER-CONCEPT-EXPRESSION-P
IS-VALID-RACER-CONSTRAINT-EXPRESSION-P
NEGATED-RACER-ROLE-P
DESCRIPTION
NODE-DESCRIPTION
EDGE-DESCRIPTION
GET-INVERSE-DESCRIPTION
GET-NEGATED-DESCRIPTION
GET-DISJUNCTS
GET-CONJUNCTS
CONCEPT-CONSISTENT-P
ROLE-CONSISTENT-P
CONCEPT-TAUTOLOGICAL-P
ROLE-TAUTOLOGICAL-P
RESET-SAT-STATUS
UNDERSPECIFIED-P
IMPLIES-P
CONSISTENT-P
INCONSISTENT-P
TAUTOLOGICAL-P
EQUIVALENT-P
INCONSISTENT
SATISFIABLE
TAUTOLOGICAL
RACER-ROLE
RACER-CONCEPT
SIMPLE-DESCRIPTION
SIMPLE-NODE-DESCRIPTION
SIMPLE-EDGE-DESCRIPTION
RACER-DESCRIPTION
RACER-NODE-DESCRIPTION
RACER-EDGE-DESCRIPTION
SIMPLE-CONJUNCTIVE-DESCRIPTION
SIMPLE-DISJUNCTIVE-DESCRIPTION
IS-ATOM-P
GET-NEGATED-ATOM
MAKE-DESCRIPTION
MAKE-NODE-DESCRIPTION
MAKE-STANDARD-NODE-DESCRIPTION
NCON
MAKE-EDGE-DESCRIPTION
MAKE-STANDARD-EDGE-DESCRIPTION
ECON
MAKE-AND-DESCRIPTION
MAKE-OR-DESCRIPTION
TEXTUAL-DESCRIPTION
ORIGINAL-DESCRIPTION
;; QUERY
QUERY
RACER-ABOX-QUERY
VIRTUAL-QUERY
SUBSTRATE-QUERY
COMPLEX-QUERY
BOTTOM-QUERY
TOP-QUERY
REAL-BOTTOM-QUERY
REAL-TOP-QUERY
HYBRID-QUERY
HOMOGENEOUS-QUERY
OR-QUERY
AND-QUERY
HOMOGENEOUS-COMPLEX-QUERY
ATOMIC-QUERY
ATOMIC-VIRTUAL-QUERY
COMPLEX-SUBSTRATE-QUERY
ATOMIC-SUBSTRATE-QUERY
HYBRID-OR-QUERY
HYBRID-AND-QUERY
COMPLEX-RACER-ABOX-QUERY
PREDICATE-DESCRIPTION-QUERY
RACER-DESCRIPTION-QUERY
SIMPLE-DESCRIPTION-QUERY
BINARY-QUERY
UNARY-QUERY
ATOMIC-RACER-ABOX-QUERY
VIRTUAL-SIMPLE-QUERY
VIRTUAL-EDGE-QUERY
VIRTUAL-NODE-QUERY
SUBSTRATE-RACER-QUERY
SUBSTRATE-PREDICATE-QUERY
SUBSTRATE-SIMPLE-QUERY
COMPLEX-SUBSTRATE-OR-QUERY
COMPLEX-SUBSTRATE-AND-QUERY
SUBSTRATE-EDGE-QUERY
SUBSTRATE-NODE-QUERY
COMPLEX-RACER-ABOX-OR-QUERY
COMPLEX-RACER-ABOX-AND-QUERY
SIMPLE-DISJUNCTIVE-DESCRIPTION-QUERY
SIMPLE-CONJUNCTIVE-DESCRIPTION-QUERY
BIND-INDIVIDUAL
EDGE-RETRIEVAL-QUERY
INSTANCE-RETRIEVAL-QUERY
VIRTUAL-SIMPLE-EDGE-QUERY
VIRTUAL-SIMPLE-OR-EDGE-QUERY
VIRTUAL-SIMPLE-AND-EDGE-QUERY
VIRTUAL-SIMPLE-NODE-QUERY
VIRTUAL-SIMPLE-OR-NODE-QUERY
VIRTUAL-SIMPLE-AND-NODE-QUERY
VIRTUAL-SIMPLE-OR-QUERY
VIRTUAL-SIMPLE-AND-QUERY
VIRTUAL-PREDICATE-EDGE-QUERY
VIRTUAL-PREDICATE-NODE-QUERY
SUBSTRATE-RACER-EDGE-QUERY
SUBSTRATE-RACER-NODE-QUERY
SUBSTRATE-PREDICATE-EDGE-QUERY
SUBSTRATE-PREDICATE-NODE-QUERY
SUBSTRATE-SIMPLE-EDGE-QUERY
SUBSTRATE-SIMPLE-OR-EDGE-QUERY
SUBSTRATE-SIMPLE-AND-EDGE-QUERY
SUBSTRATE-SIMPLE-NODE-QUERY
SUBSTRATE-SIMPLE-OR-NODE-QUERY
SUBSTRATE-SIMPLE-AND-NODE-QUERY
SUBSTRATE-SIMPLE-OR-QUERY
SUBSTRATE-SIMPLE-AND-QUERY
ERROR-PARSER-ASKS-WHAT-IS
UNARY-QUERY-P
BINARY-QUERY-P
UNARY-SUBSTRATE-QUERY-P
UNARY-ABOX-QUERY-P
BINARY-SUBSTRATE-QUERY-P
BINARY-ABOX-QUERY-P
ATOMIC-QUERY-P
ATOMIC-ABOX-QUERY-P
ATOMIC-SUBSTRATE-QUERY-P
OR-QUERY-P
AND-QUERY-P
COMPLEX-QUERY-P
NOT-QUERY-P
INV-QUERY-P
BIND-INDIVIDUAL-QUERY-P
AND-QUERY-AVAILABLE-P
OR-QUERY-AVAILABLE-P
MAKE-AND-QUERY
MAKE-OR-QUERY
PREDICATE
GET-TEXTUAL-HEAD-ENTRY
;;; RUNTIME
MATCHES-P
RETRIEVE-MATCHING-OBJECTS
RETRIEVE-CACHED-CONCEPT-INSTANCES
RETRIEVE-CHACHED-INDIVIDUAL-FILLERS
QUERYING-STARTED
QUERYING-ENDED
PREPARE-SUBSTRATE-FOR-QUERY-EXECUTION
ANSWER-QUERY
EXECUTE-QUERY
PREPARE-QUERY
;; REWRITING
ADD-BINDINGS
SYNTACTICALLY-REWRITE-QUERY
SYNTACTICALLY-REWRITE-ATOMIC-QUERY
SEMANTICALLY-REWRITE-QUERY
SEMANTICALLY-REWRITE-ATOMIC-QUERY
;; PARSER
GET-PARSER-CLASS-FOR-SUBSTRATE
SUBQUERIES
ALL-SUBQUERIES
SKIP-P
ACTIVE-P
PARSER
SIMPLE-PARSER
RACER-PARSER
RESERVED-TOKENS
+RESERVED-TOKENS+
PARSE-QUERY
UNPARSE-QUERY
GET-SUBEXPRESSIONS
GET-EXPRESSION-TYPE
MAKE-DISPATCHER
VALID-NODE-AND-DESCRIPTION-P
VALID-NODE-OR-DESCRIPTION-P
VALID-EDGE-AND-DESCRIPTION-P
VALID-EDGE-OR-DESCRIPTION-P
VALID-CONCEPT-DESCRIPTION-P
VALID-ROLE-DESCRIPTION-P
SUBSTRATE-THING-P
ABOX-THING-P
VAR-P
IND-P
ACTIVATE-ALL-SUBQUERIES
DEACTIVATE-ALL-SUBQUERIES
ACTIVATE
DEACTIVATE
VOI-FROM
VOI-TO
VOI
VOIS
ALL-VOIS
REFERENCED-VOIS
BOUND-TO
CORRESPONDING-VOI-P
TOP-LEVEL-QUERY
SUBQUERY-OF
SUBQUERIES
QUERY-FN
SOURCE
BINDINGS-FOUND-P
BINDINGS
RESULT-BINDINGS
COUNTER
ANSWER-PATTERN
ACTIVE-P
SATISFIABLE-P
SKIP-P
NEGATED-P
INVERSE-P
TIMEOUT-P
;;; OPTIMIZER
GET-SCORE
OPTIMIZE-QUERY
;;; COMPILER
COMPILE-QUERY
COMPILE-SUBQUERY
+CONTINUATION-MARKER+
GET-TESTER-CODE
GET-ENUMERATOR-CODE
GET-FROM-ENUMERATOR-CODE
GET-TO-ENUMERATOR-CODE
GET-CODE-CHECK-IF-CACHE-MEMBER-P
GET-CODE-RETURN-CACHE-MEMBERS
DEFQUERY-CODE
WITH-PROTECTED-BINDINGS
GET-BINDING-CODE
CACHE-BINDING-CODE
GET-DNF-QUERY
IN-DNF-P
GET-CODE-RACER-RETRIEVE-RELATED-INDIVIDUALS
GET-CODE-RACER-CHECK-INDIVIDUALS-RELATED-P
GET-CODE-RACER-RETRIEVE-INDIVIDUAL-FILLERS
ABORTABLE-DOLIST
;; QUERY REASONING
SUBSTRATE-CONJUNCTS-CONSISTENT-P
ABOX-CONJUNCTS-CONSISTENT-P
QUERY-CONSISTENT-P
QUERY-TAUTOLOGICAL-P
QUERY-ENTAILS-P
QUERY-ENTAILS-QUERY-P
QUERY-SATISFIABLE
QUERY-INCONSISTENT
QUERY-TAUTOLOGICAL
))
(DEFPACKAGE PROVER
(:USE
COMMON-LISP
TOOLS
DAG
GRAPH
HEAP
PERSISTENCE-MANAGER
THEMATIC-SUBSTRATE
;NRQL-SYMBOLS
)
(:SHADOW ABOX TBOX)
(:EXPORT
TBOX
ABOX
TBOX-CLASSIFIED-P
ATOMIC-CONCEPT-ANCESTORS
ATOMIC-CONCEPT-SYNONYMS
CLASSIFY-TBOX
ALL-CONCEPT-ASSERTIONS
ROLEBOX-ABOX
JEPD-ABOX
LABEL
ROLE
ABOX-NODE
ROLEBOX-ABOX-NODE
JEPD-ABOX-NODE
ABOX-EDGE
ROLEBOX-ABOX-EDGE
JEPD-ABOX-EDGE
IN-ABOX
IN-TBOX
WITH-ABOX
WITH-TBOX
FIND-ABOX
FIND-TBOX
DELETE-ABOX
DELETE-TBOX
ABOX
TBOX
MAKE-ABOX
MAKE-TBOX
*CUR-ABOX*
*CUR-TBOX*
*ALL-TBOXES*
*ALL-ABOXES*
INSTANCE
FORGET
RELATED
RELATE
INS
FGT
REL
SAT?
ABOX-SAT?
SUBSUMES?
EQUIVALENT?
EQUIVALENT-P
SAT-P
SUBSUMES-P
ABOX-SAT-P
MAKE-AXIOM
DELETE-AXIOM
DEF
DEF*
DEFINE-PRIMITIVE-CONCEPT
DEFINE-CONCEPT
DEFINE-PRIMITIVE-ROLE
TAXONOMY
RETRIEVE-CONCEPT-INSTANCES
PREPARE
GET-CONCEPT-DEFINITIONS
GET-PRIMITIVE-CONCEPT-DEFINITIONS
GET-META-CONSTRAINTS
GET-ORIGINAL-AXIOMS
GET-NEW-AXIOMS
GET-CONCEPT-NAMES
GET-PRIMITIVE-CONCEPT-NAMES
GET-NON-PRIMITIVE-CONCEPT-DEFINITIONS
GET-NON-PRIMITIVE-CONCEPT-NAMES
GET-GCIS
MAKE-AXIOM
DELETE-AXIOM
UNFOLD
COMPUTE-USED-BY-DAG
DAG-ISOMORPHIC-P
CREATE-CLOS-CLASSES
MAKE-POSTSCRIPT-FILE
COMPUTE-HASSE-DIAGRAM))
(DEFPACKAGE SPATIAL-SUBSTRATE
(:USE
#+:clim CLIM
#+:clim CLIM-LISP
#-:clim common-lisp
TOOLS
GUI-TOOLS
PERSISTENCE-MANAGER
GEOMETRY
GRAPH
THEMATIC-SUBSTRATE
PROVER
NRQL-SYMBOLS
SQD)
(:SHADOWING-IMPORT-FROM GRAPH
COLOR)
(:SHADOWING-IMPORT-FROM THEMATIC-SUBSTRATE
TBOX ABOX)
(:SHADOW ELEMENTS)
#+:clim
(:SHADOWING-IMPORT-FROM CLIM
WITH-TRANSLATION
WITH-ROTATION
WITH-SCALING)
(:SHADOWING-IMPORT-FROM GEOMETRY
BOUND-TO
POLYGON
MAKE-POINT
MAKE-LINE
MAKE-POLYGON
POLYGON
MAKE-POINT
MAKE-LINE
MAKE-POLYGON)
(:EXPORT
SHOW-NODES
SPATIAL-INDEX
SI-GEOM-THING
SI-GEOM-POINT
SI-GEOM-LINE
SI-GEOM-CHAIN-OR-POLYGON
SI-GEOM-CHAIN
SI-GEOM-POLYGON
INSTALL-AS-CURRENT-INDEX
MAKE-SPATIAL-INDEX
INIT-SPATIAL-INDEX
RESET-SPATIAL-INDEX
INSERT-INTO-SPATIAL-INDEX
REMOVE-FROM-SPATIAL-INDEX
ELEMENTS
SET-VALUE-FOR
GET-VALUE-FOR
IN-BUCKET
WITH-NEW-LEVEL
WITH-SELECTED-BUCKETS
WITH-SELECTED-OBJECTS
BUCKET-SELECTED-P
CANDIDATE-SELECTED-P
GET-POINT-FROM-SPATIAL-INDEX*
SORT-SPATIAL-INDEX
XMIN
YMIN
XMAX
YMAX
DISTANCE
AREA
LENGTH
MAP
MAP-OBJECT
BASIC-MAP-POINT
BASIC-MAP-LINE
BASIC-MAP-CHAIN
BASIC-MAP-POLYGON
MAP-OBJECT
RACER-MAP-POINT
RACER-MAP-LINE
RACER-MAP-CHAIN
RACER-MAP-POLYGON
BASIC-MAP-EDGE
RACER-MAP-EDGE
SORT-CURRENT-SPATIAL-INDEX
GET-CURRENT-MAP
INSTALL-AS-CURRENT-MAP
RESET-MAP
LOAD-MAP
STORE-MAP
MAKE-MAP-FROM-SQD-FILE
BOUND-TO
OBJECTS
ALL-OS
READY
MAP-VIEWER
RESULT-INSPECTOR
SET-CURRENT-MAP-POSITION-AND-RADIUS
DRAW-CURRENT-MAP-TO-FOREIGN-STREAM
HIGHLIGHT
UNHIGHLIGHT
HIGHLIGHTED-P
FILE-SELECTOR
MCL-PANE
INVERSE-HIGHLIGHTER
WITH-CENTERING
WITH-BORDER
DRAW-MARKER*
GET-SIZE-OF-GRAPHIC))
(DEFPACKAGE DLMAPS
(:USE
COMMON-LISP
TOOLS
PERSISTENCE-MANAGER
GEOMETRY
RACER
;; PROVER
NRQL-SYMBOLS
THEMATIC-SUBSTRATE
SPATIAL-SUBSTRATE)
(:SHADOWING-IMPORT-FROM GEOMETRY
DISJOINT
INVERSE
BOUND-TO)
(:SHADOWING-IMPORT-FROM TOOLS
NO)
(:SHADOWING-IMPORT-FROM THEMATIC-SUBSTRATE
ANSWER-QUERY)
(:EXPORT
*CURRENT-SUBSTRATE*
CONVERT-MAP))
| 22,773 | Common Lisp | .lisp | 1,161 | 14.778639 | 76 | 0.717614 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 4ebb6312fdfa9128e580d328a5998e56f70d5446136c99bd86ad9b1e01e0e55c | 12,470 | [
-1
] |
12,471 | box-relations.lisp | lambdamikel_DLMAPS/src/geometry/box-relations.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
(defgeneric point-truly-inside-box-p (point box)
(:documentation "Determine if point is contained by box. If point lies on the border of the box,
returns NIL."))
(defgeneric point-inside-box-p (point box)
(:documentation "Determine if point is contained by box. If point lies on the border of the box,
returns T."))
(defgeneric point-truly-outside-box-p (point box)
(:documentation "Determine if point is outside box. If point lies on the border of the box,
returns NIL."))
(defgeneric point-outside-outside-box-p (point box)
(:documentation "Determine if point is outside box. If point lies on the border of the box,
returns T."))
(defgeneric box-inside-box-p (box1 box2)
(:documentation "Determine whether box1 is inside box2. If box1 touches box2 from the inside,
returns T."))
(defgeneric box-truly-inside-box-p (box1 box2)
(:documentation "Determine whether box1 is inside box2. If box1 touches box2 from the inside,
returns NIL."))
(defgeneric box-overlaps-box-p (box1 box2)
(:documentation "Determine whether box1 overlaps box2. If only the borders intersect, but not their
interiors, returns T."))
(defgeneric box-truly-overlaps-box-p (box1 box2)
(:documentation "Determine whether box1 overlaps box2. If only the borders intersect, but not their
interiors, returns NIL."))
(defgeneric box-touches-box-p (box1 box2)
(:documentation "Determine whether box1 touches box2. This is the case, if
only the borders of the boxes intersect, but not their interiors."))
(defgeneric line-intersects-box-border-p (line box)
(:documentation "Determine whether line intersects the border of box. Intersections between the
interior and the line will be ignorerd."))
(defgeneric enlarged-box-overlaps-box-p (obj box r)
(:documentation "Enlarge box in all directions by R and determine wheter box and the bounding box of
obj are overlapping."))
;;;
;;; BOX-Relationen
;;;
(defun point-inside-box-p* (x y box)
(and (<= (x (pmin box)) x (x (pmax box)))
(<= (y (pmin box)) y (y (pmax box)))))
(defmethod point-inside-box-p ((point geom-point) (box bounding-box-mixin))
(point-inside-box-p* (x point) (y point) box))
(defun point-truly-inside-box-p* (x y box)
(and (< (x (pmin box)) x (x (pmax box)))
(< (y (pmin box)) y (y (pmax box)))))
(defmethod point-truly-inside-box-p ((point geom-point) (box bounding-box-mixin))
(point-truly-inside-box-p* (x point) (y point) box))
(defun point-outside-box-p* (x y box)
(or (>= x (x (pmax box)))
(<= x (x (pmin box)))
(>= y (y (pmax box)))
(<= y (y (pmin box)))))
(defmethod point-outside-box-p ((point geom-point) (box bounding-box-mixin))
(point-outside-box-p* (x point) (y point) box))
(defun point-truly-outside-box-p* (x y box)
(or (> x (x (pmax box)))
(< x (x (pmin box)))
(> y (y (pmax box)))
(< y (y (pmin box)))))
(defmethod point-truly-outside-box-p ((point geom-point) (box bounding-box-mixin))
(point-truly-outside-box-p* (x point) (y point) box))
;;;
;;;
;;;
(defun box-inside-box-p* (xmin1 ymin1 xmax1 ymax1
xmin2 ymin2 xmax2 ymax2)
(and (>= xmin1 xmin2)
(>= ymin1 ymin2)
(<= xmax1 xmax2)
(<= ymax1 ymax2)))
(defmethod box-inside-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin))
(box-inside-box-p* (x (pmin box1))
(y (pmin box1))
(x (pmax box1))
(y (pmax box1))
(x (pmin box2))
(y (pmin box2))
(x (pmax box2))
(y (pmax box2))))
;;;
;;;
;;;
(defun box-truly-inside-box-p* (xmin1 ymin1 xmax1 ymax1
xmin2 ymin2 xmax2 ymax2)
(and (> xmin1 xmin2)
(> ymin1 ymin2)
(< xmax1 xmax2)
(< ymax1 ymax2)))
(defmethod box-truly-inside-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin))
(box-truly-inside-box-p* (x (pmin box1))
(y (pmin box1))
(x (pmax box1))
(y (pmax box1))
(x (pmin box2))
(y (pmin box2))
(x (pmax box2))
(y (pmax box2))))
;;;
;;;
;;;
(defun box-overlaps-box-p* (xmin1 ymin1 xmax1 ymax1
xmin2 ymin2 xmax2 ymax2)
(and (<= xmin2 xmax1)
(<= ymin2 ymax1)
(>= xmax2 xmin1)
(>= ymax2 ymin1)))
(defmethod box-overlaps-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin))
(box-overlaps-box-p* (x (pmin box1))
(y (pmin box1))
(x (pmax box1))
(y (pmax box1))
(x (pmin box2))
(y (pmin box2))
(x (pmax box2))
(y (pmax box2))))
;;;
;;;
;;;
(defun box-truly-overlaps-box-p* (xmin1 ymin1 xmax1 ymax1
xmin2 ymin2 xmax2 ymax2)
(and (< xmin2 xmax1)
(< ymin2 ymax1)
(> xmax2 xmin1)
(> ymax2 ymin1)))
(defmethod box-truly-overlaps-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin))
(box-truly-overlaps-box-p* (x (pmin box1))
(y (pmin box1))
(x (pmax box1))
(y (pmax box1))
(x (pmin box2))
(y (pmin box2))
(x (pmax box2))
(y (pmax box2))))
;;;
;;;
;;;
(defun box-touches-box-p* (xmin1 ymin1 xmax1 ymax1
xmin2 ymin2 xmax2 ymax2)
(and (not (box-truly-overlaps-box-p* xmin1 ymin1 xmax1 ymax1
xmin2 ymin2 xmax2 ymax2))
(box-overlaps-box-p* xmin1 ymin1 xmax1 ymax1
xmin2 ymin2 xmax2 ymax2)))
(defmethod box-touches-box-p ((box1 bounding-box-mixin) (box2 bounding-box-mixin))
(box-touches-box-p* (x (pmin box1))
(y (pmin box1))
(x (pmax box1))
(y (pmax box1))
(x (pmin box2))
(y (pmin box2))
(x (pmax box2))
(y (pmax box2))))
;;;
;;;
;;;
(defun line-intersects-box-border-p* (x1 y1 x2 y2 b)
(let ((xmin (x (pmin b)))
(ymin (y (pmin b)))
(xmax (x (pmax b)))
(ymax (y (pmax b))))
(labels ((code (x y)
(let ((bit1 (< x xmin))
(bit2 (> x xmax))
(bit3 (< y ymin))
(bit4 (> y ymax)))
(values bit1 bit2 bit3 bit4))))
(multiple-value-bind (c1 c2 c3 c4)
(code x1 y1)
(multiple-value-bind (ca cb cc cd)
(code x2 y2)
(and (not
(or (and c1 ca) ; ein gemeinsames Bit ? (OR ...) => VOLLSTAENDIG UNSICHTBAR
(and c2 cb)
(and c3 cc)
(and c4 cd)))
(=> (not (or c1 c2 c3 c4 ca cb cc cd)) ; vollst. innen
(or (= x1 xmin) ; liegt auf Rand ?
(= x1 xmax)
(= x2 xmin)
(= x2 xmax)
(= y1 ymin)
(= y1 ymax)
(= y2 ymin)
(= y2 ymax)))))))))
(defmethod line-intersects-box-border-p ((line geom-line) (box bounding-box-mixin))
(and
(=> (and (bounding-box-p line)
(bounding-box-p box))
(box-overlaps-box-p line box))
(line-intersects-box-border-p* (x (p1 line))
(y (p1 line))
(x (p2 line))
(y (p2 line))
box)))
;;;
;;;
;;;
(defmethod enlarged-box-overlaps-box-p ((box1 bounding-box-mixin)
(box2 bounding-box-mixin) r)
(box-overlaps-box-p* (- (x (pmin box1)) r) (- (y (pmin box1)) r)
(+ (x (pmax box1)) r) (+ (y (pmax box1)) r)
(x (pmin box2)) (y (pmin box2))
(x (pmax box2)) (y (pmax box2))))
| 7,216 | Common Lisp | .lisp | 203 | 30.118227 | 102 | 0.615015 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | f5dc266898577eeb4ff810ad1cb138ff683cee3e77253117ac256febc35cc1e8 | 12,471 | [
-1
] |
12,472 | predicates.lisp | lambdamikel_DLMAPS/src/geometry/predicates.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
;;;
;;; Basis-Prädikate
;;;
(defun intersects-p* (xs1 ys1 xe1 ye1
xs2 ys2 xe2 ye2)
(let* ((a (ccw* xs1 ys1
xe1 ye1
xs2 ys2))
(b (ccw* xs1 ys1
xe1 ye1
xe2 ye2))
(c (ccw* xs2 ys2
xe2 ye2
xs1 ys1))
(d (ccw* xs2 ys2
xe2 ye2
xe1 ye1)))
(and
(<= (* a b) 0.0) (<= (* c d) 0.0))))
(defun crosses-p* (xs1 ys1 xe1 ye1
xs2 ys2 xe2 ye2)
(let* ((a (ccw* xs1 ys1
xe1 ye1
xs2 ys2))
(b (ccw* xs1 ys1
xe1 ye1
xe2 ye2))
(c (ccw* xs2 ys2
xe2 ye2
xs1 ys1))
(d (ccw* xs2 ys2
xe2 ye2
xe1 ye1)))
(when (and (<= (* a b) 0.0) (<= (* c d) 0.0)) ; Schnitt liegt vor
(not (or (zerop a)
(zerop b)
(zerop c)
(zerop d)
(zerop (ccw* xe1 ye1
xs1 ys1
xs2 ys2))
(zerop (ccw* xe1 ye1
xs1 ys1
xe2 ye2))
(zerop (ccw* xe2 ye2
xs2 ys2
xs1 ys1))
(zerop (ccw* xe2 ye2
xs2 ys2
xe1 ye1)))))))
(defmethod lies-on-p* (x y (line geom-line))
(or
(zerop (ccw* (x (p1 line))
(y (p1 line))
(x (p2 line))
(y (p2 line))
x y))
(zerop (ccw* (x (p2 line))
(y (p2 line))
(x (p1 line))
(y (p1 line))
x y))))
(defmethod-memo lies-on-p* (x y (poly-or-chain geom-chain-or-polygon))
((x y poly-or-chain))
(some #'(lambda (segment)
(lies-on-p* x y segment))
(segments poly-or-chain)))
;;;
;;; LIES-ON
;;;
(defmethod lies-on-p ((point1 geom-point) (point2 geom-point))
(point-=-p point1 point2))
(defmethod lies-on-p ((point geom-point) (line geom-line))
(or (zerop (ccw (p1 line) (p2 line) point))
(zerop (ccw (p2 line) (p1 line) point))))
(defmethod-memo lies-on-p ((point geom-point) (poly-or-chain geom-chain-or-polygon))
((point poly-or-chain))
(some #'(lambda (segment)
(lies-on-p point segment))
(segments poly-or-chain)))
(defmethod lies-on-p ((l1 geom-line) (l2 geom-line))
(and (lies-on-p (p1 l1) l2)
(lies-on-p (p2 l1) l2)))
#|
(defmethod-memo lies-on-p ((line geom-line) (poly geom-polygon))
((line poly-or-chain))
(or (some #'(lambda (segment)
(equal-p line segment))
(segments poly))
(and (intersects-p line poly)
(not (one-part-is-inside-p line poly))
(not (one-part-is-outside-p line poly)))))
|#
(defmethod-memo lies-on-p ((line geom-line) (poly geom-polygon))
((line poly))
(or (some #'(lambda (segment)
(lies-on-p line segment))
(segments poly))
(and (lies-on-p (p1 line) poly)
(lies-on-p (p2 line) poly)
(or (every #'(lambda (point)
(lies-on-p point line))
(get-points-between poly (p1 line) (p2 line)))
(every #'(lambda (point)
(lies-on-p point line))
(get-points-between poly (p2 line) (p1 line)))))))
(defmethod-memo lies-on-p ((line geom-line) (chain geom-chain))
((line chain))
(or (some #'(lambda (segment)
(lies-on-p line segment))
(segments chain))
(and (lies-on-p (p1 line) chain)
(lies-on-p (p2 line) chain)
(every #'(lambda (point)
(lies-on-p point line))
(get-points-between chain (p1 line) (p2 line))))))
(defmethod-memo lies-on-p ((poly-or-chain1 geom-chain-or-polygon) (poly-or-chain2 geom-chain-or-polygon))
((poly-or-chain1 poly-or-chain2))
(every #'(lambda (segment)
(lies-on-p segment poly-or-chain2))
(segments poly-or-chain1)))
;;;
;;; INTERSECTS
;;;
(defmethod intersects-p ((point1 geom-point) (point2 geom-point))
(point-=-p point1 point2))
(defmethod intersects-p ((point geom-point) (line geom-line))
(lies-on-p point line))
(defmethod intersects-p ((line geom-line) (point geom-point))
(lies-on-p point line))
(defmethod intersects-p ((point geom-point) (poly-or-chain geom-chain-or-polygon))
(lies-on-p point poly-or-chain))
(defmethod intersects-p ((poly-or-chain geom-chain-or-polygon) (point geom-point))
(lies-on-p point poly-or-chain))
(defmethod intersects-p ((l1 geom-line) (l2 geom-line))
(and (=> (and (bounding-box-p l1)
(bounding-box-p l2))
(box-overlaps-box-p l1 l2))
(let* ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2))
(a (ccw l1p1 l1p2 l2p1))
(b (ccw l1p1 l1p2 l2p2))
(c (ccw l2p1 l2p2 l1p1))
(d (ccw l2p1 l2p2 l1p2)))
(and
(<= (* a b) 0.0) (<= (* c d) 0.0)))))
(defmethod-memo intersects-p ((line geom-line) (poly-or-chain geom-chain-or-polygon))
((line poly-or-chain))
(and (=> (and (bounding-box-p line)
(bounding-box-p poly-or-chain))
(box-overlaps-box-p line poly-or-chain))
(some #'(lambda (segment)
(intersects-p line segment))
(segments poly-or-chain))))
(defmethod intersects-p ((poly-or-chain geom-chain-or-polygon) (line geom-line))
(intersects-p line poly-or-chain))
(defmethod-memo intersects-p ((poly-or-chain1 geom-chain-or-polygon) (poly-or-chain2 geom-chain-or-polygon))
((poly-or-chain1 poly-or-chain2))
(some #'(lambda (segment)
(intersects-p segment poly-or-chain2))
(segments poly-or-chain1)))
;;;
;;; CROSSES
;;;
(defmethod crosses-p ((l1 geom-line) (l2 geom-line))
;; "X" oder "+"
(and (=> (and (bounding-box-p l1)
(bounding-box-p l2))
(box-truly-overlaps-box-p l1 l2))
(let* ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2))
(a (ccw l1p1 l1p2 l2p1))
(a1 (ccw l1p2 l1p1 l2p1))
(b (ccw l1p1 l1p2 l2p2))
(b1 (ccw l1p2 l1p1 l2p2))
(c (ccw l2p1 l2p2 l1p1))
(c1 (ccw l2p2 l2p1 l1p1))
(d (ccw l2p1 l2p2 l1p2))
(d1 (ccw l2p2 l2p1 l1p2)))
(and (not (or (zerop a)
(zerop a1)
(zerop b)
(zerop b1)
(zerop c)
(zerop c1)
(zerop d)
(zerop d1)))
(<= (* a b) 0) (<= (* c d) 0)))))
(defmethod crossed-by-p ((l1 geom-line) (l2 geom-line))
(crosses-p l2 l1))
;;;
;;; TOUCHES
;;;
(defmethod touches-p ((l1 geom-line) (l2 geom-line))
;; z.B. meets ("--"), aber auch "T" oder "\/"
(and (=> (and (bounding-box-p l1)
(bounding-box-p l2))
(box-overlaps-box-p l1 l2))
(let ((l1p1-l2 (lies-on-p (p1 l1) l2))
(l1p2-l2 (lies-on-p (p2 l1) l2))
(l2p1-l1 (lies-on-p (p1 l2) l1))
(l2p2-l1 (lies-on-p (p2 l2) l1)))
(or ;; "T"-Faelle
(and l1p1-l2 (not l1p2-l2) (not l2p1-l1) (not l2p2-l1))
(and (not l1p1-l2) l1p2-l2 (not l2p1-l1) (not l2p2-l1))
(and (not l1p1-l2) (not l1p2-l2) l2p1-l1 (not l2p2-l1))
(and (not l1p1-l2) (not l1p2-l2) (not l2p1-l1) l2p2-l1)
;; "--" und "\/"-Faelle
(and (joins-p l1 l2)
;; 1d-Schnitte ausschliessen
(not (or (and l1p1-l2 l1p2-l2)
(and l2p1-l1 l2p2-l1))))))))
;;;
;;; 1D-INTERSECTS
;;;
(defmethod 1d-intersects-p ((l1 geom-line) (l2 geom-line))
;; overlaps, contains, covers, equal + Inverse
(and (=> (and (bounding-box-p l1)
(bounding-box-p l2))
(box-overlaps-box-p l1 l2))
(let ((l1p1-l2 (lies-on-p (p1 l1) l2))
(l1p2-l2 (lies-on-p (p2 l1) l2))
(l2p1-l1 (lies-on-p (p1 l2) l1))
(l2p2-l1 (lies-on-p (p2 l2) l1)))
(or (and l1p1-l2 (not l1p2-l2) l2p1-l1 (not l2p2-l1) ; overlaps-faelle
(not (point-=-p (p1 l1) (p1 l2)))) ; touches ausschliessen
(and l1p1-l2 (not l1p2-l2) (not l2p1-l1) l2p2-l1
(not (point-=-p (p1 l1) (p2 l2))))
(and (not l1p1-l2) l1p2-l2 l2p1-l1 (not l2p2-l1)
(not (point-=-p (p2 l1) (p1 l2))))
(and (not l1p1-l2) l1p2-l2 (not l2p1-l1) l2p2-l1
(not (point-=-p (p2 l1) (p2 l2))))
(and l1p1-l2 l1p2-l2 (not l2p1-l1) (not l2p2-l1)) ; l1 contains l2
(and (not l1p1-l2) (not l1p2-l2) l2p1-l1 l2p2-l1)
(and l1p1-l2 l1p2-l2 l2p1-l1 l2p2-l1) ; equal
(and l1p1-l2 (not l1p2-l2) l2p1-l1 l2p2-l1) ; l1 covers l2
(and (not l1p1-l2) l1p2-l2 l2p1-l1 l2p2-l1)
(and l1p1-l2 l1p2-l2 l2p1-l1 (not l2p2-l1)) ; l2 covers l1
(and l1p1-l2 l1p2-l2 (not l2p1-l1) l2p2-l1)))))
;;;
;;; Bestimme, ob bzgl. der von "line" erzeugten Halbebenen alle
;;; gegebenen Strecken auf einer Seite (bzw. in einer der Halbebenenen)
;;; liegen.
;;;
(defmethod-memo one-one-side-of-p ((segments list) (line geom-line))
((segments line))
(let ((ccws
(mapcar #'(lambda (x)
(ccw (p1 line) (p2 line) x))
(apply #'append
(mapcar #'point-list segments)))))
(or (every #'(lambda (x) (not (minusp x)))
ccws)
(every #'(lambda (x) (not (plusp x)))
ccws))))
;;;
;;; Inside-Relation
;;;
(defparameter *cur-line* ; willkuerlich gewaehlt
(l
(p 0 0)
(p 1 1)
:bounding-box-p nil))
(defparameter *test-beam* ; willkuerlich gewaehlt
(l
(p 0 0)
(p 1 1)
:bounding-box-p nil))
(defun-memo count-intersections* (x y polygon)
((x y polygon))
(let* ((points (point-list polygon))
(count 0)
(from-point nil)
(cur-point nil)
(mark-point '?)
(flag nil))
(setf
(x (p1 *test-beam*)) x
(y (p1 *test-beam*)) y
(x (p2 *test-beam*)) +big-int+
(y (p2 *test-beam*)) y)
(loop until (eq mark-point 'stop)
do ; einmal ganz rum
(setf cur-point (first points)
points (rest points))
(when (null points)
(setf points (point-list polygon)))
(when (eq cur-point mark-point)
(setf mark-point 'stop))
(cond ((and (= y (y cur-point)) ; Zeit sparen...
(<= x (x cur-point))
(lies-on-p cur-point *test-beam*))
(setf flag t))
(t
(if (not from-point) ; noch kein erster Pkt. gefunden
(progn
(setf mark-point cur-point) ; merken => einmal rum!
(setf flag nil)
(setf from-point cur-point))
(progn
(cond (flag ; es lagen Punkte zwischen from-point und cur-point a.d. Teststrahl
(when (or (<= (y from-point) y (y cur-point))
(>= (y from-point) y (y cur-point)))
(incf count)))
(t ; es lagen keine Pkt. a.d. Teststrahl
(setf (p1 *cur-line*) from-point)
(setf (p2 *cur-line*) cur-point)
(let ((p1c (p1 *cur-line*))
(p2c (p2 *cur-line*))
(p1t (p1 *test-beam*))
(p2t (p2 *test-beam*)))
(when (not (and (= (x p1c) (x p2c) x)))
(when (intersects-p* (x p1c) (y p1c) (x p2c) (y p2c)
(slot-value p1t 'x) (slot-value p1t 'y)
(slot-value p2t 'x) (slot-value p2t 'y))
(incf count))))))
(setf flag nil)
(setf from-point cur-point))))))
count))
(defun count-intersections (point polygon)
(count-intersections* (x point) (y point) polygon))
;;;
;;; ACHTUNG: ALLE INSIDE/OUTSIDE-RELATIONEN SIND "TRULY"-INSIDE => RAND GEHOERT NICHT DAZU !!!
;;;
(defmethod-memo inside-p* (x y (polygon geom-polygon))
((x y polygon))
(and
(=> (bounding-box-p polygon)
(point-truly-inside-box-p* x y polygon))
(not (lies-on-p* x y polygon))
(oddp (count-intersections* x y polygon))))
(defmethod inside-p ((point geom-point) (polygon geom-polygon))
(inside-p* (x point) (y point) polygon))
(defmethod contains-p ((polygon geom-polygon) (point geom-point) )
(inside-p point polygon))
(defmethod-memo outside-p* (x y (polygon geom-polygon))
((x y polygon))
(or
(and (bounding-box-p polygon)
(point-truly-outside-box-p* x y polygon))
(and
(not (lies-on-p* x y polygon))
(evenp (count-intersections* x y polygon)))))
(defmethod outside-p ((point geom-point) (polygon geom-polygon))
(outside-p* (x point) (y point) polygon))
;;;
;;;
;;;
(defmethod-memo inside-p ((line geom-line) (poly geom-polygon))
((line poly))
(and (=> (and (bounding-box-p line)
(bounding-box-p poly))
(box-truly-inside-box-p line poly))
(not (intersects-p line poly))
(inside-p (p1 line) poly)
(inside-p (p2 line) poly)))
(defmethod contains-p ((poly geom-polygon) (line geom-line))
(inside-p line poly))
(defmethod-memo outside-p ((line geom-line) (poly geom-polygon))
((line poly))
(or (and (bounding-box-p line)
(bounding-box-p poly)
(not (box-overlaps-box-p line poly)))
(and (not (intersects-p line poly))
(outside-p (p1 line) poly)
(outside-p (p2 line) poly))))
;;;
;;;
;;;
(defmethod-memo inside-p ((poly-or-chain geom-chain-or-polygon) (poly geom-polygon))
((poly-or-chain poly))
(and (=> (and (bounding-box-p poly-or-chain)
(bounding-box-p poly))
(box-truly-inside-box-p poly-or-chain poly))
(every #'(lambda (segment)
(inside-p segment poly))
(segments poly-or-chain))))
(defmethod contains-p ((poly geom-polygon) (poly-or-chain geom-chain-or-polygon))
(inside-p poly-or-chain poly))
(defmethod-memo outside-p ((poly-or-chain geom-chain-or-polygon) (poly geom-polygon))
((poly-or-chain poly))
(or (and (bounding-box-p poly-or-chain)
(bounding-box-p poly)
(not (box-overlaps-box-p poly-or-chain poly)))
(every #'(lambda (segment)
(outside-p segment poly))
(segments poly-or-chain))))
;;;
;;; Approximation: ist ein Teil einer Linie innerhalb eines Polygons enthalten?
;;; Bzw. gibt es einen echten Schnitt mit dem Inneren des Polygon?
;;; Gibt es hierfür einen effizienten Algorithmus?
;;; Hier zählt der Rand vom Polygon *NICHT* als Inneres!!!
;;;
(defconstant +delta+ 5)
(defmethod-memo one-part-is-inside-p ((line geom-line) (poly geom-polygon))
((line poly))
(or (inside-p (p1 line) poly)
(inside-p (p2 line) poly)
(one-part-is-inside-p* (x (p1 line)) (y (p1 line))
(x (p2 line)) (y (p2 line))
poly
(/ (+ (expt (- (x (p1 line)) (x (p2 line))) 2)
(expt (- (y (p1 line)) (y (p2 line))) 2))
400))))
(defun-memo one-part-is-inside-p* (x1 y1 x2 y2 poly &optional (delta +delta+))
((x1 y1 x2 y2 poly))
(when (< delta
(+ (expt (- x1 x2) 2)
(expt (- y1 y2) 2)))
(let ((xm (/ (+ x1 x2) 2))
(ym (/ (+ y1 y2) 2)))
(or (inside-p* xm ym poly)
(one-part-is-inside-p* x1 y1 xm ym poly delta)
(one-part-is-inside-p* xm ym x2 y2 poly delta)))))
;;;
;;; Hier zählt der Rand des Polygons *NICHT* als Äußeres!!!
;;;
(defmethod-memo one-part-is-outside-p ((line geom-line) (poly geom-polygon))
((line poly))
(or (and (not (lies-on-p (p1 line) poly))
(not (inside-p (p1 line) poly)))
(and (not (lies-on-p (p2 line) poly))
(not (inside-p (p2 line) poly)))
(one-part-is-outside-p* (x (p1 line)) (y (p1 line))
(x (p2 line)) (y (p2 line))
poly
(/ (+ (expt (- (x (p1 line)) (x (p2 line))) 2)
(expt (- (y (p1 line)) (y (p2 line))) 2))
10))))
(defun-memo one-part-is-outside-p* (x1 y1 x2 y2 poly &optional (delta +delta+))
((x1 y1 x2 y2 poly))
(unless (< (+ (expt (- x1 x2) 2)
(expt (- y1 y2) 2))
delta)
(let ((xm (/ (+ x1 x2) 2))
(ym (/ (+ y1 y2) 2)))
(or (and (not (inside-p* xm ym poly))
(not (lies-on-p* xm ym poly)))
(one-part-is-outside-p* x1 y1 xm ym poly delta)
(one-part-is-outside-p* xm ym x2 y2 poly delta)))))
;;;
;;; Equal-Relation
;;;
(defmethod equal-p ((obj1 geom-thing) (obj2 geom-thing))
nil)
(defmethod equal-p ((obj1 geom-point) (obj2 geom-point))
(point-=-p obj1 obj2))
(defmethod equal-p ((obj1 geom-line) (obj2 geom-line))
(line-=-p obj1 obj2))
(defmethod-memo equal-for-complex-objects-p ((obj1 geom-thing) (obj2 geom-thing) (access-fn function))
((obj1 obj2))
(and (= (length (funcall access-fn obj1))
(length (funcall access-fn obj2)))
(every #'(lambda (i)
(= 1
(count-if #'(lambda (j)
(equal-p i j))
(funcall access-fn obj2))))
(funcall access-fn obj1))))
(defmethod-memo equal-p ((obj1 geom-chain-or-polygon) (obj2 geom-chain-or-polygon))
((obj1 obj2))
(equal-for-complex-objects-p obj1 obj2 #'segments))
(defmethod-memo equal-p ((obj1 geom-aggregate) (obj2 geom-aggregate))
((obj1 obj2))
(equal-for-complex-objects-p obj1 obj2 #'has-parts))
;;;
;;;
;;;
(defmethod get-segments-between ((chain-or-poly geom-chain-or-polygon) (s1 geom-line) (s2 geom-line))
;;; bei einer Kette gibt's nur eine Richtung
;;; beim Polygon gibt es zwei!!!
;;; in dem Fall wird von s1 nach s2 gegangen
(labels ((do-it (chain-or-poly s1 s2)
(let ((current s1)
(list (list s1)))
(if (line-=-p s1 s2)
list
(loop
(let ((next
(find-if #'(lambda (x)
(and
(joins-p current x)
(not (member x list :test #'line-=-p))))
(segments chain-or-poly))))
(unless next
(return nil))
(push next list)
(setf current next)
(when (line-=-p next s2)
(return list))))))))
(or (do-it chain-or-poly s1 s2)
(do-it chain-or-poly s2 s1))))
(defmethod get-points-between ((chain-or-poly geom-chain-or-polygon) (p1 geom-point) (p2 geom-point))
(let* ((s1 (find-if #'(lambda (segment)
(lies-on-p p1 segment))
(segments chain-or-poly)))
(s2 (find-if #'(lambda (segment)
(lies-on-p p2 segment))
(segments chain-or-poly))))
(when (and s1 s2)
(let* ((segments (get-segments-between chain-or-poly s1 s2))
(point-list (mapcar #'point-list segments))
(points (apply #'append
(mapcar #'(lambda (x y)
(intersection x y :test #'point-=-p))
point-list (cdr point-list)))))
(remove-if #'(lambda (x)
(or (point-=-p x p1)
(point-=-p x p2)))
points)))))
| 19,343 | Common Lisp | .lisp | 516 | 28.837209 | 108 | 0.53709 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 99a296a119d21179299cecd99c90ba3f94231a1d1389deb31cbc37e42bae30be | 12,472 | [
-1
] |
12,473 | polygons.lisp | lambdamikel_DLMAPS/src/geometry/polygons.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
(defconstant +granularity+ 20)
(defmethod make-arc ((pfrom geom-point)
(pto geom-point)
xc yc &key (granularity +granularity+))
(multiple-value-bind (radius from)
(distance-and-orientation* xc yc (x pfrom) (y pfrom))
(multiple-value-bind (radius1 to)
(distance-and-orientation* xc yc (x pto) (y pto))
(if (=-eps radius radius1 0.001)
(let* ((points nil)
(diff (normalize (- to from)))
(fac (/ diff granularity)))
(dotimes (i (1- granularity) points)
(let* ((angle (+ from (* (1+ i) fac)))
(x (+ xc (* radius (cos angle))))
(y (+ yc (* radius (sin angle)))))
(push (list x y) points))))
(error "Bad points!")))))
(defun make-circle (x y radius &key (granularity +granularity+))
(let* ((points nil)
(fac (/ (* 2 pi) granularity)))
(dotimes (i granularity points)
(let* ((angle (* i fac))
(x (+ x (* radius (cos angle))))
(y (+ y (* radius (sin angle)))))
(push (list x y) points)))))
| 1,213 | Common Lisp | .lisp | 28 | 34.107143 | 77 | 0.530508 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 96a4db7fb0eb7efbe96c87c4afa44960851004ac154eb1d57765acf05f920e43 | 12,473 | [
-1
] |
12,474 | rcc-predicates.lisp | lambdamikel_DLMAPS/src/geometry/rcc-predicates.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
;;;
;;; Achtung - das sind Axproximationen!
;;; Für konvexe Polygone lassen sich einfacherere und
;;; korrekte Algorithmen angeben, die ohne die wichtigsten
;;; Funktionen "one-part-is-inside/outside-p*" auskommen
;;; (z.B. kann touches-p LINE x POLY gucken, ob alle Punkte
;;; des Polygons in nur einer der durch LINE geschaffenen
;;; Halbebene (Seite) liegen, etc.) Dann müsste man aber
;;; vorher auf Konvexität prüfen (ist das teuer?)
;;;
;;;
;;; Achtung: ein Objekt berührt sich eventuell selbst (reflexiv)!
;;; LINE X POLYGON, CHAIN x POLYGON, POLYGON x POLYGON
;;; (auch LINE X LINE im "intersects.lisp"-Modul)
;;;
(defmethod touches-p ((obj1 geom-thing) (obj2 geom-thing))
;;;(error "TOUCHES-P ~A ~A: Not well-defined!" obj1 obj2))
)
(defmethod touches-p ((line geom-line) (poly geom-polygon))
(and (intersects-p line poly)
(or (lies-on-p line poly)
(not (one-part-is-inside-p line poly)))))
(defmethod touches-p ((poly geom-polygon) (line geom-line))
(touches-p line poly))
#|
(defmethod touches-p ((chain1 geom-chain) (chain2 geom-chain))
;;; (error "TOUCHES-P ~A ~A: Not well-defined!" chain1 chain2))
)
|#
(defmethod touches-p ((chain1 geom-chain) (chain2 geom-chain))
(and (intersects-p chain1 chain2)
(every #'(lambda (segment)
(=> (intersects-p segment chain2)
(touches-p segment chain2)))
(segments chain1))))
(defmethod touches-p ((obj geom-chain) (poly geom-polygon))
(and (intersects-p obj poly)
(every #'(lambda (segment)
(=> (intersects-p segment poly)
(touches-p segment poly)))
(segments obj))))
(defmethod touches-p ((poly geom-polygon) (obj geom-chain))
(touches-p obj poly))
(defmethod touches-p ((poly1 geom-polygon) (poly2 geom-polygon))
(and (not (eq poly1 poly2))
(intersects-p poly1 poly2)
(every #'(lambda (segment)
(=> (intersects-p segment poly2)
(touches-p segment poly2)))
(segments poly1))))
;;;
;;; Achtung: ein Objekt "bedeckt" sich stets selbst (reflexiv)!
;;; Covered-by: LINE X POLYGON, CHAIN x POLYGON, POLYGON x POLYGON
;;; Covers: Inverse dazu
;;;
(defmethod covered-by-p ((chain1 geom-chain) (chain2 geom-chain))
;;; (error "COVERED-BY-P ~A ~A: Not well-defined!" chain1 chain2))
)
(defmethod covered-by-p ((obj1 geom-thing) (obj2 geom-thing))
;;; (error "COVERED-BY-P ~A ~A: Not well-defined!" obj1 obj2))
)
(defmethod covers-p ((chain1 geom-chain) (chain2 geom-chain))
;;; (error "COVERS-P ~A ~A: Not well-defined!" chain1 chain2))
)
(defmethod covers-p ((obj1 geom-thing) (obj2 geom-thing))
;;; (error "COVERS-P ~A ~A: Not well-defined!" obj1 obj2))
)
(defmethod covered-by-p ((line geom-line) (poly geom-polygon))
(and (intersects-p line poly)
(or (lies-on-p line poly)
(not (one-part-is-outside-p line poly)))))
(defmethod covers-p ((poly geom-polygon) (line geom-line))
(covered-by-p line poly))
(defmethod covered-by-p ((chain-or-poly geom-chain-or-polygon) (poly geom-polygon))
(and (not (eq chain-or-poly poly))
(intersects-p chain-or-poly poly)
(every #'(lambda (segment)
(=> (intersects-p segment poly)
(covered-by-p segment poly)))
(segments chain-or-poly))))
(defmethod covers-p ((poly geom-polygon) (chain-or-poly geom-chain-or-polygon))
(covered-by-p chain-or-poly poly))
;;;
;;; CROSSES / CROSSED-BY (OD- bzw. 1D-Schnitte)
;;; LINE X LINE, LINE X POLYGON, CHAIN X POLYGON
;;; (auch LINE X LINE im "intersects.lisp"-Modul)
;;;
(defmethod crosses-p ((obj1 geom-thing) (obj2 geom-thing))
;;; (error "CROSSES-P ~A ~A: Not well-defined!" obj1 obj2))
)
(defmethod crossed-by-p ((obj1 geom-thing) (obj2 geom-thing))
;;; (error "CROSSED-BY-P ~A ~A: Not well-defined!" obj1 obj2))
)
(defmethod crosses-p ((line geom-line) (chain geom-chain))
(some #'(lambda (segment)
(crosses-p line segment))
(segments chain)))
(defmethod crossed-by-p ((chain geom-chain) (line geom-line))
(crosses-p line chain))
(defmethod crosses-p ((line geom-line) (poly geom-polygon))
(and (intersects-p line poly)
(one-part-is-inside-p line poly)))
(defmethod crossed-by-p ((poly geom-polygon) (line geom-line))
(crosses-p line poly))
(defmethod crosses-p ((chain geom-chain) (poly geom-polygon))
(some #'(lambda (segment)
(crosses-p segment poly))
(segments chain)))
(defmethod crossed-by-p ((poly geom-polygon) (chain geom-chain))
(crosses-p chain poly))
;;;
;;; Achtung: ein Objekt überlappt sich nicht selbst!
;;; POLY X POLY
;;;
(defmethod overlaps-p ((obj1 geom-thing) (obj2 geom-thing))
;;; (error "OVERLAPS-P ~A ~A: Not well-defined!" obj1 obj2))
)
(defmethod overlaps-p ((poly1 geom-polygon) (poly2 geom-polygon))
(and (not (eq poly1 poly2))
(intersects-p poly1 poly2)
(some #'(lambda (segment)
(one-part-is-inside-p segment poly2))
(segments poly1))))
;;;
;;; Kongruenz
;;; TOTAL
;;;
(defmethod congruent-p ((obj1 geom-thing) (obj2 geom-thing))
nil)
(defmethod congruent-p ((p1 geom-point) (p2 geom-point))
(point-=-p p1 p2))
(defmethod congruent-p ((l1 geom-line) (l2 geom-line))
(line-=-p l1 l2))
(defmethod congruent-p ((obj1 geom-chain-or-polygon) (obj2 geom-chain-or-polygon))
(or (equal-p obj1 obj2)
(and (every #'(lambda (segment)
(lies-on-p segment obj2))
(segments obj1))
(every #'(lambda (segment)
(lies-on-p segment obj1))
(segments obj2)))))
| 5,808 | Common Lisp | .lisp | 143 | 35.307692 | 83 | 0.641067 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 7a5da88ace2a3e9f484481facfd36ddae666bf0c6f5f09b65e7d8a2970bfe04c | 12,474 | [
-1
] |
12,475 | tree-structure.lisp | lambdamikel_DLMAPS/src/geometry/tree-structure.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
(defgeneric primary-p (obj)
(:documentation "Returns T, if obj is no part of any other object."))
(defgeneric component-p (obj1 obj2)
(:documentation "If obj1 is a direct or indirect part of obj2, returns T."))
(defgeneric get-all-masters (obj)
(:documentation "Returns all objects which have obj as a component object (part)."))
(defgeneric get-direct-components (obj)
(:documentation "Returns all objects which are a direct component of obj."))
(defgeneric common-root-p (obj1 obj2)
(:documentation "Determine wheter obj1 and obj2 have a common ancestor."))
;;;
;;;
;;;
(defmethod primary-p ((obj geom-thing))
(null (part-of obj)))
;;;
;;;
;;;
(defmethod component-p ((component geom-thing)
(master geom-thing))
nil)
(defmethod component-p ((component geom-point)
(master geom-line))
(or (eq (p1 master) component)
(eq (p2 master) component)))
(defmethod component-p ((component geom-thing)
(master geom-chain-or-polygon))
(or (member component (segments master))
(some #'(lambda (segment)
(component-p component segment))
(segments master))))
(defmethod component-p ((component geom-thing)
(master geom-aggregate))
(or (member component (has-parts master))
(some #'(lambda (part)
(component-p component part))
(has-parts master))))
;;;
;;;
;;;
(defmethod direct-component-p ((component geom-thing)
(master geom-thing))
nil)
(defmethod direct-component-p ((component geom-point)
(master geom-line))
(or (eq (p1 master) component)
(eq (p2 master) component)))
(defmethod direct-component-p ((component geom-thing)
(master geom-chain-or-polygon))
(member component (segments master)))
(defmethod direct-component-p ((component geom-thing)
(master geom-aggregate))
(member component (has-parts master)))
;;;
;;;
;;;
(defun for-each-master-holds-p (obj fn)
(if obj
(every #'(lambda (master)
(and (funcall fn master)
(for-each-master-holds-p master fn)))
(part-of obj))
t))
(defun for-each-component-holds-p (obj fn)
(if obj
(every #'(lambda (comp)
(and (funcall fn comp)
(for-each-component-holds-p comp fn)))
(get-direct-components obj))
t))
(defun for-some-master-holds-p (obj fn)
(if obj
(some #'(lambda (master)
(or (funcall fn master)
(for-some-master-holds-p master fn)))
(part-of obj))
nil))
(defun for-some-component-holds-p (obj fn)
(if obj
(some #'(lambda (comp)
(or (funcall fn comp)
(for-some-component-holds-p comp fn)))
(get-direct-components obj))
nil))
;;;
;;;
;;;
(defun get-already-present-direct-master (&rest components)
(let ((i
(reduce #'intersection
(mapcar #'part-of components))))
(if (null (rest i))
(first i)
(error "More than one master object!"))))
(defun get-topmost-common-master (&rest components)
(reduce #'intersection
(mapcar #'get-topmost-master components)))
(defun get-topmost-master (obj)
(let ((res nil))
(labels ((do-it (obj)
(let ((masters (part-of obj)))
(if masters
(dolist (master masters)
(do-it master))
(pushnew obj res)))))
(do-it obj)
res)))
(defun get-direct-common-master (&rest components)
(reduce #'intersection
(mapcar #'part-of components)))
(defun get-direct-common-master-from-list (components)
(reduce #'intersection
(mapcar #'part-of components)))
;;;
;;;
;;;
(defmethod get-direct-components ((obj geom-thing))
nil)
(defmethod get-direct-components ((obj geom-line))
(point-list obj))
(defmethod get-direct-components ((obj geom-chain-or-polygon))
(segments obj))
(defmethod get-direct-components ((obj geom-aggregate))
(has-parts obj))
;;;
;;;
;;;
(defmethod has-parts ((obj geom-thing))
(get-direct-components obj))
;;;
;;;
;;;
(defmethod get-all-masters ((obj geom-thing))
(let ((res nil))
(dolist (master (part-of obj))
(setf res
(nconc (cons master (get-all-masters master)) res)))
res))
(defmethod get-all-components ((obj geom-thing))
(let ((res nil))
(dolist (part (get-direct-components obj))
(setf res
(nconc (cons part (get-all-components part)) res)))
res))
;;;
;;;
;;;
(defmethod common-root-p ((obj1 geom-thing) (obj2 geom-thing))
(or (eq obj1 obj2)
(intersection
(get-all-masters obj1)
(get-all-masters obj2))))
(defun for-each-parent-execute (obj fn)
(when obj
(funcall fn obj)
(dolist (master (part-of obj))
(for-each-parent-execute master fn))))
| 4,748 | Common Lisp | .lisp | 159 | 25.566038 | 86 | 0.654778 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 49c65f3fc642c8ae3e2a0cd8f11464a19466aaef4fe179605daacd189737060d | 12,475 | [
-1
] |
12,476 | epsilon2.lisp | lambdamikel_DLMAPS/src/geometry/epsilon2.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
(defgeneric inside-epsilon-p (obj1 obj2 radius &key epsilon-a epsilon-b)
(:documentation "Determine whether obj1 lies inside the epsilon-enclosure
of radius of object obj2."))
;;;
;;; Achtung! Diese Relation ist *nicht* symmetrisch!!!
;;;
(defmethod-memo inside-epsilon-p ((obj1 geom-point) (obj2 geom-thing) radius &key (epsilon-a 1) (epsilon-b 1))
((obj1 obj2 radius epsilon-a epsilon-b))
(let ((radius (* radius radius)))
(<= (distance-between obj1 obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius)))
(defmethod-memo inside-epsilon-p* ((x number) (y number) (obj geom-thing) radius &key (epsilon-a 1) (epsilon-b 1))
((x y radius epsilon-a epsilon-b))
(let ((radius (* radius radius)))
(<= (distance-between-xy x y obj :sqrt nil :sx epsilon-a :sy epsilon-b) radius)))
;;;
;;;
;;;
(defmethod-memo inside-epsilon-p ((obj1 geom-line) (obj2 geom-point) radius &key (epsilon-a 1) (epsilon-b 1))
;;; zu lesen als: ist die Linie obj1 im Epsilon-Radius der Größe radius vom Punkt obj2 enthalten?
;;; Referenz-Objekte (um das der Radius gezogen wird) ist immer obj2!!!!
;;;
((obj1 obj2 radius epsilon-a epsilon-b))
(let ((radius (* radius radius)))
(and (<= (distance-between (p1 obj1) obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius)
(<= (distance-between (p2 obj1) obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius))))
(defmethod-memo inside-epsilon-p ((obj1 geom-line) (obj2 geom-line) radius &key (epsilon-a 1) (epsilon-b 1))
((obj1 obj2 radius epsilon-a epsilon-b))
(let ((radius (* radius radius)))
(and (<= (distance-between (p1 obj1) obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius)
(<= (distance-between (p2 obj1) obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius))))
(defmethod-memo inside-epsilon-p ((obj1 geom-line) (obj2 geom-chain-or-polygon) radius &key (epsilon-a 1) (epsilon-b 1))
((obj1 obj2 radius epsilon-a epsilon-b))
(let ((radius (* radius radius)))
(labels ((do-it (x1 y1 x2 y2 mindist)
(if (< (distance-between* x1 y1 x2 y2 :sqrt nil :sx epsilon-a :sy epsilon-b) mindist)
t
(let ((mx (/ (+ x1 x2) 2))
(my (/ (+ y1 y2) 2)))
(and (some #'(lambda (segment)
(<= (distance-between-point-and-line mx my
(x (p1 segment))
(y (p1 segment))
(x (p2 segment))
(y (p2 segment))
:sqrt nil
:sx epsilon-a :sy epsilon-b)
radius))
(segments obj2))
(do-it x1 y1 mx my mindist)
(do-it mx my x2 y2 mindist))))))
(and (<= (distance-between (p1 obj1) obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius)
(<= (distance-between (p2 obj1) obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius)
(do-it (x (p1 obj1)) (y (p1 obj1))
(x (p2 obj1)) (y (p2 obj1))
(/ (length-of-line obj1) +granularity+)))))) ; Teilstrecken untersuchen!
;;;
;;;
;;;
(defmethod-memo inside-epsilon-p ((obj1 geom-chain-or-polygon) (obj2 geom-point) radius &key (epsilon-a 1) (epsilon-b 1))
((obj1 obj2 radius epsilon-a epsilon-b))
(let ((radius (* radius radius)))
(every #'(lambda (p)
(<= (distance-between p obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius))
(point-list obj1))))
(defmethod-memo inside-epsilon-p ((obj1 geom-chain-or-polygon) (obj2 geom-line) radius &key (epsilon-a 1) (epsilon-b 1))
((obj1 obj2 radius epsilon-a epsilon-b))
(let ((radius (* radius radius)))
(every #'(lambda (p)
(<= (distance-between p obj2 :sqrt nil :sx epsilon-a :sy epsilon-b) radius))
(point-list obj1))))
(defmethod-memo inside-epsilon-p ((obj1 geom-chain-or-polygon) (obj2 geom-chain-or-polygon) radius &key (epsilon-a 1) (epsilon-b 1))
((obj1 obj2 radius epsilon-a epsilon-b))
(every #'(lambda (s)
(inside-epsilon-p obj1 s radius :epsilon-a epsilon-a :epsilon-b epsilon-b))
(segments obj2)))
| 3,986 | Common Lisp | .lisp | 77 | 46.532468 | 132 | 0.641059 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6081eec91b512c38d4c5ed06d0a14dd37e694fd12f635f503365bedc23c1c223 | 12,476 | [
-1
] |
12,477 | relations.lisp | lambdamikel_DLMAPS/src/geometry/relations.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
(defgeneric calculate-relation (obj1 obj2 &rest rest)
(:documentation "Recognizes various spatial relationships between obj1 and obj2."))
;;;
;;;
;;;
(defconstant +rcc8-relationships+
'(:po :eq :dc :ec :ntpp :ntppi :tpp :tppi))
(defconstant +rcc5-relationships+
'(:po :eq :dr :pp :ppi))
(defconstant +rcc3-relationships+
'(:one :eq :dr))
(defconstant +rcc2-relationships+
'(:o :dr))
(defconstant +rcc1-relationships+
'(:sr))
;;;
;;;
;;;
(defun inverse (rel)
(list 'inv rel))
;;;
;;;
(defmethod calculate-relation ((p1 geom-point) (p2 geom-point) &key (lod 0))
;; LOD = "leve of detail" of the description
(cond ((and (plusp lod) (eq p1 p2))
`(intersects
,@(when (plusp lod)
`(0d
,@(when (plusp (1- lod))
`(equal
,@(when (plusp (- lod 2))
'(eq))))))))
((point-=-p p1 p2)
`(intersects
,@(when (plusp lod)
`(0d
,@(when (plusp (1- lod))
`(equal))))))
(t
'(disjoint))))
(defmethod calculate-relation ((p geom-point) (l geom-line) &key (lod 0))
(cond ((lies-on-p p l)
`(intersects
,@(when (plusp lod)
`(0d
,@(when (plusp (1- lod))
`(lies-on inside
,@(when (plusp (- lod 2))
(cond ((point-=-p (p1 l) p)
`(is-endpoint
,@(when (plusp (- lod 3))
`((point-p1-relation ,(calculate-relation p (p1 l)
:lod (- lod 4)))))))
((point-=-p (p2 l) p)
`(is-endpoint
,@(when (plusp (- lod 3))
`((point-p2-relation ,(calculate-relation p (p2 l)
:lod (- lod 4)))))))))))))))
(t
'(disjoint))))
(defmethod calculate-relation ((l geom-line) (p geom-point) &rest rest)
(inverse
(apply #'calculate-relation p l rest)))
(defmethod calculate-relation ((p geom-point) (poly geom-polygon) &key (lod 0))
(cond ((lies-on-p p poly)
`(intersects
,@(when (plusp lod)
`(0d
,@(when (plusp (1- lod))
`(lies-on lies-on-border
,@(when (plusp (- lod 2))
(let ((res (remove-if-not #'(lambda (segment)
(lies-on-p p segment))
(segments poly))))
`(,@(when (some #'(lambda (x)
(point-=-p x p))
(point-list poly))
'(is-vertex-of))
,@(when (and res (plusp (- lod 3)))
`(point-segment-relations
,@(mapcar #'(lambda (segment)
(calculate-relation p segment
:lod (- lod 4)))
res))))))))))))
((inside-p p poly)
`(intersects
,@(when (plusp lod)
`(0d
,@(when (plusp (1- lod))
`(inside))))))
(t '(disjoint outside))))
(defmethod calculate-relation ((poly geom-polygon) (p geom-point) &rest rest)
(inverse
(apply #'calculate-relation p poly rest)))
(defmethod calculate-relation ((p geom-point) (c geom-chain) &key (lod 0))
(cond ((lies-on-p p c)
`(intersects
,@(when (plusp lod)
`(0d
,@(when (plusp (1- lod))
`(lies-on
,@(when (plusp (- lod 2))
(when (some #'(lambda (x)
(point-=-p x p))
(point-list c))
'(is-vertex-of)))
,@(when (plusp (- lod 3))
(cond ((point-=-p (p1 c) p)
`(is-endpoint
,@(when (plusp (- lod 4))
`((point-p1-relation ,(calculate-relation p (p1 c)
:lod (- lod 5)))))))
((point-=-p (p2 c) p)
`(is-endpoint
,@(when (plusp (- lod 3))
`((point-p2-relation ,(calculate-relation p (p2 c)
:lod (- lod 5)))))))))
,@(let ((res (remove-if-not #'(lambda (segment)
(lies-on-p p segment))
(segments c))))
(when (and res (plusp (- lod 4)))
`((point-segment-relations
,@(mapcar #'(lambda (segment)
(calculate-relation p segment
:lod (- lod 5)))
res)))))))))))
(t '(disjoint))))
(defmethod calculate-relation ((l geom-chain) (p geom-point) &rest rest)
(inverse
(apply #'calculate-relation p l rest)))
;;;
;;;
;;;
(defmethod calculate-relation ((l1 geom-line) (l2 geom-line) &key (lod 0))
(if (and (bounding-box-p l1)
(bounding-box-p l2)
(not (box-overlaps-box-p l1 l2)))
'(disjoint)
(let* ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2))
(a (ccw l1p1 l1p2 l2p1))
(b (ccw l1p1 l1p2 l2p2))
(c (ccw l2p1 l2p2 l1p1))
(d (ccw l2p1 l2p2 l1p2)))
(cond ((and (<= (* a b) 0.0) (<= (* c d) 0.0)) ; Schnitt liegt vor
`(intersects
,@(when (plusp lod)
(let* ((l1p1-l2 (lies-on-p (p1 l1) l2))
(l1p2-l2 (lies-on-p (p2 l1) l2))
(l2p1-l1 (lies-on-p (p1 l2) l1))
(l2p2-l1 (lies-on-p (p2 l2) l1))
(n (+ (if l1p1-l2 1 0)
(if l1p2-l2 1 0)
(if l2p1-l1 1 0)
(if l2p2-l1 1 0))))
(let ((res
(ecase n
(0 `(0d
,@(when (plusp (1- lod))
'(crosses)))) ; X
(1 `(0d
,@(when (plusp (1- lod))
'(touches)))) ; T
(3 `(1d
,@(when (plusp (1- lod))
(if (and l1p1-l2 l1p2-l2)
'(covered-by)
'(covers)))))
(4 `(1d
,@(when (plusp (1- lod))
`(equal
,@(when (and (eq l1 l2)
(plusp (- lod 2)))
'(eq))))))
(2 (cond ((joins-p l1 l2)
`(0d ,@(when (plusp (1- lod))
'(touches)))) ; --, \/
((and l1p1-l2 l1p2-l2)
`(1d ,@(when (plusp (1- lod))
'(inside))))
((and l2p1-l1 l2p2-l1)
`(1d ,@(when (plusp (1- lod))
'(contains))))
(t
`(1d ,@(when (plusp (1- lod))
'(overlaps)))))))))
(if (plusp (- lod 2))
`(,@res (endpoint-line-relations ,(calculate-relation (p1 l1) l2 :lod (- lod 3))
,(calculate-relation (p2 l1) l2 :lod (- lod 3))
,(calculate-relation (p1 l2) l1 :lod (- lod 3))
,(calculate-relation (p2 l2) l1 :lod (- lod 3))))
res))))))
(t '(disjoint))))))
(defmethod calculate-relation ((l geom-line) (c geom-chain) &key (lod 0))
(cond ((intersects-p l c)
`(intersects
,@(when (plusp lod)
`( ,@(if (some #'(lambda (x)
(1d-intersects-p x l))
(segments c))
`(1d
,@(when (and (plusp (1- lod)))
`( ,@(when (some #'(lambda (x)
(line-=-p x l))
(segments c))
'(segment-of))
,@(when (lies-on-p l c)
'(lies-on)))))
`(0d))))
,@(when (plusp (- lod 2))
`((endpoint-chain-relations ,(calculate-relation (p1 l) c :lod (- lod 3))
,(calculate-relation (p2 l) c :lod (- lod 3)))))
,@(let ((res (remove-if-not #'(lambda (segment)
(intersects-p l segment))
(segments c))))
(when (and res (plusp (- lod 3)))
(list (cons 'line-segment-relations
(mapcar #'(lambda (segment)
(calculate-relation l segment
:lod (- lod 4)))
res)))))))
(t '(disjoint))))
(defmethod calculate-relation ((c geom-chain) (l geom-line) &rest rest)
(inverse
(apply #'calculate-relation l c rest)))
(defmethod calculate-relation ((l geom-line) (p geom-polygon) &key (lod 0))
(declare (ignore rest))
(if (intersects-p l p)
`(intersects
,@(when (plusp lod)
(cond ((inside-p l p)
`(inside
,@(when (plusp (1- lod))
`(1d))))
((lies-on-p l p)
`(lies-on lies-on-border
,@(when (plusp (1- lod))
`(1d))))
((covered-by-p l p)
`(covered-by
,@(when (plusp (1- lod))
`(1d))))
((crosses-p l p)
`(crosses
,@(when (plusp (1- lod))
`(1d))))
(t
`(touches
,@(when (plusp (1- lod))
`( ,@(if (some #'(lambda (segment)
(1d-intersects-p l segment))
(segments p))
'(1d)
'(0d))))))))
,@(when (plusp (- lod 2))
`((endpoint-polygon-relations
,(calculate-relation (p1 l) p :lod (- lod 3))
,(calculate-relation (p2 l) p :lod (- lod 3)))))
,@(let ((res (remove-if-not #'(lambda (segment)
(intersects-p l segment))
(segments p))))
(when (and res (plusp (- lod 3)))
`((line-segment-relations
,@(mapcar #'(lambda (segment)
(calculate-relation l segment
:lod (- lod 4)))
res))))))
'(disjoint)))
(defmethod calculate-relation ((p geom-polygon) (l geom-line) &rest rest)
(inverse
(apply #'calculate-relation l p rest)))
;;;
;;;
;;;
(defmethod calculate-relation ((c1 geom-chain) (c2 geom-chain) &key (lod 0))
(cond ((intersects-p c1 c2)
`(intersects
,@(when (plusp lod)
`( ,@(if (some #'(lambda (x)
(some #'(lambda (y)
(1d-intersects-p x y))
(segments c2)))
(segments c1))
`(1d
,@(when (and (plusp (1- lod)))
`( ,@(when (lies-on-p c1 c2)
'(lies-on))))
,@(when (and (plusp (- lod 2)))
`( ,@(when (some #'(lambda (x)
(some #'(lambda (y)
(line-=-p x y))
(segments c2)))
(segments c1))
'(common-segment)))))
`(0d))))
,@(when (plusp (- lod 2))
`((endpoint-chain-relations ,(calculate-relation (p1 c1) c2 :lod (- lod 3))
,(calculate-relation (p2 c1) c2 :lod (- lod 3))
,(calculate-relation (p1 c2) c1 :lod (- lod 3))
,(calculate-relation (p2 c2) c1 :lod (- lod 3)))))
,@(let ((res (remove-if-not #'(lambda (segment)
(intersects-p segment c2))
(segments c1))))
(when (and res (plusp (- lod 3)))
(list (cons 'segment-chain-relations
(mapcar #'(lambda (segment)
(calculate-relation segment c2
:lod (- lod 4)))
res)))))))
(t '(disjoint))))
(defmethod calculate-relation ((c geom-chain) (p geom-polygon) &key (lod 0))
(declare (ignore rest))
(if (intersects-p c p)
`(intersects
,@(when (plusp lod)
(cond ((inside-p c p)
`(inside
,@(when (plusp (1- lod))
`(1d))))
((lies-on-p c p)
`(lies-on lies-on-border
,@(when (plusp (1- lod))
`(1d))))
((covered-by-p c p)
`(covered-by
,@(when (plusp (1- lod))
`(1d))))
((crosses-p c p)
`(crosses
,@(when (plusp (1- lod))
`(1d))))
(t
`(touches
,@(when (plusp (1- lod))
`( ,@(if (some #'(lambda (i)
(some #'(lambda (j)
(1d-intersects-p i j))
(segments p)))
(segments c))
'(1d)
'(0d))))))))
,@(when (plusp (- lod 2))
`((endpoint-polygon-relations
,(calculate-relation (p1 c) p :lod (- lod 3))
,(calculate-relation (p2 c) p :lod (- lod 3)))))
,@(let ((res (remove-if-not #'(lambda (segment)
(intersects-p c segment))
(segments p))))
(when (and res (plusp (- lod 3)))
`((chain-segment-relations
,@(mapcar #'(lambda (segment)
(calculate-relation c segment
:lod (- lod 4)))
res))))))
'(disjoint)))
(defmethod calculate-relation ((p geom-polygon) (c geom-chain) &rest rest)
(inverse
(apply #'calculate-relation c p rest)))
;;;
;;;
;;;
(defmethod calculate-relation ((p1 geom-polygon) (p2 geom-polygon) &key (lod 0))
(declare (ignore lod))
(if (intersects-p p1 p2)
`(intersects
,@(when (plusp lod)
(cond ((inside-p p1 p2)
`(inside
,@(when (plusp (1- lod))
`(2d))))
((inside-p p2 p1)
`(contains
,@(when (plusp (1- lod))
`(2d))))
((covered-by-p p1 p2)
`(covered-by
,@(when (plusp (1- lod))
`(2d))))
((covered-by-p p2 p1)
`(covers-p
,@(when (plusp (1- lod))
`(2d))))
((overlaps-p p1 p2)
`(overlaps
,@(when (plusp (1- lod))
`(2d))))
(t
`(touches
,@(when (plusp (1- lod))
`( ,@(if (some #'(lambda (i)
(some #'(lambda (j)
(1d-intersects-p i j))
(segments p2)))
(segments p1))
'(1d)
'(0d))))))))
,@(when (plusp (- lod 2))
`((segment-poly-relations
,@(mapcar #'(lambda (segment)
(calculate-relation segment p2
:lod (- lod 3)))
(segments p1))))))
'disjoint))
;;;
;;;
;;;
(defun inverse-rcc-relation (rel)
(labels ((lookup (rel)
(case (intern (format nil "~A" rel) :keyword)
(:bottom :bottom)
(:top :top)
(:pp :ppi)
(:ppi :pp)
(:tpp :tppi)
(:ntpp :ntppi)
(:tppi :tpp)
(:ntppi :ntpp)
(:borders :bordered-by)
(:bordered-by :borders)
(:ec :ec)
(:po :po)
(:dc :dc)
(:dr :dr)
(:one :one)
(:o :o)
(:sr :sr)
(:eq :eq)
(otherwise rel))))
(if (consp rel)
(mapcar #'lookup rel)
(lookup rel))))
(defun negated-rcc-relation (rel &optional (type :rcc8))
(if (member :bottom rel)
'(:top)
(if (member :top rel)
'(:bottom)
(let ((rel (ensure-list rel)))
(ecase type
(:rcc8 (if (subsetp rel +rcc8-relationships+)
(set-difference +rcc8-relationships+ rel)
(error "Unrecognized ~A relation ~A!" type rel)))
(:rcc5 (if (subsetp rel +rcc5-relationships+)
(set-difference +rcc5-relationships+ rel)
(error "Unrecognized ~A relation ~A!" type rel)))
(:rcc3 (if (subsetp rel +rcc3-relationships+)
(set-difference +rcc3-relationships+ rel)
(error "Unrecognized ~A relation ~A!" type rel)))
(:rcc2 (if (subsetp rel +rcc2-relationships+)
(set-difference +rcc2-relationships+ rel)
(error "Unrecognized ~A relation ~A!" type rel)))
(:rcc1 (if (subsetp rel +rcc1-relationships+)
(set-difference +rcc1-relationships+ rel)
(error "Unrecognized ~A relation ~A!" type rel))))))))
(defun coarser (rel)
(remove-duplicates
(mapcar #'(lambda (x)
(case x
((:ntpp :tpp) :pp)
((:ntppi :tppi) :ppi)
((:dc :ec) :dr)
((:pp :ppi :po) :one)
((:one :eq) :o)
((:o :dr) :sr)
((:top) :top)
((:bottom) :bottom)
(otherwise x)))
(ensure-list rel))))
(defun finer (rel)
(remove-duplicates
(apply #'append
(mapcar #'(lambda (x)
(case x
(:bottom '(:bottom))
(:top '(:top))
(:pp '(:ntpp :tpp))
(:ppi '(:ntppi :tppi))
(:dr '(:dc :ec))
(:one '(:pp :ppi :po))
(:o '(:one :eq))
(:sr '(:o :dr))
(otherwise (ensure-list x))))
(ensure-list rel)))))
(let ((tools::*use-memoization* t))
(defun-memo calculate-rcc-relation (a b)
((a b))
;;; zusätzlich erweitert um "borders/bordered-by"
;;; für lineale Features
(typecase a
(geom-point
(typecase b
(geom-point
(cond ((point-=-p a b)
:eq)
(t :dc)))
(geom-line
(cond ((lies-on-p a b)
:bordered-by)
(t :dc)))
(geom-chain
(cond ((lies-on-p a b)
:bordered-by)
(t :dc)))
(geom-polygon
(cond ((inside-p a b)
:ntpp)
((lies-on-p a b)
:bordered-by)
(t
:dc)))))
(geom-line
(typecase b
(geom-point
(cond ((lies-on-p b a)
:borders)
(t :dc)))
(geom-line
(cond ((line-=-p a b)
:eq)
((touches-p a b)
:ec)
((intersects-p a b)
:po)
(t :dc)))
(geom-chain
(cond ((lies-on-p a b)
:bordered-by)
((touches-p a b)
:ec)
((intersects-p a b)
:po)
(t :dc)))
(geom-polygon
(cond ((intersects-p a b)
(cond ((lies-on-p a b)
:bordered-by)
((covered-by-p a b)
:tpp)
((touches-p a b)
:ec)
(t :po)))
((inside-p a b)
:ntpp)
(t :dc)))))
(geom-chain
(typecase b
(geom-point
(cond ((lies-on-p b a)
:borders)
(t :dc)))
(geom-line
(cond ((lies-on-p b a)
:borders)
((touches-p b a)
:ec)
((intersects-p a b)
:po)
(t :dc)))
(geom-chain
(cond ((congruent-p a b)
:eq)
((lies-on-p a b)
:bordered-by)
((lies-on-p b a)
:borders)
((touches-p b a)
:ec)
((intersects-p a b)
:po)
(t :dc)))
(geom-polygon
(cond ((intersects-p a b)
(cond ((lies-on-p a b)
:bordered-by)
((covered-by-p a b)
:tpp)
((touches-p a b)
:ec)
(t :po)))
((inside-p a b)
:ntpp)
(t :dc)))))
(geom-polygon
(typecase b
(geom-point
(cond ((lies-on-p b a)
:borders)
((inside-p b a)
:ntppi)
(t :dc)))
(geom-line
(cond ((intersects-p a b)
(cond ((lies-on-p b a)
:borders)
((covered-by-p b a)
:tppi)
((touches-p a b)
:ec)
(t :po)))
((inside-p b a)
:ntppi)
(t :dc)))
(geom-chain
(cond ((intersects-p a b)
(cond ((lies-on-p b a)
:borders)
((covered-by-p b a)
:tppi)
((touches-p a b)
:ec)
(t :po)))
((inside-p b a)
:ntppi)
(t :dc)))
(geom-polygon
(cond ((congruent-p a b)
:eq)
((intersects-p a b)
(cond ((covered-by-p b a)
:tppi)
((covered-by-p a b)
:tpp)
((touches-p a b)
:ec)
(t :po)))
((inside-p b a)
:ntppi)
((inside-p a b)
:ntpp)
(t :dc))))))))
| 26,894 | Common Lisp | .lisp | 633 | 20.595577 | 118 | 0.325901 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 35a3c3b973815b938a63d6b6e5f4146d672dc103f657b966aa2cd015cbfbc0b3 | 12,477 | [
-1
] |
12,478 | geometry.lisp | lambdamikel_DLMAPS/src/geometry/geometry.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
(defgeneric mark-obj (obj value)
(:documentation "Mark object with value."))
(defgeneric x (point)
(:documentation "Returns the x position of point with respect to *matrix*"))
(defgeneric y (point)
(:documentation "Returns the y position of point with respect to *matrix*"))
(defgeneric point-=-p (point1 point2)
(:documentation "Returns T if point1 and point2 have the same position."))
(defgeneric line-=-p (line1 line2)
(:documentation "Returns T if line1 and line2 are congruent."))
(defgeneric point->=-p (point1 point2)
(:documentation "Returns T if point1 is right and above point2."))
(defgeneric point-<=-p (point1 point2)
(:documentation "Returns T if point1 is left and below point2."))
(defgeneric joins-p (line1 line2)
(:documentation "Returns T, if line1 and line2 have a common point (point-=-p)."))
(defgeneric parallel-p (line1 line2)
(:documentation "Determine whether line1 and line2 are parallel."))
(defgeneric upright-p (line1 line2)
(:documentation "Determine whether line1 and line2 are upright."))
(defgeneric delete-object (obj &key)
(:method-combination progn)
(:documentation "Delete object."))
(defgeneric centroid (obj)
(:documentation "Returns the centroid of obj."))
(defgeneric ccw (point1 point2 point3)
(:documentation "Counterclockwise way from point1 over point2 to point3. See Sedgewick for details!"))
(defgeneric distance-between (obj1 obj2 &key sqrt sx sy)
(:documentation "Calculate the smallest distance between obj1 and obj2."))
(defgeneric global-orientation (line)
(:documentation "Calculate the angle between the x-axis and the line."))
(defgeneric calculate-intersection-point (line1 line2)
(:documentation "Returns (x,y) intersection point (if a zero dimensional intersection between
line1 and line2 holds)."))
(defgeneric calculate-intersection-line (line1 line2)
(:documentation "Returns (x1,y1,x2,y2) intersection line (if a one dimensional intersection between
line1 and line2 holds)."))
(defgeneric calculate-area (polygon)
(:documentation "Calulates the area of the polygon."))
(defgeneric orientation (polygon)
(:documentation "Calulates the orientation of the polygon."))
(defgeneric change-orientation (polygon)
(:documentation "Change the orientation of the polygon."))
(defgeneric orientate-clockwise (polygon)
(:documentation "Change the orientation of the polygon to clockwise."))
(defgeneric orientate-counterclockwise (polygon)
(:documentation "Change the orientation of the polygon to counter-clockwise."))
(defgeneric insert-new-border-points (polygon-or-chain points)
(:documentation "Create a new chain/polygon with additional points on the border of the original object."))
;;;
;;;
;;;
(defconstant +big-int+ 10000)
(defparameter *matrix* nil)
(defparameter *mark-counter* 0)
(defparameter *verbose-printing-p* nil)
(defun get-new-mark ()
(incf *mark-counter*))
(defparameter *round-p* t) ;; when t -> Koordinaten werden auf "Round precision"-Stellen Genauigkeit reduziert
(defparameter *rounding-precision* 10000)
;;;
;;;
;;;
(defpersistentclass bounding-box-mixin () ; abstrakt
((pmin :initarg :pmin :writer (setf pmin) :initform nil)
(pmax :initarg :pmax :writer (setf pmax) :initform nil)
(pcenter :initarg :pcenter :writer (setf pcenter) :initform nil)
(radius :initarg :radius :writer (setf radius) :initform nil)
(last-trafo-id :accessor last-trafo-id :initarg :last-trafo-id
:initform (if *matrix* (trafo-id *matrix*) -2))
(bounding-box-p :initform t :initarg :bounding-box-p :accessor bounding-box-p)))
(defpersistentclass bounding-box (bounding-box-mixin) ; instantiierbar, aber NICHT TRANSFORMIERBAR !!!
((pmin :reader pmin)
(pmax :reader pmax)
(pcenter :reader pcenter)
(radius :reader radius)))
;;;
;;;
;;;
(defvar *id-counter* 0)
(defpersistentclass geom-thing () ; abstrakt
((part-of :initform nil :initarg :part-of :accessor part-of)
(id :accessor id :initform (incf *id-counter*))
(class-of-internal-points :accessor class-of-internal-points
:initarg :class-of-internal-points
:initform 'geom-point)
(affected-by-matrix-p :reader affected-by-matrix-p :initform t :initarg :affected-by-matrix-p)
;;; bei Punkten: T <=> nicht von Matrix beruehrt
;;; bei anderen Objekten: entscheidet, ob bei Bedarf neu erzeugte berechnete Punkte (centroid obj)
;;; das Flag gesetzt bekommen oder nicht
(check-p :accessor check-p :initarg :check-p :initform t)
(bound-to :accessor bound-to :initform nil)
(cp-flag :accessor cp-flag :initform nil)
(mark-value :accessor mark-value :initform nil)
(error-flag :accessor error-flag :initform nil)))
(defpersistentclass geom-point (geom-thing)
((x :writer (setf x) :initarg :x)
(y :writer (setf y) :initarg :y)
(centroid-of :accessor centroid-of :initarg :centroid-of :initform nil)
(pcenter-of :accessor pcenter-of :initarg :pcenter-of :initform nil)
(p1-of :accessor p1-of :initarg :p1-of :initform nil)
(p2-of :accessor p2-of :initarg :p2-of :initform nil)))
(defmethod pcenter ((obj geom-point))
obj)
(defpersistentclass geom-line (geom-thing bounding-box-mixin)
((p1 :initarg :p1 :accessor p1)
(p2 :initarg :p2 :accessor p2)
(point-list :accessor point-list)
(centroid-p :initform t :initarg :centroid-p :accessor centroid-p)
(centroid :initform nil :initarg :centroid :writer (setf centroid))))
(defpersistentclass geom-chain-or-polygon (geom-thing bounding-box-mixin)
((segments :initarg :segments :accessor segments)
(centroid :initform nil :initarg :centroid :writer (setf centroid))
(centroid-p :initform t :initarg :centroid-p :accessor centroid-p)
(point-list :accessor point-list :initarg :point-list)))
(defpersistentclass geom-polygon (geom-chain-or-polygon)
())
(defpersistentclass geom-chain (geom-chain-or-polygon)
((p1 :initarg :p1 :accessor p1)
(p2 :initarg :p2 :accessor p2)))
(defpersistentclass geom-aggregate (geom-thing bounding-box-mixin)
((has-parts :initarg :has-parts :accessor has-parts)
(centroid-p :initform t :initarg :centroid-p :accessor centroid-p)
(centroid :initform nil :initarg :centroid :writer (setf centroid))))
;;;
;;;
;;;
(defmethod trafo-id ((obj null))
-1)
(defmethod pmin ((obj bounding-box-mixin))
(with-slots (pmin last-trafo-id) obj
(unless (and pmin (= last-trafo-id (trafo-id *matrix*)))
(recalculate-bounding-box obj))
pmin))
(defmethod pmax ((obj bounding-box-mixin))
(with-slots (pmax last-trafo-id) obj
(unless (and pmax (= last-trafo-id (trafo-id *matrix*)))
(recalculate-bounding-box obj))
pmax))
(defmethod pcenter ((obj bounding-box-mixin))
(with-slots (pcenter last-trafo-id) obj
(unless (and pcenter (= last-trafo-id (trafo-id *matrix*)))
(recalculate-bounding-box obj))
pcenter))
(defmethod radius ((obj bounding-box-mixin))
(with-slots (radius last-trafo-id) obj
(unless (and radius (= last-trafo-id (trafo-id *matrix*)))
(recalculate-bounding-box obj))
radius))
;;;
;;;
;;;
(defmethod bb-width ((obj bounding-box-mixin))
(- (x (pmax obj)) (x (pmin obj))))
(defmethod bb-height ((obj bounding-box-mixin))
(- (y (pmax obj)) (y (pmin obj))))
;;;
;;;
;;;
(defun check-for-centroid (obj)
(with-slots (centroid) obj
(unless centroid
(calculate-centroid obj))
centroid))
(defmethod centroid ((obj geom-point))
obj)
(defmethod centroid ((obj geom-line))
(check-for-centroid obj))
(defmethod centroid ((obj geom-chain-or-polygon))
(check-for-centroid obj))
(defmethod centroid ((obj geom-aggregate))
(check-for-centroid obj))
;;;
;;;
;;;
(defmethod print-object ((obj geom-thing) stream)
(format stream "#<~A ~A>"
(type-of obj)
(id obj)))
(defmethod print-object ((obj geom-point) stream)
(if *verbose-printing-p*
(format stream "#<~A ~A (~A,~A)>"
(type-of obj)
(id obj)
(x obj)
(y obj))
(call-next-method)))
(defmethod print-object ((obj geom-line) stream)
(if *verbose-printing-p*
(format stream "#<~A ~A ((~A,~A)-(~A,~A)>"
(type-of obj)
(id obj)
(x (p1 obj))
(y (p1 obj))
(x (p2 obj))
(y (p2 obj)))
(call-next-method)))
#|
(mapcar #'(lambda (x)
(list (x x) (y x)))
(point-list obj))))
|#
(defmethod print-object ((obj geom-chain-or-polygon) stream)
(if *verbose-printing-p*
(format stream "#<~A ~A ~A>"
(type-of obj)
(id obj)
(get-xy-list obj))
(call-next-method)))
;;;
;;;
;;;
(defmethod mark-object ((obj geom-thing) value)
(setf (mark-value obj) value))
;;;
;;;
;;;
(defmethod point-=-p ((p1 geom-point) (p2 geom-point))
(or (eq p1 p2)
(and (=-eps (x p1) (x p2))
(=-eps (y p1) (y p2)))))
(defmethod point->=-p ((p1 geom-point) (p2 geom-point))
(and (>=-eps (x p1) (x p2))
(>=-eps (y p1) (y p2))))
(defmethod point-<=-p ((p1 geom-point) (p2 geom-point))
(and (<=-eps (x p1) (x p2))
(<=-eps (y p1) (y p2))))
;;;
;;;
;;;
(defmethod line-=-p ((l1 geom-line) (l2 geom-line))
(or (eq l1 l2)
(and (point-=-p (p1 l1) (p1 l2))
(point-=-p (p2 l1) (p2 l2)))
(and (point-=-p (p1 l1) (p2 l2))
(point-=-p (p2 l1) (p1 l2)))))
(defmethod parallel-p ((line1 geom-line) (line2 geom-line))
(let ((dx1 (- (x (p1 line1)) (x (p2 line1))))
(dx2 (- (x (p1 line2)) (x (p2 line2))))
(dy1 (- (y (p1 line1)) (y (p2 line1))))
(dy2 (- (y (p1 line2)) (y (p2 line2)))))
(or (zerop-eps (- (* dx1 dy2) (* dx2 dy1)))
(zerop-eps (- (* dx2 dy1) (* dx1 dy2))))))
(defmethod upright-p ((line1 geom-line) (line2 geom-line))
(let ((dx1 (- (x (p1 line1)) (x (p2 line1))))
(dx2 (- (x (p1 line2)) (x (p2 line2))))
(dy1 (- (y (p1 line1)) (y (p2 line1))))
(dy2 (- (y (p1 line2)) (y (p2 line2)))))
(zerop-eps
(+ (* dx1 dx2) (* dy1 dy2)))))
(defmethod joins-p ((i geom-line) (j geom-line))
"joins-p(i,j) <=> haben mind. einen wertgleichen oder identischen Endpunkt"
(or (and (point-=-p (p1 i) (p1 j)))
(and (point-=-p (p1 i) (p2 j)))
(and (point-=-p (p2 i) (p1 j)))
(and (point-=-p (p2 i) (p2 j)))))
;;;
;;;
;;;
(defmethod x ((point geom-point))
(with-slots (x y affected-by-matrix-p) point
(let ((val
(if (and *matrix* affected-by-matrix-p)
(with-slots (a b tx) *matrix*
(+ (* a x) (* b y) tx))
x)))
(if *round-p*
(/ (my-round (* val *rounding-precision*)) *rounding-precision*)
val))))
(defmethod y ((point geom-point))
(with-slots (x y affected-by-matrix-p) point
(let ((val
(if (and *matrix* affected-by-matrix-p)
(with-slots (c d ty) *matrix*
(+ (* c x) (* d y) ty))
y)))
(if *round-p*
(/ (my-round (* val *rounding-precision*)) *rounding-precision*)
val))))
;;;
;;;
;;;
(defvar *trafo-id* 0)
(defpersistentclass matrix ()
((trafo-id :accessor trafo-id :initform (incf *trafo-id*))
; z.B. muss die BB nach Rotationen
; neuberechnet werden (=> Id aendert sich)
(a :accessor a :initarg :a :initform 1)
(b :accessor b :initarg :b :initform 0)
(tx :accessor tx :initarg :tx :initform 0)
(c :accessor c :initarg :c :initform 0)
(d :accessor d :initarg :d :initform 1)
(ty :accessor ty :initarg :ty :initform 0)))
(defmacro make-matrix (&rest rest)
`(make-instance 'matrix ,@rest))
(defmacro reset (matrix)
`(with-slots (trafo-id a b tx c d ty) ,matrix
(setf trafo-id (incf *trafo-id*))
(setf a 1
b 0
tx 0
c 0
d 1
ty 0)
,matrix))
(defmacro translate (matrix x y)
`(with-slots (trafo-id tx ty) ,matrix
(setf trafo-id (incf *trafo-id*))
(incf tx ,x)
(incf ty ,y)
,matrix))
(defmacro scale (matrix sx sy)
(let ((sx1 sx)
(sy1 sy))
`(with-slots (trafo-id a b c d tx ty) ,matrix
(setf trafo-id (incf *trafo-id*))
(psetf a (* a ,sx1)
b (* b ,sx1)
tx (* tx ,sx1)
ty (* ty ,sy1)
c (* c ,sy1)
d (* d ,sy1))
,matrix)))
(defmacro rotate (matrix r)
`(let ((rot ,r))
(with-slots (trafo-id a b c d tx ty) ,matrix
(let ((pcos (cos rot))
(msin (- (sin rot)))
(psin (sin rot)))
(setf trafo-id (incf *trafo-id*))
(psetf
a (+ (* a pcos) (* c msin))
b (+ (* b pcos) (* d msin))
tx (+ (* tx pcos) (* ty msin))
c (+ (* a psin) (* c pcos))
d (+ (* b psin) (* d pcos))
ty (+ (* tx psin) (* ty pcos)))
,matrix))))
(defmacro with-matrix ((matrix) &body body)
`(let ((*matrix* ,matrix))
,@body))
(defmacro with-no-matrix-at-all (&body body)
`(let ((*matrix* nil))
,@body))
;;;
;;;
;;;
(defmacro with-saved-matrix ((matrix) &body body)
(let ((a (gensym))
(b (gensym))
(tx (gensym))
(c (gensym))
(d (gensym))
(ty (gensym)))
`(let ((,a (a ,matrix))
(,b (b ,matrix))
(,c (c ,matrix))
(,d (d ,matrix))
(,tx (tx ,matrix))
(,ty (ty ,matrix)))
(prog1
(progn
,@body)
(with-slots (a b c d tx ty) ,matrix
(setf a ,a
b ,b
c ,c
d ,d
tx ,tx
ty ,ty))))))
(defmacro with-translation ((tx ty) &body body)
`(if *matrix*
(with-saved-matrix (*matrix*)
(translate *matrix* ,tx ,ty)
,@body)
(let ((*matrix* (make-matrix :tx ,tx :ty ,ty)))
,@body)))
(defmacro with-scaling ((sx sy) &body body)
`(if *matrix*
(with-saved-matrix (*matrix*)
(scale *matrix* ,sx ,sy)
,@body)
(let ((*matrix* (make-matrix :a ,sx :d ,sy)))
,@body)))
(defmacro with-rotation ((rot) &body body)
`(if *matrix*
(with-saved-matrix (*matrix*)
(rotate *matrix* ,rot)
,@body)
(let ((*matrix* (make-matrix)))
(rotate *matrix* ,rot)
,@body)))
;;;
;;;
(defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point))
(let* ((x0 (x p0))
(x1 (x p1))
(x2 (x p2))
(y0 (y p0))
(y1 (y p1))
(y2 (y p2)))
(ccw* x0 y0 x1 y1 x2 y2)))
(defun ccw* (x0 y0 x1 y1 x2 y2)
(let* ((dx1 (- x1 x0))
(dy1 (- y1 y0))
(dx2 (- x2 x0))
(dy2 (- y2 y0)))
(cond ((> (* dx1 dy2) (* dy1 dx2)) 1)
((< (* dx1 dy2) (* dy1 dx2)) -1)
((or (< (* dx1 dx2) 0)
(< (* dy1 dy2) 0))
-1)
((< (+ (* dx1 dx1) (* dy1 dy1))
(+ (* dx2 dx2) (* dy2 dy2)))
1)
(t 0))))
;;;
;;; Konstruktoren
;;;
(defun make-bounding-box (xmin ymin xmax ymax &rest initargs) ; BB als "eigenständiges" Objekt
(apply #'make-instance 'bounding-box
:xmin xmin :ymin ymin
:xmax xmax :ymax ymax
:allow-other-keys t
initargs))
(defun make-point (x y &rest initargs &key (class 'geom-point) &allow-other-keys)
(apply #'make-instance class
:x x :y y
:allow-other-keys t
initargs))
(defun make-line (p1 p2 &rest initargs &key (class 'geom-line) &allow-other-keys)
(apply #'make-instance class
:p1 p1
:p2 p2
:allow-other-keys t
initargs))
(defun make-chain (segment-list &rest initargs &key (class 'geom-chain) &allow-other-keys)
(apply #'make-instance class
:segments segment-list
:allow-other-keys t
initargs))
(defun make-polygon (segment-list &rest initargs &key (class 'geom-polygon) &allow-other-keys)
(apply #'make-instance class
:segments segment-list
:allow-other-keys t
initargs))
(defun make-aggregate (has-parts &rest initargs &key (class 'geom-aggregate) &allow-other-keys)
(apply #'make-instance class
:has-parts has-parts
:allow-other-keys t
initargs))
;;;
;;;
;;;
(defun bb (xmin ymin xmax ymax &rest initargs)
(apply #'make-bounding-box xmin ymin xmax ymax initargs))
(defun p (x y &rest initargs)
(apply #'make-point x y initargs))
(defun l (p1 p2 &rest initargs)
(apply #'make-line p1 p2 initargs))
(defun chain (segment-list &rest initargs)
(apply #'make-chain segment-list initargs))
(defun chain-from-xy-list (xy-list &rest initargs)
(let ((points
(mapcar #'(lambda (c)
(apply #'p
(first c)
(second c)
initargs))
xy-list)))
(apply #'chain
(mapcar #'(lambda (p1 p2)
(apply #'l p1 p2 initargs))
points (rest points))
initargs)))
(defun poly (segment-list &rest initargs)
(apply #'make-polygon segment-list initargs))
(defun poly-from-xy-list (xy-list &rest initargs)
(let ((points
(mapcar #'(lambda (c)
(apply #'p
(first c)
(second c)
initargs))
xy-list)))
(apply #'poly
(mapcar #'(lambda (p1 p2)
(apply #'l p1 p2 initargs))
points (rest points))
initargs)))
(defun agg (has-parts &rest initargs)
(apply #'make-aggregate has-parts initargs))
;;;
;;;
;;;
(defun segment-list-ok-p (segments polygon-p must-be-simple-p)
"Bedingung: mind. 2 Segmente, keine (wert)gleichen Strecken, keine Selbstueberschneidungen"
(let ((first (first segments))
(last (first (last segments)))
(n (length segments)))
(and (>= n 2)
(=> polygon-p
(>= n 3))
(every #'(lambda (i)
(= (count i segments) 1))
segments)
(if (not polygon-p)
(and (every #'(lambda (i j)
(joins-p i j))
segments (rest segments))
(=> (> n 2)
(not (joins-p (first segments)
(first (last segments))))))
(and (every #'(lambda (i j)
(joins-p i j))
(cons last segments) segments)
(every #'(lambda (i)
(= 2 (count-if #'(lambda (j)
(and (not (eq i j))
(joins-p i j)))
segments)))
segments)))
(=> must-be-simple-p
(every #'(lambda (i)
(let ((count ; Schnitte zaehlen
(count-if
#'(lambda (j)
(and (not (eq i j))
(intersects-p i j)))
segments)))
(if (or (eq first i) (eq last i)) ; erstes od. letztes Segment ?
(if (not polygon-p)
(= count 1)
(= count 2))
(= count 2))))
segments)))))
;;;
;;;
;;;
(defun order-chain-segments (segments &key (adjust-segments-p t))
(unless (cdr segments)
(error "More than one segment needed!"))
(let* ((points
(mapcan #'(lambda (s) (list (p1 s) (p2 s))) segments))
(end-points
(remove-if-not #'(lambda (p)
(= 1 (count-if #'(lambda (segment)
(or (point-=-p p (p1 segment))
(point-=-p p (p2 segment))))
segments)))
points))
(current (first end-points))
(new-segments nil))
(unless (cdr end-points)
(error "Bad segments list!"))
(loop while segments do
(let ((seg (remove-if-not #'(lambda (x)
(or (point-=-p current (p1 x))
(point-=-p current (p2 x))))
segments)))
(when (or (not seg)
(cddr seg))
(error "Bad segments list!"))
(let ((seg (first seg)))
(push seg new-segments)
(setf segments (remove seg segments))
(cond ((point-=-p current (p1 seg))
(setf current (p2 seg)))
((point-=-p current (p2 seg))
(psetf
current (p1 seg))
(when adjust-segments-p
(psetf
(p1 seg) (p2 seg)
(p2 seg) (p1 seg))
(push seg (p1-of (p1 seg)))
(push seg (p2-of (p2 seg)))
(setf (point-list seg)
(list (p1 seg)
(p2 seg)))
(setf (p1-of (p2 seg))
(delete seg (p1-of (p2 seg))))
(setf (p2-of (p1 seg))
(delete seg (p2-of (p1 seg))))))))))
(nreverse new-segments)))
(defun order-poly-segments (segments &key p1 (adjust-segments-p t))
(unless (cddr segments)
(error "More than one segment needed!"))
(let* ((points
(mapcan #'(lambda (s) (list (p1 s) (p2 s))) segments))
(current (or p1 (first points)))
(new-segments nil))
(loop while segments do
(let ((seg (remove-if-not #'(lambda (x)
(or (point-=-p current (p1 x))
(point-=-p current (p2 x))))
segments)))
(when (or (not seg)
(cddr seg))
(error "Bad segments list!"))
(let ((seg (first seg)))
(push seg new-segments)
(setf segments (remove seg segments))
(cond ((point-=-p current (p1 seg))
(setf current (p2 seg)))
((point-=-p current (p2 seg))
(psetf
current (p1 seg))
(when adjust-segments-p
(psetf
(p1 seg) (p2 seg)
(p2 seg) (p1 seg))
(push seg (p1-of (p1 seg)))
(push seg (p2-of (p2 seg)))
(setf (point-list seg)
(list (p1 seg)
(p2 seg)))
(setf (p1-of (p2 seg))
(delete seg (p1-of (p2 seg))))
(setf (p2-of (p1 seg))
(delete seg (p2-of (p1 seg))))))))))
(nreverse new-segments)))
;;;
;;;
;;;
(defmethod initialize-instance :after ((chain geom-chain)
&rest initargs
&key (error-p t) (hierarchicly-p t) (check-p t) (must-be-simple-p t))
(declare (ignore initargs))
(with-slots (segments point-list) chain
(setf segments
(order-chain-segments segments))
(setf point-list
(apply #'append (mapcar #'point-list segments)))
(when (and check-p
(not (segment-list-ok-p segments
nil
must-be-simple-p)))
(setf (error-flag chain) t)
(when error-p
(error "Bad ~A!" (type-of chain))))
(when hierarchicly-p
(let ((p1 (first point-list))
(p2 (first (last point-list))))
(setf (p1 chain) p1
(p2 chain) p2)
(push chain (part-of p1))
(push chain (part-of p2))
(push chain (p1-of p1))
(push chain (p2-of p2)))
(dolist (segment segments)
(push chain (part-of segment))))))
(defmethod initialize-instance :after ((poly geom-polygon)
&rest initargs
&key (hierarchicly-p t) (error-p t) (check-p t) (must-be-simple-p t))
(declare (ignore initargs))
(with-slots (segments point-list) poly
(setf segments
(order-poly-segments segments))
(setf point-list
(apply #'append (mapcar #'point-list segments)))
(when (and check-p
(not (segment-list-ok-p segments
t
must-be-simple-p)))
(setf (error-flag poly) t)
(when error-p
(error "Bad ~A!" (type-of poly))))
(when hierarchicly-p
(dolist (segment segments)
(push poly (part-of segment))))
(orientate-counterclockwise poly)))
;;;
;;;
;;;
(defmethod delete-object progn ((obj geom-chain-or-polygon) &key)
(dolist (segment (segments obj))
(setf (part-of segment)
(delete obj (part-of segment))))
(when (typep obj 'geom-chain)
(let ((p1 (p1 obj))
(p2 (p2 obj)))
(setf (p1-of p1)
(delete obj (p1-of p1)))
(setf (p2-of p2)
(delete obj (p2-of p2))))))
;;;
;;;
;;;
(defmethod initialize-instance :after ((line geom-line)
&rest initargs
&key (hierarchicly-p t) (check-p t))
(declare (ignore initargs))
(with-slots (p1 p2 point-list) line
(when (and check-p (point-=-p p1 p2))
(error "Bad ~A!" (type-of line)))
(setf point-list (list p1 p2))
(when hierarchicly-p
(push line (part-of p1))
(push line (part-of p2))
(push line (p1-of p1))
(push line (p2-of p2)))))
(defmethod delete-object progn ((obj geom-line) &key)
(let ((p1 (p1 obj))
(p2 (p2 obj)))
(setf (p1-of p1)
(delete obj (p1-of p1)))
(setf (p2-of p2)
(delete obj (p2-of p2)))
(setf (part-of p1)
(delete obj (part-of p1)))
(setf (part-of p2)
(delete obj (part-of p2)))))
;;;
;;;
;;;
(defmethod initialize-instance :after ((agg geom-aggregate)
&rest initargs
&key (hierarchicly-p t) (check-p t))
(declare (ignore initargs))
(with-slots (has-parts) agg
(when (and check-p (not has-parts))
(error "Bad ~A!" (type-of agg)))
(when hierarchicly-p
(dolist (part has-parts)
(push agg (part-of part))))))
(defmethod delete-object progn ((obj geom-aggregate) &key)
(dolist (part (has-parts obj))
(setf (part-of part)
(delete obj (part-of part)))))
;;;
;;;
;;;
(defmethod initialize-instance :after ((bounding-box bounding-box)
&rest initargs
&key xmin ymin xmax ymax)
(declare (ignore initargs))
(setf (pmin bounding-box)
(make-point (min xmin xmax)
(min ymin ymax)
:affected-by-matrix-p nil))
(setf (pmax bounding-box)
(make-point (max xmin xmax)
(max ymin ymax)
:affected-by-matrix-p nil))
(setf (radius bounding-box)
(sqrt
(+ (expt (/ (- xmax xmin) 2) 2)
(expt (/ (- ymax ymin) 2) 2))))
(setf (pcenter bounding-box)
(make-point (/ (+ xmin xmax) 2)
(/ (+ ymin ymax) 2)
:affected-by-matrix-p nil)))
;;;
;;;
;;;
(defmethod (setf centroid) :after (centroid (master geom-thing))
(push master
(centroid-of centroid)))
(defmethod (setf pcenter) :after (center (master bounding-box-mixin))
(push master
(pcenter-of center)))
(defun centroid-of-pointlist (pointlist)
(let ((n (length pointlist)))
(values (/ (reduce #'+ (mapcar #'x pointlist)) n)
(/ (reduce #'+ (mapcar #'y pointlist)) n))))
(defmethod calculate-centroid ((obj geom-line))
(when (centroid-p obj)
(multiple-value-bind (x y)
(centroid-of-pointlist
(list (p1 obj) (p2 obj)))
(setf (centroid obj)
(make-point x y
:class (class-of-internal-points obj)
:affected-by-matrix-p
(affected-by-matrix-p obj))))))
(defmethod calculate-centroid ((obj geom-chain-or-polygon))
(when (centroid-p obj)
(multiple-value-bind (x y)
(centroid-of-pointlist
(point-list obj))
(setf (centroid obj)
(make-point x y
:class (class-of-internal-points obj)
:affected-by-matrix-p
(affected-by-matrix-p obj))))))
(defmethod calculate-centroid ((obj geom-aggregate))
(when (centroid-p obj)
(multiple-value-bind (x y)
(centroid-of-pointlist
(mapcar #'centroid (has-parts obj)))
(setf (centroid obj)
(make-point x y
:make (class-of-internal-points obj)
:affected-by-matrix-p
(affected-by-matrix-p obj))))))
;;;
;;;
;;;
(defmethod calculate-bounding-box :after ((obj bounding-box-mixin)
&key reuse-internal-points-p)
(when (bounding-box-p obj)
(with-slots (radius pmin pmax pcenter) obj
(let ((xc (/ (+ (x pmin) (x pmax)) 2))
(yc (/ (+ (y pmin) (y pmax)) 2)))
(if (and reuse-internal-points-p pcenter)
(with-slots (x y) pcenter
(setf xc x
yc y))
(setf (pcenter obj) ; weg. Writer-After-Methode !
(make-point xc yc
:class (class-of-internal-points obj)
:affected-by-matrix-p nil)))
(setf radius
(sqrt
(+ (expt (/ (- (x pmax) (x pmin)) 2) 2)
(expt (/ (- (y pmax) (y pmin)) 2) 2))))))))
(defmethod calculate-bounding-box ((obj geom-line)
&key reuse-internal-points-p)
(when (bounding-box-p obj)
(with-slots (pmin pmax p1 p2) obj
(let ((xmax (max (x p1) (x p2)))
(ymax (max (y p1) (y p2)))
(xmin (min (x p1) (x p2)))
(ymin (min (y p1) (y p2))))
(if (and reuse-internal-points-p pmin pmax)
(setf (x pmax) xmax
(y pmax) ymax
(x pmin) xmin
(y pmin) ymin)
(setf pmax (make-point
xmax ymax
:class (class-of-internal-points obj)
:affected-by-matrix-p nil)
pmin (make-point
xmin ymin
:class (class-of-internal-points obj)
:affected-by-matrix-p nil)))))))
(defmethod calculate-bounding-box-for-complex-object ((obj bounding-box-mixin) parts
&key reuse-internal-points-p)
(when (bounding-box-p obj)
(with-slots (pmin pmax) obj
(let ((xmin nil)
(ymin nil)
(xmax nil)
(ymax nil))
(dolist (part parts)
(dolist (point
(if (typep part 'bounding-box-mixin)
(list (pmin part)
(pmax part))
(list part)))
(let ((x (x point))
(y (y point)))
(when (or (not xmin) (< x xmin)) (setf xmin x))
(when (or (not xmax) (> x xmax)) (setf xmax x))
(when (or (not ymin) (< y ymin)) (setf ymin y))
(when (or (not ymax) (> y ymax)) (setf ymax y)))))
(if (and reuse-internal-points-p pmin pmax)
(setf (x pmin) xmin
(y pmin) ymin
(x pmax) xmax
(y pmax) ymax)
(setf pmin (make-point xmin ymin
:affected-by-matrix-p nil)
pmax (make-point xmax ymax
:affected-by-matrix-p nil)))))))
(defmethod calculate-bounding-box ((obj geom-chain-or-polygon)
&key reuse-internal-points-p)
(calculate-bounding-box-for-complex-object obj (segments obj)
:reuse-internal-points-p reuse-internal-points-p))
(defmethod calculate-bounding-box ((obj geom-aggregate)
&key reuse-internal-points-p)
(calculate-bounding-box-for-complex-object obj (has-parts obj)
:reuse-internal-points-p reuse-internal-points-p))
;;;
;;;
;;;
(defmethod recalculate-bounding-box ((obj bounding-box-mixin))
(calculate-bounding-box obj :reuse-internal-points-p t)
(setf (last-trafo-id obj) (trafo-id *matrix*)))
;;;
;;;
;;;
(defmethod invalidate-bounding-box ((obj bounding-box-mixin))
(setf (last-trafo-id obj) -2))
(defmethod invalidate-bounding-box ((obj geom-chain-or-polygon))
(dolist (segment (segments obj))
(invalidate-bounding-box segment))
(call-next-method))
(defmethod invalidate-bounding-box ((obj geom-aggregate))
(dolist (part (has-parts obj))
(invalidate-bounding-box part))
(call-next-method))
;;;
;;;
;;;
;;;
;;;
#|
(defmethod calculate-intersection-point ((line1 geom-line) (line2 geom-line))
(when (member '0d (calculate-relation line1 line2))
(let* ((x1l1 (x (p1 line1)))
(y1l1 (y (p1 line1)))
(x2l1 (x (p2 line1)))
(y2l1 (y (p2 line1)))
(x1l2 (x (p1 line2)))
(y1l2 (y (p1 line2)))
(x2l2 (x (p2 line2)))
(y2l2 (y (p2 line2)))
(m1 (if (= x2l1 x1l1) 'infinit (/ (- y2l1 y1l1) (- x2l1 x1l1))))
(m2 (if (= x2l2 x1l2) 'infinit (/ (- y2l2 y1l2) (- x2l2 x1l2)))))
(cond
((or (and (eq m1 'infinit)
(eq m2 'infinit))
(and (not (or (eq m1 'infinit)
(eq m2 'infinit))) ; (= ..) schuetzen
(= m1 m2)))
(let ((p
(if (or (point-=-p (p1 line1)
(p1 line2))
(point-=-p (p1 line1)
(p2 line2)))
(p1 line1)
(p2 line1))))
(values (x p) (y p))))
((eq m1 'infinit)
(let* ((xs x2l1)
(ys (+ y1l2 (* m2 (- xs x1l2)))))
(values xs ys)))
((eq m2 'infinit)
(let* ((xs x2l2)
(ys (+ y1l1 (* m1 (- xs x1l1)))))
(values xs ys)))
(t
(let* ((xs (/ (- (* m1 x1l1) (* m2 x1l2) (- y1l1 y1l2))
(- m1 m2)))
(ys (+ y1l1 (* m1 (- xs x1l1)))))
(values xs ys)))))))
(defmethod calculate-intersection-line ((line1 geom-line) (line2 geom-line))
(let* ((x1l1 (x (p1 line1)))
(y1l1 (y (p1 line1)))
(x2l1 (x (p2 line1)))
(y2l1 (y (p2 line1)))
(x1l2 (x (p1 line2)))
(y1l2 (y (p1 line2)))
(x2l2 (x (p2 line2)))
(y2l2 (y (p2 line2))))
(multiple-value-bind (rel l1p1-l2 l1p2-l2 l2p1-l1 l2p2-l1)
(calculate-relation line1 line2 :detailed t)
(case rel
(equal (values x1l1 y1l1 x2l1 y2l1))
((inside covered-by) (values x1l1 y1l1 x2l1 y2l1))
((contains covers) (values x1l2 y1l2 x2l2 y2l2))
(overlaps (cond ((and l1p1-l2 l2p1-l1)
(values x1l1 y1l1 x1l2 y1l2))
((and l1p1-l2 l2p2-l1)
(values x1l1 y1l1 x2l2 y2l2))
((and l1p2-l2 l2p1-l1)
(values x2l1 y2l1 x1l2 y1l2))
((and l1p2-l2 l2p2-l1)
(values x2l1 y2l1 x2l2 y2l2))))))))
|#
;;;
;;;
;;;
(defun distance-between* (x1 y1 x2 y2 &key (sqrt t) (sx 1) (sy 1))
(let* ((dx (/ (- x2 x1) sx))
(dy (/ (- y2 y1) sy)))
(if sqrt
(sqrt (+ (* dx dx) (* dy dy)))
(+ (* dx dx) (* dy dy)))))
(defmethod distance-between-xy ((x number) (y number)
(point geom-point)
&key (sqrt t) (sx 1) (sy 1))
(distance-between* x y (x point) (y point)
:sqrt sqrt :sx sx :sy sy))
(defmethod distance-between ((point1 geom-point)
(point2 geom-point)
&key (sqrt t) (sx 1) (sy 1))
(distance-between* (x point1) (y point1)
(x point2) (y point2)
:sqrt sqrt :sx sx :sy sy))
(defun distance-between-point-and-line (px py
lx1 ly1
lx2 ly2
&key (sqrt t) (sx 1) (sy 1))
(flet ((betw-0-and-1 (number)
(and (not (minusp number))
(<= number 1.0))))
(let* ((ax (/ (- lx2 lx1) sx))
(ay (/ (- ly2 ly1) sy))
(dx (/ (- lx1 px) sx))
(dy (/ (- ly1 py) sy))
(a2 (+ (* ax ax) (* ay ay)))
(scalar
(if (zerop-eps a2)
+big-int+
(/ (+ (* ax (- dx))
(* ay (- dy)))
a2)))
(x (+ dx
(* scalar ax)))
(y (+ dy
(* scalar ay)))
(res
(if (betw-0-and-1 scalar)
(+ (* x x) (* y y))
(min (distance-between* px py lx1 ly1 :sqrt nil :sx sx :sy sy)
(distance-between* px py lx2 ly2 :sqrt nil :sx sx :sy sy)))))
(if sqrt
(sqrt res)
res))))
(defmethod distance-between ((point geom-point)
(line geom-line)
&key (sqrt t) (sx 1) (sy 1))
(distance-between-point-and-line (x point)
(y point)
(x (p1 line))
(y (p1 line))
(x (p2 line))
(y (p2 line))
:sqrt sqrt :sx sx :sy sy))
(defmethod distance-between-xy ((x number) (y number)
(line geom-line)
&key (sqrt t) (sx 1) (sy 1))
(distance-between-point-and-line x
y
(x (p1 line))
(y (p1 line))
(x (p2 line))
(y (p2 line))
:sqrt sqrt :sx sx :sy sy))
(defmethod distance-between ((line geom-line)
(point geom-point)
&key (sqrt t) (sx 1) (sy 1))
(distance-between point line :sqrt sqrt :sx sx :sy sy))
(defmethod distance-between ((line1 geom-line)
(line2 geom-line)
&key (sqrt t) (sx 1) (sy 1))
(let* ((d1
(distance-between (p1 line1) line2 :sqrt sqrt :sx sx :sy sy))
(d2
(distance-between (p2 line1) line2 :sqrt sqrt :sx sx :sy sy))
(d3
(distance-between (p1 line2) line1 :sqrt sqrt :sx sx :sy sy))
(d4
(distance-between (p2 line2) line1 :sqrt sqrt :sx sx :sy sy)))
(if (intersects-p line1 line2)
0
(min d1 d2 d3 d4))))
(defmethod distance-between ((line geom-line)
(poly geom-chain-or-polygon)
&key (sqrt t) (sx 1) (sy 1))
(loop as i in (segments poly) minimize
(distance-between i line :sqrt sqrt :sx sx :sy sy)))
(defmethod distance-between ((poly geom-chain-or-polygon)
(line geom-line)
&key (sqrt t) (sx 1) (sy 1))
(distance-between line poly :sqrt sqrt :sx sx :sy sy))
(defmethod distance-between ((poly1 geom-chain-or-polygon)
(poly2 geom-chain-or-polygon)
&key (sqrt t) (sx 1) (sy 1))
(loop as i in (segments poly1) minimize
(distance-between i poly2 :sqrt sqrt :sx sx :sy sy)))
(defmethod distance-between ((point geom-point)
(poly geom-chain-or-polygon)
&key (sqrt t) (sx 1) (sy 1))
(loop as i in (segments poly) minimize
(distance-between point i :sqrt sqrt :sx sx :sy sy)))
(defmethod distance-between-xy ((x number) (y number)
(poly geom-chain-or-polygon)
&key (sqrt t) (sx 1) (sy 1))
(loop as i in (segments poly) minimize
(distance-between-xy x y i :sqrt sqrt :sx sx :sy sy)))
(defmethod distance-between ((poly geom-chain-or-polygon)
(point geom-point)
&key (sqrt t) (sx 1) (sy 1))
(distance-between point poly :sqrt sqrt :sx sx :sy sy))
;;;
;;;
;;;
(defun angle-between* (x1 y1 x2 y2)
(let* ((dx (- x2 x1))
(dy (- y2 y1))
(phi
(phase (complex dx dy))))
(if (minusp phi)
(+ +2pi+ phi)
phi)))
(defun distance-and-orientation* (x1 y1 x2 y2)
(let ((dist (distance-between* x1 y1 x2 y2))
(angle (angle-between* x1 y1 x2 y2)))
(values dist angle)))
(defun normalize (angle)
(mod angle +2pi+))
(defun angle-difference (a b)
(min
(normalize
(- a b))
(normalize
(- b a))))
;;;
;;;
;;;
(defmethod length-of-line ((line geom-line))
(distance-between (p1 line) (p2 line)))
(defmethod global-orientation ((line geom-line))
(angle-between* (x (p1 line)) (y (p1 line)) (x (p2 line)) (y (p2 line))))
#|
(defmethod angle-between ((line1 geom-line) (line2 geom-line))
"Draw line1 around nearest point w.r.t. line2 counterclockwise and measure angle!"
(let* ((d11 (distance-between (p1 line1) (p1 line2)))
(d21 (distance-between (p2 line1) (p1 line2)))
(d12 (distance-between (p1 line1) (p2 line2)))
(d22 (distance-between (p2 line1) (p2 line2)))
(dmin (min d11 d21 d12 d22)))
(multiple-value-bind (as ae bs be)
(cond ((= dmin d11) (values (p1 line1) (p2 line1) (p1 line2) (p2 line2)))
((= dmin d12) (values (p1 line1) (p2 line1) (p2 line2) (p1 line2)))
((= dmin d21) (values (p2 line1) (p1 line1) (p1 line2) (p2 line2)))
((= dmin d22) (values (p2 line1) (p1 line1) (p2 line2) (p1 line2))))
(normalize (- (angle-between* (x as) (y as) (x ae) (y ae))
(angle-between* (x bs) (y bs) (x be) (y be)))))))
|#
;;;
;;;
;;;
(defmethod calculate-area ((obj geom-polygon))
(with-slots (point-list) obj
(let ((f 0)
(first (first point-list))
(last (first (last point-list))))
(mapc #'(lambda (pj pj+1 pj-1)
(let ((xj (x pj))
(yj+1 (y pj+1))
(yj-1 (y pj-1)))
(incf f (* xj (- yj+1 yj-1)))))
point-list
(append (rest point-list) (list first))
(cons last point-list))
(/ f 2))))
;;;
;;;
;;;
(defun det-0-vecs (x1 y1 x2 y2)
(- (* x1 y2)
(* x2 y1)))
(defun det (x1s y1s x1e y1e
x2s y2s x2e y2e)
(let ((x1 (- x1e x1s))
(y1 (- y1e y1s))
(x2 (- x2e x2s))
(y2 (- y2e y2s)))
(- (* x1 y2)
(* x2 y1))))
;;;
;;;
;;;
(defmethod insert-new-border-points ((poly geom-polygon) points)
(let ((points
(mapcar #'(lambda (x)
(if (typep x 'geom-point)
x
(if (and (typep x 'cons)
(cdr x)
(not (cddr x)))
(p (first x)
(second x))
(error "Bad point ~A in list!" x))))
points)))
(unless (every #'(lambda (p) (lies-on-p p poly))
points)
(error "Not on polygon border!"))
(let ((points (remove-if #'(lambda (p) ;;; vorhandene entfernen
(some #'(lambda (q)
(point-=-p p q))
(point-list poly)))
points))
(new-points nil))
(dolist (seg (segments poly))
(setf new-points
(append new-points
(sort (cons (p1 seg)
(remove-if-not #'(lambda (p)
(lies-on-p p seg))
points))
#'<
:key #'(lambda (x)
(distance-between (p1 seg) x))))))
(let ((new-points
(mapcar #'(lambda (p)
(list (x p)
(y p)))
(remove-duplicates new-points
:test #'point-=-p))))
(poly-from-xy-list (append new-points
(list (first new-points)))
:affected-by-matrix-p nil)))))
(defmethod insert-new-border-points ((chain geom-chain) points)
(let ((points
(mapcar #'(lambda (x)
(if (typep x 'geom-point)
x
(if (and (typep x 'cons)
(cdr x)
(not (cddr x)))
(p (first x)
(second x))
(error "Bad point ~A in list!" x))))
points)))
(unless (every #'(lambda (p) (lies-on-p p chain))
points)
(error "Not on chain border!"))
(let ((points (remove-if #'(lambda (p) ;;; vorhandene entfernen
(some #'(lambda (q)
(point-=-p p q))
(point-list chain)))
points))
(new-points nil))
(dolist (seg (segments chain))
(setf new-points
(append new-points
(sort (cons (p1 seg)
(remove-if-not #'(lambda (p)
(lies-on-p p seg))
points))
#'<
:key #'(lambda (x)
(distance-between (p1 seg) x))))))
(let ((new-points
(mapcar #'(lambda (p)
(list (x p)
(y p)))
(remove-duplicates new-points
:test #'point-=-p))))
(chain-from-xy-list (append new-points
(list (list (x (p2 (first (last (segments chain)))))
(y (p2 (first (last (segments chain))))))))
:affected-by-matrix-p nil)))))
;;;
;;;
;;;
(defmethod orientation ((poly geom-polygon))
(let* ((points
(remove-duplicates (point-list poly)
:test #'point-=-p))
(rightmost-lowest-point
(let ((current (first points)))
(dolist (point points)
(when (or (< (y point)
(y current))
(and (= (y point)
(y current))
(> (x point)
(x current))))
(setf current point)))
current))
(pos (position rightmost-lowest-point points))
(points (if (zerop pos)
(list (first (last points))
(first points)
(second points))
(if (= pos (1- (length points)))
(append (subseq points
(1- pos)
(+ (1- pos) 2))
(list (first points)))
(subseq points
(1- pos)
(+ (1- pos) 3))))))
(apply #'ccw points)))
(defun decode-ccw (num)
(ecase num
(1 :counterclockwise)
(-1 :clockwise)))
(defmethod change-orientation ((poly geom-polygon))
(dolist (seg (segments poly))
(psetf
(p1 seg) (p2 seg)
(p2 seg) (p1 seg))
(push seg (p1-of (p1 seg)))
(push seg (p2-of (p2 seg)))
(setf (point-list seg)
(list (p1 seg)
(p2 seg)))
(setf (p1-of (p2 seg))
(delete seg (p1-of (p2 seg))))
(setf (p2-of (p1 seg))
(delete seg (p2-of (p1 seg)))))
(setf (segments poly)
(nreverse (segments poly)))
(setf (point-list poly)
(apply #'append (mapcar #'point-list (segments poly))))
poly)
(defmethod orientate-counterclockwise ((poly geom-polygon))
(if (= (orientation poly) 1)
poly
(change-orientation poly)))
(defmethod orientate-clockwise ((poly geom-polygon))
(if (= (orientation poly) -1)
poly
(change-orientation poly)))
;;;
;;;
;;;
(defmethod get-xy-list ((point geom-point))
(list (x point) (y point)))
(defmethod get-xy-list ((line geom-line))
(mapcar #'get-xy-list (point-list line)))
(defmethod get-xy-list ((obj geom-chain-or-polygon))
(mapcar #'get-xy-list (segments obj)))
;;;
;;;
;;;
(defmethod (setf affected-by-matrix-p) (val (obj geom-point))
(setf (slot-value obj 'affected-by-matrix-p) val))
(defmethod (setf affected-by-matrix-p) (val (obj geom-line))
(setf (slot-value obj 'affected-by-matrix-p) val
(affected-by-matrix-p (p1 obj)) val
(affected-by-matrix-p (p2 obj)) val))
(defmethod (setf affected-by-matrix-p) (val (obj geom-chain-or-polygon))
(setf (slot-value obj 'affected-by-matrix-p) val)
(mapc #'(lambda (s)
(setf
(affected-by-matrix-p s) val))
(segments obj)))
| 47,403 | Common Lisp | .lisp | 1,329 | 26.920993 | 110 | 0.542852 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 8f4d185674636b91d34be7de3230b65f84ab4b6031b9e5b79074aaf6e0f3c7d0 | 12,478 | [
-1
] |
12,480 | persistence3.lisp | lambdamikel_DLMAPS/src/persistence/persistence3.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: PERSISTENCE-MANAGER; Base: 10 -*-
(in-package persistence-manager)
;;;
;;; Achtung! Diese Version unterstützt KEIN Struktur-Sharing für Listen!
;;; Daher nicht verwendet, nur für Racer!
;;;
(defun print-persistence-manager-info (&optional (stream t))
(format stream ";;; The store/restore facility is based on software developed~%~
;;; by Michael Wessel.~2%"))
(cl:defstruct (big-vector (:constructor make-big-vector-internal))
n-elements
n-subarrays
(arrays nil))
(defconstant +max-n-of-array-elements+ (- array-total-size-limit 1))
(defun make-big-vector (dimension &key (initial-element nil))
(multiple-value-bind (n-subarrays-minus-1 size-of-rest-array)
(floor dimension +max-n-of-array-elements+)
(let ((big-vector (make-big-vector-internal)))
(setf (big-vector-n-subarrays big-vector) (+ n-subarrays-minus-1 1))
(setf (big-vector-n-elements big-vector) dimension)
(setf (big-vector-arrays big-vector)
(coerce (append (loop repeat n-subarrays-minus-1
collect (make-array +max-n-of-array-elements+
:initial-element initial-element))
(list (make-array size-of-rest-array)))
'vector))
big-vector)))
;; (declaim (inline bvref))
(defun bvref (big-array index)
(multiple-value-bind (subarray-index index-of-rest-array)
(floor index +max-n-of-array-elements+)
(svref (svref (big-vector-arrays big-array) subarray-index)
index-of-rest-array)))
;; (declaim (inline (setf bvref)))
(defun (setf bvref) (new-value big-array index)
(multiple-value-bind (subarray-index index-of-rest-array)
(floor index +max-n-of-array-elements+)
(setf (svref (svref (big-vector-arrays big-array) subarray-index)
index-of-rest-array)
new-value)))
;;;
;;;
;;;
(defconstant +persistence-version+ 3)
(defconstant +n-bytes-for-written-objects+ 16)
(defconstant +maximum-written-objects+
(- (expt 10 +n-bytes-for-written-objects+) 1))
;;(defconstant +vector-size+ 1000000)
(defconstant +hash-table-size+ 10000)
(defconstant +rehash-size+ 40000)
(defvar *read-objects* nil)
;; (make-array +vector-size+ :initial-element nil)
(defvar *written-objects*
(make-hash-table :test #'eql
:size +hash-table-size+
:rehash-size +rehash-size+))
;;;
;;;
;;;
(defvar *io-id-counter* 0)
(defvar *aux-counter* 0)
(defvar *ref-counter* 0)
;;;
;;;
;;;
#|
(declaim (inline get-io-id-for create-io-id store retrieve
write-coded-string1
write-coded-string
read-coded-string
write-coded-symbol
read-coded-symbol
write-coded-integer
read-coded-integer
write-coded-number
read-coded-numer
write-coded-marker
read-coded-marker
write-coded-list
read-coded-list
read-byte*
unread-byte*))
|#
(defun write-coded-integer (stream num)
(unless (integerp num)
(error "You have given ~A to write-coded-integer!" num))
(let ((orig-num num)
(num (abs num)))
(loop
(multiple-value-bind (div mod)
(floor num 254)
(write-byte mod stream)
(setf num div)
(when (= 0 div)
(write-byte (if (minusp orig-num)
254 255)
stream)
(return-from write-coded-integer))))))
(defun read-coded-integer (stream)
(let ((num 0)
(index 1))
(loop
(let ((byte (read-byte* stream)))
(cond ((eq byte 'eof)
(return-from read-coded-integer 'eof))
((= byte 255)
(return-from read-coded-integer num))
((= byte 254)
(return-from read-coded-integer (- num)))
(t (incf num (* index byte))
(setf index (* index 254))))))))
(defun write-coded-string (stream string)
(write-coded-integer stream (length string))
(loop as char across string do
(write-byte (char-code char) stream)))
(defun write-coded-string-1 (stream string)
(loop as char across string do
(write-byte (char-code char) stream)))
(defun read-coded-string (stream)
(let* ((n (read-coded-integer stream))
(string (make-string n :initial-element #\space)))
(loop as i from 1 to n do
(setf (aref string (1- i))
(code-char (read-byte stream))))
string))
(defun write-coded-symbol (stream symbol)
(let* ((package (symbol-package symbol))
(name (symbol-name symbol))
(length (if (null package)
(+ 2 (length name))
(+ (length (package-name package)) 2 (length name)))))
(write-coded-integer stream length)
(if (null package)
(write-coded-string-1 stream "#:")
(progn
(write-coded-string-1 stream (package-name package))
(write-coded-string-1 stream "::")))
(write-coded-string-1 stream (symbol-name symbol))))
(defun read-coded-symbol (stream)
(read-from-string (read-coded-string stream)))
(defun write-coded-number (stream num)
(write-coded-string stream (write-to-string num)))
(defun read-coded-number (stream)
(read-from-string (read-coded-string stream)))
(defun write-coded-marker (stream marker)
(write-byte marker stream))
(defun read-coded-marker (stream)
(read-byte* stream))
(defun write-coded-list (stream list)
(write-coded-string stream (format nil "~S" list)))
(defun read-coded-list (stream)
(read-from-string (read-coded-string stream)))
;;;
;;;
;;;
(defvar *last-byte-read* nil)
(defvar *unread-occured-p* nil)
(defun read-byte* (stream)
(if (and *unread-occured-p* *last-byte-read*)
(progn
(setf *unread-occured-p* nil)
*last-byte-read*)
(let ((byte (read-byte stream nil 'eof)))
(if (eq byte 'eof)
(setf *last-byte-read* nil)
(setf *last-byte-read* byte))
byte)))
(defun unread-byte* ()
(setf *unread-occured-p* t))
;;;
;;;
;;;
(defun get-io-id-for (object)
(or (gethash object *written-objects*)
(error "Can't find object ~A!" object)))
(defun create-io-id ()
(incf *io-id-counter*))
(defun store (io-id obj)
(setf *io-id-counter* (max io-id *io-id-counter*))
(setf (bvref *read-objects* io-id) obj)
obj)
(defun retrieve (io-id)
(or (bvref *read-objects* io-id)
(error "Object ~A not found! Dangling pointer!" io-id)))
(defun reset ()
(setf *io-id-counter* 0
*aux-counter* 0
*ref-counter* 0
*unread-occured-p* nil)
(clrhash *written-objects*))
(defun read-reset (n-of-objects-to-read)
(setf *io-id-counter* 0
*aux-counter* 0
*ref-counter* 0
*unread-occured-p* nil)
(setf *read-objects* (make-big-vector (+ n-of-objects-to-read 3)
:initial-element nil)))
;;;
;;;
;;;
(cl:defclass persistent-object ()
())
(defmethod write-object-constructor ((obj persistent-object) stream)
(declare (ignore stream))
nil)
(defmethod write-object-initializer ((obj persistent-object) stream)
(declare (ignore stream))
nil)
(defmethod fill-persistent-object ((obj persistent-object) stream)
(declare (ignore stream))
nil)
;;;
;;; verhindere, da"s initialize-instance fuer Subklassen aufgerufen wird!
;;;
(defmethod initialize-instance :around ((obj persistent-object)
&rest initargs
&key (dont-initialize nil))
(if (not dont-initialize)
(progn
(call-next-method)) ; normale Initialisierung
(apply #'shared-initialize obj t initargs)))
(defmethod initialize-loaded-persistent-object ((obj persistent-object))
nil)
;;;
;;;
;;;
(cl:defstruct persistent-structure)
(defmethod write-object-constructor ((obj persistent-structure) stream)
(declare (ignore stream))
nil)
(defmethod write-object-initializer ((obj persistent-structure) stream)
(declare (ignore stream))
nil)
(defmethod fill-persistent-object ((obj persistent-structure) stream)
(declare (ignore stream))
nil)
(defmethod initialize-loaded-persistent-object ((obj persistent-structure))
nil)
;;;
;;;
;;;
(defconstant +string-marker+ 10)
(defconstant +array-marker+ 20)
(defconstant +hashtable-marker+ 30)
(defconstant +list-marker+ 40)
(defconstant +dotted-list-marker+ 45)
(defconstant +nil-marker+ 50)
(defconstant +integer-marker+ 60)
(defconstant +number-marker+ 70)
(defconstant +symbol-marker+ 80)
(defconstant +object-marker+ 90)
(defconstant +structure-marker+ 100)
(defconstant +unbound-marker+ 110)
(defconstant +section-marker+ 120)
(defconstant +user-responsibility-marker+ 130)
(defvar *secret-hashtable-size-key* (gensym "*#?@secret-"))
;;;
;;;
;;;
(defun length1 (list)
(let* ((x list)
(length 0))
(loop
(pop x)
(unless (listp x)
(return))
(unless x
(return))
(incf length))
length))
(defun is-dotted-list-p (list)
(loop
(pop list)
(unless (listp list)
(return-from is-dotted-list-p t))
(unless list
(return-from is-dotted-list-p nil))))
;;;
;;;
;;;
(defmacro with-only-once-constructed-object ((object marker stream) &body body)
`(unless (gethash ,object *written-objects*)
(let ((io-id (create-io-id)))
(setf (gethash ,object *written-objects*) io-id)
(write-coded-marker ,stream ,marker)
(write-coded-integer ,stream io-id)
,@body)))
(defmethod write-constructor :after ((object t) stream)
(declare (ignore stream))
(incf *ref-counter*))
;;;
;;;
;;;
(defmethod user-write-constructor (stream (object t))
(declare (ignorable stream))
(error "Please create a method \"USER-WRITE-CONSTRUCTOR (STREAM (OBJECT ~S))\"
and use subsequent calls to \"(USER-WRITE-COMPONENT-CONSTRUCTOR STREAM COMPONENT)\" to construct the
component objects of the object!" (type-of object)))
(defmethod user-write-component-constructor (stream (object t))
(declare (ignorable stream))
(write-constructor object stream))
;;;
;;;
;;;
(defmethod write-constructor ((object t) stream)
(with-only-once-constructed-object (object +user-responsibility-marker+ stream)
(write-coded-symbol stream (type-of object))
(user-write-constructor stream object))
(values))
(defmethod write-constructor ((object null) stream)
(declare (ignore stream))
(values))
(defmethod write-constructor ((object number) stream)
(declare (ignore stream))
(values))
(defmethod write-constructor ((object list) stream)
(if (is-dotted-list-p object)
(let ((length (length1 object)))
(with-only-once-constructed-object (object +dotted-list-marker+ stream)
(write-coded-integer stream length)
(let ((x object))
(dotimes (i length)
(write-constructor (pop x) stream))
;; letzte CONS-Zelle schreiben
(write-constructor (car x) stream)
(write-constructor (cdr x) stream))))
(let ((length (length object)))
(with-only-once-constructed-object (object +list-marker+ stream)
(write-coded-integer stream length)
(let ((x object))
(dotimes (i length)
(write-constructor (pop x) stream))))))
(values))
(defmethod write-constructor ((object string) stream)
(with-only-once-constructed-object (object +string-marker+ stream)
(write-coded-string stream object))
(values))
(defmethod write-constructor ((object symbol) stream)
(with-only-once-constructed-object (object +symbol-marker+ stream)
(write-coded-symbol stream object))
(values))
(defmethod write-constructor ((object array) stream)
(with-only-once-constructed-object (object +array-marker+ stream)
(write-coded-list stream (array-dimensions object))
(dotimes (i (array-total-size object))
(write-constructor (row-major-aref object i) stream)))
(values))
(defmethod write-constructor ((object hash-table) stream)
(with-only-once-constructed-object (object +hashtable-marker+ stream)
(write-coded-integer stream (hash-table-count object))
(write-coded-integer stream (hash-table-size object))
(write-coded-number stream (hash-table-rehash-size object))
(write-coded-number stream (hash-table-rehash-threshold object))
(write-coded-symbol stream (hash-table-test object))
(maphash #'(lambda (key value)
(write-constructor key stream)
(write-constructor value stream))
object))
(values))
(defmethod write-constructor ((object persistent-object) stream)
(write-constructor (type-of object) stream)
(with-only-once-constructed-object (object +object-marker+ stream)
(write-referencer (type-of object) stream)
(write-object-constructor object stream))
(values))
(defmethod write-constructor ((object persistent-structure) stream)
(write-constructor (type-of object) stream)
(with-only-once-constructed-object (object +structure-marker+ stream)
(write-referencer (type-of object) stream)
(write-object-constructor object stream))
(values))
;;;
;;;
;;;
(defmacro with-complex-object-header ((stream object) &body body)
`(progn
(write-coded-integer ,stream (get-io-id-for ,object))
,@body))
(defun write-referencer (object stream)
(typecase object
(null
(write-coded-marker stream +nil-marker+))
((or cons array hash-table string symbol persistent-object)
(write-coded-marker stream +object-marker+)
(write-coded-integer stream (get-io-id-for object)))
(persistent-structure
(write-coded-marker stream +structure-marker+)
(write-coded-integer stream (get-io-id-for object)))
(integer (write-coded-marker stream +integer-marker+)
(write-coded-integer stream object))
(number
(write-coded-marker stream +number-marker+)
(write-coded-number stream object))
(otherwise
(write-coded-marker stream +user-responsibility-marker+)
(write-coded-integer stream (get-io-id-for object)))))
;;;
;;;
;;;
(defmethod user-write-initializer (stream (object t))
(declare (ignorable stream))
(error "Please create a method \"USER-WRITE-INITIALIZER (STREAM (OBJECT ~S))\"
and use subsequent calls to \"(USER-WRITE-COMPONENT-INITIALIZER STREAM COMPONENT)\" to initialize
the component objects of the object!" (type-of object)))
(defmethod user-write-component-initializer (stream (object t))
(declare (ignorable stream))
(write-referencer object stream))
;;;
;;;
;;;
(defmethod write-initializer ((object t) stream)
(with-complex-object-header (stream object)
(user-write-initializer stream object))
(values))
(defmethod write-initializer ((object string) stream)
(declare (ignorable stream))
(values))
(defmethod write-initializer ((object symbol) stream)
(declare (ignorable stream))
(values))
(defmethod write-initializer ((object list) stream)
(with-complex-object-header (stream object)
(if (is-dotted-list-p object)
(let ((length (length1 object))
(x object))
(dotimes (i length)
(write-referencer (pop x) stream))
;; letzte CONS-Zelle schreiben
(write-referencer (car x) stream)
(write-referencer (cdr x) stream))
(let ((length (length object))
(x object))
(dotimes (i length)
(write-referencer (pop x) stream)))))
(values))
(defmethod write-initializer ((object array) stream)
(with-complex-object-header (stream object)
(dotimes (i (array-total-size object))
(write-referencer (row-major-aref object i)
stream)))
(values))
(defmethod write-initializer ((object hash-table) stream)
(with-complex-object-header (stream object)
(maphash #'(lambda (key value)
(write-referencer key stream)
(write-referencer value stream))
object))
(values))
(defmethod write-initializer ((object persistent-object) stream)
(with-complex-object-header (stream object)
(write-object-initializer object stream))
(values))
(defmethod write-initializer ((object persistent-structure) stream)
(with-complex-object-header (stream object)
(write-object-initializer object stream))
(values))
;;;
;;;
;;;
(defmethod fill-object ((object symbol) stream)
(declare (ignore stream))
object)
(defmethod fill-object ((object string) stream)
(declare (ignore stream))
object)
(defmethod fill-object ((object list) stream)
(let ((x object))
(loop
(setf (car x) (read-value stream))
(unless (cdr x)
(return))
(unless (listp (cdr x))
(setf (cdr x)
(read-value stream))
(return))
(setf x (cdr x)))
object))
(defmethod fill-object ((object array) stream)
(dotimes (i (array-total-size object))
(setf (row-major-aref object i)
(read-value stream)))
object)
(defmethod fill-object ((object hash-table) stream)
(dotimes (i (gethash *secret-hashtable-size-key* object))
(let ((key (read-value stream))
(value (read-value stream)))
(setf (gethash key object) value)))
(remhash *secret-hashtable-size-key* object)
object)
(defmethod fill-object ((object persistent-object) stream)
(fill-persistent-object object stream)
object)
(defmethod fill-object ((object persistent-structure) stream)
(fill-persistent-object object stream)
object)
(defmethod fill-object ((object t) stream)
(user-fill-object stream object))
;;;
;;;
;;;
(defmethod user-fill-object (stream (object t))
(declare (ignorable stream))
(error "Please create a method \"USER-FILL-OBJECT (STREAM (OBJECT ~S))\"
and use subsequent calls to \"(USER-READ-COMPONENT-OBJECT STREAM)\" to read-in
and get the component objects of the object; assign these to the appropriate places
within the ~S and return the object!" (type-of object) (type-of object)))
(defmethod user-read-component-object (stream)
(read-value stream))
;;;
;;;
;;;
(defun read-value (stream)
(let ((marker (read-coded-marker stream)))
(cond ((or (= marker +object-marker+)
(= marker +structure-marker+)
(= marker +array-marker+)
(= marker +hashtable-marker+)
(= marker +user-responsibility-marker+))
(values
(retrieve (read-coded-integer stream))))
((= marker +nil-marker+)
(values
nil))
((= marker +integer-marker+)
(values
(read-coded-integer stream)))
((= marker +number-marker+)
(values
(read-coded-number stream)))
((= marker +unbound-marker+)
(values
nil))
(t (error "Bad marker ~A in read-value!" marker)))))
(defun probe-bound-p (stream)
(let ((marker (read-coded-marker stream)))
(prog1
(not (= marker +unbound-marker+))
(unread-byte*))))
(defmethod user-create-empty-object ((type t))
(error "Please create a method \"USER-CREATE-EMPTY-OBJECT (TYPE (EQL '~S))\"
that creates an EMPTY container object of type ~S!"
type type))
(defun construct-object (stream)
(loop
(let ((marker (read-coded-marker stream)))
(if (or (= marker +section-marker+)
(eq marker 'eof))
(return)
(let ((id (read-coded-integer stream)))
(store id
(cond ((= marker +string-marker+)
(read-coded-string stream))
((= marker +symbol-marker+)
(read-coded-symbol stream))
((= marker +list-marker+)
(loop as i from 1 to (read-coded-integer stream)
collect (incf *aux-counter*)))
((= marker +dotted-list-marker+)
(let ((list
(loop as i from 1 to (read-coded-integer stream)
collect (incf *aux-counter*))))
(if list
(setf (cdr (last list))
(cons (incf *aux-counter*)
;;; damit als DOTTED-LIST erkennbar!
(incf *aux-counter*)))
(cons (incf *aux-counter*)
(incf *aux-counter*)))))
((= marker +array-marker+)
(make-array (read-coded-list stream)))
((= marker +hashtable-marker+)
(let* ((no-of-entries (read-coded-integer stream))
(size (read-coded-integer stream))
(rehash-size (read-coded-number stream))
(rehash-threshold (read-coded-number stream))
(test (read-coded-symbol stream))
(table (make-hash-table
:size size
:rehash-size rehash-size
:rehash-threshold rehash-threshold
:test test)))
(setf (gethash *secret-hashtable-size-key* table)
no-of-entries)
table))
((= marker +object-marker+)
(make-instance (read-value stream)
:allow-other-keys t
:dont-initialize t))
((= marker +structure-marker+)
(funcall (structure-initializer (read-value stream))))
((= marker +user-responsibility-marker+)
(let ((type (read-coded-symbol stream)))
(user-create-empty-object type)))
(t (error "Unknown marker: ~A." marker)))))))))
(defun initialize-object (stream)
(loop
(let ((io-id (read-coded-integer stream)))
(if (eq io-id 'eof)
(return)
(fill-object (retrieve io-id) stream)))))
;;;
;;;
;;;
(defmacro defpersistentclass (&rest rest)
`(progn ,@(let* ((name (first rest))
(superclasses (append (second rest) '(persistent-object)))
(body (third rest))
(slotnames (mapcar #'first body)))
(list
`(cl:defclass ,name ,superclasses
,(loop for slotspec in body collect
(remove :not-persistent slotspec)))
`(defun ,(intern (string-upcase (format nil "is-~A-p" name))) (obj)
(typep obj ',name))
`(defmethod write-object-constructor ((obj ,name) stream)
(declare (ignorable stream))
(with-slots ,slotnames obj
,@(mapcan #'(lambda (slot)
(let ((name (first slot)))
(unless (member :not-persistent slot)
`((when (slot-boundp obj ',name)
(write-constructor ,name stream))))))
(reverse body)))
(call-next-method))
`(defmethod write-object-initializer ((obj ,name) stream)
(declare (ignorable stream))
(progn ;;with-slots ,slotnames obj
,@(mapcan #'(lambda (slot)
(let ((name (first slot)))
(unless (member :not-persistent slot)
`((if (slot-boundp obj ',name)
(write-referencer (slot-value obj ',name) stream)
(write-coded-marker stream +unbound-marker+))))))
(reverse body)))
(call-next-method))
`(defmethod fill-persistent-object ((obj ,name) stream)
(declare (ignorable stream))
(let (val unbound)
(declare (ignorable val unbound))
(with-slots ,slotnames obj
,@(mapcan #'(lambda (slot)
(let ((name (first slot)))
(unless (member :not-persistent slot)
`((if (probe-bound-p stream)
(setf ,name (read-value stream))
(read-value stream))))))
(reverse body)))
(call-next-method)))
(list 'quote name)))))
(defmacro defclass (&rest forms)
`(defpersistentclass .,forms))
;;;
;;;
;;;
(cl:defstruct structure-info
name
options
slot-specifications
slotnames
initializer)
(defvar *structures* (make-hash-table))
(defun find-structure (name &key (error-p t))
(let ((result (gethash name *structures*)))
(if (null result)
(if error-p
(error "Cannot find structure with name ~A." name)
nil)
result)))
(defun (setf find-structure) (new-value name)
(if (null new-value)
(remhash name *structures*)
(setf (gethash name *structures*) new-value)))
(defmacro with-structure-slots (structure-name slotnames obj &body forms)
`(symbol-macrolet ,(mapcar (lambda (slotname)
(list slotname
(structure-slot-accessor structure-name
slotname
obj)))
slotnames)
.,forms))
(defun structure-slot-accessor (structure-name slotname obj)
(let ((conc-name (or (second
(find ':conc-name
(structure-info-options (find-structure structure-name))
:key #'first))
(concatenate 'string (symbol-name structure-name) "-"))))
(if (symbolp conc-name)
(setf conc-name (symbol-name conc-name)))
(list
(intern (concatenate 'string
conc-name
(symbol-name slotname))
(symbol-package structure-name))
obj)))
(defun set-structure-initializer (structure-entry)
(let* ((user-defined-constructor
(find ':constructor
(structure-info-options structure-entry)
:key #'first))
(constructor
(if user-defined-constructor
(let ((arguments (required-arguments (third user-defined-constructor))))
(if arguments
#'(lambda ()
(apply (second user-defined-constructor)
(loop repeat (length arguments) collect nil)))
(second user-defined-constructor)))
(intern
(concatenate 'string "MAKE-"
(symbol-name (structure-info-name structure-entry)))
(symbol-package (structure-info-name structure-entry))))))
(setf (structure-info-initializer structure-entry) constructor)))
(defun required-arguments (arguments)
(if (null arguments)
nil
(if (member (first arguments) '(&rest &key &optional &allow-other-keys))
nil
(cons (first arguments)
(required-arguments (rest arguments))))))
;; (declaim (inline structure-initializer))
(defun structure-initializer (structure-name)
(structure-info-initializer (find-structure structure-name)))
(defun all-structure-slots (structure-entry)
(let ((included-structure-name
(structure-info-included-structure structure-entry)))
(if (null included-structure-name)
(structure-info-slotnames structure-entry)
(append (structure-info-slotnames structure-entry)
(all-structure-slots (find-structure included-structure-name))))))
(defun structure-info-included-structure (structure-entry)
(second (find ':include (structure-info-options structure-entry)
:key #'first)))
(defun real-structure-p (options)
(not (find ':type options :key #'first)))
(defmacro defpersistentstruct (name-or-name-and-specifications &rest doc-and-slots)
(let* ((name (if (consp name-or-name-and-specifications)
(first name-or-name-and-specifications)
name-or-name-and-specifications))
(options (if (consp name-or-name-and-specifications)
(rest name-or-name-and-specifications)
nil))
(include (second (find ':include options :key #'first)))
(documentation (if (stringp (first doc-and-slots))
(list (first doc-and-slots))))
(slots (if documentation
(rest doc-and-slots)
doc-and-slots))
(slot-specifications (mapcar (lambda (slot-spec)
(cond ((symbolp slot-spec) (list slot-spec nil))
((consp slot-spec) slot-spec)
(t (error "Illegal slot specification: ~A."
slot-spec))))
slots))
(slotnames (mapcar #'first slot-specifications))
all-slotnames
(structure-entry-var (gensym))
(structure-entry (find-structure name :error-p nil)))
(if structure-entry
(setf (structure-info-options structure-entry) options
(structure-info-slot-specifications structure-entry) slots
(structure-info-slotnames structure-entry) slotnames)
(setf structure-entry
(make-structure-info :name name
:options options
:slot-specifications slot-specifications
:slotnames slotnames)))
(set-structure-initializer structure-entry)
(setf (find-structure name) structure-entry)
(setf all-slotnames (all-structure-slots structure-entry))
(if (real-structure-p options)
`(progn
(let ((,structure-entry-var (find-structure ',name :error-p nil)))
(if ,structure-entry-var
(setf (structure-info-options ,structure-entry-var) ',options
(structure-info-slot-specifications ,structure-entry-var) ',slots
(structure-info-slotnames ,structure-entry-var) ',slotnames)
(setf ,structure-entry-var
(make-structure-info :name ',name
:options ',options
:slot-specifications ',slot-specifications
:slotnames ',slotnames)))
(set-structure-initializer ,structure-entry-var)
(setf (find-structure ',name) ,structure-entry-var))
(cl:defstruct (,name .,(if (null include)
(cons (list :include 'persistent-structure)
options)
options))
,@documentation
.,slot-specifications)
(defmethod write-object-constructor ((obj ,name) stream)
(declare (ignorable stream))
(with-structure-slots ,name ,all-slotnames obj
,@(mapcan #'(lambda (slotname)
`((write-constructor ,slotname stream)))
all-slotnames)))
(defmethod write-object-initializer ((obj ,name) stream)
(declare (ignorable stream))
(with-structure-slots ,name ,all-slotnames obj
,@(mapcan #'(lambda (slotname)
`((write-referencer ,slotname stream)))
all-slotnames)))
(defmethod fill-persistent-object ((obj ,name) stream)
(declare (ignorable stream))
(with-structure-slots ,name ,all-slotnames obj
,@(mapcan #'(lambda (slotname)
`((setf ,slotname
(read-value stream))))
all-slotnames)))
',name)
`(cl:defstruct (,name .,options)
,@documentation
.,slot-specifications))))
(defmacro defstruct (&rest forms)
`(defpersistentstruct .,forms))
;;;
;;;
;;;
(defconstant +file-type-marker+ 66647963)
(defun write-section-separator (stream)
(write-coded-marker stream +section-marker+))
(defun generate-temp-filename (filename)
(let* ((pathname (pathname filename))
(name (pathname-name pathname))
new-name)
(loop for i from 1 to 100 do
(when (not (probe-file (setf new-name
(merge-pathnames (concatenate 'string
name
"-"
(format nil "~D" i))
pathname))))
(return-from generate-temp-filename new-name)))
(error "Cannot generate name for temp file.")))
(defun make-object-persistent (obj fn &optional (package *package*))
(let ((filename (generate-temp-filename fn)))
(handler-case
(progn
(with-open-file (stream filename
:element-type 'unsigned-byte
:direction :output :if-exists :supersede
:if-does-not-exist :create)
(let ((*package* package))
(reset)
(write-coded-integer stream +file-type-marker+)
(write-coded-string stream
(make-string +n-bytes-for-written-objects+
:initial-element #\space))
(write-coded-string stream (package-name package))
(write-coded-integer stream +persistence-version+)
(write-constructor (list obj) stream)
(write-section-separator stream)
(maphash #'(lambda (key value)
(declare (ignorable value))
(write-initializer key stream))
*written-objects*)))
(when (> *io-id-counter* +maximum-written-objects+)
(error "Maximum number of objects per file (~D) exceeded."
+maximum-written-objects+))
(with-open-file (stream filename
:element-type 'unsigned-byte
:direction :output :if-exists :overwrite
:if-does-not-exist :create)
(write-coded-integer stream +file-type-marker+)
(write-coded-string stream
(format nil
(concatenate 'string
"~"
(format nil "~D" +n-bytes-for-written-objects+)
",d")
*io-id-counter*)))
(delete-file fn)
(rename-file filename fn)
(format nil "~A objects and ~A references have been written to ~A." *io-id-counter* *ref-counter* fn))
(error (c)
(format *error-output* "~A" c)
(delete-file filename)
nil))))
(defun load-persistent-object (fn &key (initialization-protocol t))
(with-open-file (stream fn :direction :input :element-type 'unsigned-byte)
(let ((file-type-marker (read-coded-integer stream)))
(unless (= file-type-marker +file-type-marker+)
(error "File ~S is not a Racer dump file." fn))
(let* ((n-of-objects-to-read (read-from-string (read-coded-string stream)))
(package-name (read-coded-string stream))
(package (find-package package-name))
(*package* (or package
(error "Cannot restore object: Package ~S not found." package-name)))
(version (read-coded-integer stream)))
(unless (= version +persistence-version+)
(error "Dump file format of ~A not compatible with current version of Racer." fn))
(read-reset n-of-objects-to-read)
(construct-object stream)
(initialize-object stream)
(when initialization-protocol
(dotimes (i (+ 2 *io-id-counter*))
(let ((obj (bvref *read-objects* i)))
(when (or (typep obj 'persistent-object)
(typep obj 'persistent-structure))
(initialize-loaded-persistent-object obj)))))
(let ((result (first (retrieve 1))))
(setf *read-objects* nil)
(values result
(format nil "Loaded ~A objects from ~A." (+ 2 *io-id-counter*) fn)
#|(loop as i from 1 to *io-id-counter* when (typep (retrieve i) 'persistent-object)
collect (retrieve i))|#))))))
;;;
;;; How to enable the framework to store and restore CLIM's RGB-COLOR objects!
;;;
#+:clim
(progn
(defmethod user-write-constructor (stream (object clim-utils:rgb-color))
;; write appropriate component constructors for the object
;; (the frame work doesn't know the structure of the object!)
(multiple-value-bind (r g b)
(clim-utils::color-rgb object)
(user-write-component-constructor stream r) ;; not strictly necessary if the component objects are
(user-write-component-constructor stream g) ;; atomic values (e.g., symbols or numbers), but
(user-write-component-constructor stream b) ;; doesn't harm the frame work either
(values)))
(defmethod user-write-initializer (stream (object clim-utils:rgb-color))
(multiple-value-bind (r g b)
(clim-utils::color-rgb object)
(user-write-component-initializer stream r) ;; ensure to write-out the component objects
(user-write-component-initializer stream g) ;; (numbers in this case)
(user-write-component-initializer stream b)))
(defmethod user-create-empty-object ((type (eql 'clim-utils::rgb-color)))
;; create an "empty container" object of appropriate type, return it
;; in this case, ensure that CLIM really creates an RGB-COLOR object
;; (and not just a GRAY-COLOR object!)
(clim::make-rgb-color 0.1 0.2 0.3))
(defmethod user-fill-object (stream (object clim-utils::rgb-color))
;; read in the component values and assign them to appropriate places within object
;; don't forget to return the object!
(with-slots (clim-utils::red clim-utils::green clim-utils::blue) object
(setf clim-utils::red (user-read-component-object stream)
clim-utils::green (user-read-component-object stream)
clim-utils::blue (user-read-component-object stream)))
object)
;;;
;;; Same Thing for Gray Colors
;;;
;;;
;;; aus irgendeinem Grund gibt der "make-gray-color"-Konstruktor
;;; u.U. ein bereits konstruiertes (falsches!) Farb-Objekt zurück!
;;; Funktioniert also nicht richtig...
;;;
(defmethod user-write-constructor (stream (object clim-utils:gray-color))
(with-slots (clim-utils::luminosity) object
(user-write-component-constructor stream clim-utils::luminosity)
(values)))
(defmethod user-write-initializer (stream (object clim-utils:gray-color))
(with-slots (clim-utils::luminosity) object
(user-write-component-initializer stream clim-utils::luminosity)))
(defmethod user-create-empty-object ((type (eql 'clim-utils::gray-color)))
(clim::make-gray-color 0.3))
(defmethod user-fill-object (stream (object clim-utils::gray-color))
(setf (slot-value object 'clim-utils::luminosity)
(user-read-component-object stream))
object))
;;;
;;;
;;;
#|
(progn
;;; Demo
(defpersistentclass test ()
((x :initarg :x)
(y :initarg :y)
(temp :initform (random 100) :not-persistent) ;; don't save this slot
))
(defpersistentclass testtest (test)
((z :initarg :z)))
(let* ((x (list 1 2 3))
(y (vector 1 2 3 4 5))
(z (make-instance 'testtest :x x :y :y))
(h (make-hash-table)))
(setf (gethash 'x h) x
(gethash 'y h) y
(gethash 'z h) z)
(setf (slot-value z 'z) h)
(let ((object (list x y z (list x) (list x y z) (vector x y z)
"hallo" (list "hallo" 'test 123 123.0 4/5)
clim-utils::+red+ clim-utils::+green+
h
)))
(make-object-persistent object "test-object.obj")
(let ((object2 (load-persistent-object "test-object.obj")))
(Setf *x* (list object object2))
(princ *x*)))))
|#
| 41,556 | Common Lisp | .lisp | 990 | 31.345455 | 112 | 0.585712 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 82be28790238236391a81d06e0444dcbd4d5bbc37822b4a5d8c2bda1b6d89019 | 12,480 | [
-1
] |
12,481 | lracer-sysdcl.lisp | lambdamikel_DLMAPS/src/lracer/lracer-sysdcl.lisp | ;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: CL-USER -*-
(in-package :cl-user)
(defparameter *lracer-filenames*
'("nrql-symbols-1-9-0"
"lracer-package-1-9-0"
"lracer-1-9-0"
#-:nrql-dev "lracer-nrql-stubs-1-9-0"
"lracer-test-support-1-9-0"))
(defun compile-load-lracer (&optional (directory "dlmaps:lracer;"))
(loop for filename in *lracer-filenames*
for pathname = (merge-pathnames (pathname filename)
(pathname directory))
do
(compile-file (merge-pathnames pathname (make-pathname :type "lisp"))
:verbose t)
(load pathname :verbose t)))
| 664 | Common Lisp | .lisp | 1 | 661 | 664 | 0.582831 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | deadaf21878b2a9df322ae6bcd78a7ac37c69642661507cbbeef161763417de1 | 12,481 | [
-1
] |
12,482 | lracer-test-support-1-9-0.lisp | lambdamikel_DLMAPS/src/lracer/lracer-test-support-1-9-0.lisp | (in-package cl-user)
(defmacro with-timeout ((seconds . timeout-forms) &body body)
#+:ALLEGRO
`(let ((timeout-fn #'(lambda () ,@timeout-forms)))
(unwind-protect
(restart-case
(mp:with-timeout (,seconds (funcall timeout-fn))
,@body)
(abort-execution ()
:report
(lambda (stream)
(format stream "Abort execution as timeout"))
(funcall timeout-fn)))))
#+:MCL
`(with-timeout-1 ,seconds #'(lambda () ,@timeout-forms) #'(lambda () ,@body) ',body)
#+:Lispworks
`(with-timeout-internal ,seconds #'(lambda () ,@body) #'(lambda () ,@timeout-forms))
#-(or :ALLEGRO :MCL :Lispworks)
(declare (ignore seconds timeout-forms))
#-(or :ALLEGRO :MCL :Lispworks)
`(progn ,@body))
#+:Lispworks
(defun with-timeout-internal (timeout function timeout-function)
(declare (dynamic-extent function))
(let ((catch-tag nil)
(process mp:*current-process*))
(labels ((timeout-throw ()
(throw catch-tag nil))
(timeout-action ()
(mp:process-interrupt process #'timeout-throw)))
(declare (dynamic-extent #'timeout-throw #'timeout-action))
(let ((timer (mp:make-named-timer 'timer #'timeout-action)))
(setq catch-tag timer)
(catch timer
(unwind-protect
(progn
(mp:schedule-timer-relative timer timeout)
(return-from with-timeout-internal
(funcall function)))
(mp:unschedule-timer timer)))
(when timeout-function
(funcall timeout-function))))))
#+:MCL
(defun with-timeout-1 (seconds timeout-fn body-fn timeout-forms)
(let* ((tag 'tag-1)
(current-process *current-process*)
(timeout-process
(process-run-function
(format nil "Timeout ~D" (round seconds))
#'(lambda ()
(sleep (round seconds))
(process-interrupt current-process
#'(lambda ()
(throw tag (funcall timeout-fn))))))))
(catch tag
(unwind-protect
(restart-case
(funcall body-fn)
(abort-execution ()
:report
(lambda (stream)
(format stream "Abort execution as timeout: ~A" timeout-forms))
(funcall timeout-fn)))
(process-kill timeout-process)))))
#+:ALLEGRO
(let ((elapsed-gc-time-user 0)
(elapsed-gc-time-system 0)
(elapsed-run-time-user 0)
(elapsed-run-time-system 0)
(elapsed-real-time 0)
(used-cons-cells 0)
(used-symbols 0)
(used-other-bytes 0))
(defun set-time-vars (pelapsed-gc-time-user
pelapsed-gc-time-system
pelapsed-run-time-user
pelapsed-run-time-system
pelapsed-real-time
pused-cons-cells
pused-symbols
pused-other-bytes)
(setf elapsed-gc-time-user pelapsed-gc-time-user)
(setf elapsed-gc-time-system pelapsed-gc-time-system)
(setf elapsed-run-time-user pelapsed-run-time-user)
(setf elapsed-run-time-system pelapsed-run-time-system)
(setf elapsed-real-time pelapsed-real-time)
(setf used-cons-cells pused-cons-cells)
(setf used-symbols pused-symbols)
(setf used-other-bytes pused-other-bytes))
(defun gctime ()
(+ elapsed-gc-time-user elapsed-gc-time-system))
(defun total-bytes-allocated ()
(+ (* 8 used-cons-cells) (* 64 used-symbols) used-other-bytes)))
#+:MCL
(defun total-bytes-allocated ()
(ccl::total-bytes-allocated))
(let (#+:mcl initial-gc-time
#+:mcl initial-consed
#+(or :mcl :allegro) initial-real-time
#+(or :mcl :allegro) initial-run-time)
#+:mcl
(defun with-timed-form (thunk)
(setf initial-gc-time (gctime))
(setf initial-consed (total-bytes-allocated))
(setf initial-real-time (get-internal-real-time))
(setf initial-run-time (get-internal-run-time))
(let* ((result (funcall thunk))
(elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (- (gctime) initial-gc-time)
internal-time-units-per-second))
(bytes-consed (- (total-bytes-allocated) initial-consed
(if (fixnump initial-consed) 0 16))))
(values result elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time bytes-consed)))
#+:ALLEGRO
(defun with-timed-form (thunk)
(setf initial-real-time (get-internal-real-time))
(setf initial-run-time (get-internal-run-time))
(let* ((result (excl::time-a-funcall thunk #'set-time-vars))
(elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (gctime) internal-time-units-per-second))
(bytes-consed (total-bytes-allocated)))
(values result elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time (abs bytes-consed))))
#+:mcl
(defun timed-out-handler ()
(let* ((elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (- (gctime) initial-gc-time)
internal-time-units-per-second))
(bytes-consed (- (total-bytes-allocated) initial-consed
(if (fixnump initial-consed) 0 16))))
(values '(?) elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time bytes-consed)))
#+:ALLEGRO
(defun timed-out-handler ()
(let* ((elapsed-real-time (/ (- (get-internal-real-time) initial-real-time)
internal-time-units-per-second))
(elapsed-run-time (/ (- (get-internal-run-time) initial-run-time)
internal-time-units-per-second))
(elapsed-mf-time (max 0 (- elapsed-real-time elapsed-run-time)))
(elapsed-gc-time (/ (gctime) internal-time-units-per-second))
(bytes-consed (total-bytes-allocated)))
(values '(?) elapsed-run-time elapsed-real-time elapsed-mf-time
elapsed-gc-time (abs bytes-consed)))))
(defparameter *test-assert-timeout* 15)
(defmacro test-assert (form)
(let ((var (gensym)))
`(let ((,var (with-timeout (*test-assert-timeout*
(progn
(format t "~&TIMED OUT: ~S~%Current TBox=~S, ABox=~S~%"
',form (current-tbox) (current-abox))
(when *with-server-connection*
(reopen-server-connection))
t))
,form)))
(unless ,var
(cerror "ignore error" "Failed assertion: ~S" ',form)))))
(defun test-verify-with-concept-tree-list (tree-list
&optional (tbox (current-tbox)))
(with-timeout (*test-assert-timeout*
(progn
(format t "~&verify-with-concept-tree-list TIMED OUT~%")
(when *with-server-connection*
(reopen-server-connection))
t))
(verify-with-concept-tree-list tree-list tbox)))
(defun test-verify-with-abox-individuals-list (individuals-list
&optional (abox (current-abox)))
(with-timeout (*test-assert-timeout*
(progn
(format t "~&verify-with-abox-individuals-list TIMED OUT~%")
(when *with-server-connection*
(reopen-server-connection))
t))
(verify-with-abox-individuals-list individuals-list abox)))
(defmacro test-with-timeout (&body forms)
`(with-timeout (*test-assert-timeout*
(progn
(format t "~&TIMED OUT: ~S~%" ',forms)
(when *with-server-connection*
(reopen-server-connection))
t))
. ,forms)) | 9,384 | Common Lisp | .lisp | 1 | 9,384 | 9,384 | 0.522272 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | c02ce3157ebf469069b9ab0b4bde8116d802541e37ee1b84a40a02b2e2e95c2b | 12,482 | [
-1
] |
12,483 | lracer-package-1-9-0.lisp | lambdamikel_DLMAPS/src/lracer/lracer-package-1-9-0.lisp | (in-package cl-user)
#+:mcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :opentransport))
#+:lispworks
(eval-when (:compile-toplevel :load-toplevel :execute)
(require "comm"))
(defpackage racer
(:use common-lisp nrql-symbols #+:allegro excl)
(:export "+TOP-SYMBOL+"
"+BOTTOM-SYMBOL+"
"TBOX"
"INIT-TBOX"
"SAVE-TBOX"
"DELETE-TBOX"
"FORGET-TBOX"
"CURRENT-TBOX"
"SET-NOMINALS-DISJOINT-P"
"NOMINALS-DISJOINT-P"
"FIND-TBOX"
"SET-FIND-TBOX"
"CREATE-TBOX-CLONE"
"CLONE-TBOX"
"TBOX-NAME"
"IN-TBOX"
"INIT-ABOX"
"SET-CURRENT-TBOX"
"SET-CURRENT-ABOX"
"SAVE-ABOX"
"DELETE-ABOX"
"FORGET-ABOX"
"CURRENT-ABOX"
"FIND-ABOX"
"SET-FIND-ABOX"
"CREATE-ABOX-CLONE"
"CLONE-ABOX"
"ABOX-NAME"
"IN-ABOX"
"*TOP*"
"TOP"
"*BOTTOM*"
"BOTTOM"
"AT-LEAST"
"AT-MOST"
"EXACTLY"
"SOME"
"ALL"
"NOT"
"AND"
"OR"
"INV"
"DEFINE-TBOX"
"SIGNATURE"
"ENSURE-TBOX-SIGNATURE"
"ENSURE-ABOX-SIGNATURE"
"GET-KB-SIGNATURE"
"GET-TBOX-SIGNATURE"
"GET-ABOX-SIGNATURE"
"IN-KNOWLEDGE-BASE"
"DEFINE-PRIMITIVE-CONCEPT"
"DEFPRIMCONCEPT"
"DEFINE-CONCEPT"
"DEFCONCEPT"
"IMPLIES"
"EQUIVALENT"
"DISJOINT"
"DEFINE-DISJOINT-PRIMITIVE-CONCEPT"
"ADD-DISJOINTNESS-AXIOM"
"ADD-CONCEPT-AXIOM"
"FORGET-CONCEPT-AXIOM"
"FORGET-CONSTRAINT"
"FORGET-CONSTRAINED-ASSERTION"
"FORGET-DISJOINTNESS-AXIOM"
"FORGET-DISJOINTNESS-AXIOM-STATEMENT"
"DEFINE-PRIMITIVE-ROLE"
"DEFPRIMROLE"
"DEFINE-PRIMITIVE-ATTRIBUTE"
"DEFPRIMATTRIBUTE"
"DEFCDATTRIBUTE"
"DEFINE-CONCRETE-DOMAIN-ATTRIBUTE"
"ADD-ROLE-AXIOMS"
;"ADD-ROLE-AXIOM" ;now obsolete?
"DEFINE-DISTINCT-INDIVIDUAL"
"DEFINE-INDIVIDUAL"
"ADD-INDIVIDUAL"
"STATE"
"INSTANCE"
"RELATED"
"ADD-CONCEPT-ASSERTION"
"ADD-ROLE-ASSERTION"
"FORGET-CONCEPT-ASSERTION"
"FORGET-ROLE-ASSERTION"
"FORGET"
"FORGET-STATEMENT"
"CONCEPT-SATISFIABLE?"
"CONCEPT-SATISFIABLE-P"
"ALC-CONCEPT-COHERENT"
"CONCEPT-SUBSUMES?"
"CONCEPT-SUBSUMES-P"
"CONCEPT-EQUIVALENT?"
"CONCEPT-EQUIVALENT-P"
"CONCEPT-DISJOINT?"
"CONCEPT-DISJOINT-P"
"CLASSIFY-TBOX"
"CHECK-TBOX-COHERENCE"
"TBOX-COHERENT-P"
"TBOX-COHERENT?"
"TBOX-CLASSIFIED-P"
"TBOX-CLASSIFIED?"
"TBOX-PREPARED-P"
"TBOX-PREPARED?"
"TBOX-CYCLIC-P"
"TBOX-CYCLIC?"
"CYCLIC-CONCEPTS-IN-TBOX"
"ATOMIC-CONCEPT-DESCENDANTS"
"ATOMIC-CONCEPT-ANCESTORS"
"ATOMIC-CONCEPT-CHILDREN"
"ATOMIC-CONCEPT-PARENTS"
"ATOMIC-CONCEPT-SYNONYMS"
"CONCEPT-SYNONYMS"
"CONCEPT-DESCENDANTS"
"CONCEPT-OFFSPRING"
"CONCEPT-CHILDREN"
"CONCEPT-ANCESTORS"
"CONCEPT-PARENTS"
"CONCEPT-IS-PRIMITIVE-P"
"CONCEPT-IS-PRIMITIVE?"
"CONCEPT-INSTANCES"
"TAXONOMY"
"ROLE-PARENTS"
"ROLE-CHILDREN"
"ROLE-OFFSPRING"
"ROLE-ANCESTORS"
"ROLE-DESCENDANTS"
"ROLE-INVERSE"
"ATOMIC-ROLE-PARENTS"
"ATOMIC-ROLE-CHILDREN"
"ATOMIC-ROLE-ANCESTORS"
"ATOMIC-ROLE-DESCENDANTS"
"ATOMIC-ROLE-INVERSE"
"DEFINE-ABOX"
"REALIZE-ABOX"
"CHECK-ABOX-COHERENCE"
"ABOX-REALIZED-P"
"ABOX-REALIZED?"
"ABOX-PREPARED-P"
"ABOX-PREPARED?"
"ABOX-CONSISTENT-P"
"ABOX-CONSISTENT?"
"ABOX-UNA-CONSISTENT-P"
"ABOX-UNA-CONSISTENT?"
"ROLE-SUBSUMES?"
"ROLE-SUBSUMES-P"
"INDIVIDUAL-P"
"INDIVIDUAL?"
"CD-OBJECT-P"
"CD-OBJECT?"
"INDIVIDUAL-TYPES"
"INDIVIDUAL-DIRECT-TYPES"
"INDIVIDUAL-INSTANCE?"
"INDIVIDUAL-INSTANCE-P"
"INDIVIDUAL-FILLERS"
"INDIVIDUAL-ATTRIBUTE-FILLERS"
"INDIVIDUALS-RELATED?"
"INDIVIDUALS-RELATED-P"
"INDIVIDUALS-EQUAL?"
"INDIVIDUALS-NOT-EQUAL?"
"INDIVIDUALS-EQUAL-P"
"INDIVIDUALS-NOT-EQUAL-P"
"INSTANTIATORS"
"MOST-SPECIFIC-INSTANTIATORS"
"RETRIEVE-CONCEPT-INSTANCES"
"RETRIEVE-INDIVIDUAL-FILLED-ROLES"
"INDIVIDUAL-FILLED-ROLES"
"RETRIEVE-DIRECT-PREDECESSORS"
"DIRECT-PREDECESSORS"
"RETRIEVE-RELATED-INDIVIDUALS"
"RETRIEVE-INDIVIDUAL-FILLERS"
"RETRIEVE-INDIVIDUAL-ATTRIBUTE-FILLERS"
"TOLD-VALUE"
"RELATED-INDIVIDUALS"
"ALL-TBOXES"
"DELETE-ALL-TBOXES"
"ALL-ABOXES"
"DELETE-ALL-ABOXES"
"LOOP-OVER-ABOXES"
"LOOP-OVER-TBOXES"
"ALL-ROLES"
"ALL-FEATURES"
"ALL-TRANSITIVE-ROLES"
"ALL-ATTRIBUTES"
"ATTRIBUTE-TYPE"
"ATTRIBUTE-HAS-RANGE"
"ATTRIBUTE-DOMAIN"
"ATTRIBUTE-DOMAIN-1"
"ATTRIBUTE-HAS-DOMAIN"
"ALL-ATOMIC-CONCEPTS"
"ALL-EQUIVALENT-CONCEPTS"
"ALL-INDIVIDUALS"
"ALL-CONCEPT-ASSERTIONS-FOR-INDIVIDUAL"
"ALL-ROLE-ASSERTIONS-FOR-INDIVIDUAL-IN-DOMAIN"
"ALL-ROLE-ASSERTIONS-FOR-INDIVIDUAL-IN-RANGE"
"ALL-ROLE-ASSERTIONS"
"ALL-ATTRIBUTE-ASSERTIONS"
"ALL-CONCEPT-ASSERTIONS"
"ALL-CONSTRAINTS"
"ROLE-P"
"ROLE?"
"TRANSITIVE-P"
"TRANSITIVE?"
"FEATURE-P"
"FEATURE?"
"CD-ATTRIBUTE-P"
"CD-ATTRIBUTE?"
"SYMMETRIC-P"
"SYMMETRIC?"
"REFLEXIVE-P"
"REFLEXIVE?"
"CONCEPT-P"
"CONCEPT?"
"DESCRIBE-TBOX"
"DESCRIBE-CONCEPT"
"DESCRIBE-ROLE"
"DESCRIBE-ABOX"
"DESCRIBE-INDIVIDUAL"
"ALC-CONCEPT-COHERENT"
"VALIDATE-TRUE"
"VALIDATE-FALSE"
"VALIDATE-SET"
"VERIFY-WITH-CONCEPT-TREE-LIST"
"VERIFY-WITH-ABOX-INDIVIDUALS-LIST"
"VERIFY-WITH-CONCEPT-TREE"
"TEST-ASSERT"
"TEST-VERIFY-WITH-CONCEPT-TREE-LIST"
"TEST-VERIFY-WITH-ABOX-INDIVIDUALS-LIST"
"DISPLAY-GRAPH"
"PRINT-TBOX-TREE"
"WITH-RACER-STATISTICS"
"WITH-SAT-STATISTICS"
"WITH-KB-STATISTICS"
"WITH-VERBOSE-STATISTICS"
"CONSTRAINED"
"ADD-ATTRIBUTE-ASSERTION"
"CONSTRAINTS"
"ADD-CONSTRAINT-ASSERTION"
">="
"<="
">"
"<"
"<>"
"="
"*"
"+"
"-"
"A"
"AN"
"NO"
"ENSURE"
"MIN"
"MAX"
"RANGE"
"EQUAL"
"STRING="
"STRING<>"
"COMPLEX"
"REAL"
"INTEGER"
"CARDINAL"
"STRING"
"BOOLEAN"
"XML-READ-TBOX-FILE"
"RDFS-READ-TBOX-FILE"
"RACER-READ-FILE"
"RACER-READ-DOCUMENT"
"DAML-READ-FILE"
"DAML-READ-DOCUMENT"
"OWL-READ-FILE"
"OWL-READ-DOCUMENT"
"DIG-READ-FILE"
"DIG-READ-DOCUMENT"
"ASSOCIATED-TBOX"
"SET-ASSOCIATED-TBOX"
"ASSOCIATED-ABOXES"
"SAVE-KB"
"INCLUDE-KB"
"IMPORT-KB"
"CLEAR-DEFAULT-TBOX"
"COMPUTE-INDEX-FOR-INSTANCE-RETRIEVAL"
"ENSURE-SUBSUMPTION-BASED-QUERY-ANSWERING"
"ENSURE-SMALL-TBOXES"
"PUBLISH"
"PUBLISH-1"
"UNPUBLISH"
"UNPUBLISH-1"
"SUBSCRIBE"
"SUBSCRIBE-1"
"UNSUBSCRIBE"
"UNSUBSCRIBE-1"
"INIT-SUBSCRIPTIONS"
"INIT-SUBSCRIPTIONS-1"
"INIT-PUBLICATIONS"
"INIT-PUBLICATIONS-1"
"CHECK-SUBSCRIPTIONS"
"FUNCTIONAL"
"ROLE-IS-FUNCTIONAL"
"TRANSITIVE"
"ROLE-IS-TRANSITIVE"
"INVERSE"
"INVERSE-OF-ROLE"
"DECLARE-DISJOINT"
"DOMAIN"
"ROLE-HAS-DOMAIN"
;;"RANGE"
"ROLE-HAS-RANGE"
"IMPLIES-ROLE"
"ROLE-HAS-PARENT"
"GET-TBOX-LANGUAGE"
"GET-ABOX-LANGUAGE"
"GET-META-CONSTRAINT"
"GET-CONCEPT-DEFINITION"
"GET-CONCEPT-NEGATED-DEFINITION"
"GET-CONCEPT-DEFINITION-1"
"GET-CONCEPT-NEGATED-DEFINITION-1"
"ATOMIC-ROLE-RANGE"
"ROLE-RANGE"
"ATOMIC-ROLE-DOMAIN"
"ROLE-DOMAIN"
"DEFAULT"
"LOGGING-ON"
"LOGGING-OFF"
"TBOX-NAMESPACES"
"REMOVE-PREFIX"
"GET-NAMESPACE-PREFIX"
"EXPT"
"STORE-TBOX-IMAGE"
"STORE-TBOXES-IMAGE"
"STORE-ABOX-IMAGE"
"STORE-ABOXES-IMAGE"
"STORE-KB-IMAGE"
"STORE-KBS-IMAGE"
"RESTORE-ABOX-IMAGE"
"RESTORE-ABOXES-IMAGE"
"RESTORE-TBOX-IMAGE"
"RESTORE-TBOXES-IMAGE"
"RESTORE-KB-IMAGE"
"RESTORE-KBS-IMAGE"
"MIRROR"
"CLEAR-MIRROR-TABLE"
"KB-ONTOLOGIES"
"COMPUTE-IMPLICIT-ROLE-FILLERS"
"COMPUTE-ALL-IMPLICIT-ROLE-FILLERS"
"CONSTRAINT-ENTAILED-P"
"CONSTRAINT-ENTAILED?"
"ROLES-EQUIVALENT"
"ROLES-EQUIVALENT-1"
"ATOMIC-ROLE-SYNONYMS"
"ROLE-SYNONYMS"
"PRINT-ABOX-INDIVIDUALS"
"INDIVIDUAL-TOLD-DATATYPE-FILLERS"
"RETRIEVE-INDIVIDUAL-TOLD-DATATYPE-FILLERS"
"ROLE-USED-AS-DATATYPE-PROPERTY-P"
"ROLE-IS-USED-AS-DATATYPE-PROPERTY"
"DATATYPE-ROLE-RANGE"
"DATATYPE-ROLE-HAS-RANGE"
"SET-SERVER-TIMEOUT"
"GET-SERVER-TIMEOUT"
"DEFINE-DATATYPE-PROPERTY"
"ADD-DATATYPE-PROPERTY"
"WITH-UNIQUE-NAME-ASSUMPTION"
"WITHOUT-UNIQUE-NAME-ASSUMPTION"
"SET-UNIQUE-NAME-ASSUMPTION"
"RETRIEVE-INDIVIDUAL-SYNONYMS"
"INDIVIDUAL-SYNONYMS"
"ATTRIBUTE-FILLER"
"SET-ATTRIBUTE-FILLER"
"DATATYPE-ROLE-FILLER"
"ADD-DATATYPE-ROLE-FILLER"
"GET-TBOX-VERSION"
"GET-ABOX-VERSION"
"INDIVIDUAL-ATTRIBUTE-VALUE"
"RETRIEVE-INDIVIDUAL-ATTRIBUTE-VALUE"
"CREATE-TBOX-INTERNAL-MARKER-CONCEPT"
"PARSE-EXPRESSION"
"ROLE-USED-AS-ANNOTATION-PROPERTY-P"
"ROLE-IS-USED-AS-ANNOTATION-PROPERTY"
"ADD-ANNOTATION-CONCEPT-ASSERTION"
"ADD-ANNOTATION-ROLE-ASSERTION"
"ALL-ANNOTATION-CONCEPT-ASSERTIONS"
"ALL-ANNOTATION-ROLE-ASSERTIONS"
"TRUE?"
"FALSE?"
"CREATE-TBOX-INTERNAL-MARKER-CONCEPT"
"RACER-INTERNAL%HAS-STRING-VALUE"
"RACER-INTERNAL%HAS-INTEGER-VALUE"
"RACER-INTERNAL%HAS-CARDINAL-VALUE"
"RACER-INTERNAL%HAS-REAL-VALUE"
"RACER-INTERNAL%HAS-BOOLEAN-VALUE"
"INTERNAL-INDIVIDUALS-RELATED-P"
"SWRL-FORWARD-CHAINING"
"PREPARE-RACER-ENGINE"
"SET-REWRITE-DEFINED-CONCEPTS"
"ENABLE-OPTIMIZED-QUERY-PROCESSING"
"PREPARE-ABOX"
"WITHOUT-SIGNATURE-CHECKS"
"WITH-CRITICAL-SECTION"
"WITH-SERVER-CONNECTION"
"*DEFAULT-RACER-HOST*"
"*DEFAULT-RACER-TCP-PORT*"
"*VERBOSE-CONNECTION*"
"*WITH-SERVER-CONNECTION*"
"*SERVICE-REQUEST-VERBOSE*"
"OPEN-SERVER-CONNECTION"
"REOPEN-SERVER-CONNECTION"
"CLOSE-SERVER-CONNECTION"))
(eval-when (:load-toplevel :execute)
(defun use-racer-in-cl-user ()
(dolist (package '(racer nrql-symbols))
(loop for sym being the external-symbols of (find-package package) do
(let ((cl-user-sym (find-symbol (symbol-name sym) 'cl-user)))
(when cl-user-sym
(unintern cl-user-sym 'cl-user)))
(import sym 'cl-user)))))
(eval-when (:load-toplevel :execute)
(use-racer-in-cl-user))
(defpackage racer-user
(:use common-lisp racer))
| 13,290 | Common Lisp | .lisp | 1 | 13,285 | 13,290 | 0.495937 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 1c33fb79d92a2f3b0e4f350ff2b4197708d733541c6847ad87dc8f490c471384 | 12,483 | [
-1
] |
12,484 | nrql-symbols-1-9-0.lisp | lambdamikel_DLMAPS/src/lracer/nrql-symbols-1-9-0.lisp | (in-package cl-user)
;;;
;;;--------------------------------------------
;;; Automatically Generated nRQL Symbol List
;;; Version: 1.9.0
;;;--------------------------------------------
;;;
(DEFPACKAGE NRQL-SYMBOLS
(:EXPORT
"QUERY"
"WITH-NRQL-STANDARD-SETTINGS"
"RACER-RETRIEVE-INDIVIDUAL-FILLED-ROLES"
"RACER-RETRIEVE-INDIVIDUAL-FILLERS"
"RACER-RETRIEVE-RELATED-INDIVIDUALS"
"XML-OUTPUT"
"XML-INPUT"
"LISP-TO-XML"
"XML-TO-LISP"
"BIND-INDIVIDUAL"
"INV"
"NOT"
"NEG"
"AND"
"OR"
"SATISFIES"
"TOP"
"BOTTOM"
"TRUE-QUERY"
"FALSE-QUERY"
"CONSTRAINT"
"HAS-KNOWN-SUCCESSOR"
"SUBSTITUTE"
"INSERT"
"SAME-AS"
"EQUAL"
"="
"INTERSECTION"
"UNION"
"CAP"
"CUP"
"TOLD-VALUE"
"TOLD-VALUES"
"TOLD-FILLER"
"TOLD-FILLERS"
"FILLER"
"FILLERS"
"DATATYPE-FILLER"
"DATATYPE-FILLERS"
"BINDINGS-FROM"
"ANNOTATION"
"ANNOTATIONS"
"NO-TOLD-VALUE"
"NO-KNOWN-CD-OBJECTS"
"PROJECT"
"PROJECT-TO"
"PI"
"REAL-TOP"
"REAL-BOTTOM"
"STORE-SUBSTRATE-FOR-CURRENT-ABOX"
"RESTORE-ALL-SUBSTRATES"
"RESTORE-SUBSTRATE"
"STORE-ALL-SUBSTRATES"
"STORE-SUBSTRATE-FOR-ABOX"
"GET-NRQL-VERSION"
"DEL-RCC-EDGE1"
"DEL-RCC-NODE1"
"RCC-EDGE-LABEL1"
"RCC-NODE-LABEL1"
"RCC-EDGE1"
"RCC-NODE1"
"RCC-RELATED1"
"RCC-INSTANCE1"
"RCC-CONSISTENT-P"
"CREATE-RCC-EDGE"
"CREATE-RCC-NODE"
"SET-RCC-BOX"
"SET-MIRROR-DATA-BOX"
"DESCRIPTION-IMPLIES-P"
"SET-DATA-BOX"
"GET-DATA-EDGE-LABEL"
"GET-DATA-NODE-LABEL"
"DELETE-DATA-EDGE"
"DELETE-DATA-NODE"
"CREATE-DATA-EDGE"
"CREATE-DATA-NODE"
"GET-PROCESS-POOL-SIZE"
"GET-MAXIMUM-SIZE-OF-PROCESS-POOL"
"GET-INITIAL-SIZE-OF-PROCESS-POOL"
"SET-MAXIMUM-SIZE-OF-PROCESS-POOL"
"SET-INITIAL-SIZE-OF-PROCESS-POOL"
"SET-REWRITE-DEFINED-CONCEPTS"
"SET-NRQL-MODE"
"SHOW-CURRENT-QBOX"
"GET-ABOX-OF-CURRENT-QBOX"
"DISABLE-QUERY-REALIZATION"
"ENABLE-QUERY-REALIZATION"
"OPTIMIZER-DONT-USE-CARDINALITY-HEURISTICS"
"OPTIMIZER-USE-CARDINALITY-HEURISTICS"
"DISABLE-QUERY-OPTIMIZATION"
"ENABLE-QUERY-OPTIMIZATION"
"DISABLE-QUERY-REPOSITORY"
"ENABLE-QUERY-REPOSITORY"
"DONT-REPORT-TAUTOLOGICAL-QUERIES"
"REPORT-TAUTOLOGICAL-QUERIES"
"DONT-REPORT-INCONSISTENT-QUERIES"
"REPORT-INCONSISTENT-QUERIES"
"DESCRIBE-QUERY-PROCESSING-MODE"
"DESCRIBE-CURRENT-SUBSTRATE"
"INCLUDE-PERMUTATIONS"
"EXCLUDE-PERMUTATIONS"
"DONT-ADD-RULE-CONSEQUENCES-AUTOMATICALLY"
"ADD-RULE-CONSEQUENCES-AUTOMATICALLY"
"PROCESS-SET-AT-A-TIME"
"PROCESS-TUPLE-AT-A-TIME"
"GET-MAX-NO-OF-TUPLES-BOUND"
"SET-MAX-NO-OF-TUPLES-BOUND"
"DONT-CHECK-ABOX-CONSISTENCY-BEFORE-QUERYING"
"CHECK-ABOX-CONSISTENCY-BEFORE-QUERYING"
"ENABLE-LAZY-TUPLE-COMPUTATION"
"ENABLE-EAGER-TUPLE-COMPUTATION"
"RESTORE-STANDARD-SETTINGS"
"DONT-ADD-ROLE-ASSERTIONS-FOR-DATATYPE-PROPERTIES"
"ADD-ROLE-ASSERTIONS-FOR-DATATYPE-PROPERTIES"
"DISABLE-TOLD-INFORMATION-QUERYING"
"ENABLE-TOLD-INFORMATION-QUERYING"
"DISABLE-NRQL-WARNINGS"
"ENABLE-NRQL-WARNINGS"
"DISABLE-KB-HAS-CHANGED-WARNING-TOKENS"
"ENABLE-KB-HAS-CHANGED-WARNING-TOKENS"
"DISABLE-PHASE-TWO-STARTS-WARNING-TOKENS"
"ENABLE-PHASE-TWO-STARTS-WARNING-TOKENS"
"DISABLE-TWO-PHASE-QUERY-PROCESSING-MODE"
"ENABLE-TWO-PHASE-QUERY-PROCESSING-MODE"
"DISABLE-ABOX-MIRRORING"
"ENABLE-VERY-SMART-ABOX-MIRRORING"
"ENABLE-SMART-ABOX-MIRRORING"
"ENABLE-ABOX-MIRRORING"
"DISABLE-SQL-DATA-SUBSTRATE-MIRRORING"
"ENABLE-SQL-DATA-SUBSTRATE-MIRRORING"
"DISABLE-DATA-SUBSTRATE-MIRRORING"
"ENABLE-DATA-SUBSTRATE-MIRRORING"
"WAIT-FOR-RULES-TO-TERMINATE"
"WAIT-FOR-QUERIES-TO-TERMINATE"
"DESCRIBE-ALL-RULES"
"DESCRIBE-ALL-QUERIES"
"GET-ALL-ANSWERS"
"GET-ANSWER-SIZE"
"RUN-ALL-RULES"
"REEXECUTE-ALL-RULES"
"EXECUTE-ALL-RULES"
"RUN-ALL-QUERIES"
"REEXECUTE-ALL-QUERIES"
"EXECUTE-ALL-QUERIES"
"ABORT-ALL-RULES"
"ABORT-ALL-QUERIES"
"TERMINATED-RULES"
"INACTIVE-RULES"
"PROCESSED-RULES"
"TERMINATED-QUERIES"
"INACTIVE-QUERIES"
"PROCESSED-QUERIES"
"WAITING-EXPENSIVE-RULES"
"WAITING-CHEAP-RULES"
"WAITING-RULES"
"WAITING-EXPENSIVE-QUERIES"
"WAITING-CHEAP-QUERIES"
"WAITING-QUERIES"
"RUNNING-EXPENSIVE-RULES"
"RUNNING-CHEAP-RULES"
"RUNNING-RULES"
"RUNNING-EXPENSIVE-QUERIES"
"RUNNING-CHEAP-QUERIES"
"RUNNING-QUERIES"
"ACTIVE-EXPENSIVE-RULES"
"ACTIVE-CHEAP-RULES"
"ACTIVE-RULES"
"ACTIVE-EXPENSIVE-QUERIES"
"ACTIVE-CHEAP-QUERIES"
"ACTIVE-QUERIES"
"PREPARED-RULES"
"READY-RULES"
"PREPARED-QUERIES"
"READY-QUERIES"
"EXPENSIVE-RULES"
"CHEAP-RULES"
"INACCURATE-RULES"
"ACCURATE-RULES"
"ALL-RULES"
"EXPENSIVE-QUERIES"
"CHEAP-QUERIES"
"INACCURATE-QUERIES"
"ACCURATE-QUERIES"
"ALL-QUERIES"
"DESCRIBE-ALL-DEFINITIONS"
"DESCRIBE-DEFINITION"
"DELETE-ALL-DEFINITIONS"
"UNDEFINE-QUERY"
"DEFINE-AND-PREPARE-QUERY"
"DEFINE-AND-EXECUTE-QUERY"
"DEFINE-QUERY"
"RACER-PREPARE-TBOX-QUERY"
"RACER-ANSWER-TBOX-QUERY"
"RACER-PREPARE-RULE"
"RACER-APPLY-RULE"
"PREPARE-NRQL-ENGINE"
"RACER-PREPARE-QUERY"
"RACER-ANSWER-QUERY-UNDER-PREMISE"
"RACER-ANSWER-QUERY"
"FULL-RESET"
"RESET-NRQL-ENGINE"
"RESET-ALL-SUBSTRATES"
"DELETE-ALL-RULES"
"DELETE-ALL-QUERIES"
"SET-TUPLE-BOUND"
"DESCRIBE-RULE"
"DESCRIBE-QUERY"
"GET-DAG-OF-QBOX-FOR-ABOX"
"SHOW-QBOX-FOR-ABOX"
"GET-NODES-IN-QBOX-FOR-ABOX"
"GET-NODES-IN-CURRENT-QBOX"
"GET-DAG-OF-CURRENT-QBOX"
"QUERY-EQUIVALENTS"
"QUERY-DESCENDANTS"
"QUERY-CHILDREN"
"QUERY-ANCESTORS"
"QUERY-PARENTS"
"QUERY-EQUIVALENT-P"
"QUERY-ENTAILS-P"
"CLASSIFY-QUERY"
"QUERY-TAUTOLOGICAL-P"
"QUERY-INCONSISTENT-P"
"QUERY-CONSISTENT-P"
"ABORT-RULE"
"ABORT-QUERY"
"ORIGINAL-RULE-BODY"
"ORIGINAL-QUERY-BODY"
"RULE-BODY"
"QUERY-BODY"
"ORIGINAL-RULE-HEAD"
"ORIGINAL-QUERY-HEAD"
"RULE-HEAD"
"QUERY-HEAD"
"RULE-ACCURATE-P"
"QUERY-ACCURATE-P"
"GET-ANSWER"
"GET-ALL-REMAINING-SETS-OF-RULE-CONSEQUENCES"
"GET-ALL-REMAINING-TUPLES"
"GET-NEXT-N-REMAINING-SETS-OF-RULE-CONSEQUENCES"
"GET-NEXT-N-REMAINING-TUPLES"
"DESCRIBE-RULE-STATUS"
"DESCRIBE-QUERY-STATUS"
"RULE-INACTIVE-P"
"RULE-PROCESSED-P"
"QUERY-INACTIVE-P"
"QUERY-PROCESSED-P"
"ACTIVE-EXPENSIVE-RULE-P"
"ACTIVE-EXPENSIVE-QUERY-P"
"CHEAP-RULE-P"
"CHEAP-QUERY-P"
"RULE-ACTIVE-P"
"QUERY-ACTIVE-P"
"RULE-WAITING-P"
"QUERY-WAITING-P"
"EXECUTE-APPLICABLE-RULES"
"UNAPPLICABLE-RULES"
"APPLICABLE-RULES"
"ADD-CHOSEN-SETS-OF-RULE-CONSEQUENCES"
"CHOOSE-CURRENT-SET-OF-RULE-CONSEQUENCES"
"RULE-APPLICABLE-P"
"RULE-PREPARED-P"
"QUERY-PREPARED-P"
"REEXECUTE-RULE"
"REEXECUTE-QUERY"
"REPREPARE-RULE"
"REPREPARE-QUERY"
"EXECUTE-RULE"
"EXECUTE-QUERY"
"RULE-READY-P"
"QUERY-READY-P"
"NEXT-SET-OF-RULE-CONSEQUENCES-AVAILABLE-P"
"NEXT-TUPLE-AVAILABLE-P"
"GET-CURRENT-SET-OF-RULE-CONSEQUENCES"
"GET-NEXT-SET-OF-RULE-CONSEQUENCES"
"GET-CURRENT-TUPLE"
"GET-NEXT-TUPLE"
"DELETE-RULE"
"DELETE-QUERY"
"DEL-RCC-EDGE"
"DEL-RCC-NODE"
"RCC-EDGE-LABEL"
"RCC-NODE-LABEL"
"RCC-EDGE"
"RCC-NODE"
"RCC-RELATED"
"RCC-INSTANCE"
"RCC-CONSISTENT?"
"IN-RCC-BOX"
"IN-MIRROR-DATA-BOX"
"DESCRIPTION-IMPLIES?"
"EDGE-LABEL"
"NODE-LABEL"
"DEL-DATA-EDGE"
"DEL-DATA-NODE"
"DATA-EDGE"
"DATA-NODE"
"IN-DATA-BOX"
"UNDEFQUERY"
"DEF-AND-EXEC-QUERY"
"DEF-AND-PREP-QUERY"
"DEFQUERY"
"PREPRULE"
"FIRERULE"
"PREPARE-ABOX-RULE"
"PREPARE-TBOX-QUERY"
"PREPARE-ABOX-QUERY"
"APPLY-ABOX-RULE"
"TBOX-RETRIEVE"
"RETRIEVE-UNDER-PREMISE"
"RETRIEVE"
"WITH-NRQL-SETTINGS"))
(DEFCONSTANT +NRQL-SYMBOLS+ (QUOTE
("WITH-NRQL-STANDARD-SETTINGS"
"RACER-RETRIEVE-INDIVIDUAL-FILLED-ROLES"
"RACER-RETRIEVE-INDIVIDUAL-FILLERS"
"RACER-RETRIEVE-RELATED-INDIVIDUALS"
"XML-OUTPUT"
"XML-INPUT"
"LISP-TO-XML"
"XML-TO-LISP"
"BIND-INDIVIDUAL"
"INV"
"NOT"
"NEG"
"AND"
"OR"
"SATISFIES"
"TOP"
"BOTTOM"
"TRUE-QUERY"
"FALSE-QUERY"
"CONSTRAINT"
"HAS-KNOWN-SUCCESSOR"
"SUBSTITUTE"
"INSERT"
"SAME-AS"
"EQUAL"
"="
"INTERSECTION"
"UNION"
"CAP"
"CUP"
"TOLD-VALUE"
"TOLD-VALUES"
"TOLD-FILLER"
"TOLD-FILLERS"
"FILLER"
"FILLERS"
"DATATYPE-FILLER"
"DATATYPE-FILLERS"
"BINDINGS-FROM"
"ANNOTATION"
"ANNOTATIONS"
"NO-TOLD-VALUE"
"NO-KNOWN-CD-OBJECTS"
"PROJECT"
"PROJECT-TO"
"PI"
"REAL-TOP"
"REAL-BOTTOM"
"STORE-SUBSTRATE-FOR-CURRENT-ABOX"
"RESTORE-ALL-SUBSTRATES"
"RESTORE-SUBSTRATE"
"STORE-ALL-SUBSTRATES"
"STORE-SUBSTRATE-FOR-ABOX"
"GET-NRQL-VERSION"
"DEL-RCC-EDGE1"
"DEL-RCC-NODE1"
"RCC-EDGE-LABEL1"
"RCC-NODE-LABEL1"
"RCC-EDGE1"
"RCC-NODE1"
"RCC-RELATED1"
"RCC-INSTANCE1"
"RCC-CONSISTENT-P"
"CREATE-RCC-EDGE"
"CREATE-RCC-NODE"
"SET-RCC-BOX"
"SET-MIRROR-DATA-BOX"
"DESCRIPTION-IMPLIES-P"
"SET-DATA-BOX"
"GET-DATA-EDGE-LABEL"
"GET-DATA-NODE-LABEL"
"DELETE-DATA-EDGE"
"DELETE-DATA-NODE"
"CREATE-DATA-EDGE"
"CREATE-DATA-NODE"
"GET-PROCESS-POOL-SIZE"
"GET-MAXIMUM-SIZE-OF-PROCESS-POOL"
"GET-INITIAL-SIZE-OF-PROCESS-POOL"
"SET-MAXIMUM-SIZE-OF-PROCESS-POOL"
"SET-INITIAL-SIZE-OF-PROCESS-POOL"
"SET-REWRITE-DEFINED-CONCEPTS"
"SET-NRQL-MODE"
"SHOW-CURRENT-QBOX"
"GET-ABOX-OF-CURRENT-QBOX"
"DISABLE-QUERY-REALIZATION"
"ENABLE-QUERY-REALIZATION"
"OPTIMIZER-DONT-USE-CARDINALITY-HEURISTICS"
"OPTIMIZER-USE-CARDINALITY-HEURISTICS"
"DISABLE-QUERY-OPTIMIZATION"
"ENABLE-QUERY-OPTIMIZATION"
"DISABLE-QUERY-REPOSITORY"
"ENABLE-QUERY-REPOSITORY"
"DONT-REPORT-TAUTOLOGICAL-QUERIES"
"REPORT-TAUTOLOGICAL-QUERIES"
"DONT-REPORT-INCONSISTENT-QUERIES"
"REPORT-INCONSISTENT-QUERIES"
"DESCRIBE-QUERY-PROCESSING-MODE"
"DESCRIBE-CURRENT-SUBSTRATE"
"INCLUDE-PERMUTATIONS"
"EXCLUDE-PERMUTATIONS"
"DONT-ADD-RULE-CONSEQUENCES-AUTOMATICALLY"
"ADD-RULE-CONSEQUENCES-AUTOMATICALLY"
"PROCESS-SET-AT-A-TIME"
"PROCESS-TUPLE-AT-A-TIME"
"GET-MAX-NO-OF-TUPLES-BOUND"
"SET-MAX-NO-OF-TUPLES-BOUND"
"DONT-CHECK-ABOX-CONSISTENCY-BEFORE-QUERYING"
"CHECK-ABOX-CONSISTENCY-BEFORE-QUERYING"
"ENABLE-LAZY-TUPLE-COMPUTATION"
"ENABLE-EAGER-TUPLE-COMPUTATION"
"RESTORE-STANDARD-SETTINGS"
"DONT-ADD-ROLE-ASSERTIONS-FOR-DATATYPE-PROPERTIES"
"ADD-ROLE-ASSERTIONS-FOR-DATATYPE-PROPERTIES"
"DISABLE-TOLD-INFORMATION-QUERYING"
"ENABLE-TOLD-INFORMATION-QUERYING"
"DISABLE-NRQL-WARNINGS"
"ENABLE-NRQL-WARNINGS"
"DISABLE-KB-HAS-CHANGED-WARNING-TOKENS"
"ENABLE-KB-HAS-CHANGED-WARNING-TOKENS"
"DISABLE-PHASE-TWO-STARTS-WARNING-TOKENS"
"ENABLE-PHASE-TWO-STARTS-WARNING-TOKENS"
"DISABLE-TWO-PHASE-QUERY-PROCESSING-MODE"
"ENABLE-TWO-PHASE-QUERY-PROCESSING-MODE"
"DISABLE-ABOX-MIRRORING"
"ENABLE-VERY-SMART-ABOX-MIRRORING"
"ENABLE-SMART-ABOX-MIRRORING"
"ENABLE-ABOX-MIRRORING"
"DISABLE-SQL-DATA-SUBSTRATE-MIRRORING"
"ENABLE-SQL-DATA-SUBSTRATE-MIRRORING"
"DISABLE-DATA-SUBSTRATE-MIRRORING"
"ENABLE-DATA-SUBSTRATE-MIRRORING"
"WAIT-FOR-RULES-TO-TERMINATE"
"WAIT-FOR-QUERIES-TO-TERMINATE"
"DESCRIBE-ALL-RULES"
"DESCRIBE-ALL-QUERIES"
"GET-ALL-ANSWERS"
"GET-ANSWER-SIZE"
"RUN-ALL-RULES"
"REEXECUTE-ALL-RULES"
"EXECUTE-ALL-RULES"
"RUN-ALL-QUERIES"
"REEXECUTE-ALL-QUERIES"
"EXECUTE-ALL-QUERIES"
"ABORT-ALL-RULES"
"ABORT-ALL-QUERIES"
"TERMINATED-RULES"
"INACTIVE-RULES"
"PROCESSED-RULES"
"TERMINATED-QUERIES"
"INACTIVE-QUERIES"
"PROCESSED-QUERIES"
"WAITING-EXPENSIVE-RULES"
"WAITING-CHEAP-RULES"
"WAITING-RULES"
"WAITING-EXPENSIVE-QUERIES"
"WAITING-CHEAP-QUERIES"
"WAITING-QUERIES"
"RUNNING-EXPENSIVE-RULES"
"RUNNING-CHEAP-RULES"
"RUNNING-RULES"
"RUNNING-EXPENSIVE-QUERIES"
"RUNNING-CHEAP-QUERIES"
"RUNNING-QUERIES"
"ACTIVE-EXPENSIVE-RULES"
"ACTIVE-CHEAP-RULES"
"ACTIVE-RULES"
"ACTIVE-EXPENSIVE-QUERIES"
"ACTIVE-CHEAP-QUERIES"
"ACTIVE-QUERIES"
"PREPARED-RULES"
"READY-RULES"
"PREPARED-QUERIES"
"READY-QUERIES"
"EXPENSIVE-RULES"
"CHEAP-RULES"
"INACCURATE-RULES"
"ACCURATE-RULES"
"ALL-RULES"
"EXPENSIVE-QUERIES"
"CHEAP-QUERIES"
"INACCURATE-QUERIES"
"ACCURATE-QUERIES"
"ALL-QUERIES"
"DESCRIBE-ALL-DEFINITIONS"
"DESCRIBE-DEFINITION"
"DELETE-ALL-DEFINITIONS"
"UNDEFINE-QUERY"
"DEFINE-AND-PREPARE-QUERY"
"DEFINE-AND-EXECUTE-QUERY"
"DEFINE-QUERY"
"RACER-PREPARE-TBOX-QUERY"
"RACER-ANSWER-TBOX-QUERY"
"RACER-PREPARE-RULE"
"RACER-APPLY-RULE"
"PREPARE-NRQL-ENGINE"
"RACER-PREPARE-QUERY"
"RACER-ANSWER-QUERY-UNDER-PREMISE"
"RACER-ANSWER-QUERY"
"FULL-RESET"
"RESET-NRQL-ENGINE"
"RESET-ALL-SUBSTRATES"
"DELETE-ALL-RULES"
"DELETE-ALL-QUERIES"
"SET-TUPLE-BOUND"
"DESCRIBE-RULE"
"DESCRIBE-QUERY"
"GET-DAG-OF-QBOX-FOR-ABOX"
"SHOW-QBOX-FOR-ABOX"
"GET-NODES-IN-QBOX-FOR-ABOX"
"GET-NODES-IN-CURRENT-QBOX"
"GET-DAG-OF-CURRENT-QBOX"
"QUERY-EQUIVALENTS"
"QUERY-DESCENDANTS"
"QUERY-CHILDREN"
"QUERY-ANCESTORS"
"QUERY-PARENTS"
"QUERY-EQUIVALENT-P"
"QUERY-ENTAILS-P"
"CLASSIFY-QUERY"
"QUERY-TAUTOLOGICAL-P"
"QUERY-INCONSISTENT-P"
"QUERY-CONSISTENT-P"
"ABORT-RULE"
"ABORT-QUERY"
"ORIGINAL-RULE-BODY"
"ORIGINAL-QUERY-BODY"
"RULE-BODY"
"QUERY-BODY"
"ORIGINAL-RULE-HEAD"
"ORIGINAL-QUERY-HEAD"
"RULE-HEAD"
"QUERY-HEAD"
"RULE-ACCURATE-P"
"QUERY-ACCURATE-P"
"GET-ANSWER"
"GET-ALL-REMAINING-SETS-OF-RULE-CONSEQUENCES"
"GET-ALL-REMAINING-TUPLES"
"GET-NEXT-N-REMAINING-SETS-OF-RULE-CONSEQUENCES"
"GET-NEXT-N-REMAINING-TUPLES"
"DESCRIBE-RULE-STATUS"
"DESCRIBE-QUERY-STATUS"
"RULE-INACTIVE-P"
"RULE-PROCESSED-P"
"QUERY-INACTIVE-P"
"QUERY-PROCESSED-P"
"ACTIVE-EXPENSIVE-RULE-P"
"ACTIVE-EXPENSIVE-QUERY-P"
"CHEAP-RULE-P"
"CHEAP-QUERY-P"
"RULE-ACTIVE-P"
"QUERY-ACTIVE-P"
"RULE-WAITING-P"
"QUERY-WAITING-P"
"EXECUTE-APPLICABLE-RULES"
"UNAPPLICABLE-RULES"
"APPLICABLE-RULES"
"ADD-CHOSEN-SETS-OF-RULE-CONSEQUENCES"
"CHOOSE-CURRENT-SET-OF-RULE-CONSEQUENCES"
"RULE-APPLICABLE-P"
"RULE-PREPARED-P"
"QUERY-PREPARED-P"
"REEXECUTE-RULE"
"REEXECUTE-QUERY"
"REPREPARE-RULE"
"REPREPARE-QUERY"
"EXECUTE-RULE"
"EXECUTE-QUERY"
"RULE-READY-P"
"QUERY-READY-P"
"NEXT-SET-OF-RULE-CONSEQUENCES-AVAILABLE-P"
"NEXT-TUPLE-AVAILABLE-P"
"GET-CURRENT-SET-OF-RULE-CONSEQUENCES"
"GET-NEXT-SET-OF-RULE-CONSEQUENCES"
"GET-CURRENT-TUPLE"
"GET-NEXT-TUPLE"
"DELETE-RULE"
"DELETE-QUERY"
"DEL-RCC-EDGE"
"DEL-RCC-NODE"
"RCC-EDGE-LABEL"
"RCC-NODE-LABEL"
"RCC-EDGE"
"RCC-NODE"
"RCC-RELATED"
"RCC-INSTANCE"
"RCC-CONSISTENT?"
"IN-RCC-BOX"
"IN-MIRROR-DATA-BOX"
"DESCRIPTION-IMPLIES?"
"EDGE-LABEL"
"NODE-LABEL"
"DEL-DATA-EDGE"
"DEL-DATA-NODE"
"DATA-EDGE"
"DATA-NODE"
"IN-DATA-BOX"
"UNDEFQUERY"
"DEF-AND-EXEC-QUERY"
"DEF-AND-PREP-QUERY"
"DEFQUERY"
"PREPRULE"
"FIRERULE"
"PREPARE-ABOX-RULE"
"PREPARE-TBOX-QUERY"
"PREPARE-ABOX-QUERY"
"APPLY-ABOX-RULE"
"TBOX-RETRIEVE"
"RETRIEVE-UNDER-PREMISE"
"RETRIEVE"
"WITH-NRQL-SETTINGS"))) | 26,883 | Common Lisp | .lisp | 1 | 26,883 | 26,883 | 0.381431 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 4c14aeff1102cf5918e684632955a611fbcd4ac1bfaaf65ff3c435d18106c0d2 | 12,484 | [
-1
] |
12,485 | qbox-browser.lisp | lambdamikel_DLMAPS/src/tools/qbox-browser.lisp | (in-package :TOOLS)
(defvar *node* nil)
(define-application-frame qbox-browser ()
((qbox :initarg :qbox
:accessor qbox)
(show-equivalents-p :initform t)
(variable-vectors-p :initform t)
(show-top-p :initform t)
(show-bottom-p :initform t)
(app-stream :initform nil :accessor app-stream))
(:panes
(display :application
:display-function 'draw-display
:display-after-commands t)
(info :application
:scroll-bars :both
:end-of-line-action :allow
:end-of-page-action :allow
:display-after-commands t)
(options :accept-values
:scroll-bars nil
:display-function
`(accept-values-pane-displayer
:displayer ,#'(lambda (frame stream)
(accept-options frame stream)))))
(:layouts
(:defaults
(vertically ()
(1/10 options)
(5/10 display)
(4/10 info)))))
(defmethod accept-options ((frame qbox-browser) stream)
(with-slots (show-equivalents-p
variable-vectors-p
show-top-p show-bottom-p) frame
(formatting-table (stream :multiple-columns t)
(formatting-row (stream)
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'boolean
:prompt "Show Equivalents"
:prompt-mode :raw
:stream stream
:default show-equivalents-p)
(setf show-equivalents-p object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'boolean
:prompt "Show Variable Vectors"
:prompt-mode :raw
:stream stream
:default variable-vectors-p)
(setf variable-vectors-p object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'boolean
:prompt "Show Top"
:prompt-mode :raw
:stream stream
:default show-top-p)
(setf show-top-p object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'boolean
:prompt "Show Bottom"
:prompt-mode :raw
:stream stream
:default show-bottom-p)
(setf show-bottom-p object)))))))
(defmethod draw-display ((frame qbox-browser) stream)
(with-slots (show-bottom-p show-top-p qbox) frame
(format-graph-from-roots
(if show-top-p
(list (thematic-substrate::top-query qbox))
(thematic-substrate::children (thematic-substrate::top-query qbox)))
#'draw-node
#'(lambda (x)
(if (not show-bottom-p)
(remove-if #'thematic-substrate::is-bottom-query-p
(thematic-substrate::children x))
(thematic-substrate::children x)))
:center-nodes t
:orientation :down
:stream stream
:graph-type :directed-acyclic-graph
:merge-duplicates t
:arc-drawer
#'(lambda (stream from-object
to-object x1 y1
x2 y2
&rest
drawing-options)
(declare (dynamic-extent
drawing-options))
(declare (ignore from-object
to-object))
(apply #'draw-arrow* stream
x1 y1 x2 y2 drawing-options))
:merge-duplicates t)
(setf (app-stream frame) stream)))
(define-presentation-type node ())
(defun draw-node (object stream)
(with-slots (variable-vectors-p show-equivalents-p) *application-frame*
(labels ((draw-it (stream)
(let ((*print-right-margin* 40)
(*print-pretty* t))
(if show-equivalents-p
(if variable-vectors-p
(format stream "~A~%~A~%~A"
(thematic-substrate::all-vois object)
(thematic-substrate::unparse-query object)
(thematic-substrate::equivalents object))
(format stream "~A~%~A"
(thematic-substrate::unparse-query object)
(thematic-substrate::equivalents object)))
(if variable-vectors-p
(format stream "~A~%~A"
(thematic-substrate::all-vois object)
(thematic-substrate::unparse-query object))
(format stream "~A"
(thematic-substrate::unparse-query object)))))))
(with-output-as-presentation (stream object 'node)
(if (not (thematic-substrate::unique-name-assumption-p object))
(surrounding-output-with-border
(stream :shape :rectangle)
(surrounding-output-with-border
(stream :shape :rectangle)
(draw-it stream)))
(surrounding-output-with-border
(stream :shape :rectangle)
(draw-it stream)))))))
(define-qbox-browser-command (exit :menu "Exit") ()
(frame-exit *application-frame*))
(define-qbox-browser-command (inspect-node
:menu "Inspect"
:name "Inspect")
((node 'node :gesture :select))
(let ((*standard-output* (get-frame-pane *application-frame* 'info))
(*print-length* nil)
(*print-depth* nil)
(*print-pretty* t))
(setf *node* node)
(window-clear *standard-output*)
(describe-object node *standard-output*)))
(defun qbox-browser (qbox &optional (port (find-port)))
(let ((qbox-browser (make-application-frame 'qbox-browser
:frame-manager
(find-frame-manager :port port)
:width 800
:height 600
:qbox qbox)))
(run-frame-top-level qbox-browser)))
(defun show-qbox (qbox)
(when qbox
(qbox-browser qbox)))
| 6,030 | Common Lisp | .lisp | 155 | 26.709677 | 96 | 0.554726 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 1b87f5bb889b14aed30155269b813496e34fa513ab49faffbe2e448ff0ce029c | 12,485 | [
-1
] |
12,486 | gui-tools.lisp | lambdamikel_DLMAPS/src/tools/gui-tools.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GUI-TOOLS; Base: 10 -*-
(in-package gui-tools)
#+:mcl
(defun file-selector (title directory pattern &key save)
(declare (ignore title))
(loop
(let ((pathname
(ccl:catch-cancel
(if (not save)
(ccl:choose-file-dialog :directory directory)
(ccl:choose-new-file-dialog :directory directory)))))
(cond ((eq pathname :cancel)
(return nil))
((string-equal (pathname-type pathname) pattern)
(return pathname))
(t (ccl:message-dialog
(format nil "Required File Extension: ~A" pattern)))))))
#+:allegro
(defun file-selector (title directory pattern &key (save nil))
(with-application-frame (frame)
(loop
(let ((file (select-file frame
:pattern (concatenate 'string "*." pattern)
:title title
:directory (namestring
(truename directory)))))
(if file
(when (and file (not (string= "" file)))
(cond ((char= (elt file
(1- (length file)))
#\/)
(notify-user frame
"You must select a file, not a directory!"
:style :error))
((not (string= (subseq file (- (length file) (length pattern)))
pattern))
(notify-user frame
(format nil "Required File Extension: ~A" pattern)
:style :error))
(save
(when (=> (probe-file file)
(notify-user frame
(format nil "Overwrite ~A?" file)
:style :warning))
(return file)))
((and (not save)
(probe-file file))
(return file))
(t
(notify-user frame
(format nil "File ~A does not exist" file)
:style :error))))
(return nil))))))
#+:lispworks
(defun file-selector (title directory pattern &key (save nil))
(with-application-frame (frame)
(loop
(let ((file (select-file frame
:pattern (concatenate 'string "*." pattern)
:title title
:directory (directory-namestring
(translate-logical-pathname directory)))))
(if file
(let ((file (namestring file)))
(when (and file (not (string= "" file)))
(cond ((char= (elt file
(1- (length file)))
#\/)
(notify-user frame
"You must select a file, not a directory!"
:style :error))
((not (string= (subseq file (- (length file) (length pattern)))
pattern))
(notify-user frame
(format nil "Required File Extension: ~A" pattern)
:style :error))
(save
(when (=> (probe-file file)
(notify-user frame
(format nil "Overwrite ~A?" file)
:style :warning))
(return file)))
((and (not save)
(probe-file file))
(return file))
(t
(notify-user frame
(format nil "File ~A does not exist" file)
:style :error)))))
(return nil))))))
#+:mcl
(defmacro mcl-pane (&body body)
`(outlining ()
,@body))
(defun inverse-highlighter (type record stream state)
(declare (ignore state type))
(multiple-value-bind (xoff yoff)
(convert-from-relative-to-absolute-coordinates
stream (output-record-parent record))
(with-bounding-rectangle* (left top right bottom) record
(draw-rectangle* stream
(+ left xoff) (+ top yoff)
(+ right xoff) (+ bottom yoff)
:ink +flipping-ink+))))
(defmacro with-centering ((stream) &body body)
(let ((x (gensym)))
`(multiple-value-bind (,x)
(window-inside-size ,stream)
(formatting-table (stream)
(formatting-row (stream)
(formatting-cell (stream :align-x :center
:align-y :center
:min-width ,x)
,@body)))
(terpri stream))))
(defmacro with-border ((stream &key (offset 0)) &body body)
(let ((or (gensym)))
`(let ((,or
(with-output-to-output-record (,stream)
,@body)))
(draw-rectangle* ,stream
(- (bounding-rectangle-min-x ,or) ,offset)
(- (bounding-rectangle-min-y ,or) ,offset)
(+ (bounding-rectangle-max-x ,or) ,offset)
(+ (bounding-rectangle-max-y ,or) ,offset)
:line-dashes '(1 1)
:filled nil)
,@body)))
(defmacro draw-marker* (stream x y radius &rest args)
`(let ((x ,x)
(y ,y)
(r ,radius))
(clim:draw-rectangle* ,stream
(- x r)
(- y r)
(+ x r)
(+ y r)
:line-thickness 1
:filled nil ,@args)
(clim:draw-line* stream
(- x r)
(- y r)
(+ x r)
(+ y r)
:line-thickness 1
,@args)
(clim:draw-line* stream
(- x r)
(+ y r)
(+ x r)
(- y r)
:line-thickness 1
,@args)))
(defun get-size-of-graphic (stream fn)
(let ((or
(with-output-to-output-record (stream)
(funcall fn))))
(values
(bounding-rectangle-width or)
(bounding-rectangle-height or))))
#+:lispworks
(defmacro with-correct-clipping ((stream) &body body)
`(multiple-value-bind (window-width window-height)
(clim:bounding-rectangle-size (clim:bounding-rectangle (clim:window-viewport ,stream)))
(clim:with-drawing-options (,stream :clipping-region
(clim:make-bounding-rectangle 0 0 window-width window-height))
,@body)))
#-:lispworks
(defmacro with-correct-clipping ((stream) &body body)
body)
| 6,500 | Common Lisp | .lisp | 170 | 24.529412 | 103 | 0.475428 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | bbbd0f03fb29a194c356d8dc24ebf000b2756f4152b06a38b90a3bb23c11b3d1 | 12,486 | [
-1
] |
12,487 | dag3.lisp | lambdamikel_DLMAPS/src/tools/dag3.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: DAG; Base: 10 -*-
(in-package :DAG)
;;;
;;;
;;;
(defvar *node* nil)
(defvar *type* :directed-acyclic-graph)
#+:RACER
(defmacro defpersistentclass (&rest rest)
`(progn ,@(let ((name (first rest)))
(list
`(PERSISTENCE-MANAGER:DEFCLASS ,@rest)
`(defun ,(intern (string-upcase (format nil "is-~A-p" name))) (obj)
(typep obj ',name))))))
#-:RACER
(defmacro defpersistentclass (&rest rest)
`(progn ,@(let ((name (first rest)))
(list
`(DEFCLASS ,@rest)
`(defun ,(intern (string-upcase (format nil "is-~A-p" name))) (obj)
(typep obj ',name))))))
(defpersistentclass dag ()
(#+:clim
(gprinter :accessor gprinter :initarg :gprinter :initform 'draw-dag-node)
(tprinter :accessor tprinter :initarg :tprinter :initform 'dag-node-name)
(dag-name :accessor dag-name :initarg :name)
(dag-nodes :accessor dag-nodes :initform nil :initarg :nodes)))
;;;
;;;
;;;
(defmethod dag-roots ((dag dag))
(remove-if #'dag-node-parents (dag-nodes dag)))
(defmethod dag-top ((dag dag))
(let ((roots
(dag-roots dag)))
(when (and roots (not (cdr roots)))
(first roots))))
;;;
;;;
;;;
(defmethod dag-leaves ((dag dag))
(remove-if #'dag-node-children (dag-nodes dag)))
(defmethod dag-bottom ((dag dag))
(let ((leaves
(dag-leaves dag)))
(when (and leaves (not (cdr leaves)))
(first leaves))))
;;;
;;;
;;;
(defpersistentclass dag-node ()
((dag-node-name :accessor dag-node-name :initarg :name :initform nil)
(in-dag :accessor in-dag :initarg :in-dag :initform nil)
(dag-node-ancestors)
(dag-node-descendants)
(dag-node-children :accessor dag-node-children :initarg :children :initform nil)
(dag-node-parents :accessor dag-node-parents :initarg :parents :initform nil)
(dag-node-marked-p :accessor dag-node-marked-p :initarg :dag-node-marked-p :initform nil)))
(defpersistentclass node-proxy (dag-node)
((for-node :accessor for-node :initform nil :initarg :for-node)))
;;;
;;;
;;;
(defmethod copy-dag-node ((node dag-node))
(make-instance 'node-proxy :for-node node))
(defmethod copy-dag-node ((node node-proxy))
(make-instance 'node-proxy :for-node (for-node node)))
;;;
;;;
;;;
(defmethod dag-node-ancestors ((node dag-node))
(unless (slot-boundp node 'dag-node-ancestors)
(compute-transitive-closure (in-dag node)))
(slot-value node 'dag-node-ancestors))
(defmethod dag-node-descendants ((node dag-node))
(unless (slot-boundp node 'dag-node-descendants)
(compute-transitive-closure (in-dag node)))
(slot-value node 'dag-node-descendants))
;;;
;;;
;;;
(defun make-dag (&rest args &key (type 'dag) &allow-other-keys)
(apply #'make-instance type :allow-other-keys t args))
(defmethod make-dag-node (&rest args &key (type 'dag-node) &allow-other-keys)
(apply #'make-instance type :allow-other-keys t args))
;;;
;;;
;;;
(defmethod insert-dag-node ((dag dag) (node dag-node))
(let ((parents (dag-node-parents node))
(children (dag-node-children node)))
(setf (in-dag node) dag)
;; (format t "~%Node: ~A Parents: ~A Children: ~A" node parents children))
(dolist (parent parents)
(setf (dag-node-children parent)
(remove-duplicates
(cons node (set-difference (dag-node-children parent) children)))))
(dolist (child children)
(setf (dag-node-parents child)
(remove-duplicates
(cons node (set-difference (dag-node-parents child) parents)))))
(push node (dag-nodes dag))
(dolist (node (dag-nodes dag))
(slot-makunbound node 'dag-node-descendants)
(slot-makunbound node 'dag-node-ancestors))
dag))
(defmethod delete-dag-node ((dag dag) (node dag-node))
(let ((parents (dag-node-parents node))
(children (dag-node-children node)))
(dolist (child children)
(setf (dag-node-parents child)
(append (delete node (dag-node-parents child))
(dag-node-parents node))))
(dolist (parent parents)
(setf (dag-node-children parent)
(append (delete node (dag-node-children parent))
(dag-node-children node))))
(setf (dag-nodes dag)
(delete node (dag-nodes dag)))
(dolist (node (dag-nodes dag))
(setf (slot-value node 'dag-node-descendants) nil
(slot-value node 'dag-node-ancestors) nil))
dag))
;;;
;;;
;;;
(defmethod unmark-all-dag-nodes ((dag dag))
(dolist (node (dag-nodes dag))
(unmark-dag-node node)))
(defmethod mark-all-dag-nodes ((dag dag) &optional (val t))
(dolist (node (dag-nodes dag))
(mark-dag-node node val)))
;;;
;;;
;;;
(defmethod mark-dag-node ((node dag-node) &optional (val t))
(setf (dag-node-marked-p node) val))
(defmethod unmark-dag-node ((node dag-node))
(setf (dag-node-marked-p node) nil))
;;;
;;;
;;;
(defmethod print-object ((node dag-node) stream)
(format stream "#<~A ~A>"
(type-of node)
(dag-node-name node)))
(defmethod print-object ((dag dag) stream)
(format stream "#<~A ~A>"
(type-of dag)
(dag-name dag)))
;;;
;;;
;;;
(defmethod show-dag ((dag dag) stream &key (printer (tprinter dag)))
(labels ((do-it (node &optional (level 0) next)
(format stream ";;;")
(if (= level 0)
(format stream " ~A~%" (funcall printer node))
(progn
(dolist (item (butlast next))
(if item
(format stream " |")
(format stream " ")))
(let ((last (first (last next))))
(if last
(format stream " |---~A~%" (funcall printer node))
(format stream " \\___~A~%" (funcall printer node))))))
(let ((last (first (last (dag-node-children node)))))
(dolist (child (dag-node-children node))
(do-it child (1+ level) (append next (list (not (eq child last)))))))))
;; (format stream "~%~%")
(dolist (root (dag-roots dag))
(do-it root)
(terpri))))
;;;
;;;
;;;
(defmethod node-equivalent-p ((a dag-node) (b dag-node))
(equal (dag-node-name a)
(dag-node-name b)))
;;;
;;;
;;;
(defmethod dag-isomorphic-p ((dag1 dag) (dag2 dag))
(labels ((matches-p (a b)
(and (node-equivalent-p a b)
(let ((as (dag-node-children a))
(bs (dag-node-children b)))
(when (= (length as) (length bs))
(setf as (sort as #'string-lessp :key #'dag-node-name))
(setf bs (sort bs #'string-lessp :key #'dag-node-name))
(every #'matches-p
(dag-node-children a)
(dag-node-children b)))))))
(or (eq dag1 dag2)
(let ((as (dag-roots dag1))
(bs (dag-roots dag2)))
(when (= (length as) (length bs))
(setf as (sort as #'string-lessp :key #'dag-node-name))
(setf bs (sort bs #'string-lessp :key #'dag-node-name))
(every #'matches-p
as
bs))))))
;;;
;;;
;;;
#+:clim
(defmethod create-clos-classes ((dag dag))
(labels ((do-it (node)
(eval `(cl:defclass ,(dag-node-name node)
,(mapcar #'(lambda (x)
(dag-node-name x))
(dag-node-parents node))))))
(mapc #'do-it (dag-nodes dag)))
dag)
(defmethod compute-hasse-diagram ((dag dag))
(labels ((do-it (node)
(let* ((succs (slot-value node 'dag-node-descendants))
(dag-node-children (copy-list succs)))
(dolist (succ succs)
(dolist (succ-succ (slot-value succ 'dag-node-descendants))
(when (member succ-succ succs)
(setf dag-node-children
(delete succ-succ dag-node-children)))))
(setf (dag-node-children node) dag-node-children))))
(dolist (node (dag-nodes dag))
(do-it node))
(dolist (node (dag-nodes dag))
(dolist (child (dag-node-children node))
(pushnew node (dag-node-parents child))))
dag))
(defmethod compute-transitive-closure ((dag dag))
(labels ((compute-descendants (node)
(append (dag-node-children node)
(apply #'append
(mapcar #'compute-descendants (dag-node-children node)))))
(compute-ancestors (node)
(append (dag-node-parents node)
(apply #'append
(mapcar #'compute-ancestors (dag-node-parents node))))))
(dolist (node (dag-nodes dag))
(setf (slot-value node 'dag-node-descendants)
(remove-duplicates (compute-descendants node)))
(setf (slot-value node 'dag-node-ancestors)
(remove-duplicates (compute-ancestors node))))
dag))
;;;
;;;
;;;
#+(and :clim :lispworks)
(progn
(defmethod make-postscript-file ((dag dag) filename)
(with-open-file (stream filename
:direction :output
:if-exists :supersede)
#| (let ((*standard-output* stream))
(when (dag-top dag)
(cl-user::psgraph (dag-top dag)
#'dag-node-children
#'(lambda (x) (list (dag-node-name x)))))) |#
(clim:with-output-to-postscript-stream (ps-stream stream
:scale-to-fit t)
(draw-dag-display *application-frame* ps-stream :printing-p t))))
(define-application-frame dag-browser ()
((dag :initform nil
:initarg :dag
:accessor dag)
(orientation :accessor orientation :initform :right)
(graph-type :accessor graph-type :initform *type*)
(show-top-p :initform t)
(show-bottom-p :initform nil)
(app-stream :initform nil :accessor app-stream))
(:panes
(dag-display :application
:display-function 'draw-dag-display
:end-of-line-action :allow
:end-of-page-action :allow
:display-after-commands t)
(dag-info :application
:scroll-bars :both
:end-of-line-action :allow
:end-of-page-action :allow
:display-after-commands t)
(dag-options :accept-values
:scroll-bars nil
:display-function
`(accept-values-pane-displayer
:displayer ,#'(lambda (frame stream)
(accept-options frame stream)))))
(:layouts
(:defaults
(vertically ()
(1/10 dag-options)
(5/10 dag-display)
(4/10 dag-info)))))
(defmethod accept-options ((frame dag-browser) stream)
(with-slots (show-top-p show-bottom-p orientation graph-type) frame
(formatting-table (stream :multiple-columns t)
(formatting-row (stream)
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'clim:boolean
:prompt "Show Top"
:prompt-mode :raw
:stream stream
:default show-top-p)
(setf show-top-p object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'clim:boolean
:prompt "Show Bottom"
:prompt-mode :raw
:stream stream
:default show-bottom-p)
(setf show-bottom-p object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'completion
:prompt "Orientation"
:stream stream
:default orientation
:view `(option-pane-view :items (:down :right)))
(setf orientation object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'completion
:prompt "Graph Type"
:stream stream
:default graph-type
:view `(option-pane-view :items (:tree :directed-acyclic-graph)))
(setf graph-type object)))))))
;;;
;;;
;;;
(defmethod draw-dag-display ((frame dag-browser) stream &key printing-p)
(with-slots (show-bottom-p show-top-p dag graph-type orientation) frame
(with-slots (gprinter) dag
(labels ((do-it ()
(format-graph-from-roots
(if show-top-p
(dag-roots dag)
(let ((roots (dag-roots dag)))
(remove-if-not #'(lambda (x)
(some #'(lambda (parent)
(member parent roots))
(dag-node-parents x)))
(dag-nodes dag))))
(symbol-function gprinter)
#'(lambda (x)
(remove-duplicates
(if show-bottom-p
(dag-node-children x)
(remove-if #'(lambda (node)
(eq node (dag-bottom dag)))
(dag-node-children x)))))
:center-nodes t
:orientation orientation
:stream stream
:graph-type graph-type
:duplicate-test #'equalp
:merge-duplicates t
:arc-drawer
#'(lambda (stream from-object
to-object x1 y1
x2 y2
&rest
drawing-options)
(declare (dynamic-extent
drawing-options))
(declare (ignore from-object
to-object))
(apply #'draw-arrow* stream
x1 y1 x2 y2 drawing-options))
:merge-duplicates t)
(setf (app-stream frame) stream)))
(if printing-p
(indenting-output (stream '(8 :character))
(do-it))
(do-it))))))
;;;
;;;
;;;
(defmethod draw-dag-node ((object node-proxy) stream)
(draw-dag-node (for-node object) stream))
(defmethod draw-dag-node ((object dag-node) stream)
(with-output-as-presentation (stream object (type-of object))
(if (dag-node-marked-p object)
(surrounding-output-with-border
(stream :shape :rectangle)
(surrounding-output-with-border
(stream :shape :rectangle)
(format stream "~A" (funcall (symbol-function (tprinter (in-dag object))) object))))
(surrounding-output-with-border
(stream :shape :rectangle)
(format stream "~A" (funcall (symbol-function (tprinter (in-dag object))) object))))))
;;;
;;;
;;;
(defmethod make-subdag-from ((node dag-node))
(let* ((dag (in-dag node))
(subdag (make-dag :type (type-of dag)
:name (format nil "Sub-DAG of DAG ~A from Node ~A"
(dag-name dag) (dag-node-name node))))
(nodes (cons node (dag-node-descendants node))))
(unmark-all-dag-nodes dag)
(dolist (node nodes)
(mark-dag-node node))
(let ((new-nodes (make-hash-table :size (length nodes))))
(dolist (node nodes)
(setf (gethash node new-nodes)
(copy-dag-node node)))
(dolist (node nodes)
(let* ((new-node (gethash node new-nodes))
(parents (mapcar #'(lambda (x)
(gethash x new-nodes))
(remove-if-not #'dag-node-marked-p (dag-node-parents node))))
(children (mapcar #'(lambda (x)
(gethash x new-nodes))
(remove-if-not #'dag-node-marked-p (dag-node-children node)))))
(setf (dag-node-parents new-node) parents
(dag-node-children new-node) children)
(setf (in-dag new-node) subdag)
(push new-node (dag-nodes subdag)))))
(unmark-all-dag-nodes subdag)
(unmark-all-dag-nodes dag)
(visualize-dag subdag)))
(defun swap (first second list)
(let* ((pos1 (position first list))
(pos2 (position second list))
(min (min pos1 pos2))
(max (max pos1 pos2)))
(append (subseq list 0 min)
(if (= min pos1)
(list second)
(list first))
(subseq list (1+ min) max)
(if (= min pos1)
(list first)
(list second))
(subseq list (1+ max)))))
;;;
;;; Commands
;;;
(define-dag-browser-command (com-exit :menu "Exit") ()
(frame-exit *application-frame*))
(define-dag-browser-command (com-ps-file :menu "Make Postscript File") ()
(make-postscript-file (dag *application-frame*)
"dag.ps" ))
(define-dag-browser-command (com-inspect-node
:menu nil)
((node 'dag-node :gesture :select))
(let ((*standard-output* (get-frame-pane *application-frame* 'dag-info))
(*print-pretty* t))
(setf *node* node)
(window-clear *standard-output*)
(describe-object node *standard-output*)))
(define-dag-browser-command (com-make-subdag-from-node :menu nil)
((node 'dag-node :gesture :select))
(make-subdag-from node))
(define-dag-browser-command (com-exchange-child-node-positions :menu nil)
((first 'dag-node :gesture :select))
(let ((dag (in-dag first)))
(unmark-all-dag-nodes dag)
(dolist (parent (dag-node-parents first))
(dolist (child (dag-node-children parent))
(unless (eq child first)
(mark-dag-node child))))
(redisplay-frame-panes *application-frame*)
(terpri) (terpri)
(let* ((second (accept
`(and dag-node
(satisfies ,#'(lambda (object)
(dag-node-marked-p object))))
:prompt "Enter exchange node on same level")))
(exchange-child-nodes
(dag *application-frame*) ;; wichtig! evtl. ungleich dag! wegen proxies etc. !
first second))
(unmark-all-dag-nodes dag))
(draw-dag-display *application-frame*
(get-frame-pane *application-frame* 'dag-display)))
(defmethod exchange-child-nodes ((dag dag) (first dag-node) (second dag-node))
(let ((first (find-if #'(lambda (x) (if (typep x 'node-proxy)
(eq (for-node x) first)
(eq x first)))
(dag-nodes dag)))
(second (find-if #'(lambda (x) (if (typep x 'node-proxy)
(eq (for-node x) second)
(eq x second)))
(dag-nodes dag))))
(let ((common-parents (intersection (dag-node-parents first)
(dag-node-parents second))))
(dolist (parent common-parents)
(let* ((children (dag-node-children parent))
(pos1 (position first children))
(pos2 (position second children)))
(when (and pos1 pos2)
(setf (dag-node-children parent)
(swap first second children))))))))
;;;
;;;
;;;
(define-presentation-method highlight-presentation ((node dag-node) record stream state)
(let* ((node (presentation-object record))
(parents (dag-node-parents node))
(children (dag-node-children node))
(objects (cons node (append parents children)))
(history (stream-output-history stream))
(roots (graph-root-nodes
(first (output-record-children history))))
(nodes nil))
(labels ((do-it (current)
(let ((object
(slot-value current 'clim-internals::object)))
(let ((object (if (typep object 'node-proxy)
(for-node object)
object)))
(when (member object objects)
(unless (member object nodes)
(push object nodes)
(multiple-value-bind (x y)
(bounding-rectangle-position current)
(multiple-value-bind (w h)
(bounding-rectangle-size current)
(draw-rectangle* stream x y (+ x w) (+ y h) :ink +flipping-ink+)))))))
(dolist (child (graph-node-children current))
(do-it child))))
(dolist (root roots)
(do-it root)))))
)
;;;
;;;
;;;
(defmethod visualize-dag ((dag dag) &rest args &key
printer
#+:clim (view :graphically)
#-:clim (view :textually)
(type 'dag-browser) &allow-other-keys)
(declare (ignorable type args))
(ecase view
#+(and :clim :lispworks)
(:graphically
(let ((dag-browser
(apply #'make-application-frame type
:pretty-name (dag-name dag)
:dag dag
:frame-manager
(find-frame-manager :port (find-port))
:width 800
:height 600
:allow-other-keys t
args)))
(mp:process-run-function
"DAG Browser"
'(:size 1400000)
#'(lambda ()
(run-frame-top-level dag-browser)))))
(:textually
(show-dag dag t :printer (or printer (tprinter dag))))))
| 22,918 | Common Lisp | .lisp | 558 | 28.249104 | 99 | 0.517706 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 273d4ae355a0831c2190c6d65d5cd1fa6e57e1f178189feaa2ad5a94e491fc96 | 12,487 | [
-1
] |
12,488 | racer-dag.lisp | lambdamikel_DLMAPS/src/tools/racer-dag.lisp | ;; -*- Mode: LISP; Syntax: Common-Lisp; Package: RACER-DAG -*-
(in-package :RACER-DAG)
;;;
;;;
;;;
(defclass racer-taxonomy (dag)
((dag::tprinter :initform 'equivalent-nodes)))
(defclass racer-taxonomy-node (dag-node)
((equivalent-nodes :accessor equivalent-nodes :initarg :equivalent-nodes)))
(defun get-racer-taxonomy (tbox &optional (classify-tbox-p t))
(let ((*print-readably* nil))
(when classify-tbox-p (classify-tbox tbox))
(set-current-tbox tbox)
(let ((dag (make-dag :name (format nil "Taxonomy of RACER TBox ~A" tbox)
:printer #'(lambda (x stream)
(format stream "~A" (dag-node-name x)))
:type 'racer-taxonomy))
(nodes (make-hash-table :size 1000))
(nodes-list nil))
(dolist (concept-cluster
(remove-duplicates
(mapcar #'first (taxonomy tbox))
:test #'equal))
(let* ((concept-cluster (tools::ensure-list concept-cluster))
(node-name (first concept-cluster))
(node (make-dag-node :name
node-name
:equivalent-nodes
concept-cluster
:type 'racer-taxonomy-node)))
(push node nodes-list)
(dolist (concept concept-cluster)
(setf (gethash concept nodes)
node))))
(dolist (triple (taxonomy tbox))
(let* ((node-name (first (tools::ensure-list (first triple))))
(parents (second triple))
(children (third triple))
(node (gethash node-name nodes))
(parents (remove-duplicates
(mapcar #'(lambda (x)
(gethash (first (tools::ensure-list x)) nodes))
parents)))
(children (remove-duplicates
(mapcar #'(lambda (x)
(gethash (first (tools::ensure-list x)) nodes))
children))))
(setf (dag-node-children node) children)
(setf (dag-node-parents node) parents)
(insert-dag-node dag node)))
dag)))
#+:clim
(defun show-racer-taxonomy (&optional (tbox (racer:current-tbox)))
(visualize-dag (get-racer-taxonomy tbox)))
| 2,521 | Common Lisp | .lisp | 54 | 30.5 | 85 | 0.507744 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 0c2a4f4b157203794cdfe3180cd09fda55b896331e40a5af21d66cb254c97be4 | 12,488 | [
-1
] |
12,489 | fonts.lisp | lambdamikel_DLMAPS/src/tools/fonts.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GUI-TOOLS; Base: 10 -*-
(cl:in-package gui-tools)
;;;
;;;
;;;
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *y-to-x* 1.5)
(defparameter *char-to-font-function*
(make-array 256))
(defparameter *char-to-font-def*
(make-array 256))
(defparameter *strings* (make-hash-table :size 10000))
;;;
;;;
;;;
(defun get-code (char)
(let* ((vectors (second char))
(measures (third char))
(x-measures (first measures))
#| (y-measures (second measures)) |#
(xstart (first x-measures))
(xend (second x-measures))
#| (ystart (first y-measures))
(yend (second y-measures)) |#
(delta (abs (- xstart xend)))
(code nil))
(dolist (line vectors)
(let* ((p1 (first line))
(p2 (second line))
(x1 (- (first p1) xstart))
(x2 (- (first p2) xstart))
(y1 (- (second p1)))
(y2 (- (second p2))))
(push
`(medium-draw-line*
stream
(+ xoff ,x1) (+ yoff ,y1) (+ xoff ,x2) (+ yoff ,y2))
code)))
`(progn
,@code
,delta)))
(defun get-full-code (char)
(princ char) (terpri)
(let* ((namex (first char))
(name
(typecase namex
(string
(elt namex 0))
(character namex)))
(char-code (char-code name))
(dummy-var1 (gensym))
(dummy-var2 (gensym))
(dummy-var3 (gensym)))
(values
`(lambda (stream xoff yoff)
(let ((,dummy-var1 stream)
(,dummy-var2 xoff)
(,dummy-var3 yoff))
(declare (ignore ,dummy-var1 ,dummy-var2 ,dummy-var3))
,(get-code char)))
char-code)))
(defconstant +char-definitions+
'((" " nil ((-1 1) (-1 1)))("," (((-1 11/17) (-2/3 15/17)) ((-2/3 15/17) (-2/3 23/17)) ((-2/3 23/17) (-1 27/17)) ((-1 27/17) (-2/3 27/17)) ((-2/3 27/17) (-1/3 23/17)) ((-1/3 23/17) (-1/3 15/17)) ((-1/3 15/17) (-2/3 11/17)) ((-2/3 11/17) (-1 11/17))) ((-1 -1/3) (11/17 27/17))) ("." (((-1 7/17) (-1 15/17)) ((-1 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1/3 7/17)) ((-1/3 7/17) (-1 7/17))) ((-1 -1/3) (7/17 15/17))) ("Ü" (((2/3 -1) (1 -21/17)) ((1 -21/17) (2/3 -25/17)) ((2/3 -25/17) (1/3 -21/17)) ((1/3 -21/17) (2/3 -1)) ((-1 -21/17) (-2/3 -25/17)) ((-2/3 -25/17) (-1/3 -21/17)) ((-1/3 -21/17) (-2/3 -1)) ((-2/3 -1) (-1 -21/17)) ((1 -1) (1 7/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 -1))) ((-1 1) (-25/17 15/17)))
("Ä" (((-2/3 -1) (-1 -21/17)) ((-1 -21/17) (-2/3 -25/17)) ((-2/3 -25/17) (-1/3 -21/17)) ((-1/3 -21/17) (-2/3 -1)) ((2/3 -1) (1/3 -21/17)) ((1/3 -21/17) (2/3 -25/17)) ((2/3 -25/17) (1 -21/17)) ((1 -21/17) (2/3 -1)) ((-1 15/17) (0 -1)) ((-2/3 3/17) (2/3 3/17)) ((1 15/17) (0 -1))) ((-1 1) (-25/17 15/17))) ("Ö" (((2/3 -1) (1/3 -21/17)) ((1/3 -21/17) (2/3 -25/17)) ((2/3 -25/17) (1 -21/17)) ((1 -21/17) (2/3 -1)) ((-2/3 -1) (-1 -21/17)) ((-1 -21/17) (-2/3 -25/17)) ((-2/3 -25/17) (-1/3 -21/17)) ((-1/3 -21/17) (-2/3 -1)) ((-1/3 -1) (-1 -9/17)) ((-1 -9/17) (-1 7/17)) ((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 7/17) (1 -9/17)) ((1 -9/17) (1/3 -1)) ((1/3 -1) (-1/3 -1))) ((-1 1) (-25/17 15/17)))
("ß" (((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (2/3 11/17)) ((2/3 11/17) (2/3 7/17)) ((2/3 7/17) (2/3 3/17)) ((2/3 3/17) (1/3 -5/17)) ((1/3 -5/17) (-2/3 -5/17)) ((-2/3 -5/17) (1/3 -5/17)) ((1/3 -5/17) (2/3 -9/17)) ((2/3 -9/17) (2/3 -13/17)) ((2/3 -13/17) (1/3 -1)) ((1/3 -1) (-1/3 -1)) ((-1/3 -1) (-1 -13/17)) ((-1 -13/17) (-1 15/17))) ((-1 2/3) (-1 15/17))) ("ü" (((1/3 -9/17) (2/3 -13/17)) ((2/3 -13/17) (1/3 -1)) ((1/3 -1) (0 -13/17)) ((0 -13/17) (1/3 -9/17)) ((-1/3 -9/17) (0 -13/17)) ((0 -13/17) (-1/3 -1)) ((-1/3 -1) (-2/3 -13/17)) ((-2/3 -13/17) (-1/3 -9/17)) ((-1 -5/17) (-1 7/17)) ((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 -5/17) (1 15/17))) ((-1 1) (-1 15/17)))
("ö" (((1/3 -9/17) (2/3 -13/17)) ((2/3 -13/17) (1/3 -1)) ((1/3 -1) (0 -13/17)) ((0 -13/17) (1/3 -9/17)) ((-1/3 -9/17) (-2/3 -13/17)) ((-2/3 -13/17) (-1/3 -1)) ((-1/3 -1) (0 -13/17)) ((0 -13/17) (-1/3 -9/17)) ((-1/3 -5/17) (1/3 -5/17)) ((1/3 -5/17) (1 3/17)) ((1 3/17) (1 7/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 3/17)) ((-1 3/17) (-1/3 -5/17))) ((-1 1) (-1 15/17))) ("ä" (((-1/3 -9/17) (-2/3 -13/17)) ((-2/3 -13/17) (-1/3 -1)) ((-1/3 -1) (0 -13/17)) ((0 -13/17) (-1/3 -9/17)) ((1/3 -9/17) (0 -13/17)) ((0 -13/17) (1/3 -1)) ((1/3 -1) (2/3 -13/17)) ((2/3 -13/17) (1/3 -9/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 3/17)) ((-1 3/17) (-1/3 -5/17)) ((-1/3 -5/17) (1/3 -5/17)) ((1/3 -5/17) (1 3/17)) ((1 -5/17) (1 15/17))) ((-1 1) (-1 15/17))) ("z" (((1 15/17) (-1 15/17)) ((-1 15/17) (1 -5/17)) ((1 -5/17) (-1 -5/17))) ((-1 1) (-5/17 15/17)))
("y" (((1/3 27/17) (2/3 11/17)) ((1 -5/17) (2/3 11/17)) ((2/3 11/17) (-1 -5/17))) ((-1 1) (-5/17 27/17))) ("x" (((1 -5/17) (-1 15/17)) ((1 15/17) (-1 -5/17))) ((-1 1) (-5/17 15/17))) ("w" (((1 -5/17) (1/3 15/17)) ((1/3 15/17) (0 3/17)) ((0 3/17) (-1/3 15/17)) ((-1/3 15/17) (-1 -5/17))) ((-1 1) (-5/17 15/17))) ("v" (((1 -5/17) (0 15/17)) ((0 15/17) (-1 -5/17))) ((-1 1) (-5/17 15/17))) ("u" (((-1 -5/17) (-1 7/17)) ((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 -5/17) (1 15/17))) ((-1 1) (-5/17 15/17))) ("t" (((2/3 -1/17) (-2/3 -1/17)) ((1 11/17) (2/3 15/17)) ((2/3 15/17) (1/3 15/17)) ((1/3 15/17) (0 11/17)) ((0 11/17) (0 -1))) ((-2/3 1) (-1 15/17))) ("s" (((1 -1/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 -1/17)) ((-1 -1/17) (-1 3/17)) ((-1 3/17) (1 7/17)) ((1 7/17) (1 11/17)) ((1 11/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 11/17))) ((-1 1) (-5/17 15/17)))
("r" (((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 3/17)) ((-1 15/17) (-1 -5/17))) ((-1 1) (-5/17 15/17))) ("q" (((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 3/17)) ((-1 3/17) (-1/3 -5/17)) ((-1/3 -5/17) (1/3 -5/17)) ((1/3 -5/17) (1 3/17)) ((1 27/17) (1 -5/17))) ((-1 1) (-5/17 27/17))) ("p" (((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 7/17) (1 3/17)) ((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 3/17)) ((-1 27/17) (-1 -5/17))) ((-1 1) (-5/17 27/17))) ("o" (((-1/3 -5/17) (-1 3/17)) ((-1 3/17) (-1 7/17)) ((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 7/17) (1 3/17)) ((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17))) ((-1 1) (-5/17 15/17))) ("n" (((1 15/17) (1 3/17)) ((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 3/17)) ((-1 15/17) (-1 -5/17))) ((-1 1) (-5/17 15/17)))
("m" (((0 15/17) (0 3/17)) ((1 15/17) (1 3/17)) ((1 3/17) (2/3 -5/17)) ((2/3 -5/17) (1/3 -5/17)) ((1/3 -5/17) (0 3/17)) ((0 3/17) (-1/3 -5/17)) ((-1/3 -5/17) (-2/3 -5/17)) ((-2/3 -5/17) (-1 3/17)) ((-1 15/17) (-1 -5/17))) ((-1 1) (-5/17 15/17))) ("l" (((1/3 15/17) (0 15/17)) ((0 15/17) (0 -1))) ((0 1/3) (-1 15/17))) ("k" (((1 15/17) (-1 3/17)) ((-1 3/17) (2/3 -9/17)) ((2/3 -9/17) (-1 3/17)) ((-1 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("j" (((0 -9/17) (-1/3 -13/17)) ((-1/3 -13/17) (0 -1)) ((0 -1) (1/3 -13/17)) ((1/3 -13/17) (0 -9/17)) ((-1 19/17) (-2/3 23/17)) ((-2/3 23/17) (-1/3 23/17)) ((-1/3 23/17) (0 15/17)) ((0 15/17) (0 -1/17))) ((-1 1/3) (-1 23/17))) ("i" (((0 -9/17) (-1/3 -13/17)) ((-1/3 -13/17) (0 -1)) ((0 -1) (1/3 -13/17)) ((1/3 -13/17) (0 -9/17)) ((0 15/17) (0 -1/17))) ((-1/3 1/3) (-1 15/17))) ("h" (((1 15/17) (1 3/17)) ((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 3/17)) ((-1 15/17) (-1 -1))) ((-1 1) (-1 15/17)))
("g" (((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 3/17)) ((-1 3/17) (-1 7/17)) ((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((-1 23/17) (-1/3 27/17)) ((-1/3 27/17) (1/3 27/17)) ((1/3 27/17) (1 23/17)) ((1 23/17) (1 -5/17))) ((-1 1) (-5/17 27/17))) ("f" (((1/3 -1/17) (-1 -1/17)) ((2/3 -13/17) (1/3 -1)) ((1/3 -1) (0 -1)) ((0 -1) (-1/3 -13/17)) ((-1/3 -13/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1/3 15/17))) ((-1 2/3) (-1 15/17))) ("e" (((1 11/17) (2/3 15/17)) ((2/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 11/17)) ((-1 11/17) (-1 3/17)) ((-1 3/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 3/17)) ((-1 3/17) (1 3/17)) ((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17))) ((-1 1) (-5/17 15/17))) ("d" (((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 3/17)) ((-1 3/17) (-1 7/17)) ((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 15/17) (1 -1))) ((-1 1) (-1 15/17)))
("c" (((1 11/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 3/17)) ((-1 3/17) (-1/3 -5/17)) ((-1/3 -5/17) (1/3 -5/17)) ((1/3 -5/17) (1 -1/17))) ((-1 1) (-5/17 15/17))) ("b" (((-1 3/17) (-1/3 -5/17)) ((-1/3 -5/17) (1/3 -5/17)) ((1/3 -5/17) (1 3/17)) ((1 3/17) (1 7/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("a" (((1 3/17) (1/3 -5/17)) ((1/3 -5/17) (-1/3 -5/17)) ((-1/3 -5/17) (-1 3/17)) ((-1 3/17) (-1 7/17)) ((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 15/17) (1 -5/17)) ((1 -5/17) (1 -5/17))) ((-1 1) (-5/17 15/17))) ("9" (((1 -5/17) (1/3 -1/17)) ((1/3 -1/17) (-1/3 -1/17)) ((-1/3 -1/17) (-1 -5/17)) ((-1 -5/17) (-1 -13/17)) ((-1 -13/17) (-1/3 -1)) ((-1 11/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 7/17) (1 -13/17)) ((1 -13/17) (1/3 -1)) ((1/3 -1) (-1/3 -1))) ((-1 1) (-1 15/17)))
("8" (((1/3 -1/17) (1 3/17)) ((1 3/17) (1 11/17)) ((1 11/17) (2/3 15/17)) ((2/3 15/17) (-2/3 15/17)) ((-2/3 15/17) (-1 11/17)) ((-1 11/17) (-1 3/17)) ((-1 3/17) (-1/3 -1/17)) ((-1/3 -1) (-2/3 -13/17)) ((-2/3 -13/17) (-2/3 -5/17)) ((-2/3 -5/17) (-1/3 -1/17)) ((-1/3 -1/17) (1/3 -1/17)) ((1/3 -1/17) (2/3 -5/17)) ((2/3 -5/17) (2/3 -13/17)) ((2/3 -13/17) (1/3 -1)) ((1/3 -1) (-1/3 -1))) ((-1 1) (-1 15/17))) ("7" (((-1/3 15/17) (1 -1)) ((1 -1) (-1 -1))) ((-1 1) (-1 15/17))) ("6" (((-1 3/17) (-1/3 -1/17)) ((-1/3 -1/17) (1/3 -1/17)) ((1/3 -1/17) (1 3/17)) ((1 3/17) (1 11/17)) ((1 11/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 11/17)) ((-1 11/17) (-1 -1/17)) ((-1 -1/17) (-2/3 -9/17)) ((-2/3 -9/17) (2/3 -1))) ((-1 1) (-1 15/17))) ("5" (((-1 11/17) (-2/3 15/17)) ((-2/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 11/17)) ((1 11/17) (1 -1/17)) ((1 -1/17) (1/3 -5/17)) ((1/3 -5/17) (-1 -5/17)) ((-1 -5/17) (-1 -1)) ((-1 -1) (1 -1))) ((-1 1) (-1 15/17)))
("4" (((0 15/17) (0 -13/17)) ((1 -1/17) (-1 -1/17)) ((-1 -1/17) (-1/3 -1))) ((-1 1) (-1 15/17))) ("3" (((-1 7/17) (-1 11/17)) ((-1 11/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 11/17)) ((1 11/17) (1 3/17)) ((1 3/17) (1/3 -1/17)) ((1/3 -1/17) (-2/3 -1/17)) ((-2/3 -1/17) (1/3 -1/17)) ((1/3 -1/17) (1 -5/17)) ((1 -5/17) (1 -13/17)) ((1 -13/17) (1/3 -1)) ((1/3 -1) (-1/3 -1)) ((-1/3 -1) (-1 -13/17)) ((-1 -13/17) (-1 -9/17))) ((-1 1) (-1 15/17))) ("2" (((-1 -9/17) (-1 -13/17)) ((1 15/17) (-1 15/17)) ((-1 15/17) (1 -5/17)) ((1 -5/17) (1 -13/17)) ((1 -13/17) (1/3 -1)) ((1/3 -1) (-1/3 -1)) ((-1/3 -1) (-1 -13/17))) ((-1 1) (-1 15/17))) ("1" (((2/3 15/17) (2/3 -1)) ((2/3 -1) (-1 -1/17))) ((-1 2/3) (-1 15/17))) ("0" (((1 -1) (-1 15/17)) ((-1 -1) (-1 15/17)) ((-1 15/17) (1 15/17)) ((1 15/17) (1 -1)) ((1 -1) (-1 -1))) ((-1 1) (-1 15/17))) ("Z" (((1 15/17) (-1 15/17)) ((-1 15/17) (1 -1)) ((1 -1) (-1 -1))) ((-1 1) (-1 15/17)))
("Y" (((0 15/17) (0 -1/17)) ((1 -1) (0 -1/17)) ((0 -1/17) (-1 -1))) ((-1 1) (-1 15/17))) ("X" (((1 -1) (-1 15/17)) ((1 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("W" (((1 -1) (2/3 15/17)) ((2/3 15/17) (0 -1/17)) ((0 -1/17) (-2/3 15/17)) ((-2/3 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("V" (((1 -1) (0 15/17)) ((0 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("U" (((1 -1) (1 7/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 -1))) ((-1 1) (-1 15/17))) ("T" (((0 15/17) (0 -1)) ((1 -1) (-1 -1))) ((-1 1) (-1 15/17))) ("S" (((-1 11/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 11/17)) ((1 11/17) (1 3/17)) ((1 3/17) (1/3 -1/17)) ((1/3 -1/17) (-1/3 -1/17)) ((-1/3 -1/17) (-1 -5/17)) ((-1 -5/17) (-1 -13/17)) ((-1 -13/17) (-1/3 -1)) ((-1/3 -1) (1/3 -1)) ((1/3 -1) (1 -13/17))) ((-1 1) (-1 15/17)))
("R" (((1 15/17) (-1 -1/17)) ((-1 -1/17) (1/3 -1/17)) ((1/3 -1/17) (1 -5/17)) ((1 -5/17) (1 -13/17)) ((1 -13/17) (1/3 -1)) ((1/3 -1) (-1 -1)) ((-1 -1) (-1 15/17))) ((-1 1) (-1 15/17))) ("Q" (((1 19/17) (0 -1/17)) ((-1 -9/17) (-1/3 -1)) ((-1/3 -1) (1/3 -1)) ((1/3 -1) (1 -9/17)) ((1 -9/17) (1 7/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 -9/17))) ((-1 1) (-1 19/17))) ("P" (((-1 -1/17) (1/3 -1/17)) ((1/3 -1/17) (1 -5/17)) ((1 -5/17) (1 -13/17)) ((1 -13/17) (1/3 -1)) ((1/3 -1) (-1 -1)) ((-1 -1) (-1 15/17))) ((-1 1) (-1 15/17))) ("O" (((1 -9/17) (1 7/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 -9/17)) ((-1 -9/17) (-1/3 -1)) ((-1/3 -1) (1/3 -1)) ((1/3 -1) (1 -9/17))) ((-1 1) (-1 15/17))) ("N" (((1 -1) (1 15/17)) ((1 15/17) (-1 -1)) ((-1 -1) (-1 15/17))) ((-1 1) (-1 15/17))) ("M" (((1 15/17) (1 -1)) ((1 -1) (0 -1/17)) ((0 -1/17) (-1 -1)) ((-1 -1) (-1 15/17))) ((-1 1) (-1 15/17)))
("L" (((1 15/17) (-1 15/17)) ((-1 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("K" (((1 -1) (-1 -1/17)) ((1 15/17) (-1 -1/17)) ((-1 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("G" (((-1/3 -1/17) (1 -1/17)) ((1 -1/17) (1 7/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1/3 15/17)) ((-1/3 15/17) (-1 7/17)) ((-1 7/17) (-1 -9/17)) ((-1 -9/17) (-1/3 -1)) ((-1/3 -1) (1/3 -1)) ((1/3 -1) (1 -9/17))) ((-1 1) (-1 15/17))) ("J" (((-1 7/17) (-1/3 15/17)) ((-1/3 15/17) (1/3 15/17)) ((1/3 15/17) (1 7/17)) ((1 7/17) (1 -1)) ((1 -1) (-1 -1))) ((-1 1) (-1 15/17))) ("I" (((0 15/17) (0 -1))) ((0 0) (-1 15/17))) ("H" (((-1 -1/17) (1 -1/17)) ((1 -1) (1 15/17)) ((-1 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("F" (((-1 15/17) (-1 -1/17)) ((1 -1) (-1 -1)) ((-1 -1) (-1 -1/17)) ((-1 -1/17) (0 -1/17)) ((0 -1/17) (1/3 -1/17))) ((-1 1) (-1 15/17))) ("E" (((1/3 -1/17) (-1 -1/17)) ((1 15/17) (-1 15/17)) ((-1 15/17) (-1 -1)) ((-1 -1) (1 -1))) ((-1 1) (-1 15/17)))
("D" (((-1 -1) (1/3 -1)) ((1/3 -1) (1 -9/17)) ((1 -9/17) (1 7/17)) ((1 7/17) (1/3 15/17)) ((1/3 15/17) (-1 15/17)) ((-1 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("C" (((1 7/17) (2/3 15/17)) ((2/3 15/17) (-2/3 15/17)) ((-2/3 15/17) (-1 3/17)) ((-1 3/17) (-1 -5/17)) ((-1 -5/17) (-2/3 -1)) ((-2/3 -1) (2/3 -1)) ((2/3 -1) (1 -9/17))) ((-1 1) (-1 15/17))) ("B" (((-1 -1) (1/3 -1)) ((1/3 -1) (1 -13/17)) ((1 -13/17) (1 -5/17)) ((1 -5/17) (2/3 -1/17)) ((2/3 -1/17) (-1 -1/17)) ((-1 -1/17) (2/3 -1/17)) ((2/3 -1/17) (1 3/17)) ((1 3/17) (1 11/17)) ((1 11/17) (2/3 15/17)) ((2/3 15/17) (-1 15/17)) ((-1 15/17) (-1 -1))) ((-1 1) (-1 15/17))) ("A" (((-2/3 3/17) (2/3 3/17)) ((1 15/17) (0 -1)) ((0 -1) (-1 15/17))) ((-1 1) (-1 15/17)))))
#| (with-open-file (stream
"dlmaps:fonts;char3n"
:direction :input)
(read stream)))
|#
(defmacro compile-font ()
(let ((code nil))
(dolist (char +char-definitions+)
(multiple-value-bind (draw-code char-code)
(get-full-code char)
(setf (svref *char-to-font-def* char-code)
(get-code char))
(push `(setf (svref *char-to-font-function* ,char-code)
,draw-code)
code)))
`(progn ,@code)))
(compile-font)
)
#|
(defun draw-vector-text (string stream)
(let ((x 0))
(with-scaling (stream 1.0 *y-to-x*)
(map nil
#'(lambda (char)
(let* ((char-code (char-code char))
(fn (svref *char-to-font-function* char-code)))
(incf x 0.3)
(incf x
(if fn
(funcall
fn
stream x 1.2)
(funcall (svref *char-to-font-function*
(char-code #\space))
stream x 1.2)))))
string))))
|#
(defun draw-vector-text (string stream &key compile-p)
(let ((x 0))
(with-scaling (stream 1.0 *y-to-x*)
(if (not compile-p)
(map nil
#'(lambda (char)
(let* ((char-code (char-code char))
(fn (svref *char-to-font-function* char-code)))
(incf x 0.3)
(incf x
(if fn
(funcall
fn
stream x 1.2)
(funcall (svref *char-to-font-function*
(char-code #\space))
stream x 1.2)))))
string)
(let ((draw-code
(gethash string *strings*)))
(if draw-code
(funcall draw-code stream x 1.2)
(let ((def
`(lambda (stream xoff yoff)
,@(apply #'append
(map 'list
#'(lambda (char)
(let* ((char-code (char-code char))
(def (svref *char-to-font-def* char-code)))
(if def
`((incf xoff 0.3)
(incf xoff
,def))
(let* ((char-code (char-code #\space))
(def (svref *char-to-font-def* char-code)))
`((incf xoff 0.3)
(incf xoff
,def))))))
string)))))
(let ((code (compile nil def)))
(setf (gethash string *strings*) code)
(funcall code stream x 1.2)))))))))
| 18,270 | Common Lisp | .lisp | 156 | 104.205128 | 991 | 0.38413 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 3a8cc7de0eb45dd41271791d2d14e10f554fdda3446b871e088adf803f1bf764 | 12,489 | [
-1
] |
12,490 | heap-test.lisp | lambdamikel_DLMAPS/src/tools/heap-test.lisp | ;;;
;;; $Header: /home/gene/library/website/docsrc/lisp-heap/RCS/test.lisp,v 201.1 2004/08/31 06:49:54 gene Exp $
;;;
;;; Copyright (c) 2002 by Gene Michael Stover.
;;; All rights reserved.
;;; Permission to copy, store, & view this document unmodified &
;;; in its entirety is granted.
;;;
(require "heap" '("heap.lisp"))
(defvar *tests* nil)
(setq *tests* nil)
(defmacro deftest (name &rest args-doc-body)
`(progn
;; I don't understand why the SETQ is necessary. NCONC is
;; destructive, it should affect *TESTS* inherently. NCONC
;; has the expected behaviour when I experiment with it in
;; interactive mode, but experience shows that SETQ is
;; needed here.
(setq *tests* (nconc *tests* (list ',name)))
(defun ,name ,@args-doc-body)))
(deftest test0000 ()
"Verifies that we can create a heap without crashing."
(create-heap #'<))
(deftest test0010 ()
"Verifies that we can insert some things into a heap without
crashing."
(let ((h (create-heap #'<)))
(dotimes (i 10)
(heap-insert h i))
h))
(deftest test0012 ()
"Verifies that we can insert some things & then remove as many
things & that the heap is then empty."
(let ((h (create-heap #'<)))
(dotimes (i 10)
(heap-insert h i))
(dotimes (i 10)
(heap-remove h))
(heap-empty-p h)))
(deftest test0013 ()
"Places some numbers in a heap, in order, & then verifies that
the numbers are removed in that order & that the heap is then empty."
(let ((h (create-heap #'<)))
(dotimes (i 10)
(heap-insert h i))
(dotimes (i 10)
(assert (eql (heap-remove h) i)))
(heap-empty-p h)))
(deftest test0014 (&optional (count 10))
"Places some random numbers in a heap & verifies that they are
removed in the correct order & that the heap is then empty."
(let ((h (create-heap #'<))
(lst (loop for i from 1 to count collect (random 100))))
(mapc #'(lambda (x) (heap-insert h x)) lst)
(mapc #'(lambda (x) (assert (eql (heap-remove h) x))) (sort lst #'<))
(heap-empty-p h)))
(deftest test0015 ()
"Performs TEST0014 many times & with larger COUNTs."
(dotimes (i 100)
(assert (test0014 (* 3 i))))
t)
(deftest test0016 ()
"Verify that we can create a heap & specify its INITIAL-CONTENTS
without crashing."
(create-heap #'< :initial-contents '(28 20 19 18 15 14 13 12 11)))
(deftest test0017 ()
"Verify that a heap created with an INITIAL-CONTENTS is in order."
(let ((h (create-heap #'< :initial-contents (loop for i from 99 downto 0
collect i))))
(loop for i from 0 to 99
do (assert (eql (heap-remove h) i))))
t)
(labels ((expect (lst less-fn)
"Put the items from LST into a heap in order, then
verify that they are removed from the heap in the correct order.
The heap orders by LESS-FN. The list is sorted by LESS-FN before
the removal/comparisons."
(let ((h (create-heap less-fn)))
(mapc #'(lambda (x) (heap-insert h x)) lst)
(mapc #'(lambda (x)
(unless (equal x (heap-remove h))
(return-from expect nil)))
(sort lst less-fn))
(heap-empty-p h))))
(deftest test0018 ()
"Put some strings in a heap, in order, make sure they come
out of the heap in that order."
(expect '("a" "b" "c") #'string-lessp))
(deftest test0019 ()
"Put some strings in a heap, in reverse order, make sure
they come out of the heap in order."
(expect '("c" "b" "a") #'string-lessp)))
(deftest test0030 ()
"Test that HEAP-CLEAR changes a non-empty heap into an
empty heap."
(let ((h (create-heap #'>)))
(heap-insert h 3)
(heap-insert h 5)
(heap-insert h 2)
(heap-clear h)
(heap-empty-p h)))
(deftest test0031 ()
"Test that HEAP-CLEAR is faster than removing every element."
(let ((h (create-heap #'>))
(lst (loop for i from 1 to 10000 collect (random 10000))))
(dolist (x lst) (heap-insert h x))
(let* ((start-clear (get-internal-run-time))
(end-clear (progn (heap-clear h) (get-internal-run-time)))
(time-clear (- end-clear start-clear)))
(dolist (x lst) (heap-insert h x))
(let* ((start-loop (get-internal-run-time))
(end-loop (do ()
((heap-empty-p h) (get-internal-run-time))
(heap-remove h)))
(time-loop (- end-loop start-loop)))
(unless (< time-clear time-loop)
(format t "~&Time to HEAP-CLEAR should be less than time to")
(format t "~&remove all elements with HEAP-REMOVE. Instead,")
(format t "~&~A is ~A, & ~A is ~A." 'time-clear time-clear
'time-loop time-loop))
(< time-clear time-loop)))))
(deftest test0035 ()
"Test using HEAP-DELETE to remove the single element from a heap
with one element. The heap has one element, we DELETE it, & then
we check that the heap is empty."
(let ((h (create-heap #'>)))
(heap-insert h 42)
(and (heap-remove h #'(lambda (h x) (eql x 42)))
(heap-empty-p h))))
(deftest test0037 ()
"Test that interleaved INSERTs & REMOVEs return the right
elements, in the right order, & finally leave the heap empty."
(let ((h (create-heap #'<)))
(and (eql (heap-insert h 5) 5)
(eql (heap-insert h 11) 11)
(eql (heap-remove h) 5)
(eql (heap-insert h 17) 17)
(eql (heap-remove h) 11)
(eql (heap-insert h 21) 21)
(eql (heap-remove h) 17)
(eql (heap-remove h) 21)
(heap-empty-p h))))
(defun check (lst)
"Executes all the tests in LST until they all execute or one of
them fails."
(do ((rc t (funcall (first x)))
(x lst (rest x)))
((or (endp x) (not rc)) (progn (unless rc
(format t "~&failure"))
rc))
(print (first x))))
(defun demo-numbers (&optional (count 10000))
"Fills a heap with COUNT random numbers, then removes them all.
Prints the number of seconds required for each operation."
(let* ((h (create-heap #'<))
(start-time (get-internal-run-time)))
(format t "~%inserting ~A numbers" count)
(dotimes (i count) (heap-insert h (random count)))
(format t "~&removing ~A numbers" count)
(dotimes (i count) (heap-remove h))
(assert (heap-empty-p h))
(let* ((end-time (get-internal-run-time))
(second (/ (- end-time start-time) internal-time-units-per-second))
(rate (/ count second)))
(format t "~&inserted, then removed, ~A items" count)
(format t "~&duration ~,2G seconds" second)
(format t "~&~,2G item per second" rate)
rate)))
(defun demo-game (&optional (count 1000))
"Simulate a game with an event loop to see how quickly a
game could process events. Return the number of messages
per second. Approximates a game's event queue by putting
10,000 events in the queue, then inserts & removes elements
one at a time for a while. Elements are random integers.
My laptop, Plague, a 750 MHz Pentium 3, running clisp in
interpreted mode, does nearly 1,500 insert/remove operations
per second. If a game frame is 1/30th of a second, that is
about 50 events per frame, if that's all the game does,
which of course it is not. In an a-life program, if the
event loop handles less than 1,500 messages per simulation
second, the simulation will run faster than real-time."
(let ((h (create-heap #'<)))
;; Prime the queue.
(dotimes (i 10000) (heap-insert h (random 10000)))
(let ((start (get-internal-run-time)))
(dotimes (i count)
(heap-remove h)
(heap-insert h (random 10000)))
(let* ((end (get-internal-run-time))
(second (/ (- end start) internal-time-units-per-second))
(rate (/ count second)))
rate))))
;;; --- end of file ---
| 7,526 | Common Lisp | .lisp | 193 | 35.103627 | 109 | 0.655031 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 95c271ccec5288d9089cf135071823a2c6146ba68cc405b0fbe67da2bf89afdd | 12,490 | [
-1
] |
12,491 | tools.lisp | lambdamikel_DLMAPS/src/tools/tools.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: TOOLS; Base: 10 -*-
(in-package tools)
(defconstant +pi/2+ (/ pi 2))
(defconstant +2pi+ (* 2 pi))
;;;
;;;
;;;
(defun subclass-responsibility (method)
(error "~A: Subclasses must implement!" method))
(defun to-be-implemented (method)
(error "~A: To be implemented!" method))
;;;
;;;
;;;
(defun maximum (list)
(loop as item in list maximize item))
(defun minimum (list)
(loop as item in list minimize item))
(defun yes (&rest args)
(declare (ignore args))
t)
(defun no (&rest args)
(declare (ignore args))
nil)
;;;
;;;
;;;
(defun smallest (list &optional (fn #'identity))
(when list
(let ((found nil)
(val nil))
(dolist (x list)
(when x
(unless found
(setf found x))
(unless val
(setf val (funcall fn x)))
(let ((fn-val (funcall fn x)))
(if (< fn-val val)
(setf found x
val fn-val)))))
found)))
(defun greatest (list &optional (fn #'identity))
(when list
(let ((found nil)
(val nil))
(dolist (x list)
(when x
(unless found
(setf found x))
(unless val
(setf val (funcall fn x)))
(let ((fn-val (funcall fn x)))
(if (> fn-val val)
(setf found x
val fn-val)))))
found)))
;;;
;;;
;;;
(defun forcecdr (stream &key num (fn #'identity))
(let ((res nil)
(count 0))
(loop while (and stream (if (numberp num) (< count num) t)) do
(incf count)
(push (funcall fn (first stream)) res)
(setf stream (funcall (second stream))))
(reverse res)))
#+(or allegro mcl)
(defun get-lambda-args (fn)
(nreverse
(mapcar #'(lambda (arg)
(if (consp arg)
(first arg)
arg))
(set-difference
#+:allegro
(excl:arglist fn)
#+:mcl
(arglist fn)
'(&rest &optional &key)))))
(defun set-disjoint (a b)
(and (not (some #'(lambda (i)
(member i b))
a))
(not (some #'(lambda (i)
(member i a))
b))))
(defun set-equal (a b &rest args)
(and (apply #'subsetp a b args)
(apply #'subsetp b a args)))
(defun make-cyclic (x)
(when x
(setf (cdr (last x)) x)))
;;;
;;;
;;;
(defconstant +epsilon+ 1e-8)
(defmacro zerop-eps (a)
`(=-eps 0 ,a))
(defmacro =-eps (a b &optional (epsilon +epsilon+))
`(<= (abs (- ,a ,b)) ,epsilon))
(defmacro <=-eps (a b &optional (epsilon +epsilon+))
`(<= ,a (+ ,b ,epsilon)))
(defmacro >=-eps (a b &optional (epsilon +epsilon+))
`(>= ,a (- ,b ,epsilon)))
;;;
;;;
;;;
;(defun => (a b)
; (or (not a) b))
(defmacro => (a b)
`(or (not ,a) ,b))
(defmacro <=> (a b)
`(and (=> ,a ,b)
(=> ,b ,a)))
(defmacro xor (&rest args)
`(or ,@(mapcar #'(lambda (arg)
`(and ,arg ,@(mapcar #'(lambda (arg)
`(not ,arg))
(remove arg args :count 1))))
args)))
(defun ensure-list (arg)
(if (listp arg)
arg
(list arg)))
;;;
;;;
;;;
(defmacro rotate-to (list n)
`(rotate-by ,list (position ,n ,list)))
(defmacro rotate-by (list n)
`(progn
(when (and ,n ,list)
(let ((n (mod ,n (length ,list))))
(unless (zerop n)
(setf ,list
(nconc (subseq ,list n)
(subseq ,list 0 n))))))
,list))
;;;
;;;
;;;
(defun tree-reverse (liste)
(labels ((do-it (liste akku)
(cond ((null liste) akku)
(t (let ((first (first liste)))
(do-it (rest liste)
(cons
(if (listp first)
(do-it first nil) first)
akku)))))))
(do-it liste nil)))
(defun tree-remove (item tree)
(cond ((not (consp tree))
(if (eq item tree) nil tree))
(t
(let ((car (tree-remove item (car tree)))
(cdr (tree-remove item (cdr tree))))
(if car
(cons car cdr)
cdr)))))
(defun tree-collect-if (fn tree)
(let ((items nil))
(labels ((do-it (tree)
(if (and tree (not (consp tree)))
(when (funcall fn tree)
(push tree items))
(when tree
(do-it (car tree))
(do-it (cdr tree))))))
(do-it tree)
items)))
(defun tree-find (tree x &rest args)
(or (apply #'member x tree args)
(some #'(lambda (sub)
(and (consp sub)
(apply #'tree-find sub x args)))
tree)))
(defun tree-find-if (fn tree &rest args)
(some #'(lambda (sub)
(cond ((consp sub)
(apply #'tree-find-if fn sub args))
(t (apply fn sub args))))
tree))
(defun tree-flatten (tree)
(tflatten tree))
(defun tflatten (tree)
(if (consp tree)
(append (tflatten (car tree))
(tflatten (cdr tree)))
(when tree (list tree))))
(defun tree-map (fn tree &rest args)
(mapcar #'(lambda (item)
(if (consp item)
(apply #'tree-map fn item args)
(apply fn item args)))
tree))
;;;
;;;
;;;
(defun one-of (sequence)
(elt sequence (random (length sequence))))
;;;
;;;
;;;
(defun subseq-member (seqa sequence)
(let ((n (length seqa)))
(some #'(lambda (item)
(loop as seq on item
when (equal (subseq seq 0 (min n (length seq)))
seqa)
return t))
sequence)))
(defmacro enqueue (elem queue)
`(setf ,queue
(nconc ,queue (list ,elem))))
(defmacro dequeue (queue)
`(prog1
(first (last ,queue))
(setf ,queue (butlast ,queue))))
(defun reorder (sequence)
(let ((res nil)
(sequence (copy-list sequence))
(length (length sequence)))
(loop
(when (null sequence)
(return res))
(let ((elem (elt sequence (random length))))
(push elem res)
(setf sequence (delete elem sequence :count 1)
length (1- length))))))
;;;
;;;
;;;
(defun splice-in (sym list)
(append (mapcan #'(lambda (x)
(list x sym))
(butlast list))
(last list)))
(defun build-elem-pairs-in-list (list)
(let ((res nil)
(pre nil)
(succ (copy-list list)))
(loop
(unless (cdr succ) (return res))
(push (append pre
(cons (list (first succ)
(second succ))
(cddr succ)))
res)
(setf pre (append pre
(list (first succ))))
(setf succ (cdr succ)))))
(defun stringsubst-char-with-string (orgstring char string)
(let ((pos (position char orgstring)))
(if pos
(concatenate 'string
(subseq orgstring 0 pos)
string
(stringsubst-char-with-string (subseq orgstring (1+ pos))
char string))
orgstring)))
(defparameter *replacements*
`(("--" "-" t)
(" " " " t)))
(defun blank-line-p (line)
(or (eq line 'newline)
(and (typep line 'string)
(not (position-if-not #'(lambda (i) (char= i #\space)) line)))))
(defun string-substitute (string &optional (rules *replacements*)
&key add-spaces)
(labels ((do-it (string akku)
(cond ((blank-line-p string) akku)
(t
(let ((min-pos nil)
(min-from-to))
(dolist (from-to rules)
(let* ((from (first from-to))
(pos (search from string)))
(when pos
(if (or (not min-pos)
(< pos min-pos))
(setf min-from-to from-to
min-pos pos)))))
(let ((from (first min-from-to))
(to (second min-from-to))
(replaced-as-new-input-p (third min-from-to)))
(if min-pos
(if replaced-as-new-input-p
(do-it
(concatenate 'string
to
(subseq string (+ min-pos (length from))))
(append akku
(list (subseq string 0 min-pos))))
(do-it
(subseq string (+ min-pos (length from)))
(append akku
(list (subseq string 0 min-pos))
(list to))))
(append akku (list string)))))))))
(let ((res (do-it (if add-spaces
(concatenate 'string " " string " ")
string)
nil)))
(if res
(reduce #'(lambda (x y)
(concatenate 'string x y))
res)
""))))
(defun transform-xy-list (xylist)
(loop for x in xylist by #'cddr
for y in (cdr xylist) by #'cddr
collect (list x y)))
(defmacro pushend (obj list)
`(setf ,list (nconc ,list (list ,obj))))
(defmacro mynconc (lista listb)
`(setf ,lista
(nconc ,lista ,listb)))
(defmacro my-format (stream indent-level string &rest args)
`(progn
(dotimes (i (* 7 ,indent-level))
(princ " " ,stream))
(format ,stream ,string ,@args)))
(defmacro my-read (stream)
#+:allegro
`(read ,stream)
#+(or mcl lispworks)
`(read-from-string (read-line ,stream)))
#+(or allegro lispworks)
(defun circle-subseq (list from to)
(let* ((copy (copy-list list)))
(setf (rest (last copy)) copy)
(subseq copy from to)))
#+:mcl
(defun circle-subseq (list from to)
(let* ((copy (copy-list list)))
(setf (rest (last copy)) copy)
(let ((start copy))
(loop repeat from do
(setf start (cdr start)))
(loop repeat (- to from)
collect (car start) do
(setf start (cdr start))))))
#+:allegro
(defun recode-german-characters (string)
(nsubstitute (character 228) (character 204) string) ; dos aeh -> unix aeh
(nsubstitute (character 246) (character 224) string) ; dos oeh -> unix oeh
(nsubstitute (character 252) (character 201) string) ; dos ueh -> unix ueh
(nsubstitute (character 196) (character 216) string) ; dos AEH -> unix AEH
(nsubstitute (character 214) (character 231) string) ; dos OEH -> unix OEH
(nsubstitute (character 220) (character 232) string) ; dos UEH -> unix UEH
(nsubstitute (character 223) #\· string) ; dos sz -> unix sz
(nsubstitute (character 228) (character 132) string) ; siemens aeh -> unix aeh ; dxf
(nsubstitute (character 246) (character 148) string) ; siemens oeh -> unix oeh ; dxf
(nsubstitute (character 252) (character 129) string) ; siemens ueh -> unix ueh ; dxf
(nsubstitute (character 214) (character 153) string) ; siemens OEH -> unix OEH ; andere Code unbekannt! ; dxf
(nsubstitute (character 228) (character #xbf) string) ; siemens aeh -> unix aeh ; sqd
(nsubstitute (character 246) (character #xd0) string) ; siemens oeh -> unix oeh ; sqd
(nsubstitute (character 252) (character #xdd) string) ; siemens ueh -> unix ueh ; sqd
(nsubstitute (character 214) (character #xf0) string) ; siemens OEH -> unix OEH ; andere Codes sind unbekannt! ; dxf
(nsubstitute (character 223) (character #xc5) string) ; dos sz -> unix sz ; dxf
string)
#+:lispworks
(defun recode-german-characters (string)
(dolist (subs '((#\Ö #\U+0095)
(#\Ö #\U+0099)
(#\ß #\U+0089)
(#\ß #\á)
(#\ä #\ø)
(#\ä #\U+0084)
(#\ü #\ð)
(#\ü #\U+0081)
(#\ö #\Soft-Hyphen)
(#\ö #\U+0094)))
(nsubstitute (first subs) (second subs) string))
string)
#+:mcl
(defun recode-german-characters (string)
string)
;;;
;;;
;;;
(defun compute-all-subsets (set &optional (akku '(nil)))
(let ((newakku akku))
(mapl #'(lambda (lset)
(let ((item (first lset)))
(unless (some #'(lambda (set) (member item set)) newakku)
(dolist (expand akku)
(let ((new (cons item expand)))
(push new newakku)))
(setf newakku (compute-all-subsets (rest lset) newakku)))))
set)
newakku))
(defun compute-all-subsets-of-cardinality (set m)
(let ((all nil))
(labels ((do-it (set n)
(cond ((zerop n)
(list nil))
(t
(let ((local nil))
(mapl #'(lambda (res)
(let* ((item (first res))
(res (do-it (rest res) (1- n))))
(dolist (res res)
(push (cons item res) local)
(when (= m n)
(push (cons item res) all)))))
set)
local)))))
(do-it set m)
all)))
(defmacro loop-over-subsets-of-cardinality ((subset set card) &body body)
(let ((n (gensym))
(akku (gensym))
(remset (gensym))
(i (gensym)))
`(labels ((do-it (,remset ,n ,akku)
(if (zerop ,n)
(let ((,subset ,akku))
,@body)
(loop as ,remset on ,remset
as ,i = (first ,remset) do
(do-it (rest ,remset)
(1- ,n)
(cons ,i ,akku))))))
(do-it ,set ,card nil))))
;;;
;;;
;;;
(defun prod-pow-n (xs n)
(if (= n 1)
(mapcar #'list xs)
(prodnx
(loop as i from 1 to n collect xs))))
(defun prod (xs ys)
(reduce
#'nconc
(mapcar #'(lambda (x)
(mapcar #'(lambda (y)
(list x y))
ys))
xs)))
(defun prodn (&rest args)
(reduce #'prod args))
(defun prodnx (arguments)
(reduce #'prod arguments))
(defun newprod (list-of-args)
(if (not (cdr list-of-args))
list-of-args
(let ((list (first list-of-args))
(res (newprod (rest list-of-args))))
(if (not (cddr list-of-args))
(reduce #'append
(mapcar #'(lambda (elem1)
(mapcar #'(lambda (elem2)
(list elem1 elem2))
(first list-of-args)))
(second list-of-args)))
(reduce #'append
(mapcar #'(lambda (list2)
(mapcar #'(lambda (elem1)
(cons elem1 list2))
list))
res))))))
(defun power (xs n)
(mapcar #'tflatten (prod-pow-n xs n)))
#|
(defun perm (list)
(if (cdr list)
(remove-duplicates
(mapcan #'(lambda (a)
(let ((rest (remove a list :count 1)))
(mapcar #'(lambda (rest)
(cons a rest))
(perm rest))))
list)
:test #'equal)
(list list)))
|#
(defun permutations (list &optional (n (length list)) (i 0))
(perm list n i))
(defun perm (list &optional (n (length list)) (i 0))
;;; choose "k" out of "n"
(if (= i n)
'(nil)
(remove-duplicates
(mapcan #'(lambda (a)
(let ((rest (remove a list :count 1)))
(mapcar #'(lambda (rest)
(cons a rest))
(perm rest n (1+ i)))))
list)
:test #'equal)))
(defun is-permutation-p (a b)
(loop as a on a do
(unless (member (first a) b)
(return-from is-permutation-p nil))
(setf b (remove (first a) b :count 1))
(when (and (not b) (cdr a))
(return-from is-permutation-p nil)))
(if b nil t))
;;;
;;;
;;;
(defun fac (n)
(if (minusp n)
0
(if (zerop n)
1
(* n (fac (1- n))))))
(defun n-over-k (n k)
(let ((res (* (fac (- n k)) (fac k))))
(if (zerop res)
0
(/ (fac n) res))))
(defun k-out-of-n (k n)
(/ (fac n) (fac (- n k))))
;;;
;;;
;;;
(defun vector-orientation (fromx fromy tox toy)
(let ((dx (let ((d (- tox fromx)))
(if (< (abs d) 0.0001)
0 d)))
(dy (let ((d (- toy fromy)))
(if (< (abs d) 0.0001)
0 d))))
(if (and (zerop dx) (zerop dy))
(error "~A ~A. Degenerate point vector - no orientation!" dx dy)
(if (zerop dy)
(if (plusp dx)
0
pi)
(if (zerop dx)
(if (plusp dy)
(/ pi 2)
(* 3/2 pi))
(if (plusp dx)
(if (plusp dy)
(atan (/ dy dx))
(- (* 2 pi)
(atan (/ (abs dy) dx))))
(if (plusp dy) ;;; (minusp dx)
(- pi (atan (/ dy (abs dx))))
(+ pi (atan (/ (abs dy) (abs dx)))))))))))
(defun intervall-intersects-p (a b c d)
(not (or (< b c)
(< d a))))
(defun lies-in-circle-intervall-p (x a b)
(if (= a b)
t
(if (<= a b)
(<= a x b)
(or (>= b x) (>= x a)))))
(defun circle-intervall-intersects-p (a b c d)
(or (lies-in-circle-intervall-p b c d)
(lies-in-circle-intervall-p d a b)))
(defun circle-intervall-length (a b &optional (modulo +2pi+))
(if (<= a b)
(- b a)
(+ (- modulo a) b)))
;;;
;;;
;;;
(defun rad-to-deg (phi)
(* 180 (/ phi pi)))
(defun deg-to-rad (phi)
(* pi (/ phi 180)))
(defmacro my-round (num)
`(floor (+ ,num 1/2)))
;;;
;;;
;;;
(defparameter *use-memoization* nil)
(defvar *memo-tables* nil)
(defun reset-memo ()
(mapc #'clrhash *memo-tables*))
(defmacro defun-memo (function-name
lambda-list
(params-to-memoize
&rest hash-args)
&body body)
(let ((hash (apply #'make-hash-table
(append '(:test equal) hash-args))))
(push hash *memo-tables*)
`(defun ,function-name ,lambda-list
(if *use-memoization*
(multiple-value-bind (ret found-p)
(gethash (list ,@params-to-memoize)
,hash)
(if found-p
(apply #'values ret)
(apply #'values
(setf (gethash (list ,@params-to-memoize)
,hash)
(multiple-value-list
(progn ,@body))))))
(progn ,@body)))))
(defmacro defmethod-memo (method-name
lambda-list
(params-to-memoize
&rest hash-args)
&body body)
(let ((hash (apply #'make-hash-table
(append '(:test equal) hash-args))))
(push hash *memo-tables*)
`(defmethod ,method-name ,lambda-list
(if *use-memoization*
(multiple-value-bind (ret found-p)
(gethash (list ,@params-to-memoize)
,hash)
(if found-p
(apply #'values ret)
(apply #'values
(setf (gethash (list ,@params-to-memoize)
,hash)
(multiple-value-list
(progn ,@body))))))
(progn ,@body)))))
;;;
;;;
;;;
(defun change-package-of-description (description &optional (package :cl-user) change-keyword-p (keep-racer-symbols-p t))
(when description
(typecase description
(list
(mapcar #'(lambda (x)
(change-package-of-description x package change-keyword-p keep-racer-symbols-p))
description))
(symbol
(if (and (keywordp description)
(not change-keyword-p))
description
(if (and (eq (symbol-package description)
(find-package :racer))
keep-racer-symbols-p
;;; Racer "interne" Symbole werden beibehalten!!!
)
description
(let ((*package*
(if package (find-package package)
*package*)))
(read-from-string (format nil "|~A|" (symbol-name description)))))))
(otherwise description))))
;;;
;;;
;;;
(defun concept-name (x &optional package)
(let ((x (format nil "~A" x)))
(intern
(nstring-upcase
(string-substitute
(string-substitute x
'((" " " " t)
(" " "-" t)
("." "-" t)
(";" "-" t)
("," "-" t)
("/" "-" t)
("\\" "-" t)
("!" "" t)
("," "-" t)
("(" "-" t)
(")" "" t)
("--" "-" t)))
'(("--" "-" t))))
(or package *package*))))
#+:lispworks
(defun run (fn)
(mp:process-run-function
"Process"
'(:size 250000)
fn))
#+:lispworks
(defun kill (&optional name)
(let ((process (mp:find-process-from-name
(or name "Process"))))
(when process
(mp:process-kill process))))
;;;
;;;
;;;
(defmacro with-standard-output-to-file ((file) &rest body)
`(with-open-file (stream ,file :direction :output :if-exists :supersede)
(let ((*standard-output* stream))
,@body)))
;;;
;;; AVL-Trees laut Wirth
;;;
(defun balance-l (p h)
(macrolet ((item (x)
`(first ,x))
(bal (x)
`(second ,x))
(left (x)
`(third ,x))
(right (x)
`(fourth ,x)))
(case (bal p)
(-1 (setf (bal p) 0))
(0 (setf (bal p) 1
h nil))
(1 (let* ((p1 (right p))
(b1 (bal p1)))
(if (>= b1 0)
(progn
(setf (right p) (left p1)
(left p1) p)
(if (= 0 b1)
(setf (bal p) 1
(bal p1) -1
h nil)
(setf (bal p) 0
(bal p1) 0))
(setf p p1))
(let* ((p2 (left p1))
(b2 (bal p2)))
(setf (left p1) (right p2)
(right p2) p1
(right p) (left p2)
(left p2) p)
(if (= 1 b2)
(setf (bal p) -1)
(setf (bal p) 0))
(if (= -1 b2)
(setf (bal p1) 1)
(setf (bal p1) 0))
(setf p p2
(bal p2) 0))))))
(values p h)))
(defun balance-r (p h)
(macrolet ((item (x)
`(first ,x))
(bal (x)
`(second ,x))
(left (x)
`(third ,x))
(right (x)
`(fourth ,x)))
(case (bal p)
(1 (setf (bal p) 0))
(0 (setf (bal p) -1
h nil))
(-1 (let* ((p1 (left p))
(b1 (bal p1)))
(if (<= b1 0)
(progn
(setf (left p) (right p1)
(right p1) p)
(if (= 0 b1)
(setf (bal p) -1
(bal p1) 1
h nil)
(setf (bal p) 0
(bal p1) 0))
(setf p p1))
(let* ((p2 (right p1))
(b2 (bal p2)))
(setf (right p1) (left p2)
(left p2) p1
(left p) (right p2)
(right p2) p)
(if (= -1 b2)
(setf (bal p) 1)
(setf (bal p) 0))
(if (= 1 b2)
(setf (bal p1) -1)
(setf (bal p1) 0))
(setf p p2
(bal p2) 0))))))
(values p h)))
;; (declaim (inline balance-r balance-l))
(defun find-in-avl-tree (item tree &key
(key #'identity) (compare-fn #'<) (match-fn #'=)
(apply-key-to-item-argument-p t))
(macrolet ((item (x)
`(first ,x))
(bal (x)
`(second ,x))
(left (x)
`(third ,x))
(right (x)
`(fourth ,x)))
(let ((x (if apply-key-to-item-argument-p
(funcall key item)
item)))
(labels ((search-node (p)
(when p
(if (funcall match-fn (funcall key (item p)) x)
(item p)
(if (funcall compare-fn x (funcall key (item p)))
(search-node (left p))
(search-node (right p)))))))
(search-node tree)))))
(defun insert-into-avl-tree* (item tree &key (key #'identity) (compare-fn #'<) (match-fn #'=) (error-p t))
(macrolet ((item (x)
`(first ,x))
(bal (x)
`(second ,x))
(left (x)
`(third ,x))
(right (x)
`(fourth ,x)))
(let ((x (funcall key item)))
(labels ((search-node (p)
(if (not p)
(values (list item 0 nil nil) t)
(if (funcall match-fn (funcall key (item p)) x)
(if error-p (error "Already present!")
(return-from insert-into-avl-tree* tree))
(if (funcall compare-fn x (funcall key (item p)))
(multiple-value-bind (subtree h)
(search-node (left p))
(setf (left p) subtree)
(when h
(case (bal p)
(1 (setf (bal p) 0
h nil))
(0 (setf (bal p) -1))
(-1
;; rebalance
(let ((p1 (left p)))
(if (= (bal p1) -1)
(setf (left p) (right p1)
(right p1) p
(bal p) 0
p p1)
(let ((p2 (right p1)))
(setf (right p1) (left p2)
(left p2) p1
(left p) (right p2)
(right p2) p)
(if (= (bal p2) -1)
(setf (bal p) 1)
(setf (bal p) 0))
(if (= (bal p2) 1)
(setf (bal p1) -1)
(setf (bal p1) 0))
(setf p p2))))
(setf (bal p) 0
h nil))))
(values p h))
;; (> x (item p))
(multiple-value-bind (subtree h)
(search-node (right p))
(setf (right p) subtree)
(when h
(case (bal p)
(-1 (setf (bal p) 0
h nil))
(0 (setf (bal p) 1))
(1
;; rebalance
(let ((p1 (right p)))
(if (= (bal p1) 1)
(setf (right p) (left p1)
(left p1) p
(bal p) 0
p p1)
(let ((p2 (left p1)))
(setf (left p1) (right p2)
(right p2) p1
(right p) (left p2)
(left p2) p)
(if (= (bal p2) 1)
(setf (bal p) -1)
(setf (bal p) 0))
(if (= (bal p2) -1)
(setf (bal p1) 1)
(setf (bal p1) 0))
(setf p p2))))
(setf (bal p) 0
h nil))))
(values p h)))))))
(search-node tree)))))
(defun delete-from-avl-tree* (item tree &key (key #'identity) (compare-fn #'<) (match-fn #'=)
(apply-key-to-item-argument-p t))
(macrolet ((item (x)
`(first ,x))
(bal (x)
`(second ,x))
(left (x)
`(third ,x))
(right (x)
`(fourth ,x)))
(let ((x (if apply-key-to-item-argument-p
(funcall key item)
item)))
(labels ((get-subtree-and-rightmost-item (r)
(if (right r)
(multiple-value-bind (subtree item h)
(get-subtree-and-rightmost-item (right r))
(setf (right r) subtree)
(when h
(multiple-value-bind (nr nh)
(balance-r r h)
(setf r nr
h nh)))
(values r item h))
(progn
(values (left r) (item r) t))))
(delete-it (p h)
(when p
(if (funcall match-fn x (funcall key (item p)))
(cond ((not (right p))
(setf p (left p)
h t))
((not (left p))
(setf p (right p)
h t))
(t
(multiple-value-bind (subtree item nh)
(get-subtree-and-rightmost-item (left p))
(setf (item p) item)
(setf (left p) subtree)
(setf h nh)
(when h
(multiple-value-bind (np nh)
(balance-l p h)
(setf p np
h nh))))))
(if (funcall compare-fn x (funcall key (item p)))
(multiple-value-bind (subtree nh)
(delete-it (left p) h)
(setf (left p) subtree)
(setf h nh)
(when h
(multiple-value-bind (np nh)
(balance-l p h)
(setf p np
h nh))))
(multiple-value-bind (subtree nh)
(delete-it (right p) h)
(setf (right p) subtree)
(setf h nh)
(when h
(multiple-value-bind (np nh)
(balance-r p h)
(setf p np
h nh))))))
(values p h))))
(delete-it tree nil)))))
(defun get-items-from-avl-tree (tree)
(macrolet ((item (x)
`(first ,x))
(bal (x)
`(second ,x))
(left (x)
`(third ,x))
(right (x)
`(fourth ,x)))
(when tree
(cons (item tree)
(append (get-items-from-avl-tree (left tree))
(get-items-from-avl-tree (right tree)))))))
(defmacro loop-over-avl-tree ((var tree &optional finally-return) &rest body)
(let ((fn-sym (gensym))
(node-sym (gensym)))
`(progn
(labels ((,fn-sym (,node-sym)
(when ,node-sym
(let ((,var (first ,node-sym)))
,@body)
(,fn-sym (third ,node-sym))
(,fn-sym (fourth ,node-sym)))))
(,fn-sym ,tree)
,finally-return))))
(defun avl-tree-equal (a b &rest args)
(and (loop-over-avl-tree (x a t)
(unless (apply #'find-in-avl-tree x b args)
(return-from avl-tree-equal nil)))
(loop-over-avl-tree (x b t)
(unless (apply #'find-in-avl-tree x a args)
(return-from avl-tree-equal nil)))))
(defmacro make-avl-tree-from-list (list &rest args)
`(let ((tree nil))
(dolist (item ,list)
(insert-into-avl-tree item tree ,@args))
tree))
(defmacro insert-into-avl-tree (item tree &rest args)
`(setf ,tree (insert-into-avl-tree* ,item ,tree ,@args)))
(defmacro delete-from-avl-tree (item tree &rest args)
`(setf ,tree (delete-from-avl-tree* ,item ,tree ,@args)))
(defun print-avl-tree (tree stream)
(macrolet ((item (x)
`(first ,x))
(bal (x)
`(second ,x))
(left (x)
`(third ,x))
(right (x)
`(fourth ,x)))
(labels ((do-it (tree &optional (level 0) next)
(let ((node (item tree))
(children (remove nil
(list (left tree)
(right tree)))))
(format stream ";;;")
(if (= level 0)
(format stream " ~A~%" node)
(progn
(dolist (item (butlast next))
(if item
(format stream " |")
(format stream " ")))
(let ((last (first (last next))))
(if last
(format stream " |---~A~%" node)
(format stream " \\___~A~%" node)))))
(let ((last (first (last children))))
(dolist (child children)
(do-it child (1+ level) (append next (list (not (eq child last))))))))))
(do-it tree))))
#|
(defun test-avl-trees (n)
(loop
(let* ((keys (reorder (loop as i from 1 to n collect i)))
(tree nil))
(princ "*")
(dolist (key keys)
(setf tree (insert-into-avl-tree key tree)))
(dolist (key (reorder keys))
(unless tree (error "!"))
(setf tree (delete-from-avl-tree key tree)))
(when tree (error "!")))))
|#
(defmacro measure-time (&body body)
`(let ((t1 (get-internal-real-time)))
,@body
(round
(/ (- (get-internal-real-time) t1)
internal-time-units-per-second))))
| 36,116 | Common Lisp | .lisp | 1,034 | 21.181818 | 121 | 0.415525 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | b7157a4d3afdd76d9a8df0cf3c8ca08311b79fe72b97dc8a2520cb2425027181 | 12,491 | [
-1
] |
12,492 | heap.lisp | lambdamikel_DLMAPS/src/tools/heap.lisp | ;; -*- Mode: LISP; Syntax: Common-Lisp; Package: HEAP -*-
;;;
;;; $Header: /home/gene/library/website/docsrc/lisp-heap/RCS/heap.lisp,v 201.1 2004/08/31 06:49:54 gene Exp $
;;;
;;; Copyright (c) 2002, 2003 Gene Michael Stover.
;;;
;;; This library is free software; you can redistribute it
;;; and/or modify it under the terms of version 2.1 of the GNU
;;; Lesser General Public License as published by the Free
;;; Software Foundation.
;;;
;;; This library 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 library; if not, write to the
;;; Free Software Foundation, Inc., 59 Temple Place, Suite 330,
;;; Boston, MA 02111-1307 USA
;;;
(in-package :heap)
(defstruct heap
less-fn
order
a
max-count)
(defun percolate-down (heap hole x)
"Private. Move the HOLE down until it's in a location suitable for X.
Return the new index of the hole."
(do ((a (heap-a heap))
(less (heap-less-fn heap))
(child (lesser-child heap hole) (lesser-child heap hole)))
((or (>= child (fill-pointer a)) (funcall less x (aref a child)))
hole)
(setf (aref a hole) (aref a child)
hole child)))
(defun percolate-up (heap hole x)
"Private. Moves the HOLE until it's in a location suitable for holding
X. Does not actually bind X to the HOLE. Returns the new
index of the HOLE. The hole itself percolates down; it's the X
that percolates up."
(let ((d (heap-order heap))
(a (heap-a heap))
(less (heap-less-fn heap)))
(setf (aref a 0) x)
(do ((i hole parent)
(parent (floor (/ hole d)) (floor (/ parent d))))
((not (funcall less x (aref a parent))) i)
(setf (aref a i) (aref a parent)))))
(defun heap-init (heap less-fn &key (order 2) (initial-contents nil))
"Initialize the indicated heap. If INITIAL-CONTENTS is a non-empty
list, the heap's contents are intiailized to the values in that
list; they are ordered according to LESS-FN. INITIAL-CONTENTS must
be a list or NIL."
(setf (heap-less-fn heap) less-fn
(heap-order heap) order
(heap-a heap) (make-array 2 :initial-element nil
:adjustable t :fill-pointer 1)
(heap-max-count heap) 0)
(when initial-contents
(dolist (i initial-contents) (vector-push-extend i (heap-a heap)))
(loop for i from (floor (/ (length (heap-a heap)) order)) downto 1
do (let* ((tmp (aref (heap-a heap) i))
(hole (percolate-down heap i tmp)))
(setf (aref (heap-a heap) hole) tmp)))
(setf (heap-max-count heap) (length (heap-a heap))))
heap)
(defun create-heap (less-fn &key (order 2) (initial-contents nil))
(heap-init (make-heap) less-fn :order order
:initial-contents initial-contents))
(defun heap-clear (heap)
"Remove all elements from the heap, leaving it empty. Faster
(& more convenient) than calling HEAP-REMOVE until the heap is
empty."
(when heap
(setf (fill-pointer (heap-a heap)) 1)
nil))
(defun heap-count (heap)
(1- (fill-pointer (heap-a heap))))
(defun heap-empty-p (heap)
"Returns non-NIL if & only if the heap contains no items."
(= (fill-pointer (heap-a heap)) 1))
(defun heap-insert (heap x)
"Insert a new element into the heap. Return the element (which probably
isn't very useful)."
(let ((a (heap-a heap)))
;; Append a hole for the new element.
(vector-push-extend nil a)
;; Move the hole from the end towards the front of the
;; queue until it is in the right position for the new
;; element.
(setf (aref a (percolate-up heap (1- (fill-pointer a)) x)) x)))
(defun heap-items (heap)
(unless (heap-empty-p heap)
(loop as i from 1 to (1- (fill-pointer (heap-a heap))) collect (aref (heap-a heap) i))))
(defmacro loop-over-heap-items ((var heap) &body body)
(let ((ivar (gensym)))
`(unless (heap-empty-p ,heap)
(loop as ,ivar from 1 to (1- (fill-pointer (heap-a ,heap)))
do
(let ((,var (aref (heap-a ,heap) ,ivar)))
,@body)))))
(defun heap-find-idx (heap fnp)
"Return the index of the element which satisfies the predicate FNP.
If there is no such element, return the fill pointer of HEAP's array A."
(do* ((a (heap-a heap))
(fp (fill-pointer a))
(i 1 (1+ i)))
((or (>= i fp) (funcall fnp heap (aref a i)))
i)))
(defun heap-find (heap fnp)
(let ((a (heap-a heap))
(i (heap-find-idx heap fnp)))
(when (< i (fill-pointer a))
(aref a i))))
(defun heap-remove-item (heap item)
(heap-remove heap #'(lambda (h x)
(declare (ignorable h))
(eq x item))))
(defun heap-find-item (heap item)
(heap-find heap #'(lambda (h x)
(declare (ignorable h))
(eq x item))))
(defun heap-remove (heap &optional (fn #'(lambda (h x)
(declare (ignorable h x))
t)))
"Remove the minimum (first) element in the heap & return it. It's
an error if the heap is already empty. (Should that be an error?)"
(unless heap (error "no heap?"))
(unless (heap-empty-p heap)
(let ((a (heap-a heap))
(i (heap-find-idx heap fn)))
(cond ((< i (fill-pointer a));; We found an element to remove.
(let ((x (aref a i))
(last-object (vector-pop a)))
(setf (aref a (percolate-down heap i last-object)) last-object)
x))
(t nil)))));; Nothing to remove
(defun heap-peek (heap)
"Return the first element in the heap, but don't remove it. It'll
be an error if the heap is empty. (Should that be an error?)"
(unless (heap-empty-p heap)
(aref (heap-a heap) 1)))
(defun lesser-child (heap parent)
"Return the index of the lesser child. If there's one child,
return its index. If there are no children, return
(FILL-POINTER (HEAP-A HEAP))."
(let* ((a (heap-a heap))
(left (* parent (heap-order heap)))
(right (1+ left))
(fp (fill-pointer a)))
(cond ((>= left fp) fp)
((= right fp) left)
((funcall (heap-less-fn heap) (aref a left) (aref a right)) left)
(t right))))
(provide "heap")
;;; --- end of file ---
| 6,405 | Common Lisp | .lisp | 159 | 35.289308 | 109 | 0.634229 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d8dab8117f1854b8dd37766f6ae24560553b60a08edee070ace93b911b17bcfb | 12,492 | [
-1
] |
12,493 | logic-tools.lisp | lambdamikel_DLMAPS/src/tools/logic-tools.lisp | ;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: TOOLS -*-
(in-package :tools)
(defmethod macroreldef ((obj symbol))
nil)
(defun nnf (concept &optional negate-p)
(if (consp concept)
(let ((op (first concept)))
(if (eq op 'not)
(nnf (second concept) (not negate-p))
(case op
(=> (nnf `(or (not ,(second concept))
,(third concept))
negate-p))
(<= (nnf `(or (not ,(third concept))
,(second concept))
negate-p))
(<=> (nnf `(and (or (not ,(third concept))
,(second concept))
(or (not ,(second concept))
,(third concept)))
negate-p))
(and `(,(if negate-p 'or 'and)
,@(mapcar #'(lambda (x) (nnf x negate-p)) (rest concept))))
(or `(,(if negate-p 'and 'or)
,@(mapcar #'(lambda (x) (nnf x negate-p)) (rest concept))))
(all
(cond ((consp (second concept))
(nnf `(and ,@(mapcar #'(lambda (role)
`(all ,role ,(third concept)))
(second concept)))
negate-p))
((macroreldef (second concept))
(nnf `(and ,@(mapcar #'(lambda (role)
`(all ,role ,(third concept)))
(macroreldef (second concept))))
negate-p))
(t
(if (eq (second concept) 'id)
(nnf (third concept) negate-p)
`(,(if negate-p 'some 'all)
,(second concept) ,(nnf (third concept)
negate-p))))))
(some
(cond ((consp (second concept))
(nnf `(or ,@(mapcar #'(lambda (role)
`(some ,role ,(third concept)))
(second concept)))
negate-p))
((macroreldef (second concept))
(nnf `(or ,@(mapcar #'(lambda (role)
`(some ,role ,(third concept)))
(macroreldef (second concept))))
negate-p))
(t
(if (eq (second concept) 'id)
(nnf (third concept) negate-p)
`(,(if negate-p 'all 'some)
,(second concept) ,(nnf (third concept)
negate-p)))))))))
(if negate-p
`(not ,concept)
concept)))
(defun flatten (concept)
(if (consp concept)
(let ((op (first concept)))
(case op
((and or => <= <=>)
(if (not (third concept))
(flatten (second concept))
(let ((args
(remove-duplicates
(apply #'append
(mapcar #'(lambda (x)
(let ((res (flatten x)))
(if (consp res)
(if (eq (first res) op)
(rest res)
res)
(list res))))
(rest concept)))
:test #'(lambda (x y) (set-equal (ensure-list x) (ensure-list y))))))
(if (cdr args)
`(,op ,@args)
(first args)))))
((some all)
`(,op ,(second concept)
,(flatten (third concept))))
(not
`(,op ,(flatten (second concept))))))
concept))
(defun dnf (concept)
(boolean-dnf concept))
(defun boolean-dnf (concept)
(labels ((simple-simplify (concept)
(if (not (consp concept))
concept
(let ((op (first concept)))
(if (member op '(and or))
(let ((args
(remove-duplicates
(apply #'append
(mapcar #'(lambda (x)
(cond ((symbolp x) (list x))
((and (consp x)
(eq (first x) 'not))
(list x))
((and (consp x)
(eq (first x) op))
(rest x))
(t (list x))))
(rest concept)))
:test #'(lambda (x y) (set-equal (ensure-list x) (ensure-list y))))))
(if (cdr args)
(cons op args)
(first args)))
concept))))
(rewrite (concept)
(if (or (and (consp concept)
(eq (first concept) 'not))
(not (consp concept)))
concept
(let ((op (first concept))
(args (rest concept)))
(if (eq op 'or)
(simple-simplify
(cons 'or (mapcar #'rewrite args)))
;; op="and"; args kommen in DNF wieder => beginnen mir "or"
(if (eq op 'and)
(let* ((args (mapcar #'(lambda (x)
(let ((x (rewrite x)))
(if (or (symbolp x)
(and (consp x)
(or (eq (first x) 'not)
(eq (first x) 'some)
(eq (first x) 'all))))
(list 'or x)
x)))
args))
(or-terms (remove-if-not #'(lambda (x)
(and (consp x)
(eq (first x) 'or)))
args))
(non-or-terms (remove-if #'(lambda (x)
(and (consp x)
(eq (first x) 'or)))
args)))
(simple-simplify
(if or-terms
(let ((crosprod (newprod
(mapcar #'rest or-terms))))
(cons 'or
(mapcar #'(lambda (or-term)
(simple-simplify
(cons 'and (append non-or-terms
or-term))))
crosprod)))
(cons 'and args))))
;; op=some or op=all
(list op
(second concept)
(rewrite (third concept)))))))))
(rewrite concept)))
;;;
;;;
;;;
(defun trafo (c)
(if (symbolp c)
c
(let ((op (first c))
(args (rest c))
(role (second c))
(qual (third c)))
(case op
(not `(not ,(trafo (first args))))
((and or)
`(,op ,@(mapcar #'trafo args)))
(some
(case role
(eq
(if (and (consp qual)
(eq (first qual) 'or))
`(or ,@(mapcar #'(lambda (x) (trafo `(some eq ,x))) (rest qual)))
(multiple-value-bind (mp bp)
(modal-and-boolean-part-of (nnf qual))
`(or (and ,@(mapcar #'trafo mp)
,@(when bp
`((some eq* (and EQN ,@bp)))))
,(trafo qual)))))
(otherwise
`(some ,role ,(trafo `(some eq ,qual))))))
(all
(case role
(eq
(if (and (consp qual)
(eq (first qual) 'or))
(let ((qual (nnf
(cons 'and
(mapcar #'(lambda (x)
(list 'not x))
(rest qual))))))
`(not ,(trafo `(some eq ,qual))))
(multiple-value-bind (mp bp)
(modal-and-boolean-part-of qual)
`(and (and ,@(mapcar #'trafo mp)
,@(when bp
`((all eq* (=> EQN (and ,@bp))))))
,(trafo qual)))))
(otherwise
`(all ,role ,(trafo `(all eq ,qual))))))))))
(defun modal-and-boolean-part-of (c)
(labels ((atomic (c)
(or (symbolp c)
(and (consp c)
(eq (first c) 'not)
(symbolp (second c)))))
(bool (x)
(or (atomic x)
(and (consp x)
(or (eq (first x) 'and)
(eq (first x) 'or))))))
(if (atomic c)
(values nil (list c))
(if (or (eq (first c) 'some)
(eq (first c) 'all))
(values (list c) nil)
(if (eq (first c) 'not)
(error "Bad concept! Not in NNF!")
(let ((bp
(remove-if-not #'bool
(rest c)))
(mp
(remove-if-not
#'(lambda (x)
(and (consp x)
(or (eq (first x) 'some)
(eq (first x) 'all))))
(rest c))))
(values mp bp)))))))
;;;
;;;
;;;
(defun simplify-boolean-expression (expr &optional (recursively-p t))
;;; (OP (OP c d)) -> (OP c d) etc.
(if (consp expr)
(let ((op (intern (format nil "~A" (first expr))
:keyword)))
(case op
((:not :neg)
(if recursively-p
`(:not ,(simplify-boolean-expression (second expr)))
expr))
((:and :or :intersection :union :cap :cup)
(let ((args
(remove-duplicates
(if recursively-p
(mapcar #'(lambda (x)
(simplify-boolean-expression x))
(rest expr))
(rest expr))
:test #'equal)))
(if (not args)
(ecase op
((:and :intersection :cap) :top)
((:or :union :cup) :bottom))
(if (not (cdr args))
(first args)
`(,(case op
((:and :intersection :cap) :and)
((:or :union :cup) :or))
,@(reduce #'append
(mapcar #'(lambda (arg)
(if (consp arg)
(if (eq (first arg) op)
(rest arg)
(list arg))
(list arg)))
args)))))))
(otherwise expr)))
expr))
(defun get-boolean-dnf (expr)
;;;
;;; (AND (OR C (NOT D)) (OR E F)) (muss in NNF sein!) ->
;;; (OR (AND C E) (AND C F) (AND (NOT D) E) (AND (NOT D) F))
;;;
(labels ((dnf (expr)
(if (consp expr)
(let ((op (intern (format nil "~A" (first expr))
:keyword)))
(if (member op '(:not :neg))
`(:not ,(second expr))
(let ((args (remove-duplicates (rest expr) :test #'equal)))
(cond ((member op '(:or :union :cup))
(simplify-boolean-expression
(cons :or (mapcar #'dnf args))
nil))
((member op '(:and :intersection :cap))
(let* ((args (mapcar #'(lambda (x)
(let ((x (dnf x)))
(if (or (member (first x) '(:neg :not))
(not (member (first x)
'(:and :or :cup :cap :intersection :union))))
(list :or x)
x)))
args))
(args (remove-duplicates args :test #'equal))
(or-terms (remove-if-not #'(lambda (x)
(member (first x) '(:or :union :cup)))
args))
(non-or-terms (remove-if #'(lambda (x)
(member (first x) '(:or :union :cup)))
args)))
(simplify-boolean-expression
(if or-terms
(let ((crosprod (newprod
(mapcar #'rest or-terms))))
(cons :or
(mapcar #'(lambda (or-term)
(simplify-boolean-expression
(cons :and (append non-or-terms
or-term))))
crosprod)))
(cons :and args))
nil)))
(t expr)))))
expr)))
(dnf (simplify-boolean-expression expr))))
| 14,614 | Common Lisp | .lisp | 326 | 21.263804 | 123 | 0.315584 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | bd6e76f8e62b9236bf6c9ca34dceb43414d190bcad792d60789e2576f5f66c01 | 12,493 | [
-1
] |
12,494 | heap-simple-test.lisp | lambdamikel_DLMAPS/src/tools/heap-simple-test.lisp | ;;;
;;; $Header: /home/gene/library/website/src/htdocs/lisp-heap/RCS/test.lisp,v 1.3 2003/03/21 15:30:58 gene Exp gene $
;;;
;;; Copyright (c) 2003 by Gene Michael Stover.
;;; All rights reserved.
;;; Permission to copy, store, & view this document unmodified &
;;; in its entirety is granted.
;;;
(require "heap" '("heap.lisp"))
;;;
;;; Create a heap to hold integers \& nothing
;;; else. Order the integers from small to
;;; large.
;;;
(defvar *h* (heap::create-heap #'<))
(pprint (heap:heap-empty-p *h*))
;;;
;;; Insert some hard-coded integers into the heap.
;;; Notice that they are out of order.
;;;
(dolist (i '(5 3 8))
(heap::heap-insert *h* i))
(pprint (heap:heap-empty-p *h*))
(pprint (list (heap:heap-items *h*)))
;;;
;;; Remove the items from the heap & print them.
;;; It should print 3, then 5, then 8.
;;;
(pprint (list (heap:heap-find *h* #'(lambda (h x) (= x 3)))
(heap:heap-find *h* #'(lambda (h x) (= x 13)))))
(pprint (list (heap:heap-items *h*)))
(print (list (heap:heap-remove *h*)
(heap:heap-remove *h*)))
(pprint (list (heap:heap-items *h*)))
(pprint (heap:heap-empty-p *h*))
(print (list (heap:heap-remove *h*)
(heap:heap-remove *h*)))
(pprint (heap:heap-empty-p *h*))
;;; --- end of file ---
| 1,288 | Common Lisp | .lisp | 39 | 30.25641 | 116 | 0.622441 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 2ef4e62e30ae2603370f7e8adb041160d5543d85bad5ed95ef2795fc99d8472b | 12,494 | [
-1
] |
12,495 | class-browser.lisp | lambdamikel_DLMAPS/src/tools/class-browser.lisp | (in-package :TOOLS)
(defun make-postscript-file (application-frame filename)
(with-open-file (stream filename
:direction :output
:if-exists :supersede)
(clim:with-output-to-postscript-stream (ps-stream stream
:scale-to-fit t)
(draw-display application-frame ps-stream))))
(define-application-frame class-browser ()
((root-node :initform (find-class 'clim:design)
:initarg :root-node
:accessor root-node)
(app-stream :initform nil :accessor app-stream))
(:panes (display :application
:display-function 'draw-display
:display-after-commands :no-clear))
(:layouts
(:defaults
(horizontally () display))))
(defmethod draw-display ((frame class-browser) stream)
(indenting-output (stream '(8 :character))
(format-graph-from-roots (root-node *application-frame*)
#'draw-class-node
#'clos:class-direct-subclasses
:stream stream
:center-nodes nil
:arc-drawer
#'(lambda (stream from-object
to-object x1 y1
x2 y2
&rest
drawing-options)
(declare (dynamic-extent
drawing-options))
(declare (ignore from-object
to-object))
(apply #'draw-arrow* stream
x1 y1 x2 y2 drawing-options))
:merge-duplicates t)
(setf (app-stream frame) stream)))
(define-presentation-type node ())
(defun draw-class-node (object stream)
(with-output-as-presentation (stream object 'node)
(surrounding-output-with-border
(stream :shape :rectangle)
(format stream "~A"
(class-name object)))))
(define-class-browser-command (exit :menu "Exit") ()
(frame-exit *application-frame*))
(define-class-browser-command (com-ps-file :menu "Make Postscript File") ()
(make-postscript-file *application-frame*
"dag.ps" ))
(defun class-browser (&optional (root-node (find-class 'basic-sheet))
(port (find-port)))
(if (atom root-node) (setf root-node (list root-node)))
(let ((class-browser (make-application-frame 'class-browser
:frame-manager
(find-frame-manager
:port port)
:width 800
:height 600
:root-node root-node)))
(run-frame-top-level class-browser)))
(defun show-subclasses (class)
(class-browser (find-class class)))
| 3,287 | Common Lisp | .lisp | 65 | 29.369231 | 75 | 0.460962 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | fd7ec2ac7eb67e33d98f59295b7cf03acc7ebe7ba4a6fcbaaca358d65a1c9a16 | 12,495 | [
-1
] |
12,496 | grapher.lisp | lambdamikel_DLMAPS/src/tools/grapher.lisp | ;;; -*- Mode: Lisp; Package: CL-USER -*-
;;;
;;; ****************************************************************
;;; PostScript DAG Grapher *****************************************
;;; ****************************************************************
;;; Written by Joseph Bates, CMU CSD, March 1988. [email protected]
;;;
;;; The PSGrapher is a set of Lisp routines that can be called to produce
;;; PostScript commands that display a directed acyclic graph.
;;;
;;; Modifications History:
;;;
;;; 1993 franconi set rotation variable
;;; JULY 90 mkant Fixed shrink mode so that it scales x and y
;;; axes uniformly (e.g., aspect ratio = 1).
;;; MAY 90 Chiles Made exported specials have stars.
;;; APR 90 Skef Now lives in PSGRAPH package (instead of USER,
;;; or *package*...) with user-tweakable stuff exported.
;;; Node equivalence function can now be specified as
;;; EQ, EQUAL, or EQUALP.
;;; DEC 88 Bates Modified to include optional insert param. to psgraph.
;;; MAR 88 Bates File created.
;;;
(defstruct psnode
name
info
children
parents
appears-in-top-sort
children-appear-in-top-sort
yvalue
height
)
(defvar *max-psnodes* 5000)
(defvar *extra-x-spacing* 20)
(defvar *extra-y-spacing* 6)
(defvar *fontname* "Helvetica")
(defvar *fontsize* 10)
(defvar *second-fontname* "Helvetica-Oblique")
(defvar *second-fontsize* 8)
(defvar *boxgray* ".2") ;; 0 is black, 1 is white
(defvar *boxkind* "stroke") ;; stroke for outline, fill for solid
(defvar *edgewidth* ".5") ;; .5 is thin lines, 1 is fairly thick
(defvar *edgegray* ".2") ;; dark, but not solid black, lines
(defvar *edgecap* "1") ;; round the line caps
(defvar *textgray* "0") ;; solid black text
(defvar *pageheight* 720)
(defvar *pagewidth* (+ (* 7 72) 36))
(defvar *boxradius* (floor *fontsize* 2))
(defvar *boxedge* (floor *fontsize* 4))
(defvar *chunksize* 400)
(defvar *rotation-angle* 0) ;;; E.Franconi: rotation variable
(defvar num-psnodes)
(defvar narray)
(defvar psnode-index)
(defvar child-function)
(defvar info-function)
(defvar top-sort)
(defvar maximum-y)
(defvar minimum-y)
(defvar rows)
(defvar y-offset)
(defvar psnodes-at-y)
(defvar ancestor-cache)
(defun psgraph (root childf infof &optional (shrink nil) (insert nil) (test #'equal)
rotate)
(unless (member test (list 'eq 'equal 'equalp #'eq #'equal #'equalp))
(error "Test must be a function suitable to hand to Make-Hash-Table."))
;;; E.Franconi: set rotation variable
(cond ((numberp rotate)
(setf *rotation-angle* rotate))
(rotate (setf *rotation-angle* 90.0))
(t (setf *rotation-angle* 0)))
(when insert (setf shrink t))
(setq narray (make-array *max-psnodes*))
(setq num-psnodes 0)
(setq psnode-index (make-hash-table :test test
:size 500
:rehash-size 2.0))
(setq child-function childf)
(setq info-function infof)
(setq ancestor-cache (make-hash-table :test test
:size 1000
:rehash-size 2.0))
;;; walk the graph computing node info
(walk-graph root)
(dotimes (index num-psnodes)
(setf (psnode-parents (aref narray index))
(nreverse (psnode-parents (aref narray index))))
(setf (psnode-children (aref narray index))
(nreverse (psnode-children (aref narray index)))))
;;; topological sort the graph
(setq top-sort nil)
(top-sort-node 0)
(setq top-sort (nreverse top-sort))
;;; declare this as a PostScript file
(format t "%!PS-Adobe-1.0~%")
;;; this is required for the Apple LaserWriter (it likes to know the page
;;; ordering so that it can print pages upside down). It is best not to
;;; confuse the LaserWriter when inserting things into a other documents.
(when (not insert)
(format t "%%Page: ? ?~%"))
;;; define global functions
(dolist (line '(
"/max {2 copy lt {exch} if pop} def"
"/min {2 copy gt {exch} if pop} def"
"/inch {72 mul} def"
"/drawbox"
" {/height exch def"
" /width exch def"
" /y exch def"
" /x exch def"
" gsave newpath"
" x y boxradius add moveto"
" x y height add x width add y height add boxradius arcto pop pop pop pop"
" x width add y height add x width add y boxradius arcto pop pop pop pop"
" x width add y x y boxradius arcto pop pop pop pop"
" x y x y height add boxradius arcto pop pop pop pop"
" boxgray setgray boxkind grestore"
" } def"
"/printposter"
" {/rows exch def"
" /columns exch def"
" /bigpictureproc exch def"
" newpath"
" leftmargin botmargin moveto"
" 0 pageheight rlineto"
" pagewidth 0 rlineto"
" 0 pageheight neg rlineto"
" closepath clip"
" leftmargin botmargin translate"
" 0 1 rows 1 sub"
" {/rowcount exch def"
" 0 1 columns 1 sub"
" {/colcount exch def"
" gsave"
" pagewidth colcount mul neg"
" pageheight rowcount mul neg"
" translate"
" bigpictureproc"
" gsave showpage grestore"
" grestore"
" } for"
" } for"
" } def"
)) (format t "~A~%" line))
;;; declare arrays
(format t "/xarray ~D array def~%" num-psnodes)
(format t "/widtharray ~D array def~%" num-psnodes)
;;; define global settings
(format t "/leftmargin 36 def~%")
(format t "/botmargin 36 def~%")
(format t "/pagewidth ~D def~%" *pagewidth*)
(format t "/pageheight ~D def~%" *pageheight*)
(format t "/boxradius ~D def ~%" *boxradius*)
(format t "/boxedge ~D def ~%" *boxedge*)
(format t "/boxgray ~A def ~%" *boxgray*)
(format t "/boxkind {~A} def~%" *boxkind*)
;;; compute width and height of each node
(format t "/~A findfont ~D scalefont setfont~%" *fontname* *fontsize*)
(dotimes (index num-psnodes)
(format t "widtharray ~D (~A) stringwidth pop put~%"
index
(car (psnode-info (aref narray index)))))
(format t "/~A findfont ~D scalefont setfont~%"
*second-fontname* *second-fontsize*)
(dotimes (index num-psnodes)
(format t "widtharray ~D get~%" index)
(dolist (info (cdr (psnode-info (aref narray index))))
(format t "(~A) stringwidth pop max~%" info))
(format t "~D add widtharray exch ~D exch put~%"
(* 2 *boxedge*)
index))
(dotimes (index num-psnodes)
(setf (psnode-height (aref narray index))
(+ (* 2 *boxedge*)
*extra-y-spacing*
*fontsize*
(* (- (length (psnode-info (aref narray index))) 1)
*second-fontsize*))))
;;; compute x location of each node
(format t "xarray 0 0 put~%")
(dolist (index (cdr top-sort))
(let ((parents (psnode-parents (aref narray index))))
(format t "xarray ~D get widtharray ~D get add~%"
(car parents) (car parents))
(dolist (parent (cdr parents))
(format t "xarray ~D get widtharray ~D get add max~%"
parent parent))
(format t "~D add xarray exch ~D exch put~%" *extra-x-spacing* index)))
;;; compute maximum x used
(format t "/maximum-x 0~%")
(dotimes (index num-psnodes)
(format t "xarray ~D get widtharray ~D get add max~%"
index index))
(format t "def~%")
;;; compute y location of each node and maximum and minimum y used
(setq maximum-y 0)
(setq minimum-y 0)
(setq psnodes-at-y (make-hash-table :test test
:size (* num-psnodes *fontsize*)
:rehash-size 2.0))
(let ((currenty 0))
(dolist (index (reverse top-sort))
(let (desired-y)
(cond ((null (psnode-children (aref narray index)))
(setf desired-y currenty)
(setf currenty (+ currenty (psnode-height
(aref narray index)))))
(t
(let ((children (psnode-children (aref narray index)))
(ysum 0))
(dolist (child children)
(setf ysum (+ ysum (psnode-yvalue (aref narray child)))))
(setq desired-y (floor ysum (length children))))))
;;; We may not be able to put the node at the desired y.
;;; If there is another node that overlaps in the y direction
;;; and that node is neither a parent* nor child* (hence its x
;;; location may overlap this one) then we have to choose
;;; another y value -- we choose the nearest (up or down)
;;; location so that there is no possible overlap in y or x.
(let ((height (psnode-height (aref narray index)))
(related (make-hash-table :test test
:size (+ 50 num-psnodes)
:rehash-size 2.0))
collision
upward-bot
upward-top
downward-bot
downward-top)
(setq upward-bot desired-y)
(setq upward-top upward-bot)
(setq downward-top (- (+ desired-y height) 1))
(setq downward-bot downward-top)
(loop
;;; check upward-top for collision
(setq collision nil)
(dolist (n (gethash upward-top psnodes-at-y))
(let ((r (gethash n related)))
(when (null r)
(setf r (related-classes n index))
(setf (gethash n related) r))
(when (eql r 'no)
(setq collision t)
(return))))
;;; if no collision and big enough space then we win
(incf upward-top)
(when (and (not collision) (= (- upward-top upward-bot) height))
(setf desired-y upward-bot)
(return))
(when collision
(setf upward-bot upward-top))
;;; check downward-bot for collision
(setq collision nil)
(dolist (n (gethash downward-bot psnodes-at-y))
(let ((r (gethash n related)))
(when (null r)
(setf r (related-classes n index))
(setf (gethash n related) r))
(when (eql r 'no)
(setq collision t)
(return))))
;;; if no collision and big enough space then we win
(decf downward-bot)
(when (and (not collision) (= (- downward-top downward-bot) height))
(setf desired-y (+ 1 downward-bot))
(return))
(when collision
(setf downward-top downward-bot))
)
;;; add our name to psnodes-at-y table
(dotimes (i height)
(push index (gethash (+ i desired-y) psnodes-at-y)))
(setf (psnode-yvalue (aref narray index)) desired-y)
)
(setf minimum-y (min minimum-y (psnode-yvalue (aref narray index))))
(setf maximum-y
(max maximum-y (+ (psnode-yvalue (aref narray index))
(psnode-height (aref narray index))))))))
;;; compute y-offset to center graph vertically
(setq rows (ceiling (- maximum-y minimum-y) *pageheight*))
(setq y-offset (- (floor (- (* rows *pageheight*) (- maximum-y minimum-y)) 2)
minimum-y))
(when shrink (setq y-offset (- 0 minimum-y)))
;;; create dictionary big enough to hold all the
;;; procedures defined below and make it a current dictionary
(format t "~D dict begin~%"
(+ (* 4 (+ num-psnodes (ceiling num-psnodes *chunksize*))) 50))
;;; define procedures to display the background box for each node
(dotimes (index num-psnodes)
(format t "/box~D {~%" index)
(format t "xarray ~D get ~D widtharray ~D get ~D drawbox~%"
index
(+ y-offset
(psnode-yvalue (aref narray index))
(floor *extra-y-spacing* 2))
index
(- (psnode-height (aref narray index)) *extra-y-spacing*))
(format t "} def~%"))
;;; define procedures to display the text info for each node
(dotimes (index num-psnodes)
(let ((yvalue (+ y-offset
(floor *extra-y-spacing* 2)
(floor *fontsize* 5)
*boxedge*
(psnode-yvalue (aref narray index))
(* *second-fontsize*
(- (length (psnode-info (aref narray index))) 1)))))
(format t "/text~D {xarray ~D get boxedge add ~D moveto (~A) show} def~%"
index
index
yvalue
(car (psnode-info (aref narray index))))
(when (not (null (cdr (psnode-info (aref narray index)))))
(format t "/secondtext~D {~%" index)
(dolist (info (cdr (psnode-info (aref narray index))))
(setq yvalue (- yvalue *second-fontsize*))
(format t "xarray ~D get boxedge add ~D moveto (~A) show~%"
index
yvalue
info))
(format t "} def~%"))))
;;; define procedures to display the edges leading into each node
(dotimes (index num-psnodes)
(format t "/edge~D {newpath~%" index)
(dolist (parent (psnode-parents (aref narray index)))
(format t "xarray ~D get widtharray ~D get add ~D moveto~%"
parent
parent
(+ (psnode-yvalue (aref narray parent))
(floor (psnode-height (aref narray parent)) 2)
y-offset))
(format t "xarray ~D get ~D lineto~%"
index
(+ (psnode-yvalue (aref narray index))
(floor (psnode-height (aref narray index)) 2)
y-offset)))
(format t "stroke } def~%"))
;;; Define procedures to display chunks of boxes, text, and edges.
;;; We limit each chunk to at most *chunksize* calls, to avoid overflowing
;;; the Postscript operand stack.
(dotimes (index num-psnodes)
(when (eql (mod index *chunksize*) 0)
(format t "/boxchunk~D {~%" (floor index *chunksize*)))
(format t "box~D~%" index)
(when (or (eql (mod index *chunksize*) (- *chunksize* 1))
(eql index (- num-psnodes 1)))
(format t "} def~%")))
(dotimes (index num-psnodes)
(when (eql (mod index *chunksize*) 0)
(format t "/textchunk~D {~%" (floor index *chunksize*)))
(format t "text~D~%" index)
(when (or (eql (mod index *chunksize*) (- *chunksize* 1))
(eql index (- num-psnodes 1)))
(format t "} def~%")))
(dotimes (index num-psnodes)
(when (eql (mod index *chunksize*) 0)
(format t "/secondtextchunk~D {~%" (floor index *chunksize*)))
(when (not (null (cdr (psnode-info (aref narray index)))))
(format t "secondtext~D~%" index))
(when (or (eql (mod index *chunksize*) (- *chunksize* 1))
(eql index (- num-psnodes 1)))
(format t "} def~%")))
(dotimes (index num-psnodes)
(when (eql (mod index *chunksize*) 0)
(format t "/edgechunk~D {~%" (floor index *chunksize*)))
(format t "edge~D~%" index)
(when (or (eql (mod index *chunksize*) (- *chunksize* 1))
(eql index (- num-psnodes 1)))
(format t "} def~%")))
;;; Define procedure to display entire graph.
;;; First do the boxes, then the edges, then the text.
(format t "/drawgraph { gsave~%")
;;; E.Franconi: set rotation variable
(unless (= *rotation-angle* 0)
(format t "~5,1,,,'0F rotate~%" *rotation-angle*))
(dotimes (i (ceiling num-psnodes *chunksize*))
(format t "boxchunk~D~%" i))
(format t "~A setlinewidth~%" *edgewidth*)
(format t "~A setlinecap~%" *edgecap*)
(format t "~A setgray~%" *edgegray*)
(dotimes (i (ceiling num-psnodes *chunksize*))
(format t "edgechunk~D~%" i))
(format t "~A setgray~%" *textgray*)
(format t "/~A findfont ~D scalefont setfont~%" *fontname* *fontsize*)
(dotimes (i (ceiling num-psnodes *chunksize*))
(format t "textchunk~D~%" i))
(format t "/~A findfont ~D scalefont setfont~%" *second-fontname* *second-fontsize*)
(dotimes (i (ceiling num-psnodes *chunksize*))
(format t "secondtextchunk~D~%" i))
(format t "grestore } def~%")
;;; show the virtual page in as many actual pages as needed
(cond (shrink
;;; shrink the output to fit on one page
(format t "leftmargin botmargin translate~%")
;; Fix so that it scales x and y to the same ratio.
(format t "pagewidth dup maximum-x max div ~
pageheight dup ~D max div ~
min dup scale~%"
(- maximum-y minimum-y))
; (format t "pagewidth dup maximum-x max div pageheight dup ~
; ~D max div scale~%"
; (- maximum-y minimum-y))
(if insert
(format t "drawgraph end~%")
(format t "drawgraph showpage end~%")))
(t
(format t "{drawgraph} maximum-x pagewidth div ceiling ~
~D printposter end~%"
rows)))
)
(defun walk-graph (root)
(when (eql num-psnodes *max-psnodes*)
(error "More than ~D nodes in graph. Graphing aborted."))
(let ((root-index num-psnodes)
(child-names (apply child-function (list root))))
(incf num-psnodes)
(setf (gethash root psnode-index) root-index)
(setf (aref narray root-index) (make-psnode))
(setf (psnode-name (aref narray root-index)) root)
(setf (psnode-info (aref narray root-index))
(apply info-function (list root)))
(setf (psnode-children (aref narray root-index)) nil)
(setf (psnode-parents (aref narray root-index)) nil)
(setf (psnode-appears-in-top-sort (aref narray root-index)) nil)
(setf (psnode-children-appear-in-top-sort (aref narray root-index)) nil)
(dolist (child child-names)
(let ((child-index (gethash child psnode-index)))
(cond (child-index
(push child-index
(psnode-children (aref narray root-index)))
(push root-index
(psnode-parents (aref narray child-index))))
(t
(let ((child-index (walk-graph child)))
(push child-index
(psnode-children (aref narray root-index)))
(push root-index
(psnode-parents (aref narray child-index))))))))
root-index)
)
(defun top-sort-node (index)
(when (not (psnode-appears-in-top-sort (aref narray index)))
;;; make sure the parents are processed
(dolist (parent (psnode-parents (aref narray index)))
(top-sort-parent parent))
;;; add this node to top-sort
(push index top-sort)
(setf (psnode-appears-in-top-sort (aref narray index)) t))
(when (not (psnode-children-appear-in-top-sort (aref narray index)))
(dolist (child (psnode-children (aref narray index)))
(top-sort-node child))
(setf (psnode-children-appear-in-top-sort (aref narray index)) t))
)
(defun top-sort-parent (index)
(when (not (psnode-appears-in-top-sort (aref narray index)))
;;; make sure the parents are processed
(dolist (parent (psnode-parents (aref narray index)))
(top-sort-parent parent))
;;; add this node to top-sort
(push index top-sort)
(setf (psnode-appears-in-top-sort (aref narray index)) t))
)
(defun related-classes (x y)
(cond ((ancestor x y) 'yes)
((ancestor y x) 'yes)
(t 'no))
)
(defun ancestor (x y)
(let ((cached-value (gethash (list x y) ancestor-cache)))
(cond (cached-value (car cached-value))
(t
(setq cached-value
(cond ((equal x y) t)
(t
(some #'(lambda (child) (ancestor child y))
(psnode-children (aref narray x))))))
(setf (gethash (list x y) ancestor-cache) (list cached-value))
cached-value)))
)
| 18,420 | Common Lisp | .lisp | 480 | 33.575 | 86 | 0.627702 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | b8837d4c9832c348f043b935a739ff129b048fa40b57ccb7a0efedcc9d0813f4 | 12,496 | [
-1
] |
12,497 | heap-sort.lisp | lambdamikel_DLMAPS/src/tools/heap-sort.lisp | ;;;
;;; $Header: /home/gene/library/website/docsrc/lisp-heap/RCS/ex11.lisp,v 201.1 2004/08/31 06:49:54 gene Exp $
;;;
;;; Copyright (c) 2003 by Gene Michael Stover.
;;; All rights reserved.
;;; Permission to copy, store, & view this document unmodified &
;;; in its entirety is granted.
;;;
(require "heap" '("heap.lisp"))
(defun heap-sort-basic (lst lessp)
(let ((h (create-heap lessp)))
;; Copy the elements of LST into the heap.
(dolist (x lst) (heap-insert h x))
;; Remove the elements from the heap,
;; collecting them into a new list.
(loop while (not (heap-empty-p h)) collect (heap-remove h))))
(defun heap-sort-smart (lst lessp)
(let ((h (create-heap lessp :initial-contents lst)))
(loop while (not (heap-empty-p h)) collect (heap-remove h))))
(defun ex11 ()
"Compare HEAP-SORT-BASIC & HEAP-SORT-SMART."
(let ((lst (loop for i from 1 to 10000 collect (random 100000))))
(dolist (fn '(heap-sort-basic heap-sort-smart))
(let* ((start-time (get-internal-run-time))
(ignored (funcall fn lst #'<))
(end-time (get-internal-run-time))
(second (/ (- end-time start-time)
internal-time-units-per-second)))
(format t "~&~16A ~5,2F" fn second)))))
;;; --- end of file ---
| 1,248 | Common Lisp | .lisp | 30 | 38.033333 | 109 | 0.648805 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ed5c8932b083d1a43824d126438a40091eedf60f94237ee68b4e3eecef2c1b7f | 12,497 | [
-1
] |
12,498 | qbox-browser2.lisp | lambdamikel_DLMAPS/src/tools/qbox-browser2.lisp | (in-package :TOOLS)
(defvar *node* nil)
(define-application-frame qbox-browser (dag-browser)
((show-equivalents-p :initform t)
(variable-vectors-p :initform t)))
(defmethod accept-options ((frame qbox-browser) stream)
(with-slots (show-equivalents-p
variable-vectors-p
show-top-p show-bottom-p) frame
(formatting-table (stream :multiple-columns t)
(formatting-row (stream)
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'boolean
:prompt "Show Equivalents"
:prompt-mode :raw
:stream stream
:default show-equivalents-p)
(setf show-equivalents-p object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'boolean
:prompt "Show Variable Vectors"
:prompt-mode :raw
:stream stream
:default variable-vectors-p)
(setf variable-vectors-p object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'boolean
:prompt "Show Top"
:prompt-mode :raw
:stream stream
:default show-top-p)
(setf show-top-p object)))
(formatting-cell (stream)
(multiple-value-bind (object)
(accept 'boolean
:prompt "Show Bottom"
:prompt-mode :raw
:stream stream
:default show-bottom-p)
(setf show-bottom-p object)))))))
(defmethod draw-dag-node ((object thematic-substrate::query) stream)
(with-slots (variable-vectors-p show-equivalents-p) *application-frame*
(labels ((draw-it (stream)
(let ((*print-right-margin* 40)
(*print-pretty* t))
(if show-equivalents-p
(if variable-vectors-p
(format stream "~A~%~A~%~A"
(thematic-substrate::all-vois object)
(thematic-substrate::unparse-query object)
(thematic-substrate::equivalents object))
(format stream "~A~%~A"
(thematic-substrate::unparse-query object)
(thematic-substrate::equivalents object)))
(if variable-vectors-p
(format stream "~A~%~A"
(thematic-substrate::all-vois object)
(thematic-substrate::unparse-query object))
(format stream "~A"
(thematic-substrate::unparse-query object)))))))
(with-output-as-presentation (stream object 'node)
(if (not (thematic-substrate::unique-name-assumption-p object))
(surrounding-output-with-border
(stream :shape :rectangle)
(surrounding-output-with-border
(stream :shape :rectangle)
(draw-it stream)))
(surrounding-output-with-border
(stream :shape :rectangle)
(draw-it stream)))))))
| 3,086 | Common Lisp | .lisp | 73 | 29 | 77 | 0.552835 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 2293f20e6990df9aa22f9d744b0f3af78ada285ae50f3f2546676c162f578ba9 | 12,498 | [
-1
] |
12,499 | q-queries.lisp | lambdamikel_DLMAPS/src/map-viewer/q-queries.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: SPATIAL-SUBSTRATE; Base: 10 -*-
(in-package spatial-substrate)
(defun q1 ()
(let ((q '(?*x wohngebiet))
(v '(?*x)))
(inspector-answer-query q v
"Zeige mir alle Wohngebiete.")))
(defun q2 ()
(let ((q '(?*x park))
(v '(?*x)))
(inspector-answer-query q v
"Zeige mir alle Parks.")))
(defun q3 ()
(let ((q '(and (?*x wohngebiet) (?*y gruenflaeche) (?*x ?*y ec)))
(v '(?*x ?*y)))
(inspector-answer-query q v "Zeige mir alle Wohngebiete,
die an einer Grünfläche liegen.")))
(defun q4 ()
(let ((q '(and (?*x park) (?*x ?*y ppi) (?*y teich)))
(v '(?*x ?*y)))
(inspector-answer-query q v "Zeige mir alle Parks,
die einen Teich enthalten.")))
(defun q5 ()
(let ((q '(and (?*x wohngebiet) (?*x ?*y ec) (?*y gruenflaeche) (?*y ?*z ppi) (?*z (:or teich see))))
(v '(?*x ?*y ?*z)))
(inspector-answer-query q v "Zeige mir alle Wohngebiete,
die an einer Grünfläche liegen,
welche einen Teich oder See enthält.")))
(defun q6 ()
(let ((q '(and (?*x wohngebiet)
(?*x ?*y ec)
(?*y gruenflaeche)
(?*y ?*z ppi)
(?*z (:or teich see))
(?*x ?*u ec)
(?*u gewerbe)))
(v '(?*x ?*y ?*z ?*u)))
(inspector-answer-query q v
"Zeige mir alle Wohngebiete,
die an einer Gruenfläche liegen,
welche einen Teich oder See enthält;
das Wohngebiet soll zudem an einem
Gewerbegebiet liegen (zum Einkaufen).")))
(defun q7 ()
(let ((q '(and (?*x (:or teich see))
(?*x ?*y ec)
(?*y (:or fluss bach))
(?*y ?*z (:or ec po))
(?*z wohngebiet)
(?*x ?*w pp)
(?*w park)))
(v '(?*x ?*y ?*z ?*w)))
(inspector-answer-query q v
"Gibt es einen Fluss oder Bach,
der ein Wohngebiet kreutzt,
und dann in einen Teich oder See fließt,
der in einem Park liegt?")))
(defun q8 ()
(let ((q '(and (?*x wohngebiet)
(?*x ?*y (:or ec po))
(?*y autobahn)))
(v '(?*x ?*y)))
(inspector-answer-query q v
"Zeige mir alle Wohngebiete,
die an einer Autobahn liegen.")))
(defun q9 ()
(let ((q '(and (?*x park)
(?*x ?*y (:or ec po))
(?*y autobahn)
(?*x ?*z ppi)
(?*z (and wasser flaeche))))
(v '(?*x ?*y)))
(inspector-answer-query q v
"Zeige mir alle Parks,
die an der Autobahn liegen,
und die eine Wasserfläche enthalten.")))
(defun q10 ()
(let ((q '(and (?*x park)
(?*x ?*y ppi)
(?*y laubbaum)))
(v '(?*x ?*y)))
(inspector-answer-query q v
"Zeige mir alle Parks mit Laubbäumen")))
(defun q11 ()
(let ((q '(and (?*x wald)))
(v '(?*x)))
(inspector-answer-query q v
"Zeige mir alle Wälder.")))
(defun q12 ()
(let ((q
`(?*x (and wohnen
(some ec
(and wiese-weide
(:or (some tppi teich-nicht-schiffbar)
(some ntppi teich-nicht-schiffbar))))
(:or (some tppi oeffentliches-gebaeude)
(some ntppi oeffentliches-gebaeude))
(all ec (:or wiese-weide
parkplatz)))))
(v '(?*x)))
(inspector-answer-query q v
"Zeige mir Wohngebiete,
die an eine Wiese/Weide angrenzen,
die einen Teich enthält,
sodass alle angrenzenden Flächen
ebenfalls Wiesen/Weiden oder
Parkplätze sind.")))
(defun q13 ()
(let ((q '(and (?*wohngebiet wohngebiet)
(?*u-bahn-station u-bahn-station)
(?u-bahn-station ?wohngebiet (:inside-epsilon 100))
(?*wohngebiet ?*teich :contains)
(?*teich (:or :teich :see))))
(v '(?*wohngebiet ?*u-bahn-station ?*teich)))
(inspector-answer-query q v
"Zeige mir Wohngebiete,
die Teiche oder Seen enthalten,
und in deren Epsilon-Umgebung von
100 Metern eine U-Bahn-Station liegt.")))
(defun q14 ()
(let ((q '(and
;; note: Q operator not implemented in MIDELORA:
;; (?*x (and wohngebiet (at-least 8 ntppi gebaeude)))
;; hence:
(?*x (and wohngebiet (at-least 8 ntppi top)))
(?x (:satisfies
(and (geometry::is-geom-polygon-p object)
(> (geometry:calculate-area object) 50000))))))
(v '(?*x)))
(inspector-answer-query q v
"Zeige mir Wohngebiete,
die mindestens 8 Gebäude enthalten,
und deren Fläche größer als 50000 ist.")))
(defun q15 ()
(let ((q '(and (?*x (and wohngebiet (at-least 8 ntppi top)))
(?x (:area (< area 50000)))))
(v '(?*x)))
(inspector-answer-query q v
"Welche Wohngebiete mit mindestens 8 Gebäuden
haben eine Fläche, die kleiner als 5000 ist?")))
(defun q16 ()
(let ((q '(and (?*x :bach)
(?*x ?*y :touches)
(?*y :teich)
(?*x ?*z :crosses)
(?*z :park)
(?*z ?*y :contains)
(?*x ?*w :touches)
(?*w :wohngebiet)))
(v '(?*x ?*y ?*z ?*w)))
(inspector-answer-query q v
"Welcher Bach fließt von einem Wohngebiet
in einen Teich, der in einem Park liegt?")))
(defun q17 ()
(let ((q '(and (?*wohngebiet wohngebiet)
(?*wohngebiet (ALL EC (not (:or industrie gewerbe))))
(?*wohngebiet ?*gebaeude :contains)
(?*gebaeude gebaeude)
(?kirche ?wohngebiet (:inside-epsilon 200))
(?*u-bahn-station u-bahn-station)
(?u-bahn-station ?wohngebiet (:inside-epsilon 100))
(?*wohngebiet ?*teich :contains)
(?*teich (:or :teich :see))
(?*kirche kirche)))
(v
'(?*wohngebiet
?*gebaeude
?*kirche
?*u-bahn-station
?*teich)))
(inspector-answer-query q v
"Zeige mir Wohngebiete,
die nicht an Industrie- oder Gewerbegebiete angrenzen,
die Gebaeude enthalten, und
die eine Kirche in der Epsilon-Umgebung von 200 Metern,
eine U-Bahn-Station im Epsilon-Umkreis von 100 Metern,
sowie einen Teich (oder See) enthalten.")))
(defun q18 ()
(let ((q '(?*x wohngebiet))
(v '(?*x)))
(inspector-answer-query q v
"Zeige mir alle Wohngebiete.")))
(defun q19 ()
(let ((q '(and (?*wohngebiet wohngebiet)
(?u-bahn-station ?wohngebiet (:inside-epsilon 100))))
(v '(?*wohngebiet ?u-bahn-station)))
(inspector-answer-query q v
"Zeige mir Wohngebiete,
in deren Epsilon-Umgebung von
100 Metern eine U-Bahn-Station liegt.")))
(defun q20 ()
)
| 7,239 | Common Lisp | .lisp | 192 | 26.911458 | 103 | 0.497079 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 88811c120090344c91e71525883a57391112d135a91dec23534eefa4ef3e1964 | 12,499 | [
-1
] |
12,500 | result-inspector2.lisp | lambdamikel_DLMAPS/src/map-viewer/result-inspector2.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: SPATIAL-SUBSTRATE; Base: 10 -*-
(in-package spatial-substrate)
(defconstant +x-no-of-thumbnails+ 6)
(defconstant +y-no-of-thumbnails+ 6)
(defconstant +spacing+ 10)
(defconstant +offset-radius+ 100)
(defconstant +light-blue+ (make-rgb-color 0.5 0.5 1))
(defconstant +inspector-text-style+
(make-text-style :sans-serif :bold :large))
(defconstant +inspector-interactor-text-style+
(make-text-style :sans-serif :bold :normal))
;;;
;;; Achtung: die Spatial Atoms (s. spatial-substrate;compiler5.lisp)
;;; können NUR compiliert werden! -> *runtime-evaluation* = NIL
;;; ts::*compile-queries-p* = T bedeutet, dass die erzeugten
;;; Lambdas Lisp-compiliert werden; bei NIL werden sie EVALUIERT
;;; (aber letztlich wurde die Query "compiliert")
;;;
(defparameter *searching-active* nil)
(defparameter *buttons* nil)
(defparameter *draw-thumbnails* t)
(defparameter *inspector-solid-areas* t)
(defparameter *experimental* nil)
(defparameter *exclude-permutations* nil)
(defparameter *inspector-display-binding-names-mode* t)
;;;
;;;
;;;
(defvar *result-inspector-frame* nil)
(defvar *inspector-process*)
;;;
;;;
;;;
(defvar +button-abort+)
(defvar +button-draw-thumbnails+)
(defvar +button-solid-areas+)
(defvar +button-experimental+)
(defvar +button-permutations+)
(defvar +button-show-bindings+)
(defvar +button-next+)
(defvar +button-previous+)
(defvar +button-delete-all-pages+)
(defvar +button-delete-page+)
(defvar +button-delete-selected+)
(defvar +button-delete-unselected+)
(defvar +button-unselect-all+)
;;;
;;;
;;;
(defmacro with-result-inspector ((name) &body body)
`(let ((,name *result-inspector-frame*))
,@body))
(defmacro with-query-result-output (&body body)
`(let ((*display-binding-names-mode*
*inspector-display-binding-names-mode*)
(*solid-areas*
*inspector-solid-areas*)
(*display-nodes-mode* nil)
(*sensitive-objects-mode* nil)
(*highlight-bindings* t))
,@body))
(defmacro with-overview-output (&body body)
`(let ((*display-map-text-mode* nil)
(*display-nodes-mode* nil)
(*sensitive-objects-mode* nil)
(*highlight-bindings* t)
(*solid-areas* *inspector-solid-areas*)
(*display-binding-names-mode*
*inspector-display-binding-names-mode*))
,@body))
;;;
;;;
;;;
(defun result-inspector-running-p ()
*result-inspector-frame*)
(define-command-table query-table
:menu (("Answer Query" :command (com-inspector-answer-query))))
(define-application-frame inspector ()
((pages :accessor pages :initform nil)
(selected-page :accessor selected-page :initform nil)
(active-page :accessor active-page :initform nil)
(selected-query-result :accessor selected-query-result :initform nil)
(map-on-display-p :accessor map-on-display-p :initform nil)
(all-matches :accessor all-matches :initform nil)
(last-percent :initform nil)
(last-time :initform nil))
(:command-table (inspector
:inherit-from (query-table)
:menu (("Query" :menu query-table))))
(:menu-bar nil)
(:panes
(query-results :application
:label
"Query Results"
:initial-cursor-visibility :inactive
:display-after-commands nil
:textcusor nil
:scroll-bars nil
:display-function #'draw-query-results)
(infos :application
:label "Infos"
:text-style +inspector-text-style+
:scroll-bars :both
:textcursor nil
:initial-cursor-visibility :inactive
:end-of-line-action :allow
:end-of-page-action :follow)
(progress-bar :application
:label nil
:borders nil
:scroll-bars nil
:textcursor nil
:initial-cursor-visibility :inactive)
(command :interactor
:text-style +inspector-interactor-text-style+
:scroll-bars :vertical)
(button-abort (setf +button-abort+
(make-pane 'push-button
:label "Abort Search"
:activate-callback 'abort-search)))
(button-draw-thumbnails (setf +button-draw-thumbnails+
(make-pane 'toggle-button
:value *draw-thumbnails*
:default *draw-thumbnails*
:label "DT"
:value-changed-callback 'button-draw-thumbnails)))
(button-show-bindings (setf +button-show-bindings+
(make-pane 'toggle-button
:value *inspector-display-binding-names-mode*
:label "SB"
:default *inspector-display-binding-names-mode*
:value-changed-callback 'button-show-bindings)))
(button-solid-areas (setf +button-solid-areas+
(make-pane 'toggle-button
:value *inspector-solid-areas*
:label "SA"
:default *inspector-solid-areas*
:value-changed-callback 'button-solid-areas)))
(button-experimental (setf +button-experimental+
(make-pane 'toggle-button
:value *experimental*
:default *experimental*
:label "ES"
:value-changed-callback 'button-experimental)))
(button-permutations (setf +button-permutations+
(make-pane 'toggle-button
:value *exclude-permutations*
:default *exclude-permutations*
:label "EP"
:value-changed-callback 'button-permutations)))
(button-previous (setf +button-previous+
(make-pane 'push-button
:label "<< Previous Page <<"
:activate-callback 'previous-page)))
(button-next (setf +button-next+
(make-pane 'push-button
:label ">> Next Page >>"
:activate-callback 'next-page)))
(button-delete-all-pages (setf +button-delete-all-pages+
(make-pane 'push-button
:label "Delete All Pages"
:activate-callback 'delete-all-pages)))
(button-delete-page (setf +button-delete-page+
(make-pane 'push-button
:label "Delete Page"
:activate-callback 'delete-page)))
(button-delete-selected (setf +button-delete-selected+
(make-pane 'push-button
:label "Delete Selected"
:activate-callback 'delete-selected)))
(button-delete-unselected (setf +button-delete-unselected+
(make-pane 'push-button
:label "Delete Unselected"
:activate-callback 'delete-unselected)))
(button-unselect-all (setf +button-unselect-all+
(make-pane 'push-button
:label "Unselect All"
:activate-callback 'unselect-all)))
(page-nr :application
:label nil
:borders nil
:scroll-bars nil
:textcursor nil
:initial-cursor-visibility :inactive
:display-function #'show-page-nr))
(:layouts
(:default
#+(and :lispworks :win32)
(horizontally ()
(1/2 (outl
(vertically ()
(1/26 progress-bar)
(1/26 (horizontally () (1 button-abort) +fill+))
(1/26 (horizontally ()
(1/2 button-previous)
(1/2 button-next)
+fill+))
(1/26 page-nr)
(19/26 query-results)
(1/26 (horizontally ()
(1/2 button-delete-page)
(1/2 button-delete-all-pages)
+fill+))
(1/26 (horizontally ()
(1/3 button-unselect-all)
(1/3 button-delete-selected)
(1/3 button-delete-unselected)
+fill+))
(1/26 (horizontally ()
(1/5 button-draw-thumbnails)
(1/5 button-solid-areas)
(1/5 button-show-bindings)
(1/5 button-experimental)
(1/5 button-permutations)
+fill+)))))
(1/2
(vertically ()
(1/2 (outl infos))
(1/2 (outl
(labelling (:label "Query Processor")
command))))))
#-(and :lispworks :win32)
(horizontally ()
(1/2 (outl
(vertically ()
(1/26 progress-bar)
(1/26 button-abort)
(1/26 (horizontally ()
(1/2 button-previous)
(1/2 button-next)))
(1/26 page-nr)
(19/26 query-results)
(1/26 (horizontally ()
(1/2 button-delete-page)
(1/2 button-delete-all-pages)))
(1/26 (horizontally ()
(1/3 button-unselect-all)
(1/3 button-delete-selected)
(1/3 button-delete-unselected)))
(1/26 (horizontally ()
(1/5 button-draw-thumbnails)
(1/5 button-solid-areas)
(1/5 button-show-bindings)
(1/5 button-experimental)
(1/5 button-permutations))))))
(1/2
(vertically ()
(1/2 (outl infos))
(1/2 (outl
(labelling (:label "Query Processor")
command)))))))))
(defun result-inspector (&key (force t)
left
top
width height
&allow-other-keys)
(let ((port (find-port)))
(when (or force (null *map-viewer-frame*))
(unless left
(multiple-value-bind (screen-width screen-height)
(bounding-rectangle-size
(sheet-region (find-graft :port port)))
(setf left 0
top 0
width screen-width
height screen-height)))
(setf *result-inspector-frame*
(make-application-frame
'inspector
:left left
:top top
:width (- width 40)
:height (- height 100)
:pretty-name "Inspector"))
(setf *inspector-process*
(mp:process-run-function
"Result Inspector"
nil
#'(lambda ()
(run-frame-top-level *result-inspector-frame*))))
*result-inspector-frame*)))
(defmethod frame-standard-output ((frame inspector))
(get-frame-pane frame 'infos))
(defmethod frame-error-output ((frame inspector))
(get-frame-pane frame 'infos))
(defmethod frame-query-io ((frame inspector))
(get-frame-pane frame 'command))
;;;
;;;
;;;
(defun show-search-progress (percent &key force-p)
(with-result-inspector (frame)
(let* ((stream (get-frame-pane frame 'progress-bar))
(time (get-universal-time)))
(with-slots (last-percent last-time) frame
(when (or (not last-percent)
(and (not (= last-percent percent))
(or force-p
(> (- time last-time) 1))))
(multiple-value-bind (width height)
(bounding-rectangle-size (bounding-rectangle stream))
(with-output-recording-options (stream :draw t :record nil)
(when last-percent
(draw-rectangle* stream 0 0 (* (/ last-percent 100) width) height
:ink +background-ink+))
(setf last-percent percent)
(draw-rectangle* stream 0 0 (* (/ percent 100) width) height
:ink +red+)
(setf last-time time))))))))
(defmethod run-frame-top-level :before ((frame inspector) &key)
(lock-buttons)
(deactivate-gadget +button-abort+))
;;;
;;;
;;;
(defclass query-result ()
((bindings :accessor bindings :initarg :bindings)
(selected :accessor selected :initform nil)
(map-radius :accessor map-radius :initarg :map-radius)
(map-xcenter :accessor map-xcenter :initarg :map-xcenter)
(map-ycenter :accessor map-ycenter :initarg :map-ycenter)))
(defclass query-page ()
((objects :accessor objects :initarg :objects :initform nil)))
;;;
;;;
;;;
(defmethod full ((obj query-page))
(= (length (objects obj))
(* +x-no-of-thumbnails+
+y-no-of-thumbnails+)))
(defun make-new-page ()
(with-result-inspector (frame)
(let ((obj (make-instance 'query-page)))
(pushend obj (pages frame))
(setf (active-page frame) obj)
(setf (selected-page frame) obj)
(update-buttons)
obj)))
(defun get-position (obj)
(with-result-inspector (frame)
(when (and obj (selected-page frame))
(let ((pos (position obj (objects (selected-page frame)))))
(when pos
(multiple-value-bind (w h)
(thumbnail-size frame)
(let ((y (floor pos +x-no-of-thumbnails+))
(x (mod pos +x-no-of-thumbnails+)))
(values (+ (* w x) +spacing+)
(+ (* h y) +spacing+)
(- (* w (1+ x)) +spacing+)
(- (* h (1+ y)) +spacing+)))))))))
(defmethod thumbnail-size ((frame inspector))
(multiple-value-bind (width height)
(window-inside-size (get-frame-pane frame 'query-results))
(values (/ (- width 1) +x-no-of-thumbnails+)
(/ (- height 1) +y-no-of-thumbnails+))))
;;;
;;;
;;;
(defclass foobar () ())
(defmethod draw-result ((result query-result) stream w h &key (fast-p t) text-p full-view)
(set-current-map-position-and-radius (map-xcenter result)
(map-ycenter result)
(+ (map-radius result) 50))
(select-query-result result)
(labels ((draw-it ()
(when *draw-thumbnails*
(with-query-result-output
(let ((*display-map-text-mode* text-p))
(draw-current-map-to-foreign-stream stream
:fast-p fast-p
:overview t
:width w
:height h))))))
(let ((bgink +background-ink+)
(fgink +black+))
(if (not full-view)
(progn
(when (selected result)
(setf bgink +red+)
(setf fgink +black+))
(with-output-as-presentation (stream result 'query-result
:single-box t
:allow-sensitive-inferiors nil)
(draw-rectangle* stream -7 -7 (+ 7 w) (+ 7 h)
:ink bgink)
(draw-rectangle* stream 0 0 w h
:ink fgink
:filled nil))
(with-drawing-options (stream
:clipping-region
(make-bounding-rectangle 0 0 (1+ w) (1+ h)))
(with-output-as-presentation (stream result 'foobar
:single-box nil
:allow-sensitive-inferiors nil)
(draw-it))))
(draw-it)))))
(defmethod draw-overview ((frame inspector) stream)
(with-slots (overview-pattern current-map-range
overview-transformation) frame
(multiple-value-bind (width height)
(bounding-rectangle-size (bounding-rectangle (window-viewport stream)))
(when (get-current-map)
(with-overview-output
(full-map-range)
(recalculate-transformation stream :width width :height height)
(with-map-viewer-frame (map-viewer)
(draw-rectangle* stream 0 0 width height
:ink +white+)
(draw-current-map map-viewer stream
:overview t
:fast-p t
:clear-p nil)))))))
(defmethod draw-thumbnail ((result query-result))
(with-result-inspector (frame)
(let ((stream (get-frame-pane frame 'query-results)))
(when (map-on-display-p frame)
(window-clear stream))
(setf (map-on-display-p frame) nil)
(multiple-value-bind (xf yf xt yt)
(get-position result)
(when (and xf yf xt yt)
(with-translation (stream xf yf)
(draw-result result stream (- xt xf) (- yt yf))))))))
;;;
;;;
;;;
(define-presentation-method highlight-presentation ((obj query-result) record stream state)
(declare (ignore state))
(let* ((obj (presentation-object record)))
(multiple-value-bind (xf yf xt yt)
(get-position obj)
(when xf ; get-position kann NIL liefern
(draw-rectangle* stream
xf yf xt yt
:filled nil
:ink +flipping-ink+
:line-thickness 10)))))
#|
(define-presentation-method presentation-refined-position-test ((obj query-result) record stream state)
(break)
|#
(defun get-page-nr ()
(with-result-inspector (frame)
(if (selected-page frame)
(1+ (position (selected-page frame) (pages frame)))
0)))
;;;
;;;
;;;
(defun abort-search (&optional button)
(declare (ignore button))
(thematic-substrate::abort-all-queries))
(defun previous-page (&optional button)
(declare (ignore button))
(with-result-inspector (frame)
(setf (map-on-display-p frame) nil)
(when (selected-page frame)
(let ((pos (position (selected-page frame) (pages frame))))
(unless (zerop pos)
(setf (selected-page frame)
(nth (1- pos) (pages frame)))
(update-buttons))))))
(defun next-page (&optional button)
(declare (ignore button))
(with-result-inspector (frame)
(setf (map-on-display-p frame) nil)
(let ((rest (rest (member (selected-page frame) (pages frame)))))
(when rest
(setf (selected-page frame) (first rest))
(update-buttons)))))
(defun delete-all-pages (&optional button)
(declare (ignore button))
(with-result-inspector (frame)
(setf (map-on-display-p frame) nil)
(setf (pages frame) nil
(active-page frame) nil
(selected-page frame) nil)
(update-buttons)))
(defun delete-page (&optional button)
(declare (ignore button))
(with-result-inspector (frame)
(setf (map-on-display-p frame) nil)
(when (selected-page frame)
(setf (pages frame)
(delete (selected-page frame)
(pages frame)))
(setf (selected-page frame)
(first (pages frame)))
(update-buttons))))
(defun delete-selected (&optional button)
(declare (ignore button))
(with-result-inspector (frame)
(setf (map-on-display-p frame) nil)
(when (selected-page frame)
(dolist (obj (remove-if-not #'selected (objects (selected-page frame))))
(setf (objects (selected-page frame))
(delete obj (objects (selected-page frame)))))
(if (objects (selected-page frame))
(update-buttons)
(delete-page +button-delete-page+)))))
(defun delete-unselected (&optional button)
(declare (ignore button))
(with-result-inspector (frame)
(setf (map-on-display-p frame) nil)
(when (selected-page frame)
(dolist (obj (remove-if #'selected (objects (selected-page frame))))
(setf (objects (selected-page frame))
(delete obj (objects (selected-page frame)))))
(if (objects (selected-page frame))
(update-buttons)
(delete-page +button-delete-page+)))))
(defun unselect-all (&optional button)
(declare (ignore button))
(with-result-inspector (frame)
(setf (map-on-display-p frame) nil)
(when (selected-page frame)
(dolist (obj (objects (selected-page frame)))
(setf (selected obj) nil))
(update-buttons))))
(defun button-draw-thumbnails (button value)
(declare (ignore button))
(setf *draw-thumbnails* value)
(with-result-inspector (frame)
(redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t)))
(defun button-show-bindings (button value)
(declare (ignore button))
(setf *inspector-display-binding-names-mode* value)
(with-result-inspector (frame)
(redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t)))
(defun button-solid-areas (button value)
(declare (ignore button))
(setf *inspector-solid-areas* value)
(with-result-inspector (frame)
(redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t)))
(defun button-permutations (button value)
(declare (ignore button))
(setf *exclude-permutations* value))
(defun button-experimental (button value)
(declare (ignore button))
(setf *experimental* value))
;;;
;;;
;;;
(defun lock-buttons ()
(dolist (button (list +button-previous+ +button-next+
+button-delete-all-pages+ +button-delete-page+
+button-delete-selected+ +button-delete-unselected+
+button-unselect-all+))
(deactivate-gadget button))
(activate-gadget +button-abort+)
(show-search-progress 100)
(setf *searching-active* t))
(defun unlock-buttons ()
(setf *searching-active* nil)
(deactivate-gadget +button-abort+)
(update-buttons)
(show-search-progress 0 :force-p t))
(defun update-buttons ()
(with-result-inspector (frame)
(unless *searching-active*
(cond ((pages frame)
(let ((nr (get-page-nr)))
(if (= 1 nr)
(deactivate-gadget +button-previous+)
(activate-gadget +button-previous+))
(if (= nr (length (pages frame)))
(deactivate-gadget +button-next+)
(activate-gadget +button-next+))
(activate-gadget +button-delete-selected+)
(activate-gadget +button-delete-unselected+)
(activate-gadget +button-delete-page+)
(activate-gadget +button-delete-all-pages+)
(activate-gadget +button-unselect-all+)))
(t (deactivate-gadget +button-previous+)
(deactivate-gadget +button-next+)
(deactivate-gadget +button-delete-all-pages+)
(deactivate-gadget +button-delete-page+)
(deactivate-gadget +button-delete-selected+)
(deactivate-gadget +button-delete-unselected+)
(deactivate-gadget +button-unselect-all+))))
(window-clear (get-frame-pane frame 'query-results))
(redisplay-frame-pane frame (get-frame-pane frame 'page-nr) :force-p t)
(draw-query-results frame (get-frame-pane frame 'query-results))))
(defmethod show-page-nr ((frame inspector) stream)
(format stream " Page No. ~A of ~A Pages." (get-page-nr) (length (pages frame))))
;;;
;;;
;;;
(defun make-query-result (vars binding)
(with-result-inspector (inspector-frame)
(let ((binding
(mapcar #'(lambda (var object)
(list var
(etypecase object
(symbol
(get-associated-substrate-node (get-current-map) object))
(map-object object))))
vars binding)))
(when (or (not (active-page inspector-frame))
(full (active-page inspector-frame)))
(make-new-page))
(let* ((agg (make-aggregate (mapcar #'second binding) :hierarchicly-p nil))
(xcenter (x (pcenter agg)))
(ycenter (y (pcenter agg)))
(radius (max (+ +offset-radius+ (/ (- (x (pmax agg)) (x (pmin agg))) 2))
(+ +offset-radius+ (/ (- (y (pmax agg)) (y (pmin agg))) 2))))
(res-object (make-instance 'query-result
:bindings binding
:map-radius radius
:map-xcenter xcenter
:map-ycenter ycenter)))
(pushend res-object (objects (active-page inspector-frame)))
(delete-object agg)
(when (eq (selected-page inspector-frame)
(active-page inspector-frame))
(draw-thumbnail res-object))))))
;;;
;;;
;;;
(defun draw-selected-query-result ()
(with-result-inspector (frame)
(let ((result (selected-query-result frame))
(stream (get-frame-pane frame 'infos)))
(window-clear stream)
(multiple-value-bind (w h)
(window-inside-size stream)
(when result
(let ((*draw-thumbnails* t)
(*display-map-text-mode* t))
(draw-result result stream (- w 2) (- h 2) :fast-p nil :text-p t :full-view t)))))))
(defmethod draw-query-results ((frame inspector) stream)
(declare (ignore stream))
(if (map-on-display-p frame)
(com-inspector-show-map)
(when (selected-page frame)
(dolist (result (objects (selected-page frame)))
(let ((*display-map-text-mode* nil))
(draw-thumbnail result))))))
;;;
;;;
;;;
(define-gesture-name :select-query-result :pointer-button (:left :shift))
(define-gesture-name :inspect-query-result :pointer-button :left)
;;;
;;;
;;;
(define-inspector-command (com-inspector-query :name "Query")
()
(com-inspector-answer-query))
(define-inspector-command (com-inspector-answer-query :name "Answer Query")
()
(let ((query (accept 'form :prompt "Enter Query")))
(terpri *standard-input*)
(let ((vois (accept '((sequence symbol) :separator #\Space)
:prompt "Enter Variables")))
(inspector-answer-query query vois))))
(define-inspector-command (com-inspector-load-sqd-map :name "Load SQD Map")
()
(let ((file (file-selector "Load SQD Map" "maps:" "sqd")))
(when file
(window-clear *standard-output*)
(format *standard-output* "Attempting to load SQD map ~A!" file)
(install-as-current-mapviewer-map
(load-and-install-map file)))))
(define-inspector-command (com-inspector-load-map :name "Load Map")
()
(let ((file (file-selector "Load Map" "maps:" "map")))
(when file
(install-as-current-mapviewer-map (load-map file)))))
(define-inspector-command (com-inspector-map :name "Map")
()
(com-inspector-show-map))
(define-inspector-command (com-inspector-show-map :name "Show Map")
()
(with-result-inspector (frame)
(let ((stream (get-frame-pane frame 'query-results)))
(setf (map-on-display-p frame) t)
(unhighlight-all)
(when (and *last-query*
(is-map-query-p *last-query*))
(dolist (binding (result-bindings *last-query*))
(mapcar #'(lambda (var object)
(let ((object (if (symbolp object)
(get-associated-substrate-node (substrate *last-query*)
object)
object)))
(when object
(setf (geometry::bound-to object) var))))
(answer-pattern *last-query*) binding)))
(window-clear stream)
(draw-overview frame stream))))
(define-inspector-command (com-inspector-thumbnails :name "Thumbnails")
()
(com-inspector-show-thumbnails))
(define-inspector-command (com-inspector-show-thumbnails :name "Show Thumbnails")
()
(with-result-inspector (frame)
(let ((stream (get-frame-pane frame 'query-results)))
(setf (map-on-display-p frame) nil)
(window-clear stream)
(draw-query-results frame stream))))
(define-inspector-command (com-reload-ontology :name "Reload Ontology")
()
(load-geo-ontology))
(define-inspector-command (com-reload-queries :name "Reload Queries")
()
(load "q-queries.lisp"))
(define-inspector-command (com-inspector-ontology :name "Ontology")
()
(com-inspector-show-ontology))
#+:midelora
(define-inspector-command (com-inspector-show-ontology :name "Show Ontology")
()
(if (is-midelora-map-p *cur-map*)
(dag::visualize-dag (taxonomy (find-tbox 'prover::oejendorf :error-p t)))
(let ((taxonomy (racer-dag::get-racer-taxonomy 'racer-user::oejendorf)))
(dag:visualize-dag taxonomy))))
#-:midelora
(define-inspector-command (com-inspector-show-ontology :name "Show Ontology")
()
(let ((taxonomy (racer-dag::get-racer-taxonomy 'racer-user::oejendorf)))
(dag:visualize-dag taxonomy)))
(define-inspector-command (com-inspector-delete-page :name "Delete Page")
()
(delete-page))
(define-inspector-command (com-inspector-delete-all-pages :name "Delete All Pages")
()
(delete-all-pages))
(define-inspector-command (com-inspector-next-page :name "Next Page")
()
(next-page))
(define-inspector-command (com-inspector-prev-page :name "Previous Page")
()
(previous-page))
(define-inspector-command (com-inspector-show-query :name "Show Query")
()
(window-clear *standard-output*)
(when *last-query*
(terpri *standard-output*)
(format t "Query: ")
(write (unparse-query *last-query*) :pretty t :escape nil :readably nil)
(format t "~%~% Variables: ")
(write (answer-pattern *last-query*) :pretty t :escape nil :readably nil)))
(define-inspector-command (com-inspector-show-code :name "Show Code")
()
(window-clear *standard-output*)
(when *last-query*
(dolist (query (cons *last-query*
(thematic-substrate::all-subqueries *last-query*)))
(pprint (source query) *standard-output*))))
(define-inspector-command (com-inspector-answer :name "Answer")
()
(com-inspector-show-answer))
(define-inspector-command (com-inspector-show-answer :name "Show Answer")
()
(let ((stream *standard-output*) )
(when *last-query*
(run #'(lambda ()
(window-clear stream)
(format stream "Last query returned ~A tuples: ~%"
(length (result-bindings *last-query*)))
(pprint (mapcar #'(lambda (binding)
(mapcar #'(lambda (var object)
(list var
(if (symbolp object)
object
(name object))))
(answer-pattern *last-query*) binding))
(result-bindings *last-query*) )
stream))))))
(define-inspector-command (com-inspector-clear :name "Clear")
()
(window-clear *standard-output*)
(window-clear *query-io*)
(unhighlight-all)
(setf *last-query* nil)
(setf (map-on-display-p *application-frame*) nil)
(delete-all-pages)
(update-buttons))
(define-inspector-command (com-inspector-show-repository :name "Show Repository")
()
(show-qbox (get-current-map)))
(define-inspector-command (com-inspector-clear-repository :name "Clear Repository")
()
(thematic-substrate::clear-repository (get-current-map)))
#|
(define-inspector-command (com-inspector-kill :name "Kill")
()
(kill)
(unlock-buttons))
|#
(define-inspector-command (com-inspector-restart-map-viewer :name "Restart Map Viewer")
()
(map-viewer))
(define-inspector-command (com-inspector-quit :name "Quit")
()
(with-result-inspector (frame)
(let ((yes-or-no (notify-user frame
"Quit selected! Are you sure?"
:style :question)))
(when yes-or-no
(setf *result-inspector-frame* nil)
(frame-exit frame)))))
;;;
;;;
;;;
(define-inspector-command (com-inspector-inspect-query-result)
((object 'query-result))
(select-query-result object)
(draw-selected-query-result))
(defmethod select-query-result ((object query-result))
(with-result-inspector (frame)
(setf (selected-query-result frame) object)
(unhighlight-all)
(dolist (tuple (bindings object))
(let ((object (second tuple))
(var (first tuple)))
(setf (geometry::bound-to
(if (symbolp object)
(get-associated-substrate-node (substrate *last-query*)
object)
object))
var)))))
(define-presentation-to-command-translator inspect-query-result
(query-result
com-inspector-inspect-query-result inspector
:tester (() (not *searching-active*))
:echo t
:maintain-history nil
:gesture :inspect-query-result)
(object)
(list object))
;;;
;;;
;;;
(define-inspector-command (com-inspector-select-query-result)
((object 'query-result))
(setf (selected object) (not (selected object)))
(com-inspector-inspect-query-result object)
(draw-thumbnail object))
(define-presentation-to-command-translator select-query-result
(query-result
com-inspector-select-query-result inspector
:echo nil
:tester (() (not *searching-active*))
:maintain-history nil
:gesture :select-query-result)
(object)
(list object))
;;;
;;;
;;;
(defmacro with-dlmaps-standard-settings (&body body)
`(if *exclude-permutations*
(with-nrql-settings (:abox-mirroring nil
:query-optimization t
:two-phase-query-processing-mode nil
:told-information-querying nil
:tuple-computation-mode :set-at-a-time
:exclude-permutations t
:query-repository nil
:report-inconsistent-queries nil
:report-tautological-queries nil
:query-realization nil
:check-abox-consistency nil
:rewrite-to-dnf t)
(racer:with-unique-name-assumption
(let ((ts::*runtime-evaluation-p* nil)
(ts::*compile-queries-p* nil))
,@body)))
(with-nrql-settings (:abox-mirroring nil
:query-optimization t
:two-phase-query-processing-mode nil
:told-information-querying nil
:tuple-computation-mode :set-at-a-time
:exclude-permutations nil
:query-repository nil
:report-inconsistent-queries nil
:report-tautological-queries nil
:query-realization nil
:check-abox-consistency nil
:rewrite-to-dnf t)
(racer:with-unique-name-assumption
(let ((ts::*runtime-evaluation-p* nil)
(ts::*compile-queries-p* nil))
,@body)))))
(defmacro with-dlmaps-experimental-settings (&body body)
`(if *exclude-permutations*
(with-nrql-settings (:query-optimization t
:two-phase-query-processing-mode nil
:tuple-computation-mode :set-at-a-time
:exclude-permutations t
:query-repository t
:report-inconsistent-queries t
:query-realization nil)
(racer:with-unique-name-assumption
(let ((ts::*runtime-evaluation-p* nil)
(ts::*compile-queries-p* nil))
,@body)))
(with-nrql-settings (:query-optimization t
:two-phase-query-processing-mode t
:tuple-computation-mode :set-at-a-time
:exclude-permutations nil
:query-repository t
:report-inconsistent-queries t
:query-realization nil)
(racer:with-unique-name-assumption
(let ((ts::*runtime-evaluation-p* nil)
(ts::*compile-queries-p* nil))
,@body)))))
;;;
;;;
;;;
(defun inspector-answer-query (query vois &optional doc)
(present-query query vois)
(terpri *standard-input*)
(terpri *standard-input*)
(in-substrate* (get-current-map))
(with-result-inspector (frame)
(setf (map-on-display-p frame) nil)
(delete-all-pages)
(let ((*standard-output* (frame-standard-output frame))
(*package* ;(racer-package *cur-substrate*)
(find-package :racer-user)))
(window-clear *standard-output*)
(terpri *standard-output*)
(when doc
(format t "Natürlichsprachlich:~%")
(format t doc)
(terpri *standard-output*)
(terpri *standard-output*))
(format t "Query: ")
(write query :pretty t :escape nil :readably nil)
(format t "~%~% Variables: ")
(write vois :pretty t :escape nil :readably nil)
(terpri *standard-output*)
(terpri *standard-output*)
(pprint
;;; aus irgendwelchen Gründen (locking?)
;;; blockiert die Anwendung, wenn kein
;;; Prozess gestartet wird!
(run #'(lambda ()
(if *experimental*
(with-dlmaps-experimental-settings
(answer-query query vois))
(with-dlmaps-standard-settings
(answer-query query vois)))))))))
(defun present-query (q v)
(let ((stream *standard-input* )
(*print-pretty* t))
(format stream "Command: Answer Query~%")
(format stream "Enter Query: ")
(present q 'form :stream stream)
(terpri stream)
(format stream "Enter Variables: ")
(present v '(sequence symbol)
:separator #\Space
:stream stream)))
;;;
;;; Demo-Queries
;;;
(define-inspector-command (com-inspector-q1 :name "Q1")
()
(q1))
(define-inspector-command (com-inspector-q2 :name "Q2")
()
(q2))
(define-inspector-command (com-inspector-q3 :name "Q3")
()
(q3))
(define-inspector-command (com-inspector-q4 :name "Q4")
()
(q4))
(define-inspector-command (com-inspector-q5 :name "Q5")
()
(q5))
(define-inspector-command (com-inspector-q6 :name "Q6")
()
(q6))
(define-inspector-command (com-inspector-q7 :name "Q7")
()
(q7))
(define-inspector-command (com-inspector-q8 :name "Q8")
()
(q8))
(define-inspector-command (com-inspector-q9 :name "Q9")
()
(q9))
(define-inspector-command (com-inspector-q10 :name "Q10")
()
(q10))
(define-inspector-command (com-inspector-q11 :name "Q11")
()
(q11))
(define-inspector-command (com-inspector-q12 :name "Q12")
()
(q12))
(define-inspector-command (com-inspector-q13 :name "Q13")
()
(q13))
(define-inspector-command (com-inspector-q14 :name "Q14")
()
(q14))
(define-inspector-command (com-inspector-q15 :name "Q15")
()
(q15))
(define-inspector-command (com-inspector-q16 :name "Q16")
()
(q16))
(define-inspector-command (com-inspector-q17 :name "Q17")
()
(q17))
(define-inspector-command (com-inspector-q18 :name "Q18")
()
(q18))
(define-inspector-command (com-inspector-q19 :name "Q19")
()
(q19))
(define-inspector-command (com-inspector-q20 :name "Q20")
()
(q20))
| 39,951 | Common Lisp | .lisp | 1,022 | 28.784736 | 103 | 0.579292 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6129fb63b426f47dda6f6c8cdf508a20bdedca7b74850b32c9fd9af88908a31e | 12,500 | [
-1
] |
12,501 | interface.lisp | lambdamikel_DLMAPS/src/map-viewer/interface.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: SPATIAL-SUBSTRATE; Base: 10 -*-
(in-package spatial-substrate)
;;;
;;;
;;;
(defparameter *show-in-inspector-p* t)
(defmethod prepare-substrate-for-query-execution ((substrate map*) (query query))
t)
;;;
;;;
;;;
(defmethod querying-started ((map map*) (query query))
(when *show-in-inspector-p*
(when (result-inspector-running-p)
(lock-buttons))
(unhighlight-all)))
(defmethod querying-ended ((map map*) (query query))
(when *show-in-inspector-p*
(when (result-inspector-running-p)
(unlock-buttons))
(dolist (binding (result-bindings query))
(loop as var in (answer-pattern query)
as object in binding do
(progn
(etypecase object
(symbol ; Racer ABox-Individuum!
(when (get-associated-substrate-node map object)
(setf (geometry:bound-to (get-associated-substrate-node map object)) var)))
(map-object
(setf (geometry:bound-to object) var))))))))
;;;
;;;
;;;
(defmethod register-bindings ((map map*) (query map-query) (answer-pattern list) (new-bindings list))
(when (and *show-in-inspector-p*
(result-inspector-running-p)
(not (ts::bottom-up-component-query-p query))
(not (abort-search-p query)))
(make-query-result answer-pattern new-bindings)))
;;;
;;;
;;;
(defun show-nodes (inds)
(unhighlight-all)
(highlight (mapcar #'(lambda (x)
(if (is-map-object-p x)
x
(get-associated-substrate-node (get-current-map) x)))
(ensure-list inds))))
(defun from-tuples-to-inds (tuples)
(apply #'append
(mapcar #'(lambda (tuple)
(mapcar #'second tuple))
tuples)))
;;;;
;;;;
;;;;
(defmethod get-successors-of-type ((obj map-object) (type symbol))
(in-substrate* (get-current-map))
(let ((frame *result-inspector-frame*))
(setf *result-inspector-frame* nil)
(prog1
(loop as binding in
(with-dlmaps-standard-settings
(answer-query `(,(intern (format nil "*~A" (name obj))) ?*x ,type)
'(?*x)))
collect (second (first binding)))
(setf *result-inspector-frame* frame))))
;;;
;;;
;;;
#|
(defmethod answer-query :around ((query map-query)
(res-args list)
&rest args)
(with-dlmaps-standard-settings
(apply #'call-next-method query res-args args)))
|#
;;;
;;;
;;;
(defmethod get-answer ((query map-query))
(if (not (slot-value query 'query-satisfiable))
nil
(progn
(get-all-remaining-tuples query)
(if (answer-pattern query)
(let* ((pat (answer-pattern query))
(res
(mapcar #'(lambda (binding)
(mapcar #'(lambda (var val)
(list (get-textual-head-entry var) val))
pat binding))
(result-bindings query))))
(if (timeout-p query)
(cons :timeout res)
res))
(or (eq (bindings-found-p query) t)
(when (timeout-p query)
:timeout))))))
;;;
;;; Test-Interface:
;;;
(defvar *start-time* 0)
(defmacro with-timing ((var) &body body)
`(let ((*start-time* (get-internal-run-time)))
(unwind-protect
(progn ,@body)
(incf ,var (- (get-internal-run-time) *start-time*)))))
(defun load-and-install-map (file &optional (type *kind-of-map*))
(make-map-from-sqd-file file
:delete-if-exists-p t
:racer-package 'racer-user
:abox
(intern
(string-upcase
(pathname-name
(truename file))))
:tbox
'oejendorf
:type type))
(defmacro answer-map-query (head body &optional (compile-p t))
`(funcall #'(lambda ()
(let ((*package* ;(racer-package *cur-substrate*)
(find-package :racer-user))
(*show-in-inspector-p* nil)
(time 0)
(*add-rcc-atoms-to-abox-for-reasoning* nil))
(let ((res
(with-timing (time)
(WITH-NRQL-SETTINGS (:QUERY-OPTIMIZATION
t
:TWO-PHASE-QUERY-PROCESSING-MODE
nil
:TUPLE-COMPUTATION-MODE
:SET-AT-A-TIME
:mode 3
:EXCLUDE-PERMUTATIONS
NIL
:QUERY-REPOSITORY
nil
:REPORT-INCONSISTENT-QUERIES
T
:QUERY-REALIZATION
nil)
(RACER:WITH-UNIQUE-NAME-ASSUMPTION
(LET ((THEMATIC-SUBSTRATE::*RUNTIME-EVALUATION-P* ,(not compile-p))
(THEMATIC-SUBSTRATE::*COMPILE-QUERIES-P* ,compile-p)
(ts::*multiprocess-queries* nil))
'(ANSWER-QUERY ',(change-package-of-description
body
:racer-user)
',(change-package-of-description
head
:racer-user))
(ANSWER-QUERY ', body
',head)))))))
(pprint (list res
(length res)
(float (/ time
internal-time-units-per-second))))
(values res
(length res)
(float (/ time
internal-time-units-per-second))))))))
(defun diskql-test (n)
(let* ((map (ecase n
(0 "~/maps/small.sqd")
(1 "~/maps/va5.sqd")
(2 "~/maps/oejendorf2.sqd")))
(type ; 'basic-explicit-racer-explicit-relations-map
'midelora-explicit-relations-map))
(time (load-and-install-map map type))
;(when (= n 1) (close-roles (get-current-map)))
(case n
(1
(racer:instance racer-user::ind-1215 racer-user::gewerbe)
(racer:instance racer-user::ind-2951 racer-user::fabrik)
(racer:instance racer-user::ind-423 racer-user::naturschutzgebiet))
(2
(racer:instance racer-user::ind-9474 racer-user::gewerbe)
(racer:instance racer-user::ind-19664 racer-user::fabrik)
(racer:instance racer-user::ind-8765 racer-user::naturschutzgebiet)))
(terpri)
(princ "Prepare...") (terpri)
(answer-map-query (?*x) (?*x racer-user::top))
(terpri)
(princ "Q1") (terpri)
(answer-map-query (?*x) (?*x racer-user::wohnen))
(terpri)
(princ "Q2") (terpri)
(answer-map-query (?x ?y)
(and (?*x racer-user::wohnen) (?x ?y :adjacent) (?*y racer-user::autobahn)))
(terpri)
(princ "Q3") (terpri)
(answer-map-query (?w ?g ?e ?t)
(and (?*w racer-user::wohnen) (?*g racer-user::wiese-weide)
(?*e racer-user::gewerbe)
(?*t (or racer-user::teich racer-user::see))
(?w ?g :adjacent) (?w ?e :adjacent) (?g ?t :contains)))
(terpri)
(princ "Q3 b)") (terpri)
(answer-map-query (?w ?g ?e ?t)
(and (?*w racer-user::wohnen) (?*g racer-user::wiese-weide)
(?*e racer-user::gewerbe)
(or (?*t racer-user::teich) (?*t racer-user::see))
(?w ?g :adjacent) (?w ?e :adjacent) (?g ?t :contains)))
(terpri)
(princ "Q4") (terpri)
(answer-map-query (?x)
(and (?*x (and racer-user::wohnen
(racer-user::at-least 8 racer-user::ntppi racer-user::gebaeude)))
(?x (:area (> area 30000)))))
(terpri)
(princ "Q5") (terpri)
(answer-map-query (?x)
(and (?*x racer-user::wohnen)
(neg (project-to (?x)
(and (?x ?y :adjacent)
(?*y (or racer-user::industrie
racer-user::gewerbe)))))))
(terpri)
(princ "Q5 (b)") (terpri)
(racer-user::implies racer-user::gruenflaeche (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::natuerliche-flaeche (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::parkplatz (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::wasser (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::bab (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::weg (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::verkehrsbegleitgruen (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::bab-randbegrenzung (and (not racer-user::industrie) (not racer-user::gewerbe)))
(answer-map-query (?*x)
(and (?*x (and racer-user::wohnen (all racer-user::ec
(not (or racer-user::industrie
racer-user::gewerbe)))))))
(terpri)
(princ "Q6") (terpri)
(answer-map-query (?x ?y ?z ?u ?*f
)
(and (?*x racer-user::teich)
(?x ?y :inside)
(?*y racer-user::naturschutzgebiet)
(?x ?z :flows-in)
(?*z racer-user::bach)
(?z ?u (:or :touches :crosses))
(?*u racer-user::gewerbe )
(?u ?f :contains)
(?*f racer-user::fabrik)
))
(terpri)
(princ "Q7") (terpri)
(answer-map-query (?x ?y)
(and (?x racer-user::wohnen)
(?y ?x (:inside-distance 750))
(?y racer-user::u-bahn-station-symbol*)))
(terpri)
(princ "Q8") (terpri)
(answer-map-query (?w ?g ?e ?t ?ubahn)
(and (?*w racer-user::wohnen)
(or (?*g racer-user::wiese-weide)
(?*g racer-user::park))
(?*t racer-user::teich)
(?w ?g :adjacent)
(?w ?e :adjacent)
(?g ?t :contains)
(?ubahn ?w (:inside-distance 750)) (?*ubahn racer-user::u-bahn-station-symbol*)
(neg (project-to (?w)
(and (?*w racer-user::wohnen)
(?w ?x :adjacent)
(?*x racer-user::autobahn))))))))
(defun diskql-test2 (n)
(let* ((map (ecase n
(0 "~/maps/small.sqd")
(1 "~/maps/va5.sqd")
(2 "~/maps/oejendorf2.sqd")))
(type 'basic-explicit-racer-explicit-relations-map))
(time (load-and-install-map map type))
(when (= n 1) (close-roles (get-current-map)))
(case n
(1
(racer:instance racer-user::ind-1215 racer-user::gewerbe)
(racer:instance racer-user::ind-2951 racer-user::fabrik)
(racer:instance racer-user::ind-423 racer-user::naturschutzgebiet))
(2
(racer:instance racer-user::ind-9474 racer-user::gewerbe)
(racer:instance racer-user::ind-19664 racer-user::fabrik)
(racer:instance racer-user::ind-8765 racer-user::naturschutzgebiet)))
(terpri)
(princ "Prepare...") (terpri)
(answer-map-query (?*x) (?*x racer-user::top))
(terpri)
(princ "Q1") (terpri)
(answer-map-query (?*x) (?*x racer-user::wohnen))
(terpri)
(princ "Q2") (terpri)
(answer-map-query (?*x ?*y)
(and (?*x racer-user::wohnen) (?*x ?*y :adjacent) (?*y racer-user::autobahn)))
(terpri)
(princ "Q3") (terpri)
(answer-map-query (?*w ?*g ?*e ?*t)
(and (?*w racer-user::wohnen) (?*g racer-user::wiese-weide)
(?*e racer-user::gewerbe)
(?*t (or racer-user::teich racer-user::see))
(?*w ?*g :adjacent) (?*w ?*e :adjacent) (?*g ?*t :contains)))
(terpri)
(princ "Q3 b)") (terpri)
(answer-map-query (?*w ?*g ?*e ?*t)
(and (?*w racer-user::wohnen) (?*g racer-user::wiese-weide)
(?*e racer-user::gewerbe)
(or (?*t racer-user::teich) (?*t racer-user::see))
(?*w ?*g :adjacent) (?*w ?*e :adjacent) (?*g ?*t :contains)))
(terpri)
(princ "Q4") (terpri)
(answer-map-query (?*x)
(and (?*x (and racer-user::wohnen
(racer-user::at-least 8 racer-user::ntppi racer-user::gebaeude)))
(?x (:area (> area 30000)))))
(terpri)
(princ "Q5") (terpri)
(answer-map-query (?*x)
(and (?*x racer-user::wohnen)
(neg (project-to (?*x)
(and (?*x ?*y :adjacent)
(?*y (or racer-user::industrie
racer-user::gewerbe)))))))
(terpri)
(princ "Q5 (b)") (terpri)
(racer-user::implies racer-user::gruenflaeche (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::natuerliche-flaeche (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::parkplatz (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::wasser (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::bab (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::weg (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::verkehrsbegleitgruen (and (not racer-user::industrie) (not racer-user::gewerbe)))
(racer-user::implies racer-user::bab-randbegrenzung (and (not racer-user::industrie) (not racer-user::gewerbe)))
(answer-map-query (?*x)
(and (?*x (and racer-user::wohnen (all racer-user::ec
(not (or racer-user::industrie
racer-user::gewerbe)))))))
(terpri)
(princ "Q6") (terpri)
(answer-map-query (?*x ?*y ?*z ?*u ?*f
)
(and (?*x racer-user::teich)
(?*x ?*y :inside)
(?*y racer-user::naturschutzgebiet)
(?*x ?*z :flows-in)
(?*z racer-user::bach)
(?*z ?*u (:or :touches :crosses))
(?*u racer-user::gewerbe )
(?*u ?*f :contains)
(?*f racer-user::fabrik)
))
(terpri)
(princ "Q7") (terpri)
(answer-map-query (?*x ?*y)
(and (?*x racer-user::wohnen)
(?y ?x (:inside-distance 750))
(?*y racer-user::u-bahn-station-symbol*)))
(terpri)
(princ "Q8") (terpri)
(answer-map-query (?*w ?*g ?*e ?*t ?*ubahn)
(and (?*w racer-user::wohnen)
(or (?*g racer-user::wiese-weide)
(?*g racer-user::park))
(?*t racer-user::teich)
(?*w ?*g :adjacent)
(?*w ?*e :adjacent)
(?*g ?*t :contains)
(?ubahn ?w (:inside-distance 750))
(?*ubahn racer-user::u-bahn-station-symbol*)
(neg (project-to (?*w)
(and (?*w racer-user::wohnen)
(?*w ?*x :adjacent)
(?*x racer-user::autobahn))))))))
(defun bug (n)
(let* ((map (ecase n
(1 "~/maps/va5.sqd")
(2 "~/maps/oejendorf2.sqd")))
(type 'basic-explicit-racer-implicit-relations-map))
(time (load-and-install-map map type))
(ecase n
(1
(racer:instance racer-user::ind-1215 racer-user::gewerbe)
(racer:instance racer-user::ind-2951 racer-user::fabrik)
(racer:instance racer-user::ind-423 racer-user::naturschutzgebiet))
(2
(racer:instance racer-user::ind-9474 racer-user::gewerbe)
(racer:instance racer-user::ind-19664 racer-user::fabrik)
(racer:instance racer-user::ind-8765 racer-user::naturschutzgebiet)))
(terpri)
(princ "Q2") (terpri)
(answer-map-query (?x ?y)
(and (?*x racer-user::wohnen) (?x ?y :adjacent) (?*y racer-user::autobahn)))))
;;;
;;;
;;;
(defmacro midelora-answer-map-query (head body &optional (compile-p t))
`(funcall #'(lambda ()
(let ((*package* ;(racer-package *cur-substrate*)
(find-package :prover))
(*show-in-inspector-p* nil)
(time 0)
(*add-rcc-atoms-to-abox-for-reasoning* nil))
(let ((res
(with-timing (time)
(WITH-NRQL-SETTINGS (:QUERY-OPTIMIZATION
t
:TWO-PHASE-QUERY-PROCESSING-MODE
nil
:TUPLE-COMPUTATION-MODE
:SET-AT-A-TIME
:mode 3
:EXCLUDE-PERMUTATIONS
NIL
:QUERY-REPOSITORY
nil
:REPORT-INCONSISTENT-QUERIES
nil
:QUERY-REALIZATION
nil)
(LET ((THEMATIC-SUBSTRATE::*RUNTIME-EVALUATION-P* ,(not compile-p))
(THEMATIC-SUBSTRATE::*COMPILE-QUERIES-P* ,compile-p)
(ts::*multiprocess-queries* nil))
'(ANSWER-QUERY ',(change-package-of-description
body
:prover)
',(change-package-of-description
head
:prover))
(ANSWER-QUERY ', body
',head))))))
(pprint (list res
(length res)
(float (/ time
internal-time-units-per-second))))
(values res
(length res)
(float (/ time
internal-time-units-per-second))))))))
(defun midelora-diskql-test (n)
(let* ((map (ecase n
(0 "~/maps/small.sqd")
(1 "~/maps/va5.sqd")
(2 "~/maps/oejendorf2.sqd")))
(type ; 'basic-explicit-racer-explicit-relations-map
'midelora-explicit-relations-map))
(time (load-and-install-map map type))
;(when (= n 1)
;(close-roles (get-current-map))
(prover::implies prover::gruenflaeche (and (not prover::industrie) (not prover::gewerbe)))
(prover::implies prover::natuerliche-flaeche (and (not prover::industrie) (not prover::gewerbe)))
(prover::implies prover::parkplatz (and (not prover::industrie) (not prover::gewerbe)))
(prover::implies prover::wasser (and (not prover::industrie) (not prover::gewerbe)))
(prover::implies prover::bab (and (not prover::industrie) (not prover::gewerbe)))
(prover::implies prover::weg (and (not prover::industrie) (not prover::gewerbe)))
(prover::implies prover::verkehrsbegleitgruen (and (not prover::industrie) (not prover::gewerbe)))
(prover::implies prover::bab-randbegrenzung (and (not prover::industrie) (not prover::gewerbe)))
(case n
(1
(prover:instance prover::ind-1232 prover::gewerbe)
(prover:instance prover::ind-2951 prover::fabrik)
(prover:instance prover::ind-423 prover::naturschutzgebiet))
(2
(prover:instance prover::ind-9474 prover::gewerbe)
(prover:instance prover::ind-19664 prover::fabrik)
(prover:instance prover::ind-8765 prover::naturschutzgebiet)))
(terpri)
(princ "Prepare...") (terpri)
(midelora-answer-map-query (?*x) (?*x prover::top))
(prover::with-abox-retrieval ( (prover::current-abox) )
(terpri)
(princ "Q1") (terpri)
(midelora-answer-map-query (?*x) (?*x prover::wohnen))
(terpri)
(princ "Q2") (terpri)
(midelora-answer-map-query (?*x ?*y)
(and (?*x prover::wohnen) (?*x ?*y :adjacent) (?*y racer-user::autobahn)))
(terpri)
(princ "Q3") (terpri)
(midelora-answer-map-query (?*w ?*g ?*e ?*t)
(and (?*w prover::wohnen) (?*g prover::wiese-weide)
(?*e prover::gewerbe)
(?*t (or prover::teich prover::see))
(?*w ?*g :adjacent) (?*w ?*e :adjacent) (?*g ?*t :contains)))
(terpri)
(princ "Q3 b)") (terpri)
(midelora-answer-map-query (?*w ?*g ?*e ?*t)
(and (?*w prover::wohnen) (?*g prover::wiese-weide)
(?*e prover::gewerbe)
(or (?*t prover::teich) (?*t prover::see))
(?*w ?*g :adjacent) (?*w ?*e :adjacent) (?*g ?*t :contains)))
(unless (= n 2)
(terpri)
(princ "Q4") (terpri)
(midelora-answer-map-query (?*x)
(and (?*x (and prover::wohnen
(prover::at-least 8 prover::ntppi prover::top)))
(?x (:area (> area 30000))))))
(terpri)
(princ "Q5") (terpri)
(midelora-answer-map-query (?*x)
(and (?*x prover::wohnen)
(neg (project-to (?*x)
(and (?*x ?*y :adjacent)
(?*y (or prover::industrie
prover::gewerbe)))))))
(terpri)
(princ "Q5 (b)") (terpri)
(midelora-answer-map-query (?*x)
(and (?*x (and prover::wohnen (all prover::ec
(not (or prover::industrie
prover::gewerbe)))))))
(terpri)
(princ "Q6") (terpri)
(midelora-answer-map-query (?*x ?*y ?*z ?*u ?*f
)
(and (?*x prover::teich)
(?*x ?*y :inside)
(?*y prover::naturschutzgebiet)
(?*x ?*z :flows-in)
(?*z prover::bach)
(?*z ?*u (:or :touches :crosses))
(?*u prover::gewerbe )
(?*u ?*f :contains)
(?*f prover::fabrik)
))
(terpri)
(princ "Q7") (terpri)
(midelora-answer-map-query (?*x ?*y)
(and (?*x prover::wohnen)
(?y ?x (:inside-distance 750))
(?*y prover::u-bahn-station-symbol*)))
(terpri)
(princ "Q8") (terpri)
(midelora-answer-map-query (?*w ?*g ?*e ?*t ?*ubahn)
(and (?*w prover::wohnen)
(or (?*g prover::wiese-weide)
(?*g prover::park))
(?*t prover::teich)
(?*w ?*g :adjacent)
(?*w ?*e :adjacent)
(?*g ?*t :contains)
(?ubahn ?w (:inside-distance 750))
(?*ubahn prover::u-bahn-station-symbol*)
(neg (project-to (?*w)
(and (?*w prover::wohnen)
(?*w ?*x :adjacent)
(?*x prover::autobahn)))))))))
| 29,724 | Common Lisp | .lisp | 549 | 29.810565 | 134 | 0.395533 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d9278279bc71a4c975508fd3bb178fe8d714de6def371dc742bbb82456b71a3b | 12,501 | [
-1
] |
12,502 | map-viewer3.lisp | lambdamikel_DLMAPS/src/map-viewer/map-viewer3.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: SPATIAL-SUBSTRATE; Base: 10 -*-
(in-package spatial-substrate)
(defvar *map-viewer-frame*)
(defvar *selected-object*)
;(defvar *kind-of-map* 'basic-explicit-racer-explicit-relations-map)
(defvar *kind-of-map* 'midelora-explicit-relations-map)
#+(or mcl lispworks)
(defmacro outl (&body body)
`(spacing (:thickness 2)
(outlining (:thickness 2)
(spacing (:thickness 2)
,@body))))
;;;
;;; Text Styles and Colors etc.
;;;
(defconstant +highlight-thickness+ 10)
(defconstant +highlight-line-thickness+ 6)
(defconstant +gravity-field+ nil)
(defconstant +gravity-field-thickness+ 15)
(defconstant +gravity-field-thickness2+ 5)
(defconstant +info-text-style+
(make-text-style :serif :roman :small))
(defconstant +text-height+ 10)
(defconstant +command-listener-text-style+
(make-text-style
:sans-serif :roman :normal))
(defconstant +bound-to-text-style+
(parse-text-style '(:sans-serif :bold :LARGE)))
(defconstant +bound-to-text-ink+
(make-rgb-color 0 0 0))
(defconstant +bound-to-ink+
+yellow+)
(defconstant +map-viewer-text-style+
(make-text-style :sans-serif
:roman
:normal))
(defconstant +non-map-object-color+
(make-rgb-color 0.7 0.7 0.7))
(defconstant +non-map-object-bound-to-color+
(make-rgb-color 0.8 0.8 0))
(defconstant +marker-color+
(make-rgb-color 1.0 1.0 0.0))
(defconstant +text-color+
(make-rgb-color 0 0 1))
(defconstant +grayed-item-ts+
(parse-text-style '(:sans-serif nil :small)))
(defconstant +grayed-item-i+
(make-gray-color 0.7))
(defconstant +selected-item-ts+
(parse-text-style '(:sans-serif (:bold :italic) :small)))
(defconstant +selected-item-i+
(make-gray-color 0.0))
(defconstant +unselected-item-ts+
(parse-text-style '(:sans-serif :bold :small)))
(defconstant +unselected-item-i+
(make-gray-color 0.4))
;;;
;;;
;;;
(defvar *unknown-os-keys* nil)
;;;
;;;
;;;
(defparameter *highlight-bindings* t)
(defparameter *display-binding-names-mode* t)
(defparameter *warn-mode* nil)
(defparameter *solid-areas* t)
(defparameter *draw-contours* t)
(defparameter *autotracking-mode* t)
(defparameter *display-map-text-mode* nil)
(defparameter *display-nodes-mode* nil)
(defparameter *sensitive-objects-mode* t)
(defparameter *single-box-mode* nil)
(defparameter *use-query-processor* t)
(defparameter *display-only-bound-objects* nil)
;;;
;;;
;;;
(defvar *draw-overview* nil)
(defvar *draw-components* nil)
;;;
;;;
;;;
(defmacro with-pretty-map-output (&body body)
`(let ((*display-map-text-mode* nil)
(*display-binding-names-mode* nil)
(*display-nodes-mode* nil)
(*sensitive-objects-mode* nil)
(*highlight-bindings* nil)
(*solid-areas* t)
(*draw-contours* nil))
,@body))
;;;
;;;
;;;
(defmethod dont-display ((obj t))
t)
;;;
;;;
;;;
(defmethod label-pos ((obj geom-thing))
(values (x (centroid obj)) (y (centroid obj))))
(defmacro with-map-viewer-frame ((name) &body body)
`(let ((,name *map-viewer-frame*))
,@body))
(defmethod highlighted-p ((obj si-geom-thing))
(eq (bound-to obj) t))
;;;
;;:
;;;
(defmethod highlight ((obj t) &key &allow-other-keys)
t)
(defmethod highlight ((obj si-geom-thing) &key components-p set-focus-p)
(setf (bound-to obj) t)
(when components-p
(highlight (get-direct-components obj) :components-p t))
(when (and set-focus-p t)
(with-map-viewer-frame (frame)
(with-slots (current-map-radius) frame
(typecase obj
(bounding-box-mixin
(set-current-map-position-and-radius (x (centroid obj))
(y (centroid obj))
;current-map-radius
(radius obj)))
(otherwise
(set-current-map-position-and-radius (x obj)
(y obj)
(/ current-map-radius 20))))))))
(defmethod highlight ((obj list) &key components-p)
(dolist (obj obj)
(highlight obj :components-p components-p)))
;;;
;;;
;;;
(defmethod unhighlight ((obj t) &key &allow-other-keys)
t)
(defmethod unhighlight ((obj si-geom-thing) &key components-p)
(setf (bound-to obj) nil)
(when components-p
(unhighlight (get-direct-components obj) :components-p t)))
(defmethod unhighlight ((obj list) &key components-p)
(dolist (obj obj)
(unhighlight obj :components-p components-p)))
;;;
;;;
;;;
(defun select (obj)
(highlight (or (get-topmost-master obj)
obj)
:components-p t))
(defun unselect (obj)
(unhighlight (or (get-topmost-master obj)
obj)
:components-p t))
;;;
;;;
;;;
(define-presentation-type os-key-item ())
(define-presentation-type current-map-range ())
;;;
;;;
;;;
(define-gesture-name :select-os-key-item :pointer-button :left)
(define-gesture-name :unselect-os-keys-of-object :pointer-button (:left :shift))
(define-gesture-name :unselect-all-but-os-keys-of-object :pointer-button (:left :control))
(define-gesture-name :highlight-os-keys-of-object :pointer-button :middle)
(define-gesture-name :hide-object :pointer-button (:left :meta))
(define-gesture-name :adjust-map-center :pointer-button (:left))
(define-gesture-name :adjust-map-extent :pointer-button (:shift :left))
(define-gesture-name :full-map-extent :pointer-button :middle)
(define-gesture-name :select-object :pointer-button (:shift :right))
(define-gesture-name :describe-object :pointer-button :left)
;;;
;;;
;;;
(define-command-table file-table
:menu (("Install Current Map" :command (com-install-as-current-mapviewer-map))
("divide1" :divider nil)
("Load SQD Map" :command (com-load-sqd-map))
("divide2" :divider nil)
("Load Map" :command (com-load-map))
("Save Map As" :command (com-save-map-as))
("Save Map" :command (com-save-map))
("divide3" :divider nil)
("Restart Inspector" :command (com-restart-inspector))
("divide4" :divider nil)
("Quit" :command (com-quit))))
(define-command-table map-table
:menu (("Show Map Infos" :command (com-show-map-infos))
("divide1" :divider nil)
("Redraw Map" :command (com-redraw))
("Clear Display" :command (com-clear-display))
("Reset Map" :command (com-reset-map))
("divide2" :divider nil)
("Unhighlight" :command (com-unhighlight))
("Invert Highlighted" :command (com-invert-highlighted))
("Highlight in Current Range" :command (com-highlight-objects-in-current-range))
("Highlight Hidden Objects" :command (com-highlight-hidden-objects))
("divide3" :divider nil)
("Delete Highlighted Objects" :command (com-delete-highlighted-objects))
("divide4" :divider nil)
("Crop Map" :command (com-crop-map))
("Close Roles" :command (com-close-roles))
("Classify Map" :command (com-classify-map))))
(define-command-table keys-table
:menu (("Undo Nothing" :command (com-undo))
("divide1" :divider nil)
("Lookup Key" :command (com-lookup-os-key))
("Select All Keys" :command (com-highlight-all-os-keys))
("Unselect All Keys" :command (com-unselect-all-os-keys))))
(define-command-table spatial-table
:menu (("Highlight Intersecting Objects" :command (com-highlight-intersecting-objects*))
("Highlight Touching Objects" :command (com-highlight-touching-objects*))
("Highlight Contained Objects" :command (com-highlight-contained-objects*))
("Highlight Strictly Contained Objects" :command (com-highlight-strictly-contained-objects*))
("Highlight Convered Objects" :command (com-highlight-covered-objects*))
("Highlight Overlaping Objects" :command (com-highlight-overlapping-objects*))
("Highlight Bordered Objects" :command (com-highlight-bordered-objects*))))
;;;
;;;
;;;
#+:allegro
(defun generate-name-for-undo-command ()
(remove-command-from-command-table
'com-undo 'keys-table)
(with-map-viewer-frame (map-viewer-frame)
(with-slots (unselect-stack) map-viewer-frame
(let ((first (first unselect-stack)))
(if first
(add-command-to-command-table 'com-undo
'keys-table
:menu (list
(if (typep first 'map-object)
(format nil "Undo Hide ~A"
(id first))
"Undo Last Selection")
:after :start))
(add-command-to-command-table 'com-undo
'keys-table
:menu (list
"Undo Nothing"
:after :start)))))))
#+:lispworks
(defun generate-name-for-undo-command ()
t)
(defun register-selected-keys-for-undo ()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (unselect-stack selected-os-keys) map-viewer-frame
(push (copy-list selected-os-keys) unselect-stack)
(generate-name-for-undo-command)
(redisplay-frame-pane map-viewer-frame 'os-selector))))
(defun register-hide-for-undo (object)
(with-map-viewer-frame (map-viewer-frame)
(with-slots (unselect-stack) map-viewer-frame
(push object unselect-stack)
(generate-name-for-undo-command))))
;;;
;;;
;;;
(defclass overview-pane
(application-pane)
())
(defclass display-pane
(application-pane)
())
(define-application-frame map-viewer ()
( (map :initform nil)
(unselect-stack :initform nil)
(current-map-range :initform nil :accessor current-map-range)
(current-map-radius :initform 100)
(current-map-position :initform nil)
(current-map-transformation :initform nil)
(overview-pattern :initform nil)
(old-overview-vp-width :initform nil)
(old-overview-vp-height :initform nil)
(overview-transformation :initform nil)
(present-os-keys :initform nil)
(selected-os-keys :initform nil))
(:command-table (map-viewer
:inherit-from (file-table map-table keys-table spatial-table)
:menu (("File" :menu file-table)
("Map" :menu map-table)
("Key Control" :menu keys-table)
("Spatial Querying" :menu spatial-table))))
(:panes
(display (make-pane 'display-pane
:scroll-bars nil
:end-of-line-action :allow
:end-of-page-action :allow
:textcursor nil))
(button-undo (make-pane 'push-button
:label "Undo"
:activate-callback 'button-undo))
(button-unhighlight (make-pane 'push-button
:label "Unhighlight"
:activate-callback 'button-unhighlight))
(button-clear (make-pane 'push-button
:label "Clear"
:activate-callback 'button-clear))
(button-redraw (make-pane 'push-button
:label "Redraw"
:activate-callback 'button-redraw))
(button-infos (make-pane 'push-button
:label "Infos"
:activate-callback 'button-infos))
(button-reset (make-pane 'push-button
:label "Reset"
:activate-callback 'button-reset))
(button-delete (make-pane 'push-button
:label "Delete"
:activate-callback 'button-delete))
(overview (make-pane 'overview-pane
:scroll-bars nil
:end-of-line-action :allow
:end-of-page-action :allow
:textcursor nil
:display-after-commands nil
:display-function #'draw-overview))
(infos :application
:label "Map Infos"
:textcursor nil
:end-of-line-action :allow
:end-of-page-action :allow
:text-style +info-text-style+
:scroll-bars :both)
(coordinates :application
:label "Map Coordinates"
:textcursor nil
:end-of-line-action :allow
:end-of-page-action :allow
:text-style +info-text-style+
:scroll-bars nil
:display-function #'show-coordinates)
(buttons :accept-values
:scroll-bars nil
:min-height :compute :height :compute :max-height :compute
:display-function
`(accept-values-pane-displayer
:displayer ,#'(lambda (frame stream)
(accept-buttons
frame stream))))
(os-selector :application
:incremental-redisplay t
:scroll-bars :both
:end-of-line-action :allow
:end-of-page-action :allow
:display-function #'accept-os-selection)
(type :accept-values
:scroll-bars nil
:min-height :compute :height :compute :max-height :compute
:display-function
`(accept-values-pane-displayer
:displayer ,#'(lambda (frame stream)
(declare (ignore frame))
(multiple-value-bind (object ptype changed)
(accept 'completion
:query-identifier 'kind-of-map
:prompt nil
:prompt-mode :raw
:stream stream
:default *kind-of-map*
:view `(option-pane-view :items
,(reverse
(remove-if-not (lambda (x) (search "MIDELORA" x))
(mapcar #'class-name
(clos:class-direct-subclasses
(find-class 'final-class))) :key #'symbol-name))))
(declare (ignore ptype))
(when changed (setf *kind-of-map* object))))))
(command :interactor
:label nil
:text-style +command-listener-text-style+
:scroll-bars :vertical
:min-height '(4 :line)
:max-height '(4 :line)
:height '(4 :line))
(pointer-documentation-pane
(make-clim-stream-pane :type 'pointer-documentation-pane
:foreground +white+
:background +black+
:text-style (make-text-style
:sans-serif :bold :small)
:scroll-bars nil
:min-height '(1 :line)
:max-height '(1 :line)
:height '(1 :line))))
(:layouts
(:default
(vertically ()
#+(or allegro lispworks) (outl buttons)
#-(or allegro lispworks) (outl buttons)
(horizontally ()
#+(or allegro lispworks)
(1/4 (spacing (:thickness 2)
(outl os-selector)))
#-(or allegro lispworks)
(1/4 (spacing (:thickness 2)
(outl os-selector)))
(2/4
(spacing (:thickness 2)
#+allegro
(vertically ()
(outlining ()
(labelling (:label "Current Range")
display))
(30 (horizontally ()
(1/7 button-undo)
(1/7 button-unhighlight)
(1/7 button-delete)
(1/7 button-clear)
(1/7 button-reset)
(1/7 button-redraw)
(1/7 button-infos))))
#-allegro
(vertically ()
(outl (labelling (:label "Current Range")
display))
(horizontally ()
(1/7 button-undo)
(1/7 button-unhighlight)
(1/7 button-clear)
(1/7 button-reset)
(1/7 button-redraw)
(1/7 button-delete)
(1/7 button-infos)))))
(1/4
(spacing (:thickness 2)
#+allegro
(vertically ()
(1/15 type)
(2/15 coordinates)
(6/15 (outlining ()
(labelling (:label "Map Overview")
overview)))
(6/15 infos))
#-allegro
(vertically ()
(1/15 (outl type))
(2/15 (outl coordinates))
(6/15 (outl
(labelling (:label "Map Overview")
overview)))
(6/15 (outl infos))))))
#-lispworks
command
#+lispworks
(outl command)
#+allegro
pointer-documentation-pane
#+mcl
(outl pointer-documentation-pane)))))
;;;
;;;
;;;
(defun button-unhighlight (button)
(declare (ignore button))
(com-unhighlight))
(defun button-undo (button)
(declare (ignore button))
(com-undo))
(defun button-clear (button)
(declare (ignore button))
(com-clear-display))
(defun button-redraw (button)
(declare (ignore button))
(com-redraw))
(defun button-infos (button)
(declare (ignore button))
(com-show-map-infos))
(defun button-reset (button)
(declare (ignore button))
(com-reset-map))
(defun button-delete (button)
(declare (ignore button))
(com-delete-highlighted-objects))
;;;
;;;
;;;
(define-map-viewer-command (com-reset-map :name "Reset Map")
()
(reset-map-range)
(com-redraw))
(define-map-viewer-command (com-unhighlight :name "Unhighlight")
()
(unhighlight-all)
(com-redraw))
(defun unhighlight-all ()
(with-map-viewer-frame (frame)
(with-slots (map) frame
(when map
(unhighlight (elements (spatial-index map)))))))
;;;
;;;
;;;
(define-map-viewer-command (com-undo :name "Undo")
()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (unselect-stack selected-os-keys) map-viewer-frame
(let ((first (pop unselect-stack)))
(when first
(cond ((typep first 'si-geom-thing) ; undo hide object
(setf (dont-display first) nil)
(com-clear-display)
(com-draw-current-map))
(t
(setf selected-os-keys first)))
(generate-name-for-undo-command)
(com-draw-current-map))))))
(defmethod accept-buttons ((frame map-viewer) stream)
(let ((changed nil))
(formatting-table (stream :x-spacing '(2 :character))
(formatting-row (stream)
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed1)
(accept 'boolean
:prompt "Autotracking"
:stream stream :default *autotracking-mode*
:query-identifier 'autotracking)
(declare (ignore ptype))
(setf changed (or changed changed1))
(when changed1 (setf *autotracking-mode* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed4)
(accept 'boolean
:prompt "Sensitive"
:stream stream :default *sensitive-objects-mode*
:query-identifier 'sensitive-objects-mode)
(declare (ignore ptype))
(setf changed (or changed changed4))
(when changed4 (setf *sensitive-objects-mode* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed2)
(accept 'boolean
:prompt "Text"
:stream stream :default *display-map-text-mode*
:query-identifier 'display-text)
(declare (ignore ptype))
(setf changed (or changed changed2))
(when changed2 (setf *display-map-text-mode* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed3)
(accept 'boolean
:prompt "Nodes"
:stream stream :default *display-nodes-mode*
:query-identifier 'display-nodes)
(declare (ignore ptype))
(setf changed (or changed changed3))
(when changed3 (setf *display-nodes-mode* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed6)
(accept 'boolean
:prompt "Contours"
:stream stream :default *draw-contours*
:query-identifier 'contours)
(declare (ignore ptype))
(setf changed (or changed changed6))
(when changed6 (setf *draw-contours* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed8)
(accept 'boolean
:prompt "Areas"
:stream stream :default *solid-areas*
:query-identifier 'solid-areas)
(declare (ignore ptype))
(setf changed (or changed changed8))
(when changed8 (setf *solid-areas* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed9)
(accept 'boolean
:prompt "Highlight Bound"
:stream stream :default *highlight-bindings*
:query-identifier 'highlight-bindings)
(declare (ignore ptype))
(setf changed (or changed changed9))
(when changed9 (setf *highlight-bindings* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed10)
(accept 'boolean
:prompt "Show Bindings"
:stream stream :default *display-binding-names-mode*
:query-identifier 'display-bindings)
(declare (ignore ptype))
(setf changed (or changed changed10))
(when changed10 (setf *display-binding-names-mode* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed5)
(accept 'boolean
:prompt "Draw Only Bound"
:stream stream :default *display-only-bound-objects*
:query-identifier 'display-only-bound-objects)
(declare (ignore ptype))
(setf changed (or changed changed5))
(when changed5 (setf *display-only-bound-objects* bool))))
(formatting-cell (stream :align-x :center)
(multiple-value-bind (bool ptype changed11)
(accept 'boolean
:prompt "Use Query Processor"
:stream stream :default *use-query-processor*
:query-identifier 'use-query-processor)
(declare (ignore ptype))
(setf changed (or changed changed11))
(when changed11 (setf *use-query-processor* bool))))
(when (and changed *autotracking-mode*)
(com-draw-current-map))))))
(defmethod accept-os-selection ((frame map-viewer) stream)
(with-map-viewer-frame (map-viewer-frame)
(let ((y 0))
(flet ((set-item (item)
(let ((item (lookup-os item)))
(draw-text* stream
(format nil "~A ~A" (first item) (third item))
0 y)))
(set-unknown-item (item)
(draw-text* stream
(format nil "??? ~A ???" item)
0 y)))
(with-slots (present-os-keys selected-os-keys) map-viewer-frame
(dolist (item *unknown-os-keys*)
(incf y 14)
(let ((selected (member item selected-os-keys :test #'equal)))
(updating-output (stream :unique-id item
:cache-value (list y selected)
:cache-test #'equal)
(with-output-as-presentation
(stream item 'os-key-item)
(if selected
(with-drawing-options (stream :text-style +selected-item-ts+
:ink +selected-item-i+)
(set-unknown-item item))
(with-drawing-options (stream :text-style +unselected-item-ts+
:ink +unselected-item-i+)
(set-unknown-item item)))))))
(dolist (item *os*)
(let ((item (second item)))
(incf y 14)
(let ((selected (member item selected-os-keys :test #'equal)))
(updating-output (stream :unique-id item
:cache-value (list y selected)
:cache-test #'equal)
(if (member item present-os-keys :test #'equalp)
(with-output-as-presentation
(stream item 'os-key-item)
(if selected
(with-drawing-options (stream :text-style +selected-item-ts+
:ink +selected-item-i+)
(set-item item))
(with-drawing-options (stream :text-style +unselected-item-ts+
:ink +unselected-item-i+)
(set-item item))))
(with-drawing-options (stream :text-style +grayed-item-ts+
:ink +grayed-item-i+)
(set-item item))))))))))))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-os-key-item :name "Select Key")
((object 'os-key-item))
(with-map-viewer-frame (map-viewer-frame)
(with-slots (present-os-keys selected-os-keys) map-viewer-frame
(register-selected-keys-for-undo)
(setf selected-os-keys
(if (member object selected-os-keys :test #'equalp)
(remove object selected-os-keys :test #'equalp)
(cons object selected-os-keys)))
(when *autotracking-mode*
(com-draw-current-map)))))
(define-presentation-to-command-translator select-os-key-item
(os-key-item com-highlight-os-key-item map-viewer
:gesture :select-os-key-item)
(object)
(list object))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-all-os-keys :name "Select All Keys")
()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (present-os-keys selected-os-keys) map-viewer-frame
(register-selected-keys-for-undo)
(setf selected-os-keys (copy-tree present-os-keys))
(com-draw-current-map))))
(define-map-viewer-command (com-unselect-all-os-keys :name "Unselect All Keys")
()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (present-os-keys selected-os-keys) map-viewer-frame
(register-selected-keys-for-undo)
(setf selected-os-keys nil)
(com-draw-current-map))))
;;;
;;;
;;;
(define-map-viewer-command (com-unselect-os-keys-of-object :name "Unselect OS Keys Of Object")
((object 'map-object))
(with-map-viewer-frame (map-viewer-frame)
(with-slots (present-os-keys selected-os-keys) map-viewer-frame
(register-selected-keys-for-undo)
(dolist (os (all-os object))
(setf selected-os-keys
(delete os selected-os-keys :test #'equalp)))
(com-draw-current-map))))
(define-map-viewer-command (com-unselect-all-but-os-keys-of-object :name "Unselect All But OS Keys Of Object")
((object 'map-object))
(with-map-viewer-frame (map-viewer-frame)
(with-slots (present-os-keys selected-os-keys) map-viewer-frame
(register-selected-keys-for-undo)
(setf selected-os-keys
(all-os object))
(com-draw-current-map))))
(define-presentation-to-command-translator unselect-os-keys-of-object
(map-object com-unselect-os-keys-of-object map-viewer
:gesture :unselect-os-keys-of-object)
(object)
(list object))
(define-presentation-to-command-translator unselect-all-but-os-keys-of-object
(map-object com-unselect-all-but-os-keys-of-object map-viewer
:gesture :unselect-all-but-os-keys-of-object)
(object)
(list object))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-os-keys-of-object :name "Highlight OS Keys Of Object")
((object 'map-object))
(with-map-viewer-frame (map-viewer-frame)
(let ((os (all-os object)))
(with-slots (map) map-viewer-frame
(dolist (obj (objects map))
(when (intersection (all-os obj) os)
(if (highlighted-p obj)
(unselect obj)
(select obj)))))))
(com-draw-current-map))
(define-presentation-to-command-translator highlight-os-keys-of-object
(map-object com-highlight-os-keys-of-object map-viewer
:gesture :highlight-os-keys-of-object)
(object)
(list object))
;;;
;;;
;;;
(define-map-viewer-command (com-lookup-os-key :name "Lookup OS Key")
()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (unselect-stack) map-viewer-frame
(let* ((stream (get-frame-pane map-viewer-frame 'display))
(os-number
(accepting-values (stream :own-window t :label "Lookup OS Key:")
(accept 'integer :stream stream :view 'gadget-dialog-view))))
(window-clear *standard-output*)
(terpri)
(format t " ~A~%"
(lookup-os os-number))))))
;;;
;;;
;;;
(define-map-viewer-command (com-hide-object :name "Hide Object")
((object 'si-geom-thing))
(register-hide-for-undo object)
(setf (dont-display object) t)
(com-clear-display)
(com-draw-current-map))
(define-presentation-to-command-translator hide-object
(si-geom-thing com-hide-object map-viewer
:gesture :hide-object)
(object)
(list object))
;;;
;;;
;;;
(defun show-current-map-range (&key (record t)
(coordinates t)
stream
transformation)
(with-map-viewer-frame (frame)
(let ((stream (or stream (get-frame-pane frame 'overview))))
(with-slots (map overview-transformation
current-map-range
current-map-position current-map-radius) frame
(flet ((draw-it ()
(with-correct-clipping (stream)
(with-drawing-options (stream :transformation
(or transformation overview-transformation))
(draw-circle* stream
(first current-map-position)
(second current-map-position)
(- current-map-radius 4)
:ink +flipping-ink+
:line-thickness 2
:filled nil)
(draw-rectangle* stream
(x (pmin current-map-range))
(y (pmin current-map-range))
(x (pmax current-map-range))
(y (pmax current-map-range))
:line-thickness 2
:ink +flipping-ink+
:filled t)))))
(when map
(when coordinates
(show-coordinates frame (get-frame-pane frame 'coordinates)))
(if record
(with-output-as-presentation (stream current-map-range
'current-map-range)
(draw-it))
(with-output-recording-options (stream :draw t :record nil)
(draw-it)))))))))
(define-map-viewer-command (com-adjust-map-center :name "Adjust Map Center")
((object 'current-map-range))
(declare (ignore object))
(adjust-map-center))
(define-map-viewer-command (com-adjust-map-extent :name "Adjust Map Extent")
((object 'current-map-range))
(declare (ignore object))
(adjust-map-extent))
(define-map-viewer-command (com-full-map-extent :name "Full Map Extent")
((object 'current-map-range))
(declare (ignore object))
(full-map-range))
(define-presentation-to-command-translator adjust-map-center
(current-map-range com-adjust-map-center map-viewer
:gesture :adjust-map-center)
(object)
(list object))
(define-presentation-to-command-translator adjust-map-extent
(current-map-range com-adjust-map-extent map-viewer
:gesture :adjust-map-extent)
(object)
(list object))
(define-presentation-to-command-translator full-map-extent
(current-map-range com-full-map-extent map-viewer
:gesture :full-map-extent)
(object)
(list object))
(defmethod set-current-map-position-and-radius (xcenter ycenter r)
(with-map-viewer-frame (frame)
(with-slots (current-map-position current-map-radius) frame
(setf current-map-position
(list xcenter ycenter))
(setf current-map-radius r))
(let ((*autotracking-mode* nil))
(adjust-current-map-range))))
(defun full-map-range ()
(with-map-viewer-frame (frame)
(with-slots (map old-overview-vp-width
old-overview-vp-height) frame
(when map
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(set-current-map-position-and-radius
(floor (+ xmin xmax) 2)
(floor (+ ymin ymax) 2)
(- xmax (floor (+ xmin xmax) 2)))
(when *autotracking-mode*
(adjust-current-map-range)))))))
(defun reset-map-range ()
(with-map-viewer-frame (frame)
(with-slots (map current-map-radius current-map-position) frame
(when map
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(setf current-map-radius (floor (- xmax xmin) 5))
(setf current-map-position
(list (floor (+ xmin xmax) 2)
(floor (+ ymin ymax) 2)))
(let ((*autotracking-mode* nil))
(adjust-current-map-range)))))))
(defun adjust-current-map-range ()
(with-map-viewer-frame (frame)
(with-slots (current-map-range
current-map-position current-map-radius) frame
(let ((xcenter (first current-map-position))
(ycenter (second current-map-position)))
(if (not current-map-range)
(setf current-map-range
(make-bounding-box
(- xcenter current-map-radius) (- ycenter current-map-radius)
(+ xcenter current-map-radius) (+ ycenter current-map-radius)))
(with-slots (pmin pmax) current-map-range
(setf (x pmin) (- xcenter current-map-radius)
(y pmin) (- ycenter current-map-radius)
(x pmax) (+ xcenter current-map-radius)
(y pmax) (+ ycenter current-map-radius))))
(recalculate-transformation (get-frame-pane frame 'display))
(when *autotracking-mode*
(com-draw-current-map))))))
(defun adjust-map-center ()
(with-map-viewer-frame (map-viewer-frame)
(let ((stream (get-frame-pane map-viewer-frame 'overview)))
(with-slots (current-map-position
map
old-overview-vp-width
old-overview-vp-height) map-viewer-frame
(when map
(block track-pointer
(with-output-recording-options (stream :draw t :record nil)
(tracking-pointer (stream)
(:pointer-motion (x y)
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(let* ((xscale (/ old-overview-vp-width (- xmax xmin)))
(yscale (/ old-overview-vp-height (- ymax ymin)))
(xcenter
(+ xmin (* (/ 1 xscale) x)))
(ycenter
(+ ymax (* (- (/ 1 yscale)) y))))
(show-current-map-range :record nil)
(setf current-map-position
(list xcenter ycenter))
(adjust-current-map-range)
(show-current-map-range :record nil))))
(:pointer-button-press ()
(return-from track-pointer))))))))))
(defun adjust-map-extent ()
(with-map-viewer-frame (map-viewer-frame)
(let ((stream (get-frame-pane map-viewer-frame 'overview)))
(with-slots (current-map-radius
current-map-position
map
old-overview-vp-width
old-overview-vp-height) map-viewer-frame
(when map
(block track-pointer
(with-output-recording-options (stream :draw t :record nil)
(tracking-pointer (stream)
(:pointer-motion (x y)
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(let* ((xscale (/ old-overview-vp-width (- xmax xmin)))
(yscale (/ old-overview-vp-height (- ymax ymin)))
(xcenter (first current-map-position))
(ycenter (second current-map-position))
(xr
(- xcenter (+ xmin (* (/ 1 xscale) x))))
(yr
(- ycenter (+ ymax (* (- (/ 1 yscale)) y))))
(r (sqrt (+ (* xr xr) (* yr yr)))))
(unless (zerop r)
(show-current-map-range :record nil)
(setf current-map-radius r)
(adjust-current-map-range)
(show-current-map-range :record nil)))))
(:pointer-button-press ()
(return-from track-pointer))))))))))
(defmethod show-coordinates ((frame map-viewer) stream)
(with-slots (current-map-range map) frame
(when map
(window-clear stream)
;(terpri stream)
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(format stream " Full Map: (~A,~A) - (~A,~A)"
(round xmin) (round ymin)
(round xmax) (round ymax)))
(terpri stream)
(with-slots (pmin pmax) current-map-range
(format stream " Map Range: (~A,~A) - (~A,~A)"
(round (x pmin)) (round (y pmin))
(round (x pmax)) (round (y pmax)))
(terpri stream)
(let ((size (abs (round (- (x pmin) (x pmax))))))
(format stream " Range: ~A * ~A meters" size size))))))
;;;
;;;
;;;
(defmethod selectedp ((object map-object))
(with-map-viewer-frame (map-viewer-frame)
(with-slots (selected-os-keys) map-viewer-frame
(some #'(lambda (os)
(member os selected-os-keys :test #'equal))
(all-os object)))))
(defmethod selectedp ((obj si-geom-thing))
t)
;;;
;;;
;;;
(defmethod draw-current-map ((frame map-viewer) stream &key
overview
fast-p
(clear-p t))
(with-slots (current-map-range
current-map-transformation
selected-os-keys map) frame
(with-slots (pmin pmax) current-map-range
(let ((*draw-overview* overview)
(*draw-components* nil))
(labels ((draw-it (cur-obj)
(when (not (dont-display cur-obj))
(if (and (=> (not *display-only-bound-objects*)
(selectedp cur-obj))
(=> *display-only-bound-objects*
(bound-to cur-obj)))
(draw cur-obj stream)
(when *warn-mode* (warn "~%Object not drawn! ~A" cur-obj))))))
(when clear-p (window-clear stream))
(when map
(with-correct-clipping (stream)
(with-drawing-options (stream :transformation current-map-transformation)
(with-selected-objects (cur-obj current-map-range
(and (typep cur-obj 'si-geom-polygon)
(primary-p cur-obj)
(not (bound-to cur-obj)))
:intersects)
(draw-it cur-obj))
;;;
;;; highlighted objects liegen immer "oben"!
;;;
(when fast-p
;;; ausser den Polygonen werden nur noch die
;;; gehighlighteten gemalt ("fast")
(with-selected-objects (cur-obj current-map-range
(bound-to cur-obj)
:intersects)
(draw-it cur-obj)))
(unless fast-p
(with-selected-objects (cur-obj current-map-range
(and (typep cur-obj 'si-geom-polygon)
(primary-p cur-obj)
(bound-to cur-obj))
:intersects)
(draw-it cur-obj))
(with-selected-objects (cur-obj current-map-range
(and (not (typep cur-obj 'si-geom-polygon))
(primary-p cur-obj))
:intersects)
(draw-it cur-obj))
(when *draw-contours*
(with-selected-objects (cur-obj current-map-range
(and (typep cur-obj 'si-geom-polygon)
(primary-p cur-obj))
:intersects)
(dolist (segment (segments cur-obj))
(when (and (not (dont-display segment))
(selectedp segment))
(draw-it segment))))))
(when *display-binding-names-mode*
(dolist (object (elements (spatial-index map)))
(when (and (bound-to object)
(not (eq (bound-to object) t)))
(multiple-value-bind (lx ly)
(label-pos object)
(with-output-as-presentation
(stream object (type-of object)
:single-box *single-box-mode* :allow-sensitive-inferiors t)
(draw-text* stream
(format nil "~A" (bound-to object))
lx ly
:ink +bound-to-text-ink+
:text-style +bound-to-text-style+))))))
(dolist (cur-obj (text-objects map))
(when (box-overlaps-box-p (bbox cur-obj)
current-map-range)
(draw cur-obj stream)))))))))))
(defun draw-current-map-to-foreign-stream (stream &key width height overview fast-p)
(with-map-viewer-frame (map-viewer)
(recalculate-transformation stream :width width :height height)
(draw-current-map map-viewer stream
:fast-p fast-p
:clear-p nil
:overview overview)
(recalculate-transformation (get-frame-pane map-viewer 'display))))
;;;
;;;
;;;
#+allegro
(defmethod draw-overview ((frame map-viewer) stream)
(with-slots (overview-pattern current-map-range
overview-transformation
map) frame
(when map
(multiple-value-bind (viewport-width viewport-height)
(bounding-rectangle-size (bounding-rectangle (window-viewport stream)))
(unless overview-pattern
(setf overview-pattern
(make-pattern-from-pixmap
(with-output-to-pixmap (stream
(sheet-medium (get-frame-pane frame 'overview))
:width viewport-width
:height viewport-height)
(with-drawing-options (stream :transformation overview-transformation)
(with-pretty-map-output
(let ((*draw-overview* t))
(dolist (obj (elements (spatial-index map)))
(when (primary-p obj)
(draw obj stream))))))))))
(draw-pattern* stream overview-pattern 0 0)
(show-current-map-range)))))
#+(and mcl antiker-mac)
(defmethod draw-overview ((frame map-viewer) stream)
(with-slots (overview-pattern current-map-range
overview-transformation
map) frame
(show-current-map-range)))
#+(or (and mcl (not antiker-mac)) lispworks)
(defmethod draw-overview ((frame map-viewer) stream)
(with-slots (overview-pattern current-map-range
overview-transformation
map) frame
(when map
(multiple-value-bind (viewport-width viewport-height)
(bounding-rectangle-size (bounding-rectangle (window-viewport stream)))
(unless overview-pattern
(setf overview-pattern
(with-output-to-pixmap (stream
(sheet-medium (get-frame-pane frame 'overview))
:width viewport-width
:height viewport-height)
(draw-rectangle* stream 0 0 viewport-width viewport-height
:ink +white+)
(with-drawing-options (stream :transformation overview-transformation)
(with-pretty-map-output
(let ((*draw-overview* t))
(dolist (obj (elements (spatial-index map)))
(when (primary-p obj)
(draw obj stream)))))))))
(draw-pixmap* stream
overview-pattern
0 0)
(show-current-map-range)))))
;;;
;;;
;;;
(define-presentation-method highlight-presentation ((type si-geom-thing) record stream state)
(with-map-viewer-frame (frame)
(with-slots (current-map-transformation map) frame
(with-correct-clipping (stream)
(with-drawing-options (stream :transformation current-map-transformation)
(highlight-object (presentation-object record) stream state))))))
(defmethod highlight-object ((object si-geom-chain) stream state)
(dolist (segment (segments object))
(draw-line* stream
(x (p1 segment))
(y (p1 segment))
(x (p2 segment))
(y (p2 segment))
:ink +flipping-ink+
:line-thickness +highlight-thickness+)))
(defmethod highlight-object ((object si-geom-polygon) stream state)
(draw-polygon* stream (xy-list object)
:filled t
:ink +flipping-ink+
:line-thickness +highlight-thickness+))
(defmethod highlight-object ((object si-geom-point) stream state)
(with-slots (x y) object
(if (primary-p object)
(progn
(draw-circle*
stream
x y 10
:ink +flipping-ink+
:line-thickness +highlight-thickness+
:filled nil)
(draw-circle*
stream
x y 8
:line-thickness +highlight-thickness+
:filled t
:ink +flipping-ink+))
(draw-circle*
stream
x y (if (bound-to object)
10
6)
:line-thickness +highlight-thickness+
:filled t
:ink +flipping-ink+))))
(defmethod highlight-object ((object si-geom-line) stream state)
(with-slots (p1 p2) object
(draw-line*
stream
(x p1) (y p1)
(x p2) (y p2)
:ink +flipping-ink+
:line-thickness +highlight-thickness+)))
;;;
;;;
;;;
(defmethod draw :around ((object si-geom-thing) stream)
(labels ((draw-it ()
(if *sensitive-objects-mode*
(with-output-as-presentation
(stream object (type-of object)
:single-box *single-box-mode* :allow-sensitive-inferiors t)
(call-next-method))
(call-next-method))))
(if (typep object 'map-object)
(with-drawing-options (stream :ink (if (and *highlight-bindings*
(bound-to object))
+bound-to-ink+
(map-color object))
:line-thickness (if (and *highlight-bindings*
(bound-to object))
+highlight-line-thickness+
1))
(draw-it))
(with-drawing-options (stream :ink (if (and *highlight-bindings*
(bound-to object))
+bound-to-ink+
+non-map-object-color+)
:line-thickness (if (and *highlight-bindings*
(bound-to object))
+highlight-line-thickness+
1))
(draw-it)))))
(defmethod draw ((object si-geom-line) stream)
(with-slots (p1 p2) object
(when (and *sensitive-objects-mode* +gravity-field+)
(draw-line*
stream
(x p1) (y p1)
(x p2) (y p2)
:ink +transparent-ink+
:line-thickness +gravity-field-thickness2+))
(draw-line*
stream
(x p1) (y p1)
(x p2) (y p2))
(when (or *display-nodes-mode* *draw-components*)
(draw p1 stream)
(draw p2 stream))))
(defmethod draw ((object si-geom-chain) stream)
(when (selectedp object)
(unless *draw-overview*
(draw-marker* stream
(x (centroid object))
(y (centroid object))
5
:ink +marker-color+))
(when (and *sensitive-objects-mode* +gravity-field+)
(dolist (segment (segments object))
(draw-line* stream
(x (p1 segment))
(y (p1 segment))
(x (p2 segment))
(y (p2 segment))
:ink +transparent-ink+
:line-thickness +gravity-field-thickness+)))
(dolist (segment (segments object))
(draw-line* stream
(x (p1 segment))
(y (p1 segment))
(x (p2 segment))
(y (p2 segment))))
(when *draw-components*
(dolist (segment (segments object))
(when (and (not (dont-display segment))
(selectedp segment))
(draw segment stream))))))
(defmethod draw ((object si-geom-polygon) stream)
(when (selectedp object)
(when (and *sensitive-objects-mode* +gravity-field+)
(draw-polygon* stream (xy-list object)
:filled nil
:ink +transparent-ink+
:line-thickness +gravity-field-thickness+))
(draw-polygon* stream (xy-list object)
:filled *solid-areas*)
(dolist (hole (holes object))
(draw-polygon* stream (xy-list hole)
:filled *solid-areas*
:ink +white+))
(unless *draw-overview*
(draw-marker* stream
(x (centroid object))
(y (centroid object))
5
:ink +marker-color+))
(when *draw-components*
(dolist (segment (segments object))
(when (and (not (dont-display segment))
(selectedp segment))
(draw segment stream))))))
(defmethod draw ((object si-geom-point) stream)
(with-slots (x y name) object
(draw-circle*
stream
x y (if (and (bound-to object)
*highlight-bindings*)
8
4)
:filled t)))
(defmethod draw ((object basic-map-symbol) stream)
(with-slots (x y name) object
(draw-circle*
stream
x y 8
:filled nil)
(draw-circle*
stream
x y 6
:filled nil)
(draw-line* stream
(- x 5) (- y 5)
(+ x 5) (+ y 5))
(draw-line* stream
(- x 5) (+ y 5)
(+ x 5) (- y 5))))
(defmethod draw ((object map-text) stream)
(when *display-map-text-mode*
(with-drawing-options (stream :transformation (matrix object)
:ink +text-color+)
(with-slots (text) object
(draw-vector-text text stream)))))
;;;
;;;
;;;
(defun measure-and-draw-map ()
(with-map-viewer-frame (frame)
(with-slots (overview-transformation
present-os-keys
overview-pattern
current-map-position current-map-radius map) frame
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(window-clear *standard-output*)
(dolist (text-obj (text-objects map))
(let ((stream (get-frame-pane frame 'display))
(*display-map-text-mode* t))
(init text-obj stream)))
(setf overview-pattern nil)
(setf present-os-keys nil)
(setf *unknown-os-keys* nil)
(labels ((insert-os-key (object)
(dolist (item (all-os object))
(if (lookup-os item)
(pushnew item
present-os-keys)
(pushnew item
*unknown-os-keys*)))
(if (or (typep object 'basic-map-polygon)
(typep object 'basic-map-chain))
(dolist (object (segments object))
(when (typep object 'map-object)
(insert-os-key object))))))
(dolist (obj (objects map))
(insert-os-key obj))
(show-map-infos)
(change-os-key-selection)
(recalculate-transformation (get-frame-pane frame 'overview) :force t)
(reset-map-range)
(com-draw-current-map)
(draw-overview frame (get-frame-pane frame 'overview)))))))
(defmethod recalculate-transformation (sheet &key width height)
(with-map-viewer-frame (map-viewer-frame)
(with-slots (map current-map-range current-map-transformation) map-viewer-frame
(when map
(let* ((vbb
(window-viewport sheet))
(vb-width
(or width (bounding-rectangle-width vbb)))
(vb-height
(or height (bounding-rectangle-height vbb)))
(xscale (/ vb-width (- (x (pmax current-map-range)) (x (pmin current-map-range)))))
(yscale (/ vb-height (- (y (pmax current-map-range)) (y (pmin current-map-range)))))
(trans1 (make-translation-transformation (- (x (pmin current-map-range)))
(- (y (pmax current-map-range)))))
(trans2 (make-scaling-transformation
xscale
(- yscale)))
(trans
(compose-transformations trans2 trans1)))
(setf current-map-transformation trans))))))
(defmethod recalculate-transformation ((pane overview-pane) &key force)
(with-map-viewer-frame (map-viewer-frame)
(with-slots (map
overview-transformation
old-overview-vp-width
old-overview-vp-height) map-viewer-frame
(when map
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(let* ((vpbb
(window-viewport
(get-frame-pane map-viewer-frame 'overview)))
(vp-width
(bounding-rectangle-width vpbb))
(vp-height
(bounding-rectangle-height vpbb)))
(when (or force
(not old-overview-vp-width) (not old-overview-vp-height)
(not (and (= old-overview-vp-width vp-width)
(= old-overview-vp-height vp-height))))
(let*
((trans1 (make-translation-transformation (- xmin) (- ymax)))
(trans2 (make-scaling-transformation
(/ vp-width (- xmax xmin))
(- (/ vp-height (- ymax ymin)))))
(trans (compose-transformations trans2 trans1)))
(setf old-overview-vp-width vp-width
old-overview-vp-height vp-height)
(setf overview-transformation trans)))))))))
(defmethod calculate-transformation ((pane application-pane))
(with-map-viewer-frame (map-viewer-frame)
(with-slots (map) map-viewer-frame
(when map
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(let* ((vpbb
(window-viewport pane))
(vp-width
(bounding-rectangle-width vpbb))
(vp-height
(bounding-rectangle-height vpbb))
(trans1 (make-translation-transformation (- xmin) (- ymax)))
(trans2 (make-scaling-transformation
(/ vp-width (- xmax xmin))
(- (/ vp-height (- ymax ymin))))))
(compose-transformations trans2 trans1)))))))
;;;
;;;
;;;
(define-map-viewer-command (com-show-map-infos :name "Show Map Infos")
()
(window-clear *standard-output*)
(show-map-infos))
(defun show-map-infos (&optional (stream *standard-output*))
(with-map-viewer-frame (map-viewer-frame)
(with-slots (map present-os-keys) map-viewer-frame
(when map
(fresh-line stream)
(terpri stream)
(format stream " Infos For Map ~A:~%" (name map))
(format stream " ~A,~%" map)
(format stream " ~A Objects in Map, ~%" (length (objects map)))
(format stream " ~A Objects in Spatial Index, ~%" (length (elements (spatial-index map))))
(format stream " ~A Unknown Object OS Keys,~%" (length *unknown-os-keys*))
(format stream " ~A Known Object OS Keys. " (length present-os-keys))))))
;;;
;;;
;;;
(define-map-viewer-command (com-invert-highlighted :name "Invert Highlighted")
()
(invert-highlighted)
(com-redraw))
(defun invert-highlighted ()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (map) map-viewer-frame
(dolist (object (elements (spatial-index map)))
(setf (bound-to object) (not (bound-to object))))
(dolist (object (elements (spatial-index map)))
(when (for-some-component-holds-p object #'bound-to)
(setf (bound-to object) t))))))
(define-map-viewer-command (com-delete-highlighted-objects :name "Delete Highlighted Objects")
()
(with-map-viewer-frame (map-viewer-frame)
(invert-highlighted)
(with-slots (map) map-viewer-frame
(with-slots (xmin ymin xmax ymax) (spatial-index map)
(recompute-map xmin ymin xmax ymax)))))
(define-map-viewer-command (com-highlight-hidden-objects :name "Highlight Hidden Objects")
()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (map) map-viewer-frame
(dolist (obj (elements (spatial-index map)))
(when (dont-display obj)
(select obj)
(setf (dont-display obj) nil)))))
(com-redraw))
(define-map-viewer-command (com-crop-map :name "Crop Map")
()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (map current-map-range) map-viewer-frame
(unhighlight-all)
(with-selected-objects (cur-obj current-map-range
t
:truly-inside)
(setf (bound-to cur-obj) t))
(recompute-map (x (pmin current-map-range))
(y (pmin current-map-range))
(x (pmax current-map-range))
(y (pmax current-map-range))))))
(define-map-viewer-command (com-highlight-objects-in-current-range :name "Highlight Objects in Current Range")
()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (current-map-range map) map-viewer-frame
(with-selected-objects (cur-obj current-map-range
t
:truly-inside)
(select cur-obj))))
(com-redraw))
(defun recompute-map (xmin ymin xmax ymax)
(with-map-viewer-frame (map-viewer-frame)
(with-slots (current-map-range map) map-viewer-frame
(let* ((objects (remove-if-not #'(lambda (x)
(and (highlighted-p x)
(for-each-master-holds-p x #'highlighted-p)))
(elements (spatial-index map)))))
(dolist (obj (set-difference (objects map) objects))
(delete-node map obj))
(setf (text-objects map)
(remove-if-not #'(lambda (x)
(box-overlaps-box-p (bbox x)
current-map-range))
(text-objects map)))
(set-client-bb xmin ymin xmax ymax)
(dolist (obj objects)
(insert-into-spatial-index obj))
(sort-current-spatial-index)
(unhighlight (elements (spatial-index map)))
(measure-and-draw-map)))))
(defun change-os-key-selection ()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (present-os-keys selected-os-keys) map-viewer-frame
(setf selected-os-keys present-os-keys))))
;;;
;;;
;;;
(define-map-viewer-command (com-classify-map :name "Classify Map")
()
t)
;;;
;;;
;;;
(define-map-viewer-command (com-close-roles :name "Close Roles")
()
(close-roles (get-current-map)))
;;;
;;;
;;;
(define-map-viewer-command (com-load-sqd-map :name "Load SQD Map")
()
(with-map-viewer-frame (map-viewer-frame)
(let ((stream (get-frame-pane map-viewer-frame 'infos)))
(let ((file (file-selector "Load SQD Map" "maps:" "sqd")))
(when file
(window-clear stream)
(terpri stream)
(format stream " Attempting to load SQD map ~A!" file)
(install-as-current-mapviewer-map (make-map-from-sqd-file file
:delete-if-exists-p t
:racer-package 'racer-user
:abox
(intern
(string-upcase
(pathname-name
(truename file))))
:tbox
(unless (eq *kind-of-map* 'alcrcc-explicit-relations-map)
'oejendorf)
:type *kind-of-map*)))))))
(defmethod install-as-current-mapviewer-map ((obj map*))
(with-map-viewer-frame (frame)
(with-slots (map) frame
(setf map obj)
(setf *kind-of-map*
(type-of map))
(measure-and-draw-map))))
(defun reinstall-map-viewer-map ()
(install-as-current-map (slot-value *map-viewer-frame* 'map)))
;;;
;;;
;;;
(define-map-viewer-command (com-install-as-current-mapviewer-map :name "Install Current Map DB")
()
(when (get-current-map)
(install-as-current-mapviewer-map (get-current-map))))
;;;
;;;
;;;
(define-map-viewer-command (com-load-map :name "Load Map")
()
(let ((file (file-selector "Load Map" "maps:" "map")))
(when file
(install-as-current-mapviewer-map (load-map file)))))
(define-map-viewer-command (com-save-map-as :name "Save Map As")
()
(with-map-viewer-frame (map-viewer-frame)
(let ((file (file-selector "Save Map" "maps:" "map" :save t)))
(when file
(with-slots (map) map-viewer-frame
(save-map map file))))))
(define-map-viewer-command (com-save-map :name "Save Map")
()
(with-map-viewer-frame (map-viewer-frame)
(with-slots (map) map-viewer-frame
(let ((file (format nil "~A-~A-~A-~A.map"
(let* ((name (format nil "~A" (name map)))
(pos (position #\/ name :from-end t))
(pos2 (position #\. name :from-end t)))
(if pos
(subseq name (1+ pos)
(or pos2 (length name)))
name))
(type-of map)
(if (dc-edges-p map)
'with-dc
'no-dc)
(when (typep map 'racer-map)
(if (closed-roles-p map)
'closed-roles
'open-roles)))))
(save-map map file)))))
;;;
;;;
;;;
(defun com-draw-current-map ()
(with-map-viewer-frame (map-viewer-frame)
(draw-current-map map-viewer-frame (get-frame-pane map-viewer-frame 'display))
(redisplay-frame-pane map-viewer-frame 'os-selector)))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-object :name "Highlight Object")
((object 'map-object))
(if (bound-to object)
(unselect object)
(select object))
(setf *selected-object* object)
(com-redraw))
(define-presentation-to-command-translator select-object
((map-object) com-highlight-object map-viewer
:gesture :select-object)
(object)
(list object))
(define-map-viewer-command (com-describe-object :name "Describe Object")
((object 'si-geom-thing))
(labels ((describe-this-object (object level &key slave)
(when (typep object 'map-object)
(dolist (os (all-os object))
(multiple-value-bind (os-info found)
(lookup-os os)
(if found
(my-format *standard-output* level
"~A ~A"
(thematic-substrate::name object)
os-info)
(my-format *standard-output* level
"~A Unknown Object!"
(thematic-substrate::name object))))))
(when (and (not slave)
(or (typep object 'si-geom-chain)
(typep object 'si-geom-polygon)))
(fresh-line *standard-output*)
(my-format *standard-output* level "Has Segments:")
(dolist (segment (segments object))
(terpri *standard-output*)
(describe-this-object segment (1+ level)
:slave slave)))
(when (and slave (part-of object))
(dolist (part (part-of object))
(fresh-line *standard-output*)
(my-format *standard-output* level "Part Of:~%")
(describe-this-object part (1+ level)
:slave slave)))))
(window-clear *standard-output*)
(terpri)
(setf *selected-object* object)
(describe-this-object object 0
:slave
(part-of object))))
(define-presentation-to-command-translator describe
((si-geom-thing) com-describe-object map-viewer
:gesture :describe-object)
(object)
(list object))
;;;
;;;
;;;
(define-map-viewer-command (com-clear-display :name "Clear Map Display")
()
(with-map-viewer-frame (map-viewer-frame)
(let ((stream (get-frame-pane map-viewer-frame 'display)))
(window-clear stream))))
(define-map-viewer-command (com-redraw :name "Redraw Current Range")
()
(with-map-viewer-frame (frame)
(redisplay-frame-pane frame 'overview)
(com-clear-display)
(com-draw-current-map)
(redisplay-frame-pane frame 'os-selector)))
;;;
;;;
;;;
(define-map-viewer-command (com-restart-inspector :name "Restart Inspector")
()
(result-inspector))
(define-map-viewer-command (com-quit :name "Quit")
()
(with-map-viewer-frame (map-viewer-frame)
(let ((yes-or-no (notify-user map-viewer-frame
"Quit selected! Are you sure?"
:style :question)))
(when yes-or-no
(setf *map-viewer-frame* nil)
(frame-exit map-viewer-frame)))))
;;;
;;; SPATIAL QUERYING
;;;
(define-map-viewer-command (com-highlight-intersecting-objects* :name "Highlight Intersecting Objects")
()
(let ((object
(accept 'si-geom-thing)))
(show-intersecting-objects object)))
(define-map-viewer-command (com-highlight-intersecting-objects)
((object 'si-geom-thing :gesture nil))
(show-intersecting-objects object))
(defmethod show-intersecting-objects ((object si-geom-thing))
(unhighlight-all)
(if (and *use-query-processor* (typep object 'map-object))
(mapc #'highlight (get-successors-of-type object :po))
(with-selected-objects (obj object (not (eq obj object)) :intersects)
(highlight obj)))
(com-draw-current-map))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-contained-objects* :name "Highlight Contained Objects")
()
(let ((object
(accept 'si-geom-polygon)))
(show-contained-objects object)))
(define-map-viewer-command (com-highlight-contained-objects)
((object 'si-geom-polygon :gesture nil))
(show-contained-objects object))
(defmethod show-contained-objects ((object si-geom-polygon))
(unhighlight-all)
(if (and *use-query-processor* (typep object 'map-object))
(progn
(mapc #'highlight (get-successors-of-type object :tppi))
(mapc #'highlight (get-successors-of-type object :ntppi)))
(with-selected-objects (obj object t :inside)
(highlight obj)))
(com-draw-current-map))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-strictly-contained-objects* :name "Highlight Strictly Contained Objects")
()
(let ((object
(accept 'si-geom-polygon)))
(show-strictly-contained-objects object)))
(define-map-viewer-command (com-highlight-strictly-contained-objects)
((object 'si-geom-polygon :gesture nil))
(show-strictly-contained-objects object))
(defmethod show-strictly-contained-objects ((object si-geom-polygon))
(unhighlight-all)
(if (and *use-query-processor* (typep object 'map-object))
(mapc #'highlight (get-successors-of-type object :ntppi))
(with-selected-objects (obj object t :truly-inside)
(highlight obj)))
(com-draw-current-map))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-covered-objects* :name "Highlight Covered Objects")
()
(let ((object
(accept 'si-geom-polygon)))
(show-covered-objects object)))
(define-map-viewer-command (com-highlight-covered-objects)
((object 'si-geom-polygon :gesture nil))
(show-covered-objects object))
(defmethod show-covered-objects ((object si-geom-polygon))
(unhighlight-all)
(if (and *use-query-processor* (typep object 'map-object))
(mapc #'highlight (get-successors-of-type object :tppi))
(with-selected-objects (obj object t :covered-by)
(highlight obj)))
(com-draw-current-map))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-touching-objects* :name "Highlight Touching Objects")
()
(let ((object
(accept 'si-geom-thing)))
(show-touching-objects object)))
(define-map-viewer-command (com-highlight-touching-objects)
((object 'si-geom-thing :gesture nil))
(show-touching-objects object))
(defmethod show-touching-objects ((object si-geom-thing))
(unhighlight-all)
(if (and *use-query-processor* (typep object 'map-object))
(mapc #'highlight (get-successors-of-type object :ec))
(with-selected-objects (obj object t :touches)
(highlight obj)))
(com-draw-current-map))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-overlapping-objects* :name "Highlight Overlapping Objects")
()
(let ((object
(accept 'si-geom-polygon)))
(show-overlapping-objects object)))
(define-map-viewer-command (com-highlight-overlapping-objects)
((object 'si-geom-polygon :gesture nil))
(show-overlapping-objects object))
(defmethod show-overlapping-objects ((object si-geom-polygon))
(unhighlight-all)
(if (and *use-query-processor* (typep object 'map-object))
(mapc #'highlight (get-successors-of-type object :po))
(with-selected-objects (obj object t :overlaps)
(highlight obj)))
(com-draw-current-map))
;;;
;;;
;;;
(define-map-viewer-command (com-highlight-bordered-objects* :name "Highlight Bordered Objects")
()
(let ((object
(accept 'si-geom-thing)))
(show-bordered-objects object)))
(define-map-viewer-command (com-highlight-bordered-objects)
((object 'si-geom-thing :gesture nil))
(show-bordered-objects object))
(defmethod show-bordered-objects ((object si-geom-thing))
(unhighlight-all)
(if (and *use-query-processor* (typep object 'map-object))
(mapc #'highlight (get-successors-of-type object :borders))
(with-selected-objects (obj object (not (eq obj object)) :lies-on)
(highlight obj)))
(com-draw-current-map))
;;;
;;;
;;;
#+allegro
(defmethod note-frame-iconified ((manager tk-silica::motif-frame-manager) (frame map-viewer))
nil)
#|
(defmethod resize-sheet :after ((sheet display-pane) width height)
(declare (ignore width height))
(recalculate-transformation sheet)
(com-draw-current-map))
(defmethod resize-sheet :after ((sheet overview-pane) width height)
(declare (ignore width height))
(recalculate-transformation sheet)
(draw-overview (pane-frame sheet) sheet))
|#
(defun map-viewer (&key (force t)
(process t)
left
top width height
&allow-other-keys)
(let ((port (find-port)))
#+allegro
(setf (clim:text-style-mapping port
+map-viewer-text-style+)
"-*-lucida-medium-r-normal-*-12-*-*-*-*-*-*-*")
(when (or force (null *map-viewer-frame*))
(unless left
(multiple-value-bind (screen-width screen-height)
(bounding-rectangle-size
(sheet-region (find-graft :port port)))
(setf left 0
top 0
width screen-width
height screen-height)))
(setf *map-viewer-frame*
(make-application-frame
'map-viewer
:left left
:top top
:width (- width 40)
:height (- height 100)))
#+allegro
(if process
(mp:process-run-function
"Map-Viewer"
#'(lambda ()
(run-frame-top-level *map-viewer-frame*)))
(run-frame-top-level *map-viewer-frame*))
#+mcl
(if process
(ccl:process-run-function
"Map Viewer"
#'(lambda ()
(run-frame-top-level *map-viewer-frame*)))
(run-frame-top-level *map-viewer-frame*))
#+lispworks
(if process
(mp:process-run-function
"Map-Viewer"
'(:size 250000) ;;; set Stack Size!
#'(lambda ()
(run-frame-top-level *map-viewer-frame*)))
(run-frame-top-level *map-viewer-frame*))
*map-viewer-frame*)))
;;;
;;;
;;;
(defmethod frame-standard-input ((frame map-viewer))
(get-frame-pane frame 'command))
(defmethod frame-standard-output ((frame map-viewer))
(get-frame-pane frame 'infos))
(defmethod frame-error-output ((frame map-viewer))
(get-frame-pane frame 'infos))
| 74,015 | Common Lisp | .lisp | 1,879 | 29.051623 | 139 | 0.57298 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | decc4899f644e88a335090fb0ae0c469afe437ff7db1ce525ffa09b6c8fb475d | 12,502 | [
-1
] |
12,503 | tables.lisp | lambdamikel_DLMAPS/src/tables/tables.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: THEMATIC-SUBSTRATE; Base: 10 -*-
(in-package :THEMATIC-SUBSTRATE)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun swap-first-args (entry)
`(,(second entry) ,(first entry) ,@(cddr entry)))
(defconstant +rcc1-roles+ '(sr))
(defconstant +rcc1-rolebox+
(create-rbox 'rcc1-rolebox
+rcc1-roles+
:inverse-roles '((sr sr))
:reflexive-roles '(sr)
:type 'jepd-rolebox
:axioms
(mapcar #'swap-first-args
'((sr sr (sr))))))
(defconstant +rcc2-roles+ '(o dr))
(defconstant +rcc2-rolebox+
(create-rbox 'rcc2-rolebox
+rcc2-roles+
:inverse-roles '((o o) (dr dr))
:reflexive-roles '(o)
:type 'jepd-rolebox
:axioms
(mapcar #'swap-first-args
'((dr o (dr o))
(dr dr (dr o))
(o dr (dr o))
(o o (dr o))))))
(defconstant +rcc3-roles+ '(dr one eq))
(defconstant +rcc3-rolebox+
(create-rbox 'rcc3-rolebox
+rcc3-roles+
:inverse-roles '((dr dr) (one one))
:reflexive-roles '(eq)
:type 'jepd-rolebox
:axioms
(mapcar #'swap-first-args
'((dr dr (dr one eq))
(dr one (dr one))
(dr eq (dr))
(one dr (dr one))
(one one (dr one eq))
(one eq (one))
(eq dr (dr))
(eq one (one))
(eq eq (eq))))))
(defconstant +rcc5-roles+ '(dr po eq pp ppi))
(defconstant +rcc5-rolebox+
(create-rbox 'rcc5-rolebox
+rcc5-roles+
:inverse-roles '((dr dr) (po po) (pp ppi))
:reflexive-roles '(eq)
:type 'jepd-rolebox
:axioms
(mapcar #'swap-first-args
`((dr dr ,+rcc5-roles+)
(dr po (dr po ppi))
(dr eq (dr))
(dr pp (dr))
(dr ppi (dr po ppi))
(po dr (dr po pp))
(po po ,+rcc5-roles+)
(po eq (po))
(po pp (dr po pp))
(po ppi (po ppi))
(eq dr (dr))
(eq po (po))
(eq eq (eq))
(eq pp (pp))
(eq ppi (ppi))
(pp dr (dr po pp))
(pp po (po pp))
(pp eq (pp))
(pp pp (pp))
(pp ppi ,(remove 'dr +rcc5-roles+)) ; = overlap
(ppi dr (dr))
(ppi po (dr po ppi))
(ppi eq (ppi))
(ppi pp ,+rcc5-roles+)
(ppi ppi (ppi))))))
(defconstant +rcc8-roles+ '(dc ec po eq tpp tppi ntpp ntppi))
(defconstant +rcc8-rolebox+
(create-rbox 'rcc8-rolebox +rcc8-roles+
:reflexive-roles '(eq)
:inverse-roles '((dc dc) (ec ec) (po po)
(tpp tppi) (ntpp ntppi))
:type 'jepd-rolebox
:axioms
(let ((top +rcc8-roles+)
(dc '(dc))
(ec '(ec))
(po '(po))
(tpp '(tpp))
(ntpp '(ntpp))
(tppi '(tppi))
(ntppi '(ntppi))
(eq '(eq))
(dr '(ec dc))
(pp '(tpp ntpp))
(ppi '(tppi ntppi)))
(mapcar #'swap-first-args
`((dc dc ,top)
(dc ec (,@dr ,@po ,@ppi))
(dc po (,@dr ,@po ,@ppi))
(dc tpp ,dc)
(dc ntpp ,dc)
(dc tppi (,@dr ,@po ,@ppi))
(dc ntppi (,@dr ,@po ,@ppi))
(dc eq ,dc)
(ec dc (,@dr ,@po ,@pp))
(ec ec (,@dr ,@eq ,@po ,@tpp ,@tppi))
(ec po (,@dr ,@po ,@ppi))
(ec tpp ,dr)
(ec ntpp ,dc)
(ec tppi (,@ec ,@po ,@ppi))
(ec ntppi (,@po ,@ppi))
(ec eq ,ec)
(po dc (,@dr ,@po ,@pp))
(po ec (,@dr ,@po ,@pp))
(po po (,@top))
(po tpp (,@dr ,@po ,@pp))
(po ntpp (,@dr ,@po ,@pp))
(po tppi (,@po ,@ppi))
(po ntppi (,@po ,@ppi))
(po eq (,@po))
(tpp dc (,@dr ,@po ,@pp))
(tpp ec (,@ec ,@po ,@pp))
(tpp po (,@po ,@pp))
(tpp tpp ,pp)
(tpp ntpp ,ntpp)
(tpp tppi (,@po ,@eq ,@tpp ,@tppi))
(tpp ntppi (,@po ,@ppi))
(tpp eq (,@tpp))
(ntpp dc (,@dr ,@po ,@pp))
(ntpp ec (,@po ,@pp))
(ntpp po (,@po ,@pp))
(ntpp tpp (,@ntpp))
(ntpp ntpp (,@ntpp))
(ntpp tppi (,@po ,@pp))
(ntpp ntppi (,@po ,@eq ,@pp ,@ppi))
(ntpp eq (,@ntpp))
(tppi dc ,dc)
(tppi ec ,dr)
(tppi po (,@dr ,@po ,@ppi))
(tppi tpp (,@dr ,@eq ,@po ,@tpp ,@tppi))
(tppi ntpp (,@dr ,@po ,@pp))
(tppi tppi ,ppi)
(tppi ntppi ,ntppi)
(tppi eq ,tppi)
(ntppi dc ,dc)
(ntppi ec ,dc)
(ntppi po (,@dr ,@po ,@ppi))
(ntppi tpp (,@dr ,@po ,@ppi))
(ntppi ntpp ,top)
(ntppi tppi ,ntppi)
(ntppi ntppi ,ntppi)
(ntppi eq ,ntppi)
(eq dc ,dc)
(eq ec ,ec)
(eq po ,po)
(eq tpp ,tpp)
(eq ntpp ,ntpp)
(eq tppi ,tppi)
(eq ntppi ,ntppi)
(eq eq ,eq)))))))
| 7,782 | Common Lisp | .lisp | 165 | 21.666667 | 87 | 0.28735 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | f2aac1355a268b61373807041db0347136c26ee4b08542ab5d6a5f36035c1116 | 12,503 | [
-1
] |
12,504 | tables2.lisp | lambdamikel_DLMAPS/src/tables/tables2.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: THEMATIC-SUBSTRATE; Base: 10 -*-
(in-package :THEMATIC-SUBSTRATE)
(defun swap-first-args (entry)
`(,(second entry) ,(first entry) ,@(cddr entry)))
(defparameter +rcc1-roles+ '(sr))
(defparameter +rcc1-rolebox+
(create-rbox 'rcc1-rolebox
+rcc1-roles+
:inverse-roles '((sr sr))
:reflexive-roles '(sr)
:type 'jepd-rolebox
:axioms
(mapcar #'swap-first-args
'((sr sr (sr))))))
(defparameter +rcc2-roles+ '(o dr))
(defparameter +rcc2-rolebox+
(create-rbox 'rcc2-rolebox
+rcc2-roles+
:inverse-roles '((o o) (dr dr))
:reflexive-roles '(o)
:type 'jepd-rolebox
:axioms
(mapcar #'swap-first-args
'((dr o (dr o))
(dr dr (dr o))
(o dr (dr o))
(o o (dr o))))))
(defparameter +rcc3-roles+ '(dr one eq))
(defparameter +rcc3-rolebox+
(create-rbox 'rcc3-rolebox
+rcc3-roles+
:inverse-roles '((dr dr) (one one))
:reflexive-roles '(eq)
:type 'jepd-rolebox
:axioms
(mapcar #'swap-first-args
'((dr dr (dr one eq))
(dr one (dr one))
(dr eq (dr))
(one dr (dr one))
(one one (dr one eq))
(one eq (one))
(eq dr (dr))
(eq one (one))
(eq eq (eq))))))
(defparameter +rcc5-roles+ '(dr po eq pp ppi))
(defparameter +rcc5-rolebox+
(create-rbox 'rcc5-rolebox
+rcc5-roles+
:inverse-roles '((dr dr) (po po) (pp ppi))
:reflexive-roles '(eq)
:type 'jepd-rolebox
:axioms
(mapcar #'swap-first-args
`((dr dr ,+rcc5-roles+)
(dr po (dr po ppi))
(dr eq (dr))
(dr pp (dr))
(dr ppi (dr po ppi))
(po dr (dr po pp))
(po po ,+rcc5-roles+)
(po eq (po))
(po pp (dr po pp))
(po ppi (po ppi))
(eq dr (dr))
(eq po (po))
(eq eq (eq))
(eq pp (pp))
(eq ppi (ppi))
(pp dr (dr po pp))
(pp po (po pp))
(pp eq (pp))
(pp pp (pp))
(pp ppi ,(remove 'dr +rcc5-roles+)) ; = overlap
(ppi dr (dr))
(ppi po (dr po ppi))
(ppi eq (ppi))
(ppi pp ,+rcc5-roles+)
(ppi ppi (ppi))))))
(defparameter +rcc8-roles+ '(dc ec po eq tpp tppi ntpp ntppi))
(defparameter +rcc8-rolebox+
(create-rbox 'rcc8-rolebox +rcc8-roles+
:reflexive-roles '(eq)
:inverse-roles '((dc dc) (ec ec) (po po)
(tpp tppi) (ntpp ntppi))
:type 'jepd-rolebox
:axioms
(let ((top +rcc8-roles+)
(dc '(dc))
(ec '(ec))
(po '(po))
(tpp '(tpp))
(ntpp '(ntpp))
(tppi '(tppi))
(ntppi '(ntppi))
(eq '(eq))
(dr '(ec dc))
(pp '(tpp ntpp))
(ppi '(tppi ntppi)))
(mapcar #'swap-first-args
`((dc dc ,top)
(dc ec (,@dr ,@po ,@ppi))
(dc po (,@dr ,@po ,@ppi))
(dc tpp ,dc)
(dc ntpp ,dc)
(dc tppi (,@dr ,@po ,@ppi))
(dc ntppi (,@dr ,@po ,@ppi))
(dc eq ,dc)
(ec dc (,@dr ,@po ,@pp))
(ec ec (,@dr ,@eq ,@po ,@tpp ,@tppi))
(ec po (,@dr ,@po ,@ppi))
(ec tpp ,dr)
(ec ntpp ,dc)
(ec tppi (,@ec ,@po ,@ppi))
(ec ntppi (,@po ,@ppi))
(ec eq ,ec)
(po dc (,@dr ,@po ,@pp))
(po ec (,@dr ,@po ,@pp))
(po po (,@top))
(po tpp (,@dr ,@po ,@pp))
(po ntpp (,@dr ,@po ,@pp))
(po tppi (,@po ,@ppi))
(po ntppi (,@po ,@ppi))
(po eq (,@po))
(tpp dc (,@dr ,@po ,@pp))
(tpp ec (,@ec ,@po ,@pp))
(tpp po (,@po ,@pp))
(tpp tpp ,pp)
(tpp ntpp ,ntpp)
(tpp tppi (,@po ,@eq ,@tpp ,@tppi))
(tpp ntppi (,@po ,@ppi))
(tpp eq (,@tpp))
(ntpp dc (,@dr ,@po ,@pp))
(ntpp ec (,@po ,@pp))
(ntpp po (,@po ,@pp))
(ntpp tpp (,@ntpp))
(ntpp ntpp (,@ntpp))
(ntpp tppi (,@po ,@pp))
(ntpp ntppi (,@po ,@eq ,@pp ,@ppi))
(ntpp eq (,@ntpp))
(tppi dc ,dc)
(tppi ec ,dr)
(tppi po (,@dr ,@po ,@ppi))
(tppi tpp (,@dr ,@eq ,@po ,@tpp ,@tppi))
(tppi ntpp (,@dr ,@po ,@pp))
(tppi tppi ,ppi)
(tppi ntppi ,ntppi)
(tppi eq ,tppi)
(ntppi dc ,dc)
(ntppi ec ,dc)
(ntppi po (,@dr ,@po ,@ppi))
(ntppi tpp (,@dr ,@po ,@ppi))
(ntppi ntpp ,top)
(ntppi tppi ,ntppi)
(ntppi ntppi ,ntppi)
(ntppi eq ,ntppi)
(eq dc ,dc)
(eq ec ,ec)
(eq po ,po)
(eq tpp ,tpp)
(eq ntpp ,ntpp)
(eq tppi ,tppi)
(eq ntppi ,ntppi)
(eq eq ,eq)))))) | 7,410 | Common Lisp | .lisp | 164 | 21.52439 | 87 | 0.297891 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ce21040b185450ad88de8987f35349e2e72b459c9b006fe29812d05dd7ee81fc | 12,504 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.