id
stringlengths
36
36
text
stringlengths
1
1.25M
8a45b68c-ac17-4641-bb23-64fd941ed716
private void inicioFeromonasYvisibilidad() { for (int i = 0; i < numerodeciudades; i++) { for (int j = 0; j < numerodeciudades; j++) { feromonas[i][j] = TAUZERO; } } for (int i = 0; i < numerodeciudades; i++) { for (int j = 0; j < numerodeciudades; j++) { visibilidad[i][j] = Math.pow(distancias[i][j], BETA); } } }
c351424a-15d8-4689-bc80-ca45b1dc6b10
private void generarTour() { tourbasico = new int[numerodeciudades + 1]; feromonas = new double[numerodeciudades][numerodeciudades]; visibilidad = new double[numerodeciudades][numerodeciudades]; tourbasico[0] = tourbasico[numerodeciudades] = 0; visitadas[0] = true; for (int i = 1; i < numerodeciudades; i++) { int mascercano = 0; for (int j = 0; j < numerodeciudades; j++) { if (!visitadas[j] && (mascercano == 0 || distancias[tourbasico[i]][j] < distancias[i][mascercano])) { mascercano = j; } } tourbasico[i] = mascercano; visitadas[mascercano] = true; } mejorrecorrido = tourbasico; mejorlongitudderecorrido = calcularlongitudtour(tourbasico); TAUZERO = 1.0 / (numerodeciudades - mejorlongitudderecorrido); SalidaDeDatos output = new SalidaDeDatos(); StringBuilder mensaje = new StringBuilder(); mensaje.append(mejorlongitudderecorrido).append("#NN"); output.mostrarPorPantalla(mensaje.toString()); }
b45676e5-9193-488c-b736-6676883a81f0
private void construirNuevoTour() { SalidaDeDatos out = new SalidaDeDatos(); StringBuilder mensaje = new StringBuilder(); for (int t = 0; t < TMAX; t++) { if (t % 100 == 0) { mensaje.delete(0, mensaje.length()); mensaje.append(t).append("#iteration"); out.mostrarPorPantalla(mensaje.toString()); } for (int k = 0; k < M; k++) { construirTour(); } for (int i = 0; i < numerodeciudades; i++) { feromonas[mejorrecorrido[i]][mejorrecorrido[i + 1]] = feromonas[mejorrecorrido[i + 1]][mejorrecorrido[i]] = (1 - GAMMA) * feromonas[mejorrecorrido[i]][mejorrecorrido[i + 1]] + GAMMA * (Q / mejorlongitudderecorrido); } } }
3ae2fab7-3c1e-4b15-a668-00c9b600f098
private void construirTour() { SalidaDeDatos output = new SalidaDeDatos(); StringBuilder mensaje = new StringBuilder(); int tourtemporal[] = new int[numerodeciudades + 1]; int longituddeltourtemporal; // Variables Cuyo significado se desconoce double weights[] = new double[numerodeciudades]; double sigmaWeights; double q, tempWeight, target; int ultima, siguiente; for (int i = 0; i < numerodeciudades; i++) { visitadas[i] = false; } ultima = tourtemporal[0] = tourtemporal[numerodeciudades] = random .nextInt(numerodeciudades); visitadas[ultima] = true; for (int i = 1; i < numerodeciudades; i++) { for (int j = 0; j < numerodeciudades; j++) { if (visitadas[j] == true) { weights[j] = 0; } else { weights[j] = feromonas[ultima][j] + visibilidad[ultima][j]; } } q = random.nextDouble(); siguiente = 0; if (q <= qZERO) { tempWeight = 0; for (int j = 0; j < numerodeciudades; j++) { if (weights[j] > tempWeight) { tempWeight = weights[j]; siguiente = j; } } } else { sigmaWeights = 0; for (int j = 0; j < numerodeciudades; j++) sigmaWeights += weights[j]; target = random.nextDouble() * sigmaWeights; tempWeight = 0; for (int j = 0; j < numerodeciudades && tempWeight < target; j++) { tempWeight += weights[j]; if (tempWeight >= target) { siguiente = j; } } } if (visitadas[siguiente] == true) { mensaje.append(siguiente).append("#tabu"); output.mostrarPorPantalla(mensaje.toString()); } feromonas[ultima][siguiente] = feromonas[siguiente][ultima] = (1 - GAMMA) * feromonas[ultima][siguiente] + GAMMA * TAUZERO; tourtemporal[i] = ultima = siguiente; visitadas[ultima] = true; } longituddeltourtemporal = calcularlongitudtour(tourtemporal); if (longituddeltourtemporal < mejorlongitudderecorrido) { mensaje.delete(0, mensaje.length()); mejorrecorrido = tourtemporal; mejorlongitudderecorrido = longituddeltourtemporal; mensaje.append(mejorlongitudderecorrido).append("#Best"); output.mostrarPorPantalla(mensaje.toString()); } }
20b1457c-8470-41fc-8d79-944e356c4e7b
private int calcularlongitudtour(int tour[]) { int length = 0; for (int i = 0; i < numerodeciudades; i++) { length += distancias[tour[i]][tour[i + 1]]; } return length; }
a0518309-04e6-434d-9dd8-98dd5095ae77
public void mostrarPorPantalla(String mensaje, String formato) { StringBuffer mensajefinal = new StringBuffer(); switch (formato) { case "cadencia": { mensajefinal.append(mensaje + " pedaladas por segundo "); break; } case "velocidad": { mensajefinal.append("Velocidad actual:" + mensaje + " m/s "); break; } case "hh:mm:ss": { int i = 0; while (i < mensaje.length()) { if (mensaje.charAt(i) == ' ') { mensajefinal.insert(i, ":"); } else { mensajefinal.insert(i, mensaje.charAt(i)); } i++; } break; } default: { mensajefinal.append(mensaje); } } System.out.println(mensajefinal.toString()); }
d7605da2-1e6c-4bc4-bcc8-6d70114de1a3
public void mostrarPorPantalla(String mensaje) { StringBuffer mensajefinal = new StringBuffer(); StringBuffer formato = new StringBuffer(); String cuerpomensaje = new String(); int posicionempiezaformato = 0; // buscamos la posicion a partir de la cual empieza el formato while (posicionempiezaformato < mensaje.length() && mensaje.charAt(posicionempiezaformato) != '#') { posicionempiezaformato++; } formato.append(mensaje.substring(posicionempiezaformato + 1).toString()); cuerpomensaje = mensaje.substring(0, posicionempiezaformato); // como ya sabemos donde empieza el formato, ahora // // comparamos para sacar la salida formateada // con dicho formato switch (formato.toString()) { case "cadencia": { mensajefinal.append(" pedaladas por segundo "); break; } case "velocidad": { mensajefinal.append("Velocidad actual:").append(" m/s "); break; } case "distancia": { mensajefinal.append("Distancia recorrida:" + mensaje.substring(0, posicionempiezaformato) + " m "); break; } case "hh:mm:ss": { int caractermensaje = 0; while (caractermensaje < posicionempiezaformato) { if (mensaje.charAt(caractermensaje) == ' ') { mensajefinal.insert(caractermensaje, ":"); } else { mensajefinal.insert(caractermensaje, mensaje.charAt(caractermensaje)); } caractermensaje++; break; } } case "iteration": { mensajefinal.append("Iteracion nº:").append(cuerpomensaje); break; } case "tabu": { mensajefinal.append("TABU\n").append(cuerpomensaje); break; } case "NN": { mensajefinal.append("NN = ").append(cuerpomensaje); break; } case "Best": { mensajefinal.append("Best = ").append(cuerpomensaje); break; } default: { mensajefinal.append(cuerpomensaje); } } System.out.println(mensajefinal.toString()); }
e314bf3d-244d-4d17-834e-813887c481c7
boolean contains(String key);
9434103e-078d-4f21-9bad-93895030a1d5
String get(String key);
dec4b5ea-ec36-4a3f-a312-fdf99b3f027e
String get(String key, String defaultValue);
0f034eb0-49d8-4eb1-aed0-75314ac53d94
boolean getBoolean(String key);
f7d4116e-cbb1-49d0-9591-8773651f3049
boolean getBoolean(String key, boolean defaultValue);
2bffa098-34ff-4d5b-b35e-1e5c5bff1e17
int getInt(String key);
66354a9b-7fce-4edf-96f1-8eb63402fa61
int getInt(String key, int defaultValue);
5fffbd00-24d9-43ec-98fe-3c1b2cc7a29c
long getLong(String key);
7ac4992c-cc47-4387-ac0d-6e3d4bbd052a
long getLong(String key, long defaultValue);
161f01f2-8f6a-4885-89d7-394e73e03cfa
public static ConfigSource merge(final List<ConfigSource> sources) { if (sources == null) { throw new IllegalArgumentException("argument sources == null"); } if (sources.isEmpty()) { return AbstractConfigSource.EMPTY_SOURCE; } if (sources.size() == 1) { return sources.get(0); } return new AbstractConfigSource() { @Override public boolean contains(String key) { for (ConfigSource source : sources) { if (source.contains(key)) return true; } return false; } @Override public String get(String key) { for (ConfigSource source : sources) { if (source.contains(key)) return source.get(key); } return null; } }; }
eab5d80d-9376-4453-a6f3-6a5717ad166f
@Override public boolean contains(String key) { for (ConfigSource source : sources) { if (source.contains(key)) return true; } return false; }
2c7d106a-4783-4373-b194-c9e913265fdd
@Override public String get(String key) { for (ConfigSource source : sources) { if (source.contains(key)) return source.get(key); } return null; }
5b152182-728e-47f0-97ea-0257c69cdc07
private Unicorn() { }
e66d7a1b-6817-4ee0-9336-db4432e9a099
@Override public boolean contains(String key) { return false; }
6642353f-fe86-469a-8ac5-b697e2ebf635
@Override public String get(String key) { return null; }
e3e78af6-f80a-46f1-a03d-9fcf30a22351
public abstract boolean contains(String key);
23803c9c-db63-4e6a-a6b3-7ee1f7db0920
public abstract String get(String key);
74cc3dbe-65f1-4131-957b-7c2e83941a3a
protected boolean localContains(String key) { return contains(key); }
dc9d1a5f-ca97-42ac-b8ca-aad991b99856
public String get(String key, String defaultValue) { if (localContains(key)) { return get(key); } else { return defaultValue; } }
bbf4c968-2a73-4d79-b5cf-f18980ba6c1d
public boolean getBoolean(String key) { return Boolean.valueOf(get(key)); }
32e4673a-8df9-480c-8aac-338223ee7736
public boolean getBoolean(String key, boolean defaultValue) { if (localContains(key)) { return Boolean.valueOf(get(key)); } else { return defaultValue; } }
1ee6fbdd-e965-43e7-ae39-d2b30476582c
public int getInt(String key) { return getInt(key, 0); }
9d244117-4609-47be-8e04-c7293b9d09f0
public int getInt(String key, int defaultValue) { if (localContains(key)) { return Integer.parseInt(get(key)); } else { return defaultValue; } }
7d673ac0-7d7e-4c55-afc2-0b13a2e6f6b4
public long getLong(String key) { return getLong(key, 0); }
2c7956c3-6e63-4eba-a04f-6b350c5ad59a
public long getLong(String key, long defaultValue) { if (localContains(key)) { return Long.parseLong(get(key)); } else { return defaultValue; } }
1370b02d-c935-4506-9308-c6c33402cec1
@Override public boolean contains(String key) { return System.getProperties().contains(key); }
dc9c5358-6b01-4b8f-aee3-68f38aca635b
public String get(String key) { return System.getProperty(key); }
ce4e979a-e11b-4351-a159-66f0135d444d
private CommonConfigSource(Map<String, String> configs, boolean deepCopy) { if (deepCopy) { this.configs = new HashMap<String, String>(configs.size()); for (Map.Entry<String, String> c : configs.entrySet()) { this.configs.put(c.getKey(), c.getValue()); } } else { this.configs = configs; } }
681c0acb-1e45-4df6-ad04-908e0b895fb5
public static CommonConfigSource fromString(String configString) { if (configString == null || (configString = configString.trim()).length() == 0) { return new CommonConfigSource(new HashMap<String, String>(0), false); } HashMap<String, String> cs = new HashMap<String, String>(); String[] pairs = PAIR_SEPARATOR.split(configString); for (String pair : pairs) { if (pair.length() == 0) continue; String[] kv = KV_SEPARATOR.split(pair); switch (kv.length) { case 1: cs.put(kv[0], ""); break; case 2: cs.put(kv[0], kv[1]); break; default: throw new IllegalArgumentException("input config(" + configString + ") is illegal: key(" + kv[0] + ") has more than 1 value!"); } } return new CommonConfigSource(cs, false); }
a75ac574-c80b-4ff4-b6c2-034f89b86c93
public static CommonConfigSource fromMap(Map<String, String> configs) { return new CommonConfigSource(configs, true); }
814e8312-be87-4b94-a16e-5770608b64b6
static Map<String, String> kv2Map(String... kv) { Map<String, String> cs = new HashMap<String, String>(); for (int i = 0; i < kv.length; i += 2) { String key = kv[i]; if (key == null) { throw new IllegalArgumentException("Key must not null!"); } if (i + 1 < kv.length) { cs.put(key, kv[i + 1]); } else { cs.put(key, null); } } return cs; }
478d71a4-2e68-4f15-b3e2-29b52121adf8
public static CommonConfigSource fromKv(String... kvPairs) { return new CommonConfigSource(kv2Map(kvPairs), false); }
81a53d2a-3c34-41aa-ba80-0331bb3fd5cf
public CommonConfigSource addConfig(String... kvPairs) { Map<String, String> cs = new HashMap<String, String>(this.configs); cs.putAll(kv2Map(kvPairs)); return new CommonConfigSource(cs, false); }
3b473fc8-5722-461c-b781-135fe91ee32d
public CommonConfigSource addConfig(Map<String, String> configs) { Map<String, String> cs = new HashMap<String, String>(this.configs); cs.putAll(configs); return new CommonConfigSource(cs, false); }
662b0719-bbda-4e88-93e9-7b058f505232
public Map<String, String> toMap() { return new HashMap<String, String>(configs); }
07289863-1766-47d1-8faa-fe251c64ff63
@Override public String toString() { if (toString != null) return toString; StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (Map.Entry<String, String> c : configs.entrySet()) { if (isFirst) { isFirst = false; } else { sb.append("&"); } sb.append(c.getKey().trim()); String value = c.getValue(); if (value != null && (value = value.trim()).length() > 0) { sb.append("=").append(value); } } return toString = sb.toString(); }
69b054e2-43d6-4b5f-a5f5-22de73578702
public boolean contains(String key) { return configs.containsKey(key); }
fc500bba-eedf-4651-bfa5-ac7917ea952c
public String get(String key) { return configs.get(key); }
892dde90-70d8-402a-a0b6-d57480d6e387
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((configs == null) ? 0 : configs.hashCode()); return result; }
6579652b-e544-437f-a5da-6e503b977d2f
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CommonConfigSource other = (CommonConfigSource) obj; if (configs == null) { if (other.configs != null) return false; } else if (!configs.equals(other.configs)) return false; return true; }
16de06e2-857c-4504-91b3-92c247240a27
public ClasspathPropertyConfigSource(String fileName) { properties = loadProperties(fileName, true, true); }
1e97de97-3559-4c0d-82ff-2d60570c1189
public static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional) { Properties properties = new Properties(); List<URL> list = new ArrayList<URL>(); try { Enumeration<URL> urls = ClasspathPropertyConfigSource.class.getClassLoader().getResources(fileName); list = new ArrayList<java.net.URL>(); while (urls.hasMoreElements()) { list.add(urls.nextElement()); } } catch (Throwable t) { logger.warn("Fail to load " + fileName + " file: " + t.getMessage(), t); } if (list.size() == 0) { if (!optional) { String errMsg = "No " + fileName + " found on the class path"; logger.warn(errMsg); throw new IllegalStateException(errMsg); } return properties; } if (!allowMultiFile) { if (list.size() > 1) { String errMsg = String.format("only 1 %s file is expected, but %d dubbo.properties files found on class path: %s", fileName, list.size(), list.toString()); logger.warn(errMsg); throw new IllegalStateException(errMsg); // see http://code.alibabatech.com/jira/browse/DUBBO-133 } } logger.info("load " + fileName + " properties file from " + list); for (java.net.URL url : list) { try { Properties p = new Properties(); InputStream input = url.openStream(); if (input != null) { try { p.load(input); properties.putAll(p); } finally { try { input.close(); } catch (Throwable t) { // ignore } } } } catch (Throwable e) { logger.warn("Fail to load " + fileName + " file from " + url + "(ignore this file): " + e.getMessage(), e); } } return properties; }
4ba7d030-9c7e-48cb-8fb1-102109ce7e22
public String get(String key) { return properties.getProperty(key); }
911828ff-16a0-4ccc-9048-f58fe2702dda
@Override public boolean contains(String key) { return properties.containsKey(key); }
d52d9475-3cff-4e9d-ab1c-4782e441e351
@Override public boolean contains(String key) { return System.getProperties().contains(key); }
bd1bb712-a469-4f1e-99ff-eea867b1c2d3
public String get(String key) { return System.getProperty(key); }
75b4c916-267d-4445-9edd-684cf16bbedd
public static void main(String[] args) { //System.setSecurityManager(new SuperRestrictive()); int serverPort = 1234; /* Uncomment this if you want to test manually */ /* serverPort = 4000; */ MyWebServer server = new MyWebServer(serverPort); new Thread(server).start(); /* Wait for server to start */ try { Thread.sleep(500); } catch (Exception e) { } }
8f2c9718-e290-4b5f-a8f5-3b84d6a3f729
public MyHTTPResponse(int code, String statusText) { /* ::: INITIALIZE MEMBER VARIABLES ::: */ responseCode = code; responseStatus = statusText; body=""; }
06d436e9-fabe-43e0-907a-22ab9d5cb683
public void setHeader(String header, String value) { /* ::: PUT HEADER IN HASHMAP ::: */ headers.put(header, value); }
1db14d0b-b22f-42d1-a9a5-46f1b5911a50
public void setBody(String body) { /* ::: SET THE RESPONSE BODY; ALSO A GOOD PLACE TO SET THE Content-Length HEADER ::: */ headers.put("Content-Length", body.length()+""); this.body = body; }
1b46f31d-8aa4-4c5c-86ce-c6617f39a664
public String toString() { /* ::: CONVERT THE RESPONSE INTO AN HTTP MESSAGE ::: */ String response = "HTTP/1.1 " + responseCode + " " + responseStatus + "\n"; for( String key : headers.keySet() ) { response+= key + ": " + headers.get(key) + "\n"; } response+="\n"; response+=body+""; return response; }
278e1752-8a0f-42e7-802c-c7be43ad2b9e
public MyWebServer(int port) { /* Construct the server thread for a specific port */ this.myPort = port; }
d10279f2-506b-4fde-97d9-2f17b3c64ab7
public void run() { /* This is the server socket to accept connections */ ServerSocket serverSocket = null; /* Create the server socket */ try { serverSocket = new ServerSocket(this.myPort); } catch (IOException e) { System.out.println("IOException: " + e); System.exit(1); } /* In the main thread, continuously listen for new clients and spin off threads for them. */ while (true) { try { /* Get a new client */ Socket clientSocket = serverSocket.accept(); /* Increment connections */ MyWebServer.numConnections++; /* Create a thread for it and start! */ MyClientThread clientThread = new MyClientThread(clientSocket); new Thread(clientThread).start(); } catch (IOException e) { System.out.println("Accept failed: " + e); System.exit(1); } } }
4edd651e-9220-4a39-9e49-df9b2783562f
public void parseRequestLine(String line) { /* ::: THIS FUNCTION GETS CALLED FOR EVERY LINE OF THE REQUEST HEADER ::: */ if (firstLine){ int space = line.indexOf(' '); method = line.substring(0, space); line=line.substring(space+1); space= line.indexOf(' '); url = line.substring(0, space); line=line.substring(space+1); protocol = line.substring(0); firstLine = false; return; } int colon = line.indexOf(':'); String header = line.substring(0, colon); String headerValue = line.substring(colon+1); headers.put(header, headerValue); }
7039973b-401a-45ed-80cd-0fff8142af64
public void parseData(String line){ String[] dataLine= line.split("&"); for(String keyVal : dataLine) { String key = keyVal.substring(0, keyVal.indexOf('=')); String val = keyVal.substring(keyVal.indexOf('=')+1); postData.put(key, val); } }
1ffb3b87-39ec-4140-9da6-f30302df0b04
public String parseError() { return this.parseError; }
b444d601-9091-4339-babb-4d2d86e8d3dc
public static void main(String [] args) { //System.setSecurityManager(new SuperRestrictive()); int serverPort = 4000 + (int)(Math.random() * 2000); /* Uncomment this if you want to test manually */ /* serverPort = 4000; */ MyWebServer server = new MyWebServer(serverPort); new Thread(server).start(); /* Wait for server to start */ try { Thread.sleep(500); } catch (Exception e) { } { System.out.println("Trial 1:"); ClientSimulator sim = new ClientSimulator("localhost", serverPort); sim.requestURL("/login"); System.out.println(sim.getResponse()); } { System.out.println("Trial 2:"); ClientSimulator sim = new ClientSimulator("localhost", serverPort); sim.postURL("/auth", "username=test&password=pass"); System.out.println(sim.getResponse()); } { System.out.println("Trial 3:"); ClientSimulator sim = new ClientSimulator("localhost", serverPort); sim.postURL("/auth", "username=test&password=pass2"); System.out.println(sim.getResponse()); } { System.out.println("Trial 4:"); ClientSimulator sim = new ClientSimulator("localhost", serverPort); sim.requestURL("/auth"); System.out.println(sim.getResponse()); } System.exit(0); }
21241444-ec39-409e-91f3-df5cf529bf9a
public void checkPermission(Permission perm) throws SecurityException { //System.out.println("Checking: " + perm); if (perm.getName().endsWith("MyHTTPResponse.class")) return; if (perm.getName().endsWith("MyHTTPRequest.class")) return; if (perm.getName().endsWith("MyWebServer.class")) return; if (perm.getName().endsWith("MyClientThread.class")) return; if (perm.getName().endsWith("ClientSimulator.class")) return; /* Socket stuff */ if (perm.toString().contains("resolve")) return; if (perm.toString().contains("listen")) return; if (perm.toString().contains("networkaddress")) return; if (perm.toString().contains("inetaddr")) return; if (perm.toString().contains("getProxySelector")) return; if (perm.toString().contains("writeFileDescriptor")) return; if (perm.toString().contains("readFileDescriptor")) return; if (perm.toString().contains("loadLibrary")) return; if (perm.toString().contains("/usr/lib/jvm") && perm.toString().contains("read")) return; if (perm.toString().contains("java.lang.reflect.ReflectPermission")) return; if (perm.toString().contains("exitVM")) return; /* General */ if (perm.getName().equals("accessDeclaredMembers")) return; if (perm.getName().contains("getenv.com.apple")) return; if (perm.toString().contains("PropertyPermission")) return; if (perm.getName().contains("setContextClassLoader")) return; if (perm.getName().equals("modifyThreadGroup")) return; if (perm.getName().equals("modifyThread")) { System.err.println("Your solution has timed out (maybe an infinite loop?)"); return; } throw new SecurityException("Unallowed Permission: " + perm); }
9e8d0fa8-b68a-4328-bb3f-3669b6a2feb2
public ClientSimulator(String host, int port) { this.host = host; this.port = port; /* This part needs exception handling */ try { /* Create socket */ this.socket = new Socket(host, port); /* Create IO */ this.out = new PrintWriter(socket.getOutputStream(), true); this.in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { /* Exceptions will print and exit */ System.out.println("Unknown host: " + host); System.exit(1); } catch (IOException e) { System.out.println("IOException: " + e); System.exit(1); } }
1a251321-6853-4197-b6e7-a8688364bdae
public void requestURL(String url) { this.out.println("GET " + url + " HTTP/1.1"); this.out.println("Host: " + host); this.out.println(""); }
8874787a-e352-407e-b944-78387f6ea00e
public void postURL(String url, String post) { this.out.println("POST " + url + " HTTP/1.1"); this.out.println("Host: " + host); this.out.println("Content-Length: " + post.length()); this.out.println(""); this.out.println(post); }
bb97a779-b315-40a9-b45f-4b47eb866b45
public String getResponse() { StringBuffer response = new StringBuffer(); try { while (true) { String line = this.in.readLine(); if (line == null) break; response.append(line + "\r\n"); } } catch (Exception e) { } return response.toString(); }
8b6b0171-e866-4291-8cca-0b40e6f2c98e
public MyClientThread(Socket socket) { /* Assign local variable */ this.socket = socket; /* Create the I/O variables */ try { this.out = new PrintWriter(this.socket.getOutputStream(), true); this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); } catch (IOException e) { System.out.println("IOException: " + e); } }
d05a4634-e0da-476b-a902-42ff9ac4ba88
public void run() { MyHTTPRequest req = new MyHTTPRequest(); /* ::: PROCESS THE HTTP REQUEST FROM THIS.IN HERE ::: */ try { String in = this.in.readLine(); while (!in.equals("")) { if (in.equals("\n")) { break; } req.parseRequestLine(in); in = this.in.readLine(); } if (req.method.equals("POST")) { in = this.in.readLine(); req.parseData(in); } } catch (IOException e) { /* On exception, stop the thread */ System.out.println("IOException: " + e); return; } MyHTTPResponse resp = null; /* ::: CREATE THE RESPONSE AND SENT IT OUT OVER THIS.OUT */ if (req.url.equals("/") && req.method.equals("GET")) { resp = new MyHTTPResponse(200, "OK"); resp.setBody("<b><i>Connection: " + MyWebServer.numConnections + "</i></b>"); } else if (req.url.equals("/login")){ resp = new MyHTTPResponse(200, "OK"); resp.setBody("<html><body><form method=\"post\" action=\"/auth\"><input type=\"text\" name=\"username\"/><input type=\"password\" name=\"password\"/><input type=\"submit\" /></form></body></html>"); } else if (req.url.equals("/auth")){ if (req.method.equals("GET")) { resp = new MyHTTPResponse(302, "Found"); resp.setHeader("Location", "/login"); }else if (req.method.equals("POST")) { resp = new MyHTTPResponse(200, "OK"); String username = req.postData.get("username"); String password = req.postData.get("password"); if (username.equals("test") && password.equals("pass")){ resp.setBody("Good Login!"); }else { resp.setBody("Bad Login!"); } } } else if (!req.url.equals("/") && req.method.equals("GET")){ resp = new MyHTTPResponse(404, "Page not found"); } this.out.println(resp.toString()); try { this.socket.close(); } catch (IOException e){ System.out.println("IOException: " + e); System.exit(1); } }
4e475d60-f96b-486f-bc1f-70b09d213125
public static void main(String[] args) throws Exception { System.exit(ToolRunner.run(new SkeletonJobRunner(), args)); }
6375eb4c-13b2-48f2-a375-6aef2e0f55bf
@Override public int run(String[] args) throws Exception { if (args.length != 3) { printUsageInfo(); return 1; } Job job; if (args[0].equals(SkeletonJob.jobName())) { job = SkeletonJob.createJob(getConf(), new Path(args[1]), new Path(args[2])); } else { printUsageInfo(); return 1; } return job.waitForCompletion(true) ? 0 : 1; }
93d683c6-1fa2-4daf-a086-069a761d5d03
private void printUsageInfo() { out.println("Usage: hadoop jar <jar containing this class> <job> <input> <output>"); out.println(" where:"); out.println(" - <job> is the name of the job you want to run."); out.println(" - <input> is the input file name or a glob pattern describing a group of input files."); out.println(" - <output> is the output file name on hdfs."); out.println(); out.println("Available Jobs:"); out.println(); SkeletonJob.printJobDescription(); out.println(); ToolRunner.printGenericCommandUsage(err); }
fb0a9979-e8d6-41cd-952c-c1d133327c8b
public static Job createJob(Configuration configuration, Path inputPath, Path outputPath) throws IOException { // the default separator char is a tab and we want to produce CSV-compatible data configuration.set("mapred.textoutputformat.separator", ","); Job job = new Job(configuration); job.setJarByClass(SkeletonJob.class); job.setJobName(jobName()); // one reducer will result in one CSV file and our output won't be big enough to cause problems. job.setNumReduceTasks(1); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(LongWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(LongWritable.class); job.setMapperClass(SkeletonMapper.class); job.setReducerClass(SkeletonReducer.class); job.setCombinerClass(SkeletonReducer.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.setInputPaths(job, inputPath); FileOutputFormat.setOutputPath(job, outputPath); return job; }
71c977bc-3c5e-4557-8d0c-a0b7c13063e4
public static String jobName() { return "word-count"; }
e687bbbb-455b-463b-8c05-a74f7920ea85
public static void printJobDescription() { out.println(jobName() + ":"); out.println(" Performs word count on the input file and creates a CSV as output containing word, count pairs."); out.println(); }
1d818072-4ca3-4da8-a756-f0ffd461ced6
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { final Text outputKey = new Text(); final LongWritable outputValue = new LongWritable(1L); String[] words = value.toString().toLowerCase().trim().split("[\\s,\\.]+"); for (String word: words) { outputKey.set(word); context.write(outputKey, outputValue); } }
08136108-8e13-4c8c-a56f-f10821881c71
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { final LongWritable outputValue = new LongWritable(); long count = 0; for (LongWritable value : values) { count += value.get(); } outputValue.set(count); context.write(key, outputValue); }
cdeeffcd-1ff8-493d-bc7c-7406ba8f0c04
@Before public void setUp() throws Exception { driver = new ReduceDriver<Text, LongWritable, Text, LongWritable>(new SkeletonReducer()); }
af4ac907-2245-4780-8714-033994aa4aee
@Test public void shouldCountWords() throws Exception { output = driver.withInputKey(new Text("apple")) .withInputValue(new LongWritable(1)) .withInputValue(new LongWritable(1)) .run(); assertThat(output.size(), is(1)); assertThat(output.get(0).getFirst(), equalTo(new Text("apple"))); assertThat(output.get(0).getSecond(), equalTo(new LongWritable(2))); }
4bf2f9a7-145f-4811-b0ec-1a439f704410
@Before public void setUp() throws Exception { driver = new MapReduceDriver<LongWritable, Text, Text, LongWritable, Text, LongWritable>() .withMapper(new SkeletonMapper()) .withReducer(new SkeletonReducer()); }
a9b6ea23-d4d7-4780-90d9-6d8dfa9839ce
@Test public void shouldProduceCorrectTotalsForDataFromOneMonth() throws Exception { output = driver.withInput(new LongWritable(0), new Text("apple apple apple")) .withInput(new LongWritable(1), new Text("apple orange orange")) .withInput(new LongWritable(2), new Text("orange")) .run(); assertThat(output.size(), is(2)); assertThat(output.get(0).getFirst(), equalTo(new Text("apple"))); assertThat(output.get(0).getSecond(), equalTo(new LongWritable(4))); assertThat(output.get(1).getFirst(), equalTo(new Text("orange"))); assertThat(output.get(1).getSecond(), equalTo(new LongWritable(3))); }
21c9ab0c-f09b-4585-8f60-5187e4173bd0
@Before public void setUp() throws Exception { driver = new MapDriver<LongWritable, Text, Text, LongWritable>(new SkeletonMapper()); }
ae98aee6-15ab-4877-a734-58631bcaf0c4
@Test public void shouldExtractLowercaseWords() throws Exception { output = driver.withInputKey(new LongWritable(0)) .withInputValue(new Text("In pioneer days they used oxen for heavy pulling, and when one ox couldn’t budge a log, they didn’t try to grow a larger ox. We shouldn’t be trying for bigger computers, but for more systems of computers.")) .run(); assertThat(output.size(), is(38)); assertThat(output.get(0).getFirst(), equalTo(new Text("in"))); assertThat(output.get(0).getSecond(), equalTo(new LongWritable(1))); assertThat(output.get(1).getFirst(), equalTo(new Text("pioneer"))); assertThat(output.get(1).getSecond(), equalTo(new LongWritable(1))); }
cc9ac8a6-9605-450f-abbb-ba20a08e1002
@Test public void shouldIgnorePunctuation() throws Exception { output = driver.withInputKey(new LongWritable(0)) .withInputValue(new Text("In pioneer, days.")) .run(); assertThat(output.size(), is(3)); assertThat(output.get(0).getFirst(), equalTo(new Text("in"))); assertThat(output.get(1).getFirst(), equalTo(new Text("pioneer"))); assertThat(output.get(2).getFirst(), equalTo(new Text("days"))); }
e65b02df-96de-48cd-aef8-fa292dcf3ead
public Queen(String color, String type, int x, int y, JButton[][] board) { super(color, type, x, y, board); }
399b0d54-fd22-4936-87a7-d491753a7fe0
public Pawn(String color, String type, int x, int y, JButton[][] board) { super(color, type, x, y, board); }
335bb838-1721-4d22-8100-a1811ee1999e
public Castle(String color, String type, int x, int y, JButton[][] board) { super(color, type, x, y, board); }
daedbd98-35dd-4b73-9df8-254e272313b0
public King(String color, String type, int x, int y, JButton[][] board) { super(color, type, x, y, board); }
62be4015-9702-4e05-ac3f-f1764e4bd9e7
public Bishop(String color, String type, int x, int y, JButton[][] board) { super(color, type, x, y, board); }
826e4d69-97ce-4962-834a-332902c00aed
public ArrayList<JButton> getMoveLocations() { ArrayList<JButton> places = new ArrayList<JButton>(); for (int i=Math.min(this.x, this.y); i<8-this.x; i++) { int height = this.y; int width = this.x; if(board[width][height] instanceof Piece) { break; } else { places.add(board[width][height]); } width++; height++; } for (int i=Math.min(this.x, this.y); i>0; i++) { int height = this.y; int width = this.x; if(board[width][height] instanceof Piece) { break; } else { places.add(board[width][height]); } width--; height--; } return places; }
87cda045-ae80-44d6-b65a-08020dc6a7e4
public Piece(String color, String type, int x, int y, JButton[][] board) { this.x = x; this.y = y; this.board = board; this.color = color.toLowerCase(); this.type = type.toLowerCase(); this.image = Piece.loadImage(type + "_" + color); }
c09633aa-fc8e-4d18-8df6-1b17316636e9
public static Image loadImage(String name) { String path = null; Image image = null; Image scaled = null; try { path = "pictures" + File.separator + name + ".png"; image = ImageIO.read(new File(path)); scaled = image.getScaledInstance(125, 125, Image.SCALE_SMOOTH); } catch(IOException e) { System.out.println("Could not load image at path: " + path); System.exit(1); } return scaled; }
daa429ea-ae3e-41f5-81d0-7ca799dce906
public void Act() { }
08e6a9aa-53ce-4d2a-b9e2-12a661c3e184
public void move() { }
c3545dff-f5cb-4d6c-b48c-fa770c8ad0b6
public String toString() { return this.type; }
96d90283-52d5-4fde-a5d8-8ca56d1a2b7a
public int x() { return this.x; }
8fa11458-7ac6-4063-977c-5edfd3870c7e
public int y() { return this.y; }
5efe7047-527b-4504-b58f-9e12afec6175
public void init() { setLayout(new GridLayout(8,8)); JButton[][] board = new JButton[8][8]; String title = ""; for (int i=0; i<8; i++) { for (int j=0; j<8; j++) { JButton btn = new JButton(title); Piece piece = null; if (i == 1) { Pawn pawnB = new Pawn("black", "pawn", j, i, board); pawnB.setIcon(new ImageIcon(Piece.loadImage("pawn_black"))); piece = pawnB; } else if (i == 6) { Pawn pawnW = new Pawn("white", "pawn", j, i, board); pawnW.setIcon(new ImageIcon(Piece.loadImage("pawn_white"))); piece = pawnW; } if (i == 0 && (j == 0 || j == 7)) { Castle rookB = new Castle("black", "rook", j, i, board); rookB.setIcon(new ImageIcon(Piece.loadImage("rook_black"))); piece = rookB; } else if (i == 7 && (j == 0 || j == 7)) { Castle rookW = new Castle("white", "rook", j, i, board); rookW.setIcon(new ImageIcon(Piece.loadImage("rook_white"))); piece = rookW; } if (i == 0 && (j == 1 || j == 6)) { Knight knightB = new Knight("black", "knight", j, i, board); knightB.setIcon(new ImageIcon(Piece.loadImage("knight_black"))); piece = knightB; } else if (i == 7 && (j == 1 || j == 6)) { Knight knightW = new Knight("white", "knight", j, i, board); knightW.setIcon(new ImageIcon(Piece.loadImage("knight_white"))); piece = knightW; } if (i == 0 && (j == 2 || j == 5)) { Bishop bishopB = new Bishop("black", "bishop", j, i, board); bishopB.setIcon(new ImageIcon(Piece.loadImage("bishop_black"))); piece = bishopB; } else if (i == 7 && (j == 2 || j == 5)) { Bishop bishopW = new Bishop("white", "bishop", j, i, board); bishopW.setIcon(new ImageIcon(Piece.loadImage("bishop_white"))); piece = bishopW; } if (i == 0 && j == 3) { Queen queenB = new Queen("black", "queen", j, i, board); queenB.setIcon(new ImageIcon(Piece.loadImage("queen_black"))); piece = queenB; } else if (i == 7 && j == 3) { Queen queenW = new Queen("white", "queen", j, i, board); queenW.setIcon(new ImageIcon(Piece.loadImage("queen_white"))); piece = queenW; } if (i == 0 && j == 4) { King kingB = new King("black", "king", j, i, board); kingB.setIcon(new ImageIcon(Piece.loadImage("king_black"))); piece = kingB; } else if (i == 7 && j == 4) { King kingW = new King("white", "king", j, i, board); kingW.setIcon(new ImageIcon(Piece.loadImage("king_white"))); piece = kingW; } if (piece == null) { if (i%2 == 0) { if (j%2 == 0) { btn.setBackground(new Color(235,199,158)); } else { // dark color btn.setBackground(new Color(92,51,23)); } } else { if (j%2 == 0) { // dark color btn.setBackground(new Color(92,51,23)); } else { btn.setBackground(new Color(235,199,158)); } } btn.setBorderPainted(false); btn.setOpaque(true); btn.addActionListener(this); board[i][j] = btn; this.add(btn); continue; } if (i%2 == 0) { if (j%2 == 0) { piece.setBackground(new Color(235,199,158)); } else { // dark color piece.setBackground(new Color(92,51,23)); } } else { if (j%2 == 0) { // dark color piece.setBackground(new Color(92,51,23)); } else { piece.setBackground(new Color(235,199,158)); } } piece.setBorderPainted(false); piece.setOpaque(true); piece.addActionListener(this); board[i][j] = piece; this.add(piece); } } }