text
stringlengths
14
410k
label
int32
0
9
@Override public void run() { t1 = new Date(); try { serverSocket = new DatagramSocket(514); receiveData = new byte[1024]; scoresTimout = new Date(); outOfOrderCall = false; } catch (SocketException e) { Logger.getLogger(SyslogServer.class.getName()).log(Level.SEVERE, null, e); } try { while (true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); sentence = new String(receivePacket.getData()); /*scoresNewSentence = new Date(); System.err.println("0"); if (!scores.isEmpty() && abs(scoresNewSentence.getTime() - scoresTimout.getTime()) > 10000) { System.err.println("1"); scores.clear(); long xx = abs(scoresNewSentence.getTime() - transfertest1.getTime()); System.out.println(xx + " " + "Scores DATA Succesfully Cleared"); } System.err.println("2"); scoresTimout = new Date();*/ System.err.println(sentence); row = sentence.split(","); scores.add(row); testing(row, scores); typeAppel = 1; } } catch (IOException e) { Logger.getLogger(SyslogServer.class.getName()).log(Level.SEVERE, null, e); } }
3
public FieldAnalyzer(ClassAnalyzer cla, FieldInfo fd, ImportHandler i) { clazz = cla; imports = i; modifiers = fd.getModifiers(); type = Type.tType(fd.getType()); fieldName = fd.getName(); constant = null; this.isSynthetic = fd.isSynthetic(); this.isDeprecated = fd.isDeprecated(); if (fd.getConstant() != null) { constant = new ConstOperator(fd.getConstant()); constant.setType(type); constant.makeInitializer(type); } }
1
@Override public void onClick(MouseEvent event, int x, int y){ editPanel.setVisible(false); if (selectedAnim != null){ for (ImageData iData : MainWindow.MAIN_WINDOW.getSheetData().getAllImageData()){ if (iData.getRect() != null && iData.getRect().contains(x, y)){ selectedFrame = iData; editPanel.setVisible(true); break; } } } if (selectedFrame != null && event.isControlDown()){ if (selectedAnim.getFrames().contains(selectedFrame)){ doFrameAction("REMOVE"); } else { doFrameAction("ADD"); } } }
7
public void createGraph(){ Scanner console = new Scanner(System.in); String fileName; if (gSize != 0) clearGraph(); Scanner infile = null; try{ System.out.print("Input file name for nodes: "); fileName = console.nextLine(); System.out.println(); infile = new Scanner(new FileReader(fileName)); } catch (FileNotFoundException fnfe){ System.out.println(fnfe.toString()); System.exit(0); } gSize = infile.nextInt(); //get the number of vertices for (int index = 0; index < gSize; index++){ int vertex = infile.nextInt(); String name = infile.next(); int adjacentVertex = infile.nextInt(); while (adjacentVertex != -999){ graph[vertex].insertLast(adjacentVertex); adjacentVertex = infile.nextInt(); } } }
4
@SuppressWarnings("resource") public final void registModule() { try { Socket clientSocket = null; DataInputStream reader = null; DataOutputStream writer = null; try { logger.info("正在连接..." + Setting.str_MalayansIP + ":" + Setting.int_DataInPort); clientSocket = new Socket( Setting.str_MalayansIP, Setting.int_DataInPort); reader = new DataInputStream(clientSocket.getInputStream()); writer = new DataOutputStream(clientSocket.getOutputStream()); } catch (Exception e) { logger.warning("链接创建失败!"); return; } String jsonmodule = JSON.toJSONString(moduleInfo); writer.writeUTF(jsonmodule); writer.flush(); String jsonport = reader.readUTF(); port = JSON.parseObject(jsonport, Port.class); this.registRMI(); writer.writeUTF("ok!"); writer.flush(); } catch (JSONException e){ logger.warning("模块注册失败!"); return; } catch (RemoteException e) { logger.warning("模块注册失败!"); return; } catch (Exception e) { logger.info("模块注册成功!"); return; } }
4
@Override public boolean execute(WorldChannels plugin, CommandSender sender, Command command, String label, String[] args) { final Map<Flag, String> info = new EnumMap<Flag, String>(Flag.class); info.put(Flag.TAG, WorldChannels.TAG); if(sender.hasPermission(PermissionNode.SHOUT.getNode())) { // Set info of fields for formatting message and format final EnumMap<Field, String> shoutInfo = new EnumMap<Field, String>( Field.class); shoutInfo.put(Field.NAME, sender.getName()); String worldName = "", groupName = "", prefix = "", suffix = ""; if(sender instanceof Player) { worldName = ((Player) sender).getWorld().getName(); try { groupName = plugin.getChat().getPlayerGroups( (Player) sender)[0]; } catch(ArrayIndexOutOfBoundsException a) { // IGNORE } prefix = plugin.getChat().getPlayerPrefix(worldName, sender.getName()); suffix = plugin.getChat().getPlayerSuffix(worldName, sender.getName()); } shoutInfo.put(Field.WORLD, worldName); shoutInfo.put(Field.GROUP, groupName); shoutInfo.put(Field.PREFIX, prefix); shoutInfo.put(Field.SUFFIX, suffix); final StringBuilder sb = new StringBuilder(); String out = ""; for(int i = 0; i < args.length; i++) { sb.append(args[i] + " "); out = sb.toString(); } if(sb.length() > 0) { out = sb.toString().replaceAll("\\s+$", ""); } shoutInfo.put(Field.MESSAGE, out); plugin.getServer().broadcastMessage( WChat.parseString( plugin.getModuleForClass(ConfigHandler.class) .getShoutFormat(), shoutInfo)); } else { info.put(Flag.EXTRA, PermissionNode.SHOUT.getNode()); sender.sendMessage(Localizer.parseString( LocalString.PERMISSION_DENY, info)); } return true; }
5
public WorldSavedData loadData(Class par1Class, String par2Str) { WorldSavedData var3 = (WorldSavedData)this.loadedDataMap.get(par2Str); if (var3 != null) { return var3; } else { if (this.saveHandler != null) { try { File var4 = this.saveHandler.getMapFileFromName(par2Str); if (var4 != null && var4.exists()) { try { var3 = (WorldSavedData)par1Class.getConstructor(new Class[] {String.class}).newInstance(new Object[] {par2Str}); } catch (Exception var7) { throw new RuntimeException("Failed to instantiate " + par1Class.toString(), var7); } FileInputStream var5 = new FileInputStream(var4); NBTTagCompound var6 = CompressedStreamTools.readCompressed(var5); var5.close(); var3.readFromNBT(var6.getCompoundTag("data")); } } catch (Exception var8) { var8.printStackTrace(); } } if (var3 != null) { this.loadedDataMap.put(par2Str, var3); this.loadedDataList.add(var3); } return var3; } }
7
public int getSeat() { return seat; }
0
public static String escape(String string) { StringBuffer sb = new StringBuffer(); for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: sb.append(c); } } return sb.toString(); }
6
private void deal() { final List<Suit> suits = asList(Suit.Hearts,Suit.Diamonds,Suit.Spades,Suit.Clubs); final List<Face> faces = asList(Face.Nine,Face.Jack,Face.Queen,Face.King,Face.Ten,Face.Ace); List<Card> deck = new ArrayList<Card>(48); // Fill new Pinochle deck for (int i = 0; i < 2; i++) { // 2 of each card * for (Suit suit : suits) { // 4 of each suit * for (Face face : faces) { // 6 of each face = 48 cards deck.add(new Card(suit,face)); } } } // Shuffle deck Collections.shuffle(deck); // Deal out 12 cards to each player int from = 0; int to = 12; for (PinochlePlayer player : mP.getPlayers()) { player.setCards(deck.subList(from, to)); from += 12; to += 12; } }
4
public static boolean containsJavaFile(File file) { boolean containsJavaFile = false; if (file.isDirectory()) { File list[] = file.listFiles(); for (int i=0; i < list.length; ++i) { boolean ret = containsJavaFile(list[i]); if (ret) { return true; } } } else { if (file.getName().endsWith(".java")) { return true; } } return false; }
4
private void Remover_Button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Remover_Button1ActionPerformed try { if (NomeJogador_TextField2.getText().equals("")) { JOptionPane.showMessageDialog(null, "Selecione um jogador para remover!", "Alerta!", JOptionPane.WARNING_MESSAGE); } else { a.removeJogador(NomeJogador_TextField2.getText(), AnoNascimento_TextField2.getText(), Escola_ComboBox1.getSelectedItem().toString() + "-" + Equipa_ComboBox2.getSelectedItem().toString(), Escola_ComboBox1.getSelectedItem().toString()); NomeJogador_TextField2.setText(""); AnoNascimento_TextField2.setText(""); Jogadores_List2.clearSelection(); } } catch (HeadlessException ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_Remover_Button1ActionPerformed
2
private void load() { // Load main model, if file is present boolean haveOldData = false; File file = settings.getStaticFile(); try { FileInputStream reader = new FileInputStream(file); XmlModelAdapter xml = new XmlModelAdapter(); xml.readModel(reader, model); reader.close(); haveOldData = true; } catch (FileNotFoundException e) { System.err.println("Initial data file " + file + " is not found. Starting empty."); } catch (IOException e) { e.printStackTrace(); } if (haveOldData) { file = settings.getStatusFile(); try { FileReader reader = new FileReader(file); StatusFileModelAdapter adap = new StatusFileModelAdapter(); adap.updateStatuses(reader, model); reader.close(); } catch (FileNotFoundException e) { System.err.println("Status file " + file + " is not found. Assuming UNKNOWN for everything."); } catch (IOException e) { e.printStackTrace(); } model.fireModelReloaded(); } }
5
public static TileEntity createAndLoadEntity(NBTTagCompound var0) { TileEntity var1 = null; try { Class var2 = (Class)nameToClassMap.get(var0.getString("id")); if(var2 != null) { var1 = (TileEntity)var2.newInstance(); } } catch (Exception var3) { var3.printStackTrace(); } if(var1 != null) { var1.readFromNBT(var0); } else { System.out.println("Skipping TileEntity with id " + var0.getString("id")); } return var1; }
3
public static void main(String[] args) { World w = new World(); w.setAutoRepaint(false); Deer[] deerArray = new Deer[20]; for (int i = 0; i < 20; i++) { deerArray[i] = new Deer(w); } // now loop to do simulation for (int i = 0; i < 100; i++) { for (int d = 0; d < 20; d++) deerArray[d].act(); w.repaint(); try { Thread.sleep(1000); } catch (Exception ex) { } } }
4
private void updateArgs() { GameSize newSize; if (R8.isSelected()) { newSize = GameSize.C8; } else if (R7.isSelected()) { newSize = GameSize.C7; } else { newSize = GameSize.C6; } // Check if settings have changed and there is still a game active if (Game.getThis() != null) { if (Options.Size != newSize) { int Confirmation = JOptionPane.showConfirmDialog(this, "Changes will not affect the current game. Quit the current game and start a new one?", "Options Confirmation", JOptionPane.YES_NO_CANCEL_OPTION ); if (JOptionPane.NO_OPTION == Confirmation) { Options.Size = newSize; } else if (JOptionPane.YES_OPTION == Confirmation) { Options.Size = newSize; new Game(); } } } else { Options.Size = newSize; int Confirmation = JOptionPane.showConfirmDialog(this, "Start a new game?", "Options Confirmation", JOptionPane.YES_NO_OPTION); if (JOptionPane.YES_OPTION == Confirmation) { new Game(); } } }
7
public SessionFactory getSf() { return sessionFactory; }
0
public static final void renderLine(final int x0, final int y0, final int x1, final int y1, final float[] v) { final int dy=y1-y0; final int adx=x1-x0; final int base=dy/adx; final int sy=dy<0?base-1:base+1; int x=x0; int y=y0; int err=0; final int ady=(dy<0?-dy:dy)-(base>0?base*adx:-base*adx); v[x]*=Floor.DB_STATIC_TABLE[y]; for(x=x0+1; x<x1; x++) { err+=ady; if(err>=adx) { err-=adx; v[x]*=Floor.DB_STATIC_TABLE[y+=sy]; } else { v[x]*=Floor.DB_STATIC_TABLE[y+=base]; } } }
5
@Override public Properties getOutputProperties() { Properties properties = new Properties(); properties.put(NAME,getName()); if(startCapital!=null){ properties.put(Mortgages.TOTAL, startCapital.toString()); } properties.put(Mortgages.NRPAYED, Integer.toString(alreadyPayed)); if(capital!=null){ properties.put(Mortgages.CAPITAL_ACCOUNT,capital.getName()); } if(intrest!=null){ properties.put(Mortgages.INTREST_ACCOUNT,intrest.getName()); } return properties; }
3
public Kuuntelija(Pelaaja pelaaja) { this.pelaaja = pelaaja; }
0
public void setMobileLab(String mobileLab) { MobileLab = mobileLab; }
0
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); final Room room=mob.location(); int affectType=CMMsg.MSG_CAST_VERBAL_SPELL; if(auto) affectType=affectType|CMMsg.MASK_ALWAYS; if((success)&&(room!=null)) { CMMsg msg=CMClass.getMsg(mob,null,this,affectType,auto?"":L("^S<S-NAME> @x1 for an aura of mobility!^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); for(int i=0;i<room.numInhabitants();i++) { final MOB target=room.fetchInhabitant(i); if(target==null) break; msg=CMClass.getMsg(mob,target,this,affectType,L("Mobility is invoked upon <T-NAME>.")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } } } else { beneficialWordsFizzle(mob,null,L("<S-NAME> @x1, but nothing happens.",prayWord(mob))); return false; } return success; }
9
public static List<ABObject> Hit (ABObject bird, ABObject obs, List<ABObject> objects, List<Point> trajs) { // List of affected object List<ABObject> affectedList = new ArrayList<ABObject>(); affectedList.add(obs); // Regular Rectangle double ratio = obs.height / obs.width; // Red bird - lowest damage if (bird.getType() == ABType.RedBird) { // Falling if (ratio >= HIT_RATIO_THRESHOLD) { List<ABObject> temp = ABUtil.getSupportees(obs, objects, 1); List<ABObject> temp1 = ABUtil.getAllSupportees(temp, objects); affectedList.addAll(temp); affectedList.addAll(temp1); temp = ABUtil.getSupporters(obs, objects, 1); temp1 = ABUtil.getAllSupporter(temp, objects); affectedList.addAll(temp); affectedList.addAll(temp1); affectedList.addAll(GetNeighbour(obs, objects, false)); } else { List<ABObject> temp = ABUtil.getSupporters(obs, objects, 1); List<ABObject> temp1 = ABUtil.getAllSupporter(temp, objects); affectedList.addAll(temp); affectedList.addAll(temp1); } } else if (bird.getType() == ABType.YellowBird) { affectedList.add(obs); for (int i = 0; i < trajs.size(); i++) { Point traj = trajs.get(i); if (affectedList.size() <= 3) { for (int j = 0; j < objects.size(); j++) { ABObject x = objects.get(j); if (x.contains(traj) && !affectedList.contains(x)) affectedList.add(x); } } else break; } List<ABObject> temp = ABUtil.getSupportees(obs, objects, 1); List<ABObject> temp1 = ABUtil.getAllSupportees(temp, objects); affectedList.addAll(temp); affectedList.addAll(temp1); } for (int i = 0; i < affectedList.size(); i++) { //System.out.println(affectedList.get(i).id); } return affectedList; }
9
public void onTopic(String chan, IRCUserInfo u, String topic) { System.out.println(chan + " " + u.getNick() + " " + topic); if(isJoiningAChannel && u.getNick() == main.getNick()){ System.out.println("Topic received..."); //channels.add(new ChatChannel(chan, main, topic)); numChannelFlag--; if(numChannelFlag == 0){ isJoiningAChannel = false; System.out.println("Done.");}} }
3
public static boolean isValid(String value) { if (value == null || value.length() != 24) { return false; } value = value.toUpperCase(); for (int i = 0; i < value.length(); ++i) { char c = value.charAt(i); if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) { return false; } } return true; }
7
@Override public void run() { String firstMessage = ""; try { getStreams(); do { firstMessage = (String) input.readObject(); if (firstMessage.equals(Messages.REGISTER)) { registerUser(); } else if (firstMessage.equals(Messages.LOGIN)) { loginUser(); } else if (firstMessage.equals(Messages.CONTACTLIST)) { sendUserList(); } else if (firstMessage.equals(Messages.GETUSER)) { sendUser(); } else if (firstMessage.equals(Messages.LOGOUT)) { logout(); } else { output.writeObject("Error!! unknow message"); output.flush(); firstMessage = Messages.LOGOUT; } } while (!firstMessage.equals(Messages.LOGOUT)); } catch (IOException ioException) { System.err.println("Error in networking " + ioException.getMessage()); } catch (ClassNotFoundException classNotFoundException) { System.err.println("Error in networking " + classNotFoundException.getMessage()); } finally { if (username != null) { LogoutController logoutController = new LogoutController( sessions); logoutController.logout(username); } close(); } }
9
public static void main(String[] args) { for(int i=0; i<=10; i++ ) { if( i%2 == 0) System.out.println(i); } System.out.println(); for(int i=10; i>0; i-- ) { if( i%2 == 0) System.out.println(i); } }
4
static void download(File url, File local) throws IOException { logger.info("Installing :" + url + " -> " + local); File tmp = File.createTempFile(local.getName() + "-", ".part", local.getParentFile()); tmp.deleteOnExit(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(url)); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(tmp)); byte data[] = new byte[4096]; int len = 0; while ((len = in.read(data, 0, data.length)) >= 0) { bout.write(data, 0, len); } bout.close(); in.close(); tmp.renameTo(local); }
1
public boolean setJTableRow(String[] result, String name) { // TODO game={key1:value;key2:value...},game={key1:value;key2:value...} Component comp = fetchComponent(null, name); if (comp instanceof JTable) { JTable table = (JTable) comp; int count =0; for (String game : result) { for (int j = 0; j < table.getColumnCount(); j++) { String cName = table.getColumnName(j); String[] tempResults = game.replace("}", "").split(";"); // Search for value to place for (int k = 0; k < tempResults.length; k++) { if (tempResults[k].contains(cName)) { String value = tempResults[k].split(":")[1]; table.setValueAt(value, count, j); break; } } } count++; } return true; } return false; }
5
public static double futureDirection(int move) { scenarios[move].setNext(); double down = scenarios[move].move(0, false); scenarios[move].setNext(); double left = scenarios[move].move(1, false); scenarios[move].setNext(); double up = scenarios[move].move(2, false); scenarios[move].setNext(); double right = scenarios[move].move(3, false); double largeScore = 0; double largest = Math.max(Math.max(down, left), Math.max(up, right)); if (largest == down) largeScore = scenarios[move].move(0, false); if (largest == left) largeScore = scenarios[move].move(1, false); if (largest == up) largeScore = scenarios[move].move(2, false); if (largest == right) largeScore = scenarios[move].move(3, false); return largeScore; }
4
@Override public boolean load(File file, SSGlobals glob) throws ParserConfigurationException, IOException, SAXException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { if (!(glob.getConfig() instanceof IChangeableConfig)) { return false; } IChangeableConfig config = (IChangeableConfig) glob.getConfig(); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file); doc.getDocumentElement().normalize(); NodeList configList = doc.getElementsByTagName(ISaveConstants.CONFIG_TAG); if (configList.getLength() == 1) { Node configNode = configList.item(0); if (configNode.getNodeType() == Node.ELEMENT_NODE) { Element configElement = (Element) configNode; for (Method method : glob.getConfig().getClass().getMethods()) { if (method.getDeclaringClass().equals(Config.class)) { Node item = configElement.getElementsByTagName(method.getName()).item(0); if (item != null) { String value = item.getTextContent(); int beginIndex = 3; if (method.getReturnType().equals(boolean.class)||method.getReturnType().equals(Boolean.class) ) { beginIndex = 2; } String name = "set" + method.getName().substring(beginIndex); try { Method setMethod = config.getClass().getMethod(name, method.getReturnType()); Object[] args = new Object[1]; args[0] = ReflectionUtils.cast(value, method.getReturnType()); setMethod.invoke(config, args); } catch (NoSuchMethodException e) { System.out.println("e = " + e); } } } } } } return false; //To change body of implemented methods use File | Settings | File Templates. }
9
public GeoJsonObject getGeometry() { return geometry; }
0
private boolean checkDiagonalDescending(CellState player, int col, int row) { // diagonal-\ // check winLength-in-a-row int winCounter = 0; int x = 0; int y = 0; for (int i = -model.getWinLength() - 1; i < model.getWinLength(); ++i) { x = col + i; // FIXME wtf?? i+1?? y = row + i + 1; if (isInsideBoard(x, y)) { if (model.getCell(x, y) == player) { ++winCounter; } else { winCounter = 0; } if (winCounter == model.getWinLength()) { return true; } } } return false; }
4
public void deleteMiddleNode(LinkedNode node){ if(node==null || node.nextNode==null){ return; } LinkedNode current = node; while(current.nextNode !=null){ current.value = current.nextNode.value; if(current.nextNode.nextNode==null){ current.nextNode=null; } else{ current=current.nextNode; } } }
4
public Date getBuiltOn() { return builtOn; }
0
public InputStream getResourceAsStream(String name) { System.out.println("getResourceAsStream >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); InputStream ret = super.getResourceAsStream(name); if(ret == null) { JarFile jar = null; ZipEntry ze = null; Enumeration enumeration = jarFiles.elements(); while (enumeration.hasMoreElements() && ze == null) { jar = (JarFile) enumeration.nextElement(); //System.out.println("searching for " + pathName + " in " + jar.getName()); ze = jar.getEntry(name); if (ze != null) { System.out.println("found:" + name + " in " + jar.getName()); try { ret = jar.getInputStream(ze); System.out.println("ret:" + ret); } catch (IOException ex) { ex.printStackTrace(); } } } } return ret; }
5
public long[] keySetArray(long from, long to) { TreeSet<Long> t = new TreeSet<Long>(keySet()); if (from == 0 && to == Reconciler.getDatamax()) return Reconciler.toArray(t); return Reconciler.toArray(t.subSet(from, to)); }
2
public static void main(String[] args) { ServerSocket server = null; int port = DEFAULT_PORT; if (args.length > 0) { try { port = Integer.parseInt(args[0]); if (port < 0 || port >= 65535) { LOGGER.log(Level.SEVERE, "port must between 0 ~ 65535"); return; } } catch (NumberFormatException e) { //use default port } } try { server = new ServerSocket(port); LOGGER.log(Level.INFO, "server started at: " + server); //listening forever while (true) { // Blocks until a connection occurs: Socket socket = server.accept(); LOGGER.log(Level.INFO, "connection " + (count++) + " accepted: " + socket); //use independent i/o thread Thread readThread = new ReadThread(socket.getInputStream()); readThread.start(); Thread writeThread = new WriteThread(socket.getOutputStream()); writeThread.start(); //wait for input and output try { readThread.join(); writeThread.join(); LOGGER.log(Level.INFO, "IO finished, closing tcp..."); socket.close(); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (IOException e) { //server startup problem e.printStackTrace(); try { if (null != server) server.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RGBColor other = (RGBColor) obj; if (b != other.b) return false; if (g != other.g) return false; if (r != other.r) return false; return true; }
6
public void closeConnection(){ try { this.clone(); } catch (CloneNotSupportedException ex) { Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex); } }
1
public static List<Aikaslotti> haeAikaslotit() throws NamingException, SQLException { Yhteys tietokanta = new Yhteys(); Connection yhteys = tietokanta.getYhteys(); String sql = "SELECT * FROM Aikaslotti"; PreparedStatement kysely = yhteys.prepareStatement(sql); ResultSet rs = kysely.executeQuery(); List<Aikaslotti> aikaslotit = new ArrayList<Aikaslotti>(); while(rs.next()) { Aikaslotti a = new Aikaslotti(rs); aikaslotit.add(a); } try { rs.close(); } catch (Exception e) {} try { kysely.close(); } catch (Exception e) {} try { yhteys.close(); } catch (Exception e) {} return aikaslotit; }
4
public void sendOnlineUsers (List<String> clients) { String clientString = ""; for (String user : clients) { clientString = clientString + user+", "; } send("ONLINE# " + clientString); }
1
public void stop() { if (frame != null) frame.dispose(); }
1
public Usuario validarLoginUser(String user, String password) throws Throwable { String jsql = "SELECT u FROM Usuario u WHERE u.login=:loginname and u.status='true'"; try { Query query = HibernateUtil.getSession().createQuery(jsql); query.setParameter("loginname", user); List l = query.list(); if (l == null || l.isEmpty() || l.size() > 1) { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN,"Usuário desativado", "Caso queira desativar contacte o admnistrador do Sistema."); FacesContext.getCurrentInstance().addMessage("add", msg); return null; } return (Usuario) l.get(0); } catch (Exception e) { e.printStackTrace(); return null; } }
4
private boolean isKeyWord(String token, ArrayList<String> keywordList) { for (int i = 0; i < keywordList.size(); i++) { if (token.equals(keywordList.get(i))) { return true; } } return false; }
2
public void sendRunScript(int scriptId, Object... params) { try { OutputStream stream = new OutputStream(); stream.writePacketVarShort(50); String parameterTypes = ""; if (params != null) { for (int count = params.length - 1; count >= 0; count--) { if (params[count] instanceof String) parameterTypes += "s"; // string else parameterTypes += "i"; // integer } } stream.writeString(parameterTypes); if (params != null) { int index = 0; for (int count = parameterTypes.length() - 1; count >= 0; count--) { if (parameterTypes.charAt(count) == 's') stream.writeString((String) params[index++]); else stream.writeInt((Integer) params[index++]); } } stream.writeInt(scriptId); stream.endPacketVarShort(); session.write(stream); System.out.println("scriptid: " + scriptId); return; } catch (Exception e) { e.printStackTrace(); } }
7
public void setDistance(Distance distance) { for(int i=0;i<_distances.length;++i) { if(_distances[i] == distance) { _setDistance(i); return; } } }
2
public void setSymtab(Symtab st) { SymtabEntry funcEntry = st.lookup(id.toString()); if (funcEntry == null) Main.error("The function " + id.toString() + " does not exist"); Symtab table = st.lookup(id.toString()).getTable(); int plLength; if (pl == null) plLength = 0; else plLength = pl.getLength(); if (table.size() != plLength) Main.error("Improper number of arguments for " + id.toString()); if (pl != null) { pl.setScope(scope); pl.checkType(st, table, pl.getLength()); } }
4
public static String vectorCaddieDeletionToHTML(Vector<Caddie> rs){ if (rs.isEmpty()) return ""; String toReturn = "<TABLE BORDER='1' width=\"1000\">"; toReturn+="<CAPTION>Ces places ne sont pas réservables car la représentation a déjà eu lieu :</CAPTION>"; toReturn+="<TR>"; toReturn+="<TH> <i>Reservation n°</i></TH>"; toReturn+="<TH> <i>Spectacle</i> </TH><TH> <i>Date représentation</i></TH>"; toReturn+="<TH> <i> Zone </i></TH>"; toReturn+="</TR>"; for (int i = 0; i < rs.size(); i++) { toReturn+="<TR>"; toReturn+="<TH> "+(i+1)+"</TH>"; toReturn+="<TH>"+rs.elementAt(i).getNom()+" </TH><TH> "+rs.elementAt(i).getDate()+"</TH>"; toReturn+="<TH> "+rs.elementAt(i).getZone()+" ("+rs.elementAt(i).getNomZ()+")</TH>"; toReturn+="</TR>"; } return toReturn+"</TABLE>"; }
2
public void update() throws MaltChainedException { // Retrieve the address value final AddressValue arg1 = addressFunction.getAddressValue(); // if arg1 or arg2 is null, then set a NO_NODE null value as feature value if (arg1.getAddress() == null ) { featureValue.setIndexCode(table.getNullValueCode(NullValueId.NO_NODE)); featureValue.setSymbol(table.getNullValueSymbol(NullValueId.NO_NODE)); featureValue.setNullValue(true); } else { // Unfortunately this method takes a lot of time arg1.getAddressClass().asSubclass(org.maltparser.core.syntaxgraph.node.DependencyNode.class); // Cast the address arguments to dependency nodes final DependencyNode node = (DependencyNode)arg1.getAddress(); HashSet<String> uDeprels = new HashSet<String>(); /*if (!node.isRoot()) { if (node.hasHead()) { int indexCode = node.getHeadEdge().getLabelCode(column.getSymbolTable()); String symbol = column.getSymbolTable().getSymbolCodeToString(indexCode); if (column.getType() == ColumnDescription.STRING) { featureValue.update(indexCode, symbol, false, 1); } else { castFeatureValue(symbol); } } else { featureValue.update(column.getSymbolTable().getNullValueCode(NullValueId.NO_VALUE), column.getSymbolTable().getNullValueSymbol(NullValueId.NO_VALUE), true, 1); } } else { featureValue.update(column.getSymbolTable().getNullValueCode(NullValueId.ROOT_NODE), column.getSymbolTable().getNullValueSymbol(NullValueId.ROOT_NODE), true, 1); }*/ if (labelsetOfRelation == LabelSetOfRelation.DEPS) { for(DependencyNode child:node.getLeftDependents()) uDeprels.add(child.getHeadEdgeLabelSymbol(column.getSymbolTable())); for(DependencyNode child:node.getRightDependents()) uDeprels.add(child.getHeadEdgeLabelSymbol(column.getSymbolTable())); } else if (labelsetOfRelation == LabelSetOfRelation.LDEPS) { for(DependencyNode child:node.getLeftDependents()) uDeprels.add(child.getHeadEdgeLabelSymbol(column.getSymbolTable())); } else if (labelsetOfRelation == LabelSetOfRelation.RDEPS) { for(DependencyNode child:node.getRightDependents()) uDeprels.add(child.getHeadEdgeLabelSymbol(column.getSymbolTable())); } if(uDeprels.size() !=0) { String uDeprelStr = uDeprels.toString(); featureValue.setIndexCode(table.addSymbol(uDeprelStr)); featureValue.setSymbol(uDeprelStr); featureValue.setNullValue(false); } else { featureValue.update(table.getNullValueCode(NullValueId.NO_VALUE), table.getNullValueSymbol(NullValueId.NO_VALUE), true, 1); } } featureValue.setValue(1); // featureValue.setKnown(true); }
9
public static Socket getSocket(Neighbor from, Neighbor to) throws IOException { if (!sockets.containsKey(to)){ // crear socket Setup.println("[Broadcaster.getSocket] Creando socket a " + to.getAddr().getHostAddress()); Socket socket = new Socket(to.getAddr(), to.getPort()); sockets.put(to, socket); // enviar hello try { Setup.println("[Broadcaster.getSocket] Enviando hello a " + to.getAddr().getHostAddress()); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeBytes(getHelloMsg(from)); out.flush(); // sock.close(); } catch (Exception e) { Setup.println("[Broadcaster.getSocket] No es posible enviar HELLO a" + to.getAddr().getHostAddress()); } return socket; } Setup.println("[Broadcaster.getSocket] Reutilizando socket a " + to.getAddr().getHostAddress()); return sockets.get(to); }
2
@RequestMapping(value = "/hall-event-sponsor-list/{hallEventId}", method = RequestMethod.GET) @ResponseBody public PartnerListResponse hallEventSponsorList( @PathVariable(value = "hallEventId") final String hallEventIdStr ) { return typedPartnerList(hallEventIdStr, PartnerRole.SPONSOR_ROLE_NAME); }
0
public static Cons allEquivalentRelations(NamedDescription relation, boolean reflexiveP) { { MemoizationTable memoTable000 = null; Cons memoizedEntry000 = null; Stella_Object memoizedValue000 = null; if (Stella.$MEMOIZATION_ENABLEDp$) { memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_ALL_EQUIVALENT_RELATIONS_MEMO_TABLE_000.surrogateValue)); if (memoTable000 == null) { Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_ALL_EQUIVALENT_RELATIONS_MEMO_TABLE_000, "(:MAX-VALUES 500 :TIMESTAMPS (:META-KB-UPDATE))"); memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_ALL_EQUIVALENT_RELATIONS_MEMO_TABLE_000.surrogateValue)); } memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), relation, ((Context)(Stella.$CONTEXT$.get())), (reflexiveP ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER), Stella.MEMOIZED_NULL_VALUE, -1); memoizedValue000 = memoizedEntry000.value; } if (memoizedValue000 != null) { if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) { memoizedValue000 = null; } } else { memoizedValue000 = Logic.filterOutUnnamedDescriptions(LogicObject.allEquivalentCollections(relation, reflexiveP)); if (Stella.$MEMOIZATION_ENABLEDp$) { memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000); } } { Cons value000 = ((Cons)(memoizedValue000)); return (value000); } } }
7
public void populationDistribution(){ int[][] species = new int[library.size()][2]; for(int i=0; i<bucket.size(); i++){ Molecule M = bucket.get(i); species[M.getID()][0] = M.getID(); species[M.getID()][1]++; } int k; for(int j=0; j<library.size(); j++){ int a = species[j][1]; k=j; while(k>0 && species[k-1][1] > a){ species[k][1] = species[k-1][1]; k--; } species[k][1]=a; } for(int j=0; j<library.size(); j++){ System.out.printf("%d\n", species[j][1]); } }
5
private void broadcastChange(Slot<T> slot) { for(DraftListener<? super T> crnt : allListeners) { crnt.onChange(slot); } }
2
public static XStoreFault getInstance(String faultCode, String faultString) { XStoreFault xStoreFault = new XStoreFault(); xStoreFault.setFaultCode(faultCode); xStoreFault.setFaultString(faultString); return xStoreFault; }
0
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { Cliente c; String cpf; int tam; cpf = jTextField1.getText(); tam = cpf.length(); if ((tam != 11 && !cpf.matches("[0-9]+")) || tam == 0) { warningLabel.setText("<html>CPF Inválido!!! <br />O CPF deve ter 11 dígitos e apenas números.</html>"); } else if (tam != 11) { warningLabel.setText("<html>CPF Inválido!!! <br />O CPF deve ter 11 dígitos.</html>"); } else if (!cpf.matches("[0-9]+")) { warningLabel.setText("<html>CPF Inválido!!! <br />O CPF deve conter apenas números.</html>"); } else { c = new Cliente(); c.setCpf(jTextField1.getText()); c.setNome("Zeh"); c.setEndereco("Buraco Negro, 42"); setVisible(false); if (cpf.equals("00000000000")) { new MenuFuncionario().setVisible(true); } else { new MenuCliente(c).setVisible(true); } } } }//GEN-LAST:event_jTextField1KeyPressed
7
public static boolean streetAddress(String address){ if(address.matches("(\\d)+(\\s)[a-zA-Z\\s\\.]+")&&address.length()<100) return true; return false; }
2
public boolean contains(double d) { if (lowerUndefined) return (upperOpen ? d < upperBound : d <= upperBound); else if (upperUndefined) return (lowerOpen ? d > lowerBound : d >= lowerBound); else return (upperOpen ? d < upperBound : d <= upperBound) && (lowerOpen ? d > lowerBound : d >= lowerBound); }
7
public void go() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { //System.out.println("Bite!!!"); Stat eaterAttack = eater.getConstStats().get(StatType.C_ATTACK); Stat eaterHunger = eater.getDynamicStats().get(StatType.D_HUNGER); Stat victimHealth = victim.getDynamicStats().get(StatType.D_HEALTH); victimHealth.addToValue(-eaterAttack.getValue()); eaterHunger.addToValue(-eaterAttack.getValue() * EATING_EFFICIENCY); eater.getDynamicStats().get(StatType.D_EATEN).addToValue(eaterAttack.getValue() * EATING_EFFICIENCY); }
0
public void sort(Comparable[] arr) { if (arr == null || arr.length <= 1) return; int size = arr.length; int h = 1; while (h < size / 3) h = 3 * h + 1; // 1, 4, 13 ............ while (h >= 1) { for (int k = h; k < size; k += h) { int index = k; Comparable tmp = arr[k]; while (index - h >= 0 && tmp.compareTo(arr[index-h]) < 0) { arr[index] = arr[index - h]; index -= h; } arr[index] = tmp; } h /= 3; } }
7
public Boolean userNameExists(String username){ try { cs = con.prepareCall("{call GET_USERNAME(?)}"); cs.setString(1, username); if(!cs.executeQuery().next()){ return false; } } catch (SQLException e) { e.printStackTrace(); } return true; }
2
public void tick(JFrame frame) { if (game_over) { board.resetBoard(); this.timer.stop(); activeTetromino = null; frame.repaint(); return; } if (this.running) { if (firstFrame) { lastTime = System.nanoTime(); frameAverageCounter = 1; firstFrame = false; this.activateNextTetromino(); frame.repaint(); } this.hold_panel.setType(this.holdingPiece() ? this.getHoldPiece(): Tetromino.Type.X); if (this.activeTetromino.isLocked()) { this.activeTetromino.addTo(board); this.lastClearedCounter++; if (this.lastClearedCounter % 50 == 0) { int cleared = this.board.clearLines(); this.lines += cleared; this.score += Math.pow(2, cleared) * 1000; this.level = this.lines / 10 + 1; if (!this.activateNextTetromino()) this.game_over = true; } } this.dropCounter++; if ((this.dropCounter % Math.max(50 - this.level, 5)) == 0) { dropCounter = 1; activeTetromino.drop(board); } frameAverageCounter = (frameAverageCounter + 1) % 15; if (frameAverageCounter == 0) { framerate = -15e9 / (lastTime - (lastTime = System.nanoTime())); } frame.repaint(); } }
9
private void writeBody(OutputStreamWriter out, List<PackageCoverageStatistics> stats, PackageCoverageStatistics totalStats) throws IOException { out.append("<table class=\"report\" id=\"packageResults\">\n"); out.append("<thead><tr> <td class=\"heading\">Package</td> <td class=\"heading\"># Procedures</td> <td class=\"heading\">Line Coverage</td></tr></thead>\n"); out.append("<tbody>\n"); out.append(String.format(" <tr class=\"total\"><td class=\"title\">All Packages</td><td class=\"value\">%d</td><td><table cellpadding=\"0px\" cellspacing=\"0px\" class=\"percentgraph\"><tr class=\"percentgraph\"><td align=\"right\" class=\"percentgraph\" width=\"40\">%d%%</td><td class=\"percentgraph\"><div class=\"percentgraph\"><div class=\"greenbar\" style=\"width:%dpx\"><span class=\"text\">%d/%d</span></div></div></td></tr></table></td></tr>%n", totalStats.getNumProcedures(), totalStats.getPercentCovered(), totalStats.getPercentCovered(), totalStats.getLinesCovered(), totalStats.getTotalLines())); out.append("\n"); for (PackageCoverageStatistics stat : stats) { if (stat.getLinesCovered() < 0 || stat.getTotalLines() < 0) { // Invalid stat objects should be treated as having no coverage stat = new PackageCoverageStatistics(stat.getHtmlFileName(), stat.getPackageName(), 0, 0, 0); } String packageName = stat.getPackageName(); if (packageName == null || stat.getPackageName().trim().equals("")) { if (stat.getHtmlFileName() == null || stat.getHtmlFileName().trim().equals("")) { packageName = "<name not found>"; } else { packageName = stat.getHtmlFileName().substring(0, stat.getHtmlFileName().lastIndexOf('.')); } } out.append(String.format(" <tr><td><a href=\"%s\">%s</a></td><td class=\"value\">%d</td><td><table cellpadding=\"0px\" cellspacing=\"0px\" class=\"percentgraph\"><tr class=\"percentgraph\"><td align=\"right\" class=\"percentgraph\" width=\"40\">%d%%</td><td class=\"percentgraph\"><div class=\"percentgraph\"><div class=\"greenbar\" style=\"width:%dpx\"><span class=\"text\">%d/%d</span></div></div></td></tr></table></td></tr>%n", stat.getHtmlFileName(), packageName, stat.getNumProcedures(), stat.getPercentCovered(), stat.getPercentCovered(), stat.getLinesCovered(), stat.getTotalLines())); } out.append("</tbody>\n"); out.append("</table>\n"); }
7
@Test(expected=IllegalNumberOfOperandsException.class) public void testIllegalNumberOfOperandsPlus() { calculator.pushOperand(7.0); calculator.pushPlusOperator(); calculator.evaluateStack(); //assertTrue("An IllegalNumberOfOperandsException should heve been thrown here.", false); }
0
private <X,Y> void addToMapSet(Map<X, Set<Y>> target, X layoutFile, Y callback) { if (target.containsKey(layoutFile)) target.get(layoutFile).add(callback); else { Set<Y> callbackSet = new HashSet<Y>(); callbackSet.add(callback); target.put(layoutFile, callbackSet); } }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Patient other = (Patient) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (ssn == null) { if (other.ssn != null) return false; } else if (!ssn.equals(other.ssn)) return false; return true; }
9
public int calculate(int a, int b) { return a + b; }
0
private String convert2Java(final String program, final boolean hasStatus) { StringBuilder b = new StringBuilder(); Map<String, Integer> methodMap = Utils.getMethods(program); b.append(convertMethod2Java(program, methodMap, false, hasStatus)); b.append("}"); for (Map.Entry<String, Integer> entry : methodMap.entrySet()) { if (hasStatus) { b.append("private static void meth").append(entry.getValue()).append(" (StatusState s) {byte add;"); } else { b.append("private static void meth").append(entry.getValue()).append(" (State s) {byte add;"); } b.append(convertMethod2Java(entry.getKey(), methodMap, true, hasStatus)).append("}"); } return b.toString(); }
2
private static int decodeConnectionId(byte connectionId) { return (int) (connectionId < 0 ? connectionId - 2*Byte.MIN_VALUE : connectionId); }
1
public static int versionLaterThan(String v1, String v2) { if (v1 == null) { return 1; } if (v2 == null) { return -1; } String[] v1Decomp = formatVersion(v1).split("\\."); String[] v2Decomp = formatVersion(v2).split("\\."); int shortestLength = Math.min(v1Decomp.length, v2Decomp.length); for (int i = 0; i < shortestLength; i++) { if (Integer.parseInt(v1Decomp[i]) < Integer.parseInt(v2Decomp[i])) { return -1; } if (Integer.parseInt(v1Decomp[i]) > Integer.parseInt(v2Decomp[i])) { return 1; } } if (v1Decomp.length < v2Decomp.length) { return -1; } if (v1Decomp.length > v2Decomp.length) { return 1; } return 0; }
7
public String get() throws IOException, JSONException, NullPointerException { try{ long StartTime = System.currentTimeMillis(); String keyvalue = null; if(Table == null) { System.err.println("Table name not set"); } else if(ColumnFamily == null) { System.err.println("Column family not set"); } else{ keyvalue = read(Table); if(keyvalue.contains(ColumnFamily)) { String DBloc = getDBloc(); Fetch(DBloc); } else{ System.err.println("Column family does not exist"); } } long endTime = System.currentTimeMillis(); System.out.println("Time Taken : "+(endTime-StartTime)+" ms"); } catch(Exception e) { e.printStackTrace(); } return Result; }
4
@Override public String adiciona(HttpServletRequest request, HttpServletResponse response) { String nome = request.getParameter("nome"); Empresa e1 = new Empresa(nome); new EmpresaDAO().adiciona(e1); request.setAttribute("nome", nome); return "/WEB-INF/paginas/novaEmpresa.jsp"; }
0
private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed // TODO add your handling code here: int returnVal = openFileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = openFileChooser.getSelectedFile(); ProjectStore project = ProjectStore.getInstance(); // check if stakeholders data is encrypted if (project.isEncrypted(file.getPath())) { ArrayList<Stakeholder> tmpStakeholders; // prompt for passphrase passwordPromptWindow(); tmpStakeholders = project.openEncryptedProjectFile(file.getPath(), password); // check if password is correct if (tmpStakeholders != null) { Stakeholders = tmpStakeholders; updateStakehodlerList(); isEncrypted = true; } else { // TODO implement better user notification of bad password System.out.println("HMAC failed for file and password of " + password); } } else { // open project as normal this.Stakeholders = project.openProjectFile(file.getPath()); updateStakehodlerList(); } //testFrame.updateModel(Stakeholders); //} else { // System.out.println("File access cancelled by user."); } }//GEN-LAST:event_openMenuItemActionPerformed
3
@Override public List<Status<?>> getStatuses() { /* * COMMENTS: I moved this code here from onStatusUpdateRequested. */ int speed = fanGpioUtility.getFanSpeed(); List<Status<?>> statusList = new ArrayList<Status<?>>(); if (speed == 0) { statusList.add(Status.newStatus("Power On", Type.BOOLEAN, false)); } else { statusList.add(Status.newStatus("Power On", Type.BOOLEAN, true)); if(speed == 1) { statusList.add(Status.newStatus("Speed", Type.STRING, "Low")); } else if(speed == 2) { statusList.add(Status.newStatus("Speed", Type.STRING, "Medium")); } else if(speed == 3) { statusList.add(Status.newStatus("Speed", Type.STRING, "High")); } } return statusList; }
7
@Override public String toString() { String main1=main.replaceAll("\n","\\\\n"); char delimiter='|'; String other=""; if (subType!=null) { other=delimiter+subType; } if (enamexType.equals("SP")) { return("("+main1+delimiter+startOffset+delimiter+enamexType+")"); } return("("+main1+delimiter+startOffset+delimiter+enamexType+"-"+position+other+")"); }
2
void addText(String text) { if (currentStringArray.size() == 0) { charCount = 0; } if (isParSave && !_endnoteMode) { int par = parSkip; while (par > 0) { _pagePrinter.write((String) null); par--; } isParSave = false; } if ((isParSave && _endnoteMode)) { int par = endParSkip; while (par > 0) { _pageCollector.write((String) null); par--; } isParSave = false; } boolean endNoteWillHappen = false; if (prepareReference) { endNoteWillHappen = true; current += "[" + _refNum + "]" + " "; prepareReference = false; } current += text; if (endNoteWillHappen) { endWord(); endNoteWillHappen = false; } }
9
boolean WESTdiagnoalHasCraftedBlock(Location startLocation) { boolean res = false; // Check WEST 45 degrees ========================================================= // Check if there is a valid crafted ceiling block in 45 degrees upwards to the player within given distance Location checkedLoc = new Location(startLocation.getWorld(), startLocation.getX(), startLocation.getY(), startLocation.getZ()); // set start of check to the block 45 degrees above players head in checked direction checkedLoc.setY(checkedLoc.getY() + 2); checkedLoc.setX(checkedLoc.getX() - 1); int checkLimitY = (int)checkedLoc.getY() + Arctica.checkRadius; for(int checkedLocY = (int)checkedLoc.getY(); checkedLocY <= checkLimitY; checkedLocY++, checkedLoc.setY(checkedLoc.getY() + 1), checkedLoc.setX(checkedLoc.getX() - 1)) // go one block up and WEST { //if(Arctica.debug) plugin.getServer().broadcastMessage(ChatColor.AQUA + "Gecheckt: " + checkedLoc.getBlock().getX() + " " + checkedLoc.getBlock().getY() + " " + checkedLoc.getBlock().getZ()); if (!checkedLoc.getBlock().isEmpty()) { if(craftedBlocksIDlist.contains(checkedLoc.getBlock().getTypeId())) // its a valid crafted block { //if(Arctica.debug) plugin.getServer().broadcastMessage(ChatColor.AQUA + "WEST_TOP45 Block gefunden: " + checkedLoc.getBlock().getType().toString()); res = true; break; } } } return (res); }
3
private boolean isObserverMatch(String key,String url) { String[] keya= key.split("/"); String[] urla= url.split("/"); for (int i=1;i<keya.length;i++) { // we need to match each part all must be valid String skey = keya[i]; if (urla.length-1<i) return false; String surl = urla[i]; // if we don't have a surl we always fail if (surl==null) { return false; } else if (!skey.equals("*") && !skey.equals(surl)) { return false; } } return true; }
5
public void itemStateChanged(ItemEvent evt){//***Event if(evt.getStateChange() == ItemEvent.SELECTED) { if (evt.getSource() == cBoxUnlead) { que.setUserChoice(Q1_GasType.UNLEAD); }else if (evt.getSource() == cBoxPlus) { que.setUserChoice(Q1_GasType.PLUS_UNLEAD); }else if (evt.getSource() == cBoxPremium) { que.setUserChoice(Q1_GasType.PREMIUM_UNLEAD); } else if (evt.getSource() == cBoxDiesel){ que.setUserChoice(Q1_GasType.DIESEL); } } }
5
public static void setGamePanel(Game panel) { instance.contentPanel.removeAll(); if (panel != null) { instance.contentPanel.add(panel, BorderLayout.CENTER); instance.repaint(); instance.revalidate(); } }
1
public Sphere(Location center, int radius) { this.center = center; this.radius = radius; for(int X = -radius; X < radius; X++) { for(int Y = -radius; Y < radius; Y++) { for(int Z = -radius; Z < radius; Z++) { if(Math.sqrt((X * X) + (Y * Y) + (Z * Z)) <= radius) { Block block = center.getWorld().getBlockAt(X + center.getBlockX(), Y + center.getBlockY(), Z + center.getBlockZ()); sphere.add(block); } } } } }
4
@Override public Key next() { if (!hasNext()) throw new NoSuchElementException(); Key key = current.key; current = current.next; return key; }
1
public static int[][] rotate_right(int [][] matrix) { System.out.println("Rotating to right 90 degrees: "); int new_matrix [][] = new int [matrix.length][matrix.length]; int z = 0; for(int i=2; i >= 0; i--) { for(int j=0; j<=2; j++) { new_matrix[j][z] = matrix[i][j]; } z++; } for(int i=0; i < new_matrix.length; i++) { for(int j=0; j<new_matrix.length; j++) { System.out.print(new_matrix[i][j]); } System.out.println(); } return new_matrix; }
4
@Override public void onBrowserEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONMOUSEDOWN: if (!mouseDown) { mouseDown = true; CSSUtils.setStyleName(staticClass, this); } break; case Event.ONMOUSEUP: if (mouseDown) { mouseDown = false; CSSUtils.setStyleName(staticClass, this); } break; case Event.ONMOUSEOVER: if (!mouseOver) { mouseOver = true; CSSUtils.setStyleName(staticClass, this); } break; case Event.ONMOUSEOUT: if (mouseDown || mouseOver) { mouseDown = false; mouseOver = false; CSSUtils.setStyleName(staticClass, this); } } super.onBrowserEvent(event); }
9
public static String getAttribute(Element element, String key, String defaultRet) { return element.hasAttribute(key)? element.getAttribute(key):defaultRet; }
1
private String loadHeightmap() { if (details) System.out.println("Loading the heightmap."); File imageFile = new File("output/"+name+"/overviews/heightmap_overview.png"); if (imageFile.exists()) { try { BufferedImage heightmapImage = ImageIO.read(imageFile); if (heightmapImage.getWidth() == chunksX * MyzoGEN.DIMENSION_X && heightmapImage.getHeight() == chunksY * MyzoGEN.DIMENSION_Y) { for (int i = 0; i < chunksX * MyzoGEN.DIMENSION_X; i++) { for (int j = 0; j < chunksY * MyzoGEN.DIMENSION_Y; j++) { Color pixel = new Color(heightmapImage.getRGB(i, j)); double height = Utils.pixelToHeight(pixel); MyzoGEN.getOutput().setHeightAndFloor(new Point(i, j), Utils.roundToDecimals(height, 4)); } } } else return "BaseTerrainGenerator critical error - the loaded heightmap does not match the specified dimensions. Loaded file is: "+heightmapImage.getWidth()+"x"+heightmapImage.getHeight()+ "while the specified dimensions are: "+(chunksX * MyzoGEN.DIMENSION_X)+"x"+(chunksY * MyzoGEN.DIMENSION_Y); } catch (IOException e) { e.printStackTrace(); return "BaseTerrainGenerator critical error - LOAD option is on but I can't load the file."; } } else return "BaseTerrainGenerator critical error - LOAD option is on but I can't find the heightmap_overview.png file."; return "No errors."; }
7
public void start() { keepGoing = true; /* create socket server and wait for connection requests */ try { keyPair = KeyPairFactory.generateKeyPair(); // System.out.println(publicKey); // the socket used by the server ServerSocket serverSocket = new ServerSocket(port); // infinite loop to wait for connections while (keepGoing) { // format message saying we are waiting display("Server waiting for Clients on port " + port + "."); Socket socket = serverSocket.accept(); // accept connection // if I was asked to stop if (!keepGoing) break; ClientThread t = new ClientThread(socket); // make a thread of // it al.add(t); // save it in the ArrayList t.start(); } // I was asked to stop try { serverSocket.close(); for (int i = 0; i < al.size(); ++i) { ClientThread tc = al.get(i); try { tc.sInput.close(); tc.sOutput.close(); tc.socket.close(); } catch (IOException ioE) { // not much I can do } } } catch (Exception e) { display("Exception closing the server and clients: " + e); } } // something went bad catch (IOException | NoSuchAlgorithmException e) { String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n"; display(msg); } }
6
private void AjouterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AjouterActionPerformed Pattern patternpseudo = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*"); Matcher matcherpseudo = patternpseudo.matcher(login.getText()); if(matcherpseudo.matches() ) { Pattern patternprix = Pattern.compile("^[0-9]{4,5}$"); Matcher matcherprix = patternprix.matcher(price.getText()); if(matcherprix.matches() ) { Pattern patterncityd = Pattern.compile("^[_A-Za-z-]([_A-Za-z-]+)*"); Matcher matchercityd = patterncityd.matcher(CityD.getText()); if (matchercityd.matches()) { Pattern patterncityr = Pattern.compile("^[_A-Za-z-]([_A-Za-z-]+)*"); Matcher matchercityr = patterncityr.matcher(CityR.getText()); if (matchercityr.matches()) { Pattern patternseat = Pattern.compile("^[1-4]$"); Matcher matcherseat = patternseat.matcher(seat.getValue().toString()); if (matcherseat.matches()) { Pattern patterncar = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*"); Matcher matchercar = patterncar.matcher(car.getText()); if (matchercar.matches()) { RoadDAO rdao = new RoadDAO(); Road r = new Road(); r.setDriver(login.getText()); r.setPrice(parseFloat(price.getText())); r.setCityD(CityD.getText()); r.setCityR(CityR.getText()); r.setSeat(parseInt(seat.getValue().toString())); String road=""; if(oui.isSelected()){ road=oui.getText(); } if(non.isSelected()){ road=non.getText(); } r.setRound(road); rdao.AddRoad(r); JOptionPane.showMessageDialog(this,"Ajout effectué"); } else{ JOptionPane.showMessageDialog(this, "You have to add your car description"); } } else{ JOptionPane.showMessageDialog(this, "The number of seats must be different from 0"); } } else{ JOptionPane.showMessageDialog(this, "Your City R is unvalid"); } } else{ JOptionPane.showMessageDialog(this, "Your City D is unvalid"); } } else{ JOptionPane.showMessageDialog(this, "Your Price is unvalid"); } } else { JOptionPane.showMessageDialog(this, "Your Login is unvalid"); } }//GEN-LAST:event_AjouterActionPerformed
8
private void findZip() { //郵便番号検索 //画面の郵便番号を取得 String searchZip = textZipCode.getText().replaceAll("-", ""); int serchL = searchZip.length(); if ((serchL == 3) || (serchL == 5)) { //3桁・5桁指定 //一覧呼び出し JyusyoJDialog digJyusyo = new JyusyoJDialog(frm, true, this); digJyusyo.setZipCode(searchZip); //モーダルの場合ここで止まる // textZipCodeActionPerformed(evt); これをやると閉じただけでも上書きして危険 return; } if (serchL != 7) { JOptionPane.showMessageDialog(this, "郵便番号の桁数をご確認下さい。\n指定できるのは、3,5,7桁のみです。"); return; } //CSVファイルの読み込み File csv = null; try { csv = new File("KEN_ALL.CSV"); BufferedReader br; br = new BufferedReader(new InputStreamReader(new FileInputStream(csv), "MS932")); String line = ""; boolean find = false; while ((line = br.readLine()) != null) { String[] strArr = line.split(","); String zipcode = strArr[2].replaceAll("\"", ""); if (searchZip.equals(zipcode)) { textZipCode.setText(searchZip.substring(0, 3) + "-" + searchZip.substring(3)); textJyusyo1.setText(strArr[6].replaceAll("\"", "") + strArr[7].replaceAll("\"", "") + strArr[8].replaceAll("\"", "")); textJyusyo2.setText(""); find = true; break; } } if (!find) { JOptionPane.showMessageDialog(this, "指定された郵便番号が見つかりません。"); } } catch (FileNotFoundException e) { // Fileオブジェクト生成時の例外捕捉 e.printStackTrace(); JOptionPane.showMessageDialog(this, "郵便番号CSVファイルがありません。\n" + csv.getAbsolutePath()); } catch (IOException e) { // BufferedReaderオブジェクトのクローズ時の例外捕捉 e.printStackTrace(); JOptionPane.showMessageDialog(this, "エラーが発生しました"); } }
8
public static double runTest(int numThreads, int N) { ExecutorService execService = Executors.newFixedThreadPool(numThreads); List<Future<Double>> results = null; try { results = execService.invokeAll(init(numThreads, N)); } catch (InterruptedException ex) { System.out.println("Unexpected interruption of ExecutorService"); return -1.0; } finally { execService.shutdown(); } double sum = 0.0; int counter = 0; for (Future<Double> future : results) { try { sum += future.get(); } catch (InterruptedException ex) { System.out.println("Interrupted while getting result from thread " + counter); return -1.0; } catch (ExecutionException ex) { System.out.println("ExecutionException while getting result from" + "thread" + counter); } ++counter; } return sum; }
4
public static ArrayList<Integer> generate(int n) { ArrayList<Integer> factors = new ArrayList<Integer>(); for(int i = 2; n > 1; i++) { for(; n % i == 0; n /= i) { factors.add(i); } } return factors; }
2
public void testMinus_int() { Minutes test2 = Minutes.minutes(2); Minutes result = test2.minus(3); assertEquals(2, test2.getMinutes()); assertEquals(-1, result.getMinutes()); assertEquals(1, Minutes.ONE.minus(0).getMinutes()); try { Minutes.MIN_VALUE.minus(1); fail(); } catch (ArithmeticException ex) { // expected } }
1
public void rotate() { ImageData src = sourceImage.getImageData(); if (src == null) return; PaletteData srcPal = src.palette; PaletteData destPal; ImageData dest; // construct a new ImageData if (srcPal.isDirect) { destPal = new PaletteData(srcPal.redMask, srcPal.greenMask, srcPal.blueMask); } else { destPal = new PaletteData(srcPal.getRGBs()); } dest = new ImageData(src.height, src.width, src.depth, destPal); // rotate by rearranging the pixels for (int i = 0; i < src.width; i++) { for (int j = 0; j < src.height; j++) { int pixel = src.getPixel(i, j); dest.setPixel(j, src.width - 1 - i, pixel); } } if (sourceImage != null) sourceImage.dispose(); if (dest != null) sourceImage = new Image(getDisplay(), dest); syncScrollBars(); }
6
private boolean parseTWO(int[] buf) { switch (buf[0]) { case IAC: // doubled IAC to escape 255 is handled within the // read method. break; case AYT: IamHere(); break; case AO: case IP: case EL: case EC: case NOP: break; case BRK: nvtBreak(); break; default: return false; } return true; }// parseTWO
8
public CreateUserResponse createUser(CreateUserRequest request) throws GongmingApplicationException, GongmingConnectionException { URL path = _getPath(CREATE_USER); CreateUserResponse response = _POST(path, request, CreateUserResponse.class); if (response.code != GMResponseCode.COMMON_SUCCESS) { throw new GongmingApplicationException(response.code.toString(), response.errorMessage); } return response; }
1
public Integer decrement(K key){ if (map.containsKey(key)){ map.put(key, map.get(key)-1); } else { map.put(key, 1); } return map.get(key); }
1
public void testPrinterSettings( WorkBookHandle book ) { WorkSheetHandle sheet = null; PrinterSettingsHandle printersetup = null; try { sheet = book.getWorkSheet( 0 ); for( int x = 0; x < 10; x++ ) { for( int t = 0; t < 10; t++ ) { sheet.add( "Hello World " + t, t, x ); } } printersetup = sheet.getPrinterSettings(); } catch( Exception e ) { log.error( "testPrinterSettings failed: " + e.toString() ); } // fit width printersetup.setFitWidth( 3 ); // fit height printersetup.setFitHeight( 5 ); // header margin printersetup.setHeaderMargin( 1.025 ); // footer margin printersetup.setFooterMargin( 1.025 ); // number of copies printersetup.setCopies( 10 ); // Paper Size printersetup.setPaperSize( PrinterSettingsHandle.PAPER_SIZE_LEDGER_17x11 ); // Scaling printersetup.setScale( 125 ); // resolution printersetup.setResolution( 300 ); // GRBIT settings: // left to right printing printersetup.setLeftToRight( true ); // print as draft quality printersetup.setDraft( true ); // black and white printersetup.setNoColor( true ); // landscape / portrait printersetup.setLandscape( true ); // write it out testWrite( book, "PrinterSettings_out.xls" ); // read it in book = new WorkBookHandle( outputdir + "PrinterSettings_out.xls" ); try { sheet = book.getWorkSheet( 0 ); printersetup = sheet.getPrinterSettings(); } catch( Exception e ) { log.error( "testPrinterSettings failed: " + e.toString() ); } // header margin log.info( "Header Margin: " + printersetup.getHeaderMargin() ); // footer margin log.info( "Header Margin: " + printersetup.getFooterMargin() ); // assertions // fit width assertEquals( (short) 3, printersetup.getFitWidth() ); // fit height assertEquals( (short) 5, printersetup.getFitHeight() ); // number of copies assertEquals( (short) 10, printersetup.getCopies() ); // Paper Size assertEquals( (short) PrinterSettingsHandle.PAPER_SIZE_LEDGER_17x11, printersetup.getPaperSize() ); // TODO: find out what these are // Scaling assertEquals( (short) 125, printersetup.getScale() ); // resolution assertEquals( (short) 300, printersetup.getResolution() ); // left to right printing assertEquals( true, printersetup.getLeftToRight() ); // print as draft quality assertEquals( true, printersetup.getDraft() ); // No color assertEquals( true, printersetup.getNoColor() ); // landscape / portrait assertEquals( true, printersetup.getLandscape() ); }
4
@Override public void validate() { if (platform == null) { addActionError("Please Select Platorm"); } if (location == null) { addActionError("Please Select Location"); } if (iphone.equals("Please select")) { addActionError("Please Select Os"); } if (gender == null) { addActionError("Please Select Gender"); } if (age == null) { addActionError("Please Select Age"); } }
5
public ArrayList<Player> mostBooks() { ArrayList<Player> mosts = new ArrayList<Player>(); Player most = this.playerList[0]; int mostPos = 0; // Searches for the player with the most books. // Keeps track of the position at which that player is found, // so that when searching through the list of players again for a tie, // that player is not selected as a "tie" with himself. for (int i = 0; i < this.numPlayers; i++) { if (most.getNumBooks() < this.playerList[i].getNumBooks()) { most = this.playerList[i]; mostPos = i; } } // Check for a tie for (int i = 0; i < this.numPlayers; i++) { if (most.getNumBooks() == this.playerList[i].getNumBooks() && mostPos != i) { mosts.add(this.playerList[i]); } } mosts.add(most); return mosts; }
5