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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44,641 | day17.lisp | blake-watkins_advent-of-code-2023/day17.lisp | (in-package :aoc-2023)
(defun parse-file ()
(parse-lines (one-or-more (parse-digit))))
(defparameter *directions* '((-1 0) (0 1) (1 0) (0 -1) ))
(defclass vertex ()
((pos :initarg :pos :reader vertex-pos)
(dir :initarg :dir)
(straight :initarg :straight :reader vertex-straight)))
(defmethod print-object ((object vertex) stream)
(print-unreadable-object (object stream :type t)
(with-slots (pos dir straight) object
(format stream "(~a ~a ~a)" pos dir straight))))
(defmethod fset:compare ((v1 vertex) (v2 vertex))
(fset:compare-slots v1 v2 'pos 'dir 'straight))
(defun turn (dir c-cw)
(elt *directions*
(mod (+ (position dir *directions* :test 'equal) (if (eq c-cw :cw) 1 -1))
(length *directions*))))
(defun get-next-vertices (vertex part)
(with-slots (pos dir straight) vertex
(let ((new-dirs
(let ((turn-dirs (mapcar (lambda (d) `(,(turn dir d) 1)) '(:cw :ccw)))
(straight-dir `((,dir ,(1+ straight)))))
(if (= part 1)
(append turn-dirs (when (< straight 3) straight-dir))
(append (when (>= straight 4) turn-dirs)
(when (< straight 10) straight-dir))))))
(iter
(for (new-dir new-straight) in new-dirs)
(collect (make-instance 'vertex
:pos (point+ pos new-dir)
:dir new-dir
:straight new-straight))))))
(defun neighbours (vertex map part)
(iter
(for neighbour in (get-next-vertices vertex part))
(for cost = (gethash (vertex-pos neighbour) map))
(when cost (collect (list neighbour cost)))))
(defun day17 (input &key (part 1))
(let* ((parsed (run-parser (parse-file) input))
(map (hash-table-from-list-list parsed)))
(iter
(for start-dir in '((0 1) (1 0)))
(minimize
(iter
(with end = (hash-table-dimensions map))
(for (vertex parent distance)
in-dijkstra-from
(make-instance 'vertex :pos '(0 0) :dir start-dir :straight 1)
:neighbours (lambda (vertex) (neighbours vertex map part)))
(setf (gethash vertex parents) parent)
(until (and (equal end (vertex-pos vertex))
(or (= part 1) (>= (vertex-straight vertex) 4))))
(finally (return distance )))))))
| 2,185 | Common Lisp | .lisp | 54 | 35.203704 | 80 | 0.626296 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 58236b078773b2c87b356edb1b0bc3539740c80fee3538278b8c09ff59cc0303 | 44,641 | [
-1
] |
44,642 | day4.lisp | blake-watkins_advent-of-code-2023/day4.lisp | (in-package :aoc-2023)
(defun parse-file ()
(parse-lines
(with-monad
(parse-string "Card")
(parse-whitespace)
(assign id (parse-number))
(parse-string ":")
(parse-whitespace)
(assign winning-numbers (parse-list (parse-number) (parse-whitespace)))
(parse-string " |")
(parse-whitespace)
(assign my-numbers (parse-list (parse-number) (parse-whitespace)))
(unit (list id winning-numbers my-numbers)))))
(defun winning-count (card)
(iter
(with (nil winning-numbers my-numbers) = card)
(for number in my-numbers)
(count (find number winning-numbers))))
(defun card-score (card)
(let ((winning-count (winning-count card)))
(if (> winning-count 0) (expt 2 (1- winning-count)) 0)))
(defun day4 (input &key (part 1))
(let* ((cards (run-parser (parse-file) input)))
(if (= part 1)
(reduce #'+ (mapcar #'card-score cards))
(iter
(with instances = (make-hash-table))
(for card in cards)
(for card-num = (first card))
(for num-instances = (gethash card-num instances 1))
(sum num-instances)
(iter
(repeat (winning-count card))
(for i from (1+ card-num))
(incf (gethash i instances 1) num-instances))))))
| 1,288 | Common Lisp | .lisp | 36 | 29.305556 | 76 | 0.607372 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 93c35cea0d17ad287ae544b331b21fa8fc566f7624409e0d4147dea8d90392c2 | 44,642 | [
-1
] |
44,643 | day15.lisp | blake-watkins_advent-of-code-2023/day15.lisp | (in-package :aoc-2023)
(defun parse-file ()
(parse-list
(parse-characters (lambda (c) (not (or (char= c #\,) (whitespace-char-p c)))))))
(defun parse-file-2 ()
(parse-list
(with-monad
(assign label (parse-characters #'alphanumericp))
(assign operation (either (then (parse-character #\-) (unit (list :remove)))
(with-monad
(parse-character #\=)
(assign focal-length (parse-number))
(unit (list :insert focal-length)))))
(unit (cons label operation)))))
(defun hash (str)
(iter
(with current-value = 0)
(for char in-string str)
(setf current-value (mod (* (+ current-value (char-code char)) 17) 256))
(finally (return current-value))))
(defun focusing-power (boxes)
(iter outer
(for (box-number lenses) in-hashtable boxes)
(iter
(for (label focal-length) in (reverse lenses))
(for slot from 1)
(in outer (summing (* (1+ box-number) slot focal-length))))))
(defun day15 (input &key (part 1))
(if (= part 1)
(iter
(for step in (run-parser (parse-file) input))
(summing (hash step)))
(iter
(with boxes = (make-hash-table))
(for (label operation value) in (run-parser (parse-file-2) input))
(for label-hash = (hash label))
(for lenses = (gethash label-hash boxes))
(case operation
(:remove
(setf (gethash label-hash boxes)
(remove label lenses :test #'string= :key #'first)))
(:insert
(let ((position (position label lenses :test #'string= :key #'first)))
(if position
(setf (second (elt lenses position)) value)
(push (list label value) (gethash label-hash boxes))))))
(finally (return (focusing-power boxes))))))
| 1,893 | Common Lisp | .lisp | 47 | 31.12766 | 83 | 0.56491 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 52b2c73d1d0acbcda82dc1d0088757aa75165b78823c6db5a225fcf63f892632 | 44,643 | [
-1
] |
44,644 | day14.lisp | blake-watkins_advent-of-code-2023/day14.lisp | (in-package :aoc-2023)
(defun parse-file ()
(parse-lines
(one-or-more
(with-monad
(assign char (parse-character "O.#"))
(unit (case char (#\. :blank) (#\# :fixed) (#\O :round)))))))
;; NEXT-ROCK-INDEX tracks the next index in each column that a round rock can go
;; into. Assumes ROCKS is sorted from topmost rocks. :FIXED rocks stay
;; where they are, :ROUND rocks go into the next rock index for the column.
(defun roll-north (rocks)
(iter
(with next-rock-index = (make-hash-table))
(for ((r c) rock-type) in rocks)
(for this-r = (case rock-type
(:fixed r)
(:round (gethash c next-rock-index 0))))
(collect `((,this-r ,c) ,rock-type))
(setf (gethash c next-rock-index) (1+ this-r))))
(defun north-load (rocks dimension)
"Calculate load on north wall. "
(iter
(for ((r c) rock-type) in rocks)
(when (eq rock-type :round)
(sum (- dimension r)))))
(defun topmost-leftmost< (a b)
"Compares A and B. A is less than B if it's above, or left on the same row. "
(or (and (= (caar a) (caar b)) (< (cadar a) (cadar b)))
(< (caar a) (caar b))))
(defun rotate-rocks (rocks dimension)
"Rotate ROCKS clockwise. Assumes rocks are in a square map. "
(iter
(for ((r c) rock-type) in rocks)
(collect `((,c ,(- dimension 1 r)) ,rock-type) into ret)
(finally (return (sort ret #'topmost-leftmost<)))))
(defun roll-cycle (rocks dimension &optional (cycles 1))
"Roll ROCKS north, west, south, then east. Repeats cycle CYCLES times. "
(iter
(repeat (* 4 cycles))
(setf rocks (rotate-rocks (roll-north rocks) dimension))
(finally (return rocks))))
(defun get-rocks (map)
(iter outer
(for row in map)
(for r from 0)
(iter
(for rock-type in row)
(for c from 0)
(unless (eq :blank rock-type)
(in outer (collect `((,r ,c) ,rock-type)))))))
(defun find-nth-load (n rocks dimension)
(destructuring-bind (cycle-start cycle-end)
(iter
(with cache = (make-hash-table :test 'equal))
(for idx from 0)
(for iter-rocks initially rocks then (roll-cycle iter-rocks dimension))
(until (gethash iter-rocks cache))
(setf (gethash iter-rocks cache) idx)
(finally (return (list (gethash iter-rocks cache) idx))))
(let* ((cycle-length (- cycle-end cycle-start))
(cycles (if (< n cycle-start)
n
(+ cycle-start (mod (- n cycle-start) cycle-length)))))
(north-load (roll-cycle rocks dimension cycles) dimension))))
(defun day14 (input &key (part 1))
(let* ((parsed (run-parser (parse-file) input))
(rocks (get-rocks parsed))
(dimension (length parsed)))
(if (= part 1)
(north-load (roll-north rocks) dimension)
(find-nth-load 1000000000 rocks dimension))))
| 2,866 | Common Lisp | .lisp | 71 | 34.366197 | 80 | 0.614501 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | ef49465f2503b3f1a760e86927dc7588e6e0b658109d729df67b8b8f6147d8f4 | 44,644 | [
-1
] |
44,645 | day9.lisp | blake-watkins_advent-of-code-2023/day9.lisp | (in-package :aoc-2023)
(defun parse-file ()
(parse-lines (parse-number-list #\Space)))
(defun get-differences (values)
(iter
(for difference initially values then
(iter
(for (a b) on difference)
(when b (collect (- b a)))))
(collect difference)
(until (every #'zerop difference))))
(defun predict (values part)
(reduce (lambda (a diffs)
(if (= part 1)
(+ a (car (last diffs)))
(- (first diffs) a)))
(reverse (get-differences values))
:initial-value 0))
(defun day9 (input &key (part 1))
(reduce #'+
(run-parser (parse-file) input)
:key (lambda (values) (predict values part))))
| 717 | Common Lisp | .lisp | 22 | 25.272727 | 56 | 0.567294 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | f4494bab9ed706d0c07f4801570db3938ef70377600a5c3dbac68fcc0c5d7587 | 44,645 | [
-1
] |
44,646 | day18.lisp | blake-watkins_advent-of-code-2023/day18.lisp | (in-package :aoc-2023)
(defun parse-hex-code ()
(with-monad
(parse-character #\#)
(assign distance (parse-subparser 5 (parse-number :base 16)))
(assign direction (parse-character "0123"))
(unit (list (case direction (#\0 :r) (#\1 :d) (#\2 :l) (#\3 :u)) distance))))
(defun parse-file (part)
(if (= part 1)
(one-or-more (with-monad
(assign dir (parse-keyword "ULRD"))
(parse-space)
(assign amt (parse-number))
(parse-until (parse-newline))
(unit (list dir amt))))
(parse-lines (parse-until (parse-bracketed (parse-hex-code) "()")))))
(defparameter *directions* '((:u (-1 0)) (:r (0 1)) (:d (1 0)) (:l (0 -1)) ))
(defun move (pos dir &optional (amt 1))
(point+ pos (point* amt (second (assoc dir *directions*)))))
(defun day18 (input &key (part 1))
(let ((parsed (run-parser (parse-file part) input)))
(destructuring-bind (corners boundary)
(iter
(with cur = '(0 0))
(with boundary = 0)
(for (dir amt) in parsed)
(incf boundary amt)
(setf cur (move cur dir amt))
(collect cur into corners)
(finally (return (list corners boundary))))
(+ (interior (abs (area corners)) boundary) boundary))))
;; https://en.wikipedia.org/wiki/Shoelace_formula
(defun area (corners)
(/ (iter
(for (a b) on corners)
(when (null b) (setf b (first corners)))
(summing (- (* (first a) (second b)) (* (first b) (second a)))))
2))
;; https://en.wikipedia.org/wiki/Pick%27s_theorem
(defun interior (area boundary)
(- (+ area 1 ) (/ boundary 2)))
| 1,683 | Common Lisp | .lisp | 41 | 33.560976 | 81 | 0.563303 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | f0887b88da54e102f319f19d5cd5a7cf140eee0f4c8a60bc7660612f9715bc32 | 44,646 | [
-1
] |
44,647 | day11.lisp | blake-watkins_advent-of-code-2023/day11.lisp | (in-package :aoc-2023)
(defun parse-file ()
(parse-lines (one-or-more (parse-character ".#"))))
(defun galaxies (map)
(iter outer
(for row in map)
(for r from 0)
(iter
(for char in row)
(for c from 0)
(when (char= #\# char) (in outer (collect (list r c)))))))
(defun blank-rows (map)
(iter
(for row in map)
(for r from 0)
(when (every (lambda (c) (char= #\. c)) row) (collect r))))
(defun blank-cols (map)
(iter
(for c from 0 below (length (first map)))
(when (every (lambda (row) (char= #\. (elt row c))) map) (collect c))))
(defun included-blanks (start end blanks)
(count-if (lambda (blank) (<= (min start end) blank (max start end))) blanks))
(defun galaxy-distance (a b blanks expansion-factor)
(flet ((coord-distance (a b blanks)
(+ (abs (- b a))
(* (1- expansion-factor) (included-blanks a b blanks)))))
(reduce #'+ (map 'list #'coord-distance a b blanks))))
(defun day11 (input &key (part 1))
(let* ((parsed (run-parser (parse-file) input))
(galaxies (galaxies parsed))
(blanks (list (blank-rows parsed) (blank-cols parsed)))
(expansion (if (= part 1) 2 1000000)))
(reduce #'+ (mapcar (lambda (pair)
(destructuring-bind (a b) pair
(galaxy-distance a b blanks expansion)))
(pairs galaxies)))))
| 1,312 | Common Lisp | .lisp | 36 | 32.361111 | 80 | 0.618597 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 7f1a078266fe153bb01282a82dc2e4e4259de8aeba0fdf4107fabc99180a6b97 | 44,647 | [
-1
] |
44,648 | day10.lisp | blake-watkins_advent-of-code-2023/day10.lisp | (in-package :aoc-2023)
(defun parse-file ()
(parse-lines (one-or-more (parse-character (complement #'whitespace-char-p)))))
(defun get-map (input)
(let ((parsed (run-parser (parse-file) input)))
(iter
(with ret = (make-hash-table :test 'equal))
(with start-pos = nil)
(for r from 0)
(for row in parsed)
(iter
(for c from 0)
(for char in row)
(when (char= #\S char)
(setf start-pos (list r c)))
(setf (gethash (list r c) ret) char))
(finally (return (list start-pos ret))))))
;;store offset and position of this cell in relation to neighbour
(defparameter *directions*
'(((-1 0) :north) ((0 1) :east) ((1 0) :south) ((0 -1) :west)))
(defparameter *pipe-types* '((#\| (:north :south))
(#\- (:east :west))
(#\L (:north :east))
(#\J (:north :west))
(#\7 (:south :west))
(#\F (:south :east))
(#\S (:north :south :east :west))))
(defun pipe-connected? (a b map)
"Are A and B both correctly pointing at each other to make a pipe?"
(flet ((connected-one-way? (a b map)
(let* ((offset (point- b a))
(dir (find offset *directions* :test 'equal :key #'first))
(dir-name (second dir))
(map-char (gethash a map))
(pipe-type (find map-char *pipe-types* :test 'eq :key #'first))
(connection-names (second pipe-type)))
(and dir-name (member dir-name connection-names)))))
(and (connected-one-way? a b map) (connected-one-way? b a map))))
(defun pipe-neighbours (pos map)
"Return list of (POS DIR) pairs that are correctly connected neighbours of POS."
(iter
(for (offset dir) in *directions*)
(for next-pos = (point+ offset pos))
(when (pipe-connected? pos next-pos map) (collect (list next-pos dir)))))
(defun mark-loop (loop-squares)
"Return hash table with all squares in LOOP-SQUARES marked as :LOOP."
(iter
(with ret = (make-hash-table :test 'equal))
(for square in loop-squares)
(setf (gethash square ret) :loop)
(finally (return ret))))
(define-condition outside-map (condition) ())
(defun can-mark? (pos marked map)
"Is POS on the map and unmarked? Signal 'OUTSIDE-MAP condition if outside map."
(when (not (gethash pos map)) (signal 'outside-map))
(and (gethash pos map) (not (gethash pos marked))))
(defun unmarked-neighbours (pos marked map)
"Return list of neighbours that can be marked. "
(iter
(for (offset nil) in *directions*)
(for next-square = (point+ pos offset))
(when (can-mark? next-square marked map) (collect next-square))))
(defun mark-connected (from mark marked map)
"Mark all connected neighbours of FROM with MARK. Alters MARKED hash table."
(when (can-mark? from marked map)
(iter
(for (pos . nil)
in-bfs-from from
neighbours (lambda (from) (unmarked-neighbours from marked map))
test 'equal
single t)
(setf (gethash pos marked) mark))))
(defun turn (dir rotation)
"Return element of *DIRECTIONS* list corresponding to DIR (:north etc) rotated by ROTATION (:cw, :ccw etc). "
(elt *directions*
(mod (+ (position dir *directions* :key #'second)
(ecase rotation (:cw 1) (:ccw -1)))
(length *directions*))))
(defparameter *outside-mark* nil)
(defun mark-pos-sides (pos dir marked map)
"Mark sides of pos with different marks. Alters MARKED hash table. Handles 'OUTSIDE-MAP condition and sets *OUTSIDE-MARK* if any landed outside the map."
(iter
(for rotation in '(:cw :ccw))
(handler-case (mark-connected (point+ pos (first (turn dir rotation)))
rotation marked map)
(outside-map () (setf *outside-mark* rotation)))))
(defun walk-loop (start-pos marked map)
(iter
(for prev-pos previous pos)
(for pos initially start-pos then next-pos)
(for neighbours =
(remove prev-pos (pipe-neighbours pos map) :test 'equal :key #'first))
(for (next-pos dir) = (first neighbours))
(for prev-dir previous dir)
(mapc (lambda (dir) (mark-pos-sides pos dir marked map))
(remove nil (list dir prev-dir)))
(until (and prev-pos (equal pos start-pos)))))
(defun count-table (marked)
(iter
(with ret = (make-hash-table))
(for (key val) in-hashtable marked)
(incf (gethash val ret 0))
(finally (return ret))))
(defun day10 (input &key (part 1))
(destructuring-bind (start-pos map) (get-map input)
(destructuring-bind (steps loop-squares)
(iter
(for (pos from steps root)
in-bfs-from start-pos
neighbours (lambda (n) (mapcar #'first (pipe-neighbours n map)))
test 'equal
single t)
(collect pos into loop)
(maximizing steps)
(finally (return (list steps loop))))
(if (= part 1)
steps
(let ((marked (mark-loop loop-squares)))
(walk-loop start-pos marked map)
(gethash (if (eq *outside-mark* :cw) :ccw :cw)
(count-table marked)))))))
| 4,854 | Common Lisp | .lisp | 121 | 35.495868 | 155 | 0.651252 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 6dd36a2dab92d378dd1d9a17e36112c27faa07268d88f26668d9f6d5ee8a5006 | 44,648 | [
-1
] |
44,649 | day23.lisp | blake-watkins_advent-of-code-2023/day23.lisp | (in-package :aoc-2023)
(defun parse-file ()
(parse-lines (one-or-more (parse-character "#.><^v"))))
(defparameter *directions* '((-1 0) (0 1) (1 0) (0 -1)))
(defun neighbours (cur map part)
(let ((possible-directions
(if (= part 1)
(case (gethash cur map)
(#\. *directions*)
(#\> `((0 1)))
(#\< `((0 -1)))
(#\^ `((-1 0)))
(#\v `((1 0))))
*directions*)))
(remove-if-not
(lambda (n)
(let ((char (gethash n map)))
(and char (not (char= char #\#)))))
(mapcar (lambda (d) (point+ cur d)) possible-directions))))
(defun find-path-reduced (cur end distance visited graph)
(if (equal cur end)
distance
(let ((neighbours (remove-if
(lambda (n) (gethash (first n) visited))
(gethash cur graph))))
(iter
(initially (setf (gethash cur visited) t))
(for (n dist) in neighbours)
(maximizing (find-path-reduced n end (+ dist distance) visited graph) into ret)
(finally (remhash cur visited)
(return (or ret 0)))))))
(defun reduced-neighbours (cur map part)
(let ((neighbours (neighbours cur map part)))
(iter
(for neighbour in neighbours)
(collect
(iter
(for path-square first neighbour then next-path-square)
(for path-square-prev previous path-square initially cur)
(for path-square-neighbours = (neighbours path-square map part))
(for distance from 1)
(while (= 2 (length path-square-neighbours)))
(for next-path-square =
(first (remove path-square-prev
path-square-neighbours
:test 'equal)))
(finally (return (list path-square distance))))))))
(defun build-reduced-graph (start map part)
(iter
(with to-visit = (make-queue))
(with graph = (make-hash-table :test 'equal))
(initially (queue-push-backf start to-visit))
(until (queue-empty-p to-visit))
(for cur = (queue-pop-frontf to-visit))
(unless (gethash cur graph)
(for neighbours = (reduced-neighbours cur map part))
(setf (gethash cur graph) neighbours)
(iter
(for (neighbour dist) in neighbours)
(unless (gethash neighbour graph)
(queue-push-backf neighbour to-visit))))
(finally (return graph))))
(defun day23 (input &key (part 1))
(let* ((parsed (run-parser (parse-file) input))
(start (list 0 (position #\. (first parsed))))
(end (list (1- (length parsed)) (position #\. (car (last parsed)))))
(map (hash-table-from-list-list parsed))
(visited (make-hash-table :test 'equal)))
(find-path-reduced start end 0 visited (build-reduced-graph start map part))))
| 2,917 | Common Lisp | .lisp | 69 | 32.391304 | 89 | 0.559958 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 401359b11b194cec2b57cd750d8aadf9f018e4aa130ed88dc7382a41259fe082 | 44,649 | [
-1
] |
44,650 | day7.lisp | blake-watkins_advent-of-code-2023/day7.lisp | (in-package :aoc-2023)
(defun parse-card ()
(either (parse-digit)
(bind (parse-alphanumeric)
(lambda (c) (unit (intern (string (char-upcase c)) :keyword))))))
(defun parse-file ()
(parse-lines
(with-monad
(assign cards (n-of 5 (parse-card)))
(parse-space)
(assign bid (parse-number))
(unit (list cards bid)))))
(defparameter *part-1-order* '(:a :k :q :j :t 9 8 7 6 5 4 3 2))
(defparameter *part-2-order* '(:a :k :q :t 9 8 7 6 5 4 3 2 :j))
(defparameter *hand-types* '(((5) :five-of-a-kind)
((4 1) :four-of-a-kind)
((3 2) :full-house)
((3 1 1) :three-of-a-kind)
((2 2 1) :two-pair)
((2 1 1 1) :pair)
((1 1 1 1 1) :high-card)))
(defun count-cards (hand)
(iter
(with ret = (make-hash-table))
(for card in hand)
(incf (gethash card ret 0))
(finally (return (sort (alexandria:hash-table-alist ret) #'> :key #'cdr)))))
(defun hand-type (hand part)
(let* ((type-and-count (count-cards hand))
(count
(if (= part 1)
(mapcar #'cdr type-and-count)
(let ((jokers (find :j type-and-count :key #'car))
(without-jokers (remove :j type-and-count :key #'car)))
(cond
((and jokers (= 5 (cdr jokers))) '(5))
(jokers (cons (+ (cdr (first without-jokers)) (cdr jokers))
(mapcar #'cdr (rest without-jokers))))
(t (mapcar #'cdr without-jokers)))))))
(iter
(for (pattern type) in *hand-types*)
(finding type such-that (equal pattern count)))))
(defun compare-hands (a b part)
(let ((hand-type-compare
(- (position (hand-type b part) *hand-types* :key #'second)
(position (hand-type a part) *hand-types* :key #'second))))
(if (= 0 hand-type-compare)
(let ((order (if (= part 1) *part-1-order* *part-2-order*)))
(or (iter
(for card-a in a)
(for card-b in b)
(for card-compare = (- (position card-b order)
(position card-a order)))
(finding card-compare such-that (not (= 0 card-compare))))
0))
hand-type-compare)))
(defun day7 (input &key (part 1))
(let* ((parsed (run-parser (parse-file) input)))
(iter
(for (hand bid) in
(sort parsed
(lambda (a b) (<= (compare-hands a b part) 0))
:key #'first))
(for rank from 1)
(summing (* bid rank)))))
| 2,705 | Common Lisp | .lisp | 65 | 30.015385 | 81 | 0.489176 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 290f95ac14915ebe471cdc7ce3d858943a3e85e239adff197e6f04ae306a3bff | 44,650 | [
-1
] |
44,651 | day1.lisp | blake-watkins_advent-of-code-2023/day1.lisp | (in-package :aoc-2023)
(defun get-number-strings (&key part)
(iter
(for i from 1 to 9)
(collect (list (format nil "~a" i) i))
(when (= part 2)
(collect (list (format nil "~R" i) i)))))
(defun match-number-string (input number-strings)
(iter
(for (str val) in number-strings)
(for first-match = (search str input))
(for last-match = (search str input :from-end t))
(when first-match (finding val minimizing first-match into first-number))
(when last-match (finding val maximizing last-match into last-number))
(finally (return (+ (* 10 first-number) last-number)))))
(defun day1 (input &key (part 1))
(let ((lines (str:lines input))
(number-strings (get-number-strings :part part)))
(reduce #'+
(mapcar (lambda (x) (match-number-string x number-strings)) lines))))
| 833 | Common Lisp | .lisp | 20 | 37.2 | 78 | 0.654321 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | f04121083a11b600fd9a4c560141f65503ecc6a9684306dac55e3544c181a6d8 | 44,651 | [
-1
] |
44,652 | day20.lisp | blake-watkins_advent-of-code-2023/day20.lisp | (in-package :aoc-2023)
(define-condition queue-empty (condition) ())
(define-condition recieved-value (condition) ((name :initarg :name)))
;; PARSING
(defun parse-type ()
(either (with-monad
(assign type (parse-character "%&"))
(unit (case type (#\% :flip-flop) (#\& :conjunction))))
(unit :other)))
(defun parse-file ()
(parse-lines
(with-monad
(assign type (parse-type))
(assign name (parse-keyword))
(parse-string " -> ")
(assign destinations (parse-list (parse-keyword #'alpha-char-p) ", "))
(unit (list name type destinations)))))
;; MODULES
;; Each MODULE has a name, a list of (input) terminals, and a list of terminals
;; of other modules to output to.
(defclass module ()
((name :initarg :name)
(terminals :initform '())
(outputs :initform '())))
;; Flip flop modules have a STATE that can be :off or :on.
(defclass flip-flop-module (module)
((state :initform :off)))
(defclass conjunction-module (module) ())
;; A button module keeps track of how many times it's been pushed (pulsed).
(defclass button-module (module)
((pushes :initform 0 :accessor button-pushes)))
;; A watcher contains a value to watch for.
(defclass watcher-module (module)
((watch-for :initform '())))
;; TERMINALS
;; A terminal keeps track of which module created it.
(defclass terminal ()
((module :initarg :module :initform nil)))
;; Terminals of conjunction modules keep track of the last pulse they recieved.
(defclass conjunction-terminal (terminal)
((last-pulse :initform :low :accessor last-pulse)))
;; MAKE-TERMINAL
(defgeneric make-terminal (module))
(defmethod make-terminal ((module module))
(make-instance 'terminal :module module))
;; Store the newly created terminal.
(defmethod make-terminal :around ((module module))
(let ((new-terminal (call-next-method)))
(push new-terminal (slot-value module 'terminals))
new-terminal))
(defmethod make-terminal ((module conjunction-module))
(make-instance 'conjunction-terminal :module module))
;; PULSE
;; Sends THING a PULSE. Returns (possibly updated) QUEUE.
(defgeneric pulse (thing pulse queue))
;; TERMINALS send the pulse to their module.
(defmethod pulse ((terminal terminal) pulse queue)
(pulse (slot-value terminal 'module) pulse queue))
;; MODULES queue pulses for all of their outputs.
(defmethod pulse ((module module) pulse queue)
(with-slots (name outputs) module
(iter
(for (output-name output) in (reverse outputs))
(queue-push-backf (list name output-name output pulse) queue)
(finally (return queue)))))
;; A FLIP-FLOP-MODULE changes state on a low pulse, and then calls PULSE on the
;; base module to send a pulse to all its outputs.
(defmethod pulse ((module flip-flop-module) pulse queue)
(if (eq pulse :low)
(with-slots (state) module
(case state
(:off
(setf state :on)
(call-next-method module :high queue))
(:on
(setf state :off)
(call-next-method module :low queue))))
queue))
;; A CONJUNCTION-TERMINAL stores the pulse before forwarding it to its module.
(defmethod pulse ((terminal conjunction-terminal) pulse queue)
(with-slots (module last-pulse) terminal
(setf last-pulse pulse)
(pulse module pulse queue)))
;; A CONJUNCTION-MODULE tests whether all it's inputs are high, then calls PULSE
;; on the base module to send the appropriate pulse to its outputs.
(defmethod pulse ((module conjunction-module) pulse queue)
(declare (ignore pulse))
(with-slots (terminals) module
(let ((all-high (every (lambda (terminal)
(eq (last-pulse terminal) :high))
terminals)))
(call-next-method module (if all-high :low :high) queue))))
;; A BUTTON-MODULE counts how many times it's been pulsed.
(defmethod pulse ((module button-module) pulse queue)
(incf (slot-value module 'pushes))
(call-next-method))
;; A WATCHER-MODULE watches for a specific :low/:high pulse. Raises 'RECIEVED-VALUE
;; when it see it.
(defmethod pulse ((module watcher-module) pulse queue)
(when (eq pulse (slot-value module 'watch-for))
(cerror "Continue" 'recieved-value))
(call-next-method))
;; OTHER FUNCTIONS
(defun connect (source destination)
"Create input terminal at DESTINATION then add it to SOURCE's outputs. "
(let ((input-terminal (make-terminal destination)))
(push (list (slot-value destination 'name) input-terminal)
(slot-value source 'outputs))))
(defun make-module (type name)
"Make module of appropriate type. "
(make-instance (case type
(:flip-flop 'flip-flop-module)
(:conjunction 'conjunction-module)
(:button 'button-module)
(:watcher 'watcher-module)
(otherwise 'module))
:name name))
(defun make-modules (input button)
"Parse INPUT, create and connect all modules, connect BUTTON to broadcaster. "
(let* ((parsed (run-parser (parse-file) input))
(modules (iter
(with ret = (make-hash-table))
(for (name type outputs) in parsed)
(setf (gethash name ret) (make-module type name))
(finally (return ret)))))
(iter
(for (name type outputs) in parsed)
(for source = (gethash name modules))
(iter
(for destination-name in outputs)
(for destination = (or (gethash destination-name modules)
(make-module :other destination-name)))
(connect source destination)))
(connect button (gethash :broadcaster modules))
modules))
(defun add-watchers (names watch-for modules)
"Connect a watcher to each of the modules in NAMES. "
(iter
(for name in names)
(for watcher = (make-module :watcher :watcher))
(setf (slot-value watcher 'watch-for) watch-for)
(connect (gethash name modules) watcher)))
(defun run-simulation ()
(iter
(with queue = (make-queue))
(with results = (make-hash-table))
(restart-case
(when (queue-empty-p queue) (error 'queue-empty))
(push-button (button)
(setf queue (pulse button :low queue)))
(exit () (finish)))
(until (queue-empty-p queue))
(for (src dest terminal pulse) = (queue-pop-frontf queue))
;; (format t "~a ~a -> ~a~%" src pulse dest)
(incf (gethash pulse results 0))
(restart-case
(setf queue (pulse terminal pulse queue))
(exit () (finish)))
(finally (return results))))
(defun day20 (input &key (part 1))
(let* ((button (make-module :button :button))
(modules (make-modules input button))
(num-button-pushes '()))
(when (= part 2) (add-watchers '(:sr :sn :rf :vq) :high modules))
(handler-bind
((queue-empty (lambda (c)
(declare (ignore c))
(if (or (= part 2) (< (button-pushes button) 1000))
(invoke-restart 'push-button button)
(invoke-restart 'exit))))
(recieved-value (lambda (c)
(declare (ignore c))
(push (button-pushes button) num-button-pushes)
(if (< (length num-button-pushes) 4)
(invoke-restart 'continue)
(invoke-restart 'exit)))))
(let ((pulses (run-simulation)))
(if (= part 1)
(apply #'* (alexandria:hash-table-values pulses))
(apply #'lcm num-button-pushes))))))
| 7,668 | Common Lisp | .lisp | 180 | 35.4 | 83 | 0.635656 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | eb9eba105da408cc660cf0a6f9ea08164b26be21d6ab8fe278317e65258e47f6 | 44,652 | [
-1
] |
44,653 | day2.lisp | blake-watkins_advent-of-code-2023/day2.lisp | (in-package :aoc-2023)
(defun parse-roll ()
(parse-list
(with-monad
(assign amount (parse-number))
(parse-string " ")
(assign color (parse-keyword #'alphanumericp))
(unit (list amount color)))
", "))
(defun parse-game ()
(with-monad
(parse-string "Game ")
(assign id (parse-number))
(parse-string ": ")
(assign rolls (parse-list (parse-roll) "; "))
(unit (list id rolls))))
(defun game-valid? (limits game)
(iter
(for (limit-amount limit-color) in limits)
(always
(iter
(for rolls in (second game))
(always
(iter
(for (roll-amount roll-color) in rolls)
(never (and (eq roll-color limit-color)
(> roll-amount limit-amount)))))))))
(defun game-power (game)
(let ((maxs (iter
(with maximums = (make-hash-table :test 'eq))
(for roll-set in (second game))
(iter
(for (amount color) in roll-set)
(setf (gethash color maximums)
(max amount (gethash color maximums 0))))
(finally (return maximums)))))
(reduce #'* (mapcar (lambda (c) (gethash c maxs 0)) '(:red :blue :green)))))
(defun day2 (input &key (part 1))
(let ((limits '((12 :red) (13 :green) (14 :blue)))
(games (run-parser (parse-lines (parse-game)) input)))
(if (= part 1)
(iter
(for game in games)
(when (game-valid? limits game) (sum (first game))))
(reduce #'+ (mapcar #'game-power games)))))
| 1,564 | Common Lisp | .lisp | 45 | 26.755556 | 80 | 0.547918 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | d28d157266e96c37e871b73bddd098f16917a6a10b00057b9c6ab98f70f8f583 | 44,653 | [
-1
] |
44,654 | day8.lisp | blake-watkins_advent-of-code-2023/day8.lisp | (in-package :aoc-2023)
(defun parse-file ()
(with-monad
(assign directions (one-or-more (parse-character "LR")))
(n-of 2 (parse-newline))
(assign network
(parse-lines
(with-monad
(assign name (parse-keyword))
(parse-string " = ")
(assign paths (parse-bracketed
(parse-list (parse-keyword #'alphanumericp) ", ")
"()"))
(unit (cons name paths)))))
(unit (list directions network))))
(defun make-circular (lst)
(setf (cdr (last lst)) lst))
(defun locations-ending-with (network char)
(iter
(for (name nil nil) in network)
(when (char= char (elt (symbol-name name) 2)) (collect name))))
(defun steps-to-finish (directions network start-symbol end-symbols)
(iter
(for steps from 0)
(for direction in directions)
(for location initially start-symbol then next-location)
(until (member location end-symbols))
(for next-locations = (find location network :key #'first))
(for next-location = (if (char= direction #\L)
(second next-locations)
(third next-locations)))
(finally (return steps))))
(defun day8 (input &key (part 1))
(destructuring-bind (directions network) (run-parser (parse-file) input)
(setf directions (make-circular directions))
(if (= part 1)
(steps-to-finish directions network :aaa '(:zzz))
(apply #'lcm
(iter
(with end-symbols = (locations-ending-with network #\Z))
(for start-symbol in (locations-ending-with network #\A))
(collect
(steps-to-finish directions network
start-symbol end-symbols)))))))
| 1,833 | Common Lisp | .lisp | 44 | 31.113636 | 79 | 0.568946 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | f1b3e83f471ce61465f620ddc58041e69e0e16a5d2e894f43eb18031828c15f3 | 44,654 | [
-1
] |
44,655 | advent-of-code-2023.asd | blake-watkins_advent-of-code-2023/advent-of-code-2023.asd | (asdf:defsystem "advent-of-code-2023"
:description "Advent of Code 2023"
:version "0.0.1"
:author "Blake Watkins <blakewatkins@gmail.com>"
:licence "GNU General Public License (GPL) version 3"
:depends-on ("advent-of-code" "iterate" "fset" "str")
:components ((:file "package")
(:file "day1" :depends-on ("package"))
(:file "day2" :depends-on ("package"))
(:file "day3" :depends-on ("package"))
(:file "day4" :depends-on ("package"))
(:file "day5" :depends-on ("package"))
(:file "day6" :depends-on ("package"))
(:file "day7" :depends-on ("package"))
(:file "day8" :depends-on ("package"))
(:file "day9" :depends-on ("package"))
(:file "day10" :depends-on ("package"))
(:file "day11" :depends-on ("package"))
(:file "day12" :depends-on ("package"))
(:file "day13" :depends-on ("package"))
(:file "day14" :depends-on ("package"))
(:file "day15" :depends-on ("package"))
(:file "day16" :depends-on ("package"))
(:file "day17" :depends-on ("package"))
(:file "day18" :depends-on ("package"))
(:file "day19" :depends-on ("package"))
(:file "day20" :depends-on ("package"))
(:file "day21" :depends-on ("package"))
(:file "day22" :depends-on ("package"))
(:file "day23" :depends-on ("package"))))
| 1,506 | Common Lisp | .asd | 30 | 38.7 | 56 | 0.519648 | blake-watkins/advent-of-code-2023 | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 88be14efc439af6e794578f37f766c2b8d0e599bb69651f8f0ce59ef5c103f7b | 44,655 | [
-1
] |
44,694 | package.lisp | eriedaberrie_cl-hyprland-ipc/src/package.lisp | (uiop:define-package #:hyprland-ipc
(:use #:cl #:alexandria #:split-sequence)
(:local-nicknames (#:jzon #:com.inuoe.jzon))
(:export
#:*hyprctl-socket*
#:*events-socket*
;; Hyprctl
#:*hyprctl-retry-send-count*
#:hyprctl
#:hyprctl-batch
#:find-client-data
#:find-workspace-data
#:find-monitor-data
;; Events
#:*events-spec*
#:handle-events-raw
#:handle-events
))
| 412 | Common Lisp | .lisp | 18 | 19.055556 | 46 | 0.647059 | eriedaberrie/cl-hyprland-ipc | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 8ac59f442e7ccace17a187242ad3b21c297877d0cc6dcce0c89a4e91ada8d21d | 44,694 | [
-1
] |
44,695 | sockets.lisp | eriedaberrie_cl-hyprland-ipc/src/sockets.lisp | (in-package #:hyprland-ipc)
(defvar *hyprctl-socket* nil)
(defvar *events-socket* nil)
(defun init-socket-locations ()
(when-let ((signature (uiop:getenv "HYPRLAND_INSTANCE_SIGNATURE")))
(macrolet ((hypr-socket-for (var file)
`(setf ,var
(namestring (uiop:xdg-runtime-dir "hypr" signature ,file)))))
(hypr-socket-for *hyprctl-socket* ".socket.sock")
(hypr-socket-for *events-socket* ".socket2.sock"))))
(uiop:register-image-restore-hook #'init-socket-locations
(not (and *hyprctl-socket* *events-socket*)))
(defmacro with-local-stream-socket ((socket address) &body body)
`(let ((,socket (make-instance 'sb-bsd-sockets:local-socket :type :stream)))
(sb-bsd-sockets:socket-connect ,socket ,address)
(unwind-protect
(progn ,@body)
(sb-bsd-sockets:socket-close ,socket))))
| 896 | Common Lisp | .lisp | 18 | 41.777778 | 85 | 0.640732 | eriedaberrie/cl-hyprland-ipc | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 02743873bd1816175e64040cd59d03c64431b1374fc13a65a2e5685f2fe80a0a | 44,695 | [
-1
] |
44,696 | events.lisp | eriedaberrie_cl-hyprland-ipc/src/events.lisp | (in-package #:hyprland-ipc)
(defvar *events-spec* '((:workspace "workspace" 1)
(:focused-monitor "focusedmon" 2)
(:active-window nil 3)
(:fullscreen "fullscreen" 1)
(:monitor-removed "monitorremoved" 1)
(:monitor-added "monitoradded" 1)
(:create-workspace "createworkspace" 1)
(:destroy-workspace "destroyworkspace" 1)
(:move-workspace "moveworkspace" 2)
(:rename-workspace "renameworkspace" 2)
(:active-special "activespecial" 2)
(:active-layout "activelayout" 2)
(:open-window "openwindow" 4)
(:close-window "closewindow" 1)
(:move-window "movewindow" 2)
(:open-layer "openlayer" 1)
(:close-layer "closelayer" 1)
(:submap "submap" 1)
(:change-floating-mode "changefloatingmode" 2)
(:urgent "urgent" 1)
(:minimize "minimize" 2)
(:screencast "screencast" 2)
(:window-title "windowtitle" 1)
(:ignore-group-lock "ignoregrouplock" 1)
(:lock-groups "lockgroups" 1))
"A list containing the spec for the events received from the socket.
In order: identifier for use in HANDLE-EVENTS, string prefix received from the socket, and argument count.")
(defun handle-events-raw (handler &key return-on-non-nil-p)
"Listen to Hyprland events, calling HANDLER every time a new event happens.
HANDLER should have a single argument, which is the line that was received from the socket. If RETURN-ON-NON-NIL-P is non-NIL, stop at and return the first non-NIL result."
(with-local-stream-socket (events-socket *events-socket*)
(loop :with events-stream := (sb-bsd-sockets:socket-make-stream events-socket
:input t)
:for line := (read-line events-stream)
:while line
:for value := (funcall handler line)
:when (and return-on-non-nil-p value)
:return value)))
(defun handle-line-if-matching-event (line prefix argc handler)
"If LINE starts with PREFIX, split the remainder of the line into ARGC strings with commas and apply them to HANDLER.
Return whether or not LINE started with PREFIX, and also the result of HANDLER if it was called."
(when-let (data-string (nth-value 1
(starts-with-subseq prefix
line
:return-suffix t)))
(multiple-value-bind (sequences index)
(split-sequence #\,
data-string
:count (1- argc))
(values t
(apply handler
(nconc sequences (list (subseq data-string index))))))))
(defun handle-events (&rest handlers &key return-on-non-nil-p &allow-other-keys)
"Listen for events from Hyprland, and apply the arguments of the events to the HANDLER with the matching KEY in HANDLERS.
Pass RETURN-ON-NON-NIL-P to HANDLE-EVENTS-RAW."
(let ((handler-table (loop :with active-window-data
:with added-active-window-listener-p
:with event-spec
:for (key handler) :on handlers :by #'cddr
:when (eq key :active-window)
:collect (list "activewindowv2>>"
1
(let ((handler handler))
(lambda (&rest args)
(apply handler
(append active-window-data
args)))))
:and :unless added-active-window-listener-p
:collect (list "activewindow>>"
2
(lambda (&rest args)
(setf active-window-data args)
nil))
:and :do (setf added-active-window-listener-p t)
:end
:else :when (setf event-spec (assoc key *events-spec*))
:collect (destructuring-bind (prefix argc)
(cdr event-spec)
(list (concatenate 'string prefix ">>")
argc
handler)))))
(handle-events-raw (lambda (line)
(dolist (handler-spec handler-table)
(multiple-value-bind (matchp value)
(apply #'handle-line-if-matching-event line handler-spec)
(when matchp
(return value)))))
:return-on-non-nil-p return-on-non-nil-p)))
| 5,570 | Common Lisp | .lisp | 89 | 36.595506 | 172 | 0.454778 | eriedaberrie/cl-hyprland-ipc | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | d31dea80b3029ee4a4dfad7e176fa43d0e9e0cb510bb95db709cad590a3d5680 | 44,696 | [
-1
] |
44,697 | cl-hyprland-ipc.asd | eriedaberrie_cl-hyprland-ipc/cl-hyprland-ipc.asd | (asdf:defsystem cl-hyprland-ipc
:version "0.1.0"
:author "eriedaberrie <eriedaberrie@gmail.com>"
:maintainer "eriedaberrie <eriedaberrie@gmail.com>"
:license "gpl3"
:description "Common Lisp bindings for Hyprland IPC"
:homepage "https://github.com/eriedaberrie/cl-hyprland-ipc"
:pathname #P"src/"
:components ((:file "package")
(:file "sockets" :depends-on ("package"))
(:file "hyprctl" :depends-on ("sockets"))
(:file "events" :depends-on ("sockets")))
:depends-on (#:alexandria #:babel #:com.inuoe.jzon #:sb-bsd-sockets #:split-sequence))
| 604 | Common Lisp | .asd | 13 | 40.615385 | 88 | 0.661591 | eriedaberrie/cl-hyprland-ipc | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | da29ca364fd3d12e6f045a688f35815a0dabd06e6ac115945d6db07045591757 | 44,697 | [
-1
] |
44,700 | flake.lock | eriedaberrie_cl-hyprland-ipc/flake.lock | {
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1715087517,
"narHash": "sha256-CLU5Tsg24Ke4+7sH8azHWXKd0CFd4mhLWfhYgUiDBpQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "b211b392b8486ee79df6cdfb1157ad2133427a29",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs",
"systems": "systems"
}
},
"systems": {
"locked": {
"lastModified": 1689347949,
"narHash": "sha256-12tWmuL2zgBgZkdoB6qXZsgJEH9LR3oUgpaQq2RbI80=",
"owner": "nix-systems",
"repo": "default-linux",
"rev": "31732fcf5e8fea42e59c2488ad31a0e651500f68",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default-linux",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
| 1,025 | Common Lisp | .l | 43 | 16.790698 | 73 | 0.511202 | eriedaberrie/cl-hyprland-ipc | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 1794c9386f4965bfe963bef2e9419fbb8f2f4a5c274732d6421fa74cec0e98a3 | 44,700 | [
-1
] |
44,701 | flake.nix | eriedaberrie_cl-hyprland-ipc/flake.nix | {
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
systems.url = "github:nix-systems/default-linux";
};
outputs = {
self,
nixpkgs,
systems,
...
}: let
inherit (nixpkgs) lib;
forSystems = f:
lib.genAttrs (import systems) (system: f nixpkgs.legacyPackages.${system});
in {
overlays = {
default = _: prev: {
cl-hyprland-ipc = prev.callPackage ./nix {
lispImpl = prev.sbcl;
};
};
};
packages = forSystems (pkgs: rec {
inherit (self.overlays.default pkgs pkgs) cl-hyprland-ipc;
default = cl-hyprland-ipc;
});
devShells = forSystems (
pkgs: {
default = pkgs.mkShell {
name = "cl-hyprland-ipc-shell";
nativeBuildInputs = [
(pkgs.sbcl.withPackages (lib.const self.packages.${pkgs.system}.cl-hyprland-ipc.lispLibs))
];
};
}
);
formatter = forSystems (pkgs: pkgs.alejandra);
};
}
| 987 | Common Lisp | .l | 39 | 19.128205 | 102 | 0.57839 | eriedaberrie/cl-hyprland-ipc | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 5f027af2c87934a4b721c0301f46e88e35f4717eb4938ea08ff6b64012262570 | 44,701 | [
-1
] |
44,705 | default.nix | eriedaberrie_cl-hyprland-ipc/nix/default.nix | {
lib,
lispImpl,
}:
lispImpl.buildASDFSystem {
pname = "cl-hyprland-ipc";
version = "0.1.0";
src = lib.cleanSource ../.;
lispLibs = with lispImpl.pkgs; [alexandria babel jzon split-sequence];
}
| 206 | Common Lisp | .l | 10 | 18.4 | 72 | 0.688776 | eriedaberrie/cl-hyprland-ipc | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 841e94da53692e2ad45a8bb8bc731c088db3e22407e7fc6cc6dbb1dcce8ce0e1 | 44,705 | [
-1
] |
44,720 | day-template.lisp | jonakeys_AdventOfCode2023/day-template.lisp | (defun name-day ()
(name-day-part1)
(name-day-part2))
(defun name-day-part1 ()
(with-open-file (file "input.txt")
(let ((sum 0))
(loop for line = (read-line file nil nil)
while line
do
)
(format t "Part 1: ~d~%" sum))))
(defun name-day-part2 ()
(with-open-file (file "input.txt")
(let ((sum 0))
(loop for line = (read-line file nil nil)
while line
do
)
(format t "Part 2: ~d~%" sum))))
| 430 | Common Lisp | .lisp | 19 | 19.315789 | 44 | 0.599509 | jonakeys/AdventOfCode2023 | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | 42c7d1eef50dcb6651a92042f2d0bde579130282c4133a2b41faa7d73d432248 | 44,720 | [
-1
] |
44,721 | day1.lisp | jonakeys_AdventOfCode2023/day1/day1.lisp | (defun trebuchet ()
(trebuchet-part1)
(trebuchet-part2))
(defun trebuchet-part1 ()
(with-open-file (file "input.txt")
(let ((numbers) (sum 0))
(loop for line = (read-line file nil nil)
while line
do
(setq line (coerce line 'list))
(setq numbers '())
(dolist (x line numbers)
(if (digit-char-p x)
(push (digit-char-p x) numbers)))
(setq sum (+ sum (* (car (last numbers)) 10) (car numbers))))
(format t "Part 1: ~d~%" sum))))
(defun trebuchet-part2 ()
(with-open-file (file "input.txt")
(let ((numbers) (sum 0)
(duos '(("one" "o1e") ("two" "t2o") ("three" "th3ee") ("four" "f4ur")
("five" "f5ve") ("six" "s6x") ("seven" "se7en")
("eight" "ei8ht") ("nine" "n9ne") ("zero" "z0ro"))))
(loop for line = (read-line file nil nil)
while line
do
(dolist (duo duos)
(setq line (cl-ppcre:regex-replace-all
(car duo) line (cdr duo))))
(setq line (coerce line 'list))
(setq numbers '())
(dolist (x line numbers)
(if (digit-char-p x)
(push (digit-char-p x) numbers)))
(setq sum (+ sum (* (car (last numbers)) 10) (car numbers))))
(format t "Part 2: ~d~%" sum))))
| 1,190 | Common Lisp | .lisp | 35 | 28.971429 | 73 | 0.568083 | jonakeys/AdventOfCode2023 | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | b8113401a4728192813ad7264c67ba9e6d1a56b56d192aa4db0a051f2922ab04 | 44,721 | [
-1
] |
44,722 | day3.lisp | jonakeys_AdventOfCode2023/day3/day3.lisp | (defun gear-ratios ()
(gear-ratios-part1)
(gear-ratios-part2))
(defun gear-ratios-part1 ()
(with-open-file (file "input.txt")
(let ((sum 0))
(loop for line = (read-line file nil nil)
while line
do
)
(format t "Part 1: ~d~%" sum))))
(defun gear-ratios-part2 ()
(with-open-file (file "input.txt")
(let ((sum 0))
(loop for line = (read-line file nil nil)
while line
do
)
(format t "Part 2: ~d~%" sum))))
| 457 | Common Lisp | .lisp | 19 | 20.105263 | 44 | 0.613744 | jonakeys/AdventOfCode2023 | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | fc49d857e48ffcffc32db6cf3e32edcfbbfc2f1162ac51b97711777bbcbe5475 | 44,722 | [
-1
] |
44,723 | day2.lisp | jonakeys_AdventOfCode2023/day2/day2.lisp | (defun cube-conundrum ()
(cube-conundrum-part1)
(cube-conundrum-part2))
(defun cube-conundrum-part1 ()
(with-open-file (file "input.txt")
(let ((sum 0) (gamenr) (line-split) (sets) (colors) (couple) (cubecolor)
(cubeamount) (redcubes 12) (greencubes 13) (bluecubes 14)
(red) (green) (blue))
(loop for line = (read-line file nil nil)
while line
do
(setq red 0)
(setq green 0)
(setq blue 0)
;; split line in game info and sets
(setq line-split (split-sequence:split-sequence #\: line))
;; set game number
(setq gamenr (parse-integer
(car (cdr
(split-sequence:split-sequence
#\Space
(car line-split))))))
;; split sets
(setq sets (split-sequence:split-sequence
#\;
(car (cdr line-split))))
;; traverse set items
(dolist (item sets)
;; split set in colors
(setq colors (split-sequence:split-sequence #\, item))
;; traverse per color
(dolist (color colors)
;; couple is <num> <color>
(setq couple (split-sequence:split-sequence #\Space color))
;; get color of cubes
(setq cubecolor (car (cdr (cdr couple))))
;; get amount of cubes
(setq cubeamount (parse-integer (car (cdr couple))))
;; count number of cubes per color
(if (and (equalp "red" cubecolor) (> cubeamount red))
(setq red cubeamount))
(if (and (equalp "green" cubecolor) (> cubeamount green))
(setq green cubeamount))
(if (and (equalp "blue" cubecolor) (> cubeamount blue))
(setq blue cubeamount))))
;; check if game is possible
(if (and
(<= red redcubes)
(<= green greencubes)
(<= blue bluecubes))
(incf sum gamenr)))
(format t "Part 1: ~d~%" sum))))
(defun cube-conundrum-part2 ()
(with-open-file (file "input.txt")
(let ((sum 0) (line-split) (sets) (colors) (couple) (cubecolor) (cubeamount)
(red) (green) (blue))
(loop for line = (read-line file nil nil)
while line
do
(setq red 0)
(setq green 0)
(setq blue 0)
;; split line in game info and sets
(setq line-split (split-sequence:split-sequence #\: line))
;; split sets
(setq sets (split-sequence:split-sequence
#\;
(car (cdr line-split))))
;; traverse set items
(dolist (item sets)
;; split set in colors
(setq colors (split-sequence:split-sequence #\, item))
;; traverse per color
(dolist (color colors)
;; couple is <num> <color>
(setq couple (split-sequence:split-sequence #\Space color))
;; get color of cubes
(setq cubecolor (car (cdr (cdr couple))))
;; get amount of cubes
(setq cubeamount (parse-integer (car (cdr couple))))
;; count number of cubes per color
(if (and (equalp "red" cubecolor) (> cubeamount red))
(setq red cubeamount))
(if (and (equalp "green" cubecolor) (> cubeamount green))
(setq green cubeamount))
(if (and (equalp "blue" cubecolor) (> cubeamount blue))
(setq blue cubeamount))))
(incf sum (* red green blue)))
(format t "Part 2: ~d~%" sum))))
| 3,190 | Common Lisp | .lisp | 89 | 29.157303 | 77 | 0.599548 | jonakeys/AdventOfCode2023 | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:37 AM (Europe/Amsterdam) | da721d3d7a84504d15f69c3facc8b3c6672d0670088cd74013685cf066a14103 | 44,723 | [
-1
] |
44,743 | moonlander.lisp | steve-ttt_moonlander_lisp/moonlander.lisp | ;; compile with
;; (sb-ext:save-lisp-and-die "moonlander.exe" :executable t :toplevel 'main)
;;10 print "moonlander"
;;20 let time = 0
;;30 let height = 500
;;40 let vel = 50
;;50 let fuel = 120
;;60 print "time ";time,"height ";height
;;70 print "vel ";vel,"fuel ";fuel
;;85 for i = 2 to height/500*40
;;86 print " ";
;;87 next i
;;88 print "*"
;;90 if fuel=0 goto 140
;;100 print "burn? (1-30)"
;;110 input b
;;120 if b<=0 then let b = 0
;;130 if b>=30 then let b = 30
;;140 if b > fuel then let b = fuel
;;150 let v1 = vel-b+5
;;160 let fuel = fuel - b
;;170 if (v1-vel)/2 >= height then goto 220
;;180 let height = height - (v1-vel)/2
;;190 let time = time + 1
;;200 let vel = v1
;;210 goto 60
;;220 let v1 = vel + (5 - b) * height / vel
;;230 if v1 > 5 then print "You crashed all dead"
;;240 if v1 > 1 and v1 <= 5 then print "Ok but some injuries"
;;250 if v1 < 1 then print "Good landing !"
;;260 stop
;; 1.625 m/s^2 luna grav
;; v = v_0 + at ; where v is the final velocity, v_0 is the initial velocity,
;; a is the acceleration, and t is the time.
;; A space craft falling at 5 m/s after 10 seconds on luna acceleration
;; would be traveling at 21 m/s = 5 + (1.625 * 10)
(defvar *velocity* (+ 7 (random 18)) ) ;; random number between 7 and 25
(defvar *time* 0)
(defvar *start-height* (+ 400 (random 100)))
(defvar *fuel* (+ 80 (random 11)))
(defvar *term-column-width* 80)
(defvar *grav* 1.625)
(defun print-height-bar (column-width)
(if (zerop column-width) '*
(progn (format t "#")
(print-height-bar (1- column-width)))))
(defun print-stats (height)
(format t "~%Time: ~A (sec)~tHeight: ~A (M)" *time* (floor height))
(format t "~%Velocity: ~A (m/s)~tFuel: ~A (L)~%" *velocity* *fuel*)
(if (< 500 height) (format t "* * * * * * * * * * * * * * TOO HIGH * * * * * * * * * * * * *")
(print-height-bar (floor (* (/ height *start-height*) *term-column-width*)))))
(defun landed (vel)
(cond ((> vel 2.5) (format t "~%You crashed all dead!~%~%"))
((and (> vel 1) (< vel 2.5)) (format t "~%Ok but some injuries!~%~%"))
(t (format t "~%Good landing commander!~%~%")))
(exit))
(defun get-valid-number ()
(let ((input nil))
(loop
(format t "~%[burn #] > " )
(finish-output)
(setf input (read-line))
(if (numberp (parse-integer input :junk-allowed t))
(if (>= (parse-integer input) 0)
(return (parse-integer input))
(format t "Nice try but you can't give yourself fuel!~%"))
(format t "Invalid input. Try again.~%")))))
(defun clear-screen ()
(format t "~c[2J" #\Escape))
(defun game-loop (height)
(let ((burn 0)
(v_0 *velocity*))
(if (<= height 0)
(landed *velocity*)
(progn
(clear-screen)
(print-stats height)
;(format t "~%[burn #] > ")
(setf burn (get-valid-number))
(if (and (not (null burn)) (numberp burn))
'burn
(setf burn 0))
(setf *fuel* (- *fuel* burn))
(setf v_0 (+ *velocity* (* -1 burn)))
(setf *velocity* (+ v_0 (* *grav* 1))) ; Fix parentheses here
(setf height (- height (* *velocity* 1))) ; Fix calculation here
(setf *time* (1+ *time*))
(game-loop height))))) ; Add closing parenthesis here
;;run game
(defun main ()
(game-loop *start-height*))
| 3,382 | Common Lisp | .lisp | 91 | 33.164835 | 96 | 0.574702 | steve-ttt/moonlander_lisp | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:45 AM (Europe/Amsterdam) | 3c778fc2f0f1c49289215c67bd0c1f37a56ef82a3eb2d56b219f0bbadec6e85e | 44,743 | [
-1
] |
44,760 | mandel.compile.lisp | sourceprobe_mandelbrot_lisp/mandel.compile.lisp | #!/usr/local/bin/sbcl --script
(load "mandel.lisp")
; Compile to an executable.
(defun save ()
(sb-ext:save-lisp-and-die
"mandel.sbcl.o"
:toplevel #'main
:executable t))
(save)
| 209 | Common Lisp | .lisp | 9 | 18.666667 | 30 | 0.619289 | sourceprobe/mandelbrot_lisp | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:45 AM (Europe/Amsterdam) | 8f68f0049581f2cd7a1b6175741b77940f282f4ed671a7289ee50ddd89ff2b87 | 44,760 | [
-1
] |
44,761 | mandel.lisp | sourceprobe_mandelbrot_lisp/mandel.lisp | (defconstant MAX_ITERATIONS 27)
(defconstant OUTPUT_RES_X 3.5)
(defconstant OUTPUT_RES_Y 2)
(defconstant OUTPUT_OFFSET_X -2.5)
(defconstant OUTPUT_OFFSET_Y -1)
(defconstant RESOLUTION_X 150)
(defconstant RESOLUTION_Y 60)
; turn # interations into a char for display
(defun show (val)
(if (<= val 26)
(code-char (+ val
-1
(char-code #\A)))
" "))
; Calculate how many steps are required.
(defun calc (x y)
(let (
(xi (+ OUTPUT_OFFSET_X (* OUTPUT_RES_X (/ x RESOLUTION_X))))
(yi (+ OUTPUT_OFFSET_Y (* OUTPUT_RES_Y (/ y RESOLUTION_Y)))))
(loop for iters below MAX_ITERATIONS
for x = 0 then (+ (+ xi (* x x) (* -1 y y)))
and y = 0 then (+ yi (* x y 2))
when (< 4 (+ (* x x) (* y y)))
do (return iters)
finally (return iters))))
(defun draw_window (width height)
(dotimes (y height)
(dotimes (x width)
(princ (show (calc x y))))
(terpri)))
(defun main ()
(draw_window RESOLUTION_X RESOLUTION_Y))
| 1,049 | Common Lisp | .lisp | 32 | 26.8125 | 67 | 0.578265 | sourceprobe/mandelbrot_lisp | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:45 AM (Europe/Amsterdam) | 8377d9d1b366d9bf0f5192575f58035a63d2e810c912f6263c5cbd8f92da3d91 | 44,761 | [
-1
] |
44,779 | bf.compile.lisp | sourceprobe_bf_lisp/bf.compile.lisp | #!/usr/local/bin/sbcl --script
(load "bf.lisp")
; Compile to an executable.
(defun save ()
(sb-ext:save-lisp-and-die
"bf.sbcl.o"
:toplevel #'main
:executable t))
(save)
| 201 | Common Lisp | .lisp | 9 | 17.777778 | 30 | 0.603175 | sourceprobe/bf_lisp | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | a5bb48d5672d1b5daccdab3da12bdf6c64c7f80dd741d85fade623be64d62833 | 44,779 | [
-1
] |
44,780 | bf.lisp | sourceprobe_bf_lisp/bf.lisp | (defconstant TAPE_LEN 30000)
; return hash tables to find matching braces
(defun build_jumps (program)
; first element of stack is top of stack
(let ((stack nil)
(forward (make-hash-table))
(backward (make-hash-table)))
(loop for i below (length program)
for c = (char program i)
do (cond
((eq c #\[) (setf stack (cons i stack)))
((eq c #\])
(let ((open (car stack))
(close i))
(progn
(setf stack (cdr stack))
(setf (gethash open forward) close)
(setf (gethash close backward) open)))))
finally
(return (if
(eq nil stack)
(cons forward backward)
(error "jump stack not empty"))))))
(defun jump (table i)
(if (gethash i table)
(gethash i table)
(error "missing jump.")))
(defun tape-inc (tape i)
(if (< i 0)
(error "negative index: " i)
(setf (aref tape i) (rem (+ (aref tape i) 1) 256))))
(defun tape-dec (tape i)
(if (< i 0)
(error "negative index: " i)
(setf (aref tape i) (rem (- (aref tape i) 1) 256))))
(defun bf (program)
(let* ((jumps (build_jumps program))
(tape (make-array (list TAPE_LEN) :initial-element 0))
(pc 0)
(ptr 0)
(forward (car jumps))
(backward (cdr jumps)))
(loop while (< pc (length program))
do
(let ((c (char program pc)))
(cond
((eq c #\+) (tape-inc tape ptr))
((eq c #\-) (tape-dec tape ptr))
((eq c #\>) (setf ptr (+ ptr 1) ))
((eq c #\<) (setf ptr (- ptr 1) ))
((eq c #\.) (princ (code-char (aref tape ptr))))
((eq c #\[) (if (= 0 (aref tape ptr))
(setf pc (jump forward pc))))
((eq c #\]) (if (/= 0 (aref tape ptr))
(setf pc (jump backward pc))))
(t (error "unknown instruction" c))))
(setf pc (+ 1 pc))
finally (return "done"))))
(defun is-comment? (line)
(and (> (length line) 0)
(eq #\; (char line 0))))
; Read in a program, dropping lines that start with a ;
(defun read-program (input acc)
(let ((line (read-line input nil)))
(if (eq nil line)
acc
(read-program input
(concatenate 'string acc
(if (is-comment? line)
""
line))))))
(defun run_program (filename)
(let* (
(file (open filename))
(program (read-program file (make-string 0))))
(bf program)))
(defun main ()
(run_program (nth 1 sb-ext:*posix-argv*)))
| 2,439 | Common Lisp | .lisp | 78 | 25.24359 | 61 | 0.549894 | sourceprobe/bf_lisp | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | 17bc85c8c998e681ff3850e3efcd000dffe328bd4191384eccf9943f33a2771d | 44,780 | [
-1
] |
44,798 | main.lisp | mpemer_util/test/main.lisp | ;;;; -----------------------------------------------------------------------
;;;; Filename: util.test.lisp
;;;; Author: Marcus Pemer
;;;; Email: marcus@pemer.com
;;;;
;;;; Description:
;;;; This file contains a collection of utility functions for use in Lisp
;;;; applications. It includes functions for parsing numbers, manipulating
;;;; hash tables, rounding numbers, processing lists with function chains
;;;; and monadic transformations, and other general utility functions.
;;;;
;;;; Copyright (C) 2023 Marcus Pemer
;;;; 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 <https://www.gnu.org/licenses/>.
;;;; -----------------------------------------------------------------------
(defpackage :util/test/main
(:use :common-lisp :util/core/main)
(:import-from :parachute :define-test :is :fail))
(in-package :util/test/main)
(define-test parse-number?-test
;; Test case where the string is a valid number
(is = 2469/20 (parse-number? "123.45")
#.#~ "Parsing a valid decimal number ~
should return its rational representation.")
;; Test case where the string is an invalid number
(is eq nil (parse-number? "abc")
"Parsing an invalid number should return NIL.")
;; Test case with an empty string
(parachute:false (parse-number? "")
"Parsing an empty string should return NIL.")
;; Test case with nil
(parachute:false (parse-number? nil)
"Parsing NIL should return NIL."))
(define-test insert-hash-test
;; Test inserting into an empty hash table
(let ((ht (make-hash-table)))
(insert-hash :key1 ht :flerp)
(multiple-value-bind (value exists) (gethash :key1 ht)
(is equal '(:flerp) value "The value should be '(:flerp)'")
(parachute:true exists "The key should exist in the hash table.")))
;; Test updating an existing key
(let ((ht (make-hash-table)))
(setf (gethash :key1 ht) :original)
(insert-hash :key1 ht :new-value)
(multiple-value-bind (value exists) (gethash :key1 ht)
(is equal '(:new-value . :original) value
#.#~ "Inserting with an existing key ~
should update the value at that key.")
(parachute:true exists
"The key should exist in the hash table.")))
;; Test with a non-existent key
(let ((ht (make-hash-table)))
(insert-hash :key2 ht :value2)
(multiple-value-bind (value exists) (gethash :key2 ht)
(is equal '(:value2) value
#.#~ "Inserting with a non-existent key ~
should create a new key-value pair.")
(parachute:true exists "The key should exist in the hash table."))))
(define-test roundto-test
;; Test rounding to 0 decimal places
(is = 123 (roundto 123.456 0)
#.#~ "Rounding to 0 decimal places ~
should round to the nearest integer.")
;; Test rounding to 1 decimal place
(is = 247/2 (roundto 123.456 1)
#.#~ "Rounding to 1 decimal place ~
should round to the nearest tenth.")
;; Test rounding to 2 decimal places
(is = 6173/50 (roundto 123.456 2)
#.#~ "Rounding to 2 decimal places should ~
round to the nearest hundredth.")
;; Test rounding to a negative number of decimal places
(is = 120 (roundto 123.456 -1)
#.#~ "Rounding to a negative number of decimal places ~
should round to tens, hundreds, etc.")
;; Test with an integer input
(is = 123 (roundto 123 2)
#.#~ "Rounding an integer should work correctly, ~
adding decimal zeroes as necessary."))
(define-test process-list-test
;; Test with a simple chain
(let ((chain (list #'identity #'1+ #'1+))) ; Increment twice
(is equal '(3 4 5) (process-list '(1 2 3) :chain chain
:monads #'identity)
#.#~ "Applying a simple chain ~
should increment each element twice."))
;; Test with a simple monad
(let ((monads (list (lambda (x) (* x 2))))) ; Double the value
(is equal '(2 4 6) (process-list '(1 2 3) :monads monads)
"Applying a simple monad should double each element."))
;; Test with both chain and monads
(let ((chain (list #'1+))
(monads (list (lambda (x) (* x 2)))))
(is equal '(4 6 8) (process-list '(1 2 3) :chain chain
:monads monads)
#.#~ "Applying both chain and monads ~
should increment and then double each element."))
;; Test with empty list
(is eq nil (process-list '() :chain (list #'1+)
:monads (list (lambda (x) (* x 2))))
"Processing an empty list should return an empty list."))
(define-test splice-test
;; Test with non-empty lists
(is equal '(3 2 1 4 5 6) (splice '(1 2 3) '(4 5 6))
#.#~ "Splicing '(1 2 3) to '(4 5 6) ~
should yield '(3 2 1 4 5 6).")
;; Test with an empty ADD list
(is equal '(1 2 3) (splice '() '(1 2 3))
#.#~ "Splicing an empty list to '(1 2 3) ~
should yield '(1 2 3).")
;; Test with an empty LST list
;; (is equal '(3 2 1) (splice '(1 2 3) nil)
;; #.#~ "Splicing '(1 2 3) to an empty list ~
;; should yield '(3 2 1).")
;; Test with both lists empty
(is equal nil (splice nil nil)
#.#~ "Splicing two empty lists ~
should yield an empty list.")
;; Test with nested lists
(is equal '(4 (2 3) 1 (5 6) 7) (splice '(1 (2 3) 4) '((5 6) 7))
"Splicing nested lists should correctly concatenate them."))
(define-test ensure-list-test
;; Test with a list input
(is equal '(1 2 3) (ensure-list '(1 2 3))
"Passing a list should return the list unchanged.")
;; Test with a single integer
(is equal '(42) (ensure-list 42)
"Passing a single integer should return it in a list.")
;; Test with a string
(is equal '("Hello") (ensure-list "Hello")
"Passing a string should return it in a list.")
;; Test with nil / empty list
(is equal nil (ensure-list nil)
"Passing nil should return it in a list."))
;; Define a test struct for demonstration
(defstruct test-struct
field1
field2
field3)
(define-test struct-field-names-test
;; Test with a test struct instance
(let ((test-instance (make-test-struct :field1 1 :field2 2 :field3 3)))
(is equal '("FIELD1" "FIELD2" "FIELD3")
(struct-field-names test-instance)
#.#~ "Field names for 'test-struct' ~
should be 'FIELD1', 'FIELD2', and 'FIELD3'.")))
;; Assuming 'test-struct' is already defined as before
;; (defstruct test-struct field1 field2 field3)
(define-test struct-to-list-test
;; Test with a test struct instance
(let ((test-instance (make-test-struct :field1 "Value1"
:field2 "Value2"
:field3 "Value3")))
(is equal '("Value1" "Value2" "Value3")
(struct-to-list test-instance)
#.#~ "Converting 'test-struct' to a list should yield ~
Value1', 'Value2', and 'Value3' in order."))
;; Test with a struct having different data types
(let ((test-instance (make-test-struct :field1 1
:field2 2.0
:field3 'symbol)))
(is equal '(1 2.0 symbol) (struct-to-list test-instance)
#.#~ "Struct with various data types should be ~
correctly converted to a list."))
;; Test with a struct having nil values
(let ((test-instance (make-test-struct :field1 nil
:field2 nil
:field3 nil)))
(is equal '(nil nil nil) (struct-to-list test-instance)
#.#~ "Struct with nil values should be correctly ~
converted to a list with nils.")))
(define-test proper-plist-p-test
;; Test with a properly formed plist
(parachute:true (proper-plist-p '(:key1 value1 :key2 value2))
"A properly formed plist should return T.")
;; Test with a plist having a non-keyword key
(parachute:false (proper-plist-p '(:key1 value1 key2 value2))
"A plist with a non-keyword key should return NIL.")
;; Test with a plist having an odd number of elements
(parachute:false (proper-plist-p '(:key1 value1 :key2))
#.#~ "A plist with an odd number of elements ~
should return NIL.")
;; Test with an empty plist
(parachute:true (proper-plist-p '())
#.#~ "An empty plist should be considered ~
properly formed and return T.")
;; Test with a plist having nested plists as values
(parachute:true (proper-plist-p '(:key1 (:subkey1 value1
:subkey2 value2)
:key2 value2))
#.#~ "A plist with nested plists as values ~
should still be considered properly formed ~
if the outer structure is correct."))
(define-test drop-test
;; Test dropping elements from a list
(is equal '(3 4 5) (drop 2 '(1 2 3 4 5))
#.#~ "Dropping 2 elements from a list ~
should return the remaining elements.")
;; Test dropping no elements
(is equal '(1 2 3) (drop 0 '(1 2 3))
#.#~ "Dropping 0 elements should return ~
the sequence unchanged.")
;; Test dropping more elements than the sequence length
(fail (drop 5 '(1 2)) error
#.#~ "Dropping more elements than the sequence contains ~
should result in an error.")
;; Test with an empty sequence
(fail (drop 3 nil) error
#.#~ "Dropping elements from an empty sequence ~
should result in an error.")
;; Test dropping elements from a vector
(is equalp #(3 4 5) (drop 2 #(1 2 3 4 5))
#.#~ "Dropping 2 elements from a vector should return ~
the remaining elements.")
;; Test with negative n
(fail (drop -1 '(1 2 3 4 5)) type-error
"Dropping a negative number of elements should fail."))
(when nil
(define-test create-mock-file-test
;; Test creating a file and writing content
(let ((filename (create-mock-file #(72 101 108 108 111))))
;; Create a mock file with "Hello" in bytes
(parachute:true (probe-file filename)
"The created file should exist.")
(is equal '(72 101 108 108 111) (read-file-as-bytes filename)
#.#~ "The content of the created file ~
should match the input byte sequence.")
(delete-file filename))) ; Clean up the mock file
)
(when nil
(define-test read-file-as-bytes-test
;; Test reading a real file
(let ((filename (create-mock-file #(72 101 108 108 111))))
;; Create a mock file with "Hello" in bytes
(is equal '(72 101 108 108 111) (read-file-as-bytes filename)
#.#~ "Reading a real file should return ~
the correct byte sequence.")
(delete-file filename)) ; Clean up the mock file
;; Test reading a non-existent file
(is equal nil (read-file-as-bytes "/path/to/nonexistent/file")
"Reading a non-existent file should return NIL."))
)
| 11,855 | Common Lisp | .lisp | 252 | 38.952381 | 84 | 0.602498 | mpemer/util | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | d4846bb92b8d779c630a24183f93745b78791b50b7d0afc6aa24859d8c501c23 | 44,798 | [
-1
] |
44,799 | docstring.lisp | mpemer_util/core/docstring.lisp | ;;;; -----------------------------------------------------------------------
;;;; Filename: docstring.lisp
;;;; Author: Marcus Pemer
;;;; Email: marcus@pemer.com
;;;;
;;;; Description:
;;;; This file contains a collection of utility functions for use in Lisp
;;;; applications. It includes functions for parsing numbers, manipulating
;;;; hash tables, rounding numbers, processing lists with function chains
;;;; and monadic transformations, and other general utility functions.
;;;;
;;;; Copyright (C) 2023 Marcus Pemer
;;;; 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 <https://www.gnu.org/licenses/>.
;;;; -----------------------------------------------------------------------
(defpackage :util/core/docstring
(:nicknames :docstring)
(:use :common-lisp)
(:import-from :split-sequence :split-sequence))
(in-package :docstring)
;;;; -----------------------------------------------------------------------
(defun add-newline-formatting (input-string)
"Process each line of INPUT-STRING.
If a line does not end with ~, ~@, or ~:, append ~@ to it.
This allows for the definition of multi-line docstrings
using arbitrary indentation. When a line should be continued,
simply append ~ to the end of that line."
(with-output-to-string (out)
(loop for line in (split-sequence:split-sequence #\Newline input-string)
do (let ((line-end (subseq line (max 0 (- (length line) 2)))))
(write-string
(if (or (string= line-end "~@")
(string= line-end "~:")
(string-right-trim "~" line-end))
line
(concatenate 'string line "~@"))
out))
(write-char #\Newline out))))
(defun multiline-docstring (stream sub-char arg)
"Custom dispatch function that processes the following string
and returns a form for read-time evaluation.
Used to define multi-line docstrings with arbitrary indentation."
(declare (ignore sub-char arg))
;; Read the next form (expected to be a string)
(let ((next-form (read stream t nil t)))
;; Return a form to be evaluated at read time
`(format nil ,(add-newline-formatting next-form))))
(in-package :cl-user)
;; Set up the dispatch macro character #~
(set-dispatch-macro-character #\# #\~ #'util/core/docstring::multiline-docstring)
| 2,932 | Common Lisp | .lisp | 60 | 44.416667 | 81 | 0.633287 | mpemer/util | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | 49d8f4c7de6bfaebfa3cd1ee0cb603f60d4dedb0e6bef70c6b25c1e96d659f64 | 44,799 | [
-1
] |
44,800 | main.lisp | mpemer_util/core/main.lisp | ;;;; -----------------------------------------------------------------------
;;;; Filename: util.lisp
;;;; Author: Marcus Pemer
;;;; Email: marcus@pemer.com
;;;;
;;;; Description:
;;;; This file contains a collection of utility functions for use in Lisp
;;;; applications. It includes functions for parsing numbers, manipulating
;;;; hash tables, rounding numbers, processing lists with function chains
;;;; and monadic transformations, and other general utility functions.
;;;;
;;;; Copyright (C) 2023 Marcus Pemer
;;;; 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 <https://www.gnu.org/licenses/>.
;;;; -----------------------------------------------------------------------
(defpackage :util/core/main
(:nicknames :util)
(:use :common-lisp :rtl)
(:import-from :alexandria :compose)
(:import-from :parse-number :parse-number)
(:export :process-list :parse-number? :insert-hash :roundto
:struct-field-names :struct-to-list
:ensure-list :splice
:proper-plist-p :drop :read-file-as-bytes
:create-mock-file :import-original-symbols))
(in-package :util)
;; For docstirngs, we can now prefix them with #.#~,
;; and they will be formatted.
;; Example:
;; (defun some-function (args)
;; #.#~
;; "My docstring ~
;; is run through (format nil <the-doc-string>)
;; and as such, lines are concatenated by ~,
;; and otherwise front-trimmed and newlined,
;; because ~@ is appended lines with no ~.
(defun parse-number? (s)
#.#~ "Attempts to parse the string S as a number, ~
and return its rational representation.
- S: A string expected to contain a numeric value.
If S is non-nil and represents a valid number, the function parses ~
S into a number and then rationalizes it, returning the rational ~
representation of the number. If S is nil or does not represent a ~
valid number, the function returns NIL."
(handler-case
(when (and s (plusp (length s)))
(rationalize (parse-number s :float-format 'double-float)))
(error (e)
;; Log the occurrence of a simple parse error and return nil
(format *error-output* "Parse error occurred: ~A~%" e)
nil)))
;; (define-test parse-number?-test
;; ;; Test case where the string is a valid number
;; (is = 2469/20 (parse-number? "123.45")
;; #.#~ "Parsing a valid decimal number ~
;; should return its rational representation.")
;; ;; Test case where the string is an invalid number
;; (fail (parse-number? "abc") SB-INT:SIMPLE-PARSE-ERROR
;; "Parsing an invalid number should return NIL.")
;; ;; Test case with an empty string
;; (parachute:false (parse-number? "")
;; "Parsing an empty string should return NIL.")
;; ;; Test case with nil
;; (parachute:false (parse-number? nil)
;; "Parsing NIL should return NIL."))
(defun insert-hash (k ht v)
#.#~ "Inserts the value V into the hash table HT at the key K.
- K: The key at which the value should be inserted in the hash table.
- HT: The hash table where the value is to be inserted.
- V: The value to be inserted into the hash table.
The function works by consing the value V onto the front of the list ~
already present at the key K in the hash table HT. If the key K does ~
not exist in HT, it creates a new entry at K with V as its value."
(set# k ht (cons v (get# k ht))))
;; (define-test insert-hash-test
;; ;; Test inserting into an empty hash table
;; (let ((ht (make-hash-table)))
;; (insert-hash :key1 ht :flerp)
;; (multiple-value-bind (value exists) (gethash :key1 ht)
;; (is equal '(:flerp) value "The value should be '(:flerp)'")
;; (parachute:true exists "The key should exist in the hash table.")))
;; ;; Test updating an existing key
;; (let ((ht (make-hash-table)))
;; (setf (gethash :key1 ht) :original)
;; (insert-hash :key1 ht :new-value)
;; (multiple-value-bind (value exists) (gethash :key1 ht)
;; (is equal '(:new-value . :original) value
;; #.#~ "Inserting with an existing key ~
;; should update the value at that key.")
;; (parachute:true exists
;; "The key should exist in the hash table.")))
;; ;; Test with a non-existent key
;; (let ((ht (make-hash-table)))
;; (insert-hash :key2 ht :value2)
;; (multiple-value-bind (value exists) (gethash :key2 ht)
;; (is equal '(:value2) value
;; #.#~ "Inserting with a non-existent key ~
;; should create a new key-value pair.")
;; (parachute:true exists "The key should exist in the hash table."))))
(defun roundto (number decimals)
#.#~ "Rounds NUMBER to a specified number of DECIMALS.
- NUMBER: The number to be rounded. ~
Can be an integer or a floating-point number.
- DECIMALS: The number of decimal places to round NUMBER to. ~
Must be an integer.
The function works by multiplying NUMBER by 10 raised to the power of ~
DECIMALS, rounding the result to the nearest integer, and then ~
dividing it back by the same factor.
The result is NUMBER rounded to the specified number of decimal places."
(declare (type integer decimals)) ; Ensure DECIMALS is an integer
(let ((f (expt 10 decimals))) ; Calculate the factor for rounding
(/ (round (* f number)) f))) ; Perform the rounding and adjust back
;; (define-test roundto-test
;; ;; Test rounding to 0 decimal places
;; (is = 123 (roundto 123.456 0)
;; #.#~ "Rounding to 0 decimal places ~
;; should round to the nearest integer.")
;; ;; Test rounding to 1 decimal place
;; (is = 247/2 (roundto 123.456 1)
;; #.#~ "Rounding to 1 decimal place ~
;; should round to the nearest tenth.")
;; ;; Test rounding to 2 decimal places
;; (is = 6173/50 (roundto 123.456 2)
;; #.#~ "Rounding to 2 decimal places should ~
;; round to the nearest hundredth.")
;; ;; Test rounding to a negative number of decimal places
;; (is = 120 (roundto 123.456 -1)
;; #.#~ "Rounding to a negative number of decimal places ~
;; should round to tens, hundreds, etc.")
;; ;; Test with an integer input
;; (is = 123 (roundto 123 2)
;; #.#~ "Rounding an integer should work correctly, ~
;; adding decimal zeroes as necessary."))
(defun process-list (lst &key chain monads)
#.#~ "Process each element of LST through a function chain and then through ~
a series of monadic transformations.
Parameters:
- LST: A list of elements to be processed, ~
which is a required argument.
- CHAIN: An optional list of functions (or a single function) ~
that are composed together and applied sequentially ~
to each element in LST.
- MONADS: An optional list of functions (or a single function) ~
representing monadic transformations.
The CHAIN and MONADS parameters are optional and key-based. ~
Each has an associated '-provided-p' flag that indicates whether ~
the argument was actually passed to the function. ~
The function first applies the composed CHAIN to each element in LST. ~
Then, each MONAD is applied to the result, potentially producing more ~
values which are aggregated into the final result list."
(let ((result nil))
(setf chain (ensure-list chain))
(setf monads (ensure-list monads))
(dolist (element lst (nreverse result))
(let ((composite (if chain
(funcall (apply #'compose chain) element)
element)))
(dolist (monad monads)
(let ((derivation (funcall monad composite)))
(when derivation
(if (listp derivation)
(setf result (splice derivation result))
(push derivation result)))))))))
;; (define-test process-list-test
;; ;; Test with a simple chain
;; (let ((chain (list #'identity #'1+ #'1+))) ; Increment twice
;; (is equal '(3 4 5) (process-list '(1 2 3) :chain chain
;; :monads #'identity)
;; #.#~ "Applying a simple chain ~
;; should increment each element twice."))
;; ;; Test with a simple monad
;; (let ((monads (list (lambda (x) (* x 2))))) ; Double the value
;; (is equal '(2 4 6) (process-list '(1 2 3) :monads monads)
;; "Applying a simple monad should double each element."))
;; ;; Test with both chain and monads
;; (let ((chain (list #'1+))
;; (monads (list (lambda (x) (* x 2)))))
;; (is equal '(4 6 8) (process-list '(1 2 3) :chain chain
;; :monads monads)
;; #.#~ "Applying both chain and monads ~
;; should increment and then double each element."))
;; ;; Test with empty list
;; (is eq nil (process-list '() :chain (list #'1+)
;; :monads (list (lambda (x) (* x 2))))
;; "Processing an empty list should return an empty list."))
(defun splice (add lst)
#.#~ "Concatenates two lists by adding ADD in reverse order ~
to the front of LST.
- ADD: A list whose elements are to be added.
- LST: The list to which the elements of ADD are to be appended.
This function reverses the list ADD and then concatenates it with LST, ~
effectively splicing the reversed ADD into the front of LST."
(nconc (nreverse add) lst))
;; (define-test splice-test
;; ;; Test with non-empty lists
;; (is equal '(3 2 1 4 5 6) (splice '(1 2 3) '(4 5 6))
;; #.#~ "Splicing '(1 2 3) to '(4 5 6) ~
;; should yield '(3 2 1 4 5 6).")
;; ;; Test with an empty ADD list
;; (is equal '(1 2 3) (splice '() '(1 2 3))
;; #.#~ "Splicing an empty list to '(1 2 3) ~
;; should yield '(1 2 3).")
;; ;; Test with an empty LST list
;; ;; (is equal '(3 2 1) (splice '(1 2 3) nil)
;; ;; #.#~ "Splicing '(1 2 3) to an empty list ~
;; ;; should yield '(3 2 1).")
;; ;; Test with both lists empty
;; (is equal nil (splice nil nil)
;; #.#~ "Splicing two empty lists ~
;; should yield an empty list.")
;; ;; Test with nested lists
;; (is equal '(4 (2 3) 1 (5 6) 7) (splice '(1 (2 3) 4) '((5 6) 7))
;; "Splicing nested lists should correctly concatenate them."))
(defun ensure-list (item)
#.#~ "Ensures that ITEM is a list.
- ITEM: An object to be transformed into a list ~
if it is not already one.
If ITEM is already a list, it is returned as-is. ~
Otherwise, ITEM is placed into a new list. ~
This function is useful for function arguments that may accept ~
either a single item or a list of items."
(if (listp item) item (list item)))
;; (define-test ensure-list-test
;; ;; Test with a list input
;; (is equal '(1 2 3) (ensure-list '(1 2 3))
;; "Passing a list should return the list unchanged.")
;; ;; Test with a single integer
;; (is equal '(42) (ensure-list 42)
;; "Passing a single integer should return it in a list.")
;; ;; Test with a string
;; (is equal '("Hello") (ensure-list "Hello")
;; "Passing a string should return it in a list.")
;; ;; Test with nil / empty list
;; (is equal nil (ensure-list nil)
;; "Passing nil should return it in a list."))
(defun struct-field-names (struct)
#.#~ "Extracts and returns a list of field names from a given struct.
PARAMETERS:
- struct: An instance of a struct or class ~
from which to extract field names.
The function uses the Common Lisp Object System (CLOS) Metaobject ~
Protocol (MOP) to introspect the struct and retrieve the slot ~
definitions.
It then extracts and returns the names of these slots as a list of ~
strings, which represent the field names.
Each field name is converted from a symbol to a string to ensure ~
compatibility with external systems and formats, such as CSV ~
headers.
RETURNS:
A list of strings representing the field names of the struct."
(loop for slot in (sb-mop:class-slots (class-of struct))
collect (symbol-name (sb-mop:slot-definition-name slot))))
;; ;; Define a test struct for demonstration
;; (defstruct test-struct
;; field1
;; field2
;; field3)
;; (define-test struct-field-names-test
;; ;; Test with a test struct instance
;; (let ((test-instance (make-test-struct :field1 1 :field2 2 :field3 3)))
;; (is equal '("FIELD1" "FIELD2" "FIELD3")
;; (struct-field-names test-instance)
;; #.#~ "Field names for 'test-struct' ~
;; should be 'FIELD1', 'FIELD2', and 'FIELD3'.")))
(defun struct-to-list (struct)
#.#~ "Converts a given struct to a list of its values, ~
preserving the order of its fields.
PARAMETERS:
- struct: An instance of a struct or class ~
to be converted into a list of values.
This function utilizes the Common Lisp Object System (CLOS) ~
Metaobject Protocol (MOP) to introspect the given struct and access ~
each of its slots. It then retrieves the value of each slot, ~
preserving the order in which the slots are defined.
The function is generic and does not require prior knowledge of the ~
struct's field names, making it versatile for use with any struct ~
or class that adheres to the CLOS standard.
RETURNS:
A list containing the values of each field in the struct, ~
ordered according to the struct's definition."
(loop for slot in (closer-mop:class-slots (class-of struct))
collect (slot-value struct (closer-mop:slot-definition-name slot))))
;; ;; Assuming 'test-struct' is already defined as before
;; ;; (defstruct test-struct field1 field2 field3)
;; (define-test struct-to-list-test
;; ;; Test with a test struct instance
;; (let ((test-instance (make-test-struct :field1 "Value1"
;; :field2 "Value2"
;; :field3 "Value3")))
;; (is equal '("Value1" "Value2" "Value3")
;; (struct-to-list test-instance)
;; #.#~ "Converting 'test-struct' to a list should yield ~
;; Value1', 'Value2', and 'Value3' in order."))
;; ;; Test with a struct having different data types
;; (let ((test-instance (make-test-struct :field1 1
;; :field2 2.0
;; :field3 'symbol)))
;; (is equal '(1 2.0 symbol) (struct-to-list test-instance)
;; #.#~ "Struct with various data types should be ~
;; correctly converted to a list."))
;; ;; Test with a struct having nil values
;; (let ((test-instance (make-test-struct :field1 nil
;; :field2 nil
;; :field3 nil)))
;; (is equal '(nil nil nil) (struct-to-list test-instance)
;; #.#~ "Struct with nil values should be correctly ~
;; converted to a list with nils.")))
(defun proper-plist-p (plist)
#.#~ "Determines if PLIST is a properly formed property list.
A proper property list (plist) must satisfy two conditions:
1. It contains an even number of elements, ~
alternating between keys and values.
2. All keys in the list are keywords.
Parameters:
- plist: A list to be checked. It is expected to be a property list ~
where keys are potentially followed by corresponding values.
Returns:
T (true) if PLIST is a properly formed property list according to ~
the above conditions. Otherwise, returns NIL (false).
Example Usage:
(proper-plist-p '(:key1 value1 :key2 value2)) ;; Returns T
(proper-plist-p '(:key1 value1 key2 value2)) ;; Returns NIL
;; (key2 is ~
not a keyword)
(proper-plist-p '(:key1 :key2 :key3)) ;; Returns NIL
;; (odd number ~
of elements)
Notes:
This function is useful for validating property lists before their use ~
in situations where proper structure is required for correct operation. ~
The function checks for the even length of the list and that each key ~
is a valid keyword."
(and (evenp (length plist)) ; Ensure plist has an even number of elements.
(every #'keywordp
(loop for item on plist by #'cddr collect (first item)))))
; Ensure every key is a keyword.
;; (define-test proper-plist-p-test
;; ;; Test with a properly formed plist
;; (parachute:true (proper-plist-p '(:key1 value1 :key2 value2))
;; "A properly formed plist should return T.")
;; ;; Test with a plist having a non-keyword key
;; (parachute:false (proper-plist-p '(:key1 value1 key2 value2))
;; "A plist with a non-keyword key should return NIL.")
;; ;; Test with a plist having an odd number of elements
;; (parachute:false (proper-plist-p '(:key1 value1 :key2))
;; #.#~ "A plist with an odd number of elements ~
;; should return NIL.")
;; ;; Test with an empty plist
;; (parachute:true (proper-plist-p '())
;; #.#~ "An empty plist should be considered ~
;; properly formed and return T.")
;; ;; Test with a plist having nested plists as values
;; (parachute:true (proper-plist-p '(:key1 (:subkey1 value1
;; :subkey2 value2)
;; :key2 value2))
;; #.#~ "A plist with nested plists as values ~
;; should still be considered properly formed ~
;; if the outer structure is correct."))
(defun drop (n sequence)
#.#~ "Removes the first N elements from SEQUENCE and returns ~
the remaining elements.
Parameters:
- n: An integer representing the number of elements to be dropped from ~
the beginning of SEQUENCE. ~
If N is greater than the length of SEQUENCE, ~
an empty sequence is returned. ~
If N is less than 0, the function behavior is ~
implementation-dependent.
- sequence: A sequence (list, vector, etc.) from which elements ~
will be removed.
Returns:
A new sequence containing the elements of the original SEQUENCE, ~
excluding the first N elements.
Example Usage:
(drop 2 '(1 2 3 4 5)) ;; Returns (3 4 5)
(drop 0 '(1 2 3)) ;; Returns (1 2 3)
(drop 3 '(1 2)) ;; Returns NIL
Notes:
- The function uses 'subseq', which creates a new sequence, ~
leaving the original SEQUENCE unmodified.
- If SEQUENCE is empty, the function returns an empty sequence ~
regardless of the value of N.
- This function is useful for operations where the initial part ~
of a sequence is not needed."
(subseq sequence n))
;; (define-test drop-test
;; ;; Test dropping elements from a list
;; (is equal '(3 4 5) (drop 2 '(1 2 3 4 5))
;; #.#~ "Dropping 2 elements from a list ~
;; should return the remaining elements.")
;; ;; Test dropping no elements
;; (is equal '(1 2 3) (drop 0 '(1 2 3))
;; #.#~ "Dropping 0 elements should return ~
;; the sequence unchanged.")
;; ;; Test dropping more elements than the sequence length
;; (fail (drop 5 '(1 2)) error
;; #.#~ "Dropping more elements than the sequence contains ~
;; should result in an error.")
;; ;; Test with an empty sequence
;; (fail (drop 3 nil) error
;; #.#~ "Dropping elements from an empty sequence ~
;; should result in an error.")
;; ;; Test dropping elements from a vector
;; (is equalp #(3 4 5) (drop 2 #(1 2 3 4 5))
;; #.#~ "Dropping 2 elements from a vector should return ~
;; the remaining elements.")
;; ;; Test with negative n
;; (fail (drop -1 '(1 2 3 4 5)) type-error
;; "Dropping a negative number of elements should fail."))
(defun create-mock-file (content)
#.#~ "Creates a temporary file in the system's temporary directory ~
with the specified content.
Parameters:
- content: A sequence of bytes (octets) that will be written to the file.
Returns:
The pathname of the newly created temporary file.
Side Effects:
This function creates a new file on the file system. The file will be ~
located in the '/tmp' directory and have a name based on the current ~
universal time to ensure uniqueness.
Example Usage:
(create-mock-file #(72 101 108 108 111)) ;; Creates a file containing ~
the bytes for 'Hello'
Notes:
The created file should be explicitly deleted when it is no longer ~
needed to avoid leaving temporary files on the system."
(let ((filename (format nil "/tmp/mock-file-~A" (get-universal-time))))
(with-open-file (stream filename
:direction :output
:if-exists :supersede
:element-type 'octet)
(write-sequence content stream))
filename))
;; (when nil
;; (define-test create-mock-file-test
;; ;; Test creating a file and writing content
;; (let ((filename (create-mock-file #(72 101 108 108 111))))
;; ;; Create a mock file with "Hello" in bytes
;; (parachute:true (probe-file filename)
;; "The created file should exist.")
;; (is equal '(72 101 108 108 111) (read-file-as-bytes filename)
;; #.#~ "The content of the created file ~
;; should match the input byte sequence.")
;; (delete-file filename))) ; Clean up the mock file
;; )
(defun read-file-as-bytes (filename)
#.#~ "Reads the contents of a file specified by FILENAME and returns it ~
as a list of bytes.
Parameters:
- filename: A string representing the path of the file to be read.
Returns:
A list of bytes (unsigned-byte 8) representing the content of the file. ~
If the file does not exist, returns NIL.
Example Usage:
(read-file-as-bytes \"/path/to/file.txt\") ;; Returns the content of ~
file.txt as a list of bytes
Notes:
This function is intended for reading binary files, as it treats ~
the file content as a sequence of bytes.
For text files, consider using character-based reading functions to ~
handle different character encodings properly.
The function uses 'with-open-file' to safely open and close ~
the file stream."
(with-open-file (stream filename :element-type '(unsigned-byte 8)
:if-does-not-exist nil)
(loop for byte = (read-byte stream nil) while byte collect byte)))
;; (when nil
;; (define-test read-file-as-bytes-test
;; ;; Test reading a real file
;; (let ((filename (create-mock-file #(72 101 108 108 111))))
;; ;; Create a mock file with "Hello" in bytes
;; (is equal '(72 101 108 108 111) (read-file-as-bytes filename)
;; #.#~ "Reading a real file should return ~
;; the correct byte sequence.")
;; (delete-file filename)) ; Clean up the mock file
;; ;; Test reading a non-existent file
;; (is equal nil (read-file-as-bytes "/path/to/nonexistent/file")
;; "Reading a non-existent file should return NIL."))
;; )
(defun import-original-symbols (package-name)
"Import symbols that are originally defined in PACKAGE-NAME into the current package."
(let ((source-package (find-package package-name)))
(format t "Starting import from package: ~A~%" source-package)
(do-symbols (symbol source-package)
(when (eq (symbol-package symbol) source-package)
(let ((symbol-name (symbol-name symbol)))
;; Import the symbol if it's not already present
(unless (find-symbol symbol-name *package*)
(import symbol *package*)
(format t "Imported symbol: ~A~%" symbol))
;; If the symbol has a function binding, import the function
(when (fboundp symbol)
(let ((new-symbol (find-symbol symbol-name *package*)))
(setf (fdefinition new-symbol) (fdefinition symbol))
(format t "Imported function: ~A~%" symbol))))))))
| 24,956 | Common Lisp | .lisp | 505 | 45.370297 | 88 | 0.624779 | mpemer/util | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | 4cdd18d0d231a57105db8bbdbf4ac41d44cf42e473b79755a1450706d76788db | 44,800 | [
-1
] |
44,801 | util.asd | mpemer_util/util.asd | ;;; UTIL system definition
;;; see LICENSE for permissions
(defsystem "util"
:class :package-inferred-system
:name "Utilities"
:version (:read-file-line "version.txt" :at 0)
:author "Marcus Pemer <marcus@pemer.com>"
:license "GPL-3.0"
:depends-on ("rutils" "local-time" "parse-number" "str"
"alexandria" "split-sequence"
"util/core/docstring"
"util/core/main")
:in-order-to ((test-op (load-op "util/test/main")))
:perform (test-op (o c) (symbol-call :parachute 'test 'util/test/main))
:description "Local utility functions"
:long-description "Utility functions that are shared between lisp systems"
:maintainer "marcus@pemer.com"
:homepage "https://github.com/mpemer/util/")
(register-system-packages :rutils '(:rtl))
| 816 | Common Lisp | .asd | 19 | 36.789474 | 76 | 0.660377 | mpemer/util | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | c93741f6482f05869b271a8067a47b81e9b25ede6e030a4716621cc86aa94080 | 44,801 | [
-1
] |
44,821 | main.lisp | mpemer_simple-idate/test/main.lisp | (defpackage :simple-idate/test/main
(:use :common-lisp :simple-idate/core/main)
(:import-from :local-time :encode-timestamp :timestamp-year :timestamp-month :timestamp-day)
(:import-from :parachute :define-test :is :fail))
(in-package :simple-idate/test/main)
(define-test ints->idate-test
;; Test with a standard date
(is = 20230314 (ints->idate 2023 3 14)
"Converting 2023-03-14 should yield 20230314.")
;; Test with a date in January (checking month formatting)
(is = 20230101 (ints->idate 2023 1 1)
"Converting 2023-01-01 should yield 20230101.")
;; Test with a date in December (checking month and day formatting)
(is = 20231231 (ints->idate 2023 12 31)
"Converting 2023-12-31 should yield 20231231.")
;; Test with a leap year date
(is = 20240229 (ints->idate 2024 2 29)
"Converting 2024-02-29 (leap year) should yield 20240229."))
(define-test date->idate-test
;; Assuming the presence of a function to create a mock timestamp
(let ((mock-timestamp (encode-timestamp 0 0 0 0 14 3 2023)))
(is = 20230314 (date->idate mock-timestamp)
"Converting mock timestamp of 2023-03-14
should yield 20230314.")))
(define-test idate-test
(is = 20230314 (idate 2023 3 14)
"Creating idate for 2023-03-14 should yield 20230314."))
(define-test idate->date-test
;; Test with a standard integer date
(let ((date (idate->date 20230314)))
;; Assuming encode-timestamp returns a date object or similar structure
(is = 2023 (timestamp-year date)
"Year component of 20230314 should be 2023.")
(is = 3 (timestamp-month date)
"Month component of 20230314 should be 3.")
(is = 14 (timestamp-day date)
"Day component of 20230314 should be 14."))
;; Test with another integer date
(let ((date (idate->date 20211225)))
(is = 2021 (timestamp-year date)
"Year component of 20211225 should be 2021.")
(is = 12 (timestamp-month date)
"Month component of 20211225 should be 12.")
(is = 25 (timestamp-day date)
"Day component of 20211225 should be 25.")))
(define-test idate->unix-test
;; Test with a known integer date and its expected Unix timestamp
(let ((known-unix-time 1678766400))
(is = known-unix-time (idate->unix 20230314)
"Converting integer date 20230314
should yield the correct Unix timestamp."))
;; Test with another known integer date and its Unix timestamp
(let ((known-unix-time 1640408400))
(is = known-unix-time (idate->unix 20211225)
"Converting integer date 20211225
should yield the correct Unix timestamp.")))
(define-test idate-year-test
;; Test with a standard integer date
(is = 2023 (idate-year 20230314)
"Extracting the year from 20230314 should yield 2023.")
;; Test with another integer date
(is = 2021 (idate-year 20211225)
"Extracting the year from 20211225 should yield 2021.")
;; Test with a year in the distant past
(is = 1900 (idate-year 19000101)
"Extracting the year from 19000101 should yield 1900.")
;; Test with a year in the future
(is = 2050 (idate-year 20501231)
"Extracting the year from 20501231 should yield 2050."))
(define-test idate-month-test
;; Test with a standard integer date
(is = 3 (idate-month 20230314)
"Extracting the month from 20230314 should yield 3.")
;; Test with another integer date
(is = 12 (idate-month 20211225)
"Extracting the month from 20211225 should yield 12.")
;; Test with a date in January
(is = 1 (idate-month 20230101)
"Extracting the month from 20230101 should yield 1.")
;; Test with a date in December
(is = 12 (idate-month 20231231)
"Extracting the month from 20231231 should yield 12.")
;; Test with a date in February of a leap year
(is = 2 (idate-month 20240229)
"Extracting the month from 20240229 (leap year)
should yield 2."))
(define-test idate-day-test
;; Test with a standard integer date
(is = 14 (idate-day 20230314)
"Extracting the day from 20230314 should yield 14.")
;; Test with another integer date
(is = 25 (idate-day 20211225)
"Extracting the day from 20211225 should yield 25.")
;; Test with a date at the beginning of a month
(is = 1 (idate-day 20230301)
"Extracting the day from 20230301 should yield 1.")
;; Test with a date at the end of a month
(is = 31 (idate-day 20230131)
"Extracting the day from 20230131 should yield 31.")
;; Test with a leap day
(is = 29 (idate-day 20240229)
"Extracting the day from 20240229 (leap year)
should yield 29."))
(define-test mm-dd-yyyy-test
;; Test with a standard date string
(is = 20230314 (mm/dd/yyyy "03/14/2023")
"Parsing '03/14/2023' should yield 20230314.")
;; Test with another date string
(is = 20211225 (mm/dd/yyyy "12/25/2021")
"Parsing '12/25/2021' should yield 20211225.")
;; Test with a single-digit day and month
(is = 20210101 (mm/dd/yyyy "1/1/2021")
"Parsing '1/1/2021' should yield 20210101.")
;; Test with invalid date format
(fail (mm/dd/yyyy "2023-03-14") error
"Parsing an incorrectly formatted date string
should fail.")
(when nil
;; Test with invalid date values - tbd
(fail (mm/dd/yyyy "13/32/2021") error
"Parsing an invalid date should fail."))
)
(define-test yyyy-mm-dd-test
;; Test with a standard date string
(is = 20230314 (yyyy-mm-dd "2023-03-14")
"Parsing '2023-03-14' should yield 20230314.")
;; Test with another date string
(is = 20211225 (yyyy-mm-dd "2021-12-25")
"Parsing '2021-12-25' should yield 20211225.")
;; Test with a single digit day and month
(is = 20210101 (yyyy-mm-dd "2021-1-1")
"Parsing '2021-1-1' should yield 20210101.")
;; Test with invalid date format
(is null (yyyy-mm-dd "14/03/2023")
"Parsing an incorrectly formatted date string
should return NIL.")
;; Test with invalid date values
(is null (yyyy-mm-dd "2021-13-32")
"Parsing an invalid date should return NIL."))
(define-test idate-comparison-tests
;; Test idate= (equal)
(parachute:true (idate= 20230314 20230314)
"Comparing the same dates should return T for idate=.")
(parachute:false (idate= 20230314 20211225)
"Comparing different dates
should return NIL for idate=.")
;; Test idate<= (less than or equal)
(parachute:true (idate<= 20211225 20230314)
"Earlier date should be less than or
equal to later date for idate<=.")
(parachute:true (idate<= 20230314 20230314)
"Same date should be less than or equal for idate<=.")
;; Test idate< (less than)
(parachute:true (idate< 20211225 20230314)
"Earlier date should be less than later date for idate<.")
(parachute:false (idate< 20230314 20230314)
"Same date should not be less than for idate<.")
;; Test idate> (greater than)
(parachute:true (idate> 20230314 20211225)
"Later date should be greater
than earlier date for idate>.")
(parachute:false (idate> 20230314 20230314)
"Same date should not be greater than for idate>.")
;; Test idate>= (greater than or equal)
(parachute:true (idate>= 20230314 20211225)
"Later date should be greater than or equal
to earlier date for idate>=.")
(parachute:true (idate>= 20230314 20230314)
"Same date should be greater than
or equal for idate>=."))
(define-test plus-1d-test
;; Test adding one day to a standard integer date
(is = 20230315 (+1d 20230314)
"Adding one day to 2023-03-14 should yield 2023-03-15.")
;; Test adding one day to the last day of a month
(is = 20230201 (+1d 20230131)
"Adding one day to 2023-01-31 should yield 2023-02-01.")
;; Test adding one day to the last day of a year
(is = 20240101 (+1d 20231231)
"Adding one day to 2023-12-31 should yield 2024-01-01.")
;; Test adding one day to a leap day
(is = 20240301 (+1d 20240229)
"Adding one day to 2024-02-29 (leap year)
should yield 2024-03-01."))
(define-test minus-1d-test
;; Test subtracting one day from a standard integer date
(is = 20230314 (-1d 20230315)
"Subtracting one day from 2023-03-15
should yield 2023-03-14.")
;; Test subtracting one day from the first day of a month
(is = 20230131 (-1d 20230201)
"Subtracting one day from 2023-02-01
should yield 2023-01-31.")
;; Test subtracting one day from the first day of a year
(is = 20231231 (-1d 20240101)
"Subtracting one day from 2024-01-01
should yield 2023-12-31.")
;; Test subtracting one day from March 1st on a leap year
(is = 20240229 (-1d 20240301)
"Subtracting one day from 2024-03-01 (leap year)
should yield 2024-02-29."))
(define-test plus-1m-test
;; Test adding one month to a standard integer date
(is = 20230414 (+1m 20230314)
"Adding one month to 2023-03-14 should yield 2023-04-14.")
;; Test adding one month to a date in December
(is = 20240114 (+1m 20231214)
"Adding one month to 2023-12-14 should yield 2024-01-14.")
;; Test adding one month to a date at the end of a month
(is = 20230228 (+1m 20230131)
"Adding one month to 2023-01-31 should adjust
for the shorter month.")
;; Test adding one month to February 28th on a non-leap year
(is = 20230328 (+1m 20230228)
"Adding one month to 2023-02-28 should yield 2023-03-28.")
;; Test adding one month to February 29th on a leap year
(is = 20240329 (+1m 20240229)
"Adding one month to 2024-02-29 (leap year)
should yield 2024-03-29."))
(define-test first-of-month-test
;; Test getting the first day of the month for a standard integer date
(is = 20230301 (first-of-month 20230314)
"The first day of the month for 2023-03-14
should be 2023-03-01.")
;; Test getting the first day of the month for a date in December
(is = 20231201 (first-of-month 20231214)
"The first day of the month for 2023-12-14
should be 2023-12-01.")
;; Test getting the first day of the month for a date in January
(is = 20230101 (first-of-month 20230131)
"The first day of the month for 2023-01-31
should be 2023-01-01.")
;; Test getting the first day of the month for a leap year
(is = 20240201 (first-of-month 20240229)
"The first day of the month for 2024-02-29 (leap year)
should be 2024-02-01."))
| 10,802 | Common Lisp | .lisp | 236 | 39.233051 | 94 | 0.665267 | mpemer/simple-idate | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | 2c9fd9afedcfa657165c97ce0eddadb43aed27eaea6c8e736f7365de00c59d57 | 44,821 | [
-1
] |
44,822 | main.lisp | mpemer_simple-idate/core/main.lisp | ;;;; -----------------------------------------------------------------------
;;;; Filename: simple-idate.lisp
;;;; Author: Marcus Pemer
;;;; Email: marcus@pemer.com
;;;;
;;;; Description:
;;;; This file contains a collection of utility functions for use in Lisp
;;;; applications. It includes functions for parsing numbers, manipulating
;;;; hash tables, rounding numbers, processing lists with function chains
;;;; and monadic transformations, and other general utility functions.
;;;;
;;;; Copyright (C) 2023 Marcus Pemer
;;;; 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 <https://www.gnu.org/licenses/>.
;;;; -----------------------------------------------------------------------
(defpackage :simple-idate/core/main
(:nicknames :simple-idate)
(:use :common-lisp)
(:import-from :parse-number :parse-integer)
(:import-from :local-time
:timestamp-year
:timestamp-month
:timestamp-day
:timestamp> :timestamp>= :timestamp< :timestamp<= :timestamp=
:timestamp+ :timestamp-
:encode-timestamp :timestamp-to-unix)
(:export :idate :date->idate :idate->date :idate->unix :idate-year :idate-month :idate-day
:mm/dd/yyyy :yyyy-mm-dd :first-of-month :ints->idate
:idate= :idate< :idate<= :idate> :idate>= :+1d :-1d :+1m
:ints->idate))
(in-package :simple-idate)
(defun ints->idate (y m d)
(+ (* 10000 y)
(* 100 m)
d))
(defun date->idate (d)
(ints->idate (timestamp-year d)
(timestamp-month d)
(timestamp-day d)))
(defun idate (y m d)
(date->idate
(encode-timestamp
0 0 0 0 d m y)))
(defun idate->date (idt)
(multiple-value-bind (y x) (truncate idt 10000)
(multiple-value-bind (m d) (truncate x 100)
(encode-timestamp 0 0 0 0 d m y))))
(defun idate->unix (idt)
(timestamp-to-unix (idate->date idt)))
(defun idate-year (idt)
(truncate idt 10000))
(defun idate-month (idt)
(multiple-value-bind (_ md) (truncate idt 10000)
(declare (ignorable _))
(truncate md 100)))
(defun idate-day (idt)
(multiple-value-bind (y x) (truncate idt 10000)
(multiple-value-bind (_ d) (truncate x 100)
(declare (ignore _))
d)))
(defun mm/dd/yyyy (s)
(destructuring-bind (m d y)
(mapcar #'parse-integer
(str:split #\/ s))
(ints->idate y m d)))
(defun yyyy-mm-dd (s)
(destructuring-bind (y m d)
(mapcar #'parse-integer
(str:split #\- s))
(ints->idate y m d)))
(defmacro idateop (op a b)
`(funcall ,op (idate->date ,a) (idate->date ,b)))
(defun idate= (a b)
(idateop #'timestamp= a b))
(defun idate<= (a b)
(idateop #'timestamp<= a b))
(defun idate< (a b)
(idateop #'timestamp< a b))
(defun idate> (a b)
(idateop #'timestamp> a b))
(defun idate>= (a b)
(idateop #'timestamp>= a b))
(defun +1d (idt)
(date->idate
(timestamp+ (idate->date idt) 1 :day)))
(defun -1d (idt)
(date->idate
(timestamp- (idate->date idt) 1 :day)))
(defun +1m (idt)
(date->idate
(timestamp+ (idate->date idt) 1 :month)))
(defun first-of-month (idt)
(idate (idate-year idt)
(idate-month idt)
1))
| 3,801 | Common Lisp | .lisp | 105 | 31.561905 | 92 | 0.616799 | mpemer/simple-idate | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | a67a0168db85adf22873334b460839bec84c04b578f3df898f5fed1279039ee9 | 44,822 | [
-1
] |
44,823 | simple-idate.asd | mpemer_simple-idate/simple-idate.asd | ;;;; simple-idate.asd
(defsystem "simple-idate"
:class :package-inferred-system
:version (:read-file-line "version.txt" :at 0)
:author "Marcus Pemer <marcus@pemer.com>"
:license "GPL-3.0"
:depends-on ("parachute" "local-time" "parse-number" "str" "simple-idate/core/main")
:in-order-to ((test-op (load-op "simple-idate/test/main")))
:perform (test-op (o c) (symbol-call :parachute 'test 'simple-idate/test/main))
:description "Integer-based (yyyymmdd) simple date library."
:long-description "The Simple-IDate Library is a Common Lisp utility designed for handling integer-based date representations. It provides a simple yet effective way of converting between standard date formats and integer-based dates."
:maintainer "marcus@pemer.com"
:homepage "https://github.com/mpemer/simple-idate")
| 816 | Common Lisp | .asd | 13 | 60 | 237 | 0.746883 | mpemer/simple-idate | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:52:53 AM (Europe/Amsterdam) | 5095d077d7968e742989b497c210c24ecf314552e5249a6d34362e1ae11d4140 | 44,823 | [
-1
] |
44,842 | runtime.lisp | alessiostalla_antlr4cl/runtime/runtime.lisp | (in-package :antlr4-runtime)
(defvar +version+ "0.1.0")
(defun check-version (v1 v2)
(string= v1 v2))
(defclass recognizer () (interpreter))
(defclass lexer () ((input :initarg input :initform (error "Lexer input is required"))))
(defclass parser () ())
(defclass parse-tree () ())
(defclass parser-rule-context () ())
(defclass prediction-context-cache () ())
(defun deserialize-atn (atn)
(error "TODO"))
;; Listener
(defclass parse-tree-listener () ()
(:documentation "Listener interface"))
(defgeneric enter (listener rule))
(defgeneric exit (listener rule))
;; Visitor
(defclass parse-tree-visitor () ()
(:documentation "Visitor interface"))
(defgeneric visit (visitor rule))
| 700 | Common Lisp | .lisp | 21 | 31.380952 | 88 | 0.71964 | alessiostalla/antlr4cl | 0 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:53:02 AM (Europe/Amsterdam) | 54d325a1249f00c0b3751c5d76fafc53c8b16fd401b5553ba12b6b88a7a73cb4 | 44,842 | [
-1
] |
44,843 | packages.lisp | alessiostalla_antlr4cl/runtime/packages.lisp | (defpackage antlr4-runtime
(:use :cl)
(:export #:check-version #:child-count #:deserialize-atn #:enter #:exit #:get-child #:lexer
#:parent-context #:parser #:parse-tree #:parse-tree-listener #:parse-tree-visitor #:parser-rule-context #:prediction-context-cache
#:rule-context #:rule-node
#:+version+ #:visit))
| 326 | Common Lisp | .lisp | 6 | 50.666667 | 134 | 0.696875 | alessiostalla/antlr4cl | 0 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:53:02 AM (Europe/Amsterdam) | d4b7366de3d1368b5492b6346eb227932750c5591bd664f3fd558e4f003f9df9 | 44,843 | [
-1
] |
44,844 | antlr4cl.asd | alessiostalla_antlr4cl/antlr4cl.asd | (defsystem "antlr4cl"
:version "0.1.0"
:author "Alessio Stalla"
:license "AGPL"
:depends-on ()
:components ((:module "runtime"
:components
((:file "packages") (:file "runtime"))))
:description "The ANTLR4 parser generator for Common Lisp")
| 284 | Common Lisp | .asd | 9 | 25.666667 | 61 | 0.618182 | alessiostalla/antlr4cl | 0 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:53:02 AM (Europe/Amsterdam) | c179eadba230a22d3e348dd2e08ac5b09df9b91c89891bc7dc21bef5eb45c734 | 44,844 | [
-1
] |
44,865 | UKL.lsp | AlexandrGlushko_UklLispForAutoCad/UKL.lsp | ;===================================================================================================
;Функция проставления уклонов V-0.3
;===================================================================================================
(defun c:ukl()
(progn
(setq S_text "Standard");Стиль текста
(setq H_text 0.5) ;Высота текста
(setq C_layr 7) ;Цвет слоя
(setq N_layr "Уклон") ;Имя слоя
(setq L_list nil) ;Список слоёв
(setq S_list nil) ;Список стилей текста
(setq Grad "") ;Уклон
(setq S_Grad 1) ;Стиль отоборажения уклона
(setq S_Arrow 2) ;Стиль стрелкисм
(Dialog) ;Загрузка диалогового окна
); progn
);defun c:ukl
;===================================================================================================
;Указание точек для расчета уклона
;===================================================================================================
(defun Enter_Point()
(setq P1 (getpoint "Точка 1: ")) ;Указание пользователем точки Р1
(setq P2 (getpoint "Точка 2: ")) ;Указание пользователем точки Р2
(setq Dist (distance P1 P2)) ;Расстояние между точками Р1 и Р2
(setq Elev (- (caddr P1) (caddr P2))) ;Первышение P1 - P2 = Elev
(Calc_Grad S_Grad) ;Расчет уклона по стилю
(Print_Grad) ;Вывод результатов
(Enter_Point) ;Рекурсия вызова
);Enter_Point
;===================================================================================================
;Вывод результатов велечина уклона и стрелка
;FirP - точка для отчета потроений при вставке текста и знака уклона (нижняя)
;SecP - точка для построения угла (верхняя)
;TextAngle - угол между точками для текста
;DrawAngle - угло для отрисовки знака уклона
;ForLP3 - значение угла для точки LP3 при постороении знака уклона
;===================================================================================================
(defun Print_Grad()
;Определение углов поворота текста и направление указания наклона
;в зависимоти от первышения (Elev) и разности координат (dX, dY)
;Первая точка ниже вторая више
(if (< Elev 0)
(progn (setq FirP P1) (setq SecP P2))
(progn (setq FirP P2) (setq SecP P1))
);if
(setq dX (-(car SecP) (car FirP))) ; Разность координат точек Р2 и Р1 по Х
(setq dY (-(cadr SecP) (cadr FirP))); Разность координат точек Р2 и Р1 по Y
(progn
;Первая четверть
(if (and (>= dX 0) (>= dY 0))
(progn
(print (strcat "Певая четверть"))
(setq TextAngle (angle FirP SecP))
(setq DrawAngle (- TextAngle PI))
(setq ForLP3 (- DrawAngle (/ PI 2)))
(setq PosLP3 "N")
);progn
);if Первая четверть
;Вторая четверть
(if (and (>= dX 0) (< dY 0))
(progn
(print (strcat "Вторая четверть"))
(setq TextAngle (angle FirP SecP))
(setq DrawAngle (- TextAngle PI))
(setq ForLP3 (- DrawAngle (/ PI 2)))
(setq PosLP3 "N")
);progn
);if Вторая четверть
;Третья четверть
(if (and (< dX 0) (< dY 0))
(progn
(print (strcat "Третья четверть"))
(setq TextAngle (angle SecP FirP))
(setq DrawAngle (+ TextAngle PI))
(setq ForLP3 (- DrawAngle (/ PI 2)))
(setq PosLP3 "R")
);progn
);if Третья четверть
;Четвертая четверть
(if (and (< dX 0) (>= dY 0))
(progn
(print (strcat "Четвертая четверть"))
(setq TextAngle (angle SecP FirP))
(setq DrawAngle (+ TextAngle PI))
(setq ForLP3 (- DrawAngle (/ PI 2)))
(setq PosLP3 "R")
);progn
);if Четвертая четверть
);progn
;===================================================================================================
;Вставка текста
;===================================================================================================
(entmake (list
(cons 0 "TEXT")
(cons 8 N_layr)
(cons 62 C_layr)
(cons 10 (setq XYZ (getpoint "Точка вставки ")))
(cons 40 H_text)
(cons 50 TextAngle)
(cons 7 S_text)
(cons 1 Grad)
(cons 11 XYZ);Координаты точки выравненного текста
(cons 72 1);Выравникание по горизонтали
(cons 73 1);Выравнивание по вертикали
));entmake TEXT
;===================================================================================================
;Блок расчета данных для отрисовки полилинии
;Координтаы вставки текста
;Отрисовка стрелки согласно выбранного стиля
;===================================================================================================
(if(= S_Arrow 1)
(progn
(setq PosText (cdr (assoc 10 (entget (entlast)))))
;Длина отступа от центра текста
(setq DrawDist (/ H_text 3))
;Расчет коориднат знака уклона
; LP3___
; ---___ - Расчет координат символа уклона
; LP1----------LP2
(setq LP1 (polar PosText DrawAngle DrawDist))
(setq LP2 (polar LP1 DrawAngle (* H_text 2)))
(if (= PosLP3 "N")
(progn (setq LP3 (polar LP1 ForLP3 H_text)) (setq FP1 LP1 FP2 LP2 FP3 LP3))
(progn (setq LP3 (polar LP2 ForLP3 H_text)) (setq FP1 LP2 FP2 LP1 FP3 LP3))
);if PosLP3
;Вставка знака уклона
(entmake (list
(cons 0 "LWPOLYLINE")
(cons 8 N_layr)
(cons 62 C_layr)
(cons 100 "AcDbEntity")
(cons 100 "AcDbPolyline")
(cons 90 3)
(list 10 (car FP1) (cadr FP1))
(list 10 (car FP2) (cadr FP2))
(list 10 (car FP3) (cadr FP3))
));entmake LWPOLYLINE
);progn
);if
(if(= S_Arrow 2)
(progn
(setq PosText (cdr (assoc 11 (entget (entlast)))))
;Длина отступа от центра текста
;Расчет коориднат знака уклона
; LP2
; ---___
; PosText----------LP1 - Расчет координат символа уклона
; ---
; LP3---
(setq DrawDist (* (/ (strlen Grad) 2) H_text 2))
;Определяем направление стрелки в сторону уклона
(if (= PosLP3 "N")
(setq DrawAngle DrawAngle)
(setq DrawAngle (+ DrawAngle PI))
);if
;Вычисляем координаты стрелки и создаём стрелку
(setq LP1 (polar PosText DrawAngle DrawDist))
(setq LP2 (polar LP1 (+ DrawAngle (+ PI(/ PI 6))) (* H_text 1.5)))
(setq LP3 (polar LP1 (- DrawAngle (+ PI(/ PI 6))) (* H_text 1.5)))
(entmake (list
(cons 0 "LWPOLYLINE")
(cons 8 N_layr)
(cons 62 C_layr)
(cons 100 "AcDbEntity")
(cons 100 "AcDbPolyline")
(cons 90 3)
(list 10 (car LP2) (cadr LP2))
(list 10 (car LP1) (cadr LP1))
(list 10 (car LP3) (cadr LP3))
));entmake LWPOLYLINE
`(entmake (list
(cons 0 "LWPOLYLINE")
(cons 8 N_layr)
(cons 62 C_layr)
(cons 100 "AcDbEntity")
(cons 100 "AcDbPolyline")
(cons 90 3)
(list 10 (car LP1) (cadr LP1))
(list 10 (car PosText) (cadr PosText))
));entmake LWPOLYLINE
);progn
);if
);Print_Grand
;===================================================================================================
; Функция вызова основного диалогового окна
;===================================================================================================
(defun Dialog()
(setq name_dcl "UKL.dcl")
(setq dcl_id (load_dialog name_dcl))
(if (= dcl_id -1)
(progn
(print) (princ "Файл ") (princ name_dcl) (princ " не найден") (print)
(exit)
)
);if dcl_id
(setq new_dial (new_dialog "dc_ukl" dcl_id))
(if (null new_dial)
(progn
(print "Не смог загрузить диалоговое окно")
(exit)
)
);End if
(Initialization)
(action_tile "ListLayer" "(Input_Layer (get_tile \"ListLayer\"))")
(action_tile "LayerName" "(Input_Layer_Name (get_tile \"LayerName\"))")
(action_tile "LayerColor" "(Enter_Color_Take)")
(action_tile "ListSText" "(Input_SText (get_tile \"ListSText\"))")
(action_tile "TextHeight" "(Input_HText (get_tile \"TextHeight\"))")
(action_tile "g1" "(if (= (get_tile \"g1\") \"1\")(setq S_Grad 1))")
(action_tile "g2" "(if (= (get_tile \"g2\") \"1\")(setq S_Grad 2))")
(action_tile "g3" "(if (= (get_tile \"g3\") \"1\")(setq S_Grad 3))")
(action_tile "g4" "(if (= (get_tile \"g4\") \"1\")(setq S_Grad 4))")
(action_tile "g5" "(if (= (get_tile \"g5\") \"1\")(setq S_Grad 5))")
(action_tile "a1" "(if (= (get_tile \"a1\") \"1\")(setq S_Arrow 1))")
(action_tile "a2" "(if (= (get_tile \"a2\") \"1\")(setq S_Arrow 2))")
(action_tile "accept" "(done_dialog 1)")
(action_tile "cancel" "(done_dialog 2)")
(if (= (start_dialog) 1 ) (Enter_Point))
(if (= (start_dialog) 2 ) (Exit))
(unload_dialog dcl_id)
); End Dialog
;===================================================================================================
;Функция ввода и проверки начальных значений
;===================================================================================================
(defun Initialization()
(ListSTible "LAYER") ;Формирование списка слоёв
(setq L_list (cons "Создать" L_list)) ;в начало списка добавляем "Создать"
(ListSTible "STYLE") ;Формирование списка стилей текста
(start_list "ListLayer")(mapcar 'add_list L_list)(end_list) ;Загрузка списка слоёв в диалог
(start_list "ListSText")(mapcar 'add_list S_list)(end_list) ;Загрузка списка стиелей текста в диалог
(set_tile "LayerName" N_layr) ;Надпись в диалоге имя слоя
(set_tile "TextHeidht" (rtos H_text)) ;Надпись в диалоге высота текста
);End Initialization
;;;===================================================================================================
;;; Имена стелй из стандартного набора по запросу
;;; List_Tible - список формата string
;;; sType - имена табличных стилей "APPID", "BLOCK", "DIMSTYLE", "LAYER", "LTYPE", "STYLE", "UCS",
;;; "VIEW", "VPORT"
;;;===================================================================================================
(defun ListSTible(sType / i temp lay_list lay1 lay2 tmp_elem List_Tible)
(setq temp T)
(setq lay_list '())
(setq lay1 (tblnext sType T))
(setq lay_list (append lay_list (list lay1)))
(while (/= temp nil)
(setq lay2 '())
(setq lay2 (tblnext sType))
(setq temp lay2)
(setq lay_list (append lay_list (list temp)))
)
(setq i 0)
(setq List_Tible '())
(repeat (length lay_list)
(setq tmp_elem (cdr (assoc 2 (nth i lay_list))))
(if (/= tmp_elem nil )(setq List_Tible (append List_Tible (list tmp_elem))))
(setq i (1+ i))
);End repeat
;Осторожно костыль
(cond
((= sType "LAYER") (setq L_list List_Tible)) ;Если Слои
((= sType "STYLE") (setq S_list List_Tible)) ;Если стили текста
);cond
);End List_layer
;===================================================================================================
;Функция проверки ввод Имени слоя
;===================================================================================================
(defun Input_Layer_Name(L_Name)
(if (or (= L_Name "") (null L_Name))
(progn
(alert "Введите ИМЯ слоя") ;Флаг запрета
);progn
(progn
(setq N_layr L_Name) ;Присвоить имя слоя
);progn
);if
);End Input_Diam
;===================================================================================================
;Функция проверки Выбора слоя из списка
;===================================================================================================
(defun Input_Layer(Layer / i)
(setq i (atoi Layer))
(if (> i 0)
(progn(mode_tile "LayerName" 1)(mode_tile "LayerColor" 1))
(progn(mode_tile "LayerName" 0)(mode_tile "LayerColor" 0))
);if
(setq N_layr (nth i L_list))
(if (= (atoi (get_tile "ListLayer")) 0) (New_Layer N_layr C_layr)) ;Создание слоя если истина
);End Input_Layer
;===================================================================================================
; Функция вызова диалогового окан для присвоения цвета
; и заливки цветом кнопкпи выбора
; - C_layr
;===================================================================================================
(defun Enter_Color_Take(/ dx dy tk_col)
(setq dx (dimx_tile "LayerColor") dy (dimy_tile "LayerColor"))
(setq tk_col (acad_colordlg C_layr))
(if (null tk_col) (princ)
(setq C_layr tk_col))
(start_image "LayerColor")
(fill_image 0 0 dx dy C_layr)
(end_image)
);End Enter_Color_Take
;===================================================================================================
;Функция проверки Выбора стиля текста из списка
;===================================================================================================
(defun Input_SText(sText / i)
(setq i (atoi sText))
(setq S_text (nth i S_list))
);End Input_Layer
;===================================================================================================
;Функция проверки ввод высоты текста
;===================================================================================================
(defun Input_HText(hText)
(if (or (= hText "") (null hText) (= hText "0"))
(progn
(alert "Введите ВЫСОТУ текста") ;Флаг запрета
);progn
(progn
(setq H_text (atof hText)) ;Присвоить выстоту текста
);progn
);if
);End Input_Diam
;===================================================================================================
;Функция создания нового Слоя
;===================================================================================================
(defun New_Layer(N_layr C_layr)
(entmake (list
(cons 0 "LAYER")
(cons 100 "AcDbSymbolTableRecord")
(cons 100 "AcDbLayerTableRecord")
(cons 2 N_layr)
(cons 70 0)
(cons 62 C_layr)
(cons 6 "Continuous")
);list
);entmake
);End New_Layer
;===================================================================================================
;Функция расчета уклона
;===================================================================================================
(defun Calc_Grad(gType / tmp)
(cond
((= gType 1) (setq Grad (rtos (abs (/ Elev Dist))2 3))) ;мм на метр
((= gType 2) (setq Grad (rtos (abs (/ Elev Dist))2 2))) ;см на метр
((= gType 3) (setq Grad (strcat (rtos (abs (* (/ Elev Dist) 100))2 0)"%"))) ;проценты %
((= gType 4) (setq Grad (strcat (rtos (abs (* (/ Elev Dist) 1000))2 0)"‰"))) ;промили ‰
((= gType 5)
(setq tmp (fix (abs (/ Dist Elev)))) ;соотношение
(setq Grad (strcat "1:" (rtos tmp 2 0))) ; 1:N
);gType 5
);end cond
);End Calc_Grad
;=================================================================================================== | 14,817 | Common Lisp | .l | 353 | 37.232295 | 103 | 0.474776 | AlexandrGlushko/UklLispForAutoCad | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:10 AM (Europe/Amsterdam) | f94143052b9d684b170a11c454e1818a2e693104e530f2bd29f058a38d45d440 | 44,865 | [
-1
] |
44,881 | CIR.dcl | AlexandrGlushko_CirLispForAutoCad/CIR.dcl | main_cir: dialog {
label = "Построение окружностей";
:boxed_column {
label = "Данные съёмки";
:row {
:text { label = "Выбирите точку(и) съемки"; }
:button {
key = "obj_take";
label = "Выбрать";
action = "(done_dialog 10)";
fixed_width = true;
}//button
}//row
:row {
:edit_box {
label = "Введите диаметр свай, мм";
key = "diam_take";
edit_width = 10;
edit_limit = 10;
value = "";
}//edit_box
}//row
}//boxed_row
:boxed_row {
label = "Слой и цвет для построения";
children_alignment = centered;
:popup_list {
label = "Слой ";
key = "layer_take";
list = "";
width = 25;
}//popup_list
:edit_box {
key = "layer_name";
edit_width = 12;
edit_limit = 20;
}//edit box
:image_button {
key = "colortake";
width = 4;
fixed_width = true;
}//image_button
}//boxed_row
:row {
children_alignment = centered;
:row {
children_alignment = centered;
:column {
children_alignment = centered;
:button {
key = "build";
label = " Построить ";
action = "(done_dialog 9)";
height = 5;
fixed_width = true;
}//button
}//column
}//row
:boxed_radio_column {
label = "Способ построения";
:radio_button {label = "По трем точкам"; key = "cir1"; value = "1";}
:radio_button {label = "По лучшему радиусу"; key = "cir2"; value = "0";}
}//boxed_
}//row
ok_cancel_help;
}//main_ci
//Диалог справки
help_cir: dialog {
label = "Справка";
:boxed_column {
label = "Последовательность постороения";
:text {label = "Шаг 1 Выбирать точку(и) съёмки";}
:text {label = "Шаг 2 Ввести диаметр в мм";}
:text {label = "Шаг 3 Выбрать слой и цвет для построения";}
:text {label = "Шаг 4 Нажать кнопу \"Построить\" или \"ОК\"";}
spacer_1;
:text {label = "\"ОК\" - построение с выходом из диалога";}
:text {label = "\"Построить\" - построение с возвратом в диалог";}
spacer_1;
:text {label = "\"По трем точкам\" - построение по трем точкам съёмки";}
:text {label = "которые были выбраны первыми им множества отснятых точек сваи";}
:text {label = "построение не всегда корректно";}
spacer_1;
:text {label = "\"По лучшему радиусу\" - построение по лучшему радиусу";}
:text {label = "который определяется из множества точек съёмки одной сваи";}
:text {label = "построение более корректно, работает медленно";}
spacer_1;
:text {label = "\"Коэффициент поиска точек\" - чем больше значение";}
:text {label = "тем больше зона поиска точек съёмки для заданного диаметра";}
spacer_1;
:text {label = "Примечание: все не построенные окружности при максимальном";}
:text {label = "коэффициенте говорят о большом \"отлёте\" съемочных точек от диаметра";}
}//boxed_column
:boxed_row {
label = "Коэффициент поиска точек";
:slider {
key = "slid_val";
big_increment = 1;
small_increment = 1;
min_value = 102;
max_value = 117;
}//slider
:text {label = "k=";}
:text {key = "Show_slide_val";}
}//boxed_row
:column {
children_alignment = centered;
:text {label = "Автор Глушко Александр, 2019г.";}
:text {label = "aleksandr-glushko@bk.ru";}
}//column
:ok_button{label = "Вернутья";}
}//dialog | 3,140 | Common Lisp | .cl | 112 | 25.0625 | 89 | 0.648363 | AlexandrGlushko/CirLispForAutoCad | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:10 AM (Europe/Amsterdam) | e47876c80010626aba2d1dca0340a0d985a17342a82455e4e3e6544d45d51d27 | 44,881 | [
-1
] |
44,883 | CIR.lsp | AlexandrGlushko_CirLispForAutoCad/CIR.lsp | ;===================================================================================================
;Автоматическое построение окружности по точкам съемки
;===================================================================================================
(defun c:cir()
(setq Input 0) ;Флаг готовности к построению
(setq Func_Draw 0) ;Флаг выбора функции для отрисовки
(setq Set_Obj_Point nil) ;Тип объекта для поиска
(setq Set_Layer_Find nil) ;Слой для поиска
(setq Set_Diam 0.630) ;Диаметр для поиска соседних точек
(setq Set_Coef_Diam 1.07) ;Коэффициент искажнеия для поиска нужного диаметра
(setq Set_Max_Diam (* Set_Diam Set_Coef_Diam)) ;Максимальный диаметр для поиска и отрисовки
(setq Set_Min_Diam (* Set_Diam (- 2 Set_Coef_Diam))) ;Минимальный диаметр для откисовки
(setq Set_Name_Layer "Съемка") ;Имя слоя для рисования
(setq Set_Color_Layer 1) ;Цвет слоя
(Dialog) ;Запуск диалогового окна
(Clear_Memory) ;Очистка памяти
(princ) ;Тихай выход
);End Cir
;===================================================================================================
;Функция обнуления глобальных переменных
;===================================================================================================
(defun Clear_Memory()
(setq Set_Obj_Point nil) ;Тип объекта для поиска
(setq Set_Layer_Find nil) ;Слой для поиска
(setq Input 0) ;Флаг готовности к построению
(setq Func_Draw 0) ;Флаг выбора функции для отрисовки
(setq list_point nil) ;Список найденных точек функцией Find_Point
(setq gruop_list nil) ;Список групп точек составленной функцией List_For_Draw
)
;===================================================================================================
;Функция активации расширеных функций ActiveX для обработки точек COGO Civli3D
;===================================================================================================
(defun Load_ActiveX()
(vl-load-com)
(setq Acad_Application (vlax-get-acad-object))
(setq Active_Document (vla-get-ActiveDocument Acad_Application))
(setq Model_Space (vla-get-ModelSpace Active_Document))
(setq Paper_Space (vla-get-PaperSpace Active_Document))
);End Load_ActiveX
;===================================================================================================
;Функция ввода и проверки начальных значений
;===================================================================================================
(defun Initialization(/ q dx dy )
(if (null Set_Obj_Point) (setq Input -2) (setq Input 1)) ;Выбраны или нет точки съемки
(List_layer) ;Создание списка слоев
(start_list "layer_take")
(mapcar 'add_list list_of_layer) ;Загрузка списка в диалог
(end_list)
(set_tile "diam_take" (rtos (* Set_Diam 1000))) ;Диаметр, мм
(set_tile "layer_name" Set_Name_Layer) ;Имя слоя
;Установка имени слоя в списке и вкл/отк поля ввода
(if (/= Set_Name_Layer "Съемка")
(progn
(setq pos_lis_lay (vl-position Set_Name_Layer list_of_layer))
(if (= pos_lis_lay nil)
(setq list_of_layer (append list_of_layer (list Set_Name_Layer)))
(progn
(set_tile "layer_take" (itoa pos_lis_lay))
(if (> pos_lis_lay 0) (mode_tile "layer_name" 1)(mode_tile "layer_name" 0))
(setq Set_Name_Layer (nth pos_lis_lay list_of_layer))
);End progn
);End if
);End progn
);End if
;Выбор цвета слоя и заливка кнопки выбора
(setq dx (dimx_tile "colortake") dy (dimy_tile "colortake"))
(start_image "colortake")
(fill_image 0 0 dx dy Set_Color_Layer) ;Цвет слоя
(end_image)
);End Initialization
;===================================================================================================
;Функция запуска построения окуржностей
; Draw_Circle - построение окружности по первым трем точкам в группе
; Draw_Circle_2 - построение окружности по лучшему радиусу из множества точек группы
;===================================================================================================
(defun Start_Build(Input /)
(Initialization) ;Контрольная проверка данных
(if (= Input 1) ;При нормальных вводных данных
(progn
(Find_Point) ;Поиск точек на черетже
(List_For_Draw) ;Составление групп из точек
(if (= Func_Draw 0) (Draw_Circle) (Draw_Circle_2)) ;Построение в дной из функций
);progn
(progn
(cond
((= Input -1) (alert "Введите ДИАМЕТР сваи, мм")) ;Выдача сообщений о не верно
((= Input -2) (alert "Выберите ТОЧКУ(И) СЪЕМКИ")) ;введенных или не введенных
((= Input -3) (alert "Введите ИМЯ СЛОЯ для Построения")) ;начальных значениях
);cond
);progn
);if
);End Start_Dtaw
;===================================================================================================
;Функция проверки ввода Диаметра
;===================================================================================================
(defun Input_Diam(Diam / dm)
(setq dm (atoi Diam))
(if (or (null dm) (minusp dm) (zerop dm))
(progn
(setq Input -1) ;Флаг запрета
);progn
(progn
(setq Set_Diam (/ (float dm) 1000)) ;Присвоить диаметр
(setq Set_Max_Diam (* Set_Diam Set_Coef_Diam)) ;Максимальный диаметр для поиска и отрисовки
(setq Set_Min_Diam (* Set_Diam (- 2 Set_Coef_Diam)));Минимальный диаметр для откисовки
(setq Input 1) ;Флаг разрешения
);prong
);if
);End Input_Diam
;===================================================================================================
;Функция проверки ввод Имени слоя
;===================================================================================================
(defun Input_Layer_Name(L_Name)
(if (or (= L_Name "") (null L_Name))
(progn
(setq Input -3) ;Флаг запрета
);progn
(progn
(setq Set_Name_Layer L_Name) ;Присвоить имя слоя
(setq Input 1) ;Флаг разрешения
);progn
);if
);End Input_Diam
;===================================================================================================
;Функция проверки Выбора слоя из списка
;===================================================================================================
(defun Input_Layer(Layer / i)
(setq i (atoi Layer))
(if (> i 0) (mode_tile "layer_name" 1)(mode_tile "layer_name" 0))
(setq Set_Name_Layer (nth i list_of_layer))
);End Input_Diam
;===================================================================================================
; Функция составление списка слоев текущего чертежа
; list_of_layer - список слоев формата string
;===================================================================================================
(defun List_layer(/ temp lay_list lay1 lay2 tmp_elem i)
(setq temp T)
(setq lay_list '())
(setq lay1 (tblnext "LAYER" T))
(setq lay_list (append lay_list (list lay1)))
(while (/= temp nil)
(setq lay2 '())
(setq lay2 (tblnext "LAYER"))
(setq temp lay2)
(setq lay_list (append lay_list (list temp)))
)
(setq i 0)
(setq list_of_layer '())
(repeat (length lay_list)
(setq tmp_elem (cdr (assoc 2 (nth i lay_list))))
(if (/= tmp_elem nil )(setq list_of_layer (append list_of_layer (list tmp_elem))))
(setq i (1+ i))
);End repeat
(setq list_of_layer (cons "Создать" list_of_layer))
);End List_layer
;===================================================================================================
;Функция выбора элемента съмки по элементам модели
;При выборе объекта присваивает параметры:
; Ent_point - тип объекта для поиска
; Ent_layer - слой на котором расположены объекты для поиска
;===================================================================================================
(defun Enter_Data_Take(/ Ent_layer Ent_point Ent_data First_Elem)
(setq Ent_layer "")
(setq Ent_point "")
(setq Ent_data (ssget)) ;Выбор элемента пользователем
(if (null Ent_data)
(progn
(print "Ничего не выбранно")
)
(progn
(setq First_Elem (entget (ssname Ent_data 0)))
(setq Ent_point (cdr (assoc 0 First_Elem)))
(setq Ent_layer (cdr (assoc 8 First_Elem)))
(princ "Выбранный слой: ") (princ Ent_layer) (print)
(princ "Выбранный тип объекта: ") (princ Ent_point) (print)
(setq Set_Obj_Point Ent_point)
(setq Set_Layer_Find Ent_layer)
)
);if Ent_data
);End Enter_Data_Take
;===================================================================================================
; Функция вызова диалогового окан для присвоения цвета
; и заливки цветом кнопкпи выбора
; - Set_Color_Layer
;===================================================================================================
(defun Enter_Color_Take(/ dx dy tk_col)
(setq dx (dimx_tile "colortake") dy (dimy_tile "colortake"))
(setq tk_col (acad_colordlg Set_Color_Layer))
(if (null tk_col) (princ)
(setq Set_Color_Layer tk_col))
(start_image "colortake")
(fill_image 0 0 dx dy Set_Color_Layer)
(end_image)
);End Enter_Color_Take
;===================================================================================================
; Функция вызова основного диалогового окна
;===================================================================================================
(defun Dialog()
(setq name_dcl "CIR.dcl")
(setq dcl_id (load_dialog name_dcl))
(if (= dcl_id -1)
(progn
(print) (princ "Файл ") (princ name_dcl) (princ " не найден") (print)
(exit)
)
);if dcl_id
(setq enter 2)
(while (>= enter 2) ;Основной цикл окна
(setq new_dial (new_dialog "main_cir" dcl_id))
(if (null new_dial)
(progn
(print "Не смог загрузить диалоговое окно")
(exit)
)
);End if
(Initialization) ;Проверка введенных данных
(action_tile "diam_take" "(Input_Diam (get_tile \"diam_take\"))")
(action_tile "layer_take" "(Input_Layer (get_tile \"layer_take\"))")
(action_tile "layer_name" "(Input_Layer_Name (get_tile \"layer_name\"))")
(action_tile "colortake" "(Enter_Color_Take)")
(action_tile "cir1" "(setq Func_Draw 0)")
(action_tile "cir2" "(setq Func_Draw 1)")
(action_tile "accept" "(done_dialog 1)")
(action_tile "cancel" "(done_dialog)")
(action_tile "help" "(Help_Dialog dcl_id)")
(setq enter (start_dialog))
(cond
((= enter 10) (Enter_Data_Take)) ;Выбор точек съемки
((= enter 9) (Start_Build Input)) ;Построение с возвратом из диалога
((= enter 1) (Start_Build Input)) ;Построение с выходом из диалога
);cond
);Конец основного цикла окна
(unload_dialog dcl_id)
(princ)
); End Dialog
;===================================================================================================
; Функция вызова окна справки
;===================================================================================================
(defun Help_Dialog(id)
(new_dialog "help_cir" id)
(set_tile "Show_slide_val" (rtos Set_Coef_Diam)) ;Присвоить значение коэффициента
(action_tile "slid_val" "(Slider_Val $value)")
(start_dialog)
);End Help_Dialog
;===================================================================================================
; Функция управления полосой прокрутки для фоэффициента поиска точек
;===================================================================================================
(defun Slider_Val(val)
(setq Set_Coef_Diam (/(float(atoi val))100))
(set_tile "Show_slide_val" (rtos Set_Coef_Diam))
);End Slider_Val
;===================================================================================================
; Функция поиска точек по типу объекта и на слое указанном в функции Enter_Data_Take
; list_point - список всех найденных точек в чертеже
;===================================================================================================
(defun Find_Point(/ i point_list xyz_list)
(setq list_point '())
(setq nab_point (ssget "_X" (list (cons 8 Set_Layer_Find) (cons 0 Set_Obj_Point))))
(if (null nab_point)
(progn
(print "Нет точек на данном слое")
(exit)
)
(progn
(princ "Количество точек для построения: ") (prin1 (sslength nab_point))
)
);if nab_point
(if (= Set_Obj_Point "AECC_COGO_POINT")
(progn
(Load_ActiveX)
(setq nab_lenght (sslength nab_point))
(setq i -1)
(repeat nab_lenght
(setq i (1+ i))
(setq vlx_point (vlax-ename->vla-object (ssname nab_point i)))
(setq xyz_list (list (vlax-get-property vlx_point 'Easting)
(vlax-get-property vlx_point 'Northing)
(vlax-get-property vlx_point 'Elevation)))
(setq list_point (append list_point (list xyz_list)))
);repeat nab_lenght
);End progn true
(progn
(setq nab_lenght (sslength nab_point))
(setq i -1)
(repeat nab_lenght
(setq i (1+ i))
(setq point_list (entget (ssname nab_point i)))
(setq xyz_list (cdr (assoc 10 point_list)))
(setq list_point (append list_point (list xyz_list)))
);repeat nab_lenght
); End progn false
);End if
);End Find_Point
;===================================================================================================
;Функция поиска и формирования групп точек для рисования
;Измеряеться расстояния между всеми точками по очереди
;На основании наименьшей длины согласно ВВЕДЕННОГО диаметра
;Точки собираются в группы, затем все группы добавляються в общий список для печати
;Повторения исключены на этапе добавлении группы в список групп
; gruop_list - список групп точек
;===================================================================================================
(defun List_For_Draw(/ temp_gruop p1 p2 j i have_data temp_elem gruop_elem)
(setq gruop_list '()) ;Список групп точек
(setq temp_gruop '()) ;Группа кандидат на добавление в список
(setq i 0) ;Внешний перебор
(setq j 0) ;Внутренний перебор
(repeat nab_lenght ;Перебор всех точек чертежа и создание групп точек
(setq p1 (nth i list_point)) ;Внешний перебор
(setq temp_gruop (append temp_gruop (list p1))) ;Первая точка в группе
(repeat nab_lenght
(setq p2 (nth j list_point)) ;Внутренний перебор
(if (/= p1 p2) (setq dist (distance p1 p2)))
;Если точки не совпадают и расстояние между точками <= Максимального диаметра
; и между точками боьше 2 см
(if (and (/= p1 p2) (<= dist Set_Max_Diam) (>= dist 0.02))
(setq temp_gruop (append temp_gruop (list p2))))
(setq j (1+ j)) ;Итерация внутренний перебор
);repeat
;Перед добавлением кандидата (temp_gruop)проверяеться последний добавленный элемент в (gruop_list)
;если совпаденией нет то кандидат добавляеться если есть то пропускаеться
;В пустой список (gruop_list) добавляеться первый кандидат
(progn
(setq have_data (length gruop_list))
(if (= have_data 0)
;Певый кандидат в пустом списке
(setq gruop_list (append gruop_list (list temp_gruop)))
(progn
;Последний добавленный кандидат
(setq gruop_elem (nth (- (length gruop_list) 1) gruop_list))
;Первый элемент кандидата на добавление
(setq temp_elem (nth 0 temp_gruop))
;Проверка на принадлежность элемента к последнему списку
(setq have_elem (member temp_elem gruop_elem))
(if (null have_elem )
;Если нет такого элемента в списке то добавляем новый список
(setq gruop_list (append gruop_list (list temp_gruop)))
);if
);progn
);if
);progn
(setq temp_gruop '()) ;Обнуление группы кандидата
(setq j 0) ;и счетчика внутреннего перебора
(setq i (1+ i)) ;Итерация Внешнего перебора
);End repeat
);End List_For_Draw
;===================================================================================================
;Функция рисования окружностей по первым трем точкам в группе
;===================================================================================================
(defun Draw_Circle( / )
(setvar "CMDECHO" 0)
(setvar "OSMODE" 0)
(command-s "._-LAYER" "_M" Set_Name_Layer "_C" Set_Color_Layer "" "")
(setq counter 0) ;Счетчик отрисованных кругов
(setq no_counter 0) ;Счетчик групп с количеством точек для построения < 3
(setq i 0) ;Индекс для перебора групп точек
(setq print_list '()) ;Список точек для печати
(repeat (length gruop_list) ;Перебор списка групп точек
(setq print_list (nth i gruop_list)) ;Список точек <- [Индекс] списка группы точек
(setq pr_length (length print_list)) ;Количество точе в списке для рисования
(if (>= pr_length 3) ;Если точек 3 и более то рисуем
(progn
(command-s "_.CIRCLE" "_3P" (nth 0 print_list) (nth 1 print_list) (nth 2 print_list))
(setq last_obj (entlast))
(setq tmp_cir (entget last_obj))
(entdel last_obj)
(setq new_cir_pos (cdr (assoc 10 tmp_cir)))
(setq new_cir_rad (cdr (assoc 40 tmp_cir)))
(if (and (<= new_cir_rad (/ Set_Max_Diam 2)) (>= new_cir_rad (/ Set_Min_Diam 2)))
(progn
(command-s "_.CIRCLE" new_cir_pos new_cir_rad)
(setq counter (1+ counter)) ;Итерация счетчика отрисованных кругов
);progn
);if
)
(progn (setq no_counter (1+ no_counter))) ;Мало точек для построения
);End if
(setq print_list '()) ;Очистка списка печати
(setq i (1+ i)) ;Итерация индекса списка из групп точек
);End repeat
(setvar "OSMODE" 1)
(setvar "CMDECHO" 1)
(print) (princ "Групп с количеством точек меньше трех: ") (prin1 no_counter)
(print) (princ "Количество построенных окружностей: ") (prin1 counter)
);End Draw_Cirle
;===================================================================================================
;Функция рисования окружностей по лучшему радиасу при 4 и более точках в группе
;===================================================================================================
(defun Draw_Circle_2( / )
(setvar "CMDECHO" 0)
(setvar "OSMODE" 0)
(command-s "._-LAYER" "_M" Set_Name_Layer "_C" Set_Color_Layer "" "")
(setq counter 0)
(setq no_counter 0)
(setq i 0)
(setq print_list '())
(repeat (length gruop_list)
(setq print_list (nth i gruop_list))
(setq pr_length (length print_list))
(if (>= pr_length 3)
(progn
(setq radius_list '())
(setq p1 0)
(setq p2 1)
(setq p3 2)
(repeat pr_length ;p1
(repeat pr_length ;p2
(repeat pr_length ;p3
(if (and (/= p1 p2) (/= p1 p3) (/= p2 p3))
(progn
(command-s "_.CIRCLE" "_3P" (nth p1 print_list) (nth p2 print_list) (nth p3 print_list))
(setq last_obj (entlast))
(setq tmp_cir (entget last_obj))
(entdel last_obj)
(setq tmp_cand (list (cons (cdr (assoc 40 tmp_cir)) (cdr(assoc 10 tmp_cir)))))
(if (/= (car (car tmp_cand)) nil)
(if (null (member tmp_cand radius_list)) (setq radius_list (append radius_list tmp_cand)))
)
(setq tmp_cand '())
);progn
);End if
(setq p3 (1+ p3))
(if (= p3 pr_length) (setq p3 (- p3 1)))
);repeat p3
(setq p3 2)
(setq p2 (1+ p2))
(if (= p2 pr_length) (setq p2 (- p2 1)))
);repeat p2
(setq p2 1)
(setq p1 (1+ p1))
(if (= p1 pr_length) (setq p1 (- p1 1)))
);repeat p1
(setq difer_list (mapcar '(lambda (elem) (abs (- (/ Set_Diam 2) (car elem))))radius_list))
(setq some_min (car (vl-sort difer_list '<)))
(setq pos_rad (vl-position some_min difer_list))
(setq new_cir_pos (cdr (nth pos_rad radius_list)))
(setq new_cir_rad (car (nth pos_rad radius_list)))
(if (and (<= new_cir_rad (/ Set_Max_Diam 2)) (>= new_cir_rad (/ Set_Min_Diam 2)))
(progn
(command-s "_.CIRCLE" new_cir_pos new_cir_rad)
(setq counter (1+ counter)) ;Итерация счетчика отрисованных кругов
);progn
);if
);progn
(setq no_counter (1+ no_counter)) ;Мало точек для построения
);End if
(setq radius_list '())
(setq print_list '())
(setq i (1+ i))
);End repeat
(setvar "OSMODE" 1)
(setvar "CMDECHO" 1)
(print) (princ "Групп с количеством точек меньше трех: ") (prin1 no_counter)
(print) (princ "Количество построенных окружностей: ") (prin1 counter)
);End Draw_Cirle
;===================================================================================================
(defun TestGit) | 20,555 | Common Lisp | .l | 456 | 40.692982 | 101 | 0.533037 | AlexandrGlushko/CirLispForAutoCad | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:10 AM (Europe/Amsterdam) | 529dda13c814e7e46d2e2f8e7f9509c16163169bfbe684cf04e1d52247b7f442 | 44,883 | [
-1
] |
44,900 | salt.lisp | proton-group_salt/salt.lisp | (defpackage :salt
(:use :common-lisp :alexandria)
(:export
#:split))
(in-package :salt)
(defun split (str)
(defvar i -1)
(defvar j 0)
(loop
while (not (eql i nil))
do
(setf j (+ 1 i))
(setq i (position #\linefeed str :start (+ i 1) :end nil))
(print i)
collect (subseq str j i))
) | 328 | Common Lisp | .lisp | 16 | 16.5625 | 62 | 0.573718 | proton-group/salt | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:10 AM (Europe/Amsterdam) | 9ab8b4bc14396d64e525b3d9e2bc673535ebc4b2c12856aed00dc8d5cd75cd50 | 44,900 | [
-1
] |
44,918 | Makefile | joe-ds_bfc/Makefile | bfcmake: bfc.lisp
sbcl --script bfc.lisp
nasm -f elf64 bf_out.nasm
ld bf_out.o -o bf
rm -v bf_out.nasm bf_out.o | 115 | Common Lisp | .l | 5 | 21.4 | 27 | 0.711712 | joe-ds/bfc | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:10 AM (Europe/Amsterdam) | 7f427ec567eda06eabb7709a3556359bec70313a1c1d90a6a84e3f40f1157242 | 44,918 | [
-1
] |
44,933 | fnv.lisp | AbdeltwabMF_lisp-hashpalooza/src/fnv.lisp | (defpackage lisp-hashpalooza/fnv
(:use :cl)
(:export :fnv-32a
:fnv-64a
:fnv-128a
:fnv-256a
:fnv-512a
:fnv-1024a))
(in-package :lisp-hashpalooza/fnv)
;; Source: http://www.isthe.com/chongo/tech/comp/fnv/index.html
(defconstant +prime-32+ 16777619)
(defconstant +offset-32+ 2166136261)
(defconstant +mod-32+ (ash 1 32))
(defconstant +prime-64+ 1099511628211)
(defconstant +offset-64+ 14695981039346656037)
(defconstant +mod-64+ (ash 1 64))
(defconstant +prime-128+ 309485009821345068724781371)
(defconstant +offset-128+ 144066263297769815596495629667062367629)
(defconstant +mod-128+ (ash 1 128))
(defconstant +prime-256+ 374144419156711147060143317175368453031918731002211)
(defconstant +offset-256+ 100029257958052580907070968620625704837092796014241193945225284501741471925557)
(defconstant +mod-256+ (ash 1 256))
(defconstant +prime-512+ 35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759)
(defconstant +offset-512+ 9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785)
(defconstant +mod-512+ (ash 1 512))
(defconstant +prime-1024+ 5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573)
(defconstant +offset-1024+ 14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915)
(defconstant +mod-1024+ (ash 1 1024))
(defun fnv-hash (offset prime mod bytes)
"Compute FNV hash for given OFFSET, PRIME, MOD, and BYTES."
(let ((hash offset))
(loop for b across bytes do
(setf hash (mod (* (logxor hash (char-code b)) prime) mod)))
hash))
(defun fnv-32a (bytes)
"Compute 32-bit FNV-1a hash."
(fnv-hash +offset-32+ +prime-32+ +mod-32+ bytes))
(defun fnv-64a (bytes)
"Compute 64-bit FNV-1a hash."
(fnv-hash +offset-64+ +prime-64+ +mod-64+ bytes))
(defun fnv-128a (bytes)
"Compute 128-bit FNV-1a hash."
(fnv-hash +offset-128+ +prime-128+ +mod-128+ bytes))
(defun fnv-256a (bytes)
"Compute 256-bit FNV-1a hash."
(fnv-hash +offset-256+ +prime-256+ +mod-256+ bytes))
(defun fnv-512a (bytes)
"Compute 512-bit FNV-1a hash."
(fnv-hash +offset-512+ +prime-512+ +mod-512+ bytes))
(defun fnv-1024a (bytes)
"Compute 1024-bit FNV-1a hash."
(fnv-hash +offset-1024+ +prime-1024+ +mod-1024+ bytes))
| 2,692 | Common Lisp | .lisp | 52 | 49.230769 | 315 | 0.805027 | AbdeltwabMF/lisp-hashpalooza | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | 1924c8d07cd5391cc69559752ae0958c95ba5376abe68eeb0e0f1d950862525e | 44,933 | [
-1
] |
44,934 | fnv.lisp | AbdeltwabMF_lisp-hashpalooza/tests/fnv.lisp | (defpackage lisp-hashpalooza/tests/fnv
(:use :cl
:lisp-hashpalooza/fnv))
(in-package :lisp-hashpalooza/tests/fnv)
(defun test-fnv (fnv-size bytes expected-hash test-name)
(let ((result (funcall fnv-size bytes)))
(if (= result expected-hash)
(format t "~a OK~%" test-name)
(format t "~a FAIL~%~TExpected: ~a~%~TFound: ~a~%" test-name expected-hash result))))
(test-fnv #'fnv-32a "Abdeltwab" 4250523589 "FNV-32a")
(test-fnv #'fnv-64a "Abdeltwab" 15868749042133058245 "FNV-64a")
(test-fnv #'fnv-128a "Abdeltwab" 245623176195325149255754323885064107269 "FNV-128a")
(test-fnv #'fnv-256a "Abdeltwab" 5579611486752253052114639925472386104307805330558211631792199649318346887557 "FNV-256a")
(test-fnv #'fnv-512a "Abdeltwab" 4183189348975840892679718008458342356023693137418566086551877465692366837857271243016033820937012125405659320146949274230162581706406812609194990192150061 "FNV-512a")
(test-fnv #'fnv-1024a "Abdeltwab" 173425379102706622578532913025069130275212387278252719466505271693154582309951430084388112031209010948230797115055057003075801645053415509005786294812901003658053499691324206877090570962628241091460876411375312590239656087346604315146095117997620945280199979914570481870728797559041362462308474942719305707121 "FNV-1024a")
| 1,267 | Common Lisp | .lisp | 15 | 81.666667 | 356 | 0.8312 | AbdeltwabMF/lisp-hashpalooza | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | 90c925168f4b418c4cd58306c64d3ab116b078145ca45fd0e677f6f5c7c3c05c | 44,934 | [
-1
] |
44,935 | lisp-hashpalooza.asd | AbdeltwabMF_lisp-hashpalooza/lisp-hashpalooza.asd | (defsystem "lisp-hashpalooza"
:version "0.1.0"
:author "Abd El-Twab M. Fakhry"
:license "GPLv3"
:depends-on ()
:components ((:module "src"
:components
((:file "fnv"))))
:description "Diverse array of non-cryptographic hash functions in Common Lisp"
:in-order-to ((test-op (test-op "lisp-hashpalooza/tests"))))
(defsystem "lisp-hashpalooza/tests"
:depends-on ("lisp-hashpalooza"
"rove")
:components ((:module "tests"
:components
((:file "fnv"))))
:perform (test-op (op c) (symbol-call :rove :run c)))
| 600 | Common Lisp | .asd | 17 | 28.411765 | 81 | 0.599656 | AbdeltwabMF/lisp-hashpalooza | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | 99bfa66c95858b17d6ba7e8c2960de016f8a468c20febfc393018b064e3a4e28 | 44,935 | [
-1
] |
44,954 | snake.lisp | Jerkab_cl-snake/snake.lisp | ;; snake.lip -- Jeu du snake
;;
(eval-when (:compile-toplevel :execute :load-toplevel)
(ql:quickload "croatoan"))
;; Defining a package is always a good idea
(defpackage #:jsa.game.snake
(:use #:cl)
(:export #:main))
;; TODO: Revoir un peu le code pour le simplifier
;; TODO: Utilisation de caracteres speciaux
;; TODO: Gerer la vitesse du jeu
;; TODO: Activation du score
;; TODO: Prendre en compte les points de vie
;; TODO: Gerer le 'resize'
(in-package #:jsa.game.snake)
(defparameter *scr* nil)
(defvar *game-width* 40)
(defvar *game-height* 40)
(defun game (win)
(let ((snake '((20 3) (20 2) (20 1) (20 0)))
(direction '(0 1))
(foods '())
(size (list (1- *game-width*) (1- *game-height*)))
(ended 0)
(cycle 0)
(score 0)
(life 0)
(window-game (make-instance 'crt:window :height *game-height* :width *game-width* :y 0 :x 0 :fgcolor :white :border t))
(window-info (make-instance 'crt:window :height 10 :width 20 :y 0 :x (1+ *game-width*) :fgcolor :white :border t)))
(labels ((initialize-game ()
(setq snake '((20 3) (20 2) (20 1) (20 0)))
(setq direction '(0 1))
(setq foods '())
(setq size (list *game-width* *game-height*))
(setq ended 0)
(setq life 0)
(setq score 0)
(add-food))
(display-game ()
(crt:clear window-game)
(crt:draw-border window-game)
(crt:add-string window-game (format nil " Area ") :y 0 :x 2 :fgcolor :white)
(crt:add-char window-game #\* :y (second (first snake)) :x (caar snake) :fgcolor :green)
(dolist (b (butlast (cdr snake)))
(crt:add-char window-game #\= :y (second b) :x (first b) :fgcolor :green))
(crt:add-char window-game #\- :y (second (first (last snake))) :x (caar (last snake)) :fgcolor :green)
(dolist (f foods) (crt:add-char window-game #\# :y (second f) :x (car f) :fgcolor :yellow))
(crt:refresh window-game))
(display-info ()
(crt:clear window-info)
(crt:draw-border window-info)
(crt:add-string window-info (format nil " Info ") :y 0 :x 2 :fgcolor :white)
(crt:add-string window-info (format nil "Cycle: ~D" cycle) :y 1 :x 1)
(crt:add-string window-info (format nil "Snake: ~D" (length snake)) :y 2 :x 1)
(crt:add-string window-info (format nil "Foods: ~D" (length foods)) :y 3 :x 1)
(crt:add-string window-info (format nil "Life: ~D" life) :y 4 :x 1)
(crt:add-string window-info (format nil "Score: ~D" score) :y 6 :x 1)
(if (= ended 1)
(crt:add-string window-info "GAME OVER" :y 8 :x 1 :fgcolor :red :bgcolor :black))
(crt:refresh window-info))
(move-snake ()
(let* ((nhead (list (+ (first direction) (caar snake))
(+ (second direction) (second (first snake))))))
(setq snake (cons nhead
(if (eat-food nhead)
snake
(butlast snake))))))
(change-direction (dx dy)
(setq direction (list dx dy)))
(collision-snake ()
(find (car snake) (cdr snake) :test #'equal))
(collision-border ()
(let ((x (caar snake))
(y (second (first snake))))
(when (or (< x 1) (>= x (first size)) (< y 1) (>= y (second size)))
t)))
(add-food () ; random between 1 to size
(setq foods (cons (list (1+ (random (1- (first size))))
(1+ (random (1- (second size)))))
foods)))
(eat-food (pos)
(when (find pos foods :test #'equal)
(setq foods (remove pos foods :test #'equal))
(add-food)
t))
(game-over ()
(setq ended 1)
(crt:add-string window-info "GAME OVER" :y 0 :x 0)))
;; Bind Event
;; TODO: definir le bind sur la fenetre
(crt:bind win #\q 'crt:exit-event-loop)
(crt:bind win #\c (lambda (win event) (crt:clear win)))
(crt:bind win #\r (lambda (win event) (initialize-game)))
(crt:bind win #\j (lambda () (change-direction -1 0)))
(crt:bind win #\l (lambda () (change-direction 1 0)))
(crt:bind win #\i (lambda () (change-direction 0 -1)))
(crt:bind win #\k (lambda () (change-direction 0 1)))
;; (crt:bind win :left (lambda () (change-direction -1 0)))
;; (crt:bind win :right (lambda () (change-direction 1 0)))
;; (crt:bind win :up (lambda () (change-direction 0 -1)))
;; (crt:bind win :down (lambda () (change-direction 0 1)))
(crt:bind win nil (lambda (win event)
(if (= ended 0)
(move-snake))
(if (or (= ended 1) (collision-snake) (collision-border))
(game-over)
(progn
(setq cycle (1+ cycle))
(display-game)))
(display-info)))
(add-food))))
(defun main ()
(crt:with-screen (scr
:input-echoing nil
:input-blocking nil
:enable-function-keys t
:cursor-visible nil)
(game scr)
(setf (crt:frame-rate scr) 10)
(crt:run-event-loop (setf *scr* scr))))
(main)
| 5,809 | Common Lisp | .lisp | 121 | 34.438017 | 127 | 0.491982 | Jerkab/cl-snake | 0 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | 61a7b5efa07de3c73e4cd0afed4d388bc30a0881c1c93e7e85f10036d064518c | 44,954 | [
-1
] |
44,971 | matrix.lisp | DominikM_matrix/matrix.lisp | (defpackage :matrix
(:use :cl)
(:local-nicknames (:jzon :com.inuoe.jzon)
(:alex :alexandria)))
(in-package :matrix)
(defvar *server* nil)
(defun start ()
(unless *server*
(setq *server*
(clack:clackup #'app
:server :woo
:port 5050))))
(defun stop ()
(when *server*
(clack:stop *server*)
(setq *server* nil)))
(defun restart-server ()
(stop)
(start))
;;;
(defun request-method (env)
(getf env :request-method))
(defun path-info (env)
(getf env :path-info))
(defun raw-body (env)
(getf env :raw-body))
(defun content-type (env)
(getf env :content-type))
(defun content-length (env)
(getf env :content-length))
(defun headers (env)
(getf env :headers))
(defun query-params (env)
(and (getf env :query-string)
(quri:url-decode-params (getf env :query-string))))
(defun json-body (env)
(getf env :json-body))
(defun remote-addr (env)
(getf env :remote-addr))
;;; ROUTING
(defun app (env)
(handle-request env))
(defun handle-request (env)
(log-request env)
(setf (getf env :json-body) (read-json-request env))
(route-request env))
(defun log-request (env)
(format t "~a at ~a from ~a ~%"
(request-method env)
(path-info env)
(remote-addr env)))
(defun read-json-request (env)
(if (string= "application/json" (content-type env))
(jzon:parse (raw-body env))
(make-hash-table :test 'equal)))
(defun route-request (env)
(let* ((routes (case (request-method env)
(:get *get-routes*)
(:post *post-routes*)
(:options *options-routes*)
(t '())))
(path (path-info env)))
(loop for route in routes do
(multiple-value-bind (match regs) (cl-ppcre:scan-to-strings (car route) path)
(if match
(return (funcall (cdr route) regs env))))
finally (return (route-not-found path env)))))
;;; RESPONSES
(defvar +cors-headers+ '(:Access-Control-Allow-Origin "*"
:Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
:Access-Control-Allow-Headers "X-Requested-With, Content-Type, Authorization"))
(defun text-response (content)
`(200 (:content-type "text/plain") (,content)))
(defun json-response (alist &optional (http-code 200) (headers '()))
(list http-code
(append headers +cors-headers+ '(:content-type "application/json"))
(list (jzon:stringify (alex:alist-hash-table alist)))))
(defun json-error (code message &optional (http-code 400) (headers '()))
(json-response
`(("errcode" . ,code)
("error" . ,message))
http-code headers))
(defun route-not-found (path env)
(json-error :m_not_found "no path" 404))
(defun server-error (message)
(json-error :m_unknown message 500))
;; Authorization
(defvar *auth-session* (make-hash-table :test 'equal))
(defun auth-json (env)
(gethash "auth" (getf env :json-body)))
(defstruct auth-flow
id
completed
completed-stages ;; list of completed stages
possible-stages) ;; list of lists of possible stages
(defun registration-auth-flow (id)
(make-auth-flow
:id id
:possible-stages '(("m.login.dummy"))))
(defun login-auth-flow (id)
(make-auth-flow
:id id
:possible-stages '(("m.login.password"))))
(defun auth-flow-alist (flow &optional (params (make-hash-table)))
`(("flows" .
,(coerce
(mapcar (lambda (f) (alex:alist-hash-table `(("stages" . ,f)))) (auth-flow-possible-stages flow))
'vector))
("params" . ,params)
("session" . ,(auth-flow-id flow))))
(defmacro with-user-interactive-auth (env-var reg-var &rest body)
`(or (intercept-unfinished-auth ,env-var ,reg-var)
(progn ,@body)))
(defun intercept-unfinished-auth (env &optional reg)
(let ((auth-json (auth-json env)))
(if auth-json
(let* ((session-id (gethash "session" auth-json))
(session (gethash session-id *auth-session*)))
(continue-unfinished-auth auth-json session))
(start-new-auth reg))))
(defun continue-unfinished-auth (auth-json session)
(let* ((request-auth-stage (gethash "type" auth-json))
(expected-next (and session (expected-next-stages session)))
(valid? (member request-auth-stage expected-next :test 'equal)))
(format t "~a ~a ~a ~%" request-auth-stage expected-next valid?)
(if valid?
(multiple-value-bind (success? repeat? result) (do-auth-stage request-auth-stage auth-json session)
(if success?
(nconc (auth-flow-completed-stages session) (list request-auth-stage)))
(cond
( ;; success and final stage
(and success? (completed-auth-flow? session))
(remhash (auth-flow-id session) *auth-session*)
nil)
( ;; success and more to do
success?
(json-response (auth-flow-alist session)) 401)
( ;; fail but let's try again
(and (not success?) repeat?)
(json-response (append result (auth-flow-alist session)) 401))
( ;; fail and we're done here
(not (or success? repeat?))
(remhash (auth-flow-id session) *auth-session*)
(json-response result 400))))
(json-error :m_unauthorized "invalid auth stage"))))
(defun do-auth-stage (auth-stage auth-json auth-flow)
(cond
((equal auth-stage "m.login.dummy") (values t nil nil))))
(defun completed-auth-flow? (auth-flow)
(member (auth-flow-completed-stages auth-flow) (auth-flow-possible-stages auth-flow)) :test 'equal)
(defun expected-next-stages (auth-flow)
(with-slots (completed-stages possible-stages) auth-flow
(let ((remaining-stages possible-stages))
(dolist (completed-stage completed-stages)
(setq remaining-stages
(mapcar (lambda (stages)
(if (equal (car stages) completed-stage)
(cdr stages)
nil))
remaining-stages)))
(setq remaining-stages (mapcar #'car remaining-stages))
(remove nil remaining-stages))))
(defun start-new-auth (reg)
(let* ((session-id (write-to-string (uuid:make-v4-uuid)))
(this-flow (if reg
(registration-auth-flow session-id)
(login-auth-flow session-id))))
(setf (gethash session-id *auth-session*) this-flow)
(json-response (auth-flow-alist this-flow) 401)))
(defun header-access-token (env)
(let* ((headers (headers env))
(header-value (gethash "Authorization" headers)))
(cl-ppcre:register-groups-bind (access-token) ("^Bearer (.+)$" header-value)
access-token)))
(defun access-token (env)
(let ((query-access-token (cdr (assoc "access_token" (query-params env) :test #'equalp)))
(header-access-token (header-access-token (headers env))))
(or header-access-token query-access-token)))
(defun valid-access-token? (env)
t)
(defmacro with-authorization (env-var &rest body)
`(let ((access-token (access-token ,env-var)))
(if access-token
(if (valid-access-token? access-token)
(progn ,@body)
(json-response (error-alist :m_unknown_token "unknown token") 401))
(json-response (error-alist :m_missing_token "missing token") 401))))
;; API
(defparameter *get-routes*
'(("^/.well-known/matrix/client$" . well-known-client)
("^/_matrix/client/versions$" . versions)
("^/_matrix/client/v3/needs_auth$" . need-auth)
("^/_matrix/client/v3/login$" . login-get)
("^/_matrix/client/v3/register/available$" . username-available)))
(defparameter *post-routes*
'(("^/_matrix/client/v3/register$" . register)
("^/_matrix/client/v3/login$" . login)))
(defparameter *options-routes*
(mapcar (lambda (route) (cons (car route) 'options)) (append *get-routes* *post-routes*)))
;;; GET
(defun well-known-client (path-arr env)
(json-response `(("m.homeserver" . ,(alex:alist-hash-table '(("base_url" . "https://localhost.test"))))) 200))
(defun versions (path-arr env)
(json-response '((:versions . ("v1.10" "v1.9")))))
(defun need-auth (path-arr env)
(with-authorization env
(json-response '((:message . "hello")) 200)))
(defun login-get (path-arr env)
(json-response (login-flow-password)))
(defun login-flow-password ()
`(("flows" . ,(vector (alex:alist-hash-table '(("type" . "m.login.password")))))))
(defun username-available (path-arr env)
(let ((username (cdr (assoc "username" (query-params env) :test 'equal))))
(cond
((not username) (json-error :m_invalid_username "enter a username!!" 400))
((> (length username) 100) (json-error :m_invalid_username "username too long" 400))
(t (let ((user (matrix-database:get-user username)))
(if user
(json-error :m_user_in_use "pick another username!!" 400)
(json-response '(("available" . t)))))))))
;;; OPTIONS
(defun options (path-arr env)
(json-response '() 200))
;;; POST
(defun register (path-arr env)
(with-user-interactive-auth env t
(let* ((json-body (json-body env))
(device-id (or (gethash "device_id" json-body)
(write-to-string (uuid:make-v4-uuid))))
(inhibit-login? (gethash "inhibit_login" json-body))
(initial-device-display-name (gethash "initial_device_display_name" json-body))
(password (gethash "password" json-body))
(username (gethash "username" json-body))
(new-user (matrix-database:create-user username password))
(new-device (matrix-database:create-device username device-id initial-device-display-name))
(response (list '("home_server" . "localhost.test")
`("refresh_token" . ,(getf new-device :refresh-token))
`("user_id" . ,(format nil "@~a:localhost.test" username)))))
(unless inhibit-login?
(setq response
(append response (list (cons "access_token" (getf new-device :access-token))
(cons "device_id" (getf new-device :id))))))
(json-response response))))
(defun login (path-arr env)
(with-user-interactive-auth env nil))
| 9,738 | Common Lisp | .lisp | 245 | 35.567347 | 112 | 0.664005 | DominikM/matrix | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | 36af08b7a9f489796e411eb8dd4e3f965f0c14a17c8af77e3a378edf9b4f7bfe | 44,971 | [
-1
] |
44,972 | matrix-database.lisp | DominikM_matrix/matrix-database.lisp | (defpackage :matrix-database
(:use :cl)
(:export #:create
#:drop
#:reset
#:initialize
#:get-user
#:create-user
#:authenticate-user
#:get-device
#:create-device)
(:import-from :clsql #:with-database))
(in-package :matrix-database)
(clsql:locally-enable-sql-reader-syntax)
(defvar +database-spec+
'("localhost" ; hostname
"matrix_server" ; database name
"postgres" ; username
"")) ; password
(defun create ()
(clsql:create-database +database-spec+))
(defun drop ()
(clsql:destroy-database +database-spec+))
(defun reset ()
(clsql:disconnect-pooled)
(drop)
(create)
(initialize))
(defun initialize ()
(with-database (db +database-spec+ :pool t)
(clsql:create-table 'users
'((username "varchar(100)" :primary-key)
(password "text" :not-null))
:database db)
(clsql:create-table 'devices
'((id "text" :primary-key)
(display-name "text")
(username "varchar(100)" :references users)
(access_token "text")
(refresh_token "text"))
:database db)))
(defun get-user (username)
(let* ((result (with-database (db +database-spec+ :pool t)
(clsql:select '*
:from 'users
:where [= [username] username]
:database db)))
(user (car result)))
(when user
(list :username (nth 0 user)))))
(defun create-user (username password)
(let ((hashed-password (cl-pass:hash password)))
(with-database (db +database-spec+ :pool t)
(clsql:insert-records :into 'users
:attributes '(username password)
:values (list username hashed-password)
:database db))))
(defun authenticate-user? (username password)
(with-database (db +database-spec+ :pool t)
(let* ((hashed-password (clsql:select 'password :from 'users :database db :where [= [username] username])))
(cl-pass:check-password password hashed-password))))
(defun get-device (username device-id)
(let* ((result (with-database (db +database-spec+ :pool t)
(clsql:select '*
:from 'devices
:where [and [= [username] username] [= [id] device-id]]
:database db)))
(device (car result)))
(list :id (nth 0 device)
:display-name (nth 1 device)
:username (nth 2 device)
:access-token (nth 3 device)
:refresh-token (nth 4 device))))
(defun create-device (username device-id display-name)
(let ((access-token (write-to-string (uuid:make-v4-uuid)))
(refresh-token (write-to-string (uuid:make-v4-uuid))))
(with-database (db +database-spec+ :pool t)
(clsql:insert-records :into 'devices
:attributes '(id display-name username access_token refresh_token)
:values (list device-id display-name username access-token refresh-token)
:database db))
(list :id device-id
:display-name display-name
:username username
:access-token access-token
:refresh-token refresh-token)))
(clsql:restore-sql-reader-syntax-state)
| 2,945 | Common Lisp | .lisp | 87 | 29.436782 | 111 | 0.663845 | DominikM/matrix | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | cc82bfc14b4d200d05d3d28167b38b31c87d0fa07ff7557dfecfad3d2cb835ae | 44,972 | [
-1
] |
44,973 | matrix.asd | DominikM_matrix/matrix.asd | (asdf:defsystem :matrix
:description ""
:version "0.1"
:author "Dominik Martinez"
:depends-on (:woo
:clack
:com.inuoe.jzon
:clsql-postgresql-socket3
:alexandria
:uuid
:cl-pass)
:components ((:file "matrix-database")
(:file "matrix")))
| 301 | Common Lisp | .asd | 13 | 17.076923 | 40 | 0.586806 | DominikM/matrix | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | da8dcca56f24078c11418f75ad2022b8efa9c2c663a4b68ee7227212b7b9e622 | 44,973 | [
-1
] |
44,991 | cl-concord.lisp | chise_cl-concord/cl-concord.lisp | (in-package :cl-user)
(eval-when (:execute :compile-toplevel :load-toplevel)
(require 'cl-redis))
(defpackage :concord
(:use :cl)
(:export
:default-ds
:genre
:genre-name :genre-ds
:feature :find-feature
:object :decode-object
:object-genre :object-id
:object-put :object-get
:object-adjoin
:define-object :find-object :object-spec
:object-p
:some-in-feature :intersection-in-feature :union-in-feature
:store-union-in-feature
:metadata-feature-name-p
:id-feature-name-p :decomposition-feature-name-p
:structure-feature-name-p
:relation-feature-name-p
:make-reversed-relation-feature-name
:expand-feature-name
:sequence-list-p :association-list-p
:while
:=id :=_id :=ucs))
(in-package :concord)
(defmacro while (test &body body)
`(loop while ,test do ,@body))
(defun sequence-list-p (object)
(cond ((null object))
((consp object)
(sequence-list-p (cdr object)))))
(defun association-list-p (object)
(cond ((null object))
((and (consp object)
(consp (car object)))
(association-list-p (cdr object)))))
(defvar *default-ds* nil "The default data-store of Concord.")
(defclass data-store ()
((location :initform nil :accessor ds-location)
(genres :initform (make-hash-table))
))
(defmethod ds-find-genre ((ds data-store) genre-name)
(gethash genre-name (slot-value ds 'genres)))
(defmethod ds-register-genre ((ds data-store) genre-name gobj)
(setf (gethash genre-name (slot-value ds 'genres)) gobj))
(defmethod ds-make-genre ((ds data-store) genre-name)
(let ((gobj (ds-find-genre ds genre-name)))
(unless gobj
(setq gobj (make-instance 'genre :name genre-name))
(ds-register-genre ds genre-name gobj))
gobj))
(defun default-ds ()
(unless *default-ds*
(setq *default-ds* (make-instance 'redis-ds :db-number 3)))
*default-ds*)
(defun genre (genre-name &key ds)
(unless ds
(setq ds (default-ds)))
(if (keywordp genre-name)
(setq genre-name (read-from-string (format nil "~a" genre-name))))
(ds-make-genre ds genre-name))
(defclass location ()())
(defclass redis-location (location)
((connection :accessor redis-location-connection)
(db-number :initform 0 :accessor redis-location-db-number)
))
(defmethod initialize-instance :after ((location redis-location)
&key (host #(127 0 0 1)) (port 6379) auth
(db-number 0))
(setf (redis-location-connection location)
(redis:connect :host host :port port :auth auth))
(setf (redis-location-db-number location) db-number))
(defmethod (setf redis-location-db-number) :after (db-number
(location redis-location))
(red:select db-number))
(defclass redis-ds (data-store)())
(defmethod initialize-instance :after ((ds redis-ds)
&key (host #(127 0 0 1)) (port 6379) auth
(db-number 0))
(setf (ds-location ds)
(make-instance 'redis-location
:host host :port port :auth auth
:db-number db-number)))
(defmethod redis-ds-host ((ds redis-ds))
(redis::conn-host (redis-location-connection (ds-location ds))))
(defmethod redis-ds-port ((ds redis-ds))
(redis::conn-port (redis-location-connection (ds-location ds))))
(defmethod redis-ds-auth ((ds redis-ds))
(redis::conn-auth (redis-location-connection (ds-location ds))))
(defmethod ds-get-atom ((ds redis-ds) key &optional default-value)
(let ((ret (red:get key)))
(if ret
(read-from-string ret)
default-value)))
(defmethod ds-set-atom ((ds redis-ds) key value)
(when (string= (red:set key (format nil "~S" value)) "OK")
value))
(defmethod ds-del ((ds redis-ds) key)
(red:del key))
(defmethod ds-rpush ((ds redis-ds) key value)
(red:rpush key value))
(defmethod ds-set-list ((ds redis-ds) key value)
(let (ret)
(red:del key)
(when (integerp (setq ret (apply #'red:rpush key
(mapcar (lambda (unit)
(format nil "~S" unit))
value))))
(values value ret))))
(defmethod ds-get-list ((ds redis-ds) key)
(mapcar #'read-from-string (red:lrange key 0 -1)))
(defmethod ds-adjoin ((ds redis-ds) key value)
(unless (string= (red:type key) "set")
(red:del key))
(red:sadd key value))
(defmethod ds-set-members ((ds redis-ds) key value)
(let (ret)
(red:del key)
(cond ((null value)
(ds-set-atom ds key value)
)
(t
(when (integerp (setq ret (apply #'red:sadd key
(mapcar (lambda (unit)
(format nil "~S" unit))
value))))
(values value ret))
))))
(defmethod ds-get-members ((ds redis-ds) key)
(mapcar #'read-from-string (red:smembers key)))
(defmethod ds-intersection ((ds redis-ds) &rest keys)
(mapcar #'read-from-string (apply #'red:sinter keys)))
(defmethod ds-union ((ds redis-ds) &rest keys)
(mapcar #'read-from-string (apply #'red:sunion keys)))
(defmethod ds-store-union ((ds redis-ds) dest-key &rest keys)
(apply #'red:sunionstore dest-key keys))
(defmethod ds-get ((ds redis-ds) key &optional default-value)
(cond ((string= (red:type key) "list")
(ds-get-list ds key)
)
((string= (red:type key) "set")
(ds-get-members ds key)
)
(t
(ds-get-atom ds key default-value)
)))
(defmethod ds-get-object-feature-names ((ds redis-ds) genre-name id
&key (require-system-features nil))
(let ((pat (format nil "~(~a~):obj:~a;" genre-name id))
len fname dest)
(setq len (length pat))
(dolist (key (red:keys (format nil "~a*" pat)))
(setq fname (subseq key len))
(when (or require-system-features
(and (not (eq (search "$_" fname) 0))
(not (eq (search "=_" fname) 0))))
(setq dest (cons fname dest))))
dest))
(defmethod ds-get-object-spec ((ds redis-ds) genre-name id)
(let ((pat (format nil "~(~a~):obj:~a;" genre-name id))
len)
(setq len (length pat))
(mapcar (lambda (key)
(cons (read-from-string (subseq key len))
(ds-get ds key)))
(red:keys (format nil "~a*" pat)))))
(defmethod ds-some-in-feature ((ds redis-ds) func genre-name feature-name)
(let ((pat (format nil "~(~a~):obj:*;~a" genre-name feature-name)))
(some func (red:keys pat))))
(defvar *ideographic-structure-feature-hash*
(make-hash-table :test 'equal))
(defun some-in-feature (func feature-name &key genre ds)
(unless genre
(setq genre 'default))
(unless ds
(setq ds *default-ds*))
(let (pos end id obj ret)
(cond
((or (eq feature-name 'ideographic-structure)
(equal feature-name "ideographic-structure"))
(ds-some-in-feature
ds
(lambda (key)
(setq end (position #\; key :from-end t))
(setq pos (position #\: key :from-end t :end end))
(setq id (read-from-string (subseq key (1+ pos) end)))
(setq obj (object genre id :ds ds))
(setq ret (gethash
obj
*ideographic-structure-feature-hash*
'unload))
(if (eq ret 'unload)
(setq ret (ds-get ds key)))
(funcall func obj ret))
genre feature-name)
)
(t
(ds-some-in-feature
ds
(lambda (key)
(setq end (position #\; key :from-end t))
(setq pos (position #\: key :from-end t :end end))
(setq id (read-from-string (subseq key (1+ pos) end)))
(funcall func
(object genre id :ds ds)
(ds-get ds key)))
genre feature-name)
))))
(defun intersection-in-feature (feature-name &rest objects)
(let (genre ds)
(when (and (object-p (car objects))
(setq genre (object-genre (car objects)))
(setq ds (genre-ds genre)))
(apply #'ds-intersection
ds (mapcar (lambda (obj)
(format nil "~a:obj:~a;~a"
(genre-name genre)
(object-id obj)
feature-name))
objects)))))
(defun union-in-feature (feature-name &rest objects)
(let (genre ds)
(when (and (object-p (car objects))
(setq genre (object-genre (car objects)))
(setq ds (genre-ds genre)))
(apply #'ds-union
ds (mapcar (lambda (obj)
(format nil "~a:obj:~a;~a"
(genre-name genre)
(object-id obj)
feature-name))
objects)))))
(defclass genre ()
((name :accessor genre-name :initform 'default :initarg :name)
(ds :accessor genre-ds :initarg :ds)
(objects :initform (make-hash-table))))
(defmethod initialize-instance :after ((g genre) &key (ds nil))
(unless ds
(setq ds (default-ds)))
(setf (slot-value g 'ds) ds)
(ds-register-genre ds (slot-value g 'name) g))
(defmethod genre-find-object ((g genre) id)
(gethash id (slot-value g 'objects)))
(defmethod genre-register-object ((g genre) id obj)
(setf (gethash id (slot-value g 'objects)) obj))
(defmethod genre-make-object ((g genre) id)
(let ((obj (genre-find-object g id)))
(unless obj
(setq obj (make-instance 'object :id id :genre g))
(genre-register-object g id obj))
obj))
(defmethod generate-object-id ((g genre))
(let* ((next-id (format nil "~a:sys:next-id" (genre-name g)))
(ret (ds-get-atom (genre-ds g) next-id
(if (eq (genre-name g) 'character)
#xF0000
0)))
status)
(setq status (red:set next-id (1+ ret)))
(if (string= status "OK")
ret)))
(defun object (genre-name id &key ds)
(genre-make-object (genre genre-name :ds ds) id))
(defun decode-object (id-feature id &key genre)
(cond ((null genre)
(setq genre (genre :default))
)
((symbolp genre)
(setq genre (genre genre))
))
(let ((index (format nil "~(~a~):idx:~a;~(~a~)"
(genre-name genre) id-feature id)))
(ds-get-atom (genre-ds genre) index)))
(defclass object ()
((genre :accessor object-genre :initarg :genre)
(id :accessor object-id :initarg :id)))
(defmethod initialize-instance :after ((obj object) &key (genre nil)(id nil)
(ds nil))
(let (gobj genre-name)
(setq gobj
(cond (genre
(cond ((symbolp genre)
(setq genre-name genre)
(genre genre-name :ds ds)
)
(t genre))
)
(t
(ds-make-genre (or ds *default-ds*) 'default)
)))
(setf (object-genre obj) gobj)
(unless id
(setq id (generate-object-id gobj)))
(setf (object-id obj) id)
(genre-register-object gobj id obj)
(object-put obj '=_id id)))
(defun object-p (obj)
(typep obj 'object))
(defmethod print-object ((obj object) out)
(format out "#.(concord:object :~(~a~) ~a)"
(genre-name (object-genre obj))
(let ((id (object-id obj)))
(if (symbolp id)
(format nil "'~a" id)
id))))
(defun metadata-feature-name-p (feature-name)
(if (symbolp feature-name)
(setq feature-name (symbol-name feature-name)))
(search "*" feature-name))
(defun id-feature-name-p (feature-name)
(and (not (metadata-feature-name-p feature-name))
(progn
(if (symbolp feature-name)
(setq feature-name (format nil "~a" feature-name)))
(eql (elt feature-name 0) #\=))
(not (let ((pos (search "decomposition" feature-name)))
(and pos
(or (= pos 1)
(and (= pos 2)
(eql (elt feature-name 1) #\>))))))))
(defun structure-feature-name-p (feature-name)
(and (not (metadata-feature-name-p feature-name))
(progn
(if (symbolp feature-name)
(setq feature-name (format nil "~a" feature-name)))
(eql (search "ideographic-structure" feature-name) 0))))
(defun decomposition-feature-name-p (feature-name)
(and (not (metadata-feature-name-p feature-name))
(progn
(if (symbolp feature-name)
(setq feature-name (format nil "~a" feature-name)))
(eql (search "=decomposition" feature-name) 0))))
(defun products-feature-name-p (feature-name)
(and (not (metadata-feature-name-p feature-name))
(progn
(if (symbolp feature-name)
(setq feature-name (format nil "~a" feature-name)))
(eql (search "ideographic-products" feature-name) 0))))
(defun relation-feature-name-p (feature-name)
(and (not (metadata-feature-name-p feature-name))
(progn
(if (symbolp feature-name)
(setq feature-name (format nil "~a" feature-name)))
(or (eql (search "<-" feature-name) 0)
(eql (search "->" feature-name) 0)))))
(defun make-reversed-relation-feature-name (feature-name)
(and (not (metadata-feature-name-p feature-name))
(progn
(if (symbolp feature-name)
(setq feature-name (format nil "~a" feature-name)))
(cond ((eql (search "<-" feature-name) 0)
(read-from-string
(format nil "->~a"
(subseq feature-name 2)))
)
((eql (search "->" feature-name) 0)
(read-from-string
(format nil "<-~a"
(subseq feature-name 2)))
)))))
(defun expand-feature-name (feature domain)
(if domain
(format nil "~a@~a" feature domain)
feature))
(defun feature (feature-name &key ds)
(object :feature feature-name :ds ds))
(defun find-feature (feature-name)
(genre-find-object (genre :feature) feature-name))
(defun find-object (genre object-spec)
(let (ret)
(if (find-if (lambda (feature-pair)
(and (id-feature-name-p (car feature-pair))
(setq ret (decode-object (car feature-pair)
(cdr feature-pair)
:genre genre))))
object-spec)
ret)))
(defun define-object (genre object-spec &key id)
(if (symbolp genre)
(setq genre (genre (or genre 'default))))
(unless id
(setq id (cdr (assoc '=_id object-spec))))
(let (ret obj)
(unless id
(when (setq ret (assoc '=id object-spec))
(setq id (cdr ret))))
(unless id
(when (eql (genre-name genre) 'character)
(setq id (cdr (assoc '=ucs object-spec)))))
(cond (id
(setq obj (genre-make-object genre id))
)
((setq obj (find-object genre object-spec))
)
((setq id (generate-object-id genre))
(setq obj (genre-make-object genre id))
))
(when obj
(dolist (feature-pair object-spec)
(object-put obj (car feature-pair)(cdr feature-pair))))
obj))
(defun normalize-object-representation (object-rep &key genre ds)
(cond
((symbolp object-rep)
(let ((name (format nil "~a" object-rep)))
(if (and (eql (aref name 0) #\?)
(= (length name) 2))
(aref name 1)
object-rep))
)
((association-list-p object-rep)
(if genre
(or (find-object genre object-rep)
(if (some (lambda (pair)
(id-feature-name-p (car pair)))
object-rep)
(define-object genre object-rep)
object-rep))
(let* ((ucs (cdr (assoc '=ucs object-rep)))
(obj (find-object 'character object-rep)))
(cond (obj
(if (and (integerp (object-id obj))
(< (object-id obj) #xF0000))
(code-char (object-id obj))
obj)
)
(ucs
(code-char ucs)
)
((some (lambda (pair)
(id-feature-name-p (car pair)))
object-rep)
(define-object 'character object-rep)
)
(t
object-rep)
)))
)
((and (consp object-rep)
(symbolp (car object-rep))
(association-list-p (nth 1 object-rep)))
(define-object (genre (car object-rep) :ds ds)
(nth 1 object-rep))
)
(t
object-rep)))
(defmethod object-put ((obj object) feature value)
(let* ((genre (object-genre obj))
(ds (genre-ds genre))
(key (format nil "~a:obj:~a;~a"
(genre-name genre)
(object-id obj)
feature))
index rep-list rev-feature rev-key)
(cond ((id-feature-name-p feature)
(setq index (format nil "~a:idx:~a;~a"
(genre-name genre) feature value))
(when (ds-set-atom ds key value)
(when (ds-set-atom ds index obj)
value))
)
((decomposition-feature-name-p feature)
(setq rep-list (mapcar #'normalize-object-representation
value))
(ds-set-list ds key rep-list)
)
((structure-feature-name-p feature)
(setq rep-list (mapcar #'normalize-object-representation
value))
(if (or (eq feature 'ideographic-structure)
(equal feature "ideographic-structure"))
(setf (gethash obj *ideographic-structure-feature-hash*)
rep-list))
(ds-set-list ds key rep-list)
)
((products-feature-name-p feature)
(setq rep-list (mapcar #'normalize-object-representation
value))
(ds-set-members ds key rep-list)
)
((setq rev-feature (make-reversed-relation-feature-name feature))
(setq rep-list (mapcar #'normalize-object-representation
value))
(dolist (rev-item rep-list)
(cond ((object-p rev-item)
(setq rev-key (format nil "~a:obj:~a;~a"
(genre-name (object-genre rev-item))
(object-id rev-item)
rev-feature))
(unless (member obj (ds-get-list ds rev-key))
(ds-rpush ds rev-key obj))
)
((characterp rev-item)
(setq rev-key (format nil "character:obj:~a;~a"
(char-code rev-item)
rev-feature))
(unless (member obj (ds-get-list ds rev-key))
(ds-rpush ds rev-key obj))
)))
(ds-set-list ds key rep-list)
)
((and value (sequence-list-p value))
(ds-set-list ds key value)
)
(t
(ds-set-atom ds key value)
))))
(defmethod object-adjoin ((obj object) feature item)
(if (products-feature-name-p feature)
(let* ((genre (object-genre obj))
(ds (genre-ds genre))
(key (format nil "~a:obj:~a;~a"
(genre-name genre)
(object-id obj)
feature)))
(ds-adjoin ds key (normalize-object-representation item)))
(let ((ret (object-get obj feature)))
(unless (member obj ret)
(object-put obj feature (cons obj ret))))))
(defmethod store-union-in-feature (feature-name (dest-obj object) &rest objects)
(let (genre ds)
(setq genre (object-genre dest-obj)
ds (genre-ds genre))
(apply #'ds-store-union
ds
(format nil "~a:obj:~a;~a"
(genre-name genre)
(object-id dest-obj)
feature-name)
(mapcar (lambda (obj)
(format nil "~a:obj:~a;~a"
(genre-name genre)
(if (characterp obj)
(char-code obj)
(object-id obj))
feature-name))
objects))))
(defmethod object-get ((obj object) feature &optional default-value
&key (recursive nil))
(let* ((genre (object-genre obj))
(key (format nil "~a:obj:~a;~a"
(genre-name genre)
(object-id obj)
feature))
(unbound (gensym))
ret)
(cond ((or (eq feature 'ideographic-structure)
(equal feature "ideographic-structure"))
(setq ret (gethash
obj
*ideographic-structure-feature-hash*
'unload))
(cond
((eq ret 'unload)
(setq ret
(if (string= (red:type key) "list")
(ds-get-list (genre-ds genre) key)
(ds-get-atom (genre-ds genre) key)))
(setf (gethash obj *ideographic-structure-feature-hash*)
ret)
ret)
(t
ret))
)
((string= (red:type key) "list")
(ds-get-list (genre-ds genre) key)
)
((string= (red:type key) "set")
(ds-get-members (genre-ds genre) key)
)
(t
(setq ret (ds-get-atom (genre-ds genre) key unbound))
(if (eq ret unbound)
(or (if recursive
(or (dolist (parent (object-get obj "<-subsumptive"))
(setq ret (object-get parent feature
unbound :recursive t))
(unless (eq ret unbound)
(return ret)))
(dolist (parent (object-get obj "<-denotational"))
(setq ret (object-get parent feature
unbound :recursive t))
(unless (eq ret unbound)
(return ret)))))
default-value)
ret)))))
(defmethod object-get ((obj character) feature &optional default-value
&key (recursive nil))
(object-get (concord:object :character (char-code obj))
feature default-value
:recursive recursive))
(defmethod object-spec ((obj object) &key (require-system-features nil))
(let* ((genre (object-genre obj))
(ds (genre-ds genre))
dest)
(dolist (fname (ds-get-object-feature-names
ds (genre-name genre) (object-id obj)
:require-system-features require-system-features))
(when (or require-system-features
(not (member fname '("ideographic-products") :test #'equal)))
(setq dest (cons (cons (read-from-string fname)
(concord:object-get obj fname))
dest))))
dest))
| 19,920 | Common Lisp | .lisp | 607 | 27.917628 | 80 | 0.63652 | chise/cl-concord | 0 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | 07ce35d753ea16b21f4162e6dfbd59dd2132a60850dbc0186470b1165586f18a | 44,991 | [
-1
] |
44,992 | cl-concord.asd | chise_cl-concord/cl-concord.asd | (defsystem :cl-concord
:description "CONCORD implementation based on Common Lisp"
:version "1.0"
:author "Tomohiko Morioka"
:licence "LGPL"
:depends-on (:cl-redis)
:serial t
:components ((:file "cl-concord")))
| 224 | Common Lisp | .asd | 8 | 25.25 | 60 | 0.712963 | chise/cl-concord | 0 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:53:18 AM (Europe/Amsterdam) | 49cb7516e161d4f3130351ba96b77017f56e1a14467614ea51b072565ab96d18 | 44,992 | [
-1
] |
45,011 | registrarAbogado.lsp | SebastianTuquerrezG_Menu-Lisp-/registrarAbogado.lsp | ; Integrantes:
; - Pablo Jose Restrepo Ruiz
; - Joan Sebastian Tuquerrez Gomez
(defun registrarAbogados(nit)
(setq band 1) ; Bandera para las validaciones de los datos
(setq encontrado 0) ; Bandera para verificar si se encontro el consorcio de abogados
(setq i 0) ; Variable iteradora para el LOOP de buscar el consorcio de abogados
; Si el primer consorcio de abogados es null significa que NO se registraron los consorcios
(if (null (aref vectorConsorcios 0))
(print "No hay consorcios de abogados registrados")
(progn
; Se busca el consorcio de abogados en el vector de consorcios
(loop
(setf auxConsorcio (aref vectorConsorcios i))
(if (eq (Consorcio-nit auxConsorcio) nit)
; Si se encuentra, se piden los datos de los abogados de ese consorcio
(progn
(setq encontrado 1)
(format t "==== Abogados del Consorcio de Abogados ~S ====~%" (Consorcio-nombre auxConsorcio))
(setq j 0) ; Variable iteradora para el LOOP de agregar abogados al vector de abogados del consorcio
(loop
(format t "----Datos Abogado: ~d----~%" (+ j 1))
(setq abogado (make-Abogado)) ; Estructura de abogado
; Ingresar Numero de Tarjeta Profesional del Abogado
(loop
(print "Digite el numero de tarjeta profesional del abogado:")
(setf (Abogado-numero_tarjeta abogado) (read))
(if (and (integerp (Abogado-numero_tarjeta abogado))
(<= (Abogado-numero_tarjeta abogado) 255))
(setq band 1) ; Si el tipo de dato es entero y <= 255, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un numero entero valido (<= 255) para el número de tarjeta profesional...~%")))
(when (= band 1) (return)))
; Ingresar Nombre del Abogado
(loop
(print "Digite el nombre del abogado:")
(setf (Abogado-nombre abogado) (read-line))
(if (and (stringp (Abogado-nombre abogado))
(not (some #'digit-char-p (Abogado-nombre abogado))))
(setq band 1) ; Si el tipo de dato es una cadena y no contiene números, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un nombre valido (solo letras)...~%")))
(when (= band 1) (return)))
; Ingresar Apellido del Abogado
(loop
(print "Digite el apellido del abogado:")
(setf (Abogado-apellido abogado) (read-line))
(if (and (stringp (Abogado-apellido abogado))
(not (some #'digit-char-p (Abogado-apellido abogado))))
(setq band 1) ; Si el tipo de dato es una cadena y no contiene números, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un apellido valido (solo letras)...~%")))
(when (= band 1) (return)))
; Ingresar el Tipo de Abogado
(loop
(print "Digite el tipo de abogado (PENALISTA, CIVIL, LABORAL):")
(setf (Abogado-tipo abogado) (read))
(if (or (string= (Abogado-tipo abogado) "PENALISTA")
(string= (Abogado-tipo abogado) "CIVIL")
(string= (Abogado-tipo abogado) "LABORAL"))
(setq band 1) ; Si el tipo de abogado es válido, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un tipo de abogado valido...~%")))
(when (= band 1) (return)))
; Registrar el abogado en el vector de abogados del consorcio
(setf (aref (Consorcio-vectorAbogados auxConsorcio) j) abogado)
(setq j (+ j 1))
(when (> j 2) (return)))
)
)
; Incrementa el indice para buscar el siguiente consorcio de abogados
(setq i (+ i 1))
(when (> i 1) (return)))
; Si el consorcio de abogados no se encuentra, muestra un mensaje de error
(if (= encontrado 0)
(format t "El consorcio de abogados con NIT: ~d no se encuentra registrado~%" nit)
)
)
)
)
| 5,225 | Common Lisp | .l | 76 | 43.065789 | 163 | 0.471576 | SebastianTuquerrezG/Menu-Lisp- | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:26 AM (Europe/Amsterdam) | 7c1dc81f0670b03172ae97a45481d0f262076a3abf4dc000f8584c7d0b2049dd | 45,011 | [
-1
] |
45,012 | registrarConsorcio.lsp | SebastianTuquerrezG_Menu-Lisp-/registrarConsorcio.lsp | ; Integrantes:
; - Pablo Jose Restrepo Ruiz
; - Joan Sebastian Tuquerrez Gomez
; Función para registrar consorcios de abogados
(defun registrarConsorcios()
(setq band 1) ; Bandera para las validaciones de los datos
(setq i 0) ; Variable iteradora para el LOOP de buscar el consorcio de abogados
(print "= El programa guardara 2 consorcios de abogados =")
(loop
(format t "~%")
(format t "---- Datos Consorcio de Abogados: ~d ----~%" (+ i 1))
(setq consorcio (make-Consorcio)) ; Estructura de consorcio de abogados
; Ingresar NIT del Consorcio de Abogados
(loop
(print "Digite el NIT del Consorcio de Abogados:")
(setf (Consorcio-nit consorcio) (read))
(if (and (integerp (Consorcio-nit consorcio)) (<= (Consorcio-nit consorcio) 255) (> (Consorcio-nit consorcio) 0))
(setq band 1) ; Si el tipo de dato es entero positivo y <= 255, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un NIT valido (entero positivo y <= 255)...~%")))
(when (= band 1) (return)))
; Ingresar Nombre del Consorcio de Abogados
(loop
(print "Digite el nombre del Consorcio de Abogados:")
(setf (Consorcio-nombre consorcio) (read-line))
(if (and (stringp (Consorcio-nombre consorcio))
(not (some #'digit-char-p (Consorcio-nombre consorcio))))
(setq band 1) ; Si el tipo de dato es una cadena y no contiene números, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un nombre valido (solo letras)...~%")))
(when (= band 1) (return)))
; Ingresar el tipo de consorcio de abogados
(loop
(print "Digite el tipo de consorcio de abogados (NACIONAL o INTERNACIONAL):")
(setf (Consorcio-tipo consorcio) (read))
(if (or (string= (Consorcio-tipo consorcio) "NACIONAL") (string= (Consorcio-tipo consorcio) "INTERNACIONAL"))
(setq band 1) ; Si el tipo de dato es valido, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un tipo de consorcio valido...~%")))
(when (= band 1) (return)))
; Inicializar el vector de abogados
(setf vectorAbogadosConsorcio (make-array 3))
(setf (Consorcio-vectorAbogados consorcio) vectorAbogadosConsorcio)
; Registrar el consorcio de abogados en el vector
(setf (aref vectorConsorcios i) consorcio)
(setq i (+ i 1))
(when (> i 1) (return))
)
)
| 2,478 | Common Lisp | .l | 46 | 46.282609 | 126 | 0.649668 | SebastianTuquerrezG/Menu-Lisp- | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:26 AM (Europe/Amsterdam) | f3fed5bc5074507bc1dac6e673e4076f52a9995be1816a00cba2422db4bb6328 | 45,012 | [
-1
] |
45,013 | BuscarConsorcioAbogado.lsp | SebastianTuquerrezG_Menu-Lisp-/BuscarConsorcioAbogado.lsp | ; Integrantes:
; - Pablo Jose Restrepo Ruiz
; - Joan Sebastian Tuquerrez Gomez
; Funcion para buscar un Abogado por su id en un Consorcio por su nit
(defun BuscarConsorcioAbogado(nit num_tarjeta)
(setq encontrado 0) ; Bandera para verificar si se encontro
(setq i 0) ; Recorrer el vector de Consorcios preguntando si el nit coincide
; Si el primer Consorcio es null significa que NO se registraron los dos Consorcios
(if (null (aref vectorConsorcios 0))
(progn (print "No hay Consorcios registrados"))
(progn
(loop
(setf auxConsorcio (aref vectorConsorcios i))
(if (eq (Consorcio-nit auxConsorcio) nit)
; Si coincide entonces la bandera se pone en 1 y se busca el Abogado
(progn
(setq encontrado 1)
; Si el primer Abogado no tiene datos entonces no se han ingresado los Abogados de ese Consorcio
(if (eq (aref (Consorcio-vectorAbogados auxConsorcio) 0) nil)
(format t "El Consorcio no tiene Abogados registrados...~%")
(progn
(setq j 0)
(loop
; Si el Consorcio tiene Abogados entonces se busca el Abogado por su id
(setf auxAbogado (aref (Consorcio-vectorAbogados auxConsorcio) j))
(if (eq (Abogado-numero_tarjeta auxAbogado) num_tarjeta)
(progn
; Si se encuentra el Abogado se imprimen sus datos
(setq encontrado 2)
(format t "~%")
(format t "Id del Abogado: ~d~%" (Abogado-numero_tarjeta auxAbogado))
(format t "Nombre del Abogado: ~S~%" (Abogado-nombre auxAbogado))
(format t "Apellido del Abogado: ~S~%" (Abogado-apellido auxAbogado))
(format t "Tipo del Abogado: ~S~%" (Abogado-tipo auxAbogado))
(format t "~%")
)
)
(setq j (+ j 1))
(when (> j 2) (return))
)
)
)
)
)
(setq i (+ i 1))
(when (> i 1) (return))
)
)
)
(case encontrado
(0
(format t "~%El Consorcio con nit: ~d no se encuentra registrado~%" nit)
)
(1
(format t "El Abogado con id: ~d no se encuentra registrado en el Consorcio con nit: ~d~%" num_tarjeta nit)
)
)
)
| 3,103 | Common Lisp | .l | 58 | 30.568966 | 121 | 0.43785 | SebastianTuquerrezG/Menu-Lisp- | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:26 AM (Europe/Amsterdam) | ec2a366b334694daf89b5bf7ea2daacbcfd94c807b76d2241f385629d5e00bd0 | 45,013 | [
-1
] |
45,014 | buscarConsorcio.lsp | SebastianTuquerrezG_Menu-Lisp-/buscarConsorcio.lsp | ; Integrantes:
; - Pablo Jose Restrepo Ruiz
; - Joan Sebastian Tuquerrez Gomez
; Funcion para buscar un Consorcio por su nit
(defun buscarConsorcio(nit)
(setq encontrado 0) ; Bandera para verificar si se encontro
(setq i 0) ; Recorrer el vector de Consorcios preguntando si el nit coincide
; Si el primer Consorcio es null significa que NO se registraron los dos Consorcios
(if (null (aref vectorConsorcios 0))
(progn
(print "No hay Consorcios registrados"))
(progn
(loop
(setf auxConsorcio (aref vectorConsorcios i))
(if (eq (Consorcio-nit auxConsorcio) nit)
; Si coincide entonces la bandera se pone en true y se imprimen los datos del Consorcio y sus Abogados
(progn
(setq encontrado 1)
(format t "Nit del Consorcio: ~d~%" (Consorcio-nit auxConsorcio))
(format t "Nombre del Consorcio: ~S~%" (Consorcio-nombre auxConsorcio))
(format t "Tipo del Consorcio: ~S~%" (Consorcio-tipo auxConsorcio))
; Si el primer Abogado no tiene datos entonces no se han ingresado los Abogados de ese Consorcio
(if (eq (aref (Consorcio-vectorAbogados auxConsorcio) 0) nil)
(format t "El Consorcio no tiene Abogados registrados...~%")
(progn
(setq j 0)
(loop
(format t "~%")
(format t "----Datos Abogado: ~d----~%" (+ j 1))
(setf auxAbogado (aref (Consorcio-vectorAbogados auxConsorcio) j))
(format t "Id del Abogado: ~d~%" (Abogado-numero_tarjeta auxAbogado))
(format t "Nombre del Abogado: ~S~%" (Abogado-nombre auxAbogado))
(format t "Apellido del Abogado: ~S~%" (Abogado-apellido auxAbogado))
(format t "Tipo del Abogado: ~S~%" (Abogado-tipo auxAbogado))
(format t "~%")
(setq j (+ j 1))
(when (> j 2) (return))
)
)
)
)
)
(setq i (+ i 1))
(when (> i 1) (return))
)
)
)
(if (eq encontrado 0) (format t "El Consorcio con nit: ~d no se encuentra registrado~%" nit))
)
| 2,771 | Common Lisp | .l | 49 | 34.714286 | 123 | 0.466493 | SebastianTuquerrezG/Menu-Lisp- | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:26 AM (Europe/Amsterdam) | fa6a23c16c075fa4ed4a1fc18af2dd96a3ebc429bdbdd51adc06c8041c9e4b72 | 45,014 | [
-1
] |
45,015 | menu.lsp | SebastianTuquerrezG_Menu-Lisp-/menu.lsp | ; Integrantes:
; - Pablo Jose Restrepo Ruiz
; - Joan Sebastian Tuquerrez Gomez
(load "vectoresYStructs.lsp")
(load "registrarConsorcio.lsp")
(load "registrarAbogado.lsp")
(load "buscarConsorcio.lsp")
(load "consultarPenal.lsp")
(load "BuscarConsorcioAbogado.lsp")
(crearStructConsorcio) ; Crea la estructura para los consorcios de abogados y el vector de consorcios
(crearStructAbogado) ; Crea la estructura para los abogados
(loop
(print " ===========================================")
(print " | M E N U |")
(print " ===========================================")
(format t " ~%")
(print " 1. Registrar Consorcio de Abogados ")
(print " 2. Registrar Abogado ")
(print " 3. Buscar Consorcio de Abogados por NIT ")
(print " 4. Buscar Abogado para un Consorcio Especifico")
(print " 5. Consultar numero de Abogados PENAL para un Consorcio Especifico")
(print " 6. Salir.")
(format t " ~%")
(print " Digite la opcion:")
(setq Opcion (read))
(setq band 1) ; Bandera para las validaciones de los datos: 1=true, 0=false
(case Opcion
(1 (registrarConsorcios))
(2 (progn
(loop
(print "= Registre 3 abogados por Consorcio =")
(print "Ingrese el NIT del consorcio al cual desea registrar abogados: ")
(setq nit (read))
(if (and (integerp nit) (> nit 0))
(setq band 1) ; Si el tipo de dato es entero positivo, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un NIT valido (entero positivo)...~%"))
)
(when (= band 1) (return))
)
(registrarAbogados nit)
)
)
(3 (progn
(loop
(print "Ingrese el nit del consorcio a buscar: ")
(setq nit (read))
(if (and (integerp nit) (> nit 0))
(setq band 1) ; Si el tipo de dato es entero positivo, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un NIT valido (entero positivo)...~%"))
)
(when (= band 1) (return))
)
(buscarConsorcio nit)
)
)
(4 (progn
(loop
(print "Ingrese el NIT del consorcio a buscar: ")
(setq nit (read))
(if (and (integerp nit) (> nit 0))
(progn ; Si el tipo de dato del NIT es entero positivo, entonces se pide el ID del abogado
(print "Ingrese el ID del abogado a buscar: ")
(setq num_tarjeta (read))
(if (and (integerp num_tarjeta) (> num_tarjeta 0))
(setq band 1) ; Si el tipo de dato del ID es entero positivo, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un ID valido (entero positivo)...~%"))
)
)
(progn (setq band 0) (format t "Error! Ingrese un NIT valido (entero positivo)...~%"))
)
(when (= band 1) (return))
)
(BuscarConsorcioAbogado nit num_tarjeta)
)
)
(5 (progn
(loop
(print "Ingrese el NIT del consorcio a buscar: ")
(setq nit (read))
(if (and (integerp nit) (> nit 0))
(setq band 1) ; Si el tipo de dato es entero positivo, el loop termina
(progn (setq band 0) (format t "Error! Ingrese un NIT valido (entero positivo)...~%"))
)
(when (= band 1) (return))
)
(consultarPenal nit)
)
)
)
(when (eq Opcion 6) (print "Fin del programa") (return))
)
| 4,216 | Common Lisp | .l | 91 | 31.054945 | 118 | 0.463426 | SebastianTuquerrezG/Menu-Lisp- | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:26 AM (Europe/Amsterdam) | f4eda7943191d8bd2faf5f58285767537c98419624165809e1c74692145dab94 | 45,015 | [
-1
] |
45,016 | consultarPenal.lsp | SebastianTuquerrezG_Menu-Lisp-/consultarPenal.lsp | ; Integrantes:
; - Pablo Jose Restrepo Ruiz
; - Joan Sebastian Tuquerrez Gomez
; Funcion para consultar el numero de Abogados que son de genero PENALISTA de un Consorcio especifico.
(defun consultarPenal(nit)
(setq encontrado 0) ; Bandera para verificar si se encontro
(setq i 0) ; Recorrer el vector de Consorcios preguntando si el nit coincide
; Si el primer Consorcio es null significa que NO se registraron los dos Consorcios
(if (null (aref vectorConsorcios 0))
(progn (print "No hay Consorcios registrados"))
(progn
; Comienza el primer bucle que recorre los Consorcios
(loop
; Obtiene el Consorcio actual
(setf auxConsorcio (aref vectorConsorcios i))
; Verifica si el nit del Consorcio actual coincide con el nit proporcionado
(if (eq (Consorcio-nit auxConsorcio) nit)
(progn
(setq encontrado 1)
; Verifica si el Consorcio tiene Abogados registrados
(if (eq (aref (Consorcio-vectorAbogados auxConsorcio) 0) nil)
; Si el Consorcio no tiene Abogados, imprime un mensaje
(format t "El Consorcio no tiene Abogados registrados...~%")
; Si el Consorcio tiene Abogados, comienza el segundo bucle que recorre los Abogados
(progn
(setq numPenal 0)
(setq j 0)
(loop
; Obtiene el Abogado actual
(setf auxAbogado (aref (Consorcio-vectorAbogados auxConsorcio) j))
; Verifica si el tipo del Abogado es penalista
(if (string-equal (Abogado-tipo auxAbogado) "PENALISTA")
; Si el tipo es penalista, incrementa el contador de penalistas
(setq numPenal (+ numPenal 1)))
; Incrementa el contador de Abogados
(setq j (+ j 1))
; Si se han revisado todos los Abogados, sale del bucle de Abogados
(when (>= j (length (Consorcio-vectorAbogados auxConsorcio))) (return))
)
; Si no hay Abogados penalistas, imprime un mensaje
(if (= numPenal 0)
(format t "No hay Abogados PENALISTAS en el Consorcio: ~S, con NIT: ~d~%" (Consorcio-nombre auxConsorcio) nit)
; Si los hay, imprime el numero de Abogados penalistas
(format t "Numero de Abogados PENALISTAS: ~d del Consorcio: ~S~%" numPenal (Consorcio-nombre auxConsorcio))
)
)
)
)
)
(setq i (+ i 1))
(when (>= i (length vectorConsorcios)) (return))
)
)
)
(if (eq encontrado 0) (format t "El Consorcio con nit: ~d no se encuentra registrado~%" nit))
)
| 3,412 | Common Lisp | .l | 56 | 37.875 | 147 | 0.489558 | SebastianTuquerrezG/Menu-Lisp- | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:26 AM (Europe/Amsterdam) | da0cc951fac44965c3d73553d774bc397476ab7004feef3d2cd53987a2edf14c | 45,016 | [
-1
] |
45,017 | vectoresYStructs.lsp | SebastianTuquerrezG_Menu-Lisp-/vectoresYStructs.lsp | ; Integrantes:
; - Pablo Jose Restrepo Ruiz
; - Joan Sebastian Tuquerrez Gomez
; Declaracion de la estructura de Consorcio
(defun crearStructConsorcio()
(defstruct Consorcio
nit ; Numero de identificacion tributaria del Consorcio
nombre ; Nombre del Consorcio
tipo ; Tipo de consorcio
vectorAbogados ; Vector de abogados asociados al consorcio
)
; Vector de Consorcios con capacidad para 2 Consorcios
(setf vectorConsorcios (make-array 2))
)
; Declaracion de la estructura de Abogado
(defun crearStructAbogado()
(defstruct Abogado
numero_tarjeta ; Numero de tarjeta profesional del abogado
nombre ; Nombre del abogado
apellido ; Apellido del abogado
tipo ; Tipo de abogado (PENALISTA, CIVIL, LABORAL, etc.)
)
)
| 879 | Common Lisp | .l | 23 | 32.217391 | 75 | 0.661972 | SebastianTuquerrezG/Menu-Lisp- | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:26 AM (Europe/Amsterdam) | ec2468b62fd82d0d40f5c2aa6ad6bccc26f4bdb94a3a2f9b2ea7f8741b7a0e06 | 45,017 | [
-1
] |
45,039 | uuidv7.lisp | omarjatoi_uuidv7_lisp/src/uuidv7.lisp | ;;;; This Source Code Form is subject to the terms of the Mozilla Public
;;;; License, v. 2.0. If a copy of the MPL was not distributed with this
;;;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;; 0 1 2 3
;;; 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
;;; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
;;; | unix_ts_ms |
;;; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
;;; | unix_ts_ms | ver | rand_a |
;;; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
;;; |var| rand_b |
;;; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
;;; | rand_b |
;;; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
(defpackage #:uuidv7
(:use #:alexandria
#:cl
#:local-time)
(:export #:generate
#:bytes->string
#:string->bytes))
(in-package #:uuidv7)
(alexandria:define-constant +version+ #*0111
:test #'equal
:documentation "bit vector constant for the UUID version (7 in binary)")
(alexandria:define-constant +variant+ #*10
:test #'equal
:documentation "bit vector constant for the RFC4122 variant field")
(alexandria:define-constant +bit-vector-length+ 128
:test #'equal
:documentation "bit vector length for UUIDv7 values in bits")
(alexandria:define-constant +byte-vector-length+ 16
:test #'equal
:documentation "byte vector length for UUIDv7 values in bytes")
(alexandria:define-constant +timestamp-bit-length+ 48
:test #'equal
:documentation "bit vector length for the timestamp in milliseconds")
(alexandria:define-constant +uuidv7-string-length+ 36
:test #'equal
:documentation "length of UUIDv7 string")
(defun generate ()
"Generate and return a UUIDv7 as a byte vector (16 bytes)."
(let ((unix-ts-ms (timestamp->bits (unix-epoch-in-ms)))
(rand-a (generate-random 12))
(rand-b (generate-random 62)))
(bits->bytes (concat-bits unix-ts-ms
+version+
rand-a
+variant+
rand-b))))
(defun bytes->string (bytes)
"Returns a formatted string from raw UUIDv7 bytes."
(let ((first (subseq-to-string bytes 0 4))
(second (subseq-to-string bytes 4 6))
(third (subseq-to-string bytes 6 8))
(fourth (subseq-to-string bytes 8 10))
(fifth (subseq-to-string bytes 10 16)))
(format nil "~a-~a-~a-~a-~a" first second third fourth fifth)))
(defun string->bytes (string)
"Returns raw UUIDv7 bytes from a string."
(let* ((cleaned-string (remove #\- string :test #'char=))
(byte-count (/ (length cleaned-string) 2))
(bytes (make-array byte-count :element-type '(unsigned-byte 8))))
(dotimes (i byte-count)
(setf (aref bytes i)
(parse-integer (subseq cleaned-string (* 2 i) (* 2 (1+ i))) :radix 16)))
bytes))
;; Internal helper functions (not exposed to the user).
(defun unix-epoch-in-ms ()
"Get the unix epoch timestamp in milliseconds"
(let ((time (local-time:now)))
(+ (* 1000 (local-time:timestamp-to-unix time)) ; Current epoch time is in seconds
(local-time:timestamp-millisecond time)))) ; This adds millisecond precision
(defun generate-random (n)
"Generates `n` bits worth of random bytes, returned as a bit vector."
(let ((bits (make-array n :element-type 'bit))
(bytes (generate-random-bytes (round-up-to-closest-bytes n))))
(loop for i below n
do (setf (aref bits i)
(if (logbitp (mod i 8)
(aref bytes (floor i 8)))
1 0)))
bits))
(defun round-up-to-closest-bytes (n)
(ceiling n 8))
(defun generate-random-bytes (n)
(let ((bytes (make-array n :element-type '(unsigned-byte 8))))
(loop for i below n
do (setf (aref bytes i) (random 256)))
bytes))
(defun subseq-to-string (array start end)
"Given an array of bytes, a start, and an end, returns a string containing those bytes."
(apply #'concatenate
'string
(map 'list
(lambda (x) (format nil "~2,'0X" x))
(subseq array start end))))
(defun concat-bits (&rest vectors)
"Concatenate multiple bit vectors into a unified bit vector."
(apply #'concatenate
'simple-bit-vector
(mapcar (lambda (x) (coerce x 'simple-bit-vector))
vectors)))
(defun timestamp->bits (timestamp)
"Returns the epoch timestamp as a 48 bit vector."
(let ((bits (make-array +timestamp-bit-length+
:element-type 'bit
:initial-element 0)))
(dotimes (i +timestamp-bit-length+)
(setf (aref bits (- 47 i)) (if (logbitp i timestamp) 1 0)))
bits))
(defun bits->bytes (bits)
"Converts a 128 bit vector to a 16 byte vector."
(let ((bytes (make-array +byte-vector-length+ :element-type '(unsigned-byte 8))))
(dotimes (i +byte-vector-length+)
(setf (aref bytes i)
(let* ((start (* i 8))
(end (+ start 8)))
(bits->int (subseq bits start end)))))
bytes))
(defun bits->int (bits)
"Convert a simple-bit-vector into an integer."
(let ((end (- (length bits) 1))
(reversed (reverse bits)))
(loop for i below end
sum (if (logbitp 0 (aref reversed i))
(ash 1 i)
0))))
| 5,668 | Common Lisp | .lisp | 128 | 37.46875 | 90 | 0.546821 | omarjatoi/uuidv7.lisp | 0 | 0 | 0 | MPL-2.0 | 9/19/2024, 11:53:43 AM (Europe/Amsterdam) | bfd7da35f1f6607036fb1c81d9bb360ff7efa50f1d91a2c9c9cfa4ea0c40c222 | 45,039 | [
-1
] |
45,040 | uuidv7.lisp | omarjatoi_uuidv7_lisp/t/uuidv7.lisp | ;;;; This Source Code Form is subject to the terms of the Mozilla Public
;;;; License, v. 2.0. If a copy of the MPL was not distributed with this
;;;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
(defpackage #:uuidv7-test
(:use #:cl
#:uuidv7
#:fiveam)
(:export #:run-tests))
(in-package #:uuidv7-test)
(fiveam:def-suite uuidv7-test-suite :description "Test suite for this UUIDv7 library.")
(fiveam:in-suite uuidv7-test-suite)
(fiveam:test generate-ids-and-convert
"Generate a bunch of UUIDv7 values and verify that they are unique and can be converted into
strings, and then back into bytes."
(defvar ids '())
(finishes (dotimes (_ 1000)
(let ((id (generate)))
(finishes (bytes->string id))
(finishes (string->bytes (bytes->string id)))
(push (generate) ids))))
(let ((number-of-ids (length ids))
(number-of-ids-without-duplicates (length (remove-duplicates ids))))
(is (= number-of-ids
number-of-ids-without-duplicates))))
(fiveam:test string-to-bytes-roundtrip-conversion
"Test string->bytes and bytes->string functions using example from spec."
(let* ((uuidv7-string "017F22E2-79B0-7CC3-98C4-DC0C0C07398F")
(uuidv7-bytes (string->bytes uuidv7-string)))
(is (string= uuidv7-string (bytes->string uuidv7-bytes)))))
(defun run-tests ()
(fiveam:run! 'uuidv7-test-suite))
| 1,424 | Common Lisp | .lisp | 31 | 40.451613 | 94 | 0.671717 | omarjatoi/uuidv7.lisp | 0 | 0 | 0 | MPL-2.0 | 9/19/2024, 11:53:43 AM (Europe/Amsterdam) | c46a1ed38cfb682239e2979ada1d09e23fe1821523767d678cc37d06855961db | 45,040 | [
-1
] |
45,041 | uuidv7-test.asd | omarjatoi_uuidv7_lisp/uuidv7-test.asd | ;;;; This Source Code Form is subject to the terms of the Mozilla Public
;;;; License, v. 2.0. If a copy of the MPL was not distributed with this
;;;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
(asdf:defsystem #:uuidv7-test
:author "Omar Jatoi <git@omarjatoi.com>"
:license "MPL-2.0"
:name "uuidv7-test"
:depends-on (#:uuidv7
#:fiveam)
:components ((:module "t"
:serial t
:components ((:file "uuidv7"))))
:perform (test-op (o s)
(symbol-call :uuidv7-test '#:run-tests)))
| 569 | Common Lisp | .asd | 14 | 33.928571 | 73 | 0.599278 | omarjatoi/uuidv7.lisp | 0 | 0 | 0 | MPL-2.0 | 9/19/2024, 11:53:43 AM (Europe/Amsterdam) | 12ad97dd6de47c8c783f40b9be77b4764f5214afc28abe37cbab0d58eb337ac6 | 45,041 | [
-1
] |
45,042 | uuidv7.asd | omarjatoi_uuidv7_lisp/uuidv7.asd | ;;;; This Source Code Form is subject to the terms of the Mozilla Public
;;;; License, v. 2.0. If a copy of the MPL was not distributed with this
;;;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
(asdf:defsystem #:uuidv7
:description "UUIDv7 Implementation."
:author "Omar Jatoi <git@omarjatoi.com>"
:license "MPL-2.0"
:version "0.1.0"
:bug-tracker "https://github.com/omarjatoi/uuidv7.lisp/issues"
:source-control (:git "https://github.com/omarjatoi/uuidv7.lisp.git")
:name "uuidv7"
:depends-on (#:alexandria
#:local-time)
:components ((:module "src"
:serial t
:components ((:file "uuidv7"))))
:long-description #.(uiop:read-file-string (uiop:subpathname *load-pathname* "README.md"))
:in-order-to ((test-op (test-op #:uuidv7-test))))
| 822 | Common Lisp | .asd | 18 | 40.777778 | 92 | 0.66127 | omarjatoi/uuidv7.lisp | 0 | 0 | 0 | MPL-2.0 | 9/19/2024, 11:53:43 AM (Europe/Amsterdam) | ec6c33b6ddad1099cf111a1ccc9a763feef0dc81995dc2f43d9be448ab4b2e07 | 45,042 | [
-1
] |
45,060 | illust-pp34-35.lisp | atakan_chaotic-dynamics-in-H-systems/illust-pp34-35.lisp | ;; producing the data for the illustration on pp.34-35
;; see README for details
(defvar H 0.62)
(defun drift (dt)
"Evolution with kinetic energy (positions change)"
)
(defun kick (dt)
"Evolution with potential energy (momenta change)"
)
| 249 | Common Lisp | .lisp | 9 | 25.444444 | 54 | 0.742616 | atakan/chaotic-dynamics-in-H-systems | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:43 AM (Europe/Amsterdam) | 54cb66b8267a0f3fda461228ed050e6461c891e6572f8a9444d9a3402ca587fa | 45,060 | [
-1
] |
45,062 | symb-diff.lisp | atakan_chaotic-dynamics-in-H-systems/symb-diff.lisp | (defun variablep (e)
"this requires (variablep 'x), i.e., x needs to be quoted"
(symbolp e))
(defmacro varp2 (e)
"this allows (varp2 x) even when x is unbound"
(symbolp e))
| 182 | Common Lisp | .lisp | 6 | 27.833333 | 60 | 0.68 | atakan/chaotic-dynamics-in-H-systems | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:53:43 AM (Europe/Amsterdam) | 28e481a57863f578798866d684fb367364c54ce0be5f9a9bb0a9336fdba7dcfe | 45,062 | [
-1
] |