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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,776 | vector-utilities.lisp | keithj_deoxybyte-utilities/src/vector-utilities.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
(defun vector-positions (elt vector &key (start 0) end (test #'eql))
"Returns a list of indices into VECTOR between START and END where
ELT is present according to TEST (which defaults to EQL)."
(declare (optimize (speed 3) (debug 0)))
(declare (type vector vector)
(type function test))
(let ((end (or end (length vector))))
(declare (type vector-index start end))
(check-arguments (<= 0 start end (length vector)) (start end)
"must satisfy (<= 0 start end ~d)" (length vector))
(loop for i from start below end
when (funcall test elt (aref vector i))
collect i)))
(defun vector-split-indices (elt vector &key (start 0) end (test #'eql))
"Returns two values, a list of start indices and a list of end
indices into VECTOR between START and END such that if used as
start/end arguments to subseq, VECTOR will be split on ELT. ELT is
compared with elements in VECTOR using TEST, which defaults to EQL."
(declare (optimize (speed 3) (safety 0) (debug 0)))
(declare (type vector vector))
(let ((end (or end (length vector))))
(declare (type vector-index start end))
(check-arguments (<= 0 start end (length vector)) (start end)
"must satisfy (<= 0 start end ~d)" (length vector))
(let ((positions (vector-positions elt vector
:start start :end end :test test)))
(if positions
(loop
with starts = ()
with ends = ()
for pos of-type vector-index in positions
and prev = start then (the vector-index (1+ pos))
maximize pos into last-pos
do (progn
(push prev starts)
(push pos ends))
finally (progn
(push (the vector-index (1+ last-pos)) starts)
(push end ends)
(return
(values (nreverse starts) (nreverse ends)))))
nil))))
(defun vector-split (elt vector &key (start 0) end (test #'eql)
remove-empty-subseqs displace-to-vector)
"Returns a list of vectors made by splitting VECTOR at ELT, between
START and END. ELT is compared with elements in VECTOR using TEST,
which defaults to EQL. If REMOVE-EMPTY-SUBSEQS is T, any empty
subsequences will be omitted from the returned list. If
DISPLACE-TO-VECTOR id T, the returned subsequences will be displaced
to the actual subsequences within VECTOR and will therefore share
structure with VECTOR."
(let ((end (or end (length vector)))
(elt-type (array-element-type vector)))
(check-arguments (<= 0 start end (length vector)) (start end)
"must satisfy (<= 0 start end ~d)" (length vector))
(multiple-value-bind (starts ends)
(vector-split-indices elt vector :start start :end end :test test)
(cond ((and starts ends)
(loop
for i in starts
for j in ends
when (not (and remove-empty-subseqs
(= i j)))
collect (if displace-to-vector
(make-array (- j i)
:element-type elt-type
:displaced-to vector
:displaced-index-offset i)
(subseq vector i j))))
(displace-to-vector
(make-array (- end start)
:element-type elt-type
:displaced-to vector
:displaced-index-offset start))
(t
(list (subseq vector start end)))))))
(defun binary-search (vector item &key (test #'<) key
(start 0) (end (length vector)))
"Searches for ITEM in VECTOR by binary search.
Arguments:
- vector (vector): A sorted vector to be searched.
- item (object): The item to be found.
Key:
- test (function): The test used to compare ITEM with VECTOR elements.
- key (function): A key function with which to transform VECTOR elements.
- start (fixnum): The lower bound index of the search in VECTOR.
- end (fixnum): The upper bound index of the search in VECTOR.
Returns:
- An object, or NIL."
(labels ((bin-search (start end)
(when (< start end)
(let ((mid (+ start (floor (- end start) 2))))
(let ((mid-item (if key
(funcall key (aref vector mid))
(aref vector mid))))
(cond ((funcall test item mid-item)
(bin-search start mid))
((funcall test mid-item item)
(bin-search (1+ mid) end))
(t
(aref vector mid))))))))
(bin-search start end)))
| 5,740 | Common Lisp | .lisp | 121 | 36.636364 | 74 | 0.586022 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ff29500a0b35c87c26b2b1f5f034270358b822e8cb0e55682d7c522d6b35d71d | 17,776 | [
-1
] |
17,777 | queue.lisp | keithj_deoxybyte-utilities/src/queue.lisp | ;;;
;;; Copyright (c) 2009-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
(defstruct queue
"A FIFO queue. For consistency, all functions that operate on a
QUEUE carry the QUEUE- prefix, even though this results in tautology
for some functions, such as QUEUE-ENQUEUE/QUEUE-DEQUEUE. This is a
standard way of making a linked-list queue; the QUEUE structure
contains pointers to both the head and tail of a single list."
(head nil :type list)
(tail nil :type list))
(defun queue-enqueue (item queue)
"Inserts ITEM at the end of QUEUE and returns QUEUE."
(let ((new-tail (list item)))
(if (queue-empty-p queue)
(setf (queue-head queue) new-tail
(queue-tail queue) new-tail)
(setf (cdr (queue-tail queue)) new-tail
(queue-tail queue) new-tail)))
queue)
(defun queue-dequeue (queue)
"Removes one item from the front of QUEUE and returns two values.
The first value is the item, or NIL if QUEUE was empty and the second
value is T if an item was dequeued, or NIL otherwise."
(let ((presentp (not (null (queue-head queue))))
(item (pop (queue-head queue))))
(when (null (queue-head queue))
(setf (queue-tail queue) nil))
(values item presentp)))
(defun queue-dequeue-if (test queue &key key)
"Removes items from QUEUE that pass predicate TEST, returning two
values, QUEUE and a list of the deleted items. The KEY keyword
argument is the same as for C:DELETE-IF."
(let ((items (queue-head queue))
(key (cond ((null key)
#'identity)
((functionp key)
key)
(t
(fdefinition key)))))
(loop
for item in items
if (funcall test (funcall key item))
collect item into fail
else
collect item into pass
finally (progn
(setf (queue-head queue) pass
(queue-tail queue) (last pass))
(return (values queue fail))))))
(defun queue-append (queue &rest lists)
"Inserts LISTS of items at the end of QUEUE and returns QUEUE."
(let ((new-tail (apply #'concatenate 'list lists)))
(if (queue-empty-p queue)
(setf (queue-head queue) new-tail
(queue-tail queue) new-tail)
(setf (cdr (queue-tail queue)) new-tail
(queue-tail queue) new-tail)))
queue)
(defun queue-clear (queue)
"Removes all items from queue, returning two values, the queue and a
list of all the items that were in the queue."
(let ((items (queue-head queue)))
(setf (queue-head queue) nil
(queue-tail queue) nil)
(values queue items)))
(defun queue-first (queue)
"Returns the first item in QUEUE, without removing it."
(first (queue-head queue)))
(defun queue-last (queue)
"Returns the last item in QUEUE, without removing it."
(first (queue-tail queue)))
(defun queue-nth (n queue)
"Returns the Nth item in QUEUE."
(nth n (queue-head queue)))
(defun queue-empty-p (queue)
"Returns T if QUEUE is empty, or NIL otherwise."
(null (queue-head queue)))
(defun queue-length (queue)
"Returns the length of QUEUE."
(list-length (queue-head queue)))
(defun queue-position (item queue &key key (test #'eql))
"Returns the zero-based index of ITEM in QUEUE, or NIL if ITEM is
not present. The TEST and KEY keyword arguments are the same as for
CL:POSITION."
(position item (queue-head queue) :key key :test test))
(defun queue-delete (item queue &key key (test #'eql))
"Deletes the first occurrence of ITEM in QUEUE, if present,
returning QUEUE. The TEST and KEY keyword arguments are the same as
for CL:DELETE."
(setf (queue-head queue) (delete item (queue-head queue) :key key :test test)
(queue-tail queue) (last (queue-head queue)))
queue)
| 4,542 | Common Lisp | .lisp | 109 | 36.733945 | 79 | 0.681828 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6a28ce8af5fda9942362f2e34da2dd7aca16276d6b7600836bac162ef5c4afe6 | 17,777 | [
-1
] |
17,778 | numeric-utilities.lisp | keithj_deoxybyte-utilities/src/numeric-utilities.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
(defun iota (count &optional (start 0) (step 1))
"Generates a list of COUNT integers from START (defaults to 0) with
subsequent integers STEP (defaults to 1) greater than the last, or
less, if a negative STEP is given."
(cond ((zerop step)
(loop repeat count
collect start))
((minusp step)
(loop repeat count
for i downfrom start by (abs step)
collect i))
(t
(loop repeat count
for i upfrom start by step
collect i))))
(defun number-generator (&optional (start 0) (step 1))
"Creates a closure of zero arity that returns an integer from START
with subsequent integers incrementing by STEP greater than the last,
or less, is a negative step is given.
Optional:
- start (integer): the start value, defaults to 0.
- step (integer): the step size, defaults to 1.
Returns:
- A closure of zero arity."
(let ((current start))
(defgenerator
(more t)
(next (prog1
current
(incf current step)))
(current current))))
(defmacro with-numeric-selector ((name num-bins &key (start 0)
(end (+ start num-bins))
(out-of-bounds :error))
&body body)
"Defines a local function NAME that accepts a single fixnum
argument and returns an integer between 0 and NUM-BINS, indicating in
which of NUM-BINS sequential, equal-sized bins that value belongs.
Arguments:
- name (symbol): the local function name.
- num-bins (integer): the number of bins into which values are to be
assigned.
Key:
- start (number): the lower bound of the range of values to be binned,
defaults to 0.
- end (number): the upper bound of the range of values to be binned.
- oob-error (boolean): if T the function will throw an
INVALID-ARGUMENT-ERROR when passed values less than START or greater
than END, otherwise the function will return NIL."
(with-gensyms (bin-size lower-bound upper-bound)
`(let ((,lower-bound ,start)
(,upper-bound (1- ,end))
(,bin-size (/ (- ,end ,start) ,num-bins)))
(declare (type fixnum ,bin-size ,lower-bound ,upper-bound))
(flet ((,name (value)
(declare (type fixnum value))
(if (<= ,lower-bound value ,upper-bound)
(floor (- value ,lower-bound) ,bin-size)
,(ecase out-of-bounds
(:include `(if (< value ,lower-bound)
0
,upper-bound))
(:ignore nil)
(:error
`(error 'invalid-argument-error
:parameters 'value
:arguments value
:format-control "expected a value in the range ~a"
:format-arguments (list ,lower-bound
(1- (+ ,lower-bound ,end)))))))))
,@body))))
(defmacro define-categorical-binner (value &rest categories)
"Creates a closure that accepts a single fixnum argument. The argument
value is assigned to the appropriate bin and that bin's total is
incremented. The closure returns two values, the bins as an array of
fixnums and the total number of times values did not fall into any
category. Note that the return values are cumulative across calls
because the counters are closed over.
Arguments:
- value (symbol): a symbol to which values are bound on the subsequent
category forms.
Rest:
- categories (forms): test forms, one for each bin, that evaluate to a
generalized boolean. These forms are evaulated in the order given in
to assign values to bins.
For example, counting numbers into four bins of odd/positive,
odd/negative, even/positive and even/negative.
;;; (define-categorical-binner x
;;; (and (oddp x) (plusp x))
;;; (and (oddp x) (minusp x))
;;; (and (evenp x) (plusp x))
;;; (and (evenp x) (minusp x)))
Returns:
- A closure accepting a numeric value."
(let ((num-categories (length categories)))
`(progn
(let ((bins (make-array ,num-categories :element-type 'fixnum
:initial-element 0))
(outside 0))
(lambda (,value)
(cond ,@(loop
for category in categories
for i = 0 then (1+ i)
collect `(,category
(incf (aref bins ,i))))
(t
(incf outside)))
(values bins outside))))))
(defun quotedp (form)
"Returns T if FORM is quoted."
(and (listp form)
(eql 'quote (car form))))
| 5,552 | Common Lisp | .lisp | 131 | 34.129771 | 80 | 0.619744 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5d0f3a53d63d5f9e94526b20888bdc4da6383eb39a7093e2c1d854e775a6990e | 17,778 | [
-1
] |
17,779 | ccl.lisp | keithj_deoxybyte-utilities/src/ccl.lisp | ;;;
;;; Copyright (c) 2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
;;; clos-utilities
;;; Introspection utility functions
(defun has-superclass-p (class superclass)
"Returns T if CLASS has SUPERCLASS, or NIL otherwise."
(member superclass (ccl:compute-class-precedence-list class)))
(defun direct-superclasses (class)
"Returns a list of the direct superclasses of CLASS."
(ccl:class-direct-superclasses class))
(defun direct-subclasses (class)
"Returns a list of the direct subclasses of CLASS."
(ccl:class-direct-subclasses class))
(defun all-superclasses (class &optional
(ceiling (find-class 'standard-object)))
"Returns a list of all superclasses of CLASS, up to, but not
including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(set-difference (ccl:class-precedence-list class)
(ccl:class-precedence-list ceiling)))
(defun all-specialized-methods (class &optional
(ceiling (find-class 'standard-object)))
"Returns a list of all methods specialized on CLASS, up to, but not
including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(apply #'append (mapcar #'ccl:specializer-direct-methods
(all-superclasses class ceiling))))
(defun all-specialized-generic-functions (class &optional
(ceiling (find-class
'standard-object)))
"Returns a list of all generic functions specialized on CLASS, up to,
but not including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(mapcar #'ccl:method-generic-function
(all-specialized-methods class ceiling)))
(defun all-slots (class)
"Returns a sorted list of all slots of CLASS."
(flet ((slot-def-name (slot-def)
(ccl:slot-definition-name slot-def)))
(stable-sort (mapcar #'slot-def-name (all-slot-definitions class))
#'string< :key #'symbol-name)))
(defun slot-documentation (slot class)
"Returns the documentation string for SLOT of CLASS."
(check-arguments (and slot class) (slot class)
"neither slot nor class may be NIL")
(flet ((slot-def-name (slot-def)
(ccl:slot-definition-name slot-def)))
(documentation (find slot (all-slot-definitions class)
:key #'slot-def-name) t)))
(defun all-slot-definitions (class)
"Returns a list of all slot definitions of CLASS."
(unless (ccl:class-finalized-p class)
(ccl:finalize-inheritance class))
(ccl:compute-slots class))
| 3,355 | Common Lisp | .lisp | 71 | 41.267606 | 73 | 0.692942 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 8f9e8ba637da2beacd6c76fbed59d88096aa23b1c79b594420737d22bbf7e975 | 17,779 | [
-1
] |
17,780 | set-utilities.lisp | keithj_deoxybyte-utilities/src/set-utilities.lisp | ;;;
;;; Copyright (c) 2010-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
;;; TODO - maybe implement these functions with bit-vectors for some
;;; cases
(defun linear-union (list1 list2 &key key test)
"Returns a list that is the union of LIST1 and LIST2, in linear
time. See CL:UNION for the meaning of KEY and TEST."
(let ((hash (make-hash-table :size (+ (length list1) (length list2))
:test (or test #'eql))))
(dolist (elt1 list1)
(setf (gethash (funcall-if-fn key elt1) hash) t))
(dolist (elt2 list2)
(let ((elt (funcall-if-fn key elt2)))
(unless (gethash elt hash)
(setf (gethash elt hash) t))))
(loop
for elt being the hash-keys of hash
collect elt)))
(defun linear-intersection (list1 list2 &key key test)
"Returns a list that is the intersection of LIST1 and LIST2, in
linear time. See CL:INTERSECTION for the meaning of KEY and TEST."
(cond ((null list1)
nil)
((null list2)
nil)
(t
(let* ((len1 (length list1))
(len2 (length list2))
(hash (make-hash-table :size (min len1 len2)
:test (or test #'eql))))
(multiple-value-bind (smaller larger)
(if (< len1 len2)
(values list1 list2)
(values list2 list1))
(dolist (elt smaller)
(setf (gethash (funcall-if-fn key elt) hash) t))
(loop
for elt in larger
when (gethash (funcall-if-fn key elt) hash)
collect elt))))))
(defun linear-set-difference (list1 list2 &key key test)
"Returns a list that is the set difference of LIST1 and LIST2, in
linear time. See CL:SET-DIFFERENCE for the meaning of KEY and TEST."
(cond ((null list2)
list1)
(t
(let ((hash (make-hash-table :size (length list1)
:test (or test #'eql))))
(dolist (elt1 list1)
(setf (gethash (funcall-if-fn key elt1) hash) t))
(dolist (elt2 list2)
(remhash (funcall-if-fn key elt2) hash))
(loop
for elt being the hash-keys of hash
collect elt)))))
(defun linear-set-exclusive-or (list1 list2 &key key test)
"Returns a list that is the set exclusive-or of LIST1 and LIST2, in
linear time. See CL:SET-EXCLUSIVE-OR for the meaning of KEY and TEST."
(cond ((and (null list1) (null list2))
nil)
((null list1)
list2)
((null list2)
list1)
(t
(linear-set-difference
(linear-union list1 list2 :key key :test test)
(linear-intersection list1 list2 :key key :test test)))))
(defun linear-subsetp (list1 list2 &key key test)
"Returns T if LIST1 is a subset of LIST2, in linear time. See
CL:SUBSETP for the meaning of KEY and TEST."
(cond ((null list1)
t)
(t
(let* ((len1 (length list1))
(len2 (length list2))
(hash (make-hash-table :size (max len1 len2)
:test (or test #'eql))))
(multiple-value-bind (smaller larger)
(if (< len1 len2)
(values list1 list2)
(values list2 list1))
(dolist (elt larger)
(setf (gethash (funcall-if-fn key elt) hash) t))
(loop
for elt in smaller
always (gethash (funcall-if-fn key elt) hash)))))))
(defun linear-set-equal (list1 list2 &key key test)
(and (not (linear-set-difference list1 list2 :key key :test test))
(not (linear-set-difference list2 list1 :key key :test test))))
| 4,505 | Common Lisp | .lisp | 107 | 33.140187 | 73 | 0.594761 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9cb7b92e1db2f66aa874f7d570e6d879d551b184b95bb751b99db6a2e5d6c035 | 17,780 | [
-1
] |
17,781 | octet-vector-utilities.lisp | keithj_deoxybyte-utilities/src/octet-vector-utilities.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
(defun octets-to-string (octets &optional (start 0) (end nil end-supplied-p))
"Returns a new simple-base-string created from the values in
OCTET-VECTOR, a simple-array of (unsigned-byte 8), between indices
START and END. The elements of the returned string are the result of
calling code-char on the respective elements of OCTET-VECTOR."
(declare (optimize (speed 3)))
(declare (type simple-octet-vector octets))
(declare (type vector-index start))
(cond ((and (zerop start) (not end-supplied-p))
(map-into (make-array (length octets) :element-type 'base-char)
#'code-char octets))
(t
(let ((end (or end (length octets))))
(declare (type vector-index end))
(check-arguments (<= 0 start end) (start end)
"must satisfy (<= 0 start end)")
(let ((len (- end start)))
(map-into (make-string len :element-type 'base-char) #'code-char
(replace (make-array len :element-type 'octet) octets
:start2 start :end2 end)))))))
(defun string-to-octets (str &optional (start 0) (end nil end-supplied-p))
"Returns a new vector of octets created from the simple-string
STR, between indices START and END. The elements of the returned
vector are the result of calling char-code on the respective
characters of STR."
(declare (optimize (speed 3)))
(declare (type vector-index start))
;; This is here because we can get a significant speed boost for the
;; cases where we can determine that a string is a simple-base-string
(macrolet
((map-string (type s)
`(locally (declare (type ,type ,s))
(cond ((and (zerop start) (not end-supplied-p))
(map-into (make-array (length ,s) :element-type 'octet)
#'char-code ,s))
(t
(let ((end (or end (length ,s))))
(declare (type vector-index end))
(check-arguments (<= 0 start end) (start end)
"must satisfy (<= 0 start end)")
(let* ((len (- end start))
(tmp (make-string len :element-type 'base-char)))
(map-into
(make-array len :element-type 'octet)
#'char-code
(replace tmp ,s :start2 start :end2 end)))))))))
(etypecase str
(simple-base-string (map-string simple-base-string str))
(simple-string (map-string (simple-array character (*)) str)))))
| 3,438 | Common Lisp | .lisp | 68 | 41.455882 | 77 | 0.615682 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 21108ee7cb9fa46099fbe4f350dd23a3977d40808016f84edb45907d7d58d281 | 17,781 | [
-1
] |
17,782 | cons-utilities.lisp | keithj_deoxybyte-utilities/src/cons-utilities.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
(defmacro assocdr (key alist &rest args)
"Returns the cdr of the cons cell returned by calling (assoc KEY
ALIST ARGS)."
`(cdr (assoc ,key ,alist ,@args)))
(defmacro rassocar (val alist &rest args)
"Returns the car of the cons cell returned by calling (rassoc KEY
ALIST ARGS)."
`(car (rassoc ,val ,alist ,@args)))
(defmacro rplassoc (key alist val &rest args)
"Performs destructive replacement with VAL (using RPLACD) of the cdr
of the cons returned when calling assoc on ALIST with KEY and ARGS."
`(rplacd (assoc ,key ,alist ,@args) ,val))
(defmacro assocpush (key alist val &rest args)
"Pushes VAL onto the cdr of the cons returned from ALIST by calling
assoc with KEY and ARGS."
`(push ,val (assocdr ,key ,alist ,@args)))
(defmacro assocpop (key alist &rest args)
"Pops a value from the cdr of the cons returned from ALIST by
calling assoc with KEY and ARGS."
`(pop (assocdr ,key ,alist ,@args)))
(defun dotted-pair-p (list)
"Returns T if LIST is a dotted pair, or NIL otherwise."
(and (consp list)
(cdr list)
(not (consp (cdr list)))))
(defun proper-list-p (list)
"Returns T if LIST is a proper list, or NIL otherwise. A proper list
is defined as a list whose terminal cdr is NIL. This function does not
test the list for circularity."
(or (null list)
(and (consp list)
(proper-list-p (rest list)))))
(defun splice (list obj n)
"Splices atom or (a copy of) list OBJ into a copy of LIST at
position N."
(if (atom obj)
(nsplice (copy-list list) obj n)
(nsplice (copy-list list) (copy-list obj) n)))
(defun nsplice (list obj n)
"Destructively splices atom or list OBJ into LIST at position N."
(cond ((and (zerop n) (atom obj))
(cons obj list))
((and (zerop n) (listp obj))
(nconc obj list))
(t
(let ((join (nthcdr (1- n) list)))
(if (atom obj)
(setf (cdr join)
(cons obj (cdr join)))
(setf (cdr join)
(nconc obj (cdr join)))))
list)))
(defun intersperse (list obj)
"Returns a list containing the members of LIST interspersed with
OBJ."
(if (endp (rest list))
list
(append (list (car list) obj)
(intersperse (rest list) obj))))
(defun flatten (tree)
"Returns a new list containing the members of TREE."
(cond ((null tree)
nil)
((atom tree)
(list tree))
(t
(append (flatten (first tree))
(flatten (rest tree))))))
(defun exactly-n (predicate n first-seq &rest more-seqs)
"Analagous to the ANSI standard functions EVERY and SOME, except
that this function returns T if exactly N tests of PREDICATE are true,
or NIL otherwise."
(loop
for i from 0 below (apply #'min (length first-seq)
(mapcar #'length more-seqs))
count (apply predicate (elt first-seq i) (loop
for seq in more-seqs
collect (elt seq i)))
into total
finally (return (= n total))))
(defun exactly-one (predicate first-seq &rest more-seqs)
"Analagous to the ANSI standard functions EVERY and SOME, except
that this function returns T if exactly one test of PREDICATE is true,
or NIL otherwise."
(apply #'exactly-n predicate 1 first-seq more-seqs))
(defun collect-key-values (keywords arg-list)
"For all keywords in list KEYWORDS, finds the keyword and its value
in ARG-LIST, a list containing only keyword and value pairs. Returns
two values, a list of matched keywords and a list of their
corresponding values."
(loop
for keyword in arg-list by #'cddr
for value in (rest arg-list) by #'cddr
when (member keyword keywords)
collect keyword into matched-keywords
and collect value into values
finally (return (values matched-keywords values))))
(defun key-value (keyword arg-list)
"Returns the current value of KEYWORD in list ARG-LIST, a list
containing only keyword and value pairs."
(second (member keyword arg-list)))
(defun remove-key-values (keywords arg-list)
"Returns two values, a copy of ARG-LIST, a list containing only
keyword and value pairs, with KEYWORDS and their values removed and an
alist containing KEYWORDS and their corresponding values."
(loop
for keyword in arg-list by #'cddr
for value in (rest arg-list) by #'cddr
if (not (member keyword keywords))
nconc (list keyword value) into new-arg-list
else
collect keyword into removed-keywords
and collect value into removed-values
finally (return (values new-arg-list
(pairlis removed-keywords
removed-values)))))
(defun modify-key-value (keyword arg-list mod-fn &rest fn-args)
"Returns a copy of ARG-LIST where the value corresponding to KEYWORD
has been replaced by the result of applying MOD-FN to that
value. MOD-FN must be a function that accepts KEYWORDS's value and may
accept additional arguments supplied in FN-ARGS."
(loop
for keyword-n in arg-list by #'cddr
for value in (rest arg-list) by #'cddr
if (eql keyword keyword-n)
nconc (list keyword-n (apply mod-fn value fn-args))
else
nconc (list keyword-n value)))
(defun canonical-fn-args (lambda-list fn-args)
"Returns a canonical version of FN-ARGS corresponding to LAMBDA-LIST."
(let* ((key-pos (position '&key lambda-list))
(fixed-args (subseq fn-args 0 key-pos))
(keyword-args (subseq fn-args key-pos)))
(loop
for key in keyword-args by #'cddr
for val in (rest keyword-args) by #'cddr
collect key into keys
collect (list key val) into key-vals
finally (return
(append fixed-args
(mapcan (lambda (key)
(assoc key key-vals))
(sort keys #'string< :key #'symbol-name)))))))
| 6,811 | Common Lisp | .lisp | 162 | 35.938272 | 79 | 0.665611 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2263658f9bf4d598821817a645e8ae96c6dde88216c1bcf66c4feeb2d7863944 | 17,782 | [
-1
] |
17,783 | conditions.lisp | keithj_deoxybyte-utilities/src/conditions.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
;; CL's simple-condition and simple-error give some basic error
;; message formatting and I was tempted to use one of them as a
;; superclass. However, in view of this comment from Kent Pitman on
;; comp.lang.lisp (16 Apr 1999), it seems that this is not their
;; intended use:
;;
;; "There was never an intent that simple-condition could be or should be
;; extended. They were intended for use with people too lazy to make
;; type-specific errors, but it was assumed that the people who did make
;; something easier to use would do so in a better way."
(define-condition formatted-condition (condition)
((format-control :initform nil
:initarg :format-control
:reader format-control-of
:documentation "The format control used to create
the condition message.")
(format-arguments :initform nil
:initarg :format-arguments
:reader format-arguments-of
:documentation "The list of format arguments used
to create the condition message.")))
(define-condition simple-text-condition (condition)
((text :initform nil
:initarg :text
:reader text-of)))
(define-condition invalid-argument-error (error formatted-condition)
((parameters :initform "<not supplied>"
:initarg :parameters
:reader parameters-of
:documentation "The invalid parameters.")
(arguments :initform "<not supplied>"
:initarg :arguments
:reader arguments-of
:documentation "The invalid arguments."))
(:report (lambda (condition stream)
(format stream
"invalid ~a argument~:[s~;~] ~@[~a~]~@[: ~a~]"
(parameters-of condition)
(or (atom (parameters-of condition))
(endp (rest (parameters-of condition))))
(arguments-of condition)
(message-of condition))))
(:documentation "An error that is raised when an invalid argument is
passed to a function."))
(define-condition missing-argument-error (error formatted-condition)
((parameters :initform "<not supplied>"
:initarg :parameters
:reader parameters-of
:documentation "The invalid parameters."))
(:report (lambda (condition stream)
(format stream
"missing ~a argument~:[s~;~]~@[: ~a~]"
(parameters-of condition)
(atom (parameters-of condition))
(message-of condition))))
(:documentation "An error that is raised when a required argument is
not passed to a function."))
(define-condition invalid-operation-error (error formatted-condition)
()
(:report (lambda (condition stream)
(format stream "invalid operation~@[: ~a~]"
(message-of condition))))
(:documentation "An error that is raised when an invalid operation
is attempted."))
(define-condition deprecation-warning (style-warning)
((feature :initform nil
:initarg :feature
:reader feature-of)
(in-favour :initform nil
:initarg :in-favour
:reader in-favour-of))
(:report (lambda (condition stream)
(format stream "~a is deprecated~@[ in favour of ~a~]"
(feature-of condition) (in-favour-of condition))))
(:documentation "A warning that is raised when a deprecated feature
is used."))
(defgeneric message-of (condition)
(:documentation "Returns the condition message string."))
(defmethod message-of ((condition formatted-condition))
(with-accessors ((str format-control-of) (args format-arguments-of))
condition
(cond ((and str args)
(apply #'format nil str args))
(str
str)
(t
nil))))
(defmethod message-of ((condition simple-text-condition))
(text-of condition))
| 4,830 | Common Lisp | .lisp | 108 | 36.453704 | 73 | 0.642539 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 89d8aa64c38fbfb0b2aaae0181894a4ea1a58dc5b8750bce6e09f6af44a27221 | 17,783 | [
-1
] |
17,784 | default.lisp | keithj_deoxybyte-utilities/src/default.lisp | ;;;
;;; Copyright (c) 2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
;;; clos-utilities
;;; Introspection utility functions
(defun has-superclass-p (class superclass)
"Returns T if CLASS has SUPERCLASS, or NIL otherwise."
(error "IS-SUPERCLASS-P not supported on this Lisp implementation."))
(defun direct-superclasses (class)
"Returns a list of the direct superclasses of CLASS."
(error "DIRECT-SUPERCLASSES not supported on this Lisp implementation."))
(defun direct-subclasses (class)
"Returns a list of the direct subclasses of CLASS."
(error "DIRECT-SUBCLASSES not supported on this Lisp implementation."))
(defun all-superclasses (class &optional
(ceiling (find-class 'standard-object)))
"Returns a list of all superclasses of CLASS, up to, but not
including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(error "ALL-SUPERCLASSES not supported on this Lisp implementation."))
(defun all-specialized-methods (class &optional
(ceiling (find-class 'standard-object)))
"Returns a list of all methods specialized on CLASS, up to, but not
including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(error (msg "ALL-SPECIALIZED-METHODS not supported"
"on this Lisp implementation.")))
(defun all-specialized-generic-functions (class &optional
(ceiling (find-class
'standard-object)))
"Returns a list of all generic functions specialized on CLASS, up to,
but not including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(error (msg "ALL-SPECIALIZED-GENERIC-FUNCTIONS not supported"
"on this Lisp implementation.")))
(defun all-slots (class)
"Returns a sorted list of all slots of CLASS."
(error "ALL-SLOTS not supported on this Lisp implementation."))
(defun slot-documentation (slot class)
"Returns the documentation string for SLOT of CLASS."
(error "SLOT-DOCUMENTATION not supported on this Lisp implementation."))
(defun all-slot-definitions (class)
"Returns a list of all slot definitions of CLASS."
(error "ALL-SLOT-DEFINITIONS not supported on this Lisp implementation."))
| 3,005 | Common Lisp | .lisp | 60 | 45.266667 | 76 | 0.722563 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 1eb7d32d63b4a67ff0412c58004d4efcaf4d9693b0819efd1035b1652446fc7e | 17,784 | [
-1
] |
17,785 | type-utilities.lisp | keithj_deoxybyte-utilities/src/type-utilities.lisp | ;;;
;;; Copyright (c) 2009-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
(deftype octet ()
"Alias for unsigned-byte 8."
'(unsigned-byte 8))
(deftype nibble ()
"Alias for unsigned-byte 4"
'(unsigned-byte 4))
(deftype uint8 ()
"Alias for unsigned-byte 8."
'(unsigned-byte 8))
(deftype int8 ()
"Alias for signed-byte 8."
'(signed-byte 8))
(deftype uint16 ()
"Alias for unsigned-byte 16."
'(unsigned-byte 16))
(deftype int16 ()
"Alias for signed-byte 16."
'(signed-byte 16))
(deftype uint32 ()
"Alias for unsigned-byte 32."
'(unsigned-byte 32))
(deftype int32 ()
"Alias for signed-byte 32."
'(signed-byte 32))
;; array-index is deprecated in favour of vector-index
(deftype array-index ()
"Array index type."
'(and fixnum (integer 0 *)))
(deftype vector-index ()
"Vector index type."
'(and fixnum (integer 0 *)))
(deftype simple-octet-vector ()
"Alias for (simple-array (unsigned-byte 8) (*)), using a naming
convention analagous to simple-base-string."
'(simple-array (unsigned-byte 8) (*)))
| 1,796 | Common Lisp | .lisp | 54 | 31.185185 | 73 | 0.712139 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9d3aa2f0be048a7246f206782dce5004ad1a1a7b3494d1107c57536d1211aa8b | 17,785 | [
-1
] |
17,786 | deoxybyte-utilities.lisp | keithj_deoxybyte-utilities/src/deoxybyte-utilities.lisp | ;;;
;;; Copyright (c) 2007-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
;;; Core macros
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro with-gensyms ((&rest names) &body body)
`(let ,(loop for n in names
collect `(,n (gensym)))
,@body)))
(defmacro funcall-if-fn (function arg)
"If FUNCTION is not null, funcalls FUNCTION on ARG, otherwise
returns ARG."
`(if ,function
(funcall ,function ,arg)
,arg))
;;; Vector copying macro
(defmacro copy-vector (source source-start source-end
dest dest-start &optional key)
"Copies elements SOURCE indices SOURCE-START and SOURCE-END to DEST,
inserting them into DEST at DEST-START onwards. If the function KEY is
supplied, it is applied to each element of SOURCE prior to its
insertion into DEST."
`(loop
for si of-type vector-index from ,source-start below ,source-end
for di of-type vector-index = ,dest-start
then (the vector-index (1+ di))
do (setf (aref ,dest di) ,(if key
`(funcall ,key (aref ,source si))
`(aref ,source si)))
finally (return ,dest)))
(defmacro check-arguments (test-form arguments &optional error-message
&rest message-arguments)
"Checks the validity of ARGUMENTS. If TEST-FORM returns false an
{define-condition invalid-argument-error} is raised. The default error
message may be refined with an additional ERROR-MESSAGE.
Arguments:
- test-form (form): A form to be evaluated. If the form returns NIL,
an error is raised.
- arguments (list symbols): A list of symbols to which argument values
are bound.
Optional:
- error-message (string): An error message string.
Rest:
- message-arguments (forms): Forms that evaluate to arguments for the
error message."
`(progn
(unless ,test-form
(error 'invalid-argument-error
:parameters ',arguments
:arguments (list ,@arguments)
:format-control ,error-message
:format-arguments (list ,@message-arguments)))
t))
(defmacro defgenerator (more-form next-form &optional current-form)
"Returns a generator function that may be passed to any of the
generator utility functions {defun has-more-p} , {defun next}
and {defun current} .
Arguments:
- more-form (form): A form that returns T if the generator can supply
more values, or NIL otherwise. Used by {defun has-more-p } .
- next-form (form): A form that returns the next value of the
generator. Used by {defun next} .
Optional:
- current-form (form): A form that returns the current value of the
generator. Used by {defun current} .
Returns:
- A form that evaluates to an anonymous function."
(destructuring-bind ((more more-body) (next next-body))
(list more-form next-form)
(assert (equal "MORE" (symbol-name more)) ()
"Expected a MORE form, but found ~a" more-form)
(assert (equal "NEXT" (symbol-name next)) ()
"Expected a NEXT form, but found ~a" next-form)
`(lambda (op)
(ecase op
,@(when current-form
(destructuring-bind (current current-body)
current-form
(assert (equal "CURRENT" (symbol-name current)) ()
"Expected a CURRENT form, but found ~a"
current-form)
`((:current ,current-body))))
(:more ,more-body)
(:next ,next-body)))))
;;; Generator utility functions
(defun current (gen)
"Returns the current value of generator function GEN."
(declare (optimize (speed 3)))
(declare (type function gen))
(funcall gen :current))
(defun next (gen)
"Returns the next available value from generator function GEN."
(declare (optimize (speed 3)))
(declare (type function gen))
(funcall gen :next))
(defun has-more-p (gen)
"Returns T if generator function GEN has more available values, or
NIL otherwise."
(declare (optimize (speed 3)))
(declare (type function gen))
(funcall gen :more))
;;; Consumer utility functions
(defun consume (con &rest args)
"Applies consumer function CON with arguments ARGS."
(declare (optimize (speed 3)))
(declare (type function con))
(apply con args))
(defun collect (gen &optional (n 1))
"Returns a list of up to N values collected from generator function
GEN. Uses {defun has-more-p} to test the generator and may return an
empty list if no items are available."
(loop
repeat n
while (has-more-p gen)
collect (next gen)))
(defun discard (gen &optional (n 1))
"Discards up to N values collected from generator function GEN. Uses
{defun has-more-p} to test the generator and finally returns the
number of values actually discarded."
(loop
repeat n
while (has-more-p gen)
count (next gen)))
(defun discarding-if (test gen)
"Returns a new generator function that discards values from
generator function GEN while they satisfy TEST."
(declare (optimize (speed 3)))
(declare (type function test))
(flet ((skip-to-next ()
(multiple-value-bind (elt found)
(loop
while (has-more-p gen)
do (let ((elt (next gen)))
(unless (funcall test elt)
(return (values elt t)))))
(values elt found))))
(multiple-value-bind (elt more)
(skip-to-next)
(defgenerator
(more more)
(next (prog1
elt
(multiple-value-setq (elt more)
(skip-to-next))))))))
| 6,388 | Common Lisp | .lisp | 160 | 33.8125 | 73 | 0.66226 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 4b5bcad761e9057b214512891f3b8318245066cf3bdd6df8f3f19b20aa2b2bca | 17,786 | [
-1
] |
17,787 | sbcl.lisp | keithj_deoxybyte-utilities/src/sbcl.lisp | ;;;
;;; Copyright (c) 2008-2011 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
;;; clos-utilities
;;; Introspection utility functions
(defun has-superclass-p (class superclass)
"Returns T if CLASS has SUPERCLASS, or NIL otherwise."
(member superclass (sb-mop:compute-class-precedence-list class)))
(defun direct-superclasses (class)
"Returns a list of the direct superclasses of CLASS."
(sb-mop:class-direct-superclasses class))
(defun direct-subclasses (class)
"Returns a list of the direct subclasses of CLASS."
(sb-mop:class-direct-subclasses class))
(defun all-superclasses (class &optional
(ceiling (find-class 'standard-object)))
"Returns a list of all superclasses of CLASS, up to, but not
including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(set-difference (sb-mop:compute-class-precedence-list class)
(sb-mop:compute-class-precedence-list ceiling)))
(defun all-specialized-methods (class &optional
(ceiling (find-class 'standard-object)))
"Returns a list of all methods specialized on CLASS, up to, but not
including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(apply #'append (mapcar #'sb-mop:specializer-direct-methods
(all-superclasses class ceiling))))
(defun all-specialized-generic-functions (class &optional
(ceiling (find-class
'standard-object)))
"Returns a list of all generic functions specialized on CLASS, up to,
but not including, class CEILING. The class CEILING defaults to
STANDARD-OBJECT."
(mapcar #'sb-mop:method-generic-function
(all-specialized-methods class ceiling)))
(defun all-slots (class)
"Returns a sorted list of all slots of CLASS."
(flet ((slot-def-name (slot-def)
(sb-mop:slot-definition-name slot-def)))
(stable-sort (mapcar #'slot-def-name (all-slot-definitions class))
#'string< :key #'symbol-name)))
(defun slot-documentation (slot class)
"Returns the documentation string for SLOT of CLASS."
(check-arguments (and slot class) (slot class)
"neither slot nor class may be NIL")
(flet ((slot-def-name (slot-def)
(sb-mop:slot-definition-name slot-def)))
(documentation (find slot (all-slot-definitions class)
:key #'slot-def-name) t)))
(defun all-slot-definitions (class)
"Returns a list of all slot definitions of CLASS."
(unless (sb-mop:class-finalized-p class)
(sb-mop:finalize-inheritance class))
(sb-mop:compute-slots class))
| 3,413 | Common Lisp | .lisp | 71 | 42.084507 | 73 | 0.693485 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2a054bf81a4a530b998647fa6fec91f4405b45ab66ab5ee97b593aa559909d2e | 17,787 | [
-1
] |
17,788 | string-utilities.lisp | keithj_deoxybyte-utilities/src/string-utilities.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
(defvar *whitespace-chars*
(make-array 5 :element-type 'base-char
:initial-contents '(#\Space #\Tab #\Return #\Linefeed #\Page))
"Whitespace characters.")
(defun control-char-p (char)
"Returns T if CHAR is an ASCII control character (all characters
with codes 0-31, inclusive, and the character with code 127), or NIL
otherwise."
(or (<= (char-code char) 31)
(= 127 (char-code char))))
(defun whitespace-char-p (char)
"Returns T if CHAR is one of the currently bound set of whitespace
characters (defaults to #\Space #\Tab #\Return #\Linefeed and
#\FormFeed), or NIL otherwise."
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-base-string *whitespace-chars*)
(type character char))
(find char *whitespace-chars*))
(defun whitespace-string-p (str)
"Returns T if all the characters in STR are whitespace as defined by
WHITESPACE-CHAR-P, or NIL otherwise."
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-string str))
(loop
for c across str
always (whitespace-char-p c)))
(defun content-string-p (str)
"Returns T if any of the characters in STR are not whitespace as
defined by WHITESPACE-CHAR-P, or NIL otherwise."
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-string str))
(flet ((fn (c)
(not (whitespace-char-p c))))
(find-if #'fn str)))
(defun empty-string-p (str)
"Returns T if STR is a zero-length string or contains only
whitespace as defined by WHITESPACE-CHAR-P, or NIL otherwise."
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-string str))
(or (zerop (length str))
(whitespace-string-p str)))
(defun contains-char-p (str char &key (test #'char=))
"Returns T if STR contains CHAR, determined by TEST (defaults to
CHAR=) or NIL otherwise."
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-string str)
(type character char)
(type function test))
(find char str :test test))
(defun has-char-at-p (str char index &key (test #'char=))
"Returns T if STR has CHAR at INDEX, determined by TEST (defaults to
CHAR=), or NIL otherwise."
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-string str)
(type function test))
(and (not (zerop (length str)))
(funcall test char (char str index))))
(defun starts-with-char-p (str char &key (test #'char=))
"Returns T if STR has CHAR at index 0, determined by TEST (defaults
to CHAR=), or NIL otherwise."
(has-char-at-p str char 0 :test test))
(defun ends-with-char-p (str char &key (test #'char=))
"Returns T if STR has CHAR at its last index, determined by
TEST (defaults to CHAR=), or NIL otherwise."
(has-char-at-p str char (1- (length str)) :test test))
(defun every-char-p (str test &rest indices)
"Applies predicate TEST to characters of string STR indicated by
INDICES and returns T if all those characters match TEST."
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-string str)
(type function test))
(loop
for i in indices
always (funcall test (char str i))))
(defun starts-with-string-p (str1 str2 &key (test #'string=))
"Returns T if STR1 starts with STR2, determined by TEST (defaults to
STRING=), or NIL otherwise."
(declare (optimize (speed 3)))
(declare (type simple-string str1 str2)
(type function test))
(let ((len2 (length str2)))
(and (>= (length str1) len2)
(funcall test str1 str2 :end1 len2))))
(defun ends-with-string-p (str1 str2 &key (test #'string=))
"Returns T if STR1 ends with STR2, determined by TEST (defaults to
STRING=), or NIL otherwise."
(declare (optimize (speed 3)))
(declare (type simple-string str1 str2)
(type function test))
(let ((len1 (length str1))
(len2 (length str2)))
(and (>= len1 len2)
(funcall test str1 str2 :start1 (- len1 len2)))))
(defun concat-strings (strs)
"Returns a new simple-string created by concatenating, in the order
supplied, the simple-strings contained in the vector STRS."
(declare (optimize (speed 3) (safety 0)))
(declare (type (vector simple-string) strs))
(if (= 1 (length strs))
(aref strs 0)
(let ((new-str (make-string (reduce #'+ strs :key #'length)
:element-type 'character))
(num-strs (length strs)))
(do ((i 0 (1+ i))
(offset 0))
((= i num-strs) new-str)
(let ((str (aref strs i)))
(declare (type simple-string str)
(type vector-index offset))
(unless (zerop (length str))
(copy-vector str 0 (length str)
new-str offset)
(incf offset (length str))))))))
(defun txt (&rest strings)
"Returns the result of concatenating STRINGS, separated by spaces."
(apply #'concatenate 'string
(intersperse strings (make-string 1 :initial-element #\Space))))
(defun str (&rest strings)
"Returns the result of concatenating strings STRINGS."
(apply #'concatenate 'string strings))
(defun string-positions (str char &key (start 0) end)
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-string str))
(let ((end (or end (length str))))
(declare (type vector-index start end))
(check-arguments (<= 0 start end (length str)) (start end)
"start must be >= 0 and be <= end")
(loop
for i from start below end
when (char= char (char str i))
collect i)))
(defun string-split-indices (str char &key (start 0) end)
"Returns two values, a list of start indices and a list of end
indices into STR between START and END such that if used as start/end
arguments to subseq, STR will be split on CHAR. CHAR is compared with
elements in STR using TEST, which defaults to EQL."
(declare (optimize (speed 3) (safety 0)))
(declare (type simple-string str))
(let ((end (or end (length str))))
(declare (type vector-index start end))
(check-arguments (<= 0 start end (length str)) (start end)
"start must be >= 0 and be <= end")
(let ((positions (string-positions str char :start start :end end)))
(if positions
(loop
with starts = ()
with ends = ()
for pos of-type fixnum in positions
and prev = start then (the vector-index (1+ pos))
maximize pos into last-pos
do (progn
(push prev starts)
(push pos ends))
finally (progn
(push (the vector-index (1+ last-pos)) starts)
(push end ends)
(return
(values (nreverse starts) (nreverse ends)))))
nil))))
(defun string-split (str char &key (start 0) end remove-empty-substrings)
"Returns a list of strings made by splitting simple-string STR at
CHAR, between START and END. If REMOVE-EMPTY-SUBSEQS is T, any empty
subsequences will be omitted from the returned list."
(declare (optimize (speed 3) (safety 1)))
(declare (type simple-string str))
(let ((end (or end (length str))))
(declare (type vector-index start end))
(check-arguments (<= 0 start end (length str)) (start end)
"start must be >= 0 and be <= end")
(multiple-value-bind (starts ends)
(string-split-indices str char :start start :end end)
(if (and starts ends)
(loop
for i of-type vector-index in starts
for j of-type vector-index in ends
when (not (and remove-empty-substrings
(= i j)))
collect (subseq str i j))
(list (subseq str start end))))))
| 8,596 | Common Lisp | .lisp | 198 | 37.30303 | 76 | 0.648245 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 84c43179dedbbbc5ec930182b2509429650358ba8d3ece7476a9203298f7f679 | 17,788 | [
-1
] |
17,789 | deoxybyte-utilities.asd | keithj_deoxybyte-utilities/deoxybyte-utilities.asd | ;;;
;;; Copyright (c) 2007-2013 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :cl-user)
(asdf:load-system :deoxybyte-systems)
(in-package :uk.co.deoxybyte-systems)
(defsystem deoxybyte-utilities
:name "deoxybyte-utilities"
:version "0.11.0"
:author "Keith James"
:licence "GPL v3"
:in-order-to ((test-op (load-op :deoxybyte-utilities
:deoxybyte-utilities-test))
(doc-op (load-op :deoxybyte-utilities
:cldoc)))
:depends-on ((:version :deoxybyte-systems "1.0.0"))
:components
((:module :deoxybyte-utilities
:serial t
:pathname "src/"
:components ((:file "package")
(:file "conditions")
(:file "type-utilities")
(:file "deoxybyte-utilities")
(:file "numeric-utilities")
(:file "cons-utilities")
(:file "set-utilities")
(:file "vector-utilities")
(:file "string-utilities")
(:file "octet-vector-utilities")
(:file "clos-utilities")
(:file "finite-state-machine")
(:file "queue")
#+:sbcl(:file "sbcl")
#+:ccl (:file "ccl")
#-(or :sbcl :ccl) (:file "default"))))
:perform (test-op :after (op c)
(maybe-run-lift-tests :deoxybyte-utilities
"deoxybyte-utilities-test.config"))
:perform (doc-op :after (op c)
(maybe-build-cldoc-docs :deoxybyte-utilities "doc/html")))
| 2,473 | Common Lisp | .asd | 56 | 32.464286 | 77 | 0.553668 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 567c6de203d54075f84fb617e743d182367d36fc207c89e5a748ea3d2a992213 | 17,789 | [
-1
] |
17,790 | deoxybyte-utilities-test.asd | keithj_deoxybyte-utilities/deoxybyte-utilities-test.asd | ;;;
;;; Copyright (c) 2007-2013 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(defsystem deoxybyte-utilities-test
:depends-on ((:version :lift "1.7.0")
:deoxybyte-utilities)
:components ((:module :deoxybyte-utilities-test
:serial t
:pathname "test/"
:components ((:file "package")
(:file "deoxybyte-utilities-test")
(:file "cons-utilities-test")
(:file "set-utilities-test")
(:file "numeric-utilities-test")
(:file "vector-utilities-test")
(:file "octet-vector-utilities-test")
(:file "string-utilities-test")
(:file "clos-utilities-test")
(:file "finite-state-machine-test")
(:file "queue-test")))))
| 1,767 | Common Lisp | .asd | 35 | 36.285714 | 74 | 0.543039 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 56ac3fe26116c14b6888419395027c0cba84217891de135d260bdc26a77114c8 | 17,790 | [
-1
] |
17,794 | deoxybyte-utilities-test.config | keithj_deoxybyte-utilities/deoxybyte-utilities-test.config | ;;; Configuration for LIFT tests
;; Settings
(:if-dribble-exists :supersede)
;; (:dribble "lift.dribble")
(:dribble nil)
(:print-length 10)
(:print-level 5)
(:print-test-case-names t)
(:log-pathname t)
;; Suites to run
(uk.co.deoxybyte-utilities-test:deoxybyte-utilities-tests)
;; Report properties
(:report-property :title "deoxybyte-utilities | Test results")
(:report-property :relative-to deoxybyte-utilities)
(:report-property :name "test-results")
(:report-property :format :html)
(:report-property :style-sheet "test-style.css")
(:report-property :if-exists :supersede)
(:report-property :unique-name nil)
(:build-report)
;; (:report-property :format :describe)
;; (:report-property :full-pathname *standard-output*)
;; (:build-report)
| 748 | Common Lisp | .l | 23 | 31.304348 | 62 | 0.754167 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fa18da670651d30cf559aa149aeac9f557c0459091997d7ffb73640936645c57 | 17,794 | [
-1
] |
17,838 | package.lisp | fosskers_cl-nonempty/src/package.lisp | (defpackage nonempty
(:use :cl)
(:shadow #:cons #:car #:cdr #:last
#:map #:append
#:length #:reverse #:elt)
;; --- Lists --- ;;
(:export #:nelist #:nel
#:cons #:car #:cdr
#:map #:filter #:fold)
;; --- Generics --- ;;
(:export #:length #:reverse #:elt #:last #:append
#:to-list)
(:documentation "Non-empty collections.
Non-emptiness can be a powerful guarantee. There are often times when a
collection is passed to a function, but must contain some value to be useful. In
these cases we must manually check, or otherwise account for NIL in our logic.
This can muddle the clarity of the code, especially when empty is not a valid
state. It is here that non-empty variants of the usual collection types can be
used to great effect.
See `nel', the main way to construct a non-empty list."))
(in-package :nonempty)
| 883 | Common Lisp | .lisp | 21 | 37.571429 | 80 | 0.667832 | fosskers/cl-nonempty | 3 | 0 | 0 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 00fefc03778a9e8567d9006e8fc6d2b0edb4b57761e109939b63b6c002dc079b | 17,838 | [
-1
] |
17,839 | transducers.lisp | fosskers_cl-nonempty/src/transducers.lisp | (defpackage nonempty/transducers
(:use :cl)
(:local-nicknames (:ne :nonempty)
(:t :transducers))
(:export #:nelist)
(:documentation "Transducers support for nonempty."))
(in-package :nonempty/transducers)
(defmethod t:transduce (xform f (source ne:nelist))
(t:transduce xform f (ne:to-list source)))
#+nil
(t:transduce (t:map #'1+) #'t:cons (ne:nel 1 2 3))
(defun nelist (&optional (acc nil a-p) (input nil i-p))
"Reducer: Collect all results into a non-empty list.
# Conditions
- `transducers:empty-transduction': when no values made it through the transduction."
(cond ((and a-p i-p) (cons input acc))
;; The transduction is complete and items were actually saved.
((and a-p (not i-p) acc)
(let ((r (nreverse acc)))
(ne::make-nelist :head (car r)
:tail (cdr r))))
;; The transduction is complete but nothing made it through.
((and a-p (not i-p)) (error 't:empty-transduction :msg "nelist: the transduction was empty."))
(t '())))
#+nil
(t:transduce (t:filter #'evenp) #'nelist (ne:nel 1 2 3 5))
| 1,126 | Common Lisp | .lisp | 26 | 37.346154 | 102 | 0.632205 | fosskers/cl-nonempty | 3 | 0 | 0 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 355b27ee321841958d72b120de75998ef938ec1b7af0ce8bca41239e2632f0d7 | 17,839 | [
-1
] |
17,840 | generics.lisp | fosskers_cl-nonempty/src/generics.lisp | (in-package :nonempty)
(defgeneric length (items)
(:documentation "The length of the given non-empty structure."))
(defmethod length ((items nelist))
(1+ (cl:length (nelist-tail items))))
#+nil
(length (nel 1 2 3))
(defgeneric reverse (items)
(:documentation "The reverse of the given non-empty structure."))
(defmethod reverse ((items nelist))
(let ((revd (cl:reverse (cl:cons (nelist-head items)
(nelist-tail items)))))
(make-nelist :head (cl:car revd) :tail (cl:cdr revd))))
#+nil
(reverse (nel 1 2 3))
(defgeneric elt (items index)
(:documentation "The element of ITEMS specified by INDEX."))
(defmethod elt ((items nelist) index)
"Yields NIL if the index is out of range."
(if (zerop index)
(nelist-head items)
(cl:elt (nelist-tail items) (1- index))))
#+nil
(elt (nel 1 2 3) 2)
(defgeneric to-list (items)
(:documentation "Convert this non-empty collection into a normal list."))
(defmethod to-list ((items nelist))
(cl:cons (nelist-head items)
(nelist-tail items)))
#+nil
(to-list (nel 1 2 3))
(defgeneric last (items)
(:documentation "The last element of the ITEMS. Guaranteed to exist."))
(defmethod last ((items nelist))
(if (null (nelist-tail items))
(nelist-head items)
(cl:car (cl:last (nelist-tail items)))))
#+nil
(last (nel 1 2 3))
(defgeneric append (nonempty other)
(:documentation "Append some OTHER collection to a NONEMPTY one."))
(defmethod append ((nonempty nelist) (other nelist))
(make-nelist :head (nelist-head nonempty)
:tail (cl:append (nelist-tail nonempty)
(to-list other))))
(defmethod append ((nonempty nelist) (other list))
(make-nelist :head (nelist-head nonempty)
:tail (cl:append (nelist-tail nonempty)
other)))
#+nil
(append (nel 1 2 3) (nel 4 5 6))
#+nil
(append (nel 1 2 3) '(4 5 6))
| 1,938 | Common Lisp | .lisp | 53 | 31.509434 | 75 | 0.650589 | fosskers/cl-nonempty | 3 | 0 | 0 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3e3fa1e668b586a3516f6429d24ea17b314f14f1c4079582dfba553e385ad029 | 17,840 | [
-1
] |
17,841 | list.lisp | fosskers_cl-nonempty/src/list.lisp | (in-package :nonempty)
(defstruct nelist
"A list guaranteed to contain at least one item."
(head nil :read-only t)
(tail nil :read-only t :type list))
(defun nel (item &rest items)
"Construct a non-empty list from at least one input argument."
(make-nelist :head item :tail items))
#+nil
(nel 1 2 3)
(declaim (ftype (function (t nelist) nelist) cons))
(defun cons (item list)
"Append a new item onto the front of a non-empty list."
(make-nelist :head item :tail (to-list list)))
#+nil
(cons 0 (nel 1 2 3))
(declaim (ftype (function (nelist) t) car))
(defun car (items)
"The first element of a non-empty list."
(nelist-head items))
#+nil
(car (nel 1 2 3))
(declaim (ftype (function (nelist) list) cdr))
(defun cdr (items)
"The possibly-empty tail of a non-empty list."
(nelist-tail items))
#+nil
(cdr (nel 1 2 3))
(declaim (ftype (function ((function (t) *) nelist) nelist) map))
(defun map (fn items)
"Map some FN over the given ITEMS, yielding a new non-empty list."
(make-nelist :head (funcall fn (nelist-head items))
:tail (mapcar fn (nelist-tail items))))
#+nil
(map #'1+ (nel 1 2 3))
(declaim (ftype (function ((function (t) boolean) nelist) list) filter))
(defun filter (pred items)
"Keep ITEMS for which a PRED function succeeds."
(remove-if-not pred (to-list items)))
#+nil
(filter #'evenp (nel 1 2 3 4 5 6))
(declaim (ftype (function ((function (t t) *) nelist &key (:seed t)) *) fold))
(defun fold (fn items &key (seed nil seedp))
"Reduce some ITEMS via a 2-arity FN.
The first argument to FN is the accumulator value, and the second is the current
item in the list."
(if seedp
(reduce fn (to-list items) :initial-value seed)
(reduce fn (to-list items))))
#+nil
(fold #'+ (nel 1 2 3))
#+nil
(fold #'+ (nel 1 2 3) :seed 10)
| 1,811 | Common Lisp | .lisp | 53 | 31.698113 | 80 | 0.682366 | fosskers/cl-nonempty | 3 | 0 | 0 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 968ce422b3e2bbdbc384f2e53d71b02bb91b6dd3a6b3c77fe2291b92373eb76a | 17,841 | [
-1
] |
17,842 | main.lisp | fosskers_cl-nonempty/tests/main.lisp | (defpackage nonempty/tests
(:use :cl :parachute)
(:local-nicknames (:ne :nonempty)
(:nt :nonempty/transducers)
(:t :transducers)))
(in-package :nonempty/tests)
(define-test suite)
(define-test "Lists"
:parent suite
(is equalp (ne:nel 1 2 3) (ne:nel 1 2 3))
(is equalp 1 (ne:car (ne:nel 1 2 3)))
(is equalp (ne:nel 2 3 4) (ne:map #'1+ (ne:nel 1 2 3)))
(is equalp (list 2 4 6) (ne:filter #'evenp (ne:nel 1 2 3 4 5 6)))
(is equal 6 (ne:fold #'+ (ne:nel 1 2 3)))
(is equal 16 (ne:fold #'+ (ne:nel 1 2 3) :seed 10)))
(define-test "Generics"
:parent suite
(is equal 3 (ne:length (ne:nel 1 2 3)))
(is equalp (ne:nel 3 2 1) (ne:reverse (ne:nel 1 2 3)))
(is equalp (ne:nel 1) (ne:reverse (ne:nel 1)))
(is equal 3 (ne:elt (ne:nel 1 2 3) 2))
(false (ne:elt (ne:nel 1 2 3) 20))
(is equal (list 1 2 3) (ne:to-list (ne:nel 1 2 3)))
(is equal 3 (ne:last (ne:nel 1 2 3)))
(is equal 1 (ne:last (ne:nel 1)))
(is equalp (ne:nel 1 2 3 4 5 6) (ne:append (ne:nel 1 2 3) (ne:nel 4 5 6)))
(is equalp (ne:nel 1 2 3 4 5 6) (ne:append (ne:nel 1 2 3) '(4 5 6))))
(define-test "Transducers"
:parent suite
(is equalp (list 2 3 4) (t:transduce (t:map #'1+) #'t:cons (ne:nel 1 2 3)))
(is equalp (ne:nel 2 3 4) (t:transduce (t:map #'1+) #'nt:nelist (ne:nel 1 2 3)))
(fail (t:transduce (t:filter #'evenp) #'nt:nelist (ne:nel 1 3 5))))
| 1,394 | Common Lisp | .lisp | 32 | 39.65625 | 82 | 0.587325 | fosskers/cl-nonempty | 3 | 0 | 0 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a3a762ad9ea79ed756137e7824b4fb4f62cbe53943ccfe0fb7479bfadeee3a62 | 17,842 | [
-1
] |
17,843 | nonempty.asd | fosskers_cl-nonempty/nonempty.asd | (defsystem "nonempty"
:version "0.1.0"
:author "Colin Woodbury <[email protected]>"
:license "LGPL-3.0-only"
:depends-on ()
:components ((:module "src"
:components
((:file "package")
(:file "list")
(:file "generics"))))
:description "Non-empty collections."
:in-order-to ((test-op (test-op "nonempty/tests"))))
(defsystem "nonempty/tests"
:author "Colin Woodbury <[email protected]>"
:license "LGPL-3.0-only"
:depends-on (:nonempty
:nonempty/transducers
:parachute
:transducers)
:components ((:module "tests"
:components
((:file "main"))))
:description "Test system for nonempty"
:perform (test-op (op c) (symbol-call :parachute :test :nonempty/tests)))
(defsystem "nonempty/transducers"
:author "Colin Woodbury <[email protected]>"
:license "LGPL-3.0-only"
:depends-on (:nonempty :transducers)
:components ((:module "src"
:components
((:file "transducers"))))
:description "Transducers support for nonempty.")
| 1,124 | Common Lisp | .asd | 32 | 27.46875 | 75 | 0.6 | fosskers/cl-nonempty | 3 | 0 | 0 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 85952f0d3099a55f23ccfe0e45a6cf9e9c13cad79eca34603848b67e1399580b | 17,843 | [
-1
] |
17,845 | qlfile.lock | fosskers_cl-nonempty/qlfile.lock | ("quicklisp" .
(:class qlot/source/dist:source-dist
:initargs (:distribution "https://beta.quicklisp.org/dist/quicklisp.txt" :%version :latest)
:version "2023-10-21"))
("fosskers-cl-transducers" .
(:class qlot/source/ultralisp:source-ultralisp
:initargs (:%version :latest)
:version "ultralisp-20240217095504"))
("Shinmera-parachute" .
(:class qlot/source/ultralisp:source-ultralisp
:initargs (:%version :latest)
:version "ultralisp-20240217095504"))
| 466 | Common Lisp | .l | 12 | 36.583333 | 93 | 0.751101 | fosskers/cl-nonempty | 3 | 0 | 0 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7e3660a401f0f5930781277108f2fe6c2ebb102bb7ca116c3e8f9261ce6dafb5 | 17,845 | [
-1
] |
17,865 | validate.lisp | fisxoj_validate/src/validate.lisp | (defpackage validate
(:use :iterate :cl)
(:nicknames #:v)
(:shadow #:list)
(:export #:parse
#:schema
#:<validation-error>
#:with-validated-values
#:str
#:int
#:bool
#:email
#:list
#:regex
#:timestamp)
(:documentation "Validate is a pretty simple library that is meant to be used in situations where you want to throw errors when data isn't quite what you expected. For example, when you receive user input, because who knows what a user will really do!
You will likely use validate like this::
(handler-case
(let ((my-int (v:int some-user-data)))
(code-expecting-an-int my-int))
(v:<validation-error> (e)
(report-error e)))"))
(in-package :validate)
;;; Conditions
(define-condition <validation-error> (simple-error)
((value :initarg :value)
(rule :initarg :rule))
(:report (lambda (condition stream)
(with-slots (rule value) condition
(format stream "Value ~a didn't satisfy condition ~S" value rule))))
(:documentation "Error to signal a validation condition wasn't met.
e.g. Value 'a' didn't satisfy contition 'length at least 3 characters'"))
(defun fail (value reason-str &rest args)
"Throw a validation error."
(error '<validation-error>
:value value
:rule (apply #'format nil reason-str args)))
;;; Validators
(defun int (value &key (radix 10) max min)
"Accepts a :param:`value` as an integer or string.
If :param:`value` is a string, interpret it as a value with base- :param:`radix`.
If specified, make sure :param:`min` <= :param:`value` <= :param:`max`."
(handler-case
(let ((number (etypecase value
(string (parse-integer value :radix radix))
(integer value))))
(when (and max (> number max))
(fail value "must be larger smaller than ~a" max))
(when (and min (< number min))
(fail value "must be larger than ~a" min))
number)
(parse-error (e)
(declare (ignore e))
(fail value "must be parseable as an integer"))))
;; https://github.com/alecthomas/voluptuous/blob/master/voluptuous.py#L1265
(defun bool (value)
"Attempts to convert :param:`value` to a ``t`` or ``nil`` by comparing it to a list of stringy true or false values. Throws a :class:`<validation-error>` if it can't figure out if :param:`value` is truthy or falsey."
(cond
((member value '("y" "yes" "t" "true" "on" "enable" ) :test #'string-equal) t)
((member value '("n" "no" "f" "false" "off" "disable") :test #'string-equal) nil)
(t (fail value "is not a valid boolean value"))))
(defun str (value &key min-length max-length)
"Checks that :param:`value` is a string.
If specified, checks that :param:`min-length` <= ``(length value)`` <= :param:`max-length`."
(unless (typep value 'string)
(fail value "must be a string."))
(when min-length
(unless (>= (length value) min-length)
(fail value "string length must be > ~d" min-length)))
(when max-length
(unless (<= (length value) max-length)
(fail value "string length must be < ~d" max-length)))
value)
(defun email (value)
"Checks that :param:`value` resembles an email address.
This is not an exhaustive check - some characters between an ``@`` and a ``.`` will suffice."
(str value)
(unless (ppcre:scan ".+@.+\\\..{2,}" value)
(fail value "string doesn't contain an email address."))
value)
(defun regex (value regex)
"Checks if :param:`value` matches :param:`regex`."
(if (ppcre:scan regex value)
value
(fail value "string doesn't match regex ~s" regex)))
(defun list (value &key length truncate element-type)
"Checks that :param:`value` is a list.
If :param:`length` is specified, check that the list has that length.
If :param:`length` is given and :param:`truncate` is true, truncate the list to that length.
If :param:`element-type` is given, it should be another validation function that will be called on every element of :param:`value`."
(unless (consp value)
(fail value "value is not a list."))
(let ((maybe-truncated-list
(cond
((and length truncate) (subseq value 0 length))
(length (if (= (length value) length)
value
(fail value "list length is ~d, not ~d." (length value) length)))
(t value))))
(if element-type
(handler-case
(mapcar element-type maybe-truncated-list)
(<validation-error> (e)
(with-slots (rule (subval value)) e
(fail value "Element ~a of list ~a failed rule ~S" subval value rule))))
maybe-truncated-list)))
(defun timestamp (value)
"Check that :param:`value` is a timestamp as recognized by `local-time`_.
.. _local-time: https://common-lisp.net/project/local-time/"
(etypecase value
(local-time:timestamp value)
(string (handler-case
(local-time:parse-timestring value)
(local-time::invalid-timestring (c)
(declare (ignore c))
(fail value "value is not a valid timestamp."))))))
| 5,107 | Common Lisp | .lisp | 116 | 38.206897 | 254 | 0.649757 | fisxoj/validate | 3 | 0 | 3 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e61cc049be9bc18c7a43299737ed26d936b4c33bd7a6d40f938ed70384484672 | 17,865 | [
-1
] |
17,866 | validate.lisp | fisxoj_validate/t/validate.lisp | (defpackage validate-test
(:use #:cl
#:prove))
(in-package :validate-test)
(plan 7)
;; Test parsing
;;; Email
(subtest "Email"
(is (v:email "[email protected]") "[email protected]" "Valid emails are ok.")
(is-error (v:email "me@here") 'v:<validation-error> "Email without a TLD throws an error.")
(is-error (v:email "[email protected]") 'v:<validation-error> "Email with an invalid TLD throws an error.")
(is-error (v:email "mehere.xyz") 'v:<validation-error> "Email with no @ throws an error."))
(subtest "regex"
(ok (v:regex "aaaaaa" "[a]{5}")
"Works for simple regexes.")
(ok (v:regex "cat" "^(cat|dog)$")
"Allows another simple regex.")
(is-error (v:regex "potato" "\\d+")
'v:<validation-error>
"An non-matching string raises a validation error."))
;;; String
(subtest "Strings"
(is-error (v:str 4) 'v:<validation-error> "A number is not a string.")
(is-error (v:str "me" :min-length 3) 'v:<validation-error> "A too-short string throws an error.")
(is-error (v:str "pizza" :max-length 3) 'v:<validation-error> "A too-long string throws an error.")
(ok (v:str "three" :min-length 5 :max-length 5) "A string that matches the constraints is fine (constraints are inclusive)")
(is (v:str "a string") "a string" "Validated strings match the original string."))
;;; Integer
(subtest "Integers"
(is (v:int "12") 12 "An integer gets converted to a string.")
(is (v:int "A" :radix 16) 10 "Integers in hex work.")
(is (v:int "10" :radix 2) 2 "Binary integers work.")
(is (v:int 34) 34 "An int is passed through.")
(is (v:int 34 :max 100) 34 "An int below a maximum is allowed.")
(is (v:int 34 :min 3) 34 "An int above a minimum is allowed.")
(is (v:int 34 :min 34) 34 "An int equal to the minimum value is allowed.")
(is (v:int 34 :max 34) 34 "An int equal to the maximum value is allowed.")
(is-error (v:int "a pizza")
'validate:<validation-error>
"A validate error is raised on strings that aren't integers.")
(is-error (v:int "127" :min 200)
'validate:<validation-error>
"A validate error is raised on numbers below a minimum.")
(is-error (v:int "127" :max 20)
'validate:<validation-error>
"A validate error is raised on numbers above a maximum."))
;;; Booleans
(subtest "Boolean values"
(subtest "True/False"
(is (v:bool "true") t "'true'")
(is (v:bool "True") t "'True")
(is (v:bool "false") nil "'false'")
(is (v:bool "FALSE") nil "'FALSE'")
(is (v:bool "f") nil "'f'")
(is (v:bool "t") t "'t'"))
(subtest "Yes/No"
(is (v:bool "no") nil "'No'")
(is (v:bool "n") nil "'n")
(is (v:bool "Yes") t "'Yes'")
(is (v:bool "YES") t "'YES")
(is (v:bool "y") t "'y'"))
(subtest "On/Off"
(is (v:bool "on") t "'on'")
(is (v:bool "off") nil "'off'"))
(subtest "Enable/Disable"
(is (v:bool "disable") nil "'disable'")
(is (v:bool "enable") t "'enable'"))
(is-error (v:bool "2")
'validate:<validation-error>
"raise a validation error on strings that aren't boolean values"))
;;; List
(subtest "List"
(ok (v:list (list 1 2))
"validates a simple json list.")
(is-error (v:list (list 1 2 3 4) :length 2)
'v:<validation-error>
"Too long a list generates an error.")
(is (v:list (list 1 2 3) :length 2 :truncate t)
'(1 2)
"Truncate truncates lists.")
(is-error (v:list (list "a" "bc") :element-type 'v:int)
'v:<validation-error>
"Raises an error on invalid element types.")
(is-error (v:list "12")
'v:<validation-error>
"Rases an error when value is not a list at all!"))
;;; Timestamps
(subtest "Timestamp"
(ok (v:timestamp (local-time:parse-timestring "2016-10-18T23:20:18.594Z"))
"Accepts a LOCAL-TIME:TIMESTAMP.")
(ok (v:timestamp "2016-10-18T23:20:18.594Z")
"Parses a timestamp.")
(is-error (v:timestamp "potato") 'v:<validation-error>
"Raises an error on an invalid timestamp."))
(finalize)
| 3,976 | Common Lisp | .lisp | 95 | 37.484211 | 126 | 0.625356 | fisxoj/validate | 3 | 0 | 3 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 95564b3bd651d597487d25dfcecef660a84b38ca2bb0d8baf6e6a76d1cb7598b | 17,866 | [
-1
] |
17,867 | validate-test.asd | fisxoj_validate/validate-test.asd | #|
This file is a part of validate project.
Copyright (c) 2016 Matt Novenstern ([email protected])
|#
(defsystem validate-test
:author "Matt Novenstern"
:license ""
:depends-on ("validate"
"prove")
:pathname "t"
:components ((:test-file "validate"))
:description "Test system for validate"
:defsystem-depends-on (:prove-asdf)
:perform (test-op (op c)
(funcall (read-from-string "prove:run")
(system-relative-pathname :validate-test #P"t/"))))
| 493 | Common Lisp | .asd | 16 | 26.625 | 59 | 0.671579 | fisxoj/validate | 3 | 0 | 3 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 54f8bcde79f0b9fca51ba86141cec1ba611556957b24cce046d11de4b0d9556f | 17,867 | [
-1
] |
17,868 | validate.asd | fisxoj_validate/validate.asd | #|
This file is a part of validate project.
Copyright (c) 2016 Matt Novenstern ([email protected])
|#
(defsystem validate
:version "0.8.0"
:author "Matt Novenstern"
:license "LLGPLv3"
:depends-on ("iterate"
"cl-ppcre"
"alexandria"
"local-time")
:pathname #P"src/"
:components ((:file "validate"))
:description "A data validation library for common lisp."
:in-order-to ((test-op (test-op validate-test))))
| 470 | Common Lisp | .asd | 16 | 24.25 | 59 | 0.640177 | fisxoj/validate | 3 | 0 | 3 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 786d05cba9c51bad093de159851b4cc668898c3e18930b2b16c58e54315a50c1 | 17,868 | [
-1
] |
17,872 | .travis.yml | fisxoj_validate/.travis.yml | language: common-lisp
sudo: false
notifications:
email: false
env:
global:
- PATH=$HOME/.roswell/bin:$PATH
- ROSWELL_INSTALL_DIR=$HOME/.roswell
- COVERAGE_EXCLUDE=t
matrix:
- LISP=sbcl-bin COVERALLS=true
- LISP=ccl-bin
install:
# Install Roswell
- curl -L https://raw.githubusercontent.com/snmsts/roswell/release/scripts/install-for-ci.sh | sh
- ros install prove
# Coveralls support
- git clone https://github.com/fukamachi/cl-coveralls ~/lisp/cl-coveralls
cache:
directories:
- $HOME/.roswell
- $HOME/.config/common-lisp
before_script:
- ros --version
- ros config
script:
- run-prove validate-test.asd
| 662 | Common Lisp | .l | 27 | 21.407407 | 99 | 0.725397 | fisxoj/validate | 3 | 0 | 3 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 1d590b55632fdfe830982db8f493e8a43fdfa211c88eb60697f13d4e862124c6 | 17,872 | [
-1
] |
17,874 | validate.html | fisxoj_validate/docs/validate.html | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="default.css" type="text/css" />
<title>validate package</title>
</head>
<body>
<div id="validate-package" class="document"><h1 class="title">validate package</h1>
<p>Validate is a pretty simple library that is meant to be used in situations where you want to throw errors when data isn't quite what you expected. For example, when you receive user input, because who knows what a user will really do!</p>
<dl class="docutils"><dt>You will likely use validate like this::</dt>
<dd><dl class="docutils first last"><dt>(handler-case</dt>
<dd><dl class="docutils first last"><dt>(let ((my-int (v:int some-user-data)))</dt>
<dd>(code-expecting-an-int my-int))</dd>
<dt>(v:<validation-error> (e)</dt>
<dd>(report-error e)))</dd>
</dl>
</dd>
</dl>
</dd>
</dl>
<div id="classes" class="section"><h2><a name="classes">Classes</a></h2>
<a id="class-3cvalidation-error-3e" class="target" name="class-3cvalidation-error-3e"></a><dl class="docutils"><dt><tt class="docutils literal">
<span class="pre"><validation-error></span></tt></dt>
<dd>Error to signal a validation condition wasn't met. e.g. Value 'a' didn't satisfy contition 'length at least 3 characters'</dd>
</dl>
</div>
<div id="functions" class="section"><h2><a name="functions">Functions</a></h2>
<a id="function-timestamp" class="target" name="function-timestamp"></a><dl class="docutils"><dt><tt class="docutils literal">
<span class="pre">timestamp</span></tt></dt>
<dd>Check that <tt class="docutils literal param">
<span class="pre">value</span></tt> is a timestamp as recognized by <a class="reference" href="https://common-lisp.net/project/local-time/"><span>local-time</span></a>.</dd>
</dl>
<a id="function-bool" class="target" name="function-bool"></a><dl class="docutils"><dt><tt class="docutils literal">
<span class="pre">bool</span></tt></dt>
<dd>Attempts to convert <tt class="docutils literal param">
<span class="pre">value</span></tt> to a <tt class="docutils literal">
<span class="pre">t</span></tt> or <tt class="docutils literal">
<span class="pre">nil</span></tt> by comparing it to a list of stringy true or false values. Throws a <a class="reference ref-class" href="validate.html#class-%3cvalidation-error%3e"><span class="ref-class"><validation-error></span></a> if it can't figure out if <tt class="docutils literal param">
<span class="pre">value</span></tt> is truthy or falsey.</dd>
</dl>
<a id="function-str" class="target" name="function-str"></a><dl class="docutils"><dt><tt class="docutils literal">
<span class="pre">str</span></tt></dt>
<dd>Checks that <tt class="docutils literal param">
<span class="pre">value</span></tt> is a string.</dd>
</dl>
<p>If specified, checks that <tt class="docutils literal param">
<span class="pre">min-length</span></tt> <= <tt class="docutils literal">
<span class="pre">(length</span> <span class="pre">value)</span></tt> <= <tt class="docutils literal param">
<span class="pre">max-length</span></tt>.</p>
<a id="function-regex" class="target" name="function-regex"></a><dl class="docutils"><dt><tt class="docutils literal">
<span class="pre">regex</span></tt></dt>
<dd>Checks if <tt class="docutils literal param">
<span class="pre">value</span></tt> matches <tt class="docutils literal param">
<span class="pre">regex</span></tt>.</dd>
</dl>
<a id="function-list" class="target" name="function-list"></a><dl class="docutils"><dt><tt class="docutils literal">
<span class="pre">list</span></tt></dt>
<dd>Checks that <tt class="docutils literal param">
<span class="pre">value</span></tt> is a list.</dd>
</dl>
<p>If <tt class="docutils literal param">
<span class="pre">length</span></tt> is specified, check that the list has that length.</p>
<p>If <tt class="docutils literal param">
<span class="pre">length</span></tt> is given and <tt class="docutils literal param">
<span class="pre">truncate</span></tt> is true, truncate the list to that length.</p>
<p>If <tt class="docutils literal param">
<span class="pre">element-type</span></tt> is given, it should be another validation function that will be called on every element of <tt class="docutils literal param">
<span class="pre">value</span></tt>.</p>
<a id="function-int" class="target" name="function-int"></a><dl class="docutils"><dt><tt class="docutils literal">
<span class="pre">int</span></tt></dt>
<dd>Accepts a <tt class="docutils literal param">
<span class="pre">value</span></tt> as an integer or string.</dd>
</dl>
<p>If <tt class="docutils literal param">
<span class="pre">value</span></tt> is a string, interpret it as a value with base- <tt class="docutils literal param">
<span class="pre">radix</span></tt>.</p>
<p>If specified, make sure <tt class="docutils literal param">
<span class="pre">min</span></tt> <= <tt class="docutils literal param">
<span class="pre">value</span></tt> <= <tt class="docutils literal param">
<span class="pre">max</span></tt>.</p>
<a id="function-email" class="target" name="function-email"></a><dl class="docutils"><dt><tt class="docutils literal">
<span class="pre">email</span></tt></dt>
<dd>Checks that <tt class="docutils literal param">
<span class="pre">value</span></tt> resembles an email address.</dd>
</dl>
<p>This is not an exhaustive check - some characters between an <tt class="docutils literal">
<span class="pre">@</span></tt> and a <tt class="docutils literal">
<span class="pre">.</span></tt> will suffice.</p>
</div>
<hr class ="docutils footer" /><div class="footer">Generated on : Mon, 03 Sep 2018 23:22:45 .
Generated by cl-docutils 0.1.1 from <a class="reference" href="http://docutils.sourceforge.net/rst.html"><span>restructured text</span></a> source.
</div>
</div>
</body>
</html> | 5,878 | Common Lisp | .l | 96 | 60.229167 | 305 | 0.703268 | fisxoj/validate | 3 | 0 | 3 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9578c3765d56200241fa87e4f04fa39fb537ded2c585529ed13e039e7fe1cad0 | 17,874 | [
-1
] |
17,876 | index.html | fisxoj_validate/docs/index.html | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="default.css" type="text/css" />
<title>validate</title>
<meta name="Author" content="Matt Novenstern" />
</head>
<body>
<div id="id1" class="document"><h1 class="title">validate</h1>
<table class="docinfo" frame="void" rules="none"><col class="docinfo-name" />
<col class="docinfo-content" />
<tbody valign="top">
<tr><th class="docinfo-name">Author</th><td>Matt Novenstern</td></tr><tr><th class="docinfo-name">Version</th><td>0.7.1</td></tr><tr class="field"><th colspan="1" class="docinfo-name">license:</th><td class="field-body">LLGPLv3</td>
</tr>
</tbody>
</table>
<p>A data validation library for common lisp.</p>
<div id="packages" class="section"><h2><a name="packages">Packages</a></h2>
<ul>
<li><p class="first last"><a class="reference" href="validate.html"><span>validate</span></a></p>
</li>
</ul>
</div>
<hr class ="docutils footer" /><div class="footer">Generated on : Mon, 03 Sep 2018 23:22:45 .
Generated by cl-docutils 0.1.1 from <a class="reference" href="http://docutils.sourceforge.net/rst.html"><span>restructured text</span></a> source.
</div>
</div>
</body>
</html> | 1,293 | Common Lisp | .l | 30 | 42.1 | 232 | 0.696203 | fisxoj/validate | 3 | 0 | 3 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 98c33139d19bc3baacd07fa342feb4dcbb8bd3e29f955dc86b1b9f1909c00273 | 17,876 | [
-1
] |
17,892 | package.lisp | admich_scliba/package.lisp | ;;;; package.lisp
(in-package #:cl-user)
(defpackage #:scliba
(:use #:cl ;; #:antik ;; #:local-time conflict with antik
)
(:import-from #:alexandria #:compose #:ensure-list #:flatten #:symbolicate #:first-elt #:shuffle)
;; antik::*antik-user-shadow-symbols*
;; (:shadowing-import-from #:antik #:MAXIMIZING #:MAXIMIZE #:MINIMIZING #:MINIMIZE
;; #:MULTIPLYING #:MULTIPLY #:SUMMING #:SUM #:FOR #:TIME
;; #:LENGTH #:DECF #:INCF #:SIGNUM #:ROUND #:FLOOR
;; #:COERCE #:< #:<= #:> #:>= #:= #:MAX #:MIN
;; #:ZEROP #:MINUSP #:PLUSP #:ABS #:EXP #:LOG #:EXPT
;; #:SQRT #:TANH #:COSH #:SINH #:ATAN #:ACOS #:ASIN
;; #:TAN #:COS #:SIN #:/ #:* #:- #:+ GRID:AREF
;; #:POLAR-TO-RECTANGULAR #:RECTANGULAR-TO-POLAR #:ACCELERATION
;; #:PSI #:KNOTS #:ROTATE)
(:shadow #:columns)
(:export #:*math*
#:*debug*
#:*randomize*
#:*top-level-document*
#:input
#:read-file
#:authoring-tree
#:authoring-tree-arguments
#:authoring-tree-body
#:authoring-tree-parent
#:authoring-tree-source-file
#:get-argument
#:export-document
#:export-document-on-string
#:backend
#:backend-outstream
#:context-backend
#:autarchy-backend
#:aut-context-backend
#:mixin-context-backend
#:def-authoring-tree
#:def-simple-authoring-tree
#:def-startstop
#:choose-one-of
#:mischia
#:authoring-document
#:startstop
#:input-tex
#:random-body
#:par
#:hline
#:footnote
#:book
#:section
#:section-n
#:counter-section-inc
#:counter-section-set
#:counter-section-val
#:*section-level*
#:*section-context-labels*
#:bf
#:framedtext
#:framed
#:columns
#:align-right
#:randomize
#:itemize
#:item
#:it
#:newpage
#:emph
#:newcolumn
#:math
#:ref
#:figure
#:table-float
#:mpcode
#:table
#:table-row
#:table-cell
#:imath
#:formula
#:compila-context
#:pq-format
#:pq-change-unit
#:hlinefill
#:title
#:centering
#:tfxx
#:tfx
#:tf
#:tfa
#:tfb
#:tfc
#:tfd
#:tfe
#:footer
#:def-counter
#:def-enumerated
#:*outstream*
#:*output-file*
#:*buffers*
#:buffered
#:def-buffer
#:def-buffered
#:def-enumerated-slave
#:def-enumerated-slave-buffered
#:*counters*
#:reset-all-counters
#:export-standard-file
#:html-backend
#:view-html
#:view-pdf
#:standard-output-file
#:export-file
#:enumerated
#:enumerated-n
#:html-output
#:*i-random*
#:with-document-arguments
#:newline
#:nbsp
#:compila-guarda
#:*main-backend*
#:*section-head-fn*
#:roman
#:*section-fonts*
#:sans-serif
#:small-caps
#:section-level
#:*default-backend*
#:compila
#:*current-node*
#:mixin-multiple-random-output-backend
#:backend-n
#:simple-table-rows
#:hss
#:inmargin
#:inframed
#:*s-o-u*)
(:export
#:scliba-physical-quantity
#:pq-exponent
#:pq-new-unit
#:pq-s-o-u
#:pq-precision
#:hfil
#:hfill
#:underbar
#:simple-itemize
#:vspace
#:simple-table-by-rows))
(antik:make-user-package :scliba)
(defpackage #:physics
(:use #:cl #:scliba)
(:shadowing-import-from #:scliba #:columns)
(:nicknames #:phys)
(:export
#:big-g
#:little-g
#:costante-stefan-boltzmann
#:densita))
(antik:make-user-package :physics)
(defpackage #:scliba-pedb
(:use #:cl #:scliba #:physics)
(:import-from #:alexandria #:with-unique-names #:flatten)
(:shadowing-import-from #:scliba #:columns)
;; (:shadowing-import-from #:antik #:MAXIMIZING #:MAXIMIZE #:MINIMIZING #:MINIMIZE
;; #:MULTIPLYING #:MULTIPLY #:SUMMING #:SUM #:FOR #:TIME
;; #:LENGTH #:DECF #:INCF #:SIGNUM #:ROUND #:FLOOR
;; #:COERCE #:< #:<= #:> #:>= #:= #:MAX #:MIN
;; #:ZEROP #:MINUSP #:PLUSP #:ABS #:EXP #:LOG #:EXPT
;; #:SQRT #:TANH #:COSH #:SINH #:ATAN #:ACOS #:ASIN
;; #:TAN #:COS #:SIN #:/ #:* #:- #:+ GRID:AREF
;; #:POLAR-TO-RECTANGULAR #:RECTANGULAR-TO-POLAR #:ACCELERATION
;; #:PSI #:KNOTS #:ROTATE)
(:nicknames #:pedb)
(:export
#:*esercizi-directory*
#:*compiti-directory*
#:*eserciziari-directory*
#:*esercizi-preview-directory*
#:*mpinclusion*
#:new-compito
#:pedb-all-exercize
#:tutti-esercizi
#:compila-esercizio-preview
#:*esercizi-argomenti*
#:input-esercizio
#:esercizi
#:genera-all-exercize))
(antik:make-user-package :scliba-pedb)
(defpackage #:scliba-ptnh
(:use #:cl #:scliba #:pedb #:physics)
(:shadowing-import-from #:scliba #:columns)
(:nicknames #:ptnh))
(antik:make-user-package :scliba-ptnh)
(defpackage #:scliba-itas
(:use #:cl #:scliba)
(:nicknames #:itas)
(:local-nicknames (#:a #:alexandria)))
| 5,308 | Common Lisp | .lisp | 198 | 19.90404 | 99 | 0.551262 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e77a27ffc3ccce130cc5b0ff117431f11972b842c8ef44a714d24cc8258004a3 | 17,892 | [
-1
] |
17,893 | backend.lisp | admich_scliba/backend.lisp | ;;;;; backend.lisp
(in-package #:scliba)
(defclass backend ()
((outstream :initarg :stream
:initform *standard-output*
:accessor backend-outstream)
(view-fn :initarg :view-fn
:accessor backend-view-fn)
(compile-fn :initarg :compile-fn
:accessor backend-compile-fn
:initform #'export-file)))
(defclass mixin-multiple-random-output-backend (backend) ((n :initarg :n
:initform 1
:accessor backend-n)))
(defmethod export-file (file (backend mixin-multiple-random-output-backend))
(let* ((n (backend-n backend))
(*randomize* (if (> n 1) t nil)))
(export-document
(authoring-document ()
(loop for *i-random* upto (1- n)
collect (read-file file)))
backend)))
(defclass mixin-context-backend (backend) ())
(defclass mixin-context-xtable-backend (backend) ())
(defclass mixin-context-natural-table-backend (backend) ())
(defmethod initialize-instance :after ((obj mixin-context-backend) &rest rest)
(setf (backend-view-fn obj) #'view-pdf
(backend-compile-fn obj) (compose #'compila-context #'export-file)))
(defclass context-backend (mixin-context-backend mixin-context-xtable-backend) ())
(defmethod standard-output-file (file (backend context-backend))
(merge-pathnames (merge-pathnames (pathname-name file) "context/prova.tex") file))
(defclass autarchy-backend (backend) ())
(defclass aut-context-backend (autarchy-backend mixin-context-backend mixin-context-xtable-backend) ())
(defmethod standard-output-file (file (backend aut-context-backend))
(merge-pathnames (merge-pathnames (pathname-name file) "aut-context/prova.tex") file))
(defclass html-backend (autarchy-backend) ())
(defmethod standard-output-file (file (backend html-backend))
(merge-pathnames (merge-pathnames (pathname-name file) "html/prova.html") file))
(defmethod initialize-instance :after ((obj html-backend) &rest rest)
(setf (backend-view-fn obj) #'view-html))
;; (defconstant +context-backend+ (make-instance 'context-backend))
;; (defconstant +aut-context-backend+ (make-instance 'aut-context-backend))
;; (defconstant +html-backend+ (make-instance 'html-backend))
(setf (who:html-mode) :html5)
(defmacro html-output (&body body)
`(who:with-html-output (*outstream* nil :indent t)
(who:htm ,@body)))
(defparameter *default-backend* (make-instance 'aut-context-backend))
| 2,370 | Common Lisp | .lisp | 48 | 45.708333 | 103 | 0.726759 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7186d5e9cf591f59eeec5fd1c386580b6976a77d4dac764a42d7095e8610097e | 17,893 | [
-1
] |
17,894 | pedb.lisp | admich_scliba/pedb.lisp | (in-package #:scliba-pedb)
(defparameter *pedb-directory* #p"/home/admich/Documents/scuola/my-didattica/pedb/")
(defparameter *esercizi-directory* (uiop:merge-pathnames* #p"exercises/" *pedb-directory*)) ; #p"/home/admich/Documenti/scuola/my-didattica/context/esercizi/"
(defparameter *esercizi-preview-directory* (uiop:merge-pathnames* #p"preview/" *pedb-directory*))
(defparameter *compiti-directory* (uiop:merge-pathnames* #p"compiti/file.lisp" *pedb-directory*))
(defparameter *eserciziari-directory* (uiop:merge-pathnames* #p"eserciziari/file.lisp" *pedb-directory*))
(defparameter *esercizi-argomenti* '(("Misure" . "mis") ("Rappresentazione" . "rap") ("Vettori" . "vet") ("Forze" . "for") ("Momenti" . "mom") ("Fluidi" . "fl") ("Cinematica1d" . "cin1") ("Cinematica2d" . "cin2") ("Dinamica" . "din") ("Energia" . "ener") ("Termologia" . "term") ("Elettrostatica" . "elect") ("Correnti elettriche" . "electcurr"))
"argomenti")
(defparameter *esercizi-tipi* '(("true/false" . "tf") ("choices" . "ch") ("free" . "fr") ("fill" . "fl"))
"tipi")
(defparameter *skeleton-compito*
"
(in-package :pedb)
(compito (:title \"Esercizi sul movimento\" :rfoot \"MMM. YYYY qNcN (WNN)\")
(columns (:context \"n=2, balance=no\")
)
(soluzioni ()))")
(defparameter *mpinclusion*
"
\\def \\textsf #1{\\ss #1}
\\setupMPinstance[method=decimal]
\\startMPinclusions
input metaobj;;
string LaTeXsetup ; LaTeXsetup := \"\";
input \"makecirc.mp\";
vardef latex(expr t) = textext(t) enddef ;
vardef markanglebetween (expr endofa, endofb, common, length, str) =
save curve, where ; path curve ; numeric where ;
where := turningnumber (common--endofa--endofb--cycle) ;
curve := (unitvector(endofa-common){(endofa-common) rotated (where*90)}
.. unitvector(endofb-common)) scaled length shifted common ;
draw thefreelabel(str,point .5 of curve,common) withcolor black ;
curve
enddef ;
u:=5mm;
def grid(expr xi,xf,yi,yf)=
for i=xi+1 upto xf-1:
draw (i*u,yi*u)..(i*u,yf*u) withcolor .7white ;
endfor
for i=yi+1 upto yf-1:
draw (xi*u,i*u)..(xf*u,i*u) withcolor .7white;
endfor
enddef;
def assi(expr xi,xf,yi,yf)=
drawarrow (xi*u,0)--(xf*u,0);
drawarrow (0,yi*u)--(0,yf*u);
label.bot(btex $x$ etex, (xf*u,0));
label.lft(btex $y$ etex, (0,yf*u));
enddef;
def labelgriglia(expr xi,xf,yi,yf)=
for i=xi+1 upto xf-1:
draw (i*u,-2pt)--(i*u,2pt);
draw textext(decimal(i)) scaled .8 shifted (i*u-3pt,-5pt);
% label.llft(decimal(i) infont \"ptmr\" scaled (6pt/fontsize defaultfont), (i*u,0));
endfor
for i=yi+1 upto yf-1:
draw (-2pt,i*u)--(2pt,i*u);
draw textext(decimal(i)) scaled .8 shifted (-6pt,i*u+4pt);
% label.llft(decimal(i) infont \"ptmr\" scaled (6pt/fontsize defaultfont), (0,i*u));
endfor;
enddef;
def righello(expr strt, stp, btick, stick, meas)=
draw (-5+strt*u,0)--(-5+strt*u,-1cm)--(stp*u+5,-1cm)--(stp*u+5,0)--cycle;
for i= strt step btick until stp:
draw (i*u,0)--(i*u,-0.3cm);
label.bot(decimal i,(i*u,-0.3cm));
endfor
for i=strt step stick until stp:
draw (i*u,0)--(i*u,-0.2cm);
endfor;
label(\"mm\",((strt+stp)*u/2,-0.8cm));
draw (strt*u,3)--(meas*u,3) withpen pensquare yscaled 3pt;
enddef;
def termometro(expr strt, stp, btick, stick, meas, um)=
u:=um*mm;
draw (0,-5+strt*u)--(-1cm,-5+strt*u)--(-1cm,stp*u+5)--(0,stp*u+5)--cycle;
for i= strt step btick until stp:
draw (0,i*u)--(-0.3cm,i*u);
label.lft(decimal i,(-0.3cm,i*u));
endfor
for i=strt step stick until stp:
draw (0,i*u)--(-0.2cm,i*u);
endfor
label(btex ℃ etex,(-0.8cm,(strt+stp)*u/2));
draw (-1mm,-5+strt*u)--(-1mm,meas*u) withpen pensquare xscaled 2pt;
enddef;
def millimetrata (expr x, y)=
u := 1mm;
xmax:= 10 * x;
ymax := 10 * y;
color cc;
cc := .5[red,white];
pickup pencircle scaled 0.1;
% mm
for i=0 step 1 until ymax:
draw (0,i)*u -- (xmax,i)*u withcolor cc;
endfor;
for i=0 step 1 until xmax:
draw (i,0)*u -- (i,ymax)*u withcolor cc;;
endfor;
pickup pencircle scaled .5;
% 5mm
for i=0 step 5 until ymax:
draw (0,i)*u -- (xmax,i)*u withcolor cc;
endfor;
for i=0 step 5 until xmax:
draw (i,0)*u -- (i,ymax)*u withcolor cc;;
endfor;
pickup pencircle scaled 1;
% 10mm
for i=0 step 10 until ymax:
draw (0,i)*u -- (xmax,i)*u withcolor cc;
endfor;
for i=0 step 10 until xmax:
draw (i,0)*u -- (i,ymax)*u withcolor cc;;
endfor;
enddef;
def puntoconerrore (expr x, y, dx, dy)=
draw ((x-dx)*u,(y-dy)*u)--((x-dx)*u,(y+dy)*u)--((x+dx)*u,(y+dy)*u)--((x+dx)*u,(y-dy)*u)--cycle;
drawdot (x*u,y*u) withpen pencircle scaled 3 ;
enddef;
\\stopMPinclusions")
(def-authoring-tree pedb-document (authoring-document) :documentation "A pedb root document")
(def-authoring-tree compito (pedb-document) :documentation "Compito root document")
(defmethod export-document :around ((document pedb-document) (backend context-backend))
(loop for ff in '("tex/env_esercizi.tex") do
(uiop:copy-file (merge-pathnames ff (asdf:system-source-directory :scliba))
(merge-pathnames (make-pathname :name (pathname-name ff) :type (pathname-type ff)) *output-file*)))
(format *outstream* "
~&\\environment env_esercizi~%
~:[% ~;~]\\enablemode[soluzioni]
"
(get-argument document :soluzioni))
(call-next-method))
(defmethod export-document ((document compito) (backend html-backend))
(who:with-html-output (*outstream*)
(who:htm (:div :class 'compito
(:h1 (who:str (get-argument document :title)))
(call-next-method)))))
(defmethod export-document :before ((document compito) (backend context-backend))
(write-string *mpinclusion* *outstream*)
(format *outstream*"
\\compito[title=~A,scuola=none]
\\makecompitotitle
~@[\\def\\rfoot{~A}~]" (get-argument document :title) (get-argument document :rfoot)))
(defmethod export-document :around ((document compito) (backend aut-context-backend))
(format *outstream* "~&\\setuppagenumbering[location=footer]
\\setuplayout[
topspace=1cm,
backspace=2cm,
width=middle,
height=middle,
header=0pt]
"
)
(write-string *mpinclusion* *outstream* )
(call-next-method))
(defmethod export-document :before ((document compito) (backend aut-context-backend))
(export-document (footer (:left "" :right (get-argument document :rfoot))) backend)
(export-document (title (get-argument document :title)) backend))
(defmacro infoform-1line ()
"Form nome e cognome per compiti in una riga"
`(table (:widths '(0.5 0.5) :frame nil :stretch t)
(table-row ()
(table-cell () "Alunno: " (hlinefill ()))
(table-cell () "Classe: " (hlinefill ()) "Data: " (hlinefill ())))))
(defmacro infoform ()
"Form nome e cognome per compiti"
`(table (:widths '(0.5 0.5) :frame nil :stretch t)
(table-row ()
(table-cell () "Nome: " (hlinefill ()))
(table-cell () "Classe: " (hlinefill ())))
(table-row ()
(table-cell () "Cognome: " (hlinefill ()))
(table-cell () "Data: " (hlinefill ())))))
(def-enumerated esercizio ())
(defmethod export-document :around ((document esercizio) backend)
(if *top-level-document*
(let ((doc (make-instance 'compito :arguments '(:title "Esercizio" :soluzioni t) :body (list document))))
(export-document doc backend))
(call-next-method)))
(defmethod export-document ((document esercizio) (backend aut-context-backend))
(format *outstream* "~&{\\bf ~d.} " (enumerated-n document)))
(defmethod export-document :after ((document esercizio) (backend aut-context-backend))
(format *outstream* "~&\\blank~%~%"))
(defmethod export-document ((document esercizio) (backend html-backend))
(html-output (:div :class "esercizio-head" (:h4 (who:fmt "Esercizio ~d" (enumerated-n document)))))
(call-next-method)
(format *outstream*"~&~%"))
(def-enumerated-slave-buffered soluzione esercizio)
(defmethod export-document ((document soluzione) (backend aut-context-backend))
(format *outstream* "~&~%{\\bf Soluzione ~d}~%" (enumerated-n document))
(call-next-method)
(format *outstream*"~&~%"))
(defmethod export-document ((document soluzione) (backend html-backend))
(html-output (:div :class "esercizio-head" (:h4 (who:fmt "Soluzione ~d" (enumerated-n document)))))
(call-next-method)
(format *outstream*"~&~%"))
;;temp hack I want implement soluzione buffer in lisp
(defmethod export-document :around ((document soluzione) (backend context-backend))
(format *outstream*"~&\\beginsoluzione~%")
(call-next-method)
(format *outstream*"~&\\endsoluzione~%"))
(def-authoring-tree soluzioni)
(defmethod export-document ((document soluzioni) (backend context-backend))
(format *outstream* "~&{\\printsoluzioni}~%"))
(defmethod export-document ((document soluzioni) (backend autarchy-backend))
(format *outstream* "~&~%~%{\\tfc Soluzioni. ~%~%}~a" (get-output-stream-string (cdr (assoc 'soluzione *buffers*)))))
(defparameter *last-sol* nil)
(defclass last-sol (authoring-tree)
())
(defmacro last-sol ()
`(make-instance 'last-sol))
(defmethod export-document ((document last-sol) (backend mixin-context-backend))
(format *outstream*"~[A~;B~;C~;D~;E~;F~]~%~% " *last-sol*))
(def-authoring-tree verofalso (itemize random-body))
(defmethod initialize-instance :after ((class verofalso) &rest rest)
(setf (getf (authoring-tree-arguments class) :context) "a,packed,joinedup"))
;; ;aggiustare parent
(defmacro verofalso (arguments &body body)
`(macrolet ((item (arguments &body body) `(make-instance 'item :arguments (list ,@arguments) :body (flatten (list (vfbox) ,@body)))))
(make-instance 'verofalso :arguments (list ,@arguments) :body (flatten (list ,@body)))))
(def-simple-authoring-tree vfbox)
(defmethod export-document ((document vfbox) (backend mixin-context-backend))
(format *outstream*"\\framed[width=1em,strut=yes]{V}\\thinspace\\framed[width=1em,strut=yes]{F}\\thinspace "))
(def-authoring-tree scelte (itemize random-body))
;; columns in itemize don't work inside two column layout
(defmethod initialize-instance :after ((class scelte) &rest rest)
(let ((cols (get-argument class :columns)))
(if cols
(setf (getf (authoring-tree-arguments class) :context) (format nil "A,packed,joinedup,columns,~r" cols))
(setf (getf (authoring-tree-arguments class) :context) "A,packed,joinedup"))))
(defmethod export-document :after ((document scelte) backend)
(setf *last-sol* (position :sol (authoring-tree-body document) :key #'authoring-tree-arguments :test #'member)))
(def-authoring-tree parti (itemize))
(defmethod initialize-instance :after ((class parti) &rest rest)
(setf (getf (authoring-tree-arguments class) :context) "i,packed"))
(defmacro input-esercizio (file)
(with-unique-names (new-path)
`(let ((,new-path
(or (probe-file ,file)
(probe-file (merge-pathnames *esercizi-directory* (make-pathname :name ,file :type "lisp")))
(merge-pathnames *esercizi-directory* (make-pathname :name ,file :type "tex")))))
(input ,new-path))))
(defmacro esercizi (&rest exes)
`(loop for x in (list ,@exes)
collect (input-esercizio x)))
;;;;;
(defun tutti-esercizi ()
(remove-if-not (lambda (x) (let ((str (pathname-type x))) (or (string= "tex" str) (string= "lisp" str) (string= "scl" str))))
(uiop:directory-files *esercizi-directory*)))
(defun get-esercizio-argomento (ese)
(second (ppcre:split "-" (pathname-name ese))))
(defun get-esercizio-numero (ese)
(parse-integer (fourth (ppcre:split "-" (pathname-name ese)))))
(defun esercizio-numero (n)
(find-if (lambda (x) (= n (get-esercizio-numero x))) (tutti-esercizi)))
(defun esercizi-di (argomento)
(remove-if-not (lambda (x) (string= argomento (get-esercizio-argomento x))) (tutti-esercizi)))
(defun raccolta-esercizi ()
(let ((*randomize* nil))
(compito (:title "Eserciziario di fisica" :soluzioni t :rfoot (format nil "Compilato \\date\\ \\currenttime"))
"
\\enablemode[soluzioni]
% \\setupbodyfont[11pt]
\\setupenumerations[esercizio][margin=yes, way=bysection, prefix=yes,prefixsegments=section,width=fit]
\\setupenumerations[soluzione][margin=yes, way=bysection, prefix=yes,prefixsegments=section,width=fit]"
(loop for topic in *esercizi-argomenti*
collect
(section (:title (car topic))
(loop for ese in (esercizi-di (cdr topic))
append
(list (input-esercizio ese)
(format nil "~&\\rightaligned{\\color[middlegray]{~A}}~%" (pathname-name ese))))
"
\\doifmode{soluzioni}{\\subject{Soluzioni}
\\selectblocks[soluzione][criterium=section]}")))))
(defun genera-all-exercize ()
(with-open-file (stream (merge-pathnames "all-exercise.tex" *eserciziari-directory*) :direction :output :if-exists :supersede :if-does-not-exist :create)
(let* ((*section-level* 1)
(*output-file* *eserciziari-directory*)
(backend (make-instance 'context-backend :stream stream))
(*outstream* stream))
(export-document (raccolta-esercizi) backend))))
;;; Compiling
(defclass mixin-pedb-backend (mixin-multiple-random-output-backend)
())
(defclass pedb-context-backend (mixin-pedb-backend context-backend)
())
(defclass pedb-aut-context-backend (mixin-pedb-backend aut-context-backend)
())
(defclass pedb-html-backend (html-backend)
())
(defparameter *backends* '(pedb-context-backend pedb-aut-context-backend pedb-html-backend))
;; ;; rivedere
(defun compito-lisp-file (name)
"return the lisp file for compito"
(make-pathname :name name :type "lisp" :directory (pathname-directory *compiti-directory*)))
(defun export-compito-in-all-backends (compito &key n)
"genera all the backends for compito "
(loop for backend in *backends*
do (export-file (compito-lisp-file compito) (make-instance backend) :n n)))
(defun export-and-view-compito-in-all-backends (compito &key n)
(export-compito-in-all-backends compito :n n)
(compila-context (standard-output-file (compito-lisp-file compito) 'context-backend))
(compila-context (standard-output-file (compito-lisp-file compito) 'aut-context-backend)))
;;;; Compiling functions
;; rimettere n con backend
(defun compila-guarda-compito (document &key (n 1) (directory *compiti-directory*) (soluzioni nil) (backend (make-instance 'pedb-context-backend)))
(setf (backend-n backend) n)
(compila-guarda (merge-pathnames document directory) backend))
(defmethod export-document :after ((document esercizio) backend)
(unless (authoring-tree-parent document)
(format *outstream* (export-document-on-string (soluzioni ()) backend))))
(defun compila-esercizio-preview (document &key (backend *default-backend*))
(compila document backend))
;;;; Utils
(defun controlla-esercizi-uguali (eserciziario compito &key (eserciziario-directory *eserciziari-directory*)
(compito-directory *compiti-directory*))
"Cerca se gli esercizi del compito COMPITO sono già nell'eserciziario ESERCIZIARIO."
(labels ((find-esercizi (x)
(typecase x
(esercizio
(list (authoring-tree-source-file x)))
(authoring-tree (find-esercizi (authoring-tree-body x)))
(list (loop for y in x append (find-esercizi y)))
(otherwise nil))))
(let* ((compito1 (merge-pathnames eserciziario eserciziario-directory))
(compito2 (merge-pathnames compito compito-directory))
(es1 (find-esercizi (read-file compito1)))
(es2 (find-esercizi (read-file compito2))))
(intersection es1 es2))))
;;;; Skeletons
(defun new-compito (file)
(with-open-file (stream file :direction :output :if-does-not-exist :create)
(format stream "~a" *skeleton-compito*))
(format nil "~a" file))
| 15,885 | Common Lisp | .lisp | 337 | 42.967359 | 348 | 0.679425 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ffaf47bd5f531f786bec2a1dcdfd6bfd7ac2856358fa48ff30009ad0ac2aec66 | 17,894 | [
-1
] |
17,895 | scliba.lisp | admich_scliba/scliba.lisp | ;;; scliba.lisp
;;;; exp-backend
(in-package #:scliba)
(defvar *math* nil)
(defparameter *debug* nil)
(defparameter *outstream* *standard-output*)
(defparameter *output-file* "./file.lisp")
(defparameter *main-backend* nil)
(defparameter *top-level-document* nil)
(defparameter *command-pdf-viewer* "emacsclient -n") ;;emacsclient -n zathura
(defparameter *command-html-viewer* "firefox ")
(defparameter *current-node* nil)
(named-readtables:defreadtable :scribble-antik
(:fuze :antik :scribble-both))
(setf *read-default-float-format* 'double-float)
(defun read-file (file)
"Read the file and generate the clos structure of the document.
ATTENTION: don't read untrusted file. You read the file with common lisp reader."
(named-readtables:in-readtable :scribble-antik) ;scribble-both
(let ((*source-file* file))
(with-open-file (ifile file)
(let ( ;; (*default-pathname-defaults* (uiop:truename* file))
(old-package *package*))
(loop for form = (read ifile nil :eof)
with value = '()
until (eq form :eof)
do (push (eval form) value)
finally
(setf *package* old-package)
(return (reverse value)))))))
;;;;;;;;;;;;;;;;;;;;
;;; compile utility os interaction
;;;;;;;;;;;;;;;;;
(defgeneric standard-output-file (file backend)
(:documentation "Return the output file for the backend")
(:method (file (backend symbol)) (standard-output-file file (make-instance backend))))
(defgeneric export-file (file backend))
(defmethod export-file :around ((file t) (backend t))
(let ((outfile (standard-output-file file backend))
(*top-level-document* t))
(uiop:ensure-all-directories-exist (list outfile))
(with-open-file (stream outfile :direction :output :if-exists :supersede :if-does-not-exist :create)
(let ((*outstream* stream)
(*output-file* outfile))
(call-next-method)))
outfile))
(defmethod export-file ((file t) (backend t))
(export-document (read-file file) backend))
;; (defun export-file (file backend &key n)
;; (let ((outfile (standard-output-file file backend))
;; (*top-level-document* t))
;; (uiop:ensure-all-directories-exist (list outfile))
;; (with-open-file (stream outfile :direction :output :if-exists :supersede :if-does-not-exist :create)
;; (let ((*outstream* stream)
;; (*outdirectory* (pathname-directory outfile)))
;; (if n
;; (let ((*randomize* t))
;; (export-document
;; (authoring-document ()
;; (loop for *i-random* upto (1- n)
;; collect (read-file file)))
;; backend))
;; (export-document (read-file file) backend))))
;; outfile))
(defun compila-context (file &key (mode nil) (output nil))
(uiop:with-current-directory ((uiop:pathname-directory-pathname file))
(let* ((filetex (pathname-name file))
(command (format nil "context --purgeall ~@[--mode=~a~] ~@[--result=~a~] ~a" mode output filetex)))
(print command)
(uiop:run-program command :output t)
(or output (merge-pathnames (make-pathname :type "pdf") file)))))
(defun view-pdf (file)
(uiop:with-current-directory ((uiop:pathname-directory-pathname file))
(let* ((file (merge-pathnames (make-pathname :type "pdf") (pathname-name file)))
(command (format nil "~a ~a &" *command-pdf-viewer* file)))
(uiop:launch-program command))))
(defun view-html (file)
(uiop:with-current-directory ((uiop:pathname-directory-pathname file))
(let ((command (format nil "~a ~a &" *command-html-viewer* file)))
(uiop:run-program command :output t))))
(defun compila-guarda (filelisp &optional (backend *default-backend*))
(funcall (compose (backend-view-fn backend) (backend-compile-fn backend)) filelisp backend))
(defun compila (filelisp backend)
(funcall (backend-compile-fn backend) filelisp backend))
| 3,864 | Common Lisp | .lisp | 84 | 42.261905 | 107 | 0.674289 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d6f8a7c25935a99a21e45396677f97155108107a151467f3073cb869009afbb6 | 17,895 | [
-1
] |
17,896 | itas.lisp | admich_scliba/itas.lisp | ;;;; Un pacchetto per documenti dell'ITAS Anzilotti
(in-package #:scliba-itas)
(defclass tabella-itas () ())
(defclass itas-document (authoring-document) ())
(def-authoring-tree relazione-finale (itas-document))
(defmethod export-document :before ((document tabella-itas) (backend mixin-context-backend))
(export-document (newline ()) backend))
(def-authoring-tree programmazione (authoring-document tabella-itas) :documentation "programmazione modulare")
(defmethod export-document :before ((document programmazione) (backend mixin-context-backend))
(format *outstream*
"
\\mainlanguage[italian]
\\setuppapersize[A4][A4]
\\setuplayout[
topspace=1cm,
backspace=2cm,
rightmargin=3cm,
% width=,
%height=middle,
header=0pt]
\\setuppagenumbering[alternative=singlesided,location={footer, center}]
")
(with-document-arguments (title docente materia classe) document
(export-document
(table (:frame t :widths '(1) :stretch t)
(table-row () (table-cell (:nc 2) (bf (format nil "DOCENTE: ~a" docente))))
(table-row ()
(table-cell (:frame '(1 1 nil 1)) (bf (format nil "Materia: ~a" materia)))
(table-cell (:frame '(nil 1 1 1) :align :r) (bf (format nil "Classe: ~a" classe)))))
backend)))
(def-counter modulo)
(def-counter unita)
(defclass unita-di-programmazione () ())
(defun durata-ore (unita)
(with-document-arguments (durata) unita
(if durata durata
(loop for i in (authoring-tree-body unita)
when (typep i 'authoring-tree)
summing (durata-ore i))
)))
(def-authoring-tree modulo0 (authoring-tree tabella-itas unita-di-programmazione) :documentation "modulo accoglienza della programmazione")
(defmethod export-document :before ((document modulo0) (backend autarchy-backend))
(with-document-arguments (title descrizione prerequisiti metodologie valutazione) document
(export-document
(table (:frame t :stretch t)
(table-row ()
(table-cell (:nc 3)
(table (:stretch t)
(table-row ()
(table-cell () (bf (format nil "MODULO N°~d " (counter-modulo-val))) title)
(table-cell (:align :r) (bf (format nil " durata ore ~d" (durata-ore document))))))))
(table-row ()
(table-cell (:nc 3) descrizione))
(table-row ()
(table-cell () (bf "Prerequisiti"))
(table-cell () (bf "Metodologie e strategie operative"))
(table-cell () (bf "Modalità di valutazione")))
(table-row ()
(table-cell () prerequisiti)
(table-cell () metodologie)
(table-cell () valutazione)))
backend)))
(def-authoring-tree u-didattica0 (authoring-tree tabella-itas unita-di-programmazione) :documentation "ud accoglienza della programmazione")
(defmethod export-document :before ((document u-didattica0) (backend autarchy-backend))
(counter-unita-inc)
(with-document-arguments (title attivita obiettivi durata split) document
(export-document
(table (:frame t :stretch t :split split )
(table-row ()
(table-cell (:nc 2)
(table (:stretch t)
(table-row ()
(table-cell () (bf (format nil "UNITÀ DIDATTICA N°~d.~d " (counter-modulo-val) (counter-unita-val))) title)
(table-cell (:align :r) (bf (format nil " durata ore ~d" (durata-ore document))))))))
(table-row ()
(table-cell () (bf "Attività"))
(table-cell () (bf "Obiettivi")))
(table-row ()
(table-cell () attivita)
(table-cell () obiettivi)))
backend)))
(def-authoring-tree modulo (authoring-tree) :documentation "modulo della programmazione")
(defmethod export-document :before ((document modulo) (backend autarchy-backend))
(counter-modulo-inc)
(counter-unita-set)
(with-document-arguments (title competenze conoscenze livelli-minimi prerequisiti metodologie valutazione split) document
(export-document (vspace ()) backend)
(export-document
(table (:frame t :stretch t :split t)
(table-row ()
(table-cell (:nc 3)
(table (:stretch t)
(table-row ()
(table-cell () (bf (format nil "MODULO N°~d " (counter-modulo-val))) title)
(table-cell (:align :r) (bf (format nil " durata ore ~d" (durata-ore document))))))
))
(table-row ()
(table-cell () (bf "Competenze"))
(table-cell () (bf "Conoscenze"))
(table-cell () (bf "Livelli minimi"))
)
(table-row ()
(table-cell () competenze
)
(table-cell () conoscenze
)
(table-cell () livelli-minimi
)
)
(table-row ()
(table-cell () (bf "Prerequisiti"))
(table-cell () (bf "Metodologie e strategie operative"))
(table-cell () (bf "Modalità di valutazione"))
)
(table-row ()
(table-cell () prerequisiti)
(table-cell () metodologie)
(table-cell () valutazione)
)
)
backend)))
(defmethod export-document :after ((document modulo) (backend autarchy-backend))
(with-document-arguments (recupero valutazione-modulo) document
(export-document
(table (:frame t :stretch t)
(table-row ()
(table-cell () (bf (format nil "ATTIVITÀ DI RECUPERO"))))
(table-row () (table-cell () recupero))
(table-row ()
(table-cell () (bf (format nil "VALUTAZIONE SOMMATIVA DEL MODULO"))))
(table-row () (table-cell () valutazione-modulo)))
backend)))
(def-authoring-tree u-didattica (authoring-tree) :documentation "ud della programmazione")
(defmethod export-document :before ((document u-didattica) (backend autarchy-backend))
(counter-unita-inc)
(with-document-arguments (title competenze conoscenze livelli-minimi prerequisiti metodologie valutazione split) document
(export-document
(table (:frame t :stretch t :split split)
(table-row ()
(table-cell (:nc 3)
(table (:stretch t)
(table-row ()
(table-cell () (bf (format nil "UNITÀ DIDATTICA N°~d.~d " (counter-modulo-val) (counter-unita-val))) title)
(table-cell (:align :r) (bf (format nil " durata ore ~d" (durata-ore document))))))))
(table-row ()
(table-cell () (bf "Competenze"))
(table-cell () (bf "Conoscenze"))
(table-cell () (bf "Livelli minimi")))
(table-row ()
(table-cell () competenze)
(table-cell () conoscenze)
(table-cell () livelli-minimi))
(table-row ()
(table-cell () (bf "Prerequisiti"))
(table-cell () (bf "Metodologie e strategie operative"))
(table-cell () (bf "Modalità di valutazione")))
(table-row ()
(table-cell () prerequisiti)
(table-cell () metodologie)
(table-cell () valutazione)))
backend)))
(defparameter *testo-valutazione*
"Scaturisce da verifiche orali e scritte, dalla considerazione
dell’atteggiamento, dell’impegno (in particolare per le attività in
laboratorio si terrà conto dell’autonomia nell’operare e della
puntualità nella riconsegna delle relazioni sugli esperimenti
realizzati), dei progressi realizzati e delle competenze acquisite.")
(defun testo-recupero (rif)
"esempio rif '((1 1) (2 3 4))"
(let ((out nil))
(push (format nil "È prevista la possibilità di ore destinate al recupero sia in orario
curricolare (recupero in itinere), sia in orario extracurricolare
pomeridiano. In particolare è necessaria l’acquisizione delle ") out)
(push (underbar "conoscenze") out)
(push (format nil " relative ") out)
(loop for i in rif
with n = 0
do
(incf n)
(let* ((mod (car i))
(uds (cdr i))
(n-uds (length uds)))
(unless (= n 1) (push (format nil " e ") out))
(if uds
(progn
(push (format nil "~:[alle ~;all'~]" (= 1 n-uds)) out)
(push (if (= 1 n-uds)
(bf (format nil "Unità didattica ~d " (car uds)))
(bf (format nil "Unità didattiche ~{~d~#[ ~; e ~:;, ~]~}" uds))) out)
(push (format nil "del ") out))
(push (format nil "al ") out))
(push (bf (format nil "Modulo ~d " mod)) out))
)
(push (format nil "per un proficuo prosieguo dello studio della disciplina, ulteriori azioni di
recupero nel corso dell’anno saranno volte a raggiungere i livelli
minimi e integrare le competenze.") out)
(nreverse out)))
(defun riassunto-didattica (dida)
(format t "~{~a~}~%" (loop for i below 50 collect "-"))
(loop for i in (authoring-tree-body dida) do
(format t "~31a~10@a~%" (subseq (get-argument i :title) 0 (min 30 (length (get-argument i :title)))) (durata-ore i))
(loop for j in (authoring-tree-body i) do
(format t " ~20a ~8@a~%" (subseq (get-argument j :title) 0 (min 19 (length (get-argument j :title)))) (durata-ore j))))
(format t "~{~a~}~%" (loop for i below 50 collect "-"))
(format t "~41@a" (durata-ore dida)))
| 8,755 | Common Lisp | .lisp | 205 | 37.273171 | 141 | 0.655584 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7153ef92cc6a84eadfc94e2211b47fc5d7a11c54d2a1220949c2757acbce2ca3 | 17,896 | [
-1
] |
17,897 | physical-quantity.lisp | admich_scliba/physical-quantity.lisp | (in-package #:scliba)
(defparameter *s-o-u* '(:si :deg))
(define-units 'time '((hour (* 3600 second) (hr hours) "h")))
(define-units 'time '((minute (* 60 second) (min minutes) "min")))
(define-units 'length '((decimeter 0.1 (dm decimeters) "dm")))
(define-units 'mass '((hectogram (* 0.1 kilogram) (hg hectogram) "hg")))
(define-units 'pressure
'((pascal (/ newton (* meter meter)) (pa) "Pa") ))
(define-units 'current '((ampere 1 (amperes amps amp) "A")
(milliampere (* milli ampere) (milliamp milliamps ma) "mA")
(microampere (* micro ampere) (microamp microamps ua) "\\mu A")))
(define-units 'electric-potential
'((volt (/ (* kilogram meter meter)
(* ampere second second second))
(v volts) "V")
(millivolt (* milli volt) (mv millivolts) "mV")
(microvolt (* micro volt) (uv microvolts) "\\mu V")
))
(define-units 'resistance
'((ohm (/ (* kilogram meter meter)
(* ampere ampere second second second))
(ohms) "\\Omega")
(kilohm (* kilo ohm) (kilohms) "k\\Omega")
(megohm (* mega ohm) (megohms) "M\\Omega")
))
(define-units 'power
'((watt (/ (* kilogram meter meter) (* second second second))
(w watts) "W")
(milliwatt (* milli watt) (mlw milli-watt milli-watts) "mW")
(microwatt (* micro watt) (uw micro-watt micro-watts) "\\mu W")
(kilowatt (* kilo watt) (kw kilowatts) "kW")
(megawatt (* mega watt) (mw megawatts mega-watt mega-watts) "MW")
(gigawatt (* giga watt) (gw gigawatts giga-watt giga-watts) "GW")
(horsepower (* 550 (/ (* foot pound-force) second)) (hp) "hp")))
(define-units 'temperature
'((kelvin 1.0 (k kelvin kelvins) "K")
(celsius 1.0 (celsius) "°C")
(rankine 5/9 ()) ))
(define-units 'charge
'((coulomb (* ampere second) (coul coulombs) "C")))
;; (antik::define-derived-dimensions
;; '((elastic-costant (/ force length))))
;; (define-units 'elastic-costant
;; '((si-elastic-costant (/ newton meter) (newton/meter N/m) "N/m")))
;; print number
(defun number-parts (num &key (precision 3))
(let* ((fmt (format nil "~~,~d,1,1,,,'ee" (1- precision)))
(parts (map 'list #'read-from-string (remove "" (ppcre:split "e|\\+" (format nil fmt num)) :test #'string=))))
(values-list parts)))
(defun number-format% (num &key (precision 3) (exponent 0) &allow-other-keys)
(if (zerop num)
"0"
(multiple-value-bind (n exp) (number-parts num :precision precision)
(let* ((exponent (or exponent exp))
(k (- exp exponent))
(d% (- precision k 1))
(d (if (> d% 0) d% 0))
(fmt (format nil "~~,~d,~df" d k))
(strn% (format nil fmt n))
(strn (if (or (char= #\0 (elt (remove-if (lambda (x) (char= x #\-)) strn%) 0))
(< 0 d))
strn%
(ppcre:regex-replace "\\..*" strn% ""))))
(ppcre:regex-replace "\\." (format nil "\\text{~a}~[~:;\\times 10^\{~a\}~]" strn exponent exponent) ",")))))
(define-system-of-units si-my-mod (deg hz) :si)
(set-system-of-units :si-my-mod)
(defun print-unit (unit)
(cond
((null unit) nil)
((numberp unit) (format nil "~a" unit))
((symbolp unit)
(let ((print-names (print-name (get-canonical-name unit))))
(if (listp print-names)
(first print-names)
print-names)))
((stringp unit) unit)
((eql '/ (first unit)) (format nil "~a/~a" (print-unit (second unit)) (print-unit (third unit))))
((eql 'expt (first unit)) (format nil "~a^{~a}" (print-unit (second unit)) (print-unit (third unit))))
((eql '* (first unit)) (format nil "~a\\ ~a" (print-unit (second unit)) (print-unit (third unit))))
(t "unknown"))
;; (when (and unit (not (listp unit)))
;; (let ((print-names (print-name (get-canonical-name unit))))
;; (if (listp print-names)
;; (first print-names)
;; print-names)))
)
(defclass pq-format (authoring-tree)
((pq :accessor pq-format-pq
:initarg :pq
:initform nil)
(precision :accessor pq-format-precision
:initarg :precision
:initform 3)
(exponent :accessor pq-format-exponent
:initarg :exponent
:initform 0)
(s-o-u :accessor pq-format-s-o-u
:initarg :s-o-u
:initform *s-o-u*)
(new-unit :accessor pq-format-new-unit
:initarg :new-unit
:initform nil)))
(defgeneric pq-format (pq &key &allow-other-keys))
(defmethod pq-format ((pq physical-quantity) &key (precision 3) (exponent 0 exponent-p) (s-o-u *s-o-u*) (new-unit nil new-unit-p) &allow-other-keys)
"format the physical quantity"
(make-instance 'pq-format :pq pq :precision precision :exponent exponent :s-o-u s-o-u :new-unit new-unit))
(defmethod pq-format (pq &key &allow-other-keys)
"format the physical quantity"
"--")
(defmethod pq-format ((pq real) &rest keys &key &allow-other-keys)
(apply #'number-format% pq keys))
(defmethod pq-format ((pq cons) &rest keys &key &allow-other-keys )
"format the physical quantity"
(list "["(apply #'make-instance 'pq-format :pq (car pq) keys) " -- " (apply #'make-instance 'pq-format :pq (cdr pq) keys) "]"))
(defmethod export-document ((document pq-format) (backend mixin-context-backend))
(with-slots (pq precision exponent s-o-u new-unit) document
(with-nf-options (:system-of-units (funcall #'antik::make-sysunits (cdr s-o-u) (car s-o-u)))
(multiple-value-bind (num unit) (pqval pq)
(let* ((unit (or (print-unit new-unit) (print-unit unit)))
(str (format nil "~a~:[\\ ~;~]~@[{\\rm ~a}~]"
(number-format% num :precision precision :exponent exponent)
(or (not unit) (string= unit (print-unit :degree)))
unit)))
(unless *math* (setf str (concatenate 'string "$" str "$")))
(format *outstream* "~a" str))))))
(defun pq-change-unit (pq new-unit)
"Return a new physical-quantity with the same value of PQ and NEW-UNIT as unit"
(make-pq (pqval pq) new-unit))
| 6,094 | Common Lisp | .lisp | 128 | 42.046875 | 148 | 0.595246 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3bfd78b5884cbe23f2ff27c083daabaacf5def7dc149da10e2d043b2c92e5cea | 17,897 | [
-1
] |
17,898 | macro.lisp | admich_scliba/macro.lisp | (in-package :scliba)
(defmacro with-document-arguments (args document &body body)
(let ((in (gensym)))
`(let ((,in ,document))
;; ,@(maybe-rebinding in documents 'with-slots)
;; ,in
(symbol-macrolet
,(mapcar (lambda (arg-entry)
(destructuring-bind
(var-name &optional (arg-name (alexandria:make-keyword (symbol-name var-name))))
(ensure-list arg-entry)
`(,var-name
(get-argument ,in ,arg-name)))
)
args)
,@body))))
;;; macro utility
(defmacro def-authoring-tree (name &optional (superclass '(authoring-tree)) &key (slot '()) (documentation "No documentation"))
`(progn
(defclass ,name (,@superclass)
,slot
(:documentation ,documentation))
(defmacro ,name (arguments &body body)
(let ((cl '',name))
`(let ((*math* (if (typep (make-instance ,cl) 'mixin-math) t nil))
(tree (make-instance ,cl :arguments (list ,@arguments))))
(let ((*current-node* tree))
(setf (authoring-tree-body tree) (flatten (list ,@body)))
tree))))))
(defmacro def-simple-authoring-tree (name &optional (superclass '(authoring-tree)) (documentation "No documentation"))
`(progn
(defclass ,name (,@superclass)
())
(defmacro ,name (&body body)
(let ((cl '',name))
`(let ((*math* (if (typep (make-instance ,cl) 'mixin-math) t nil))
(tree (make-instance ,cl)))
(let ((*current-node* tree))
(setf (authoring-tree-body tree) (flatten (list ,@body)))
tree))))))
(defmacro def-simple-authoring-tree-fn (name &optional (superclass '(authoring-tree)) (documentation "No documentation"))
`(progn
(defclass ,name (,@superclass)
())
(defun ,name (&rest body)
(let ((*math* (if (typep (make-instance ',name) 'mixin-math) t nil)))
(make-instance ',name :body body)))))
| 1,975 | Common Lisp | .lisp | 47 | 33.553191 | 127 | 0.576183 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f96657599468ee91a14954124ad2cbbc61577e7c3fb3e38f8068b718c20fcb9a | 17,898 | [
-1
] |
17,899 | itas-odt.lisp | admich_scliba/itas-odt.lisp | (in-package :scliba-itas)
(defparameter *xml-indentation* 2)
(defparameter *odf-version* "1.3")
(eval-when (::compile-toplevel :load-toplevel :execute)
(defparameter *namespaces*
'(("manifest" . "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0")
("office" . "urn:oasis:names:tc:opendocument:xmlns:office:1.0")
("grddl" . "http://www.w3.org/2003/g/data-view#")
("dc" . "http://purl.org/dc/elements/1.1/")
("xlink" . "http://www.w3.org/1999/xlink")
("meta" . "urn:oasis:names:tc:opendocument:xmlns:meta:1.0")
("ooo" . "http://openoffice.org/2004/office")
("css3t" . "http://www.w3.org/tr/css3-text/")
("rpt" . "http://openoffice.org/2005/report")
("chart" . "urn:oasis:names:tc:opendocument:xmlns:chart:1.0")
("svg" . "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0")
("draw" . "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0")
("text" . "urn:oasis:names:tc:opendocument:xmlns:text:1.0")
("oooc" . "http://openoffice.org/2004/calc")
("style" . "urn:oasis:names:tc:opendocument:xmlns:style:1.0")
("ooow" . "http://openoffice.org/2004/writer")
("fo" . "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0")
("dr3d" . "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0")
("table" . "urn:oasis:names:tc:opendocument:xmlns:table:1.0")
("number" . "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0")
("of" . "urn:oasis:names:tc:opendocument:xmlns:of:1.2")
("calcext" . "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0")
("tableooo" . "http://openoffice.org/2009/table")
("drawooo" . "http://openoffice.org/2010/draw")
("dom" . "http://www.w3.org/2001/xml-events")
("field" . "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0")
("math" . "http://www.w3.org/1998/math/mathml")
("form" . "urn:oasis:names:tc:opendocument:xmlns:form:1.0")
("script" . "urn:oasis:names:tc:opendocument:xmlns:script:1.0")
("xhtml" . "http://www.w3.org/1999/xhtml")
("formx" . "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0")
("xsi" . "http://www.w3.org/2001/xmlschema-instance")
("xsd" . "http://www.w3.org/2001/xmlschema")
("xforms" . "http://www.w3.org/2002/xforms")
;; extendend conformant
("loext" . "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0")
("officeooo" . "http://openoffice.org/2009/office"))))
(defmacro attributes* (ns prop-alist)
(a:once-only (ns prop-alist)
`(loop for (prop val) in ,prop-alist do
(cxml:attribute* ,ns prop val))))
(defmacro with-style-named-element ((element name) &body body)
`(cxml:with-element* ("style" ,element)
(cxml:attribute* "style" "name" ,name)
,@body))
(defmacro odt-table ((&key (columns 1) (style "Tbl")) &body body)
(a:once-only (columns)
`(cxml:with-element* ("table" "table")
(cxml:attribute* "table" "style-name" ,style)
(typecase ,columns
(number
(cxml:with-element* ("table" "table-column")
(cxml:attribute* "table" "style-name" (format nil "colonna-~d" ,columns))
(cxml:attribute* "table" "number-columns-repeated" (format nil "~d" ,columns))))
(list (loop for x in ,columns do
(cxml:with-element* ("table" "table-column")
(cxml:attribute* "table" "style-name" x)))))
,@body)))
(defmacro odt-table-row ((&key (style "TblR")) &body body)
`(cxml:with-element* ("table" "table-row")
(cxml:attribute* "table" "style-name" ,style)
,@body))
(defmacro odt-table-cell ((&key (style "TblCell") (span nil)) &body body)
`(progn
(cxml:with-element* ("table" "table-cell")
(cxml:attribute* "table" "style-name" ,style)
(cxml:attribute* "office" "value-type" "string")
(when ,span
(cxml:attribute* "table" "number-columns-spanned" (format nil "~d" ,span)))
,@body)
(when ,span
(loop repeat ,span do (cxml:with-element* ("table" "covered-table-cell"))))))
(defmacro odt-paragraph ((&key (style "Text_20_body")) &body body)
`(cxml:with-element* ("text" "p")
(cxml:attribute* "text" "style-name" ,style)
,@body))
(defmacro odt-span ((style) &body body)
`(cxml:with-element* ("text" "span")
(cxml:attribute* "text" "style-name" ,style)
,@body))
(defmacro odt-italic (&body body)
`(cxml:with-element* ("text" "span")
(cxml:attribute* "text" "style-name" "Italic")
,@body))
(defmacro odt-bold (&body body)
`(cxml:with-element* ("text" "span")
(cxml:attribute* "text" "style-name" "Bold")
,@body))
(defmacro odt-underline (&body body)
`(cxml:with-element* ("text" "span")
(cxml:attribute* "text" "style-name" "Underline")
,@body))
(defmacro odt-list ((&key (style "L1")) &body body)
`(cxml:with-element* ("text" "list")
(cxml:attribute* "text" "style-name" ,style)
,@body))
(defmacro odt-list-item ((&key (style nil)) &body body)
`(cxml:with-element* ("text" "list-item")
(odt-paragraph (:style "list-item-paragraph")
,@body)))
(defmacro with-namespaces (namespaces &body body)
(if namespaces
(let* ((aa (car namespaces))
(bb (cdr (assoc aa *namespaces* :test #'string=)))
(cc (cdr namespaces)))
`(cxml:with-namespace (,aa ,bb)
(with-namespaces ,cc ,@body)))
`(progn ,@body)))
(defun output-font-face-decls ()
(cxml:with-element* ("office" "font-face-decls")
(cxml:with-element* ("style" "font-face")
(cxml:attribute* "style" "name" "Liberation Serif")
(cxml:attribute* "svg" "font-family" "'Liberation Serif'")
(cxml:attribute* "style" "font-family-generic" "roman")
(cxml:attribute* "style" "font-pitch" "variable"))
(cxml:with-element* ("style" "font-face")
(cxml:attribute* "style" "name" "liberation sans")
(cxml:attribute* "svg" "font-family" "'Liberation Sans'")
(cxml:attribute* "style" "font-family-generic" "swiss")
(cxml:attribute* "style" "font-pitch" "variable"))
(cxml:with-element* ("style" "font-face")
(cxml:attribute* "style" "name" "DejaVu Sans")
(cxml:attribute* "svg" "font-family" "'DejaVu Sans'")
(cxml:attribute* "style" "font-family-generic" "system")
(cxml:attribute* "style" "font-pitch" "variable"))
(with-style-named-element ("font-face" "OpenSymbol")
(attributes* "svg" '(("font-family" "OpenSymbol")))
(attributes* "style" '(("font-charset" "x-symbol"))))))
(defun write-manifest-file (file mimetype &key (indentation *xml-indentation*))
(with-open-file (ostream file :direction :output :if-exists :supersede)
(cxml:with-xml-output (cxml:make-character-stream-sink ostream :indentation indentation)
(cxml:with-namespace ("manifest" "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0") ;; manifest:version=??
(cxml:with-element* ("manifest" "manifest")
(cxml:attribute* "manifest" "version" *odf-version*)
(cxml:with-element* ("manifest" "file-entry")
(cxml:attribute* "manifest" "full-path" "/") ;; version ??
(cxml:attribute* "manifest" "media-type" mimetype))
(cxml:with-element* ("manifest" "file-entry")
(cxml:attribute* "manifest" "full-path" "styles.xml")
(cxml:attribute* "manifest" "media-type" "text/xml"))
(cxml:with-element* ("manifest" "file-entry")
(cxml:attribute* "manifest" "full-path" "content.xml")
(cxml:attribute* "manifest" "media-type" "text/xml"))
(cxml:with-element* ("manifest" "file-entry")
(cxml:attribute* "manifest" "full-path" "meta.xml")
(cxml:attribute* "manifest" "media-type" "text/xml")))))))
(defun write-meta-file (file author &key (indentation *xml-indentation*))
(let ((date (local-time:format-rfc3339-timestring nil (local-time:now))))
(with-open-file (ostream file :direction :output :if-exists :supersede)
(cxml:with-xml-output (cxml:make-character-stream-sink ostream :indentation indentation)
(cxml:with-namespace ("office" "urn:oasis:names:tc:opendocument:xmlns:office:1.0")
(cxml:with-namespace ("grddl" "http://www.w3.org/2003/g/data-view#")
(cxml:with-namespace ("dc" "http://purl.org/dc/elements/1.1/")
(cxml:with-namespace ("xlink" "http://www.w3.org/1999/xlink")
(cxml:with-namespace ("meta" "urn:oasis:names:tc:opendocument:xmlns:meta:1.0")
(cxml:with-namespace ("ooo" "http://openoffice.org/2004/office")
(cxml:with-element* ("office" "document-meta")
(cxml:attribute* "office" "version" *odf-version*)
(cxml:with-element* ("office" "meta")
(cxml:with-element* ("meta" "generator")
(cxml:text "scliba-odt-backend"))
(cxml:with-element* ("meta" "initial-creator")
(cxml:text author))
(cxml:with-element* ("dc" "creator")
(cxml:text author))
(cxml:with-element* ("meta" "creation-date")
(cxml:text date))
(cxml:with-element* ("dc" "date")
(cxml:text date))))))))))))))
(defun write-style-file (file &key (indentation *xml-indentation*))
(with-open-file (ostream file :direction :output :if-exists :supersede)
(cxml:with-xml-output (cxml:make-character-stream-sink ostream :indentation indentation)
(with-namespaces ("office" "grddl" "dc" "xlink" "ooo" "css3t" "rpt" "chart" "svg" "draw" "text" "oooc" "style" "ooow" "fo" "dr3d" "table" "number" "of" "calcext" "tableooo" "drawooo" "dom" "field" "math" "form" "script" "xhtml")
(cxml:with-element* ("office" "document-styles")
(cxml:attribute* "office" "version" *odf-version*)
(output-font-face-decls)
(cxml:with-element* ("office" "styles")
;; default-styles
(cxml:with-element* ("style" "default-style")
(cxml:attribute* "style" "family" "table")
(cxml:with-element* ("style" "table-properties")
(cxml:attribute* "table" "border-model" "collapsing")))
(cxml:with-element* ("style" "default-style")
(cxml:attribute* "style" "family" "table-row")
(cxml:with-element* ("style" "table-row-properties")
(cxml:attribute* "fo" "keep-together" "auto")))
(cxml:with-element* ("style" "default-style")
(cxml:attribute* "style" "family" "paragraph")
(cxml:with-element* ("style" "paragraph-properties")
(cxml:attribute* "fo" "orphans" "2")
(cxml:attribute* "fo" "widows" "2")
(cxml:attribute* "fo" "hyphenation-ladder-count" "no-limit")
(cxml:attribute* "style" "text-autospace" "ideograph-alpha")
(cxml:attribute* "style" "punctuation-wrap" "hanging")
(cxml:attribute* "style" "line-break" "strict")
(cxml:attribute* "style" "tab-stop-distance" "1.251cm")
(cxml:attribute* "style" "writing-mode" "page"))
(cxml:with-element* ("style" "text-properties")
(cxml:attribute* "style" "use-window-font-color" "true")
;; (cxml:attribute* "loext" "opacity" "0%")
(cxml:attribute* "style" "font-name" "Liberation Serif")
(cxml:attribute* "style" "font-family-generic" "roman")
(cxml:attribute* "fo" "font-size" "12pt")
(cxml:attribute* "fo" "language" "it")
(cxml:attribute* "fo" "country" "it")
(cxml:attribute* "style" "letter-kerning" "true")
(cxml:attribute* "style" "font-name-asian" "dejavu sans")
(cxml:attribute* "style" "font-size-asian" "10.5pt")
(cxml:attribute* "style" "language-asian" "zh")
(cxml:attribute* "style" "country-asian" "cn")
(cxml:attribute* "style" "font-name-complex" "freesans")
(cxml:attribute* "style" "font-size-complex" "12pt")
(cxml:attribute* "style" "language-complex" "hi")
(cxml:attribute* "style" "country-complex" "in")
(cxml:attribute* "fo" "hyphenate" "false")
(cxml:attribute* "fo" "hyphenation-remain-char-count" "2")
(cxml:attribute* "fo" "hyphenation-push-char-count" "2")
;;(cxml:attribute* "loext" "hyphenation-no-caps" "false")
))
;; styles
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Standard")
(cxml:attribute* "style" "family" "paragraph")
(cxml:attribute* "style" "class" "text"))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Text_20_body")
(cxml:attribute* "style" "display-name" "Text body")
(cxml:attribute* "style" "family" "paragraph")
(cxml:attribute* "style" "parent-style-name" "Standard")
(cxml:attribute* "style" "class" "text")
(cxml:with-element* ("style" "paragraph-properties")
(cxml:attribute* "fo" "margin-top" "0cm")
(cxml:attribute* "fo" "margin-bottom" "0.247cm")
(cxml:attribute* "fo" "text-align" "justify")
(cxml:attribute* "style" "contextual-spacing" "false")
(cxml:attribute* "fo" "line-height" "115%")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Titoli")
(cxml:attribute* "style" "family" "paragraph")
(cxml:attribute* "style" "parent-style-name" "Standard")
(cxml:attribute* "style" "next-style-name" "Text_20_body")
(cxml:attribute* "style" "class" "text")
(cxml:with-element* ("style" "paragraph-properties")
(cxml:attribute* "fo" "margin-top" "0cm")
(cxml:attribute* "fo" "margin-bottom" "0cm")
(cxml:attribute* "style" "contextual-spacing" "false")
(cxml:attribute* "fo" "text-align" "left")
(cxml:attribute* "fo" "keep-with-next" "always"))
(cxml:with-element* ("style" "text-properties")
(cxml:attribute* "style" "font-pitch" "variable")
(cxml:attribute* "fo" "font-size" "100%")
(cxml:attribute* "fo" "font-weight" "bold")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Titoli-destra")
(cxml:attribute* "style" "display-name" "Titoli a destra")
(cxml:attribute* "style" "family" "paragraph")
(cxml:attribute* "style" "parent-style-name" "Titoli")
(cxml:attribute* "style" "next-style-name" "Text_20_body")
(cxml:attribute* "style" "class" "text")
(cxml:with-element* ("style" "paragraph-properties")
(cxml:attribute* "fo" "text-align" "right")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Titoli-centro")
(cxml:attribute* "style" "display-name" "Titoli al centro")
(cxml:attribute* "style" "family" "paragraph")
(cxml:attribute* "style" "parent-style-name" "Titoli")
(cxml:attribute* "style" "next-style-name" "Text_20_body")
(cxml:attribute* "style" "class" "text")
(cxml:with-element* ("style" "paragraph-properties")
(cxml:attribute* "fo" "text-align" "center")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Italic")
(cxml:attribute* "style" "family" "text")
(cxml:attribute* "style" "class" "text")
(cxml:with-element* ("style" "text-properties")
(cxml:attribute* "fo" "font-style" "italic")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Bold")
(cxml:attribute* "style" "family" "text")
(cxml:attribute* "style" "class" "text")
(cxml:with-element* ("style" "text-properties")
(cxml:attribute* "fo" "font-weight" "bold")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Underline")
(cxml:attribute* "style" "family" "text")
(cxml:attribute* "style" "class" "text")
(cxml:with-element* ("style" "text-properties")
(attributes* "style" '(("text-underline-style" "solid")
("text-underline-width" "auto")
("text-underline-color" "font-color")))))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Unbold")
(cxml:attribute* "style" "family" "text")
(cxml:attribute* "style" "class" "text")
(cxml:with-element* ("style" "text-properties")
(cxml:attribute* "fo" "font-weight" "normal")))
(with-style-named-element ("style" "Dash_20_Symbols")
(attributes* "style" '(("display-name" "Dash Symbols") ("family" "text")))
(cxml:with-element* ("style" "text-properties")
(attributes* "style" '(("font-name" "OpenSymbol") ("font-charset" "x-symbol")))
(attributes* "fo" '(("font-family" "OpenSymbol"))))))
;; pages layout
(cxml:with-element* ("office" "automatic-styles")
(cxml:with-element* ("style" "page-layout")
(cxml:attribute* "style" "name" "Mpm1")
(cxml:with-element* ("style" "page-layout-properties")
(cxml:attribute* "fo" "page-width" "21.0cm")
(cxml:attribute* "fo" "page-height" "29.7cm")
(cxml:attribute* "style" "num-format" "1")
(cxml:attribute* "style" "print-orientation" "portrait")
(cxml:attribute* "fo" "margin-top" "2cm")
(cxml:attribute* "fo" "margin-bottom" "2cm")
(cxml:attribute* "fo" "margin-left" "2cm")
(cxml:attribute* "fo" "margin-right" "2cm")
(cxml:attribute* "style" "writing-mode" "lr-tb")
(cxml:attribute* "style" "footnote-max-height" "0cm")
(cxml:with-element* ("style" "footnote-sep")
(cxml:attribute* "style" "width" "0.018cm")
(cxml:attribute* "style" "distance-before-sep" "0.101cm")
(cxml:attribute* "style" "distance-after-sep" "0.101cm")
(cxml:attribute* "style" "line-style" "solid")
(cxml:attribute* "style" "adjustment" "left")
(cxml:attribute* "style" "rel-width" "25%")
(cxml:attribute* "style" "color" "#000000")))
(cxml:with-element* ("style" "header-style"))
(cxml:with-element* ("style" "footer-style"))))
(cxml:with-element* ("office" "master-styles")
(cxml:with-element* ("style" "master-page")
(cxml:attribute* "style" "name" "Standard")
(cxml:attribute* "style" "page-layout-name" "Mpm1"))))))))
;;;; Backend
(defun view-odt (file)
(uiop:with-current-directory ((uiop:pathname-directory-pathname file))
(let* ((file-new (format nil "~a" (merge-pathnames (make-pathname :type "odt") (pathname-name file))))
(command "libreoffice"))
(uiop:run-program (list command file-new) :output t))))
(defclass prog-odt-backend (backend)
()
(:default-initargs :view-fn #'view-odt))
(defmethod standard-output-file (file (backend prog-odt-backend))
(merge-pathnames (merge-pathnames (pathname-name file) "odt/prova.odt") file))
(defmethod export-file :around ((file t) (backend prog-odt-backend))
(labels ((tmp-odt-dir (path)
(let ((name (format nil "~a" (a:make-gensym (pathname-name path)))))
(merge-pathnames (concatenate 'string "scliba-odt/" name "/") (uiop:temporary-directory)))))
(let* ((*top-level-document* t)
(outfile (standard-output-file file backend))
(dir (tmp-odt-dir file))
(manifest-file (merge-pathnames "META-INF/manifest.xml" dir))
(content-file (merge-pathnames "content.xml" dir))
(meta-file (merge-pathnames "meta.xml" dir))
(styles-file (merge-pathnames "styles.xml" dir))
(mimetype-file (merge-pathnames "mimetype" dir))
(mimetype "application/vnd.oasis.opendocument.text"))
(unwind-protect
(progn
(uiop:ensure-all-directories-exist (list outfile manifest-file))
;; mimetype
(with-open-file (*standard-output* mimetype-file :direction :output :if-exists :supersede)
(format t mimetype))
;; manifestfile
(write-manifest-file manifest-file mimetype)
;; meta xml file
(write-meta-file meta-file "Andrea De Michele")
;; manifest.rdf TODO
;; thumbnails TODO
;; style file
(write-style-file styles-file)
;; Rivedere usando (call-next-method)
(with-open-file (stream content-file :direction :output :if-exists :supersede :if-does-not-exist :create)
(let ((*outstream* stream)
(*output-file* outfile))
(cxml:with-xml-output (cxml:make-character-stream-sink *outstream* :indentation *xml-indentation*)
(export-document (read-file file) backend))))
(zip:with-output-to-zipfile (zip outfile :if-exists :supersede)
(zip:write-zipentry zip "mimetype" mimetype-file :deflate nil)
(zip:write-zipentry zip "content.xml" content-file)
(zip:write-zipentry zip "meta.xml" meta-file)
(zip:write-zipentry zip "styles.xml" styles-file)
(zip:write-zipentry zip "META-INF/manifest.xml" manifest-file)))
;; pulisci directory temporanea
(dolist (x (list manifest-file content-file meta-file styles-file mimetype-file))
(delete-file x))
(uiop:delete-empty-directory (merge-pathnames "META-INF/" dir))
(uiop:delete-empty-directory dir))
outfile)))
;;;; export-document
(defun odt-table-style ()
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "Tbl")
(cxml:attribute* "style" "family" "table")
(cxml:with-element* ("style" "table-properties")
(cxml:attribute* "style" "width" "17.0cm")
(cxml:attribute* "fo" "margin-left" "0cm")
(cxml:attribute* "style" "page-number" "auto")
(cxml:attribute* "table" "align" "left")
(cxml:attribute* "style" "writing-mode" "lr-tb")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "TblCol")
(cxml:attribute* "style" "family" "table-column"))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "TblR")
(cxml:attribute* "style" "family" "table-row")
(cxml:with-element* ("style" "table-row-properties")
(cxml:attribute* "fo" "keep-together" "auto")
(cxml:attribute* "style" "min-row-height" "36pt")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "TblCell")
(cxml:attribute* "style" "family" "table-cell")
(cxml:with-element* ("style" "table-cell-properties")
(cxml:attribute* "style" "vertical-align" "middle")
(cxml:attribute* "fo" "padding-left" "0.191cm")
(cxml:attribute* "fo" "padding-right" "0.191cm")
(cxml:attribute* "fo" "padding-top" "0cm")
(cxml:attribute* "fo" "padding-bottom" "0cm")
(cxml:attribute* "fo" "border" "0.5pt solid #000000")
(cxml:attribute* "style" "writing-mode" "lr-tb")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "TblCellTop")
(cxml:attribute* "style" "family" "table-cell")
(cxml:with-element* ("style" "table-cell-properties")
(cxml:attribute* "style" "vertical-align" "top")
(cxml:attribute* "fo" "padding-left" "0.191cm")
(cxml:attribute* "fo" "padding-right" "0.191cm")
(cxml:attribute* "fo" "padding-top" "0cm")
(cxml:attribute* "fo" "padding-bottom" "0cm")
(cxml:attribute* "fo" "border" "0.5pt solid #000000")
(cxml:attribute* "style" "writing-mode" "lr-tb")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "TabellaSubH.L")
(cxml:attribute* "style" "family" "table-column")
(cxml:with-element* ("style" "table-column-properties")
(cxml:attribute* "style" "column-width" "12cm")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "TabellaSubH.R")
(cxml:attribute* "style" "family" "table-column")
(cxml:with-element* ("style" "table-column-properties")
(cxml:attribute* "style" "column-width" "5cm")))
(with-style-named-element ("style" "colonna-3")
(attributes* "style" '(("family" "table-column")))
(cxml:with-element* ("style" "table-column-properties")
(cxml:attribute* "style" "column-width" "5.67cm")))
(with-style-named-element ("style" "colonna-2")
(attributes* "style" '(("family" "table-column")))
(cxml:with-element* ("style" "table-column-properties")
(cxml:attribute* "style" "column-width" "8.5cm")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "TabellaSubH.L1")
(cxml:attribute* "style" "family" "table-cell")
(cxml:with-element* ("style" "table-cell-properties")
(cxml:attribute* "style" "vertical-align" "middle")
(cxml:attribute* "fo" "padding-left" "0.191cm")
(cxml:attribute* "fo" "padding-right" "0.191cm")
(cxml:attribute* "fo" "padding-top" "0cm")
(cxml:attribute* "fo" "padding-bottom" "0cm")
(cxml:attribute* "fo" "border-top" "0.5pt solid #000000")
(cxml:attribute* "fo" "border-bottom" "0.5pt solid #000000")
(cxml:attribute* "fo" "border-left" "0.5pt solid #000000")
(cxml:attribute* "style" "writing-mode" "lr-tb")))
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "TabellaSubH.R1")
(cxml:attribute* "style" "family" "table-cell")
(cxml:with-element* ("style" "table-cell-properties")
(cxml:attribute* "style" "vertical-align" "middle")
(cxml:attribute* "fo" "padding-left" "0.191cm")
(cxml:attribute* "fo" "padding-right" "0.191cm")
(cxml:attribute* "fo" "padding-top" "0cm")
(cxml:attribute* "fo" "padding-bottom" "0cm")
(cxml:attribute* "fo" "border-top" "0.5pt solid #000000")
(cxml:attribute* "fo" "border-bottom" "0.5pt solid #000000")
(cxml:attribute* "fo" "border-right" "0.5pt solid #000000")
(cxml:attribute* "style" "writing-mode" "lr-tb"))))
(defun odt-list-style ()
(cxml:with-element* ("style" "style")
(attributes* "style" '(("name" "list-item-paragraph")
("family" "paragraph")
("parent-style-name" "Standard")
("list-style-name" "L1")))
(cxml:with-element* ("style" "paragraph-properties")
(cxml:attribute* "fo" "text-align" "justify"))
(cxml:with-element* ("style" "text-properties")
(attributes* "fo" '(("font-size" "10pt")))))
(cxml:with-element* ("text" "list-style")
(cxml:attribute* "style" "name" "L1")
(cxml:with-element* ("text" "list-level-style-bullet")
(attributes* "text" '(("level" "1")
("style-name" "Dash_20_Symbols")
("bullet-char" "-")))
(cxml:with-element* ("style" "list-level-properties")
(cxml:attribute* "text" "list-level-position-and-space-mode" "label-alignment")
(cxml:with-element* ("style" "list-level-label-alignment")
(attributes* "text" '(("label-followed-by" "space") ("list-tab-stop-position" "0cm")))
(attributes* "fo" '(("text-indent" "0cm") ("margin-left" "0cm"))))))))
(defmethod export-document :around ((document authoring-document) (backend prog-odt-backend))
(with-namespaces ("css3t" "grddl" "xhtml" "formx" "xsi" "rpt" "dc" "chart" "svg" "draw" "text" "oooc" "style" "ooow" "meta" "xlink" "ooo" "fo" "office" "dr3d" "table" "number" "of" "calcext" "tableooo" "drawooo" "dom" "field" "xsd" "math" "form" "script" "xforms")
(cxml:with-element* ("office" "document-content")
(cxml:attribute* "office" "version" *odf-version*)
(cxml:with-element* ("office" "scripts"))
(output-font-face-decls)
(cxml:with-element* ("office" "automatic-styles")
(cxml:with-element* ("style" "style")
(cxml:attribute* "style" "name" "P1")
(cxml:attribute* "style" "family" "paragraph")
(cxml:attribute* "style" "parent-style-name" "Text_20_body"))
(odt-table-style)
(odt-list-style))
(cxml:with-element* ("office" "body")
(cxml:with-element* ("office" "text")
(call-next-method))))))
(defmethod export-document ((document programmazione) (backend prog-odt-backend))
(odt-table (:columns '("TabellaSubH.L" "TabellaSubH.R"))
(odt-table-row ()
(odt-table-cell (:span 2)
(odt-paragraph (:style "Titoli")
(cxml:text "DOCENTE:")
(odt-italic (cxml:text (get-argument document :docente))))))
(odt-table-row ()
(odt-table-cell (:style "TabellaSubH.L1")
(odt-paragraph (:style "Titoli")
(cxml:text "MATERIA: ")
(odt-italic (cxml:text (get-argument document :materia)))))
(odt-table-cell (:style "TabellaSubH.R1")
(odt-paragraph (:style "Titoli-destra")
(cxml:text "CLASSE: ")
(odt-italic (cxml:text (get-argument document :classe)))))))
(cxml:with-element* ("text" "p") (cxml:text " ")))
(defmethod export-document ((document modulo0) (backend prog-odt-backend))
(with-document-arguments (title descrizione prerequisiti metodologie valutazione) document
(odt-table (:columns 3)
(odt-table-row ()
(odt-table-cell (:span 3)
(odt-paragraph (:style "Titoli")
(cxml:text (format nil "MODULO N°~d: " (counter-modulo-val)))
(odt-span ("Unbold")
(cxml:text (format nil "~a" title))))
(odt-paragraph (:style "Titoli-destra")
(cxml:text (format nil "durata ore: " ))
(odt-span ("Unbold") (cxml:text (format nil "~d" (durata-ore document)))))))
(odt-table-row ()
(odt-table-cell (:span 3)
(odt-paragraph () (cxml:text descrizione))))
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Prerequisiti")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Metodologie e strategie operative")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Modalità di valutazione"))))
(odt-table-row ()
(odt-table-cell (:style "TblCellTop")
(export-document prerequisiti backend))
(odt-table-cell (:style "TblCellTop") (export-document metodologie backend))
(odt-table-cell (:style "TblCellTop")(export-document valutazione backend))))))
(defmethod export-document :around ((documnent itemize) (backend prog-odt-backend))
(odt-list () (call-next-method)))
(defmethod export-document :around ((documnent item) (backend prog-odt-backend))
(odt-list-item () (call-next-method)))
(defmethod export-document ((document string) (backend prog-odt-backend))
(cxml:text document))
(defmethod export-document :around ((document bf) (backend prog-odt-backend))
(odt-bold (call-next-method)))
(defmethod export-document :around ((document underbar) (backend prog-odt-backend))
(odt-underline (call-next-method)))
(defmethod export-document :around ((document par) (backend prog-odt-backend))
(odt-paragraph () (call-next-method)))
(defmethod export-document ((document u-didattica0) (backend prog-odt-backend))
(counter-unita-inc)
(with-document-arguments (title attivita obiettivi) document
(odt-table (:columns 2)
(odt-table-row ()
(odt-table-cell (:span 2)
(odt-paragraph (:style "Titoli")
(cxml:text (format nil "UNITÀ DIDATTICA N°~d.~d: " (counter-modulo-val) (counter-unita-val)))
(odt-span ("Unbold")
(cxml:text (format nil "~a" title))))
(odt-paragraph (:style "Titoli-destra")
(cxml:text (format nil "durata ore: " ))
(odt-span ("Unbold") (cxml:text (format nil "~d" (durata-ore document)))))))
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Attività")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Obiettivi"))))
(odt-table-row ()
(odt-table-cell (:style "TblCellTop") (export-document attivita backend))
(odt-table-cell (:style "TblCellTop")(export-document obiettivi backend))))))
(defmethod export-document :around ((document modulo) (backend prog-odt-backend))
(counter-modulo-inc)
(counter-unita-set)
(with-document-arguments (title competenze conoscenze livelli-minimi prerequisiti metodologie valutazione) document
(odt-table (:columns 3)
(odt-table-row ()
(odt-table-cell (:span 3)
(odt-paragraph (:style "Titoli")
(cxml:text (format nil "MODULO N°~d: " (counter-modulo-val)))
(odt-span ("Unbold")
(cxml:text (format nil "~a" title))))
(odt-paragraph (:style "Titoli-destra")
(cxml:text (format nil "durata ore: " ))
(odt-span ("Unbold") (cxml:text (format nil "~d" (durata-ore document)))))))
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Competenze")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Conoscenze")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Livelli minimi"))))
(odt-table-row ()
(odt-table-cell (:style "TblCellTop")
(export-document competenze backend))
(odt-table-cell (:style "TblCellTop") (export-document conoscenze backend))
(odt-table-cell (:style "TblCellTop")(export-document livelli-minimi backend)))
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Prerequisiti")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Metodologie e strategie operative")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Modalità di valutazione"))))
(odt-table-row ()
(odt-table-cell (:style "TblCellTop")
(export-document prerequisiti backend))
(odt-table-cell (:style "TblCellTop") (export-document metodologie backend))
(odt-table-cell (:style "TblCellTop")(export-document valutazione backend)))))
(call-next-method)
(with-document-arguments (recupero valutazione-modulo) document
(odt-table ()
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph (:style "Titoli") (cxml:text "ATTIVITÀ DI RECUPERO"))))
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph () (export-document recupero backend)))))
(odt-table ()
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph (:style "Titoli") (cxml:text "VALUTAZIONE SOMATIVA DEL MODULO"))))
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph () (export-document valutazione-modulo backend)))))))
(defmethod export-document ((document u-didattica) (backend prog-odt-backend))
(counter-unita-inc)
(with-document-arguments (title competenze conoscenze livelli-minimi prerequisiti metodologie valutazione) document
(odt-table (:columns 3)
(odt-table-row ()
(odt-table-cell (:span 3)
(odt-paragraph (:style "Titoli")
(cxml:text (format nil "UNITÀ DIDATTICA N°~d.~d: " (counter-modulo-val) (counter-unita-val)))
(odt-span ("Unbold")
(cxml:text (format nil "~a" title))))
(odt-paragraph (:style "Titoli-destra")
(cxml:text (format nil "durata ore: " ))
(odt-span ("Unbold") (cxml:text (format nil "~d" (durata-ore document)))))))
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Competenze")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Conoscenze")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Livelli minimi"))))
(odt-table-row ()
(odt-table-cell (:style "TblCellTop")
(export-document competenze backend))
(odt-table-cell (:style "TblCellTop") (export-document conoscenze backend))
(odt-table-cell (:style "TblCellTop")(export-document livelli-minimi backend)))
(odt-table-row ()
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Prerequisiti")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Metodologie e strategie operative")))
(odt-table-cell ()
(odt-paragraph (:style "Titoli-centro")
(cxml:text "Modalità di valutazione"))))
(odt-table-row ()
(odt-table-cell (:style "TblCellTop")
(export-document prerequisiti backend))
(odt-table-cell (:style "TblCellTop") (export-document metodologie backend))
(odt-table-cell (:style "TblCellTop")(export-document valutazione backend))))))
;;;; Piano di lavoro notizie generali della classe
;; (defmethod export-document ((document piano-lavoro) (backend prog-odt-backend))
;; (odt-paragraph (:style "Titoli")
;; (cxml:text "ISTITUTO TECNICO AGRARIO STATALE \"Dionisio Anzilotti di Pescia (PT\"" ))
;; ;; (odt-table (:columns '("TabellaSubH.L" "TabellaSubH.R"))
;; ;; (odt-table-row ()
;; ;; (odt-table-cell (:span 2)
;; ;; (odt-paragraph (:style "Titoli")
;; ;; (cxml:text "DOCENTE:")
;; ;; (odt-italic (cxml:text (get-argument document :docente))))))
;; ;; (odt-table-row ()
;; ;; (odt-table-cell (:style "TabellaSubH.L1")
;; ;; (odt-paragraph (:style "Titoli")
;; ;; (cxml:text "MATERIA: ")
;; ;; (odt-italic (cxml:text (get-argument document :materia)))))
;; ;; (odt-table-cell (:style "TabellaSubH.R1")
;; ;; (odt-paragraph (:style "Titoli-destra")
;; ;; (cxml:text "CLASSE: ")
;; ;; (odt-italic (cxml:text (get-argument document :classe)))))))
;; ;; (cxml:with-element* ("text" "p") (cxml:text " "))
;; )
| 39,459 | Common Lisp | .lisp | 720 | 44.979167 | 268 | 0.590078 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 85425a2526a9ac21bbfab337661a00a297cd7051aca64e8fb5b8429c76b1fbbd | 17,899 | [
-1
] |
17,900 | physics.lisp | admich_scliba/physics.lisp | (in-package #:physics)
(set-reader-in-file)
(defmacro define-scliba-physical-constant (name pq &key (precision 3) (exponent 0) (s-o-u *s-o-u*) new-unit)
`(progn
(define-physical-constant ,name ,pq)
(defun ,name (&key (precision ,precision) (exponent ,exponent) (s-o-u ',s-o-u) (new-unit ,new-unit))
(pq-format ,name :precision precision :exponent exponent :s-o-u s-o-u :new-unit new-unit))))
(define-physical-constant big-g
#_6.67408d-11_N*m^2/kg^2)
(define-physical-constant little-g
#_1_gs)
(define-scliba-physical-constant costante-stefan-boltzmann
#_5.67e-8_W/m^2*K^4 :exponent nil :new-unit "W m^{-2} K^{-4}")
(define-scliba-physical-constant carica-e
#_1.602176565e-19_coulomb :exponent nil)
(define-physical-constant raggio-terra
#_6373_km)
(define-scliba-physical-constant k-elettrica
#_8.98755e9_N*m^2/coulomb^2 :exponent nil :new-unit "N m^{2} C^{-2}")
(define-scliba-physical-constant carica-e
#_1.602176565d-19_coulomb)
(defmacro tabella-costanti (name init)
(let ((table-name (alexandria:symbolicate '* name '-tabella*)))
`(progn
(defparameter ,table-name (make-hash-table :test #'equalp))
(dolist (x ,init)
(setf (gethash (car x) ,table-name) (cdr x)))
(defun ,name (element)
(gethash element ,table-name))
(export (list ',name ',table-name)))))
(tabella-costanti densita '(("mercurio" . #_1.36e4_kg/m^3)
("alluminio" . #_2.7e3_kg/m^3)))
(tabella-costanti dilatazione-volumetrica '(("mercurio" . #_1.8e-4_/kelvin)
("acetone" . #_1.4e-3_/kelvin)
("etanolo" . #_1.1e-3_/kelvin)
("benzina" . #_9.4e-3_/kelvin)
("etere" . #_1.6e-3_/kelvin)
("glicerina" . #_5.3e-4_/kelvin)
("olio" . #_7.2e-4_/kelvin)))
(tabella-costanti calore-specifico '(("Alluminio" . #_880_J/kg-K)
("Acciaio" . #_502_J/kg-k)
("Acqua" . #_4186_J/kg-k)
("Aria" . #_1005_J/kg-k)
("Diamante" . #_502_J/kg-k)
("Etanolo" . #_2460_J/kg-k)
("Ferro" . #_460_J/kg-k)
("Ghiaccio" . #_2090_J/kg-k)
("Glicerina" . #_2260_J/kg-k)
("Grafite" . #_720_J/kg-k)
("Idrogeno" . #_14435_J/kg-k)
("Mercurio" . #_139_J/kg-k)
("Olio" . #_2000_J/kg-k)
("Oro" . #_129_J/kg-k)
("Ottone" . #_377_J/kg-k)
("Piombo" . #_130_J/kg-k)
("Polistirene" . #_1450_J/kg-k)
("Rame" . #_385_J/kg-k)
("Stagno" . #_228_J/kg-k)
("Zinco" . #_388_J/kg-k)))
(tabella-costanti conducibilita-termica
'(("argento" . #_460_W/m-K)
("rame" . #_390_W/m-K)
("oro" . #_320_W/m-K)
("alluminio" . #_290_W/m-K)
("ottone" . #_111_W/m-K)
("piombo" . #_35_W/m-K)
("acciaio" . #_17_W/m-K)
("vetro" . #_1_W/m-K)
("acqua" . #_0.6_W/m-K)
("laterizi" . #_0.5_W/m-K)
("carta" . #_0.2_W/m-K)
("legno" . #_0.2_W/m-K)
("sughero" . #_0.05_W/m-K)
("lana" . #_0.04_W/m-K)
("poliuretano" . #_0.03_W/m-K)
("aria" . #_0.02_W/m-K)))
(tabella-costanti resistivita
'(("argento" . #_1.6e-8_ohm-m)
("rame" . #_1.7e-8_ohm-m)
("oro" . #_2.4e-8_ohm-m)
("alluminio" . #_2.7e-8_ohm-m)
("tungsteno" . #_5.6e-8_ohm-m)
("ferro" . #_9.7e-8_ohm-m)
("platino" . #_1.0e-7_ohm-m)
("stagno" . #_1.1e-7_ohm-m)
("costantana" . #_4.9e-7_ohm-m)
("germanio" . #_4.6e-1_ohm-m)
("silicio" . #_6.4e2_ohm-m)
("vetro" . (#_1e11_ohm-m . #_1e15_ohm-m))
("legno" . (#_1e14_ohm-m . #_1e16_ohm-m))
("quarzo" . #_7.5e17_ohm-m)
("teflon" . (#_1e23_ohm-m . #_1e25_ohm-m))))
(tabella-costanti resistivita-coefficiente-termico
'(("argento" . #_0.0038_/K)
("rame" . #_0.00404_/K)
("oro" . #_0.0034_/K)
("alluminio" . #_0.0039_/K)
("tungsteno" . #_0.0045_/K)
("ferro" . #_0.005_/K)
("platino" . #_3.5e-3_/K)
("stagno" . #_0.0045_/K)
("costantana" . #_0.000008_/K)
("germanio" . #_-0.048_/K)
("silicio" . #_-0.075_/K)))
| 4,670 | Common Lisp | .lisp | 104 | 32.5 | 108 | 0.458462 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 493abd2c9e1a0d3d1747c36aae15c7bf73d522e9fa51bb6bfc5e1b845767e8c6 | 17,900 | [
-1
] |
17,901 | esercizio.lisp | admich_scliba/examples/esercizio.lisp | (in-package #:pedb)
(esercizio ()
"In un grafico v-t un moto rettilineo uniforme è rappresentato da: "
(scelte ()
(item (:sol) "una retta orizzontale ")
(item () "una retta qualsiasi ")
(item () "una parabola ")
(item () "una retta verticale ")
)
(soluzione ()
(last-sol) )
)
| 310 | Common Lisp | .lisp | 12 | 22.083333 | 71 | 0.606061 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d4d85feb3adb860c074b841adba34c91782a8505f9ebf5b349766e30aac535d8 | 17,901 | [
-1
] |
17,902 | compito.lisp | admich_scliba/examples/compito.lisp | (in-package #:pedb)
(compito (:title "Verifica di fisica" :rfoot (format nil " ott. 2016 (W43) f~d" *i-random*) :bodyfont 12 :soluzioni t)
(infoform)
(framedtext (:context "location=middle, bodyfont=8pt") [Punteggio min. 1pt. Esercizi 1--6 0.5pt. Esercizi 7--9 2pt. TOT: 10pt])
(randomize ()
(esercizi "q-cin2-ch-00087"
"q-cin2-ch-00088"
"q-cin2-ch-00089"
"q-cin2-ch-00090"
"q-cin2-ch-00091"
"q-cin2-ch-00166"
))
(esercizi "q-cin2-fr-00092")
(soluzioni ()))
| 499 | Common Lisp | .lisp | 14 | 31.785714 | 131 | 0.64657 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0ca7957beb8482cc4401fd42666bcb2cd72f2229cf921d62afb6946be4e184bc | 17,902 | [
-1
] |
17,903 | all-exercise.lisp | admich_scliba/examples/all-exercise.lisp | (in-package #:pedb)
(setf *randomize* nil)
(compito (:title "Eserciziario di fisica" :soluzioni t :rfoot (format nil "Compilato \\date\\ \\currenttime"))
"
\\enablemode[soluzioni]
% \\setupbodyfont[11pt]
\\setupenumerations[esercizio][margin=yes, way=bysection, prefix=yes,prefixsegments=section,width=fit]
\\setupenumerations[soluzione][margin=yes, way=bysection, prefix=yes,prefixsegments=section,width=fit]"
(loop for topic in *esercizi-argomenti*
collect
(section (:title (car topic))
(append
(loop for ese in (esercizi-di (cdr topic))
collect
(list (input-esercizio ese)
(format nil "~&\\rightaligned{\\color[middlegray]{~A}}~%" (pathname-name ese))
))
(list "
\\doifmode{soluzioni}{\\subject{Soluzioni}
\\selectblocks[soluzione][criterium=section]}"))
)))
| 844 | Common Lisp | .lisp | 21 | 35.285714 | 110 | 0.690798 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | af1c239b7d0c1621a4a1c39ce386e0bb0e73caadfa16db69ae2034d4a9a9fa25 | 17,903 | [
-1
] |
17,904 | convert.lisp | admich_scliba/utils/convert.lisp | (in-package #:scliba)
(ql:quickload "split-sequence")
(defvar *in-string* nil)
(defvar *in-item* nil)
(defun remove-comment (line)
"remove comment"
(let ((pos% (position #\% line))
(pos%% (search "\\%" line)))
(cond
((not pos%) line)
((not pos%%) (subseq line 0 (position #\% line)))
((= pos% (+ 1 pos%%)) (concatenate 'string (subseq line 0 (+ 1 pos%)) (remove-comment (subseq line (+ 1 pos%))))))))
(defun pre-process-line (line)
"process line"
(let ((line (substitute #\Space #\Tab (string-trim '(#\Space #\Linefeed #\Return #\Newline) (remove-comment line)))))
(cond
((search "\\startcomponent" line) "")
((search "\\stopcomponent" line) "")
((search "\\project" line) "")
((search "\\product" line) "")
((search "\\usepath" line) "")
((search "\\doifmode{esercizio}{\\printsoluzioni}" line) "")
(t (format nil "~a" line)))))
(defun final-process-line (line)
(ppcre:regex-replace-all "\"" (ppcre:regex-replace-all "[\\\\ ~]" line "\\&\\&") "\\\""))
(defun exit-from-string ()
(when *in-string* (format t "\"") (setf *in-string* nil)))
(defun exit-from-item ()
(when *in-item* (format t ")~%") (setf *in-item* nil)))
(defun analyse-word (word)
(cond
; ((string= "\\startesercizio" word) (progn (exit-from-string) (format t "~a~%""(esercizio ()")))
((string= "\\startesercizio" word) (progn (exit-from-string) (format t "~%")))
((string= "\\stopesercizio" word) (progn (exit-from-string) (format t ")~%")))
((string= "\\startformula" word) (progn (exit-from-string) (format t "~%~a~%""(formula ()")))
((string= "\\stopformula" word) (progn (exit-from-string) (format t ")~%")))
((string= "\\startMPcode" word) (progn (exit-from-string) (format t "~%~a~%""(mpcode ()")))
((string= "\\stopMPcode" word) (progn (exit-from-string) (format t ")~%")))
((string= "\\startsoluzione" word) (progn (exit-from-string) (format t "~a~%""(soluzione ()")))
((string= "\\stopsoluzione" word) (progn (exit-from-string) (format t ")~%")))
((string= "\\beginsoluzione" word) (progn (exit-from-string)))
((string= "\\endsoluzione" word) (progn (exit-from-string)))
((string= "\\startchoices" word) (progn (exit-from-string) (format t "~%~a~%" "(scelte ()")))
((string= "\\stopchoices" word) (progn (exit-from-string) (exit-from-item) (format t ")~%")))
((string= "\\startparts" word) (progn (exit-from-string) (format t "~%~a~%" "(parti ()")))
((string= "\\stopparts" word) (progn (exit-from-string) (exit-from-item) (format t ")~%")))
((ppcre:scan "\\item\\[.*\\]" word) (progn (exit-from-string) (exit-from-item) (format t "~a " "(item (:sol)") (setf *in-item* t)))
((ppcre:scan "\\in\\[.*\\]" word) (progn (exit-from-string) (format t "~a " "(last-sol)")))
((string= "\\item" word) (progn (exit-from-string) (exit-from-item) (format t "~a " "(item ()") (setf *in-item* t)))
((ppcre:scan "\\var\\[.*\\]\\[.*\\]\\[.*\\]" word)
(progn (format t "~:[\"~;~]~a%~% " *in-string* (final-process-line word))
(setf *in-string* t)))
((ppcre:scan "\\dervar\\[.*\\]\\[.*\\]\\[.*\\]" word)
(progn (format t "~:[\"~;~]~a%~% " *in-string* (final-process-line word))
(setf *in-string* t)))
(t (progn
(format t "~:[\"~;~]~a " *in-string* (final-process-line word))
(setf *in-string* t)))))
(defun analyse-line (line)
(let ((words (split-sequence:split-sequence #\Space line :remove-empty-subseqs t)))
(loop with out = ""
for w in words
do ;; (setf out (concatenate 'string out (analyse-word w)))
;; finally (return out)
(analyse-word w)
)))
(defun process-line (line stream)
(analyse-line (pre-process-line line)))
(defun convert-from-context (file)
"convert the context file to lisp"
(setf *in-item* nil *in-string* nil)
(let ((f (merge-pathnames *esercizi-directory* (make-pathname :name file :type "tex"))))
(with-open-file (stream f)
(format t "~a~%""(esercizio ()")
(loop for line = (read-line stream nil 'foo)
until (eq line 'foo)
do (process-line line stream)))))
(defun convert-from-context-tofile (file)
(with-open-file (*standard-output* (merge-pathnames *esercizi-directory* (make-pathname :name file :type "lisp")) :direction :output :if-exists :supersede)
(convert-from-context file)))
(defun convert-multiple-from-context-tofile (n1 n2)
(loop for i from n1 to n2
do (convert-from-context-tofile (pathname-name (esercizio-numero i)))))
(defun test-convert (&optional (n1 1) (n2 2))
(compito (:title "Prova conversione" :soluzioni t)
(loop for i from n1 to n2
append
(list (input-esercizio (esercizio-numero i))
(format nil "~&\\rightaligned{\\color[middlegray]{~A}}~%" (pathname-name (esercizio-numero i)))))
(soluzioni ())))
#|
(with-open-file (stream (merge-pathnames *compiti-directory* "testauto.tex") :direction :output :if-exists :supersede :if-does-not-exist :create)
(export-document (test-convert 1 2) :context stream))
|#
| 5,034 | Common Lisp | .lisp | 94 | 49.12766 | 157 | 0.606504 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 8b2c6d6548f1ee49d51981f0abfcfa8c4dde2593d19fef52db45238f17aeb90a | 17,904 | [
-1
] |
17,905 | package.lisp | admich_scliba/gui/package.lisp | ;;
(in-package #:cl-user)
(defpackage #:scliba-gui
(:use #:clim #:clim-lisp #:scliba #:scliba-pedb #:scliba-ptnh)
(:export #:scliba-gui))
| 144 | Common Lisp | .lisp | 5 | 26.6 | 64 | 0.656934 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | cb9899b1802d6c5d2aac93150fb1d24997b28b5163a932124f82650f131bf14a | 17,905 | [
-1
] |
17,906 | climacs-scliba-syntax.lisp | admich_scliba/gui/climacs-scliba-syntax.lisp | (defpackage :climacs-scliba-syntax
(:use :clim-lisp :clim :drei-buffer :drei-base :drei-syntax :flexichain :drei :drei-fundamental-syntax :drei-lisp-syntax :drei-lr-syntax)
(:shadowing-import-from :drei-lisp-syntax :form)
(:export #:scliba-syntax))
(in-package :climacs-scliba-syntax)
(define-syntax-command-table scliba-table
:errorp nil
:inherit-from '(lisp-table))
(define-syntax scliba-syntax (lisp-syntax)
()
(:name "sCLiba")
(:pathname-types "scl")
(:command-table scliba-table))
(defmethod name-for-info-pane ((syntax scliba-syntax) &key view)
(format nil "sCLiba~@[:~(~A~)~]"
(drei-lisp-syntax::provided-package-name-at-mark syntax (if (typep view 'point-mark-view)
(point view)
0))))
(defmethod display-syntax-name ((syntax scliba-syntax) (stream extended-output-stream) &key view)
(princ "sCLiba:" stream) ; FIXME: should be `present'ed
; as something.
(let ((package-name (drei-lisp-syntax::provided-package-name-at-mark syntax (if (typep view 'point-mark-view)
(point view)
0))))
(if (find-package package-name)
(with-output-as-presentation (stream (find-package package-name) 'expression)
(princ package-name stream))
(with-text-face (stream :italic)
(princ package-name stream)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; LEXER
(define-lexer-state lexer-scliba-state (lexer-toplevel-state)
()
(:documentation "In this state, the lexer assumes it can skip
whitespace and should recognize ordinary lexemes of the language"))
(defclass scribble-start-lexeme (drei-lisp-syntax::lisp-lexeme) ())
(defclass scribble-stop-lexeme (drei-lisp-syntax::lisp-lexeme) ())
(defclass scribble-unmatched-stop-lexeme (drei-lisp-syntax::lisp-lexeme) ())
(defmethod lex ((syntax scliba-syntax) (state drei-lisp-syntax::lexer-toplevel-state) scan)
(macrolet ((fo () `(forward-object scan)))
(let ((object (object-after scan)))
(case object
(#\[ (fo) (make-instance 'scribble-start-lexeme))
(#\] (fo) (make-instance 'scribble-unmatched-stop-lexeme))
(t (call-next-method))
))))
(defmethod lex ((syntax scliba-syntax) (state lexer-scliba-state) scan)
(macrolet ((fo () `(forward-object scan)))
(let ((object (object-after scan)))
(cond ((eql object #\]) (fo) (make-instance 'scribble-stop-lexeme))
((eql object #\\)
(fo)
(unless (end-of-buffer-p scan)
(fo))
(make-instance 'drei-lisp-syntax::delimiter-lexeme))
((constituentp object)
(loop until (or (end-of-buffer-p scan)
(not (constituentp (object-after scan))))
do (fo))
(make-instance 'drei-lisp-syntax::word-lexeme))
(t (fo) (make-instance
(if (characterp object)
'drei-lisp-syntax::delimiter-lexeme
'drei-lisp-syntax::literal-object-delimiter-lexeme)))))))
;; parse (action? new-state parser-state
(defclass scribble-form (drei-lisp-syntax::form-lexeme) ())
(defclass complete-scribble-form (scribble-form drei-lisp-syntax::complete-form-mixin) ())
(defclass incomplete-scribble-form (scribble-form drei-lisp-syntax::incomplete-form-mixin) ())
(define-parser-state |[ word* | (lexer-scliba-state parser-state) ())
(define-parser-state |[ word* ] | (lexer-toplevel-state parser-state) ())
(defmacro define-new-scliba-state ((state parser-symbol) &body body)
`(defmethod new-state ((syntax scliba-syntax) (state ,state) (tree ,parser-symbol))
,@body))
(define-new-scliba-state (|[ word* | drei-lisp-syntax::word-lexeme) |[ word* |)
(define-new-scliba-state (|[ word* | drei-lisp-syntax::delimiter-lexeme) |[ word* |)
(define-new-scliba-state (drei-lisp-syntax::form-may-follow scribble-start-lexeme) |[ word* |)
(define-new-scliba-state (|[ word* | scribble-stop-lexeme) |[ word* ] |)
(defmacro define-scliba-action ((state lexeme) &body body)
`(defmethod action ((syntax scliba-syntax) (state ,state) (lexeme ,lexeme))
,@body))
;;; reduce according to the rule form -> " word* "
(define-scliba-action (|[ word* ] | t)
(reduce-until-type complete-scribble-form scribble-start-lexeme))
;;; reduce at the end of the buffer
(define-scliba-action (|[ word* | (eql nil))
(reduce-until-type incomplete-scribble-form scribble-start-lexeme t))
;; ;highlight
(define-syntax-highlighting-rules scliba-style-highlighting
(drei-lisp-syntax::error-lexeme (*error-drawing-options*))
(drei-lisp-syntax::string-form (*string-drawing-options*))
(scribble-form (*string-drawing-options*))
(drei-lisp-syntax::comment (*comment-drawing-options*))
(drei-lisp-syntax::literal-object-form (:options :function (object-drawer)))
(drei-lisp-syntax::complete-token-form (:function #'(lambda (view form)
(cond ((drei-lisp-syntax::symbol-form-is-keyword-p (syntax view) form)
*keyword-drawing-options*)
((drei-lisp-syntax::symbol-form-is-macrobound-p (syntax view) form)
*special-operator-drawing-options*)
((drei-lisp-syntax::symbol-form-is-boundp (syntax view) form)
*special-variable-drawing-options*)
(t +default-drawing-options+)))))
(drei-lisp-syntax::parenthesis-lexeme (:function #'drei-lisp-syntax::parenthesis-highlighter))
(drei-lisp-syntax::reader-conditional-positive-form
(:function (drei-lisp-syntax::reader-conditional-rule-fn t *comment-drawing-options*)))
(drei-lisp-syntax::reader-conditional-negative-form
(:function (drei-lisp-syntax::reader-conditional-rule-fn nil *comment-drawing-options*))))
(defmethod syntax-highlighting-rules ((syntax scliba-syntax))
'scliba-style-highlighting)
;; (setq *syntax-highlighting-rules* 'my-style-highlighting
;; )
(defmethod form-to-object ((syntax scliba-syntax) (form scribble-form)
&key &allow-other-keys)
(values (read-from-string "PIPPO"))
;; (values (read-from-string (concatenate 'string (form-string syntax form) "\"")))
)
;; command
(setf scliba::*command-pdf-viewer* "zathura")
(define-command (com-compila-guarda-file :name t :command-table scliba-table) ()
(let ((file (filepath (buffer (current-view)))))
(scliba:compila-guarda file scliba:*default-backend*)))
(esa:set-key 'com-compila-guarda-file
'scliba-table
'((#\c :control) (#\c :control)))
| 6,704 | Common Lisp | .lisp | 123 | 46.487805 | 139 | 0.646771 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 80d02f3909b43db696b287299d7fec4a3246de28beff230ae43ab35ad2be0440 | 17,906 | [
-1
] |
17,907 | scliba-gui.lisp | admich_scliba/gui/scliba-gui.lisp | ;;
(in-package #:scliba-gui)
(defparameter *pedb* (make-hash-table))
(defclass scliba-document ( )
()
(:documentation "general scliba-document"))
(defclass scliba-file-document (scliba-document)
((file :accessor document-file
:initarg :file
:type 'pathname))
(:documentation "scliba-document stored in a file"))
(defclass scliba-exercise-document (scliba-file-document)
((number :accessor exercise-number
:initarg :number
:type 'integer)
(subject :accessor exercise-subject
:initarg :subject
:documentation "subject of the exercise")
(type :initarg :type
:accessor exercise-type
:documentation "type of exercise"))
(:documentation "scliba exercise"))
(defun make-exercise (filepath)
(let* ((exe (make-instance 'scliba-exercise-document :file filepath))
(filename-parts (ppcre:split "-" (pathname-name (document-file exe)))))
(setf (exercise-number exe) (parse-integer (fourth filename-parts))
(exercise-subject exe) (second filename-parts)
(exercise-type exe) (third filename-parts))
exe))
(defun pedb-preview-file (exe)
(merge-pathnames (make-pathname :type "pdf") (standard-output-file (document-file exe) *default-backend*)))
(defun push-exercise (exercise)
(setf (gethash (document-file exercise) *pedb*) exercise))
(defun refresh-pedb ()
(dolist (exe (uiop:directory-files *esercizi-directory* "*.lisp"))
(push-exercise (make-exercise exe)))
(update-list-exercises))
(defclass tabular-view (view)
())
(defconstant +tabular-view+ (make-instance 'tabular-view))
(define-presentation-type scliba-exercise-document ())
(define-presentation-method present (obj (type scliba-exercise-document) stream view &key)
(declare (ignore view))
(format stream "~d ~a ~a ~a" (exercise-number obj) (pathname-name (document-file obj)) (exercise-type obj) (exercise-subject obj))
)
(define-presentation-method present (obj (type scliba-exercise-document) stream (view tabular-view) &key)
(declare (ignore view))
(formatting-row ()
(formatting-cell () (present (exercise-number obj)))
(formatting-cell () (present (pathname-name (document-file obj))))
(formatting-cell () (present (exercise-type obj)))
(formatting-cell () (present (exercise-subject obj)))))
(defclass file-view (view)
((%file :initarg :file :reader file :initform nil)))
(defclass pdf-view (file-view)
())
(defparameter *file-view* (make-instance 'file-view))
(defgeneric display-pane-with-view (frame pane view))
;;;; command table
(define-command-table exercise-selector-commands)
(define-command (com-next-exercise :name "Next"
:command-table exercise-selector-commands
:keystroke (#\i :control)
:menu t
:name t
:provide-output-destination-keyword nil
)
()
(format (find-pane-named (find-application-frame 'scliba-gui) 'inter) "PIPPO"))
(define-application-frame scliba-gui ()
((%filter-criteria :accessor filter-criteria
:initform nil)
(%listed-exercises :accessor listed-exercises
:initform nil)
(%current-exercise :accessor current-exercise
:initform nil))
(:command-table (scliba-gui
:inherit-from (exercise-selector-commands)
:inherit-menu t))
(:menu-bar t)
(:panes
(list :application
:display-function 'display-list
:min-width 10
:width 400
:max-width 800
:scroll-bars :both)
(main :application
:display-function 'display-main
:scroll-bars :both
:default-view *file-view*)
(button :application
:display-time :command-loop
:display-function 'display-button
:max-height 5)
(inter :interactor
:max-height 100))
(:layouts (default
(vertically ()
button
(horizontally ()
;; (1/4 list)
list
(make-pane 'clim-extensions:box-adjuster-gadget)
main
;; (3/4 main)
)
(make-pane 'clim-extensions:box-adjuster-gadget)
inter)
)))
(defun scliba-gui (&key new-process)
(clim-sys:make-process (lambda () (run-frame-top-level (make-application-frame 'scliba-gui)) :name "scliba-gui")))
(defun display-main (frame pane)
(display-pane-with-view frame pane (stream-default-view pane)))
(defun cat (file &optional (stream *standard-output*))
(with-open-file (input file )
(loop for line = (read-line input nil nil)
while line
do
(write-string line stream)
(terpri stream))))
(defmethod display-pane-with-view (frame pane (view file-view))
(let ((file (file view)))
(if file
(cat file pane)
(if (current-exercise *application-frame*)
(cat (document-file (current-exercise *application-frame*)) pane)
(write-string "no file" pane)))))
(defmethod display-pane-with-view (frame pane (view pdf-view))
(let ((file (file view)))
(if (uiop:file-exists-p file)
(progn
(format pane "~a~%" file)
(uiop:run-program (format nil "mutool draw -o /home/admich/tmp/tmp.png ~a 1" file))
(let ((pattern (make-pattern-from-bitmap-file "/home/admich/tmp/tmp.png")))
(multiple-value-bind (x y) (stream-cursor-position pane)
(draw-pattern* pane pattern x y)
(stream-increment-cursor-position pane 0 (pattern-height pattern)))))
(format pane "no pdf file: ~a" file))))
(defun update-list-exercises ()
(setf (listed-exercises *application-frame*)
(loop for exe being the hash-value of *pedb*
when (exe-match-criteria exe) collect exe
))
(setf (current-exercise *application-frame*) (first (listed-exercises *application-frame*) ))
)
(defun display-list (frame pane)
(list-exercises frame pane))
(defun list-exercises (frame pane &key (directory *esercizi-directory*))
(let (current-presentation)
(formatting-table (pane :x-spacing 50 :y-spacing 15)
(loop for exe in (listed-exercises *application-frame*)
do
(if (equal exe (current-exercise *application-frame*))
(surrounding-output-with-border (pane :shape :rounded :background +red+) (setf current-presentation (present exe 'scliba-exercise-document :stream pane :view +tabular-view+)))
(present exe 'scliba-exercise-document :stream pane :view +tabular-view+)))
;; (loop for exe being the hash-value of *pedb* do
;; (when (exe-match-criteria exe)
;; (surrounding-output-with-border (pane :shape :rounded :background +red+)
;; (present exe 'scliba-exercise-document :stream pane :view +tabular-view+))
;; ))
)
(format pane "~%")
(when current-presentation (multiple-value-bind (x y) (output-record-position current-presentation)
(scroll-extent pane 0 y)))
))
(defun exe-match-criteria (exe)
(if (filter-criteria *application-frame*)
(equal (filter-criteria *application-frame*) (exercise-subject exe)) t))
(defun display-button (frame pane)
(let ((medium (sheet-medium pane)))
(with-text-style (medium (make-text-style :sans-serif :bold :huge)) (format pane "sCLiba GUI"))))
(define-scliba-gui-command (com-refresh-pedb :name t :menu t) ()
(refresh-pedb))
(define-scliba-gui-command (com-next-exercise :name t :menu t :keystroke (#\n :control))
()
(let* ((exercises (listed-exercises *application-frame*))
(n-exe (position (current-exercise *application-frame*) exercises)))
(setf (current-exercise *application-frame*) (nth (mod (1+ n-exe) (length exercises)) exercises))
))
(define-scliba-gui-command (com-previous-exercise :name t :menu t :keystroke (#\p :control))
()
(let* ((exercises (listed-exercises *application-frame*))
(n-exe (position (current-exercise *application-frame*) exercises)))
(setf (current-exercise *application-frame*) (nth (mod (1- n-exe) (length exercises)) exercises))
))
(define-scliba-gui-command (com-show-exercise :name t :menu t)
((exe 'scliba-exercise-document :prompt "Esercizio" :gesture :select))
(setf (current-exercise *application-frame*) exe)
;; (setf (stream-default-view (find-pane-named *application-frame* 'main)) (make-instance 'file-view :file (document-file exe)))
)
(define-gesture-name :view :pointer-button-press (:middle :control))
(define-scliba-gui-command (com-preview-exercise :name t :menu t)
((exe 'scliba-exercise-document :prompt "Esercizio" :gesture :view))
(setf (stream-default-view (find-pane-named *application-frame* 'main)) (make-instance 'pdf-view :file (pedb-preview-file exe))))
(define-scliba-gui-command (com-edit-exercise :name t :menu t)
((exe 'scliba-exercise-document :prompt "Esercizio" :gesture :edit))
(climacs:edit-file (document-file exe)))
(define-gesture-name :compile :pointer-button-press (:left :control))
(define-scliba-gui-command (com-compile-exercise :name t :menu t)
((exe 'scliba-exercise-document :prompt "Esercizio" :gesture :compile))
(pedb:compila-esercizio-preview (document-file exe))
(format *query-io* "compilato esercizio: ~a" exe))
(define-scliba-gui-command (com-new-compito :name t :menu t)
((file-name 'string :prompt "File name (es: 16-bio-i-q1c1)"))
(let ((file (merge-pathnames file-name *compiti-directory*)))
(pedb:new-compito file)
(format (frame-query-io *application-frame*) "Creato il compito ~a" file)
(climacs:edit-file file)))
(define-scliba-gui-command (com-new-eserciziario :name t :menu t)
((file-name 'string :prompt "File name (es: esercizi-argomento)"))
(let ((file (merge-pathnames file-name *eserciziari-directory*)))
(pedb:new-compito file)
(format (frame-query-io *application-frame*) "Creato l'eserciziario ~a" file)
(climacs:edit-file file)))
(define-presentation-type-abbreviation esercizi-argomenti ()
`(completion ,(cons '("Tutti" . nil) *esercizi-argomenti*)))
(define-scliba-gui-command (com-filter-exercises :name t :menu t)
((arg 'esercizi-argomenti :prompt "Argomento:"))
(setf (filter-criteria *application-frame*) (cdr arg))
(format (find-pane-named *application-frame* 'inter) "Filtro: ~a" (car arg))
(update-list-exercises))
(define-scliba-gui-command (com-open-directory :name t :menu t)
((directory 'pathname :prompt "Directory: "))
(format *query-io* "~a" directory))
(define-scliba-gui-command (com-quit :name t :menu t :keystroke (#\q :control)) ()
(frame-exit *application-frame*))
| 10,319 | Common Lisp | .lisp | 227 | 40.9163 | 183 | 0.696038 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7676d7a1e17fc1b7270adb1957dd406992c7dab6daac7eea501f8df31312b83c | 17,907 | [
-1
] |
17,908 | scliba-test.lisp | admich_scliba/t/scliba-test.lisp | (defpackage scliba-test
(:use #:cl #:scliba #:fiveam))
(in-package #:scliba-test)
(def-suite scliba-test :description "Test suite for sCLiba")
(in-suite scliba-test)
(test compito
(let ((sclibafile (uiop:merge-pathnames* "examples/compito.lisp" (asdf:system-source-directory "scliba"))))
(finishes (read-file sclibafile))
(dolist (x (list 'context-backend 'aut-context-backend 'html-backend))
(finishes (export-file sclibafile (make-instance x))))
(finishes (view-html (standard-output-file sclibafile (make-instance 'html-backend))))
(finishes (compila-context (standard-output-file sclibafile (make-instance 'context-backend))))
(finishes (compila-context (standard-output-file sclibafile (make-instance 'aut-context-backend))))
(finishes (view-pdf (standard-output-file sclibafile (make-instance 'context-backend))))
(finishes (view-pdf (standard-output-file sclibafile (make-instance 'aut-context-backend))))))
(test all-exercise
(let ((sclibafile (uiop:merge-pathnames* "examples/all-exercise.lisp" (asdf:system-source-directory "scliba"))))
(finishes (read-file sclibafile))
(dolist (x (list 'context-backend 'aut-context-backend 'html-backend))
(finishes (export-file sclibafile (make-instance x))))
(finishes (view-html (standard-output-file sclibafile (make-instance 'html-backend))))
(finishes (compila-context (standard-output-file sclibafile (make-instance 'context-backend))))
(finishes (compila-context (standard-output-file sclibafile (make-instance 'aut-context-backend))))
(finishes (view-pdf (standard-output-file sclibafile (make-instance 'context-backend))))
(finishes (view-pdf (standard-output-file sclibafile (make-instance 'aut-context-backend))))))
| 1,753 | Common Lisp | .lisp | 25 | 65.96 | 114 | 0.74173 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5a4788129b606c8ce17d9800e6e11404bc0d9b36bb1a427168cc80c18915c3bf | 17,908 | [
-1
] |
17,909 | scliba-test.asd | admich_scliba/scliba-test.asd | (asdf:defsystem #:scliba-test
:description "Test suite for sCLiba"
:author "Andrea De Michele <[email protected]>"
:license "GPL v3"
:depends-on (#:scliba #:fiveam)
:serial t
:components ((:module "t"
:serial t
:components ((:file "scliba-test")))))
| 292 | Common Lisp | .asd | 9 | 27.888889 | 59 | 0.650177 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0893100bb53092be30f3b073fc65f90468c421c1ab3fd8a0d9a23e4e21deb3df | 17,909 | [
-1
] |
17,910 | scliba-gui.asd | admich_scliba/scliba-gui.asd | (asdf:defsystem #:scliba-gui
:description "A CLIM gui for sCLiba authoring system in Common Lisp"
:author "Andrea De Michele <[email protected]>"
:license "GPL v3"
:depends-on (#:mcclim #:scliba #:climacs)
:serial t
:components ((:module "gui"
:serial t
:components ((:file "package")
(:file "scliba-gui")
(:file "climacs-scliba-syntax")))))
| 455 | Common Lisp | .asd | 11 | 31 | 70 | 0.566591 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 11cc23fe74cf7a2243f55a4fdceaa9aa9456522584c213b88ab33ba6e8e372ad | 17,910 | [
-1
] |
17,911 | scliba.asd | admich_scliba/scliba.asd | ;;;; scliba.asd
(asdf:defsystem #:scliba
:description "A authoring system in Common Lisp"
:author "Andrea De Michele <[email protected]>"
:license "GPL v3"
:depends-on (#:uiop #:alexandria #:cl-ppcre #:local-time #:scribble #:physical-dimension #:cl-who #:cxml #:zip)
:serial t
:components ((:file "package")
(:file "macro")
(:file "scliba")
(:file "base")
(:file "backend")
(:file "backend-exporter")
(:file "physical-quantity")
(:file "physics")
(:file "pedb")
(:file "ptnh")
(:file "itas")
(:file "itas-odt")))
| 675 | Common Lisp | .asd | 19 | 26.578947 | 113 | 0.53681 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a84925e2df2ba39bbc417b75cccdba744272bb5acef4c07af2522dc6deabd0aa | 17,911 | [
-1
] |
17,912 | scliba-mode.el | admich_scliba/scliba-mode.el |
(define-derived-mode scliba-mode lisp-mode "sCLiba"
"major mode for editing sCLiba code."
)
(defvar scliba-mode-map (make-sparse-keymap)
"Keymap for scliba-mode.")
(define-key scliba-mode-map "\C-c\C-c" 'scliba-compila-guarda-file)
(define-skeleton scliba-skeleton-pq-format
"Box per chiedere il Nome degli alunni nelle verifiche"
nil
"(pq-format " _ ")")
(define-skeleton scliba-skeleton-imath
"Box per chiedere il Nome degli alunni nelle verifiche"
nil
"(imath " _ ")")
(define-abbrev-table 'scliba-mode-abbrev-table
'(("pqf" "" scliba-skeleton-pq-format)
("imath" "" scliba-skeleton-imath)))
| 631 | Common Lisp | .cl | 17 | 34.058824 | 68 | 0.726368 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | dca7b8d05ef5a58774394cd05598b5a550dccbae6e654d27003ddfa7d2d858e2 | 17,912 | [
-1
] |
17,914 | scliba.el | admich_scliba/scliba.el | (require 'cl)
(load "skeletons-cl-authoring" nil)
(defun pedb-store-dir ()
(substring (second (slime-eval '(swank:eval-and-grab-output "(directory-namestring pedb::*esercizi-directory*)"))) 1 -1))
(defun pedb-preview-dir ()
(substring (second (slime-eval '(swank:eval-and-grab-output "(directory-namestring pedb::*esercizi-preview-directory*)"))) 1 -1))
(defvar *pedb-raccolta-buffer* nil "nome file e buffer del compito associato")
(defun pedb-esercizi-argomenti ()
(car (read-from-string (second (slime-eval '(swank:eval-and-grab-output "pedb::*esercizi-argomenti*"))))))
(defun pedb-esercizi-tipi ()
(car (read-from-string (second (slime-eval '(swank:eval-and-grab-output "pedb::*esercizi-tipi*"))))))
(defun pedb-max-num ()
"return the maximum number of exercize"
(apply 'max (mapcar (lambda (x) (string-to-number (substring x -9 -4))) (remove-if-not (lambda (x) (string-match-p "^q-.*.[0-9]\." x)) (directory-files (pedb-store-dir))))))
(defun pedb-new-esercizio ()
(interactive)
(let* ((argomento (cdr (assoc (completing-read "Argomento: " (pedb-esercizi-argomenti)) (pedb-esercizi-argomenti))))
(tipo (cdr (assoc (completing-read "Tipo: " (pedb-esercizi-tipi)) (pedb-esercizi-tipi))))
(esnum (+ 1 (pedb-max-num)))
(name (format "q-%s-%s-%05d" argomento tipo esnum))
(fname (concat name ".lisp")))
(find-file (expand-file-name fname (pedb-store-dir)))
(lisp-mode)
(pcase tipo
("ch" (cl-auth-skeleton-esercizio-scelte))
;; ("tf" (context-skeleton-esercizio-truefalse))
(_ (cl-auth-skeleton-esercizio)))))
(defun pedb-new-compito ()
(interactive)
(let* ((fname (read-from-minibuffer "File Name (es: 15-al-i-q1c1.lisp): "))
(file-to-open
(second (slime-eval `(swank:eval-and-grab-output
,(concat "(pedb::new-compito (merge-pathnames \"" fname "\" pedb::*compiti-directory*))"))))))
(find-file (read file-to-open))
(lisp-mode)))
;; (defun exe-new-esercitazione ()
;; (interactive)
;; (let ((fname (read-from-minibuffer "File Name (es: esercizi-argomento.tex): ")))
;; (find-file (expand-file-name fname *exe-esercitazioni-dir*))
;; (context-mode)
;; (context-skeleton-esercitazione)))
(defun pedb-all-exercises ()
"Return all the exercises"
(first (read-from-string
(second
(slime-eval
'(swank:eval-and-grab-output "(map 'list (lambda (x) (format nil \"~a\" x)) (pedb:tutti-esercizi))"))))))
(defvar pedb-list-mode-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map tabulated-list-mode-map)
(define-key map "e" 'exe-edit-exercise)
(define-key map (kbd "RET") 'exe-edit-exercise)
(define-key map "E" 'pedb-new-esercizio)
(define-key map "c" 'pedb-genera-esercizio)
(define-key map "v" 'pedb-view-exercise)
(define-key map "V" 'pedb-compile-and-view-exercise)
(define-key map "N" 'pedb-new-compito)
(define-key map "s" 'pedb-set-raccolta)
;; (define-key map "o" 'exe-open-compilation)
(define-key map "a" 'pedb-add-esercizio)
;; (define-key map "A" 'exe-add-exercise-component)
map)
"Local keymap for `pedb-list-mode' buffers.")
;; (defun exe-open-compilation ()
;; "open the compilation buffer"
;; (interactive)
;; (switch-to-buffer-other-window *exe-compilation-buffer*))
(defun pedb-set-raccolta (arg buf)
"Set the compito or esercitazione buffer"
(interactive "P\nbbuffer:")
(let ((buf-db (get-buffer (concat "*PEDB*:" *pedb-raccolta-buffer*))))
(with-current-buffer buf-db
(setq *pedb-raccolta-buffer* buf)
(rename-buffer (concat "*PEDB*:" *pedb-raccolta-buffer*)))))
(define-derived-mode pedb-list-mode tabulated-list-mode "PEDB"
"Major mode for browsing a list of exercise.
Letters do not insert themselves; instead, they are commands."
; \\<package-menu-mode-map>
; \\{package-menu-mode-map}
; "
(setq tabulated-list-format
`[("N." 8 t)
("File" 20 t)
("Argomento" 20 t)
("Tipoplogia" 15 t)
("Modificato" 15 t)])
(setq tabulated-list-padding 2)
;(add-hook 'tabulated-list-revert-hook 'package-menu--refresh nil t)
(tabulated-list-init-header))
(defun pedb-exe-get-topic (exe)
"Return the argument of an exercise"
(second (split-string exe "-")))
(defun pedb-exe-get-number (exe)
"Return the number of an exercise"
(fourth (split-string exe "[-.]")))
(defun pedb-exe-get-type (exe)
"Return the type of an exercise"
(third (split-string exe "[-.]")))
(defun pedb-exe-get-modified (exe)
"Return the last modified date of an exercise"
(format-time-string "%Y-%m-%d %H:%M" (sixth (file-attributes exe))))
(defun exe-edit-exercise ()
(interactive)
(message "%s" (tabulated-list-get-id))
(find-file-other-window (tabulated-list-get-id)))
(defun pedb-add-esercizio ()
(interactive)
(let ((exe (tabulated-list-get-id)))
(with-current-buffer *pedb-raccolta-buffer*
(insert "\"" (subseq exe 0 -5) "\" \n"))))
(defun pedb-esercizio--print-info (exe)
(let ((exe-name (file-name-base exe)))
(list exe `[,(pedb-exe-get-number exe-name)
,(file-name-base exe) ; ,(list (file-name-base exe))
,(pedb-exe-get-topic exe-name)
,(pedb-exe-get-type exe-name)
,(pedb-exe-get-modified exe)])))
(defun pedb-show-db ()
"Dispay exercize"
(interactive)
(let ((buf (get-buffer-create (concat "*PEDB*:" *pedb-raccolta-buffer*))))
(with-current-buffer buf
(pedb-list-mode)
(setq default-directory (pedb-store-dir))
(setq tabulated-list-entries (mapcar #'pedb-esercizio--print-info (pedb-all-exercises)))
(tabulated-list-print)
;(dolist (i (exe-all-exercise)) (insert (file-name-base i)) (insert "\n"))
)
(switch-to-buffer buf)))
;;; compile
(defun scliba-compila-guarda-file ()
(interactive)
(let* ((file-name (buffer-file-name))
(comand (format "(scliba:compila-guarda %S)" file-name)))
(slime-eval `(swank:eval-and-grab-output ,comand))
(message "Compilato file %s" file-name)))
(defun pedb-genera-esercizio ()
(interactive)
(let ((comand
(concat "(pedb:compila-esercizio-preview \"" (tabulated-list-get-id) "\")")))
(slime-eval `(swank:eval-and-grab-output ,comand))
(message "Compilato esercizio %s" (tabulated-list-get-id))))
(defun pedb-view-exercise ()
(interactive)
(let ((command (concat "(funcall (scliba::backend-view-fn scliba:*default-backend*) (scliba:standard-output-file \"" (tabulated-list-get-id) "\" scliba:*default-backend*))")))
(slime-eval `(swank:eval-and-grab-output ,command))))
(defun pedb-compile-and-view-exercise ()
(interactive)
(save-excursion (pedb-genera-esercizio))
(pedb-view-exercise))
;;; prove
;(slime-eval-async `(swank:eval-and-grab-output "(+ 1 2)"))
| 6,709 | Common Lisp | .cl | 152 | 40.493421 | 177 | 0.671825 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fa0ec180727a40428d7cafce6ddaa5b4c46528be6e39013d7945ce8305026887 | 17,914 | [
-1
] |
17,944 | env_esercizi.el | admich_scliba/tex/auto/env_esercizi.el | (TeX-add-style-hook
"env_esercizi"
(lambda ()
(TeX-add-symbols
"compito"
"makecompitotitle"
"mypagenumber"
"rfoot"
"infoform"
"printsoluzioni"
"olditem"
"var"
"dervar"
"dervarp"
"varp"))
:context)
| 248 | Common Lisp | .l | 16 | 11.3125 | 22 | 0.61039 | admich/scliba | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c2a011a27d93d932bc2c7cd53bf5298864088e8246acb78110cb0374922ac690 | 17,944 | [
-1
] |
17,960 | rsa.lsp | ored95_rsa/rsa.lsp | ; ==================================
; GENERATE PRIME
; ==================================
; ******** LOOP version ********
; (defun divisible-by (number list)
; "return true if divisible by an element in the list"
; (loop for i in list
; thereis (= (mod number i) 0)
; )
; )
; ***** FUNCTIONAL version *****
(defun divisible-by(number lst)
"return true if divisible by an element in the list"
(> (count
'0
(mapcar #'(lambda(i) (mod number i)) lst)
)
0
)
)
; DETERMINE all primes in range [current..max-value]
(defun prime-list-generator (current max-value prime-list)
"business end of gen"
(if (= current max-value)
prime-list
(if (divisible-by current prime-list)
(prime-list-generator (+ current 1) max-value prime-list)
(prime-list-generator (+ current 1) max-value (nconc prime-list (list current)))
)
)
)
; GENERATE prime in range [1..n]
(defun gen-prime(n)
; "Find the sum of all the primes below n"
; (time (reduce #'+ (prime-list-generator 2 n '())))
(setq lst (prime-list-generator 2 n '()))
(nth (random (length lst)) lst)
)
; ==================================
; GET coprime value of N
; ==================================
; ******** LOOP version ********
; (defun get-coprime(n)
; (setq prime-list (reverse (prime-list-generator 2 n '()))) ; HERE <- cdr (edited)
; (loop for p in prime-list
; when (= (gcd p n) 1)
; return p
; )
; )
; ***** FUNCTIONAL version *****
(defun get-coprime(n)
(find-if
#'(lambda(p) (= (gcd p n) 1))
(reverse (prime-list-generator 2 n '()))
)
)
; ==============================================================
; DETERMINE the modular multiplicative inverse of e in modulo n
; ==============================================================
; ******** LOOP version ********
; (defun inverse-modulo(e n)
; (loop for d from 1 to n
; when (= (mod (* d e) n) 1)
; return d
; )
; )
; ***** FUNCTIONAL version *****
(defun gen-range-help(i N result)
(if (<= i N)
(gen-range-help (+ i 1) N (nconc result (cons i Nil)))
result
)
)
(defun gen-range(n)
(gen-range-help 1 n '())
)
(defun inverse-modulo(e n)
(find-if
#'(lambda(x) (= (mod (* x e) n) 1))
(gen-range n)
)
)
; ========================================================
" RSA algorithm "
; Source: https://en.wikipedia.org/wiki/RSA_(cryptosystem)
; Author: Binh D. Nguyen
; ========================================================
(defun rsa(range)
; First step: Generate 2 primes (p, q).
(setq p (gen-prime range))
(setq q (gen-prime range))
; Second step: Calculate N = p*q - the KEY length.
(setq n (* p q))
; Third step: Calculate totient of N - 位(N). This value is kept private!
(setq totient (lcm (- p 1) (- q 1)))
; Fourth step: Choose number e in order that e and 位(N) are coprime.
(setq ke (get-coprime totient))
; Fifth step: Determine d - the modular multiplicative inverse of e in modulo 位(N)
(setq kd (inverse-modulo ke totient))
; Return keys
; The public key consists of the modulus N and the public (or encryption) exponent E.
; The private key consists of the modulus n and the private (or decryption) exponent D, which must be kept secret.
; P, Q, and 位(N) must also be kept secret because they can be used to calculate D.
(format T "+ The public key is (n = ~D, e = ~D).~%" n ke)
(format T "+ The private key is (n = ~D, d = ~D).~%" n kd)
)
; The encryption function c(m)
(defun encrypt(m ke kn)
(mod (expt m ke) kn)
)
; The decryption function m(c)
(defun decrypt(c kd kn)
(mod (expt c kd) kn)
) | 3,677 | Common Lisp | .l | 114 | 29.280702 | 117 | 0.551177 | ored95/rsa | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 676262dba41524d2b0b21f6a8e76c351c037757d1cd6671a799cbc9c38191ae9 | 17,960 | [
-1
] |
17,976 | devin.lisp | ColinPitrat_CLispMisc/Devin/devin.lisp | (defun prompt-number (string)
(format t "~a: " string) (read nil 'eof nil))
(defun prompt-string (string)
(format t "~a: " string) (read-line))
(defun game-internal-loop (random-state)
(let ((answer (random 1000 random-state))
(max_essais 12))
; Uncomment to cheat
;(format t "~a~%" answer)
(do ((essais 1 (+ 1 essais))
(essai 0 0)
(gagne nil)
(fini nil))
((or fini gagne) gagne)
(let ()
(setq essai (prompt-number "Votre propositon: "))
(cond
((> essai answer) (format t "Trop grand~%"))
((< essai answer) (format t "Trop petit~%"))
((= essai answer) (setq gagne T)))
(if (>= essais max_essais) (setq fini T))))))
(defun game ()
(do ((state (make-random-state T))
(exit nil))
(exit nil)
(let ()
(format t "J'ai choisi un nombre entre 0 et 1000. Trouvez le en 12 essais !~%")
(format t (if (game-internal-loop state) "Bravo, vous avez gagné !~%" "Dommage, vous avez perdu !~%"))
(if (equalp "y" (prompt-string "Quitter ? [y/n]")) (setq exit T)))))
(game)
| 1,115 | Common Lisp | .lisp | 30 | 30.866667 | 109 | 0.564292 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6175d51ea024326bca28b642a7183c8a031f8dfa3e33c45fa8f50150af5d8e35 | 17,976 | [
-1
] |
17,977 | pendu.lisp | ColinPitrat_CLispMisc/Pendu/pendu.lisp | (defun prompt-letter (string)
(format t "~a: " string)
(setf result (read-char))
(read-line)
(return-from prompt-letter result))
(defun choose-word (from)
(nth (random (length from)) from))
(defun known-word (word letters)
(map 'string (lambda (x) (if (find x letters) x #\_)) word))
(defun complete (word letters)
(equal nil (find #\_ (known-word word letters))))
(defun game-loop (dict)
(let ((word (choose-word dict))
(letters nil)
(missed 0)
(max_missed 6))
(do ()
((or (complete word letters) (>= missed max_missed)) nil)
(let ()
(format t "~a~%" (known-word word letters))
(setf letter (prompt-letter "Votre proposition: ")))
(push letter letters)
(setf missed (if (find letter word) missed (+ 1 missed))))
(if (complete word letters) (format t "Bravo, c'était bien: ") (format t "Perdu, c'était: "))
(format t "~a~%" word)))
(defun load-dict (filename)
(let ((result nil))
(with-open-file (stream filename :direction :input)
(do ((line (read-line stream nil) (read-line stream nil)))
((null line))
(push line result)))
(return-from load-dict result)))
(defun game ()
(setf *random-state* (make-random-state t))
(do ((exit nil))
(exit nil)
(let ()
(format t "J'ai choisis un mot. Trouvez les lettres qui le composent. Vous avez le droit à 6 erreurs.~%")
(game-loop (load-dict "dictionnaire.txt"))
(if (equalp #\y (prompt-letter "Quitter ? [y/n]")) (setq exit T)))))
;(format t "~a~%" (choose-word (list "toto" "titi" "tata" "tutu")))
;(format t "~a~%" (known-word "toto" "t"))
;(format t "~a~%" (known-word "antioxydant" "abedt"))
| 1,705 | Common Lisp | .lisp | 43 | 34.744186 | 111 | 0.611985 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e0d972846b7c9fa4d64534fd84cdb47b8fc7acb00d90a396a5d78036485bd1b0 | 17,977 | [
-1
] |
17,978 | test.lisp | ColinPitrat_CLispMisc/Pendu/test.lisp | (load 'asdf)
(asdf:load-system :xlunit)
(load "pendu.lisp")
(defclass pendu-test (xlunit:test-case) ())
(xlunit:def-test-method known-word-with-empty-letter-list ((xlunit:test pendu-test))
(xlunit:assert-equal (known-word "marathon" nil) "________"))
(xlunit:def-test-method known-word-with-some-unique-letters ((xlunit:test pendu-test))
(xlunit:assert-equal (known-word "marathon" (list #\m #\t)) "m___t___"))
(xlunit:def-test-method known-word-with-some-repeated-letters ((xlunit:test pendu-test))
(xlunit:assert-equal (known-word "marathon" (list #\a #\t)) "_a_at___"))
(xlunit:def-test-method known-word-with-some-absent-letters ((xlunit:test pendu-test))
(xlunit:assert-equal (known-word "marathon" (list #\t #\z #\w)) "____t___"))
(xlunit:def-test-method complete-with-completed-word ((xlunit:test pendu-test))
(xlunit:assert-equal (complete "marathon" (list #\a #\t #\h #\m #\n #\o #\r)) T))
(xlunit:def-test-method complete-with-missing-letter ((xlunit:test pendu-test))
(xlunit:assert-equal (complete "marathon" (list #\a #\w #\h #\m #\n #\o #\r)) nil))
(xlunit:def-test-method complete-with-no-letter ((xlunit:test pendu-test))
(xlunit:assert-equal (complete "marathon" nil) nil))
| 1,369 | Common Lisp | .lisp | 18 | 65.166667 | 107 | 0.613721 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 54a6afa67a57db139512f7dbf89a1f2a67824ed712baf9314b6a30ace36256c1 | 17,978 | [
407689
] |
17,979 | main.lisp | ColinPitrat_CLispMisc/Sudoku/main.lisp | (load "sudoku.lisp")
(pretty-solve-sudoku "tests/empty.txt")
(pretty-solve-sudoku "grids/level1.txt")
(pretty-solve-sudoku "grids/level2.txt")
(pretty-solve-sudoku "grids/level3.txt")
(pretty-solve-sudoku "grids/level4.txt")
| 226 | Common Lisp | .lisp | 6 | 36.5 | 40 | 0.767123 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 8b101c16b2e494598e13e2c669de0a19d03e6d3370324fa2adfc33666a726dc8 | 17,979 | [
-1
] |
17,980 | sudoku.lisp | ColinPitrat_CLispMisc/Sudoku/sudoku.lisp | (defun parse-sudoku-line (line)
(nreverse (reduce #'(lambda (x y) (push y x)) line :initial-value nil)))
(defun load-sudoku (file)
(let ((sudoku nil))
(with-open-file (stream file :direction :input)
(do ((line (read-line stream nil) (read-line stream nil)))
((null line) (nreverse sudoku))
(push (parse-sudoku-line line) sudoku)))))
(defun print-sudoku (sudoku)
(map 'nil #'(lambda (x) (format t "~a~%" x)) sudoku))
(defun numbers ()
(list #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))
(defun indices ()
(list 0 1 2 3 4 5 6 7 8))
(defun sub-indices ()
(list 0 1 2))
(defun present-twice (n line)
(> (count n line) 1))
(defun has-double-number (line)
(reduce #'(lambda (x y) (or x (present-twice y line))) (numbers) :initial-value nil))
(defun are-sudoku-lines-ok (sudoku)
(not (reduce #'(lambda (x y) (or x y)) (map 'list 'has-double-number sudoku))))
(defun get-column (n sudoku)
(map 'list #'(lambda (x) (nth n x)) sudoku))
(defun are-sudoku-columns-ok (sudoku)
(are-sudoku-lines-ok (map 'list #'(lambda (n) (get-column n sudoku)) (indices))))
(defun cartesian-product (l1 l2)
(remove-if
'null
(reduce
'append
(map 'list
#'(lambda (x)
(map 'list #'(lambda (y) (list x y)) l2))
l1))))
(defun half-indices-area (n)
(map 'list #'(lambda (x) (+ (* n 3) x)) '(0 1 2)))
(defun indices-area (idx)
(cartesian-product (half-indices-area (car idx)) (half-indices-area (cadr idx))))
(defun all-indices()
(cartesian-product (indices) (indices)))
; idx is a list (row col)
(defun get-element (idx sudoku)
(nth (cadr idx) (nth (car idx) sudoku)))
(defun set-element (idx sudoku n)
(setf (nth (cadr idx) (nth (car idx) sudoku)) n))
(defun extract-sudoku-area (idx sudoku)
(map 'list #'(lambda (idx) (get-element idx sudoku)) (indices-area idx)))
(defun all-sudoku-areas (sudoku)
(map 'list #'(lambda (idx) (extract-sudoku-area idx sudoku)) (cartesian-product (sub-indices) (sub-indices))))
(defun are-sudoku-areas-ok (sudoku)
(are-sudoku-lines-ok (all-sudoku-areas sudoku)))
(defun is-sudoku-valid (sudoku)
(and
;(let ()
; (format t "Is valid: ~%")
; (print-sudoku sudoku)
; (equal 1 1))
(are-sudoku-lines-ok sudoku)
(are-sudoku-columns-ok sudoku)
(are-sudoku-areas-ok sudoku)
))
(defun finished-sudoku (sudoku)
(and (is-sudoku-valid sudoku)
(loop for idx in (all-indices)
never (equalp #\. (get-element idx sudoku)))))
; TODO: solve-sudoku
(defun solve-sudoku (sudoku)
(if (finished-sudoku sudoku) (return-from solve-sudoku sudoku))
(loop for idx in (all-indices)
when (equalp #\. (get-element idx sudoku))
do (loop for n in (numbers)
do (set-element idx sudoku n)
(if (is-sudoku-valid sudoku) (if (solve-sudoku sudoku) (return-from solve-sudoku sudoku))))
(set-element idx sudoku #\.)
(return-from solve-sudoku nil)))
(defun pretty-solve-sudoku (file)
(let ((sudoku (load-sudoku file)))
(format t " === ~a === ~%" file)
(print-sudoku sudoku)
(format t "~%" file)
(print-sudoku (solve-sudoku sudoku))))
| 3,200 | Common Lisp | .lisp | 82 | 34.195122 | 112 | 0.621971 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f2eab4bcaa1e3c1b501a41fd8e170ff2df6e381e54e23a596d9fa2a8192bf4cd | 17,980 | [
-1
] |
17,981 | test.lisp | ColinPitrat_CLispMisc/Sudoku/test.lisp | (require "asdf")
(asdf:load-system :xlunit)
(load "sudoku.lisp")
(defclass sudoku-test (xlunit:test-case) ())
(xlunit:def-test-method parse-sudoku-empty-line ((xlunit:test sudoku-test))
(xlunit:assert-equal '(#\. #\. #\. #\. #\. #\. #\. #\. #\.) (parse-sudoku-line ".........")))
(xlunit:def-test-method parse-sudoku-line ((xlunit:test sudoku-test))
(xlunit:assert-equal '(#\. #\2 #\. #\4 #\. #\6 #\. #\8 #\.) (parse-sudoku-line ".2.4.6.8.")))
(xlunit:def-test-method present-twice-no ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (present-twice 1 (parse-sudoku-line "122345678"))))
(xlunit:def-test-method present-twice-yes ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (present-twice 2 (parse-sudoku-line "122345678"))))
(xlunit:def-test-method has-double-number-no ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (has-double-number (parse-sudoku-line "123456789"))))
(xlunit:def-test-method has-double-number-yes ((xlunit:test sudoku-test))
(xlunit:assert-equal t (has-double-number (parse-sudoku-line "113456789"))))
(xlunit:def-test-method has-double-number-yes-with-holes ((xlunit:test sudoku-test))
(xlunit:assert-equal t (has-double-number (parse-sudoku-line ".1.456.49"))))
(xlunit:def-test-method has-double-number-no-with-holes ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (has-double-number (parse-sudoku-line ".1.456.39"))))
(xlunit:def-test-method has-double-number-no-with-holes ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (has-double-number (parse-sudoku-line ".1.456.39"))))
(xlunit:def-test-method are-sudoku-lines-ok-empty ((xlunit:test sudoku-test))
(xlunit:assert-equal t (are-sudoku-lines-ok (load-sudoku "tests/empty.txt"))))
(xlunit:def-test-method are-sudoku-lines-ok-diag ((xlunit:test sudoku-test))
(xlunit:assert-equal t (are-sudoku-lines-ok (load-sudoku "tests/diag.txt"))))
(xlunit:def-test-method are-sudoku-lines-ok-invalid ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (are-sudoku-lines-ok (load-sudoku "tests/invalid_line.txt"))))
(xlunit:def-test-method get-column ((xlunit:test sudoku-test))
(xlunit:assert-equal '(#\. #\. #\3 #\. #\. #\. #\. #\. #\.) (get-column 2 (load-sudoku "tests/diag.txt"))))
(xlunit:def-test-method are-sudoku-columns-ok-empty ((xlunit:test sudoku-test))
(xlunit:assert-equal t (are-sudoku-columns-ok (load-sudoku "tests/empty.txt"))))
(xlunit:def-test-method are-sudoku-columns-ok-diag ((xlunit:test sudoku-test))
(xlunit:assert-equal t (are-sudoku-columns-ok (load-sudoku "tests/diag.txt"))))
(xlunit:def-test-method are-sudoku-columns-ok-invalid ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (are-sudoku-columns-ok (load-sudoku "tests/invalid_column.txt"))))
(xlunit:def-test-method cartesian-product-nil-nil ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (cartesian-product nil nil)))
(xlunit:def-test-method cartesian-product-2-nil ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (cartesian-product '(0 1) nil)))
(xlunit:def-test-method cartesian-product-2-2 ((xlunit:test sudoku-test))
(xlunit:assert-equal '((0 2) (0 3) (1 2) (1 3)) (cartesian-product '(0 1) '(2 3))))
(xlunit:def-test-method half-indices-area-0 ((xlunit:test sudoku-test))
(xlunit:assert-equal '(0 1 2) (half-indices-area 0)))
(xlunit:def-test-method half-indices-area-1 ((xlunit:test sudoku-test))
(xlunit:assert-equal '(3 4 5) (half-indices-area 1)))
(xlunit:def-test-method half-indices-area-2 ((xlunit:test sudoku-test))
(xlunit:assert-equal '(6 7 8) (half-indices-area 2)))
(xlunit:def-test-method indices-area-0-0 ((xlunit:test sudoku-test))
(xlunit:assert-equal '((0 0) (0 1) (0 2) (1 0) (1 1) (1 2) (2 0) (2 1) (2 2)) (indices-area '(0 0))))
(xlunit:def-test-method get-element ((xlunit:test sudoku-test))
(xlunit:assert-equal #\3 (get-element '(2 3) (load-sudoku "tests/invalid_column.txt"))))
(xlunit:def-test-method get-element2 ((xlunit:test sudoku-test))
(xlunit:assert-equal #\4 (get-element '(4 3) (load-sudoku "tests/invalid_column.txt"))))
(xlunit:def-test-method get-element2 ((xlunit:test sudoku-test))
(xlunit:assert-equal #\5 (get-element '(6 3) (load-sudoku "tests/invalid_column.txt"))))
(xlunit:def-test-method set-element ((xlunit:test sudoku-test))
(xlunit:assert-equal #\3 (let ((sudoku (load-sudoku "tests/invalid_column.txt")))
(set-element '(2 3) sudoku #\3)
(get-element '(2 3) sudoku))))
(xlunit:def-test-method extract-sudoku-area ((xlunit:test sudoku-test))
(xlunit:assert-equal '(#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (extract-sudoku-area '(0 0) (load-sudoku "tests/area_1_full.txt"))))
(xlunit:def-test-method are-sudoku-areas-ok-yes ((xlunit:test sudoku-test))
(xlunit:assert-equal t (are-sudoku-areas-ok (load-sudoku "tests/area_1_full.txt"))))
(xlunit:def-test-method are-sudoku-areas-ok-no1 ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (are-sudoku-areas-ok (load-sudoku "tests/area_1_invalid.txt"))))
(xlunit:def-test-method are-sudoku-areas-ok-no2 ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (are-sudoku-areas-ok (load-sudoku "tests/area_9_invalid.txt"))))
(xlunit:def-test-method is-sudoku-valid-yes1 ((xlunit:test sudoku-test))
(xlunit:assert-equal t (is-sudoku-valid (load-sudoku "tests/area_1_full.txt"))))
(xlunit:def-test-method is-sudoku-valid-yes2 ((xlunit:test sudoku-test))
(xlunit:assert-equal t (is-sudoku-valid (load-sudoku "tests/diag.txt"))))
(xlunit:def-test-method is-sudoku-valid-yes3 ((xlunit:test sudoku-test))
(xlunit:assert-equal t (is-sudoku-valid (load-sudoku "tests/empty.txt"))))
(xlunit:def-test-method is-sudoku-valid-no1 ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (is-sudoku-valid (load-sudoku "tests/area_1_invalid.txt"))))
(xlunit:def-test-method is-sudoku-valid-no2 ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (is-sudoku-valid (load-sudoku "tests/invalid_column.txt"))))
(xlunit:def-test-method is-sudoku-valid-no3 ((xlunit:test sudoku-test))
(xlunit:assert-equal nil (is-sudoku-valid (load-sudoku "tests/invalid_line.txt"))))
(xlunit:textui-test-run (xlunit:get-suite sudoku-test))
| 7,018 | Common Lisp | .lisp | 81 | 72.925926 | 152 | 0.620995 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c65b7fa43b334e1db554b45992bed922bf2175620929e95c2d1797c9ecba9785 | 17,981 | [
-1
] |
17,982 | main.lisp | ColinPitrat_CLispMisc/GameOfLife/main.lisp | (load "gameoflife.lisp")
(in-package :gameoflife)
;(load-and-show-evolution "board/pentadecathlon.txt" 16)
(show-evolution (board-randomize (make-instance 'gol :width 127 :height 20)) 1000)
| 192 | Common Lisp | .lisp | 4 | 46.5 | 82 | 0.768817 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 1b404798c3cf4c16556b08658f9f4274d919f9fb8c707c2fb4f03b7a6689ada1 | 17,982 | [
-1
] |
17,983 | gameoflife.lisp | ColinPitrat_CLispMisc/GameOfLife/gameoflife.lisp | (defpackage :gameoflife
(:use :common-lisp)
(:export :idx :gol :set-alive :set-dead :get-cell :get-neighbours-indices
:count-neighbours :next-state :all-indices :next-generation
:load-game-of-life :print-board :board-randomize :show-evolution
:load-and-show-evolution))
(in-package :gameoflife)
(defclass gol ()
((width
:initarg :width
:initform 10)
(height
:initarg :height
:initform 10)
(cells
:initarg :cells)))
(defmethod initialize-instance :after ((board gol) &key)
(let ((width (slot-value board 'width))
(height (slot-value board 'height)))
(setf (slot-value board 'cells)
(make-list (* width height) :initial-element 0))))
(defun idx (x y board)
(let ((width (slot-value board 'width))
(height (slot-value board 'height)))
(+ (mod x width) (* (mod y height) width))))
(defmacro get-cell (x y board)
`(nth (idx ,x ,y ,board) (slot-value ,board 'cells)))
(defun set-cell (x y val board)
(setf (get-cell x y board) val))
(defun set-alive (x y board)
(set-cell x y 1 board))
(defun set-dead (x y board)
(set-cell x y 0 board))
(defun cartesian-product (l1 l2)
(reduce 'append
(map 'list
#'(lambda (x)
(map 'list
#'(lambda (y) (list x y))
l2))
l1)))
(defun neighbourhood-1d-indices (z)
(map 'list #'(lambda (m) (+ z m)) '(-1 0 1)))
(defun get-neighbours-indices (x y)
(remove (list x y)
(cartesian-product (neighbourhood-1d-indices x)
(neighbourhood-1d-indices y))
:test 'equalp))
(defun next-state (state neighbours)
(case neighbours
(2 state)
(3 1)
(otherwise 0)))
(defun count-neighbours (x y board)
(reduce #'(lambda (a b) (+ a (get-cell (car b) (cadr b) board))) (get-neighbours-indices x y) :initial-value 0))
(defun all-indices (board)
(let ((width (slot-value board 'width))
(height (slot-value board 'height)))
(cartesian-product
(loop for x from 0 below width by 1 collect x)
(loop for y from 0 below height by 1 collect y))))
(defun next-generation (board)
(let ((copy-board (make-instance 'gol :width (slot-value board 'width) :height (slot-value board 'height))))
(loop for idx in (all-indices board)
do
(let ((x (car idx))
(y (cadr idx)))
(set-cell x y (next-state (get-cell x y board) (count-neighbours x y board)) copy-board)))
(return-from next-generation copy-board)))
(defun read-integer (stream)
(parse-integer (read-line stream)))
(defun load-game-of-life (file)
(with-open-file (stream file :direction :input)
(let* ((width (read-integer stream))
(height (read-integer stream))
(board (make-instance 'gol :width width :height height)))
(do ((l (read-line stream) (read-line stream nil 'eof))
(y 0 (+ 1 y))
(x 0 0))
((eq l 'eof) board)
(loop for v across l
do
(set-cell x y (digit-char-p v) board)
(setf x (+ 1 x)))))))
(defun print-board (board)
(loop for y from 0 below (slot-value board 'height)
do
(loop for x from 0 below (slot-value board 'width)
do
(format t (if (equalp 0 (get-cell x y board)) " " "X")))
(format t "~%"))
(format t "~%"))
(defun show-evolution (board generations)
(do ((copy-board board (next-generation copy-board))
(gen 0 (+ 1 gen)))
((equalp generations gen) copy-board)
(print-board copy-board)
(sleep 0.1)))
(defun load-and-show-evolution (file generations)
(let ((board (load-game-of-life file)))
(show-evolution board generations)))
(defun board-randomize (board)
(let ((width (slot-value board 'width))
(height (slot-value board 'height)))
(loop for x from 0 below width
do (loop for y from 0 below height
do (set-cell x y (random 2 (make-random-state t)) board)))
(return-from board-randomize board)))
| 3,784 | Common Lisp | .lisp | 108 | 31.046296 | 114 | 0.652257 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c0e2267b838c6d4264184905532a834c7df7621c2fbc327fc5ef7461bd219de9 | 17,983 | [
-1
] |
17,984 | test.lisp | ColinPitrat_CLispMisc/GameOfLife/test.lisp | (load 'asdf)
(asdf:load-system :xlunit)
(load "gameoflife.lisp")
(defpackage :gameoflife-test
(:use :common-lisp :xlunit :gameoflife))
(in-package :gameoflife-test)
(defclass gameoflife-test (test-case) ())
(defmacro test-gameoflife (name expr)
`(def-test-method ,name ((test gameoflife-test)) ,expr))
(test-gameoflife idx-0-0-is-0 (assert-equal (idx 0 0 (make-instance 'gol)) 0))
(test-gameoflife idx-1-0-is-1 (assert-equal (idx 1 0 (make-instance 'gol)) 1))
(test-gameoflife idx-1-1-is-11 (assert-equal (idx 1 1 (make-instance 'gol)) 11))
(test-gameoflife idx-10-10-is-0 (assert-equal (idx 10 10 (make-instance 'gol)) 0))
(test-gameoflife idx--1--1-is-81 (assert-equal (idx -1 -1 (make-instance 'gol)) 99))
(test-gameoflife get-cell (assert-equal (get-cell 0 0 (make-instance 'gol)) 0))
(test-gameoflife set-alive-get-cell-0-0 (assert-equal
(let ((board (make-instance 'gol)))
(set-alive 0 0 board)
(get-cell 0 0 board))
1))
(test-gameoflife set-dead-get-cell-0-0 (assert-equal
(let ((board (make-instance 'gol)))
(set-alive 0 0 board)
(set-dead 0 0 board)
(get-cell 0 0 board))
0))
(test-gameoflife get-neighbours-indices-3-3 (assert-equal
(get-neighbours-indices 3 3)
'((2 2) (2 3) (2 4) (3 2) (3 4) (4 2) (4 3) (4 4))))
(test-gameoflife count-neighbours-0 (assert-equal
(let ((board (make-instance 'gol)))
(set-alive 0 0 board)
(count-neighbours 0 0 board))
0))
(test-gameoflife count-neighbours-1 (assert-equal
(let ((board (make-instance 'gol)))
(set-alive 0 0 board)
(count-neighbours 1 1 board))
1))
(test-gameoflife count-neighbours-8 (assert-equal
(let ((board (make-instance 'gol)))
(set-alive 0 0 board)
(set-alive 0 1 board)
(set-alive 0 2 board)
(set-alive 1 0 board)
(set-alive 1 1 board)
(set-alive 1 2 board)
(set-alive 2 0 board)
(set-alive 2 1 board)
(set-alive 2 2 board)
(count-neighbours 1 1 board))
8))
(defmacro test-next-state (state neighbours expected)
`(test-gameoflife (format t nil "next-state-~a-~a" ,state ,neighbours)
(assert-equal (next-state ,state ,neighbours) ,expected)))
(defmacro test-next-state-both (neighbours expected)
`(test-next-state 0 ,neighbours ,expected)
`(test-next-state 1 ,neighbours ,expected))
; A cell always end-up dead ...
(test-next-state-both 0 0)
(test-next-state-both 1 0)
(test-next-state-both 4 0)
(test-next-state-both 5 0)
(test-next-state-both 6 0)
(test-next-state-both 7 0)
(test-next-state-both 8 0)
; A cell always end-up except if it has 2 or 3 neighbours
(test-next-state 0 2 0)
(test-next-state 0 3 1)
(test-next-state 1 2 1)
(test-next-state 1 3 1)
(test-gameoflife all-indices-3-3 (assert-equal (all-indices (make-instance 'gol :width 3 :height 3))
'((0 0) (0 1) (0 2) (1 0) (1 1) (1 2) (2 0) (2 1) (2 2))))
(test-gameoflife all-indices-2-3 (assert-equal (all-indices (make-instance 'gol :width 2 :height 3))
'((0 0) (0 1) (0 2) (1 0) (1 1) (1 2))))
(test-gameoflife next-generation-1 (assert-equal '(0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0)
(let ((board (make-instance 'gol :width 4 :height 4)))
(set-alive 1 1 board)
(set-alive 1 2 board)
(set-alive 2 1 board)
(set-alive 2 2 board)
(next-generation board))))
(test-gameoflife load-game-of-life-1 (assert-equal 0 (get-cell 0 0 (load-game-of-life "board/small_empty.txt"))))
(test-gameoflife load-game-of-life-2 (assert-equal 1 (get-cell 0 0 (load-game-of-life "board/small_diag.txt"))))
(test-gameoflife load-game-of-life-3 (assert-equal 1 (get-cell 1 1 (load-game-of-life "board/small_diag.txt"))))
(test-gameoflife load-game-of-life-4 (assert-equal 0 (get-cell 2 1 (load-game-of-life "board/small_diag.txt"))))
(test-gameoflife load-game-of-life-5 (assert-equal '(0 0 0 0 0 0
0 0 1 1 0 0
0 1 0 0 1 0
0 0 1 1 0 0
0 0 0 0 0 0)
(let ((board (load-game-of-life "board/beehive.txt")))
(list
(get-cell 0 0 board)
(get-cell 1 0 board)
(get-cell 2 0 board)
(get-cell 3 0 board)
(get-cell 4 0 board)
(get-cell 5 0 board)
(get-cell 0 1 board)
(get-cell 1 1 board)
(get-cell 2 1 board)
(get-cell 3 1 board)
(get-cell 4 1 board)
(get-cell 5 1 board)
(get-cell 0 2 board)
(get-cell 1 2 board)
(get-cell 2 2 board)
(get-cell 3 2 board)
(get-cell 4 2 board)
(get-cell 5 2 board)
(get-cell 0 3 board)
(get-cell 1 3 board)
(get-cell 2 3 board)
(get-cell 3 3 board)
(get-cell 4 3 board)
(get-cell 5 3 board)
(get-cell 0 4 board)
(get-cell 1 4 board)
(get-cell 2 4 board)
(get-cell 3 4 board)
(get-cell 4 4 board)
(get-cell 5 4 board)))))
(textui-test-run (get-suite gameoflife-test))
| 5,185 | Common Lisp | .lisp | 124 | 34.403226 | 113 | 0.599364 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 61b59c07979cf07574c97491742fb98990bc1acc8af417d8f1fcaa4ff70a755b | 17,984 | [
-1
] |
17,985 | main.lisp | ColinPitrat_CLispMisc/LabyrinthSolver/main.lisp | (load "labyrinth-solver.lisp")
;(format t "50! = ~a" (factorial 50))
;(format t "~a~%" (load-labyrinth "test1.txt"))
(print-labyrinth (load-labyrinth "test1.txt"))
(format t "~a~%" (find-entrance (load-labyrinth "test1.txt")))
(format t "~a~%" (find-output (load-labyrinth "test1.txt")))
(let ((labyrinth (load-labyrinth "test1.txt")))
(format t "~a~%" (item-at (find-entrance labyrinth) labyrinth))
(format t "~a~%" (item-at (find-output labyrinth) labyrinth)))
(format t "~a~%" (neighbours (list 2 2)))
(labyrinth-solve (load-labyrinth "test1.txt"))
(labyrinth-solve (load-labyrinth "test2.txt"))
| 604 | Common Lisp | .lisp | 12 | 48.916667 | 65 | 0.678511 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 820e9c18b2e58e8bbb731b5dfeac1269db496dbace61d6b84dbea7326df409db | 17,985 | [
-1
] |
17,986 | labyrinth-solver.lisp | ColinPitrat_CLispMisc/LabyrinthSolver/labyrinth-solver.lisp | (defun load-labyrinth (filename)
(with-open-file (stream filename :direction :input)
(do ((line (read-line stream nil) (read-line stream nil))
(labyrinth nil))
((null line) (nreverse labyrinth))
(push (reduce #'(lambda (x y) (push x y)) line :from-end t :initial-value nil) labyrinth))))
(defun print-labyrinth (labyrinth)
(map 'nil #'(lambda (x)
(map 'nil #'(lambda (y)
(format t "~a" y))
x)
(format t "~%"))
labyrinth))
(defun line-contains (item line)
(find item line))
(defun find-item (item labyrinth)
(flet ((line-contains-item (line) (line-contains item line)))
(list
(position-if #'line-contains-item labyrinth)
(position item (find-if #'line-contains-item labyrinth)))))
(defun find-entrance (labyrinth)
(find-item #\A labyrinth))
(defun find-output (labyrinth)
(find-item #\B labyrinth))
(defun item-at (pos labyrinth)
(nth (nth 1 pos) (nth (nth 0 pos) labyrinth)))
(defun set-item-at (pos labyrinth item)
(setf (nth (nth 1 pos) (nth (nth 0 pos) labyrinth)) item))
(defun shift-pos (pos delta)
(list (+ (nth 0 pos) (nth 0 delta)) (+ (nth 1 pos) (nth 1 delta))))
(defun neighbours (pos)
(map 'list
(lambda (x) (shift-pos pos x))
(list '(-1 0) '(0 1) '(1 0) '(0 -1))))
(defun find-path (start end labyrinth)
(loop for pos in (neighbours start)
do (if
(and (> (nth 0 pos) 0) (> (nth 1 pos) 0))
(progn
(if
(eq #\B (item-at pos labyrinth))
(print-labyrinth labyrinth))
(if
(eq #\ (item-at pos labyrinth))
(progn
(set-item-at pos labyrinth #\.)
(find-path pos end labyrinth)
(set-item-at pos labyrinth #\ )
)
)
)
)
)
)
(defun labyrinth-solve (labyrinth)
(find-path (find-entrance labyrinth) (find-output labyrinth) labyrinth)
)
| 1,835 | Common Lisp | .lisp | 57 | 27.649123 | 98 | 0.621744 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c74df9b8bf7c80d69c7fefc514e1b3ae3fbdc437158bd504a4075f490536684d | 17,986 | [
-1
] |
17,987 | test.lisp | ColinPitrat_CLispMisc/LabyrinthSolver/test.lisp | (load 'asdf)
(asdf:load-system :xlunit)
(load "labyrinth-solver.lisp")
(defclass labyrinth-solver-test (xlunit:test-case) ())
;(xlunit:def-test-method factorial-0-is-1 ((xlunit:test factorial-test))
; (xlunit:assert-equal (factorial 0) 1))
| 266 | Common Lisp | .lisp | 6 | 42.833333 | 72 | 0.680934 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 264e7d6d6e9233d040fdfb69e1f071242622868173c588ab92908ef5defb94e1 | 17,987 | [
-1
] |
17,988 | main.lisp | ColinPitrat_CLispMisc/Model/main.lisp | (load "factorial.lisp")
(loop for x from 1 to 50
do (format t "~a! = ~a~%" x (factorial:factorial x)))
| 110 | Common Lisp | .lisp | 3 | 33.333333 | 59 | 0.613208 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d1fece1fded8537c98ec024afb774d9fd1e44e30726e02265b5e88aa89a7e7e9 | 17,988 | [
-1
] |
17,989 | factorial.lisp | ColinPitrat_CLispMisc/Model/factorial.lisp | (defpackage :factorial
(:use :common-lisp)
(:export :factorial))
(in-package :factorial)
(defun factorial (n)
(if (> n 1)
(* (factorial (- n 1)) n)
1))
| 169 | Common Lisp | .lisp | 8 | 18 | 29 | 0.613924 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 783f93ee9aac62187ec8dfd5726fbb7aa1efd0d4be287535ddc2e1e3e55173b8 | 17,989 | [
-1
] |
17,990 | test.lisp | ColinPitrat_CLispMisc/Model/test.lisp | (load 'asdf)
(asdf:load-system :xlunit)
(load "factorial.lisp")
(defpackage :factorial-test
(:use :common-lisp :xlunit :factorial))
(in-package :factorial-test)
(defclass factorial-test (test-case) ())
(defmacro test-factorial (name expr)
`(def-test-method ,name ((test factorial-test)) ,expr))
(test-factorial factorial-0-is-1 (assert-equal (factorial 0) 1))
(test-factorial factorial-1-is-1 (assert-equal (factorial 1) 1))
(test-factorial factorial-2-is-2 (assert-equal (factorial 2) 2))
(test-factorial factorial-3-is-6 (assert-equal (factorial 3) 6))
(test-factorial factorial-10-is-3628800 (assert-equal (factorial 10) 3628800))
(test-factorial
factorial-50-is-huge
(assert-equal
(factorial 50)
30414093201713378043612608166064768844377641568960512000000000000))
(textui-test-run (get-suite factorial-test))
| 842 | Common Lisp | .lisp | 20 | 39.65 | 78 | 0.765142 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2571c7dd203818add15d34c2a5710098205d46a649a5dbc98ba6975a93efcae9 | 17,990 | [
-1
] |
18,001 | pentadecathlon.txt | ColinPitrat_CLispMisc/GameOfLife/board/pentadecathlon.txt | 11
18
00000000000
00000000000
00000000000
00000000000
00000000000
00001110000
00001010000
00001110000
00001110000
00001110000
00001110000
00001010000
00001110000
00000000000
00000000000
00000000000
00000000000
00000000000
| 222 | Common Lisp | .l | 20 | 10.1 | 11 | 1 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f41c8fd74eeb6047b995a2275f447a5f2c38650c36f97d3a5a361bea9d235dcc | 18,001 | [
-1
] |
18,002 | pulsar.txt | ColinPitrat_CLispMisc/GameOfLife/board/pulsar.txt | 17
17
00000000000000000
00000000000000000
00001110001110000
00000000000000000
00100001010000100
00100001010000100
00100001010000100
00001110001110000
00000000000000000
00001110001110000
00100001010000100
00100001010000100
00100001010000100
00000000000000000
00001110001110000
00000000000000000
00000000000000000
| 312 | Common Lisp | .l | 19 | 15.421053 | 17 | 1 | ColinPitrat/CLispMisc | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 90787a5fdde82087bd6f22d63253c745f89f7867052c52f3c5eee642d9654a1c | 18,002 | [
-1
] |
18,023 | clasm.lisp | gentoomen_CLASM/clasm.lisp | (defun asm (&rest rest)
(mapcar (lambda (str) (progn (princ str)
(terpri)))
rest)
t)
(defun join-strings-with-comma (s1 s2)
(concatenate 'string s1 "," s2))
(defun operands-from-list (l)
(reduce #'join-strings-with-comma
(mapcar #'princ-to-string l)))
(defmacro definstruction (name)
`(defun ,name (&rest rest)
(let ((operands (operands-from-list rest)))
(concatenate 'string
" "
,(string-downcase (symbol-name name))
" "
operands))))
(defmacro defregister (name)
`(defvar ,name (concatenate 'string
"$"
,(string-downcase (symbol-name name)))))
(defun label (name)
(concatenate 'string name ":"))
; Sample x86 instructions and registers
(definstruction add)
(definstruction xor)
(definstruction cmp)
(definstruction jge)
(definstruction inc)
(definstruction jmp)
(defregister eax)
(defregister ebx)
(defregister ecx)
(defregister edx)
; Sample program
(defun sample-program ()
(asm
(label "start")
(xor eax eax)
(xor ebx ebx)
(add ebx 100)
(label "loop")
(cmp eax ebx)
(jge "end")
(inc eax)
(jmp "loop")
(label "end")))
| 1,322 | Common Lisp | .lisp | 48 | 20.375 | 70 | 0.586797 | gentoomen/CLASM | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9d1e17bb68c18c8219b85a0fe6d0018da6dbf149a84d920118d978eb5eba485f | 18,023 | [
-1
] |
18,040 | compile.lisp | clarkeaa_jsresume/compile.lisp | (require 'parenscript)
(in-package :parenscript)
(defun compile-fish ()
(with-open-file (ostr "fish.js"
:if-does-not-exist :create
:direction :output
:if-exists :supersede)
(let ((js (parenscript:ps-compile-file
"/Users/clarkeaa/dev/jsresume/fish.lisp")))
(format t "~a" js)
(format ostr "~a" js))))
| 411 | Common Lisp | .lisp | 11 | 26.272727 | 58 | 0.532663 | clarkeaa/jsresume | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6ee9042058ad7806978a7521971d875126d254987ea63c7e746eda291af0827b | 18,040 | [
-1
] |
18,041 | fish.lisp | clarkeaa_jsresume/fish.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; fish resume
;;; (c) Aaron Clarke 2014
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar *ctx* nil)
(defvar *width* 640)
(defvar *height* 480)
(defvar *position* 0)
(defvar *loc-widget-height* 20)
(defvar *loc-widget-knob-width* 26)
(defvar *ground-height* 100)
(defvar *fps* 30)
(defvar *frame* 0)
(defvar *fish-direction* 1)
(defvar *fish-width* 240)
(defvar *fish-height* 160)
(defvar *input-time* 0)
(defvar *min-position* -100)
(defvar *max-position* 3800)
(defvar *move-speed* 10)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro ctx (func &rest args) (cons `(@ *ctx* ,func) args))
(defmacro clear () `(ctx clearRect 0 0 *width* *height*))
(defmacro with-ctx-state (&body body)
`(progn
(ctx save)
,@body
(ctx restore)))
(defmacro setf-rgb (data index red green blue)
`(progn (setf (aref ,data ,index) ,red)
(setf (aref ,data (+ 1 ,index)) ,green)
(setf (aref ,data (+ 2 ,index)) ,blue)))
(defmacro with-mod-img-data ((pix-var x y width height) &body body)
(let ((img-data (gensym)))
`(let* ((,img-data (ctx getImageData ,x ,y ,width ,height))
(,pix-var (@ ,img-data data)))
,@body
(ctx putImageData ,img-data ,x ,y))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun draw-loc-widget ()
(setf (@ *ctx* lineWidth) 2)
(setf (@ *ctx* strokeStyle) "#00ff00")
(let ((loc-widget-top (- *height* *loc-widget-height*))
(loc-widget ((@ document getElementById) "locwidget")))
(ctx drawImage loc-widget 0 loc-widget-top))
(ctx strokeRect
(* (- *width* *loc-widget-knob-width*)
(/ (- *position* *min-position*)
(- *max-position* *min-position*)))
loc-widget-top
*loc-widget-knob-width*
*loc-widget-height*))
(defun handle-keyboard (event)
(case (@ event keyCode)
(37 (progn (setf *position* (max (- *position* *move-speed*) *min-position*))
(setf *fish-direction* -1)
(setf *input-time* *frame*)))
(39 (progn (setf *position* (min (+ *position* *move-speed*) *max-position*))
(setf *fish-direction* 1)
(setf *input-time* *frame*)))))
(defun draw-ground ()
(setf (@ *ctx* fillStyle) "#996600")
(let ((ground-top (- *height* *loc-widget-height* *ground-height*)))
(ctx fillRect 0 ground-top *width* *ground-height*)
(with-mod-img-data (pix 0 ground-top *width* *ground-height*)
(dotimes (y *ground-height*)
(dotimes (x *width*)
(let* ((index (* 4 (+ x (* *width* y))))
(depth (+ 1.0 (* 0.5 (sin (+ (* x 1)
(* 7 y y)
*position*))))))
(setf-rgb pix index (* depth 200) (* depth 100) 0)))))))
(defun draw-aaron-fish ()
(let* ((fish-index (% (Math.floor (/ *frame* 10)) 3))
fish)
(if (< (- *frame* *input-time*) 10)
(case fish-index
(0 (setf fish ((@ document getElementById) "fish1swim")))
(1 (setf fish ((@ document getElementById) "fish2swim")))
(2 (setf fish ((@ document getElementById) "fish3swim"))))
(case fish-index
(0 (setf fish ((@ document getElementById) "fish1")))
(1 (setf fish ((@ document getElementById) "fish2")))
(2 (setf fish ((@ document getElementById) "fish3")))))
(with-ctx-state
(let ((scalar 0.5;(+ 0.5 (/ *position* 1000))
))
(ctx translate (/ *fish-width* 2) 80)
(case *fish-direction*
(-1 (ctx scale (* -1 scalar) scalar))
(1 (ctx scale scalar scalar)))
(ctx translate 0 20))
(ctx translate (/ *fish-width* -2) -80)
(let ((yoffset (* 4 (sin (* 2 pi 0.5 (/ *frame* *fps*))))))
(ctx translate 0 yoffset))
(ctx drawImage fish 0 0))))
(defun draw-water ()
(let* ((water-height (- *height* *ground-height* *loc-widget-height*))
(grad (ctx createLinearGradient 0 0 0 water-height)))
((@ grad addColorStop) 0 "#3377ff")
((@ grad addColorStop) 1 "#0000AA")
(setf (@ *ctx* fillStyle) grad)
(ctx fillRect 0 0 *width* water-height)))
(defun draw-image (id-name x-offset)
(let ((title ((@ document getElementById) id-name)))
(with-ctx-state
(ctx translate (* -1 *position*) 0)
(ctx drawImage title x-offset 0))))
(defun draw-weed (scalar x-offset y-offset parallax repeat-buffer anim-speed)
(let* ((weed-index (% (Math.floor (/ *frame* anim-speed)) 3))
weed)
(case weed-index
(0 (setf weed ((@ document getElementById) "weed1")))
(1 (setf weed ((@ document getElementById) "weed2")))
(2 (setf weed ((@ document getElementById) "weed3"))))
(with-ctx-state
(ctx translate
(- (+ *width* (/ repeat-buffer 2))
(% (+ (* parallax *position*) x-offset)
(+ *width* repeat-buffer)))
y-offset)
(ctx scale scalar scalar)
(ctx drawImage weed 0 0))))
(defun draw ()
(clear)
(setf *frame* (+ *frame* 1))
(draw-water)
(draw-ground)
(draw-weed 0.2 0 300 0.5 700 13)
(draw-weed 0.2 0 300 0.5 300 11)
(draw-weed 0.2 0 300 0.5 30 10.5)
(draw-image "title" 0)
(draw-image "lpt" 900)
(draw-image "techsmith" (* 2 900))
(draw-image "education" (* 3 900))
(draw-image "contact" (* 4 900))
(draw-aaron-fish)
(draw-loc-widget)
(draw-weed 0.5 1000 280 2.0 700 13)
(draw-weed 0.5 200 280 2.0 300 11)
)
(defun main ()
(let ((elem ((@ document getElementById) "resume-canvas")))
(when elem
(let ((ctx ((@ elem getContext) "2d")))
(when ctx
(setf *ctx* ctx)
(draw)
(setf (@ document onkeydown) handle-keyboard)
(setInterval draw *fps*))))))
| 6,015 | Common Lisp | .lisp | 152 | 32.75 | 82 | 0.53233 | clarkeaa/jsresume | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | cb46ef755d4ff2f0820eb3591d43b9d2a5c015c32082cfc626f7b28c7559d446 | 18,041 | [
-1
] |
18,045 | index.html | clarkeaa_jsresume/index.html | <html>
<head>
<link href="jsresume.css" rel="stylesheet" type="text/css">
<script src="fish.js" type="text/javascript"></script>
<title>A. Clarke Resume</title>
</head>
<body onload="main();">
<div id="canvas-div">
<canvas id="resume-canvas" width=640 height=480>
The canvas element is not supported on this browser, sorry.
</canvas>
<img id="weed1" src="img/weed1.png"></img>
<img id="weed2" src="img/weed2.png"></img>
<img id="weed3" src="img/weed3.png"></img>
<img id="fish1" src="img/fish1.png"></img>
<img id="fish2" src="img/fish2.png"></img>
<img id="fish3" src="img/fish3.png"></img>
<img id="fish1swim" src="img/fish1swim.png"></img>
<img id="fish2swim" src="img/fish2swim.png"></img>
<img id="fish3swim" src="img/fish3swim.png"></img>
<img id="title" src="img/title.png"></img>
<img id="education" src="img/education.png"></img>
<img id="lpt" src="img/lpt.png"></img>
<img id="techsmith" src="img/techsmith.png"></img>
<img id="contact" src="img/contact.png"></img>
<img id="locwidget" src="img/locwidget.png"></img>
<a href="./fish.lisp">source code</a>
<a id="return-link" href="/">return</a>
</div>
</body>
</html>
| 1,280 | Common Lisp | .l | 31 | 35.387097 | 69 | 0.598879 | clarkeaa/jsresume | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f30a9a2bcdbc20809f4a9bced627f53961ebf08dfcdc9cf02648c37768e51aa6 | 18,045 | [
-1
] |
18,060 | menus.lisp | eadmund_cl-xdg/menus.lisp | ;;;; menus.lisp
;;;; Copyright (C) 2016 Robert A. Uhl
(in-package #:cl-xdg)
(defun dont-resolve-entities (a b)
(declare (ignore a b))
(flexi-streams:make-in-memory-input-stream nil))
(defun dtd-resolver (public-id system-id)
(declare (ignore system-id))
(cond
((find public-id '("-//freedesktop//DTD Menu 1.0//EN"
"-//freedesktop//DTD Menu 0.8//EN")
:test #'string=)
(open (asdf:system-relative-pathname '#:cl-xdg "dtds/menu-latest.dtd")))))
;; (defun build-filter (source)
;; (xspam:with-xspam-source source
;; (let (exprs)
;; (xspam:zero-or-more
;; (xspam:one-of
;; (xspam:element "And"
;; (push (list 'and (build-filter source)) exprs))
;; (xspam:element "Or"
;; (push (list 'or (build-filter source)) exprs))
;; (xspam:element "Not"
;; (push (list 'not (build-filter source)) exprs))
;; (xspam:element "All"
;; (return t))
;; (xspam:element "Filename"
;; (xspam:text
;; (push (list 'filename xspam:_) exprs)))
;; (xspam:element "Category"
;; (xspam:text
;; (push (list 'category xspam:_) exprs)))))
;; (if (> (length exprs) 1)
;; (cons 'or exprs)
;; (first exprs)))))
;; (defun merge-menus (a b)
;; "Merge B into A. A should be a menu plist being processed; B should
;; be a completed menu plist.
;; 1. Merge child menus
;; 2. Resolve duplicate Move elements"
;; (flet ((extract-submenus (menu hash start)
;; (loop for submenu in (getf menu :submenus)
;; for i from start
;; for pre-existing = (gethash (getf submenu :name) hash)
;; do (setf (gethash (getf submenu :name) hash)
;; (cons i (if pre-existing
;; (merge-menus (cdr pre-existing) submenu)
;; submenu)))
;; finally (return i))))
;; (let* ((hash (make-hash-table :test 'equal))
;; submenus
;; (app-dirs (delete-duplicates (append (getf a :app-dirs)
;; (getf b :app-dirs))
;; :from-end t
;; :test #'equal))
;; (directory-dirs (delete-duplicates (append (getf a :directory-dirs)
;; (getf b :directory-dirs))
;; :from-end t
;; :test #'equal))
;; (filter-a (getf a :filter))
;; (filter-b (getf b :filter))
;; (filter (cond
;; ((and filter-a filter-b) (list filter-a filter-b))
;; (filter-a filter-a)
;; (filter-b filter-b))))
;; (extract-submenus b hash (extract-submenus a hash 0))
;; (maphash (lambda (k v)
;; (declare (ignorable k))
;; (push v submenus))
;; hash)
;; (setf submenus (mapcar #'cdr (sort submenus #'< :key #'car)))
;; `(:name ,(getf a :name)
;; ,@(when app-dirs `(:app-dirs ,app-dirs))
;; ,@(when directory-dirs `(:directory-dirs ,directory-dirs))
;; ,@(when filter `(:filter ,filter))
;; ,@(when submenus `(:submenus ,submenus))))))
(defvar *menu-files-in-flight* nil)
(defun read-menu (filespec)
(let* ((handler (make-instance 'cl-sxml:sxml-handler
:package (find-package '#:cl-xdg/sxml)))
(truename (uiop:ensure-pathname filespec))
(*menu-files-in-flight* (cons truename *menu-files-in-flight*)))
(unless truename
(error "cannot find menu file ~a" filespec))
(when (find truename (rest *menu-files-in-flight*) :test #'equal)
(error "already loading menu file ~a" filespec))
(car (merge-menus
(cxml:parse-file truename handler :entity-resolver #'dont-resolve-entities)))))
(defun merge-path (path)
(rest
(remove 'cl-xdg/sxml:|Name|
(find 'cl-xdg/sxml:|Menu|
(cdar
(merge-menus
(read-menu
(uiop:merge-pathnames* path (first *menu-files-in-flight*)))))
:key #'first)
:key (lambda (x) (when (consp x) (first x))))))
(defun merge-parent ()
;; see if the current file is a child of any XDG data directory
(let ((file (first *menu-files-in-flight*))
(data-dirs (cons (uiop:xdg-data-home) (uiop:xdg-data-dirs))))
(loop for dir in data-dirs
for path = (uiop:subpathp file dir)
when path
do (loop for parent-dir in (remove dir data-dirs :test #'equal)
for subpath = (uiop:file-exists-p
(uiop:merge-pathnames* path parent-dir))
when subpath
do (return-from merge-parent (merge-path subpath))))))
(defun merge-file (element)
(cond
((and (consp (second element))
(eq (first (second element)) 'cl-xdg/sxml:@))
(let ((type (second
(find 'cl-xdg/sxml:|type| (rest (second element)) :key #'first))))
(cond
((string= type "parent") (merge-parent))
((string= type "path") (merge-path (third element)))
(t (error "don't understand MergeFile type ~a" type)))))
((stringp (second element))
(merge-path (second element)))
(t (error "unparseable MergeFile contents: ~s" (second element)))))
(defun merge-dir (path)
(let* ((path (uiop:ensure-directory-pathname path))
(dir (uiop:subpathname
(uiop:pathname-directory-pathname(first *menu-files-in-flight*))
path))
(paths (uiop:directory* (uiop:merge-pathnames* #P"*.menu" dir))))
(append (mapcar #'merge-path paths))))
(defun merge-menus (element)
"Process MergeFile, MergeDir and LegacyDir elements, and remove
extraneous whitespace."
(typecase element
(string (let ((string (string-trim
'(#\Space #\Backspace #\Tab #\Linefeed #\Page
#\Return #\Newline #\Rubout)
element)))
(when (string/= string "")
(list string))))
(symbol (list element))
(cons (case (car element)
(cl-xdg/sxml:|MergeFile| (merge-file element))
(cl-xdg/sxml:|MergeDir| (merge-dir (second element)))
(cl-xdg/sxml:|LegacyDir| )
(t (list (apply 'concatenate 'cons (mapcar #'merge-menus element))))))))
#|(defun merge-if (element)
(when ))
(defun fold-menu (menu)
(mapl ))
(defun read-menu (path source)
(xspam:with-xspam-source source
(let (name
submenus
app-dirs
directory-dirs
directories
only-unallocated
deleted
filter)
(xspam:zero-or-more
(xspam:one-of
(xspam:element "Name"
(xspam:text
(when name
(error "more than one name in menu (have ~a; got ~a)"
name xspam:_))
(setf name xspam:_)))
(xspam:element "Menu"
(push (read-menu path source) submenus))
(xspam:element "AppDir"
(xspam:text (push xspam:_ app-dirs)))
(xspam:element "DefaultAppDirs"
(loop for dir in (reverse (cons (uiop:xdg-data-home)
(uiop:xdg-data-dirs)))
do (push (uiop:subpathname* dir #P"applications/") app-dirs)))
(xspam:element "DirectoryDir"
(xspam:text (push xspam:_ directory-dirs)))
(xspam:element "DefaultDirectoryDirs"
(loop for dir in (reverse (cons (uiop:xdg-data-home)
(uiop:xdg-data-dirs)))
do (push (uiop:subpathname* dir #P"desktop-directories/")
directory-dirs)))
(xspam:element "Directory"
(xspam:text (push xspam:_ directories)))
(xspam:element "OnlyUnallocated"
(setf only-unallocated t))
(xspam:element "NotOnlyUnallocated"
(setf only-unallocated nil))
(xspam:element "Deleted"
(setf deleted t))
(xspam:element "NotDeleted"
(setf deleted nil))
(xspam:element "Include"
;;(format t "~&inc ~a" (build-filter source)))
(push (cons 'include (build-filter source)) filter))
(xspam:element "Exclude"
(push (cons 'exclude (build-filter source)) filter))
(xspam:element "MergeFile"
(let ((type 'path)
child-path)
(xspam:optional-attribute "type"
(setf type
(cond
((string= xspam:_ "path") 'path)
((string= xspam:_ "parent") 'parent)
(t (error "Unknown MergeFile type ~a" xspam:_)))))
(xspam:optional
(xspam:text
(when (eq type 'path)
(setf child-path (pathname xspam:_)))))
(format t "~&~a ~a ~a" type child-path (uiop:relative-pathname-p child-path))
(when (and (eq type 'path) (uiop:relative-pathname-p child-path))
(setf child-path (uiop:merge-pathnames* child-path path)))
(format t "~&~a ~a" child-path (uiop:relative-pathname-p child-path))
(when (find child-path *menu-files-in-flight* :test 'equal)
;; FIXME: in the future, offer ignorable restart
(error "infinite menu merge detected"))
(push child-path *menu-files-in-flight*)
(destructuring-bind (&key child-name
child-app-dirs
child-directory-dirs
child-directories
(child-only-unallocated
nil
only-unallocated-p)
(child-deleted nil deleted-p)
child-filter)
(read-menu child-path
(xspam:make-xspam-source
child-path
:entity-resolver #'dont-resolve-entities))
(declare (ignore child-name))
(when child-app-dirs
(setf app-dirs
(delete-duplicates (append child-app-dirs app-dirs)
:from-end t)))
(when child-directory-dirs
(setf directory-dirs
(delete-duplicates (append child-directory-dirs
directory-dirs)
:from-end t)))
(when child-directories
(setf directories
(delete-duplicates (append child-directories
directories)
:from-end t)))
(when only-unallocated-p
(setf only-unallocated child-only-unallocated))
(when deleted-p
(setf deleted child-deleted))
(setf filter
(cond
((and filter child-filter) `(or filter child-filter))
(filter filter)
(child-filter child-filter))))))))
`(:name ,(or name (error "no name for menu"))
,@(when submenus `(:submenus ,(nreverse submenus)))
,@(when app-dirs `(:app-dirs ,app-dirs))
,@(when directory-dirs `(:directory-dirs ,directory-dirs))
,@(when directories `(:directories ,directories))
,@(when only-unallocated `(:only-unallocated ,only-unallocated))
,@(when deleted `(:deleted ,deleted))
,@(when filter
`(:filter ,filter))))))
(defun load-menu-file (filespec)
(when (find filespec *menu-files-in-flight* :test 'equal)
(return-from load-menu-file nil))
(let* ((path (pathname filespec))
(source (xspam:make-xspam-source
path
:entity-resolver #'dont-resolve-entities))
(*menu-files-in-flight* (cons filespec *menu-files-in-flight*)))
(xspam:with-xspam-source source
;; FIXME: after reading, deduplicate & consolidate
(xspam:element "Menu" (read-menu path source)))))
|#
| 12,536 | Common Lisp | .lisp | 277 | 34.761733 | 89 | 0.514132 | eadmund/cl-xdg | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 81b5a271fb4b418cdb12c9b90e3265b5bd1d1e38f957a03a99a7748602704f7f | 18,060 | [
-1
] |
18,061 | package.lisp | eadmund_cl-xdg/package.lisp | ;;;; package.lisp
;;;; Copyright (C) 2016 by Robert A. Uhl
(in-package "CL-USER")
(defpackage #:cl-xdg
(:use #:cl)
(:export #:load-desktop-file
#:load-desktop-files
#:find-desktop-file-by-id
#:desktop-file
#:desktop-files
#:id
#:path
#:get-string-key
#:get-strings-key
#:get-locale-string-key
#:get-locale-strings-key
#:get-boolean-key
#:get-number-key))
(defpackage #:cl-xdg/sxml
(:use)
(:export #:|Menu|
#:|Name|
#:|Directory|
#:|DefaultAppDirs|
#:|AppDir|
#:|DefaultDirectoryDirs|
#:|DirectoryDir|
#:|LegacyDir|
#:|KDELegacyDirs|
#:|MergeFile|
#:|DefaultMergeDirs|
#:|MergeDir|
#:|OnlyUnallocated|
#:|NotOnlyUnallocated|
#:|Deleted|
#:|NotDeleted|
#:|Include|
#:|Exclude|
#:|Move|
#:|Menu|
#:|Layout|
#:|DefaultLayout|
#:|prefix|
#:|type|
#:|Category|
#:|Filename|
#:|And|
#:|Or|
#:|Not|
#:|All|
#:|Old|
#:|New|
#:|Menuname|
#:|Separator|
#:|Merge|
#:|show_empty|
#:|inline|
#:|inline_limit|
#:|inline_header|
#:|inline_alias|
#:*top*
#:@
#:*doctype*
#:*pi*))
| 1,581 | Common Lisp | .lisp | 64 | 14.046875 | 40 | 0.405423 | eadmund/cl-xdg | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 4c4f663dbcffad672abb2face347525b23341032b67d4aa345d78f46422becd4 | 18,061 | [
-1
] |
18,062 | ordered-hash-table.lisp | eadmund_cl-xdg/ordered-hash-table.lisp | ;;;; ordered-hash-table.lisp
;;;; Copyright (C) 2016 Robert A. Uhl
(in-package :cl-xdg)
(defclass ordered-hash-table ()
((hash :type hash-table
:initarg :hash)
(keys :type (vector t 1)
:initarg :keys)))
(defun make-ordered-hash-table (&key
(test 'eql)
(size 16)
(rehash-size 1.5)
(rehash-threshold 1))
(make-instance 'ordered-hash-table
:hash (make-hash-table :test test
:size size
:rehash-size rehash-size
:rehash-threshold rehash-threshold)
:keys (make-array 1 :adjustable t :fill-pointer 0)))
(defun get-ordered-hash (key hash-table &optional default)
(gethash key (slot-value hash-table 'hash) default))
(defun (setf get-ordered-hash) (value key hash-table)
(with-slots (hash keys) hash-table
(let* ((newsym (gensym))
(old-value (gethash key hash newsym)))
(when (eq old-value newsym)
(vector-push-extend key keys)))
(setf (gethash key hash) value)))
(defun rem-ordered-hash (key hash-table)
(with-slots (hash keys) hash-table
(when (remhash key hash)
(let ((new-keys (remove key keys :test (hash-table-test hash))))
(setf keys (make-array (length new-keys)
:adjustable t
:initial-contents new-keys
:fill-pointer (length new-keys)))))))
(defun map-ordered-hash (function hash-table)
(with-slots (hash keys) hash-table
(when (plusp (fill-pointer keys))
(loop for i from 0 below (fill-pointer keys)
for key = (aref keys i)
do (funcall function key (gethash key hash))))))
;; maybe a WITH-ORDERED-HASH-TABLE-ITERATOR someday
| 1,930 | Common Lisp | .lisp | 43 | 32.186047 | 75 | 0.547632 | eadmund/cl-xdg | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 54a3cbfc08ea8b35c17d0f7ebe2e0f09cec9e0889213c4b5f064f81b9184a93f | 18,062 | [
-1
] |
18,063 | desktop.lisp | eadmund_cl-xdg/desktop.lisp | ;;;; cl-xdg.lisp
;;;; cl-xdg - freedesktop.org desktop file handling
;;;; Copyright (C) 2016 Robert A. Uhl
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(in-package #:cl-xdg)
(defclass desktop-files ()
((files :type hash-table
:initarg :files)))
(defclass desktop-file ()
((hash :type ordered-hash-table
:initarg :hash)
(id :type string
:initarg :id
:reader id)
(path :type pathname
:initarg :path
:reader path)))
(defun load-desktop-file (filespec)
"Load the desktop file found in FILESPEC into a DESKTOP-FILE object."
(with-open-file (file filespec :external-format asdf:*utf-8-external-format*)
;; stash each line of the file into an ordered hash table, with a
;; key designed to be easy to look up: comments just get a gensym;
;; group lines use the group name; keys use (GROUP KEY) or (GROUP
;; KEY LOCALE).
(loop with group = nil
with hash = (make-ordered-hash-table :test 'equal)
for line = (read-line file nil :eof)
until (eq line :eof)
do (destructuring-bind (key value)
(parse-desktop-file-line line group)
(when (stringp key)
(setf group key))
(setf (get-ordered-hash key hash) value))
finally (return (make-instance 'desktop-file
:hash hash
:path (pathname filespec))))))
(defun parse-desktop-file-line (line current-group)
"Given a line and the currently-active group, return a key and a
value to store in the desktop file ordered hash. The possibilities
are:
- comment: (GENSYM COMMENT)
- group: (GROUP NIL)
- key: ((GROUP KEY LOCALE) VALUE) or ((GROUP KEY) VALUE)"
(cond
;; comment
((or (string= line "") (char= (aref line 0) #\#))
(list (gensym "COMMENT") line))
;; group
((char= (aref line 0) #\[)
(if (char= (aref line (1- (length line))) #\])
(list (subseq line 1 (1- (length line))) nil)
(error "invalid group in line ~a" line)))
;; key
(t
(when (null current-group)
(error "key found without an active group"))
(let* ((pos (position #\= line))
(key (subseq line 0 pos))
(value (subseq line (1+ pos))))
(if (char= (aref key (1- (length key))) #\])
(destructuring-bind (key locale)
(split-sequence:split-sequence #\[ key :end (1- (length key)))
`((,current-group ,key ,locale) ,value))
`((,current-group ,key) ,value))))))
(defun lc-messages-to-locales ()
"Convert LC_MESSAGES to a preference-ordered list of locales."
(let ((lc-messages (uiop:getenvp "LC_MESSAGES")))
(when lc-messages
(destructuring-bind (lang country encoding modifier &aux locales)
(parse-locale lc-messages)
(declare (ignore encoding))
(when (and lang country modifier)
(push (format nil "~a_~a@~a" lang country modifier) locales))
(when (and lang country)
(push (format nil "~a_~a" lang country) locales))
(when (and lang modifier)
(push (format nil "~a@~a" lang modifier) locales))
(when lang (push lang locales))
(reverse locales)))))
(defun parse-locale (locale)
(loop for char across locale and i from 0
with lang = 0 and country and encoding and modifier
do (case char
(#\_ (cond
((integerp lang) (setf lang (subseq locale lang i)))
(t (error "Unexpected #\_.")))
(setf country (1+ i)))
(#\. (cond
((integerp lang) (setf lang (subseq locale lang i)))
((integerp country) (setf country (subseq locale country i)))
(t (error "Unexpected #\..")))
(setf encoding (1+ i)))
(#\@ (cond
((integerp lang) (setf lang (subseq locale lang i)))
((integerp country) (setf country (subseq locale country i)))
((integerp encoding) (setf encoding (subseq locale encoding i)))
(t (error "Unexpected #\@.")))
(setf modifier (1+ i))))
finally (progn
(cond
((integerp lang) (setf lang (subseq locale lang)))
((integerp country) (setf country (subseq locale country)))
((integerp encoding) (setf encoding (subseq locale encoding)))
((integerp modifier) (setf modifier (subseq locale modifier))))
(return (list lang country encoding modifier)))))
;; taken from http://cl-cookbook.sourceforge.net/strings.html
(defun replace-all (string part replacement &key (test #'char=))
"Returns a new string in which all the occurences of the part
is replaced with replacement."
(with-output-to-string (out)
(loop with part-length = (length part)
for old-pos = 0 then (+ pos part-length)
for pos = (search part string
:start2 old-pos
:test test)
do (write-string string out
:start old-pos
:end (or pos (length string)))
when pos do (write-string replacement out)
while pos)))
(defun replace-escapes (str)
(let ((escapes '(("\\s" . " ")
("\\n" . "
")
("\\t" . " ")
("\\r" . "
")
("\\\\" . "\\"))))
(loop for (escape . replacement) in escapes
do (setf str (replace-all str escape replacement)))
str))
(defun get-string-key (key file &key (group "Desktop Entry"))
(let ((str (get-ordered-hash `(,group ,key) (slot-value file 'hash))))
(when str
(replace-escapes str))))
(defun split-multi-string (str)
(loop for char across str
with items and acc and in-escape
do (case char
(#\\ (if in-escape
(push #\\ acc)
(setf in-escape t)))
(#\s (push (if in-escape
#\Space
#\s)
acc))
(#\n (push (if in-escape
#\Newline
#\n)
acc))
(#\t (push (if in-escape
#\Tab
#\t)
acc))
(#\r (push (if in-escape
#\Return
#\r)
acc))
(#\; (if in-escape
(push #\; acc)
(progn (push (coerce (reverse acc) 'string) items)
(setf acc nil))))
(t (push char acc)))
finally (progn
(when acc
(push (coerce (reverse acc) 'string) items))
(return (reverse items)))))
(defun get-strings-key (key file &key (group "Desktop Entry"))
(let ((str (get-ordered-hash `(,group ,key) (slot-value file 'hash))))
(when str
(split-multi-string str))))
(defun get-locale-string-key (key file &key
(group "Desktop Entry")
(locales (lc-messages-to-locales)))
(loop for locale in locales
for value = (get-ordered-hash (append `(,group ,key) `(,locale))
(slot-value file 'hash))
when value
do (return (replace-escapes value))
finally (return (get-string-key key file :group group))))
(defun get-locale-strings-key (key file &key
(group "Desktop Entry")
(locales (lc-messages-to-locales)))
(loop for locale in locales
for value = (get-ordered-hash (append `(,group ,key) `(,locale))
(slot-value file 'hash))
when value
do (return (split-multi-string value))
finally (return (get-strings-key key file :group group))))
(defun get-boolean-key (key file &key (group "Desktop Entry"))
(let ((value (get-ordered-hash `(,group ,key) (slot-value file 'hash))))
(when value
(cond
((string= value "false") nil)
((string= value "true") t)
(t (error "malformed boolean"))))))
(defun get-number-key (key file &key (group "Desktop Entry"))
"PARSE-NUMBER:PARSE-NUMBER doesn't _quite_ implement the semantics
of strtod/sscanf, but it's portable. The desktop file spec doesn't
define any standard number keys anyway."
(let ((value (get-ordered-hash `(,group ,key) (slot-value file 'hash))))
(when value
(parse-number:parse-real-number value))))
(defun load-desktop-files (&optional (subdir #P"applications/"))
"Load desktop files from SUBDIR underneath $XDG_DATA_HOME and each
of $XDG_DATA_DIRS. Desktop files found under #P\"applications/\"
have IDs; files earlier in the search path take precedence over
files later in the search path with the same ID."
;; FIXME: this is hideous code
(loop for (file . id) in (mapcan (lambda (dir)
(let ((subdir (uiop:merge-pathnames* subdir dir)))
(mapcar (lambda (file)
(cons file (replace-all (namestring (uiop:subpathp file subdir)) "/" "-")))
(uiop:directory*
(uiop:merge-pathnames*
"*.desktop"
(uiop:wilden subdir))))))
(cons (uiop:xdg-data-home) (uiop:xdg-data-dirs)))
with hash = (make-hash-table :test 'equal)
unless (gethash id hash)
do (let ((desktop-file (load-desktop-file file)))
(setf (gethash id hash) desktop-file
(slot-value desktop-file 'id) id))
finally (return (make-instance 'desktop-files :files hash))))
(defun find-desktop-file-by-id (files id)
"Find the desktop file with the given ID in FILES."
(gethash id (slot-value files 'files)))
| 10,809 | Common Lisp | .lisp | 238 | 33.941176 | 124 | 0.548289 | eadmund/cl-xdg | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 97015959281cee85eb879595bd12a1a0f30f24789c8989cc82146428cecfcefe | 18,063 | [
-1
] |
18,064 | test.lisp | eadmund_cl-xdg/test.lisp | ;;;; test.lisp
;;;; Copyright (C) 2016 by Robert A. Uhl
(in-package "CL-USER")
(defpackage #:cl-xdg-test
(:use #:cl #:fiveam #:cl-xdg))
(in-package #:cl-xdg-test)
(def-suite cl-xdg)
(in-suite cl-xdg)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun canonicalise-env-binding (binding)
;; user bindings may be of the form "VAR", VAR, ("VAR" value) or (VAR value)
(etypecase binding
(list
(etypecase (first binding)
(symbol (setf (first binding) (symbol-name (first binding))))
(string))
(push (gensym (concatenate 'string "OLD-" (first binding))) binding))
(string (list (gensym (concatenate 'string "OLD-" binding)) binding ""))
(symbol (list (gensym (concatenate 'string "OLD-" (symbol-name binding)))
(symbol-name binding)
""))))
(defmacro with-env (bindings &body body)
"Set environment variables to values according to BINDINGS, then
execute BODY, the revert the environment variable settings.
Bindings may be of the form VARIABLE (a symbol),
\"VARIABLE\", (VARIABLE VALUE) or (\"VARIABLE\" value). Values must
evaluate to strings.
BUG: cannot unset an environment variable, but rather sets it to \"\"."
(loop for binding in (mapcar #'canonicalise-env-binding bindings)
with return-value = (gensym "RETURN-VALUE")
collect `(,(first binding) (uiop:getenvp ,(second binding))) into let-bindings
collect `(setf (uiop:getenv ,(second binding)) ,(third binding)) into setf-bindings
collect `(setf (uiop:getenv ,(second binding)) (or ,(first binding) "")) into unsetf-bindings
finally (return `(let (,return-value ,@let-bindings)
,@setf-bindings
(setf ,return-value (progn ,@body))
,@unsetf-bindings
,return-value)))))
(test load-desktop-files
(with-env (("XDG_DATA_HOME"
(namestring (asdf:system-relative-pathname '#:cl-xdg #P"test/")))
("XDG_DATA_DIRS" "/PATH/to/NOWHERE/7c1cef10-d57d-466d-9efc-f97110db112d/"))
(let ((files (load-desktop-files)))
(is-true files)
(is (= (hash-table-count (slot-value files 'cl-xdg::files)) 1))
(is-true (cl-xdg::find-desktop-file-by-id files "foo.desktop")))))
(test desktop-file
(with-env (("XDG_DATA_HOME"
(namestring (asdf:system-relative-pathname '#:cl-xdg #P"test/")))
("XDG_DATA_DIRS" "/path/TO/nowhere/6d1a6023-c194-4a70-a3c2-0e0c19df2bac/"))
(let* ((files (load-desktop-files))
(file (cl-xdg::find-desktop-file-by-id files "foo.desktop")))
(is (null (get-string-key "Does-not-exist" file)))
(is (string= (get-string-key "Name" file) "Test"))
(is (string= (get-string-key "Field2" file) "Test2"))
(is (string= (get-locale-string-key "Field2" file :locales '("en")) "Test3"))
(is (string= (get-locale-string-key "Field2" file :locales '("en@test")) "Test4"))
(is (string= (get-locale-string-key "Field2" file :locales '("en_US")) "Test5"))
(is (string= (get-locale-string-key "Field2" file :locales '("en_US@test")) "Test6"))
(is (string= (get-locale-string-key "Field2" file :locales '("ang")) "Hw√¶t"))
(is (= (get-number-key "Field3" file) 12))
(is-true (get-boolean-key "Field4" file)))))
(test read-menu
(let ((menu (cl-xdg::read-menu "test/menus/applications.menu")))
(is-true menu)))
(run!)
| 3,483 | Common Lisp | .lisp | 66 | 45.227273 | 100 | 0.62232 | eadmund/cl-xdg | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2aafb5ce3930ba960b9a0f95be48e23c2eb15e545eb2eb0dd24d6fdda1f52822 | 18,064 | [
-1
] |
18,065 | cl-xdg.asd | eadmund_cl-xdg/cl-xdg.asd | ;;;; cl-xdg.asd
;;;; Copyright (C) 2016 by Robert A. Uhl
(asdf:defsystem #:cl-xdg
:description "freedesktop.org standards handling"
:author "Bob Uhl <[email protected]>"
:license "GNU General Public License"
:serial t
:depends-on (#:uiop
#:split-sequence
#:parse-number
#:flexi-streams
#:cl-sxml
#:cl-xmlspam
#+sbcl #:sb-posix )
:in-order-to ((test-op (test-op #:cl-xdg-test)))
:components ((:file "package")
(:file "ordered-hash-table")
(:file "desktop")
(:file "menus")))
(defsystem #:cl-xdg-test
:depends-on (#:cl-xdg #:fiveam #:asdf #:uiop)
:components ((:file "package")
(:file "test"))
:perform (test-op (o s)
(let ((results
(uiop:symbol-call '#:fiveam
'#:run
(uiop:find-symbol* '#:cl-xdg
'#:cl-xdg-test))))
(unless (uiop:symbol-call '#:fiveam '#:results-status
results)
(uiop:symbol-call :fiveam '#:explain! results)
(warn "tests failed")))))
| 1,347 | Common Lisp | .asd | 33 | 24.939394 | 82 | 0.4375 | eadmund/cl-xdg | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a024f22477aacfe257ed89aca83c2952537d6c4473a75f7e2685ecdd5ce4bd4e | 18,065 | [
-1
] |
18,073 | applications.menu | eadmund_cl-xdg/test/menus/applications.menu | <!DOCTYPE Menu PUBLIC "-//freedesktop//DTD Menu 1.0//EN"
"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd">
<!--
taken from https://specifications.freedesktop.org/menu-spec/menu-spec-1.1.html#example
-->
<Menu>
<Name>Applications</Name>
<Directory>Applications.directory</Directory>
<DefaultAppDirs/>
<DefaultDirectoryDirs/>
<MergeFile type="parent" />
<MergeDir>applications-merged</MergeDir>
<LegacyDir>/usr/share/applnk</LegacyDir>
<DefaultLayout>
<Merge type="menus"/>
<Merge type="files"/>
<Separator/>
<Menuname>More</Menuname>
</DefaultLayout>
<Move>
<Old>Foo</Old>
<New>Bar</New>
<Old>Foo2</Old>
<New>Bar2</New>
</Move>
<Menu>
<Name>Preferences</Name>
<Directory>Preferences.directory</Directory>
<MergeFile>preferences.menu</MergeFile>
</Menu>
<Menu>
<Name>Office</Name>
<Directory>Office.directory</Directory>
<Include>
<Category>Office</Category>
</Include>
<Exclude>
<Filename>foo.desktop</Filename>
</Exclude>
</Menu>
</Menu>
| 1,047 | Common Lisp | .l | 41 | 22.195122 | 87 | 0.703815 | eadmund/cl-xdg | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 46542b4a4b0853b6026f28e2a990a666dc5371d7d12e3051b69908c0d5d3a1db | 18,073 | [
-1
] |
18,074 | menu-latest.dtd | eadmund_cl-xdg/dtds/menu-latest.dtd | <!-- For explanations see http://www.freedesktop.org/standards/menu-spec -->
<!ELEMENT Menu (
Name, (
Directory
| DefaultAppDirs
| AppDir
| DefaultDirectoryDirs
| DirectoryDir
| LegacyDir
| KDELegacyDirs
| MergeFile
| DefaultMergeDirs
| MergeDir
| OnlyUnallocated
| NotOnlyUnallocated
| Deleted
| NotDeleted
| Include
| Exclude
| Move
| Menu
| Layout
| DefaultLayout
)*
)>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT Directory (#PCDATA)>
<!ELEMENT DefaultAppDirs EMPTY>
<!ELEMENT AppDir (#PCDATA)>
<!ELEMENT DefaultDirectoryDirs EMPTY>
<!ELEMENT DirectoryDir (#PCDATA)>
<!ELEMENT LegacyDir (#PCDATA)>
<!ATTLIST LegacyDir prefix CDATA #IMPLIED>
<!ELEMENT KDELegacyDirs EMPTY>
<!ELEMENT MergeFile (#PCDATA)>
<!ATTLIST MergeFile type (path|parent) #IMPLIED>
<!ELEMENT DefaultMergeDirs EMPTY>
<!ELEMENT MergeDir (#PCDATA)>
<!ELEMENT OnlyUnallocated EMPTY>
<!ELEMENT NotOnlyUnallocated EMPTY>
<!ELEMENT Deleted EMPTY>
<!ELEMENT NotDeleted EMPTY>
<!ELEMENT Exclude ((Category|Filename|And|Or|Not|All)*)>
<!ELEMENT Include ((Category|Filename|And|Or|Not|All)*)>
<!ELEMENT And ((Category|Filename|And|Or|Not|All)*)>
<!ELEMENT Or ((Category|Filename|And|Or|Not|All)*)>
<!ELEMENT Not ((Category|Filename|And|Or|Not|All)*)>
<!ELEMENT Filename (#PCDATA)>
<!ELEMENT Category (#PCDATA)>
<!ELEMENT All EMPTY>
<!ELEMENT Move ((Old,New)*)>
<!ELEMENT Old (#PCDATA)>
<!ELEMENT New (#PCDATA)>
<!ELEMENT Layout ((Filename|Menuname|Separator|Merge)*)>
<!ELEMENT DefaultLayout ((Filename|Menuname|Separator|Merge)*)>
<!ATTLIST DefaultLayout show_empty (true|false) #IMPLIED>
<!ATTLIST DefaultLayout inline (true|false) #IMPLIED>
<!ATTLIST DefaultLayout inline_limit CDATA #IMPLIED>
<!ATTLIST DefaultLayout inline_header (true|false) #IMPLIED>
<!ATTLIST DefaultLayout inline_alias (true|false) #IMPLIED>
<!ELEMENT Menuname (#PCDATA)>
<!ATTLIST Menuname inline (true|false) #IMPLIED>
<!ATTLIST Menuname inline_limit CDATA #IMPLIED>
<!ATTLIST Menuname inline_header (true|false) #IMPLIED>
<!ATTLIST Menuname inline_alias (true|false) #IMPLIED>
<!ELEMENT Separator EMPTY>
<!ELEMENT Merge EMPTY>
<!ATTLIST Merge type (menus|files|all) #REQUIRED>
| 2,220 | Common Lisp | .l | 68 | 31.058824 | 76 | 0.738764 | eadmund/cl-xdg | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2026d6866c5f769ec4e34a630d6daa456c375a89ce879fadbff33cb87d6d69b0 | 18,074 | [
-1
] |
18,089 | package.lisp | iamgreaser_orionsfurnace-cl/src/package.lisp | ;;;; package.lisp
(defpackage #:orions-furnace
(:use #:cl #:alexandria)
(:export #:run))
(in-package #:orions-furnace)
(defmacro standard-optimisation-settings ()
(progn))
;; Feel free to play around with these if it starts sucking in one direction --GM
(defmacro standard-optimisation-settings ()
`(declaim (optimize (speed 0) (compilation-speed 0) (space 3) (debug 2) (safety 3))))
| 396 | Common Lisp | .lisp | 10 | 37.4 | 87 | 0.722513 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f1a90419a801a3a07bf35cfb79e0a032150ce797d881f1249b5e1064d98b5549 | 18,089 | [
-1
] |
18,090 | orions-furnace.lisp | iamgreaser_orionsfurnace-cl/src/orions-furnace.lisp | ;;;; orions-furnace.lisp
(in-package #:orions-furnace)
(standard-optimisation-settings)
(defparameter *base-screen-width* 640)
(defparameter *base-screen-height* 360)
(defparameter *screen-scale* 2)
(defparameter *cell-w* 24)
(defparameter *cell-h* 24)
(defparameter *cam-w-cells* 15)
(defparameter *cam-h-cells* 15)
(defparameter *cam-x* 0)
(defparameter *cam-y* 0)
(define-symbol-macro *cam-w* (* *cell-w* *cam-w-cells*))
(define-symbol-macro *cam-h* (* *cell-h* *cam-h-cells*))
(defparameter *cam-offs-x* nil)
(defparameter *cam-offs-y* nil)
(define-symbol-macro *sidebar-x* *cam-w*)
(define-symbol-macro *sidebar-y* 0)
(define-symbol-macro *sidebar-w* (- *base-screen-width* *sidebar-x*))
(define-symbol-macro *sidebar-h* *base-screen-height*)
(defparameter *window* nil)
(defparameter *renderer* nil)
(defparameter *backbuf* nil)
(defparameter *current-render-target* nil)
;; FIXME: TEMPORARY REPRESENTATION --GM
(defparameter *player-walk-key-xn* nil)
(defparameter *player-walk-key-yn* nil)
(defparameter *player-walk-key-xp* nil)
(defparameter *player-walk-key-yp* nil)
(defparameter *board* nil)
(defparameter *player-entity* nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| 1,227 | Common Lisp | .lisp | 32 | 37.03125 | 76 | 0.69789 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 11dd271ff3b6e1279554b790ff3221e2a4265c9f8be40d361acd9b4708018669 | 18,090 | [
-1
] |
18,091 | board.lisp | iamgreaser_orionsfurnace-cl/src/board.lisp | (in-package #:orions-furnace)
(standard-optimisation-settings)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Generics
(defgeneric cell-on-board (board cx cy)
(:documentation "Given a board, does the given cell exist?"))
(defgeneric can-enter-cell (board entity cx cy)
(:documentation "Can, on the given board, the given entity enter the cell at the given position?"))
(defgeneric draw-tile-at-lower (board cx cy px py)
(:documentation "Draws a tile onto somewhere on the screen - lower z-level."))
(defgeneric draw-tile-at-upper (board cx cy px py)
(:documentation "Draws a tile onto somewhere on the screen - upper z-level."))
(defgeneric board-entities-at (board cx cy)
(:documentation "The list of entities at a given cell on a board."))
(defgeneric (setf board-entities-at) (entities board cx cy)
(:documentation "Setter for the list of entities at a given cell on a board."))
(defgeneric board-tile-at (board cx cy)
(:documentation "The tile at a given cell on a board."))
(defgeneric (setf board-tile-at) (tile board cx cy)
(:documentation "Setter for the tile at a given cell on a board."))
(defgeneric tile-graphics (tile board cx cy)
(:documentation "Returns (values texture src-cx src-cy) for a given tile."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod board-entities-at ((board board) cx cy)
(with-slots (entities-grid) board
(aref entities-grid cx cy)))
(defmethod (setf board-entities-at) (entities (board board) cx cy)
(with-slots (entities-grid) board
(setf (aref entities-grid cx cy) entities)))
(defmethod board-tile-at ((board null) cx cy) :space)
(defmethod board-tile-at ((board board) cx cy)
(if (cell-on-board board cx cy)
(with-slots (tile-grid) board
(aref tile-grid cx cy))
:space))
(defmethod (setf board-tile-at) (tile (board board) cx cy)
(with-slots (tile-grid) board
(setf (aref tile-grid cx cy) tile)))
(defun generate-board (&key (w 64) (h 64))
"Generates and returns a board."
;; TODO: Have some sort of tile type enum here --GM
(let* ((tile-grid (make-array `(,w ,h)
:initial-element :floor))
(entities-grid (make-array `(,w ,h)
:initial-element nil))
(board (make-instance 'board
:tile-grid tile-grid
:entities-grid entities-grid)))
(prog1 board
;; TODO: Have some fun with this --GM
(setf (board-tile-at board 4 7) :wall)
(setf (board-tile-at board 5 7) :wall)
(setf (board-tile-at board 4 8) :wall)
(setf (board-tile-at board 5 8) :wall)
(setf (board-tile-at board 5 9) :wall)
(setf (board-tile-at board 6 10) :wall)
(setf (board-tile-at board 7 9) :wall)
(setf (board-tile-at board 6 4) :closed-door)
;; Floor tiles
(let* ((entity (make-instance 'floor-tile-entity
:board board
:x 8
:y 4)))
(setf (entity-walk-cooldown entity) 40)
(setf (entity-walk-dx entity) -1)
(setf (entity-walk-dy entity) -2)
(vector-push-extend
entity
(board-entities-array board)))
;; Dummy player
(let* ((entity (make-instance 'player-entity
:board board
:x 10
:y 3)))
(setf (entity-walk-dx entity) -1)
(setf (entity-walk-dy entity) 0)
(vector-push-extend
entity
(board-entities-array board)))
)))
(defmethod cell-on-board ((board (eql nil)) cx cy)
;; Nothing has no cells.
nil)
(defmethod cell-on-board ((board board) cx cy)
(with-slots (tile-grid) board
(destructuring-bind (bw bh) (array-dimensions tile-grid)
(and (<= 0 cx bw)
(<= 0 cy bh)))))
(defmethod can-enter-cell ((board (eql nil)) (entity entity) cx cy)
;; Normal entities cannot move around in nothingness.
nil)
(defmethod can-enter-cell ((board board) (entity entity) cx cy)
(block result
(macrolet ((nope! () `(return-from result nil)))
(with-slots (tile-grid
entities-grid)
board
(destructuring-bind (bw bh) (array-dimensions tile-grid)
(unless (<= 0 cx bw) (nope!))
(unless (<= 0 cy bh) (nope!))
;; Check against the tile grid
(case (aref tile-grid cx cy)
;; These are good
(:space)
(:floor)
;; These are not
(t (nope!))
)
;; Check against the entities list
(dolist (other (board-entities-at board cx cy))
;; If it exists, check if we can enter into it
(when (and (is-in-player-space entity)
(is-in-player-space other))
;; Nope!
(nope!)))
;; OK, we're good!
t)))))
(defmethod draw-tile-at-lower ((board board) cx cy px py)
(with-slots (tile-grid
entities-grid
)
board
(destructuring-bind (bw bh) (array-dimensions tile-grid)
(when (and (<= 0 cx bw)
(<= 0 cy bh))
(multiple-value-bind (texture sx sy) (tile-graphics (board-tile-at board cx cy)
board cx cy)
(with-pooled-rects ((d-rect px py *cell-w* *cell-h*)
(s-rect (* *cell-w* sx)
(* *cell-h* sy)
*cell-w* *cell-h*))
(sdl2:render-copy *renderer* texture
:source-rect s-rect
:dest-rect d-rect)))
))))
(defmethod tile-graphics ((tile (eql :floor)) board cx cy)
(values *gfx-tiles-floor001* 0 0))
(defmethod tile-graphics ((tile (eql :wall)) board cx cy)
(let* ((sx 0) (sy 0))
(when (eql tile (board-tile-at board (1+ cx) cy)) (incf sx 1))
(when (eql tile (board-tile-at board (1- cx) cy)) (incf sx 2))
(when (eql tile (board-tile-at board cx (1+ cy))) (incf sy 1))
(when (eql tile (board-tile-at board cx (1- cy))) (incf sy 2))
(values *gfx-tiles-wall001* sx sy)))
;; Fallback
(defmethod tile-graphics ((tile t) board cx cy)
(values *gfx-unknown* 0 0))
(defmethod draw-tile-at-upper ((board board) cx cy px py)
(with-slots (tile-grid
entities-grid
)
board
(destructuring-bind (bw bh) (array-dimensions tile-grid)
(when (and (<= 0 cx bw)
(<= 0 cy bh))
(dolist (entity (reverse (aref entities-grid cx cy)))
(draw-entity entity))
))))
(defmethod tick ((board board))
;; Tick entities
(with-slots (entities-array) board
(dotimes (i (fill-pointer entities-array))
(tick (aref entities-array i))))
)
| 7,027 | Common Lisp | .lisp | 164 | 33.176829 | 101 | 0.555117 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a5ca6158f2f1cfc29a473141e0c4ca92066e92ce344a224f32b370ae139a2aa1 | 18,091 | [
-1
] |
18,092 | tick.lisp | iamgreaser_orionsfurnace-cl/src/tick.lisp | ;;;; tick.lisp
(in-package #:orions-furnace)
(standard-optimisation-settings)
(defparameter *ticks-per-second* 60)
(defparameter *last-tick-secs* nil)
(defparameter *last-tick-frames* nil)
(defun run-ticks ()
(let* ((sec-current (/ (get-internal-real-time) internal-time-units-per-second))
(frame-current (floor (* sec-current *ticks-per-second*))))
;; Do we have a previous time?
(when *last-tick-secs*
;; Yes - take a delta.
(let* ((frame-delta (- frame-current *last-tick-frames*)))
(dotimes (reps frame-delta)
(run-one-tick))))
;; Set last tick.
(setf *last-tick-secs* sec-current)
(setf *last-tick-frames* frame-current)))
(defun run-one-tick ()
(let* ((walk-dx 0)
(walk-dy 0))
;; Calculate walk direction
(when *player-walk-key-xn* (decf walk-dx))
(when *player-walk-key-xp* (incf walk-dx))
(when *player-walk-key-yn* (decf walk-dy))
(when *player-walk-key-yp* (incf walk-dy))
(setf walk-dx (max -1 (min 1 walk-dx)))
(setf walk-dy (max -1 (min 1 walk-dy)))
(setf (entity-walk-dx *player-entity*) walk-dx)
(setf (entity-walk-dy *player-entity*) walk-dy)
;; Tick the board!
(tick *board*)
))
| 1,224 | Common Lisp | .lisp | 33 | 32.212121 | 82 | 0.632291 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | aa30b3913c698d0f3758b48ce39fd6b049fb25b8b53aef9e24c885cf18514f9f | 18,092 | [
-1
] |
18,093 | classes.lisp | iamgreaser_orionsfurnace-cl/src/classes.lisp | (in-package #:orions-furnace)
(standard-optimisation-settings)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Serialisation
(defmacro define-serial-class (class-name (&rest subclasses)
(&body field-defs)
&body extra-params)
`(progn
(defclass ,class-name (,@subclasses)
(,@field-defs)
,@extra-params)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Widespread generics
(defgeneric tick (thing)
(:documentation "Ticks... well, anything really."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar *entity-id-counter* 0)
(define-serial-class entity ()
((id :type (unsigned-byte 32)
:accessor entity-id
:initarg :id
:initform (prog1 *entity-id-counter* (incf *entity-id-counter*)))
(board :type (or null board)
:accessor entity-board
:initform nil
:initarg :board)
(cx :type (signed-byte 16)
:accessor entity-cx
:initform -1
:initarg :x)
(cy :type (signed-byte 16)
:accessor entity-cy
:initform -1
:initarg :y)
(cooldown-ticks :type (unsigned-byte 16)
:accessor entity-cooldown-ticks
:initform 0)
(walk-cooldown :type (signed-byte 16)
:accessor entity-walk-cooldown
:initform 8)
;; Input handling
(walk-dx :type (signed-byte 8)
:accessor entity-walk-dx
:initform 0)
(walk-dy :type (signed-byte 8)
:accessor entity-walk-dy
:initform 0)
;; For lerping
(lerp-pdx :type (signed-byte 32)
:accessor entity-lerp-pdx
:initform 0)
(lerp-pdy :type (signed-byte 32)
:accessor entity-lerp-pdy
:initform 0)
(lerp-num :type (unsigned-byte 16)
:accessor entity-lerp-num
:initform 0)
(lerp-den :type (unsigned-byte 16)
:accessor entity-lerp-den
:initform 0)
)
(:documentation "An entity with a position which can be bound to a board. Subclass me!"))
(define-serial-class player ()
((id :type (unsigned-byte 16)
:initarg :id
:initform (error "Must provide :ID"))
(entity :type (or null entity) :initform nil :initarg :entity)
)
(:documentation "A player which can be bound to an entity."))
(define-serial-class board ()
((id :type (unsigned-byte 32)
:accessor board-id
:initarg :id
:initform (prog1 *entity-id-counter* (incf *entity-id-counter*)))
;; TODO: Have some sort of tile type enum here --GM
(tile-grid :type (simple-array keyword (* *))
:initarg :tile-grid
:initform (error "Must provide :ENTITIES-GRID"))
(entities-grid :type (simple-array list (* *))
:initarg :entities-grid
:initform (error "Must provide :ENTITIES-GRID"))
(entities-array :type (array list (*))
:accessor board-entities-array
:initform (make-array `(0)
:element-type 'entity
:adjustable t
:fill-pointer 0))
)
(:documentation "A board with a lot of things in it."))
| 3,400 | Common Lisp | .lisp | 89 | 28.516854 | 91 | 0.525917 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5a32b775d3223cfe868dcd5573bd4e32dc31af32990b1d4f865712ad60756c87 | 18,093 | [
-1
] |
18,094 | run.lisp | iamgreaser_orionsfurnace-cl/src/run.lisp | ;;;; run.lisp
(in-package #:orions-furnace)
(standard-optimisation-settings)
(defun main ()
(sdl2:with-init (:video)
(with-overall-rects-pool ()
(sdl2:with-window (*window* :title "Orion's Furnace (Lisp version)"
:w (* *base-screen-width* *screen-scale*)
:h (* *base-screen-height* *screen-scale*))
(sdl2:with-renderer (*renderer* *window* :flags '())
(with-image-lib ()
(with-ttf-lib ()
(with-game-assets ()
(with-texture (*backbuf* *renderer*
sdl2:+pixelformat-bgra8888+
:target
*base-screen-width*
*base-screen-height*)
(core-event-loop)
)))))))))
(defun run ()
(sdl2:make-this-thread-main #'main))
(defmacro with-game-state (() &body body)
`(let* ((*board* (generate-board))
(*player-entity* (make-instance 'player-entity
:board *board*
:x 3 :y 2)))
(vector-push-extend
*player-entity*
(board-entities-array *board*))
,@body))
(defun core-event-loop ()
(with-game-state ()
(sdl2:with-event-loop ()
(:keydown (:keysym keysym) (handle-key keysym t))
(:keyup (:keysym keysym) (handle-key keysym nil))
(:quit () t)
(:idle () (handle-idle))
)))
(defun handle-key (keysym pressed)
(keysym-case keysym
;; Movement keys
(:a (setf *player-walk-key-xn* pressed))
(:d (setf *player-walk-key-xp* pressed))
(:w (setf *player-walk-key-yn* pressed))
(:s (setf *player-walk-key-yp* pressed))
;; G: Collect garbage
(:g (when pressed (let () #+sbcl (sb-ext:gc :full t))))
;; R: Show "room" (memory stats)
(:r (when pressed (room t)))
;; Escape: Quit
(:escape
(when (not pressed)
(sdl2:push-quit-event)))
))
(defun handle-idle ()
;; TODO!
(run-ticks)
(draw-frame)
(sleep 1/1000)
)
| 2,139 | Common Lisp | .lisp | 61 | 24.704918 | 77 | 0.504112 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fffe8821d6d31d48096d7014201e424ac9efe3384203513ded4228a60c6b2a15 | 18,094 | [
-1
] |
18,095 | draw.lisp | iamgreaser_orionsfurnace-cl/src/draw.lisp | ;;;; draw.lisp
(in-package #:orions-furnace)
(standard-optimisation-settings)
(defun draw-frame ()
(with-render-target (*renderer* *backbuf*)
;; Clear screen
(sdl2:set-render-draw-color *renderer* 85 85 255 0)
(sdl2:render-clear *renderer*)
;; Draw things
(draw-playfield)
(draw-sidebar)
(draw-gui)
)
;; Blit and present
(sdl2:render-copy *renderer* *backbuf*)
(sdl2:render-present *renderer*)
)
(defun draw-playfield ()
(with-pooled-rects ((clip *cam-x* *cam-y* *cam-w* *cam-h*))
(sdl2:set-render-draw-color *renderer* 40 0 20 0)
(sdl2:render-fill-rect *renderer* clip)
(sdl2:set-render-draw-color *renderer* 255 255 255 255)
(let* ((cam-pixel-x (+ (entity-vis-px *player-entity*) (floor *cell-w* 2)))
(cam-pixel-y (+ (entity-vis-py *player-entity*) (floor *cell-h* 2)))
(*cam-offs-x* (- cam-pixel-x (floor *cam-w* 2)))
(*cam-offs-y* (- cam-pixel-y (floor *cam-h* 2)))
)
;; Draw tiles with entities
(do ((cy 0 (1+ cy)))
((>= (- (* *cell-h* cy) *cam-offs-y*) *cam-h*))
(do ((cx 0 (1+ cx)))
((>= (- (* *cell-w* cx) *cam-offs-x*) *cam-w*))
(draw-tile-lower cx cy)))
(do ((cy 0 (1+ cy)))
((>= (- (* *cell-h* cy) *cam-offs-y*) *cam-h*))
(do ((cx 0 (1+ cx)))
((>= (- (* *cell-w* cx) *cam-offs-x*) *cam-w*))
(draw-tile-upper cx cy)))
)))
(defun draw-tile-lower (cx cy)
(let* ((px (- (* *cell-w* cx) *cam-offs-x*))
(py (- (* *cell-h* cy) *cam-offs-y*)))
(draw-tile-at-lower *board* cx cy px py)))
(defun draw-tile-upper (cx cy)
(let* ((px (- (* *cell-w* cx) *cam-offs-x*))
(py (- (* *cell-h* cy) *cam-offs-y*)))
(draw-tile-at-upper *board* cx cy px py)))
(defun draw-sidebar ()
(with-pooled-rects ((clip *sidebar-x* *sidebar-y* *sidebar-w* *sidebar-h*))
(sdl2:set-render-draw-color *renderer* 0 0 0 0)
(sdl2:render-fill-rect *renderer* clip)
(draw-text (+ *sidebar-x* 10)
(+ *sidebar-y* 10)
(format nil "Pos (~d, ~d)"
(entity-cx *player-entity*)
(entity-cy *player-entity*))
170 170 255)
))
(defun draw-gui ()
)
;; I added a font cache as part of trying to fix a memory leak,
;; but it turns out the memory leak was in with-pooled-rects.
;; If it's crap, feel free to get rid of it.
;; But if it helps, feel free to keep it. --GM
(defvar *font-texture-cache* nil)
(defparameter *font-texture-cache-max* 50)
(defparameter *font-texture-cache-reduce-to* 10)
(defun draw-text (px py text &optional (r 255) (g 255) (b 255) (a 255))
(let* ((key (list text r g b a))
(assoc-result (assoc key *font-texture-cache* :test #'equal))
(texture (cdr assoc-result)))
(unless texture
;;(format t "Cache len ~d~%" (length *font-texture-cache*))
(setf texture (make-new-text-texture text r g b a))
(push (cons key texture) *font-texture-cache*)
(when (>= (length *font-texture-cache*) *font-texture-cache-max*)
;;(format t "Reducing~%")
(setf *font-texture-cache*
(subseq *font-texture-cache*
0 *font-texture-cache-reduce-to*))))
(with-pooled-rects ((d-rect px py
(sdl2:texture-width texture)
(sdl2:texture-height texture)))
(sdl2:render-copy *renderer* texture :dest-rect d-rect))))
(defun make-new-text-texture (text r g b a)
(let* ((surface (sdl2-ttf:render-utf8-blended
*font-base*
text
r g b a)))
(let* ((texture (sdl2:create-texture-from-surface *renderer* surface)))
;; cl-sdl2-ttf autocollects its surfaces,
;; and I'm considering patching it to not do that --GM
;;(sdl2:free-surface surface)
texture)))
| 3,912 | Common Lisp | .lisp | 94 | 33.978723 | 79 | 0.560084 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | df8f1377b6d6c45d3eda41c3bc88f69367d97c6abe014353180b70787d9bbc9d | 18,095 | [
-1
] |
18,096 | macros.lisp | iamgreaser_orionsfurnace-cl/src/macros.lisp | ;;;; macros.lisp
(in-package #:orions-furnace)
(standard-optimisation-settings)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SDL2 WITH- helpers
(defmacro with-image-lib ((&key (formats '(:png))) &body body)
"Temporarily loads the SDL2_Image library."
`(unwind-protect
(progn
(sdl2-image:init ',formats)
,@body)
(sdl2-image:quit)))
(defmacro with-ttf-lib (() &body body)
"Temporarily loads the SDL2_TTF library."
`(unwind-protect
(progn
(sdl2-ttf:init)
,@body)
(sdl2-ttf:quit)))
(defmacro with-render-target ((renderer texture) &body body)
"Uses a texture as a render target for the duration of the block."
(with-gensyms (g-renderer g-texture)
`(let* ((,g-renderer ,renderer)
(,g-texture ,texture))
(unwind-protect
(let* ((*current-render-target* ,g-texture))
(sdl2:set-render-target ,g-renderer ,g-texture)
,@body)
(sdl2:set-render-target ,g-renderer *current-render-target*)))))
(defmacro with-texture ((texture renderer pixel-format access width height) &body body)
"Create a texture, and free it after we leave this block."
`(let* ((,texture (sdl2:create-texture ,renderer ,pixel-format ,access ,width ,height)))
(unwind-protect
(progn ,@body)
(progn (sdl2:destroy-texture ,texture)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SDL2 KEYSYM-CASE helper
(defmacro keysym-case (keysym &body body)
"Case statement for SDL2 keysyms. Use the :SCANCODE-* symbols without the SCANCODE- bit."
(with-gensyms (g-scancode)
`(let* ((,g-scancode (sdl2:scancode-value ,keysym)))
(cond
,@(mapcar (lambda (clause)
(%keysym-case-clause g-scancode clause))
body)
))))
(defun %keysym-case-clause (g-scancode clause)
(let* ((key (intern (format nil "SCANCODE-~a" (symbol-name (car clause)))
:keyword))
(body (cdr clause)))
;;(format t "clause ~s / ~s~%" key body)
`((sdl2:scancode= ,g-scancode ,key)
,@body)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SDL2 pool-based replacement for WITH-RECTS
(defparameter *rects-pool* (make-array 10 :fill-pointer 0 :initial-element nil))
(defmacro with-overall-rects-pool (() &body body)
`(unwind-protect
(progn ,@body)
(progn
(do () ((= (fill-pointer *rects-pool*) 0))
(sdl2:free-rect (vector-pop *rects-pool*))))))
(defmacro with-pooled-rects ((&rest rects) &body body)
`(let (,@(mapcar #'%parse-rect-def rects))
(unwind-protect
(progn ,@body)
(progn
,@(mapcar #'%cleanup-rect-def rects)))))
(defun %parse-rect-def (rect-def)
(etypecase rect-def
(symbol (%parse-rect-def `(,rect-def 0 0 0 0)))
(cons
(destructuring-bind (name x y w h) rect-def
`(,name (%pop-from-rects-pool ,x ,y ,w ,h))))))
(defun %cleanup-rect-def (rect-def)
(etypecase rect-def
(symbol `(%push-into-rects-pool ,rect-def))
(cons
(destructuring-bind (name x y w h) rect-def
(declare (ignore x y w h))
(%cleanup-rect-def name)))))
(defun %push-into-rects-pool (rect)
(vector-push-extend rect *rects-pool*))
(defun %pop-from-rects-pool (x y w h)
(if (>= (fill-pointer *rects-pool*) 1)
(let* ((rect (vector-pop *rects-pool*)))
(setf (sdl2:rect-x rect) x)
(setf (sdl2:rect-y rect) y)
(setf (sdl2:rect-width rect) w)
(setf (sdl2:rect-height rect) h)
rect)
(sdl2:make-rect x y w h)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| 3,697 | Common Lisp | .lisp | 93 | 34.053763 | 91 | 0.570911 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9a07d855e6bdb114a8a01b8244bbd448e80d083880edfa5cae59611cdd86117c | 18,096 | [
-1
] |
18,097 | assets.lisp | iamgreaser_orionsfurnace-cl/src/assets.lisp | ;;;; assets.lisp
(in-package #:orions-furnace)
(standard-optimisation-settings)
(defparameter *img-floor* ())
(defparameter *asset-image-tuples*
'((*gfx-unknown* #p"dat/gfx/unknown.png")
(*gfx-tiles-floor001* #p"dat/gfx/tiles/floor001.png")
(*gfx-tiles-floortile001* #p"dat/gfx/tiles/floortile001.png")
(*gfx-tiles-wall001* #p"dat/gfx/tiles/wall001.png")
(*gfx-player-base* #p"dat/gfx/player/base.png")
))
(defparameter *asset-font-tuples*
'((*font-base* #p"dat/fonts/DejaVuSans.ttf" 11)
))
(defmacro with-game-assets (() &body body)
"Load all game assets, and free them when we leave this block."
`(unwind-protect
(progn
,@(mapcar #'%with-game-assets-font-tuple-init *asset-font-tuples*)
,@(mapcar #'%with-game-assets-image-tuple-init *asset-image-tuples*)
,@body)
(progn
,@(mapcar #'%with-game-assets-image-tuple-deinit *asset-image-tuples*)
,@(mapcar #'%with-game-assets-font-tuple-deinit *asset-font-tuples*)
)))
(defun %with-game-assets-image-tuple-init (tuple)
(destructuring-bind (key fname) tuple
(with-gensyms (g-surface g-texture)
`(let* ((,g-surface (sdl2-image:load-image ,fname))
(,g-texture (sdl2:create-texture-from-surface *renderer* ,g-surface)))
(sdl2:free-surface ,g-surface)
(setf ,key ,g-texture)))))
(defun %with-game-assets-image-tuple-deinit (tuple)
(destructuring-bind (key fname) tuple
(declare (ignore fname))
;; TODO: Catch any conditions which may fire --GM
`(when ,key
(sdl2:destroy-texture ,key)
(setf ,key nil)
)))
(defun %with-game-assets-font-tuple-init (tuple)
(destructuring-bind (key fname size) tuple
(with-gensyms (g-font)
`(let* ((,g-font (sdl2-ttf:open-font ,fname ,size)))
(setf ,key ,g-font)))))
(defun %with-game-assets-font-tuple-deinit (tuple)
(destructuring-bind (key fname size) tuple
(declare (ignore fname size))
;; TODO: Catch any conditions which may fire --GM
`(when ,key
(sdl2-ttf:close-font ,key)
(setf ,key nil)
)))
| 2,101 | Common Lisp | .lisp | 53 | 34.320755 | 84 | 0.654563 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 113cddb55b9acb296f638c23e0e0f783ad5546dd5d882820788d37a8d46449c5 | 18,097 | [
-1
] |
18,098 | player.lisp | iamgreaser_orionsfurnace-cl/src/entity/player.lisp | (in-package #:orions-furnace)
(standard-optimisation-settings)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-serial-class player-entity (dir4-entity entity)
()
(:documentation "A player entity."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod entity-texture ((entity player-entity)) *gfx-player-base*)
(defmethod is-in-player-space ((entity player-entity)) t)
| 451 | Common Lisp | .lisp | 9 | 48 | 76 | 0.497706 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d5a27e31442b5cb4cc89ab4c673021c7c74b3dc920ddff32b77f9943725ed239 | 18,098 | [
-1
] |
18,099 | item.lisp | iamgreaser_orionsfurnace-cl/src/entity/item.lisp | (in-package #:orions-furnace)
(standard-optimisation-settings)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-serial-class item-entity (entity)
()
(:documentation "An entity that can be picked up."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| 323 | Common Lisp | .lisp | 7 | 44 | 76 | 0.387821 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9d3cbda758a618cc7922c5849f0843475d9cc7719d04f768691b044805af5aec | 18,099 | [
-1
] |
18,100 | base.lisp | iamgreaser_orionsfurnace-cl/src/entity/base.lisp | (in-package #:orions-furnace)
(standard-optimisation-settings)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Entity generics
(defgeneric entity-vis-px (entity)
(:documentation "Visual pixel X coordinate."))
(defgeneric entity-vis-py (entity)
(:documentation "Visual pixel Y coordinate."))
(defgeneric entity-texture (entity)
(:documentation "The texture to use for this entity."))
(defgeneric entity-graphic (entity)
(:documentation "The graphic of this entity, in the form (texture subimg-x subimg-y). Used for normal one-tile-sized graphics."))
(defgeneric update-entity-direction (entity dx dy)
(:documentation "Update the direction that this entity is facing."))
(defgeneric draw-entity-at (entity px py)
(:documentation "Draw the given entity at the given position."))
(defgeneric attempt-move-entity-by (entity dx dy &key cooldown)
(:documentation "Attempt to move an entity by a vector, with lerping. Returns T if successful, NIL if it failed."))
(defgeneric force-move-entity-by (entity dx dy &key cooldown)
(:documentation "Force moving an entity by a vector, with lerping."))
(defgeneric force-move-entity-to (entity cx cy &key cooldown)
(:documentation "Force moving an entity to a position, without lerping."))
(defgeneric is-in-player-space (entity)
(:documentation "Does the given entity share player-space, and thus conflicts with standing players being in the same space?"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Entity default methods
(defmethod entity-vis-px ((entity entity))
(+ (* *cell-w* (entity-cx entity))
(if (>= (entity-lerp-den entity) 1)
(round (* (entity-lerp-num entity) (entity-lerp-pdx entity))
(entity-lerp-den entity))
0)))
(defmethod entity-vis-py ((entity entity))
(+ (* *cell-h* (entity-cy entity))
(if (>= (entity-lerp-den entity) 1)
(round (* (entity-lerp-num entity) (entity-lerp-pdy entity))
(entity-lerp-den entity))
0)))
(defmethod update-entity-direction ((entity entity) dx dy)
;; Nondirectional entity needs no direction update.
)
(defgeneric entity-texture (entity)
(:documentation "Texture for this entity."))
(defmethod tick ((entity entity))
(with-slots (board
cx cy dir
walk-dx walk-dy
lerp-pdx lerp-pdy
lerp-num lerp-den
cooldown-ticks)
entity
;; If we aren't on the correct cell on the board, put us there.
(when board
(when (cell-on-board board cx cy)
(unless (member entity (board-entities-at board cx cy)
:test #'eq)
(push entity (board-entities-at board cx cy)))))
;; Update lerp
(when (> lerp-num 0)
(decf lerp-num))
;; Calculate entity sprite
;; Tick movement cooldown
(when (> cooldown-ticks 0)
(decf cooldown-ticks))
;; Are we wanting to go in some direction?
(unless (and (= 0 walk-dx)
(= 0 walk-dy))
;; Yes.
;; Update direction
(update-entity-direction entity walk-dx walk-dy)
;; Is our cooldown finished?
(when (<= cooldown-ticks 0)
;; Yes - try moving.
(attempt-move-entity-by
entity walk-dx walk-dy
:cooldown (entity-walk-cooldown entity))))
;; Delete walk step
(setf walk-dx 0)
(setf walk-dy 0)
))
(defmethod attempt-move-entity-by ((entity entity) dx dy &key (cooldown 0))
(let* ((new-x (+ (entity-cx entity) dx))
(new-y (+ (entity-cy entity) dy)))
(if (can-enter-cell (entity-board entity) entity new-x new-y)
(force-move-entity-by entity dx dy
:cooldown cooldown))))
(defmethod force-move-entity-by ((entity entity) dx dy &key (cooldown 0))
(with-slots (cx cy
lerp-pdx lerp-pdy lerp-num lerp-den
cooldown-ticks)
entity
(let* ((new-x (+ cx dx))
(new-y (+ cy dy))
(old-vis-px (entity-vis-px entity))
(old-vis-py (entity-vis-py entity)))
(setf cooldown-ticks cooldown)
(force-move-entity-to entity new-x new-y :cooldown cooldown)
(setf lerp-pdx (- old-vis-px (* cx *cell-w*)))
(setf lerp-pdy (- old-vis-py (* cy *cell-h*)))
(setf lerp-den (floor (* cooldown-ticks 3/2)))
(setf lerp-num lerp-den)
)))
(defmethod force-move-entity-to ((entity entity) new-x new-y &key (cooldown 0))
(with-slots (cx cy
board
lerp-pdx lerp-pdy lerp-num lerp-den
cooldown-ticks)
entity
;; Remove ourself from the cell
(setf (board-entities-at board cx cy)
(delete entity (board-entities-at board cx cy)
:test #'eq))
(setf cooldown-ticks cooldown)
(setf lerp-pdx 0)
(setf lerp-pdy 0)
(setf lerp-num 0)
(setf lerp-den 1)
(setf cx new-x)
(setf cy new-y)
(pushnew entity (board-entities-at board cx cy)
:test #'eq)
))
(defmethod entity-graphic ((entity entity))
(values (entity-texture entity) 0 0))
;; Default
(defmethod entity-texture ((entity entity)) *gfx-unknown*)
(defmethod is-in-player-space ((entity entity)) nil)
(defun draw-entity (entity)
(let* ((cx (entity-cx entity))
(cy (entity-cy entity))
(px (- (entity-vis-px entity) *cam-offs-x*))
(py (- (entity-vis-py entity) *cam-offs-y*)))
(draw-entity-at entity px py)))
(defmethod draw-entity-at ((entity entity) px py)
(multiple-value-bind (texture subx suby) (entity-graphic entity)
(with-pooled-rects ((d-rect px py *cell-w* *cell-h*)
(s-rect (* *cell-w* subx)
(* *cell-h* suby)
*cell-w* *cell-h*))
(sdl2:render-copy *renderer* texture
:source-rect s-rect
:dest-rect d-rect))))
| 5,959 | Common Lisp | .lisp | 142 | 34.626761 | 131 | 0.605245 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f27c75ded256583359eaa9719ec66396954402a319961d4ab10033f01fb736d5 | 18,100 | [
-1
] |
18,101 | floor-tile.lisp | iamgreaser_orionsfurnace-cl/src/entity/floor-tile.lisp | (in-package #:orions-furnace)
(standard-optimisation-settings)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-serial-class floor-tile-entity (item-entity)
()
(:documentation "A floor tile item."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod entity-texture ((entity item-entity)) *gfx-tiles-floortile001*)
| 396 | Common Lisp | .lisp | 8 | 47.375 | 76 | 0.462141 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fa5cca111184edf66d049537f8052c3a3731fcdc399a21e445a0bbfeaf0c76e1 | 18,101 | [
-1
] |
18,102 | dir4.lisp | iamgreaser_orionsfurnace-cl/src/entity/mixin/dir4.lisp | (in-package #:orions-furnace)
(standard-optimisation-settings)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: Make an enum system for dir --GM
(define-serial-class dir4-entity (entity)
((dir :type symbol
:accessor entity-dir
:initform :south
:initarg :dir))
(:documentation "Mixin for ENTITY: 4 directions."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod entity-graphic ((entity dir4-entity))
(let* ((dir-idx (ecase (entity-dir entity)
(:north 0)
(:south 1)
(:west 2)
(:east 3))))
(values (entity-texture entity) dir-idx 0)))
(defmethod update-entity-direction ((entity dir4-entity) dx dy)
(with-slots (dir) entity
(cond
((< dy 0) (setf dir :north))
((> dy 0) (setf dir :south))
((< dx 0) (setf dir :west))
((> dx 0) (setf dir :east)))))
| 972 | Common Lisp | .lisp | 25 | 31.88 | 76 | 0.481403 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 59b2d168202b9d21a7e9f5157b94d0a7e59cb0312d645761252a61bd9cf46893 | 18,102 | [
-1
] |
18,103 | orions-furnace.asd | iamgreaser_orionsfurnace-cl/orions-furnace.asd | ;;;; orions-furnace.asd
(asdf:defsystem #:orions-furnace
:description "Describe orions-furnace here"
;; :author "Your Name <[email protected]>"
:license "AGPLv3+"
:version "0.0.0"
:serial t
:depends-on (#:alexandria
#:bordeaux-threads
#:cffi
#:sdl2
#:sdl2-image
#:sdl2-ttf
#:trivial-gray-streams)
:pathname "src"
:components ((:file "package")
(:file "assets")
(:file "macros")
(:file "classes")
(:file "orions-furnace")
(:file "board")
;; Entities
(:file "entity/base")
;; Entity mixins
(:file "entity/mixin/dir4")
;; Entity base classes, likely to become mixins?
(:file "entity/item")
;; Entity implementations
(:file "entity/floor-tile")
(:file "entity/player")
(:file "draw")
(:file "tick")
(:file "run")
))
| 1,096 | Common Lisp | .asd | 34 | 20.058824 | 63 | 0.461248 | iamgreaser/orionsfurnace-cl | 3 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 032fd4c759cde5159e656c7c9626356910936265f07aaee2befd99ef1c9f6d92 | 18,103 | [
-1
] |
18,133 | roswell.lisp | jstoddard_roswell/roswell.lisp | ;;;;---------------------------------------------------------------------------
;;;; roswell.lisp
;;;; A game for the 2011 Spring Lisp Game Jam
;;;; Copyright (C) 2011 Jeremiah Stoddard
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;---------------------------------------------------------------------------
(in-package #:roswell)
(defparameter +data-directory+ "/home/jeremiah/src/lisp/roswell/")
(defparameter +screen-width+ 640)
(defparameter +screen-height+ 480)
(defparameter +gravity+ 2)
(defparameter *player-won* nil)
(defparameter *game-counter* 0) ;; for animation & other timing needs
;;; These will hold the SDL surfaces containing tiles and sprites
(defparameter *characters* nil)
(defparameter *tiles* nil)
(defparameter *projectile* nil)
;;; Some utilities that may come in handy...
(defun word-wrap (string num-chars)
"Add newlines to string to keep each line <= num-chars."
(let ((string (remove #\Newline string)))
(cond ((<= (length string) num-chars) string)
(t
(let ((string1 (subseq string 0 num-chars))
(string2 (subseq string num-chars)))
(setf string1 (substitute #\Newline #\Space string1
:count 1 :from-end t))
(setf string2 (concatenate
'string
(subseq string1 (or (position #\Newline string1)
num-chars))
string2))
(setf string1 (subseq string1 0 (1+ (or (position #\Newline string1)
(1- num-chars)))))
(concatenate 'string string1 (word-wrap string2 num-chars)))))))
(declaim (inline get-collision-tiles))
(defun get-collision-tiles (x y &optional (x-bbox 13) (y-bbox 15))
"Return the tiles that a character in position (x,y) would collide with,
assuming a 26x26 bounding box."
(remove-duplicates
(list
(list (ash (- x x-bbox) -5) (ash (- y y-bbox) -5))
(list (ash (+ x x-bbox) -5) (ash (- y y-bbox) -5))
(list (ash (+ x x-bbox) -5) (ash (+ y y-bbox) -5))
(list (ash (- x x-bbox) -5) (ash (+ y y-bbox) -5)))
:test #'equal))
;;; This class defines a game character. Both the player and the bad guys
;;; will be subclassed from this. The position and velocity variables are
;;; self-explanatory. direction is the direction in which the projectile
;;; will be sent if the character shoots, and also is used in determining
;;; how the character will be drawn. step-count determines the animation
;;; frame. hit-points determines how much damage the character can take
;;; before dying. sprite indicates which sprites to use for drawing the
;;; character.
(defparameter *player* nil) ; Instance of player representing the player
(defparameter *enemies* nil) ; List containing instances of all enemies
(defclass game-char ()
((x-position :initarg :x-position :accessor x-position)
(y-position :initarg :y-position :accessor y-position)
(x-velocity :initarg :x-velocity :initform 0 :accessor x-velocity)
(y-velocity :initarg :y-velocity :initform 0 :accessor y-velocity)
(direction :initarg :direction :initform 'right :accessor direction)
(step-count :initarg :step-count :initform 0 :accessor step-count)
(hit-points :initarg :hit-points :accessor hit-points)
(sprite :initarg :sprite :accessor sprite)))
(defmethod collisionp ((character game-char))
(cond ((or (>= (+ (x-position character) 16) (ash (map-width *current-level*) 5))
(< (- (x-position character) 16) 0)
(>= (+ (y-position character) 16) (ash (map-height *current-level*) 5))
(< (- (y-position character) 16) 0)) t)
((and (not (position nil
(mapcar #'(lambda (x)
(= -1 (aref (obstacle-map *current-level*)
(first x) (second x))))
(get-collision-tiles
(x-position character)
(y-position character))))))
nil)
(t t)))
(defmethod move ((character game-char) direction)
(case direction
(up (decf (y-position character) 2)
(when (collisionp character)
(incf (y-position character) 2)
(setf (y-velocity character) 0)))
(down (incf (y-position character) 2)
(when (collisionp character)
(decf (y-position character) 2)
(setf (y-velocity character) 0)))
(left (setf (direction character) 'left)
(decf (x-position character) 2)
(when (collisionp character)
(incf (x-position character) 2)
(setf (x-velocity character) 0)))
(right (setf (direction character) 'right)
(incf (x-position character) 2)
(when (collisionp character)
(decf (x-position character) 2)
(setf (x-velocity character) 0))))
(when (or (eq direction 'left) (eq direction 'right))
(setf (step-count character) (mod (1+ (step-count character)) 32))))
(defmethod shoot ((character game-char) &optional (sprite 2))
(let ((x (x-position character)) (y (- (y-position character) 10)))
(cond ((eq (direction character) 'up) (decf y 38))
((eq (direction character) 'down) (incf y 26))
((eq (direction character) 'left) (decf x 16))
((eq (direction character) 'right) (incf x 16)))
(make-instance 'projectile :x-position x :y-position y
:direction (direction character) :sprite sprite)))
(defclass player (game-char)
((points :initarg :points :initform 0 :accessor points)
(keys :initarg :keys :initform 0 :accessor keys)
(max-hp :initarg :max-hp :initform 15 :accessor max-hp)))
(defmethod jump ((player player))
(when (and (position nil
(mapcar #'(lambda (x)
(= -1 (aref (obstacle-map *current-level*)
(first x) (second x))))
(get-collision-tiles
(x-position player)
(y-position player) 1 16))))
(setf (y-velocity player) -20)))
(defmethod shoot ((player player)
&optional (sprite (if (or (eq (direction player) 'up)
(eq (direction player) 'down))
1 0)))
(call-next-method player sprite))
;;; The projectile class contains details of a bullet or a laser beam.
(defparameter *projectiles* nil)
(defclass projectile ()
((x-position :initarg :x-position :accessor x-position)
(y-position :initarg :y-position :accessor y-position)
(direction :initarg :direction :accessor direction)
(ttl :accessor ttl)
(sprite :initarg :sprite :initform 2 :accessor sprite)))
(defmethod initialize-instance :after ((projectile projectile) &rest rest)
(declare (ignore rest))
(case (direction projectile)
(up (setf (ttl projectile) (floor (+ (ash +screen-height+ -1)
(- (y-position projectile)
(y-position *player*))) 6)))
(down (setf (ttl projectile) (floor (+ (ash +screen-height+ -1)
(- (y-position *player*)
(y-position projectile))) 6)))
(left (setf (ttl projectile) (floor (+ (ash +screen-width+ -1)
(- (x-position projectile)
(x-position *player*))) 6)))
(right (setf (ttl projectile) (floor (+ (ash +screen-width+ -1)
(- (x-position *player*)
(x-position projectile))) 6))))
(when (null (ttl projectile)) (setf (ttl projectile) 0))
(push projectile *projectiles*))
(defmethod detect-projectile-collision ((projectile projectile))
(dolist (enemy *enemies*)
(when (and (> (x-position projectile) (- (x-position enemy) 16))
(< (x-position projectile) (+ (x-position enemy) 16))
(> (y-position projectile) (- (y-position enemy) 16))
(< (y-position projectile) (+ (y-position enemy) 16)))
(decf (hit-points enemy))
(setf (ttl projectile) 0)))
(when (and (> (x-position projectile) (- (x-position *player*) 16))
(< (x-position projectile) (+ (x-position *player*) 16))
(> (y-position projectile) (- (y-position *player*) 16))
(< (y-position projectile) (+ (y-position *player*) 16)))
(decf (hit-points *player*))
(setf (ttl projectile) 0)))
(defun update-projectiles ()
"Loop through the projectiles, updating position, looking for collisions, and
finally remove old and collided projectiles."
(dolist (projectile *projectiles*)
(decf (ttl projectile))
(cond ((eq (direction projectile) 'up)
(decf (y-position projectile) 6))
((eq (direction projectile) 'down)
(incf (y-position projectile) 6))
((eq (direction projectile) 'left)
(decf (x-position projectile) 6))
((eq (direction projectile) 'right)
(incf (x-position projectile) 6)))
(detect-projectile-collision projectile)
(draw-tile *projectile* (sprite projectile)
(+ (- (x-position projectile) 16
(x-position *player*))
(ash +screen-width+ -1))
(+ (- (y-position projectile) 16
(y-position *player*))
(ash +screen-height+ -1))))
(setf *projectiles* (remove-if-not #'(lambda (projectile)
(> (ttl projectile) 0))
*projectiles*)))
;;; The level-map class contains the details of a map. The bg-map,
;;; obstacle-map, and object-map variables are two-dimensional arrays
;;; of map-width by map-height size.
(defparameter *current-level* nil) ; Map of current level
(defparameter *game-levels* nil) ; All maps that will be used in the game
(defclass level-map ()
((map-width :initarg :map-width :accessor map-width)
(map-height :initarg :map-height :accessor map-height)
(bg-map :initarg :bg-map :accessor bg-map)
(obstacle-map :initarg :obstacle-map :accessor obstacle-map)
(object-map :initarg :object-map :accessor object-map)
(load-function :initarg :load-function :accessor load-function)))
(defun load-level (map-file)
"Load the map given by map-file."
(load (concatenate 'string +data-directory+ map-file)))
(defun add-level (map)
"Append map to *game-levels*, creating a new map accessible to the game
via select-map."
(setf *game-levels* (append *game-levels* (list map))))
(defun select-level (level)
"Look up the map for the given level and set it as the current map. (i.e.
set *current-level* to that map)."
(setf *current-level* (nth level *game-levels*))
(if *current-level*
(funcall (load-function *current-level*))
(setf *player-won* t)))
;;; Drawing functions
(defun draw-tile (tile-set tile-number x y)
"Draw the tile given by tile-number to the display surface at x, y.
tile-number should be an integer between 0 and 299, inclusive."
(multiple-value-bind (tile-y tile-x) (floor tile-number 20)
(sdl:set-cell (sdl:rectangle :x (* tile-x 32)
:y (* tile-y 32)
:w 32 :h 32)
:surface tile-set)
(sdl:draw-surface-at tile-set (sdl:point :x x :y y))))
(defun draw-map ()
"Place tiles from the map on the display surface so that player is centered
on the screen."
(let ((top-x (- (x-position *player*) (floor +screen-width+ 2)))
(top-y (- (y-position *player*) (floor +screen-height+ 2)))
start-x start-y tile-x tile-y)
(sdl:clear-display sdl:*black*)
(setf start-x (- 0 (mod top-x 32)))
(setf start-y (- 0 (mod top-y 32)))
(loop for x upfrom start-x by 32
when (>= x +screen-width+) return nil
do (loop for y upfrom start-y by 32
when (>= y +screen-height+) return nil
when (and (>= (+ top-x x) 0) (>= (+ top-y y) 0))
do (progn
(setf tile-x (floor (+ top-x x) 32)
tile-y (floor (+ top-y y) 32))
(when (and (< tile-x (map-width *current-level*))
(< tile-y (map-height *current-level*)))
(draw-tile *tiles* (aref (bg-map *current-level*)
tile-x tile-y) x y)
(when (<= 0 (aref (obstacle-map *current-level*) tile-x tile-y))
(draw-tile *tiles* (aref (obstacle-map *current-level*)
tile-x tile-y) x y))
(when (<= 0 (aref (object-map *current-level*) tile-x tile-y))
(draw-tile *tiles* (aref (object-map *current-level*)
tile-x tile-y) x y))))))))
(defun draw-player ()
"Draw player at center of screen."
(let ((sprite (+ (sprite *player*) (ash (step-count *player*) -3))))
(case (direction *player*)
(right nil)
(left (setf sprite (+ sprite 4)))
(up (setf sprite (+ sprite 8)))
(down (setf sprite (+ sprite 12))))
(draw-tile *characters* (+ sprite 20)
(- (ash +screen-width+ -1) 16)
(- (ash +screen-height+ -1) 16))
(draw-tile *characters* sprite
(- (ash +screen-width+ -1) 16)
(- (ash +screen-height+ -1) 48))))
;;; Functions to load game assets
(defun load-assets ()
"Load media (images, sound) that will be used by the game."
(setf *characters* (sdl:convert-to-display-format
:surface (sdl:load-image
(concatenate 'string +data-directory+
"media/characters.png")
:image-type :png)
:pixel-alpha t))
(setf *tiles*
(sdl:convert-to-display-format
:surface (sdl:load-image
(concatenate 'string +data-directory+ "media/tiles.png")
:image-type :png)
:pixel-alpha t))
(setf *projectile* (sdl:convert-to-display-format
:surface (sdl:load-image
(concatenate 'string +data-directory+
"media/projectiles.png")
:image-type :ping)
:pixel-alpha t)))
;;; Logic functions -- things that will be applied every run through
;;; the game loop.
(defun apply-gravity ()
"Adjust player and enemy y-velocity for the effects of gravity."
(incf (y-velocity *player*) +gravity+))
(defun move-characters ()
"Move the game characters according to their velocities."
(when (> (x-velocity *player*) 0)
(dotimes (i (x-velocity *player*)) (move *player* 'right)))
(when (< (x-velocity *player*) 0)
(dotimes (i (- 0 (x-velocity *player*))) (move *player* 'left)))
(when (> (y-velocity *player*) 0)
(dotimes (i (y-velocity *player*)) (move *player* 'down)))
(when (< (y-velocity *player*) 0)
(dotimes (i (- 0 (y-velocity *player*))) (move *player* 'up))))
;;; Clear things out for new game, etc.
(defun clear-game ()
"Sets game state globals back to their original values..."
(setf *game-levels* nil)
(setf *current-level* nil)
(setf *projectiles* nil)
(setf *player-won* nil))
;;; Game Loop
(defun main ()
(clear-game)
(setf *player* (make-instance 'player
:x-position 1 :y-position 1
:direction 'right
:hit-points 15
:sprite 0))
(sdl:with-init ()
(sdl:window +screen-width+ +screen-height+
:double-buffer t :title-caption "Roswell")
(setf (sdl:frame-rate) 30)
(sdl:initialise-default-font)
;; load our game assets
(load-assets)
(load-level "roswell.map")
(select-level 0)
(sdl:with-events ()
(:quit-event () t)
(:key-down-event (:key key)
(cond ((sdl:key= key :sdl-key-escape) (sdl:push-quit-event))))
(:idle ()
(setf *game-counter* (mod (1+ *game-counter*) 128))
(apply-gravity)
(setf (x-velocity *player*) 0)
(when (sdl:get-key-state :sdl-key-left) (setf (x-velocity *player*) -2))
(when (sdl:get-key-state :sdl-key-right) (setf (x-velocity *player*) 2))
(when (sdl:get-key-state :sdl-key-up) (setf (direction *player*) 'up))
(when (sdl:get-key-state :sdl-key-down) (setf (direction *player*) 'down))
(when (or
(sdl:get-key-state :sdl-key-lctrl)
(sdl:get-key-state :sdl-key-rctrl))
(jump *player*))
(when (and (= 0 (mod *game-counter* 8))
(or
(sdl:get-key-state :sdl-key-lalt)
(sdl:get-key-state :sdl-key-ralt)))
(shoot *player*))
(move-characters)
(draw-map)
(draw-player)
(update-projectiles)
(sdl:update-display)))))
| 16,125 | Common Lisp | .lisp | 365 | 38.843836 | 83 | 0.636127 | jstoddard/roswell | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | b0235302a3af2506c6ac9d4a7283998b97d4eed952fbf79541b6ff81ca05f9f2 | 18,133 | [
-1
] |
18,134 | roswell.asd | jstoddard_roswell/roswell.asd | ;;;; roswell.asd
(asdf:defsystem #:roswell
:serial t
:depends-on (#:lispbuilder-sdl)
:components ((:file "package")
(:file "roswell")))
| 159 | Common Lisp | .asd | 6 | 21.666667 | 34 | 0.609272 | jstoddard/roswell | 3 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 8982dd214144304b990178394aaebff51caefdf485b6e0bb252c1a79f209d497 | 18,134 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.