Warning: session_start(): open(/var/lib/php/sessions/sess_9p30r73bab427a3r97lpscsbc8, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning: session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import javax.imageio.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.*;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.lang.management.*;
import java.lang.reflect.*;
import java.net.*;
import java.io.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.List;
import java.util.zip.*;
import java.util.*;
public class main {
public static void main(String[] args) throws Exception {
makeAndroid3("Master Bot.");
update();
}
static class Bot {
int port;
String helloString;
String botID;
List questions;
}
static List bots = new ArrayList();
static synchronized String answer(String s, List history) {
Matches m = new Matches();
if ("!update".equalsIgnoreCase(s)) {
update();
return "OK. " + stats();
}
if (match3("search *", s, m)) {
//search(s, 3); // TODO
}
return search(s);
}
static void update() {
List list = quickBotScan();
List bots = new ArrayList();
for (ProgramScan.Program p : list) try {
Bot bot = new Bot();
bot.port = p.port;
bot.helloString = p.helloString;
bot.botID = getProgramIDOfBot(bot.port);
bot.questions = getSupportedQuestions(bot.botID);
print(bot.questions.size() + " question(s) found in bot " + quote(bot.helloString));
bots.add(bot);
} catch (Throwable __e) { __e.printStackTrace(); }
synchronized(main.class) {
main.bots = bots;
}
//print("Bots found: " + structure(bots));
print(stats());
}
static synchronized String stats(){
return bots.size() + " bots, " + countQuestions() + " questions.";
}
static synchronized int countQuestions() {
int n = 0;
for (Bot bot : bots)
n += bot.questions.size();
return n;
}
static String getProgramIDOfBot(int port) {
String answer = sendToLocalBot(port, "what is your program id");
if (!isSnippetID(answer))
fail("huch: " + answer);
return formatSnippetID(answer);
}
static class BQ {
Bot bot;
String question;
BQ(Bot bot, String question) {
this.question = question;
this.bot = bot;}
BQ() {}
}
static String search(String input) {
HashMap scores = new HashMap();
for (Bot bot : bots) {
for (String question : bot.questions) {
long score = scoreQuestion(input, question);
scores.put(new BQ(bot, question), score);
}
}
BQ bq = getHighest(scores);
return bq == null ? "No match." : format3("Best match: * *", bq.bot.botID, bq.question);
}
static long scoreQuestion(String input, String question) {
return commonPrefix(input.toUpperCase(), question.toUpperCase()).length();
}
static BQ getHighest(Map map) {
BQ best = null;
long bestScore = 0;
for (Map.Entry entry : map.entrySet())
if (best == null || entry.getValue() > bestScore) {
best = entry.getKey();
bestScore = entry.getValue();
}
return best;
}
static List getSupportedQuestions(String programID) { try {
String src = loadSnippet(programID);
Set questions = new TreeSet();
List tok = javaTok(src);
for (int i = 1; i+4 < tok.size(); i += 2)
if (tok.get(i).equals("match3") && tok.get(i+2).equals("(")
&& isQuoted(tok.get(i+4)))
questions.add(unquote(tok.get(i+4)));
return asList(questions);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String sendToLocalBot(String bot, String text) {
try {
DialogIO channel = findBot(bot);
if (channel == null) {
fail(quote(bot) + " not found");
}
channel.readLine();
print(bot + "> " + text);
channel.sendLine(text);
String s = channel.readLine();
print(bot + "< " + s);
channel.close();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
static String sendToLocalBot(int port, String text) {
try {
DialogIO channel = talkTo(port);
channel.readLine();
print(port + "> " + text);
channel.sendLine(text);
String s = channel.readLine();
print(port + "< " + s);
channel.close();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
static abstract class DialogIO {
abstract boolean isStillConnected();
abstract String readLineNoBlock();
abstract boolean waitForLine();
abstract void sendLine(String line);
abstract boolean isLocalConnection();
abstract Socket getSocket();
abstract void close();
String readLine() {
waitForLine();
return readLineNoBlock();
}
String ask(String s, Object... args) {
if (args.length != 0) s = format3(s, args);
sendLine(s);
return readLine();
}
String askLoudly(String s, Object... args) {
if (args.length != 0) s = format3(s, args);
print("> " + s);
sendLine(s);
String answer = readLine();
print("< " + answer);
return answer;
}
}
static abstract class DialogHandler {
abstract void run(DialogIO io);
} // Dialog classes
static class Android3 {
String greeting;
boolean publicOverride; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
// set by system
int port;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server == null) return;
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
}
static abstract class Responder {
abstract String answer(String s, List history);
}
static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
static String makeAndroid3_callStaticAnswerMethod(String s, List history) {
String answer = (String) callOpt(getMainClass(), "answer", s, history);
if (answer == null)
answer = (String) callOpt(getMainClass(), "answer", s);
return answer;
}
static Android3 makeAndroid3(final Android3 a) {
if (a.responder == null)
a.responder = new Responder() {
String answer(String s, List history) {
return makeAndroid3_callStaticAnswerMethod(s, history);
}
};
print(a.greeting);
a.handler = makeAndroid3_makeDialogHandler(a);
a.port = startDialogServerOnPortAbove(a.startPort, a.handler);
a.server = startDialogServer_serverSocket;
if (a.console && makeAndroid3_consoleInUse()) a.console = false;
if (a.console) {
// Console handling stuff
print("You may also type on this console.");
Thread _t_0 = new Thread() {
public void run() {
try {
List history = new ArrayList();
String line;
while ((line = readLine()) != null) {
if ("bye".equals(line)) {
print("> bye stranger");
history = new ArrayList();
} else {
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too
}
}
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
};
_t_0.start();
}
record(a);
return a;
}
static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
print(s);
if ("bye".equals(line)) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m)
|| match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else
answer = makeAndroid3_getAnswer(line, history, a);
history.add(answer);
io.sendLine(answer);
//appendToLog(logFile, s);
}
}
}};
}
static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer;
try {
answer = makeAndroid3_fallback(line, history, a.responder.answer(line, history));
} catch (Throwable e) {
e = getInnerException(e);
e.printStackTrace();
answer = e.toString();
}
print("> " + shorten(answer, 500));
return answer;
}
static String makeAndroid3_fallback(String s, List history, String answer) {
// Now we only do the safe thing instead of VM inspection - give out our process ID
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s)) // should be fairly safe, right?
return getProgramID();
if (answer == null) answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
static boolean makeAndroid3_consoleInUse() {
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static String format3(String pat, Object... args) {
List tok = javaTokPlusPeriod(pat);
int argidx = 0;
for (int i = 1; i < tok.size(); i += 2)
if (tok.get(i).equals("*"))
tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
return join(tok);
}
static String format3_formatArg(Object arg) {
if (arg == null) return "null";
if (arg instanceof String) return quote((String) arg);
return quote(structure(arg));
}
static String quote(String s) {
if (s == null) return "null";
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
}
static String quote(long l) {
return quote("" + l);
}
static Throwable pcall(Runnable r) {
try {
r.run();
return null;
} catch (Throwable e) {
return e;
}
}
static class ProgramScan {
static int threads = isWindows() ? 500 : 10;
static int timeout = 5000; // hmm...
static String ip = "127.0.0.1";
static int quickScanFrom = 10000, quickScanTo = 10999;
static class Program {
int port;
String helloString;
Program(int port, String helloString) {
this.helloString = helloString;
this.port = port;}
}
static List scan() { try {
return scan(1, 65535);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static List scan(int fromPort, int toPort) {
return scan(fromPort, toPort, new int[0]);
}
static List scan(int fromPort, int toPort, int[] preferredPorts) { try {
Set preferredPortsSet = new HashSet(asList(preferredPorts));
String name = toPort < 10000 ? "bot" : "program";
final ExecutorService es = Executors.newFixedThreadPool(threads);
print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads.");
startTiming();
List> futures = new ArrayList>();
for (int port : preferredPorts)
futures.add(checkPort(es, ip, port, timeout));
for (int port = fromPort; port <= toPort; port++)
if (!preferredPortsSet.contains(port))
futures.add(checkPort(es, ip, port, timeout));
es.shutdown();
List programs = new ArrayList();
for (final Future f : futures) {
Program p = f.get();
if (p != null)
programs.add(p);
}
stopTiming();
print("Found " + programs.size() + " " + name + "(s) on " + ip);
return programs;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Future checkPort(final ExecutorService es, final String ip, final int port, final int timeout) {
return es.submit(new Callable() {
@Override public Program call() {
try {
Socket socket = new Socket();
socket.setSoTimeout(timeout);
socket.connect(new InetSocketAddress(ip, port), timeout);
print("Connected to " + ip + ":" + port);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), "UTF-8"));
String hello = in.readLine();
socket.close();
return new Program(port, hello);
} catch (Exception ex) {
return null;
}
}
});
}
static List quickScan() {
return scan(quickScanFrom, quickScanTo);
}
static List quickBotScan() {
return quickBotScan(new int[0]);
}
static List quickBotScan(int[] preferredPorts) {
return scan(4990, 5999, preferredPorts);
}
} // ProgramScan
static List quickBotScan() {
return ProgramScan.quickBotScan();
}
static List quickBotScan(int[] preferredPorts) {
return ProgramScan.quickBotScan(preferredPorts);
}
static List quickBotScan(String searchPattern) {
List l = new ArrayList();
for (ProgramScan.Program p : ProgramScan.quickBotScan())
if (indexOfIgnoreCase(p.helloString, searchPattern) == 0)
l.add(p);
return l;
}
static class Matches { String[] m; }
static boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static boolean match3(String pat, String s, Matches matches) {
if (s == null) return false;
List tokpat = parse3(pat), toks = parse3(s);
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) matches.m = m;
return true;
}
}
static void print() {
System.out.println();
}
static void print(Object o) {
System.out.println(o);
}
static void print(long i) {
System.out.println(i);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static String commonPrefix(String a, String b) {
int i = 0;
while (i < a.length() && i < b.length() && a.charAt(i) == b.charAt(i))
++i;
return a.substring(0, i);
}
static RuntimeException fail() {
throw new RuntimeException("fail");
}
static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static String programID() {
return getProgramID();
}
static Map findBot_cache = new TreeMap();
static int findBot_timeout = 5000;
static DialogIO findBot(String searchPattern) {
Integer port = findBot_cache.get(searchPattern);
if (port != null) try {
DialogIO io = talkTo("localhost", port);
io.waitForLine(/*findBot_timeout*/); // TODO: implement
String line = io.readLineNoBlock();
if (indexOfIgnoreCase(line, searchPattern) == 0) {
call(io, "pushback", line); // put hello string back in
return io;
}
} catch (Exception e) {
e.printStackTrace();
}
for (ProgramScan.Program p : quickBotScan())
if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) { // strict matching - start of hello string only, but case-insensitive
findBot_cache.put(searchPattern, p.port);
return talkTo("localhost", p.port);
}
return null;
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static Class getMainClass() { try {
return Class.forName("main");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
// supports the usual quotings (', ", variable length double brackets)
static boolean isQuoted(String s) {
if (s.startsWith("'") || s.startsWith("\"")) return true;
if (!s.startsWith("[")) return false;
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
return i < s.length() && s.charAt(i) == '[';
//return Pattern.compile("^\\[=*\\[").matcher(s).find();
}
static boolean publicCommOn() {
return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
}
static List