method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
5bbf2020-b42f-4fb8-bd66-f601d2b5ef44
8
private void conectBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_conectBotonActionPerformed if(userTF.getText().equals("") && passTF.getText().equals("") && ipTF.getText().equals("") && portTF.getText().equals("") && dbTF.getText().equals("")) { JOptionPane.showMessageDialog(this, "Empty spaces", "warning",1); } else{ principal.setUser(user = userTF.getText()); if(asCB.isEnabled()){ user +=" as "+(String)asCB.getSelectedItem(); } principal.setPass(pass = passTF.getText()); principal.setIp(ip = ipTF.getText()); principal.setPort(port = portTF.getText()); principal.setDb(db = dbTF.getText()); boolean exito = false; ServicioConexion sc = new ServicioConexion(user,pass,ip,port,db); try { exito = sc.iniciarConexion(); } catch (Exception ex) { Logger.getLogger(ConexionGUI.class.getName()).log(Level.SEVERE, null, ex); } if(exito){ principal.getTabPanel().setEnabledAt(2,true); principal.cargarTabla(); ConectadoGUI con = new ConectadoGUI(this); JPanel conPanel = principal.getConexionPanel(); conPanel.removeAll(); conPanel.add(con); conPanel.validate(); }else{ JOptionPane.showMessageDialog(this, "Can not connect to the database", "warning",1); } } }//GEN-LAST:event_conectBotonActionPerformed
68ce029c-6e39-41f3-922a-b418ff2d8cef
6
public void deleteIssueFired(ActionEvent event) { final String selectedProject = getSelectedProject(); if (model != null && selectedProject != null && table != null) { // We create a copy of the current selection: we can't delete // issue while looping over the live selection, since // deleting selected issues will modify the selection. final List<?> selectedIssue = new ArrayList<Object>(table.getSelectionModel().getSelectedItems()); for (Object o : selectedIssue) { if (o instanceof ObservableIssue) { model.deleteIssue(((ObservableIssue) o).getId()); } } table.getSelectionModel().clearSelection(); } }
e0b72cfc-ace5-46e0-b677-e0fe3eff12fa
7
public static String getLocationData() { HttpURLConnection urlConnection = null; BufferedReader reader = null; String geoip = null; final String GEO_IP = "http://www.telize.com/geoip"; try { URL url = new URL(GEO_IP); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) { return null; } geoip = buffer.toString(); }catch (IOException e) { return null; }finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { } } } return geoip; }
6fb3666e-c2c2-4553-89f3-e690b9a8ea10
5
private void refreshScriptActions() { Iterator<String> it = vetScript.iterator(); // Skip "serialNumber". if (it.hasNext()) { it.next(); } // Get number of actions and discovers how many digits it has. int total = vetScript.size(); int nDigits = 0; while (total > 0) { total = total / 10; nDigits++; } // Aux variables. int exp = 1, index = 1; nDigits--; dataModel.removeAllElements(); // Add actions. while (it.hasNext()) { String s = ""; while (s.length() < (nDigits)) { s = s + "0"; } dataModel.add(index - 1, s + index + ". " + it.next()); index++; if (index == Math.pow(10, exp)) { nDigits--; exp++; } } }
72138530-d80e-4d7f-811d-5e74c401c9b9
7
@Override public void caseAIdxAcsStmt(AIdxAcsStmt node) { inAIdxAcsStmt(node); if(node.getSmc() != null) { node.getSmc().apply(this); } if(node.getAssgn() != null) { node.getAssgn().apply(this); } if(node.getEq() != null) { node.getEq().apply(this); } if(node.getRSq() != null) { node.getRSq().apply(this); } if(node.getIdx() != null) { node.getIdx().apply(this); } if(node.getLSq() != null) { node.getLSq().apply(this); } if(node.getIdentifier() != null) { node.getIdentifier().apply(this); } outAIdxAcsStmt(node); }
63c042da-4790-4d23-acdc-253e73058d71
8
@Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { Boolean has_retweet = true; JSONObject json; try { json = (JSONObject) parser.parse(value.toString()); String time = Utility.convertDateFormat(json.get("created_at").toString()); String id = json.get("id").toString(); String text = json.get("text").toString(); JSONObject user = (JSONObject) json.get("user"); String user_id = user.get("id").toString(); JSONObject re_status = (JSONObject) json.get("retweeted_status"); String re_id = null, re_user_id = null; JSONObject re_user = null; if (re_status != null) { re_id = re_status.get("id").toString(); re_user = (JSONObject) re_status.get("user"); re_user_id = re_user.get("id").toString(); } else { has_retweet = false; } //timeKey.set(String.format("%s", bucket+"|"+time+"|"+id).getBytes()); timeKey.set(String.format("%s", bucket+HColumnEnum.splitRowKey+time+HColumnEnum.splitRowKey+id).getBytes()); if(!text.equals("")){ // mos.write(HColumnEnum.TimeTable,timeKey, kv,HColumnEnum.TimeOutput); context.write(timeKey, new Text(HColumnEnum.TXT+HColumnEnum.splitWord+text)); } userKey_1.set(String.format("%s", bucket+HColumnEnum.splitRowKey+user_id+HColumnEnum.splitRowKey+id+HColumnEnum.splitRowKey+"uid").getBytes()); //mos.write(HColumnEnum.UserTable,userKey, kv,HColumnEnum.UserOutput); if(!user_id.equals("")){ //mos.write(HColumnEnum.UserTable,userKey, kv,HColumnEnum.UserOutput); context.write(userKey_1, new Text(HColumnEnum.USER_ID+HColumnEnum.splitWord+user_id)); } userKey_2.set(String.format("%s", bucket+HColumnEnum.splitRowKey+user_id+HColumnEnum.splitRowKey+id+HColumnEnum.splitRowKey+"rud").getBytes()); if(has_retweet){ if(!re_user_id.equals("")){ //mos.write(HColumnEnum.UserTable,userKey, kv,HColumnEnum.UserOutput); context.write(userKey_2, new Text(HColumnEnum.REUSER_ID+HColumnEnum.splitWord+re_user_id)); } } userKey_3.set(String.format("%s", bucket+HColumnEnum.splitRowKey+user_id+HColumnEnum.splitRowKey+id+HColumnEnum.splitRowKey+"rst").getBytes()); context.write(userKey_3, new Text(HColumnEnum.HAS_RETEWEET+HColumnEnum.splitWord+has_retweet.toString())); userKey_4.set(String.format("%s", bucket+HColumnEnum.splitRowKey+user_id+HColumnEnum.splitRowKey+id+HColumnEnum.splitRowKey+"rid").getBytes()); if(has_retweet){ if(!re_id.equals("")){ //mos.write(HColumnEnum.UserTable,userKey, kv,HColumnEnum.UserOutput); context.write(userKey_4, new Text(HColumnEnum.RETEWEET_ID+HColumnEnum.splitWord+re_id)); } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); context.getCounter("HBaseKVMapper", "PARSE_ERRORS").increment(1); } context.getCounter("HBaseKVMapper", "NUM_MSGS").increment(1); }
c637221c-f76f-4c96-8718-21b92950aaaa
9
public void setFakeResult(){ /* * 村人騙りなら不必要 */ if(fakeRole == Role.villager){ return; } //偽占い(or霊能)の候補.以下,偽占い候補 List<Agent> fakeGiftTargetCandidateList = new ArrayList<>(); List<Agent> aliveAgentList = getLatestDayGameInfo().getAliveAgentList(); aliveAgentList.remove(getMe()); for(Agent agent: aliveAgentList){ //まだ偽占いしてないプレイヤー,かつ対抗CO者じゃないプレイヤーは偽占い候補 if(!isJudgedAgent(agent) && fakeRole != agi.getComingoutMap().get(agent)){ fakeGiftTargetCandidateList.add(agent); } } Agent fakeGiftTarget; if(fakeGiftTargetCandidateList.size() > 0){ Random rand = new Random(); fakeGiftTarget = fakeGiftTargetCandidateList.get(rand.nextInt(fakeGiftTargetCandidateList.size())); }else{ aliveAgentList.removeAll(fakeGiftTargetCandidateList); Random rand = new Random(); fakeGiftTarget = aliveAgentList.get(rand.nextInt(aliveAgentList.size())); } Species fakeResult; /* * 人狼が偽占い対象の場合 */ if(getWolfList().contains(fakeGiftTarget)){ fakeResult = Species.Human; } /* * 人間が偽占い対象の場合 */ else{ //狂人(暫定),または非COプレイヤー if(fakeGiftTarget == maybePossesedAgent || !agi.getComingoutMap().containsKey(fakeGiftTarget)){ if(Math.random() < 0.5){ fakeResult = Species.Werewolf; }else{ fakeResult = Species.Human; } } //能力者CO,かつ人間,非狂人(暫定) else{ fakeResult = Species.Werewolf; } } fakeJudgeList.add(new Judge(getDay(), getMe(), fakeGiftTarget, fakeResult)); }
62d80d62-34f5-4846-8dc9-a5eb460980f5
4
@Override public void paint(Graphics g) { try { ImageIcon img = null; if ("".equals(modal)) { img = new ImageIcon(this.getClass().getResource( "/images/" + name + ".png")); } else { img = new ImageIcon(this.getClass().getResource( "/images/" + name + "_" + modal + ".png")); } if (img.getImage() != null) g.drawImage(img.getImage(), (getWidth() - img.getIconWidth()) / 2, (getHeight() - img.getIconHeight()) / 2, image); } catch (NullPointerException e) { // super.paint(g); } if (textPanel != null) { g.setColor(Color.BLACK); g.setFont(textPanel.getFont()); g.drawString(textPanel.getText(), (int) (getWidth() - textPanel .getPreferredSize().getWidth()) / 2 + 1, getHeight() / 2 + 7); textPanel.paint(g); } }
e80ec315-96f2-4c41-94fb-7ec7d1904573
4
public Sentiment[] getSentiment ( String text ) { // System.out.println(text); text = cleanText(text); // System.out.println(text); Sentiment[] result = new Sentiment[text.split("\\.").length]; int i = 0; int count = 0; int tense = 0; Double score = 0.0; Double value = 0.0; String[] texts = text.split("\\."); for ( String sentence : texts ) { String[] words = sentence.split(" "); for ( String word : words ) { value = emotionalSentiment.checkEmotionalSentiment(word); score += value; if ( value != 0.0 ) { count++; } } String posTaggedSentence = posTagger.getTaggedSentence(sentence); // System.out.println(posTaggedSentence); value = getScore(posTaggedSentence); // System.out.println(value); tense = getTense(posTaggedSentence); // System.out.println(num); // System.out.println(tense); if ( tense > 0 ) { result[i] = new Sentiment(score, num, "past"); } else { result[i] = new Sentiment(score, num, "not-past"); } } return result; }
2a7d6c0f-8e27-4e79-a537-ff200a7bfa6b
2
public int compare(SimNode o1, SimNode o2) { // TODO Auto-generated method stub double numbera = o1.getSim(); double numberb = o2.getSim(); if(numberb > numbera) { return 1; } else if(numberb<numbera) { return -1; } else { return 0; } }
66c4f9af-b758-4145-bdbe-54fafd875fa2
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DatasetUpdateFrequency)) { return false; } DatasetUpdateFrequency other = (DatasetUpdateFrequency) object; if ((this.code == null && other.code != null) || (this.code != null && !this.code.equals(other.code))) { return false; } return true; }
5e26ef00-ede3-4ce4-99c8-fa86858df34a
2
public KeyInfo load(String password) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException { FileInputStream fin = null; try { char[] psw = password.toCharArray(); String alias = ""; this.keyInfo = null; fin = new FileInputStream( file ); // Load key store this.keyStore = KeyStore.getInstance( "JKS" ); this.keyStore.load( fin, psw ); // Get the certificate from the keystore if ( this.keyStore.size() > 0 ) { alias = this.keyStore.aliases().nextElement(); X509Certificate cert = (X509Certificate) this.keyStore.getCertificate( alias ); X500Principal principal = cert.getSubjectX500Principal(); X500Name x500Info = X500Name.asX500Name( principal ); // Now, lets decode it // Dump the info from the guts of the cert library this.keyInfo = new KeyInfo( alias, x500Info.getCommonName(), x500Info.getOrganizationalUnit(), x500Info.getOrganization(), x500Info.getLocality(), x500Info.getState(), x500Info.getCountry(), password ); } } finally { if ( fin != null ) { fin.close(); } } return this.keyInfo; }
b4014b43-44fd-4ffc-be39-9f7eb4369093
8
public Range getHelix(int index) { if((index<0)||(index>=_str.length)) { return new Range(index,index);} int j = _str[index]; if(j!=-1) { int minH = index; int maxH = index; if (j>index) { maxH = j; } else { minH = j; } boolean over = false; while (!over) { if((minH<0)||(maxH>=_str.length)) {over = true;} else { if (_str[minH]==maxH) {minH--;maxH++;} else {over = true;} } } minH++; maxH--; return new Range(minH,maxH); } return new Range(0,0); }
67702c6e-23be-4ab2-99f6-44abbbf74a3d
5
public void setUser(User newUser) { if (newUser == null || (user != null && newUser.getID().equals(user.getID()))) return; if ( (newUser.lastLog == null) || (System.currentTimeMillis() - newUser.lastLog.getTime()) > 600_000) { // if lastlog is older then 10 min or first login newUser.logins++; } mainFrame.setTitle("User: " + newUser.name + " - Logins: " + newUser.logins + " - LastLogin: " + TimeCalc.calcPrettyTime(newUser.lastLog)); newUser.lastLog = new java.sql.Timestamp(System.currentTimeMillis()); newUser.saveToDB(); this.user = newUser; updateCorePhrases(); mainFrame.updateUserBtnText(); mainFrame.nextPhrase(); }
b1c20e55-4939-4b91-87cd-3745e9bd7937
4
@Override public int hashCode() { int result = alpha != null ? alpha.hashCode() : 0; result = 31 * result + (red != null ? red.hashCode() : 0); result = 31 * result + (green != null ? green.hashCode() : 0); result = 31 * result + (blue != null ? blue.hashCode() : 0); return result; }
b963743f-472c-4c48-9d88-490e502f1a6e
4
@Override public void encode(final ByteBuffer buf, final StringBuilder log) { encoder.encode(buf, log); final byte tick_time = (byte) 10; final byte ticks = (byte) 240; buf.put(tick_time); buf.put(ticks); final short body_size = (short) body.getRequestSize(); buf.putShort(body_size); final boolean pad = needPad(); if (log != null) { log.append("CM_Unconnected_Send\n"); log.append("USINT tick_time : ").append(tick_time).append("\n"); log.append("USINT ticks : ").append(ticks).append("\n"); log.append("UINT message size : ").append(body.getRequestSize()).append("\n"); log.append(" \\/\\/\\/ embedded message \\/\\/\\/ (").append(body_size).append(" bytes)\n"); } body.encode(buf, log); if (pad) buf.put((byte) 0); buf.put((byte) 1); // Path size buf.put((byte) 0); // reserved buf.put((byte) 1); // Port 1 = backplane buf.put((byte) slot); if (log != null) { log.append(" /\\/\\/\\ embedded message /\\/\\/\\\n"); if (pad) log.append("USINT pad : 0 (odd length message)\n"); log.append("USINT path size : ").append(1).append(" words\n"); log.append("USINT reserved : 0\n"); log.append("USINT port 1, slot ").append(slot).append("\n"); } }
072ad0cd-fe6f-413d-8003-219f2efa3f74
2
public boolean instanceOf(Object obj, String className) throws InterpreterException { Class clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException ex) { throw new InterpreterException("Class " + ex.getMessage() + " not found"); } return obj != null && !clazz.isInstance(obj); }
62e07bc6-d44f-4d32-9bb4-161025e787c7
6
private void setVotableResource(final DataSetApplication datasetApp, final SimpleSpectralAccessInputParameters inputParameters, final ResourceModel model, final String dictionaryName) { final List<Field> fieldList = new ArrayList<Field>(); final List<String> columnList = new ArrayList<String>(); DatabaseRequest databaseRequest = null; try { // Get the concepts from the dictionary List<ColumnConceptMappingDTO> mappingList = getDicoFromConfiguration(datasetApp, dictionaryName); mappingList = checkRequiredMapping(mappingList, inputParameters.getVerb()); // Get query parameters final DatabaseRequestParameters dbParams = setQueryParameters(datasetApp, model, inputParameters, mappingList); databaseRequest = DatabaseRequestFactory.getDatabaseRequest(dbParams); // Execute query databaseRequest.createRequest(); LOG.log(Level.FINEST, "DB request: {0}", databaseRequest.getRequestAsString()); //Fill the template with query status and param fillInfosParamAboutQuery(model); // complete data model with fields setFields(fieldList, columnList, mappingList); dataModel.put("fields", fieldList); dataModel.put("sqlColAlias", columnList); Map conceptColAlias = new HashMap(); for (ColumnConceptMappingDTO map:mappingList) { conceptColAlias.put(map.getColumnAlias(), map.getConcept().getPropertyFromName("ucd").getValue()); } dataModel.put("mappingColAliasConceptSql", conceptColAlias); // Complete data model with data final int count = (databaseRequest.getCount() > dbParams.getPaginationExtend()) ? dbParams.getPaginationExtend() : databaseRequest.getCount(); dataModel.put("nrows", count); final ConverterChained converterChained = datasetApp.getConverterChained(); final TemplateSequenceModel rows = new DatabaseRequestModel(databaseRequest, converterChained); ((DatabaseRequestModel) rows).setSize(count); dataModel.put("rows", rows); } catch (SitoolsException ex) { try { if (Util.isSet(databaseRequest)) { databaseRequest.close(); } } catch (SitoolsException ex1) { LOG.log(Level.FINER, null, ex1); } finally { final List<Info> infos = new ArrayList<Info>(); LOG.log(Level.FINEST, "ERROR: {0}", ex.getMessage()); setVotableError(infos, "Query", "Error in query", "Error in input query: " + ex.getMessage()); if (!infos.isEmpty()) { this.dataModel.put("infos", infos); } } } }
e398df25-b049-4aed-b8ff-1c768824fa7a
1
public static void leastPaidEmployees(EntityManager entityManager) { TypedQuery<Employee> query = entityManager.createQuery( "select e from Employee e order by e.salary asc", Employee.class); query.setMaxResults(2); List<Employee> resultList = query.getResultList(); entityManager.close(); for (Employee employee : resultList) { System.out.println(employee); } }
80962267-8382-4027-b55e-70c9f0b82c67
1
public void refuel(int fuel) { tank.refuel(fuel); if(!tank.isEmpty()) { setDead(false); } }
e736e8e2-2476-4ef1-8da5-3bfa8adc4bd0
1
public Expr pop1() { final Expr top = (Expr) stack.remove(stack.size() - 1); final Type type = top.type(); if (type.isWide()) { throw new IllegalArgumentException("Expected a word " + ", got a long"); } height--; return top; }
e79aa93a-15c2-41a3-9d3a-519eef2919e4
2
public static void winLose(){ if (Empous.Gov.getStat("publicopinion")>100){ UpdateView finalUpdate = new UpdateView(0); finalUpdate.display(); System.out.println("YOU'RE WINNER!"); } else if (Empous.Gov.getStat("publicopinion")==0){ UpdateView finalUpdate = new UpdateView(0); finalUpdate.display(); System.out.println("YOU LOSE!"); } }
ba21b380-676d-47a2-ab2c-d55c1e4ab529
5
public Point getTileCollision(Sprite sprite, float newX, float newY) { float fromX = Math.min(sprite.getX(), newX); float fromY = Math.min(sprite.getY(), newY); float toX = Math.max(sprite.getX(), newX); float toY = Math.max(sprite.getY(), newY); // get the tile locations int fromTileX = TileMapRenderer.pixelsToTiles(fromX); int fromTileY = TileMapRenderer.pixelsToTiles(fromY); int toTileX = TileMapRenderer.pixelsToTiles( toX + sprite.getWidth() - 1); int toTileY = TileMapRenderer.pixelsToTiles( toY + sprite.getHeight() - 1); // check each tile for a collision for (int x=fromTileX; x<=toTileX; x++) { for (int y=fromTileY; y<=toTileY; y++) { if (x < 0 || x >= map.getWidth() || map.getTile(x, y) != null) { // collision found, return the tile pointCache.setLocation(x, y); return pointCache; } } } // no collision found return null; }
44955909-0d7c-4592-aacf-43f88dab7a05
7
public void step() { if( !ready && source.ready ) { init(); } if( !run || !ready ) return; if( actions!=null && frame<actions.length ) if( actions[frame]!=null ) actions[frame].exec(this); frame=(frame+1)%size; }
42aa13fe-91b5-464f-ada7-652fc0f2f3de
1
public Builder mass(double receivedMass) { if (receivedMass < 0) { log.warn("Wrong Mass. receivedMass =", receivedMass); throw new IllegalArgumentException("Mass must be > 0 Received value =" + receivedMass); } this.mass = receivedMass; return this; }
8b3eb99a-e5f3-4502-b3b6-0fa78f67e47f
8
public /*@non_null@*/ int [] getSelection() { if (m_Upper == -1) { throw new RuntimeException("No upper limit has been specified for range"); } int [] selectIndices = new int [m_Upper + 1]; int numSelected = 0; if (m_Invert) { for (int i = 0; i <= m_Upper; i++) { if (!m_SelectFlags[i]) { selectIndices[numSelected++] = i; } } } else { Enumeration enu = m_RangeStrings.elements(); while (enu.hasMoreElements()) { String currentRange = (String)enu.nextElement(); int start = rangeLower(currentRange); int end = rangeUpper(currentRange); for (int i = start; (i <= m_Upper) && (i <= end); i++) { if (m_SelectFlags[i]) { selectIndices[numSelected++] = i; } } } } int [] result = new int [numSelected]; System.arraycopy(selectIndices, 0, result, 0, numSelected); return result; }
2e48c8ff-ea1e-40ad-a50f-23b8e98c2676
8
@Override public int lookup(String key){ if (key == null || key.isEmpty()) return UNKNOWN_ID; CodeSequence cs = thl.get(); cs.set(key, codemap_); int src = ROOT ; int pos = 0 ; while (pos < cs.size_){ int dest = Node.BASE(nodes_[src]) + cs.sequence_[pos]; if (dest < nodes_.length){ if (src == Node.CHECK(nodes_[dest])){ pos ++ ; src = dest; continue; } } int t = Node.TAIL(nodes_[src]); if (t >= 0 && tails_.match(t, pos, cs.size_, cs.sequence_)) return src; return UNKNOWN_ID; } if (Node.TERMINAL(nodes_[src])) return src; return UNKNOWN_ID; }
155c7381-832b-402d-9d46-fc46005e624c
8
final boolean method1158() { if (anIntArray2085 == null) { return anInt2065 != -1 || anInt2101 != -1 || anInt2098 != -1; } for (int i = 0; i < anIntArray2085.length; i++) { if (anIntArray2085[i] != -1) { NPCComposite NPCComposite = Class21.npcCompositeForID(anIntArray2085[i]); if (NPCComposite.anInt2065 != -1 || NPCComposite.anInt2101 != -1 || NPCComposite.anInt2098 != -1) { return true; } } } return false; }
983bf5cc-3700-405a-ac77-285313590c93
0
public static void main(String[] args) { System.out.println(1 + 2 * 3); // 7 System.out.println((1 + 2) * 3); // 9 System.out.println(1 + (2 * 3)); // 7 }
f239893a-8d41-4269-9d1b-615b1f460620
7
public int getBlockId(int par1, int par2, int par3) { if (par2 < 0) { return 0; } else if (par2 >= 256) { return 0; } else { int var4 = (par1 >> 4) - this.chunkX; int var5 = (par3 >> 4) - this.chunkZ; if (var4 >= 0 && var4 < this.chunkArray.length && var5 >= 0 && var5 < this.chunkArray[var4].length) { Chunk var6 = this.chunkArray[var4][var5]; return var6 == null ? 0 : var6.getBlockID(par1 & 15, par2, par3 & 15); } else { return 0; } } }
e8eb909a-3807-4432-9d2e-ddfa6e5cb9b0
8
@Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(mat)) { String selected = mat.getText(); Materie materie_noua = null; for (Materie m : Centralizator.getInstance().getMaterii()) { if (m.getNume().equals(selected)) { materie_noua = m; return; } } if (materie_noua == null) { mesaj.setText("Materia nu exista in baza de date a liceului; verificati inca o data"); return; } secretar.modifyMateriePentruProfesor(selectedProfesor, materie_noua); } else if (e.getSource().equals(adaugaMaterie)) { if (!mat.getText().isEmpty()) { JOptionPane .showMessageDialog(this, "Profesorul are deja materie; stergeti materia mai intai"); // return; } dispose(); new SecretarAddMaterie(secretar, selectedProfesor); } else if (e.getSource().equals(stergeMaterie)) { secretar.removeMateriePentruProfesor(selectedProfesor); mat.setText(""); } else if (e.getSource().equals(back)) { dispose(); Centralizator cen2 = Centralizator.getInstance(); cen2.saveCentralizator(); new SecretarMeniu(secretar); } }
c4cd7528-198e-4b8f-908f-a2f7f3f4ddca
7
protected void processConnection(StreamConnection connection) { LOGGER.entry(connection); if (stopRequested) { LOGGER.exit(); return; } DataInputStream dis; try { dis = connection.openDataInputStream(); } catch (IOException e) { LOGGER.catching(e); LOGGER.exit(); return; } boolean connectionOpen = true; try { while (!stopRequested && connectionOpen) { // Get ready to publish the message long sequence = disruptor.next(); Message event = disruptor.get(sequence); event.reset(); // Read data from the socket, place into the event // This will publish the message when "-1" is returned as well. int len = dis.read(event.getBuffer()); event.setLength(len); // Publish the event disruptor.publish(sequence); if (len == -1) { connectionOpen = false; } } } catch (IOException e) { LOGGER.catching(e); } finally { try { connection.close(); } catch (IOException e) { LOGGER.catching(e); } } LOGGER.exit(); }
7ee94dab-1dad-45e6-bdd4-4913455725c0
2
private float blink(float alpha){ this.alpha += this.velocity; if(this.alpha > 255 || this.alpha < 0){ this.velocity = -this.velocity; } return this.alpha; }
1dfbf384-8fb1-43bb-964f-373c05d25608
3
public long seek(long offset, int seekOrigin) throws java.io.IOException { if (bufferSize > 0) { stream.write(buf.array(), 0, bufferSize); buf.clear(); bufferSize = 0; } if (seekOrigin == STREAM_SEEK_SET) { stream.seek(offset); } else if (seekOrigin == STREAM_SEEK_CUR) { stream.seek(offset + stream.getFilePointer()); } size = 0; return stream.getFilePointer(); }
7ceccb36-2a5b-468c-8bd8-26a6e2b5012a
6
public static boolean updateAvailable() throws Exception { String version = plugin.getDescription().getVersion(); URL url = new URL("http://api.bukget.org/api2/bukkit/plugin/everlastingweather/latest"); InputStreamReader isr; try { isr = new InputStreamReader(url.openStream()); } catch (UnknownHostException e) { return false; } String newVersion; try { JSONParser jp = new JSONParser(); Object o = jp.parse(isr); if (!(o instanceof JSONObject)) { isr.close(); return false; } JSONObject jo = (JSONObject) o; jo = (JSONObject) jo.get("versions"); newVersion = (String) jo.get("version"); String[] oldTokens = version.split("[.]"); String[] newTokens = newVersion.split("[.]"); for (int i = 0; i < 3; i++) { Integer newVer = Integer.parseInt(newTokens[i]); Integer oldVer; try { oldVer = Integer.parseInt(oldTokens[i]); } catch (NumberFormatException e) { oldVer = 0; } if (oldVer < newVer) { isr.close(); return true; } } return false; } catch (ParseException e) { isr.close(); return false; } }
5b5394da-edea-41ac-9b1c-68e72640287c
6
public static KeyValueList collectForwardChainingRules(Description description, Object [] MV_returnarray) { { MemoizationTable memoTable000 = null; Cons memoizedEntry000 = null; Stella_Object memoizedValue000 = null; if (Stella.$MEMOIZATION_ENABLEDp$) { memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_COLLECT_FORWARD_CHAINING_RULES_MEMO_TABLE_000.surrogateValue)); if (memoTable000 == null) { Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_COLLECT_FORWARD_CHAINING_RULES_MEMO_TABLE_000, "(:MAX-VALUES 500 :TIMESTAMPS (:META-KB-UPDATE))"); memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_COLLECT_FORWARD_CHAINING_RULES_MEMO_TABLE_000.surrogateValue)); } memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), description, ((Context)(Stella.$CONTEXT$.get())), Stella.MEMOIZED_NULL_VALUE, null, -1); memoizedValue000 = memoizedEntry000.value; } if (memoizedValue000 != null) { if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) { memoizedValue000 = null; } } else { memoizedValue000 = Description.helpCollectForwardRules(description, null, null, false, null); if (Stella.$MEMOIZATION_ENABLEDp$) { memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000); } } { Cons rules = ((Cons)(memoizedValue000)); { KeyValueList _return_temp = ((KeyValueList)(rules.value)); MV_returnarray[0] = ((KeyValueList)(rules.rest.value)); return (_return_temp); } } } }
5a5be80b-a431-46a7-b560-cf1a796e5a95
0
protected void end() { Robot.driveTrain.tankDrive(0, 0); }
2f8a7141-1510-43e2-8a15-721f08b8f21b
4
protected synchronized void processEvent(Sim_event ev) { /***** NOTE: debugging information System.out.println(super.get_name() + ".processEvent(): Event was scheduled for " + ev.event_time()); System.out.println(super.get_name() + ".processEvent(): ev.get_tag() is " + ev.get_tag()); System.out.println(super.get_name() + ".processEvent(): ev.get_src() is " + ev.get_src()); *************/ switch ( ev.get_tag() ) { case GridSimTags.PKT_FORWARD: case GridSimTags.JUNK_PKT: //System.out.println(super.get_name() + // ".processEvent(): processNetPacket() + at time = " + GridSim.clock()); processFlowPacket(ev, ev.get_tag()); break; case GridSimTags.ROUTER_AD: receiveAd(ev); break; case GridSimTags.INSIGNIFICANT: //System.out.println(super.get_name() + // ".processEvent(): processInternalEvent() + at time = " + GridSim.clock()); processInternalEvent(ev); break; default: System.out.println(super.get_name() + ".body(): Unable to " + "handle request from GridSimTags " + "with constant number " + ev.get_tag() ); break; } }
c5eaa29e-26f3-473f-b36e-4ef0470de892
5
private static void printNode(NodeList nodeList) { for (int count = 0; count < nodeList.getLength(); count++) { Node tempNode = nodeList.item(count); // make sure it's element node. if (tempNode.getNodeType() == Node.ELEMENT_NODE) { // get node name and value System.out.println("\nNode Name = " + tempNode.getNodeName() + " [OPEN]"); System.out.println("Node Value = " + tempNode.getTextContent()); if (tempNode.hasAttributes()) { // get attributes names and values NamedNodeMap nodeMap = tempNode.getAttributes(); for (int i = 0; i < nodeMap.getLength(); i++) { Node node = nodeMap.item(i); System.out.println("attr name : " + node.getNodeName()); System.out.println("attr value : " + node.getNodeValue()); } } if (tempNode.hasChildNodes()) { //loop again if has child nodes printNode(tempNode.getChildNodes()); } System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]"); } } }
848bc640-0152-414f-9948-d42d1cebcfa6
5
public JSONObject toJSONObject(String languagecode, String p) { JSONObject jresult = new JSONObject(); if (p.equals("*")) { JSONArray ar = new JSONArray(); jresult.put("properties", ar); for(Iterator<String> i = this.getKeys(); i.hasNext();){ JSONObject n = new JSONObject(); String key = i.next(); String value = getProperty(key); n.put("name",key); n.put("value",value); ar.add(n); } } else { String[] properties = p.split(","); if (properties != null) { for (int i=0;i<properties.length;i++) { String key = properties[i]; String value = this.getSmartProperty(languagecode,key); if (value!=null) { jresult.put(key, value); } else { jresult.put(key,""); } } } } return jresult; }
1b3bda29-f5e1-4d9d-8de0-f881b841df44
7
static private Point[] dodecahedron() { Point[] ret = new Point[20]; final double GOLDEN = (1 + sqrt(5)) / 2; int i = 0; for (int x = -1; x <= +1; x++) { for (int y = -1; y <= +1; y++) { for (int z = -1; z <= +1; z++) { if (x * y * z != 0) ret[i++] = p(x, y, z); else if (y * z != 0) ret[i++] = p(0, y / GOLDEN, z * GOLDEN); else if (z * x != 0) ret[i++] = p(x * GOLDEN, 0, z / GOLDEN); else if (x * y != 0) ret[i++] = p(x / GOLDEN, y * GOLDEN, 0); } } } return ret; }
fed6c163-b925-4ab0-bb17-2fcaf5901cb4
5
@Override public synchronized void unRegisterClient(Trader trader) throws RemoteException, RejectedException { if (!this.registeredTraders.contains(trader)) throw new TraderNotExistsException(trader); for (Item it : this.itemsOnSale) { if (it.getOwner().equals(trader)) { this.itemsOnSale.remove(it); } } for (Wish w : this.wishes) { if (w.getTrader().equals(trader)) { this.itemsOnSale.remove(w); } } this.registeredTraders.remove(trader); }
c92b3cd1-9cdd-4ee1-a310-1a73d12c4d76
8
public void extractor() throws UnknownHostException, InterruptedException { int c = 0; conf.init(); while (true) { double lastProcessTime = 0; DB db = Mongo.connect(new DBAddress(conf.getSourceHost(), conf.getSourceMongoDBName())); DB proDb = Mongo.connect(new DBAddress(conf.getProcessHost(), conf.getProcessDBName())); DBCollection coll = db.getCollection(conf.getSourceMongoCollectionName()); DBCollection proColl = proDb.getCollection(conf.getProcessCollectionName()); DBObject timeObj = proColl.findOne(); //System.out.println(timeObj != null && timeObj.containsField("time")); if (timeObj != null && timeObj.containsField("time")) { lastProcessTime = Double.parseDouble(timeObj.get("time").toString()); } System.out.println("--\tRound:" + (++c) + "\tLast Process Time:" + lastProcessTime + "\t--"); DBObject queryObj = new BasicDBObject().append("time", new BasicDBObject().append("$gt", lastProcessTime)).append("url", new BasicDBObject("$regex", "info")); DBCursor cur = coll.find(queryObj); while (cur.hasNext()) { DBObject obj = cur.next(); double curTime = (Double) obj.get("time"); if (lastProcessTime < curTime) { lastProcessTime = curTime; proColl.save(new BasicDBObject().append("date", new Date().getTime()).append("time", lastProcessTime)); } String url = obj.get("url").toString(); if (type == Extractor.SINA) { url = url.substring(url.indexOf("com/") + 4, url.indexOf("/info")); }else if(type== Extractor.TENCENT){ url=url.substring(url.indexOf("u=")+2); } synchronized (MultiExtractor.class) { int tcount = MultiExtractor.getThreadCount(); while (tcount > 20) { MultiExtractor.class.wait(); tcount = MultiExtractor.getThreadCount(); } MultiExtractor t = new MultiExtractor(conf, url, obj.get("html").toString()); t.start(); } } cur.close(); db.getMongo().close(); proDb.getMongo().close(); Thread.sleep(1000 * 60 * 10); } }
2ab27318-b1b2-4298-ac30-6e742c6c486b
4
@Override public void run() { try { report ("saving started", 1); //note: this iterator does not require locking because of CopyOnWriteArrayList implementation for (AbstractPage child: page.childPages) jobMaster.submit(new SaveDataJob(child,jobMaster)); if (!page.saveResult(this)) report("save skipped", 1); else report("saved", 1); } catch (IOException e) { report("saving caused exception", 1); //TODO: job rescheduling and error handling } catch (InterruptedException e) { } }
956fb118-d8e3-4dc1-840d-d39e4e52f2b5
7
private void executeDockCommand(String[] commandString, Player player) throws CommandException { if (DockCommand.isDockCommand(commandString[0])) { DockCommand firstCommand = DockCommand.toCommand(commandString[0]); switch (firstCommand) { case UNDOCK: undock(player); break; case BUY: buy(commandString, player); break; case SELL: sell(commandString, player); break; case CARGO: displayDockCargo(player); break; case STORE: displayDockStore(player); break; case INSTALL: install(commandString, player); break; } } else { throw new CommandException("Invalid dock command: " + commandString[0]); } }
f0aa55a1-ca82-4806-aff2-1284c556412c
6
public void setEnabled(boolean enabled) { if (!m_enabled && enabled) { // if the state changed to enable then add the stored handlers // copy the stored handlers into a new list to avoid concurred access to the list List<ClickHandler> handlers = new ArrayList<ClickHandler>(m_clickHandlers); m_clickHandlers.clear(); for (ClickHandler handler : handlers) { addClickHandler(handler); } m_textboxContainer.removeStyleName(CSS.textBoxPanelDisabled()); m_enabled = true; } else if (m_enabled && !enabled) { // if state changed to disable then remove all click handlers for (HandlerRegistration registration : m_clickHandlerRegistrations) { registration.removeHandler(); } m_clickHandlerRegistrations.clear(); m_textboxContainer.addStyleName(CSS.textBoxPanelDisabled()); setErrorMessage(null); m_enabled = false; } m_textbox.setEnabled(m_enabled); }
1e6ea2a9-0b7b-4279-8beb-6311d95549c2
7
public static void main(String[] args) { try { for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { e.printStackTrace(); } widener.setPreferredSize(new Dimension(208, 0)); result.setLayout(new GridLayout()); immunities.setLayout(new GridLayout(0, 5, 2, 2)); resistances.setLayout(new GridLayout(0, 5, 2, 2)); vulnerabilities.setLayout(new GridLayout(0, 5, 2, 2)); majorVulnerabilities.setLayout(new GridLayout(0, 5, 2, 2)); majorResistances.setLayout(new GridLayout(0, 5, 2, 2)); immunityLabel.setToolTipText("No damage will be taken"); resistanceLabel.setToolTipText("These will only inflict half damage"); vulnerabilityLabel.setToolTipText("Damage will be doubled from these sources"); majorResistLabel.setToolTipText("These will only do a fourth of the damage"); majorVulnLabel.setToolTipText("These will inflict four times the damage!"); JComboBox<String> typeList = new JComboBox<>(); JComboBox<String> typeList2 = new JComboBox<>(); JComboBox<String> pokemonList = new JComboBox<>(); JLabel helpMessage = new JLabel("To begin: Search a pokemon or set type below"); result.add(helpMessage, SwingConstants.CENTER); for (Element e : Element.values()) { typeList.addItem(e.toString()); typeList2.addItem(e.toString()); } for (Pokemon p : Pokemon.values()) { pokemonList.addItem(p.toString()); } AutoCompletion.enable(pokemonList); ItemListener pokemonListener = e -> { if (e.getStateChange() == ItemEvent.SELECTED) { typeList.setSelectedItem(getPokemon((String) pokemonList.getSelectedItem()).primaryType.toString()); typeList2.setSelectedItem(getPokemon((String)pokemonList.getSelectedItem()).secondaryType.toString()); } }; pokemonList.addItemListener(pokemonListener); Font font = new Font("Comic Sans MS", Font.BOLD, 12); typeList.setFont(font); typeList2.setFont(font); pokemonList.setFont(font); typeList.setSelectedItem(Element.NORMAL.toString()); ItemListener typeListener = e -> { if (e.getStateChange() == ItemEvent.SELECTED) { displayAttributes(getPokemonType((String)typeList.getSelectedItem()), getPokemonType((String)typeList2.getSelectedItem()) ); } }; typeList.addItemListener(typeListener); typeList2.addItemListener(typeListener); selectionPanel.add(pokemonList); selectionPanel.add(typeList); selectionPanel.add(typeList2); frame.add(widener, BorderLayout.NORTH); frame.add(result, BorderLayout.CENTER); frame.add(selectionPanel, BorderLayout.SOUTH); frame.setIconImage(new ImageIcon("Images/Icon.png").getImage()); frame.pack(); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); }
693da1ec-ff8d-4277-9187-f568491a7c8b
0
public Player returnPlayer(){ return storage; }
40db93f7-58bc-4772-a07c-69ab0b138852
5
public String getUsername() { String username = ""; if (type == 0 || type == 1) { if (menuComponents != null) { if (menuComponents.get(0) != null) { try { username = ((MenuTextBoxV2) menuComponents.get(0)) .getSubmitted(); } catch (Exception e) { } } } } return username; }
c773d748-b48c-49ab-a44e-df03f8bdc59f
7
public void update(double theta) { // position.x += theta * direction.x; obstacle.position.y += theta * velocity.y; if (obstacle.position.y > Main.game.player.main.position.y - 2 * Main.game.player.main.size && obstacle.position.y < Main.game.player.main.position.y + 2 * Main.game.player.main.size){ if(obstacle.position.x + obstacle.size > Main.game.player.main.position.x - Main.game.player.main.size && obstacle.position.x - obstacle.size < Main.game.player.main.position.x + Main.game.player.main.size){ // Collision: switch(type){ case NORMAL: obstacle.color = new float[] {0.6f,0.0f,0.0f}; Main.game.die(); break; case BONUS: obstacle.position.x = 100f; Main.game.score += 3; break; } } } if (obstacle.position.y > 1) { obstacle.position.x = (float) Math.random() * 2 - 1; velocity.y = (float) Math.random(); obstacle.position.y = -1; Main.game.score += 1; } shadow.position.x = obstacle.position.x - 0.01f; shadow.position.y = obstacle.position.y - 0.01f; }
46c3de75-9a2c-424d-a918-c1629c7ceb13
5
public static String pformat(Collection<?> c){ if(c.size() == 0) return "[]"; StringBuilder result = new StringBuilder("["); for(Object elem : c){ if(c.size() != 1) result.append("\n "); result.append(elem); } if(c.size() != 1) result.append("\n"); result.append("]"); return result.toString(); }
dac8d982-e108-4918-83c0-22af05b2c153
8
private int checkBox(GameBoardMark playerMark) { for (int k = 1; k < 8; k++) { for (int l = 1; l < 8; l++) { int cnt = 0; int pos = -1; for (int a = 0; a < 2; a++) { for (int b = 0; b < 2; b++) { int x = k + a + 10 * (l + b); int c = gameBoard.mainBoard()[x]; if (c == playerMark.index) cnt++; else if (c == 0) pos = x; } } if (cnt == 3 && pos != -1) return pos; } } return GameBoard.oneMoreThanLastPositionOnBoard; }
76f60e33-a199-4afc-92f6-5719d43be740
5
private void drawObjects(Graphics g) { if (craft.isVisible()) { g.drawImage(craft.getImage(), craft.getX(), craft.getY(), this); } ArrayList<Missile> alMissiles = craft.getMissiles(); for (Missile m : alMissiles) { if (m.isVisible()) { g.drawImage(m.getImage(), m.getX(), m.getY(), this); } } for (Alien a : alAliens) { if (a.isVisible()) { g.drawImage(a.getImage(), a.getX(), a.getY(), this); } } g.setColor(Color.WHITE); g.drawString("Aliens left: " + alAliens.size(), 5, 15); }
3d9fb3a7-01d1-47c0-b56e-6a605924dfd9
2
public static void main(String [] args) throws SQLException { DataInitialization thing = new DataInitialization(); if (args[0].equals("destroy")) { thing.destroyData(); } else if (args[0].equals("init")) { thing.initialData(); } }
03115389-a31a-45dc-bc7f-b4b857735b7e
9
public void writeUTF(String s) throws IOException { int numchars = s.length(); int numbytes = 0; for (int i = 0; i < numchars; i++) { int c = s.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) numbytes++; else if (c > 0x07FF) numbytes += 3; else numbytes += 2; } if (numbytes > 65535) throw new UTFDataFormatException(); out.write((numbytes >>> 8) & 0xFF); out.write(numbytes & 0xFF); for (int i = 0; i < numchars; i++) { int c = s.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { out.write(c); } else if (c > 0x07FF) { out.write(0xE0 | ((c >> 12) & 0x0F)); out.write(0x80 | ((c >> 6) & 0x3F)); out.write(0x80 | (c & 0x3F)); } else { out.write(0xC0 | ((c >> 6) & 0x1F)); out.write(0x80 | (c & 0x3F)); } } }
44433703-83ab-41fc-98c6-8866d13c19a9
4
public static DCPackage getPackage(byte[] raw) throws InputMismatchException{ if(raw.length != PACKAGE_SIZE) { throw new InputMismatchException("The size of the raw byte input is " + raw.length+" and does not match the expected package size " + PACKAGE_SIZE); } else { byte number = raw[0]; if(number < 0 || number > getNumberRange()) { throw new InputMismatchException("The round number " + number + " is out of bounds"); } byte[] payload = new byte[PAYLOAD_SIZE]; int payloadOffset = HEADER_SIZE; for(int i = 0; i < PAYLOAD_SIZE; i++) { payload[i] = raw[i+payloadOffset]; } return new DCPackage(number, payload); } }
43e475df-2618-4aad-a0ef-a2260ccc897a
2
public void process(float newSpeed, double newLatitude, double newLongitude, long newTimeStamp, float newAccuracy) { // Uncomment this, if you are receiving accuracy from your gps // if (newAccuracy < Constants.MIN_ACCURACY) { // newAccuracy = Constants.MIN_ACCURACY; // } if (variance < 0) { // if variance < 0, object is unitialised, so initialise with current values setState(newLatitude, newLongitude, newTimeStamp, newAccuracy); } else { // else apply Kalman filter long duration = newTimeStamp - this.timeStamp; if (duration > 0) { // time has moved on, so the uncertainty in the current position increases variance += duration * newSpeed * newSpeed / 1000; timeStamp = newTimeStamp; } // Kalman gain matrix 'k' = Covariance * Inverse(Covariance + MeasurementVariance) // because 'k' is dimensionless, // it doesn't matter that variance has different units to latitude and longitude float k = variance / (variance + newAccuracy * newAccuracy); // apply 'k' latitude += k * (newLatitude - latitude); longitude += k * (newLongitude - longitude); // new Covariance matrix is (IdentityMatrix - k) * Covariance variance = (1 - k) * variance; // Export new point exportNewPoint(newSpeed, longitude, latitude, duration); } }
309d0369-09bb-40ce-af90-98d505c3d150
9
public boolean copy(String frompath, long every, URI tofttppath){//every 8m /*System.out.println("tofttppath:"+tofttppath); System.out.println("this.host:"+this.host); System.out.println("this.port:"+this.port); System.out.println("tofttppath.getHost:"+tofttppath.getHost()); System.out.println("tofttppath.getPort:"+tofttppath.getPort());*/ boolean r=true; FileAdapter fa = new FileAdapter(frompath); if(this.host.equals(tofttppath.getHost())&&this.port==getFttpPort(tofttppath)){ if(fa.isDirectory()||fa.length()!=fa.copyTo(tofttppath.getPath(),every)) r=false; }else{ Workman wm = getWorkerElse(FTTPSN, tofttppath.getHost(), getFttpPort(tofttppath)); //just for file WareHouse inhouse = new WareHouse("filepath", tofttppath.getPath()); byte[] bts = null; long begin=0; while((bts=fa.getReader(begin, every).readAll())!=null){//readAllSafety inhouse.setObj("filebytes",bts); if(!wm.receive(inhouse)){ r=false; break; } begin+=bts.length; } if(begin==0&&fa.isFile()&&r){ inhouse.setObj("filebytes",bts); r=wm.receive(inhouse); } } fa.close(); return r; }
07cf4f42-ce83-4458-8e3d-eb0ae9322829
9
@Override public Object visitExpression(ExpressionContext ctx, CalcScope scope) { setCurrentScope(scope); CalcValue value = new CalcValue(); value.setType(int.class); if (ctx.getChildCount() == 1) { if (ctx.integerLiteral() instanceof CalcParser.IntegerLiteralContext) { value.setValue(visitIntegerLiteral(ctx.integerLiteral(), scope)); } else { CalcVariable variable = scope.child(ctx.ID().getText()); if (variable == null) { throw new CalcException("VARIABLE: " + ctx.ID().getText() + " NOT DECLARED!"); } value = scope.child(ctx.ID().getText()).getVariableValue(); } } else { if (ctx.getChild(0).getText().equals("(")) { value = (CalcValue) visitExpression(ctx.expression(0), scope); } else { CalcValue left = (CalcValue) visitExpression(ctx.expression(0), scope); CalcValue right = (CalcValue) visitExpression(ctx.expression(1), scope); if (ctx.op.getType() == CalcParser.ADD) { value.setValue(((Integer) left.getValue() + (Integer) right.getValue())); } else if (ctx.op.getType() == CalcParser.SUB) { value.setValue(((Integer) left.getValue() - (Integer) right.getValue())); } else if (ctx.op.getType() == CalcParser.MUL) { value.setValue(((Integer) left.getValue() * (Integer) right.getValue())); } else if (ctx.op.getType() == CalcParser.DIV) { value.setValue(((Integer) left.getValue() / (Integer) right.getValue())); } else if (ctx.op.getType() == CalcParser.MOD) { value.setValue(((Integer) left.getValue() % (Integer) right.getValue())); } } } return value; }
a94ce08b-8a3c-420a-a042-8daa21eb1fe3
7
@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); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> magically call(s) for a loyal steed.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final MOB target = determineMonster(mob, mob.phyStats().level()+((getX1Level(mob)+getXLEVELLevel(mob))/2)); final MOB squabble = checkPack(target, mob); beneficialAffect(mob,target,0,asLevel); if(squabble==null) { if (target.isInCombat()) target.makePeace(true); CMLib.commands().postFollow(target,mob,true); invoker=mob; if (target.amFollowing() != mob) mob.tell(L("@x1 seems unwilling to follow you.",target.name(mob))); } else { squabble.location().showOthers(squabble,target,CMMsg.MSG_OK_ACTION,L("^F^<FIGHT^><S-NAME> bares its teeth at <T-NAME> and begins to attack!^</FIGHT^>^?")); target.setVictim(squabble); } } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> call(s) for a steed, but choke(s) on the words.")); // return whether it worked return success; }
6cb13d38-df51-4b07-a8c4-0e1ccf90d632
0
public Worker () { //initial settings isInputActive = true; this.keyboard = new BufferedReader(new InputStreamReader(System.in)); students = new HashMap<String, Student>(); System.out.println(MSG_WELCOME); //start this.lifeCycle(); }
55672683-e6d9-4be8-b061-21ed93e11191
3
private void getCurrentSettings() { System.out.println("SW| start getCurSets"); mySets = new Settings(); try { FileInputStream fs = new FileInputStream("settings.txt"); ObjectInputStream os = new ObjectInputStream(fs); Object obj = os.readObject(); mySets = (Settings) obj; System.out.println("SW| guessNumber:" + mySets.getNumberOfGuessableWords()); os.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // return mySets; }
c759fbfc-2061-4f84-b431-21eeb7a1aa77
1
public VideoStore() throws Exception { try{ String username = "cs5530u33"; String password = "mdtiepn5"; String url = "jdbc:mysql://georgia.eng.utah.edu/cs5530db33"; Class.forName ("com.mysql.jdbc.Driver").newInstance (); connection = DriverManager.getConnection (url, username, password); /*//DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); //stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt = con.createStatement(); //stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);*/ } catch(Exception e) { System.err.println("Unable to open mysql JDBC connection. The error is as follows,"); System.err.println(e.getMessage()); throw e; } }
a875d704-1a2c-464b-bd72-31591f0d5f1c
4
public int itc(Model model){ int res = 0; for(Operation op : this.getArrayOperation()){ for(Argument arg : op.getArg()){ for(Classe c : model.getClasse()){ if(arg.getType().trim().equals(c.getIdentifier().trim())){ res++; } } } } //System.out.println("La Classe " + this.identifier + " possedent " + res + " classes du model comme type d'arguments"); return res; }
c834f2c3-c141-4dad-b996-0f2bbfd5fd0f
5
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String xquery = "<xml>{ for $cedar in collection('CED2AR') return "; String[] query = request.getParameter("query").split(" "); for(int i = 0; i < query.length; i++){ if(i == 0){ xquery += "$cedar/codeBook/dataDscr/var[contains(labl, '"+query[i]+"')"; } else{ xquery += " and contains(labl, '"+query[i]+"')"; } } xquery += "]}</xml>"; String xml = Functions.getXML(xquery); PrintWriter out = response.getWriter(); //out.write(xquery); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); Document doc = db.parse(is); NodeList variableNames = doc.getElementsByTagName("var"); out.print("<table class=\"codebookTable\">"); for (int i = 0; i < variableNames.getLength(); i++) { out.print("<tr>"); Element element = (Element) variableNames.item(i); out.print("<td class=\"tdLeft\"><a href=\"SimpleSearchViewVariable?variableName=" + element.getAttributes().getNamedItem("name").getNodeValue() + "&codebook=ACS2009G\" class=\"variableName\">" + element.getAttributes().getNamedItem("name").getNodeValue() + "</a></td>"); try { NodeList label = element.getElementsByTagName("labl"); out.print("<td class=\"tdRight\">" + label.item(0).getFirstChild().getNodeValue() + "</td>"); out.print("</tr>"); } catch (NullPointerException ne){ out.print("<td class=\"tdRight\"></td>"); out.print("</tr>");} } out.print("</table>"); } catch (Exception e) { e.printStackTrace(); } out.close(); }
13c818ab-a786-4a7a-9659-dbbf206b7392
0
public boolean isVisible(int row, int col){ return (visited[row][col] == RoomState.VISITED); }
63bed32c-cad4-4c73-9ba1-21203dae3f09
9
static void lsp_to_curve(float[] curve, int[] map, int n, int ln, float[] lsp, int m, float amp, float ampoffset){ int i; float wdel=M_PI/ln; for(i=0; i<m; i++) lsp[i]=Lookup.coslook(lsp[i]); int m2=(m/2)*2; i=0; while(i<n){ int k=map[i]; float p=.7071067812f; float q=.7071067812f; float w=Lookup.coslook(wdel*k); for(int j=0; j<m2; j+=2){ q*=lsp[j]-w; p*=lsp[j+1]-w; } if((m&1)!=0){ /* odd order filter; slightly assymetric */ /* the last coefficient */ q*=lsp[m-1]-w; q*=q; p*=p*(1.f-w*w); } else{ /* even order filter; still symmetric */ q*=q*(1.f+w); p*=p*(1.f-w); } // q=frexp(p+q,&qexp); q=p+q; int hx=Float.floatToIntBits(q); int ix=0x7fffffff&hx; int qexp=0; if(ix>=0x7f800000||(ix==0)){ // 0,inf,nan } else{ if(ix<0x00800000){ // subnormal q*=3.3554432000e+07; // 0x4c000000 hx=Float.floatToIntBits(q); ix=0x7fffffff&hx; qexp=-25; } qexp+=((ix>>>23)-126); hx=(hx&0x807fffff)|0x3f000000; q=Float.intBitsToFloat(hx); } q=Lookup.fromdBlook(amp*Lookup.invsqlook(q)*Lookup.invsq2explook(qexp+m) -ampoffset); do{ curve[i++]*=q; } while(i<n&&map[i]==k); } }
92f9a604-4737-46f1-bedb-62cb914bbf59
1
public CashOffice registerCashOffice(CashOffice cashOffice) { int index = cashOffices.indexOf(cashOffice); if (index == -1) { addCashOffice(cashOffice); return cashOffice; } else { CashOffice foundedCashOffice = cashOffices.get(index); // Iterator<Ticket> tickets = cashOffice.tiketsIterator(); // while (tickets.hasNext()) { // foundedCashOffice.addTicket(tickets.next()); // } return foundedCashOffice; } }
7b946485-9120-467e-b488-689350a2d400
4
@Test public void testDir() { Path dir = Paths.get("F:\\\\tmp"); //这个只能列出当前目录下符合的文件 try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.txt")) { System.out.println("=========DirectoryStream start========="); for (Path path : stream) { System.out.println(path); } System.out.println("=========DirectoryStream end========="); } catch (IOException e) { e.printStackTrace(); } //这个将递归列出所有符合的文件 try { System.out.println("=========walkFileTree start========="); Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) { if (path.toString().endsWith(".txt")) { System.out.println(path); } return FileVisitResult.CONTINUE; } }); System.out.println("=========walkFileTree end========="); } catch (IOException e) { e.printStackTrace(); } }
3490265d-7d43-4926-a25e-b256785f2822
5
GUI() { super("Michelizer (" + Resources.VERSION_NUMBER + " - " + Resources.VERSION_CODENAME + ") - The All-In-One ECE 460 Solver"); FlowLayout fl = new FlowLayout(); fl.setAlignment(FlowLayout.LEFT); setLayout(fl); createPane1(); createPane2(); createPane3(); createPane4(); createPane5(); createPane6(); jTP.setPreferredSize(new Dimension(300, 490)); jTP.addTab("Queues", pane_queue); jTP.addTab("Service Demand", pane_serviceDemand); jTP.addTab("Systems", pane_systems); jTP.addTab("Poisson", pane_poisson); jTP.addTab("Disk Access Time", pane_diskAccessTime); jTP.addTab("Clustering", pane_clustering); add(jTP); jTP.setSelectedIndex(1); jTP.addChangeListener(this); jTPQueue.addChangeListener(this); jTPSystems.addChangeListener(this); recursivelyAddKeyListener((JComponent)((JComponent)((JComponent)this.getComponent(0)).getComponent(1)).getComponent(0)); helpPane.setFont(new Font("Verdana", Font.PLAIN, 12)); helpPane.setPreferredSize(new Dimension(475, 490)); ((JTextArea)((JViewport)helpPane.getComponent(0)).getView()).setEditable(false); ((JTextArea)((JViewport)helpPane.getComponent(0)).getView()).setLineWrap(true); ((JTextArea)((JViewport)helpPane.getComponent(0)).getView()).setText(Resources.HELP_SERVICE_DEMAND); add(helpPane); Thread t1 = (new Thread() { @Override public void run() { JTextArea help = ((JTextArea)((JViewport)helpPane.getComponent(0)).getView()); while(true) { while(nCEnabled) { try { Thread.sleep(500); } catch(Exception e) { e.printStackTrace(); } if(help.getText().equals(Resources.NC_1)) help.setText(Resources.NC_2); else help.setText(Resources.NC_1); } while(!nCEnabled); } } }); t1.start(); }
5d60b774-d1d0-41c6-9b38-50935728eac0
6
public Header readFrame() throws BitstreamException { Header result = null; try { result = readNextFrame(); // E.B, Parse VBR (if any) first frame. if (firstframe == true) { result.parseVBR(frame_bytes); firstframe = false; } } catch (BitstreamException ex) { if ((ex.getErrorCode()==INVALIDFRAME)) { // Try to skip this frame. //System.out.println("INVALIDFRAME"); try { closeFrame(); result = readNextFrame(); } catch (BitstreamException e) { if ((e.getErrorCode()!=STREAM_EOF)) { // wrap original exception so stack trace is maintained. throw newBitstreamException(e.getErrorCode(), e); } } } else if ((ex.getErrorCode()!=STREAM_EOF)) { // wrap original exception so stack trace is maintained. throw newBitstreamException(ex.getErrorCode(), ex); } } return result; }
8891d13b-edf7-4b15-b2bd-c34b992bfd4c
8
public static void main(String[] args) { Connection conn = null; PreparedStatement pstat = null; ResultSet rs = null; try { Class.forName("org.h2.Driver"); /** * jdbc:h2:tcp://<server>[:<port>]/[<path>]<databaseName> * jdbc:h2:tcp://localhost/~/test * jdbc:h2:tcp://dbserv:8084/~/sample * jdbc:h2:tcp://localhost/mem:test */ conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/dbdemo;MODE=Oracle", "sa", ""); pstat = conn.prepareStatement("SELECT * FROM INFORMATION_SCHEMA.TABLES "); rs = pstat.executeQuery(); while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally{ try { if (rs != null) { rs.close(); } if (pstat != null) { pstat.close(); } if (conn != null && !conn.isClosed()) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
6bc597a2-6dd6-4c49-9d38-f3f84a5dc90b
5
public static MaplePacket showAllianceMembers(MapleCharacter chr) { MaplePacketLittleEndianWriter mplew = new MaplePacketLittleEndianWriter(); mplew.writeShort(SendPacketOpcode.ALLIANCE_OPERATION); mplew.write(0x0D); MapleAlliance az = chr.getGuild().getAlliance(chr.getClient()); int e = 0; for (int u = 0; u < 5; u++) { if (az.getGuilds().get(u) != null) { e++; } } mplew.writeInt(e);//ammount of guilds joined chr.setGuildRank(chr.getGuild().getMGC(chr.getId()).getGuildRank()); for (int i = 0; i < 5; i++) { MapleGuild g = az.getGuilds().get(i); if (g != null) { mplew.writeInt(g.getId()); mplew.writeMapleAsciiString(g.getName()); for (int a = 1; a <= 5; a++) { mplew.writeMapleAsciiString(g.getRankTitle(a)); } g.addMemberData(mplew); mplew.writeInt(g.getCapacity()); mplew.writeShort(g.getLogoBG()); mplew.write(g.getLogoBGColor()); mplew.writeShort(g.getLogo()); mplew.write(g.getLogoColor()); mplew.writeMapleAsciiString(g.getNotice()); mplew.writeInt(g.getGP()); mplew.write(HexTool.getByteArrayFromHexString("0F 03 00 00")); } } return mplew.getPacket(); }
0332a55c-be55-4dac-9385-d25fd04db793
7
public void createDatabase() { try { Class.forName("com.mysql.jdbc.Driver"); //String url = "jdbc:mysql://127.0.0.1/interactive_house?user=root&password="; Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/?user=root&password=root"); ResultSet resultSet = con.getMetaData().getCatalogs(); Statement st = con.createStatement(); String query; boolean check = false; while (resultSet.next()) { // Get the database name //databaseName.add(resultSet.getString(1)); if (resultSet.getString(1).equals("interactive_house")) { System.out.println("Database exists"); check = true; } } if (check == false) { query = "CREATE DATABASE IF NOT EXISTS interactive_house"; st.executeUpdate(query); System.out.println("Database Created"); } con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/interactive_house?user=root&password=root"); st = con.createStatement(); query = "CREATE TABLE IF NOT EXISTS `devices` (`deviceId` int(20) NOT NULL,`deviceName` varchar(40) NOT NULL,`deviceState` varchar(40) NOT NULL, PRIMARY KEY (`deviceId`))"; st.executeUpdate(query); //System.out.println("Devices Table Created"); query = "SELECT * FROM devices"; ResultSet rs = st.executeQuery(query); if (!rs.next()) { query = "INSERT INTO `devices` VALUES (1,'lightIn','on'),(2,'lightOut','on'),(3,'fan','off'),(4,'heaterRoom','off'),(5,'heaterLoft','off'),(6,'tempRoom','10'),(7,'tempLoft','12'),(8,'door','open'),(9,'stove','off'),(10,'coffee','off'),(11,'bath','on'),(12,'wash','off'),(13,'media','off')"; st.executeUpdate(query); System.out.println("Data Inserted in Device Table"); } query = "CREATE TABLE IF NOT EXISTS `users` (`userid` int(10) NOT NULL AUTO_INCREMENT,`username` varchar(25) DEFAULT NULL,`password` varchar(200) DEFAULT NULL, `access` varchar(25) DEFAULT NULL,PRIMARY KEY (`userid`))"; st.executeUpdate(query); //System.out.println("User Table Created"); query = "SELECT * FROM users"; rs = st.executeQuery(query); if (!rs.next()) { String houseMaster = cryptPassword("HouseMaster"); String housePerson = cryptPassword("HousePerson"); String anotherPerson = cryptPassword("AnotherPerson"); query = "INSERT INTO `userss` (`userid`, `username`, `password`, `access`) VALUES (1, 'HouseMaster','" + houseMaster + "','admin'),(2, 'HousePerson','" + housePerson + "', 'low'), (3, 'AnotherPerson','" + anotherPerson + "', 'high')"; st.executeUpdate(query); System.out.println("Data Inserted in users Table"); } resultSet.close(); con.close(); } catch (ClassNotFoundException ex) { Logger.getLogger(DatabaseQuery.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(DatabaseQuery.class.getName()).log(Level.SEVERE, null, ex); } }
d36c35e2-2647-4441-be72-2cd859e9f930
9
public Vector2 getCollisionPoint(Segment2D other) { Vector2 p = getIntersectionPoint(other); if (p == null) return null; if ((p.x >= start.x && p.x <= end.x) || (p.x >= end.x && p.x <= start.x)) { if ((p.y >= start.y && p.y <= end.y) || (p.y >= end.y && p.y <= start.y)) return p; } return null; }
21b24034-4585-4146-b788-6c925f89cdf7
4
public void start(Stage primaryStage) throws IOException, URISyntaxException { musicList = new ArrayList<>(); File musicFile = new File("src/gameMusic"); System.out.println("\"src/gameMusic\" exists?; " + musicFile.exists()); String file = "file:///" + musicFile.getAbsolutePath().replace('\\', '/'); System.out.println("Path is: " + file); for (String i : musicFile.list()) { if (!i.endsWith(".mp3")) continue; musicList.add(new Media(file + "/" + i)); } openScreen = new Media(file + "/menuMusic/EveningOfChaos.mp3"); menuSwitch = new SimpleBooleanProperty(true); listen = new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) { player.stop(); if (menuSwitch.get()) { player = menuBuilder.media(openScreen).build(); } else { player = gameBuilder.media( musicList.get(rand.nextInt(musicList.size()))).build(); } } }; menuSwitch.addListener(listen); // Attaches the 'on Ready, play' runnable to the builder menuBuilder = MediaPlayerBuilder.create().onReady(new Runnable() { @Override public void run() { player.play(); } }).onEndOfMedia(new Runnable() { @Override public void run() { player = menuBuilder.media(openScreen).build(); } }); player = menuBuilder.media(openScreen).build(); gameBuilder = MediaPlayerBuilder.create().onReady(new Runnable() { @Override public void run() { player.play(); } }). // Adds the looping scheme to the builder for in game music onEndOfMedia(new Runnable() { @Override public void run() { int val = rand.nextInt(musicList.size()); System.out.println("Changed to song " + val); player = gameBuilder.media(musicList.get(val)).build(); } }); isReadyFX = true; }
88232016-0617-449f-9baa-e86b1975a1ce
1
public static void main(String[] args) { Man[] myarray = new Man[4]; myarray[0] = new Employee("Mykola", "Myronov"); myarray[1] = new Employee("Evgen", "Mazek"); myarray[2] = new Employee("Олег", "Спека"); myarray[3] = new Employee("Олег", "Спека"); for (Man variant : myarray){ System.out.println(variant.getName()+" "+variant.getSurname()); } System.out.println(Arrays.toString(myarray)); System.out.println(myarray[2]==myarray[3]); System.out.println(myarray[2].equals(myarray[3])); System.out.println(myarray[2].hashcode()); }
49d7d2ef-400c-4f06-a9fa-20fc82708975
0
@Test public void testGetContent() throws Exception { new BibleContentTw().getContent(); }
769be7df-3e9b-4e63-aeb3-84f915eb1687
0
public String echo(String message) { return "hello: " + message; }
e1686a4e-0c33-4bd8-96b2-3b9b8ce32f1c
5
private Node getLowestFNode() { Node out = null; synchronized (OPENLIST) { for (Node n : OPENLIST) { if (out == null) out = n; else { if (n.F < out.F) out = n; } } } if (details && out != null) System.out.println("Lowest F Node: ("+out.x+","+out.y+")"); return out; }
b950c36b-b9a8-462b-a137-e7d122457c29
6
public static Moves getRemainingExpansionMoves(BotState state) { Moves out = new Moves(); List<Region> borderRegions = state.getVisibleMap().getBorderRegions(state); List<Region> valuableExpansionRegions = new ArrayList<>(); for (Region borderRegion : borderRegions) { if (isExpandingValuable(state, borderRegion)) { valuableExpansionRegions.add(borderRegion); } } // Now that we found out which regions are good to make an expansion // move calculate the expansion moves. for (Region valuableExpansionRegion : valuableExpansionRegions) { List<Region> possibleToRegions = getNeighborsWithinMostDesirableSuperregion(valuableExpansionRegion, state); List<Region> orderedPossibleToRegions = RegionValueCalculator.sortRegionsByExpansionRegionValue(state, possibleToRegions); Region toRegion = orderedPossibleToRegions.get(0); if (valuableExpansionRegion.getIdleArmies() > 2 || (valuableExpansionRegion.getIdleArmies() == 2 && toRegion.getArmies() == 1)) { int valuableExpansionRegionIdleArmies = valuableExpansionRegion.getIdleArmies(); AttackTransferMove move = new AttackTransferMove(state.getMyPlayerName(), valuableExpansionRegion, toRegion, valuableExpansionRegionIdleArmies); out.attackTransferMoves.add(move); } } MovesPerformer.performMoves(state, out); return out; }
3f049bc3-c0e2-4e50-95ed-cf3c946677bd
6
private static JsonObject parseObj(Buffer<Token> buf) throws JsonParseException { Token tkn = buf.next(); if (!"{".equalsIgnoreCase(tkn.str)) { throw new JsonParseException("Found \"%s\" at line %s, col %s; Was expecting \"{\"", tkn.str, tkn.line, tkn.col); } JsonObject ret = new JsonObject(); boolean kill = false; while (!"}".equalsIgnoreCase((tkn = buf.next(false)).str)) { skipWhitespace(buf); String name = parseString(buf); skipWhitespace(buf); tkn = buf.next(); if (!":".equalsIgnoreCase(tkn.str)) { throw new JsonParseException("Found \"%s\" for keypair %s at line %s, col %s; Was expecting \":\"", tkn.str, name, tkn.line, tkn.col); } skipWhitespace(buf); Object data = parseValue(buf); if (!ret.add(name, data)) { throw new JsonParseException("Duplicate key: %s", name); } skipWhitespace(buf); tkn = buf.next(); if (!",".equalsIgnoreCase(tkn.str)) { if (kill) { throw new JsonParseException("Found \"%s\" at line %s, col %s; Was expecting a comma", tkn.str, tkn.line, tkn.col); } kill = true; } skipWhitespace(buf); } return ret; }
5fb702d0-1292-4b2e-bf14-8c209f1b7096
9
public boolean twoOpt(){ int pathLength=tour.length(); int k=Math.min(160, pathLength); int progress=0; boolean better=false; outer: for(int currentVerticeIndex=0; currentVerticeIndex<pathLength;currentVerticeIndex++){ // for(int currentVerticeIndex=0; progress<pathLength; progress++){ // currentVerticeIndex=Help.mod2(progress, pathLength); int nextVerticeIndex=(currentVerticeIndex+1)%pathLength; int previousVerticeIndex=Help.mod2(currentVerticeIndex-1, pathLength); int distOldEdge=tour.indexDistance(currentVerticeIndex, nextVerticeIndex); //goes the edges in sorted order for(int iters=0;iters<k;iters++){ //want index in path instead int toVertice=se.getXNeighbor(tour.getVertice(currentVerticeIndex), iters); if(toVertice!=tour.getVertice(currentVerticeIndex) && toVertice!=tour.getVertice(previousVerticeIndex) && toVertice!=tour.getVertice(nextVerticeIndex)){ // // toVertice= Help.circleIncrement(toVertice, pathLength); int distNewEdge=ug.dist(tour.getVertice(currentVerticeIndex), toVertice); if(distNewEdge>=distOldEdge){ break; } //check if edge to swapwith is better than edge from current to next if(distNewEdge < distOldEdge ){ int swapWithIndexInPath=Help.indexInArray(tour.path, toVertice); // int swapWithIndexInPath=Help.indexInArray(tour.path, toVertice); //check if second edge swap if it really is an improvement if(swapIfBetterTwoOpt(nextVerticeIndex,swapWithIndexInPath)){ //it was better so complete the reversing int innerFrom=(nextVerticeIndex+1)%pathLength; int innerTo= swapWithIndexInPath==0 ? pathLength-1 : swapWithIndexInPath-1; tour.reverseSubPath(innerFrom, innerTo); better=true; // test! // currentVerticeIndex= currentVerticeIndex==0 ? pathLength-2 : currentVerticeIndex-1; } } } } } return better; }
992318ca-9e9a-4047-b644-89aec9413a80
0
public void setjLabelNom(JLabel jLabelNom) { this.jLabelNom = jLabelNom; }
ba90ce75-7253-49d6-8322-5519f3760f02
3
public void idle(){ if (!armChannel.getAnimationName().equals("ArmIdle") && !hasSwung){ armChannel.setAnim("ArmIdle"); } if (!legChannel.getAnimationName().equals("LegsIdle")){ legChannel.setAnim("LegsIdle"); } }
6438361d-0405-491d-bd2a-b69fa8adcf0e
1
private void resize(int capacity) { assert capacity >= N; Key k[] = (Key[]) new Comparable[capacity]; Value v[] = (Value[]) new Object[capacity]; System.arraycopy(keys, 0, k, 0, (keys.length < k.length) ? keys.length : k.length); keys = k; System.arraycopy(vals, 0, v, 0, vals.length); vals = v; }
bf3044e4-4002-447a-b803-8ecf82a68db6
7
public boolean deleteReminder(String pid,int alertType){ logger.error("Deleting the patient with patient id:"+pid+" for alert:"+alertType); boolean deletePatient=false;PAlert patientAlert=null; Patient patient=getPatient(pid); List list=getpatientAlert(pid,alertType); if(list!=null && list.size()>0) patientAlert=(PAlert) list.get(0); else{ logger.info("Patient with pid:"+pid+"\t is not register for this alert"); return false; } List allList=getpatientAllAlert(pid); if(allList.size()==1 && patient!=null) deletePatient=true; try{ Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); if(patientAlert!=null){ session.delete(patientAlert); if(deletePatient) session.delete(patient); } session.getTransaction().commit(); session.close(); return true; } catch(Exception ex){ logger.error("unable to delete patient"); return false; } }
530d7aaf-44d1-4668-b716-f8877b2780a4
7
private Response takeAnswer() throws IOException{ //Implementation to take answer input. Used for storing user responses and storing answer keys. String s; HashMap<String, ArrayList<String>> dictAns = new HashMap<String, ArrayList<String>>(); //HashMap to pass to Response for (int i=0; i < getLeft().size(); i++){ //Assign ranks for every value @SuppressWarnings("unchecked") ArrayList<String> copy = (ArrayList<String>) right.clone(); //Replacement of right to allow popping off options ArrayList<String> rank = new ArrayList<String>(); //Stores the matches Out.getDisp().renderLine("Enter the values for " + getLeft().get(i) + ":"); Out.getDisp().renderLine("Type \"-END-\" when finished for the current key."); boolean isEnd = false; //Boolean to keep looping until valid input confirmed while (!isEnd){ //Input loop boolean validInput = false; while (!validInput){ //Validity loop s = Input.inputString(); if (s.equals("-END-")){ //No more matches to this Option copy.clear(); //Skip for loop by clearing the array validInput = true; //Stop looping isEnd = true; //Stop outer looping } for (int j = 0; j < copy.size(); j++){ //Compare to every valid response if (s.equals(copy.get(j))){ //Good input validInput = true; //Stop looping rank.add(s); //Add to the array of matches copy.remove(j); //Remove the response as an option to avoid duplicates } } if (!validInput){ Out.getDisp().renderLine("Input is not one of the question's existing choices. Please input again."); } } //while (!validInput) } //while (!isEnd) dictAns.put(getLeft().get(i), rank); //Add to the Dict } //for (int i=1; i <= val; i++) return new RespDict(dictAns); }
18384227-ed76-4760-85e2-3e564ef9ad88
1
public static int getTypeSize(String typeSig) { return usingTwoSlots(typeSig.charAt(0)) ? 2 : 1; }
d472d805-f3cb-41e5-8e59-5c2198561af1
8
private static <T> T attemptLoad( final Class<T> ofClass, final String className) { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Attempting service load: " + className); } Level level; Throwable thrown; try { Class<?> clazz = Class.forName(className); if (!ofClass.isAssignableFrom(clazz)) { if (LOG.isLoggable(Level.WARNING)) { LOG.warning(clazz.getName() + " is not assignable to " + ofClass.getName()); } return null; } return ofClass.cast(clazz.newInstance()); } catch (LinkageError ex) { level = Level.FINEST; thrown = ex; } catch (ClassNotFoundException ex) { level = Level.FINEST; thrown = ex; } catch (InstantiationException ex) { level = Level.WARNING; thrown = ex; } catch (IllegalAccessException ex) { level = Level.WARNING; thrown = ex; } LOG.log(level, "Could not load " + ofClass.getSimpleName() + " instance: " + className, thrown); return null; }
c7d2d8ff-ef42-4be6-8d8b-ada7399fbd4b
2
public String doValidate(Number value) { long l = value.longValue(); if (l > max) return "Is larger than " + max; if (l < min) return "Is smaller than " + min; return null; }
d379bb0d-ce86-4013-8090-6106b9bad5ab
5
public static void loadConstants() { try { //get a connection to the constants file and read it final String fileName = "file:///" + CONSTANTS_FILE_NAME; printIfDebug("Opening constants file: " + fileName); FileConnection commandFileConnection = (FileConnection) Connector.open(fileName, Connector.READ); DataInputStream commandFileStream = commandFileConnection.openDataInputStream(); StringBuffer fileContentsBuffer = new StringBuffer((int) commandFileConnection.fileSize()); //read characters from the file until end of file is reached byte[] buff = new byte[255]; while (commandFileStream.read(buff) != -1) { fileContentsBuffer.append(new String(buff)); //inefficient, but with long files necessary buff = new byte[255]; } String fileContents = fileContentsBuffer.toString(); printIfDebug("Constants file output: " + fileContents); StringTokenizer lineTokenizer = new StringTokenizer(fileContents, "\n"); CONSTANTS = new Vector(lineTokenizer.countTokens()); //for each line, split into space-separated tokens while (lineTokenizer.hasMoreTokens()) { String line = lineTokenizer.nextToken().trim(); if (line.startsWith("#")) { continue; } StringTokenizer spaceTokenizer = new StringTokenizer(line, " "); //map the first two tokens if (spaceTokenizer.countTokens() > 1) { final String key = spaceTokenizer.nextToken().trim(); final String value = spaceTokenizer.nextToken().trim(); CONSTANTS.addElement(new Constant(key, value)); printIfDebug("Put constant: " + key + ": " + value + ", of type " + Constant.TYPE_NAMES[((Constant) CONSTANTS.lastElement()).getType()]); } } } catch (Exception ex) { System.out.println("Could not load file " + CONSTANTS_FILE_NAME + ". Are you sure it is in the root directory of the cRIO?"); } }
a3f058a7-a638-4644-b1e8-de78068a029a
8
public int[] searchRange(int[] A, int target) { // Start typing your Java solution below // DO NOT write main() function if (A.length == 0) { return new int[] { -1, -1 }; } int[] range = new int[2]; int start = 0; int end = A.length - 1; int mid; int left = -1; int right = -1; while (start <= end) { System.out.println("start " + start); System.out.println("end " + end); mid = (start + end) / 2; if (A[mid] == target) { left = mid; right = mid; for (int j = mid - 1; j >= 0; j--) { if (A[j] != target) { left = j + 1; break; } } for (int k = mid + 1; k < A.length; k++) { if (A[k] != target) { right = k - 1; break; } } break; } else if (target > A[mid]) { start = mid + 1; } else { end = mid - 1; } } range[0] = left; range[1] = right; return range; }
730db8fc-fc6c-4351-b520-77f123dc1d02
4
@Override public String toString() { StringBuilder sb = new StringBuilder(); for (int y = 0; y < boardSize; ++y) { for (int x = 0; x < boardSize; ++x) { String player = " "; if (intersections[x][y] == PLAYER_1) { player = "X"; } else if (intersections[x][y] == PLAYER_2) { player = "O"; } sb.append(player + " "); } sb.append("\n"); } return sb.toString(); }
3c091a29-b0b0-4baa-a899-00cba7cfc992
4
@Override protected void balancing() { super.balancing(); if (this.balance() == 2) { if (this.getRight().balance() >= 0) this.leftRotation(); else { this.getRight().rightRotation(); this.leftRotation(); } } else if (this.balance() == -2) { if (this.getLeft().balance() <= 0) this.rightRotation(); else { this.getLeft().leftRotation(); this.rightRotation(); } } else this.height(); }
98681c81-30d8-4960-ae2d-6f6e7d43c789
4
public Term negate() { Term[] t=new Term[sub.length]; boolean w=true; for(int i=0;i<t.length;i++) { if(w&&sub[i].isNegative()) { w=false; t[i]=sub[i].negate(); } else { t[i]=sub[i]; } } if(w) { t[0]=t[0].negate(); } return new Produkt(t); }
3bae5192-9852-4d33-9532-b4c10cfa3de6
5
@Override public void extract() throws XMLStreamException, FileNotFoundException { FileInfo ulic = this.bfis.get(Parser.Types.ULIC.toString()); this.factory = XMLInputFactory.newInstance(); this.readerRaw = factory.createXMLStreamReader(new BufferedInputStream(new FileInputStream(ulic.getFile()))); this.reader = factory.createFilteredReader(readerRaw, this.newLineFilter); while(reader.hasNext()) { int next = reader.next(); switch (next) { case XMLStreamConstants.START_ELEMENT: this.newElement(reader.getLocalName()); break; case XMLStreamConstants.CHARACTERS: tagContent = reader.getText().trim(); break; case XMLStreamConstants.END_ELEMENT: this.endElement(reader.getLocalName()); break; } if(streets.size() >= 1000) { this.save(); } parserMessages.sendProgress(reader.getLocation().getLineNumber(), ulic.getLines()); } this.save(); }
e38f4d0b-6be8-4591-8f23-b999f729fa37
6
public void choixActionBraquage() { int choix = 0; boolean recommencer = true; System.out.println("Que voulez-vous faire ?" + "\nVous avez le choix entre vous cacher (tapez 1) ou vous interposer (tapez 2)"); do{ try{ choix = keyboard.nextInt(); if(choix != 1 && choix!= 2 ){ throw new Exception("Ni 1 ni 2"); } else{ recommencer = false; } } catch(Exception e){ System.out.println("veuillez entrer 1, 2 ou 3"); keyboard.next(); } }while(recommencer); switch (choix) { case 1 : joueur.seCacher(); break; case 2 : joueur.interposerDansBraquage(); break; } }
32049e82-e1d8-4703-a96d-c4ff14c0e053
9
private void buildAmineDiConjunctiveSuffix(List<Element> words) throws StructureBuildingException { for (Element word : words) { if (!WordType.full.toString().equals(word.getAttributeValue(TYPE_ATR))){ throw new StructureBuildingException("Bug in word rule for amineDiConjunctiveSuffix"); } resolveWordOrBracket(state, word); } if (words.size() != 3) { throw new StructureBuildingException("Unexpected number of words encountered when processing name of type amineDiConjunctiveSuffix, expected 3 but found: " + words.size()); } Element aminoAcid = findRightMostGroupInWordOrWordRule(words.get(0)); if (aminoAcid == null) { throw new RuntimeException("OPSIN Bug: failed to find amino acid"); } Atom amineAtom = aminoAcid.getFrag().getDefaultInAtom(); if (amineAtom == null) { throw new StructureBuildingException("OPSIN did not know where the amino acid amine was located"); } for (int i = 1; i < words.size(); i++) { Element word = words.get(i); Fragment suffixLikeGroup = findRightMostGroupInWordOrWordRule(word).getFrag(); String locant = word.getAttributeValue(LOCANT_ATR); if (locant != null){ if (!locant.equals("N")) { throw new RuntimeException("OPSIN Bug: locant expected to be N but was: " + locant); } } Atom atomToConnectToOnConjunctiveFrag = FragmentTools.lastNonSuffixCarbonWithSufficientValency(suffixLikeGroup); if (atomToConnectToOnConjunctiveFrag == null) { throw new StructureBuildingException("OPSIN Bug: Unable to find non suffix carbon with sufficient valency"); } state.fragManager.createBond(atomToConnectToOnConjunctiveFrag, amineAtom, 1); } }
35acfe3e-f4ec-4ee4-b3ae-4440063e04f5
5
@Override public List<E> inRectangle(Vector corner1, Vector corner2) { ArrayList<E> toReturn = new ArrayList<>(); for (E item : list){ Vector p = item.getPosition(); if (p.x >= corner1.x && p.x <= corner2.x && p.y >= corner1.y && p.y <= corner2.y) list.add(item); } return toReturn; }