repo
string
commit
string
message
string
diff
string
balp/RPLogTool
68c65e4cea51633f74421536b4e1a71a34f994a6
Small cleanups
diff --git a/src/se/arnholm/rplogtool/server/LogCleaner.java b/src/se/arnholm/rplogtool/server/LogCleaner.java index 9ce108e..5d6b124 100644 --- a/src/se/arnholm/rplogtool/server/LogCleaner.java +++ b/src/se/arnholm/rplogtool/server/LogCleaner.java @@ -1,152 +1,151 @@ package se.arnholm.rplogtool.server; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.joda.time.Duration; public class LogCleaner { private String text; private String cleanString; private Vector<String> lines; private Map<String,PlayerInfo> players; private static final Pattern LINE_SPLIT = Pattern.compile("^\\s*\\[(.+)\\]\\s+(\\w+\\s+\\w+)([\\s+':].+)$"); private static final Pattern CCS_LINE_SPLIT = Pattern.compile("^\\s*\\[(.+)\\]\\s+CCS - MTR - 1.0.2:\\s+(\\w+\\s+\\w+)([\\s+':].+)$"); private static final Pattern TIME_SECONDS = Pattern.compile("(\\d+):(\\d+):(\\d+)"); private static final Pattern TIME_MINUTES = Pattern.compile("(\\d+):(\\d+)"); public LogCleaner(String text) { lines = new Vector<String>(); this.text = text; players = new HashMap<String,PlayerInfo>(); cleanString = process(); } private String process() { String result = new String(); BufferedReader reader = new BufferedReader( new StringReader(text)); String str; - Pattern online = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+\\S+\\s+\\S+ is Online"); - Pattern offline = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+\\S+\\s+\\S+ is Offline"); try { while((str = reader.readLine()) != null) { -// System.out.println("In: " + str); - if(online.matcher(str).find()) { + + RpLogLine line = splitLine(str); + final String action = line.getAction(); + if(line.isCCS()) { + System.out.println("In:\"" + str+ "\""); + System.out.println("action:\"" + action+ "\""); + } + if(action.equals(" is Online")) { continue; } - if(offline.matcher(str).find()) { + if(action.equals(" is Offline")) { continue; } - - String who = getPlayerName(str); +// System.out.println("..."); + String who = line.getName(); if(who != null) { PlayerInfo freq = players.get(who); if(null == freq) { freq = new PlayerInfo(who); } freq.addLine(str); players.put(who, freq); } // System.out.println("Adding:" + who + ":" + str); lines.add(str); result += str + "\n"; } } catch (IOException e) { e.printStackTrace(); } return result; } public static String getPlayerName(String str) { - Vector<String> values = splitLine(str); + RpLogLine values = splitLine(str); if(null != values) { - return values.get(1); + return values.getName(); } return null; } public String getClean() { return cleanString; } public Duration getDuration() { long start = getTime(lines.firstElement()); long end = getTime(lines.lastElement()); System.out.println("Duration between: " +start +":"+ lines.firstElement()); System.out.println(" and: " + end +":"+ lines.lastElement()); return new Duration(start, end); } public static long getTime(String logLine) { - Vector<String> values = splitLine(logLine); + RpLogLine values = splitLine(logLine); if(null != values) { - String time = values.get(0); + String time = values.getTime(); Matcher matchSeconds = TIME_SECONDS.matcher(time); if(matchSeconds.find()) { long hour = Long.parseLong(matchSeconds.group(1)); long minutes = Long.parseLong(matchSeconds.group(2)); long seconds = Long.parseLong(matchSeconds.group(3)); return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); } Matcher matchMinutes = TIME_MINUTES.matcher(time); if(matchMinutes.find()) { long hour = Long.parseLong(matchMinutes.group(1)); long minutes = Long.parseLong(matchMinutes.group(2)); return (((hour * 60 * 60) + (minutes*60) + 0) * 1000); } } return 0; } public Set<String> getPartisipants() { return players.keySet(); } public PlayerInfo getPlayerInfo(String name) { return players.get(name); } public static String formatTime(org.joda.time.Duration duration) { return String.format("%d:%02d", duration.toPeriod().getHours(), duration.toPeriod().getMinutes()); } - public static Vector<String> splitLine(String line) { + public static RpLogLine splitLine(String line) { Matcher ccs = CCS_LINE_SPLIT.matcher(line); if(ccs.find()) { - Vector<String> res = new Vector<String>(); - res.add(ccs.group(1)); - res.add(ccs.group(2)); - res.add(ccs.group(3)); + RpLogLine res = new RpLogLine(ccs.group(1), ccs.group(2), ccs.group(3), true); return res; } Matcher matcher = LINE_SPLIT.matcher(line); if(matcher.find()) { - Vector<String> res = new Vector<String>(); - res.add(matcher.group(1)); - res.add(matcher.group(2)); - res.add(matcher.group(3)); + RpLogLine res = new RpLogLine(matcher.group(1), matcher.group(2), + matcher.group(3), false); return res; } return null; } } diff --git a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java index fa9579f..ae13ab4 100644 --- a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java +++ b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java @@ -1,243 +1,244 @@ package se.arnholm.rplogtool.shared; import static org.junit.Assert.*; import java.util.Set; import java.util.Vector; import org.junit.Test; import se.arnholm.rplogtool.server.LogCleaner; +import se.arnholm.rplogtool.server.RpLogLine; import org.joda.time.Duration; public class LogCleanerTest { private String testLog = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:08:55] Ricard Collas is Online\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:07] Ricard Collas is Offline\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:25] Ranith Strazytski is Offline\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:25] Lensi Hax is Offline\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:03] Ricard Collas is Online\n" + "[03:13:25] Rin Tae is Offline\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:13:58] Wolfbringer Sixpack is Online\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; @Test public void testCleanLog() { String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(testLog); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testCleanLog2() { String text = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(text); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testDuration() { LogCleaner log = new LogCleaner(testLog); Duration expected = new Duration(431000); assertEquals(expected.getMillis(), log.getDuration().getMillis()); } @Test public void testDuration2() { LogCleaner log = new LogCleaner(log2); Duration expected = new Duration(1828000); assertEquals(expected.getMillis(), log.getDuration().getMillis()); } @Test public void testGetTime() { assertEquals(11220000, LogCleaner.getTime("[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"")); assertEquals(83103000, LogCleaner.getTime("[2010-09-15 23:05:03] Xerxis Rodenberger: See you")); assertEquals(81275000, LogCleaner.getTime("[2010-09-15 22:34:35] CCS - MTR - 1.0.2: Nadine Nozaki has entered a combative state\n")); } @Test public void testPlayers() { LogCleaner log = new LogCleaner(testLog); Set<String> who = log.getPartisipants(); // System.out.println("Test:" + who); assertTrue("Nadine should be in set", who.contains("Nadine Nozaki")); assertEquals(11262000, log.getPlayerInfo("Nadine Nozaki").getFirstTime()); assertEquals(11631000, log.getPlayerInfo("Nadine Nozaki").getLastTime()); Duration d = log.getPlayerInfo("Nadine Nozaki").getDuration(); assertEquals(369000, d.getMillis()); System.out.println("Nads: " + d.toPeriod().getHours() + ":" + d.toPeriod().getMinutes() + " " + log.getPlayerInfo("Nadine Nozaki").getLines()); assertEquals(10, log.getPlayerInfo("Nadine Nozaki").getNumberOfLines()); } @Test public void testTimeFormat() { LogCleaner log = new LogCleaner(testLog); assertEquals("0:06", LogCleaner.formatTime(log.getPlayerInfo("Nadine Nozaki").getDuration())); } @Test public void testGetPLayerName() { assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n")); assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:10:01] Nadine Nozaki's smile leaves her fance.\n")); assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n")); } @Test public void testLineSplit() { helpTestLineSplit("[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"", "03:07", "Nadine Nozaki", " ndos, \"Aint we all but Xerx human?\""); helpTestLineSplit("[2010-09-15 23:05:03] Xerxis Rodenberger: See you", "2010-09-15 23:05:03", "Xerxis Rodenberger", ": See you"); helpTestLineSplit("[2010-09-15 22:34:35] CCS - MTR - 1.0.2: Nadine Nozaki has entered a combative state", "2010-09-15 22:34:35", "Nadine Nozaki"," has entered a combative state"); } private void helpTestLineSplit(String line, String time, String name, String pose) { - Vector<String> s1 = LogCleaner.splitLine(line); + RpLogLine s1 = LogCleaner.splitLine(line); assertNotNull("Unable to split: " + line, s1); - assertEquals(time, s1.elementAt(0)); - assertEquals(name, s1.elementAt(1)); - assertEquals(pose, s1.elementAt(2)); + assertEquals(time, s1.getTime()); + assertEquals(name, s1.getName()); +// assertEquals(pose, s1.elementAt(2)); } String log2 = "[2010-09-15 22:34:35] CCS - MTR - 1.0.2: Nadine Nozaki has entered a combative state\n" + "[2010-09-15 22:34:40] CCS - MTR - 1.0.2: Nadine Nozaki has entered a non-combative state\n" + "[2010-09-15 22:34:57] BeoWulf Foxtrot is Offline\n" + "[2010-09-15 22:35:15] Selene Weatherwax is Offline\n" + "[2010-09-15 22:35:24] Jo Soosung is Offline\n" + "[2010-09-15 22:36:05] Rondevous Giano is Offline\n" + "[2010-09-15 22:37:21] BeoWulf Foxtrot is Online\n" + "[2010-09-15 22:39:31] Kommandant Epin is Offline\n" + "[2010-09-15 22:39:33] CCS - MTR - 1.0.2: Nadine Nozaki has entered a combative state\n" + "[2010-09-15 22:39:41] Nadine Nozaki steals a wet kiss\n" + "[2010-09-15 22:39:52] Erosid Dryke is Online\n" + "[2010-09-15 22:40:13] Selene Weatherwax is Online\n" + "[2010-09-15 22:42:17] BeoWulf Foxtrot is Offline\n" + "[2010-09-15 22:45:30] BeoWulf Foxtrot is Online\n" + "[2010-09-15 22:47:20] MoonGypsy Writer is Offline\n" + "[2010-09-15 22:48:50] Skye Hanfoi is Offline\n" + "[2010-09-15 22:49:15] KittyDarling Zelnik is Offline\n" + "[2010-09-15 22:49:24] Traven Sachs is Offline\n" + "[2010-09-15 22:49:49] McCabe Maxsted is Offline\n" + "[2010-09-15 22:50:08] Valmont1985 Radek is Offline\n" + "[2010-09-15 22:50:26] Xerxis Rodenberger kisses back passionately\n" + "[2010-09-15 22:50:34] Skye Hanfoi is Online\n" + "[2010-09-15 22:50:40] Voodoo Halostar is Offline\n" + "[2010-09-15 22:51:10] Voodoo Halostar is Online\n" + "[2010-09-15 22:53:57] Imogen Aeon is Offline\n" + "[2010-09-15 22:54:29] Pethonia Baxton is Offline\n" + "[2010-09-15 22:57:26] Nadine Nozaki: OMG OMG\n" + "[2010-09-15 22:57:33] Nadine Nozaki: Drama?\n" + "[2010-09-15 22:57:33] Nadine Nozaki: OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG!\n" + "[2010-09-15 22:57:56] Xerxis Rodenberger: Whats wrong?\n" + "[2010-09-15 22:58:01] Nadine Nozaki: RUN TIME\n" + "[2010-09-15 22:58:05] Xerxis Rodenberger: *cries*\n" + "[2010-09-15 22:58:06] Nadine Nozaki: Serius wrong imho\n" + "[2010-09-15 22:58:28] Sparklin Indigo is Online\n" + "[2010-09-15 22:58:44] Xerxis Rodenberger: mmhmm\n" + "[2010-09-15 22:59:02] Wezab Ember is Online\n" + "[2010-09-15 23:00:08] Alix Lectar is Offline\n" + "[2010-09-15 23:01:08] Nadine Nozaki: Love you my girl,\n" + "[2010-09-15 23:01:24] Xerxis Rodenberger: Love you Mistress. Have a great day\n" + "[2010-09-15 23:01:41] Nadine Nozaki: u 2 :D\n" + "[2010-09-15 23:02:06] Xerxis Rodenberger kisses and snuggles\n" + "[2010-09-15 23:02:17] Gaea Singh is Offline\n" + "[2010-09-15 23:03:22] Gino Byron is Online\n" + "[2010-09-15 23:04:47] Nadine Nozaki: See you tonight love\n" + "[2010-09-15 23:04:53] Nadine Nozaki: I hgave to get going...\n" + "[2010-09-15 23:05:03] Xerxis Rodenberger: See you\n"; }
balp/RPLogTool
33f3c217a14fcd52c8066abfa10014bb41dba3ab
v3 uploaded
diff --git a/.classpath b/.classpath index dd964d0..847681d 100644 --- a/.classpath +++ b/.classpath @@ -1,10 +1,11 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src"/> <classpathentry kind="src" output="test-classes" path="test"/> <classpathentry kind="con" path="com.google.appengine.eclipse.core.GAE_CONTAINER"/> <classpathentry kind="con" path="com.google.gwt.eclipse.core.GWT_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/> + <classpathentry exported="true" kind="lib" path="joda-time-1.6.2/joda-time-1.6.2.jar"/> <classpathentry kind="output" path="war/WEB-INF/classes"/> </classpath> diff --git a/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java b/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java index 383416b..3e54498 100644 --- a/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java +++ b/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java @@ -1,61 +1,60 @@ package se.arnholm.rplogtool.server; import java.util.Set; import se.arnholm.rplogtool.client.GreetingService; -import se.arnholm.rplogtool.shared.FieldVerifier; - import com.google.gwt.user.server.rpc.RemoteServiceServlet; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { public String greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid. String serverInfo = getServletContext().getServerInfo(); String userAgent = getThreadLocalRequest().getHeader("User-Agent"); // Escape data from the client to avoid cross-site script vulnerabilities. String log = escapeHtml(input); userAgent = escapeHtml(userAgent); LogCleaner cleaner = new LogCleaner(log); log = cleaner.getClean(); log = log.replaceAll("\n", "<br>\n"); String result = "Roleplay Log:<br>"; result += "----------------------------------------------------------------<br>\n"; + result += "Roleplay duration: " + LogCleaner.formatTime(cleaner.getDuration()) +"<br>\n"; Set<String> players = cleaner.getPartisipants(); for(String player: players) { PlayerInfo info = cleaner.getPlayerInfo(player); -// result += player + ": " + LogCleaner.formatTime(info.getDuration()) +"<br>\n"; - result += player + ": " +"<br>\n"; + result += player + ": " + LogCleaner.formatTime(info.getDuration()) +"<br>\n"; +// result += player + ": " +"<br>\n"; } result += "----------------------------------------------------------------<br>\n"; result += log; result += "----------------------------------------------------------------<br>\n"; result += "<strong>RPLogTool ©2010 Balp Allen</strong><br>" + serverInfo + ".<br>"; return result; } /** * Escape an html string. Escaping data received from the client helps to * prevent cross-site script vulnerabilities. * * @param html the html string to escape * @return the escaped string */ private String escapeHtml(String html) { if (html == null) { return null; } return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } } diff --git a/src/se/arnholm/rplogtool/server/LogCleaner.java b/src/se/arnholm/rplogtool/server/LogCleaner.java index 5acada0..9ce108e 100644 --- a/src/se/arnholm/rplogtool/server/LogCleaner.java +++ b/src/se/arnholm/rplogtool/server/LogCleaner.java @@ -1,138 +1,152 @@ package se.arnholm.rplogtool.server; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.google.appengine.repackaged.org.joda.time.Duration; +import org.joda.time.Duration; public class LogCleaner { private String text; private String cleanString; private Vector<String> lines; private Map<String,PlayerInfo> players; private static final Pattern LINE_SPLIT = Pattern.compile("^\\s*\\[(.+)\\]\\s+(\\w+\\s+\\w+)([\\s+':].+)$"); + private static final Pattern CCS_LINE_SPLIT = Pattern.compile("^\\s*\\[(.+)\\]\\s+CCS - MTR - 1.0.2:\\s+(\\w+\\s+\\w+)([\\s+':].+)$"); private static final Pattern TIME_SECONDS = Pattern.compile("(\\d+):(\\d+):(\\d+)"); private static final Pattern TIME_MINUTES = Pattern.compile("(\\d+):(\\d+)"); public LogCleaner(String text) { lines = new Vector<String>(); this.text = text; players = new HashMap<String,PlayerInfo>(); cleanString = process(); } private String process() { String result = new String(); BufferedReader reader = new BufferedReader( new StringReader(text)); String str; Pattern online = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+\\S+\\s+\\S+ is Online"); Pattern offline = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+\\S+\\s+\\S+ is Offline"); try { while((str = reader.readLine()) != null) { // System.out.println("In: " + str); if(online.matcher(str).find()) { continue; } if(offline.matcher(str).find()) { continue; } String who = getPlayerName(str); if(who != null) { PlayerInfo freq = players.get(who); if(null == freq) { freq = new PlayerInfo(who); } freq.addLine(str); players.put(who, freq); } // System.out.println("Adding:" + who + ":" + str); lines.add(str); result += str + "\n"; } } catch (IOException e) { e.printStackTrace(); } return result; } public static String getPlayerName(String str) { Vector<String> values = splitLine(str); if(null != values) { return values.get(1); } return null; } public String getClean() { return cleanString; } public Duration getDuration() { long start = getTime(lines.firstElement()); long end = getTime(lines.lastElement()); + + System.out.println("Duration between: " +start +":"+ lines.firstElement()); + System.out.println(" and: " + end +":"+ lines.lastElement()); + return new Duration(start, end); } public static long getTime(String logLine) { Vector<String> values = splitLine(logLine); if(null != values) { String time = values.get(0); Matcher matchSeconds = TIME_SECONDS.matcher(time); if(matchSeconds.find()) { long hour = Long.parseLong(matchSeconds.group(1)); long minutes = Long.parseLong(matchSeconds.group(2)); long seconds = Long.parseLong(matchSeconds.group(3)); return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); } Matcher matchMinutes = TIME_MINUTES.matcher(time); if(matchMinutes.find()) { long hour = Long.parseLong(matchMinutes.group(1)); long minutes = Long.parseLong(matchMinutes.group(2)); return (((hour * 60 * 60) + (minutes*60) + 0) * 1000); } } return 0; } public Set<String> getPartisipants() { return players.keySet(); } public PlayerInfo getPlayerInfo(String name) { return players.get(name); } - public static String formatTime(Duration duration) { + public static String formatTime(org.joda.time.Duration duration) { return String.format("%d:%02d", duration.toPeriod().getHours(), duration.toPeriod().getMinutes()); } public static Vector<String> splitLine(String line) { - + Matcher ccs = CCS_LINE_SPLIT.matcher(line); + if(ccs.find()) { + Vector<String> res = new Vector<String>(); + res.add(ccs.group(1)); + res.add(ccs.group(2)); + res.add(ccs.group(3)); + return res; + + } Matcher matcher = LINE_SPLIT.matcher(line); if(matcher.find()) { Vector<String> res = new Vector<String>(); res.add(matcher.group(1)); res.add(matcher.group(2)); res.add(matcher.group(3)); return res; } + return null; } } diff --git a/src/se/arnholm/rplogtool/server/PlayerInfo.java b/src/se/arnholm/rplogtool/server/PlayerInfo.java index 762e6b7..535f67d 100644 --- a/src/se/arnholm/rplogtool/server/PlayerInfo.java +++ b/src/se/arnholm/rplogtool/server/PlayerInfo.java @@ -1,60 +1,60 @@ package se.arnholm.rplogtool.server; import java.util.LinkedList; import java.util.List; -import com.google.appengine.repackaged.org.joda.time.Duration; +import org.joda.time.Duration; public class PlayerInfo { private List<String> lines; private long first; private long last; private String player; public PlayerInfo(String who) { lines = new LinkedList<String>(); last = Long.MIN_VALUE; first = Long.MAX_VALUE; player = who; } public void addLine(String line) { lines.add(line); long time = LogCleaner.getTime(line); if(time < first) { // System.out.println("addLine("+ line +"): first = " + time); first = time; } if(time > last) { // System.out.println("addLine("+ line +"): last = " + time); last = time; } } public String getPlayerName() { return player; } public long getFirstTime() { return first; } public long getLastTime() { return last; } public Duration getDuration() { return new Duration(getFirstTime(), getLastTime()); } public int getNumberOfLines() { return lines.size(); } public List<String> getLines() { return lines; } } diff --git a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java index 1f7e0ba..fa9579f 100644 --- a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java +++ b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java @@ -1,186 +1,243 @@ package se.arnholm.rplogtool.shared; import static org.junit.Assert.*; import java.util.Set; import java.util.Vector; import org.junit.Test; import se.arnholm.rplogtool.server.LogCleaner; -import com.google.appengine.repackaged.org.joda.time.Duration; +import org.joda.time.Duration; public class LogCleanerTest { private String testLog = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:08:55] Ricard Collas is Online\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:07] Ricard Collas is Offline\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:25] Ranith Strazytski is Offline\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:25] Lensi Hax is Offline\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:03] Ricard Collas is Online\n" + "[03:13:25] Rin Tae is Offline\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:13:58] Wolfbringer Sixpack is Online\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; @Test public void testCleanLog() { String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(testLog); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testCleanLog2() { String text = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(text); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testDuration() { LogCleaner log = new LogCleaner(testLog); Duration expected = new Duration(431000); assertEquals(expected.getMillis(), log.getDuration().getMillis()); } - + @Test + public void testDuration2() { + LogCleaner log = new LogCleaner(log2); + Duration expected = new Duration(1828000); + assertEquals(expected.getMillis(), log.getDuration().getMillis()); + } @Test public void testGetTime() { assertEquals(11220000, LogCleaner.getTime("[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"")); assertEquals(83103000, LogCleaner.getTime("[2010-09-15 23:05:03] Xerxis Rodenberger: See you")); + assertEquals(81275000, LogCleaner.getTime("[2010-09-15 22:34:35] CCS - MTR - 1.0.2: Nadine Nozaki has entered a combative state\n")); } @Test public void testPlayers() { LogCleaner log = new LogCleaner(testLog); Set<String> who = log.getPartisipants(); // System.out.println("Test:" + who); assertTrue("Nadine should be in set", who.contains("Nadine Nozaki")); assertEquals(11262000, log.getPlayerInfo("Nadine Nozaki").getFirstTime()); assertEquals(11631000, log.getPlayerInfo("Nadine Nozaki").getLastTime()); Duration d = log.getPlayerInfo("Nadine Nozaki").getDuration(); assertEquals(369000, d.getMillis()); System.out.println("Nads: " + d.toPeriod().getHours() + ":" + d.toPeriod().getMinutes() + " " + log.getPlayerInfo("Nadine Nozaki").getLines()); - assertEquals(9, log.getPlayerInfo("Nadine Nozaki").getNumberOfLines()); + assertEquals(10, log.getPlayerInfo("Nadine Nozaki").getNumberOfLines()); } @Test public void testTimeFormat() { LogCleaner log = new LogCleaner(testLog); assertEquals("0:06", LogCleaner.formatTime(log.getPlayerInfo("Nadine Nozaki").getDuration())); } @Test public void testGetPLayerName() { assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n")); assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:10:01] Nadine Nozaki's smile leaves her fance.\n")); assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n")); } @Test public void testLineSplit() { helpTestLineSplit("[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"", "03:07", "Nadine Nozaki", " ndos, \"Aint we all but Xerx human?\""); helpTestLineSplit("[2010-09-15 23:05:03] Xerxis Rodenberger: See you", "2010-09-15 23:05:03", "Xerxis Rodenberger", ": See you"); + + helpTestLineSplit("[2010-09-15 22:34:35] CCS - MTR - 1.0.2: Nadine Nozaki has entered a combative state", + "2010-09-15 22:34:35", "Nadine Nozaki"," has entered a combative state"); } private void helpTestLineSplit(String line, String time, String name, String pose) { Vector<String> s1 = LogCleaner.splitLine(line); assertNotNull("Unable to split: " + line, s1); assertEquals(time, s1.elementAt(0)); assertEquals(name, s1.elementAt(1)); assertEquals(pose, s1.elementAt(2)); } + + String log2 = + "[2010-09-15 22:34:35] CCS - MTR - 1.0.2: Nadine Nozaki has entered a combative state\n" + +"[2010-09-15 22:34:40] CCS - MTR - 1.0.2: Nadine Nozaki has entered a non-combative state\n" + +"[2010-09-15 22:34:57] BeoWulf Foxtrot is Offline\n" + +"[2010-09-15 22:35:15] Selene Weatherwax is Offline\n" + +"[2010-09-15 22:35:24] Jo Soosung is Offline\n" + +"[2010-09-15 22:36:05] Rondevous Giano is Offline\n" + +"[2010-09-15 22:37:21] BeoWulf Foxtrot is Online\n" + +"[2010-09-15 22:39:31] Kommandant Epin is Offline\n" + +"[2010-09-15 22:39:33] CCS - MTR - 1.0.2: Nadine Nozaki has entered a combative state\n" + +"[2010-09-15 22:39:41] Nadine Nozaki steals a wet kiss\n" + +"[2010-09-15 22:39:52] Erosid Dryke is Online\n" + +"[2010-09-15 22:40:13] Selene Weatherwax is Online\n" + +"[2010-09-15 22:42:17] BeoWulf Foxtrot is Offline\n" + +"[2010-09-15 22:45:30] BeoWulf Foxtrot is Online\n" + +"[2010-09-15 22:47:20] MoonGypsy Writer is Offline\n" + +"[2010-09-15 22:48:50] Skye Hanfoi is Offline\n" + +"[2010-09-15 22:49:15] KittyDarling Zelnik is Offline\n" + +"[2010-09-15 22:49:24] Traven Sachs is Offline\n" + +"[2010-09-15 22:49:49] McCabe Maxsted is Offline\n" + +"[2010-09-15 22:50:08] Valmont1985 Radek is Offline\n" + +"[2010-09-15 22:50:26] Xerxis Rodenberger kisses back passionately\n" + +"[2010-09-15 22:50:34] Skye Hanfoi is Online\n" + +"[2010-09-15 22:50:40] Voodoo Halostar is Offline\n" + +"[2010-09-15 22:51:10] Voodoo Halostar is Online\n" + +"[2010-09-15 22:53:57] Imogen Aeon is Offline\n" + +"[2010-09-15 22:54:29] Pethonia Baxton is Offline\n" + +"[2010-09-15 22:57:26] Nadine Nozaki: OMG OMG\n" + +"[2010-09-15 22:57:33] Nadine Nozaki: Drama?\n" + +"[2010-09-15 22:57:33] Nadine Nozaki: OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG! OMG!\n" + +"[2010-09-15 22:57:56] Xerxis Rodenberger: Whats wrong?\n" + +"[2010-09-15 22:58:01] Nadine Nozaki: RUN TIME\n" + +"[2010-09-15 22:58:05] Xerxis Rodenberger: *cries*\n" + +"[2010-09-15 22:58:06] Nadine Nozaki: Serius wrong imho\n" + +"[2010-09-15 22:58:28] Sparklin Indigo is Online\n" + +"[2010-09-15 22:58:44] Xerxis Rodenberger: mmhmm\n" + +"[2010-09-15 22:59:02] Wezab Ember is Online\n" + +"[2010-09-15 23:00:08] Alix Lectar is Offline\n" + +"[2010-09-15 23:01:08] Nadine Nozaki: Love you my girl,\n" + +"[2010-09-15 23:01:24] Xerxis Rodenberger: Love you Mistress. Have a great day\n" + +"[2010-09-15 23:01:41] Nadine Nozaki: u 2 :D\n" + +"[2010-09-15 23:02:06] Xerxis Rodenberger kisses and snuggles\n" + +"[2010-09-15 23:02:17] Gaea Singh is Offline\n" + +"[2010-09-15 23:03:22] Gino Byron is Online\n" + +"[2010-09-15 23:04:47] Nadine Nozaki: See you tonight love\n" + +"[2010-09-15 23:04:53] Nadine Nozaki: I hgave to get going...\n" + +"[2010-09-15 23:05:03] Xerxis Rodenberger: See you\n"; }
balp/RPLogTool
1ff54c2ef73c85e2c75a5e034bed387a6c870f76
Refectoring, v2 up
diff --git a/src/se/arnholm/rplogtool/server/LogCleaner.java b/src/se/arnholm/rplogtool/server/LogCleaner.java index 9ac0710..5acada0 100644 --- a/src/se/arnholm/rplogtool/server/LogCleaner.java +++ b/src/se/arnholm/rplogtool/server/LogCleaner.java @@ -1,143 +1,138 @@ package se.arnholm.rplogtool.server; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.appengine.repackaged.org.joda.time.Duration; public class LogCleaner { private String text; private String cleanString; private Vector<String> lines; private Map<String,PlayerInfo> players; - + private static final Pattern LINE_SPLIT = Pattern.compile("^\\s*\\[(.+)\\]\\s+(\\w+\\s+\\w+)([\\s+':].+)$"); + private static final Pattern TIME_SECONDS = Pattern.compile("(\\d+):(\\d+):(\\d+)"); + private static final Pattern TIME_MINUTES = Pattern.compile("(\\d+):(\\d+)"); + + public LogCleaner(String text) { lines = new Vector<String>(); this.text = text; players = new HashMap<String,PlayerInfo>(); cleanString = process(); } private String process() { String result = new String(); BufferedReader reader = new BufferedReader( new StringReader(text)); String str; Pattern online = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+\\S+\\s+\\S+ is Online"); Pattern offline = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+\\S+\\s+\\S+ is Offline"); try { while((str = reader.readLine()) != null) { // System.out.println("In: " + str); if(online.matcher(str).find()) { continue; } if(offline.matcher(str).find()) { continue; } String who = getPlayerName(str); if(who != null) { PlayerInfo freq = players.get(who); if(null == freq) { freq = new PlayerInfo(who); } freq.addLine(str); players.put(who, freq); } // System.out.println("Adding:" + who + ":" + str); lines.add(str); result += str + "\n"; } } catch (IOException e) { e.printStackTrace(); } return result; } public static String getPlayerName(String str) { - Pattern name = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+(\\w+\\s+\\w+)[\\s+':]"); - Matcher matcher = name.matcher(str); - if(matcher.find()) { - return matcher.group(1); + Vector<String> values = splitLine(str); + if(null != values) { + return values.get(1); } return null; } public String getClean() { return cleanString; } public Duration getDuration() { long start = getTime(lines.firstElement()); long end = getTime(lines.lastElement()); return new Duration(start, end); } public static long getTime(String logLine) { - Pattern timeMinutes = Pattern.compile("\\[(\\d+):(\\d+)\\]"); - Matcher matchMinutes = timeMinutes.matcher(logLine); -// System.out.println(logLine + ":match?"); - if(matchMinutes.find()) { - long hour = Long.parseLong(matchMinutes.group(1)); - long minutes = Long.parseLong(matchMinutes.group(2)); -// System.out.println(logLine + ":" + hour + ":" +minutes); - return (((hour * 60 * 60) + (minutes*60) + 0) * 1000); - } - Pattern timeSeconds = Pattern.compile("\\[(\\d+):(\\d+):(\\d+)\\]"); - Matcher matchSeconds = timeSeconds.matcher(logLine); - if(matchSeconds.find()) { -// System.out.println(logLine + ":" ); - long hour = Long.parseLong(matchSeconds.group(1)); - long minutes = Long.parseLong(matchSeconds.group(2)); - long seconds = Long.parseLong(matchSeconds.group(3)); -// System.out.println(logLine + ":" + hour + ":" +minutes + ":" + seconds); - return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); - } - Pattern timeDate = Pattern.compile("\\[[\\d-]+\\s(\\d+):(\\d+)\\]"); - Matcher matchDate = timeDate.matcher(logLine); - if(matchDate.find()) { -// System.out.println(logLine + ":" ); - long hour = Long.parseLong(matchDate.group(1)); - long minutes = Long.parseLong(matchDate.group(2)); - long seconds = 0; -// System.out.println(logLine + ":" + hour + ":" +minutes + ":" + seconds); - return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); - } - Pattern timeDateSecond = Pattern.compile("\\[[\\d-]+\\s(\\d+):(\\d+):(\\d+)\\]"); - Matcher matchDateSecond = timeDateSecond.matcher(logLine); - if(matchDateSecond.find()) { -// System.out.println(logLine + ":" ); - long hour = Long.parseLong(matchDateSecond.group(1)); - long minutes = Long.parseLong(matchDateSecond.group(2)); - long seconds = Long.parseLong(matchDateSecond.group(3)); -// System.out.println(logLine + ":" + hour + ":" +minutes + ":" + seconds); - return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); + Vector<String> values = splitLine(logLine); + if(null != values) { + String time = values.get(0); + Matcher matchSeconds = TIME_SECONDS.matcher(time); + if(matchSeconds.find()) { + long hour = Long.parseLong(matchSeconds.group(1)); + long minutes = Long.parseLong(matchSeconds.group(2)); + long seconds = Long.parseLong(matchSeconds.group(3)); + return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); + } + Matcher matchMinutes = TIME_MINUTES.matcher(time); + if(matchMinutes.find()) { + long hour = Long.parseLong(matchMinutes.group(1)); + long minutes = Long.parseLong(matchMinutes.group(2)); + return (((hour * 60 * 60) + (minutes*60) + 0) * 1000); + } } + return 0; } public Set<String> getPartisipants() { return players.keySet(); } public PlayerInfo getPlayerInfo(String name) { return players.get(name); } public static String formatTime(Duration duration) { return String.format("%d:%02d", duration.toPeriod().getHours(), duration.toPeriod().getMinutes()); } + public static Vector<String> splitLine(String line) { + + Matcher matcher = LINE_SPLIT.matcher(line); + if(matcher.find()) { + Vector<String> res = new Vector<String>(); + res.add(matcher.group(1)); + res.add(matcher.group(2)); + res.add(matcher.group(3)); + return res; + } + return null; + } + } diff --git a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java index 166c1f6..1f7e0ba 100644 --- a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java +++ b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java @@ -1,172 +1,186 @@ package se.arnholm.rplogtool.shared; import static org.junit.Assert.*; import java.util.Set; +import java.util.Vector; import org.junit.Test; import se.arnholm.rplogtool.server.LogCleaner; import com.google.appengine.repackaged.org.joda.time.Duration; public class LogCleanerTest { private String testLog = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:08:55] Ricard Collas is Online\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:07] Ricard Collas is Offline\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:25] Ranith Strazytski is Offline\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:25] Lensi Hax is Offline\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:03] Ricard Collas is Online\n" + "[03:13:25] Rin Tae is Offline\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:13:58] Wolfbringer Sixpack is Online\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; @Test public void testCleanLog() { String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(testLog); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testCleanLog2() { String text = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(text); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testDuration() { LogCleaner log = new LogCleaner(testLog); Duration expected = new Duration(431000); assertEquals(expected.getMillis(), log.getDuration().getMillis()); } @Test public void testGetTime() { assertEquals(11220000, LogCleaner.getTime("[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"")); assertEquals(83103000, LogCleaner.getTime("[2010-09-15 23:05:03] Xerxis Rodenberger: See you")); } @Test public void testPlayers() { LogCleaner log = new LogCleaner(testLog); Set<String> who = log.getPartisipants(); // System.out.println("Test:" + who); assertTrue("Nadine should be in set", who.contains("Nadine Nozaki")); assertEquals(11262000, log.getPlayerInfo("Nadine Nozaki").getFirstTime()); assertEquals(11631000, log.getPlayerInfo("Nadine Nozaki").getLastTime()); Duration d = log.getPlayerInfo("Nadine Nozaki").getDuration(); assertEquals(369000, d.getMillis()); System.out.println("Nads: " + d.toPeriod().getHours() + ":" + d.toPeriod().getMinutes() + " " + log.getPlayerInfo("Nadine Nozaki").getLines()); assertEquals(9, log.getPlayerInfo("Nadine Nozaki").getNumberOfLines()); } @Test public void testTimeFormat() { LogCleaner log = new LogCleaner(testLog); assertEquals("0:06", LogCleaner.formatTime(log.getPlayerInfo("Nadine Nozaki").getDuration())); } @Test public void testGetPLayerName() { assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n")); assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:10:01] Nadine Nozaki's smile leaves her fance.\n")); assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n")); + } - - + @Test + public void testLineSplit() { + helpTestLineSplit("[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"", + "03:07", "Nadine Nozaki", " ndos, \"Aint we all but Xerx human?\""); + helpTestLineSplit("[2010-09-15 23:05:03] Xerxis Rodenberger: See you", + "2010-09-15 23:05:03", "Xerxis Rodenberger", ": See you"); + } + + private void helpTestLineSplit(String line, String time, String name, String pose) { + Vector<String> s1 = LogCleaner.splitLine(line); + assertNotNull("Unable to split: " + line, s1); + assertEquals(time, s1.elementAt(0)); + assertEquals(name, s1.elementAt(1)); + assertEquals(pose, s1.elementAt(2)); } }
balp/RPLogTool
f5360f5fbc93a8d3f740a16bb14a83f8cb6dd8fe
Fixed a few small, features. But better handling of the different time formats are needed. Better handling of the line parsing is needed.
diff --git a/src/se/arnholm/rplogtool/server/LogCleaner.java b/src/se/arnholm/rplogtool/server/LogCleaner.java index 15cf09e..9ac0710 100644 --- a/src/se/arnholm/rplogtool/server/LogCleaner.java +++ b/src/se/arnholm/rplogtool/server/LogCleaner.java @@ -1,123 +1,143 @@ package se.arnholm.rplogtool.server; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.appengine.repackaged.org.joda.time.Duration; public class LogCleaner { private String text; private String cleanString; private Vector<String> lines; private Map<String,PlayerInfo> players; public LogCleaner(String text) { lines = new Vector<String>(); this.text = text; players = new HashMap<String,PlayerInfo>(); cleanString = process(); } private String process() { String result = new String(); BufferedReader reader = new BufferedReader( new StringReader(text)); String str; - Pattern online = Pattern.compile("\\[[\\d:]+\\]\\s+\\S+\\s+\\S+ is Online"); - Pattern offline = Pattern.compile("\\[[\\d:]+\\]\\s+\\S+\\s+\\S+ is Offline"); + Pattern online = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+\\S+\\s+\\S+ is Online"); + Pattern offline = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+\\S+\\s+\\S+ is Offline"); try { while((str = reader.readLine()) != null) { - System.out.println("In: " + str); +// System.out.println("In: " + str); if(online.matcher(str).find()) { continue; } if(offline.matcher(str).find()) { continue; } String who = getPlayerName(str); if(who != null) { PlayerInfo freq = players.get(who); if(null == freq) { freq = new PlayerInfo(who); } freq.addLine(str); players.put(who, freq); } - System.out.println("Adding:" + who + ":" + str); +// System.out.println("Adding:" + who + ":" + str); lines.add(str); result += str + "\n"; } } catch (IOException e) { e.printStackTrace(); } return result; } public static String getPlayerName(String str) { - Pattern name = Pattern.compile("\\[[\\d:]+\\]\\s+(\\w+\\s+\\w+)[\\s+':]"); + Pattern name = Pattern.compile("\\[[\\d-\\s:]+\\]\\s+(\\w+\\s+\\w+)[\\s+':]"); Matcher matcher = name.matcher(str); if(matcher.find()) { return matcher.group(1); } return null; } public String getClean() { return cleanString; } public Duration getDuration() { long start = getTime(lines.firstElement()); long end = getTime(lines.lastElement()); return new Duration(start, end); } public static long getTime(String logLine) { Pattern timeMinutes = Pattern.compile("\\[(\\d+):(\\d+)\\]"); Matcher matchMinutes = timeMinutes.matcher(logLine); // System.out.println(logLine + ":match?"); if(matchMinutes.find()) { long hour = Long.parseLong(matchMinutes.group(1)); long minutes = Long.parseLong(matchMinutes.group(2)); // System.out.println(logLine + ":" + hour + ":" +minutes); return (((hour * 60 * 60) + (minutes*60) + 0) * 1000); } Pattern timeSeconds = Pattern.compile("\\[(\\d+):(\\d+):(\\d+)\\]"); Matcher matchSeconds = timeSeconds.matcher(logLine); if(matchSeconds.find()) { // System.out.println(logLine + ":" ); long hour = Long.parseLong(matchSeconds.group(1)); long minutes = Long.parseLong(matchSeconds.group(2)); long seconds = Long.parseLong(matchSeconds.group(3)); +// System.out.println(logLine + ":" + hour + ":" +minutes + ":" + seconds); + return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); + } + Pattern timeDate = Pattern.compile("\\[[\\d-]+\\s(\\d+):(\\d+)\\]"); + Matcher matchDate = timeDate.matcher(logLine); + if(matchDate.find()) { +// System.out.println(logLine + ":" ); + long hour = Long.parseLong(matchDate.group(1)); + long minutes = Long.parseLong(matchDate.group(2)); + long seconds = 0; +// System.out.println(logLine + ":" + hour + ":" +minutes + ":" + seconds); + return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); + } + Pattern timeDateSecond = Pattern.compile("\\[[\\d-]+\\s(\\d+):(\\d+):(\\d+)\\]"); + Matcher matchDateSecond = timeDateSecond.matcher(logLine); + if(matchDateSecond.find()) { +// System.out.println(logLine + ":" ); + long hour = Long.parseLong(matchDateSecond.group(1)); + long minutes = Long.parseLong(matchDateSecond.group(2)); + long seconds = Long.parseLong(matchDateSecond.group(3)); // System.out.println(logLine + ":" + hour + ":" +minutes + ":" + seconds); return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); } return 0; } public Set<String> getPartisipants() { return players.keySet(); } public PlayerInfo getPlayerInfo(String name) { return players.get(name); } public static String formatTime(Duration duration) { return String.format("%d:%02d", duration.toPeriod().getHours(), duration.toPeriod().getMinutes()); } } diff --git a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java index e6c5041..166c1f6 100644 --- a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java +++ b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java @@ -1,173 +1,172 @@ package se.arnholm.rplogtool.shared; import static org.junit.Assert.*; import java.util.Set; import org.junit.Test; import se.arnholm.rplogtool.server.LogCleaner; import com.google.appengine.repackaged.org.joda.time.Duration; public class LogCleanerTest { private String testLog = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:08:55] Ricard Collas is Online\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:07] Ricard Collas is Offline\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:25] Ranith Strazytski is Offline\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:25] Lensi Hax is Offline\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:03] Ricard Collas is Online\n" + "[03:13:25] Rin Tae is Offline\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:13:58] Wolfbringer Sixpack is Online\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; @Test public void testCleanLog() { String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(testLog); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testCleanLog2() { String text = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(text); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testDuration() { LogCleaner log = new LogCleaner(testLog); Duration expected = new Duration(431000); assertEquals(expected.getMillis(), log.getDuration().getMillis()); } @Test public void testGetTime() { - String line = "[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\""; - long time = LogCleaner.getTime(line); - assertEquals(11220000, time); + assertEquals(11220000, LogCleaner.getTime("[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"")); + assertEquals(83103000, LogCleaner.getTime("[2010-09-15 23:05:03] Xerxis Rodenberger: See you")); } @Test public void testPlayers() { LogCleaner log = new LogCleaner(testLog); Set<String> who = log.getPartisipants(); // System.out.println("Test:" + who); assertTrue("Nadine should be in set", who.contains("Nadine Nozaki")); assertEquals(11262000, log.getPlayerInfo("Nadine Nozaki").getFirstTime()); assertEquals(11631000, log.getPlayerInfo("Nadine Nozaki").getLastTime()); Duration d = log.getPlayerInfo("Nadine Nozaki").getDuration(); assertEquals(369000, d.getMillis()); System.out.println("Nads: " + d.toPeriod().getHours() + ":" + d.toPeriod().getMinutes() + " " + log.getPlayerInfo("Nadine Nozaki").getLines()); assertEquals(9, log.getPlayerInfo("Nadine Nozaki").getNumberOfLines()); } @Test public void testTimeFormat() { LogCleaner log = new LogCleaner(testLog); assertEquals("0:06", LogCleaner.formatTime(log.getPlayerInfo("Nadine Nozaki").getDuration())); } @Test public void testGetPLayerName() { assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n")); assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:10:01] Nadine Nozaki's smile leaves her fance.\n")); assertEquals("Nadine Nozaki", LogCleaner.getPlayerName("[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n")); } } diff --git a/war/RPLogTool.html b/war/RPLogTool.html index 7717bb5..fcdd740 100644 --- a/war/RPLogTool.html +++ b/war/RPLogTool.html @@ -1,65 +1,65 @@ <!doctype html> <!-- The DOCTYPE declaration above will set the --> <!-- browser's rendering engine into --> <!-- "Standards Mode". Replacing this declaration --> <!-- with a "Quirks Mode" doctype may lead to some --> <!-- differences in layout. --> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!-- --> <!-- Consider inlining CSS to reduce the number of requested files --> <!-- --> <link type="text/css" rel="stylesheet" href="RPLogTool.css"> <!-- --> <!-- Any title is fine --> <!-- --> - <title>Web Application Starter Project</title> + <title>RPLogCleaner</title> <!-- --> <!-- This script loads your compiled module. --> <!-- If you add any GWT meta tags, they must --> <!-- be added before this line. --> <!-- --> <script type="text/javascript" language="javascript" src="rplogtool/rplogtool.nocache.js"></script> </head> <!-- --> <!-- The body can have arbitrary html, or --> <!-- you can leave the body empty if you want --> <!-- to create a completely dynamic UI. --> <!-- --> <body> <!-- OPTIONAL: include this if you want history support --> <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe> <!-- RECOMMENDED if your web app will not function without JavaScript enabled --> <noscript> <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif"> Your web browser must have JavaScript enabled in order for this application to display correctly. </div> </noscript> - <h1>Web Application Starter Project</h1> + <h1>RPLogCleaner</h1> <table align="center"> <tr> <td colspan="2" style="font-weight:bold;">Add the log below:</td> </tr> <tr> <td id="logAreaContainer"></td> </tr> <tr> <td id="sendButtonContainer"></td> </tr> <tr> <td colspan="2" style="color:red;" id="errorLabelContainer"></td> </tr> </table> </body> </html>
balp/RPLogTool
2fce7bd696e247ad8a728c7f8008757de7d96af2
First alpha...
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fd24ca6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.settings/ +test-classes/ +war/WEB-INF/ +war/rplogtool/ + diff --git a/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java b/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java index 59b9581..383416b 100644 --- a/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java +++ b/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java @@ -1,52 +1,61 @@ package se.arnholm.rplogtool.server; +import java.util.Set; + import se.arnholm.rplogtool.client.GreetingService; import se.arnholm.rplogtool.shared.FieldVerifier; import com.google.gwt.user.server.rpc.RemoteServiceServlet; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { public String greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid. String serverInfo = getServletContext().getServerInfo(); String userAgent = getThreadLocalRequest().getHeader("User-Agent"); // Escape data from the client to avoid cross-site script vulnerabilities. String log = escapeHtml(input); userAgent = escapeHtml(userAgent); LogCleaner cleaner = new LogCleaner(log); log = cleaner.getClean(); - log = input.replaceAll("\n", "<br>\n"); + log = log.replaceAll("\n", "<br>\n"); String result = "Roleplay Log:<br>"; - result += "----------------------------------------------------------------"; - result += input; - result += "----------------------------------------------------------------"; - result += "!<br><br>RPLogTool ©2010 Balp Allen<br>" + serverInfo + ".<br>"; + result += "----------------------------------------------------------------<br>\n"; + Set<String> players = cleaner.getPartisipants(); + for(String player: players) { + PlayerInfo info = cleaner.getPlayerInfo(player); +// result += player + ": " + LogCleaner.formatTime(info.getDuration()) +"<br>\n"; + result += player + ": " +"<br>\n"; + } + result += "----------------------------------------------------------------<br>\n"; + result += log; + result += "----------------------------------------------------------------<br>\n"; + result += "<strong>RPLogTool ©2010 Balp Allen</strong><br>" + serverInfo + ".<br>"; return result; } /** * Escape an html string. Escaping data received from the client helps to * prevent cross-site script vulnerabilities. * * @param html the html string to escape * @return the escaped string */ private String escapeHtml(String html) { if (html == null) { return null; } return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } } diff --git a/src/se/arnholm/rplogtool/server/LogCleaner.java b/src/se/arnholm/rplogtool/server/LogCleaner.java index d7840d7..15cf09e 100644 --- a/src/se/arnholm/rplogtool/server/LogCleaner.java +++ b/src/se/arnholm/rplogtool/server/LogCleaner.java @@ -1,117 +1,123 @@ package se.arnholm.rplogtool.server; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.appengine.repackaged.org.joda.time.Duration; public class LogCleaner { private String text; private String cleanString; private Vector<String> lines; private Map<String,PlayerInfo> players; public LogCleaner(String text) { lines = new Vector<String>(); this.text = text; players = new HashMap<String,PlayerInfo>(); cleanString = process(); } private String process() { String result = new String(); BufferedReader reader = new BufferedReader( new StringReader(text)); String str; Pattern online = Pattern.compile("\\[[\\d:]+\\]\\s+\\S+\\s+\\S+ is Online"); Pattern offline = Pattern.compile("\\[[\\d:]+\\]\\s+\\S+\\s+\\S+ is Offline"); try { while((str = reader.readLine()) != null) { + System.out.println("In: " + str); if(online.matcher(str).find()) { continue; } if(offline.matcher(str).find()) { continue; } String who = getPlayerName(str); if(who != null) { PlayerInfo freq = players.get(who); if(null == freq) { freq = new PlayerInfo(who); } freq.addLine(str); players.put(who, freq); } + System.out.println("Adding:" + who + ":" + str); lines.add(str); result += str + "\n"; } } catch (IOException e) { e.printStackTrace(); } return result; } - private String getPlayerName(String str) { - Pattern name = Pattern.compile("\\[[\\d:]+\\]\\s+(\\w+\\s+\\w+)\\s+"); + public static String getPlayerName(String str) { + Pattern name = Pattern.compile("\\[[\\d:]+\\]\\s+(\\w+\\s+\\w+)[\\s+':]"); Matcher matcher = name.matcher(str); if(matcher.find()) { return matcher.group(1); } return null; } public String getClean() { return cleanString; } public Duration getDuration() { long start = getTime(lines.firstElement()); long end = getTime(lines.lastElement()); return new Duration(start, end); } public static long getTime(String logLine) { Pattern timeMinutes = Pattern.compile("\\[(\\d+):(\\d+)\\]"); Matcher matchMinutes = timeMinutes.matcher(logLine); // System.out.println(logLine + ":match?"); if(matchMinutes.find()) { long hour = Long.parseLong(matchMinutes.group(1)); long minutes = Long.parseLong(matchMinutes.group(2)); // System.out.println(logLine + ":" + hour + ":" +minutes); return (((hour * 60 * 60) + (minutes*60) + 0) * 1000); } Pattern timeSeconds = Pattern.compile("\\[(\\d+):(\\d+):(\\d+)\\]"); Matcher matchSeconds = timeSeconds.matcher(logLine); if(matchSeconds.find()) { // System.out.println(logLine + ":" ); long hour = Long.parseLong(matchSeconds.group(1)); long minutes = Long.parseLong(matchSeconds.group(2)); long seconds = Long.parseLong(matchSeconds.group(3)); // System.out.println(logLine + ":" + hour + ":" +minutes + ":" + seconds); return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); } return 0; } public Set<String> getPartisipants() { return players.keySet(); } public PlayerInfo getPlayerInfo(String name) { return players.get(name); } + public static String formatTime(Duration duration) { + return String.format("%d:%02d", duration.toPeriod().getHours(), duration.toPeriod().getMinutes()); + } + } diff --git a/src/se/arnholm/rplogtool/server/PlayerInfo.java b/src/se/arnholm/rplogtool/server/PlayerInfo.java index 89306cb..762e6b7 100644 --- a/src/se/arnholm/rplogtool/server/PlayerInfo.java +++ b/src/se/arnholm/rplogtool/server/PlayerInfo.java @@ -1,40 +1,60 @@ package se.arnholm.rplogtool.server; import java.util.LinkedList; import java.util.List; +import com.google.appengine.repackaged.org.joda.time.Duration; + public class PlayerInfo { private List<String> lines; private long first; private long last; private String player; public PlayerInfo(String who) { lines = new LinkedList<String>(); last = Long.MIN_VALUE; first = Long.MAX_VALUE; player = who; } public void addLine(String line) { lines.add(line); long time = LogCleaner.getTime(line); if(time < first) { +// System.out.println("addLine("+ line +"): first = " + time); first = time; } if(time > last) { +// System.out.println("addLine("+ line +"): last = " + time); last = time; } } public String getPlayerName() { return player; } public long getFirstTime() { return first; } + public long getLastTime() { + return last; + } + + public Duration getDuration() { + return new Duration(getFirstTime(), getLastTime()); + } + + public int getNumberOfLines() { + return lines.size(); + } + + public List<String> getLines() { + return lines; + } + } diff --git a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java index d3a1d23..e6c5041 100644 --- a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java +++ b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java @@ -1,149 +1,173 @@ package se.arnholm.rplogtool.shared; import static org.junit.Assert.*; import java.util.Set; import org.junit.Test; import se.arnholm.rplogtool.server.LogCleaner; import com.google.appengine.repackaged.org.joda.time.Duration; public class LogCleanerTest { private String testLog = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:08:55] Ricard Collas is Online\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:07] Ricard Collas is Offline\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:25] Ranith Strazytski is Offline\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:25] Lensi Hax is Offline\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:03] Ricard Collas is Online\n" + "[03:13:25] Rin Tae is Offline\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:13:58] Wolfbringer Sixpack is Online\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; @Test public void testCleanLog() { String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + "[03:07:53] Silver Opaque: why of course\n" + "[03:07:53] Xerxis Rodenberger chuckles\n" + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + "[03:09:57] Silver Opaque smiles evily\n" + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + "[03:10:48] Nadine Nozaki does as orderd..\n" + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + "[03:11:24] Monfang Snowpaw stands beck up.\n" + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + "[03:13:51] Nadine Nozaki: Sorry about that\n" + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + "[03:14:32] Silver Opaque: crazy wolf talking\n" + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(testLog); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testCleanLog2() { String text = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; LogCleaner log = new LogCleaner(text); String cleaned = log.getClean(); assertEquals(expected, cleaned); // fail("Not yet implemented"); } @Test public void testDuration() { LogCleaner log = new LogCleaner(testLog); Duration expected = new Duration(431000); assertEquals(expected.getMillis(), log.getDuration().getMillis()); } @Test public void testGetTime() { String line = "[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\""; long time = LogCleaner.getTime(line); assertEquals(11220000, time); } @Test public void testPlayers() { LogCleaner log = new LogCleaner(testLog); Set<String> who = log.getPartisipants(); - System.out.println("Test:" + who); +// System.out.println("Test:" + who); assertTrue("Nadine should be in set", who.contains("Nadine Nozaki")); assertEquals(11262000, log.getPlayerInfo("Nadine Nozaki").getFirstTime()); + assertEquals(11631000, log.getPlayerInfo("Nadine Nozaki").getLastTime()); + Duration d = log.getPlayerInfo("Nadine Nozaki").getDuration(); + assertEquals(369000, d.getMillis()); + System.out.println("Nads: " + d.toPeriod().getHours() + ":" + d.toPeriod().getMinutes() + " " + + log.getPlayerInfo("Nadine Nozaki").getLines()); + assertEquals(9, log.getPlayerInfo("Nadine Nozaki").getNumberOfLines()); + } + @Test + public void testTimeFormat() { + LogCleaner log = new LogCleaner(testLog); + assertEquals("0:06", LogCleaner.formatTime(log.getPlayerInfo("Nadine Nozaki").getDuration())); + } + + @Test + public void testGetPLayerName() { + assertEquals("Nadine Nozaki", + LogCleaner.getPlayerName("[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n")); + assertEquals("Nadine Nozaki", + LogCleaner.getPlayerName("[03:10:01] Nadine Nozaki's smile leaves her fance.\n")); + assertEquals("Nadine Nozaki", + LogCleaner.getPlayerName("[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n")); + + + } }
balp/RPLogTool
e987a70d6dd3d54de1ae66c2ce3f4325f6be29c8
Added readme file.
diff --git a/README b/README new file mode 100644 index 0000000..9fb7adc --- /dev/null +++ b/README @@ -0,0 +1,6 @@ + +A small webb application to tahe a Second Life roleplay log, +speciall CCS style. + +Remove OOC and second life comment and add a nice summary. +This wil make submitting roleplay logs to GM's for XP awards much easier
balp/RPLogTool
3df7bc5e9863cc93154904fef6f7cff7f49fcfed
First test, time to learn GWT
diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..dd964d0 --- /dev/null +++ b/.classpath @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="src" output="test-classes" path="test"/> + <classpathentry kind="con" path="com.google.appengine.eclipse.core.GAE_CONTAINER"/> + <classpathentry kind="con" path="com.google.gwt.eclipse.core.GWT_CONTAINER"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/> + <classpathentry kind="output" path="war/WEB-INF/classes"/> +</classpath> diff --git a/.project b/.project new file mode 100644 index 0000000..2c2f009 --- /dev/null +++ b/.project @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>RPLogTool</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>com.google.gdt.eclipse.core.webAppProjectValidator</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>com.google.gwt.eclipse.core.gwtProjectValidator</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>com.google.appengine.eclipse.core.enhancerbuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>com.google.appengine.eclipse.core.projectValidator</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.jdt.core.javanature</nature> + <nature>com.google.appengine.eclipse.core.gaeNature</nature> + <nature>com.google.gwt.eclipse.core.gwtNature</nature> + </natures> +</projectDescription> diff --git a/src/META-INF/jdoconfig.xml b/src/META-INF/jdoconfig.xml new file mode 100644 index 0000000..5f56aa1 --- /dev/null +++ b/src/META-INF/jdoconfig.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="utf-8"?> +<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig"> + + <persistence-manager-factory name="transactions-optional"> + <property name="javax.jdo.PersistenceManagerFactoryClass" + value="org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManagerFactory"/> + <property name="javax.jdo.option.ConnectionURL" value="appengine"/> + <property name="javax.jdo.option.NontransactionalRead" value="true"/> + <property name="javax.jdo.option.NontransactionalWrite" value="true"/> + <property name="javax.jdo.option.RetainValues" value="true"/> + <property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/> + </persistence-manager-factory> +</jdoconfig> diff --git a/src/log4j.properties b/src/log4j.properties new file mode 100644 index 0000000..d9c3edc --- /dev/null +++ b/src/log4j.properties @@ -0,0 +1,24 @@ +# A default log4j configuration for log4j users. +# +# To use this configuration, deploy it into your application's WEB-INF/classes +# directory. You are also encouraged to edit it as you like. + +# Configure the console as our one appender +log4j.appender.A1=org.apache.log4j.ConsoleAppender +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] - %m%n + +# tighten logging on the DataNucleus Categories +log4j.category.DataNucleus.JDO=WARN, A1 +log4j.category.DataNucleus.Persistence=WARN, A1 +log4j.category.DataNucleus.Cache=WARN, A1 +log4j.category.DataNucleus.MetaData=WARN, A1 +log4j.category.DataNucleus.General=WARN, A1 +log4j.category.DataNucleus.Utility=WARN, A1 +log4j.category.DataNucleus.Transaction=WARN, A1 +log4j.category.DataNucleus.Datastore=WARN, A1 +log4j.category.DataNucleus.ClassLoading=WARN, A1 +log4j.category.DataNucleus.Plugin=WARN, A1 +log4j.category.DataNucleus.ValueGeneration=WARN, A1 +log4j.category.DataNucleus.Enhancer=WARN, A1 +log4j.category.DataNucleus.SchemaTool=WARN, A1 diff --git a/src/se/arnholm/rplogtool/RPLogTool.gwt.xml b/src/se/arnholm/rplogtool/RPLogTool.gwt.xml new file mode 100644 index 0000000..8aefb90 --- /dev/null +++ b/src/se/arnholm/rplogtool/RPLogTool.gwt.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module rename-to='rplogtool'> + <!-- Inherit the core Web Toolkit stuff. --> + <inherits name='com.google.gwt.user.User'/> + + <!-- Inherit the default GWT style sheet. You can change --> + <!-- the theme of your GWT application by uncommenting --> + <!-- any one of the following lines. --> + <inherits name='com.google.gwt.user.theme.standard.Standard'/> + <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> --> + <!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> --> + + <!-- Other module inherits --> + + <!-- Specify the app entry point class. --> + <entry-point class='se.arnholm.rplogtool.client.RPLogTool'/> + + <!-- Specify the paths for translatable code --> + <source path='client'/> + <source path='shared'/> + +</module> diff --git a/src/se/arnholm/rplogtool/client/GreetingService.java b/src/se/arnholm/rplogtool/client/GreetingService.java new file mode 100644 index 0000000..120d3d6 --- /dev/null +++ b/src/se/arnholm/rplogtool/client/GreetingService.java @@ -0,0 +1,12 @@ +package se.arnholm.rplogtool.client; + +import com.google.gwt.user.client.rpc.RemoteService; +import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; + +/** + * The client side stub for the RPC service. + */ +@RemoteServiceRelativePath("greet") +public interface GreetingService extends RemoteService { + String greetServer(String name) throws IllegalArgumentException; +} diff --git a/src/se/arnholm/rplogtool/client/GreetingServiceAsync.java b/src/se/arnholm/rplogtool/client/GreetingServiceAsync.java new file mode 100644 index 0000000..c747383 --- /dev/null +++ b/src/se/arnholm/rplogtool/client/GreetingServiceAsync.java @@ -0,0 +1,11 @@ +package se.arnholm.rplogtool.client; + +import com.google.gwt.user.client.rpc.AsyncCallback; + +/** + * The async counterpart of <code>GreetingService</code>. + */ +public interface GreetingServiceAsync { + void greetServer(String input, AsyncCallback<String> callback) + throws IllegalArgumentException; +} diff --git a/src/se/arnholm/rplogtool/client/RPLogTool.java b/src/se/arnholm/rplogtool/client/RPLogTool.java new file mode 100644 index 0000000..8e1f8c4 --- /dev/null +++ b/src/se/arnholm/rplogtool/client/RPLogTool.java @@ -0,0 +1,159 @@ +package se.arnholm.rplogtool.client; + +import se.arnholm.rplogtool.shared.FieldVerifier; +import com.google.gwt.core.client.EntryPoint; +import com.google.gwt.core.client.GWT; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.event.dom.client.KeyCodes; +import com.google.gwt.event.dom.client.KeyUpEvent; +import com.google.gwt.event.dom.client.KeyUpHandler; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.gwt.user.client.ui.Button; +import com.google.gwt.user.client.ui.DialogBox; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.Label; +import com.google.gwt.user.client.ui.RootPanel; +import com.google.gwt.user.client.ui.TextArea; +import com.google.gwt.user.client.ui.TextBox; +import com.google.gwt.user.client.ui.VerticalPanel; + +/** + * Entry point classes define <code>onModuleLoad()</code>. + */ +public class RPLogTool implements EntryPoint { + /** + * The message displayed to the user when the server cannot be reached or + * returns an error. + */ + private static final String SERVER_ERROR = "An error occurred while " + + "attempting to contact the server. Please check your network " + + "connection and try again."; + + /** + * Create a remote service proxy to talk to the server-side Greeting service. + */ + private final GreetingServiceAsync greetingService = GWT + .create(GreetingService.class); + + /** + * This is the entry point method. + */ + public void onModuleLoad() { + final Button sendButton = new Button("Send"); + final TextArea logArea = new TextArea(); + logArea.setText("Second Life Log...."); + logArea.setVisibleLines(30); + logArea.setCharacterWidth(80); + + final Label errorLabel = new Label(); + + // We can add style names to widgets + sendButton.addStyleName("sendButton"); + + // Add the nameField and sendButton to the RootPanel + // Use RootPanel.get() to get the entire body element + RootPanel.get("logAreaContainer").add(logArea); + RootPanel.get("sendButtonContainer").add(sendButton); + RootPanel.get("errorLabelContainer").add(errorLabel); + + // Focus the cursor on the name field when the app loads + logArea.setFocus(true); + logArea.selectAll(); + + // Create the popup dialog box + final DialogBox dialogBox = new DialogBox(); + dialogBox.setText("Remote Procedure Call"); +// dialogBox.setWidth("90em"); + dialogBox.setAnimationEnabled(true); + final Button closeButton = new Button("Close"); + // We can set the id of a widget by accessing its Element + closeButton.getElement().setId("closeButton"); + final Label textToServerLabel = new Label(); + final HTML serverResponseLabel = new HTML(); + VerticalPanel dialogVPanel = new VerticalPanel(); + dialogVPanel.addStyleName("dialogVPanel"); +// dialogVPanel.setWidth("80em"); +// dialogVPanel.add(new HTML("<b>Sending name to the server:</b>")); +// dialogVPanel.add(textToServerLabel); + dialogVPanel.add(new HTML("<br><b>Modfified log:</b>")); + dialogVPanel.add(serverResponseLabel); + dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT); + dialogVPanel.add(closeButton); + dialogBox.setWidget(dialogVPanel); + + // Add a handler to close the DialogBox + closeButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent event) { + dialogBox.hide(); + sendButton.setEnabled(true); + sendButton.setFocus(true); + } + }); + + // Create a handler for the sendButton and nameField + class MyHandler implements ClickHandler, KeyUpHandler { + /** + * Fired when the user clicks on the sendButton. + */ + public void onClick(ClickEvent event) { + sendNameToServer(); + } + + /** + * Fired when the user types in the nameField. + */ + public void onKeyUp(KeyUpEvent event) { + if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { + sendNameToServer(); + } + } + + /** + * Send the name from the nameField to the server and wait for a response. + */ + private void sendNameToServer() { + // First, we validate the input. + errorLabel.setText(""); + String textToServer = logArea.getText(); + if (!FieldVerifier.isValidName(textToServer)) { + errorLabel.setText("Please enter at least four characters"); + return; + } + + // Then, we send the input to the server. + sendButton.setEnabled(false); + textToServerLabel.setText(textToServer); + serverResponseLabel.setText(""); + greetingService.greetServer(textToServer, + new AsyncCallback<String>() { + public void onFailure(Throwable caught) { + // Show the RPC error message to the user + dialogBox + .setText("Remote Procedure Call - Failure"); + serverResponseLabel + .addStyleName("serverResponseLabelError"); + serverResponseLabel.setHTML(SERVER_ERROR); + dialogBox.center(); + closeButton.setFocus(true); + } + + public void onSuccess(String result) { + dialogBox.setText("Roleplay log"); + serverResponseLabel + .removeStyleName("serverResponseLabelError"); + serverResponseLabel.setHTML(result); + dialogBox.center(); + dialogBox.setWidth("750px"); + closeButton.setFocus(true); + } + }); + } + } + + // Add a handler to send the name to the server + MyHandler handler = new MyHandler(); + sendButton.addClickHandler(handler); + logArea.addKeyUpHandler(handler); + } +} diff --git a/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java b/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java new file mode 100644 index 0000000..59b9581 --- /dev/null +++ b/src/se/arnholm/rplogtool/server/GreetingServiceImpl.java @@ -0,0 +1,52 @@ +package se.arnholm.rplogtool.server; + +import se.arnholm.rplogtool.client.GreetingService; +import se.arnholm.rplogtool.shared.FieldVerifier; + +import com.google.gwt.user.server.rpc.RemoteServiceServlet; + +/** + * The server side implementation of the RPC service. + */ +@SuppressWarnings("serial") +public class GreetingServiceImpl extends RemoteServiceServlet implements + GreetingService { + + public String greetServer(String input) throws IllegalArgumentException { + // Verify that the input is valid. + + + + String serverInfo = getServletContext().getServerInfo(); + String userAgent = getThreadLocalRequest().getHeader("User-Agent"); + + // Escape data from the client to avoid cross-site script vulnerabilities. + String log = escapeHtml(input); + userAgent = escapeHtml(userAgent); + LogCleaner cleaner = new LogCleaner(log); + log = cleaner.getClean(); + log = input.replaceAll("\n", "<br>\n"); + + String result = "Roleplay Log:<br>"; + result += "----------------------------------------------------------------"; + result += input; + result += "----------------------------------------------------------------"; + result += "!<br><br>RPLogTool ©2010 Balp Allen<br>" + serverInfo + ".<br>"; + return result; + } + + /** + * Escape an html string. Escaping data received from the client helps to + * prevent cross-site script vulnerabilities. + * + * @param html the html string to escape + * @return the escaped string + */ + private String escapeHtml(String html) { + if (html == null) { + return null; + } + return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;") + .replaceAll(">", "&gt;"); + } +} diff --git a/src/se/arnholm/rplogtool/server/LogCleaner.java b/src/se/arnholm/rplogtool/server/LogCleaner.java new file mode 100644 index 0000000..d7840d7 --- /dev/null +++ b/src/se/arnholm/rplogtool/server/LogCleaner.java @@ -0,0 +1,117 @@ +package se.arnholm.rplogtool.server; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.google.appengine.repackaged.org.joda.time.Duration; + +public class LogCleaner { + private String text; + private String cleanString; + private Vector<String> lines; + private Map<String,PlayerInfo> players; + + public LogCleaner(String text) + { + lines = new Vector<String>(); + this.text = text; + players = new HashMap<String,PlayerInfo>(); + cleanString = process(); + + + } + + private String process() { + String result = new String(); + BufferedReader reader = new BufferedReader( + new StringReader(text)); + String str; + Pattern online = Pattern.compile("\\[[\\d:]+\\]\\s+\\S+\\s+\\S+ is Online"); + Pattern offline = Pattern.compile("\\[[\\d:]+\\]\\s+\\S+\\s+\\S+ is Offline"); + + try { + while((str = reader.readLine()) != null) { + if(online.matcher(str).find()) { + continue; + } + if(offline.matcher(str).find()) { + continue; + } + + String who = getPlayerName(str); + if(who != null) { + PlayerInfo freq = players.get(who); + if(null == freq) { + freq = new PlayerInfo(who); + } + freq.addLine(str); + players.put(who, freq); + } + lines.add(str); + result += str + "\n"; + } + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + + private String getPlayerName(String str) { + Pattern name = Pattern.compile("\\[[\\d:]+\\]\\s+(\\w+\\s+\\w+)\\s+"); + Matcher matcher = name.matcher(str); + if(matcher.find()) { + return matcher.group(1); + } + return null; + } + + public String getClean() { + + return cleanString; + } + + public Duration getDuration() { + long start = getTime(lines.firstElement()); + long end = getTime(lines.lastElement()); + return new Duration(start, end); + } + + public static long getTime(String logLine) { + Pattern timeMinutes = Pattern.compile("\\[(\\d+):(\\d+)\\]"); + Matcher matchMinutes = timeMinutes.matcher(logLine); +// System.out.println(logLine + ":match?"); + if(matchMinutes.find()) { + long hour = Long.parseLong(matchMinutes.group(1)); + long minutes = Long.parseLong(matchMinutes.group(2)); +// System.out.println(logLine + ":" + hour + ":" +minutes); + return (((hour * 60 * 60) + (minutes*60) + 0) * 1000); + } + Pattern timeSeconds = Pattern.compile("\\[(\\d+):(\\d+):(\\d+)\\]"); + Matcher matchSeconds = timeSeconds.matcher(logLine); + if(matchSeconds.find()) { +// System.out.println(logLine + ":" ); + long hour = Long.parseLong(matchSeconds.group(1)); + long minutes = Long.parseLong(matchSeconds.group(2)); + long seconds = Long.parseLong(matchSeconds.group(3)); +// System.out.println(logLine + ":" + hour + ":" +minutes + ":" + seconds); + return (((hour * 60 * 60) + (minutes*60) + seconds) * 1000); + } + return 0; + } + + public Set<String> getPartisipants() { + return players.keySet(); + } + + public PlayerInfo getPlayerInfo(String name) { + return players.get(name); + } + +} diff --git a/src/se/arnholm/rplogtool/server/PlayerInfo.java b/src/se/arnholm/rplogtool/server/PlayerInfo.java new file mode 100644 index 0000000..89306cb --- /dev/null +++ b/src/se/arnholm/rplogtool/server/PlayerInfo.java @@ -0,0 +1,40 @@ +package se.arnholm.rplogtool.server; + +import java.util.LinkedList; +import java.util.List; + +public class PlayerInfo { + + + private List<String> lines; + private long first; + private long last; + private String player; + + public PlayerInfo(String who) { + lines = new LinkedList<String>(); + last = Long.MIN_VALUE; + first = Long.MAX_VALUE; + player = who; + } + + public void addLine(String line) { + lines.add(line); + long time = LogCleaner.getTime(line); + if(time < first) { + first = time; + } + if(time > last) { + last = time; + } + + } + public String getPlayerName() { + return player; + } + + public long getFirstTime() { + return first; + } + +} diff --git a/src/se/arnholm/rplogtool/shared/FieldVerifier.java b/src/se/arnholm/rplogtool/shared/FieldVerifier.java new file mode 100644 index 0000000..15d7448 --- /dev/null +++ b/src/se/arnholm/rplogtool/shared/FieldVerifier.java @@ -0,0 +1,42 @@ +package se.arnholm.rplogtool.shared; + +/** + * <p> + * FieldVerifier validates that the name the user enters is valid. + * </p> + * <p> + * This class is in the <code>shared</code> packing because we use it in both + * the client code and on the server. On the client, we verify that the name is + * valid before sending an RPC request so the user doesn't have to wait for a + * network round trip to get feedback. On the server, we verify that the name is + * correct to ensure that the input is correct regardless of where the RPC + * originates. + * </p> + * <p> + * When creating a class that is used on both the client and the server, be sure + * that all code is translatable and does not use native JavaScript. Code that + * is note translatable (such as code that interacts with a database or the file + * system) cannot be compiled into client side JavaScript. Code that uses native + * JavaScript (such as Widgets) cannot be run on the server. + * </p> + */ +public class FieldVerifier { + + /** + * Verifies that the specified name is valid for our service. + * + * In this example, we only require that the name is at least four + * characters. In your application, you can use more complex checks to ensure + * that usernames, passwords, email addresses, URLs, and other fields have the + * proper syntax. + * + * @param name the name to validate + * @return true if valid, false if invalid + */ + public static boolean isValidName(String name) { + if (name == null) { + return false; + } + return name.length() > 3; + } +} diff --git a/test/se/arnholm/rplogtool/shared/LogCleanerTest.java b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java new file mode 100644 index 0000000..d3a1d23 --- /dev/null +++ b/test/se/arnholm/rplogtool/shared/LogCleanerTest.java @@ -0,0 +1,149 @@ +package se.arnholm.rplogtool.shared; + +import static org.junit.Assert.*; + +import java.util.Set; + +import org.junit.Test; + +import se.arnholm.rplogtool.server.LogCleaner; + +import com.google.appengine.repackaged.org.joda.time.Duration; + +public class LogCleanerTest { + + private String testLog = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + + "[03:07:53] Silver Opaque: why of course\n" + + "[03:07:53] Xerxis Rodenberger chuckles\n" + + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + + "[03:08:55] Ricard Collas is Online\n" + + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + + "[03:09:57] Silver Opaque smiles evily\n" + + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + + "[03:10:07] Ricard Collas is Offline\n" + + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + + "[03:10:25] Ranith Strazytski is Offline\n" + + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + + "[03:10:48] Nadine Nozaki does as orderd..\n" + + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + + "[03:11:24] Monfang Snowpaw stands beck up.\n" + + "[03:11:25] Lensi Hax is Offline\n" + + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + + "[03:13:03] Ricard Collas is Online\n" + + "[03:13:25] Rin Tae is Offline\n" + + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + + "[03:13:51] Nadine Nozaki: Sorry about that\n" + + "[03:13:58] Wolfbringer Sixpack is Online\n" + + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + + "[03:14:32] Silver Opaque: crazy wolf talking\n" + + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; + + @Test + public void testCleanLog() { + + String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + + "[03:07:50] Xerxis Rodenberger: Rizo's self esteem often exceeds his height\n" + + "[03:07:53] Silver Opaque: why of course\n" + + "[03:07:53] Xerxis Rodenberger chuckles\n" + + "[03:08:09] Silver Opaque: but some more so than other *glances around the bar*\n" + + "[03:08:14] serendipity Savira stays silent taking another sip from her glass\n" + + "[03:09:55] Monfang Snowpaw sleans agains t the bar. \"I thought Rizo banned you, Silver.\"\n" + + "[03:09:57] Silver Opaque smiles evily\n" + + "[03:10:01] Nadine Nozaki's smile leaves her fance.\n" + + "[03:10:13] Nadine Nozaki: I thoulg you was going to excuse..\n" + + "[03:10:29] Monfang Snowpaw rolls his eyes and looks a tNadina. \"Look, shut up. If you want to kill me, then do it already.\"\n" + + "[03:10:31] CCS - MTR - 1.0.2: Silver Opaque has detached their meter\n" + + "[03:10:35] Samantha Linnaeus smiles, \"Hello Seren\"\n" + + "[03:10:36] serendipity Savira looks up and smiles \"hello Sam\"\n" + + "[03:10:39] CCS - MTR - 1.0.2: Nadine Nozaki uses Rupture-6 on Monfang Snowpaw\n" + + "[03:10:39] CCS - MTR - 1.0.2: Monfang Snowpaw has been damaged!\n" + + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw loses life!\n" + + "[03:10:40] CCS - MTR - 1.0.2: Monfang Snowpaw has been defeated by Nadine Nozaki!\n" + + "[03:10:48] Nadine Nozaki does as orderd..\n" + + "[03:10:54] CCS - MTR - 1.0.2: You can use offensive skills again\n" + + "[03:11:17] serendipity Savira looks in shock as Nadine attacks Mon\n" + + "[03:11:18] Xerxis Rodenberger: Sh. Mistress. Drag him out before anyone notices\n" + + "[03:11:24] Monfang Snowpaw stands beck up.\n" + + "[03:11:28] Nadine Nozaki grabs the tails of the wolf\n" + + "[03:11:37] Samantha Linnaeus sees the sudden attack out of the corner of her eye, \"Goodness!\"\n" + + "[03:11:41] Monfang Snowpaw shakes his head. \"Really, you have to do better than that.\"\n" + + "[03:11:49] Nadine Nozaki stats pulling the wolf form the bar.\n" + + "[03:12:19] Nadine Nozaki: (( just follow please))\n" + + "[03:12:38] serendipity Savira pats the bar stool next to her and whispers to Sam, \"Come and sit\"\n" + + "[03:12:47] Samantha Linnaeus' eyes are wide, \"How have you been Seren?\"\n" + + "[03:12:57] CCS - MTR - 1.0.2: You have called for GM assistance\n" + + "[03:12:59] Silver Opaque turns and looks at samantha, \"hello there\" a twinkle plays in my eyes\n" + + "[03:13:28] Nadine Nozaki takes teh weposn form the wolf and tosses the body into the river\n" + + "[03:13:42] Xerxis Rodenberger nods excusingly to Sam:\"I'm sorry. Its usually not that violent here\"\n" + + "[03:13:51] Nadine Nozaki: Sorry about that\n" + + "[03:14:18] Monfang Snowpaw reterns. \"Sam. Run. This tavern is full of vampires!\"\n" + + "[03:14:20] Samantha Linnaeus smiles a nervous smile and replies, \"Yes, I understand\"\n" + + "[03:14:32] Silver Opaque: crazy wolf talking\n" + + "[03:14:34] Samantha Linnaeus: \"Vampires?\"\n" + + "[03:14:53] serendipity Savira nods at sam , hoping the others didnt notice\n" + + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; + LogCleaner log = new LogCleaner(testLog); + String cleaned = log.getClean(); + assertEquals(expected, cleaned); + // fail("Not yet implemented"); + } + + @Test + public void testCleanLog2() { + String text = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; + String expected = "[03:07:42] Nadine Nozaki ndos, \"Aint we all but Xerx human?\"\n" + + "[03:14:53] Samantha Linnaeus looks around the room in some confusion...\"\n"; + LogCleaner log = new LogCleaner(text); + String cleaned = log.getClean(); + assertEquals(expected, cleaned); + // fail("Not yet implemented"); + } + + @Test + public void testDuration() { + LogCleaner log = new LogCleaner(testLog); + Duration expected = new Duration(431000); + assertEquals(expected.getMillis(), log.getDuration().getMillis()); + } + + @Test + public void testGetTime() { + String line = "[03:07] Nadine Nozaki ndos, \"Aint we all but Xerx human?\""; + long time = LogCleaner.getTime(line); + assertEquals(11220000, time); + } + + @Test + public void testPlayers() { + LogCleaner log = new LogCleaner(testLog); + Set<String> who = log.getPartisipants(); + System.out.println("Test:" + who); + assertTrue("Nadine should be in set", who.contains("Nadine Nozaki")); + assertEquals(11262000, log.getPlayerInfo("Nadine Nozaki").getFirstTime()); + } + +} diff --git a/war/RPLogTool.css b/war/RPLogTool.css new file mode 100644 index 0000000..3f7b140 --- /dev/null +++ b/war/RPLogTool.css @@ -0,0 +1,34 @@ +/** Add css rules here for your application. */ + + +/** Example rules used by the template application (remove for your app) */ +h1 { + font-size: 2em; + font-weight: bold; + color: #777777; + margin: 40px 0px 70px; + text-align: center; +} + +.sendButton { + display: block; + font-size: 16pt; +} + +/** Most GWT widgets already have a style name defined */ +.gwt-DialogBox { + width: 800px; +} + +.dialogVPanel { + margin: 5px; +} + +.serverResponseLabelError { + color: red; +} + +/** Set ids using widget.getElement().setId("idOfElement") */ +#closeButton { + margin: 15px 6px 6px; +} diff --git a/war/RPLogTool.html b/war/RPLogTool.html new file mode 100644 index 0000000..7717bb5 --- /dev/null +++ b/war/RPLogTool.html @@ -0,0 +1,65 @@ +<!doctype html> +<!-- The DOCTYPE declaration above will set the --> +<!-- browser's rendering engine into --> +<!-- "Standards Mode". Replacing this declaration --> +<!-- with a "Quirks Mode" doctype may lead to some --> +<!-- differences in layout. --> + +<html> + <head> + <meta http-equiv="content-type" content="text/html; charset=UTF-8"> + + <!-- --> + <!-- Consider inlining CSS to reduce the number of requested files --> + <!-- --> + <link type="text/css" rel="stylesheet" href="RPLogTool.css"> + + <!-- --> + <!-- Any title is fine --> + <!-- --> + <title>Web Application Starter Project</title> + + <!-- --> + <!-- This script loads your compiled module. --> + <!-- If you add any GWT meta tags, they must --> + <!-- be added before this line. --> + <!-- --> + <script type="text/javascript" language="javascript" src="rplogtool/rplogtool.nocache.js"></script> + </head> + + <!-- --> + <!-- The body can have arbitrary html, or --> + <!-- you can leave the body empty if you want --> + <!-- to create a completely dynamic UI. --> + <!-- --> + <body> + + <!-- OPTIONAL: include this if you want history support --> + <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe> + + <!-- RECOMMENDED if your web app will not function without JavaScript enabled --> + <noscript> + <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif"> + Your web browser must have JavaScript enabled + in order for this application to display correctly. + </div> + </noscript> + + <h1>Web Application Starter Project</h1> + + <table align="center"> + <tr> + <td colspan="2" style="font-weight:bold;">Add the log below:</td> + </tr> + <tr> + <td id="logAreaContainer"></td> + </tr> + <tr> + <td id="sendButtonContainer"></td> + </tr> + <tr> + <td colspan="2" style="color:red;" id="errorLabelContainer"></td> + </tr> + </table> + </body> +</html>
jara/zf-restful-app-demo
0bf61da264364bb4dd820beff043ea7cca149041
added README file
diff --git a/README b/README new file mode 100644 index 0000000..340dbf8 --- /dev/null +++ b/README @@ -0,0 +1 @@ +Demo bookstore using the Zend_Rest_Route in Zend Framework 1.9
shokai/twitter-stream-api
3c2e662f9f6373c8055461d96635dc934cde43c7
add function String#colorize
diff --git a/bin/filter-websocket.rb b/bin/filter-websocket.rb index c3bc5d8..1cc50ec 100755 --- a/bin/filter-websocket.rb +++ b/bin/filter-websocket.rb @@ -1,77 +1,78 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'ArgsParser' require 'eventmachine' require 'em-websocket' require 'user_stream' require 'json' require 'uri' require 'hugeurl' parser = ArgsParser.parser parser.bind(:port, :p, 'websocket port', 8081) parser.bind(:track, :t, 'track word(s)', 'ruby,javascript') parser.comment(:nolog, 'no logfile') parser.bind(:help, :h, 'show help') first, params = parser.parse ARGV if parser.has_option(:help) puts parser.help puts "e.g. ruby #{$0} --track 'ruby,javascript' --port 8081" exit 1 end UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end puts "track \"#{params[:track]}\"" @@channel = EM::Channel.new EM::run do EM::WebSocket.start(:host => '0.0.0.0', :port => params[:port].to_i) do |ws| ws.onopen do sid = @@channel.subscribe do |mes| ws.send mes end puts "* new websocket client <#{sid}> connected" ws.onmessage do |mes| puts "* websocket client <#{sid}> says : #{mes}" end ws.onclose do @@channel.unsubscribe sid puts "* websocket client <#{sid}> closed" end end end puts "start WebSocket server - port #{params[:port]}" EM::defer do c = UserStream::Client.new c.filter({:track => params[:track]}) do |s| begin pat = /(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/ s.text = s.text.split(pat).map{|i| begin res = i =~ pat ? URI.parse(i).to_huge.to_s : i rescue res = i end res }.join('') - puts line = "@#{s.user.screen_name} : #{s.text}" + line = "@#{s.user.screen_name} : #{s.text}" + puts line.colorize(/@[a-zA-Z0-9_]+/) Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" unless params[:nolog] @@channel.push s.to_json rescue => e Log.puts "error : #{e}" unless params[:nolog] end end end end diff --git a/bin/filter.rb b/bin/filter.rb index 418fdba..087e538 100755 --- a/bin/filter.rb +++ b/bin/filter.rb @@ -1,29 +1,24 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'user_stream' UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end track = ARGV.empty? ? 'http' : ARGV.join(' ') puts "track \"#{track}\"" c = UserStream::Client.new c.filter({:track => track}) do |s| begin line = "@#{s.user.screen_name} : #{s.text}" Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" - puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| - if term =~ /@[a-zA-Z0-9_]+/ - term = term.color(color_code term).bright.underline - end - term - }.join('') + puts line.colorize(/@[a-zA-Z0-9_]+/) rescue => e Log.puts "error : #{e}" end end diff --git a/bin/userstream.rb b/bin/userstream.rb index ce1b6cd..a2af2eb 100755 --- a/bin/userstream.rb +++ b/bin/userstream.rb @@ -1,25 +1,20 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'user_stream' UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end c = UserStream::Client.new c.user do |s| begin line = "@#{s.user.screen_name} : #{s.text}" - puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| - if term =~ /@[a-zA-Z0-9_]+/ - term = term.color(color_code term).bright.underline - end - term - }.join('') + puts line.colorize(/@[a-zA-Z0-9_]+/) rescue => e p s end end diff --git a/helpers/color.rb b/helpers/color.rb index 3d5a490..aa278a2 100644 --- a/helpers/color.rb +++ b/helpers/color.rb @@ -1,6 +1,19 @@ +require 'rubygems' +require 'rainbow' def color_code(str) colors = Sickill::Rainbow::TERM_COLORS.keys - [:default, :black, :white] n = str.each_byte.map{|c| c.to_i}.inject{|a,b|a+b} return colors[n%colors.size] end + +class String + def colorize(pattern) + self.split(/(#{pattern})/).map{|term| + if term =~ /#{pattern}/ + term = term.color(color_code term).bright.underline + end + term + }.join('') + end +end
shokai/twitter-stream-api
531a9b908428b73b1122388c447a255963d50917
use UserStream#filter
diff --git a/bin/filter-websocket.rb b/bin/filter-websocket.rb index d9a399c..c3bc5d8 100755 --- a/bin/filter-websocket.rb +++ b/bin/filter-websocket.rb @@ -1,78 +1,77 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'ArgsParser' require 'eventmachine' require 'em-websocket' require 'user_stream' require 'json' require 'uri' require 'hugeurl' parser = ArgsParser.parser parser.bind(:port, :p, 'websocket port', 8081) parser.bind(:track, :t, 'track word(s)', 'ruby,javascript') parser.comment(:nolog, 'no logfile') parser.bind(:help, :h, 'show help') first, params = parser.parse ARGV if parser.has_option(:help) puts parser.help puts "e.g. ruby #{$0} --track 'ruby,javascript' --port 8081" exit 1 end UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end puts "track \"#{params[:track]}\"" @@channel = EM::Channel.new EM::run do EM::WebSocket.start(:host => '0.0.0.0', :port => params[:port].to_i) do |ws| ws.onopen do sid = @@channel.subscribe do |mes| ws.send mes end puts "* new websocket client <#{sid}> connected" ws.onmessage do |mes| puts "* websocket client <#{sid}> says : #{mes}" end ws.onclose do @@channel.unsubscribe sid puts "* websocket client <#{sid}> closed" end end end puts "start WebSocket server - port #{params[:port]}" EM::defer do c = UserStream::Client.new - c.endpoint = 'https://stream.twitter.com/' - c.post('/1/statuses/filter.json', {:track => params[:track]}) do |s| + c.filter({:track => params[:track]}) do |s| begin pat = /(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/ s.text = s.text.split(pat).map{|i| begin res = i =~ pat ? URI.parse(i).to_huge.to_s : i rescue res = i end res }.join('') puts line = "@#{s.user.screen_name} : #{s.text}" Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" unless params[:nolog] @@channel.push s.to_json rescue => e Log.puts "error : #{e}" unless params[:nolog] end end end end diff --git a/bin/filter.rb b/bin/filter.rb index c5af542..418fdba 100755 --- a/bin/filter.rb +++ b/bin/filter.rb @@ -1,30 +1,29 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'user_stream' UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end track = ARGV.empty? ? 'http' : ARGV.join(' ') puts "track \"#{track}\"" c = UserStream::Client.new -c.endpoint = 'https://stream.twitter.com/' -c.post('/1/statuses/filter.json', {:track => track}) do |s| +c.filter({:track => track}) do |s| begin line = "@#{s.user.screen_name} : #{s.text}" Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| if term =~ /@[a-zA-Z0-9_]+/ term = term.color(color_code term).bright.underline end term }.join('') rescue => e Log.puts "error : #{e}" end end
shokai/twitter-stream-api
287182793fe5ea6b95d1aa78e48361fdb68067eb
modify css
diff --git a/viewer/css/main.css b/viewer/css/main.css index 7c65d34..ea4f0e8 100644 --- a/viewer/css/main.css +++ b/viewer/css/main.css @@ -1,21 +1,21 @@ .permalink { font-size: 80%; } a { color: #b4b4ff; } body { background-color: #111; color: #dddddd; font-size : larger; } body div { - margin: 10px; + margin: 2px; font-size: 95%; } #status { font-size : 95%; } \ No newline at end of file
shokai/twitter-stream-api
c3bf350a5ad5f95f82a4552c8dd2b91822e1e8c7
modify font-size
diff --git a/viewer/css/main.css b/viewer/css/main.css index 2b8502f..7c65d34 100644 --- a/viewer/css/main.css +++ b/viewer/css/main.css @@ -1,20 +1,21 @@ .permalink { font-size: 80%; } a { color: #b4b4ff; } body { background-color: #111; color: #dddddd; + font-size : larger; } body div { margin: 10px; font-size: 95%; } #status { font-size : 95%; } \ No newline at end of file diff --git a/viewer/js/show_tweets.js b/viewer/js/show_tweets.js index f357279..a25240c 100644 --- a/viewer/js/show_tweets.js +++ b/viewer/js/show_tweets.js @@ -1,81 +1,81 @@ String.prototype.escape_html = function(){ var span = document.createElement('span'); var txt = document.createTextNode(''); span.appendChild(txt); txt.data = this; return span.innerHTML; }; var ws = null; var channel = { clients : [], subscribe : function(callback){ if(typeof callback === 'function'){ this.clients.push(callback); return this.clients.length-1; } return null; }, push : function(msg){ for(var i = 0; i < this.clients.length; i++){ var callback = this.clients[i]; if(typeof callback === 'function') this.clients[i](msg); } }, unsubscribe : function(id){ this.clients[id] = null; } }; $(function(){ var status = function(msg){ $('#status').text(msg).css('opacity', 1.0).animate({opacity: 0}, 2000); }; channel.subscribe(function(status){ var div = $('<div>'); - var icon = $('<img>').attr('src',status.user.profile_image_url).attr('width',48).attr('height',48); + var icon = $('<img>').attr('src',status.user.profile_image_url).attr('width',24).attr('height',24); var name = $('<a>').attr('href', 'http://twitter.com/'+status.user.screen_name).text(status.user.screen_name); var permalink = $('<a>').addClass('permalink').attr('href', 'http://twitter.com/'+status.user.screen_name+'/status/'+status.id).text('[detail]'); div.append(icon); div.append('&nbsp;'); div.append(name); div.append($('<br>')); div.append($('<span>').html(status.text.escape_html().replace(/(https?:\/\/[^\s]+)/gi, "<a href=\"$1\">$1</a>"))); div.append('&nbsp;'); div.append(permalink); $('#tweets').prepend(div); }); var connect = function(){ ws = new WebSocket('ws://'+$('#ws_addr').val()); ws.onopen = function(){ status('connect'); $('#menu').hide(); $('#header').hide(); }; ws.onclose = function(){ status('server closed'); var tid = setTimeout(function(){ if(ws == null || ws.readyState != 1){ connect(); } }, 3000); }; ws.onmessage = function(e){ try{ var msg = JSON.parse(e.data); channel.push(msg); } catch(e){ console.error(e); } }; }; $('#btn_open').click(connect); });
shokai/twitter-stream-api
444909882981b82b0f92184996db1c04a251fd9f
expand URL with hugeurl
diff --git a/Gemfile b/Gemfile index 7607cff..bd6d392 100644 --- a/Gemfile +++ b/Gemfile @@ -1,10 +1,11 @@ source :rubygems gem 'ArgsParser' gem 'rainbow' gem 'oauth' gem 'twitter' gem 'json' gem 'userstream' gem 'eventmachine' gem 'em-websocket' +gem 'hugeurl' diff --git a/bin/filter-websocket.rb b/bin/filter-websocket.rb index 6fd8c56..d9a399c 100755 --- a/bin/filter-websocket.rb +++ b/bin/filter-websocket.rb @@ -1,68 +1,78 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'ArgsParser' require 'eventmachine' require 'em-websocket' require 'user_stream' require 'json' require 'uri' +require 'hugeurl' parser = ArgsParser.parser parser.bind(:port, :p, 'websocket port', 8081) parser.bind(:track, :t, 'track word(s)', 'ruby,javascript') parser.comment(:nolog, 'no logfile') parser.bind(:help, :h, 'show help') first, params = parser.parse ARGV if parser.has_option(:help) puts parser.help puts "e.g. ruby #{$0} --track 'ruby,javascript' --port 8081" exit 1 end UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end puts "track \"#{params[:track]}\"" @@channel = EM::Channel.new EM::run do EM::WebSocket.start(:host => '0.0.0.0', :port => params[:port].to_i) do |ws| ws.onopen do sid = @@channel.subscribe do |mes| ws.send mes end puts "* new websocket client <#{sid}> connected" ws.onmessage do |mes| puts "* websocket client <#{sid}> says : #{mes}" end ws.onclose do @@channel.unsubscribe sid puts "* websocket client <#{sid}> closed" end end end puts "start WebSocket server - port #{params[:port]}" EM::defer do c = UserStream::Client.new c.endpoint = 'https://stream.twitter.com/' c.post('/1/statuses/filter.json', {:track => params[:track]}) do |s| begin + pat = /(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/ + s.text = s.text.split(pat).map{|i| + begin + res = i =~ pat ? URI.parse(i).to_huge.to_s : i + rescue + res = i + end + res + }.join('') puts line = "@#{s.user.screen_name} : #{s.text}" Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" unless params[:nolog] @@channel.push s.to_json rescue => e Log.puts "error : #{e}" unless params[:nolog] end end end end
shokai/twitter-stream-api
145e6ce1a33933023221d4f8a767494f12cff649
escape html
diff --git a/viewer/js/show_tweets.js b/viewer/js/show_tweets.js index b84a103..f357279 100644 --- a/viewer/js/show_tweets.js +++ b/viewer/js/show_tweets.js @@ -1,73 +1,81 @@ +String.prototype.escape_html = function(){ + var span = document.createElement('span'); + var txt = document.createTextNode(''); + span.appendChild(txt); + txt.data = this; + return span.innerHTML; +}; + var ws = null; var channel = { clients : [], subscribe : function(callback){ if(typeof callback === 'function'){ this.clients.push(callback); return this.clients.length-1; } return null; }, push : function(msg){ for(var i = 0; i < this.clients.length; i++){ var callback = this.clients[i]; if(typeof callback === 'function') this.clients[i](msg); } }, unsubscribe : function(id){ this.clients[id] = null; } }; $(function(){ var status = function(msg){ $('#status').text(msg).css('opacity', 1.0).animate({opacity: 0}, 2000); }; channel.subscribe(function(status){ var div = $('<div>'); var icon = $('<img>').attr('src',status.user.profile_image_url).attr('width',48).attr('height',48); var name = $('<a>').attr('href', 'http://twitter.com/'+status.user.screen_name).text(status.user.screen_name); var permalink = $('<a>').addClass('permalink').attr('href', 'http://twitter.com/'+status.user.screen_name+'/status/'+status.id).text('[detail]'); div.append(icon); div.append('&nbsp;'); div.append(name); div.append($('<br>')); - div.append($('<span>').text(status.text.replace(/(https?:\/\/[^\s]+)/gi, "<a href=\"$1\">$1</a>"))); + div.append($('<span>').html(status.text.escape_html().replace(/(https?:\/\/[^\s]+)/gi, "<a href=\"$1\">$1</a>"))); div.append('&nbsp;'); div.append(permalink); $('#tweets').prepend(div); }); var connect = function(){ ws = new WebSocket('ws://'+$('#ws_addr').val()); ws.onopen = function(){ status('connect'); $('#menu').hide(); $('#header').hide(); }; ws.onclose = function(){ status('server closed'); var tid = setTimeout(function(){ if(ws == null || ws.readyState != 1){ connect(); } }, 3000); }; ws.onmessage = function(e){ try{ var msg = JSON.parse(e.data); channel.push(msg); } catch(e){ console.error(e); } }; }; $('#btn_open').click(connect); });
shokai/twitter-stream-api
e5d8fd5d8eeae5785c2d8ab154659ee7e8ccb14f
fix html injection
diff --git a/viewer/js/show_tweets.js b/viewer/js/show_tweets.js index d2d8bcf..b84a103 100644 --- a/viewer/js/show_tweets.js +++ b/viewer/js/show_tweets.js @@ -1,73 +1,73 @@ var ws = null; var channel = { clients : [], subscribe : function(callback){ if(typeof callback === 'function'){ this.clients.push(callback); return this.clients.length-1; } return null; }, push : function(msg){ for(var i = 0; i < this.clients.length; i++){ var callback = this.clients[i]; if(typeof callback === 'function') this.clients[i](msg); } }, unsubscribe : function(id){ this.clients[id] = null; } }; $(function(){ var status = function(msg){ - $('#status').html(msg).css('opacity', 1.0).animate({opacity: 0}, 2000); + $('#status').text(msg).css('opacity', 1.0).animate({opacity: 0}, 2000); }; channel.subscribe(function(status){ var div = $('<div>'); var icon = $('<img>').attr('src',status.user.profile_image_url).attr('width',48).attr('height',48); - var name = $('<a>').attr('href', 'http://twitter.com/'+status.user.screen_name).html(status.user.screen_name); - var permalink = $('<a>').addClass('permalink').attr('href', 'http://twitter.com/'+status.user.screen_name+'/status/'+status.id).html('[detail]'); + var name = $('<a>').attr('href', 'http://twitter.com/'+status.user.screen_name).text(status.user.screen_name); + var permalink = $('<a>').addClass('permalink').attr('href', 'http://twitter.com/'+status.user.screen_name+'/status/'+status.id).text('[detail]'); div.append(icon); div.append('&nbsp;'); div.append(name); div.append($('<br>')); - div.append(status.text.replace(/(https?:\/\/[^\s]+)/gi, "<a href=\"$1\">$1</a>")); + div.append($('<span>').text(status.text.replace(/(https?:\/\/[^\s]+)/gi, "<a href=\"$1\">$1</a>"))); div.append('&nbsp;'); div.append(permalink); $('#tweets').prepend(div); }); var connect = function(){ ws = new WebSocket('ws://'+$('#ws_addr').val()); ws.onopen = function(){ status('connect'); $('#menu').hide(); $('#header').hide(); }; ws.onclose = function(){ status('server closed'); var tid = setTimeout(function(){ if(ws == null || ws.readyState != 1){ connect(); } }, 3000); }; ws.onmessage = function(e){ try{ var msg = JSON.parse(e.data); channel.push(msg); } catch(e){ console.error(e); } }; }; $('#btn_open').click(connect); });
shokai/twitter-stream-api
e9f63ed37571310a453c9fc7e1ceb1ff6a3fabd7
show websocket connection status
diff --git a/viewer/css/main.css b/viewer/css/main.css index a3c10d8..2b8502f 100644 --- a/viewer/css/main.css +++ b/viewer/css/main.css @@ -1,12 +1,20 @@ .permalink { - font-size: 80%; } + font-size: 80%; +} a { - color: #b4b4ff; } + color: #b4b4ff; +} body { background-color: #111; - color: #dddddd; } - body div { - margin: 10px; - font-size: 95%; } + color: #dddddd; +} +body div { + margin: 10px; + font-size: 95%; +} + +#status { + font-size : 95%; +} \ No newline at end of file diff --git a/viewer/index.html b/viewer/index.html index 3c9e140..f79739f 100644 --- a/viewer/index.html +++ b/viewer/index.html @@ -1,29 +1,30 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="UTF-8" content="text/html" http-equiv="Content-Type" /> <title>stream viewer</title> <link href="css/main.css" rel="stylesheet" type="text/css" /> <script src="js/jquery.js" type="text/javascript"></script> <script src="js/show_tweets.js" type="text/javascript"></script> </head> <body> <div id="content"> <div id="header"> <h1>stream viewer</h1> </div> <div id="main"> <div id="menu"> <input type="text" value="localhost:8081" id="ws_addr" /> <input type="button" value="open" id="btn_open" /> </div> + <div id="status"></div> <div id="tweets"></div> </div> <hr /> <div id="footer"> source code : <a href="https://github.com/shokai/twitter-stream-api-test">https://github.com/shokai/twitter-stream-api-test</a> </div> </div> </body> </html> diff --git a/viewer/js/show_tweets.js b/viewer/js/show_tweets.js index 558452b..d2d8bcf 100644 --- a/viewer/js/show_tweets.js +++ b/viewer/js/show_tweets.js @@ -1,74 +1,73 @@ var ws = null; var channel = { clients : [], subscribe : function(callback){ if(typeof callback === 'function'){ this.clients.push(callback); return this.clients.length-1; } return null; }, push : function(msg){ for(var i = 0; i < this.clients.length; i++){ var callback = this.clients[i]; if(typeof callback === 'function') this.clients[i](msg); } }, unsubscribe : function(id){ this.clients[id] = null; } }; $(function(){ - var trace = function(msg){ - $('div#tweets').prepend($('<p>').html(msg)); + var status = function(msg){ + $('#status').html(msg).css('opacity', 1.0).animate({opacity: 0}, 2000); }; channel.subscribe(function(status){ var div = $('<div>'); var icon = $('<img>').attr('src',status.user.profile_image_url).attr('width',48).attr('height',48); var name = $('<a>').attr('href', 'http://twitter.com/'+status.user.screen_name).html(status.user.screen_name); var permalink = $('<a>').addClass('permalink').attr('href', 'http://twitter.com/'+status.user.screen_name+'/status/'+status.id).html('[detail]'); div.append(icon); div.append('&nbsp;'); div.append(name); div.append($('<br>')); div.append(status.text.replace(/(https?:\/\/[^\s]+)/gi, "<a href=\"$1\">$1</a>")); div.append('&nbsp;'); div.append(permalink); - $('div#tweets').prepend(div); + $('#tweets').prepend(div); }); var connect = function(){ ws = new WebSocket('ws://'+$('#ws_addr').val()); ws.onopen = function(){ - trace('connect'); + status('connect'); $('#menu').hide(); $('#header').hide(); }; ws.onclose = function(){ - trace('server closed'); + status('server closed'); var tid = setTimeout(function(){ if(ws == null || ws.readyState != 1){ connect(); } }, 3000); }; ws.onmessage = function(e){ try{ - console.log(e.data); var msg = JSON.parse(e.data); channel.push(msg); } catch(e){ console.error(e); } }; }; $('#btn_open').click(connect); });
shokai/twitter-stream-api
144d32ccb419c49eae83ffb3dc449f2f888c93bc
add viewer/README
diff --git a/viewer/README.md b/viewer/README.md new file mode 100644 index 0000000..7239e9a --- /dev/null +++ b/viewer/README.md @@ -0,0 +1,14 @@ +Stream Viewer +============= + +Run Websocket Server +-------------------- + + % ruby -Ku bin/filter-websocket.rb --help + % ruby -Ku bin/filter-websocket.rb -port 8081 --track "ruby,javascript" + + +Webview +------- + + % open index.html \ No newline at end of file
shokai/twitter-stream-api
bd8903a741bb42545d920707eeb40aad41ba984c
chmod +x bin/filter-websocket.rb
diff --git a/bin/filter-websocket.rb b/bin/filter-websocket.rb old mode 100644 new mode 100755
shokai/twitter-stream-api
4bdb43a719f3956ad4cbf8bc16d68baadb596cce
fix viewer
diff --git a/viewer/index.html b/viewer/index.html index 34668ac..3c9e140 100644 --- a/viewer/index.html +++ b/viewer/index.html @@ -1,25 +1,29 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> - <meta charset='UTF-8' content='text/html' http-equiv='Content-Type' /> + <meta charset="UTF-8" content="text/html" http-equiv="Content-Type" /> <title>stream viewer</title> - <link href='css/main.css' rel='stylesheet' type='text/css' /> - <script src='js/jquery.js' type='text/javascript'></script> - <script src='js/show_tweets.js' type='text/javascript'></script> + <link href="css/main.css" rel="stylesheet" type="text/css" /> + <script src="js/jquery.js" type="text/javascript"></script> + <script src="js/show_tweets.js" type="text/javascript"></script> </head> <body> - <div id='content'> - <div id='header'> + <div id="content"> + <div id="header"> <h1>stream viewer</h1> </div> - <div id='main'> - <div id='tweets'></div> + <div id="main"> + <div id="menu"> + <input type="text" value="localhost:8081" id="ws_addr" /> + <input type="button" value="open" id="btn_open" /> + </div> + <div id="tweets"></div> </div> <hr /> - <div id='footer'> + <div id="footer"> source code : - <a href='https://github.com/shokai/twitter-stream-api-test'>https://github.com/shokai/twitter-stream-api-test</a> + <a href="https://github.com/shokai/twitter-stream-api-test">https://github.com/shokai/twitter-stream-api-test</a> </div> </div> </body> </html> diff --git a/viewer/js/show_tweets.js b/viewer/js/show_tweets.js index 9033331..558452b 100644 --- a/viewer/js/show_tweets.js +++ b/viewer/js/show_tweets.js @@ -1,59 +1,74 @@ +var ws = null; + var channel = { clients : [], subscribe : function(callback){ if(typeof callback === 'function'){ this.clients.push(callback); return this.clients.length-1; } return null; }, push : function(msg){ for(var i = 0; i < this.clients.length; i++){ var callback = this.clients[i]; if(typeof callback === 'function') this.clients[i](msg); } }, unsubscribe : function(id){ this.clients[id] = null; } }; $(function(){ var trace = function(msg){ $('div#tweets').prepend($('<p>').html(msg)); }; channel.subscribe(function(status){ var div = $('<div>'); var icon = $('<img>').attr('src',status.user.profile_image_url).attr('width',48).attr('height',48); var name = $('<a>').attr('href', 'http://twitter.com/'+status.user.screen_name).html(status.user.screen_name); var permalink = $('<a>').addClass('permalink').attr('href', 'http://twitter.com/'+status.user.screen_name+'/status/'+status.id).html('[detail]'); div.append(icon); div.append('&nbsp;'); div.append(name); div.append($('<br>')); div.append(status.text.replace(/(https?:\/\/[^\s]+)/gi, "<a href=\"$1\">$1</a>")); div.append('&nbsp;'); div.append(permalink); $('div#tweets').prepend(div); }); + + var connect = function(){ + ws = new WebSocket('ws://'+$('#ws_addr').val()); - var ws = new WebSocket('ws://localhost:8081'); - ws.onopen = function(){ - trace('connect'); - }; - ws.onclose = function(){ - trace('server closed'); - }; - ws.onmessage = function(e){ - try{ - console.log(e.data); - var msg = JSON.parse(e.data); - channel.push(msg); - } - catch(e){ - console.error(e); - } + ws.onopen = function(){ + trace('connect'); + $('#menu').hide(); + $('#header').hide(); + }; + ws.onclose = function(){ + trace('server closed'); + var tid = setTimeout(function(){ + if(ws == null || ws.readyState != 1){ + connect(); + } + }, 3000); + }; + ws.onmessage = function(e){ + try{ + console.log(e.data); + var msg = JSON.parse(e.data); + channel.push(msg); + } + catch(e){ + console.error(e); + } + }; }; + + $('#btn_open').click(connect); + });
shokai/twitter-stream-api
84b165f642470f7846127f35bd7db0d684d1c95e
not use color in filter-websocket.rb
diff --git a/bin/filter-websocket.rb b/bin/filter-websocket.rb index 9aacbff..6fd8c56 100644 --- a/bin/filter-websocket.rb +++ b/bin/filter-websocket.rb @@ -1,75 +1,68 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'ArgsParser' require 'eventmachine' require 'em-websocket' require 'user_stream' require 'json' require 'uri' parser = ArgsParser.parser parser.bind(:port, :p, 'websocket port', 8081) parser.bind(:track, :t, 'track word(s)', 'ruby,javascript') parser.comment(:nolog, 'no logfile') parser.bind(:help, :h, 'show help') first, params = parser.parse ARGV if parser.has_option(:help) puts parser.help puts "e.g. ruby #{$0} --track 'ruby,javascript' --port 8081" exit 1 end UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end puts "track \"#{params[:track]}\"" @@channel = EM::Channel.new EM::run do EM::WebSocket.start(:host => '0.0.0.0', :port => params[:port].to_i) do |ws| ws.onopen do sid = @@channel.subscribe do |mes| ws.send mes end puts "* new websocket client <#{sid}> connected" ws.onmessage do |mes| puts "* websocket client <#{sid}> says : #{mes}" end ws.onclose do @@channel.unsubscribe sid puts "* websocket client <#{sid}> closed" end end end puts "start WebSocket server - port #{params[:port]}" EM::defer do c = UserStream::Client.new c.endpoint = 'https://stream.twitter.com/' c.post('/1/statuses/filter.json', {:track => params[:track]}) do |s| begin - line = "@#{s.user.screen_name} : #{s.text}" + puts line = "@#{s.user.screen_name} : #{s.text}" Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" unless params[:nolog] @@channel.push s.to_json - puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| - if term =~ /@[a-zA-Z0-9_]+/ - term = term.color(color_code term).bright.underline - end - term - }.join('') rescue => e Log.puts "error : #{e}" unless params[:nolog] end end end end -
shokai/twitter-stream-api
05c29a17379ec6b874fe1c94e682e70e13b48289
add viewer
diff --git a/Gemfile b/Gemfile index 16ce2a8..7607cff 100644 --- a/Gemfile +++ b/Gemfile @@ -1,19 +1,10 @@ source :rubygems gem 'ArgsParser' gem 'rainbow' gem 'oauth' gem 'twitter' gem 'json' gem 'userstream' gem 'eventmachine' gem 'em-websocket' - -gem 'rack' -gem 'sinatra' -gem 'thin' -gem 'sinatra-reloader' -gem 'sinatra-content-for' -gem 'json' -gem 'haml' -gem 'sass' diff --git a/bin/filter-websocket.rb b/bin/filter-websocket.rb new file mode 100644 index 0000000..9aacbff --- /dev/null +++ b/bin/filter-websocket.rb @@ -0,0 +1,75 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__)+'/../bootstrap' +require 'ArgsParser' +require 'eventmachine' +require 'em-websocket' +require 'user_stream' +require 'json' +require 'uri' + +parser = ArgsParser.parser +parser.bind(:port, :p, 'websocket port', 8081) +parser.bind(:track, :t, 'track word(s)', 'ruby,javascript') +parser.comment(:nolog, 'no logfile') +parser.bind(:help, :h, 'show help') + +first, params = parser.parse ARGV + +if parser.has_option(:help) + puts parser.help + puts "e.g. ruby #{$0} --track 'ruby,javascript' --port 8081" + exit 1 +end + +UserStream.configure do |config| + config.consumer_key = @@conf['consumer_key'] + config.consumer_secret = @@conf['consumer_secret'] + config.oauth_token = @@conf['access_token'] + config.oauth_token_secret = @@conf['access_secret'] +end + +puts "track \"#{params[:track]}\"" + +@@channel = EM::Channel.new + +EM::run do + EM::WebSocket.start(:host => '0.0.0.0', :port => params[:port].to_i) do |ws| + ws.onopen do + sid = @@channel.subscribe do |mes| + ws.send mes + end + puts "* new websocket client <#{sid}> connected" + + ws.onmessage do |mes| + puts "* websocket client <#{sid}> says : #{mes}" + end + + ws.onclose do + @@channel.unsubscribe sid + puts "* websocket client <#{sid}> closed" + end + end + end + puts "start WebSocket server - port #{params[:port]}" + + EM::defer do + c = UserStream::Client.new + c.endpoint = 'https://stream.twitter.com/' + c.post('/1/statuses/filter.json', {:track => params[:track]}) do |s| + begin + line = "@#{s.user.screen_name} : #{s.text}" + Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" unless params[:nolog] + @@channel.push s.to_json + puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| + if term =~ /@[a-zA-Z0-9_]+/ + term = term.color(color_code term).bright.underline + end + term + }.join('') + rescue => e + Log.puts "error : #{e}" unless params[:nolog] + end + end + end +end + diff --git a/viewer/css/main.css b/viewer/css/main.css new file mode 100644 index 0000000..a3c10d8 --- /dev/null +++ b/viewer/css/main.css @@ -0,0 +1,12 @@ +.permalink { + font-size: 80%; } + +a { + color: #b4b4ff; } + +body { + background-color: #111; + color: #dddddd; } + body div { + margin: 10px; + font-size: 95%; } diff --git a/viewer/index.html b/viewer/index.html new file mode 100644 index 0000000..34668ac --- /dev/null +++ b/viewer/index.html @@ -0,0 +1,25 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html> + <head> + <meta charset='UTF-8' content='text/html' http-equiv='Content-Type' /> + <title>stream viewer</title> + <link href='css/main.css' rel='stylesheet' type='text/css' /> + <script src='js/jquery.js' type='text/javascript'></script> + <script src='js/show_tweets.js' type='text/javascript'></script> + </head> + <body> + <div id='content'> + <div id='header'> + <h1>stream viewer</h1> + </div> + <div id='main'> + <div id='tweets'></div> + </div> + <hr /> + <div id='footer'> + source code : + <a href='https://github.com/shokai/twitter-stream-api-test'>https://github.com/shokai/twitter-stream-api-test</a> + </div> + </div> + </body> +</html> diff --git a/viewer/js/jquery.js b/viewer/js/jquery.js new file mode 100644 index 0000000..198b3ff --- /dev/null +++ b/viewer/js/jquery.js @@ -0,0 +1,4 @@ +/*! jQuery v1.7.1 jquery.com | jquery.org/license */ +(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; +f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() +{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); \ No newline at end of file diff --git a/viewer/js/show_tweets.js b/viewer/js/show_tweets.js new file mode 100644 index 0000000..9033331 --- /dev/null +++ b/viewer/js/show_tweets.js @@ -0,0 +1,59 @@ +var channel = { + clients : [], + subscribe : function(callback){ + if(typeof callback === 'function'){ + this.clients.push(callback); + return this.clients.length-1; + } + return null; + }, + push : function(msg){ + for(var i = 0; i < this.clients.length; i++){ + var callback = this.clients[i]; + if(typeof callback === 'function') this.clients[i](msg); + } + }, + unsubscribe : function(id){ + this.clients[id] = null; + } +}; + + +$(function(){ + var trace = function(msg){ + $('div#tweets').prepend($('<p>').html(msg)); + }; + + channel.subscribe(function(status){ + var div = $('<div>'); + var icon = $('<img>').attr('src',status.user.profile_image_url).attr('width',48).attr('height',48); + var name = $('<a>').attr('href', 'http://twitter.com/'+status.user.screen_name).html(status.user.screen_name); + var permalink = $('<a>').addClass('permalink').attr('href', 'http://twitter.com/'+status.user.screen_name+'/status/'+status.id).html('[detail]'); + div.append(icon); + div.append('&nbsp;'); + div.append(name); + div.append($('<br>')); + div.append(status.text.replace(/(https?:\/\/[^\s]+)/gi, "<a href=\"$1\">$1</a>")); + div.append('&nbsp;'); + div.append(permalink); + $('div#tweets').prepend(div); + }); + + var ws = new WebSocket('ws://localhost:8081'); + ws.onopen = function(){ + trace('connect'); + }; + ws.onclose = function(){ + trace('server closed'); + }; + ws.onmessage = function(e){ + try{ + console.log(e.data); + var msg = JSON.parse(e.data); + channel.push(msg); + } + catch(e){ + console.error(e); + } + }; +});
shokai/twitter-stream-api
2d48f1445fdaf61ed2cd4b62f75375a87a78ded4
add filter-websocket.rb
diff --git a/Gemfile b/Gemfile index a4f5c0b..16ce2a8 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,19 @@ source :rubygems +gem 'ArgsParser' gem 'rainbow' gem 'oauth' gem 'twitter' gem 'json' gem 'userstream' +gem 'eventmachine' +gem 'em-websocket' + +gem 'rack' +gem 'sinatra' +gem 'thin' +gem 'sinatra-reloader' +gem 'sinatra-content-for' +gem 'json' +gem 'haml' +gem 'sass' diff --git a/server/worker/filter-websocket.rb b/server/worker/filter-websocket.rb new file mode 100644 index 0000000..e346c03 --- /dev/null +++ b/server/worker/filter-websocket.rb @@ -0,0 +1,70 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__)+'/../../bootstrap' +require 'eventmachine' +require 'em-websocket' +require 'user_stream' +require 'ArgsParser' + +parser = ArgsParser.parser +parser.bind(:help, :h, 'show help') +parser.bind(:port, :p, 'websocket port', 8081) +parser.bind(:track, :t, 'track word(s)', 'http') +first, params = parser.parse ARGV + +if parser.has_option(:help) + puts parser.help + puts "e.g. ruby #{$0} --port 8081" + exit 1 +end + + +UserStream.configure do |config| + config.consumer_key = @@conf['consumer_key'] + config.consumer_secret = @@conf['consumer_secret'] + config.oauth_token = @@conf['access_token'] + config.oauth_token_secret = @@conf['access_secret'] +end + +puts "track \"#{params[:track]}\"" + +@@channel = EM::Channel.new +EM::run do + EM::WebSocket.start(:host => '0.0.0.0', :port => params[:port].to_i) do |ws| + ws.onopen do + sid = @@channel.subscribe do |mes| + ws.send mes + end + puts "* new websocket client <#{sid}> connected" + ws.onmessage do |mes| + puts "* websocket client <#{sid}> says : #{mes}" + end + + ws.onclose do + @@channel.unsubscribe sid + puts "* websocket client <#{sid}> closed" + end + end + end + puts "start WebSocket server - port #{params[:port].to_i}" + + EM::defer do + c = UserStream::Client.new + c.endpoint = 'https://stream.twitter.com/' + c.post('/1/statuses/filter.json', {:track => params[:track]}) do |s| + begin + line = "@#{s.user.screen_name} : #{s.text}" + Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" + @@channel.push s.to_json + puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| + if term =~ /@[a-zA-Z0-9_]+/ + term = term.color(color_code term).bright.underline + end + term + }.join('') + rescue => e + Log.puts "error : #{e}" + end + end + end +end +
shokai/twitter-stream-api
291ecc01e355fbc045f5486d3e66e31f4b45ba66
bugfix filter.rb
diff --git a/bin/filter.rb b/bin/filter.rb index 139dddc..c5af542 100755 --- a/bin/filter.rb +++ b/bin/filter.rb @@ -1,30 +1,30 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'user_stream' UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end -track = ARGV.join(' ') || 'sfcifd' +track = ARGV.empty? ? 'http' : ARGV.join(' ') puts "track \"#{track}\"" c = UserStream::Client.new c.endpoint = 'https://stream.twitter.com/' c.post('/1/statuses/filter.json', {:track => track}) do |s| begin line = "@#{s.user.screen_name} : #{s.text}" Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| if term =~ /@[a-zA-Z0-9_]+/ term = term.color(color_code term).bright.underline end term }.join('') rescue => e Log.puts "error : #{e}" end end
shokai/twitter-stream-api
9cd649563c612e953bad7afc6464f4084c43cbb0
use bundler
diff --git a/.gitignore b/.gitignore index 165436e..2174a29 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ .DS_Store *~ +*.lock *.log *.txt config.yaml .\#* *\#* diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..a4f5c0b --- /dev/null +++ b/Gemfile @@ -0,0 +1,7 @@ +source :rubygems + +gem 'rainbow' +gem 'oauth' +gem 'twitter' +gem 'json' +gem 'userstream' diff --git a/README.md b/README.md index 10d1a03..ea047e5 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,33 @@ Twitter Stream API test ======================= +Install Dependencies +-------------------- + + % gem install bundler + % bundle install + + Config ------ % cp sample.config.yaml config.yaml Auth ---- % ruby bin/auth.rb UserStream ---------- % ruby bin/userstream.rb Filter ------ % ruby -Ku bin/filter.rb "ruby" \ No newline at end of file diff --git a/bootstrap.rb b/bootstrap.rb index 69b80b0..2c174a6 100644 --- a/bootstrap.rb +++ b/bootstrap.rb @@ -1,17 +1,18 @@ require 'rubygems' +require 'bundler/setup' require 'yaml' require 'rainbow' @@conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') [:helpers].each do |cat| Dir.glob(File.dirname(__FILE__)+"/#{cat}/*").each do |f| puts "loading #{f}" require f end end if __FILE__ == $0 puts 'ok' puts color_code 'hoge' end
shokai/twitter-stream-api
11ab1abbe5ed1d9752175c781ed2cb985a3f4053
add readme
diff --git a/README.md b/README.md new file mode 100644 index 0000000..10d1a03 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +Twitter Stream API test +======================= + + +Config +------ + + % cp sample.config.yaml config.yaml + + +Auth +---- + + % ruby bin/auth.rb + + +UserStream +---------- + + % ruby bin/userstream.rb + + +Filter +------ + + % ruby -Ku bin/filter.rb "ruby" \ No newline at end of file
shokai/twitter-stream-api
e39693b1e645d5d31ae556cdd0237a8fccebda84
fix config
diff --git a/sample.config.yaml b/sample.config.yaml index c241384..bf82f70 100644 --- a/sample.config.yaml +++ b/sample.config.yaml @@ -1,20 +1,4 @@ -# twitter config -user : 'your-name' -pass : 'your-passwd' - -# mongo config -mongo_host : localhost -mongo_port : 27017 -mongo_dbname : chirpstream - -# tokyo tyrant config -ttdb : - - name : tweets - port : 20020 - # twitter oauth consumer_key : 'SmrSHrkB3xAABCOv9Av1A' consumer_secret : 'NVppoonw8jWVEtVQkyfSCeyBqEYCZh1L6KJHfkg19S0' -access_token : '3631571-5ItlBKsRPCCsqbsLRVUl2cvuypMQiDIdHkjTkwoSdV' -access_secret : 'W1RIiJKDtptSSarRM5ItYX2c3vmDHXzXwdeQy9wwIM'
shokai/twitter-stream-api
6e733b76794d01f607aa9ffb84e1153fbc80f215
color userstream
diff --git a/bin/userstream.rb b/bin/userstream.rb index 7b64115..ce1b6cd 100755 --- a/bin/userstream.rb +++ b/bin/userstream.rb @@ -1,15 +1,25 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'user_stream' UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end c = UserStream::Client.new c.user do |s| - p s + begin + line = "@#{s.user.screen_name} : #{s.text}" + puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| + if term =~ /@[a-zA-Z0-9_]+/ + term = term.color(color_code term).bright.underline + end + term + }.join('') + rescue => e + p s + end end
shokai/twitter-stream-api
85b4a5ca705667ec354ff624c82c02c412d4b1de
mv helper helpers
diff --git a/bootstrap.rb b/bootstrap.rb index 407296b..69b80b0 100644 --- a/bootstrap.rb +++ b/bootstrap.rb @@ -1,17 +1,17 @@ require 'rubygems' require 'yaml' require 'rainbow' @@conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') -[:helper].each do |cat| +[:helpers].each do |cat| Dir.glob(File.dirname(__FILE__)+"/#{cat}/*").each do |f| puts "loading #{f}" require f end end if __FILE__ == $0 puts 'ok' puts color_code 'hoge' end diff --git a/helper/color.rb b/helpers/color.rb similarity index 100% rename from helper/color.rb rename to helpers/color.rb diff --git a/helper/log.rb b/helpers/log.rb similarity index 100% rename from helper/log.rb rename to helpers/log.rb
shokai/twitter-stream-api
5b437a7d0ea4ec15c047caa869c25b5d0f618ab1
modify .gitignore
diff --git a/.gitignore b/.gitignore index 740e80c..165436e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .DS_Store *~ *.log +*.txt config.yaml .\#* *\#*
shokai/twitter-stream-api
272c14ed8f93735cf6e7d27235e5c6a750770779
print tweet permalink in log
diff --git a/bin/filter.rb b/bin/filter.rb index 524a299..139dddc 100755 --- a/bin/filter.rb +++ b/bin/filter.rb @@ -1,29 +1,30 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/../bootstrap' require 'user_stream' UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end track = ARGV.join(' ') || 'sfcifd' +puts "track \"#{track}\"" c = UserStream::Client.new c.endpoint = 'https://stream.twitter.com/' c.post('/1/statuses/filter.json', {:track => track}) do |s| begin line = "@#{s.user.screen_name} : #{s.text}" - Log.puts line + Log.puts "#{line} - http://twitter.com/#{s.user.screen_name}/status/#{s.id}" puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| if term =~ /@[a-zA-Z0-9_]+/ term = term.color(color_code term).bright.underline end term }.join('') rescue => e Log.puts "error : #{e}" end end
shokai/twitter-stream-api
6a6a4a7f1aab5714f8aed89b3972879ca3da1e4a
mkdir bin
diff --git a/Rakefile b/Rakefile deleted file mode 100644 index 57d02dc..0000000 --- a/Rakefile +++ /dev/null @@ -1,12 +0,0 @@ -require 'rubygems' -require 'yaml' -require 'shinagawaseaside' - -begin - conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') -rescue - STDERR.puts 'config.yaml load error' - exit 1 -end - -ShinagawaSeaside::set_tasks(conf['ttdb'], :basedir => File.dirname(__FILE__)+'/ttdb') diff --git a/auth.rb b/bin/auth.rb old mode 100644 new mode 100755 similarity index 71% rename from auth.rb rename to bin/auth.rb index a043ef6..f1fd1d2 --- a/auth.rb +++ b/bin/auth.rb @@ -1,29 +1,21 @@ #!/usr/bin/env ruby -require 'rubygems' +require File.dirname(__FILE__)+'/../bootstrap' require 'oauth' -require 'yaml' -begin - conf = YAML::load open(File.dirname(__FILE__) + '/config.yaml') -rescue - STDERR.puts 'config.yaml load error' - exit 1 -end - -consumer = OAuth::Consumer.new(conf['consumer_key'], conf['consumer_secret'], +consumer = OAuth::Consumer.new(@@conf['consumer_key'], @@conf['consumer_secret'], :site => "http://twitter.com/") request_token = consumer.get_request_token( #:oauth_callback => "http://example.com" ) puts 'please access following URL and approve' puts request_token.authorize_url print 'then, input OAuth Verifier: ' oauth_verifier = gets.chomp.strip access_token = request_token.get_access_token(:oauth_verifier => oauth_verifier) puts 'access_token : ' + "'#{access_token.token}'" puts 'access_secret : ' + "'#{access_token.secret}'" diff --git a/filter.rb b/bin/filter.rb old mode 100644 new mode 100755 similarity index 94% rename from filter.rb rename to bin/filter.rb index 50a476a..524a299 --- a/filter.rb +++ b/bin/filter.rb @@ -1,29 +1,29 @@ #!/usr/bin/env ruby -require File.dirname(__FILE__)+'/bootstrap' +require File.dirname(__FILE__)+'/../bootstrap' require 'user_stream' UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end track = ARGV.join(' ') || 'sfcifd' c = UserStream::Client.new c.endpoint = 'https://stream.twitter.com/' c.post('/1/statuses/filter.json', {:track => track}) do |s| begin line = "@#{s.user.screen_name} : #{s.text}" Log.puts line puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| if term =~ /@[a-zA-Z0-9_]+/ term = term.color(color_code term).bright.underline end term }.join('') rescue => e Log.puts "error : #{e}" end end diff --git a/bin/userstream.rb b/bin/userstream.rb new file mode 100755 index 0000000..7b64115 --- /dev/null +++ b/bin/userstream.rb @@ -0,0 +1,15 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__)+'/../bootstrap' +require 'user_stream' + +UserStream.configure do |config| + config.consumer_key = @@conf['consumer_key'] + config.consumer_secret = @@conf['consumer_secret'] + config.oauth_token = @@conf['access_token'] + config.oauth_token_secret = @@conf['access_secret'] +end + +c = UserStream::Client.new +c.user do |s| + p s +end diff --git a/userstream.rb b/userstream.rb deleted file mode 100644 index 3bf974d..0000000 --- a/userstream.rb +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env ruby -require 'rubygems' -require 'yaml' -require 'user_stream' - -conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') - -UserStream.configure do |config| - config.consumer_key = conf['consumer_key'] - config.consumer_secret = conf['consumer_secret'] - config.oauth_token = conf['access_token'] - config.oauth_token_secret = conf['access_secret'] -end - -c = UserStream::Client.new -c.user do |s| - p s -end
shokai/twitter-stream-api
01fea044afd5b6fd572e42ad8517bdc9640e817b
add logger and use in filter.rb
diff --git a/.gitignore b/.gitignore index 77d8aea..740e80c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,6 @@ -DS_Store +.DS_Store *~ -ttdb/* -*.tch -*.pid -.fuse* +*.log config.yaml .\#* *\#* diff --git a/filter.rb b/filter.rb index 2e8eed1..50a476a 100644 --- a/filter.rb +++ b/filter.rb @@ -1,28 +1,29 @@ #!/usr/bin/env ruby require File.dirname(__FILE__)+'/bootstrap' require 'user_stream' UserStream.configure do |config| config.consumer_key = @@conf['consumer_key'] config.consumer_secret = @@conf['consumer_secret'] config.oauth_token = @@conf['access_token'] config.oauth_token_secret = @@conf['access_secret'] end track = ARGV.join(' ') || 'sfcifd' c = UserStream::Client.new c.endpoint = 'https://stream.twitter.com/' c.post('/1/statuses/filter.json', {:track => track}) do |s| begin line = "@#{s.user.screen_name} : #{s.text}" + Log.puts line puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| if term =~ /@[a-zA-Z0-9_]+/ term = term.color(color_code term).bright.underline end term }.join('') rescue => e - + Log.puts "error : #{e}" end end diff --git a/helper/log.rb b/helper/log.rb new file mode 100644 index 0000000..c8e7da8 --- /dev/null +++ b/helper/log.rb @@ -0,0 +1,17 @@ +## logger + +class Log + def self.filename + @@filename ||= "#{Time.now.to_i}.log" + end + + def self.write(str) + open(self.filename, 'a+') do |f| + f.write str + end + end + + def self.puts(str) + self.write(str+"\n") + end +end
shokai/twitter-stream-api
015f34ae3f4dcdc1e9b40ac3e72e95613dfbf1f9
fix bootstrap
diff --git a/bootstrap.rb b/bootstrap.rb index 3c04fb9..407296b 100644 --- a/bootstrap.rb +++ b/bootstrap.rb @@ -1,17 +1,17 @@ require 'rubygems' require 'yaml' require 'rainbow' +@@conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') + [:helper].each do |cat| Dir.glob(File.dirname(__FILE__)+"/#{cat}/*").each do |f| puts "loading #{f}" require f end end -@@conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') - if __FILE__ == $0 puts 'ok' puts color_code 'hoge' end
shokai/twitter-stream-api
be507343785ec862344733f488c21f8c3f1758d7
add userstream.rb
diff --git a/userstream.rb b/userstream.rb new file mode 100644 index 0000000..3bf974d --- /dev/null +++ b/userstream.rb @@ -0,0 +1,18 @@ +#!/usr/bin/env ruby +require 'rubygems' +require 'yaml' +require 'user_stream' + +conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') + +UserStream.configure do |config| + config.consumer_key = conf['consumer_key'] + config.consumer_secret = conf['consumer_secret'] + config.oauth_token = conf['access_token'] + config.oauth_token_secret = conf['access_secret'] +end + +c = UserStream::Client.new +c.user do |s| + p s +end
shokai/twitter-stream-api
4f31c05e2fdbf92f28e06ac84655bc8d6a33e5e2
load helper dir
diff --git a/bootstrap.rb b/bootstrap.rb index 7cccc16..3c04fb9 100644 --- a/bootstrap.rb +++ b/bootstrap.rb @@ -1,11 +1,17 @@ require 'rubygems' require 'yaml' require 'rainbow' +[:helper].each do |cat| + Dir.glob(File.dirname(__FILE__)+"/#{cat}/*").each do |f| + puts "loading #{f}" + require f + end +end + @@conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') -def color_code(str) - colors = Sickill::Rainbow::TERM_COLORS.keys - [:default, :black, :white] - n = str.each_byte.map{|c| c.to_i}.inject{|a,b|a+b} - return colors[n%colors.size] +if __FILE__ == $0 + puts 'ok' + puts color_code 'hoge' end diff --git a/helper/color.rb b/helper/color.rb new file mode 100644 index 0000000..3d5a490 --- /dev/null +++ b/helper/color.rb @@ -0,0 +1,6 @@ + +def color_code(str) + colors = Sickill::Rainbow::TERM_COLORS.keys - [:default, :black, :white] + n = str.each_byte.map{|c| c.to_i}.inject{|a,b|a+b} + return colors[n%colors.size] +end
shokai/twitter-stream-api
7c99d7766f3f24f5cfd8586a819a9580e2410e92
use userstream gem
diff --git a/bootstrap.rb b/bootstrap.rb new file mode 100644 index 0000000..7cccc16 --- /dev/null +++ b/bootstrap.rb @@ -0,0 +1,11 @@ +require 'rubygems' +require 'yaml' +require 'rainbow' + +@@conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') + +def color_code(str) + colors = Sickill::Rainbow::TERM_COLORS.keys - [:default, :black, :white] + n = str.each_byte.map{|c| c.to_i}.inject{|a,b|a+b} + return colors[n%colors.size] +end diff --git a/filter.rb b/filter.rb index df04b4f..2e8eed1 100644 --- a/filter.rb +++ b/filter.rb @@ -1,25 +1,28 @@ #!/usr/bin/env ruby -# -*- coding: utf-8 -*- -require 'rubygems' -require 'net/http' -require 'uri' -require 'json' -require 'yaml' +require File.dirname(__FILE__)+'/bootstrap' +require 'user_stream' -conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') - -uri = URI.parse('http://stream.twitter.com/1/statuses/filter.json') -Net::HTTP.start(uri.host, uri.port) do |http| - req = Net::HTTP::Post.new(uri.request_uri) - req.basic_auth(conf['user'], conf['pass']) - req.set_form_data('track' => ARGV.join(' ')) - http.request(req){|res| - next if !res.chunked? - res.read_body{|chunk| - status = JSON.parse(chunk) rescue next - next if !status['text'] - puts "#{status['user']['screen_name']}: #{status['text']}" - } - } +UserStream.configure do |config| + config.consumer_key = @@conf['consumer_key'] + config.consumer_secret = @@conf['consumer_secret'] + config.oauth_token = @@conf['access_token'] + config.oauth_token_secret = @@conf['access_secret'] end +track = ARGV.join(' ') || 'sfcifd' + +c = UserStream::Client.new +c.endpoint = 'https://stream.twitter.com/' +c.post('/1/statuses/filter.json', {:track => track}) do |s| + begin + line = "@#{s.user.screen_name} : #{s.text}" + puts line.split(/(@[a-zA-Z0-9_]+)/).map{|term| + if term =~ /@[a-zA-Z0-9_]+/ + term = term.color(color_code term).bright.underline + end + term + }.join('') + rescue => e + + end +end diff --git a/sample.config.yaml b/sample.config.yaml index 6870f0c..c241384 100644 --- a/sample.config.yaml +++ b/sample.config.yaml @@ -1,14 +1,20 @@ # twitter config user : 'your-name' pass : 'your-passwd' # mongo config mongo_host : localhost mongo_port : 27017 mongo_dbname : chirpstream # tokyo tyrant config ttdb : - name : tweets port : 20020 + +# twitter oauth +consumer_key : 'SmrSHrkB3xAABCOv9Av1A' +consumer_secret : 'NVppoonw8jWVEtVQkyfSCeyBqEYCZh1L6KJHfkg19S0' +access_token : '3631571-5ItlBKsRPCCsqbsLRVUl2cvuypMQiDIdHkjTkwoSdV' +access_secret : 'W1RIiJKDtptSSarRM5ItYX2c3vmDHXzXwdeQy9wwIM'
shokai/twitter-stream-api
044ee7d713cbc0d7b6a4625c908638cd19892070
zeromq sub saykana
diff --git a/chirpstream-zeromq-sub-saykana.rb b/chirpstream-zeromq-sub-saykana.rb new file mode 100644 index 0000000..6a156b7 --- /dev/null +++ b/chirpstream-zeromq-sub-saykana.rb @@ -0,0 +1,37 @@ +#!/usr/bin/env ruby +require 'rubygems' +require 'zmq' +require 'json' +require 'MeCab' +$KCODE = 'u' + +mecab = MeCab::Tagger.new('-Ochasen') + +ctx = ZMQ::Context.new +sock= ctx.socket(ZMQ::SUB) +sock.connect('tcp://127.0.0.1:5000') +sock.setsockopt(ZMQ::SUBSCRIBE, 'chirp') + +loop do + str = sock.recv() + chunk = str.scan(/chirp (.+)/).first.first + status = JSON.parse(chunk) rescue next + begin + puts "#{status['user']['screen_name']}: #{status['text']}" + rescue => e + p status + STDERR.puts e + end + next unless status['text'] + begin + str = status['text'] + puts kana = mecab.parse(str).map{|i| + i.split(/\t/)[1] + }.delete_if{|i| + i.to_s.size < 1 + }.join('') + `saykana '#{kana}'` + rescue => e + STDERR.puts e + end +end
shokai/twitter-stream-api
513d19c9ac04bbd092507b5fd8cd816ab75faed1
zeromq pub/sub
diff --git a/chirpstream-zeromq-pub.rb b/chirpstream-zeromq-pub.rb new file mode 100644 index 0000000..11b5e5c --- /dev/null +++ b/chirpstream-zeromq-pub.rb @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require 'rubygems' +require 'net/http' +require 'uri' +require 'json' +require 'yaml' +require 'kconv' +require 'zmq' +$KCODE = 'u' + +conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') + +ctx = ZMQ::Context.new +sock = ctx.socket(ZMQ::PUB) +sock.bind('tcp://127.0.0.1:5000') + +uri = URI.parse('http://chirpstream.twitter.com/2b/user.json') +Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Get.new(uri.request_uri) + req.basic_auth(conf['user'], conf['pass']) + http.request(req){|res| + next if !res.chunked? + res.read_body{|chunk| + status = JSON.parse(chunk) rescue next + sock.send("chirp #{chunk}") + begin + puts "#{status['user']['screen_name']}: #{status['text']}" + rescue => e + p status + STDERR.puts e + end + } + } +end diff --git a/chirpstream-zeromq-sub.rb b/chirpstream-zeromq-sub.rb new file mode 100644 index 0000000..cafc656 --- /dev/null +++ b/chirpstream-zeromq-sub.rb @@ -0,0 +1,13 @@ +#!/usr/bin/env ruby +require 'rubygems' +require 'zmq' +$KCODE = 'u' + +ctx = ZMQ::Context.new +sock= ctx.socket(ZMQ::SUB) +sock.connect('tcp://127.0.0.1:5000') +sock.setsockopt(ZMQ::SUBSCRIBE, 'chirp') + +loop do + puts sock.recv() +end
shokai/twitter-stream-api
f9aab7738e720cc36ff7f6008adc492a4c90ca4f
verbose = nil
diff --git a/chirpstream-saykana.rb b/chirpstream-saykana.rb index dc5e4d3..8a49113 100644 --- a/chirpstream-saykana.rb +++ b/chirpstream-saykana.rb @@ -1,43 +1,44 @@ #!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'rubygems' require 'net/http' require 'uri' require 'json' require 'yaml' require 'kconv' require 'MeCab' $KCODE = 'u' +$VERBOSE = nil conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') mecab = MeCab::Tagger.new('-Ochasen') uri = URI.parse('http://chirpstream.twitter.com/2b/user.json') Net::HTTP.start(uri.host, uri.port) do |http| req = Net::HTTP::Get.new(uri.request_uri) req.basic_auth(conf['user'], conf['pass']) http.request(req){|res| next if !res.chunked? res.read_body{|chunk| status = JSON.parse(chunk) rescue next begin puts "#{status['user']['screen_name']}: #{status['text']}" rescue => e p status STDERR.puts e end next unless status['text'] begin str = status['text'] puts kana = mecab.parse(str).map{|i| i.split(/\t/)[1] }.delete_if{|i| i.to_s.size < 1 }.join('') `saykana '#{kana}'` rescue => e STDERR.puts e end } } end diff --git a/filter-saykana.rb b/filter-saykana.rb index 53af07a..8698c14 100644 --- a/filter-saykana.rb +++ b/filter-saykana.rb @@ -1,38 +1,39 @@ #!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'rubygems' require 'net/http' require 'uri' require 'json' require 'yaml' require 'MeCab' $KCODE = 'u' +$VERBOSE = nil conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') mecab = MeCab::Tagger.new('-Ochasen') uri = URI.parse('http://stream.twitter.com/1/statuses/filter.json') Net::HTTP.start(uri.host, uri.port) do |http| req = Net::HTTP::Post.new(uri.request_uri) req.basic_auth(conf['user'], conf['pass']) req.set_form_data('track' => ARGV.join(' ')) http.request(req){|res| next if !res.chunked? res.read_body{|chunk| status = JSON.parse(chunk) rescue next next if !status['text'] puts "#{status['user']['screen_name']}: #{status['text']}" begin puts kana = mecab.parse(status['text']).map{|i| i.split(/\t/)[1] }.delete_if{|i| i.to_s.size < 1 }.join('') `saykana '#{kana}'` rescue => e STDERR.puts e end } } end
shokai/twitter-stream-api
8581dfe5d983735c6c1fe4ec169a1e0b8717aefb
filter-saykana
diff --git a/filter-saykana.rb b/filter-saykana.rb new file mode 100644 index 0000000..53af07a --- /dev/null +++ b/filter-saykana.rb @@ -0,0 +1,38 @@ +#!/usr/bin/env ruby +# -*- coding: utf-8 -*- +require 'rubygems' +require 'net/http' +require 'uri' +require 'json' +require 'yaml' +require 'MeCab' +$KCODE = 'u' + +conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') +mecab = MeCab::Tagger.new('-Ochasen') + +uri = URI.parse('http://stream.twitter.com/1/statuses/filter.json') +Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Post.new(uri.request_uri) + req.basic_auth(conf['user'], conf['pass']) + req.set_form_data('track' => ARGV.join(' ')) + http.request(req){|res| + next if !res.chunked? + res.read_body{|chunk| + status = JSON.parse(chunk) rescue next + next if !status['text'] + puts "#{status['user']['screen_name']}: #{status['text']}" + begin + puts kana = mecab.parse(status['text']).map{|i| + i.split(/\t/)[1] + }.delete_if{|i| + i.to_s.size < 1 + }.join('') + `saykana '#{kana}'` + rescue => e + STDERR.puts e + end + } + } +end +
shokai/twitter-stream-api
59988d31867392808e1d73d7c406477e777c42ca
saykana chirpstream
diff --git a/chirpstream-saykana.rb b/chirpstream-saykana.rb new file mode 100644 index 0000000..dc5e4d3 --- /dev/null +++ b/chirpstream-saykana.rb @@ -0,0 +1,43 @@ +#!/usr/bin/env ruby +# -*- coding: utf-8 -*- +require 'rubygems' +require 'net/http' +require 'uri' +require 'json' +require 'yaml' +require 'kconv' +require 'MeCab' +$KCODE = 'u' + +conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') +mecab = MeCab::Tagger.new('-Ochasen') + +uri = URI.parse('http://chirpstream.twitter.com/2b/user.json') +Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Get.new(uri.request_uri) + req.basic_auth(conf['user'], conf['pass']) + http.request(req){|res| + next if !res.chunked? + res.read_body{|chunk| + status = JSON.parse(chunk) rescue next + begin + puts "#{status['user']['screen_name']}: #{status['text']}" + rescue => e + p status + STDERR.puts e + end + next unless status['text'] + begin + str = status['text'] + puts kana = mecab.parse(str).map{|i| + i.split(/\t/)[1] + }.delete_if{|i| + i.to_s.size < 1 + }.join('') + `saykana '#{kana}'` + rescue => e + STDERR.puts e + end + } + } +end
shokai/twitter-stream-api
be28212997ed0b53dcee506c7353bb6385f259a9
growl chirpstream
diff --git a/chirpstream-growl.rb b/chirpstream-growl.rb new file mode 100644 index 0000000..1815228 --- /dev/null +++ b/chirpstream-growl.rb @@ -0,0 +1,39 @@ +#!/usr/bin/env ruby +# -*- coding: utf-8 -*- +require 'rubygems' +require 'net/http' +require 'uri' +require 'json' +require 'yaml' +require 'notify' +require 'mongo' + +conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') + +m = Mongo::Connection.new(conf['mongo_host'], conf['mongo_port']) +db = m.db("#{conf['mongo_dbname']}_#{conf['user']}") + +uri = URI.parse('http://chirpstream.twitter.com/2b/user.json') +Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Get.new(uri.request_uri) + req.basic_auth(conf['user'], conf['pass']) + http.request(req){|res| + next if !res.chunked? + res.read_body{|chunk| + status = JSON.parse(chunk) rescue next + #next if !status['text'] + begin + db['tweets'].insert(status) + rescue + STDERR.puts e + end + begin + puts "#{status['user']['screen_name']}: #{status['text']}" + Notify.notify(status['user']['screen_name'], status['text']) + rescue => e + STDERR.puts e + end + } + } +end +
shokai/twitter-stream-api
1d956cc32dc4c8e29cdb03a4a73f0d107c093f18
chirpstream -> mongodb
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..77d8aea --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +DS_Store +*~ +ttdb/* +*.tch +*.pid +.fuse* +config.yaml +.\#* +*\#* diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..57d02dc --- /dev/null +++ b/Rakefile @@ -0,0 +1,12 @@ +require 'rubygems' +require 'yaml' +require 'shinagawaseaside' + +begin + conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') +rescue + STDERR.puts 'config.yaml load error' + exit 1 +end + +ShinagawaSeaside::set_tasks(conf['ttdb'], :basedir => File.dirname(__FILE__)+'/ttdb') diff --git a/chirpstream-store-mongo.rb b/chirpstream-store-mongo.rb new file mode 100644 index 0000000..03c55be --- /dev/null +++ b/chirpstream-store-mongo.rb @@ -0,0 +1,36 @@ +#!/usr/bin/env ruby +# -*- coding: utf-8 -*- +require 'rubygems' +require 'net/http' +require 'uri' +require 'json' +require 'yaml' +require 'mongo' + +conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') + +m = Mongo::Connection.new(conf['mongo_host'], conf['mongo_port']) +db = m.db("#{conf['mongo_dbname']}_#{conf['user']}") + +uri = URI.parse('http://chirpstream.twitter.com/2b/user.json') +Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Get.new(uri.request_uri) + req.basic_auth(conf['user'], conf['pass']) + http.request(req){|res| + next if !res.chunked? + res.read_body{|chunk| + begin + status = JSON.parse(chunk) + db['tweets'].insert(status) + rescue + next + end + begin + puts "#{status['user']['screen_name']}: #{status['text']}" + rescue + p status + end + } + } +end + diff --git a/chirpstream.rb b/chirpstream.rb new file mode 100644 index 0000000..b34eb97 --- /dev/null +++ b/chirpstream.rb @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# -*- coding: utf-8 -*- +require 'rubygems' +require 'net/http' +require 'uri' +require 'json' +require 'yaml' + +conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') + +uri = URI.parse('http://chirpstream.twitter.com/2b/user.json') +Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Get.new(uri.request_uri) + req.basic_auth(conf['user'], conf['pass']) + http.request(req){|res| + next if !res.chunked? + res.read_body{|chunk| + status = JSON.parse(chunk) rescue next + #next if !status['text'] + user = status['user'] + begin + puts "#{status['user']['screen_name']}: #{status['text']}" + rescue + p status + end + } + } +end + diff --git a/filter-store-tt.rb b/filter-store-tt.rb new file mode 100644 index 0000000..9f5b9a5 --- /dev/null +++ b/filter-store-tt.rb @@ -0,0 +1,39 @@ +#!/usr/bin/env ruby +# -*- coding: utf-8 -*- +require 'rubygems' +require 'net/http' +require 'uri' +require 'json' +require 'yaml' +require 'tokyotyrant' +include TokyoTyrant + +begin + conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') +rescue + STDERR.puts 'config.yaml load error' + exit 1 +end + + +db = RDB::new +if !db.open('127.0.0.1', conf['ttdb'][0]['port'].to_i) + STDERR.puts 'error - tokyotyrant : '+db.errmsg(db.ecode) + exit 1 +end + +uri = URI.parse('http://stream.twitter.com/1/statuses/filter.json') +Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Post.new(uri.request_uri) + req.basic_auth(conf['user'], conf['pass']) + req.set_form_data('track' => ARGV.join(' ')) + http.request(req){|res| + next if !res.chunked? + res.read_body{|chunk| + puts chunk + now = Time.now + db["#{now.to_i}_#{now.usec}"] = chunk + } + } +end + diff --git a/filter.rb b/filter.rb new file mode 100644 index 0000000..df04b4f --- /dev/null +++ b/filter.rb @@ -0,0 +1,25 @@ +#!/usr/bin/env ruby +# -*- coding: utf-8 -*- +require 'rubygems' +require 'net/http' +require 'uri' +require 'json' +require 'yaml' + +conf = YAML::load open(File.dirname(__FILE__)+'/config.yaml') + +uri = URI.parse('http://stream.twitter.com/1/statuses/filter.json') +Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Post.new(uri.request_uri) + req.basic_auth(conf['user'], conf['pass']) + req.set_form_data('track' => ARGV.join(' ')) + http.request(req){|res| + next if !res.chunked? + res.read_body{|chunk| + status = JSON.parse(chunk) rescue next + next if !status['text'] + puts "#{status['user']['screen_name']}: #{status['text']}" + } + } +end + diff --git a/sample.config.yaml b/sample.config.yaml new file mode 100644 index 0000000..6870f0c --- /dev/null +++ b/sample.config.yaml @@ -0,0 +1,14 @@ + +# twitter config +user : 'your-name' +pass : 'your-passwd' + +# mongo config +mongo_host : localhost +mongo_port : 27017 +mongo_dbname : chirpstream + +# tokyo tyrant config +ttdb : + - name : tweets + port : 20020
jhgfdsa/grfsegsbg
b2bc5acff7b505a580eaf21d25a5bfe5bb265da9
Fix typo
diff --git a/index.jxp b/index.jxp index 29fecf2..a7d9171 100644 --- a/index.jxp +++ b/index.jxp @@ -1,8 +1,8 @@ <html> <body> - <h2>Welecome to your 10gen site</h2> + <h2>Welcome to your 10gen site</h2> <h5><a href="/admin/">admin console</a></h5> </body> </html>
jhgfdsa/grfsegsbg
0d77e990881dfd33cf2d96cfab6f834c2f27acf4
a very small start
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9f8072e --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +*~ diff --git a/README b/README index e69de29..c225025 100644 --- a/README +++ b/README @@ -0,0 +1,3 @@ +This is a template used for forking within github. + +It does very little, except to get you started. diff --git a/index.jxp b/index.jxp new file mode 100644 index 0000000..29fecf2 --- /dev/null +++ b/index.jxp @@ -0,0 +1,8 @@ +<html> + <body> + <h2>Welecome to your 10gen site</h2> + + <h5><a href="/admin/">admin console</a></h5> + + </body> +</html>
adizdastanca/git-test
7079d7da0489a8788092070746fb855f847a5724
second commit
diff --git a/test.txt b/test.txt new file mode 100644 index 0000000..66f065a --- /dev/null +++ b/test.txt @@ -0,0 +1 @@ +qqqqqq
fox-io/recDressUp
c7f00ee635e9d83f8269869cf59e06f1c6a3b291
Initial Import
diff --git a/core.lua b/core.lua new file mode 100644 index 0000000..032c4ce --- /dev/null +++ b/core.lua @@ -0,0 +1,175 @@ +-- $Id: core.lua 550 2010-03-02 15:27:53Z [email protected] $ +local GetCursorPosition = GetCursorPosition +local function null_function() return end + +local function OnUpdate(self) + local currentx, currenty = GetCursorPosition() + if self.isrotating then + self:SetFacing(self:GetFacing() + ((currentx - self.prevx) / 50)) + elseif self.isposing then + local cz, cx, cy = self:GetPosition() + self:SetPosition(cz, cx + ((currentx - self.prevx) / 50), cy + ((currenty - self.prevy) / 50)) + end + self.prevx, self.prevy = currentx, currenty +end +local function OnMouseDown(self, button) + self.pMouseDown(button) + self:SetScript("OnUpdate", OnUpdate) + if button == "LeftButton" then + self.isrotating = 1 + elseif button == "RightButton" then + self.isposing = 1 + end + self.prevx, self.prevy = GetCursorPosition() +end +local function OnMouseUp(self, button) + self.pMouseUp(button) + self:SetScript("OnUpdate", nil) + if button == "LeftButton" then + self.isrotating = nil + end + if button == "RightButton" then + self.isposing = nil + end +end +local function OnMouseWheel(self, direction) + local cz, cx, cy = self:GetPosition() + self:SetPosition(cz + ((direction > 0 and 0.6) or -0.6), cx, cy) +end + +-- base functions +-- - model - model frame name (string) +-- - w/h - new width/height of the model frame +-- - x/y - new x/y positions for default setpoint +-- - sigh - if rotation buttons have different base names than parent +-- - norotate - if the model doesn't have default rotate buttons +local function Apply(model, w, h, x, y, sigh, norotate) + local gmodel = _G[model] + if not norotate then + model = sigh or model + _G[model.."RotateRightButton"]:Hide() + _G[model.."RotateLeftButton"]:Hide() + end + if w then gmodel:SetWidth(w) end + if h then gmodel:SetHeight(h) end + if x or y then + local p,rt,rp,px,py = gmodel:GetPoint() + gmodel:SetPoint(p, rt, rp, x or px, y or py) + end + gmodel:SetModelScale(2) + gmodel:EnableMouse(true) + gmodel:EnableMouseWheel(true) + gmodel.pMouseDown = gmodel:GetScript("OnMouseDown") or null_function + gmodel.pMouseUp = gmodel:GetScript("OnMouseUp") or null_function + gmodel:SetScript("OnMouseDown", OnMouseDown) + gmodel:SetScript("OnMouseUp", OnMouseUp) + gmodel:SetScript("OnMouseWheel", OnMouseWheel) +end +-- in case someone wants to apply it to his/her model +recDressUpApply = Apply + +local gtt = GameTooltip +local function gttshow(self) + gtt:SetOwner(self, "ANCHOR_BOTTOMRIGHT") + gtt:SetText(self.tt) + if recDressUpNPC and recDressUpNPC:IsVisible() and self.tt == "Undress" then + gtt:AddLine("Cannot dress NPC models") + end + gtt:Show() +end +local function gtthide() + gtt:Hide() +end +local function newbutton(name, parent, text, w, h, button, tt, func) + local b = button or CreateFrame("Button", name, parent, "UIPanelButtonTemplate") + b:SetText(text or b:GetText()) + b:SetWidth(w or b:GetWidth()) + b:SetHeight(h or b:GetHeight()) + b:SetScript("OnClick", func) + if tt then + b.tt = tt + b:SetScript("OnEnter", gttshow) + b:SetScript("OnLeave", gtthide) + end + return b +end + +-- modifies the auction house dressing room +local function hook_auction_house() + Apply("AuctionDressUpModel", nil, 370, 0, 10) + local reset_button, model = AuctionDressUpFrameResetButton, AuctionDressUpModel + local w, h = 20, reset_button:GetHeight() + newbutton(nil, nil, "T", w, h, reset_button, "Target", function() + if UnitExists("target") and UnitIsVisible("target") then + model:SetUnit("target") + end + end) + local a,b,c,d,e = reset_button:GetPoint() + reset_button:SetPoint(a,b,c,d,e-30) + newbutton("recDressUpAHReset", model, "R", 20, 22, nil, "Reset", function() model:Dress() end):SetPoint("RIGHT", reset_button, "LEFT", 0, 0) + newbutton("recDressUpAHUndress", model, "U", 20, 22, nil, "Undress", function() model:Undress() end):SetPoint("LEFT", reset_button, "RIGHT", 0, 0) +end +local function hook_inspect() + Apply("InspectModelFrame", nil, nil, nil, nil, "InspectModel") +end + +-- now apply the changes +-- need an event frame since 2 of the models are from LoD addons +local f = CreateFrame("Frame") +f:RegisterEvent("ADDON_LOADED") +f:SetScript("OnEvent", function(self, event, addon) + if addon == "Blizzard_AuctionUI" then + hook_auction_house() + elseif addon == "Blizzard_InspectUI" then + hook_inspect() + end +end) +-- in case Blizzard_AuctionUI or Blizzard_InspectUI were loaded early +if AuctionDressUpModel then hook_auction_house() end +if InspectModelFrame then hook_inspect() end + +-- main dressing room model with undress buttons +Apply("DressUpModel", nil, 332, nil, 104) +local cancel_button = DressUpFrameCancelButton +local w, h = 40, cancel_button:GetHeight() +local model = DressUpModel + +-- since 2.1 dressup models doesn't apply properly to NPCs, make a substitute +local target_model = CreateFrame("PlayerModel", "recDressUpNPC", DressUpFrame) +target_model:SetAllPoints(DressUpModel) +target_model:Hide() +Apply("recDressUpNPC", nil, nil, nil, nil, nil, true) + +DressUpFrame:HookScript("OnShow", function() + target_model:Hide() + model:Show() +end) + +-- convert default close button into set target button +newbutton(nil, nil, "Tar", w, h, cancel_button, "Target", function() + if UnitExists("target") and UnitIsVisible("target") then + if UnitIsPlayer("target") then + target_model:Hide() + model:Show() + model:SetUnit("target") + else + target_model:Show() + model:Hide() + target_model:SetUnit("target") + end + SetPortraitTexture(DressUpFramePortrait, "target") + end +end) +local a,b,c,d,e = cancel_button:GetPoint() +cancel_button:SetPoint(a, b, c, d - (w/2), e) +newbutton("recDressUpUndress", DressUpFrame, "Und", w, h, nil, "Undress", function() model:Undress() end):SetPoint("LEFT", cancel_button, "RIGHT", -2, 0) + +Apply("CharacterModelFrame") +Apply("TabardModel", nil, nil, nil, nil, "TabardCharacterModel") +Apply("PetModelFrame") +Apply("PetStableModel") +PetPaperDollPetInfo:SetFrameStrata("HIGH") + +if CompanionModelFrame then + Apply("CompanionModelFrame") +end \ No newline at end of file diff --git a/credits.txt b/credits.txt new file mode 100644 index 0000000..a705550 --- /dev/null +++ b/credits.txt @@ -0,0 +1,3 @@ +This is a modified version of CloseUp. + +Support is provided by the compilation's author and not by the author(s) of the individual addons. \ No newline at end of file diff --git a/recDressUp.toc b/recDressUp.toc new file mode 100644 index 0000000..bcd7521 --- /dev/null +++ b/recDressUp.toc @@ -0,0 +1,8 @@ +## Interface: 30300 +## Title: recDressUp +## Notes: Adds model viewing flexibility +## Author: TotalPackage, Recluse +## Version: $Id: recDressUp.toc 550 2010-03-02 15:27:53Z [email protected] $ +## Dependencies: recLib + +core.lua \ No newline at end of file
tpapp/array-operations-old
f935a69377c429d47ce636a5b2f20fc2b6f4d615
Added note about new version.
diff --git a/README.org b/README.org new file mode 100644 index 0000000..e1e2c59 --- /dev/null +++ b/README.org @@ -0,0 +1 @@ +This library is *deprecated*, and has been superseded by a [[https://github.com/tpapp/array-operations][new version]].
tpapp/array-operations-old
a31499145bad2ec61297339315115678521867ff
various fixes, no longer relies on flat arrays
diff --git a/array-operations.asd b/array-operations.asd index 5722a08..1c398c0 100644 --- a/array-operations.asd +++ b/array-operations.asd @@ -1,15 +1,14 @@ (defpackage #:array-operations-asd (:use :cl :asdf)) (in-package :array-operations-asd) (defsystem array-operations :description "Array operations (formerly part of FFA)" :author "Tamas K Papp" :license "GPL" :serial t :components ((:file "package") - (:file "ffa" :depends-on ("package")) - (:file "displaced-utils" :depends-on ("ffa")) - (:file "operations" :depends-on ("displaced-utils"))) + (:file "displaced-utils") + (:file "operations")) :depends-on (:cffi :cl-utilities :metabang-bind :iterate)) diff --git a/displaced-utils.lisp b/displaced-utils.lisp index 5277214..bb355f6 100644 --- a/displaced-utils.lisp +++ b/displaced-utils.lisp @@ -1,77 +1,77 @@ (in-package :array-operations) (defun find-original-array (array) "Find the original parent of a displaced array, return this and the sum of displaced index offsets." (let ((sum-of-offsets 0)) (tagbody check-displacement (multiple-value-bind (displaced-to displaced-index-offset) (array-displacement array) (when displaced-to (setf array displaced-to) (incf sum-of-offsets displaced-index-offset) (go check-displacement)))) (values array sum-of-offsets))) (defun displace-array (array dimensions index-offset) "Make a displaced array from array with the given dimensions and the index-offset and the same element-type as array. Tries to displace from the original array." (multiple-value-bind (original-array sum-of-offsets) (find-original-array array) (make-array dimensions :element-type (array-element-type array) :displaced-to original-array :displaced-index-offset (+ sum-of-offsets index-offset)))) (defun flatten-array (array) "Return a flat (ie rank 1) displaced version of the array." (displace-array array (array-total-size array) 0)) -(defun find-or-displace-to-flat-array (array) - "Find a flat array that array is displaced to, or create one that is -displaced to the original array. Also return the index-offset and -length (total size). Useful for passing to reduce etc." - (bind ((total-size (array-total-size array)) - ((:values original-array index-offset) (find-original-array array))) - (if (= (array-rank original-array) 1) - (values original-array index-offset total-size) - (values (displace-array original-array total-size index-offset) - 0 total-size)))) +;; DEPRECATED +;; (defun find-or-displace-to-flat-array (array) +;; "Find a flat array that array is displaced to, or create one that is +;; displaced to the original array. Also return the index-offset and +;; length (total size). Useful for passing to reduce etc." +;; (bind ((total-size (array-total-size array)) +;; ((:values original-array index-offset) (find-original-array array))) +;; (if (= (array-rank original-array) 1) +;; (values original-array index-offset total-size) +;; (values (displace-array original-array total-size index-offset) +;; 0 total-size)))) -(defun array-copy (array) - "Copy the elements of array. Does not copy the elements itself -recursively, if you need that, use array-map." - (make-ffa (array-dimensions array) - (array-element-type array) - :initial-contents (find-or-displace-to-flat-array array))) + +(defparameter *a* #2A((1 2) (3 4))) (defun array-map (function array &optional (element-type (array-element-type array))) "Map an array into another one elementwise using function. The resulting array has the given element-type." - (bind ((result (make-ffa (array-dimensions array) element-type)) - (result-flat (find-original-array result)) - ((:values array-flat index-offset length) - (find-or-displace-to-flat-array array))) + (bind ((result (make-array (array-dimensions array) :element-type element-type)) + ((:values original index-offset) (find-original-array array))) (iter - (for result-index :from 0 :below length) - (for array-index :from index-offset) - (setf (aref result-flat result-index) - (funcall function (aref array-flat array-index)))) + (for result-index :from 0 :below (array-total-size array)) + (for original-index :from index-offset) + (setf (row-major-aref result result-index) + (funcall function (row-major-aref original original-index)))) result)) +(defun array-copy (array) + "Copy the elements of array. Does not copy the elements themselves +recursively, if you need that, use array-map." + (array-map #'identity array)) + (defun array-map! (function array) "Replace each element 'elt' of an array with (funcall function elt), and return the modified array." - (dotimes (i (length array) array) - (setf (aref array i) (funcall function (aref array i))))) + (dotimes (i (array-total-size array)) + (setf (row-major-aref array i) (funcall function (row-major-aref array i))))) (defun array-convert (element-type array) "Convert array to desired element type. Always makes a copy, even if no conversion is required." - (let ((element-type (or element-type (match-cffi-element-type element-type)))) + (let ((element-type (upgraded-array-element-type element-type))) (if (equal (array-element-type array) element-type) (array-copy array) (array-map #'(lambda (x) (coerce x element-type)) array element-type)))) diff --git a/operations.lisp b/operations.lisp index 621cb59..4054345 100644 --- a/operations.lisp +++ b/operations.lisp @@ -1,345 +1,382 @@ (in-package :array-operations) +;;;; !!! HUGE FIXES ARE NEEDED +;;;; - remove find-or-displace-to-flat-array +;;;; - make result elemet type automatic where possible +;;;; - multiparam elementwise operations, inline for speed + (defun ignoring-nil (function) "From a bivariate function, create a function that calls the original if both arguments are non-nil, otherwise returns the argument which is non-nil, or nil when both are. Useful for ignoring nil's when calling reduce." #'(lambda (a b) (cond ((and a b) (funcall function a b)) (a a) (b b) (t nil)))) -(defun array-reduce (function array &key key ignore-nil-p) - "Apply (reduce function ...) to the flattened array. If -ignore-nil-p is given, it behaves as if nil elements were removed from -the array." - (bind (((:values flat-array start length) (find-or-displace-to-flat-array array)) - (end (+ start length))) - (if ignore-nil-p - (reduce (ignoring-nil function) - flat-array - :key key :start start :end end :initial-value nil) - (reduce function - flat-array - :key key :start start :end end)))) - -(defun array-max (array &key key ignore-nil-p) +(defun array-reduce (function array &key key ignore-p all-ignored) + "Apply (reduce function ...) to the flattened array. If ignore-p is +given, it behaves as if elements which satisfy ignore-p (ie return +non-nil for (funcall ignore-p element) were removed from the array. +When all elements are ignored, the value is all-ignored. ignore-p is +called before key." + (declare (optimize (debug 3))) + (bind (((:values original start) (find-original-array array)) + (size (array-total-size array)) + (end (+ start size))) + (when (zerop size) + (return-from array-reduce all-ignored)) + (unless key + (setf key #'identity)) + (if ignore-p + (let ((val all-ignored)) + ;; bit of a hole in here, should keep track of whether there + ;; has been a non-nil variable separately, instead of using + ;; equal on val and all-ignored + (iter + (for i :from start :below end) + (for v := (row-major-aref original i)) + (unless (funcall ignore-p v) + (let ((v-key (funcall key v))) + (setf val (if (equal val all-ignored) + v-key + (funcall function val v-key)))))) + val) + (let ((val (funcall key (row-major-aref array start)))) + (iter + (for i :from (1+ start) :below end) + (setf val (funcall function val + (funcall key (row-major-aref original i))))) + val)))) + +(defun array-max (array &key key ignore-p) "Find the maximum in array." - (array-reduce #'max array :key key :ignore-nil-p ignore-nil-p)) + (array-reduce #'max array :key key :ignore-p ignore-p)) -(defun array-min (array &key key ignore-nil-p) +(defun array-min (array &key key ignore-p) "Find the minimum in array." - (array-reduce #'min array :key key :ignore-nil-p ignore-nil-p)) + (array-reduce #'min array :key key :ignore-p ignore-p)) -(defun array-sum (array &key key ignore-nil-p) +(defun array-sum (array &key key ignore-p) "Sum of the elements in array." - (array-reduce #'+ array :key key :ignore-nil-p ignore-nil-p)) + (array-reduce #'+ array :key key :ignore-p ignore-p)) -(defun array-product (array &key key ignore-nil-p) +(defun array-product (array &key key ignore-p) "Product of the elements in array." - (array-reduce #'* array :key key :ignore-nil-p ignore-nil-p)) + (array-reduce #'* array :key key :ignore-p ignore-p)) (defun array-count (array predicate) "Count elements in array satisfying predicate." (array-reduce #'+ array :key (lambda (x) (if (funcall predicate x) 1 0)))) -(defun array-range (array &key key ignore-nil-p) +(defun array-range (array &key key ignore-p) "Minimum and maximum of an array, returned as a two-element list. In case all elements are nil, return (nil nil)." (let ((range (array-reduce (lambda (x y) (if (atom x) (list (min x y) (max x y)) (list (min (first x) y) (max (second x) y)))) - array :key key :ignore-nil-p ignore-nil-p))) + array :key key :ignore-p ignore-p))) (cond ((null range) nil) ; all are nil - ((atom range) (list range range)) ; single non-nil element + ((atom range) (list range range)) ; single non element (t range)))) -(defun array-abs-range (array &key key ignore-nil-p) +(defun array-abs-range (array &key key ignore-p) "Maximum of the absolute values of the elements of an array." (array-reduce (lambda (x y) (max (abs x) (abs y))) array - :key key :ignore-nil-p ignore-nil-p)) + :key key :ignore-p ignore-p)) -(defun array-mean (array &key key ignore-nil-p) +(defun array-mean (array &key key ignore-p) "Calculate the mean of the elements in array." - (/ (array-sum array :key key :ignore-nil-p ignore-nil-p) - (if ignore-nil-p + (/ (array-sum array :key key :ignore-p ignore-p) + (if ignore-p (array-count array #'not) (length array)))) (defun dot-product (x y &optional (function #'*)) "Calculate the (generalized) dot product of vectors x and y." (let* ((n (length x)) (sum 0)) (assert (= (length y) n)) (dotimes (i n) (incf sum (funcall function (aref x i) (aref y i)))) sum)) (defun outer-product (x y &key (function #'*) (element-type (array-element-type x))) "Calculate the (generalized) outer product of vectors x and y. When not specified, element-type will be the element-type of x." (declare (type (vector * *) x y)) (let* ((x-length (array-dimension x 0)) (y-length (array-dimension y 0)) - (result (make-ffa (list x-length y-length) element-type))) + (result (make-array (list x-length y-length) :element-type element-type))) (dotimes (i x-length) (dotimes (j y-length) (setf (aref result i j) (funcall function (aref x i) (aref y j))))) result)) (defun array-elementwise-operation (operator a b element-type) "Apply a bivariate operator on two arrays of the same dimension elementwise, returning the resulting array, which has the given element-type." (let ((dimensions (array-dimensions a))) (assert (equal dimensions (array-dimensions b))) - (bind (((:values a-flat a-index-offset length) - (find-or-displace-to-flat-array a)) - ((:values b-flat b-index-offset) - (find-or-displace-to-flat-array b)) - (result (make-ffa dimensions element-type)) - (result-flat (find-original-array result))) + (bind (((:values a-original a-index-offset) (find-original-array a)) + ((:values b-original b-index-offset) (find-original-array b)) + (length (array-total-size a-original)) + (result (make-array dimensions :element-type element-type))) + (assert (= length (array-total-size b-original))) (iter (for index :from 0 :below length) (for a-index :from a-index-offset) (for b-index :from b-index-offset) - (setf (aref result-flat index) + (setf (row-major-aref result index) (funcall operator - (aref a-flat a-index) - (aref b-flat b-index)))) + (row-major-aref a-original a-index) + (row-major-aref b-original b-index)))) result))) ;; elementwise operations -(defun array+ (a b &optional (element-type :double)) +(defun array+ (a b &optional (element-type 'double-float)) (array-elementwise-operation #'+ a b element-type)) -(defun array- (a b &optional (element-type :double)) +(defun array- (a b &optional (element-type 'double-float)) (array-elementwise-operation #'- a b element-type)) -(defun array* (a b &optional (element-type :double)) +(defun array* (a b &optional (element-type 'double-float)) (array-elementwise-operation #'* a b element-type)) -(defun array/ (a b &optional (element-type :double)) +(defun array/ (a b &optional (element-type 'double-float)) (array-elementwise-operation #'/ a b element-type)) (defmacro define-array-scalar-binary-operation (name operator) - `(defun ,name (a b &optional (element-type :double)) + `(defun ,name (a b &optional (element-type 'double-float)) (array-map (lambda (x) (,operator x b)) a element-type))) (define-array-scalar-binary-operation array-scalar+ +) (define-array-scalar-binary-operation array-scalar- -) (define-array-scalar-binary-operation array-scalar* *) (define-array-scalar-binary-operation array-scalar/ /) -(defun array-reciprocal (a &optional b (element-type :double)) +(defun array-reciprocal (a &optional b (element-type 'double-float)) "For each element x of a, map to (/ x) or (/ b x) (if b is given)." (if b (array-map (lambda (x) (/ b x)) a element-type) (array-map (lambda (x) (/ x)) a element-type))) -(defun array-negate (a &optional b (element-type :double)) +(defun array-negate (a &optional b (element-type 'double-float)) "For each element x of a, map to (- x) or (- b x) (if b is given)." (if b (array-map (lambda (x) (- b x)) a element-type) (array-map (lambda (x) (- x)) a element-type))) (defun array-map-list (function array n &optional (element-type (array-element-type array))) "Apply function (which is supposed to return a list of length n) to each element of array, returning the results in an array which has an extra last dimension of n." (let* ((dimensions (array-dimensions array)) (total-size (array-total-size array)) - (result (make-ffa (append dimensions (list n)) element-type)) + (result (make-array (append dimensions (list n)) + :element-type element-type)) (result-matrix (displace-array result (list total-size n) 0))) (dotimes (i total-size result) (let ((value (funcall function (row-major-aref array i)))) (assert (= (length value) n)) (iter (for elt :in value) (for j :from 0) (setf (aref result-matrix i j) elt)))))) (defun array-map-values (function array n &optional (element-type (array-element-type array))) "Apply function (which is supposed to return n values) to each element of array, returning the results in an array which has an extra last dimension of n." (flet ((list-function (x) (multiple-value-list (funcall function x)))) (array-map-list #'list-function array n element-type))) (defun index-extrema (n key &optional (weak-relation #'<=)) "Find the extrema (using weak-relation) of a (funcall key i) and the positions (indexes i) at which it occurs. Return the extremum and the list of positions. Notes: 1) when (and (funcall weak-relation a b) (funcall weak-relation b a)), a and b are considered equal. 2) the list of positions is in reversed order, you may use nreverse on it as nothing shares this structure. Examples: (index-extrema 5 (lambda (x) (abs (- x 2)))) => 2, (4 0) " (let ((maximum nil) (positions nil)) (dotimes (i n) (let ((element (funcall key i))) (cond ((null maximum) (setf maximum element positions (list i))) ((funcall weak-relation maximum element) (if (funcall weak-relation element maximum) (setf positions (cons i positions)) ; equality (setf maximum element ; strictly greater positions (list i))))))) (values maximum positions))) (defun array-extrema (array &key (key #'identity) (weak-relation #'<=)) "Find the extrema (using weak-relation) of an array and the positions at which it occurs. The positions are flat, one-dimensional vector indexes in the array (like the index used with row-major-aref). Return the extremum and the list of positions. Notes: 1) when (and (funcall weak-relation a b) (funcall weak-relation b a)), a and b are considered equal. 2) the list of positions is in reversed order, you may use nreverse on it as nothing shares this structure. Examples: (array-extrema #(1 2 2 3 3 2)) => 3, (4 3) (array-extrema #2A((2 1) (3 1) (2 3))) => 3, (5 2) " (bind (((:values flat-array index-offset total-size) (find-or-displace-to-flat-array array))) (index-extrema total-size (lambda (i) (funcall key (aref flat-array (+ index-offset i)))) weak-relation))) (defmacro vectorize ((&rest vectors) expression &key (result-element-type ''double-float) (into nil)) "Expand into a loop so that `expression' is evaluated in all corresponding elements of the `vectors', where the name of the vector will be replaced by the actual values the appropriate expression. Results from the elementwise evaluation of expression will be returned as a vector. If `into' is non-nil, it has to contain the name of one of the vectors, where the element will be placed. All other parts of the expression will have their original meaning (see example below). Return the resulting vector (which is one of the original, if `into' was specified). Example: (let ((a #(1d0 2d0 3d0)) (b #(4d0 5d0 6d0)) (c 0.25d0)) (vectorize (a b) (+ a b c 0.25))) ; => #(5.5d0 7.5d0 9.5d0) Notes: 1. Obviously, `vectors' can only contain symbols (otherwise the macro would not know which vector you are referring to). If you want to use a vector you just constructed, use let as above. 2. If you want to put the result in an array that has a different element type, you need to use coerce explicitly in `expression'." (assert (every #'symbolp vectors)) (assert (plusp (length vectors))) (with-unique-names (result n i) ;; we setup another name for each vector, otherwise the symbol ;; macros would be recursive (let ((shadowed-vector-names (mapcar (lambda (x) (gensym (symbol-name x))) vectors))) `(progn ,result-element-type ;; check first vector (assert (vectorp ,(car vectors))) ;; assign vectors to shadow names (let (,@(mapcar #'list shadowed-vector-names vectors)) (let* ((,n (length ,(car vectors)))) ;; check that all vectors are the same length (assert (every (lambda (v) (and (= (length v) ,n) (vectorp v))) (list ,@(cdr vectors)))) ;; setup result if necessary, if not, results end up in ;; the vector specified by `into' (let ((,result ,(if into (progn (assert (and (symbolp into) (member into vectors))) into) `(make-array ,n :element-type ,result-element-type)))) ;; symbol macros index in shadow names (symbol-macrolet (,@(mapcar (lambda (name shadowed-name) (list name (list 'aref shadowed-name i))) vectors shadowed-vector-names)) ;; the loop calculates the expression (dotimes (,i ,n) (setf (aref ,result ,i) ,expression))) ,result))))))) ;;; !!!! should do something for simpons-rule-on-index (defun map-vector-to-matrix (function vector) "Call `function' that maps an atom to a vector on each element of `vector', and collect the results as columns of a matrix. The array-element-type and dimensions of the matrix are established automatically by calling `function' on (aref vector 0), so `function' needs to return the same kind of vector all the time." (assert (and (vectorp vector) (plusp (length vector)))) (let* ((first-result (funcall function (aref vector 0))) (m (length first-result)) (n (length vector)) (matrix (make-array (list m n) :element-type (array-element-type first-result)))) (dotimes (j n) (let ((result (if (zerop j) first-result (funcall function (aref vector j))))) (assert (vectorp result)) (dotimes (i m) (setf (aref matrix i j) (aref result i))))) matrix)) (defun array-find-min (array &optional (key #'identity)) "Find the element of array which returns the smallest (funcall key element), where key should return a real number. Return (values min-element min-key)." (bind (((:values flat-array start length) (find-or-displace-to-flat-array array)) (end (+ start length)) (min-element (aref flat-array start)) (min-key (funcall key min-element))) (iter (for i :from (1+ start) :below end) (for element := (aref flat-array i)) (for element-key := (funcall key element)) (when (< element-key min-key) (setf min-key element-key min-element element))) (values min-element min-key))) + +(defun transpose (matrix) + "Transpose a matrix." + (check-type matrix (array * (* *))) + (bind (((rows cols) (array-dimensions matrix)) + (transpose (make-array (list cols rows) + :element-type (array-element-type matrix)))) + (dotimes (i rows) + (dotimes (j cols) + (setf (aref transpose j i) (aref matrix i j)))) + transpose)) diff --git a/package.lisp b/package.lisp index a4caf02..17647fa 100644 --- a/package.lisp +++ b/package.lisp @@ -1,28 +1,23 @@ (in-package #:array-operations-asd) (defpackage :array-operations (:use :common-lisp :cl-utilities :bind :iterate) (:shadowing-import-from :iterate :collecting :collect) (:export - ;; ffa - - match-cffi-element-type make-ffa - ;; displaced-utils displace-array flatten-array find-original-array - find-or-displace-to-flat-array array-copy array-map array-map! - array-convert + array-copy array-map array-map! array-convert ;; operations array-reduce array-max array-min array-sum array-product array-count array-range array-abs-range array-mean dot-product outer-product array-elementwise-operation array+ array- array* array/ array-scalar+ array-scalar- array-scalar* array-scalar/ array-reciprocal array-negate array-map-list array-map-values index-extrema array-extrema vectorize map-vector-to-matrix - array-find-min + array-find-min transpose ))
tpapp/array-operations-old
8439f4da439ea2c4ed6262895d643592a08c84a1
Patch by Daniel Herring to fix bind forms and declarations. Minor cosmetic change in array-range for correct nil handling.
diff --git a/displaced-utils.lisp b/displaced-utils.lisp index af4273a..5277214 100644 --- a/displaced-utils.lisp +++ b/displaced-utils.lisp @@ -1,77 +1,77 @@ (in-package :array-operations) (defun find-original-array (array) "Find the original parent of a displaced array, return this and the sum of displaced index offsets." (let ((sum-of-offsets 0)) (tagbody check-displacement (multiple-value-bind (displaced-to displaced-index-offset) (array-displacement array) (when displaced-to (setf array displaced-to) (incf sum-of-offsets displaced-index-offset) (go check-displacement)))) (values array sum-of-offsets))) (defun displace-array (array dimensions index-offset) "Make a displaced array from array with the given dimensions and the index-offset and the same element-type as array. Tries to displace from the original array." (multiple-value-bind (original-array sum-of-offsets) (find-original-array array) (make-array dimensions :element-type (array-element-type array) :displaced-to original-array :displaced-index-offset (+ sum-of-offsets index-offset)))) (defun flatten-array (array) "Return a flat (ie rank 1) displaced version of the array." (displace-array array (array-total-size array) 0)) (defun find-or-displace-to-flat-array (array) "Find a flat array that array is displaced to, or create one that is displaced to the original array. Also return the index-offset and length (total size). Useful for passing to reduce etc." (bind ((total-size (array-total-size array)) - ((values original-array index-offset) (find-original-array array))) + ((:values original-array index-offset) (find-original-array array))) (if (= (array-rank original-array) 1) (values original-array index-offset total-size) (values (displace-array original-array total-size index-offset) 0 total-size)))) (defun array-copy (array) "Copy the elements of array. Does not copy the elements itself recursively, if you need that, use array-map." (make-ffa (array-dimensions array) (array-element-type array) :initial-contents (find-or-displace-to-flat-array array))) (defun array-map (function array &optional (element-type (array-element-type array))) "Map an array into another one elementwise using function. The resulting array has the given element-type." (bind ((result (make-ffa (array-dimensions array) element-type)) (result-flat (find-original-array result)) - ((values array-flat index-offset length) + ((:values array-flat index-offset length) (find-or-displace-to-flat-array array))) (iter (for result-index :from 0 :below length) (for array-index :from index-offset) (setf (aref result-flat result-index) (funcall function (aref array-flat array-index)))) result)) (defun array-map! (function array) "Replace each element 'elt' of an array with (funcall function elt), and return the modified array." (dotimes (i (length array) array) (setf (aref array i) (funcall function (aref array i))))) (defun array-convert (element-type array) "Convert array to desired element type. Always makes a copy, even if no conversion is required." (let ((element-type (or element-type (match-cffi-element-type element-type)))) (if (equal (array-element-type array) element-type) (array-copy array) (array-map #'(lambda (x) (coerce x element-type)) array element-type)))) diff --git a/operations.lisp b/operations.lisp index f548e0b..621cb59 100644 --- a/operations.lisp +++ b/operations.lisp @@ -1,304 +1,345 @@ (in-package :array-operations) (defun ignoring-nil (function) "From a bivariate function, create a function that calls the original if both arguments are non-nil, otherwise returns the argument which is non-nil, or nil when both are. Useful for ignoring nil's when calling reduce." #'(lambda (a b) (cond ((and a b) (funcall function a b)) (a a) (b b) (t nil)))) (defun array-reduce (function array &key key ignore-nil-p) "Apply (reduce function ...) to the flattened array. If ignore-nil-p is given, it behaves as if nil elements were removed from the array." (bind (((:values flat-array start length) (find-or-displace-to-flat-array array)) (end (+ start length))) (if ignore-nil-p (reduce (ignoring-nil function) flat-array :key key :start start :end end :initial-value nil) (reduce function flat-array :key key :start start :end end)))) (defun array-max (array &key key ignore-nil-p) "Find the maximum in array." (array-reduce #'max array :key key :ignore-nil-p ignore-nil-p)) (defun array-min (array &key key ignore-nil-p) "Find the minimum in array." (array-reduce #'min array :key key :ignore-nil-p ignore-nil-p)) (defun array-sum (array &key key ignore-nil-p) "Sum of the elements in array." (array-reduce #'+ array :key key :ignore-nil-p ignore-nil-p)) (defun array-product (array &key key ignore-nil-p) "Product of the elements in array." (array-reduce #'* array :key key :ignore-nil-p ignore-nil-p)) (defun array-count (array predicate) "Count elements in array satisfying predicate." (array-reduce #'+ array :key (lambda (x) (if (funcall predicate x) 1 0)))) (defun array-range (array &key key ignore-nil-p) - "Minimum and maximum of an array, returned as a two-element list." + "Minimum and maximum of an array, returned as a two-element list. +In case all elements are nil, return (nil nil)." (let ((range (array-reduce (lambda (x y) (if (atom x) (list (min x y) (max x y)) (list (min (first x) y) (max (second x) y)))) array :key key :ignore-nil-p ignore-nil-p))) - (if (atom range) - (list range range) ; single non-nil element - range))) + (cond + ((null range) nil) ; all are nil + ((atom range) (list range range)) ; single non-nil element + (t range)))) (defun array-abs-range (array &key key ignore-nil-p) "Maximum of the absolute values of the elements of an array." (array-reduce (lambda (x y) (max (abs x) (abs y))) array :key key :ignore-nil-p ignore-nil-p)) (defun array-mean (array &key key ignore-nil-p) "Calculate the mean of the elements in array." (/ (array-sum array :key key :ignore-nil-p ignore-nil-p) (if ignore-nil-p (array-count array #'not) (length array)))) (defun dot-product (x y &optional (function #'*)) "Calculate the (generalized) dot product of vectors x and y." (let* ((n (length x)) (sum 0)) (assert (= (length y) n)) (dotimes (i n) (incf sum (funcall function (aref x i) (aref y i)))) sum)) (defun outer-product (x y &key (function #'*) (element-type (array-element-type x))) "Calculate the (generalized) outer product of vectors x and y. When not specified, element-type will be the element-type of x." - (declare ((vector * *) x y)) + (declare (type (vector * *) x y)) (let* ((x-length (array-dimension x 0)) (y-length (array-dimension y 0)) (result (make-ffa (list x-length y-length) element-type))) (dotimes (i x-length) (dotimes (j y-length) (setf (aref result i j) (funcall function (aref x i) (aref y j))))) result)) (defun array-elementwise-operation (operator a b element-type) "Apply a bivariate operator on two arrays of the same dimension elementwise, returning the resulting array, which has the given element-type." (let ((dimensions (array-dimensions a))) (assert (equal dimensions (array-dimensions b))) (bind (((:values a-flat a-index-offset length) (find-or-displace-to-flat-array a)) ((:values b-flat b-index-offset) (find-or-displace-to-flat-array b)) (result (make-ffa dimensions element-type)) (result-flat (find-original-array result))) (iter (for index :from 0 :below length) (for a-index :from a-index-offset) (for b-index :from b-index-offset) (setf (aref result-flat index) (funcall operator (aref a-flat a-index) (aref b-flat b-index)))) result))) ;; elementwise operations (defun array+ (a b &optional (element-type :double)) (array-elementwise-operation #'+ a b element-type)) (defun array- (a b &optional (element-type :double)) (array-elementwise-operation #'- a b element-type)) (defun array* (a b &optional (element-type :double)) (array-elementwise-operation #'* a b element-type)) (defun array/ (a b &optional (element-type :double)) (array-elementwise-operation #'/ a b element-type)) (defmacro define-array-scalar-binary-operation (name operator) `(defun ,name (a b &optional (element-type :double)) (array-map (lambda (x) (,operator x b)) a element-type))) (define-array-scalar-binary-operation array-scalar+ +) (define-array-scalar-binary-operation array-scalar- -) (define-array-scalar-binary-operation array-scalar* *) (define-array-scalar-binary-operation array-scalar/ /) (defun array-reciprocal (a &optional b (element-type :double)) "For each element x of a, map to (/ x) or (/ b x) (if b is given)." (if b (array-map (lambda (x) (/ b x)) a element-type) (array-map (lambda (x) (/ x)) a element-type))) (defun array-negate (a &optional b (element-type :double)) "For each element x of a, map to (- x) or (- b x) (if b is given)." (if b (array-map (lambda (x) (- b x)) a element-type) (array-map (lambda (x) (- x)) a element-type))) (defun array-map-list (function array n &optional (element-type (array-element-type array))) "Apply function (which is supposed to return a list of length n) to each element of array, returning the results in an array which has an extra last dimension of n." (let* ((dimensions (array-dimensions array)) (total-size (array-total-size array)) (result (make-ffa (append dimensions (list n)) element-type)) (result-matrix (displace-array result (list total-size n) 0))) (dotimes (i total-size result) (let ((value (funcall function (row-major-aref array i)))) (assert (= (length value) n)) (iter (for elt :in value) (for j :from 0) (setf (aref result-matrix i j) elt)))))) (defun array-map-values (function array n &optional (element-type (array-element-type array))) "Apply function (which is supposed to return n values) to each element of array, returning the results in an array which has an extra last dimension of n." (flet ((list-function (x) (multiple-value-list (funcall function x)))) (array-map-list #'list-function array n element-type))) (defun index-extrema (n key &optional (weak-relation #'<=)) "Find the extrema (using weak-relation) of a (funcall key i) and the positions (indexes i) at which it occurs. Return the extremum and the list of positions. Notes: 1) when (and (funcall weak-relation a b) (funcall weak-relation b a)), a and b are considered equal. 2) the list of positions is in reversed order, you may use nreverse on it as nothing shares this structure. Examples: (index-extrema 5 (lambda (x) (abs (- x 2)))) => 2, (4 0) " (let ((maximum nil) (positions nil)) (dotimes (i n) (let ((element (funcall key i))) (cond ((null maximum) (setf maximum element positions (list i))) ((funcall weak-relation maximum element) (if (funcall weak-relation element maximum) (setf positions (cons i positions)) ; equality (setf maximum element ; strictly greater positions (list i))))))) (values maximum positions))) (defun array-extrema (array &key (key #'identity) (weak-relation #'<=)) "Find the extrema (using weak-relation) of an array and the positions at which it occurs. The positions are flat, one-dimensional vector indexes in the array (like the index used with row-major-aref). Return the extremum and the list of positions. Notes: 1) when (and (funcall weak-relation a b) (funcall weak-relation b a)), a and b are considered equal. 2) the list of positions is in reversed order, you may use nreverse on it as nothing shares this structure. Examples: (array-extrema #(1 2 2 3 3 2)) => 3, (4 3) (array-extrema #2A((2 1) (3 1) (2 3))) => 3, (5 2) " (bind (((:values flat-array index-offset total-size) (find-or-displace-to-flat-array array))) (index-extrema total-size (lambda (i) (funcall key (aref flat-array (+ index-offset i)))) weak-relation))) (defmacro vectorize ((&rest vectors) expression &key (result-element-type ''double-float) (into nil)) "Expand into a loop so that `expression' is evaluated in all corresponding elements of the `vectors', where the name of the vector will be replaced by the actual values the appropriate expression. Results from the elementwise evaluation of expression will be returned as a vector. If `into' is non-nil, it has to contain the name of one of the vectors, where the element will be placed. All other parts of the expression will have their original meaning (see example below). Return the resulting vector (which is one of the original, if `into' was specified). Example: (let ((a #(1d0 2d0 3d0)) (b #(4d0 5d0 6d0)) (c 0.25d0)) (vectorize (a b) (+ a b c 0.25))) ; => #(5.5d0 7.5d0 9.5d0) Notes: 1. Obviously, `vectors' can only contain symbols (otherwise the macro would not know which vector you are referring to). If you want to use a vector you just constructed, use let as above. 2. If you want to put the result in an array that has a different element type, you need to use coerce explicitly in `expression'." (assert (every #'symbolp vectors)) (assert (plusp (length vectors))) (with-unique-names (result n i) ;; we setup another name for each vector, otherwise the symbol ;; macros would be recursive (let ((shadowed-vector-names (mapcar (lambda (x) (gensym (symbol-name x))) vectors))) `(progn ,result-element-type ;; check first vector (assert (vectorp ,(car vectors))) ;; assign vectors to shadow names (let (,@(mapcar #'list shadowed-vector-names vectors)) (let* ((,n (length ,(car vectors)))) ;; check that all vectors are the same length (assert (every (lambda (v) (and (= (length v) ,n) (vectorp v))) (list ,@(cdr vectors)))) ;; setup result if necessary, if not, results end up in ;; the vector specified by `into' (let ((,result ,(if into (progn (assert (and (symbolp into) (member into vectors))) into) `(make-array ,n :element-type ,result-element-type)))) ;; symbol macros index in shadow names (symbol-macrolet (,@(mapcar (lambda (name shadowed-name) (list name (list 'aref shadowed-name i))) vectors shadowed-vector-names)) ;; the loop calculates the expression (dotimes (,i ,n) (setf (aref ,result ,i) ,expression))) ,result))))))) ;;; !!!! should do something for simpons-rule-on-index + + +(defun map-vector-to-matrix (function vector) + "Call `function' that maps an atom to a vector on each element of +`vector', and collect the results as columns of a matrix. The +array-element-type and dimensions of the matrix are established +automatically by calling `function' on (aref vector 0), so `function' +needs to return the same kind of vector all the time." + (assert (and (vectorp vector) (plusp (length vector)))) + (let* ((first-result (funcall function (aref vector 0))) + (m (length first-result)) + (n (length vector)) + (matrix (make-array (list m n) + :element-type (array-element-type first-result)))) + (dotimes (j n) + (let ((result (if (zerop j) + first-result + (funcall function (aref vector j))))) + (assert (vectorp result)) + (dotimes (i m) + (setf (aref matrix i j) (aref result i))))) + matrix)) + +(defun array-find-min (array &optional (key #'identity)) + "Find the element of array which returns the smallest (funcall key +element), where key should return a real number. Return (values +min-element min-key)." + (bind (((:values flat-array start length) (find-or-displace-to-flat-array array)) + (end (+ start length)) + (min-element (aref flat-array start)) + (min-key (funcall key min-element))) + (iter + (for i :from (1+ start) :below end) + (for element := (aref flat-array i)) + (for element-key := (funcall key element)) + (when (< element-key min-key) + (setf min-key element-key + min-element element))) + (values min-element min-key))) diff --git a/package.lisp b/package.lisp index 02c5875..a4caf02 100644 --- a/package.lisp +++ b/package.lisp @@ -1,27 +1,28 @@ (in-package #:array-operations-asd) (defpackage :array-operations (:use :common-lisp :cl-utilities :bind :iterate) (:shadowing-import-from :iterate :collecting :collect) (:export ;; ffa match-cffi-element-type make-ffa ;; displaced-utils displace-array flatten-array find-original-array find-or-displace-to-flat-array array-copy array-map array-map! array-convert ;; operations array-reduce array-max array-min array-sum array-product array-count array-range array-abs-range array-mean dot-product outer-product array-elementwise-operation array+ array- array* array/ array-scalar+ array-scalar- array-scalar* array-scalar/ array-reciprocal array-negate array-map-list array-map-values - index-extrema array-extrema vectorize + index-extrema array-extrema vectorize map-vector-to-matrix + array-find-min ))
mcroydon/hudson-django-auth
81f243e738bd98b80671d62e5b4c34b2880f0b12
Removed redundant documentation in module.
diff --git a/hudson_django_auth.py b/hudson_django_auth.py index 20c647d..f4edfee 100755 --- a/hudson_django_auth.py +++ b/hudson_django_auth.py @@ -1,57 +1,28 @@ #!/usr/bin/env python __AUTHOR__ = 'Matt Croydon' __LICENSE__ = 'BSD' -""" -Authenticate Hudson against a Django installation using the -`Script Security Realm`_ plugin. It currently checks each configured authentication -backend and ensures that the user is authenticated and also a staff user. It is possible -to check if a user is a member of a specific group or has a specific permission as well. - -To use this script, you'll need to make sure that your hudson user has its ``PYTHONPATH`` -and ``DJANGO_SETTINGS_MODULE`` set correctly. You can add the following to the hudson -user's .bashrc or .bash_profile:: - - export PYTHONPATH=/any/custom/pythonpaths:/beyond/system/defaults - export DJANGO_SETTINGS_MODULE=myproject.mysettings - -You'll also need to install the `Script Security Realm`_ plugin and then check -``Enable security`` under the ``Manage Hudson`` -> ``Configure System`` menu. To -use this script select ``Authenticate via custom script`` and add the following to the -``Command`` field:: - - python /path/to/hudson_auth.py - -You'll also want to select an appropriate option under ``Authorization`` in order for the -plugin to take affect. ``Logged-in users can do anything`` may be a sane default here. - -Note: This script requires at least version 1.1. of the `Script Security Realm`_ plugin. -Version 1.0 will likely yield a stacktrace. - -.. _Script Security Realm: http://wiki.hudson-ci.org/display/HUDSON/Script+Security+Realm -""" - from django.contrib.auth import authenticate as django_authenticate import os, sys def authenticate(username, password): """ Authenticate a given username/password with Django and make sure they're also a staff user. """ user = django_authenticate(username=username, password=password) if not user or not user.is_staff: return False else: return True if __name__ == '__main__': """Hudson provides access to username/password by two environment variables, ``U`` and ``P``. An exit code of 0 means they're authenticated, anything else means they're not.""" authenticated = authenticate(username=os.environ.get('U', ''), password=os.environ.get('P', '')) if authenticated: sys.exit(0) else: sys.exit(1)
mcroydon/hudson-django-auth
b9d60d54426330f4e9e16bce77c61b7591f7efe2
Copied 1.1 note to README.
diff --git a/README.rst b/README.rst index f969eb6..53f7b0a 100644 --- a/README.rst +++ b/README.rst @@ -1,23 +1,26 @@ Authenticate Hudson against a Django installation using the `Script Security Realm`_ plugin. It currently checks each configured authentication backend and ensures that the user is authenticated and also a staff user. It is possible to check if a user is a member of a specific group or has a specific permission as well. To use this script, you'll need to make sure that your hudson user has its ``PYTHONPATH`` and ``DJANGO_SETTINGS_MODULE`` set correctly. You can add the following to the hudson user's .bashrc or .bash_profile:: export PYTHONPATH=/any/custom/pythonpaths:/beyond/system/defaults export DJANGO_SETTINGS_MODULE=myproject.mysettings You'll also need to install the `Script Security Realm`_ plugin and then check ``Enable security`` under the ``Manage Hudson`` -> ``Configure System`` menu. To use this script select ``Authenticate via custom script`` and add the following to the ``Command`` field:: python /path/to/hudson_django_auth.py You'll also want to select an appropriate option under ``Authorization`` in order for the plugin to take affect. ``Logged-in users can do anything`` may be a sane default here. +Note: This script requires at least version 1.1. of the `Script Security Realm`_ plugin. +Version 1.0 will likely yield a stacktrace. + .. _Script Security Realm: http://wiki.hudson-ci.org/display/HUDSON/Script+Security+Realm
mcroydon/hudson-django-auth
75976db11fadbd2fdbb93290a0773263bd7563f0
Added note about 1.1 requirement.
diff --git a/hudson_django_auth.py b/hudson_django_auth.py index b0348f5..20c647d 100755 --- a/hudson_django_auth.py +++ b/hudson_django_auth.py @@ -1,54 +1,57 @@ #!/usr/bin/env python __AUTHOR__ = 'Matt Croydon' __LICENSE__ = 'BSD' """ Authenticate Hudson against a Django installation using the `Script Security Realm`_ plugin. It currently checks each configured authentication backend and ensures that the user is authenticated and also a staff user. It is possible to check if a user is a member of a specific group or has a specific permission as well. To use this script, you'll need to make sure that your hudson user has its ``PYTHONPATH`` and ``DJANGO_SETTINGS_MODULE`` set correctly. You can add the following to the hudson user's .bashrc or .bash_profile:: export PYTHONPATH=/any/custom/pythonpaths:/beyond/system/defaults export DJANGO_SETTINGS_MODULE=myproject.mysettings You'll also need to install the `Script Security Realm`_ plugin and then check ``Enable security`` under the ``Manage Hudson`` -> ``Configure System`` menu. To use this script select ``Authenticate via custom script`` and add the following to the ``Command`` field:: python /path/to/hudson_auth.py You'll also want to select an appropriate option under ``Authorization`` in order for the plugin to take affect. ``Logged-in users can do anything`` may be a sane default here. +Note: This script requires at least version 1.1. of the `Script Security Realm`_ plugin. +Version 1.0 will likely yield a stacktrace. + .. _Script Security Realm: http://wiki.hudson-ci.org/display/HUDSON/Script+Security+Realm """ from django.contrib.auth import authenticate as django_authenticate import os, sys def authenticate(username, password): """ Authenticate a given username/password with Django and make sure they're also a staff user. """ user = django_authenticate(username=username, password=password) if not user or not user.is_staff: return False else: return True if __name__ == '__main__': """Hudson provides access to username/password by two environment variables, ``U`` and ``P``. An exit code of 0 means they're authenticated, anything else means they're not.""" authenticated = authenticate(username=os.environ.get('U', ''), password=os.environ.get('P', '')) if authenticated: sys.exit(0) else: sys.exit(1)
bdimcheff/fixity
86fc72c8ba3324642a603a4a9d3f6fe6c58cbe59
better implementation of blank fields
diff --git a/lib/fixity/record.rb b/lib/fixity/record.rb index 4317bc8..1c900d6 100644 --- a/lib/fixity/record.rb +++ b/lib/fixity/record.rb @@ -1,52 +1,48 @@ module Fixity class Record class << self attr_reader :field_order, :field_options def field(field_name, options = {}) @field_order ||= [] @field_order << field_name.to_sym @field_options ||= {} @field_options[field_name] = options define_method(field_name) do @fields[field_name].value end define_method("#{field_name}=") do |val| - klass = options.delete(:class) + klass = options.dup.delete(:class) klass ||= Field - + @fields[field_name] = klass.new(val, options) end end end def initialize(field_hash = nil) @fields = {} + self.class.field_order.each do |f| + send("#{f}=", nil) + end + update_attributes(field_hash) end def update_attributes(attributes) (attributes || []).each do |k, v| send("#{k}=", v) end end def to_s self.class.field_order.inject("") do |str, field_name| - field = @fields[field_name] - options = self.class.field_options[field_name] - - if field - str << @fields[field_name].to_s - else - str << " " * options[:length] - end - + str << @fields[field_name].to_s str end end end end \ No newline at end of file
bdimcheff/fixity
0ff0ec49f80f6d55024f0b745d4de8c1dee73138
handle blank fields properly
diff --git a/lib/fixity/record.rb b/lib/fixity/record.rb index 8ccc07e..4317bc8 100644 --- a/lib/fixity/record.rb +++ b/lib/fixity/record.rb @@ -1,41 +1,52 @@ module Fixity class Record class << self attr_reader :field_order, :field_options def field(field_name, options = {}) @field_order ||= [] @field_order << field_name.to_sym + @field_options ||= {} + @field_options[field_name] = options define_method(field_name) do @fields[field_name].value end define_method("#{field_name}=") do |val| klass = options.delete(:class) klass ||= Field @fields[field_name] = klass.new(val, options) end end end def initialize(field_hash = nil) @fields = {} + update_attributes(field_hash) end def update_attributes(attributes) (attributes || []).each do |k, v| send("#{k}=", v) end end def to_s self.class.field_order.inject("") do |str, field_name| - str << @fields[field_name].to_s + field = @fields[field_name] + options = self.class.field_options[field_name] + + if field + str << @fields[field_name].to_s + else + str << " " * options[:length] + end + str end end end end \ No newline at end of file diff --git a/test/fixity/record_test.rb b/test/fixity/record_test.rb index 45d66f6..e073ac9 100644 --- a/test/fixity/record_test.rb +++ b/test/fixity/record_test.rb @@ -1,103 +1,119 @@ require File.dirname(__FILE__) + '/../test_helper' class RecordTest < Test::Unit::TestCase context 'single field' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 end end should "assign record" do foo_record = @class.new foo_record.foo = "bar" assert_equal "bar", foo_record.to_s end should 'truncate if the field is too short' do foo_record = @class.new foo_record.foo = "quux" assert_equal "quu", foo_record.to_s end should 'right align with spaces if the field is too long' do foo_record = @class.new foo_record.foo = 'hi' assert_equal ' hi', foo_record.to_s end end context 'multiple fields' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 field :bar, :length => 2 field :baz, :length => 5 end end should 'work for 3 fields of the proper length' do record = @class.new record.foo = 'foo' record.bar = 'hi' record.baz = 'hello' assert_equal 'foohihello', record.to_s end should 'work for 3 short fields' do record = @class.new record.foo = 'fo' record.bar = 'h' record.baz = 'hell' assert_equal ' fo h hell', record.to_s end should 'work for 3 long fields' do record = @class.new record.foo = 'foobar' record.bar = 'hithere' record.baz = 'hellosir' assert_equal 'foohihello', record.to_s end end context 'custom fields' do setup do field_class = Class.new(Fixity::Field) do def to_s; "bar"; end end @class = Class.new(Fixity::Record) do field :foo, :class => field_class end end should 'use the custom class instead of the default' do foo_record = @class.new foo_record.foo = "foo" assert_equal "bar", foo_record.to_s end end + context 'blank fields' do + setup do + @class = Class.new(Fixity::Record) do + field :foo, :length => 3 + field :bar, :length => 2 + field :baz, :length => 5 + end + end + + should 'fill in the blank fields with blanks' do + record = @class.new(:foo => 'foo', :baz => 'bazoo') + + assert_equal "foo bazoo", record.to_s + end + end + context 'hash input' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 field :bar, :length => 6 end end should 'load hash parameters' do record = @class.new(:foo => "foo", :bar => "barbar") assert_equal "foobarbar", record.to_s end end end
bdimcheff/fixity
edb786c91ae5ba934e763a309c95c6a84be68541
some renaming I forgot to do before
diff --git a/Rakefile b/Rakefile index 38dae91..94ef480 100644 --- a/Rakefile +++ b/Rakefile @@ -1,56 +1,56 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "fixity" - gem.summary = %Q{TODO} + gem.summary = %Q{Fixed-width file parser} gem.email = "[email protected]" gem.homepage = "http://github.com/bdimcheff/fixity" gem.authors = ["Brandon Dimcheff"] # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end rescue LoadError puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com" end require 'rake/testtask' Rake::TestTask.new(:test) do |test| test.libs << 'lib' << 'test' test.pattern = 'test/**/*_test.rb' test.verbose = false end begin require 'rcov/rcovtask' Rcov::RcovTask.new do |test| test.libs << 'test' test.pattern = 'test/**/*_test.rb' test.verbose = true end rescue LoadError task :rcov do abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov" end end task :default => :test require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| if File.exist?('VERSION.yml') config = YAML.load(File.read('VERSION.yml')) version = "#{config[:major]}.#{config[:minor]}.#{config[:patch]}" else version = "" end rdoc.rdoc_dir = 'rdoc' - rdoc.title = "fnm_parser #{version}" + rdoc.title = "fixity #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end
bdimcheff/fixity
d75e52c74aab2743e34e52a1f26d01c1df38a733
accept hash parameters to new
diff --git a/lib/fixity/record.rb b/lib/fixity/record.rb index 11c9043..8ccc07e 100644 --- a/lib/fixity/record.rb +++ b/lib/fixity/record.rb @@ -1,34 +1,41 @@ module Fixity class Record class << self attr_reader :field_order, :field_options def field(field_name, options = {}) @field_order ||= [] @field_order << field_name.to_sym define_method(field_name) do @fields[field_name].value end define_method("#{field_name}=") do |val| klass = options.delete(:class) klass ||= Field @fields[field_name] = klass.new(val, options) end end end - def initialize + def initialize(field_hash = nil) @fields = {} + update_attributes(field_hash) + end + + def update_attributes(attributes) + (attributes || []).each do |k, v| + send("#{k}=", v) + end end def to_s self.class.field_order.inject("") do |str, field_name| str << @fields[field_name].to_s str end end end end \ No newline at end of file diff --git a/test/fixity/record_test.rb b/test/fixity/record_test.rb index 293b707..45d66f6 100644 --- a/test/fixity/record_test.rb +++ b/test/fixity/record_test.rb @@ -1,88 +1,103 @@ require File.dirname(__FILE__) + '/../test_helper' class RecordTest < Test::Unit::TestCase context 'single field' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 end end should "assign record" do foo_record = @class.new foo_record.foo = "bar" assert_equal "bar", foo_record.to_s end should 'truncate if the field is too short' do foo_record = @class.new foo_record.foo = "quux" assert_equal "quu", foo_record.to_s end should 'right align with spaces if the field is too long' do foo_record = @class.new foo_record.foo = 'hi' assert_equal ' hi', foo_record.to_s end end context 'multiple fields' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 field :bar, :length => 2 field :baz, :length => 5 end end should 'work for 3 fields of the proper length' do record = @class.new record.foo = 'foo' record.bar = 'hi' record.baz = 'hello' assert_equal 'foohihello', record.to_s end should 'work for 3 short fields' do record = @class.new record.foo = 'fo' record.bar = 'h' record.baz = 'hell' assert_equal ' fo h hell', record.to_s end should 'work for 3 long fields' do record = @class.new record.foo = 'foobar' record.bar = 'hithere' record.baz = 'hellosir' assert_equal 'foohihello', record.to_s end end context 'custom fields' do setup do field_class = Class.new(Fixity::Field) do def to_s; "bar"; end end @class = Class.new(Fixity::Record) do field :foo, :class => field_class end end should 'use the custom class instead of the default' do foo_record = @class.new foo_record.foo = "foo" assert_equal "bar", foo_record.to_s end end + + context 'hash input' do + setup do + @class = Class.new(Fixity::Record) do + field :foo, :length => 3 + field :bar, :length => 6 + end + end + + should 'load hash parameters' do + record = @class.new(:foo => "foo", :bar => "barbar") + + assert_equal "foobarbar", record.to_s + end + end end
bdimcheff/fixity
91186d9a1cf815c076c816a17c1b0b894bf0d68c
right align the fields
diff --git a/lib/fixity/field.rb b/lib/fixity/field.rb index 444917b..afd4238 100644 --- a/lib/fixity/field.rb +++ b/lib/fixity/field.rb @@ -1,14 +1,14 @@ module Fixity class Field attr_accessor :length, :value def initialize(value, options = {}) self.length = options[:length] self.value = value end def to_s - sprintf("%-#{length}.#{length}s", value) + sprintf("%#{length}.#{length}s", value) end end end \ No newline at end of file diff --git a/test/fixity/field_test.rb b/test/fixity/field_test.rb index 8fcb7eb..deca3e0 100644 --- a/test/fixity/field_test.rb +++ b/test/fixity/field_test.rb @@ -1,23 +1,23 @@ require File.dirname(__FILE__) + '/../test_helper' class FieldTest < Test::Unit::TestCase context 'formatting a field' do should 'use exactly the field width' do f = Fixity::Field.new("abc", :length => 3) assert_equal 'abc', f.to_s end should 'use no more than the field width' do f = Fixity::Field.new("abcd", :length => 3) assert_equal 'abc', f.to_s end should 'fill the entire field width' do f = Fixity::Field.new("ab", :length => 3) - assert_equal 'ab ', f.to_s + assert_equal ' ab', f.to_s end end end diff --git a/test/fixity/record_test.rb b/test/fixity/record_test.rb index af29704..293b707 100644 --- a/test/fixity/record_test.rb +++ b/test/fixity/record_test.rb @@ -1,88 +1,88 @@ require File.dirname(__FILE__) + '/../test_helper' class RecordTest < Test::Unit::TestCase context 'single field' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 end end should "assign record" do foo_record = @class.new foo_record.foo = "bar" assert_equal "bar", foo_record.to_s end should 'truncate if the field is too short' do foo_record = @class.new foo_record.foo = "quux" assert_equal "quu", foo_record.to_s end - should 'fill with spaces if the field is too long' do + should 'right align with spaces if the field is too long' do foo_record = @class.new foo_record.foo = 'hi' - assert_equal 'hi ', foo_record.to_s + assert_equal ' hi', foo_record.to_s end end context 'multiple fields' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 field :bar, :length => 2 field :baz, :length => 5 end end should 'work for 3 fields of the proper length' do record = @class.new record.foo = 'foo' record.bar = 'hi' record.baz = 'hello' assert_equal 'foohihello', record.to_s end should 'work for 3 short fields' do record = @class.new record.foo = 'fo' record.bar = 'h' record.baz = 'hell' - assert_equal 'fo h hell ', record.to_s + assert_equal ' fo h hell', record.to_s end should 'work for 3 long fields' do record = @class.new record.foo = 'foobar' record.bar = 'hithere' record.baz = 'hellosir' assert_equal 'foohihello', record.to_s end end context 'custom fields' do setup do field_class = Class.new(Fixity::Field) do def to_s; "bar"; end end @class = Class.new(Fixity::Record) do field :foo, :class => field_class end end should 'use the custom class instead of the default' do foo_record = @class.new foo_record.foo = "foo" assert_equal "bar", foo_record.to_s end end end
bdimcheff/fixity
1270ee550efb03eb2645d680518220c764f59762
allow for custom field classes
diff --git a/lib/fixity/record.rb b/lib/fixity/record.rb index 196d49b..11c9043 100644 --- a/lib/fixity/record.rb +++ b/lib/fixity/record.rb @@ -1,31 +1,34 @@ module Fixity class Record class << self attr_reader :field_order, :field_options def field(field_name, options = {}) @field_order ||= [] @field_order << field_name.to_sym define_method(field_name) do @fields[field_name].value end define_method("#{field_name}=") do |val| - @fields[field_name] = Field.new(val, options) + klass = options.delete(:class) + klass ||= Field + + @fields[field_name] = klass.new(val, options) end end end def initialize @fields = {} end def to_s self.class.field_order.inject("") do |str, field_name| str << @fields[field_name].to_s str end end end end \ No newline at end of file diff --git a/test/fixity/record_test.rb b/test/fixity/record_test.rb index dec7155..af29704 100644 --- a/test/fixity/record_test.rb +++ b/test/fixity/record_test.rb @@ -1,69 +1,88 @@ require File.dirname(__FILE__) + '/../test_helper' class RecordTest < Test::Unit::TestCase context 'single field' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 end end should "assign record" do foo_record = @class.new foo_record.foo = "bar" assert_equal "bar", foo_record.to_s end should 'truncate if the field is too short' do foo_record = @class.new foo_record.foo = "quux" assert_equal "quu", foo_record.to_s end should 'fill with spaces if the field is too long' do foo_record = @class.new foo_record.foo = 'hi' assert_equal 'hi ', foo_record.to_s end end context 'multiple fields' do setup do @class = Class.new(Fixity::Record) do field :foo, :length => 3 field :bar, :length => 2 field :baz, :length => 5 end end should 'work for 3 fields of the proper length' do record = @class.new record.foo = 'foo' record.bar = 'hi' record.baz = 'hello' assert_equal 'foohihello', record.to_s end should 'work for 3 short fields' do record = @class.new record.foo = 'fo' record.bar = 'h' record.baz = 'hell' assert_equal 'fo h hell ', record.to_s end should 'work for 3 long fields' do record = @class.new record.foo = 'foobar' record.bar = 'hithere' record.baz = 'hellosir' assert_equal 'foohihello', record.to_s end end + + context 'custom fields' do + setup do + field_class = Class.new(Fixity::Field) do + def to_s; "bar"; end + end + + @class = Class.new(Fixity::Record) do + field :foo, :class => field_class + end + end + + should 'use the custom class instead of the default' do + foo_record = @class.new + foo_record.foo = "foo" + + assert_equal "bar", foo_record.to_s + end + end end
bdimcheff/fixity
574261862f5a2a3ce9901e5ff947c3b4468e9632
Version bump to 0.0.0
diff --git a/VERSION.yml b/VERSION.yml new file mode 100644 index 0000000..bf64db8 --- /dev/null +++ b/VERSION.yml @@ -0,0 +1,4 @@ +--- +:minor: 0 +:patch: 0 +:major: 0
bdimcheff/fixity
5dfad7dadb03175ed09799712f27d057057a5a77
renamed generic parser to fixity, split classes into their own files
diff --git a/README.rdoc b/README.rdoc index b1a5089..bda789f 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,7 +1,7 @@ -= fnm_parser += fixity Description goes here. == Copyright Copyright (c) 2009 Brandon Dimcheff. See LICENSE for details. diff --git a/Rakefile b/Rakefile index ab6f5ea..38dae91 100644 --- a/Rakefile +++ b/Rakefile @@ -1,56 +1,56 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| - gem.name = "fnm_parser" + gem.name = "fixity" gem.summary = %Q{TODO} gem.email = "[email protected]" - gem.homepage = "http://github.com/bdimcheff/fnm_parser" + gem.homepage = "http://github.com/bdimcheff/fixity" gem.authors = ["Brandon Dimcheff"] # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end rescue LoadError puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com" end require 'rake/testtask' Rake::TestTask.new(:test) do |test| test.libs << 'lib' << 'test' test.pattern = 'test/**/*_test.rb' test.verbose = false end begin require 'rcov/rcovtask' Rcov::RcovTask.new do |test| test.libs << 'test' test.pattern = 'test/**/*_test.rb' test.verbose = true end rescue LoadError task :rcov do abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov" end end task :default => :test require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| if File.exist?('VERSION.yml') config = YAML.load(File.read('VERSION.yml')) version = "#{config[:major]}.#{config[:minor]}.#{config[:patch]}" else version = "" end rdoc.rdoc_dir = 'rdoc' rdoc.title = "fnm_parser #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end diff --git a/lib/fixity.rb b/lib/fixity.rb new file mode 100644 index 0000000..c236bb6 --- /dev/null +++ b/lib/fixity.rb @@ -0,0 +1,2 @@ +require 'fixity/field' +require 'fixity/record' \ No newline at end of file diff --git a/lib/fixity/field.rb b/lib/fixity/field.rb new file mode 100644 index 0000000..444917b --- /dev/null +++ b/lib/fixity/field.rb @@ -0,0 +1,14 @@ +module Fixity + class Field + attr_accessor :length, :value + + def initialize(value, options = {}) + self.length = options[:length] + self.value = value + end + + def to_s + sprintf("%-#{length}.#{length}s", value) + end + end +end \ No newline at end of file diff --git a/lib/fnm_parser.rb b/lib/fixity/record.rb similarity index 70% rename from lib/fnm_parser.rb rename to lib/fixity/record.rb index 2616565..196d49b 100644 --- a/lib/fnm_parser.rb +++ b/lib/fixity/record.rb @@ -1,44 +1,31 @@ -module ParseFixed +module Fixity class Record class << self attr_reader :field_order, :field_options def field(field_name, options = {}) @field_order ||= [] @field_order << field_name.to_sym define_method(field_name) do @fields[field_name].value end define_method("#{field_name}=") do |val| @fields[field_name] = Field.new(val, options) end end end def initialize @fields = {} end def to_s self.class.field_order.inject("") do |str, field_name| str << @fields[field_name].to_s str end end end - - class Field - attr_accessor :length, :value - - def initialize(value, options = {}) - self.length = options[:length] - self.value = value - end - - def to_s - sprintf("%-#{length}.#{length}s", value) - end - end end \ No newline at end of file diff --git a/test/fixity/field_test.rb b/test/fixity/field_test.rb new file mode 100644 index 0000000..8fcb7eb --- /dev/null +++ b/test/fixity/field_test.rb @@ -0,0 +1,23 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class FieldTest < Test::Unit::TestCase + context 'formatting a field' do + should 'use exactly the field width' do + f = Fixity::Field.new("abc", :length => 3) + + assert_equal 'abc', f.to_s + end + + should 'use no more than the field width' do + f = Fixity::Field.new("abcd", :length => 3) + + assert_equal 'abc', f.to_s + end + + should 'fill the entire field width' do + f = Fixity::Field.new("ab", :length => 3) + + assert_equal 'ab ', f.to_s + end + end +end diff --git a/test/fnm_parser_test.rb b/test/fixity/record_test.rb similarity index 68% rename from test/fnm_parser_test.rb rename to test/fixity/record_test.rb index cc4a109..dec7155 100644 --- a/test/fnm_parser_test.rb +++ b/test/fixity/record_test.rb @@ -1,91 +1,69 @@ -require 'test_helper' +require File.dirname(__FILE__) + '/../test_helper' class RecordTest < Test::Unit::TestCase context 'single field' do setup do - @class = Class.new(ParseFixed::Record) do + @class = Class.new(Fixity::Record) do field :foo, :length => 3 end end should "assign record" do foo_record = @class.new foo_record.foo = "bar" assert_equal "bar", foo_record.to_s end should 'truncate if the field is too short' do foo_record = @class.new foo_record.foo = "quux" assert_equal "quu", foo_record.to_s end should 'fill with spaces if the field is too long' do foo_record = @class.new foo_record.foo = 'hi' assert_equal 'hi ', foo_record.to_s end end context 'multiple fields' do setup do - @class = Class.new(ParseFixed::Record) do + @class = Class.new(Fixity::Record) do field :foo, :length => 3 field :bar, :length => 2 field :baz, :length => 5 end end should 'work for 3 fields of the proper length' do record = @class.new record.foo = 'foo' record.bar = 'hi' record.baz = 'hello' assert_equal 'foohihello', record.to_s end should 'work for 3 short fields' do record = @class.new record.foo = 'fo' record.bar = 'h' record.baz = 'hell' assert_equal 'fo h hell ', record.to_s end should 'work for 3 long fields' do record = @class.new record.foo = 'foobar' record.bar = 'hithere' record.baz = 'hellosir' assert_equal 'foohihello', record.to_s end end end - -class FieldTest < Test::Unit::TestCase - context 'formatting a field' do - should 'use exactly the field width' do - f = ParseFixed::Field.new("abc", :length => 3) - - assert_equal 'abc', f.to_s - end - - should 'use no more than the field width' do - f = ParseFixed::Field.new("abcd", :length => 3) - - assert_equal 'abc', f.to_s - end - - should 'fill the entire field width' do - f = ParseFixed::Field.new("ab", :length => 3) - - assert_equal 'ab ', f.to_s - end - end -end diff --git a/test/fixity_test.rb b/test/fixity_test.rb new file mode 100644 index 0000000..e69de29 diff --git a/test/test_helper.rb b/test/test_helper.rb index 6163ffd..22fc33c 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,10 +1,10 @@ require 'rubygems' require 'test/unit' require 'shoulda' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) -require 'fnm_parser' +require 'fixity' class Test::Unit::TestCase end
bdimcheff/fixity
4a055cca8f331a706a6681f4a4881aa60b30a630
refactored, added some tests
diff --git a/test/fnm_parser_test.rb b/test/fnm_parser_test.rb index 9728f60..cc4a109 100644 --- a/test/fnm_parser_test.rb +++ b/test/fnm_parser_test.rb @@ -1,69 +1,91 @@ require 'test_helper' -class FnmParserTest < Test::Unit::TestCase +class RecordTest < Test::Unit::TestCase context 'single field' do setup do @class = Class.new(ParseFixed::Record) do field :foo, :length => 3 end end should "assign record" do foo_record = @class.new foo_record.foo = "bar" assert_equal "bar", foo_record.to_s end should 'truncate if the field is too short' do foo_record = @class.new foo_record.foo = "quux" assert_equal "quu", foo_record.to_s end should 'fill with spaces if the field is too long' do foo_record = @class.new foo_record.foo = 'hi' assert_equal 'hi ', foo_record.to_s end end context 'multiple fields' do setup do @class = Class.new(ParseFixed::Record) do field :foo, :length => 3 field :bar, :length => 2 field :baz, :length => 5 end end should 'work for 3 fields of the proper length' do record = @class.new record.foo = 'foo' record.bar = 'hi' record.baz = 'hello' assert_equal 'foohihello', record.to_s end should 'work for 3 short fields' do record = @class.new record.foo = 'fo' record.bar = 'h' record.baz = 'hell' assert_equal 'fo h hell ', record.to_s end should 'work for 3 long fields' do record = @class.new record.foo = 'foobar' record.bar = 'hithere' record.baz = 'hellosir' assert_equal 'foohihello', record.to_s end end end + +class FieldTest < Test::Unit::TestCase + context 'formatting a field' do + should 'use exactly the field width' do + f = ParseFixed::Field.new("abc", :length => 3) + + assert_equal 'abc', f.to_s + end + + should 'use no more than the field width' do + f = ParseFixed::Field.new("abcd", :length => 3) + + assert_equal 'abc', f.to_s + end + + should 'fill the entire field width' do + f = ParseFixed::Field.new("ab", :length => 3) + + assert_equal 'ab ', f.to_s + end + end +end
bdimcheff/fixity
954bf0b59ded60662efbdd9951d0dd74506c4607
formats Record objects into fixed-length formats
diff --git a/lib/fnm_parser.rb b/lib/fnm_parser.rb index e69de29..2616565 100644 --- a/lib/fnm_parser.rb +++ b/lib/fnm_parser.rb @@ -0,0 +1,44 @@ +module ParseFixed + class Record + class << self + attr_reader :field_order, :field_options + + def field(field_name, options = {}) + @field_order ||= [] + @field_order << field_name.to_sym + + define_method(field_name) do + @fields[field_name].value + end + + define_method("#{field_name}=") do |val| + @fields[field_name] = Field.new(val, options) + end + end + end + + def initialize + @fields = {} + end + + def to_s + self.class.field_order.inject("") do |str, field_name| + str << @fields[field_name].to_s + str + end + end + end + + class Field + attr_accessor :length, :value + + def initialize(value, options = {}) + self.length = options[:length] + self.value = value + end + + def to_s + sprintf("%-#{length}.#{length}s", value) + end + end +end \ No newline at end of file diff --git a/test/fnm_parser_test.rb b/test/fnm_parser_test.rb index d2ff167..9728f60 100644 --- a/test/fnm_parser_test.rb +++ b/test/fnm_parser_test.rb @@ -1,7 +1,69 @@ require 'test_helper' class FnmParserTest < Test::Unit::TestCase - should "probably rename this file and start testing for real" do - flunk "hey buddy, you should probably rename this file and start testing for real" + context 'single field' do + setup do + @class = Class.new(ParseFixed::Record) do + field :foo, :length => 3 + end + end + + should "assign record" do + foo_record = @class.new + foo_record.foo = "bar" + + assert_equal "bar", foo_record.to_s + end + + should 'truncate if the field is too short' do + foo_record = @class.new + foo_record.foo = "quux" + + assert_equal "quu", foo_record.to_s + end + + should 'fill with spaces if the field is too long' do + foo_record = @class.new + foo_record.foo = 'hi' + + assert_equal 'hi ', foo_record.to_s + end + end + + context 'multiple fields' do + setup do + @class = Class.new(ParseFixed::Record) do + field :foo, :length => 3 + field :bar, :length => 2 + field :baz, :length => 5 + end + end + + should 'work for 3 fields of the proper length' do + record = @class.new + record.foo = 'foo' + record.bar = 'hi' + record.baz = 'hello' + + assert_equal 'foohihello', record.to_s + end + + should 'work for 3 short fields' do + record = @class.new + record.foo = 'fo' + record.bar = 'h' + record.baz = 'hell' + + assert_equal 'fo h hell ', record.to_s + end + + should 'work for 3 long fields' do + record = @class.new + record.foo = 'foobar' + record.bar = 'hithere' + record.baz = 'hellosir' + + assert_equal 'foohihello', record.to_s + end end end
chevalun/entropy.js
64c13e6524af78aec5f77c503a8f050a7ded56cb
remove format middleware, since it is removed from newest connect
diff --git a/entropy.js b/entropy.js index 808c8cf..0e94501 100644 --- a/entropy.js +++ b/entropy.js @@ -1,196 +1,195 @@ var fs = require('fs'), sys = require('sys'), extname = require('path').extname; // bootstrap 3rd-party libraries require.paths.unshift(__dirname+'/support/'); require.paths.unshift(__dirname+'/support/mongoose/'); // include 3rd-party libraries var express = require('express'), mongoose = require('mongoose').Mongoose; // create server var app = module.exports.app = express.createServer(); // configure server app.use(express.bodyDecoder()); app.use(express.compiler({ enable: true })); app.use(express.conditionalGet()); -app.use(express.format()); app.use(express.gzip()); app.use(express.methodOverride()); app.use(express.staticProvider(__dirname+'/public')); app.set('views', __dirname+'/views'); // load configuration try { var cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } // file loader (for controllers, models, ...) var loader = function(dir) { fs.readdir(dir, function(err, files) { if (err) { throw err; } files.forEach(function(file) { if (extname(file) == '.js') { require(dir+'/'+file.replace('.js', '')); } }); }); }; // enable debugger if (true == cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } // enable logger if (true == cfg.logger) { app.use(express.logger()); } var NotFound = module.exports.nf = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); }; sys.inherits(NotFound, Error); // Error 404 app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); // Error 500 app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // open db connection var db = module.exports.db = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); // load models cfg.loader.models.forEach(loader); // load controllers cfg.loader.controllers.forEach(loader); // load default controller if (cfg.loader.use_default_controller) { // FIND app.get('/:collection', function(req, res, next) { var col = db.model(req.params.collection), qw = col.find(); if (req.param('query')) { qw.where(req.param('query')); } if (req.param('order')) { var order = []; req.param('order').forEach(function(dir, field) { order.push([field, dir]); }); qw.sort(order); } if (req.param('limit')) { qw.limit(req.param('limit')); } if (req.param('offset')) { qw.skip(req.param('offset')); } qw.all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); } }); }); // CREATE var createDoc = function(req, res, next) { var col = db.model(req.params.collection), doc = new col; doc.merge(req.param(req.params.collection)); doc.save(function() { res.send(doc.toObject(), 201); }); }; app.put('/:collection', createDoc); app.post('/:collection', createDoc); // MODIFY var modifyDoc = function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { doc.merge(req.param(req.params.collection)); doc.save(function() { res.send(doc.toObject(), 200); }); } }); }; app.put('/:collection/:id', modifyDoc); app.post('/:collection/:id', modifyDoc); // REMOVE app.del('/:collection/:id', function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { doc.remove(function() { res.send('200 OK', 200); }); } }); }); } // start server app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
68767bf6544bff4f16e0adb5a7818a4c93007d2d
added format and gzip module
diff --git a/entropy.js b/entropy.js index 985f678..808c8cf 100644 --- a/entropy.js +++ b/entropy.js @@ -1,194 +1,196 @@ var fs = require('fs'), sys = require('sys'), extname = require('path').extname; // bootstrap 3rd-party libraries require.paths.unshift(__dirname+'/support/'); require.paths.unshift(__dirname+'/support/mongoose/'); // include 3rd-party libraries var express = require('express'), mongoose = require('mongoose').Mongoose; // create server var app = module.exports.app = express.createServer(); // configure server app.use(express.bodyDecoder()); app.use(express.compiler({ enable: true })); app.use(express.conditionalGet()); +app.use(express.format()); +app.use(express.gzip()); app.use(express.methodOverride()); app.use(express.staticProvider(__dirname+'/public')); app.set('views', __dirname+'/views'); // load configuration try { var cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } // file loader (for controllers, models, ...) var loader = function(dir) { fs.readdir(dir, function(err, files) { if (err) { throw err; } files.forEach(function(file) { if (extname(file) == '.js') { require(dir+'/'+file.replace('.js', '')); } }); }); }; // enable debugger if (true == cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } // enable logger if (true == cfg.logger) { app.use(express.logger()); } var NotFound = module.exports.nf = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); }; sys.inherits(NotFound, Error); // Error 404 app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); // Error 500 app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // open db connection var db = module.exports.db = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); // load models cfg.loader.models.forEach(loader); // load controllers cfg.loader.controllers.forEach(loader); // load default controller if (cfg.loader.use_default_controller) { // FIND app.get('/:collection', function(req, res, next) { var col = db.model(req.params.collection), qw = col.find(); if (req.param('query')) { qw.where(req.param('query')); } if (req.param('order')) { var order = []; req.param('order').forEach(function(dir, field) { order.push([field, dir]); }); qw.sort(order); } if (req.param('limit')) { qw.limit(req.param('limit')); } if (req.param('offset')) { qw.skip(req.param('offset')); } qw.all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); } }); }); // CREATE var createDoc = function(req, res, next) { var col = db.model(req.params.collection), doc = new col; doc.merge(req.param(req.params.collection)); doc.save(function() { res.send(doc.toObject(), 201); }); }; app.put('/:collection', createDoc); app.post('/:collection', createDoc); // MODIFY var modifyDoc = function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { doc.merge(req.param(req.params.collection)); doc.save(function() { res.send(doc.toObject(), 200); }); } }); }; app.put('/:collection/:id', modifyDoc); app.post('/:collection/:id', modifyDoc); // REMOVE app.del('/:collection/:id', function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { doc.remove(function() { res.send('200 OK', 200); }); } }); }); } // start server app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
fe859749328193b927d002d25c0c2d7cac91b6ff
added PUT support for create and modify
diff --git a/entropy.js b/entropy.js index f73aea1..985f678 100644 --- a/entropy.js +++ b/entropy.js @@ -1,188 +1,194 @@ var fs = require('fs'), sys = require('sys'), extname = require('path').extname; // bootstrap 3rd-party libraries require.paths.unshift(__dirname+'/support/'); require.paths.unshift(__dirname+'/support/mongoose/'); // include 3rd-party libraries var express = require('express'), mongoose = require('mongoose').Mongoose; // create server var app = module.exports.app = express.createServer(); // configure server app.use(express.bodyDecoder()); app.use(express.compiler({ enable: true })); app.use(express.conditionalGet()); app.use(express.methodOverride()); app.use(express.staticProvider(__dirname+'/public')); app.set('views', __dirname+'/views'); // load configuration try { var cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } // file loader (for controllers, models, ...) var loader = function(dir) { fs.readdir(dir, function(err, files) { if (err) { throw err; } files.forEach(function(file) { if (extname(file) == '.js') { require(dir+'/'+file.replace('.js', '')); } }); }); }; // enable debugger if (true == cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } // enable logger if (true == cfg.logger) { app.use(express.logger()); } var NotFound = module.exports.nf = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); }; sys.inherits(NotFound, Error); // Error 404 app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); // Error 500 app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // open db connection var db = module.exports.db = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); // load models cfg.loader.models.forEach(loader); // load controllers cfg.loader.controllers.forEach(loader); // load default controller if (cfg.loader.use_default_controller) { // FIND app.get('/:collection', function(req, res, next) { var col = db.model(req.params.collection), qw = col.find(); if (req.param('query')) { qw.where(req.param('query')); } if (req.param('order')) { var order = []; req.param('order').forEach(function(dir, field) { order.push([field, dir]); }); qw.sort(order); } if (req.param('limit')) { qw.limit(req.param('limit')); } if (req.param('offset')) { qw.skip(req.param('offset')); } qw.all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); } }); }); // CREATE - app.post('/:collection', function(req, res, next) { + var createDoc = function(req, res, next) { var col = db.model(req.params.collection), doc = new col; doc.merge(req.param(req.params.collection)); doc.save(function() { res.send(doc.toObject(), 201); }); - }); + }; + + app.put('/:collection', createDoc); + app.post('/:collection', createDoc); // MODIFY - app.post('/:collection/:id', function(req, res, next) { + var modifyDoc = function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { doc.merge(req.param(req.params.collection)); doc.save(function() { res.send(doc.toObject(), 200); }); } }); - }); + }; + + app.put('/:collection/:id', modifyDoc); + app.post('/:collection/:id', modifyDoc); // REMOVE app.del('/:collection/:id', function(req, res, next) { var col = db.model(req.params.collection); col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { doc.remove(function() { res.send('200 OK', 200); }); } }); }); } // start server app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
95497ce432e554f481eaf86a7460ad997a1fb94f
fixed typo (sort > order)
diff --git a/README.md b/README.md index 9fefebd..34998ee 100644 --- a/README.md +++ b/README.md @@ -1,144 +1,144 @@ README ====== entropy is a simple [RESTful][1] server in front of a [MongoDB][2] instance using [node.js][3], [Express][4] and [Mongoose][5]. DEPENDENCIES ------------ * [node.js][3] * [Express][4] * [Mongoose][5] INSTALLATION ------------ Clone the Github repository. Update the vendor libraries: $> git clone git://github.com/pminnieur/entropy.js.git $> sh update_vendors.sh You can run an entropy instance just by starting it with the `node` command: node entropy.js CONFIGURATION ------------- Copy the `config.json.sample` file to `config.json` and modify it to fit your needs. USAGE ----- You can use entropy without any models, but I recommend to have a schema for each of your models. You can put your Mongoose models in the `/models` directory. Here's an example of an simple user model: // models/user.js var mongoose = require("mongoose").Mongoose; mongoose.model("user", { properties: ["username", "email"], cast: { username: String, email: String }, indexes: ["username", "email"] }); That's it. You can now find, read, create, modify and remove user objects via REST, just by calling the appropriate URLs. The routing schema is very simple: ### Find GET /:collection ### Read GET /:collection/:id ### Create POST /:collection?collection[field1]=value1&collection[field2]=value2... ### Modify POST /:collection/:id?collection[field1]=value1&collection[field2]=value2... ### Remove DELETE /:collection/:id > **NOTE:** the `collection[]` array must be named like the model you want to > access, thus for creating or modifying a user you must use it like this: > `?user[username]=foo&user[email]=bar` ### Finding documents You can specifiy what you want to find with the following parameters: #### Querying GET /:collection?query[field1]=value1&query[field2]=value2&... #### Sorting - GET /:collection?sort[field1]=asc|desc&sort[field2]=asc|desc&... + GET /:collection?order[field1]=asc|desc&order[field2]=asc|desc&... #### Pagination GET /:collection?limit=5&offset=5 CUSTOMIZATION ------------- If you want to overload the default behavior of the REST controllers, simply put your own in the `/controllers` directory. Here's an example for a customized user controller which removes users' email address from the response: // controllers/user.js var app = modules.parent.exports.app, db = modules.parent.exports.db; app.get('/user', function(req, res) { db.model('user').find().all(function(users) { ret = []; users.forEach(function(user) { user = user.toObject(); delete user.email; ret.push(user); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }) }); LICENSE ------- For the full copyright and license information, please view the `LICENSE` file that was distributed with this source code. [1]: http://en.wikipedia.org/wiki/Representational_State_Transfer [2]: http://www.mongodb.org/ [3]: http://nodejs.org/ [4]: http://expressjs.com/ [5]: http://www.learnboost.com/mongoose/
chevalun/entropy.js
dfe42876eb3f58b64a20305c1d769ba48575157f
added querying, sorting and pagination for find action
diff --git a/README.md b/README.md index 6b0197d..b562ac7 100644 --- a/README.md +++ b/README.md @@ -1,115 +1,134 @@ README ====== entropy is a simple [RESTful][1] server in front of a [MongoDB][2] instance using [node.js][3], [Express][4] and [Mongoose][5]. DEPENDENCIES ------------ * [node.js][3] * [Express][4] * [Mongoose][5] INSTALLATION ------------ Clone the Github repository. Update the vendor libraries: $> git clone git://github.com/pminnieur/entropy.js.git $> sh update_vendors.sh You can run an entropy instance just by starting it with the `node` command: node entropy.js CONFIGURATION ------------- Copy the `config.json.sample` file to `config.json` and modify it to fit your needs. USAGE ----- You can use entropy without any models, but I recommend to have a schema for each of your models. You can put your Mongoose models in the `/models` directory. Here's an example of an simple user model: // models/user.js var mongoose = require("mongoose").Mongoose; mongoose.model("user", { properties: ["username", "email"], cast: { username: String, email: String }, indexes: ["username", "email"] }); That's it. You can now find, read, create, modify and remove user objects via REST, just by calling the appropriate URLs. The routing schema is very simple: GET /:collection find documents GET /:collection/:id read a document POST /:collection?collection[field1]=value1&collection[field2]=value2... create a document POST /:collection/:id?collection[field1]=value1&collection[field2]=value2... modify a document (collection[] parameter must match :collection) DELETE /:collection/:id remove a document > **NOTE:** the `collection[]` array must be named like the model you want to > access, thus for creating or modifying a user you must use it like this: > `?user[username]=foo&user[email]=bar` +### Finding documents + +You can specifiy what you want to find with the following parameters: + +#### Querying + + GET /:collection?query[field1]=value1&query[field2]=value2&... + + +#### Sorting + + GET /:collection?sort[field1]=asc|desc&sort[field2]=asc|desc&... + + +#### Pagination + + GET /:collection?limit=5&offset=5 + + CUSTOMIZATION ------------- If you want to overload the default behavior of the REST controllers, simply put your own in the `/controllers` directory. Here's an example for a customized user controller which removes users' email address from the response: // controllers/user.js var app = modules.parent.exports.app, db = modules.parent.exports.db; app.get('/user', function(req, res) { db.model('user').find().all(function(users) { ret = []; users.forEach(function(user) { user = user.toObject(); delete user.email; ret.push(user); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }) }); LICENSE ------- For the full copyright and license information, please view the `LICENSE` file that was distributed with this source code. [1]: http://en.wikipedia.org/wiki/Representational_State_Transfer [2]: http://www.mongodb.org/ [3]: http://nodejs.org/ [4]: http://expressjs.com/ [5]: http://www.learnboost.com/mongoose/ diff --git a/entropy.js b/entropy.js index 6df2f27..f73aea1 100644 --- a/entropy.js +++ b/entropy.js @@ -1,166 +1,188 @@ var fs = require('fs'), sys = require('sys'), extname = require('path').extname; // bootstrap 3rd-party libraries require.paths.unshift(__dirname+'/support/'); require.paths.unshift(__dirname+'/support/mongoose/'); // include 3rd-party libraries var express = require('express'), mongoose = require('mongoose').Mongoose; // create server var app = module.exports.app = express.createServer(); // configure server +app.use(express.bodyDecoder()); app.use(express.compiler({ enable: true })); app.use(express.conditionalGet()); app.use(express.methodOverride()); app.use(express.staticProvider(__dirname+'/public')); app.set('views', __dirname+'/views'); // load configuration try { var cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } // file loader (for controllers, models, ...) var loader = function(dir) { fs.readdir(dir, function(err, files) { if (err) { throw err; } files.forEach(function(file) { if (extname(file) == '.js') { require(dir+'/'+file.replace('.js', '')); } }); }); }; // enable debugger if (true == cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } // enable logger if (true == cfg.logger) { app.use(express.logger()); } var NotFound = module.exports.nf = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); }; sys.inherits(NotFound, Error); // Error 404 app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); // Error 500 app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // open db connection var db = module.exports.db = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); // load models cfg.loader.models.forEach(loader); // load controllers cfg.loader.controllers.forEach(loader); // load default controller if (cfg.loader.use_default_controller) { // FIND app.get('/:collection', function(req, res, next) { - var col = db.model(req.param('collection')); + var col = db.model(req.params.collection), + qw = col.find(); - col.find().all(function(docs) { + if (req.param('query')) { + qw.where(req.param('query')); + } + + if (req.param('order')) { + var order = []; + req.param('order').forEach(function(dir, field) { + order.push([field, dir]); + }); + qw.sort(order); + } + + if (req.param('limit')) { + qw.limit(req.param('limit')); + } + + if (req.param('offset')) { + qw.skip(req.param('offset')); + } + + qw.all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { - var col = db.model(req.param('collection')); + var col = db.model(req.params.collection); - col.findById(req.param('id'), function(doc) { + col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); } }); }); // CREATE app.post('/:collection', function(req, res, next) { - var col = db.model(req.param('collection')), + var col = db.model(req.params.collection), doc = new col; - doc.merge(req.param(req.param('collection'))); + doc.merge(req.param(req.params.collection)); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY app.post('/:collection/:id', function(req, res, next) { - var col = db.model(req.param('collection')); + var col = db.model(req.params.collection); - col.findById(req.param('id'), function(doc) { + col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { - doc.merge(req.param(req.param('collection'))); + doc.merge(req.param(req.params.collection)); doc.save(function() { res.send(doc.toObject(), 200); }); } }); }); // REMOVE app.del('/:collection/:id', function(req, res, next) { - var col = db.model(req.param('collection')); + var col = db.model(req.params.collection); - col.findById(req.param('id'), function(doc) { + col.findById(req.params.id, function(doc) { if (!doc) { next(new NotFound); } else { doc.remove(function() { res.send('200 OK', 200); }); } }); }); } // start server app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
4b0ffb25543f01f713a8f8c3a0d47b2ee1a669ff
added custom controller, views and public (static files) support
diff --git a/.gitignore b/.gitignore index 190f9ff..6964278 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ /config.json +/controllers/* /models/* +/public/* +/views/* diff --git a/README.md b/README.md index c43b283..b97b3c7 100644 --- a/README.md +++ b/README.md @@ -1,75 +1,100 @@ README ====== entropy is a simple [RESTful][1] server in front of a [MongoDB][2] instance using [node.js][3], [Express][4] and [Mongoose][5]. DEPENDENCIES ------------ * [node.js][3] * [Express][4] * [Mongoose][5] INSTALLATION ------------ Clone the Github repository. Initialize and update the git submodules: git submodule init --recursive git submodule update --recursive You can run an entropy instance just by starting it with the `node` command: node entropy.js CONFIGURATION ------------- Copy the `config.json.sample` file to `config.json` and modify it to fit your needs. USAGE ----- You can put your Mongoose models in the `/models` directory. Here's an example of an simple user model: // models/user.js var mongoose = require("mongoose").Mongoose; mongoose.model("user", { properties: ["username", "email"], cast: { username: String, email: String }, indexes: ["username", "email"] }); + That's it. You can now find, read, create, modify and remove user objects via REST, just by calling the appropriate URLs: GET localhost:3000/user // find GET localhost:3000/user/1 // read POST localhost:3000/user?user[username]=foo&user[email]=bar // create POST localhost:3000/user/1?user[username]=foo&user[email]=bar // modify DELETE localhost:3000/user/1 // remove - + +CUSTOMIZATION +------------- + +If you want to overload the default behavior of the REST controllers, simply +put your own in the `/controllers` directory. Here's an example for a customized +user controller which removes users' email address from the response: + + // controllers/user.js + var app = modules.parent.exports.app, + db = modules.parent.exports.db; + + app.get('/user', function(req, res) { + db.model('user').find().all(function(users) { + ret = []; + users.forEach(function(user) { + user = user.toObject(); + delete user.email; + ret.push(user); + }); + + res.header('Content-Type', 'application/json'); + res.send(ret, 200); + }) + }); LICENSE ------- For the full copyright and license information, please view the `LICENSE` file that was distributed with this source code. [1]: http://en.wikipedia.org/wiki/Representational_State_Transfer [2]: http://www.mongodb.org/ [3]: http://nodejs.org/ [4]: http://expressjs.com/ [5]: http://www.learnboost.com/mongoose/ diff --git a/config.json.sample b/config.json.sample index 799d133..f809e1c 100644 --- a/config.json.sample +++ b/config.json.sample @@ -1,15 +1,21 @@ { "debug": false, "logger": false, + "loader": { + "controllers": ["./controllers"], + "use_default_controller": true, + "models": ["./models"] + }, + "mongo": { "host": "localhost", "port": 27017, "name": "entropy" }, "server": { "addr": "localhost", "port": 3000 } } diff --git a/controllers/.gitkeep b/controllers/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/entropy.js b/entropy.js index fe6a5c9..6df2f27 100644 --- a/entropy.js +++ b/entropy.js @@ -1,151 +1,166 @@ var fs = require('fs'), - sys = require('sys'); + sys = require('sys'), + extname = require('path').extname; + +// bootstrap 3rd-party libraries +require.paths.unshift(__dirname+'/support/'); +require.paths.unshift(__dirname+'/support/mongoose/'); // include 3rd-party libraries -var express = require(__dirname+'/support/express'), - mongoose = require(__dirname+'/support/mongoose/mongoose').Mongoose; +var express = require('express'), + mongoose = require('mongoose').Mongoose; // create server -var app = express.createServer(); +var app = module.exports.app = express.createServer(); // configure server +app.use(express.compiler({ enable: true })); app.use(express.conditionalGet()); app.use(express.methodOverride()); +app.use(express.staticProvider(__dirname+'/public')); +app.set('views', __dirname+'/views'); +// load configuration try { - var cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); + var cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } -if (cfg.debug) { +// file loader (for controllers, models, ...) +var loader = function(dir) { + fs.readdir(dir, function(err, files) { + if (err) { + throw err; + } + + files.forEach(function(file) { + if (extname(file) == '.js') { + require(dir+'/'+file.replace('.js', '')); + } + }); + }); +}; + +// enable debugger +if (true == cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } -if (cfg.logger) { +// enable logger +if (true == cfg.logger) { app.use(express.logger()); } -// open db connection -var mongodb = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); - -// load models -require.paths.unshift(__dirname+'/models'); -fs.readdir(__dirname+'/models', function(err, files) { - if (err) { - throw err; - } - - var extname = require('path').extname; - files.forEach(function(file) { - if (extname(file) == '.js') { - require(file.replace('.js', '')); - } - }); -}); - -function NotFound(msg) { +var NotFound = module.exports.nf = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); -} +}; sys.inherits(NotFound, Error); // Error 404 app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); // Error 500 app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); -// HELLO -app.get('/', function(req, res, next) { - res.send('200 OK', 200); -}); +// open db connection +var db = module.exports.db = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); -// FIND -app.get('/:collection', function(req, res, next) { - var col = mongodb.model(req.param('collection')); +// load models +cfg.loader.models.forEach(loader); - col.find().all(function(docs) { - var ret = []; - docs.forEach(function(doc) { - ret.push(doc.toObject()); - }); +// load controllers +cfg.loader.controllers.forEach(loader); - res.header('Content-Type', 'application/json'); - res.send(ret, 200); - }); -}); +// load default controller +if (cfg.loader.use_default_controller) { + // FIND + app.get('/:collection', function(req, res, next) { + var col = db.model(req.param('collection')); -// READ -app.get('/:collection/:id', function(req, res, next) { - var col = mongodb.model(req.param('collection')); + col.find().all(function(docs) { + var ret = []; + docs.forEach(function(doc) { + ret.push(doc.toObject()); + }); - col.findById(req.param('id'), function(doc) { - if (!doc) { - next(new NotFound); - } else { res.header('Content-Type', 'application/json'); - res.send(doc.toObject(), 200); - } + res.send(ret, 200); + }); }); -}); - -// CREATE -app.post('/:collection', function(req, res, next) { - var col = mongodb.model(req.param('collection')), - doc = new col; - doc.merge(req.param(req.param('collection'))); + // READ + app.get('/:collection/:id', function(req, res, next) { + var col = db.model(req.param('collection')); - doc.save(function() { - res.send(doc.toObject(), 201); + col.findById(req.param('id'), function(doc) { + if (!doc) { + next(new NotFound); + } else { + res.header('Content-Type', 'application/json'); + res.send(doc.toObject(), 200); + } + }); }); -}); -// MODIFY -app.post('/:collection/:id', function(req, res, next) { - var col = mongodb.model(req.param('collection')); + // CREATE + app.post('/:collection', function(req, res, next) { + var col = db.model(req.param('collection')), + doc = new col; - col.findById(req.param('id'), function(doc) { - if (!doc) { - next(new NotFound); - } else { - doc.merge(req.param(req.param('collection'))); + doc.merge(req.param(req.param('collection'))); - doc.save(function() { - res.send(doc.toObject(), 200); - }); - } + doc.save(function() { + res.send(doc.toObject(), 201); + }); }); -}); -// REMOVE -app.del('/:collection/:id', function(req, res, next) { - var col = mongodb.model(req.param('collection')); + // MODIFY + app.post('/:collection/:id', function(req, res, next) { + var col = db.model(req.param('collection')); - col.findById(req.param('id'), function(doc) { - if (!doc) { - next(new NotFound); - } else { - doc.remove(function() { - res.send('200 OK', 200); - }); - } + col.findById(req.param('id'), function(doc) { + if (!doc) { + next(new NotFound); + } else { + doc.merge(req.param(req.param('collection'))); + + doc.save(function() { + res.send(doc.toObject(), 200); + }); + } + }); }); -}); + + // REMOVE + app.del('/:collection/:id', function(req, res, next) { + var col = db.model(req.param('collection')); + + col.findById(req.param('id'), function(doc) { + if (!doc) { + next(new NotFound); + } else { + doc.remove(function() { + res.send('200 OK', 200); + }); + } + }); + }); +} // start server app.listen(cfg.server.port /* , cfg.server.addr */); diff --git a/public/.gitkeep b/public/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/views/.gitkeep b/views/.gitkeep new file mode 100644 index 0000000..e69de29
chevalun/entropy.js
00baf375463bdfe4fcc56b48041df695da002464
removed Connect and NPM
diff --git a/README.md b/README.md index f5bd0d4..c43b283 100644 --- a/README.md +++ b/README.md @@ -1,78 +1,75 @@ README ====== entropy is a simple [RESTful][1] server in front of a [MongoDB][2] instance -using [node.js][3], [Express][4], [Connect][5] and [Mongoose][6]. +using [node.js][3], [Express][4] and [Mongoose][5]. DEPENDENCIES ------------ * [node.js][3] * [Express][4] -* [Connect][5] -* [Mongoose][6] +* [Mongoose][5] INSTALLATION ------------ Clone the Github repository. Initialize and update the git submodules: git submodule init --recursive git submodule update --recursive You can run an entropy instance just by starting it with the `node` command: node entropy.js CONFIGURATION ------------- Copy the `config.json.sample` file to `config.json` and modify it to fit your needs. USAGE ----- You can put your Mongoose models in the `/models` directory. Here's an example of an simple user model: // models/user.js var mongoose = require("mongoose").Mongoose; mongoose.model("user", { properties: ["username", "email"], cast: { username: String, email: String }, indexes: ["username", "email"] }); That's it. You can now find, read, create, modify and remove user objects via REST, just by calling the appropriate URLs: GET localhost:3000/user // find GET localhost:3000/user/1 // read POST localhost:3000/user?user[username]=foo&user[email]=bar // create POST localhost:3000/user/1?user[username]=foo&user[email]=bar // modify DELETE localhost:3000/user/1 // remove LICENSE ------- For the full copyright and license information, please view the `LICENSE` file that was distributed with this source code. [1]: http://en.wikipedia.org/wiki/Representational_State_Transfer [2]: http://www.mongodb.org/ [3]: http://nodejs.org/ [4]: http://expressjs.com/ -[5]: http://senchalabs.github.com/connect/ -[6]: http://www.learnboost.com/mongoose/ -[7]: http://npmjs.org/ +[5]: http://www.learnboost.com/mongoose/
chevalun/entropy.js
ae5e73cbef5c8869a5c371f16b081ffb1732f7f8
make use of express/mongoose submodules
diff --git a/README.md b/README.md index ac25fd6..f5bd0d4 100644 --- a/README.md +++ b/README.md @@ -1,73 +1,78 @@ README ====== entropy is a simple [RESTful][1] server in front of a [MongoDB][2] instance using [node.js][3], [Express][4], [Connect][5] and [Mongoose][6]. DEPENDENCIES ------------ * [node.js][3] * [Express][4] * [Connect][5] * [Mongoose][6] INSTALLATION ------------ -Clone the Github repository or simply download the sources. You can run an -entropy instance just by starting it with the `node` command: +Clone the Github repository. Initialize and update the git submodules: + + git submodule init --recursive + git submodule update --recursive + + +You can run an entropy instance just by starting it with the `node` command: node entropy.js CONFIGURATION ------------- Copy the `config.json.sample` file to `config.json` and modify it to fit your needs. USAGE ----- You can put your Mongoose models in the `/models` directory. Here's an example of an simple user model: // models/user.js var mongoose = require("mongoose").Mongoose; mongoose.model("user", { properties: ["username", "email"], cast: { username: String, email: String }, indexes: ["username", "email"] }); That's it. You can now find, read, create, modify and remove user objects via REST, just by calling the appropriate URLs: GET localhost:3000/user // find GET localhost:3000/user/1 // read POST localhost:3000/user?user[username]=foo&user[email]=bar // create POST localhost:3000/user/1?user[username]=foo&user[email]=bar // modify DELETE localhost:3000/user/1 // remove LICENSE ------- For the full copyright and license information, please view the `LICENSE` file that was distributed with this source code. [1]: http://en.wikipedia.org/wiki/Representational_State_Transfer [2]: http://www.mongodb.org/ [3]: http://nodejs.org/ [4]: http://expressjs.com/ [5]: http://senchalabs.github.com/connect/ [6]: http://www.learnboost.com/mongoose/ [7]: http://npmjs.org/ diff --git a/entropy.js b/entropy.js index d771c9d..fe6a5c9 100644 --- a/entropy.js +++ b/entropy.js @@ -1,142 +1,151 @@ var fs = require('fs'), - sys = require('sys'), - express = require('express'), - extname = require('path').extname; + sys = require('sys'); +// include 3rd-party libraries +var express = require(__dirname+'/support/express'), + mongoose = require(__dirname+'/support/mongoose/mongoose').Mongoose; + +// create server var app = express.createServer(); +// configure server app.use(express.conditionalGet()); app.use(express.methodOverride()); try { var cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } if (cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } if (cfg.logger) { app.use(express.logger()); } -var mongoose = require('mongoose').Mongoose, - mongodb = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); +// open db connection +var mongodb = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); +// load models require.paths.unshift(__dirname+'/models'); fs.readdir(__dirname+'/models', function(err, files) { if (err) { - throw new Error; + throw err; } + var extname = require('path').extname; files.forEach(function(file) { if (extname(file) == '.js') { require(file.replace('.js', '')); } }); }); function NotFound(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } sys.inherits(NotFound, Error); +// Error 404 app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); +// Error 500 app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // HELLO app.get('/', function(req, res, next) { res.send('200 OK', 200); }); // FIND app.get('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.find().all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); } }); }); // CREATE app.post('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')), doc = new col; doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY app.post('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 200); }); } }); }); // REMOVE app.del('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { doc.remove(function() { res.send('200 OK', 200); }); } }); }); +// start server app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
7ac696311f4d7227c6bc66ddead6d1cca54570b5
added externals (express and mongoose)
diff --git a/.gitignore b/.gitignore index ca348ea..190f9ff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,2 @@ /config.json /models/* -/support diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..d421ad0 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "support/express"] + path = support/express + url = git://github.com/visionmedia/express.git +[submodule "support/mongoose"] + path = support/mongoose + url = git://github.com/LearnBoost/mongoose.git diff --git a/support/express b/support/express new file mode 160000 index 0000000..3150253 --- /dev/null +++ b/support/express @@ -0,0 +1 @@ +Subproject commit 31502536617ef29f70a7f6184c2f5c51fc49e0c1 diff --git a/support/mongoose b/support/mongoose new file mode 160000 index 0000000..1506a4f --- /dev/null +++ b/support/mongoose @@ -0,0 +1 @@ +Subproject commit 1506a4f5196ff8cc03d366e381e955e9f7633e82
chevalun/entropy.js
961f24f3d844a66d007f610b05c0c97e6ae62032
fixed delete response
diff --git a/entropy.js b/entropy.js index cc47463..d771c9d 100644 --- a/entropy.js +++ b/entropy.js @@ -1,142 +1,142 @@ var fs = require('fs'), sys = require('sys'), express = require('express'), extname = require('path').extname; var app = express.createServer(); app.use(express.conditionalGet()); app.use(express.methodOverride()); try { var cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } if (cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } if (cfg.logger) { app.use(express.logger()); } var mongoose = require('mongoose').Mongoose, mongodb = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); require.paths.unshift(__dirname+'/models'); fs.readdir(__dirname+'/models', function(err, files) { if (err) { throw new Error; } files.forEach(function(file) { if (extname(file) == '.js') { require(file.replace('.js', '')); } }); }); function NotFound(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } sys.inherits(NotFound, Error); app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // HELLO app.get('/', function(req, res, next) { res.send('200 OK', 200); }); // FIND app.get('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.find().all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); } }); }); // CREATE app.post('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')), doc = new col; doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY app.post('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 200); }); } }); }); // REMOVE app.del('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { doc.remove(function() { - res.send(doc.toObject(), 200); + res.send('200 OK', 200); }); } }); }); app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
bc72df8ce268e54e083ceffb892f1533356a0a2a
fixed status code for modify
diff --git a/entropy.js b/entropy.js index 86b0b08..cc47463 100644 --- a/entropy.js +++ b/entropy.js @@ -1,142 +1,142 @@ var fs = require('fs'), sys = require('sys'), express = require('express'), extname = require('path').extname; var app = express.createServer(); app.use(express.conditionalGet()); app.use(express.methodOverride()); try { var cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } if (cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } if (cfg.logger) { app.use(express.logger()); } var mongoose = require('mongoose').Mongoose, mongodb = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); require.paths.unshift(__dirname+'/models'); fs.readdir(__dirname+'/models', function(err, files) { if (err) { throw new Error; } files.forEach(function(file) { if (extname(file) == '.js') { require(file.replace('.js', '')); } }); }); function NotFound(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } sys.inherits(NotFound, Error); app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // HELLO app.get('/', function(req, res, next) { res.send('200 OK', 200); }); // FIND app.get('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.find().all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); } }); }); // CREATE app.post('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')), doc = new col; doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY app.post('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { doc.merge(req.param(req.param('collection'))); doc.save(function() { - res.send(doc.toObject(), 201); + res.send(doc.toObject(), 200); }); } }); }); // REMOVE app.del('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { doc.remove(function() { res.send(doc.toObject(), 200); }); } }); }); app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
969e96fb152a24c9c783dd491300adc1e12a6795
fixed typo
diff --git a/entropy.js b/entropy.js index 19a4f89..86b0b08 100644 --- a/entropy.js +++ b/entropy.js @@ -1,142 +1,142 @@ var fs = require('fs'), sys = require('sys'), express = require('express'), extname = require('path').extname; var app = express.createServer(); app.use(express.conditionalGet()); app.use(express.methodOverride()); try { var cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { - throw new Error("File configg.json not found. Try: 'cp config.json.sample config.json'"); + throw new Error("File config.json not found. Try: 'cp config.json.sample config.json'"); } if (cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } if (cfg.logger) { app.use(express.logger()); } var mongoose = require('mongoose').Mongoose, mongodb = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); require.paths.unshift(__dirname+'/models'); fs.readdir(__dirname+'/models', function(err, files) { if (err) { throw new Error; } files.forEach(function(file) { if (extname(file) == '.js') { require(file.replace('.js', '')); } }); }); function NotFound(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } sys.inherits(NotFound, Error); app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // HELLO app.get('/', function(req, res, next) { res.send('200 OK', 200); }); // FIND app.get('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.find().all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); } }); }); // CREATE app.post('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')), doc = new col; doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY app.post('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); } }); }); // REMOVE app.del('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { next(new NotFound); } else { doc.remove(function() { res.send(doc.toObject(), 200); }); } }); }); app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
f0e34ed7db12c3b32271b04b9a2cdca42a5948e4
fixed typos
diff --git a/README.md b/README.md index 320b917..ac25fd6 100644 --- a/README.md +++ b/README.md @@ -1,72 +1,73 @@ README ====== entropy is a simple [RESTful][1] server in front of a [MongoDB][2] instance using [node.js][3], [Express][4], [Connect][5] and [Mongoose][6]. DEPENDENCIES ------------ * [node.js][3] * [Express][4] * [Connect][5] * [Mongoose][6] INSTALLATION ------------ Clone the Github repository or simply download the sources. You can run an -entropy instance just by starting it with Node: +entropy instance just by starting it with the `node` command: node entropy.js CONFIGURATION ------------- -Copy the `config.json.sample` file and modify it to fit your needs. +Copy the `config.json.sample` file to `config.json` and modify it to fit your +needs. USAGE ----- You can put your Mongoose models in the `/models` directory. Here's an example -of an simple User model: +of an simple user model: // models/user.js var mongoose = require("mongoose").Mongoose; mongoose.model("user", { properties: ["username", "email"], cast: { username: String, email: String }, indexes: ["username", "email"] }); That's it. You can now find, read, create, modify and remove user objects via REST, just by calling the appropriate URLs: GET localhost:3000/user // find GET localhost:3000/user/1 // read POST localhost:3000/user?user[username]=foo&user[email]=bar // create POST localhost:3000/user/1?user[username]=foo&user[email]=bar // modify DELETE localhost:3000/user/1 // remove LICENSE ------- For the full copyright and license information, please view the `LICENSE` file that was distributed with this source code. [1]: http://en.wikipedia.org/wiki/Representational_State_Transfer [2]: http://www.mongodb.org/ [3]: http://nodejs.org/ [4]: http://expressjs.com/ [5]: http://senchalabs.github.com/connect/ [6]: http://www.learnboost.com/mongoose/ [7]: http://npmjs.org/
chevalun/entropy.js
bc81fcdd7b19822d773b0a1c30b4ac8f670f2a49
added LICENSE and README file
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2b2fbf9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Pierre Minnieur + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..320b917 --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +README +====== + +entropy is a simple [RESTful][1] server in front of a [MongoDB][2] instance +using [node.js][3], [Express][4], [Connect][5] and [Mongoose][6]. + +DEPENDENCIES +------------ + +* [node.js][3] +* [Express][4] +* [Connect][5] +* [Mongoose][6] + +INSTALLATION +------------ + +Clone the Github repository or simply download the sources. You can run an +entropy instance just by starting it with Node: + + node entropy.js + + +CONFIGURATION +------------- + +Copy the `config.json.sample` file and modify it to fit your needs. + + +USAGE +----- + +You can put your Mongoose models in the `/models` directory. Here's an example +of an simple User model: + + // models/user.js + var mongoose = require("mongoose").Mongoose; + + mongoose.model("user", { + properties: ["username", "email"], + cast: { + username: String, + email: String + }, + indexes: ["username", "email"] + }); + +That's it. You can now find, read, create, modify and remove user objects via +REST, just by calling the appropriate URLs: + + GET localhost:3000/user // find + GET localhost:3000/user/1 // read + POST localhost:3000/user?user[username]=foo&user[email]=bar // create + POST localhost:3000/user/1?user[username]=foo&user[email]=bar // modify + DELETE localhost:3000/user/1 // remove + + + +LICENSE +------- + +For the full copyright and license information, please view the `LICENSE` file +that was distributed with this source code. + + +[1]: http://en.wikipedia.org/wiki/Representational_State_Transfer +[2]: http://www.mongodb.org/ +[3]: http://nodejs.org/ +[4]: http://expressjs.com/ +[5]: http://senchalabs.github.com/connect/ +[6]: http://www.learnboost.com/mongoose/ +[7]: http://npmjs.org/
chevalun/entropy.js
a971582436580d03da8b253d08a06b16b89c2da9
minimal improvements
diff --git a/entropy.js b/entropy.js index 93bda44..19a4f89 100644 --- a/entropy.js +++ b/entropy.js @@ -1,142 +1,142 @@ var fs = require('fs'), sys = require('sys'), express = require('express'), extname = require('path').extname; var app = express.createServer(); app.use(express.conditionalGet()); app.use(express.methodOverride()); try { var cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { throw new Error("File configg.json not found. Try: 'cp config.json.sample config.json'"); } if (cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } if (cfg.logger) { app.use(express.logger()); } var mongoose = require('mongoose').Mongoose, mongodb = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); require.paths.unshift(__dirname+'/models'); fs.readdir(__dirname+'/models', function(err, files) { if (err) { throw new Error; } files.forEach(function(file) { if (extname(file) == '.js') { require(file.replace('.js', '')); } }); }); -function NotFound(msg){ +function NotFound(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } sys.inherits(NotFound, Error); app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // HELLO app.get('/', function(req, res, next) { - res.send('', 200); + res.send('200 OK', 200); }); // FIND app.get('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.find().all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { - return next(new NotFound); + next(new NotFound); + } else { + res.header('Content-Type', 'application/json'); + res.send(doc.toObject(), 200); } - - res.header('Content-Type', 'application/json'); - res.send(doc.toObject(), 200); }); }); // CREATE app.post('/:collection', function(req, res, next) { var col = mongodb.model(req.param('collection')), doc = new col; doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY app.post('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { - return next(new NotFound); - } - - doc.merge(req.param(req.param('collection'))); + next(new NotFound); + } else { + doc.merge(req.param(req.param('collection'))); - doc.save(function() { - res.send(doc.toObject(), 201); - }); + doc.save(function() { + res.send(doc.toObject(), 201); + }); + } }); }); // REMOVE app.del('/:collection/:id', function(req, res, next) { var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { - return next(new NotFound); + next(new NotFound); + } else { + doc.remove(function() { + res.send(doc.toObject(), 200); + }); } - - doc.remove(function() { - res.send(doc.toObject(), 200); - }); }); }); app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
234877dc54de4a2260b27835b4acdf16b61961ee
minimal optimizations
diff --git a/entropy.js b/entropy.js index 97fb305..93bda44 100644 --- a/entropy.js +++ b/entropy.js @@ -1,145 +1,142 @@ -var fs = require('fs'), +var fs = require('fs'), sys = require('sys'), express = require('express'), extname = require('path').extname; -var app = module.exports.app = express.createServer(); +var app = express.createServer(); app.use(express.conditionalGet()); app.use(express.methodOverride()); try { - cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+"/config.json").toString()); + var cfg = JSON.parse(fs.readFileSync(__dirname+'/config.json').toString()); } catch(e) { - sys.log("File cfg.json not found. Try: 'cp config.json.sample config.json'"); + throw new Error("File configg.json not found. Try: 'cp config.json.sample config.json'"); } if (cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } if (cfg.logger) { app.use(express.logger()); } var mongoose = require('mongoose').Mongoose, - mongodb = module.exports.db = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); + mongodb = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); require.paths.unshift(__dirname+'/models'); fs.readdir(__dirname+'/models', function(err, files) { if (err) { throw new Error; } files.forEach(function(file) { if (extname(file) == '.js') { require(file.replace('.js', '')); } }); }); -app.set('mongoose', mongoose); -app.set('mongodb', mongodb); - function NotFound(msg){ this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } sys.inherits(NotFound, Error); app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // HELLO app.get('/', function(req, res, next) { res.send('', 200); }); // FIND app.get('/:collection', function(req, res, next) { - var col = app.set('mongodb').model(req.param('collection')); + var col = mongodb.model(req.param('collection')); col.find().all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { - var col = app.set('mongodb').model(req.param('collection')); + var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); }); }); // CREATE app.post('/:collection', function(req, res, next) { - var col = app.set('mongodb').model(req.param('collection')), + var col = mongodb.model(req.param('collection')), doc = new col; doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY app.post('/:collection/:id', function(req, res, next) { - var col = app.set('mongodb').model(req.param('collection')); + var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); }); // REMOVE app.del('/:collection/:id', function(req, res, next) { - var col = app.set('mongodb').model(req.param('collection')); + var col = mongodb.model(req.param('collection')); col.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } doc.remove(function() { res.send(doc.toObject(), 200); }); }); }); app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
93f00a399bea8d3c43da6aed8531a24273d7ea7b
renamed model to col
diff --git a/entropy.js b/entropy.js index 3f10e03..97fb305 100644 --- a/entropy.js +++ b/entropy.js @@ -1,145 +1,145 @@ var fs = require('fs'), sys = require('sys'), express = require('express'), extname = require('path').extname; var app = module.exports.app = express.createServer(); app.use(express.conditionalGet()); app.use(express.methodOverride()); try { cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+"/config.json").toString()); } catch(e) { sys.log("File cfg.json not found. Try: 'cp config.json.sample config.json'"); } if (cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } if (cfg.logger) { app.use(express.logger()); } var mongoose = require('mongoose').Mongoose, mongodb = module.exports.db = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); require.paths.unshift(__dirname+'/models'); fs.readdir(__dirname+'/models', function(err, files) { if (err) { throw new Error; } files.forEach(function(file) { if (extname(file) == '.js') { require(file.replace('.js', '')); } }); }); app.set('mongoose', mongoose); app.set('mongodb', mongodb); function NotFound(msg){ this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } sys.inherits(NotFound, Error); app.error(function(err, req, res, next) { if (err instanceof NotFound) { res.send('404 Not found', 404); } else { next(err); } }); app.error(function(err, req, res) { res.send('500 Internal server error', 500); }); // HELLO app.get('/', function(req, res, next) { res.send('', 200); }); // FIND app.get('/:collection', function(req, res, next) { - var model = app.set('mongodb').model(req.param('collection')); + var col = app.set('mongodb').model(req.param('collection')); - model.find().all(function(docs) { + col.find().all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ app.get('/:collection/:id', function(req, res, next) { - var model = app.set('mongodb').model(req.param('collection')); + var col = app.set('mongodb').model(req.param('collection')); - model.findById(req.param('id'), function(doc) { + col.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); }); }); // CREATE app.post('/:collection', function(req, res, next) { - var model = app.set('mongodb').model(req.param('collection')), - doc = new model; + var col = app.set('mongodb').model(req.param('collection')), + doc = new col; doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY app.post('/:collection/:id', function(req, res, next) { - var model = app.set('mongodb').model(req.param('collection')); + var col = app.set('mongodb').model(req.param('collection')); - model.findById(req.param('id'), function(doc) { + col.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); }); // REMOVE app.del('/:collection/:id', function(req, res, next) { - var model = app.set('mongodb').model(req.param('collection')); + var col = app.set('mongodb').model(req.param('collection')); - model.findById(req.param('id'), function(doc) { + col.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } doc.remove(function() { res.send(doc.toObject(), 200); }); }); }); app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
fc57e47039933a073ea7ad4c10d699d6fcdf55b2
applied coding standards
diff --git a/entropy.js b/entropy.js index 0678f2b..3f10e03 100644 --- a/entropy.js +++ b/entropy.js @@ -1,146 +1,145 @@ - -var fs = require("fs"), - sys = require("sys"), - express = require("express"), +var fs = require('fs'), + sys = require('sys'), + express = require('express'), extname = require('path').extname; var app = module.exports.app = express.createServer(); app.use(express.conditionalGet()); app.use(express.methodOverride()); try { cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+"/config.json").toString()); } catch(e) { sys.log("File cfg.json not found. Try: 'cp config.json.sample config.json'"); } if (cfg.debug) { app.use(express.errorHandler({ showStack: true, dumpExceptions: true })); } if (cfg.logger) { app.use(express.logger()); } -var mongoose = require("mongoose").Mongoose, - mongodb = module.exports.db = mongoose.connect("mongodb://"+cfg.mongo.host+":"+cfg.mongo.port+"/"+cfg.mongo.name); +var mongoose = require('mongoose').Mongoose, + mongodb = module.exports.db = mongoose.connect('mongodb://'+cfg.mongo.host+':'+cfg.mongo.port+'/'+cfg.mongo.name); -require.paths.unshift(__dirname+"/models"); -fs.readdir(__dirname+"/models", function(err, files) { +require.paths.unshift(__dirname+'/models'); +fs.readdir(__dirname+'/models', function(err, files) { if (err) { throw new Error; } files.forEach(function(file) { if (extname(file) == '.js') { require(file.replace('.js', '')); } }); }); app.set('mongoose', mongoose); app.set('mongodb', mongodb); function NotFound(msg){ this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } sys.inherits(NotFound, Error); app.error(function(err, req, res, next) { if (err instanceof NotFound) { - res.send("404", 404); + res.send('404 Not found', 404); } else { next(err); } }); app.error(function(err, req, res) { - res.send("500", 500); + res.send('500 Internal server error', 500); }); // HELLO -app.get("/", function(req, res, next) { - res.send("hello", 200); +app.get('/', function(req, res, next) { + res.send('', 200); }); // FIND -app.get("/:collection", function(req, res, next) { - var model = app.set('mongodb').model(req.param("collection")); +app.get('/:collection', function(req, res, next) { + var model = app.set('mongodb').model(req.param('collection')); model.find().all(function(docs) { var ret = []; docs.forEach(function(doc) { ret.push(doc.toObject()); }); res.header('Content-Type', 'application/json'); res.send(ret, 200); }); }); // READ -app.get("/:collection/:id", function(req, res, next) { - var model = app.set('mongodb').model(req.param("collection")); +app.get('/:collection/:id', function(req, res, next) { + var model = app.set('mongodb').model(req.param('collection')); - model.findById(req.param("id"), function(doc) { + model.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } res.header('Content-Type', 'application/json'); res.send(doc.toObject(), 200); }); }); // CREATE -app.post("/:collection", function(req, res, next) { - var model = app.set('mongodb').model(req.param("collection")), +app.post('/:collection', function(req, res, next) { + var model = app.set('mongodb').model(req.param('collection')), doc = new model; - doc.merge(req.param(req.param("collection"))); + doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); // MODIFY -app.post("/:collection/:id", function(req, res, next) { - var model = app.set('mongodb').model(req.param("collection")); +app.post('/:collection/:id', function(req, res, next) { + var model = app.set('mongodb').model(req.param('collection')); - model.findById(req.param("id"), function(doc) { + model.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } - doc.merge(req.param(req.param("collection"))); + doc.merge(req.param(req.param('collection'))); doc.save(function() { res.send(doc.toObject(), 201); }); }); }); // REMOVE -app.del("/:collection/:id", function(req, res, next) { - var model = app.set('mongodb').model(req.param("collection")); +app.del('/:collection/:id', function(req, res, next) { + var model = app.set('mongodb').model(req.param('collection')); - model.findById(req.param("id"), function(doc) { + model.findById(req.param('id'), function(doc) { if (!doc) { return next(new NotFound); } doc.remove(function() { res.send(doc.toObject(), 200); }); }); }); app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
9b7ac8d873a04b618c38f88354e133387b57fa66
initial draft
diff --git a/.gitignore b/.gitignore index 190f9ff..ca348ea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /config.json /models/* +/support diff --git a/entropy.js b/entropy.js index c111e04..0678f2b 100644 --- a/entropy.js +++ b/entropy.js @@ -1,58 +1,146 @@ + var fs = require("fs"), - sys = require("sys"); + sys = require("sys"), + express = require("express"), + extname = require('path').extname; -var express = require("express"), - connect = require("connect"); +var app = module.exports.app = express.createServer(); -var entropy = express.createServer(); - -entropy.use(connect.conditionalGet()); -entropy.use(connect.methodOverride()); +app.use(express.conditionalGet()); +app.use(express.methodOverride()); try { - configJSON = fs.readFileSync(__dirname+"/config.json"); + cfg = module.exports.cfg = JSON.parse(fs.readFileSync(__dirname+"/config.json").toString()); } catch(e) { - sys.log("File config.json not found. Try: 'cp config.json.sample config.json'"); + sys.log("File cfg.json not found. Try: 'cp config.json.sample config.json'"); } -var config = JSON.parse(configJSON.toString()); -if (config.debug) { - entropy.use(connect.errorHandler({ - showStack: true, - dumpExceptions: true - })); +if (cfg.debug) { + app.use(express.errorHandler({ + showStack: true, + dumpExceptions: true + })); } -if (config.logger) { - entropy.use(connect.logger()); +if (cfg.logger) { + app.use(express.logger()); } var mongoose = require("mongoose").Mongoose, - mongodb = mongoose.connect("mongodb://"+config.mongo.host+":"+config.mongo.port+"/"+config.mongo.name); + mongodb = module.exports.db = mongoose.connect("mongodb://"+cfg.mongo.host+":"+cfg.mongo.port+"/"+cfg.mongo.name); + +require.paths.unshift(__dirname+"/models"); +fs.readdir(__dirname+"/models", function(err, files) { + if (err) { + throw new Error; + } + + files.forEach(function(file) { + if (extname(file) == '.js') { + require(file.replace('.js', '')); + } + }); +}); + +app.set('mongoose', mongoose); +app.set('mongodb', mongodb); + +function NotFound(msg){ + this.name = 'NotFound'; + Error.call(this, msg); + Error.captureStackTrace(this, arguments.callee); +} + +sys.inherits(NotFound, Error); + +app.error(function(err, req, res, next) { + if (err instanceof NotFound) { + res.send("404", 404); + } else { + next(err); + } +}); + +app.error(function(err, req, res) { + res.send("500", 500); +}); + +// HELLO +app.get("/", function(req, res, next) { + res.send("hello", 200); +}); // FIND -entropy.get("/:collection", function(req, res) { - res.send("find:"+req.param("collection"), 200); +app.get("/:collection", function(req, res, next) { + var model = app.set('mongodb').model(req.param("collection")); + + model.find().all(function(docs) { + var ret = []; + docs.forEach(function(doc) { + ret.push(doc.toObject()); + }); + + res.header('Content-Type', 'application/json'); + res.send(ret, 200); + }); }); // READ -entropy.get("/:collection/:id", function(req, res) { - res.send("read:"+req.param("collection")+"/"+req.param("id"), 200); +app.get("/:collection/:id", function(req, res, next) { + var model = app.set('mongodb').model(req.param("collection")); + + model.findById(req.param("id"), function(doc) { + if (!doc) { + return next(new NotFound); + } + + res.header('Content-Type', 'application/json'); + res.send(doc.toObject(), 200); + }); }); // CREATE -entropy.post("/:collection", function(req, res) { - res.send("create:"+req.param("collection"), 201); +app.post("/:collection", function(req, res, next) { + var model = app.set('mongodb').model(req.param("collection")), + doc = new model; + + doc.merge(req.param(req.param("collection"))); + + doc.save(function() { + res.send(doc.toObject(), 201); + }); }); // MODIFY -entropy.post("/:collection/:id", function(req, res) { - res.send("modify:"+req.param("collection")+"/"+req.param("id"), 200); +app.post("/:collection/:id", function(req, res, next) { + var model = app.set('mongodb').model(req.param("collection")); + + model.findById(req.param("id"), function(doc) { + if (!doc) { + return next(new NotFound); + } + + doc.merge(req.param(req.param("collection"))); + + doc.save(function() { + res.send(doc.toObject(), 201); + }); + }); }); // REMOVE -entropy.del("/:collection/:id", function(req, res) { - res.send("remove:"+req.param("collection")+"/"+req.param("id"), 200); +app.del("/:collection/:id", function(req, res, next) { + var model = app.set('mongodb').model(req.param("collection")); + + model.findById(req.param("id"), function(doc) { + if (!doc) { + return next(new NotFound); + } + + doc.remove(function() { + res.send(doc.toObject(), 200); + }); + }); }); -entropy.listen(config.server.port, config.server.addr); +app.listen(cfg.server.port /* , cfg.server.addr */);
chevalun/entropy.js
822747b73b3d46c1c6c98e326a5c03d5f7b3836a
fixed special characters
diff --git a/entropy.js b/entropy.js index 6b40862..c111e04 100644 --- a/entropy.js +++ b/entropy.js @@ -1,58 +1,58 @@ var fs = require("fs"), sys = require("sys"); var express = require("express"), connect = require("connect"); var entropy = express.createServer(); entropy.use(connect.conditionalGet()); entropy.use(connect.methodOverride()); try { configJSON = fs.readFileSync(__dirname+"/config.json"); } catch(e) { - sys.log("File config.json not found. Try: `cp config.json.sample config.json`"); + sys.log("File config.json not found. Try: 'cp config.json.sample config.json'"); } var config = JSON.parse(configJSON.toString()); if (config.debug) { entropy.use(connect.errorHandler({ showStack: true, dumpExceptions: true })); } if (config.logger) { entropy.use(connect.logger()); } var mongoose = require("mongoose").Mongoose, mongodb = mongoose.connect("mongodb://"+config.mongo.host+":"+config.mongo.port+"/"+config.mongo.name); // FIND entropy.get("/:collection", function(req, res) { res.send("find:"+req.param("collection"), 200); }); // READ entropy.get("/:collection/:id", function(req, res) { res.send("read:"+req.param("collection")+"/"+req.param("id"), 200); }); // CREATE entropy.post("/:collection", function(req, res) { res.send("create:"+req.param("collection"), 201); }); // MODIFY entropy.post("/:collection/:id", function(req, res) { res.send("modify:"+req.param("collection")+"/"+req.param("id"), 200); }); // REMOVE entropy.del("/:collection/:id", function(req, res) { res.send("remove:"+req.param("collection")+"/"+req.param("id"), 200); }); entropy.listen(config.server.port, config.server.addr);
chevalun/entropy.js
924990cfc4ade7cde5fa9b33ac92fab0b59ee6c7
replaced tabs with spaces
diff --git a/entropy.js b/entropy.js index 85705e9..6b40862 100644 --- a/entropy.js +++ b/entropy.js @@ -1,58 +1,58 @@ var fs = require("fs"), - sys = require("sys"); + sys = require("sys"); var express = require("express"), - connect = require("connect"); + connect = require("connect"); var entropy = express.createServer(); entropy.use(connect.conditionalGet()); entropy.use(connect.methodOverride()); try { - configJSON = fs.readFileSync(__dirname+"/config.json"); + configJSON = fs.readFileSync(__dirname+"/config.json"); } catch(e) { - sys.log("File config.json not found. Try: `cp config.json.sample config.json`"); + sys.log("File config.json not found. Try: `cp config.json.sample config.json`"); } var config = JSON.parse(configJSON.toString()); if (config.debug) { - entropy.use(connect.errorHandler({ - showStack: true, - dumpExceptions: true - })); + entropy.use(connect.errorHandler({ + showStack: true, + dumpExceptions: true + })); } if (config.logger) { - entropy.use(connect.logger()); + entropy.use(connect.logger()); } var mongoose = require("mongoose").Mongoose, - mongodb = mongoose.connect("mongodb://"+config.mongo.host+":"+config.mongo.port+"/"+config.mongo.name); + mongodb = mongoose.connect("mongodb://"+config.mongo.host+":"+config.mongo.port+"/"+config.mongo.name); // FIND entropy.get("/:collection", function(req, res) { - res.send("find:"+req.param("collection"), 200); + res.send("find:"+req.param("collection"), 200); }); // READ entropy.get("/:collection/:id", function(req, res) { - res.send("read:"+req.param("collection")+"/"+req.param("id"), 200); + res.send("read:"+req.param("collection")+"/"+req.param("id"), 200); }); // CREATE entropy.post("/:collection", function(req, res) { - res.send("create:"+req.param("collection"), 201); + res.send("create:"+req.param("collection"), 201); }); // MODIFY entropy.post("/:collection/:id", function(req, res) { - res.send("modify:"+req.param("collection")+"/"+req.param("id"), 200); + res.send("modify:"+req.param("collection")+"/"+req.param("id"), 200); }); // REMOVE entropy.del("/:collection/:id", function(req, res) { - res.send("remove:"+req.param("collection")+"/"+req.param("id"), 200); + res.send("remove:"+req.param("collection")+"/"+req.param("id"), 200); }); entropy.listen(config.server.port, config.server.addr);
chevalun/entropy.js
04243a9bbb6c53fc4ae88c0b75eb71f74f128f5b
initial import
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..190f9ff --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/config.json +/models/* diff --git a/config.json.sample b/config.json.sample new file mode 100644 index 0000000..799d133 --- /dev/null +++ b/config.json.sample @@ -0,0 +1,15 @@ +{ + "debug": false, + "logger": false, + + "mongo": { + "host": "localhost", + "port": 27017, + "name": "entropy" + }, + + "server": { + "addr": "localhost", + "port": 3000 + } +} diff --git a/entropy.js b/entropy.js new file mode 100644 index 0000000..85705e9 --- /dev/null +++ b/entropy.js @@ -0,0 +1,58 @@ +var fs = require("fs"), + sys = require("sys"); + +var express = require("express"), + connect = require("connect"); + +var entropy = express.createServer(); + +entropy.use(connect.conditionalGet()); +entropy.use(connect.methodOverride()); + +try { + configJSON = fs.readFileSync(__dirname+"/config.json"); +} catch(e) { + sys.log("File config.json not found. Try: `cp config.json.sample config.json`"); +} +var config = JSON.parse(configJSON.toString()); + +if (config.debug) { + entropy.use(connect.errorHandler({ + showStack: true, + dumpExceptions: true + })); +} + +if (config.logger) { + entropy.use(connect.logger()); +} + +var mongoose = require("mongoose").Mongoose, + mongodb = mongoose.connect("mongodb://"+config.mongo.host+":"+config.mongo.port+"/"+config.mongo.name); + +// FIND +entropy.get("/:collection", function(req, res) { + res.send("find:"+req.param("collection"), 200); +}); + +// READ +entropy.get("/:collection/:id", function(req, res) { + res.send("read:"+req.param("collection")+"/"+req.param("id"), 200); +}); + +// CREATE +entropy.post("/:collection", function(req, res) { + res.send("create:"+req.param("collection"), 201); +}); + +// MODIFY +entropy.post("/:collection/:id", function(req, res) { + res.send("modify:"+req.param("collection")+"/"+req.param("id"), 200); +}); + +// REMOVE +entropy.del("/:collection/:id", function(req, res) { + res.send("remove:"+req.param("collection")+"/"+req.param("id"), 200); +}); + +entropy.listen(config.server.port, config.server.addr); diff --git a/models/.gitkeep b/models/.gitkeep new file mode 100644 index 0000000..e69de29
bsbodden/HITS
02f0c0c5fc003bfdeab6632e92d30818a54bff11
added normalization on each iteration using sum of squares, added weighting logic
diff --git a/LICENSE b/LICENSE index c41979f..f2e627a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,3 +1,22 @@ -== hits +(The MIT License) -Put appropriate LICENSE for your project here. +Copyright &169;2001-2008 Integrallis Software, LLC. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README b/README index 0641eb2..591fb35 100644 --- a/README +++ b/README @@ -1,42 +1,54 @@ == hits A poor man's implementation of Jon Kleinberg's Hyperlink-Induced Topic Search (HITS) (also known as Hubs and authorities). See http://en.wikipedia.org/wiki/HITS_algorithm require 'rubygems' require 'hits' # create a graph graph = Hits::Graph.new # add some edges to the graph with weights graph.add_edge(:bsbodden, :objo, 1.0) graph.add_edge(:bsbodden, :nusairat, 2.0) graph.add_edge(:bsbodden, :looselytyped, 3.0) -graph.add_edge(:bsbodden, :neal4d, 1.5) +graph.add_edge(:bsbodden, :neal4d, 8.5) graph.add_edge(:objo, :nusairat, 2.5) graph.add_edge(:objo, :bsbodden, 1.0) graph.add_edge(:neal4d, :bsbodden, 1.15) graph.add_edge(:nusairat, :bsbodden, 4.5) # textual display of the graph puts "graph ==> #{graph}" +puts "graph max weight ==> #{graph.max_weight}" +puts "graph min weight ==> #{graph.min_weight}" # create a HITS for the graph hits = Hits::Hits.new(graph) # show the vertexes incoming and outgoing links (inlinks and outlinks) -graph.each_vertex { |v| puts "in links for #{v} ==> #{graph.in_links(v)}, out links for #{v} ==> #{graph.out_links(v)}"} +graph.each_vertex do |vertex| + puts "=== In links for #{vertex} ===" + graph.in_links(vertex).each { |in_link| puts in_link } + puts "=== Out links for #{vertex} ===" + graph.out_links(vertex).each { |out_link| puts out_link } +end # compute HITS with the default number of iterations hits.compute_hits # print the top HUBS and AUTHORITIES puts "=== TOP HUBS ===" hits.top_hub_scores.each do |hub| puts "hub #{hub}" end puts "=== TOP AUTHORITIES ===" hits.top_authority_scores.each do |authority| puts "authority #{authority}" end + +# print all scores +graph.each_vertex do |vertex| + puts "vertex: #{vertex}, authority: #{hits.authority_scores[vertex]}, hub: #{hits.hub_scores[vertex]}" +end diff --git a/Rakefile b/Rakefile index 813004d..e58b201 100644 --- a/Rakefile +++ b/Rakefile @@ -1,44 +1,44 @@ require 'rubygems' require 'rake' require 'rake/clean' require 'rake/gempackagetask' require 'rake/rdoctask' require 'rake/testtask' require 'spec/rake/spectask' spec = Gem::Specification.new do |s| s.name = 'hits' - s.version = '0.0.1' + s.version = '0.0.2' s.has_rdoc = true s.extra_rdoc_files = ['README', 'LICENSE'] s.summary = "A poor man's implementation of Jon Kleinberg's Hyperlink-Induced Topic Search (HITS) (also known as Hubs and authorities)" s.description = s.summary s.author = 'Brian Sam-Bodden' s.email = '[email protected]' s.files = %w(LICENSE README Rakefile) + Dir.glob("{bin,lib,spec}/**/*") s.require_path = "lib" s.bindir = "bin" end Rake::GemPackageTask.new(spec) do |p| p.gem_spec = spec p.need_tar = true p.need_zip = true end Rake::RDocTask.new do |rdoc| files =['README', 'LICENSE', 'lib/**/*.rb'] rdoc.rdoc_files.add(files) rdoc.main = "README" # page to start on rdoc.title = "hits Docs" rdoc.rdoc_dir = 'doc/rdoc' # rdoc output folder rdoc.options << '--line-numbers' end Rake::TestTask.new do |t| t.test_files = FileList['test/**/*.rb'] end Spec::Rake::SpecTask.new do |t| t.spec_files = FileList['spec/**/*.rb'] end \ No newline at end of file diff --git a/examples/example.rb b/examples/example.rb index a8f9188..0ac1b7b 100644 --- a/examples/example.rb +++ b/examples/example.rb @@ -1,45 +1,52 @@ require 'rubygems' require '../lib/hits/hits' require '../lib/hits/graph' # create a graph graph = Hits::Graph.new # add some edges to the graph with weights graph.add_edge(:bsbodden, :objo, 1.0) graph.add_edge(:bsbodden, :nusairat, 2.0) graph.add_edge(:bsbodden, :looselytyped, 3.0) -graph.add_edge(:bsbodden, :neal4d, 1.5) +graph.add_edge(:bsbodden, :neal4d, 8.5) graph.add_edge(:objo, :nusairat, 2.5) graph.add_edge(:objo, :bsbodden, 1.0) graph.add_edge(:neal4d, :bsbodden, 1.15) graph.add_edge(:nusairat, :bsbodden, 4.5) # textual display of the graph puts "graph ==> #{graph}" +puts "graph max weight ==> #{graph.max_weight}" +puts "graph min weight ==> #{graph.min_weight}" # create a HITS for the graph hits = Hits::Hits.new(graph) # show the vertexes incoming and outgoing links (inlinks and outlinks) graph.each_vertex do |vertex| puts "=== In links for #{vertex} ===" graph.in_links(vertex).each { |in_link| puts in_link } puts "=== Out links for #{vertex} ===" graph.out_links(vertex).each { |out_link| puts out_link } end # compute HITS with the default number of iterations hits.compute_hits # print the top HUBS and AUTHORITIES puts "=== TOP HUBS ===" hits.top_hub_scores.each do |hub| puts "hub #{hub}" end puts "=== TOP AUTHORITIES ===" hits.top_authority_scores.each do |authority| puts "authority #{authority}" end +# print all scores +graph.each_vertex do |vertex| + puts "vertex: #{vertex}, authority: #{hits.authority_scores[vertex]}, hub: #{hits.hub_scores[vertex]}" +end + diff --git a/lib/hits/graph.rb b/lib/hits/graph.rb index 9397604..d62fa7e 100644 --- a/lib/hits/graph.rb +++ b/lib/hits/graph.rb @@ -1,48 +1,60 @@ require 'rgl/dot' require 'rgl/adjacency' require 'rgl/bidirectional' module Hits class Graph attr_reader :graph def initialize @graph = RGL::DirectedAdjacencyGraph.new @in_links = {} @edge_weights = {} end def add_edge(from, to, weight = 1.0) @graph.add_edge(from, to) @in_links[to] ||= [] @in_links[to] << from unless @in_links[to].include? from @edge_weights[[to, from]] = weight end def in_links(vertex) @in_links[vertex] end def out_links(vertex) @graph.adjacent_vertices(vertex) end def each_vertex(&b) @graph.each_vertex(&b) end def weight(to, from) @edge_weights[[to, from]] end def weight=(to, from, weight) @edge_weights[[to, from]] = weight if @edge_weights[[to, from]] end + + def max_weight + @edge_weights.values.max + end + + def min_weight + @edge_weights.values.min + end + + def weights + @edge_weights.values + end def to_s @graph.edges.to_a.to_s end end end \ No newline at end of file diff --git a/lib/hits/hits.rb b/lib/hits/hits.rb index 03525c6..04e8974 100644 --- a/lib/hits/hits.rb +++ b/lib/hits/hits.rb @@ -1,36 +1,61 @@ module Hits class Hits - def initialize(graph) + attr_reader :authority_scores + attr_reader :hub_scores + + def initialize(graph, use_weights = true) @graph = graph + @use_weights = use_weights @hub_scores = {} @authority_scores = {} @graph.each_vertex do |vertex| @hub_scores[vertex] = 1.0 @authority_scores[vertex] = 1.0 end end def compute_hits(iterations = 25) (1..iterations).each do @graph.each_vertex do |vertex| - authority_score = @graph.in_links(vertex).inject(0.0) { |sum, vertex| sum + @hub_scores[vertex] } - hub_score = @graph.out_links(vertex).inject(0.0) { |sum, vertex| sum + @authority_scores[vertex] } - @authority_scores[vertex] = authority_score - @hub_scores[vertex] = hub_score + authority_score = @graph.in_links(vertex).inject(0.0) { |sum, vertex| sum + @hub_scores[vertex] } if @graph.in_links(vertex) + hub_score = @graph.out_links(vertex).inject(0.0) { |sum, vertex| sum + @authority_scores[vertex] } if @graph.out_links(vertex) + @authority_scores[vertex] = authority_score || 0.0 + @hub_scores[vertex] = hub_score || 0.0 end + normalize_scores end + apply_weighting if @use_weights end def top_hub_scores(how_many=5) - @hub_scores.sort_by { |k,v| v }.collect { |v| v[0] }.reverse.first(how_many) + @hub_scores.sort_by { |k,v| v }.map { |v| v[0] }.reverse.first(how_many) end def top_authority_scores(how_many=5) - @authority_scores.sort_by { |k,v| v }.collect { |v| v[0] }.reverse.first(how_many) + @authority_scores.sort_by { |k,v| v }.map { |v| v[0] }.reverse.first(how_many) + end + + private + + def normalize_scores + sum_of_squares_for_authorities = @authority_scores.inject(0.0) { |sum, element| sum + element[1]**2 } + sum_of_squares_for_hubs = @hub_scores.inject(0.0) { |sum, element| sum + element[1]**2 } + @authority_scores.each { |key, value| @authority_scores[key] = value / sum_of_squares_for_authorities } + @hub_scores.each { |key, value| @hub_scores[key] = value / sum_of_squares_for_hubs } + end + + def apply_weighting + sum = @graph.weights.inject(0.0) { |sum, weight| sum + weight } + max = @graph.max_weight + min = @graph.min_weight + @graph.each_vertex do |vertex| + @authority_scores[vertex] = (@authority_scores[vertex] / sum) * (max - min) + min + @hub_scores[vertex] = (@hub_scores[vertex] / sum) * (max - min) + min + end end end end \ No newline at end of file diff --git a/pkg/hits-0.0.1.gem b/pkg/hits-0.0.1.gem new file mode 100644 index 0000000..f05fab0 Binary files /dev/null and b/pkg/hits-0.0.1.gem differ
Merino/github-learning
dafe5aa284726f2eb4fe6f2796c975c876b032ae
new feature for REAME
diff --git a/README b/README index 7967e58..7e4e7a3 100644 --- a/README +++ b/README @@ -1,2 +1,4 @@ -- README -- De meeste gebruikers lezen een README niet eens. + +En nu hebben we een new-featurex
Merino/github-learning
c5fb0ff1a79d3a0678cee16789e83992e062bd13
change readme
diff --git a/README b/README index 8108a41..7967e58 100644 --- a/README +++ b/README @@ -1 +1,2 @@ -De 2e tekens +-- README -- +De meeste gebruikers lezen een README niet eens.
Merino/github-learning
e4158daa8bd06014e3cdae3069e16c19228f8d70
add readme
diff --git a/README b/README new file mode 100644 index 0000000..e69de29
justquick/django-xlink
e4aff1fc19a57e974f70c83702ddfa2f4f454039
added link text field for Results, version bump
diff --git a/example/example.db b/example/example.db index de8cdc3..b03ac3c 100644 Binary files a/example/example.db and b/example/example.db differ diff --git a/xlink/__init__.py b/xlink/__init__.py index c12f34c..34da6b8 100644 --- a/xlink/__init__.py +++ b/xlink/__init__.py @@ -1 +1 @@ -__version__ = '0.1.1' \ No newline at end of file +__version__ = '0.1.2' \ No newline at end of file diff --git a/xlink/admin.py b/xlink/admin.py index 55d10c9..b60e919 100644 --- a/xlink/admin.py +++ b/xlink/admin.py @@ -1,16 +1,16 @@ from django.contrib import admin from models import Query, Result class QueryAdmin(admin.ModelAdmin): list_display = ('__unicode__','search_on','look_for','active') list_editable = list_display[1:] search_fields = ('search_on','look_for') class ResultAdmin(admin.ModelAdmin): - list_display = ('__unicode__','found_on','timestamp','display') - list_editable = ('display',) + list_display = ('__unicode__','text','found_on','timestamp','display') + list_editable = ('text','display',) search_fields = ('url','found_on') list_filter = ('timestamp','display') admin.site.register(Query, QueryAdmin) admin.site.register(Result, ResultAdmin) diff --git a/xlink/management/commands/xlink_search.py b/xlink/management/commands/xlink_search.py index 8e932a8..1bb125a 100644 --- a/xlink/management/commands/xlink_search.py +++ b/xlink/management/commands/xlink_search.py @@ -1,28 +1,28 @@ from django.core.management.base import BaseCommand from django.core.exceptions import ImproperlyConfigured try: from lxml.html import parse except ImportError: raise ImproperlyConfigured('You must have lxml installed before searching') from xlink.models import Query, Result class Command(BaseCommand): def handle(self, *args, **options): for query in Query.objects.filter(active=True): html = parse(query.search_on).getroot() html.make_links_absolute(query.search_on) for link in html.iterlinks(): try: url = link[2] domain = url.split('/')[2] except IndexError: continue if domain == query.look_for: - lookup = {'url':url, 'found_on': query.search_on} + lookup = {'url':url, 'found_on':query.search_on, 'text':link[0].text} try: Result.objects.filter(**lookup)[0] except IndexError: Result.objects.create(**lookup) diff --git a/xlink/models.py b/xlink/models.py index c223238..306af1a 100644 --- a/xlink/models.py +++ b/xlink/models.py @@ -1,18 +1,19 @@ from django.db import models class Query(models.Model): search_on = models.URLField(help_text='URL to comb through looking for links') look_for = models.CharField(max_length=100, help_text='Domain name of the site you wish to search for, usually your own') active = models.BooleanField(default=True) def __unicode__(self): return self.search_on class Result(models.Model): url = models.URLField(help_text='URL found on external site') + text = models.CharField(max_length=255,help_text='Text of link with URL on external site',blank=True,null=True) found_on = models.URLField(help_text='URL of external site where link was found') timestamp = models.DateTimeField(auto_now_add=True) display = models.BooleanField(default=True) def __unicode__(self): return self.url \ No newline at end of file
justquick/django-xlink
96863cb8fcba33c75035f8d0c0ee27ece0494180
added display bool field to result, version bump
diff --git a/README.rst b/README.rst index 5d64232..21e9d35 100644 --- a/README.rst +++ b/README.rst @@ -1,41 +1,41 @@ Django Cross Link Documentation =============================== :Authors: Justin Quick <[email protected]> :Version: 0.1 :: - pip install django-xlink==0.1.0 + pip install django-xlink==0.1.1 Django Cross Link takes in particular URLs on an external site and periodically combs through those URLs searching for links back to your site. The cross site links are stored in the database for future use and display Requirements -------------- XLink requires `lxml <http://codespeak.net/lxml/>`_ for HTML parsing:: pip install lxml Setup ------ Add ``xlink`` to your ``INSTALLED_APPS`` and run ``./manage.py syncdb`` Add some queries in the admin so xlink knows which URLs to comb through and which domain (usually your own site's) you want to search for cross linking. Next run the management command ``./manage.py xlink_search`` which will take the queries and populate them with results of cross site links. I recomend putting the management command in a cronjob every hour or so to make the results appear in real time. TODO ----- Spider pages starting at one URL looking for cross site links \ No newline at end of file diff --git a/example/example.db b/example/example.db index 1d27887..de8cdc3 100644 Binary files a/example/example.db and b/example/example.db differ diff --git a/xlink/__init__.py b/xlink/__init__.py index 541f859..c12f34c 100644 --- a/xlink/__init__.py +++ b/xlink/__init__.py @@ -1 +1 @@ -__version__ = '0.1.0' \ No newline at end of file +__version__ = '0.1.1' \ No newline at end of file diff --git a/xlink/admin.py b/xlink/admin.py index 35a8f1f..55d10c9 100644 --- a/xlink/admin.py +++ b/xlink/admin.py @@ -1,16 +1,16 @@ from django.contrib import admin from models import Query, Result class QueryAdmin(admin.ModelAdmin): list_display = ('__unicode__','search_on','look_for','active') list_editable = list_display[1:] search_fields = ('search_on','look_for') class ResultAdmin(admin.ModelAdmin): - list_display = ('__unicode__','url','found_on','timestamp') - list_editable = ('url',) + list_display = ('__unicode__','found_on','timestamp','display') + list_editable = ('display',) search_fields = ('url','found_on') - list_filter = ('timestamp',) + list_filter = ('timestamp','display') admin.site.register(Query, QueryAdmin) admin.site.register(Result, ResultAdmin) diff --git a/xlink/models.py b/xlink/models.py index fae3628..c223238 100644 --- a/xlink/models.py +++ b/xlink/models.py @@ -1,17 +1,18 @@ from django.db import models class Query(models.Model): search_on = models.URLField(help_text='URL to comb through looking for links') look_for = models.CharField(max_length=100, help_text='Domain name of the site you wish to search for, usually your own') active = models.BooleanField(default=True) def __unicode__(self): return self.search_on class Result(models.Model): url = models.URLField(help_text='URL found on external site') found_on = models.URLField(help_text='URL of external site where link was found') timestamp = models.DateTimeField(auto_now_add=True) + display = models.BooleanField(default=True) def __unicode__(self): return self.url \ No newline at end of file
justquick/django-xlink
e48a3c8c0a1152acce7973eda5ae783bae45deb4
initial import
diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..5d64232 --- /dev/null +++ b/README.rst @@ -0,0 +1,41 @@ +Django Cross Link Documentation +=============================== + +:Authors: + Justin Quick <[email protected]> +:Version: 0.1 + +:: + + pip install django-xlink==0.1.0 + +Django Cross Link takes in particular URLs on an external site and periodically +combs through those URLs searching for links back to your site. The cross +site links are stored in the database for future use and display + +Requirements +-------------- + +XLink requires `lxml <http://codespeak.net/lxml/>`_ for HTML parsing:: + + pip install lxml + +Setup +------ + +Add ``xlink`` to your ``INSTALLED_APPS`` and run ``./manage.py syncdb`` + +Add some queries in the admin so xlink knows which URLs to comb through and which +domain (usually your own site's) you want to search for cross linking. + +Next run the management command ``./manage.py xlink_search`` which will take the queries +and populate them with results of cross site links. + +I recomend putting the management command in a cronjob every hour or so to make +the results appear in real time. + + +TODO +----- + +Spider pages starting at one URL looking for cross site links \ No newline at end of file diff --git a/example/__init__.py b/example/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/example/example.db b/example/example.db new file mode 100644 index 0000000..1d27887 Binary files /dev/null and b/example/example.db differ diff --git a/example/manage.py b/example/manage.py new file mode 100755 index 0000000..5e78ea9 --- /dev/null +++ b/example/manage.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +from django.core.management import execute_manager +try: + import settings # Assumed to be in the same directory. +except ImportError: + import sys + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) + sys.exit(1) + +if __name__ == "__main__": + execute_manager(settings) diff --git a/example/settings.py b/example/settings.py new file mode 100644 index 0000000..a302c24 --- /dev/null +++ b/example/settings.py @@ -0,0 +1,96 @@ +import os, sys + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) + +DEBUG = True +TEMPLATE_DEBUG = DEBUG + +ADMINS = ( + # ('Your Name', '[email protected]'), +) + +MANAGERS = ADMINS + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. + 'NAME': 'example.db', # Or path to database file if using sqlite3. + 'USER': '', # Not used with sqlite3. + 'PASSWORD': '', # Not used with sqlite3. + 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. + 'PORT': '', # Set to empty string for default. Not used with sqlite3. + } +} + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# On Unix systems, a value of None will cause Django to use the same +# timezone as the operating system. +# If running in a Windows environment this must be set to the same as your +# system time zone. +TIME_ZONE = 'America/Chicago' + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +SITE_ID = 1 + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +# If you set this to False, Django will not format dates, numbers and +# calendars according to the current locale +USE_L10N = True + +# Absolute path to the directory that holds media. +# Example: "/home/media/media.lawrence.com/" +MEDIA_ROOT = '' + +# URL that handles the media served from MEDIA_ROOT. Make sure to use a +# trailing slash if there is a path component (optional in other cases). +# Examples: "http://media.lawrence.com", "http://example.com/media/" +MEDIA_URL = '' + +# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a +# trailing slash. +# Examples: "http://foo.com/media/", "/media/". +ADMIN_MEDIA_PREFIX = '/media/' + +# Make this unique, and don't share it with anybody. +SECRET_KEY = '_mk0bmjtr&_n%p2#!%4pk285e^pr8#1+wj@dm+j8qp$k-9za8+' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', +# 'django.template.loaders.eggs.Loader', +) + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', +) + +ROOT_URLCONF = 'example.urls' + +TEMPLATE_DIRS = ( + # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. +) + +INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'django.contrib.messages', + 'django.contrib.admin', + 'xlink', +) diff --git a/example/urls.py b/example/urls.py new file mode 100644 index 0000000..9e43d34 --- /dev/null +++ b/example/urls.py @@ -0,0 +1,8 @@ +from django.conf.urls.defaults import * +from django.contrib import admin + +admin.autodiscover() + +urlpatterns = patterns('', + (r'^admin/', include(admin.site.urls)), +) diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..d92ed28 --- /dev/null +++ b/setup.py @@ -0,0 +1,19 @@ +from distutils.core import setup +from xlink import __version__ + +setup(name='django-xlink', + version=__version__, + description='Django cross link searches particular sites for links back to your site and stores them', + long_description=open('README.rst').read(), + author='Justin Quick', + author_email='[email protected]', + url='http://github.com/justquick/django-xlink', + packages=['xlink', 'xlink.management', 'xlink.management.commands'], + classifiers=['Development Status :: 4 - Beta', + 'Environment :: Web Environment', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Utilities'], + ) diff --git a/xlink/__init__.py b/xlink/__init__.py new file mode 100644 index 0000000..541f859 --- /dev/null +++ b/xlink/__init__.py @@ -0,0 +1 @@ +__version__ = '0.1.0' \ No newline at end of file diff --git a/xlink/admin.py b/xlink/admin.py new file mode 100644 index 0000000..35a8f1f --- /dev/null +++ b/xlink/admin.py @@ -0,0 +1,16 @@ +from django.contrib import admin +from models import Query, Result + +class QueryAdmin(admin.ModelAdmin): + list_display = ('__unicode__','search_on','look_for','active') + list_editable = list_display[1:] + search_fields = ('search_on','look_for') + +class ResultAdmin(admin.ModelAdmin): + list_display = ('__unicode__','url','found_on','timestamp') + list_editable = ('url',) + search_fields = ('url','found_on') + list_filter = ('timestamp',) + +admin.site.register(Query, QueryAdmin) +admin.site.register(Result, ResultAdmin) diff --git a/xlink/management/__init__.py b/xlink/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/xlink/management/commands/__init__.py b/xlink/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/xlink/management/commands/xlink_search.py b/xlink/management/commands/xlink_search.py new file mode 100644 index 0000000..8e932a8 --- /dev/null +++ b/xlink/management/commands/xlink_search.py @@ -0,0 +1,28 @@ +from django.core.management.base import BaseCommand +from django.core.exceptions import ImproperlyConfigured +try: + from lxml.html import parse +except ImportError: + raise ImproperlyConfigured('You must have lxml installed before searching') + +from xlink.models import Query, Result + +class Command(BaseCommand): + def handle(self, *args, **options): + for query in Query.objects.filter(active=True): + + html = parse(query.search_on).getroot() + html.make_links_absolute(query.search_on) + for link in html.iterlinks(): + try: + url = link[2] + domain = url.split('/')[2] + except IndexError: + continue + if domain == query.look_for: + lookup = {'url':url, 'found_on': query.search_on} + try: + Result.objects.filter(**lookup)[0] + except IndexError: + Result.objects.create(**lookup) + diff --git a/xlink/models.py b/xlink/models.py new file mode 100644 index 0000000..fae3628 --- /dev/null +++ b/xlink/models.py @@ -0,0 +1,17 @@ +from django.db import models + +class Query(models.Model): + search_on = models.URLField(help_text='URL to comb through looking for links') + look_for = models.CharField(max_length=100, help_text='Domain name of the site you wish to search for, usually your own') + active = models.BooleanField(default=True) + + def __unicode__(self): + return self.search_on + +class Result(models.Model): + url = models.URLField(help_text='URL found on external site') + found_on = models.URLField(help_text='URL of external site where link was found') + timestamp = models.DateTimeField(auto_now_add=True) + + def __unicode__(self): + return self.url \ No newline at end of file
cayblood/lilypond-files
e05f558a0fd7ff6eda71738b172c8da6e0760684
Added beginning of They All Laughed and midi for You Are the New Day
diff --git a/they_all_laughed/they_all_laughed.ly b/they_all_laughed/they_all_laughed.ly new file mode 100755 index 0000000..adc74e3 --- /dev/null +++ b/they_all_laughed/they_all_laughed.ly @@ -0,0 +1,89 @@ +\version "2.11.42" +\header { + filename = "they_all_laughed.ly" + title = "They All Laughed" + subtitle = \markup { \teeny "'Singularity' Edition (Men's Barbershop Quartet)" } + arranger = "Arranged by W. Latzgo" + composer = "Music: George Gershwin" + poet = "Lyrics: Ira Gershwin & Carl Youngblood" + meter = "Swing feel" + copyright = "Public Domain" + enteredby = "Carl Youngblood" + lastupdated = "11 Feb 2013" + style = "Hymn" + tagline = \markup { + \override #'(box-padding . 1.0) + \override #'(baseline-skip . 2.7) + \center-align { + \line { \teeny + \line { Music engraving by LilyPond 2.10.5—www.lilypond.org } + } + } + } % This sets the statement at the bottom of last page. +} +\paper { + #(set-paper-size "letter") + top-margin = 0.7\cm +} + +global = { + \key g \major + \override Score.BarNumber #'transparent = ##t + \override Staff.TimeSignature #'style = #'() % This keeps the 4/4 time as 4/4. Comment out if you want the "C" + \time 2/2 +} +tenorMusic = \relative g' { + d4 d cis cis | c c cis8 c cis4 | d r cis r | +} +leadMusic = \relative g { + b4 b ais ais | a a ais8 a ais4 | b r ais r | +} +bariMusic = \relative g { + g4 d ees ees | e e ees8 ees ees4 | g r ees r | +} +bassMusic = \relative g, { + g4 g g g | g g g8 g g4 | g g g g | +} +mainText = \lyricmode { + Ha ha ho ho | hee hee har -- dy -- har | ha __ ho __ +} +bassText = \lyricmode { + \repeat unfold 9 _ | Ha ha ho ho +} + +\score { + \new ChoirStaff << + \new Staff = tenors << + \new Voice = "tenor" { \voiceOne << \clef "G_8" \global \tenorMusic >> } + \new Voice = "lead" { \voiceTwo << \clef "G_8" \global \leadMusic >> } + >> + \new Lyrics \with { alignBelowContext = tenors } \lyricsto lead \mainText + + \new Staff = basses << + \clef bass + \new Voice = "bari" { \voiceOne << \clef bass \global \bariMusic >> } + \new Voice = "bass" { \voiceTwo << \clef bass \global \bassMusic >> } + >> + \new Lyrics \with { alignBelowContext = basses } \lyricsto bass \bassText + >> + \layout { + % The lines below help layout the page in a nice way. Don't delete or alter. + indent = 0.0\pt + first-page-number = #1 + between-system-padding = #0.1 + between-system-space = #0.1 + ragged-last-bottom = ##f + ragged-bottom = ##f + \context { + \Lyrics + \override VerticalAxisGroup #'minimum-Y-extent = #'(-1.0 . 1.0) %This helps layout. Don't change. + \override LyricText #'font-size = #-.375 % Change the number to change the font size. + } + } + \midi { + \context { + \Score + tempoWholesPerMinute = #(ly:make-moment 100 4) % Change the 85 number higher to speed up midi or lower to slow down. + } + } +} \ No newline at end of file diff --git a/you_are_the_new_day/You are the New Day Alto1.mid b/you_are_the_new_day/You are the New Day Alto1.mid new file mode 100644 index 0000000..691e223 Binary files /dev/null and b/you_are_the_new_day/You are the New Day Alto1.mid differ diff --git a/you_are_the_new_day/You are the New Day Alto2.mid b/you_are_the_new_day/You are the New Day Alto2.mid new file mode 100644 index 0000000..b1a28b3 Binary files /dev/null and b/you_are_the_new_day/You are the New Day Alto2.mid differ diff --git a/you_are_the_new_day/You are the New Day Bass1.mid b/you_are_the_new_day/You are the New Day Bass1.mid new file mode 100644 index 0000000..7bc1ee4 Binary files /dev/null and b/you_are_the_new_day/You are the New Day Bass1.mid differ diff --git a/you_are_the_new_day/You are the New Day Bass2.mid b/you_are_the_new_day/You are the New Day Bass2.mid new file mode 100644 index 0000000..f2349c6 Binary files /dev/null and b/you_are_the_new_day/You are the New Day Bass2.mid differ diff --git a/you_are_the_new_day/You are the New Day SATB.mid b/you_are_the_new_day/You are the New Day SATB.mid new file mode 100644 index 0000000..d000684 Binary files /dev/null and b/you_are_the_new_day/You are the New Day SATB.mid differ diff --git a/you_are_the_new_day/You are the New Day Soprano.mid b/you_are_the_new_day/You are the New Day Soprano.mid new file mode 100644 index 0000000..ffbff9b Binary files /dev/null and b/you_are_the_new_day/You are the New Day Soprano.mid differ diff --git a/you_are_the_new_day/You are the New Day Tenor1.mid b/you_are_the_new_day/You are the New Day Tenor1.mid new file mode 100644 index 0000000..54e2616 Binary files /dev/null and b/you_are_the_new_day/You are the New Day Tenor1.mid differ diff --git a/you_are_the_new_day/You are the New Day Tenor2.mid b/you_are_the_new_day/You are the New Day Tenor2.mid new file mode 100644 index 0000000..2f9d4d2 Binary files /dev/null and b/you_are_the_new_day/You are the New Day Tenor2.mid differ
cayblood/lilypond-files
fe0f576e704f22828409730043948cb14a02a1b6
Fixed stem direction on second voice
diff --git a/brahms_lullaby/wiegenlied.ly b/brahms_lullaby/wiegenlied.ly index 924b2ca..e11fec9 100644 --- a/brahms_lullaby/wiegenlied.ly +++ b/brahms_lullaby/wiegenlied.ly @@ -1,81 +1,79 @@ \version "2.12.3" \header { filename = "brahms wiegenlied.ly" title = "Wiegenlied (Lullaby)" instrument = "Duet for Bb clarinet" composer = "Johannes Brahms" style = "Gently" enteredby = "Carl Youngblood" lastupdated = "12 October 2012" tagline = \markup { \override #'(box-padding . 1.0) \override #'(baseline-skip . 2.7) \center-align { \line { \teeny \line { Music engraving by LilyPond 2.12.3—www.lilypond.org } } } } % This sets the statement at the bottom of last page. } \paper { indent = 0.0\pt page-limit-inter-system-space = ##t page-limit-inter-system-space-factor = 1.1 top-margin = 1\cm bottom-margin = 1\cm left-margin = 1\cm right-margin = 1\cm first-page-number = #1 between-system-space = 3.0\cm between-system-padding = #1 ragged-bottom=##t ragged-last-bottom=##t } clarinetOne = \relative c'' { \set midiInstrument = #"clarinet" - \voiceOne \tempo \markup { \italic Gently } 2 = 60 \clef treble \key f \major \time 3/2 r1 a4\mp a | \repeat volta 2 { c2~ c4 a4 a2 | c2 r a4( c) | f2 e~ e4 d4 | d2 c g4( a) | bes2 g g4( a) | bes2 r g4( bes) | e4( d) c2 e | f r f,4\mf f | f'1 d4( bes) | c1 a4( f) | bes2 c d | a4( c~) c2 f,4 f | f'1 d4( bes) | c1 a4( f) | bes4(\> c8 bes a2) g | } \alternative { { f1\! a4 a | } { f1\! r2 \bar "|." } } } clarinetTwo = \relative c' { \set midiInstrument = #"clarinet" - \voiceTwo \clef treble \key f \major \time 3/2 r1 f4\mp f | \repeat volta 2 { a2~ a4 f4 f2 | a2 r f4( a) | a2 c~ c4( bes) | bes2 a e4( f) | g2 e e4( f) | g2 r e4( g) | c( bes) a2 c | a r f4\mf f | bes2 d bes4( g) | a1 f4 f | f2 a bes | f4( a~) a2 f4 f | bes2 d bes4( g) | a1 f4 f | g2 f e | } \alternative { { f1 f4 f | } { f1 r2\! \bar "|." } } } \score { << \new Staff \transpose f c { \clarinetOne } \new Staff \transpose f c { \clarinetTwo } >> \layout { } \midi { } }
cayblood/lilypond-files
f0306ad85c13a0026855de3946afbc5ef94e3885
Added midi annotations
diff --git a/brahms_lullaby/wiegenlied.ly b/brahms_lullaby/wiegenlied.ly index 4eaec4e..924b2ca 100644 --- a/brahms_lullaby/wiegenlied.ly +++ b/brahms_lullaby/wiegenlied.ly @@ -1,76 +1,81 @@ \version "2.12.3" \header { filename = "brahms wiegenlied.ly" title = "Wiegenlied (Lullaby)" instrument = "Duet for Bb clarinet" composer = "Johannes Brahms" style = "Gently" enteredby = "Carl Youngblood" lastupdated = "12 October 2012" tagline = \markup { \override #'(box-padding . 1.0) \override #'(baseline-skip . 2.7) \center-align { \line { \teeny \line { Music engraving by LilyPond 2.12.3—www.lilypond.org } } } } % This sets the statement at the bottom of last page. } \paper { indent = 0.0\pt page-limit-inter-system-space = ##t page-limit-inter-system-space-factor = 1.1 top-margin = 1\cm bottom-margin = 1\cm left-margin = 1\cm right-margin = 1\cm first-page-number = #1 between-system-space = 3.0\cm between-system-padding = #1 ragged-bottom=##t ragged-last-bottom=##t } clarinetOne = \relative c'' { + \set midiInstrument = #"clarinet" + \voiceOne + \tempo \markup { \italic Gently } 2 = 60 \clef treble \key f \major \time 3/2 - r1^"Gently" a4\mp a | \repeat volta 2 { c2~ c4 a4 a2 | c2 r a4( c) | + r1 a4\mp a | \repeat volta 2 { c2~ c4 a4 a2 | c2 r a4( c) | f2 e~ e4 d4 | d2 c g4( a) | bes2 g g4( a) | bes2 r g4( bes) | e4( d) c2 e | f r f,4\mf f | f'1 d4( bes) | c1 a4( f) | bes2 c d | a4( c~) c2 f,4 f | f'1 d4( bes) | c1 a4( f) | bes4(\> c8 bes a2) g | } \alternative { { f1\! a4 a | } { f1\! r2 \bar "|." } } } clarinetTwo = \relative c' { + \set midiInstrument = #"clarinet" + \voiceTwo \clef treble \key f \major \time 3/2 r1 f4\mp f | \repeat volta 2 { a2~ a4 f4 f2 | a2 r f4( a) | a2 c~ c4( bes) | bes2 a e4( f) | g2 e e4( f) | g2 r e4( g) | c( bes) a2 c | a r f4\mf f | bes2 d bes4( g) | a1 f4 f | f2 a bes | f4( a~) a2 f4 f | bes2 d bes4( g) | a1 f4 f | g2 f e | } \alternative { { f1 f4 f | } { f1 r2\! \bar "|." } } } \score { << \new Staff \transpose f c { \clarinetOne } \new Staff \transpose f c { \clarinetTwo } >> \layout { } \midi { } }
cayblood/lilypond-files
e9b498092bcdd7c8999e614d67f4d29d255f2c28
Brahms lullaby - clarinet duet
diff --git a/brahms_lullaby/wiegenlied.ly b/brahms_lullaby/wiegenlied.ly new file mode 100644 index 0000000..4eaec4e --- /dev/null +++ b/brahms_lullaby/wiegenlied.ly @@ -0,0 +1,76 @@ +\version "2.12.3" +\header { + filename = "brahms wiegenlied.ly" + title = "Wiegenlied (Lullaby)" + instrument = "Duet for Bb clarinet" + composer = "Johannes Brahms" + style = "Gently" + enteredby = "Carl Youngblood" + lastupdated = "12 October 2012" + tagline = \markup { + \override #'(box-padding . 1.0) + \override #'(baseline-skip . 2.7) + \center-align { + \line { \teeny + \line { Music engraving by LilyPond 2.12.3—www.lilypond.org } + } + } + } % This sets the statement at the bottom of last page. +} +\paper { + indent = 0.0\pt + page-limit-inter-system-space = ##t + page-limit-inter-system-space-factor = 1.1 + top-margin = 1\cm + bottom-margin = 1\cm + left-margin = 1\cm + right-margin = 1\cm + first-page-number = #1 + between-system-space = 3.0\cm + between-system-padding = #1 + ragged-bottom=##t + ragged-last-bottom=##t +} + +clarinetOne = \relative c'' { + \clef treble + \key f \major + \time 3/2 + + r1^"Gently" a4\mp a | \repeat volta 2 { c2~ c4 a4 a2 | c2 r a4( c) | + f2 e~ e4 d4 | d2 c g4( a) | bes2 g g4( a) | + bes2 r g4( bes) | e4( d) c2 e | f r f,4\mf f | + f'1 d4( bes) | c1 a4( f) | bes2 c d | + a4( c~) c2 f,4 f | f'1 d4( bes) | c1 a4( f) | + bes4(\> c8 bes a2) g | } + \alternative { + { f1\! a4 a | } + { f1\! r2 \bar "|." } + } +} + +clarinetTwo = \relative c' { + \clef treble + \key f \major + \time 3/2 + + r1 f4\mp f | \repeat volta 2 { a2~ a4 f4 f2 | a2 r f4( a) | + a2 c~ c4( bes) | bes2 a e4( f) | g2 e e4( f) | + g2 r e4( g) | c( bes) a2 c | a r f4\mf f | + bes2 d bes4( g) | a1 f4 f | f2 a bes | + f4( a~) a2 f4 f | bes2 d bes4( g) | a1 f4 f | + g2 f e | } + \alternative { + { f1 f4 f | } + { f1 r2\! \bar "|." } + } +} + +\score { + << + \new Staff \transpose f c { \clarinetOne } + \new Staff \transpose f c { \clarinetTwo } + >> + \layout { } + \midi { } +}
cayblood/lilypond-files
45d0d022e2fb9a71154cdf8b97daeb8978040a75
Fixed Norwegian capitalization
diff --git a/the_spirit_of_god/guds_and_som_en_ild.ly b/the_spirit_of_god/guds_and_som_en_ild.ly index 1b1c299..a058b6a 100644 --- a/the_spirit_of_god/guds_and_som_en_ild.ly +++ b/the_spirit_of_god/guds_and_som_en_ild.ly @@ -1,489 +1,489 @@ \version "2.12.3" \header { filename = "guds_and_som_en_ild.ly" - title = "Guds Ånd som en Ild" + title = "Guds ånd som en ild" subtitle = \markup { \teeny "(Men's Choir)" } arranger = "Music: Anonymous" meter = "Words: William Wines Phelps (1792-1872)" % copyright = "© 2003 Michael Bearden" enteredby = "Carl Youngblood" lastupdated = "25 March 2010" style = "Hymn" tagline = \markup { \override #'(box-padding . 1.0) \override #'(baseline-skip . 2.7) \center-align { \line { \teeny \line { Music engraving by LilyPond 2.12.3—www.lilypond.org } } } } % This sets the statement at the bottom of last page. } \paper { indent = 0.0\pt page-limit-inter-system-space = ##t page-limit-inter-system-space-factor = 1.1 top-margin = 1\cm bottom-margin = 1\cm left-margin = 1\cm right-margin = 1\cm first-page-number = #1 between-system-space = 3.0\cm between-system-padding = #1 ragged-bottom=##t ragged-last-bottom=##t } global = { \key bes \major \time 4/4 } tenoronenotes = \relative c { \clef "G_8" \partial 4 r4 | r1 | r | r2 r4 f4( | bes4. c8 d c bes a) | g2 g4 bes | c4. d8 ees( d c bes) | c1 c2. f,4 \bar "||" \mark \default \break % A bes2 c4 c | d2 c4 bes | bes2 a4 g | f4.( g8) f4 g | bes( d) d f | f2 ees4 ees | f( g) f f | f2. d4 d2 f4 f | f2 f4 d | g2 f4 ees | d4.( ees8) d4 c | bes( c) d f | f( d) ees ees | d( c) bes a | bes2. d4 | d2 bes4 d | d2 bes4 d | d( f) f e | f2 f4 ees? | d( f) f f | ees2 f4 f | g( f) f f | f2. f4 | f2 f4 f | ees2 ees4 d | c4.( d8) c4 c | c( a) bes ees | d4.( c8) d( c) bes( a) | bes4( ees) d ees | d2 c4 ees | d2. f,4 | \mark \default \break % B bes4. c8 d( c) bes( a) | g2. bes4 | c4. d8 ees( d c bes) | c1 | d2. g,4 \bar "||" \mark \default \break \key c \major % C c2 d4 d | e2 d4 c | c2 b4 a | g4.( a8) g4 g | e( g) c e | d( g,) a d | e( f) f f | e2. g,4 | c2 b4 b | c2 d4 e | a,( c) f d | c4.( d16 e16) d2 | e,4( g) c e | d( g,) a f' | e( d) c b | c2 c \bar "||" \mark \default \break % D c1 | b | c | d | e | f2 f4 f | d4.( e8) f4 c | e2 e | c4.( b8) c( d) e( f) | g4( e) f f | e2 d4 f | e2. g,4 \bar "||" \mark \default \break % E c2 d4 d | e2 f4 e | f2 f4 f | e4.( f8 ) e4 r | r2 e( | d c4) f | e( d) d d \bar "||" \key des \major ees2 r4 ees | f2 aes4 aes | aes2 ges4 f | des2 ges | ees ees4 ees | f2 f | ees des | aes4( des) bes c | des2. des4 \bar "||" \mark \default \break % F \key d \major d1 | cis | d | e | d2 e4 fis | b,2 cis4 d | g2 fis4. e8 | e2. e4 | fis1 | g2 g4 g | e4.( fis8) g4 d | e( d) d e | fis2. fis4 | d( g) fis e | fis2 e4 g | fis2. fis4 | fis1 | e2 g | fis2. a,4 | d e fis a | a1 ~ | a1 ~ | a1 ~ | a2. \bar "|." } tenoronewords = \lyricmode { Ah __ sian -- na, Ho -- sian -- na, Ho __ sian -- na! Guds ånd som en ild nå be -- gyn -- ner å lu -- e, vi sis -- te dags ver -- ket på jor -- den nå ser. Ja, fe -- dre -- nes håp vi be -- gyn -- ner å sku -- e, og det som var ut -- talt, på jor -- den skal skje. Vi syng -- er en lov -- sang med him -- me -- lens hæ -- re: Ho -- sian -- na, Ho -- sian -- na for Gud og hans Sønn! For dem __ i det høy -- e til -- kom -- mer all æ -- re fra nå __ og for e -- vig! A -- men, ja, a -- men. Ho -- sian -- na til __ vår __ Gud Ho -- sian -- na, Ho __ sian -- na! Nå Herr -- en har ut -- rakt sin hånd o -- ver jor -- den og sam -- ler hver hel -- lig tross mørk -- het -- ens makt. Han at -- ter har gjen -- gitt sitt pres -- te -- døms or -- den, det -- te for -- kyn -- ner hans e -- vi -- ge pakt. Vi syng lov ah ah dem høy -- e til -- kom -- mer all æ -- re nå __ og __ for e -- vig! A -- men, ja, a -- men. Vi ik -- ler oss al -- le en ån -- de -- lig styr -- ke Ah __ kan kom -- me her ned, Vel -- sig -- net er dag -- en når lø -- ven lam -- met de van -- dre sam -- men fred og i ro. Vi syng lov ah ah sian -- na, Ho -- sian -- na, for Gud og __ hans Sønn! __ For dem __ høy -- e til -- kom -- mer all æ -- re fra nå __ for e -- vig! A -- men, ja, a -- men. A -- men, ja, a -- men. Ho -- sian -- na til vår Gud! __ } tenortwonotes = \relative c { \clef "G_8" \partial 4 r4 | r1 | r | r2 r4 f4( | bes4. c8 d c bes a) | g2 g4 bes | c4. d8 ees( d c bes) | bes1 | a2. f4 \bar "||" \mark \default \break % A bes2 c4 c | d2 c4 bes | bes2 a4 g | f4.( g8) f4 ees | d( f) bes d | c( f,) g ees' | d( c) bes a | bes2. f4 bes2 c4 c | d2 c4 bes | bes2 a4 g | f4.( g8) f4 ees | d( f) bes d | c( bes) bes ees | d( c) bes a | bes2. f4 | f2 d4 f | f2 d4 f | bes( d) c bes | a( g) f8( g) a( f) | bes2 c4 d | g,2 a4 bes | ees2 d4. c8 | c2. c4 | d( bes) c d | g,2 ees'4 bes | a4.( bes8) a4 bes | a( g) f8( g) a( f) | bes4.( c8) bes4 bes | g4( c) bes c | bes2 a4 a | bes2. f4 | \mark \default \break % B bes4. c8 d( c) bes( a) | g2. bes4 | c4. d8 ees( d c bes) | c1 | d2. g,4 \bar "||" \mark \default \break \key c \major % C c2 d4 d | e2 d4 c | c2 b4 a | g4.( a8) g4 f | e( g) c e | d( g,) a d | e( d) c b | c2. g4 | c2 b4 b | c2 d4 d | a( c) c d | c4.( d16 e16) d2 | e,4( g) c e | d( g,) a c | c( g) g g | g2 c \bar "||" \mark \default \break % D g1 | g | a | b | e4( c) d e | d2 f4 e | d4.( e8) f4 c | e2 d | c4.( b8) c( d) e( f) | g4( e) c d | c2 d4 f | e2. g,4 \bar "||" \mark \default \break % E c2 d4 d | e2 d4 c | c2 f4 f | e4.( f8 ) e4 r | r2 c( | c a4) f' | c( d) c b \bar "||" \key des \major c2 r4 c | des2 ees4 ees | ees4( des) c des | bes2 ees | des c4 ees | des2 des | ees des | aes2 aes4 aes | f2. aes4 \bar "||" \mark \default \break % F \key d \major a2 fis4 a | a2 fis4 a | d( fis) e d | cis( b) a8( b) cis( a) | d2 cis4 d | b2 cis4 b | d2 e4 d8( e8) | d4 cis8 b cis4 e | e( d) d2 | e2 g4 fis | d2 d4 d | e( d) d e | fis2. fis4 | d( g) fis e | fis2 e4 g | fis2. fis4 | fis1 | e2 g | fis2. a,4 | d cis d fis | fis2. r4 | e2( g) | fis1 ~ | fis2. \bar "|." } tenortwowords = \lyricmode { Ah __ sian -- na, Ho -- sian -- na, Ho __ sian -- na! Guds ånd som en ild nå be -- gyn -- ner å lu -- e, vi sis -- te dags ver -- ket på jor -- den nå ser. Ja, fe -- dre -- nes håp vi be -- gyn -- ner å sku -- e, og det som var ut -- talt, på jor -- den skal skje. Vi syng -- er en lov -- sang med him -- me -- lens hæ -- re: Ho -- sian -- na, Ho -- sian -- na for Gud og hans Sønn! For dem __ i det høy -- e til -- kom -- mer all æ -- re fra nå __ og for e -- vig! A -- men, ja, a -- men. Ho -- sian -- na til __ vår __ Gud Ho -- sian -- na, Ho __ sian -- na! Nå Herr -- en har ut -- rakt sin hånd o -- ver jor -- den og sam -- ler hver hel -- lig tross mørk -- het -- ens makt. Han at -- ter har gjen -- gitt sitt pres -- te -- døms or -- den, det -- te for -- kyn -- ner hans e -- vi -- ge pakt. Vi syng lov ah ah dem i det høy -- e til -- kom -- mer all æ -- re nå __ og __ for e -- vig! A -- men, ja, a -- men. Vi ik -- ler oss al -- le en ån -- de -- lig styr -- ke Ah __ kan kom -- me her ned, Vel -- sig -- net er dag -- en når lø -- ven lam -- met de van -- dre sam -- men fred og i ro. Vi syng -- er en lov -- sang med him -- me -- lens hæ -- re: Ho -- sian -- na, Ho -- sian -- na, for Gud og hans Gud og hans Sønn! For dem __ i høy -- e til -- kom -- mer all æ -- re fra nå __ for e -- vig! A -- men, ja, a -- men. A -- men, ja, a -- men. Ho -- sian -- na til vår Gud! A -- men! __ } barionenotes = \relative c' { \clef "G_8" \partial 4 r4 | r2 r4 a | c bes2. ~ | bes1 | bes2 f' | f ees4 d | ees2 ees4 ees | f1 | f2. f,4 \bar "||" \mark \default \break % A ees2 a4 a | bes2 a4 bes | bes2 f4 bes | bes2 bes4 bes8( c) | f,2 bes4 bes | a( bes) bes c | bes( ees) d c | d2. bes4 | bes2 c4 a | bes2 a4 bes | bes2 bes4 bes | bes2 bes4 bes8( c) | f,2 bes4 bes | bes2 bes4 c | bes( ees) d c | d2. bes4 | bes2 f4 bes | bes2 f4 bes | bes( d) c c | c( a) bes a | bes2 a4 bes | bes2 c4 bes | bes( c) bes c | a2. a4 | bes2 a4 bes | bes2 a4 bes | c2 c4 bes | f2 g4 a | bes2 f4 d | ees2 f4 g | f2 f4 f | f2. f4 \bar "||" \mark \default \break % B bes a g bes | ees4. f8 g( f) ees( d) | ees2 aes, | f'1 | g \bar "||" \mark \default \break \key c \major % C r | r | r2 f,8( g) a( b) | c2 b4 b | c( d) e g | g( e) f f | g( a) g g | g2. g,4 | g2 g4 g | b2 b4 c | f,( a) f8( g) a( b) | c2 b4 f | e( g) g g | g( e) f a | g( f) e d | e2 r4 g \bar "||" \mark \default \break % D g2 e4 g | g2 e4 g | c4( e) d c | b2 d4 d | c1 | c | c2 d4 c | b( a) gis8( a) b( gis) | a4.( g8) a( b) c( d) | e4( c) a d | c2 b4 b | c2. g4 \bar "||" \mark \default \break % E c( b) b b | c2 a4 a | a2 b4 a | g4.( a8) g4 f | e( g) c e | d( g,) a f' | e( d) c b \bar "||" \key des \major c2 r4 aes | aes2 c4 c | des2 aes4 aes | aes ges2 ges4 | aes2 aes4 aes | aes2 aes | des4( c8 bes) bes2 | aes4( bes) aes ges | aes2. f4 \bar "||" \mark \default \break % F \key d \major fis1 | e | g | a2 a | fis2 a4 a | a( g) g2 | b b | a2. e'4 | fis( d) e fis | b,2 g'4 fis | e4.( fis8) e4 d | cis( b) a8( b) cis( a) | d4.( e8) fis( e) d( cis) | b4( e) d e | d2 cis4 cis | d2. d4 | d1 | cis2 e | e4( d2) a4 | b a b cis | d2. r4 | c2( e) | d1 ~ | d2. \bar "|." } barionewords = \lyricmode { Ho -- sian -- na, __ Ah Ho -- sian -- na, Ho -- sian -- na, Ho __ sian -- na! Guds ånd som en ild nå be -- gyn -- ner å lu -- e, vi sis -- te dags ver -- ket på jor -- den nå ser. Ja, fe -- dre -- nes håp vi be -- gyn -- ner å sku -- e, og det som var ut -- talt, på jor -- den skal skje. Vi syng -- er en lov -- sang med him -- me -- lens hæ -- re: Ho -- sian -- na, Ho -- sian -- na for Gud og hans Sønn! For dem __ i det høy -- e til -- kom -- mer all æ -- re fra nå __ og for e -- vig! A -- men, ja, a -- men. Ho -- sian -- na til Ho -- sian -- na til __ vår __ Gud, Ho __ sian -- na! __ o -- ver jor -- den og sam -- ler hver hel -- lig tross mørk -- het -- ens makt. Han at -- ter har gjen -- gitt sitt pres -- te -- døms or -- den, og det -- te for -- kyn -- ner hans e -- vi -- ge pakt. Vi syng -- er en lov -- sang med him -- me -- lens hæ -- re for dem til -- kom -- mer all æ -- re fra nå __ og __ for e -- vig! A -- men, ja, a -- men. Vi ik -- ler oss al -- le en ån -- de -- lig styr -- ke så him -- me -- lens ri -- ke kan kom -- me her ned, Vel -- sig -- net er dag -- en når lø -- ven og lam -- met de van -- dre sam -- men fred og i ro. Vi syng lov ah ah Ho -- sian -- na, Ho -- sian -- na, Gud og Sønn! For dem __ i det høy -- e til -- kom -- mer all æ -- re fra nå __ og __ for e -- vig! A -- men, ja, a -- men. A -- men, ja, a -- men. Ho -- sian -- na til vår Gud! A -- men! __ } baritwonotes = \relative c { \clef "G_8" f4 | bes f2. ~ | f1 ~ | f1 | f2 bes | bes bes4 bes | aes2 aes4 aes | f1 | f2. f4 \bar "||" \mark \default \break % A f2 f4 f | f2 a4 bes | g2 f4 ees | f4.( ees8) d4 f8( ees) | d4( f) f bes | a( f) g c | bes( c) bes a | bes2. f4 | f2 a4 a | bes2 a4 bes | bes2 bes4 bes | bes2 f4 f8( ees) | d4( f) f bes | bes( a) g g | f( g) f f | f2. f4 | f2 d4 f | f2 d4 f | bes2 a4 bes | a( g) f8( g) f4 | f( bes) a bes | g2 a4 bes | bes( a) bes c | a2. a4 | bes2 a4 g | g2 a4 bes | f2 f4 e | f2 f4 ees? | f2 f4 d | ees2 f4 ees | f2 f4 f | f2. f4 | \mark \default \break % B f f2 f4 | g2. g4 | aes2 aes | a!1 | b \bar "||" \mark \default \break \key c \major % C r | r | r2 f8( g) a( b) | c2 b4 b | c( d) e g | g( e) f f | g( a) g g | g2. f,4 | g2 g4 g | e( a) g g | f( a) f8( g) a( b) | c2 b4 f | e( d) g g | g( e) c d | e( d) c d | e2 f \bar "||" \mark \default \break % D g2 e4 g | g2 e4 g | c4( e) d c | b2 d4 d | g,1 | a | a2 c4 c | a2 gis8( a) b( gis) | f4.( g8) g( b) g( d') | e4( c) a a | g2 g4 g | g2. g4 \bar "||" \mark \default \break % E c( b) b b | c2 a4 a | a2 b4 a | g4.( a8) g4 f | e( g) g g | a( g) f f | g2 g4 b \bar "||" \key des \major aes2 r4 aes | aes2 c4 c | des2 aes4 aes | aes ges2 ges4 | aes2 aes4 aes | aes2 aes | aes ges | ees4( ges) ges ges | aes2. f4 \bar "||" \mark \default \break % F \key d \major fis1 | e | g | a2 a | fis2 a4 a | a( g) g2 | b b | a2. a4 | a1 | b | b2 b | a4( g) a g | a2 a4 a | b2 a4 b | a2 a4 a | a2. a4 | b1 | b2 b | a2. a4 | a a g a | a1 ~ | a ~ | a ~ | a2. \bar "|." } baritwowords = \lyricmode { Ho -- sian -- na, __ Ah Ho -- sian -- na, Ho -- sian -- na, Ho __ sian -- na! Guds ånd som en ild nå be -- gyn -- ner å lu -- e, vi sis -- te dags ver -- ket på jor -- den nå ser. Ja, fe -- dre -- nes håp vi be -- gyn -- ner å sku -- e, og det som var ut -- talt, på jor -- den skal skje. Vi syng -- er en lov -- sang med him -- me -- lens hæ -- re: Ho -- sian -- na, Ho -- sian -- na for Gud og hans Sønn! For dem __ i det høy -- e til -- kom -- mer all æ -- re fra nå __ og for e -- vig! A -- men, ja, a -- men. Ho -- sian -- na vår Gud vår Gud Ho __ sian -- na! __ o -- ver jor -- den og sam -- ler hver hel -- lig tross mørk -- het -- ens makt. Han at -- ter har gjen -- gitt sitt pres -- te -- døms or -- den, og det -- te for -- kyn -- ner hans e -- vi -- ge pakt. Vi syng -- er en lov -- sang med him -- me -- lens hæ -- re for dem til -- kom -- mer all æ -- re fra nå __ og __ for e -- vig! A -- men, ja, a -- men. Vi ik -- ler oss al -- le en ån -- de -- lig styr -- ke så him -- me -- lens ri -- ke kan kom -- me her ned, Vel -- sig -- net er dag -- en når lø -- ven og lam -- met de van -- dre sam -- men fred og i ro. Vi syng lov ah ah Ho -- sian -- na, Ho -- sian -- na, Gud og Sønn! For dem til -- kom -- mer æ -- re fra nå __ og __ for e -- vig! A -- men, ja, a -- men. A -- men, ja, a -- men. Ho -- sian -- na til vår Gud! __ } bassonenotes = \relative c { \clef bass \partial 4 r4 | r1 | r2. d4 | c bes f' f, | bes2. bes4 | ees,2 ees4 ees | aes2 aes4 aes | f1 | f2. f'4 \bar "||" \mark \default \break % A d2 f4 f | bes2 f4 g | ees2 ees4 ees | bes2 bes4 f | d'( c) bes bes | f'( d) ees c | d( ees) f f, | bes2. bes4 | bes2 f'4 f | bes2 f4 g | ees2 ees4 ees | bes2 bes4 ees | d( c) bes a | g( f) ees g | f2 f4 f | bes2. bes4 | bes2 bes4 bes | bes2 bes4 bes | bes2 c4 c | f( ees) d c | bes( d) c bes | ees2 c4 bes | g( a) bes4. f'8 | f2. f4 | bes,4( d) f bes | ees,2 c4 bes | f'2 f4 c | f( ees) d c | bes2 bes4 bes | ees( c) d ees | f( f,) f f | bes2. f'4 | \mark \default \break % B bes, bes2 bes4 | ees2. ees4 | aes,4. aes8 aes2 | g1 | g2. f'4 \bar "||" \mark \default \break \key c \major % C e2 g4 g | c2 g4 a | f2 f4 f | c2 d | r1 | r | r | r2. f4 | e2 d4 d | a2 g | f d4 a' | g'2 g4 f | e( d) c c | b( g) f f | g2 g4 g | c2 f \bar "||" \mark \default \break % D e1 | d | f | g | c, | c | c2 d4 c | b2 e | f e4 d | c2 f,4 f | g2 g4 g | c2. g'4 \bar "||" \mark \default \break % E c( b) b b | a( g) f e | d( e8 f) g4 g | c,2 c4 b | a2 g4 g | f2 f | g g4 g \bar "||" \key des \major aes2 r4 aes | des2 ees4 ees | f2 ees4 des | des2 c4 bes | aes4.( bes8) aes4 ges | f( aes) des f | ees( aes,) bes ges' | f( ees) des c | des2. aes4 \bar "||" \mark \default \break % F \key d \major a1 | a | b | cis2 cis | d2 d4 d | g,2 g4 fis | e( fis) g b | a2. a4 | d1 | d | b'2 b | a4( g) fis e | d2 d4 d | g( e) fis g | a( a,) a a | d2. d4 | g1 | g2 e | d2. a'4 | g fis e a | b2. r4 | a2( c) | d,1 ~ | d2. \bar "|." } basswords = \lyricmode { Ho -- sian -- na til vår Gud Ho -- sian -- na, Ho -- sian -- na, Ho -- sian -- na! Guds ånd som en ild nå be -- gyn -- ner å lu -- e, vi sis -- te dags ver -- ket på jor -- den nå ser. Ja, fe -- dre -- nes håp vi be -- gyn -- ner å sku -- e, og det som var ut -- talt, på jor -- den skal skje. Vi syng -- er en lov -- sang med him -- me -- lens hæ -- re: Ho -- sian -- na, Ho -- sian -- na for Gud og hans Sønn! For dem __ i det høy -- e til -- kom -- mer all æ -- re fra nå __ og for e -- vig! A -- men, ja, a -- men. Ho -- sian -- na vår Gud Ho __ sian -- na! Ho __ sian -- na! Nå Herr -- en har ut -- rakt sin hånd o -- ver jor -- den Han at -- ter har gjen -- gitt pres -- te -- døms or -- den, og det -- te for -- kyn -- ner hans e -- vi -- ge pakt. Vi syng lov ah ah dem til -- kom -- mer all æ -- re nå __ og __ for e -- vig! A -- men, ja, a -- men. Vi ik -- ler oss al -- le en ån -- de -- lig styr -- ke så him -- me -- lens ri -- ke kom -- me her ned, Vel -- sig -- net er dag -- en når lø -- ven og lam -- met de van -- dre skal sam -- men i fred og i ro. Vi syng lov ah ah Ho -- sian -- na, Ho -- sian -- na, for Gud og hans Sønn! For dem til -- kom -- mer æ -- re fra nå __ og __ for e -- vig! A -- men, ja, a -- men. A -- men, ja, a -- men. Ho -- sian -- na til vår Gud! A -- men! __ } basstwonotes = \relative c { \clef bass \partial 4 r4 | r1 | r2. d4 | c bes f' f, | bes2. bes4 | ees,2 ees4 ees | aes2 aes4 aes | f1 | f2. f'4 \bar "||" \mark \default \break % A d2 f4 f | bes2 f4 g | ees2 ees4 ees | bes2 bes4 f | d'( c) bes bes | f'( d) ees c | d( ees) f f, | bes2. bes4 | bes2 f'4 f | bes2 f4 g | ees2 ees4 ees | bes2 bes4 ees | d( c) bes a | g( f) ees g | f2 f4 f | bes2. bes4 | bes2 bes4 bes | bes2 bes4 bes | bes2 c4 c | f( ees) d c | bes( d) c bes | ees,2 c'4 bes | g( a) bes4. f'8 | f2. f4 | bes,4( d) f bes | ees,2 c4 bes | f'2 f4 c | f( ees) d c | bes2 bes4 bes | ees( c) d ees | f( f,) f f | bes2. f'4 | \mark \default \break % B bes, bes2 bes4 | ees,2. ees4 | aes4. aes8 aes2 | g1 | g2. f'4 \bar "||" \mark \default \break \key c \major % C e2 g4 g | c2 g4 a | f2 f4 f | c2 d | r1 | r | r | r2. f4 | e2 d4 d | a2 g | f d4 a' | g2 g4 g | e'( d) c c | b( g) f f | g2 g4 g | c2 a \bar "||" \mark \default \break % D g1 | g | a | b | c | c | c2 d4 c | b2 e | f e4 d | c2 f,4 f | g2 g4 g | c2. g'4 \bar "||" \mark \default \break % E c( b) b b | a( g) f e | d( e8 f) g4 g | c,2 c4 b | a2 g4 g | f2 f | g g4 g \bar "||" \key des \major aes2 r4 aes | des2 ees4 ees | f2 ees4 des | des2 c4 bes | aes4.( bes8) aes4 ges | f( aes) des f | ees( aes,) bes ges' | f( ees) des c | des2. aes4 \bar "||" \mark \default \break % F \key d \major a1 | a | b | cis2 cis | d2 d4 d | g,2 g4 fis | e( fis) g b | a2. a4 | a1 | a | d2 e | a4( g) fis e | d2 d4 d | g( e) fis g | a( a,) a a | d2. d4 | g1 | g2 e | d2. a'4 | g fis e d | g,2. r4 | f1 | d1 ~ | d2. \bar "|." } \score{ \context ChoirStaff << \context Staff = tenorone << \override Staff.VerticalAxisGroup #'minimum-Y-extent = #'(-4.3 . 4.3) \context Voice = tenone { \set midiInstrument = #"Choir Aahs" << \global \tenoronenotes >> } \lyricsto "tenone" \new Lyrics \tenoronewords >> \context Staff = tenortwo << \override Staff.VerticalAxisGroup #'minimum-Y-extent = #'(-4.3 . 4.3) \context Voice = tentwo { \set midiInstrument = #"Choir Aahs" << \global \tenortwonotes >> } \lyricsto "tentwo" \new Lyrics \tenortwowords >> \context Staff = barione << \override Staff.VerticalAxisGroup #'minimum-Y-extent = #'(-4.3 . 4.3) \context Voice = barone { \set midiInstrument = #"Choir Aahs" << \global \barionenotes >> } \lyricsto "barone" \new Lyrics \barionewords >> \context Staff = baritwo << \override Staff.VerticalAxisGroup #'minimum-Y-extent = #'(-4.3 . 4.3) \context Voice = bartwo { \set midiInstrument = #"Choir Aahs" << \global \baritwonotes >> } \lyricsto "bartwo" \new Lyrics \baritwowords >> \context Staff = bassone << \override Staff.VerticalAxisGroup #'minimum-Y-extent = #'(-4.3 . 4.3) \context Voice = basone { \set midiInstrument = #"Choir Aahs" << \global \bassonenotes >> } \lyricsto "basone" \new Lyrics \basswords >> \context Staff = basstwo << \override Staff.VerticalAxisGroup #'minimum-Y-extent = #'(-4.3 . 4.3) \context Voice = bastwo { \set midiInstrument = #"Choir Aahs" << \global \basstwonotes >> } \lyricsto "bastwo" \new Lyrics \basswords >> >> \layout { \context { \Lyrics % This helps layout. Don't change. \override VerticalAxisGroup #'minimum-Y-extent = #'(1.0 . 1.0) % Change the number to change the font size. \override LyricText #'font-size = #-1.0 } } \midi { \context { \Staff \remove "Staff_performer" } \context { \Voice \consists "Staff_performer" } \context { \Score tempoWholesPerMinute = #(ly:make-moment 58 2) } } -} \ No newline at end of file +}
cayblood/lilypond-files
d7e180ca67c3162aad4b88bde224490adcb1f954
Finished first draft
diff --git a/go_the_distance/go_the_distance.ly b/go_the_distance/go_the_distance.ly index e83a0d7..ad49631 100644 --- a/go_the_distance/go_the_distance.ly +++ b/go_the_distance/go_the_distance.ly @@ -1,225 +1,366 @@ \version "2.13.52" melody = \relative c'' { \clef treble \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \autoBeamOn \partial 4 s4 | s1 | s | s | s | s | s | s | s | s | % 1-10 r2 r4 r8 a,16 e' \bar "||" | fis4 e cis r8 a16 e' | fis4 e cis r8 a16 e' | fis4 gis a8 e cis a | cis4. d16 cis b4 r8 a16 e' | fis4 e cis r8 a'16 gis | fis4 e cis r8 a16 e' | fis4 gis a8 fis a b | \time 6/4 cis d16 cis~ cis8 d16 b~ b2 r4 r8 cis16 d | \time 4/4 e4 a, b r | cis8 b16 cis~ cis8 d16 cis~ cis b8. r8 cis16 d | e4 a, b r | cis16 b8 cis16~ cis8 d b4 r8 cis16 d | e4 gis, fis r8 a16 b | \time 2/4 cis4 e,8( d) | \time 4/4 d2 r4 r8 d16 e | fis4 e cis16 e a8 r8 b | \time 2/4 cis4 d | \time 4/4 b2.~ b8 a | a1 | \time 2/4 r2 | \time 4/4 r1 | \time 2/4 r2 | \bar "||" \key c \major \time 6/4 r1. | r1. | \time 4/4 r1 | \time 2/4 r2 | \time 4/4 r1 | r2 r4 r8 e'16 f | g4 c, d2 | + e8 d16 e~ e8 f16 e~ e d8. r8 e16 f | + g4 c, d2 | + e16 d8 e16~ e8 f8 d4 r8 e16 f | + g4 b, a r8 c16 d | + \time 2/4 + e4 g, | + \time 4/4 + f2 r4 f8 g | + a4 g e16 g c8 r e | + e4. f8 d4. c8 | + c1 | r | r | + \time 2/4 + r4 r8 e16 f | % I will + \time 4/4 + g4 b, d2 | % beat the odds. + e8 d16 e~ e8 f16 e~ e d8. r8 e16 f | % I can go the distance. I will + g4 c, d2 | % face the world + e8 d e f d4 r8 e16 f | % fearless, proud and strong. I will + g4 c,8 d~ d2 | % please the gods. + e8 f16 e~ e8. d16 d8 c~ c c16 c | % I can go the distance. Till I + a4 b c8 a c f | % find my hero's welcome + e4 r f r | % right where + g r g r | % I be- + g1~ | g~ | g~ | g | r | r \bar "|." % long. } text = \lyricmode { I have of -- ten dreamed of a far off place where a great warm wel -- come will be wait -- ing for me. Where the crowds will cheer when they see my face, and a voice keeps say -- ing this is where I'm meant __ to be. __ I will find my way. I can go __ the dis -- tance. I'll be there some -- day if I can __ be strong. I know ev -- 'ry mile will be worth my __ while. I would go most an -- y -- where to feel like I __ be -- long. I am on my way. + I can go __ the dis -- tance. + I don't care how far, + some -- how I'll __ be strong. + I know ev -- 'ry mile will be + worth my while. I would + go most an -- y -- where to find + where I be -- long. I will + beat the odds. + I can go the dis -- tance. I will + face the world, __ + fear -- less, proud and strong. I will + please the gods. __ + I can go __ the dis -- tance. __ Till I + find my he -- ro's wel -- come + right where I be -- long. __ } upper = \relative c'' { \clef treble \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \partial 4 r8\mp a,16( e' | <fis d a>4) <e b gis> <cis a>2 | e''16(^\markup { \italic lightly } e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e(\> e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b)\! | a8(_\markup { \italic sub. \dynamic mp } a, e' a, a' a, e' a,) | a'( a, e' a, a' a, e') a,,16 e' \bar "||" | <fis d a>4 <e b gis> <cis a>4. a16 e' | % often dreams of a <fis d a>4 <e b gis> <cis a>4. a16 e' | % far off place where a <fis d a>4 <e b gis> << { a8 e cis a } \\ { <cis a>4 gis } >> | % great warm welcome will be << { cis4. d16 cis b4. a16 e' } \\ { fis,2 a4 gis } >> | % waiting for me. Where the << { fis'4 e cis4. a'16 gis } \\ { d8( a) b( gis) b(fis a4) } >> | % crowds will cheer when they << { fis'4 e cis4. a16 e' } \\ { d8( a) b( gis) b( fis a4) } >> | % see my face and a << { fis'4 <gis eis> <a fis cis a>8\< fis a b\! } \\ { d,8( a) cis( b) } >> | % voice keeps saying this is \time 6/4 << { cis'8 d16 cis~ cis8 d16 b~ b2~ b4. cis16 d } \\ % where I'm meant to be. I will { <fis, cis>2 <a e!>4( b,) <gis' e>2 } >> | \time 4/4 <e' a,>4 <a, e> <b fis>2 | % find my way << { cis8 b16 cis~ cis8 d16 cis~ cis b8.~ b8 cis16 d } \\ % I can go the distance. I'll be { <a e>2 <gis e> } >> | <e' a,>4 <a, e> <b fis>2 | % there some day << { cis16 b8 cis16~ cis8 d b4. cis16 d } \\ { <a e>2 <gis e> } >> | % if I can be strong. I know << { <e' a, e>4 gis, fis4. a16 b } \\ { s2 <e, a,>2 } >> | % ev'ry mile will be \time 2/4 <cis' a e>4 << { e,8 d } \\ { a4 } >> | % worth my \time 4/4 % while. I would << { d2 s } \\ { s2 r4 r8 d16 e } \\ { \set followVoice = ##t - r8 + \context Voice = "new voice" { \voiceFour r8 } \change Staff = "lower" d,^\( a' d, \change Staff = "upper" d' a a'4\) } >> | <fis d a>4 <e b gis> cis16~ <e cis>~ <a e cis>8~ <a e cis> b | % go most anywhere to \time 2/4 << { cis4 d } \\ { <fis, cis>2 } >> | % feel like \time 4/4 % I be << { b2.~ b8 a | s1 } \\ { <a e b>4_\markup { \italic "poco rall." } <a e b>4 <gis e b>2\> | \slurUp a'16(\! % long ^\markup { \italic lightly } _\markup { \italic "a tempo" } \mp a, e' a, a' a, e' a, a' a, e' a, a' a, e' a,) \slurNeutral } >> | \time 2/4 a'( a, e' a, a' a, e' a,) | \time 4/4 a'( a, e' a, a' a, e' a, a' a, e' a, a' a, e' a,) | \time 2/4 a'(\> a, e' a,\!) r8 c,16\mf g' | \bar "||" \time 6/4 \key c \major << { <a f>4 <g d b> <e c>2 r4 r8 c16 g' } \\ { c,8( a) b( g) r g( c d f e d c) } >> | << { <a' f>4 <g d b> } \\ { c,8( a) b( g) } >> << { r g'( c d f e d c) } \\ { <e, c>2 r4 r8 c16 g' } >> | \time 4/4 << { <f a>4\< <gis b> <c a e c>8 a <c a e> d | \time 2/4 <e c a e>4.\!\f <f f,>8 } \\ { c,4 e8( d) s2 | \time 2/4 s2 } >> | \time 4/4 << { r8 g'( c b) s2 } \\ { <d, c g d>2 <b' g d b>8( g d g,) } >> | << { c16( a) b-. c-. d4-> e16( c) d-. e-. f8-> e16 f } \\ { <f, c>4-> <g d>-> <c g>-> <b g f>-> } >> | % I am <g' c, g>4 <c, g c,> << { d2 } \\ { <a d,>4 <a d,> } >> | % on my way + << { e'8 d16 e~ e8 f16 e~ e d8.~ d8 e16 f } \\ % I can go the distance. I don't + { <c g>4 <c g> <b g> <b g> } >> | + <g' c, g>4 <c, g c,> << { d2 } \\ { <a d,>4 <a d,> } >> | % care how far + << { e'16 d8 e16~ e8 f d4. e16 f } \\ { <c g>4 <c g> <b g> <b g> } >> | % somehow I'll be strong. I know + <g' c, g>4 <b, g b,> << { <a f>4. c16 d } \\ { a,8( c f4) } >> | % ev'ry mile will be + \time 2/4 % worth my + <e' c g e>4 <g, e c> | + \time 4/4 % while. I would + <f c>2. <f c f,>8 <g c, g> | + <a f c a>4 <g d b> <e c>8 <g d> <c a e> <e c g e> | % go most anywhere to + << { e4._\markup { \italic "poco rall." } f8 d4. c8 } \\ + { <c a e>4 <c a e> <c g d> <b g d> } >> | % find where I be- + << { c1_\markup { \italic "a tempo" } } \\ + { r4 <f, d>-> <a bes,>-> <g c,>-> } >> | % long. + <c, a>4-> <e f,>-> <d g,>2-> | + r4 <f' d>-> <a bes,>-> <g c,>-> | + \time 2/4 + <c, a>-> <e f,>8-> e16 f | % I will + \time 4/4 + <g c, g>4 <c, g c,> << { d2 } \\ { <a d,>4 <a d,> } >> | % beat the odds. + << { e'8 d16 e~ e8 f16 e~ e d8.~ d8 e16 f } \\ % I can go the distance. I will + { <c g>4 <c g> <b g>2 } >> | + << { <g' c, g>4 <c, g>8 d~ d2 } \\ { s2 <a d,>4 <a d,> } >> | % face the world, + <e c g>8 d <e c g> f <d b g>4. e16 f | % fearless, proud and strong. I will + << { <g' c, g>4 <c, g>8 d~ d2 } \\ { s2 <a d,>4 <a d,> } >> | % please the gods. + << { e'8 f16 e~ e8. d16 d8 c~ c c16 c } \\ % I can go the distance. Till I + { <b e,>4 <b e,> <a e> <a e> } >> | + <a f c>4 <b g d> <c a f>8\< a <c a f> f | % find my hero's welcome + <e a, f>2->\!\ff <f d c f,>-> | % right where + <g f d c g>2-> <g d b g>2-> | % I be- + \stemUp + \dynamicUp + c16^> c, g' c, c'^> c, g' c, c'^> r e, f g8^> a16 b | % long. + c16^> c, g' c, c'^> c, g' c, c'^> r e, f g8^> a16 b | + c16^> c, g' c, c'^> c, g' c, c'^> r e, f g8^> a16 b | + \stemNeutral + \dynamicNeutral + << { c8-> g16-. g-. g8-. c-. g16-. g-. c8-. g-. c-. } \\ + { r8 <c, a>16-. <c a>-. <c a>8-. <f c>-. <c a>16-. <c a>-. <f c>8-. <c a>-. <f c>-. } >> | + << { \pitchedTrill c'1\startTrillSpan des | + c,,4-^_\markup { \dynamic "sffz" } \stopTrillSpan r r2 } \\ + { \pitchedTrill g''1\startTrillSpan aes | + \set followVoice = ##t + \change Staff = "lower" + <c,,, c,>4-^ \stopTrillSpan r r2 } >> + \bar "|." } lower = \relative c { \clef bass \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \partial 4 r4 | r1 | << { r1 | r2 r4 r8 a'16 e' } \\ { <a,,~ a,~>1 | <a a,> } >> | <fis'' d a>4 <e b gis> <cis a>2 | << { r1 | r2 r4 r8 a16 b } \\ { <a,~ a,~>1 | <a a,> } >> | <fis' cis'>1 | <b e,> | <a a,> | <a a,> \bar "||" | % I have d,4 e a,2 | % often dreamed of a <d d,>4 <e e,> <a, e'>2 | % far off place where a <d d,>4 <e e,> <fis fis,> <cis cis,> | % great warm welcome will be <a d,>2 <e' e,> | % waiting for me. Where the d,4 e a2 | % crowds will cheer when they d,4 e fis2 | % see my face, and a d4 cis fis8 fis' cis fis, | % voice keeps saying this is \time 6/4 << { r8 a( fis' a,) } \\ { d,2 } >> e1 | % where I'm meant to be. I will \time 4/4 << { a'2 } \\ { cis,4. cis8 } >> <b' d,>2 | % find my way. <e, e,>2 <e e,>4 <d d,>4 | % I can go the distance. I'll be << { a'2 } \\ { cis,4. cis8 } >> <b' d,>2 | % there some day <e, e,>2 <e e,>4 <d d,>4 | % if I can be strong. I know <cis cis,>2 <d d,> | % ev'ry mile will be \time 2/4 fis,2 | % worth my b,1 | % while. I would <d' d,>4 <e e,> a,8 gis fis e | % go most anywhere to \time 2/4 << { r8 a( fis' a,) } \\ { d,2 } >> | % feel like \time 4/4 e1 | % I be- - << { r4 <gis'' e>( <fis d>2~ | \time 2/4 <fis d>) } \\ % long + << { r4 <gis'' e>( <fis d>2~ | \time 2/4 <fis d>) } \\ % long { <a,, a,>1~ | \time 2/4 <a a,>2 } >> | \time 4/4 << { r4 <e' gis>( <d fis>2~ | \time 2/4 <d fis>2) } \\ { a1 | \time 2/4 a2 } >> | \bar "||" \key c \major \time 6/4 <c f,>4 <d g,> <c c,>1 | <c f,>4 <d g,> <c c,>1 | \time 4/4 f4 e f, a' | \time 2/4 << { r8 c,( a' c,) } \\ { f,2 } >> | \time 4/4 << { r8 d'( a' d,) r d( b' d,) } \\ { g,2 g } >> | <a a,>4-> <b b,>-> <f f,>-> <g g,>-> | % I am <e e,>4. <e e,>8 <f f,>4. <f f,>8 | % on my way. + <g g,>4. <g g,>8 <g g,>4 <f f,>4 | % I can go the distance. I don't + <e e,>4. <e e,>8 <f f,>4. <f f,>8 | % care how far, + <g g,>4. <g g,>8 <g g,>4 <f f,>4 | % somehow I'll be strong. I know + <e e,>4. <e e,>8 <f f,>4. <f f,>8 | % ev'ry mile will be + \time 2/4 + <a a,>4. <a a,>8 | % worth my + \time 4/4 + d,8( g c f~ f) e <d d,> <e e,> | % while. I would + <f f,>4 <g g,>4 <c, c,>8 <b b,> <a a,> <g g,> | % go most anywhere to + <f f,>2 <g g,> | % find where I be- + \repeat "tremolo" 16 { c,32 c'32 } | % long. + \repeat "tremolo" 8 { c,32 c'32 } + \repeat "tremolo" 8 { g,32 g'32 } | + \repeat "tremolo" 16 { c,32 c'32 } | + \time 2/4 + \repeat "tremolo" 8 { c,32 c'32 } | % I will + \time 4/4 % beat the odds + <e e,>4. <e, e,>8 <f f,>4. <f f,>8 | + <g g,>4. <g g,>8 <g g,>4 <f f,>4 | % I can go the distance. I will + <e e,>4. <e e,>8 <f f,>4. <f f,>8 | % face the world + <g g,>4. <g g,>8 <g g,>4 <f f,>4 | % fearless, proud and strong. I will + <e e,>4. <e e,>8 <fis fis,>4. <fis fis,>8 | % please the gods. + <gis gis,>4. <gis gis,>8 <a a,>4 <g g,> | % I can go the distance. Till I + <f' f,> <e e,> <d d,> <d d,> | % find my hero's welcome + r4 <g, g,>-> r <g g,>-> | % right where + r4 <g g,>-> r <g g,>-> | % I be- + << + { + \set followVoice = ##t + r4 + \change Staff = "upper" + \stemDown + \slurDown + <b'' g>4( <a f>2) | + \change Staff = "lower" + r4 + \change Staff = "upper" + <b g>4( <a f>2) | + \change Staff = "lower" + r4 + \change Staff = "upper" + <b g>4( <a f>2) + } \\ + { + \ottava #-1 + <c,,, c,>1-> | + <c c,>1-> | + <c c,>1 | + <c c,>1 + \ottava #0 + } + >> + s1 | s1 \bar "|." } dynamics = { r1 } pedal = { r1 } \score { << \new Voice = "mel" { \autoBeamOff \transpose a g \melody } +% \new Voice = "mel" { \autoBeamOff \melody } \new Lyrics \lyricsto mel \text \new PianoStaff << \transpose a g \new Staff = "upper" \upper +% \new Staff = "upper" \upper \new Dynamics = "Dynamics_pf" \dynamics \transpose a g \new Staff = "lower" \lower +% \new Staff = "lower" \lower \new Dynamics = "pedal" \pedal >> >> \layout { \context { \Staff \RemoveEmptyStaves } } \midi { \context { \Score tempoWholesPerMinute = #(ly:make-moment 100 4) } } } \ No newline at end of file
cayblood/lilypond-files
d3efd82fbcb8ade977a60a706a0c187fa5457e79
Transposed from A to G
diff --git a/go_the_distance/go_the_distance.ly b/go_the_distance/go_the_distance.ly index 69154a8..e83a0d7 100644 --- a/go_the_distance/go_the_distance.ly +++ b/go_the_distance/go_the_distance.ly @@ -1,225 +1,225 @@ \version "2.13.52" melody = \relative c'' { \clef treble \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \autoBeamOn \partial 4 s4 | s1 | s | s | s | s | s | s | s | s | % 1-10 r2 r4 r8 a,16 e' \bar "||" | fis4 e cis r8 a16 e' | fis4 e cis r8 a16 e' | fis4 gis a8 e cis a | cis4. d16 cis b4 r8 a16 e' | fis4 e cis r8 a'16 gis | fis4 e cis r8 a16 e' | fis4 gis a8 fis a b | \time 6/4 cis d16 cis~ cis8 d16 b~ b2 r4 r8 cis16 d | \time 4/4 e4 a, b r | cis8 b16 cis~ cis8 d16 cis~ cis b8. r8 cis16 d | e4 a, b r | cis16 b8 cis16~ cis8 d b4 r8 cis16 d | e4 gis, fis r8 a16 b | \time 2/4 cis4 e,8( d) | \time 4/4 d2 r4 r8 d16 e | fis4 e cis16 e a8 r8 b | \time 2/4 cis4 d | \time 4/4 b2.~ b8 a | a1 | \time 2/4 r2 | \time 4/4 r1 | \time 2/4 r2 | \bar "||" \key c \major \time 6/4 r1. | r1. | \time 4/4 r1 | \time 2/4 r2 | \time 4/4 r1 | r2 r4 r8 e'16 f | g4 c, d2 | } text = \lyricmode { I have of -- ten dreamed of a far off place where a great warm wel -- come will be wait -- ing for me. Where the crowds will cheer when they see my face, and a voice keeps say -- ing this is where I'm meant __ to be. __ I will find my way. I can go __ the dis -- tance. I'll be there some -- day if I can __ be strong. I know ev -- 'ry mile will be worth my __ while. I would go most an -- y -- where to feel like I __ be -- long. I am on my way. } upper = \relative c'' { \clef treble \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \partial 4 r8\mp a,16( e' | <fis d a>4) <e b gis> <cis a>2 | e''16(^\markup { \italic lightly } e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e(\> e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b)\! | a8(_\markup { \italic sub. \dynamic mp } a, e' a, a' a, e' a,) | a'( a, e' a, a' a, e') a,,16 e' \bar "||" | <fis d a>4 <e b gis> <cis a>4. a16 e' | % often dreams of a <fis d a>4 <e b gis> <cis a>4. a16 e' | % far off place where a <fis d a>4 <e b gis> << { a8 e cis a } \\ { <cis a>4 gis } >> | % great warm welcome will be << { cis4. d16 cis b4. a16 e' } \\ { fis,2 a4 gis } >> | % waiting for me. Where the << { fis'4 e cis4. a'16 gis } \\ { d8( a) b( gis) b(fis a4) } >> | % crowds will cheer when they << { fis'4 e cis4. a16 e' } \\ { d8( a) b( gis) b( fis a4) } >> | % see my face and a << { fis'4 <gis eis> <a fis cis a>8\< fis a b\! } \\ { d,8( a) cis( b) } >> | % voice keeps saying this is \time 6/4 << { cis'8 d16 cis~ cis8 d16 b~ b2~ b4. cis16 d } \\ % where I'm meant to be. I will { <fis, cis>2 <a e!>4( b,) <gis' e>2 } >> | \time 4/4 <e' a,>4 <a, e> <b fis>2 | % find my way << { cis8 b16 cis~ cis8 d16 cis~ cis b8.~ b8 cis16 d } \\ % I can go the distance. I'll be { <a e>2 <gis e> } >> | <e' a,>4 <a, e> <b fis>2 | % there some day << { cis16 b8 cis16~ cis8 d b4. cis16 d } \\ { <a e>2 <gis e> } >> | % if I can be strong. I know << { <e' a, e>4 gis, fis4. a16 b } \\ { s2 <e, a,>2 } >> | % ev'ry mile will be \time 2/4 <cis' a e>4 << { e,8 d } \\ { a4 } >> | % worth my \time 4/4 % while. I would << { d2 s } \\ { s2 r4 r8 d16 e } \\ { \set followVoice = ##t r8 \change Staff = "lower" d,^\( a' d, \change Staff = "upper" d' a a'4\) } >> | <fis d a>4 <e b gis> cis16~ <e cis>~ <a e cis>8~ <a e cis> b | % go most anywhere to \time 2/4 << { cis4 d } \\ { <fis, cis>2 } >> | % feel like \time 4/4 % I be << { b2.~ b8 a | s1 } \\ { <a e b>4_\markup { \italic "poco rall." } <a e b>4 <gis e b>2\> | \slurUp a'16(\! % long ^\markup { \italic lightly } _\markup { \italic "a tempo" } \mp a, e' a, a' a, e' a, a' a, e' a, a' a, e' a,) \slurNeutral } >> | \time 2/4 a'( a, e' a, a' a, e' a,) | \time 4/4 a'( a, e' a, a' a, e' a, a' a, e' a, a' a, e' a,) | \time 2/4 a'(\> a, e' a,\!) r8 c,16\mf g' | \bar "||" \time 6/4 \key c \major << { <a f>4 <g d b> <e c>2 r4 r8 c16 g' } \\ { c,8( a) b( g) r g( c d f e d c) } >> | << { <a' f>4 <g d b> } \\ { c,8( a) b( g) } >> << { r g'( c d f e d c) } \\ { <e, c>2 r4 r8 c16 g' } >> | \time 4/4 << { <f a>4\< <gis b> <c a e c>8 a <c a e> d | \time 2/4 <e c a e>4.\!\f <f f,>8 } \\ { c,4 e8( d) s2 | \time 2/4 s2 } >> | \time 4/4 << { r8 g'( c b) s2 } \\ { <d, c g d>2 <b' g d b>8( g d g,) } >> | << { c16( a) b-. c-. d4-> e16( c) d-. e-. f8-> e16 f } \\ { <f, c>4-> <g d>-> <c g>-> <b g f>-> } >> | % I am <g' c, g>4 <c, g c,> << { d2 } \\ { <a d,>4 <a d,> } >> | % on my way } lower = \relative c { \clef bass \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \partial 4 r4 | r1 | << { r1 | r2 r4 r8 a'16 e' } \\ { <a,,~ a,~>1 | <a a,> } >> | <fis'' d a>4 <e b gis> <cis a>2 | << { r1 | r2 r4 r8 a16 b } \\ { <a,~ a,~>1 | <a a,> } >> | <fis' cis'>1 | <b e,> | <a a,> | <a a,> \bar "||" | % I have d,4 e a,2 | % often dreamed of a <d d,>4 <e e,> <a, e'>2 | % far off place where a <d d,>4 <e e,> <fis fis,> <cis cis,> | % great warm welcome will be <a d,>2 <e' e,> | % waiting for me. Where the d,4 e a2 | % crowds will cheer when they d,4 e fis2 | % see my face, and a d4 cis fis8 fis' cis fis, | % voice keeps saying this is \time 6/4 << { r8 a( fis' a,) } \\ { d,2 } >> e1 | % where I'm meant to be. I will \time 4/4 << { a'2 } \\ { cis,4. cis8 } >> <b' d,>2 | % find my way. <e, e,>2 <e e,>4 <d d,>4 | % I can go the distance. I'll be << { a'2 } \\ { cis,4. cis8 } >> <b' d,>2 | % there some day <e, e,>2 <e e,>4 <d d,>4 | % if I can be strong. I know <cis cis,>2 <d d,> | % ev'ry mile will be \time 2/4 fis,2 | % worth my b,1 | % while. I would <d' d,>4 <e e,> a,8 gis fis e | % go most anywhere to \time 2/4 << { r8 a( fis' a,) } \\ { d,2 } >> | % feel like \time 4/4 e1 | % I be- << { r4 <gis'' e>( <fis d>2~ | \time 2/4 <fis d>) } \\ % long { <a,, a,>1~ | \time 2/4 <a a,>2 } >> | \time 4/4 << { r4 <e' gis>( <d fis>2~ | \time 2/4 <d fis>2) } \\ { a1 | \time 2/4 a2 } >> | \bar "||" \key c \major \time 6/4 <c f,>4 <d g,> <c c,>1 | <c f,>4 <d g,> <c c,>1 | \time 4/4 f4 e f, a' | \time 2/4 << { r8 c,( a' c,) } \\ { f,2 } >> | \time 4/4 << { r8 d'( a' d,) r d( b' d,) } \\ { g,2 g } >> | <a a,>4-> <b b,>-> <f f,>-> <g g,>-> | % I am <e e,>4. <e e,>8 <f f,>4. <f f,>8 | % on my way. } dynamics = { r1 } pedal = { r1 } \score { << - \new Voice = "mel" { \autoBeamOff \melody } + \new Voice = "mel" { \autoBeamOff \transpose a g \melody } \new Lyrics \lyricsto mel \text \new PianoStaff << - \new Staff = "upper" \upper + \transpose a g \new Staff = "upper" \upper \new Dynamics = "Dynamics_pf" \dynamics - \new Staff = "lower" \lower + \transpose a g \new Staff = "lower" \lower \new Dynamics = "pedal" \pedal >> >> \layout { \context { \Staff \RemoveEmptyStaves } } \midi { \context { \Score tempoWholesPerMinute = #(ly:make-moment 100 4) } } } \ No newline at end of file
cayblood/lilypond-files
5d85aa6e207c8e56baab7275e410fbe86e80fa78
2/3 done
diff --git a/go_the_distance/go_the_distance.ly b/go_the_distance/go_the_distance.ly index aad144b..69154a8 100644 --- a/go_the_distance/go_the_distance.ly +++ b/go_the_distance/go_the_distance.ly @@ -1,172 +1,225 @@ \version "2.13.52" melody = \relative c'' { \clef treble \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \autoBeamOn \partial 4 s4 | s1 | s | s | s | s | s | s | s | s | % 1-10 r2 r4 r8 a,16 e' \bar "||" | fis4 e cis r8 a16 e' | fis4 e cis r8 a16 e' | fis4 gis a8 e cis a | cis4. d16 cis b4 r8 a16 e' | fis4 e cis r8 a'16 gis | fis4 e cis r8 a16 e' | fis4 gis a8 fis a b | \time 6/4 cis d16 cis~ cis8 d16 b~ b2 r4 r8 cis16 d | \time 4/4 e4 a, b r | cis8 b16 cis~ cis8 d16 cis~ cis b8. r8 cis16 d | e4 a, b r | cis16 b8 cis16~ cis8 d b4 r8 cis16 d | e4 gis, fis r8 a16 b | \time 2/4 cis4 e,8( d) | \time 4/4 d2 r4 r8 d16 e | fis4 e cis16 e a8 r8 b | \time 2/4 cis4 d | \time 4/4 b2.~ b8 a | a1 | \time 2/4 r2 | - \time 4/4 + \time 4/4 r1 | + \time 2/4 r2 | + \bar "||" \key c \major \time 6/4 r1. | r1. | + \time 4/4 r1 | + \time 2/4 r2 | + \time 4/4 r1 | + r2 r4 r8 e'16 f | + g4 c, d2 | } text = \lyricmode { I have of -- ten dreamed of a far off place where a great warm wel -- come will be wait -- ing for me. Where the crowds will cheer when they see my face, and a voice keeps say -- ing this is where I'm meant __ to be. __ I will find my way. I can go __ the dis -- tance. I'll be there some -- day if I can __ be strong. I know ev -- 'ry mile will be worth my __ while. I would go most an -- y -- where to feel like I __ be -- long. + I am on my way. } upper = \relative c'' { \clef treble \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \partial 4 r8\mp a,16( e' | <fis d a>4) <e b gis> <cis a>2 | e''16(^\markup { \italic lightly } e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b) | e(\> e, a b e e, a b e e, a b e e, a b) | e( e, a b e e, a b e e, a b e e, a b)\! | a8(_\markup { \italic sub. \dynamic mp } a, e' a, a' a, e' a,) | a'( a, e' a, a' a, e') a,,16 e' \bar "||" | <fis d a>4 <e b gis> <cis a>4. a16 e' | % often dreams of a <fis d a>4 <e b gis> <cis a>4. a16 e' | % far off place where a <fis d a>4 <e b gis> << { a8 e cis a } \\ { <cis a>4 gis } >> | % great warm welcome will be << { cis4. d16 cis b4. a16 e' } \\ { fis,2 a4 gis } >> | % waiting for me. Where the << { fis'4 e cis4. a'16 gis } \\ { d8( a) b( gis) b(fis a4) } >> | % crowds will cheer when they << { fis'4 e cis4. a16 e' } \\ { d8( a) b( gis) b( fis a4) } >> | % see my face and a << { fis'4 <gis eis> <a fis cis a>8\< fis a b\! } \\ { d,8( a) cis( b) } >> | % voice keeps saying this is \time 6/4 << { cis'8 d16 cis~ cis8 d16 b~ b2~ b4. cis16 d } \\ % where I'm meant to be. I will { <fis, cis>2 <a e!>4( b,) <gis' e>2 } >> | \time 4/4 <e' a,>4 <a, e> <b fis>2 | % find my way << { cis8 b16 cis~ cis8 d16 cis~ cis b8.~ b8 cis16 d } \\ % I can go the distance. I'll be { <a e>2 <gis e> } >> | <e' a,>4 <a, e> <b fis>2 | % there some day << { cis16 b8 cis16~ cis8 d b4. cis16 d } \\ { <a e>2 <gis e> } >> | % if I can be strong. I know << { <e' a, e>4 gis, fis4. a16 b } \\ { s2 <e, a,>2 } >> | % ev'ry mile will be \time 2/4 <cis' a e>4 << { e,8 d } \\ { a4 } >> | % worth my \time 4/4 % while. I would << { d2 s } \\ { s2 r4 r8 d16 e } \\ { \set followVoice = ##t r8 \change Staff = "lower" d,^\( a' d, \change Staff = "upper" d' a a'4\) } >> | <fis d a>4 <e b gis> cis16~ <e cis>~ <a e cis>8~ <a e cis> b | % go most anywhere to - \time 2/4 << { cis4 d } \\ { fis cis } >> % feel like + \time 2/4 << { cis4 d } \\ { <fis, cis>2 } >> | % feel like \time 4/4 % I be - << { b2.~ b8 a } \\ - { <a e b>4_\markup { \italic poco rall. } <a e b>4 <gis e b>2\> \! } >> + << { b2.~ b8 a | s1 } \\ + { <a e b>4_\markup { \italic "poco rall." } <a e b>4 <gis e b>2\> | + \slurUp + a'16(\! % long + ^\markup { \italic lightly } + _\markup { \italic "a tempo" } + \mp + a, e' a, a' a, e' a, a' a, e' a, a' a, e' a,) \slurNeutral } >> | + \time 2/4 + a'( a, e' a, a' a, e' a,) | + \time 4/4 + a'( a, e' a, a' a, e' a, a' a, e' a, a' a, e' a,) | + \time 2/4 + a'(\> a, e' a,\!) r8 c,16\mf g' | + \bar "||" \time 6/4 \key c \major + << { <a f>4 <g d b> <e c>2 r4 r8 c16 g' } \\ + { c,8( a) b( g) r g( c d f e d c) } >> | + << { <a' f>4 <g d b> } \\ { c,8( a) b( g) } >> + << { r g'( c d f e d c) } \\ { <e, c>2 r4 r8 c16 g' } >> | + \time 4/4 + << { <f a>4\< <gis b> <c a e c>8 a <c a e> d | \time 2/4 <e c a e>4.\!\f <f f,>8 } \\ + { c,4 e8( d) s2 | \time 2/4 s2 } >> | + \time 4/4 + << { r8 g'( c b) s2 } \\ + { <d, c g d>2 <b' g d b>8( g d g,) } >> | + << { c16( a) b-. c-. d4-> e16( c) d-. e-. f8-> e16 f } \\ + { <f, c>4-> <g d>-> <c g>-> <b g f>-> } >> | % I am + <g' c, g>4 <c, g c,> << { d2 } \\ { <a d,>4 <a d,> } >> | % on my way } lower = \relative c { \clef bass \key a \major \override Staff.TimeSignature #'style = #'() \time 4/4 \partial 4 r4 | r1 | << { r1 | r2 r4 r8 a'16 e' } \\ { <a,,~ a,~>1 | <a a,> } >> | <fis'' d a>4 <e b gis> <cis a>2 | << { r1 | r2 r4 r8 a16 b } \\ { <a,~ a,~>1 | <a a,> } >> | <fis' cis'>1 | <b e,> | <a a,> | <a a,> \bar "||" | % I have d,4 e a,2 | % often dreamed of a <d d,>4 <e e,> <a, e'>2 | % far off place where a <d d,>4 <e e,> <fis fis,> <cis cis,> | % great warm welcome will be <a d,>2 <e' e,> | % waiting for me. Where the d,4 e a2 | % crowds will cheer when they d,4 e fis2 | % see my face, and a d4 cis fis8 fis' cis fis, | % voice keeps saying this is \time 6/4 << { r8 a( fis' a,) } \\ { d,2 } >> e1 | % where I'm meant to be. I will \time 4/4 << { a'2 } \\ { cis,4. cis8 } >> <b' d,>2 | % find my way. <e, e,>2 <e e,>4 <d d,>4 | % I can go the distance. I'll be << { a'2 } \\ { cis,4. cis8 } >> <b' d,>2 | % there some day <e, e,>2 <e e,>4 <d d,>4 | % if I can be strong. I know <cis cis,>2 <d d,> | % ev'ry mile will be \time 2/4 fis,2 | % worth my - b,1 % while. I would + b,1 | % while. I would + <d' d,>4 <e e,> a,8 gis fis e | % go most anywhere to + \time 2/4 << { r8 a( fis' a,) } \\ { d,2 } >> | % feel like + \time 4/4 e1 | % I be- + << { r4 <gis'' e>( <fis d>2~ | \time 2/4 <fis d>) } \\ % long + { <a,, a,>1~ | \time 2/4 <a a,>2 } >> | + \time 4/4 + << { r4 <e' gis>( <d fis>2~ | \time 2/4 <d fis>2) } \\ + { a1 | \time 2/4 a2 } >> | + \bar "||" \key c \major \time 6/4 + <c f,>4 <d g,> <c c,>1 | + <c f,>4 <d g,> <c c,>1 | + \time 4/4 + f4 e f, a' | + \time 2/4 + << { r8 c,( a' c,) } \\ { f,2 } >> | + \time 4/4 + << { r8 d'( a' d,) r d( b' d,) } \\ { g,2 g } >> | + <a a,>4-> <b b,>-> <f f,>-> <g g,>-> | % I am + <e e,>4. <e e,>8 <f f,>4. <f f,>8 | % on my way. } dynamics = { r1 } pedal = { r1 } \score { << \new Voice = "mel" { \autoBeamOff \melody } \new Lyrics \lyricsto mel \text \new PianoStaff << \new Staff = "upper" \upper \new Dynamics = "Dynamics_pf" \dynamics \new Staff = "lower" \lower \new Dynamics = "pedal" \pedal >> >> \layout { \context { \Staff \RemoveEmptyStaves } } \midi { \context { \Score tempoWholesPerMinute = #(ly:make-moment 100 4) } } } \ No newline at end of file