method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
785f25ee-6666-444a-8884-4f792b66ef5e
6
public int initialize2(byte dataSrc[], int offset) { int vertexCount = getVertexCount(); vertexIndexArray = new int[vertexCount]; for (int index = 0; index < vertexIndexArray.length; ++index) { vertexIndexArray[index] = ByteConversions.getUnsignedShortInByteArrayAtPosition(dataSrc, offset); offset += 2; } xDisplacementArray = new short[vertexCount]; for (int index = 0; index < xDisplacementArray.length; ++index) { xDisplacementArray[index] = ByteConversions.getShortInByteArrayAtPosition(dataSrc, offset); offset += 2; } yDisplacementArray = new short[vertexCount]; for (int index = 0; index < yDisplacementArray.length; ++index) { yDisplacementArray[index] = ByteConversions.getShortInByteArrayAtPosition(dataSrc, offset); offset += 2; } zDisplacementArray = new short[vertexCount]; for (int index = 0; index < zDisplacementArray.length; ++index) { zDisplacementArray[index] = ByteConversions.getShortInByteArrayAtPosition(dataSrc, offset); offset += 2; } uTextureArray = new short[vertexCount]; for (int index = 0; index < uTextureArray.length; ++index) { uTextureArray[index] = ByteConversions.getShortInByteArrayAtPosition(dataSrc, offset); offset += 2; } vTextureArray = new short[vertexCount]; for (int index = 0; index < vTextureArray.length; ++index) { vTextureArray[index] = ByteConversions.getShortInByteArrayAtPosition(dataSrc, offset); offset += 2; } return offset; }
248015d5-0291-4943-b42f-8f519d8ac485
9
private int busquedaVirus(int i, int j, int l, int maximo) { for (int k = 0; k < dx.length; k++) { int temp_dx = i+dx[k]; int temp_dy = j+dy[k]; if(temp_dx>=0 && temp_dx < tablero.filas() && temp_dy>=0 && temp_dy < tablero.columnas() && !visited[temp_dx][temp_dy] && tablero.getElemento(temp_dx, temp_dy)!=null && this != tablero.getElemento(temp_dx, temp_dy).getJugador() && tablero.getElemento(temp_dx, temp_dy).getNivel(true)==l){ maximo+=l; visited[temp_dx][temp_dy] = true; busquedaVirus(temp_dx, temp_dy, l, maximo); } } return maximo; }
439b68a8-627e-488e-baa9-3845669f6c3f
3
public Object getValueAt(int row, int column) { switch (column) { case 0: return "" + transitions[row].getFromState().getID(); case 1: return "" + transitions[row].getToState().getID(); case 2: return transitions[row].getDescription(); default: return null; } }
b64d6e7a-190b-42d1-8d30-d5bca08f6971
3
public void fill(Graphics2D g){ if(canMove)doMovement(); if(relative){ centerX=(img.getWidth()/2)-(Display.player.loc.getX()/relXT); centerY=(img.getHeight()/2)-(Display.player.loc.getY()/relYT); } testTouching(); if(textured){ int xl = (int) Math.round(centerX-(width/2)); int yl = (int) Math.round(centerY-(height/2)); g.drawImage(img,(int)xl,(int)yl,xl+(int)width,yl+(int)height,0,0,(int)img.getWidth(),(int)img.getHeight(),null); }else{ g.setColor(col); g.fill(getRect()); } doDebug(g); }
80aa0c30-77d5-49fa-905d-5f4e8c22e0a9
1
private void sendData( String message ) { try // send object to client { //PrintWriter pw = new PrintWriter(output); output.writeObject( "SERVER>>> " + message ); output.flush(); // flush output to client System.out.println( "\nSERVER>>> " + message ); } // end try catch ( IOException ioException ) { // displayArea.append( "\nError writing object" ); } // end catch } // end method sendData
86884110-7754-4dfc-989e-fb4f1a546ef0
8
static String formatHanyuPinyin(String pinyinStr, HanyuPinyinOutputFormat outputFormat) throws BadHanyuPinyinOutputFormatCombination { if ((HanyuPinyinToneType.WITH_TONE_MARK == outputFormat.getToneType()) && ((HanyuPinyinVCharType.WITH_V == outputFormat.getVCharType()) || (HanyuPinyinVCharType.WITH_U_AND_COLON == outputFormat.getVCharType()))) { throw new BadHanyuPinyinOutputFormatCombination("tone marks cannot be added to v or u:"); } if (HanyuPinyinToneType.WITHOUT_TONE == outputFormat.getToneType()) { pinyinStr = pinyinStr.replaceAll("[1-5]", ""); } else if (HanyuPinyinToneType.WITH_TONE_MARK == outputFormat.getToneType()) { pinyinStr = pinyinStr.replaceAll("u:", "v"); pinyinStr = convertToneNumber2ToneMark(pinyinStr); } if (HanyuPinyinVCharType.WITH_V == outputFormat.getVCharType()) { pinyinStr = pinyinStr.replaceAll("u:", "v"); } else if (HanyuPinyinVCharType.WITH_U_UNICODE == outputFormat.getVCharType()) { pinyinStr = pinyinStr.replaceAll("u:", "ü"); } if (HanyuPinyinCaseType.UPPERCASE == outputFormat.getCaseType()) { pinyinStr = pinyinStr.toUpperCase(); } return pinyinStr; }
66adf1c5-ae7c-4ae3-abc0-0fd610489141
4
private void RealizePorRandomAMutacao () { cadeiaDeCaminhos = new int[tamanhoTotalDoCaminho]; Caminho caminho; int numRandomico; for (int i = 0; i != numeroGenes; i++) { numRandomico = geradorRandomico.nextInt(populacaoDaPonteControladora.size()); caminho = populacaoDaPonteControladora.get(numRandomico); populacaoDaPonteControladora.remove(numRandomico); numRandomico = geradorRandomico.nextInt(17); int tempNumRandomico = numRandomico + 1; for (int iterator = 0; iterator != tamanhoTotalDoCaminho; iterator++) { if ( tempNumRandomico != iterator ) cadeiaDeCaminhos[iterator] = (Integer) caminho.retorneListaUnicaDiretoDoCaminho(iterator); else { numRandomico = geradorRandomico.nextInt(19); cadeiaDeCaminhos[iterator] = numRandomico; } } fitness = calculoDoFitness.realizarCalculoDoFitness(cadeiaDeCaminhos, tamanhoTotalDoCaminho); populacaoTemporaria = new ArrayList(); for (int num : cadeiaDeCaminhos) populacaoTemporaria.add(num); Caminho novoCaminho = new Caminho (populacaoTemporaria, fitness); populacaoDaPonteControladora.add(novoCaminho); } CalculeFitnessNovamenteParaTodos(populacaoDaPonteControladora); RetornaParaPopulacaoInicial(); }
c9cf28d0-5a27-4e02-b122-b9f3f40b5555
9
public CgiArguments(String uriQuery) { String[] params = uriQuery.split("&"); for (String param : params) { String[] keyval = param.split("=", 2); if (keyval.length < 2) { continue; } String key = keyval[0].toLowerCase(); String val = keyval[1]; if (key.equals("query")) { _query = val; } else if (key.equals("num")) { try { _numResults = Integer.parseInt(val); } catch (NumberFormatException e) { // Ignored, search engine should never fail upon invalid // user input. } } else if (key.equals("ranker")) { try { _rankerType = RankerType.valueOf(val.toUpperCase()); } catch (IllegalArgumentException e) { // Ignored, search engine should never fail upon invalid // user input. } } else if (key.equals("format")) { try { _outputFormat = OutputFormat.valueOf(val.toUpperCase()); } catch (IllegalArgumentException e) { // Ignored, search engine should never fail upon invalid // user input. } } } // End of iterating over params }
070b3d89-54ec-49c2-a949-09d7bfc1ed4a
2
public final static String MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes(); //获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); //使用指定的字节更新摘要 mdInst.update(btInput); //获得密文 byte[] md = mdInst.digest(); //把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { e.printStackTrace(); return null; } }
56c5e37d-cd52-4997-9b7b-4125965a28fa
7
private Object readJSON() throws JSONException { switch (read(3)) { case zipObject: return readObject(); case zipArrayString: return readArray(true); case zipArrayValue: return readArray(false); case zipEmptyObject: return new JSONObject(); case zipEmptyArray: return new JSONArray(); case zipTrue: return Boolean.TRUE; case zipFalse: return Boolean.FALSE; default: return JSONObject.NULL; } }
699509ca-288a-4c46-a8e6-38b24a03c738
6
public boolean isFeasible(Coordinate c) { boolean validI = c.i >= 0 && c.i < size; boolean validJ = c.j >= 0 && c.j < size; boolean validCell = false; if (validI && validJ) { validCell = (maze.get(c.i).get(c.j).val == 0); } return validI && validJ && validCell; }
260d5892-831f-4179-bad2-dc6ded36c749
7
public static int charToInt(char c) { int data = 0; switch (c) { case 'I': data = 1; break; case 'V': data = 5; break; case 'X': data = 10; break; case 'L': data = 50; break; case 'C': data = 100; break; case 'D': data = 500; break; case 'M': data = 1000; break; } return data; }
442dc85f-2e52-460a-a5be-8f0f11bd652e
0
private SaveResults() {} // Es una MAE.
92c046a6-f498-4ec2-9260-0927bb228fde
6
public CustomCanvas() { super("Custom Canvas"); // Demonstrates the use of a Swing component for rendering vertices. // Note: Use the heavyweight feature to allow for event handling in // the Swing component that is used for rendering the vertex. mxGraph graph = new mxGraph() { public void drawState(mxICanvas canvas, mxCellState state, boolean drawLabel) { String label = (drawLabel) ? state.getLabel() : ""; // Indirection for wrapped swing canvas inside image canvas (used for creating // the preview image when cells are dragged) if (getModel().isVertex(state.getCell()) && canvas instanceof mxImageCanvas && ((mxImageCanvas) canvas).getGraphicsCanvas() instanceof SwingCanvas) { ((SwingCanvas) ((mxImageCanvas) canvas).getGraphicsCanvas()) .drawVertex(state, label); } // Redirection of drawing vertices in SwingCanvas else if (getModel().isVertex(state.getCell()) && canvas instanceof SwingCanvas) { ((SwingCanvas) canvas).drawVertex(state, label); } else { super.drawState(canvas, state, drawLabel); } } }; Object parent = graph.getDefaultParent(); graph.getModel().beginUpdate(); try { Object v1 = graph.insertVertex(parent, null, "Hello", 20, 20, 80, 30); Object v2 = graph.insertVertex(parent, null, "World!", 240, 150, 80, 30); graph.insertEdge(parent, null, "Edge", v1, v2); } finally { graph.getModel().endUpdate(); } mxGraphComponent graphComponent = new mxGraphComponent(graph) { /** * */ private static final long serialVersionUID = 4683716829748931448L; public mxInteractiveCanvas createCanvas() { return new SwingCanvas(this); } }; getContentPane().add(graphComponent); // Adds rubberband selection new mxRubberband(graphComponent); }
84b4d4c2-00f0-42e7-a4a1-8af12318daa4
2
public void writeControlFile(String controlPath) throws IOException { Map<String, String> env = System.getenv(); File controlFile = new File(env.get("control_dir"), controlPath); if (!controlFile.exists()) controlFile.createNewFile(); List<String> envProperties = getProperties(); PrintWriter writer = new PrintWriter(new FileWriter(controlFile)); for (String line : envProperties) { writer.println(line); } writer.flush(); writer.close(); }
b6329c4e-9f6b-4e5d-9a65-fd26b38ecaf3
5
private boolean evaluateCardPlayable(Card c) { // There are spells that have no cost, and those cannot be played for // their cost, seeing as they don't have one. Thus, despite not // implementing those cards for a while, there will be a special case // where I check to see if their cost is null. if (c.getCost().equals("0")) { return false; } // I've found that having the card's mana cost by itself is a desirable // thing, so I made a separate method for it. int[] manaCost = this.evaluateCardCost(c); // Here I check each of the five colors, and ensure that I have enough // mana open to pay for the colored costs. for (int i = 0; i < 5; i++) { if (this.manaOpen[i] < manaCost[i]) { return false; } } // This part is only reachable if all the colored costs can be payed. // Here it checks the colorless cost against avaliable colorless mana // and all left over colored mana. int remainingMana = 0; for (int i = 0; i < 5; i++) { remainingMana += (this.manaOpen[i] - manaCost[i]); } // Add in colorless mana and check total remaining mana against // colorless cost. Return false if mana insufficient, otherwise pass to // a default return true, which is the default because zero mana stuff // exists. remainingMana += this.manaOpen[5]; if (remainingMana < manaCost[5]) { return false; } return true; }
45f65ddf-da84-4233-a261-f95a15c4752d
9
protected static boolean isCommutative(int operator) { return (operator == Token.AND || operator == Token.OR || operator == Token.UNION || operator == Token.INTERSECT || operator == Token.PLUS || operator == Token.MULT || operator == Token.EQUALS || operator == Token.FEQ || operator == Token.NE || operator == Token.FNE ); }
0001d8ac-b493-4406-8270-401e87a29f69
2
public boolean hasRole(Role role, User user) throws Exception { try { boolean itHasRole = false; session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Query q = session.getNamedQuery(getNamedQueryToHasRole()); q.setString("user", Integer.toString(user.getId())); q.setString("role", Integer.toString(role.getId())); List lt = q.list(); session.getTransaction().commit(); if (lt.size() > 0) { itHasRole = true; } return itHasRole; } catch (HibernateException e) { throw new Exception(e.getCause().getLocalizedMessage()); } finally { releaseSession(session); } }
6176aca9-371b-4c9e-83dc-9dad2ad502bb
4
@Override public Value evaluate(Value... arguments) throws Exception { // Check the number of argument if (arguments.length == 1) { // get Value Value value = arguments[0]; // If numerical if (value.getType().isNumeric()) { return new Value(new Double(Math.atan(value.getDouble()))); } if (value.getType() == ValueType.ARRAY) { Value[] vector = value.getValues(); Value result[] = new Value[vector.length]; for (int i = 0; i < vector.length; i++) { result[i] = evaluate(vector[i]); } return new Value(result); } // the type is incorrect throw new EvalException(this.name() + " function does not handle " + value.getType().toString() + " type"); } // number of argument is incorrect throw new EvalException(this.name() + " function only allows one numerical parameter"); }
dcdf4c95-d070-4e6d-a1a5-d9f10f2a4b5b
1
@Test @SuppressWarnings("unused") public void testThresholdOfNeighborhood() throws Exception { // keeping the same implementation as before except that we use a threshold based neighborhood // how does the threshold of the neighborhood influence the performance (root mean square error) of the recommender? double[] thresholds = {0.9, 0.7, 0.5, 0.1, 0.05, 0.001, 0.005, 0.001, 0.0001, 0.00001}; for (final double threshold : thresholds) { // make random behave always in the same manner RandomUtils.useTestSeed(); Assert.fail(); } }
3f813538-fdef-46a5-8651-602ceb6f02f3
2
public int getVitality(){ int value = 0; for (Armor armor : armorList) { if(armor != null) value += armor.getStats().getVitality(); } return value; }
0949b478-fb41-4073-878a-13115db97bec
0
@Column(name = "PRP_ID_ELEMENTO") @Id public Integer getPrpIdElemento() { return prpIdElemento; }
d65f5b76-5a56-4368-9075-85482326ba10
6
public static int maxRight() { int arr[] = new int[1001]; for (int i = 1; i <= 1000; i++) { for (int j = 1; j < 1000; j++) { if (i + j + Math.sqrt(i * i + j * j) > 1000) { break; } if (Math.sqrt(i * i + j * j) % 1 == 0) arr[i + j + (int) Math.sqrt(i * i + j * j)]++; } } int max = 0; int no = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { no = i; max = arr[i]; } } return no; }
27810c46-d1b4-467b-ab4a-73025b38356c
8
@Override public void keyPressed(KeyEvent e) { super.keyPressed(e); if (e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_LEFT) { controlled.move(Direction.WEST); } else if (e.getKeyCode() == KeyEvent.VK_D || e.getKeyCode() == KeyEvent.VK_RIGHT) { controlled.move(Direction.EAST); } else if (e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_UP) { controlled.move(Direction.NORTH); } else if (e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_DOWN) { controlled.move(Direction.SOUTH); } }
185c786d-4ac4-4285-b36c-1e43ab9f656e
4
public static void drawVisSquare(GOut g, Coord tc, Coord hsz) { if(JSBotUtils.playerID == -1) return; if(UI.instance.minimap == null) return; Coord current; if(JSBotUtils.getPlayerSelf() == null) current = new Coord(0, 0); else { if(JSBotUtils.getPlayerSelf() == null) current = new Coord(0, 0); else current = JSBotUtils.getPlayerSelf().position(); } Coord ptc = current.div(tileSize).add(tc.inv()).add(hsz.div(2)); g.chcolor(255, 255, 255, 64); g.frect(ptc.sub(42, 42), new Coord(85, 85)); g.chcolor(); }
19fefbeb-b4f4-4c68-a24f-40d41a20f283
0
@Override public Car driverCar() { return new AudoCar(); }
19b338c7-870f-49e5-a745-9ef643749ab4
7
public static VaryNode makeVaryNode(int iNode, FastVector nRecords, Instances instances) { VaryNode _VaryNode = new VaryNode(iNode); int nValues = instances.attribute(iNode).numValues(); // reserve memory and initialize FastVector [] nChildRecords = new FastVector[nValues]; for (int iChild = 0; iChild < nValues; iChild++) { nChildRecords[iChild] = new FastVector(); } // divide the records among children for (int iRecord = 0; iRecord < nRecords.size(); iRecord++) { int iInstance = ((Integer) nRecords.elementAt(iRecord)).intValue(); nChildRecords[(int) instances.instance(iInstance).value(iNode)].addElement(new Integer(iInstance)); } // find most common value int nCount = nChildRecords[0].size(); int nMCV = 0; for (int iChild = 1; iChild < nValues; iChild++) { if (nChildRecords[iChild].size() > nCount) { nCount = nChildRecords[iChild].size(); nMCV = iChild; } } _VaryNode.m_nMCV = nMCV; // determine child nodes _VaryNode.m_ADNodes = new ADNode[nValues]; for (int iChild = 0; iChild < nValues; iChild++) { if (iChild == nMCV || nChildRecords[iChild].size() == 0) { _VaryNode.m_ADNodes[iChild] = null; } else { _VaryNode.m_ADNodes[iChild] = makeADTree(iNode + 1, nChildRecords[iChild], instances); } } return _VaryNode; } // MakeVaryNode
2adc87d1-64b8-4ff8-8ea0-e226d621b894
0
public Long getId() { return id; }
36671f8c-dfb6-4767-8ba8-1bb5a8345840
1
public static JSONObject convertToJSON(Properties properties) throws JSONException { JSONObject jsonObject = new JSONObject(); Enumeration e = properties.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); jsonObject.put(key, properties.getProperty(key)); } return jsonObject; }
acda4ebf-0145-4fd7-98ff-e4cd3498fb56
1
@Test public void getAllRecipesTest() throws Exception { Recipe recipe = new Recipe(); recipe.setName("borscht"); recipe.setCategory(CategoryEnum.chicken); try { recipe.canSave(); recipeService.createRecipe(recipe); } catch (SaveError e) { e.printStackTrace(); } }
c075a52a-f858-4228-be44-2124306df1a2
2
private int getDistanceToNearestOpponent() { nearestOpponent = null; int distance = LONGDISTANCE; Opponent[] opponents = getOpponents(); for (int i=0; i<opponents.length; i++) { int d = (int)Vector3D.getDistance(getLocation(), opponents[i].getLocation()); if (d < distance) { distance = d; nearestOpponent = opponents[i]; } } return distance; }
31254e80-dbff-4043-930f-8026e9b67777
3
public void update (double elapsedTime, Dimension bounds, List<Force> activeForces) { for (Force f : activeForces) { f.applyForce(elapsedTime, bounds, myMasses); } for (Spring s : mySprings) { s.update(elapsedTime, bounds); } for (Mass m : myMasses) { m.update(elapsedTime, bounds); } }
f2b35fd1-02c3-4951-8f3d-bdc280723421
0
public Card DealCard(){ Card newcard = new Card(shuffledDeck.get(getDealCounter())); decremDealCounter(); return newcard; }
8ccbe505-cfda-48bf-8576-7d9e08705b70
5
public void keyReleased(KeyEvent e) { int keycode = 0; try { keycode = e.getKeyCode(); } catch (Exception E) { //pass } if (keycode == KeyEvent.VK_UP) { dy += 1; } if (keycode == KeyEvent.VK_DOWN) { dy -= 1; } if (keycode == KeyEvent.VK_RIGHT) { dx -= 1; } if (keycode == KeyEvent.VK_LEFT) { dx += 1; } }
bd237beb-269c-45dc-991b-c3d0e5fc622b
5
public void typeCounter() { try { String line, s[], ss[]; while((line=sortBr.readLine())!=null) { s = line.split(" "); sortmap.put(s[0], s[1]); } while((line=typeBr.readLine())!=null) { ss = line.split("[-:\\t]+"); if(sortmap.containsKey(ss[5])) { String type = sortmap.get(ss[5]); if(typemap.containsKey(type)) { typemap.put(type, typemap.get(type)+1); } else { typemap.put(type, 1); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
fa703222-c37c-4873-b5c5-a1b50fd8d6b5
6
@Override public String nextName() throws IOException { expect(JsonToken.NAME); Iterator<?> i = (Iterator<?>) peekStack(); Map.Entry<?, ?> entry = (Map.Entry<?, ?>) i.next(); stack.add(entry.getValue()); return (String) entry.getKey(); }
72f84654-aad3-4f2e-9f7b-d839c029bde6
7
public void setOptions(String[] options) throws Exception { String classifierString = Utils.getOption('W', options); if (classifierString.length() == 0) classifierString = weka.classifiers.rules.ZeroR.class.getName(); String[] classifierSpec = Utils.splitOptions(classifierString); if (classifierSpec.length == 0) { throw new Exception("Invalid classifier specification string"); } String classifierName = classifierSpec[0]; classifierSpec[0] = ""; setClassifier(Classifier.forName(classifierName, classifierSpec)); String cString = Utils.getOption('C', options); if (cString.length() != 0) { setClassIndex((new Double(cString)).intValue()); } else { setClassIndex(-1); } String fString = Utils.getOption('F', options); if (fString.length() != 0) { setNumFolds((new Double(fString)).intValue()); } else { setNumFolds(0); } String tString = Utils.getOption('T', options); if (tString.length() != 0) { setThreshold((new Double(tString)).doubleValue()); } else { setThreshold(0.1); } String iString = Utils.getOption('I', options); if (iString.length() != 0) { setMaxIterations((new Double(iString)).intValue()); } else { setMaxIterations(0); } if (Utils.getFlag('V', options)) { setInvert(true); } else { setInvert(false); } Utils.checkForRemainingOptions(options); }
c43dda4c-7513-4b7c-b13b-84fe842dc8ba
0
private void handleError(String message, Exception e) { MessageDialog.getInstance().showError(message); LOGGER.error(message, e); }
3cc2a5ef-e2ab-4ab3-9bff-3c6f7297cf24
1
private void checkMinimumPlayers() { if (controller.canGameBeStarted()) { startServerButton.setEnabled(true); } addButtonHandlers(); }
cb812fbb-973a-4d48-aa7e-c1a17f5d72bb
0
public LRParseTableChooserPane(LRParseTable table) { super(table); }
f140ad4c-4621-419f-b639-a9dce677a978
2
public static String trimNullSquares(String s) { if (s != null && s.indexOf('\u0000') >= 0) { s = s.substring(0, s.indexOf('\u0000')); } return s; }
b5602f85-ff7c-4fba-be28-bb49ff507aae
4
public static Set<ITrackTile> getAdjecentTrackTiles(World world, int x, int y, int z) { Set<ITrackTile> tracks = new HashSet<ITrackTile>(); ITrackTile tile = getTrackFuzzyAt(world, x, y, z - 1); if (tile != null) tracks.add(tile); tile = getTrackFuzzyAt(world, x, y, z + 1); if (tile != null) tracks.add(tile); tile = getTrackFuzzyAt(world, x - 1, y, z); if (tile != null) tracks.add(tile); tile = getTrackFuzzyAt(world, x + 1, y, z); if (tile != null) tracks.add(tile); return tracks; }
c01a809f-9bf5-4247-b82e-7e128edbf9dd
6
public static boolean adjacentCoordinates(Coordinates c1, Coordinates c2, int height, int width) { // If they are in the same row if (c1.row == c2.row) { // If they are one to the left or one to the right of // each other if ((c1.col + 1) % width == c2.col || (c2.col + 1) % width == c1.col) { return true; } } // If they are in the same column if (c1.col == c2.col) { // If they are one above or below each other if ((c1.row + 1) % height == c2.row || (c2.row + 1) % height == c1.row) { return true; } } return false; }
34a0eb40-6e02-4c2a-ac0a-4f5e514a537a
8
protected void addRandomNucleotide() { double dr = 4 * Math.random(); Nucleotide nn = null; if (dr >= 0 && dr < 1) nn = Nucleotide.ADENINE; else if (dr >= 1 && dr < 2) nn = Nucleotide.GUANINE; else if (dr >= 2 && dr < 3) nn = Nucleotide.CYTOSINE; else if (dr >= 3 && dr < 4) nn = Nucleotide.THYMINE; addNucleotide(nn); }
447a969a-5b93-469c-a4dd-4aea7df7518f
6
public String stComposeEmailForYahooEmailService(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_YAHOO_TO_FIELD); errorMsg.add("To field is not present"); xPath.add(SIGNIN_YAHOO_MESSAGE_BODY); errorMsg.add("Message field is not present"); xPath.add(SIGNIN_YAHOO_SUBJECT_FIELD); errorMsg.add("Cancel button is not present"); xPath.add(SIGNIN_YAHOO_SEND_BUTTON); errorMsg.add("Share Button is not present"); comLib.stVerifyObjects(xPath, errorMsg, "STOP"); xPath.clear(); errorMsg.clear(); emailSubjectField = browser.getValue(SIGNIN_YAHOO_SUBJECT_FIELD); System.out.println(emailSubjectField); //emailMessageBox = browser.getText(SIGNIN_YAHOO_MESSAGE_BODY); //System.out.println(emailMessageBox); Block: { /*Typing Receipient */ if(!"".equals(to)) { browser.focus(SIGNIN_YAHOO_TO_FIELD); browser.click(SIGNIN_YAHOO_TO_FIELD); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } browser.type(SIGNIN_YAHOO_TO_FIELD, to ); } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } /* Comparing Subject and message body values */ if(emailSubjectField.contains(subject)) //&& emailMessageBox.contains(message)) { actVal= 0; /*Email is Composed successfully for Yahoo service */ System.out.println("Values matched"); browser.click(SIGNIN_YAHOO_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, "stComposeEmailForYahooEmailService",flow, hm); if(flow.contains("STOP")){ assertEquals("PASS",returnVal); } return returnVal; }
83b6f481-91de-42f6-9df9-3769c5d1c5a0
6
public static void connect(TreeLinkNode root) { if (root == null) return; //connectHelper1(root); //connectHelper2(root); if (root.left != null) { root.left.next = root.right; connect(root.left); connect(root.right); } if (root.left != null &&root.right != null) { TreeLinkNode rootLeft = root.right.left; TreeLinkNode rootRight = root.left.right; while (rootLeft != null && rootRight != null) { rootRight.next = rootLeft; rootRight = rootRight.right; rootLeft = rootLeft.left; } connect(root.left); connect(root.right); } }
903a91aa-19d8-41ab-8094-804350b29591
8
public static void input (String cmd, String args) { switch (cmd) { case "/help": getHelp (); break; case "/day": // Check in debug LineManager.addDay (); System.out.println ("Day " + (LineManager.dayNum + 1) + " added."); //inManager.debugTest (); break; case "/sp": LineManager.mode = 0; System.out.println ("Spanish Mode."); break; case "/en": LineManager.mode = 1; System.out.println ("English Mode."); break; case "/desc": LineManager.mode = 2; System.out.println ("Description Mode."); DescriptionWindow.showFrame(); System.out.println ("Use the \"Add Description\" window to input " + "your descritpion."); System.out.println ("Once you're done writing, press [ENTER]."); break; case "/conj": LineManager.mode = 3; System.out.print ("Infinitive: "); InputManager.conjState = -1; break; case "/ex": LineManager.mode = 4; System.out.println ("Sub-Conjugation Mode."); break; case "/debug": String[] a = { "title", "Soy", "Eres", "Es", "Somos", "Son" }; Day.debugConjChart (a); break; // TODO: Add cases for extra commands default: System.out.println ("Command not recognized. Please use /help" + " for the command list."); break; } //inMgr.debugTest (); }
d2799496-63ed-466b-af96-57dec09669f2
4
public void remove(WeakReference<Object> wref) { Set<Entry<Long, List<WeakReference<Object>>>> entrySet = buckets.entrySet(); // iterate over the buckets Iterator<Entry<Long, List<WeakReference<Object>>>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Entry<Long, List<WeakReference<Object>>> next = iterator.next(); List<WeakReference<Object>> value = next.getValue(); if (value != null) { synchronized (value) { if (value.contains(wref)) { value.remove(wref); if (value.isEmpty()) { // we've removed the last wref with this id, // remove the bucket iterator.remove(); } break; } } } } }
a711e127-fba8-4368-a17a-139b5fe56bd1
6
public static LinkedListNode reverseEveryOtherKNodes(LinkedListNode head, int k) { LinkedListNode prev = null; LinkedListNode current = head; LinkedListNode next; int count = 0; while (count < k && current != null) { next = current.getNext(); current.setNext(prev); prev = current; current = next; count++; } if (head != null) { head.setNext(current); } count = 0; while (count < k - 1 && current != null) { current = current.getNext(); count++; } if (current != null) current.setNext(reverseEveryOtherKNodes(current.getNext(), k)); return prev; }
c522599f-ff87-4a31-be91-27609ca83d38
4
public void setGender(String gender) { if (gender.toLowerCase() == "male" && isFemale == true) { this.isFemale = false; totalWomen--; } else if (gender.toLowerCase() == "female" && isFemale == false){ this.isFemale = true; totalWomen++; } }
0d01284e-2bcb-457f-9d4d-cf1d9910d928
7
public static Stella_Object accessAlternativeBindingsSetSlotValue(AlternativeBindingsSet self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Logic.SYM_LOGIC_THE_VARIABLE) { if (setvalueP) { self.theVariable = ((PatternVariable)(value)); } else { value = self.theVariable; } } else if (slotname == Logic.SYM_LOGIC_BINDINGS) { if (setvalueP) { self.bindings = ((Set)(value)); } else { value = self.bindings; } } else if (slotname == Logic.SYM_STELLA_SURROGATE_VALUE_INVERSE) { if (setvalueP) { self.surrogateValueInverse = ((Surrogate)(value)); } else { value = self.surrogateValueInverse; } } else { if (setvalueP) { KeyValueList.setDynamicSlotValue(self.dynamicSlots, slotname, value, null); } else { value = self.dynamicSlots.lookup(slotname); } } return (value); }
173dd931-bd61-44fd-9e78-d2491e98c330
5
public static void main(String[] args) { String s = "国无锡"; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); byte[] b = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } System.out.println(buf.toString()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte[] buf = MD5(s.getBytes()); String tmp = ""; for (int i = 0; i < buf.length; i++) tmp = tmp + byteToHex(buf[i], 2); System.out.println(tmp.toUpperCase()); }
09232315-a11e-4b74-b37e-3655f39df901
1
void run() { // System.out.println("Started " + in2); for (int i = 0; i < 1000000; i++) { double f = i + Math.PI * i / 12.3456 * i; double g = Math.sin(f * f) / (i + 1) * Math.PI; } // System.out.println("Done " + in2); }
861b557b-bba9-4cd4-b1e0-7db437826e29
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 Applicant)) { return false; } Applicant other = (Applicant) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
1a4783ed-2bc6-466f-a37d-a3f175ef0554
9
private ILNode setupNode(final IFPNode fp, final DomainTuple d, final ILNode parent) throws Exception { if( ! evaluate( fp.getCondition(), d ) ) { return new LFalse(); } final FactorCatalog factCat = getFactorCatalog(fp.getId()); final GenTuple key = (fp.isFactorized() || parent == null) ? GenTuple.From(fp, d) : GenTuple.From(fp, d, parent.hashCode()); if(factCat.contains(key)) return factCat.get(key); switch(fp.getType()) { case NOr: return factCat.put(key, new LOr(true)); case Not: return factCat.put(key, new LNot()); case And: { final LAnd lAnd = new LAnd(false); // We explicit need to set two child nodes, // because NNode sets only one default node. lAnd.addChild(new LFalse()); lAnd.addChild(new LFalse()); return factCat.put(key, lAnd); } case Or: { final LOr lOr = new LOr(false); // We explicit need to set two child nodes, // because NNode sets only one default node. lOr.addChild(new LFalse()); lOr.addChild(new LFalse()); return factCat.put(key, lOr); } case Source: { final FPSource fpSource = (FPSource)fp; final LSource lSource = new LSource(); // The mask priority is later used // for the probability calculation // in order to decide which bid's // need to be masked first. lSource.setMaskPriority( fpSource.getMaskPriority()); return factCat.put(key, lSource); } default: throw new Exception(String.format( "Unknown formula pattern type: %s.", fp.getType())); } }
ba4d76d2-f267-4fb4-89e8-ecf043be2a23
5
private boolean versionCheck() { final String title = this.versionName; if (this.type != UpdateType.NO_VERSION_CHECK) { final String localVersion = this.plugin.getDescription().getVersion(); if (title.split(DELIMETER).length == 2) { // Get the newest file's version number final String remoteVersion = title.split(DELIMETER)[1].split(" ")[0]; if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) { // We already have the latest version, or this build is tagged for no-update this.result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' final String authorInfo = this.plugin.getDescription().getAuthors().isEmpty() ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); this.plugin.getLogger().warning("Please notify the author of this error."); this.result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; }
dc5124ba-4870-4b60-8ada-3a01b3d780a7
7
public static String [] partitionOptions(String [] options) { for (int i = 0; i < options.length; i++) { if (options[i].equals("--")) { // ensure it follows by a -E option int j = i; while ((j < options.length) && !(options[j].equals("-E"))) { j++; } /* if (j >= options.length) { return new String[0]; } */ options[i++] = ""; String [] result = new String [options.length - i]; j = i; while ((j < options.length) && !(options[j].equals("-E"))) { result[j - i] = options[j]; options[j] = ""; j++; } while(j < options.length) { result[j - i] = ""; j++; } return result; } } return new String [0]; }
31e9ab60-0916-47cc-ac58-1505b6b5830d
8
private static String getTaxonomy( String key ) throws Exception { key = key.toLowerCase(); for(int x=1; x < NewRDPParserFileLine.TAXA_ARRAY.length; x++) { String level = NewRDPParserFileLine.TAXA_ARRAY[x]; if( key.indexOf(level) != -1 ) return level; } if( key.endsWith("cla")) return NewRDPParserFileLine.CLASS; if( key.endsWith("ord")) return NewRDPParserFileLine.ORDER; if( key.endsWith("fami") || key.endsWith("fam") || key.endsWith("fa") || key.equals("clostridiales_incertae_sedis_xif")) return NewRDPParserFileLine.FAMILY; throw new Exception("Could not find " + key); }
1076b971-2aca-484c-8d63-283233aefadf
3
public void draw(Graphics2D graphics) { if (xOffset == -1) { xOffset = (int) (rect.width - font.getStringBounds(label, graphics.getFontRenderContext()).getWidth()) / 2; yOffset = (int) (font.getLineMetrics(label, graphics.getFontRenderContext()).getAscent() + rect.height) / 2; } if (isPressed()) graphics.setColor(Color.RED); else if (isHover()) graphics.setColor(Color.GREEN); else graphics.setColor(Color.WHITE); graphics.fill(rect); graphics.setColor(Color.GRAY); graphics.setFont(font); graphics.drawString(label, rect.x + xOffset, rect.y + yOffset); }
c163622e-6ce0-4acb-b8f2-444d4879c746
4
private int makeFieldInitializer(Bytecode code, CtClass[] parameters) throws CannotCompileException, NotFoundException { int stacksize = 0; Javac jv = new Javac(code, this); try { jv.recordParams(parameters, false); } catch (CompileError e) { throw new CannotCompileException(e); } for (FieldInitLink fi = fieldInitializers; fi != null; fi = fi.next) { CtField f = fi.field; if (!Modifier.isStatic(f.getModifiers())) { int s = fi.init.compile(f.getType(), f.getName(), code, parameters, jv); if (stacksize < s) stacksize = s; } } return stacksize; }
89c94ba2-850e-486e-adad-53ffc721e7fb
5
private void generateModeConversionRules(List<CtModeConversionRule> modeConversionRules) { if (null == modeConversionRules || modeConversionRules.size() == 0) return; for (CtModeConversionRule conversionRule : modeConversionRules) { List<String> conversionList = conversionRule.getTo(); if (null == conversionList || conversionList.size() == 0) continue; String[] to = conversionList.toArray(new String[conversionList.size()]); conversionList.toArray(to); String from = conversionRule.getFrom(); theory.addModeConversionRules(from, to); } }
a62a6f33-65d8-406b-a3f7-ba9d4010ef5e
3
public void draw(double[] input) { draw.show(0); draw.clear(Drawer.BLACK); double barWidth = 1.0 / input.length; double width = 0.90 * barWidth; for (int i = 0; i < input.length; i++) { if (exch.contains(i)) { draw.setPenColor(Drawer.RED); } else if (less.contains(i)) { draw.setPenColor(Drawer.ORANGE); } else { draw.setPenColor(Drawer.GRAY); } double x = barWidth * (i + 0.5); double y = 0.5; double halfWidth = width * 0.5; double halfHeight = input[i] * 0.45; draw.filledRectangle(x, y, halfWidth, halfHeight); } draw.setPenColor(new Color(222, 222, 222)); draw.setFont(draw.getFont().deriveFont(16.0f)); draw.textLeft(0, 1, this.name); draw.setFont(draw.getFont().deriveFont(10.0f)); draw.textLeft(0, 0, "E: " + this.exchs); draw.textLeft(0.1, 0, "C: " + this.compares); draw.textLeft(0.8, 0, "T: " + (this.compares + this.exchs)); draw.show(33); }
29aa3148-1d92-4b73-9ca1-f62f67dcf0e0
0
public static void main(String[] args) { ParentProducer producer = new ParentProducer(); ParentReturn ret = producer.process(); System.out.println(ret); producer = new ChildProducer(); ret = producer.process(); System.out.println(ret); }
975435b8-4597-4d6d-8d32-47eb3693edb1
3
private static Location getLocation(String location) throws NewCustomException { Session session = null; Transaction tx = null; Location loc = null; try { session = HibernateUtil.createSessionFactory().openSession(); tx = session.beginTransaction(); Criteria criteria = session.createCriteria(Location.class); criteria.add(Restrictions.eq("location", location)); List<Location> locList = criteria.list(); if (locList.size() == 0) { loc = null; } else { loc = locList.get(0); } tx.commit(); } catch (HibernateException e) { e.printStackTrace(); if (tx != null) tx.rollback(); throw new NewCustomException("Error in Finding Location"); } finally { session.close(); } return loc; }
861ca5d3-02ed-4643-9e17-8b866f4c4fd0
8
private static boolean validateMove(PGNMove move) { String strippedMove = move.getMove(); if (move.isCastle()) { return true; } else if (move.isEndGameMarked()) { return true; } else if (strippedMove.length() == MOVE_TYPE_1_LENGTH) { return PGNParseUtils.matchType1(strippedMove); } else if (strippedMove.length() == MOVE_TYPE_2_LENGTH) { return PGNParseUtils.matchType2(strippedMove) || PGNParseUtils.matchType5(strippedMove); } else if (strippedMove.length() == MOVE_TYPE_3_LENGTH) { return PGNParseUtils.matchType3(strippedMove) || PGNParseUtils.matchType6(strippedMove); } else if (strippedMove.length() == MOVE_TYPE_4_LENGTH) { return PGNParseUtils.matchType4(strippedMove); } return false; }
3e62f53d-b317-4fd3-8fa7-058c28730835
1
@Test public void testLoadToMemory() { //Test assembled code is loaded to memory loader.load(testProgram); loader.loadToMemory(); for (int i = 0; i < testProgram.length; i++) { assertEquals(testProgram[i].toString(), memory.accessAddress(i).toString()); } }
68d0d8a7-659a-46b2-9741-7fd36e8a1c3a
1
public static void tokenize(String line, ArrayList<String> tokens) { StringTokenizer strTok = new StringTokenizer(line); while (strTok.hasMoreTokens()) { String token = strTok.nextToken(); tokens.add(token); } }
279a0f60-4022-4625-a267-a60249c706c1
7
public static String shorten(Graphics g, String text, int width, Preference preference) { if (g.getFontMetrics().stringWidth(text) <= width) return text; if (preference == Preference.begin) { if (g.getFontMetrics().stringWidth("..") > width) return ""; int len = 0; while (g.getFontMetrics().stringWidth(text.substring(0, len + 1) + "..") <= width) len++; return text.substring(0, len) + ".."; } if (preference == Preference.end) { if (g.getFontMetrics().stringWidth("..") > width) return ""; int len = 0; while (g.getFontMetrics().stringWidth(".." + text.substring(text.length() - len)) <= width) len++; return ".." + text.substring(text.length() - len); } return ""; }
adf2dc00-6b3e-4b09-8a43-ef469e679199
0
public String getLogin() { return login; }
501b0fc2-fadf-4611-a9bf-de98c4d2b673
7
private String getSelectedExpression() { String result=""; switch(Equation.getSelectedIndex()+1) { case 1: result=fx; break; case 2: result=gx; break; case 3: result=ax; break; case 4: result=bx; break; case 5: result=cx; break; case 6: result=dx; break; case 7: result=ex; break; } return result; }
edcb9e14-729a-41f0-a473-0369f337c491
4
public static void saveAdventurer(Adventurer adventurer) throws IOException { try { List<Adventurer> adventurers = new ArrayList<>(); adventurers = getAllAdventurer(); boolean found = false; for (int i = 0, end = adventurers.size(); i < end; i++) { if (adventurers.get(i).getName().equals(adventurer.getName())) { adventurers.set(i, adventurer); found = true; break; } } if (!found) { adventurers.add(adventurer); } objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(SAVE_FILE_PATH), adventurers); } catch (IOException ex) { Logger.getLogger(JsonDao.class.getName()).log(Level.SEVERE, null, ex); } }
57e073d4-e5f3-4481-bd2b-55146e16d869
8
String getHanyuPinyinStringWithPolyphones(String string){ for(int i=0; i<string.length(); i++){ String pinyinRecord = getHanyuPinyinRecordFromChar(string.charAt(i)); if(null != pinyinRecord){ int indexOfLeftBracket = pinyinRecord.indexOf(Field.LEFT_BRACKET); int indexOfRightBracket = pinyinRecord.lastIndexOf(Field.RIGHT_BRACKET); String polyphonesStrings = pinyinRecord.substring(indexOfLeftBracket+ Field.LEFT_BRACKET.length(), indexOfRightBracket); String[] polyphonesString = polyphonesStrings.split(Field.COMMA); for(int j=0; j<polyphonesString.length; j++){ String[] phrase = polyphonesString[j].split(Field.COLON); if(phrase[0].contains(String.valueOf(string.charAt(i)))){ if(string.substring(i, i+2).equals(phrase[0])||string.substring(i, i+3).equals(phrase[0]) ||string.substring(i-1, i+1).equals(phrase[0])||string.substring(i-2, i+1).equals(phrase[0])){ string = string.replaceAll(phrase[0], phrase[1]); } } } } } return string; }
efe9f005-ed26-4756-a12a-53304cf088de
5
public Piece[][] generateBoard(){ ArrayList<Piece> figuren = new ArrayList<Piece>(); Piece[][] newBoard = new Piece[8][8]; //Weisse Figuren figuren.add(new King("weiss")); figuren.add(new Queen("weiss")); figuren.add(new Knight("weiss", 1)); figuren.add(new Knight("weiss", 2)); figuren.add(new Bishop("weiss", 1)); figuren.add(new Bishop("weiss", 2)); figuren.add(new Rock("weiss", 1)); figuren.add(new Rock("weiss", 2)); for(int i=0; i<8; i++){ figuren.add(new Pawn("weiss", i)); } //Schwarze Figuren figuren.add(new King("schwarz")); figuren.add(new Queen("schwarz")); figuren.add(new Knight("schwarz", 1)); figuren.add(new Knight("schwarz", 2)); figuren.add(new Bishop("schwarz", 1)); figuren.add(new Bishop("schwarz", 2)); figuren.add(new Rock("schwarz", 1)); figuren.add(new Rock("schwarz", 2)); for(int i=0; i<8; i++){ figuren.add(new Pawn("schwarz", i)); } //Setzen for(Piece figur: figuren){ this.putPieceOnBoard(figur, newBoard); } //Leere Felder füllen for(int i=2; i<=5; i++){ for(int j=0; j<=7;j++){ newBoard[i][j] = this.fillEmptySpot(j, i); } } return newBoard; }
6d141eaf-e377-4b9c-ba24-7d27d95566c4
8
public void setChecked(int locx, int locy, int setDirec) { //System.out.println("Set checked called"); switch (setDirec) { case 0: traversal[locy][locx] |= 0x10; if (locy > 0) traversal[locy - 1][locx] |= 0x40; break; case 1: traversal[locy][locx] |= 0x20; if (locx < MicromouseRun.BOARD_MAX - 1) traversal[locy][locx + 1] |= 0x80; break; case 2: traversal[locy][locx] |= 0x40; if (locy < MicromouseRun.BOARD_MAX - 1) traversal[locy + 1][locx] |= 0x10; break; case 3: traversal[locy][locx] |= 0x80; if (locx > 0) traversal[locy][locx - 1] |= 0x20; break; } }
1b716cd8-61d0-4d06-acc7-a41cfce87ee3
0
public void setCostPrice(double costPrice) { this.costPrice = costPrice; }
29d45b58-ec2a-48bc-9dd0-3a8e81565c6d
7
public static int discrete(double[] a) { double EPSILON = 1E-14; double sum = 0.0; for (int i = 0; i < a.length; i++) { if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]); sum = sum + a[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries not equal to one: " + sum); // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while (true) { double r = uniform(); sum = 0.0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; if (sum > r) return i; } } }
59b7a670-c0ee-4de9-aee4-d9b03f09909c
8
public FontRenderer(GameSettings var1, String var2, TextureManager var3) { this.settings = var1; BufferedImage var14; try { var14 = ImageIO.read(TextureManager.class.getResourceAsStream(var2)); } catch (IOException var13) { throw new RuntimeException(var13); } int var4 = var14.getWidth(); int var5 = var14.getHeight(); int[] var6 = new int[var4 * var5]; var14.getRGB(0, 0, var4, var5, var6, 0, var4); for(int var15 = 0; var15 < 128; ++var15) { var5 = var15 % 16; int var7 = var15 / 16; int var8 = 0; for(boolean var9 = false; var8 < 8 && !var9; ++var8) { int var10 = (var5 << 3) + var8; var9 = true; for(int var11 = 0; var11 < 8 && var9; ++var11) { int var12 = ((var7 << 3) + var11) * var4; if((var6[var10 + var12] & 255) > 128) { var9 = false; } } } if(var15 == 32) { var8 = 4; } this.widthmap[var15] = var8; } this.fontTexture = var3.load(var2); }
4f1db7c9-8311-4d0b-9590-d08176a99840
9
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed NanoPost np; byte[] parentHash = EncryptionProvider.EMPTY_HASH_SHA256; String parentHashStr = edParentHash.getText(); if (!parentHashStr.trim().isEmpty()) { if ((parentHashStr.length() == EncryptionProvider.SHA_256_HASH_SIZE_BYTES * 2) && parentHashStr.matches("[a-f0-9]+")) { parentHash = ByteUtils.stringToBytes(parentHashStr); } } if (!edAttachFile.getText().isEmpty()) { File attachFile = new File(edAttachFile.getText()); if (!attachFile.exists()) { JOptionPane.showMessageDialog(this, "Selected attach file does not exist", "Error", JOptionPane.ERROR_MESSAGE); return; } np = NanoPostFactory.createNanoPost(txtPostText.getText(), parentHash, attachFile); } else { np = NanoPostFactory.createNanoPost(txtPostText.getText(), parentHash, null); } File containerFile; if (rbRandomContainer.isSelected()) { containerFile = this.getRandomContainerPNG(); if (containerFile == null) { JOptionPane.showMessageDialog(this, "There is no any PNG file in folder " + MainClass.CONTAINERS_DIR, "Error", JOptionPane.ERROR_MESSAGE); return; } } else { containerFile = new File(edContainerFile.getText()); } if (!containerFile.exists()) { JOptionPane.showMessageDialog(this, "Selected container file does not exists.", "Error", JOptionPane.ERROR_MESSAGE); return; } File outputFile = null; NanoPost nanoPost = null; try { outputFile = new File(MainClass.OUTBOX_DIR + System.getProperty("file.separator") + System.currentTimeMillis() + ".png"); ImageUtils.encodeIntoImage(containerFile, outputFile, np.getAsBytes(), edBoardCode.getText()); byte[] dataBytes = ImageUtils.tryToDecodeSteganoImage(ByteUtils.readBytesFromFile(outputFile), edBoardCode.getText()); nanoPost = NanoPostFactory.getNanoPostFromBytes(dataBytes, true); nanoPost.setSourceImageData(ByteUtils.readBytesFromFile(outputFile)); nanoPost.saveToFile(true); nanoPost.clearAllBinaryData(); // Trying to free memory nanoPost = null; dataBytes = null; } catch (MalformedNanoPostException | IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) { JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(), "An error occured", JOptionPane.ERROR_MESSAGE); } finally { outputFile.delete(); } }//GEN-LAST:event_jButton1ActionPerformed
d5d7a3c2-9fc6-4bb3-a265-79731d3e4f93
4
public static void loadPrefsFile(CommandParser parser, String filename) { try { BufferedReader buffer = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line = buffer.readLine(); while (line != null) { try { parser.parse(line, true, true); } catch (UnknownCommandException uce) { System.out.println("Unknown Command"); } line = buffer.readLine(); } buffer.close(); } catch (FileNotFoundException fnfe) { System.err.println("File Not Found: " + filename + "\n" + fnfe); } catch (Exception e) { System.err.println("Could not create FileReader: " + filename + "\n" + e); } }
6ff9991b-e616-4d5e-a190-3e8351a0c43a
6
public void buttonInsertClicked (int xKoordinate, int yKoordinate, String objektName, JComboBox removeBox) { if (objektName == "Turtle") { Turtle turtle = new Turtle(xKoordinate, yKoordinate, getNumberOfObjekt(objektName) + " " + objektName, ocean); removeBox.addItem(getNumberOfObjekt(objektName) + " " + objektName); ocean.getOceanObjects().add(turtle); oceanArea.repaint(); } else if (objektName == "Nemo") { Fish nemo = new Fish(xKoordinate, yKoordinate, getNumberOfObjekt(objektName) + " " + objektName, ocean); removeBox.addItem(getNumberOfObjekt(objektName) + " " + objektName); ocean.getOceanObjects().add(nemo); oceanArea.repaint(); } else if (objektName == "Shark") { Shark megaloden = new Shark(xKoordinate, yKoordinate, getNumberOfObjekt(objektName) + " " + objektName, ocean); removeBox.addItem(getNumberOfObjekt(objektName) + " " + objektName); ocean.getOceanObjects().add(megaloden); oceanArea.repaint(); } else if(objektName == "Bubble") { Bubble bubble = new Bubble(xKoordinate, yKoordinate, getNumberOfObjekt(objektName) + " " + objektName, ocean); removeBox.addItem(getNumberOfObjekt(objektName) + " " + objektName); ocean.getOceanObjects().add(bubble); oceanArea.repaint(); } else if(objektName == "Plant"){ Plant plant = new Plant(xKoordinate, yKoordinate, getNumberOfObjekt(objektName) + " " + objektName, ocean); removeBox.addItem(getNumberOfObjekt(objektName) + " " + objektName); ocean.getOceanObjects().add(plant); oceanArea.repaint(); } else if(objektName == "Stone"){ Stone stone = new Stone(xKoordinate, yKoordinate, getNumberOfObjekt(objektName) + " " + objektName, ocean); removeBox.addItem(getNumberOfObjekt(objektName) + " " + objektName); ocean.getOceanObjects().add(stone); oceanArea.repaint(); } }
aa1c5398-3989-4499-b975-52142f6a8ef1
8
protected Object instanceToArray(Instance instance) throws Exception { int index; int count; int i; Object result; // determine number of non-zero attributes count = 0; for (i = 0; i < instance.numValues(); i++) { if (instance.index(i) == instance.classIndex()) continue; if (instance.valueSparse(i) != 0) count++; } if (m_Bias >= 0) { count++; } Class[] intDouble = new Class[] { int.class, double.class }; Constructor nodeConstructor = Class.forName(CLASS_FEATURENODE).getConstructor(intDouble); // fill array result = Array.newInstance(Class.forName(CLASS_FEATURENODE), count); index = 0; for (i = 0; i < instance.numValues(); i++) { int idx = instance.index(i); double val = instance.valueSparse(i); if (idx == instance.classIndex()) continue; if (val == 0) continue; Object node = nodeConstructor.newInstance(Integer.valueOf(idx+1), Double.valueOf(val)); Array.set(result, index, node); index++; } // add bias term if (m_Bias >= 0) { Integer idx = Integer.valueOf(instance.numAttributes()+1); Double value = Double.valueOf(m_Bias); Object node = nodeConstructor.newInstance(idx, value); Array.set(result, index, node); } return result; }
5595086d-115a-4ead-a4fc-7b0f83b7f89f
2
public String[] getGroupNames(){ if(!this.dataEntered)throw new IllegalArgumentException("no data has been entered"); String[] ret = new String[this.nGroups]; for(int i=0; i<this.nGroups; i++)ret[i] = this.groupNames[i]; return ret; }
cd19c71e-2aaa-4eda-b352-ab2824d80f74
8
public void declare(JFormatter f) { if (jdoc != null) f.nl().g(jdoc); if (annotations != null){ for (JAnnotationUse annotation : annotations) f.g(annotation).nl(); } f.g(mods).p(classType.declarationToken).id(name).d(generifiable); if (superClass != null && superClass != owner().ref(Object.class)) f.nl().i().p("extends").g(superClass).nl().o(); if (!interfaces.isEmpty()) { if (superClass == null) f.nl(); f.i().p(classType==ClassType.INTERFACE ? "extends" : "implements"); f.g(interfaces); f.nl().o(); } declareBody(f); }
d052f6e3-1ca1-4fd2-815b-858d05bff75b
8
public Image idleImages(int i) { Image temp = null; switch(i) { case 1: temp = new ImageIcon("src/images/idle_north.png").getImage(); break; case 2: temp = new ImageIcon("src/images/idle_north_east.png").getImage(); break; case 3: temp = new ImageIcon("src/images/idle_east.png").getImage(); break; case 4: temp = new ImageIcon("src/images/idle_south_east.png").getImage(); break; case 5: temp = new ImageIcon("src/images/idle_south.png").getImage(); break; case 6: temp = new ImageIcon("src/images/idle_south_west.png").getImage(); break; case 7: temp = new ImageIcon("src/images/idle_west.png").getImage(); break; case 8: temp = new ImageIcon("src/images/idle_north_west.png").getImage(); break; default: break; } return temp; }
caac59b1-8a08-4e75-96f6-59d4932fbe53
3
@Override public void deserialize(Buffer buf) { super.deserialize(buf); diceNum = buf.readShort(); if (diceNum < 0) throw new RuntimeException("Forbidden value on diceNum = " + diceNum + ", it doesn't respect the following condition : diceNum < 0"); diceSide = buf.readShort(); if (diceSide < 0) throw new RuntimeException("Forbidden value on diceSide = " + diceSide + ", it doesn't respect the following condition : diceSide < 0"); diceConst = buf.readShort(); if (diceConst < 0) throw new RuntimeException("Forbidden value on diceConst = " + diceConst + ", it doesn't respect the following condition : diceConst < 0"); }
258159f3-a70e-401e-957b-b3f4a362f171
0
public RandomIntTest() { }
ab7101a4-d242-4a3e-8435-fabe1820fa29
5
private void createEvents() { btnUploadSong.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { EventQueue.invokeLater(new Runnable() { public void run() { try { UploadSongFrame frame = new UploadSongFrame( indexPanel, controller); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }); btnNewRepertory.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnSync.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { mainFrame.getClient().setSync(true); mainFrame.getClient().sendToServer("data"); } catch (IOException e1) { if (alert == null || alert.isClosed()) { alert = new MessageFrame(mainFrame.getDesktopPane1()); alert.setMessage("Unable to connecto to the server at this time. Try again later."); } } } }); btnLogout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { mainFrame.getClient().closeConnection(); mainFrame.switchToLoginPanel(); } catch (IOException e1) { e1.printStackTrace(); } } }); }
afd0d300-24be-48ed-8478-996b8ae04992
4
public boolean erTegen(double nx, double ny){ if (nx <= getX()+getWidth() && nx >= getX() && ny <= getY()+getHeight() && ny >= getY()){ return true; } return false; }
d9e3f3cc-3520-4fc7-9182-7dde65e93404
4
private MulticastSocket openUDPBroadcastSocket( NetworkInterface pNetworkInterface) { MulticastSocket socket; try{ if (!simulateNotchers) { socket = new MulticastSocket(4445); if (pNetworkInterface != null) { try{ socket.setNetworkInterface(pNetworkInterface); }catch (SocketException e) {return(null);} } } else {socket = new UDPSimulator(4445, "Notcher present...", 4);} } catch (IOException e) { logSevere(e.getMessage() + " - Error: 352"); tsLog.appendLine("Couldn't create Notcher broadcast socket."); return(null); } return(socket); }//end of NotcherGroup::openUDPBroadcastSocket
625e52d9-909c-44fe-a363-b0a759e0856b
9
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Block block = (Block) o; if (initialMoves != block.initialMoves) return false; if (remainingMoves != block.remainingMoves) return false; if (origin != null ? !origin.equals(block.origin) : block.origin != null) return false; if (place != null ? !place.equals(block.place) : block.place != null) return false; return true; }
02b47c08-9ec5-4187-833b-964108d959e7
3
public VDKInnerDirectory findChild(int offset) { for(VDKInnerDirectory d : children) { if(!(d instanceof VDKInnerFile)) { if(d.getDotDirectory().getOffset() == offset) return d; return d.findChild(offset); } } //TODO - Herestt: Throw exception. return null; }
4fec2528-17de-4e1e-b320-3285c09c09b3
5
protected static String getSorting(Class<?> cls) { String r = ""; for (Field f : cls.getFields()) { if (f.isAnnotationPresent(SortBy.class)) r += (r.length() == 0 ? "" : " ,") + f.getName() + (f.getAnnotation(SortBy.class).reverse() ? " DESC" : " ASC"); } return r; }
1c36600e-eb97-4163-8c6b-be60bb1ff24b
6
private void actualizarListaProd() { abrirBase(); tablaProd.setRowCount(0); prodlista = Articulo.where("codigo like ? or descripcion like ?", "%" + textcodprod.getText() + "%", "%" + textcodprod.getText() + "%"); Iterator<Articulo> it = prodlista.iterator(); while (it.hasNext()) { Articulo a = it.next(); String rowArray[] = new String[4]; rowArray[0] = a.getId().toString(); rowArray[1] = a.getString("codigo"); rowArray[2] = a.getString("marca"); rowArray[3] = a.getString("descripcion"); tablaProd.addRow(rowArray); } Articulo a = Articulo.findFirst("codigo = ?", textcodprod.getText()); if (a != null) { String fram = a.getString("equivalencia_fram"); if (!(fram.equals(""))) { prodlista = busqueda.filtroProducto2(fram); it = prodlista.iterator(); while (it.hasNext()) { Articulo b = it.next(); if (!(b.getInteger("id").equals(a.getInteger("id")))) { String rowArray[] = new String[4]; rowArray[0] = b.getId().toString(); rowArray[1] = b.getString("codigo"); rowArray[2] = b.getString("marca"); rowArray[3] = a.getString("descripcion"); tablaProd.addRow(rowArray); { } } } } } if (Base.hasConnection()) { Base.close(); } }
2766e785-dbbe-4ecf-bd53-acf25ddf1c6c
9
private void displayCreature(Creature currCreature) { String url = "http://bulbapedia.bulbagarden.net/wiki/" + currCreature.getName(); System.out.printf("%s \n[%s]\n", currCreature, url); for (Ability a : currCreature.getAbilities()) { if (a == null) { System.out.println("NULL ABILITY"); System.exit(0); } System.out.println(a); } System.out.println(currCreature.getBaseStats()); for (Type t : currCreature.getTypes()) { if (t == null) { // something went wrong } for (Move m : t.getStrongMoves()) { // only increment attacker count if it finds // compatible moves if (currCreature.getBaseStats().getPhyDmg() >= 100 && m.getType() == MoveType.PHYSICAL) { // list all physical move of the type // System.out.println(m); } if (currCreature.getBaseStats().getMagDmg() >= 100 && m.getType() == MoveType.SPECIAL) { // list all special move of the type // System.out.println(m); } } } System.out.println(); }
6f124231-45db-441b-bf3e-8191a7276f79
5
public String[] pickValues(int[] thrown) { Player player = GameEngine.activePlayer; myBet = thrown[2]; player.addRolls(thrown); thrownSum = thrown[0]+thrown[1]; ArrayList<String> list = new ArrayList<String>(); for (int i = 1; i <= 6 ; i++) { for (int j = 1; j <= 6 ; j++) { if(i+j == thrownSum) list.add(i + " and " + j); if(i == thrown[0] && j == thrown[1]) answer = i + " and " + j; } } System.out.println("Right answer is " + answer + ". For testing purpose. "); choices = list.toArray(new String[list.size()]); GameTurn.turn.setThrown(thrown); //GameMain.userInterface.setGuess(choices); return choices; }
39c2aea1-1e06-4b01-b99e-ef206876ef03
6
public static void main(String args[]) { /* 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(PlayRound.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PlayRound.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PlayRound.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PlayRound.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PlayRound().setVisible(true); } }); }
35572e7c-f540-44b3-bd7c-d3ebf1632c4d
4
private ReflectiveTypeAdapterFactory.BoundField createBoundField( final Gson context, final Field field, final String name, final TypeToken<?> fieldType, boolean serialize, boolean deserialize) { final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType()); // special casing primitives here saves ~5% on Android... return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) { final TypeAdapter<?> typeAdapter = getFieldAdapter(context, field, fieldType); @SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree @Override void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException { Object fieldValue = field.get(value); TypeAdapter t = new TypeAdapterRuntimeTypeWrapper(context, this.typeAdapter, fieldType.getType()); t.write(writer, fieldValue); } @Override void read(JsonReader reader, Object value) throws IOException, IllegalAccessException { Object fieldValue = typeAdapter.read(reader); if (fieldValue != null || !isPrimitive) { field.set(value, fieldValue); } } }; }
e50a8131-d701-4ace-a733-6fabf0fbfc87
0
private int indexCycle(int index, int delta) { int size = m_Components.length; int next = (index + delta + size) % size; return next; }
a106eaf4-d1ee-4965-bd58-7af7215e1a2f
1
public CtConstructor makeClassInitializer() throws CannotCompileException { CtConstructor clinit = getClassInitializer(); if (clinit != null) return clinit; checkModify(); ClassFile cf = getClassFile2(); Bytecode code = new Bytecode(cf.getConstPool(), 0, 0); modifyClassConstructor(cf, code, 0, 0); return getClassInitializer(); }
ec2eb3d9-1b5f-462c-b36b-c65dc9601bfd
5
public void draw(Graphics g) { if (inMenu()) { mainMenu.draw(g); } else { currentDemo.draw(g); if (currentDemo != null && !currentDemo.running()) { g.setColor(new Color(0, 0, 0, 200)); g.fillRect(0, 0, width, height); // Resume game button if (resume.contains(Mouse.location)) { g.setColor(new Color(0x2980B9)); } else { g.setColor(new Color(0x3498DB)); } g.fillRect(resume.x, resume.y, resume.width, resume.height); g.setColor(new Color(0xECF0F1)); g.setFont(new Font("Times New Roman", Font.PLAIN, 30)); g.drawString("Resume Game", resume.x + 35, resume.y + 35); // Return to main menu button if (returnToMenu.contains(Mouse.location)) { g.setColor(new Color(0x2980B9)); } else { g.setColor(new Color(0x3498DB)); } g.fillRect(returnToMenu.x, returnToMenu.y, returnToMenu.width, returnToMenu.height); g.setColor(new Color(0xECF0F1)); g.setFont(new Font("Times New Roman", Font.PLAIN, 30)); g.drawString("Return to Menu", returnToMenu.x + 30, returnToMenu.y + 35); } } }