One recurring complaint is that nobody talks about code on /prog/. So everyone write go and write some code, any code, that does something, anything, and post it. A small explanation wouldn't go amiss either.
;; To /prog/, love that guy who uses R6RS
;;
;; So, I was using guile earlier, and I decided I wanted to add
;; generalized `set!` (which guile supports through both SRFI 17 and
;; it's own `make-procedure-with-setter`) to my R6RS
;; code. Unfortunately, there is no good way to implement SRFI 17 in
;; portable R6RS unless you use lexically hidden "tags" to access the
;; setters of procedures. Which is both ugly, and a stupid
;; implementation strategy.
;;
;; Instead I decided to settle for creating a special form for
;; defining getter/setters. The error handling isn't there yet, but
;; I'll probably fix that at some point.
;;
;; Usage:
;; > (import (generalized-set))
;; > (define-record-type cell
;; (fields (mutable var)))
;; > (define-getter/setter cell-ref cell-var cell-var-set!)
;; > (define c (make-cell 3))
;; > (cell-ref c)
;; 3
;; > (set! (cell-ref c) 9)
;; > (cell-ref c)
;; 9
;;
;; Tested on Ikarus and Mosh.
;; I see no reason why it wouldn't work on Racket though.
In this game, two players sit in front of a pile of stones. They take turns, each removing a set amount of stones (up to a specified maximum). The person who removes the last stone(s) wins. Half of the code is redundant as I don’t use a variable to track which player’s move it is. Primarily because I didn’t know how to.
If you are lonely and want to play against the ‘computer’ change the second choice variable to choice=random.randint(1,max)be sure to import random, if you do
def nims(pile, max):
while pile>0:
choice=input("How many Stones do you want to remove, P1?")
while choice not in range(1,max+1):
choice=input("You have made an invalid selection P1.\
Please chose again.")
pile=pile-choice
print pile
if pile<=0:
print 'player 1 wins!'
break
choice=input("Player 2: How many Stones do you want to remove?")
while choice not in range(1,max+1):
choice=input("You have made an invalid selection P2.\
Please chose again.")
pile=pile-choice
print pile
if pile<=0:
print 'game over, player 2 is the winner!'
x=input('How big is the pile?\n')
y=input('How many stones can one person take each time?\n')
print 'Pile set to', x, ', maximum stone number set to', y,'!'
>>19
if you like I can re-write it using list comprehensions
Name:
Anonymous2011-03-05 17:09
Putting cpuhog in check;
# !/bin/bash
#
function get_load() {
# gets cpu load from last minute
# man uptime
load=$(uptime | cut -d, -f3 | grep -o "[0-9.]\{4\}$")
echo $load
}
AVG_LOAD=$(get_load)
# if the avg load is greater than or equal to 5%
# then show us all processes using 5% or more of cpu
MAX_LOAD=$(echo "$AVG_LOAD/5" | bc)
if (($MAX_LOAD >= 1)); then
printf "\nCurrent load average: $AVG_LOAD\n";
FAT_LOAD=$(ps k +pcpu o pcpu,user,uid,pid,ppid,tty,stime,cmd -A | grep "^.[5-9]\.[0-9]\{1\}*")
printf "$FAT_LOAD\n"
if [[ $1 = "-k" ]]; then
# for each line delimted by newline get pid and uid or user
# if uid or user is not root
# kill pid
echo "Kill option passed"
fi;
fi;
How an expert newfag adds users;
#!/bin/bash
#
# lrn2bash
# ########
# prototype useradd using only primitive
# utilities and bash builtins
#
# add a new user account where uid is
# incremented and gid defaults to users
# group.
#
# overview
# ########
# this script takes 1 argument; user name
# this script takes 3 options; help, verbose, test
#
# the user id and group id is read from passwd
#
# each test will loop and read new input if fail
#
# the script will not write or execute any commands
# until all tests have passed
#
# rules/tests
# ###########
#
# the user name must be at least 3 characters in
# length and only alaphanumeric characters
# the user name must not be in use
#
# password must be at least 6 characters in length
# password must be verified
#
USERS=`ls /home`
#USERNAME=`for USER in $USERS; do echo $USER; done;`
username=$1
USERNAME_VALID=''
while [[ -z "$USERNAME_VALID" ]]; do
if [ `echo "$username" | grep "$USERS"` ]; then
echo -en "User exits.\nEnter new username: "
read username
elif [ `echo ${#username}` -le 1 ]; then
echo -en "Need at least 2 characters.\nEnter new username: "
read username
elif [[ $username != [[:alpha:]][[:alnum:]]* ]]; then
echo -en "Alpha numeric characters only. \nEnter new username: "
read username
else
USERNAME_VALID=1
echo "Your new user name: $username"
fi;
done;
PASSWORD_VALID=''
echo -en "\nCreate new password: "
read -es password
while [[ -z "$PASSWORD_VALID" ]]; do
if [[ ${#password} -lt 7 ]]; then
echo -en "Password must be at least 6 characters.\nEnter new password: "
read -es password
else
echo -en "Verify new password: "
read -es verify_password
if [[ "$password" = "$verify_password" ]]; then
PASSWORD_VALID=1
fi;
fi;
done;
GROUP_USERS_STRING=`cat /etc/group | grep "^users*"`
while IFS=: read USR PASSWD GID; do
gid=$GID
done <<< $GROUP_USERS_STRING
PASSWD_PREVIOUS_UID=tail etc/passwd -n10 | grep "\:10[0-9]\{2\}\:10[0-9]\{2\}\:" | tail -n1
while IFS=: read USR PASSWD UID; do
uid=$(($UID+1))
done <<< $PASSWD_PREVIOUS_UID
# still need to read comment, set homepath, and define shell
# define passwd string
# encrypt password with crypt
# define shadow string
# chmod shadow (and passwd if necessary)
# append each string appropriately
# i.e. /etc/passwd
# /etc/shadow
# /etc/group
# chmod files with original permissions
# cp /etc/skel to /home/{$username}
#
class m:
def __init__(self):
q=12000
x=0
while True:
x+=1
y=x%x*2
z=x+y
qp=' '+str(q)
if x % 1000 == 0:
q=q-x
qp=qp+' '+qp.replace('3','three')
print x,y,z,' ',x,z,y,' ',z,qp
def replacenumbers(self,numberstring)
if __name__=="__main__":
m1=m()
Name:
Anonymous2011-03-05 17:52
A bit of CoffeeScript I'm working on, trying to distort the language without touching the compiler.
# Arbitrary iterator over a sequence using a stepper generator
# `seq' is any list.
# `stepper' is a generator that returns either an items array or $break
# `fn' is the function to call in each item
# `apply' is just a functional version of JavaScript's Function.apply
(defun iter: (seq, stepper, fn) ->
(letb (step = (stepper seq)) ->
(until (eq (call step), $break)
(apply fn, step.item))))
`until' uses FIOC, so I'm going to replace this by something else later on
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :username
t.string :password
t.string :salt
t.timestamps
end
end
def self.down
drop_table :users
end
end
# Script For Creating Accounts, nust learn how to graphically implement this.
>> users = User.find(:all)
>> user = User.create(:username => "Tom", :password => "wertycool")
>>users = User.find(:all)
>>quit
#Atm im not sure if i need the terminal to activate this, shouldnt be a big problem though
#Well Im gonna need some help executing this,Uugh
class User < ActiveRecord::Base
end
#Some Tests to run in terminal, to check details of accounts, may be important to prevent bots joining the websitre
#This Also Enables changing of account inforamtion,good for people who forget theyre account details
user = User.find_by_username("john") # Type this in order, should receive the
class User < ActiveRecord::Base
validates_uniqueness_of :username
validates_presence_of :password
validates_confirmation_of :password
end
#This checks Information automatically when someone logs in or out.
#app/controllers/account_controller.rb This is the second fiel to modify with this code.
class AccountController < ApplicationController
def index
end
def registration
if request.post? and params[:user]
@user = User.new(params[:user])
if @user.save
flash[:notice] = "User created."
redirect_to :action => "index"
end
end
end
end
#This is How new users are created, Still have no idea on how to do this.
#app/views/account/index.html.erb is the second one we need to modify with this code:
<% if flash[:notice] %>
<%= h flash[:notice] %>
<% end %>
<h1>Welcome To The Game!</h1>
#Note: I havent thought of what to replace Welcome to the game! with,shit.
# Thats it,I think. Heres some extra stuff that maybe useful, not sure.
#This is a account protection system, stopping users from decrypting code within others accounts.
# Not sure it will work, best thing i could think of.
#For this t owork, ill need to change thi sfile app/models/user.rb
require "digest"
class User < ActiveRecord::Base
validates_uniqueness_of :username
validates_presence_of :password
validates_confirmation_of :password
# Setup the salt value and hash the password before we save everything to the
# database.
def before_save
if (self.salt == nil)
self.salt = random_numbers(5)
self.password = Digest::MD5.hexdigest(self.salt + self.password)
end
end
private
# A sequence of random numbers with no skewing of range in any particular
# direction and leading zeros preserved.
def random_numbers(len)
numbers = ("0".."9").to_a
newrand = ""
1.upto(len) { |i| newrand << numbers[rand(numbers.size - 1)] }
return newrand
end
end
#
Some Of the first script i ever did in rails
Name:
Anonymous2011-03-05 20:00
(define /prog/
(if #t
("ANUS
ANUS ANUS ANUS ANUS ANUS ANUS
ANUS ANUS ANUS ANUS ANUS ANUS
HAVE YOU READ YOUR SICP TODAY
ANUS ANUS ANUS ANUS ANUS ANUS
ANUS ANUS ANUS ANUS ANUS
FUCKING HUGE TUNA FISH
ANUS ANUS ANUS ANUS ANUS
ANUS ANUS ANUS ANUS ANUS ANUS")
("faggot")))
Name:
Anonymous2011-03-05 20:05
>>29
Man this (http://jashkenas.github.com/coffee-script/) is some hot looking documentation. What are doing with CoffeeScript and how is it practical for what you're doing? I can't really wrap my head around why this would ever make sense. I've played with node.js a bit but CoffeeScript seems to take this idea of "oh JavaScript, everything's an object, and look closures and callbacks" to the extreme.
Name:
Anonymous2011-03-05 20:08
>>29
Although I have to confess that this is minimal and hot compared to some a lot of jQuery I've written.
# Set up the compilation function, to run when you stop typing.
compileSource = ->
source = $('#repl_source').val()
window.compiledJS = ''
try
window.compiledJS = CoffeeScript.compile source, bare: on
el = $('#repl_results')[0]
if el.innerText
el.innerText = window.compiledJS
else
$(el).text window.compiledJS
$('#error').hide()
catch error
$('#error').text(error.message).show()
# Listen for keypresses and recompile.
$('#repl_source').keyup -> compileSource()
# Eval the compiled js.
$('.minibutton.run').click ->
try
eval window.compiledJS
catch error then alert error
# Load the console with a string of CoffeeScript.
window.loadConsole = (coffee) ->
$('#repl_source').val coffee
compileSource()
$('.navigation.try').addClass('active')
false
# Helper to hide the menus.
closeMenus = ->
$('.navigation.active').removeClass 'active'
# Bind navigation buttons to open the menus.
$('.navigation').click (e) ->
return if e.target.tagName.toLowerCase() is 'a'
return false if $(e.target).closest('.repl_wrapper').length
if $(this).hasClass('active')
closeMenus()
else
closeMenus()
$(this).addClass 'active'
false
$(document.body).click (e) ->
return false if $(e.target).hasClass('minibutton')
closeMenus()
>>32 CoffeeScript seems to take this idea of "oh JavaScript, everything's an object, and look closures and callbacks" to the extreme.
Didn't see anything extreme about that in the documentation. Is it possible that you're easily impressed? The syntax does seem to increase conciseness, though.
Name:
Anonymous2011-03-05 23:38
Tried my first bit of lisp just now; googled the syntax for ifs and functions then wrote this.. (defun factorial (num) (if (> num 1) (* num (factorial (- num 1))) 1))
Should probably work on my formatting, just don't really know the normal style for lisp. I imagine it's something like.. (defun factorial (num)
(if (> num 1)
(* num (factorial
(- num 1)))
1))
Name:
Anonymous2011-03-05 23:45
>>35 (defun factorial (num)
(if (> num 1)
(* num (factorial (- num 1)))
1
)
)
>>35-36
Terrible!
Please get Emacs, or some Lisp IDE (if you really don't like Emacs). They are able to automatically indent Lisp code. Of course, after having used them for so long, I do know all the indentation rules myself (sometimes I even add rules for my own macros), but I wouldn't indent manually - indentation is there to help you quickly understand what some code is doing, it's quite helpful in lisp as indentation is used to serve as a visual cue as to the purpose/functionality of the code, things which pure syntactic sugar does for you in other languages.
Example proper indentation for your code:
(defun factorial (num)
(if (> num 1)
(* num (factorial
(- num 1)))
1))
;;; or
(defun factorial (num)
(if (> num 1)
(* num (factorial (- num 1)))
1))
Oh, and you don't need to type parens out either, use Paredit (Emacs mode) to structurally edit your code. If you're new to Emacs, you basically need (for CL): SLIME, Paredit, Redshank(optional), Hyperspec, and a few CL implementations installed and configured to work with SLIME. You may also choose some cosmetic changes like themes for Emacs and whatnot.
Name:
362011-03-06 0:25
>>37
If the editor can readily autoindent the code, then why do other Lispers get pissy with my code? If they don't like my indentation style, they can just configure their stupid editors to reindent it. And it goes the other way too -- if I don't like their indent style, I can re-indent everything the way I like. For example, I prefer closing parentheses associated with special forms on separate lines to make the distinction clear.
Read the first document I linked.
Basically, the answer is that all Lispers indent the code the same (or more or less very similar with very small differences depending on configuration details of their editor) and that we use the indentation as a cue to easily understanding the code. Randomly indented parens can be very messy as you're removing the few visual cues that we have (we have no real syntactic sugar). It also makes me look at the parens - I almost never look at the parens, I read the code by indentation, however the parens give you a lot of flexibility when WRITING the code.
When I see indentation like yours, it makes it hard for me to read the code and I have to either slowly read it and match parens (nasty), or copy it to Emacs and hit a key chord to indent it. Either way, you're making me spend some extra 10-20 seconds starting up Emacs and indenting your code when I could be reading it directly.