[ cyb / tech / λ / layer ] [ zzz / drg / lit / diy / art ] [ w / rpg / r ] [ q ] [ / ] [ popular / ???? / rules / radio / $$ / news ] [ volafile / uboa / sushi / LainTV / lewd ]

λ - programming

/lam/bda /lam/bda duck
Name
Email
Subject
Comment
File
Password (For file deletion.)

BUY LAINCHAN STICKERS HERE

STREAM » LainTV « STREAM

[Return][Go to bottom]

File: 1432291144736.jpg (246.06 KB, 1300x1210, 16414390-Abstract-word-clo….jpg) ImgOps Exif iqdb

 No.6176

Why don't we have a scripting language showcase thread?

What did you write today, lainons? (And why?)
>>

 No.6180

https://github.com/fukamachi/shelly
Because I don't hate myself.

>>

 No.6182

File: 1432352040455.png (24.56 KB, 683x157, invalidJSON.png) ImgOps iqdb

For a few seconds I thought you meant that this thread was for showcasing scripting languages lainons wrote. Considering that there was a compiler thread, it might be nice to have an interpreter thread sometime.

Anyway, today I wrote a small chat in Javascript (backend with iojs/nodejs). I did it to remember a bit how websockets work since I wish to make a HTML5 multiplayer game sometime this summer.

>>

 No.6193

>>6182
keep us updated on that game! also, right some things you learn along the way and about your process for the lainzine!

also this might interest you
http://gameprogrammingpatterns.com/

to read the book ^ wrote http://gameprogrammingpatterns.com/contents.html

and >>6015

>>

 No.6194

>>6193
God damn it, I accidentally reposted this and now it's in another thread too.

>>

 No.6196

>>6176
I wrote some crap for reading binary as ASCII.

(defparameter code-1 #b0100100100100000011011000110111101110110)
(defparameter code-2 #b0110010100100000011110010110111101110101)

(defun to-nums (code n)
(let (buffer)
(dotimes (i n)
(push (ldb (byte 8 (* i 8)) code) buffer))
(nreverse buffer)))


(format t "~a"
(nreverse (append (mapcar #'code-char (to-nums code-2 5))
(mapcar #'code-char (to-nums code-1 5)))))

(defparameter code-3 #b010010010010000001101100011011110111011001100101001000000111100101101111011101010010000001110100011011110110111100101110)

(format t "~a"
(nreverse (mapcar #'code-char (to-nums code-3 15))))

>>

 No.6223

I got sick of using Lua/Scheme for scripting a while ago (Lua is ugly, Guile doesn't work on win32 so I lost portability) so I made a thing myself. Not sure if relevant, but if lainons are interested I'll gladly give advice.

https://github.com/chameco/Solid

>>

 No.6225

File: 1432614060288.png (69.89 KB, 163x217, ayas1.PNG) ImgOps iqdb

>>6223

c = 0;
while c < 10 do
print(c);
c = c + 1;
end;

>implicit variable declarations
But why.

>>

 No.6226

File: 1432639834136.jpg (836.15 KB, 1440x810, mami-dio.jpg) ImgOps Exif iqdb

Just a simple bash script which I put under startup programs.
It checks if it is after 17:00 and if it is then it turns on my keyboard backlight.

#!/bin/bash
time=$(date +%k%M)

if [[ "$time" -ge 1700 && "$time" -le 0759 ]];then
echo "Backlight on"
xset led 3
else
echo "Backlight off"
xset -led 3
fi

>>

 No.6230

>>6194
um. are you sure you linked to the right comment? I posted that.

>>

 No.6234

>>6226
You could use redshift hooks instead.

>>

 No.6238

>>6234
nah…I have googled right now to see what redshift means…I always just keep my monitors at full brightness.I like it crisp.

>>

 No.6241

>>6225
Because hash tables, anon. Because hash tables.

>>

 No.6247

>>6241
You better have Lua's 'local' keyword or something like it.

>>

 No.6269

>>6223
>>6225

Why don't you use 'for' instead? You don't need 'while' here since there's no 'guard' variable and you exactly know how many times you want to execute the command (10)

>>

 No.6726

I have just copy-pasted together a script for retrieving Youtube urls from 4chan/8chan threads for sharing music. I can then open the playlist with a program like vlc.


import sys
import re
import urllib.request
from collections import OrderedDict

if len(sys.argv)<3:
print("usage: python3 "+sys.argv[0]+" url playlist.m3u")
exit()

#I need to fake my user-agent, otherwise I get a 403
req = urllib.request.Request(
sys.argv[1],
data=None,
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
}
)

response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
matches = re.findall('https?\\:\\/\\/www\\.youtube\\.com\\/watch\\?v\\=[A-Za-z0-9._%+-]+', html)
urls = list(OrderedDict.fromkeys(matches))
f = open(sys.argv[2], 'w')
f.write("\n".join(urls))
f.close()


Yes, I know, using regex for parsing html is horrible. Please tell me what I should do instead. Other feedback welcome

>>

 No.6727

>>6726
Ooops, formatting error:
the print("usage"....) and the exit() lines should be obviously indented.

I thought lainchan kept the tabs...

>>

 No.6749

>>6726

def extractlinks(html):
soup = BeautifulSoup(html)
anchors = soup.findAll('a')
links = []
for a in anchors:
links.append(a['href'])
return links


then filter all the urls with www.youtube.com in them

>>

 No.6780

>>6749
[code]def extractlinks(html):
return [a['href'] for a in BeautifulSoup(html).findAll('a')]

>>

 No.6864

A soykafty bash script that's run as a cron job so I can have a batoto rss feed on my browser startpage.


#!/bin/bash

# Crappy xml parser than only really works for RSS because it breaks on attributes
parse_line(){
str="${1/<\/*>/}";
str="${str/<*>/}"
echo "$str"
}

# Fetches feed
rss=$(curl $(cat ignore/url))

# Removes pointless CDATA tags
rss=${rss//<![CDATA[/}
rss=${rss//]]>/}

# Get ready to loop
title=""
istitle=0
link=""
finished=0
counter=0

# Clear file first tho
echo "" > ignore/batoto.html

# More complicated than it needs to be
while read -r line; do

# Separates into < + tag
# Ex: <title> -> <title
# Probably could be done a different cuter way
parse=$(echo "$line" | cut -d ">" -f 1)

# if it's a title make $title equal it or if it's a link make $link equal it -- nothing complicated
if [[ $parse == "<title" ]] && [[ "$line" == *"English"* ]]; then
title=$(parse_line "$line")
title=${title/- English -/-}
istitle=1
counter=$[counter+1]
elif [[ $parse == "<link" ]] && [[ $istitle -eq 1 ]]; then
link=$(parse_line "$line")
istitle=0
finished=1
fi

# If there's a title and a link, clear both and format it to html then spit it out
if [[ $finished -eq 1 ]]; then
title1=$(echo "$title" | cut -d "-" -f 1)
title1=${title1%?}:
title2=$(echo "$title" | cut -d "-" -f 2)
echo "<li><a target=\"_blank\" href=\"$link\"><span class=\"bold\">$title1</span>$title2</a></li>" >> ignore/batoto.html
finished=0

# If there's 8 entries now, quit out the program
if [[ $counter = 8 ]]; then
exit;
fi
fi
# pipes content of $rss to the loop
done <<< "$rss"

>>

 No.8623

I write and maintain automation scripts for a security software company (won't say who but they are fortune 500)

wish I could share them but I can't :3
this is more of a college job to me than anything though, I don't want to do scripts for the rest of my life

>>

 No.8634


require "mechanize"
require "nokogiri"

unless ARGV.length == 1
puts "Usage: scrapper url"
exit
end

agent = Mechanize.new { |agent| agent.user_agent_alias = "Mac Safari" }

url = ARGV[0].chomp.lstrip
html_doc = Nokogiri::HTML(agent.get(url).body)
files=[]

if /https:\/\/boards\.4chan\.org/.match(url) do
(html_doc.css('div.file')).each{ |ito| files.push "https:#{ito.css("a")[0]['href']}"}
end

elsif /https:\/\/7chan\.org/.match(url) do
(html_doc.css('p.file_size')).each{ |ito| files.push "#{ito.css("a")[0]['href']}"}
end

else
(html_doc.css('p.fileinfo')).each{ |ito| files.push "#{ito.css("a")[0]['href']}"}
end


if /\Ahttp/.match(files[0]) do
files.each{ |x| `wget #{x}`}
end

else
prefix = (url.split '/')[0..-4].join '/'
files.each{ |x| `wget #{prefix}#{x}`}
end


how in the fuarrrk do i add syntax highlighting for this?

Made it a bit ago. Added support for 7chan and 4chan today.

Tested on 8chan, 4chan, lainchan and 7chan.

>>

 No.8635

>>8634

#!/Users/normie/.rvm/rubies/ruby-2.2.1/bin/ruby
require "mechanize"
require "nokogiri"

unless ARGV.length == 1
puts "Usage: scrapper url"
exit
end

agent = Mechanize.new { |agent| agent.user_agent_alias = "Mac Safari" }

url = ARGV[0].chomp.lstrip
html_doc = Nokogiri::HTML(agent.get(url).body)
files=[]

if /:\/\/boards\.4chan\.org/.match(url) do
(html_doc.css('div.file')).each{ |ito| files.push "https:#{ito.css("a")[0]['href']}"}
end

elsif /:\/\/7chan\.org/.match(url) do
(html_doc.css('p.file_size')).each{ |ito| files.push "#{ito.css("a")[0]['href']}"}
end

elsif /:\/\/boards\.420chan\.org/.match(url) do
(html_doc.css('span.filesize')).each{ |ito| files.push "#{ito.css("a")[0]['href']}"}
end

else
(html_doc.css('p.fileinfo')).each{ |ito| files.push "#{ito.css("a")[0]['href']}"}
end


if /\Ahttp/.match(files[0]) do
files.each{ |x| `wget #{x}`}
end

else
prefix = (url.split '/')[0..-4].join '/'
files.each{ |x| `wget #{prefix}#{x}`}
end


made it a tad better, added support for 420chan and https or http links now works.

basically just use it as
./scriptname https://desiredurl

>>

 No.8636

Script to play mpv, in Firefox + Vimperator, I can just hit a key, and it'll play videos (mainly youtube) on the page in mpv instead of using flash or mozplugger.

Hit 'Q' in Vimperator:
nnoremap Q y:execute "!urxvtc -e '/home/user/.local/bin/yt'"


#!/usr/bin/ruby

def print_help
puts "Available flag options: \n\
flag | intention | command \n\
------------------------------------------------------------------ \n\
-nv | 'no video' | /usr/local/bin/mpv --no-video \n\
-c | 'check' | youtube-dl --list-formats --no-playlist \n\
-md | 'music download | youtube-dl -x --audio-format best -f best \n\
-q | 'query' | /usr/local/bin/mpv --ytdl-format= \n\
-d | 'download' | youtube-dl --no-playlist \n\
none | 'default' | /usr/local/bin/mpv --ytdl-format=18"
end

link = `xclip -out`

if ARGV[0] == '-h'
print_help
elsif link =~ /youtube/
puts "#{link} contains yt"
if ARGV[0] == '-nv'
puts 'now playing: no video option'
exec "/usr/local/bin/mpv --no-video \"#{link}\""
elsif ARGV[0] == '-c'
puts 'now checking formats'
exec "youtube-dl --list-formats --no-playlist \"#{link}\""
elsif ARGV[0] == '-md'
puts 'now downloading (music only)'
exec "youtube-dl -x --audio-format best -f best \"#{link}\""
elsif ARGV[0] == '-q'
puts 'now playing with chosen quality of ' + ARGV[1]
exec '/usr/local/bin/mpv --ytdl-format=' +
ARGV[1] + " \"#{link}\""
elsif ARGV[0] == '-d'
puts 'now downloading (video)'
exec "youtube-dl --no-playlist \"#{link}\""
else
puts 'now playing: low quality'
exec "/usr/local/bin/mpv --ytdl-format=18 \"#{link}\""
end
else
puts "#{link} is not a youtube link"
print_help
end

puts link

>>

 No.8637

Selects a random wallpaper through Nitrogen



#!/usr/bin/env python3

## sets a random wallpaper through Nitrogen
## Nitrogen: http://projects.l3ib.org/nitrogen/

# the program needs a file in the home directory called '.rwall.conf',
# create the file and add the path of where you keep your wallpaper images
# EXAMPLE: path = /home/user/Pictures/Wallpapers/
# and run the program, or make it execute at the startup of your window manager

import os, random, io, sys
import subprocess

def main():
conffile = ".rwall.conf"
confpath = os.path.expanduser("~/.rwall.conf")

filespath = None

# get conf file or create it

if os.path.exists(confpath):
pass
else:
# write defaults

f = open(confpath, 'w')
f.write("path = /path/to/your/wallpapers/\n")
f.close()

# read conf file and set vars accordingly

with open(confpath, 'r') as r_config:
config_lines = r_config.readlines()

for var in config_lines:
var = var.strip().split()

filespath = var[2] # get path string

if filespath == "/path/to/your/wallpapers/":
sys.exit("Did not supply a valid directory in " + confpath)

files = os.listdir(filespath)

randomfile = random.choice(files)
chosenpath = os.path.join(filespath, randomfile)

process = subprocess.call(['nitrogen', '--set-scaled', chosenpath])

main()



>>

 No.8965

Today I made it way easier to run my tiny personal wiki software from a local machine instead of a whole webserver setup. I've been working on it on and off for a few years. It's all in one script file (except templates and styles etc.) and written in Python.

Pages/articles are written in and rendered from ReStructured Text and saved in flatfiles. It supports simple password authentication, all of the configuration is at the top of the script, and you can spawn an instance at home easily now using thttpd and the example spawn script.

Project page and description: https://github.com/pariahsoft/PyWW
Main script: https://github.com/pariahsoft/PyWW/blob/master/index.cgi (Yes CGI for ease of personal use.)
Demo Site (wiped every 24 hours): http://pariahsoft.com/pyww/

The code is too long to paste here but it's less than 300 lines.

>>

 No.8977

File: 1441132639803.jpg (14.31 KB, 300x231, lain_wat.jpg) ImgOps Exif iqdb

>>8636
> youtube
> instead of using flash or mozplugger.
what's wrong with html5?

>>

 No.8981

I made a sh script
I know it isn't ruby or some other scripting language with better features but here you go.

It's for downloading/streaming songs off the nigge.rs website (comedic songs, mostly.)


#!/bin/sh
#Licensed under the GPLv3. Requires mpv or mplayer.

usage() {
echo "Usage: nigge.rs (-d) songname"
echo "or, for a list of all songs,"
echo "nigge.rs -q"
}

if [ $# -eq 0 ]; then
usage; exit 1
fi

download=false
if [ "$1" = -d ]; then
download=true
shift
fi

query=false
if [ "$1" = -q ]; then
query=true
download=false
stream=false
shift
fi

dl() { wget http://nigge.rs/media/$1/$1.ogg ;}
stream() { mpv http://nigge.rs/media/$1/$1.ogg || mplayer http://nigge.rs/id/$1/$1.ogg ;}

if $download; then
dl $1 &
stream $1
elif $stream; then
stream $1
else
shift
fi

if $query; then
wget http://nigge.rs
awk -F '[<>]' '/<a / { gsub(/<b>/, ""); sub(/ .*/, "", $3); print $3 } ' index.html
rm -f index.html
fi

>>

 No.8997

>>8977
I fell for the mpv meme, and wrote this before HTML5 on YouTube became a thing.

Just inertia and ignorance, really.

>>

 No.9006

>>8997
>>8977
>what's wrong with html5
>[nothing]

html5 is not very secure and makes you very trackable:

1. Browsers are leaky buckets security wise due to their big attack surface. Some media decoder is always bugged and allows people with 0days to crawl out of the sandboxes (e.g. recent pdf issue with adobe plugin on windows, of course plugins on windows are especially bad in that respect)

2. the javascript API of browsers (which you need for youtube etc. to work) knows all kinds of soykaf about your computer, which you might not necessarily want.

these are two things that are not great about html5, just for completion's sake

>>

 No.9064

How would you lainons approach downloaded content from a series of URLs that were all indexed on a single URL. So the structure would go something like this:

Index URL w/ links
-- Link1
-Embedded Content we want
-- Link 2
-More juicy content
....
-- Link n
- n content


Yeah, we want to download that specific bit of content without having to follow/download every damn HTML page. Ideas?

>>

 No.9076

>>9064
With python script using httplib2 and BeatifulSoup.

>>

 No.9245

W H E R E  I S  P A G E  W I T H  M A R K U P
H
E
R
E
I
S
P
A
G
E
W
I
T
H
M
A
R
K
U
P

>>

 No.9257

>>9064
curling the page into some perl regexes

>>

 No.9356

File: 1442085934336.png (1.38 KB, 200x100, 1442085677.png) ImgOps iqdb

Bash function to show a notification window at or after a specified time period.
at-msg() {
read -p "Examples: ‘+10 mins’, ‘19:30’."$'\n'"When? > " when
read -p "Text message: > " msg
date --date="$when" +"%H:%M" >/dev/null || return 4

at "`date --date="$when" +"%H:%M"`" <<<"DISPLAY=$DISPLAY Xdialog --msgbox \"\n $msg \n\" 200x100"
}

How to use:
$ at-msg
Examples: ‘+10 mins’, ‘19:30’.
When? > +20 min
Text message: > Kettle!
warning: commands will be executed using /bin/sh
job 2017 at Sat Sep 12 22:38:00 2015


Requires atd running and Xdialog installed.

>>

 No.9361

Bash function to copy the current playlist from mpd to a specified folder (music player or an SD card)
# Copies current MPD playlist to a specified folder.
# $1 — where to copy
copy-playlist() {
err() { echo "$1" >&2; echo $2; } # $1 — message; $2 — return code
local dest="$1" cur_pl='current.m3u' pl_dir pl library_path got_a_sane_reply
pl_dir=`sed -nr 's/^\s*playlist_directory\s+"(.+)"\s*$/\1/p' ~/.mpd/mpd.conf`
library_path=`sed -nr 's/^\s*music_directory\s+"(.+)"\s*$/\1/p' ~/.mpd/mpd.conf`
eval [ -d "$pl_dir" ] \
|| return `err 'Playlist directory is indeterminable.' 3`
eval [ -d "$library_path" ] \
|| return `err 'Path to music library is indeterminable.' 4`
pl="$pl_dir/$cur_pl"
mpc save "$cur_pl" # MPD_HOST must be set in the environment
[ -f "$pl" ] || return `err 'Playlist wasn’t saved' 5`
[ -w "$dest" ] && {
while read filepath; do
filepath="${filepath/$library_path/}"
cp -v "$library_path/$filepath" "$dest" || {
unset got_a_sane_reply
until [ -v got_a_sane_reply ]; do
read -n1 -p 'Error on copying. Continue? [Y/n] > '; echo
case "$REPLY" in
y|Y|'') got_a_sane_reply=t;; # And skip further messages
n|N) break 2;;
*) echo 'Y or N.';;
esac
done
}
done < "$pl"
:
}|| return `err "Destination dir ‘$dest’ is not writable." 6`
}

>>

 No.9362

File: 1442091210640.png (144.9 KB, 363x271, uhuh.png) ImgOps iqdb

>>9361
> stripping tabs from <code>
This engine never fails to amaze me with each step I get to know it.

>>

 No.9398

>>9362
I'm pretty sure tabs are just a different width here.

This is why you should always use spaces. fuarrrk tabs.

>>

 No.9400

>>9398
fuck spaces

>>

 No.9405

while true; do espeak "rofl"; done

>>

 No.11048

Here's something I never bother saving I use for when I add new books or whatnot to my organized book directory:
(map 'string (lambda (c) (case c (#\  #\-) (t (char-downcase c)))) "")
Example:
CL-USER> (map 'string (lambda (c) (case c (#\  #\-) (t (char-downcase c)))) "The GNU C Reference Manual")
"the-gnu-c-reference-manual"
CL-USER>



Delete Post [ ]
[ cyb / tech / λ / layer ] [ zzz / drg / lit / diy / art ] [ w / rpg / r ] [ q ] [ / ] [ popular / ???? / rules / radio / $$ / news ] [ volafile / uboa / sushi / LainTV / lewd ]