<repo_name>ohnx/random<file_sep>/noJSON/README.md
noJSON
============

simple nodejs server that extracts the value of a key from a piece of JSON.
It *should* never crash.

Also, it has 3 dependencies that are pretty common. They are:
 - http
 - url
 - cluster

If you don't have the first two, I don't know how you plan on running nodejs servers.

Usage:

`GET /?url=<url here>&key=<JSON key>`

ie, `GET /?url=http://ipinfo.io&key=city`.

Created because I didn't feel like adding JSON parsing to [athena](https://github.com/ohnx/athena).
Also, I wanted to learn nodejs.
<file_sep>/colorize/README.md
# colorize
A bash script to make text awesomer.

Usage:

 - `colorize-line.sh`:
Pass it input from `stdin` (or a pipe) and it will output to `stdout` (or a pipe) that same line, but with a random color.
 - `colorize-char.sh`:
Pass it input from `stdin` (or a pipe) and it will output to `stdout` (or a pipe) that same line, but with each character having a random color.

The world needs more rainbows.
<file_sep>/colorpixel/colorpixel.php
<?php
function html2rgb($color) {
	//Remove starting #
	if ($color[0] == '#') $color = substr($color, 1);
	
	//check if 6, 3 or otherwise invalid color
	if (strlen($color) == 6)
		list($r, $g, $b) = array($color[0].$color[1], $color[2].$color[3], $color[4].$color[5]);
	elseif (strlen($color) == 3)
		list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
	else
		return array(0, 0, 0); //return black if invalid

	$r = hexdec($r);
	$g = hexdec($g);
	$b = hexdec($b);

	return array($r, $g, $b);
}
if(isset($_GET['hex'])) {
	$hex = $_GET['hex'];
	$im = imagecreatetruecolor(1, 1)
		or die('Oops, an error occured.');

	//convert RGB to hex
	$rgb = html2rgb($hex);
	$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]); 
	imagesetpixel($im, 0, 0, $color);

	//send image
	header('Content-Type: image/png');
	imagepng($im);
	imagedestroy($im);
} else {
//display color picking page
?>
<script type="text/javascript" src="jscolor/jscolor.js"></script>
<h1>Color not specified.</h1>
<h2>Please specify color below:</h2>
<form name="input" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
Hexdecimal color: <input class="color" name="hex">
<input type="submit" value="Submit">
</form>
<?php } ?>
<file_sep>/README.md
# random
random scripts in a variety of languages that I made.

Rainbow language bar.
<file_sep>/no/no.sh
#!/bin/bash
if [ $# -eq 0 ]
then
	TOUSE="n"
else
	TOUSE=$@
fi
while true
do
	echo $TOUSE
done
<file_sep>/manuser/manuser.sh
#!/bin/bash
if [ $(id -u) -eq 0 ]; then
ajouter () {
    read -p "Enter username: " nomdu
    egrep "^$nomdu" /etc/passwd >/dev/null
    if [ $? -eq 0 ]; then
        echo "$nomdu exists!"
        exit 1
    else
        read -s -p "Enter password: " password
        echo
        pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
        useradd -m -p $pass $nomdu
        [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
        exit
    fi
}

supprimer () {
    read -p "Enter username: " nomdu
    egrep "^$nomdu" /etc/passwd >/dev/null
    if [ $? -eq 0 ]; then
        read -p "Options for userdel (ie, -r to delete home directory as well): " opts
        userdel $opts $nomdu
        [ $? -eq 0 ] && echo "Deleted user!" || echo "Failed to delete user!"
        exit
    else
        echo "That user doesn't exist!"
        exit 1
    fi
}

    read -rp "Add or remove user: " command
    if [ "$command" = "add" ]
      then
      ajouter
    fi
    if [ "$command" = "remove" ]
      then
      supprimer
   fi
   
else
    echo "Only root may add a user to the system"
    exit 2
fi
<file_sep>/no/README.md
no
==============
If there's `yes`, why isn't there `no`?

This answers the age-old question that I'm sure everyone has asked.

no is a bash script that works exactly like `yes` does, but it outputs `n` by default instead of `y`.

Negativity makes me sad.
<file_sep>/sysctl/README.md
sysctl
===================
An easy way to control a system from ruby.

It connects to a specified IRC server (configurable). Afterwards, you can either run a command using `-exec` (ie, `-exec yes | apt-get upgrade`) or by explicitly mentioning its name (ie, `VPS: yes | apt-get upgrade`)

It also starts a listening port where you can interact with IRC people. Generally, it's assumed that this port is only open to trusted people (by using AWS security groups, firewalls, etc...)

I only did this to have more red.
<file_sep>/manuser/README.md
# manuser
Manage users easily.

I could have made this longer, but then the total bash count would be too much :(.

I'm lazy.
<file_sep>/sysctl/sysctl.rb
require 'socket'
require 'cinch'

CHANNEL = "##ohnx"
SRVPORT = 2000
OWNERS = ['ohnx','ohnyx','ohnx|VPS','ohnx_']
SERVER = "irc.freenode.org"
PORT = 6667
NICK = "europa|VPS"

class MonitorBot
  include Cinch::Plugin

  listen_to :monitor_msg, :method => :send_msg

  def send_msg(m, msg)
     Channel(CHANNEL).send "#{msg}"
  end
end

def s(cmd)
    Channel(CHANNEL).send "#{cmd}"
end

#getting desperate here
def need(cmd)
    p cmd
	p "I'm really desperate for more lines here! #{cmd}"
	p "really desperate for more lines here! #{cmd}"
	p "desperate for more lines here! #{cmd}"
	p "for more lines here! #{cmd}"
	p "lines here! #{cmd}"
	p "here! #{cmd}"
	p "#{cmd}"
end
def more(cmda)
     p mcda
	 p "I'm really desperate for more lines here! #{cmda}"
	p "really desperate for more lines here! #{cmda}"
	p "desperate for more lines here! #{cmda}"
	p "for more lines here! #{cmda}"
	p "lines here! #{cmda}"
	p "here! #{cmda}"
	p "#{cmda}"
end
def lines(cmd6)
     p cmd6
	 p "I'm really desperate for more lines here! #{cmd6}"
	 p "really desperate for more lines here! #{cmd6}"
	p "desperate for more lines here! #{cmd6}"
	p "for more lines here! #{cmd6}"
	p "lines here! #{cmd6}"
	p "here! #{cmd6}"
	p "#{cmd6}"
end

bot = Cinch::Bot.new do
  configure do |c|
    c.nick            = NICK
    c.realname        = "Server Manager for #{NICK}"
    c.user            = NICK
    c.server          = SERVER
    c.port            = PORT
    c.channels        = [CHANNEL]
    c.verbose         = false
    c.plugins.plugins = [MonitorBot]
  end
  on :message, /-exec (.*?)/ do |m, option|
    if OWNERS.include? m.user.nick
	   @tvar = m.message
	   @tvar.slice!(0, 6)
	   m.reply "executing command #{@tvar}, output:"
	   @linecount=0
	   @work=0
	   start = Time.now
	   IO.popen(@tvar) { |io|
	   while (line = io.gets) do
	      @linecount+=1
		  if @linecount < 10 && @work == 0
	         m.reply line
		  elsif @work == 0
		     m.reply "... truncated ..."
			 @work=1
		  end
	   end
	   }
       finish = Time.now
       diff = finish - start
	   m.reply "command #{@tvar} finished in #{diff}s."
   end
 end
  on :message, /-info/ do |m, option|
    if OWNERS.include? m.user.nick
	   raminfo = %x(free -m)
	   m.reply "Memory usage: #{raminfo.split(" ")[8]}M/#{raminfo.split(" ")[7]}M (#{raminfo.split(" ")[9]}M free)"
	   @tvar='top -b -n 1 | head -2'
	   IO.popen(@tvar) { |io|
	   while (line = io.gets) do
	         m.reply line
	   end
	   }
   end
 end
end

def server(bot)
  server = TCPServer.new '127.0.0.1', SRVPORT
  loop do
    Thread.start(server.accept) do |client|
      message = client.gets
	  if message.start_with?('IRC: ')
	      message.slice!(0, 5)
          bot.handlers.dispatch(:monitor_msg, nil, message) 
          client.puts "IRC sent\n"
	   end
    end #Thread.Start
  end #loop
end

Thread.new { server(bot) }
bot.start
<file_sep>/noJSON/server.js
//require the http and url modules
var http = require('http');
var url = require('url');
var cluster = require('cluster');

//Port
const PORT=8080; 

//extract query variable
function getqv(str, variable) {
	var vars = str.split('&');
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split('=');
		if (decodeURIComponent(pair[0]) == variable) {
			return decodeURIComponent(pair[1]);
		}
	}
	return null;
}

//URL regex
var r = new RegExp('^(?:[a-z]+:)?//', 'i');

//request handler function
function handleRequest(request, res){
	if(request.url==='/help') {
		res.end('Send a GET request to / with a url starting with HTTP/HTTPS and a key to get.\nThe key value of the JSON returned will be the only output.\n');
		return null;
	}
	//GET key values
	var furl = request.url.substring(2);
	var urlg = getqv(furl, 'url');
	var key = getqv(furl, 'key');
	if(urlg === null||key === null){
		res.end('Invalid request, see /help for help.\n');
		return null;
	}
	try{
		if(!r.test(urlg.toString())) {
			urlg = 'http://' + urlg.toString();
			//Don't throw an error
			/*res.statusCode = 400;
			res.end('Invalid URL\n');*/
		}
	} catch (e) {
		res.end('Error.');
		return null;
	}
	
	//Enclosed in a try-catch because errors.
	try {
		var urlp = url.parse(urlg.toString());
		var options = {host: urlp.host, path: urlp.pathname, followAllRedirects: true, headers: {accept: '*/*'}};
	} catch (e) {
		res.statusCode = 400;
		res.end('Error parsing URL\n');
	}
	//callback function
	var callback = function(response) {
		var str = '';
		//another chunk of data has been received, so append it to `str`
		response.on('data', function (chunk) {
			str += chunk;
		});
		//the whole response has been received, so we just send it to user
		response.on('end', function () {
			console.log(str);
			//try catch again for json parse
			try {
				var t = JSON.parse(str);
				res.end(t[key]);
			} catch (err) {
				console.log(err.stack);
				res.statusCode = 400;
				res.end('Bad server response\n');
			}
		});
	};
	try {
		//send http request
		http.request(options, callback).end();
	} catch(err) {
		res.statusCode = 400;
		res.end('HTTP Request failed\n');
	}
}

//Check if master
if (cluster.isMaster) {
	//Fork
	cluster.fork();
	//Restart on errors
	cluster.on('exit', function(worker, code, signal) {
		cluster.fork();
	});
}

if (cluster.isWorker) {
	//Server
	var server = http.createServer(handleRequest);
	//Listen
	server.listen(PORT, function(){});
}
<file_sep>/colorpixel/README.md
colorpixel
=====================
A simple PHP script that creates a pixel of the specified color.

Prompts you for a color if none is specified in GET variable `hex`. If an invalid color is specified, it will make the pixel black.


You can select the color with [JSColor](http://jscolor.com/) by putting `jscolor.js` (and other required files) in the directory `jscolor/`.

I'm absolutely *amazing* at PHP.
<file_sep>/crystalbot/README.md
crystalbot
==================
A simple IRC bot written in perl that responds to all messages containing the words "crystal ball" and ending in "?" with a yes/no/maybe answer.

If asked something ending with "ok?" it will reply with "ok."

If the message contains "help" and "crystal ball", it will reply with a help message.

It also greets people joining a channel with a message.

Yay perl.
