method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
1eb90d5e-9450-46c0-9e6a-3ec8edb332ef
4
public ArrayList<Integer> preorderTraversal(treeNode root) { ArrayList<Integer> valsInPreOrder = new ArrayList<Integer>(); Stack<treeNode> nodesInPreOrder = new Stack<treeNode>(); if (root == null) return valsInPreOrder; // push root in to begin with nodesInPreOrder.push(root); // for each node in stack, pop it up, add right/left , so left is poping // up first; treeNode curRoot = null; while (!nodesInPreOrder.isEmpty()) { curRoot = nodesInPreOrder.pop(); valsInPreOrder.add(new Integer(curRoot.value)); // add right/left in stack if (curRoot.rightLeaf != null) nodesInPreOrder.push(curRoot.rightLeaf); if (curRoot.leftLeaf != null) nodesInPreOrder.push(curRoot.leftLeaf); } return valsInPreOrder; }
ed2119e8-abfd-4fe8-ab01-0518a17f0676
5
public void onClicked(Interactable i) { if(clicked < clicks) { i.hide(); Interactable i2 = getInteractable(new Location(i.getX(), i.getY() - maze.getyWallScale())); if(i2!=null) { i2.hide(); map[i2.getX()/i2.getWidth()][i2.getY()/i2.getHeight()] = 1; } i2 = getInteractable(new Location(i.getX() + maze.getxWallScale(), i.getY())); if(i2!=null) { i2.hide(); map[i2.getX()/i2.getWidth()][i2.getY()/i2.getHeight()] = 1; } i2 = getInteractable(new Location(i.getX(), i.getY() + maze.getyWallScale())); if(i2!=null) { i2.hide(); map[i2.getX()/i2.getWidth()][i2.getY()/i2.getHeight()] = 1; } i2 = getInteractable(new Location(i.getX() - maze.getxWallScale(), i.getY())); if(i2!=null) { i2.hide(); map[i2.getX()/i2.getWidth()][i2.getY()/i2.getHeight()] = 1; } map[i.getX()/i.getWidth()][i.getY()/i.getHeight()] = 1; clicked++; } }
4dbadded-5078-453e-bad3-595036162269
8
private void onClickLogin(){ MySession sess = (MySession)getSession(); // ------------------- // ユーザ名 // ------------------- String username = _openidname.getModelObjectAsString(); // ------------------- // コンシューマ名 // ------------------- SelectOption op = (SelectOption)_openidprovider.getModelObject(); String consumer = op.getCode(); // TODO 本当は、OpenID プロバイダを通すので、ここでログインはしないんだけど・・・ // ------------------- // ログイン処理 // ------------------- System.out.println("username " + username); System.out.println("consumer " + consumer); int userid = -1; while(userid == -1){ SelectFromLoginUser sql = new SelectFromLoginUser(username, consumer); List userlist = DBUtil.selectFromDb(sql); if(userlist.isEmpty()){ InsertLoginUser sqlins = new InsertLoginUser(username, consumer); int sqlinscnt = DBUtil.updateDb(sqlins); if(sqlinscnt != 1){ throw new RuntimeException("ユーザーの追加に失敗"); } } else{ if(userlist.size() != 1){ throw new RuntimeException("ユーザーが複数見つかった!"); } SelectFromLoginUser ret = (SelectFromLoginUser)userlist.get(0); userid = ret.getUserId(); } } /* LoginUserInfo user = new LoginUserInfo(); user.setUserName(username); user.setConsumer(consumer); user.setUserId(userid); sess.setLoginUser(user); setResponsePage(IndexPage.class); */ try{ String fowardurl = ""; if(op == SELECT_HATENA){ fowardurl = op.getCode() + username; } /** * ここで、コンシューマに従った、フォワードURLを編集 * もしかするとSelectOptionクラスで編集させるといいかもしれない * */ sess.setSaveUserInfo(userid, username, consumer); // コンシューママネジャを取得 ConsumerManager manager = ConsumerManagerWrapper.getInstance(); // フォワード先を設定 List discoveries = manager.discover(fowardurl); if(discoveries==null){ error("コンシューマが見つかりません"); return; } // associate DiscoveryInformation discovered = manager.associate(discoveries); sess.setDescoveryInformation(discovered); String returnURL = RequestUtils.toAbsolutePath("verify"); AuthRequest authReq = null; authReq = manager.authenticate(discovered, returnURL); // authentication if(authReq != null){ getRequestCycle().setRequestTarget(new RedirectRequestTarget(authReq.getDestinationUrl(true))); } } catch(Exception e ){ e.printStackTrace(); throw new RuntimeException("ログインボタン中の失敗"); } }
149f4630-f86b-46d8-b291-84b63c5a05f0
6
@Override public void run() { long lastT = 0; while(true) { if(lastT != file.lastModified()) { try { List<String> lines = Files.readAllLines(file.toPath(), Charset.defaultCharset()); StringBuilder sb = new StringBuilder(); for(String l : lines) { sb.append(l); sb.append('\n'); } String fileStr = sb.toString(); synchronized(this) { tags = TaskTrackerParser.getTags(fileStr); questions = TaskTrackerParser.getQuestions(fileStr); notes = TaskTrackerParser.getNotes(fileStr); tasks = TaskTrackerParser.getIncompleteTasks(fileStr); } for(FileMonitorListener l : listeners) l.fileChanged(); } catch(IOException e) { e.printStackTrace(); } lastT = file.lastModified(); } try { Thread.sleep(500); } catch(InterruptedException e) { } } }
bc1a17a0-8df0-4e80-b61b-2fb751debbca
8
void output( int code, OutputStream outs ) throws IOException { cur_accum &= masks[cur_bits]; if ( cur_bits > 0 ) cur_accum |= ( code << cur_bits ); else cur_accum = code; cur_bits += n_bits; while ( cur_bits >= 8 ) { char_out( (byte) ( cur_accum & 0xff ), outs ); cur_accum >>= 8; cur_bits -= 8; } // If the next entry is going to be too big for the code size, // then increase it, if possible. if ( free_ent > maxcode || clear_flg ) { if ( clear_flg ) { maxcode = MAXCODE(n_bits = g_init_bits); clear_flg = false; } else { ++n_bits; if ( n_bits == maxbits ) maxcode = maxmaxcode; else maxcode = MAXCODE(n_bits); } } if ( code == EOFCode ) { // At EOF, write the rest of the buffer. while ( cur_bits > 0 ) { char_out( (byte) ( cur_accum & 0xff ), outs ); cur_accum >>= 8; cur_bits -= 8; } flush_char( outs ); } }
4b74dc8c-c83f-42c4-81c4-ab0296c6ddd2
5
public boolean isFree(int gridX,int gridY){ switch(Screen.land[gridY][gridX]){ //all the solids: case 1: case 2: case 3: case 4: case 8: return false; } return true; }
8c4565a6-56bf-481e-87bf-c952e6a36e43
6
private TagPos findTag(String tagName) { if (tagName != null) { ListIterator<TagPos> it = list.listIterator(list.size()); String fatalTag = null; TagInfo fatalInfo = getTagInfoProvider().getTagInfo(tagName); if (fatalInfo != null) { fatalTag = fatalInfo.getFatalTag(); } while (it.hasPrevious()) { TagPos currTagPos = it.previous(); if (tagName.equals(currTagPos.name)) { return currTagPos; } else if (fatalTag != null && fatalTag.equals(currTagPos.name)) { // do not search past a fatal tag for this tag return null; } } } return null; }
ab980fa8-7693-4f22-aa0c-0f322dba05f6
5
@SuppressWarnings("resource") public static void copy(File src, File dest) throws IOException { if (!src.exists()) return; if (!dest.exists()) dest.mkdir(); for (File f : src.listFiles()) { File target = new File(dest, f.getName()); if (f.isDirectory()) copy(f, target); if (f.isFile()) { FileChannel ic = new FileInputStream(f).getChannel(); FileChannel oc = new FileOutputStream(target).getChannel(); try { ic.transferTo(0, ic.size(), oc); } finally { ic.close(); oc.close(); } } } }
087cd18b-3ad7-444e-a315-2ff07ca3c849
0
private PDestination(String whereTo) { label = whereTo; }
3c151078-4de1-4a0a-bd09-3bbffb459e01
8
private void bindJNDIConfig(EnvConfigBean envConfig, Document document) { NodeList jndiNodes = document.getElementsByTagName("jndi"); if(null != jndiNodes && jndiNodes.getLength() > 0) { Node node = jndiNodes.item(0); NodeList jndiProps = node.getChildNodes(); Map<String,ConfigDataSourceBean> jndiPropertyMap = new HashMap<String,ConfigDataSourceBean>(); int i = 0; do { if(i >= jndiProps.getLength()) break; Node prop = jndiProps.item(i); short nodeType = prop.getNodeType(); switch(nodeType) { case Node.ELEMENT_NODE: // '\001' NamedNodeMap propAttr = prop.getAttributes(); ConfigDataSourceBean csb = new ConfigDataSourceBean(); csb.setName(null != propAttr.getNamedItem("name") ? propAttr.getNamedItem("name").getNodeValue() : ""); csb.setValue(null != propAttr.getNamedItem("value") ? propAttr.getNamedItem("value").getNodeValue() : ""); csb.setRemark(null != propAttr.getNamedItem("remark") ? propAttr.getNamedItem("remark").getNodeValue() : ""); jndiPropertyMap.put(csb.getName(), csb); break; } i++; } while(true); envConfig.setJndi(jndiPropertyMap); } else { throw new EnvironmentConfigException("no jndi node found"); } }
5b4f16e3-efa4-4d22-bd10-ddf91cdf616d
6
public static void setNimbus() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> }
1fb0f3e6-58a8-49e6-8b08-a7b145587c9c
6
public static Stella_Object generateOneVariable(PatternVariable self, boolean typedP) { { Stella_Object value = null; if (((Justification)(Logic.$CURRENTJUSTIFICATION$.get())) != null) { value = Logic.justificationArgumentBoundTo(self, null); } if (value == null) { value = Logic.safeArgumentBoundTo(self); } if ((value != null) && (!(value == self))) { return (Logic.generateTerm(value)); } else { { Symbol name = PatternVariable.generateNameOfVariable(self); if (typedP && (!(Logic.logicalType(self) == Logic.SGT_STELLA_THING))) { return (Cons.cons(name, Cons.cons(Surrogate.symbolize(Logic.logicalType(self)), Stella.NIL))); } else { return (name); } } } } }
0d8ee2a7-0f87-4279-9d94-c308db1ab42b
9
public void move(int spot, char symbol) { switch (spot) { case 1 : field[0][0] = symbol; break; case 2 : field[0][1] = symbol; break; case 3 : field[0][2] = symbol; break; case 4 : field[1][0] = symbol; break; case 5 : field[1][1] = symbol; break; case 6 : field[1][2] = symbol; break; case 7 : field[2][0] = symbol; break; case 8 : field[2][1] = symbol; break; case 9 : field[2][2] = symbol; break; } }
af84d59f-34e4-4a51-9d9d-d5f8a142e845
3
public String getNick() { int i = prefix.indexOf('!'); if (i != -1 || (i = prefix.indexOf('@')) != -1) return prefix.substring(0, i); return (prefix.length() != 0) ? prefix : null; }
f5147c77-2a3d-466f-bb70-5ee5c729ff78
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 Room1)) { return false; } Room1 other = (Room1) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
c7bccbf2-a315-40b2-8d29-6c63756d8505
0
@Override public void focusLost(FocusEvent e) { handleUpdate(); }
f734c897-0264-4c42-9de0-47331c887222
1
@Override public void setPricing(Character productCode, int productQuantity, float productPackPrice) { Product product = null; product = this.locateProductByCode(productCode); if (product==null) { product = new Product(productCode); product.writePriceForQuantity(productQuantity, BigDecimal.valueOf(productPackPrice)); products.put(productCode, product); } else { product.writePriceForQuantity(productQuantity, BigDecimal.valueOf(productPackPrice)); } }
1d4bc595-c2ca-4dc4-b9c4-998f0dade442
2
public void dropFlagOnAdjacentPosition(Position position) { if (position == null) throw new IllegalArgumentException("The given arguments are invalid!"); final PlayerFlag inventoryFlag = getInventory().findFlag(); if (inventoryFlag != null) { List<Position> positionsAroundPlayer = getGrid().getPositionsAround(position); positionsAroundPlayer = removeObstaclesFromPositionList(positionsAroundPlayer); positionsAroundPlayer.remove(position); final int randomIndex = new Random().nextInt(positionsAroundPlayer.size()); Position randomPositionAround = positionsAroundPlayer.get(randomIndex); getInventory().remove(inventoryFlag); getGrid().addElementToPosition(inventoryFlag, randomPositionAround); } }
5b609877-24e2-403d-87fd-0b650e9644b3
1
@Override public void mouseDragged(MouseEvent event) { if (pos == -1) return; /*Point loc = getLocation(); displacement = event.getPoint(); points[1].setRect(points[1].getX()-displacement.x,points[1].getY()-displacement.y,points[1].getWidth(),points[1].getHeight());*/ /*if(pos==0){ points[1].setRect(points[1].getX()-event.getPoint().x,points[1].getY()-event.getPoint().y,points[1].getWidth(),points[1].getHeight()); }*/ //else // for bottom right corner points[1].setRect(event.getPoint().x,event.getPoint().y,points[pos].getWidth(),points[pos].getHeight()); System.out.println("dragged x y="+event.getPoint().x+" "+event.getPoint().y); repaint(); }
d08b3726-b769-48fc-9bd2-7aba01604416
2
private void uploadSkinFile(String url) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(url); FileBody skin = new FileBody(skinFile); StringBody user = new StringBody(this.username, ContentType.TEXT_PLAIN); StringBody session = new StringBody(this.session, ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("skinfile", skin) .addPart("user", user) .addPart("sessionId", session) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String resString = EntityUtils.toString(resEntity); if (resString.equals("OK")) { publish(new SkinUploadState(true)); } else { System.err.println("[Skin Upload Error] " + resString); publish(new SkinUploadState(false)); } } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } }
b783236c-3b3b-4581-b825-463cee0865dd
0
public FirstFollowTable(Grammar grammar) { super(new FirstFollowModel(grammar)); model = (FirstFollowModel) getModel(); getColumnModel().getColumn(1).setCellRenderer(RENDERER); getColumnModel().getColumn(2).setCellRenderer(RENDERER); setCellSelectionEnabled(true); }
836f5ef8-1dec-4b0d-a811-384cb4b13f0c
1
public void reload() { try { this.yml.save(configFile); this.yml.load(configFile); } catch (Exception e) { System.out.println("[BurningCS] Could not read config file!"); e.printStackTrace(); } }
b2106300-2da3-4790-b6ed-c8fe6857297d
3
public static void main(String[] args) throws Exception { final SwingTerminal swingTerminal = new SwingTerminal(); final GUIScreen guiScreen = new GUIScreen(new Screen(swingTerminal)); guiScreen.getScreen().startScreen(); final Window window1 = new Window("Palette Switcher"); Panel mainPanel = new Panel(new Border.Invisible(), Panel.Orientation.VERTICAL); ActionListBox actionListBox = new ActionListBox(); Field[] fields = TerminalPalette.class.getFields(); for(Field field: fields) { if(field.getType() != TerminalPalette.class) continue; if((field.getModifiers() & Modifier.STATIC) != 0) actionListBox.addAction(new ActionListBoxItem(guiScreen, field)); } mainPanel.addComponent(actionListBox); window1.addComponent(mainPanel); Panel buttonPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); Button exitButton = new Button("Exit", new Action() { public void doAction() { guiScreen.closeWindow(); } }); buttonPanel.addComponent(new EmptySpace(20, 1)); buttonPanel.addComponent(exitButton); window1.addComponent(buttonPanel); guiScreen.showWindow(window1, GUIScreen.Position.CENTER); guiScreen.getScreen().stopScreen(); }
78244c6c-955f-48ec-b7b7-f9683f5971c3
7
public Coordinate move( Move move ) { Coordinate jumped = null; int jumpedPiece = 0; int movePiece = 0; //makes sure the move is valid if( isValidCoordinate( move.getStart( ) ) && isValidCoordinate( move.getEnd( ) ) && !isEmpty( move.getStart( ) ) && isEmpty( move.getEnd( ) ) ) { //removes jumped piece if( ( jumped = getJumpped( move ) ) != null ) { if(board[jumped.getY()][jumped.getX()] != null){ jumpedPiece = Integer.parseInt(board[jumped.getY()][jumped.getX()].toString()); } removePiece(jumped); } //moves the piece from its starting location to end location board[ move.getEnd( ).getY( ) ][ move.getEnd( ).getX( ) ] = board[ move.getStart( ).getY( ) ][ move.getStart( ).getX( ) ]; movePiece = Integer.parseInt(board[move.getEnd().getY()][move.getEnd().getX()].toString()); removePiece( move.getStart() ); //board[ move.getStart( ).getY( ) ][ move.getStart( ).getX( ) ] = null; } lastMove = new GUIMovement(move, jumped, movePiece, jumpedPiece); if(jumped == null){ return null; } return move.getEnd( ); }
8221d79d-5dfd-4a6e-a92c-fed9f91a5694
6
public String stComposeEmailForOutlookEmailService(int dataId,int ExpVal,String flow ) { int actVal=1000; String returnVal=null; hm.clear(); hm=STFunctionLibrary.stMakeData(dataId, "ExternalEmail"); String to = hm.get("To"); String subject = hm.get("Subject"); String message = hm.get("Message"); STCommonLibrary comLib=new STCommonLibrary(); Vector<String> xPath=new Vector<String>(); Vector<String> errorMsg=new Vector<String>(); String emailSubjectField=""; String emailMessageBox=""; try { xPath.add(SIGNIN_OUTLOOK_TO_FIELD); errorMsg.add("To field is not present"); xPath.add(SIGNIN_OUTLOOK_MESSAGE_BODY); errorMsg.add("Message field is not present"); xPath.add(SIGNIN_OUTLOOK_SUBJECT_FIELD); errorMsg.add("Cancel button is not present"); xPath.add(SIGNIN_OUTLOOK_SEND_BUTTON); errorMsg.add("Send Button is not present"); comLib.stVerifyObjects(xPath, errorMsg, "STOP"); xPath.clear(); errorMsg.clear(); emailSubjectField = browser.getValue(SIGNIN_OUTLOOK_SUBJECT_FIELD); System.out.println(emailSubjectField); emailMessageBox = browser.getText(SIGNIN_OUTLOOK_MESSAGE_BODY); System.out.println(emailMessageBox); Block: { /*Typing Receipient */ if(!"".equals(to)) { browser.focus(SIGNIN_OUTLOOK_TO_FIELD); // browser.click(SIGNIN_OUTLOOK_TO_FIELD); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } browser.type(SIGNIN_OUTLOOK_TO_FIELD, to ); } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } /* Comparing Subject and message body values */ if(emailSubjectField.contains(subject)) { actVal= 0; /*Email is Composed successfully for Outlook service */ System.out.println("Values matched"); browser.click(SIGNIN_OUTLOOK_SEND_BUTTON); break Block; } else { actVal= 1; /*Failed to Compose email for Yahoo service.*/ System.out.println("Values Not matched"); break Block; } } } catch (SeleniumException sexp) { Reporter.log(sexp.getMessage()); } returnVal=STFunctionLibrary.stRetValDes(ExpVal, actVal, "stComposeEmailForOutlookEmailService",flow, hm); if(flow.contains("STOP")){ assertEquals("PASS",returnVal); } return returnVal; }
a02bb559-e37d-4f79-9dfe-d34497d8ee44
5
public static void main(String[] args) throws UnsupportedEncodingException { Map<String, Double> orderList = new HashMap<String, Double>(); double result = 0; try { Scanner fileScanner = new Scanner(new File("input.txt")); while(fileScanner.hasNext()){ String[] tokens = fileScanner.nextLine().split("\\s"); orderList.put(tokens[0], Double.parseDouble((tokens[1]))); } Scanner fileScanner2 = new Scanner(new File("Order.txt")); while(fileScanner2.hasNext()){ Double productAmount = fileScanner2.nextDouble(); String product = fileScanner2.next(); for (Map.Entry<String, Double> e : orderList.entrySet()) { if(e.getKey().equals(product)){ result += productAmount*e.getValue(); } } } PrintWriter writer = new PrintWriter("Price.txt", "UTF-8"); // for (Map.Entry<String, Double> e : orderList.entrySet()) { // result+=e.getValue(); // } writer.printf("%.1f",result); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
c759275a-de23-4ea2-ae4a-78c2be10f970
7
public SpikeCollection getRandom(int numberOfRandomSpikesToAnalyse) { SpikeCollection randomSpikes = new SpikeCollection(); RandomDataImpl generator = new RandomDataImpl(); // find total number of spikes int total = 0; for (SingleASspikes asSpikes : allUpdates.values()) { total = total + asSpikes.getNumberOfSpikes(); } // check if I have enough spikes if (numberOfRandomSpikesToAnalyse > total) { numberOfRandomSpikesToAnalyse = total; } // get needed number of random spikes int selected = 0; ArrayList<MonitoredAS> monitoredASs = new ArrayList<MonitoredAS>( allUpdates.keySet()); while (selected < numberOfRandomSpikesToAnalyse) { // get random key MonitoredAS as; if (monitoredASs.size() > 1) { as = monitoredASs.get(generator.nextInt(0, monitoredASs.size() - 1)); } else { as = monitoredASs.get(0); } // get random spike SingleASspikes oneASspikes = allUpdates.get(as); // ArrayList<Long> seconds = new // ArrayList<Long>(oneASspikes.keySet()); long time; long minTime = oneASspikes.getCurrentMinTime(); long maxTime = oneASspikes.getCurrentMaxTime(); if (minTime < maxTime) { time = generator.nextLong(oneASspikes.getCurrentMinTime(), oneASspikes.getCurrentMaxTime()); } else { time = minTime; } if (oneASspikes.hasSpikeAtTime(time)) { Spike randomSpike = new Spike(oneASspikes.getSpikeAtTime(time) .copyPrefixSet()); // add it to map with all random spikes if (randomSpikes.addSpike(time, randomSpike, as)) { selected++; } } } return randomSpikes; }
1326d989-2a98-4eb3-b071-9e3f0b4cf5fe
0
public static void main(String[] args) { AddStrategy addStrategy = new AddStrategy(); Environment environment = new Environment(addStrategy); System.out.println(environment.calculate(3, 4)); SubStrategy subtractStrategy = new SubStrategy(); environment.setStrategy(subtractStrategy); System.out.println(environment.calculate(3, 4)); MultiplyStrtegy multiplyStrategy = new MultiplyStrtegy(); environment.setStrategy(multiplyStrategy); System.out.println(environment.calculate(3, 4)); DivideStrategy divideStrategy = new DivideStrategy(); environment.setStrategy(divideStrategy); System.out.println(environment.calculate(3, 4)); }
80be7b6c-aabb-4262-bce9-1d0f9c309bfa
0
public short getId() { return id; }
667556b1-42e0-47fa-bbab-6f187d5bbd70
9
private Object invoke(Object thiz, String name, Object... args) throws ScriptException, NoSuchMethodException { Context cx = enterContext(); try { if (name == null) { throw new NullPointerException("method name is null"); } if (thiz != null && !(thiz instanceof Scriptable)) { thiz = cx.toObject(thiz, topLevel); } Scriptable engineScope = getRuntimeScope(context); Scriptable localScope = (thiz != null) ? (Scriptable) thiz : engineScope; Object obj = ScriptableObject.getProperty(localScope, name); if (!(obj instanceof Function)) { throw new NoSuchMethodException("no such method: " + name); } Function func = (Function) obj; Scriptable scope = func.getParentScope(); if (scope == null) { scope = engineScope; } Object result = func.call(cx, scope, localScope, wrapArguments(args)); return unwrapReturnValue(result); } catch (RhinoException re) { if (DEBUG) { re.printStackTrace(); } int line = (line = re.lineNumber()) == 0 ? -1 : line; throw new ScriptException(re.toString(), re.sourceName(), line); } finally { cx.exit(); } }
d3c78d84-16bb-4fda-83bd-7aa92fb47e41
6
ArrayList<ArrayList<Integer>> permuteUnit(int[] num, int[] pre, int[] post, ArrayList<ArrayList<Integer>> permutation) { // base case if (pre.length == num.length) { ArrayList<Integer> unit = new ArrayList<Integer>(); for (int i = 0; i < pre.length; i++) { unit.add(pre[i]); } permutation.add(unit); return permutation; } int index = pre.length; for (int i = 0; i < post.length; i++) { // update pre int[] currentPre = new int[index + 1]; for (int j = 0; j < index; j++) { currentPre[j] = pre[j]; } currentPre[index] = post[i]; // update post int[] currentPost = new int[post.length - 1]; int j = 0; while (j != i) { currentPost[j] = post[j]; j++; } while (j < currentPost.length) { currentPost[j] = post[j + 1]; j++; } permuteUnit(num, currentPre, currentPost, permutation); } return permutation; }
ae315fa9-1c6b-4888-bcfe-a550aacdf47b
8
public ArrayList<ArrayList<String>> splitString(String input) { sentence = input; ArrayList<String> sentenceArray, tokenizedSentence = new ArrayList<>(), charIdentifier = new ArrayList<>(); // splits sentence into single words at spaces // Note: will also bring punctuation with word (if applicable) // i.e. "Hi, I'm Akali" will split into "Hi,", "I'm", and "Akali" sentenceArray = new ArrayList<>(Arrays.asList(sentence.split("[@ _ \\t\r]"))); for (int i = 0; i < sentenceArray.size(); i++) { for (int r = 0; r < contractions.length; r++) { if (sentenceArray.get(i).equalsIgnoreCase(contractions[r][0])) { sentenceArray.set(i, contractions[r][1].split(" ")[0]); sentenceArray.add(i + 1, contractions[r][1].split(" ")[1]); } } } for (String s : sentenceArray) { if (!(s.equals(""))) { // checks last char of s for punctuation punctuation = s.substring(s.length() - 1); if (punctuation.matches("[, ; : . ? ! ( ) [ ] \" ]")) { s = s.substring(0, s.length() - 1); } else { punctuation = ""; } } if (s.substring(0, 1).matches("[, ; : ( [ ] ) \"]")) { tokenizedSentence.add(s.substring(0, 1)); charIdentifier.add("Punctuation"); tokenizedSentence.add(s.substring(1, s.length())); charIdentifier.add("Word"); tokenizedSentence.add(" "); charIdentifier.add("space"); punctuation = ""; continue; } tokenizedSentence.add(s); charIdentifier.add("Word"); if (!(punctuation.equals(""))) { tokenizedSentence.add(punctuation); charIdentifier.add("Punctuation"); } tokenizedSentence.add(" "); charIdentifier.add("space"); punctuation = ""; } return this.passVar(tokenizedSentence, charIdentifier); }
401f7766-1eb5-4eba-b501-a180ae4583a1
2
public static void ChooseNan () { if (Game.characterChoice == 1) { Game.CharacterOne = "Nan"; Game.CharacterOneHP = CharacterStats.NanHP; Game.CharacterOneAttack = CharacterStats.NanAttack; Game.CharacterOneMana = CharacterStats.NanMana; Game.CharacterOneRegen = CharacterStats.NanRegen; Game.MovesOne = CharacterMoves.NanMoves; Game.MoveOneValue [0] = CharacterStats.NanAttack; Game.MoveOneValue [1] = CharacterMoves.Logic; Game.MoveOneValue [2] = CharacterMoves.RighteousFury; Game.MoveOneValue [3] = CharacterMoves.LanceOfLonginus; Game.MoveOneValue [4] = CharacterMoves.Ascension; Game.MoveOneCost [0] = CharacterMoves.AttackCost; Game.MoveOneCost [1] = CharacterMoves.LogicCost; Game.MoveOneCost [2] = CharacterMoves.RighteousFuryCost; Game.MoveOneCost [3] = CharacterMoves.LanceOfLonginusCost; Game.MoveOneCost [4] = CharacterMoves.AscensionCost; Game.OptionsOne [0] = "Attack (" + CharacterMoves.AttackCost + " mana)"; Game.OptionsOne [1] = "Logic (" + CharacterMoves.LogicCost + " mana)"; Game.OptionsOne [2] = "RighteousFury (" + CharacterMoves.RighteousFuryCost + " mana)"; Game.OptionsOne [3] = "LanceOfLonginus (" + CharacterMoves.LanceOfLonginusCost + " mana)"; Game.OptionsOne [4] = "Ascension (" + CharacterMoves.AscensionCost + " mana)"; Game.ActionOne [0] = Game.CharacterOne + " attacks " + Game.CharacterTwo + "."; Game.ActionOne [1] = "Nan uses the power of logic to smite " + Game.CharacterTwo + "."; Game.ActionOne [2] = "Nan activates righteous fury."; Game.ActionOne [3] = "Nan sends the holy Lance of Longinus at " + Game.CharacterTwo + "."; Game.ActionOne [4] = "Nan ascends into a higher existence."; } else if (Game.characterChoice == 2) { Game.CharacterTwo = "Nan"; Game.CharacterTwoHP = CharacterStats.NanHP; Game.CharacterTwoAttack = CharacterStats.NanAttack; Game.CharacterTwoMana = CharacterStats.NanMana; Game.CharacterTwoRegen = CharacterStats.NanRegen; Game.MovesTwo = CharacterMoves.NanMoves; Game.MoveTwoValue [0] = CharacterStats.NanAttack; Game.MoveTwoValue [1] = CharacterMoves.Logic; Game.MoveTwoValue [2] = CharacterMoves.RighteousFury; Game.MoveTwoValue [3] = CharacterMoves.LanceOfLonginus; Game.MoveTwoValue [4] = CharacterMoves.Ascension; Game.MoveTwoCost [0] = CharacterMoves.AttackCost; Game.MoveTwoCost [1] = CharacterMoves.LogicCost; Game.MoveTwoCost [2] = CharacterMoves.RighteousFuryCost; Game.MoveTwoCost [3] = CharacterMoves.LanceOfLonginusCost; Game.MoveTwoCost [4] = CharacterMoves.AscensionCost; Game.OptionsTwo [0] = "Attack (" + CharacterMoves.AttackCost + " mana)"; Game.OptionsTwo [1] = "Logic (" + CharacterMoves.LogicCost + " mana)"; Game.OptionsTwo [2] = "RighteousFury (" + CharacterMoves.RighteousFuryCost + " mana)"; Game.OptionsTwo [3] = "LanceOfLonginus (" + CharacterMoves.LanceOfLonginusCost + " mana)"; Game.OptionsTwo [4] = "Ascension (" + CharacterMoves.AscensionCost + " mana)"; Game.ActionTwo [0] = Game.CharacterTwo + " attacks " + Game.CharacterOne + "."; Game.ActionTwo [1] = "Nan uses the power of logic to smite " + Game.CharacterOne + "."; Game.ActionTwo [2] = "Nan activates righteous fury."; Game.ActionTwo [3] = "Nan sends the holy Lance of Longinus at " + Game.CharacterOne + "."; Game.ActionTwo [4] = "Nan ascends into a higher existence."; } }
8f19ffae-41c0-4d9a-933c-94723189689e
8
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Physical target=getAnyTarget(mob,commands,givenTarget,Wearable.FILTER_UNWORNONLY); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_NOISYMOVEMENT,L(auto?"":"^S<S-NAME> shoot(s) and spin(s) a web at <T-NAMESELF>!^?")+CMLib.protocol().msp("web.wav",40)); if((mob.location().okMessage(mob,msg))&&(target.fetchEffect(this.ID())==null)) { mob.location().send(mob,msg); if(msg.value()<=0) { amountRemaining=160; if(CMLib.map().roomLocation(target)==mob.location()) { success=maliciousAffect(mob,target,asLevel,(adjustedLevel(mob,asLevel)*10),-1)!=null; mob.location().show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> become(s) stuck in a mass of web!")); } } } } else return maliciousFizzle(mob,null,L("<S-NAME> spin(s) a web towards <T-NAMESELF>, but miss(es).")); // return whether it worked return success; }
7bafe8b8-9259-405e-ad79-3c576008677e
4
@SuppressWarnings("CallToThreadDumpStack") private void miFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miFornecedorActionPerformed if (getCadFornecedor() != null && !cadFornecedor.isVisible()) { deskPane.remove(getCadFornecedor()); setCadFornecedor(null); } if (getCadFornecedor() == null) { setCadFornecedor(new FrmFornecedor()); Validacoes v = new Validacoes(); v.posicao(this, getCadFornecedor()); deskPane.add(getCadFornecedor()); try { getCadFornecedor().setSelected(true); } catch (PropertyVetoException ex) { ex.printStackTrace(); } } else { getCadFornecedor().toFront(); } }//GEN-LAST:event_miFornecedorActionPerformed
2fc66a8c-f413-4f6c-965b-747fb5ed25dc
8
@Override public boolean resetDeckBackTo52Cards() { if((cardsCache==null)||(cardsCache.size()==0)) return false; // first retreive all our cards by looping // through our cached list. If we already // have a card, make sure its faced-down for(int i=0;i<cardsCache.size();i++) { final PlayingCard card=(PlayingCard)cardsCache.get(i); if(card.owner()!=owner()) addCard(card); else card.turnFaceDown(); } // next destroy and clear any hands we may // be managing. for(int h=hands.size()-1;h>=0;h--) ((Item)hands.elementAt(h,2)).destroy(); hands.clear(); // if something went wrong (because a player cast // disintegrate on their cards or something) we // just ditch the entire deck and rebuild it. if(numberOfCards()<52) { for(int i=0;i<cardsCache.size();i++) cardsCache.get(i).destroy(); cardsCache.clear(); final Vector<PlayingCard> allCards=makeAllCards(); for(int i=0;i<allCards.size();i++) addCard(allCards.elementAt(i)); cardsCache=getContents(); } return numberOfCards()==52; }
79e7c912-e800-47f0-ad4a-b698aeae240f
5
public List<Section> parseData(String[] cleanedTimetable) { Section currentSection; List<Section> sectionList = new LinkedList<Section>(); int index = 0; int nextCRNIndex; //parse sections //while there is another section while ((index = nextCRN(cleanedTimetable, index)) != -1) { currentSection = new Section(); //predict the next CRN index nextCRNIndex = nextCRN(cleanedTimetable, index + 1); //start parsing parseCRN(cleanedTimetable, index++, currentSection); parseCourse(cleanedTimetable, index++, currentSection); parseTitle(cleanedTimetable, index++, currentSection); parseType(cleanedTimetable, index++, currentSection); parseHrs(cleanedTimetable, index++, currentSection); parseCapacity(cleanedTimetable, index++, currentSection); parseInstructor(cleanedTimetable, index++, currentSection); //check if (ARR) if (isARR(cleanedTimetable, index)) { //dont parse days index++; //dont parse time(s) index++; //parse location normally parseLocation(cleanedTimetable, index++, currentSection); parseExam(cleanedTimetable, index++, currentSection); } else { parseDays(cleanedTimetable, index++, currentSection); parseBegin(cleanedTimetable, index++, currentSection); parseEnd(cleanedTimetable, index++, currentSection); parseLocation(cleanedTimetable, index++, currentSection); parseExam(cleanedTimetable, index++, currentSection); } //handle Additional Times if (isAdditionalTime(cleanedTimetable, index)) { index++; //parse day, begin, end, location AdditionalTime additional = currentSection.addAdditionalTime(); parseDays(cleanedTimetable, index++, additional); parseBegin(cleanedTimetable, index++, additional); parseEnd(cleanedTimetable, index++, additional); parseLocation(cleanedTimetable, index++, additional); } sectionList.add(currentSection); //check for Timetable formatting errors if (nextCRNIndex < index && nextCRNIndex != -1) { index = nextCRNIndex; } } return sectionList; }
eddfadc9-7b33-4a82-bc03-c15df11ea570
4
public Tweet(final Status tweet) { setBorder(new LineBorder(Color.CYAN, 2)); setLayout(new BorderLayout(0, 0)); JTextArea txtrYourTweet = new JTextArea(); txtrYourTweet.setText(tweet.getText()); add(txtrYourTweet); JPanel panel = new JPanel(); add(panel, BorderLayout.SOUTH); JButton btnNewButton = new JButton("Retweet"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Controller.getTwitter().retweetStatus(tweet.getId()); } catch (TwitterException e1) { e1.printStackTrace(); } } }); panel.add(btnNewButton); JButton btnFavourite = new JButton("Favourite"); btnFavourite.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Controller.getTwitter().createFavorite(tweet.getId()); } catch (TwitterException e1) { e1.printStackTrace(); } } }); panel.add(btnFavourite); JButton btnReply = new JButton("Reply"); panel.add(btnReply); JButton btnUser = new JButton("User"); btnUser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { User user = null; try { user = new User(tweet.getUser().getId()); } catch (TwitterException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } user.setVisible(true); } }); panel.add(btnUser); }
e486ddfd-439e-4ed1-ad65-195f920f1b01
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Point other = (Point) obj; if (x == null) { if (other.x != null) return false; } else if (!x.equals(other.x)) return false; if (y == null) { if (other.y != null) return false; } else if (!y.equals(other.y)) return false; return true; }
60d5b57c-e9a6-4afb-896a-49ed93e1d39d
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Category other = (Category) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
36a36418-7333-43a9-a5bc-22a0559247b4
9
private void skipCommon() { char ch = jsonStr.charAt(++index); if (ch == '/') { for (index++; index < length; index++) { ch = jsonStr.charAt(index); if (ch == '\n' || ch == '\r') { break; } } } else if (ch == '*') { boolean isEndReady = false; for (index++; index < length; index++) { ch = jsonStr.charAt(index); if (ch == '*') { isEndReady = true; continue; } if (isEndReady) { isEndReady = false; if (ch == '/') { break; } } } } else { vali.disPass(index); } }
1ae17e91-2011-47da-b2ca-a9152c6ffc72
7
private static <T> Letter<?> createRandomLetter(Inhabitant senderI, Inhabitant receiverI) { Random rand = new Random(); Letter<?> letter; Random rand2 = new Random(); switch (rand.nextInt(5)) { case 0: letter = new PromissoryNote(senderI, receiverI, new Money( rand2.nextInt(100))); break; case 1: letter = new RegistredLetter<Letter<?>>(createRandomLetter(senderI, receiverI)); break; case 2: letter = new UrgentLetter<Letter<?>>(createRandomLetter(senderI, receiverI)); break; default: letter = new SimpleLetter(senderI, receiverI, new Text( "bonjour " + receiverI.toString())); } return letter; }
adf335f9-aea8-4e0a-9cb9-029bc786350d
6
public int getMax(int start, int end) { if (this.start == start && this.end == end) return maxVal; int mid = (this.start + this.end) / 2; if (start <= mid && end <= mid) return left.getMax(start, end); if (start > mid && end > mid) return right.getMax(start, end); return Math.max(left.getMax(start, mid), right.getMax(mid + 1, end)); }
963de2dd-a4c8-46d0-9962-2deab180de1d
6
public void pickCode() { codeNum1 = (int) (Math.random()*10); do { codeNum2 = (int) (Math.random()*10); } while (codeNum2==codeNum1); do { codeNum3 = (int) (Math.random()*10); } while ((codeNum3==codeNum1)||(codeNum3==codeNum2)); do { codeNum4 = (int) (Math.random()*10); } while ((codeNum4==codeNum1)||(codeNum4==codeNum2)||(codeNum4==codeNum3)); }
e7e5eb51-aa0a-4378-9d20-d1e93e6362b0
3
public void saveExpression(String fileName, String expression) { if (!fileName.contains(".txt")) { fileName += ".txt"; } FileWriter writer = null; try { writer = new FileWriter(fileName); PrintWriter fout = new PrintWriter(writer); fout.printf(expression,(Object) null); } catch (IOException e) { System.out.println("ERROR writing files"); } finally { try { writer.close(); } catch (IOException ex) { System.out.println("ERROR closing file"); } } }
3c0f582e-9b9c-4800-a7b8-1c77807cfe7c
8
public static String mySqlStringLiteral(String value) { StringBuilder sql = new StringBuilder(); sql.append('\''); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); switch (c) { case '\0': sql.append("\\0"); break; case '\n': sql.append("\\n"); break; case '\r': sql.append("\\r"); break; case '\\': sql.append("\\\\"); break; case '\"': sql.append("\\\""); break; case '\'': sql.append("\\\'"); break; case (char) 26: sql.append("\\z"); break; default: sql.append(c); } } sql.append('\''); return sql.toString(); }
00416692-1680-4d3f-9276-d5bdbdc0ba6f
8
public MapleAlliance(MapleClient c, int id) { guilds = new ArrayList<MapleGuild>(); this.id = id; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM alliances WHERE id = ? "); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (!rs.first()) { // no result... most likely to be someone from a disbanded alliance that got rolled back rs.close(); ps.close(); return; } notice = rs.getString("notice"); name = rs.getString("name"); for (int i = 1; i <= 5; i++) { guildId[i] = rs.getInt("guild" + i); rankTitles[i - 1] = rs.getString("rank" + i); } rs.close(); ps.close(); } catch (SQLException ex) { System.err.println("loading Guild info failed " + ex); } for (int i = 1; i <= 5; i++) { if (guildId[i] != 0) { if (c != null && guildId[i] == c.getPlayer().getGuildId()) { try { guilds.add(c.getChannelServer().getWorldInterface().getGuild(guildId[i], c.getPlayer().getMGC())); } catch (RemoteException e) { c.getChannelServer().reconnectWorld(); } } else { guilds.add(new MapleGuild(guildId[i])); } } else { guilds.add(null); } } }
176f1ad5-780a-4476-a78f-94380b6aa92d
3
public void repaintCommon() { if(activeTrayIcon.isSelected()) { windowActionBox.setEnabled(true); windowClosing.setEnabled(true); } else { windowActionBox.setEnabled(false); windowClosing.setEnabled(false); //set status: close when click on x windowActionBox.setSelectedIndex(1); } if(useAnotherLnfBox.isSelected()) { LookAndFeelBox.setEnabled(true); lnfLabel.setEnabled(true); } else { LookAndFeelBox.setEnabled(false); lnfLabel.setEnabled(false); } if(this.useInternalAudioPlayerCB.isSelected()){ mediaPlayer.setEnabled(false); shoutcastPlayer.setEnabled(false); browseMP3Player.setEnabled(false); } else { mediaPlayer.setEnabled(true); shoutcastPlayer.setEnabled(true); browseMP3Player.setEnabled(true); } }
88d843a2-77ca-4463-b6f4-ac39f494896a
1
public void add (Object answer){ Integer answerInstances = answers.get(answer); answerInstances = answerInstances==null?0:answerInstances; answers.put(answer, answerInstances+1); }
12d5b7af-847c-4246-9601-829c31728f87
4
private ArrayList<PiezaArqueologica> generarLista(int civilizacion) { ArrayList<PiezaArqueologica> milistaObjetos=new ArrayList<>(); PiezaArqueologica artefacto; try { FileInputStream fstream = new FileInputStream("items.txt"); DataInputStream entrada = new DataInputStream(fstream); BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada)); String strLinea; while ((strLinea = buffer.readLine()) != null) { String delimt="_"; String []tokens= strLinea.split(delimt); int civ = Integer.parseInt(tokens[1]); int proba= Integer.parseInt(tokens[2]); int valor=Integer.parseInt(tokens[3]); if (civ==civilizacion || 0==civ) { artefacto=new PiezaArqueologica(tokens[0],civ,proba,valor); //artefacto.imprime(); milistaObjetos.add(artefacto); } } entrada.close(); } catch (Exception e) { System.err.println("Ocurrio un error: " + e.getMessage()); } return milistaObjetos; }
7f38258d-6536-49d5-a0c0-be1ee71a2166
9
void playSound(int intSFX,int intLocX, int intLocY) { int i, i2, i3; DuskObject objStore; LivingThing thnStore; i=0; intLocX = intLocX-viewrange; intLocY = intLocY-viewrange; if (intLocX<0) { i = -1*(intLocX); } i2=0; if (intLocY<0) { i2 = -1*(intLocY); } for (;i<mapsize;i++) { if (intLocX+i<MapColumns) { for (i3=i2;i3<mapsize;i3++) { if (intLocY+i3<MapRows) { objStore = objEntities[intLocX+i][intLocY+i3]; while (objStore != null) { if (objStore.isLivingThing()) { thnStore = (LivingThing)objStore; if (thnStore.isPlayer()) { thnStore.playSFX(intSFX); } } objStore = objStore.objNext; } } } } } }
c6fe634c-b79f-492c-804d-903465e328b4
2
public void shiftIndex(int lessThan, int delta) { int size = info.length; for (int i = 2; i < size; i += 10){ int org = ByteArray.readU16bit(info, i + 8); if (org >= lessThan) ByteArray.write16bit(org + delta, info, i + 8); } }
42a51705-0c4f-45e0-bea0-43de9979d415
5
public void move(int pX, int pY) { if(alive) { if(pY < row) super.move(NORTH); else if(pY > row) super.move(SOUTH); if(pX < column) super.move(WEST); else if(pX > column) super.move(EAST); } }
261673aa-09aa-4a89-85c5-8cb479426a24
3
public int hashCode() { int lHashCode = 0; if ( this.getCod_Jornada() != null ) { lHashCode += this.getCod_Jornada().hashCode(); } if ( this.getCod_Competicao() != null ) { lHashCode += this.getCod_Competicao().hashCode(); } if ( lHashCode == 0 ) { lHashCode = super.hashCode(); } return lHashCode; }
955c16a6-1733-4119-b6e9-3d1042158440
8
public static void update() { mouseScroll = 0; if(canvas != null && canvas.getMousePosition() != null) mousePoint = canvas.getMousePosition(); for(int i = 0; i < 3; i++) { if(mouseEvents[i] == TYPE_RELEASED) mouseEvents[i] = TYPE_NONE; if(mouseEvents[i] == TYPE_PRESSED) mouseEvents[i] = TYPE_DOWN; } Set<Integer> keys = keyEvents.keySet(); for(Integer key : keys) { int type = keyEvents.get(key); if(type == TYPE_RELEASED) keyEvents.put(key, TYPE_NONE); if(type == TYPE_PRESSED) keyEvents.put(key, TYPE_DOWN); } }
c766d0ca-d551-4d8a-9b6e-363e2d02326d
6
public static GrammarTreeMonitor getGrammarTreeBySentenceKeyWord( String value) { if (value == null || value.length() < 1) { return null; } String monitorName = value.toLowerCase(); monitorName = packageName + "." + monitorName.substring(0, 1).toUpperCase() + monitorName.substring(1) + "WordMonitor"; if (monitors.containsKey(monitorName)) { return monitors.get(monitorName); } else { GrammarTreeMonitor monitor = null; try { @SuppressWarnings("unchecked") Class<GrammarTreeMonitor> c = (Class<GrammarTreeMonitor>) Class .forName(monitorName); monitor = c.newInstance(); monitors.put(monitorName, monitor); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return monitor; } }
a69c2d12-3f65-4ea4-ab88-e77a435152ef
8
private void dropIndex(String sql, StringTokenizer tokenizer) throws Exception { try { //get index name String idxName = tokenizer.nextToken(); // Check for the semicolon String tok = tokenizer.nextToken(); if (! ";".equalsIgnoreCase(tok)) { throw new NoSuchElementException(); } // Check if there are more tokens if (tokenizer.hasMoreTokens()) { throw new NoSuchElementException(); } boolean dropped = false; for (Table table : tables) { for (Index index : table.getIndexes()) { if (index.getIdxName().equalsIgnoreCase(idxName)) { table.setNumIndexes(table.getNumIndexes() - 1); table.getIndexes().remove(index); dropped = true; File indexFile = new File(TABLE_FOLDER_NAME, table.getTableName() + idxName + INDEX_FILE_EXT); try { indexFile.delete(); } catch (Exception ex) { out.println("Unable to delete index file for " + table.getTableName() + idxName + "."); } break; } } } if (! dropped) { out.println("Index " + idxName + " does not exist."); } else { out.println("Index " + idxName + " was dropped."); } } catch (NoSuchElementException ex) { throw new DbmsError("Invalid DROP INDEX statement. '" + sql + "'."); } }
c745a0a4-3892-45fa-90fe-7da902b78edb
1
private void closeClientSocket() { try { this.clientSocket.close(); this.log.info("close client Socket " + this.clientSocket.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); this.log.info("close client Socket: fail"); } }
6dd1b219-0c1c-462a-b0db-95374b603714
4
public boolean isAllPlayersFullyAsleep() { if (this.allPlayersSleeping && !this.multiplayerWorld) { Iterator var1 = this.playerEntities.iterator(); EntityPlayer var2; do { if (!var1.hasNext()) { return true; } var2 = (EntityPlayer) var1.next(); } while (var2.isPlayerFullyAsleep()); return false; } else { return false; } }
8a6d877d-1203-48fe-875f-fd23125041b1
5
public void disconnect() { try { if(out != null) out.close(); if(in != null) in.close(); if(socket != null) socket.close(); if(ssl_socket != null) ssl_socket.close(); } catch(IOException e) { } out = null; in = null; socket = null; ssl_socket = null; connected = false; }
556893ff-4731-4390-b392-6d7085a1fa7d
9
@Override public DamageReport hit(double damage, Class<? extends Tower> towerClass) { if(!alive) { return null; } damage *= calculateMultiTowerBonus(towerClass); double adjustedDamage = damage; if(adjustedDamageTicksLeft > 0) { adjustedDamage *= damageMultiplier; } if (hp - adjustedDamage <= 0) { // This hit killed the creep, so the damage dealt is the number of hp the creep had left, // not the raw damage of the hit alive = false; double damageToReport = hp; boolean wasKill = true; if(adjustedDamageNotifier != null && adjustedDamage > damage && hp > damage) { // Notify the tower that caused the extra damage of the damage it caused // Note that it only caused extra damage if the original shot would not have killed this // creep. adjustedDamageNotifier.notifyOfDamage(hp - damage); adjustedDamageNotifier.notifyOfKills(1); damageToReport = damage; // Don't count it as a kill on the damage report wasKill = false; } double moneyEarned = Formulae.damageDollars(hp, hpFactor, currentLevel) + Formulae.killBonus(levelHP, currentLevel); return new DamageReport(damageToReport, moneyEarned, wasKill); } else { hp -= adjustedDamage; if(adjustedDamageNotifier != null && adjustedDamage > damage) { // Notify the tower that caused the extra damage of the damage it caused adjustedDamageNotifier.notifyOfDamage(adjustedDamage / damageMultiplier); } double moneyEarned = Formulae.damageDollars(adjustedDamage, hpFactor, currentLevel); // Only report the damage actually from this shot, not the extra return new DamageReport(damage, moneyEarned, false); } }
c8203749-b0d7-4038-ad77-69cd7160b273
3
@Override public void run() { while (cont) { try { Thread.sleep(100); rotateTicker(); this.repaint(); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this) { if (!isShowing()) { cont = false; } } } }
f029f981-d4ab-465e-9618-5ef37b68cb3f
9
@Override public UrlPair generateShortUrl(String longUrl) throws GenerateShortUrlFailureException { if (longUrl == null || longUrl.length() == 0) { throw new IllegalArgumentException("[generateShortUrl] longUrl is empty."); } /* If the UrlPair of the given longUrl has already existed, return it directly. */ UrlPair existedUrlPair = findUrlPairByLongUrl(longUrl); if (existedUrlPair != null) { return existedUrlPair; } /* Check the algorithms availability. */ Set<UrlShortenAlgorithm> algorithms = getUrlShortenAlgorithms(); if (algorithms == null || algorithms.isEmpty()) { throw new GenerateShortUrlFailureException("[[generateShortUrl]] UrlShortenAlgorithms is empty."); } for (UrlShortenAlgorithm algorithm : algorithms) { String generatedShortUrl = algorithm.generateShortUrl(longUrl); /* Check generatedShortUrl exist or not */ UrlPair checkUrlPair = findUrlPairByShortUrl(generatedShortUrl); if (checkUrlPair != null) { if (longUrl.equals(checkUrlPair.getLongUrl())) { return checkUrlPair; } } else { UrlPair newUrlPair = new UrlPair(generatedShortUrl, longUrl); try { persistUrlPair(newUrlPair); return newUrlPair; } catch (PersistUrlPairException e) { throw new GenerateShortUrlFailureException(e.getMessage(), e.getCause()); } } } /* All possible generated urlPair have already existed, throw a failure exception */ GenerateShortUrlFailureException ex = new GenerateShortUrlFailureException(); ex.setLongUrl(longUrl); throw ex; }
58731de4-80c5-4d2e-829b-386dfebdfdb8
5
private boolean modificaUsuario(HttpServletRequest request, HttpServletResponse response) { String nombre = request.getParameter("nombre"); String apellidos = request.getParameter("apellidos"); String dni = request.getParameter("dni"); String direccion = request.getParameter("direccion"); String tlf = request.getParameter("telefono"); String password = request.getParameter("pass"); String password2 = request.getParameter("pass2"); int grupo; if (request.getParameter("tipo").equals("Alumno")) { grupo = 0; } else { grupo = 1; } Usuario u = new Usuario(nombre, apellidos, dni, direccion, tlf, password, grupo); if (password.equals(password2) && !nombre.equals("") && !apellidos.equals("") && !dni.equals("")) { String oldDNI = (String) request.getParameter("id"); UsuarioDAO.modificaUsuario(u, oldDNI); return true; } return false; }
82a07a24-0643-4368-94ae-b09641d60149
4
@Override public void tick(EnemyWave allEnemies) { super.tick(allEnemies); //send action to all objects for (Placeable obj : getPlacablesWithinRangeOfThisTower()) { if (!obj.equals(this)) { for (GameAction currentAction : getGameActions()) { if (!currentAction.hasAnAttack()) { obj.addGameActions(currentAction); } } } } }
be8cfb58-0939-4115-843a-38d513eac639
8
private BufferedImage getCroppedImage( String innerPath, int x, int y, int w, int h) { Rectangle keyRect = new Rectangle( x, y, w, h ); BufferedImage result = null; HashMap<Rectangle, BufferedImage> cacheMap = cachedImages.get(innerPath); if ( cacheMap != null ) result = cacheMap.get(keyRect); if (result != null) return result; log.trace( "Image not in cache, loading and cropping...: "+ innerPath ); InputStream in = null; try { in = DataManager.get().getResourceInputStream( innerPath ); BufferedImage bigImage = ImageIO.read(in); result = bigImage.getSubimage(x, y, w, h); } catch (RasterFormatException e) { log.error( "Failed to load and crop image: "+ innerPath, e ); } catch (IOException e) { log.error( "Failed to load and crop image: "+ innerPath, e ); } finally { try {if (in != null) in.close();} catch (IOException f) {} } if ( result == null ) { // Guarantee a returned image, with a stand-in. result = gc.createCompatibleImage( w, h, Transparency.OPAQUE ); Graphics2D g2d = (Graphics2D)result.createGraphics(); g2d.setColor( new Color(150, 150, 200) ); g2d.fillRect( 0, 0, w-1, h-1 ); g2d.dispose(); } if ( cacheMap == null ) { cacheMap = new HashMap<Rectangle, BufferedImage>(); cachedImages.put( innerPath, cacheMap ); } cacheMap.put( keyRect, result ); return result; }
c27ef92c-e7ab-4438-979b-c8bcb03dba71
9
public Parameter getLiblinearParameters() throws MaltChainedException { Parameter param = new Parameter(SolverType.MCSVM_CS, 0.1, 0.1); String type = liblinearOptions.get("s"); if (type.equals("0")) { param.setSolverType(SolverType.L2R_LR); } else if (type.equals("1")) { param.setSolverType(SolverType.L2R_L2LOSS_SVC_DUAL); } else if (type.equals("2")) { param.setSolverType(SolverType.L2R_L2LOSS_SVC); } else if (type.equals("3")) { param.setSolverType(SolverType.L2R_L1LOSS_SVC_DUAL); } else if (type.equals("4")) { param.setSolverType(SolverType.MCSVM_CS); } else if (type.equals("5")) { param.setSolverType(SolverType.L1R_L2LOSS_SVC); } else if (type.equals("6")) { param.setSolverType(SolverType.L1R_LR); } else { throw new LiblinearException("The liblinear type (-s) is not an integer value between 0 and 4. "); } try { param.setC(Double.valueOf(liblinearOptions.get("c")).doubleValue()); } catch (NumberFormatException e) { throw new LiblinearException("The liblinear cost (-c) value is not numerical value. ", e); } try { param.setEps(Double.valueOf(liblinearOptions.get("e")).doubleValue()); } catch (NumberFormatException e) { throw new LiblinearException("The liblinear epsilon (-e) value is not numerical value. ", e); } return param; }
0a65c979-3a52-4588-98e9-22e4ade5a363
3
public static final boolean AABB_AABB(Box a, Box b) { return b.x <= a.getXMax() && b.getXMax() >= a.x && b.y <= a.getYMax() && b.getYMax() >= a.y; }
b5637115-67b3-4ccb-9743-58f227093bff
1
public java.net.Socket openSocket(int socketId) throws IOException { if (Signlink.mainapp != null) { return Signlink.opensocket(socketId); } else { return new java.net.Socket(InetAddress.getByName(getCodeBase().getHost()), socketId); } }
1ac2c999-c7d2-44d3-9dc0-e8ca832a234a
9
public void setLocale(Locale locale) { if (locale == null || isCommitted()) return; _locale = locale; setHeader(HttpFields.__ContentLanguage,locale.toString().replace('_','-')); if (this._outputState==0) { /* get current MIME type from Content-Type header */ String type=_httpResponse.getField(HttpFields.__ContentType); if (type==null) { // servlet did not set Content-Type yet // so lets assume default one type="application/octet-stream"; } HttpContext httpContext=_servletHttpRequest.getServletHandler().getHttpContext(); if (httpContext instanceof ServletHttpContext) { String charset = ((ServletHttpContext)httpContext).getLocaleEncoding(locale); if (charset != null && charset.length()>0) { int semi=type.indexOf(';'); if (semi<0) type += "; charset="+charset; else if (!_charEncodingSetInContentType) type = type.substring(0,semi)+"; charset="+charset; setHeader(HttpFields.__ContentType,type); } } } }
d77843d3-7562-4f34-87e3-b3d8680a6f0e
4
private void updateClient() { try { if(Long.parseLong(txtPhoneNo.getText()) != _client.getPhoneNo()) { if(_cliCtrl.getClientByPhone(Long.parseLong(txtPhoneNo.getText())) != null) { throw new Exception(); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, Logging.handleException(e, 10), "Telefonnummeret eksisterer for en anden klient!", JOptionPane.ERROR_MESSAGE); } try { String name = txtName.getText(); String address = txtAddress.getText(); City city = _cliCtrl.getCityByZipCode(Integer.parseInt(txtZipCode.getText())); long phoneNo = Long.parseLong(txtPhoneNo.getText()); String eMail = txtEmail.getText(); Calendar cal = Calendar.getInstance(); Date creationDate = _client.getCreationDate(); Date editedDate = cal.getTime(); Client client = new Client(name, address, city, phoneNo, eMail, creationDate, editedDate); _cliCtrl.updateClient(client); JOptionPane.showMessageDialog(null, "Kunden er nu opdateret", "INFORMATION!", JOptionPane.INFORMATION_MESSAGE); _instance = null; _frame.dispose(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, Logging.handleException(ex, 2), "Fejl", JOptionPane.WARNING_MESSAGE); } }
fb6d44fa-b7eb-4f8d-b5dc-f0e92f4037a5
3
public static String full2HalfChange(String QJstr) throws Exception { StringBuffer outStrBuf = new StringBuffer(""); String Tstr = ""; byte[] b = null; for (int i = 0; i < QJstr.length(); i++) { Tstr = QJstr.substring(i, i + 1); // 全角空格转换成半角空格 if (Tstr.equals(" ")) { outStrBuf.append(" "); continue; } b = Tstr.getBytes("unicode"); // 得到 unicode 字节数据 if (b[2] == -1) { // 表示全角? b[3] = (byte) (b[3] + 32); b[2] = 0; outStrBuf.append(new String(b, "unicode")); } else { outStrBuf.append(Tstr); } } // end for. return outStrBuf.toString(); }
593bb6bb-ab29-426e-b218-97fcd6c924ed
3
public synchronized void endThreadAccess() { Object requestingUser = Thread.currentThread(); if (m_oCurrentUser == null) { this.notifyAll(); } else if (m_oCurrentUser == requestingUser) { m_oCurrentUser = null; this.notifyAll(); } else { // Some other Thread is currently using us if (log.isLoggable(Level.SEVERE)) { log.severe( "ERROR: Thread finished using SeekableInput, but it wasn't locked by that Thread\n" + " Thread: " + Thread.currentThread() + "\n" + " Locking Thread: " + m_oCurrentUser + "\n" + " SeekableInput: " + this); } } }
faee37a7-a48f-4edf-a593-d7f0c72355dc
6
public double[][] form() { //muodostaa alkutilanteen mukaisen 2D-arrayn for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { initialGrid[i][j] = tempInitial; if (i == 0) { initialGrid[i][j] = tempUp; } else if (i == rows - 1) { initialGrid[i][j] = tempDown; } else if (j == 0) { initialGrid[i][j] = tempLeft; } else if (j == columns - 1) { initialGrid[i][j] = tempRight; } } } return initialGrid; }
919b9102-846a-431e-bdc0-f0373fa1aef1
7
public void writeTermsToFile(String strNumber, Hashtable<String, Double> oTermVsTFIDF) throws IOException { String strKey = null; Double maxValue = Double.MIN_VALUE; String strTerms = ""; int len = oTermVsTFIDF.size() < 5 ? oTermVsTFIDF.size() : 5; for (int i = 0; i < len; ++i) { for (Map.Entry<String, Double> entry : oTermVsTFIDF.entrySet()) { if (entry.getKey().length() > 2 && entry.getValue() > maxValue && !stopwordsMap.containsKey(entry.getKey() .toLowerCase()) && entry.getKey().matches("[a-zA-Z]+")) { maxValue = entry.getValue(); strKey = entry.getKey(); } } strTerms = strTerms + " " + strKey; oTermVsTFIDF.remove(strKey); strKey = null; maxValue = Double.MIN_VALUE; } oBufferedWriter.write(strNumber + " " + strTerms.trim() + "\n"); System.out.println(strTerms); }
5d6c507b-21e0-4447-b3e2-370c8bcb697b
3
public void setExpLogica(PExpLogica node) { if(this._expLogica_ != null) { this._expLogica_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._expLogica_ = node; }
6369bde8-15fc-4738-ae94-b1cd79779060
5
public boolean metodoCompare(Pessoa u ){ { if (this.end.equals(u.getEnd()) && this.nome.equals(u.getNome()) && this.login.equals(u.getLogin()) && this.senha.equals(u.getSenha()) &&this.instituicao.equals(getInstituicao())){ return true; } return false; } }
9883ee3b-e0a9-4b7f-aa1f-03aaf85b9a6a
7
public void collect() { if ( scannerData == null) return ; Vector fileList = scannerData.getFileList() ; fileList.clear() ; File file = new File( scannerData.getSourcePath() ) ; if ( file.exists() ) { Stack stack = new Stack() ; stack.push( file ) ; while ( !stack.empty() ) { file = ( File ) stack.pop() ; if ( file.isDirectory() ) { // get all entries File files[] = file.listFiles( filter ) ; if ( files != null ) { // sort all entries, files into list the vector, directories to the stack for ( int t = 0, len = files.length ; t < len ; t++ ) { file = files[t] ; if ( file.isDirectory() ) { stack.push( file ) ; } else // file { fileList.add( file ) ; } } } } else // special case => methode parameter root = file, not directory { fileList.add( file ) ; } } } }
e8eb6874-5449-4c35-a874-6af0c58da1fd
8
private static BPRMF getBprmf(CommandLine cmd) { BPRMF bprmf = new BPRMF(); String learnRate = cmd.getOptionValue(CommandLineOptions.LEARNRATE); if (learnRate != null) { bprmf.setLearnRate(Float.parseFloat(learnRate)); } String iters = cmd.getOptionValue(CommandLineOptions.ITERS); if (iters != null) { bprmf.setNumIterations(Integer.parseInt(iters)); } String factors = cmd.getOptionValue(CommandLineOptions.FACTORS); if (factors != null) { bprmf.setNumFactors(Integer.parseInt(factors)); } String regBias = cmd.getOptionValue(CommandLineOptions.REGBIAS); if (regBias != null) { bprmf.setRegBias(Float.parseFloat(regBias)); } String regU = cmd.getOptionValue(CommandLineOptions.REGU); if (regU != null) { bprmf.setRegU(Float.parseFloat(regU)); } String regI = cmd.getOptionValue(CommandLineOptions.REGI); if (regI != null) { bprmf.setRegI(Float.parseFloat(regI)); } String regJ = cmd.getOptionValue(CommandLineOptions.REGJ); if (regJ != null) { bprmf.setRegJ(Float.parseFloat(regJ)); } if (cmd.hasOption(CommandLineOptions.SKIPJUPDATE)) { bprmf.setUpdateJ(false); } return bprmf; }
af711ade-a8f2-4387-b031-4662da3d2be7
0
public String getRHS() { return myRHS; }
a11f75e3-224c-4a60-922d-32798f9e2e7e
6
public static Cons optimizeOrderOfApplicableRules(Cons rules, boolean tailP) { { Cons cursor = rules; Cons result = Stella.NIL; Description antecedent = null; int antecedentindex = (tailP ? 0 : 1); if (rules.rest == Stella.NIL) { return (rules); } { int i = Stella.NULL_INTEGER; int iter000 = 0; loop000 : for (;true; iter000 = iter000 + 1) { i = iter000; while (!(cursor == Stella.NIL)) { antecedent = ((Description)((((Proposition)(cursor.value)).arguments.theArray)[antecedentindex])); if (antecedent.internalVariables.length() == i) { result = Cons.cons(((Proposition)(cursor.value)), result); cursor.value = null; } cursor = cursor.rest; } cursor = rules.remove(null); if (cursor == Stella.NIL) { break loop000; } } } return (result.reverse()); } }
6cd2c47e-320c-4ecd-8d54-01dcd9020e01
3
public List<VcfLof> parseLof() { String lofStr = getInfo(LossOfFunction.VCF_INFO_LOF_NAME); ArrayList<VcfLof> lofList = new ArrayList<VcfLof>(); if (lofStr == null || lofStr.isEmpty()) return lofList; // Split comma separated list String lofs[] = lofStr.split(","); for (String lof : lofs) lofList.add(new VcfLof(lof)); return lofList; }
27871887-9227-4ab3-a2fa-d3929ca3217e
4
protected void assertEquals(String tekst, Object verwacht, Object werkelijk) { boolean gelijk; if (verwacht == null) { gelijk = werkelijk == null; } else { gelijk = werkelijk != null && verwacht.equals(werkelijk); } if (! gelijk) { if (! isPrinted) { System.out.println(" Test: "+description); isPrinted = true; } System.out.println(" " + tekst); System.out.println(" Expected: " + verwacht); System.out.println(" Reality: " + werkelijk); errors++; } }
319af8d4-ad97-46c8-a145-f959cf3db6b7
3
public static boolean validateTimeZone(double timeZone) { int MIN_GMT = -12; int MAX_GMT = 13; if (timeZone < MIN_GMT || timeZone > MAX_GMT) { return false; } double decimal = timeZone - (int) timeZone; if (decimal >= 0.60) { return false; } return true; }
482ea544-382b-430b-9aa0-90838b1d7011
3
public void drawBasicString(String string, int x, int y, int color) { if (string == null) { return; } y -= baseHeight; for (int index = 0; index < string.length(); index++) { char c = string.charAt(index); if (c != ' ') { drawCharacter(characterPixels[c], x + characterOffsetX[c], y + characterOffsetY[c], characterWidth[c], characterHeight[c], color); } x += characterScreenWidth[c]; } }
72c75ecd-fbac-403e-8470-5f01b14ce52f
3
@Override public void deserialize(Buffer buf) { presetId = buf.readByte(); if (presetId < 0) throw new RuntimeException("Forbidden value on presetId = " + presetId + ", it doesn't respect the following condition : presetId < 0"); code = buf.readByte(); if (code < 0) throw new RuntimeException("Forbidden value on code = " + code + ", it doesn't respect the following condition : code < 0"); int limit = buf.readUShort(); unlinkedPosition = new short[limit]; for (int i = 0; i < limit; i++) { unlinkedPosition[i] = buf.readUByte(); } }
b30b8d5e-8e5b-41b3-82bd-f5d240b0b3b7
9
@SuppressWarnings("unchecked") private void collectCourseChanges(CourseModel model, ArrayList<Change> list) { // Copy list and prune ArrayList<HashMap<String, Object>> newCourses = new ArrayList<HashMap<String, Object>>(); for (Object c : courses) newCourses.add((HashMap<String, Object>) c); for (CourseRec rec : model.getCourses(Source.COURSERA)) { // Find new course HashMap<String, Object> found = null; for (HashMap<String, Object> c : newCourses) { if (rec.getShortName().equals(c.get("slug"))) { found = c; // Check id as well? break; } } if (found == null) { list.add(CourseChange.delete(rec)); } else { diffCourse(list, rec, found, model); newCourses.remove(found); } } for (HashMap<String, Object> c : newCourses) { ArrayList<HashMap<String, Object>> map = extractSessions(c .get("id")); boolean selfStudy = true; for (HashMap<String, Object> one : map) { selfStudy &= !getNewScheduled(one); } String id = String.valueOf(c.get("id")); if (id.startsWith("v1-")) id = id.substring(3); String shortName = (String) c.get("slug"); String name = (String) c.get("name"); String description = (String) c.get("description"); String instructor = getInstructorString(c); String link = (String) c.get("homeLink"); String language = getLanguage(c); CourseRec record = new CourseRec(Source.COURSERA, id, shortName, name, description, instructor, link, language, selfStudy); for (HashMap<String, Object> one : map) { record.addOffering(makeOffering(one)); } ArrayList<String> categories = (ArrayList<String>) c .get("categories"); ArrayList<String> universities = getUniversityShortNames(c); list.add(CourseChange.add(record, categories, universities)); } }
0f146a13-01c3-45a9-9f57-298a3c021230
3
@Override public Class getColumnClass(int columnIndex) { if (columnIndex == 0) { return Person.class; } else if (columnIndex == 1 || columnIndex == 3) { return Integer.class; } return String.class; }
e32993c2-9247-4720-929c-8aafc0659845
4
private void playerStatusAction(Player user, PlayerStatusData actionData) { switch(actionData.getStatus()) { case GIVEUP: removePlayer(user, actionData); break; case FINANCIAL: for(Thread thread : actions.get(actionData.getUserId()).values()) { synchronized(thread) { if(thread.getState() == Thread.State.WAITING) { thread.notify(); //notify all waiting threads } } } break; } }
edad11a9-3ce6-4519-a63d-e7edf38fd061
1
public static void spawnHellSkeleton (Location loc, int amount) { int i = 0; while (i < amount) { Skeleton HS = (Skeleton) loc.getWorld().spawnEntity(loc, EntityType.SKELETON); LeatherArmorMeta legMeta; ItemStack HSLeg = new ItemStack(Material.LEATHER_LEGGINGS, 1); legMeta = (LeatherArmorMeta) HSLeg.getItemMeta(); legMeta.setColor(Color.fromRGB(218, 28, 28)); HSLeg.setItemMeta(legMeta); LeatherArmorMeta chestMeta; ItemStack HSChest = new ItemStack(Material.LEATHER_CHESTPLATE, 1, (short) - 98789); chestMeta = (LeatherArmorMeta) HSChest.getItemMeta(); chestMeta.setColor(Color.fromRGB(218, 28, 28)); HSChest.setItemMeta(chestMeta); LeatherArmorMeta bootsMeta; ItemStack HSBoots = new ItemStack(Material.LEATHER_BOOTS, 1); bootsMeta = (LeatherArmorMeta) HSBoots.getItemMeta(); bootsMeta.setColor(Color.fromRGB(218, 28, 28)); HSBoots.setItemMeta(bootsMeta); HS.getEquipment().setChestplate(HSChest); HS.getEquipment().setLeggings(HSLeg); HS.getEquipment().setBoots(HSBoots); HS.getEquipment().setChestplateDropChance(0.30F); HS.getEquipment().setLeggingsDropChance(0.30F); HS.getEquipment().setBootsDropChance(0.40F); HS.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 2147483647, 1)); HS.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 2147483647, 2)); HS.addPotionEffect(new PotionEffect( PotionEffectType.INCREASE_DAMAGE, 2147483647, 1)); HS.addPotionEffect(new PotionEffect( PotionEffectType.FIRE_RESISTANCE, 2147483647, 10)); HS.addPotionEffect(new PotionEffect( PotionEffectType.DAMAGE_RESISTANCE, 2147483647, 2)); HS.setFireTicks(2147483647); i++; } }
aed1408f-85af-413b-a1c9-3893800dbee0
4
public static boolean isProperYoutubeChannel(String channelName) { try { URL url = new URL("http://gdata.youtube.com/feeds/base/users/" + channelName + "/uploads"); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String inputLine = in.readLine(); if(inputLine.contains("Invalid value")) return false; in.close(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { if(e.getMessage().contains("400 for URL")) return false; } return true; }
5d26a3dc-7a57-4bf8-9a25-775f0bca1f5f
0
public final void setV(final V v) { this.v = v; }
d212b0a9-cc03-4931-b6a6-009f8b7ff1b1
7
public boolean write(aos.apib.OutStream out, aos.apib.Base o) { HeartBeatTimer v = (HeartBeatTimer)o; int i = -1; while ((i = out.nextField(i, this)) >= 0) { switch (i) { case 0: out.putInt(v.peerID, i, __def.peerID, this); break; case 1: out.putInt(v.upload, i, __def.upload, this); break; case 2: out.putInt(v.download, i, __def.download, this); break; case 5: out.writeBaseClasses(o, this); break; default: if (i >= 0 && i <= 5) break; out.error("Writer for HeartBeatTimer: illegal field number:"+i); return false; } } return true; }
7fb97e81-295e-49e2-a514-2f9188f58347
7
public boolean remove(Object o) { if (o == null) { for (int i = 0; i < size; i++) { if (taulu[i] == null) { int numMoved = size - i - 1; if (numMoved > 0) { System.arraycopy(taulu, i + 1, taulu, i, numMoved); size--; } } } } else { for (int i = 0; i < size; i++) { if (taulu[i] == o) { int numMoved = size - i - 1; if (numMoved > 0) { System.arraycopy(taulu, i + 1, taulu, i, numMoved); size--; } } } } return false; }
1e147f6d-bb73-4f2a-b0d9-8043ddcbf267
1
public static CanvasMouse getInstance(Component component) { if (instance == null) instance = new CanvasMouse(component); return instance; }
bec60c3d-b27d-459f-b703-733dc271174b
5
public static boolean idInArr(String[] param, String id) { boolean result = false; if ((param != null) && (param.length > 0) && (!isEmpty(id))) { int i = 0; for (int len = param.length; i < len; i++) { if (id.equals(param[i]) == true) { result = true; break; } } } return result; }
da7dcde9-0d7f-45ac-84b2-eb6c9a97c8dc
4
private static String executeRemoveCommand(DataBaseManager dbManager, Command command) { List<String> args = command.getArgs(); String tableName = args.get(0); String key = args.get(1); String msg = ""; try { boolean modified = dbManager.removeByKey(tableName, key); if (modified) { msg = "row with key " + tableName + ":" + key + " removed"; } else { msg = "no rows with key " + tableName + ":" + key; } } catch (DBUnavailabilityException e) { msg = e.getMessage(); } catch (DataBaseRequestException e) { msg = e.getMessage(); } catch (DataBaseTableException e) { msg = e.getMessage(); } return msg; }
5f0d76c6-b22d-4be3-bdb9-55fc3c147db8
2
public static void main(String[] args) { String series = "73167176531330624919225119674426574742355349194934" + "96983520312774506326239578318016984801869478851843" + "85861560789112949495459501737958331952853208805511" + "12540698747158523863050715693290963295227443043557" + "66896648950445244523161731856403098711121722383113" + "62229893423380308135336276614282806444486645238749" + "30358907296290491560440772390713810515859307960866" + "70172427121883998797908792274921901699720888093776" + "65727333001053367881220235421809751254540594752243" + "52584907711670556013604839586446706324415722155397" + "53697817977846174064955149290862569321978468622482" + "83972241375657056057490261407972968652414535100474" + "82166370484403199890008895243450658541227588666881" + "16427171479924442928230863465674813919123162824586" + "17866458359124566529476545682848912883142607690042" + "24219022671055626321111109370544217506941658960408" + "07198403850962455444362981230987879927244284909188" + "84580156166097919133875499200524063689912560717606" + "05886116467109405077541002256983155200055935729725" + "71636269561882670428252483600823257530420752963450"; int max= 0; for(int i=0;i<series.length()-4;i++){ int product = Integer.parseInt(Character.toString(series.charAt(i))) *Integer.parseInt(Character.toString(series.charAt(i+1))) *Integer.parseInt(Character.toString(series.charAt(i+2))) *Integer.parseInt(Character.toString(series.charAt(i+3))) *Integer.parseInt(Character.toString(series.charAt(i+4))); if(product>max){ max = product; } } System.out.println(max); }
0754b265-3c51-4372-bb6b-d0385e117b0d
8
private void updateWorkerDay(ACTION action, String imsi, long startTime, Set days) { int oldSize = days.size(); switch (action) { case ADD: days.add(startTime); break; case REMOVE: days.remove(startTime); break; } int newSize = days.size(); if ((oldSize < metrics.daysThreshold ^ newSize < metrics.daysThreshold) || (oldSize == metrics.daysThreshold ^ newSize == metrics.daysThreshold)) { listener.onChange(imsi, newSize, metrics.daysThreshold); } if (logger.isInfoEnabled()) { if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); for (Object start : days) { if (start instanceof Long) { String time = TimeUtil.getTime(((Long) start).longValue()); time = time.substring(0, time.indexOf(" ")); sb.append(time); sb.append(","); } } logger.info(format("worker days change:imsi:[%s] in [%s~%s] get days:[%s]", imsi, time2HHMMSS(metrics.startOfDay), time2HHMMSS(metrics.endOfDay), sb.toString())); } else { logger.info(format("worker days change:imsi:[%s],days:[%d]", imsi, newSize)); } } }
8e34ca1d-a976-48eb-8e8a-d8735a35b3a6
6
@Override public String toString() { String result = getName() + ", average=" + getAverage() + ", " + getProgram() + ", " + getDegree() + ", "; if (this.universityOne != null) result += this.universityOne + "-" + (this.universityOneAccept ? "admitted" : "rejected") ; if (this.universityTwo != null) result += ", " + this.universityTwo + "-" + (this.universityTwoAccept ? "admitted" : "rejected") ; if (this.universityThree != null) result += ", " + this.universityThree + "-" + (this.universityThreeAccept ? "admitted" : "rejected") ; return result; }