method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
1d4de6b8-c95d-472c-809d-22f43e505f1a | 0 | public void setReplace(int i, String s) {
this.replaces.set(i, s);
} |
f826e8b2-21c9-41a6-8a69-5aedbd075639 | 6 | public void checkWar() {
if(bb.size()>0){
for (int i = 0; i < bb.size(); i++) {
Barb b = (Barb)bb.get(i);
if(grid[b.getX()][b.getY()]==4) {
System.out.println("Farm contact");
setBlock(b.getX(),b.getY(),3);
MF.SS.Farms-=1;
MF.writeNarra("Farm Destroyed!");
}
for(int ii = 0;ii<aa.size();ii++) {
Army a = (Army)aa.get(ii);
if(b.getX() == a.getX() && b.getY() == a.getY())
MF.writeNarra("FIGHT FIGHT!");
}
}
}
} |
efbb4e01-326e-4056-aaa6-9d6875b7809d | 7 | private AlgebraicParticle constructExpression(boolean sign, ArrayList<AlgebraicParticle> list, int exponent) {
if(list.size() == 0) {
//if the exponent isn't one then it needs to be carried over to the number
if(exponent != 1) return Number.ZERO.cloneWithNewSignAndExponent(sign, exponent);
return Number.ZERO;
}
else if(list.size() == 1) {
AlgebraicParticle a = list.get(0);
boolean resultingSign = sign == a.sign();
//if sign and exponent are right already
if(exponent == 1 && a.sign() == resultingSign) return a;
else if((exponent == 1 || a.exponent() == 1)) {
// Set the sign, and exponent. At least one exponent is 1, so multiplying gives us
// the one that isn't.
return a.cloneWithNewSignAndExponent(resultingSign, exponent * a.exponent());
}
// Neither exponent is 1.
// Return a single-element term. Maybe a bad idea; not sure what to do.
else {
return new Term(resultingSign, list, exponent);
}
}
else return new Expression(sign, list, exponent);
} |
fc23da77-0465-41ad-ba6a-f855c73c70fd | 7 | public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} |
589dbd73-b90b-46f4-9e47-63acdbed2ade | 0 | public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
} |
2d35c2e3-16d4-48f4-9335-f7dbcd5f4809 | 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(CadastraCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CadastraCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CadastraCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CadastraCliente.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 CadastraCliente().setVisible(true);
}
});
} |
bb94c650-5b8f-40df-a224-6154856c7446 | 6 | public static int loadProgram(String path, String vertexName, String fragmentName) {
int program = glCreateProgram();
int vertex = glCreateShader(GL_VERTEX_SHADER);
int fragment = glCreateShader(GL_FRAGMENT_SHADER);
StringBuilder vertexSource = new StringBuilder();
StringBuilder fragmentSource = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(ShaderLoader.class.getResourceAsStream(path + vertexName + ".vert")));
String line;
while ((line = reader.readLine()) != null)
vertexSource.append(line).append('\n');
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(ShaderLoader.class.getResourceAsStream(path + fragmentName + ".frag")));
String line;
while ((line = reader.readLine()) != null)
fragmentSource.append(line).append("\n");
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
glShaderSource(vertex, vertexSource);
glCompileShader(vertex);
if (glGetShaderi(vertex, GL_COMPILE_STATUS) == GL_FALSE)
System.err.println(vertexName + "_vertex " + "Vertex-Shader '" + vertexName + "' could not be compiled \n Error log:\n" + glGetShaderInfoLog(vertex, 1024));
glShaderSource(fragment, fragmentSource);
glCompileShader(fragment);
if (glGetShaderi(fragment, GL_COMPILE_STATUS) == GL_FALSE)
System.err.println(fragmentName + "_fragment " + "Fragment-Shader '" + fragmentName + "' could not be compiled \n Error log:\n" + glGetShaderInfoLog(fragment, 1024));
glAttachShader(program, vertex);
glAttachShader(program, fragment);
glLinkProgram(program);
glValidateProgram(program);
return program;
} |
d0c3ba26-d430-4365-927d-352d4e773cd3 | 0 | public void setOwner(Owner o){
owner = o;
} |
421f5084-69da-4a0e-b685-4124b011f83d | 3 | public byte[] serialize() {
// 6 bytes for mac
byte[] serialized = new byte[1 + data.length + 13];
serialized[0] = (byte) type.ordinal();
serialized[1] = (byte) ttl;
byte[] mac = getMacAsBytes(this.receiverMac);
for (int i = 2; i <= 7; i++) {
serialized[i] = mac[i - 2];
}
mac = getMacAsBytes(this.senderMac);
for (int i = 8; i <= 13; i++) {
serialized[i] = mac[i - 8];
}
for (int i = 14; i < serialized.length; i++) {
serialized[i] = data[i - 14];
}
return serialized;
} |
d95f97e1-aa2a-4903-a1c6-f0b29bf2f6b8 | 2 | public void setSelected( Selection selection ) {
SelectableCapability capability = getCapability( CapabilityName.SELECTABLE );
if( capability != null ) {
Selection old = capability.getSelected();
if( !old.equals( selection ) ) {
capability.setSelected( selection );
}
}
} |
b4ab8e42-2947-452d-94e9-6998ae86cf9e | 1 | public void show(TreeNode node) {
if (defaultVisible)
visibleNodes.remove(node);
else
visibleNodes.put(node, null);
} |
d1be88c9-5113-44ea-b55b-407dd0aae040 | 3 | synchronized void unlockContext(int x, int z)
{
for (int xx = 0; xx < 3; xx++)
for (int zz = 0; zz < 3; zz++)
{
Chunk c = getChunk(x + xx - 1, z + zz - 1);
if (c != null)
c.opLock.unlock();
}
taskQueue.addAll(lockedTasksQueue);
lockedTasksQueue.clear();
} |
f9190d85-15f6-4770-bd1a-e2ca51e0cd3e | 9 | public static void main(String[] args) {
BoardInterface board = new Board();
BoardViewer boardViewer = new BoardViewer();
board.initializeBoard(3);
boardViewer.setViewedBoard(board);
Score score = new Score();
Output oc = new OutputImpl(new ConsoleDisplay());
Player player1 = new HumanPlayer(new PlayerConsole());
Player player2;
String gameMode = "";
try {
gameMode = initializeGame(oc,"Please choose a game mode\n1. Player vs. Computer\n2. Player vs. Player");
}
catch (IOException e) {
e.printStackTrace();
}
if (gameMode.equals("2")) {
player2 = new HumanPlayer(new PlayerConsole());
}
else {
try {
gameMode = initializeGame(oc,"Please choose a difficulty\n1. Difficult\n2. Easy");
}
catch (IOException e) {
e.printStackTrace();
}
if (gameMode.equals("2")) {
player2 = new AIPlayer(new PlayerConsole());
}
else {
player2 = new DifficultAIPlayer(new PlayerConsole());
//player2.setReferenceBoard(board);
}
}
oc.drawBoard(boardViewer);
//Move move = new Move();
player1.setPersonalSymbol("x");
player2.setPersonalSymbol("o");
oc.writeToScreen("Choose your fate");
score.setTurnCounter(0);
while (true) {
if (score.isTie(boardViewer)) {
break;
}
if (!continueGame(player1, oc, boardViewer, score)) {
oc.writeToScreen("Player 1 has won the game!");
return;
}
if (score.isTie(boardViewer)) {
break;
}
if (!continueGame(player2, oc, boardViewer, score)) {
oc.writeToScreen("Player 2 has won the game!");
return;
}
}
oc.clearScreen();
oc.drawBoard(boardViewer);
oc.writeToScreen("Game is a draw");
} |
d72ec655-1106-41f8-a385-16ff101c56ce | 2 | @Override
public BufferedImage generate() {
BufferedImage completePic = new BufferedImage(xSize, ySize,
BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < xSize; i++) {
for (int j = 0; j < ySize; j++) {
Color newPixel = colGen.getPixel();
completePic.setRGB(i, j, newPixel.getRGB());
}
}
return completePic;
} |
d4672f9e-ca34-4a24-ba9b-0526a3c01194 | 1 | public void newFiles(File file, FilterPanel searchPanel) {
MP3Container temp = showCon;
mainCon.add(file, searchPanel);
if (temp == showCon) {
update();
}
} |
61677cbb-bfaf-444e-b436-bf5cb6145122 | 9 | private void recieveHandshake() throws IOException {
ByteBuffer ch = ByteBuffer.allocate((this.remoteHandshake != null ? this.remoteHandshake.capacity() : 0) + this.buffer.capacity());
if (this.remoteHandshake != null) {
this.remoteHandshake.rewind();
ch.put(this.remoteHandshake);
}
ch.put(this.buffer);
this.remoteHandshake = ch;
// If the ByteBuffer ends with 0x0D 0x0A 0x0D 0x0A
// (or two CRLFs), then the client handshake is complete
byte[] h = this.remoteHandshake.array();
if ((h.length>=4 && h[h.length-4] == CR
&& h[h.length-3] == LF
&& h[h.length-2] == CR
&& h[h.length-1] == LF) ||
(h.length==23 && h[h.length-1] == 0)) {
completeHandshake();
}
} |
425617bc-d051-4f8e-aa5e-3f659e3b4043 | 4 | @Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
if (kirjaudutaankoUlos(request)) {
kirjauduUlos(request, response);
} else if (onkoKirjautunut(request, response)) {
try {
List<Kayttaja> asiakkaat = Kayttaja.getKayttajat(3);
request.setAttribute("asiakkaat", asiakkaat);
} catch (Exception e) {
naytaVirheSivu("Asiakkaiden hakeminen tietokannasta epäonnistui.", request, response);
}
if (napinPainallus("potilaanTiedot", request)) {
HttpSession session = request.getSession();
String asiakasId = request.getParameter("asiakasId");
session.setAttribute("asiakasId", asiakasId);
response.sendRedirect("potilaantiedot");
} else {
avaaSivunakyma(request, response, "tyotehtavat", "laakarinviikkoaikataulu", "potilaat", "web/potilaat.jsp");
}
}
} |
bd0d00db-d758-464c-a96b-d37214a42b55 | 6 | public static void main(String[] args) {
BufferedReader reader;
File file = new File("D:/www/tmp/10.183.131.236-20150309-php_2701sell.log");
String root = "d:/www/tmp/";
Map<String, FileWriter> fileWriteMap = new HashMap();
String[] typeArray = new String[]{"tid"};//$act, $value, $value2 , $tid (map_id), $item
try {
reader = new BufferedReader(new FileReader(file));
String partter;
FileWriter currentWriter;
while ((partter = reader.readLine()) != null) {
//act,value,value2,tid,item
Map<String, String> info = formatMsg(partter);
// System.out.println(info.get("msg"));
for (String type : typeArray) {
String fileName = generateFileName(info, root, type);
if (fileWriteMap.containsKey(fileName)) {
currentWriter = fileWriteMap.get(fileName);
} else {
File tmpFile = new File(fileName);
if (!tmpFile.exists()) {
tmpFile.getParentFile().mkdirs();//先创建父文件夹 然后在创建文件 要不然会抛异常
tmpFile.createNewFile();
}
currentWriter = new FileWriter(tmpFile, true);
fileWriteMap.put(fileName, currentWriter);
}
currentWriter.write(info.get("msg") + "\r\n");
}
}
} catch (IOException ex) {
Logger.getLogger(FileLogFormat.class.getName()).log(Level.SEVERE, null, ex);
} finally {
fileWriteMap.entrySet().stream().forEach((entry) -> {
try {
entry.getValue().close();
} catch (IOException ex) {
Logger.getLogger(FileLogFormat.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
} |
f1219ed5-9459-4290-b0d0-ce618899c31e | 8 | @Override
public void shade(Color outIntensity, Scene scene, Ray ray, IntersectionRecord record, int depth) {
// TODO: fill in this function.
// You may find it helpful to create helper methods if the code here gets too long.
Vector3 outgoing = new Vector3(ray.direction);
outgoing.scale(-1);
outgoing.normalize();
Vector3 incident = new Vector3(outgoing);
incident.scale(-1);
incident.normalize();
record.normal.normalize();
Ray reflected;
Ray refracted;
double nAir = 1.00;
double nGlass = refractiveIndex;
double theta1 = Math.acos(outgoing.dot(record.normal));
double theta2 = Math.asin((nAir/nGlass)*Math.sin(theta1));
Vector3 newDirection = new Vector3(incident);
Vector3 temp = new Vector3(record.normal);
temp.scale(2*incident.dot(record.normal));
newDirection.sub(temp);
newDirection.normalize();
Vector3 d = new Vector3(newDirection);
d.scale(-1);
d.normalize();
Color reflectedColor = new Color();
Color refractedColor = new Color();
if (outgoing.dot(record.normal) > 0){ //air to glass
//Schlick's Approximation
double R0 = Math.pow((nGlass-nAir)/(nGlass+nAir),2);
double R = R0 + (1-R0)*(Math.pow(1-Math.cos(theta1), 5));
double number = 1 - (Math.pow(nAir, 2)*(1-Math.pow(newDirection.dot(record.normal), 2))/Math.pow(nGlass, 2));
reflected = new Ray(record.location, newDirection);
reflected.makeOffsetRay();
IntersectionRecord iRefl = new IntersectionRecord();
if (number<0) {
RayTracer.shadeRay(reflectedColor, scene, reflected, depth+1);
} else {
RayTracer.shadeRay(reflectedColor, scene, reflected, depth+1);
scene.getFirstIntersection(iRefl, reflected);
if (iRefl.surface != null){
reflected.setAbsorption(iRefl.surface.getOutsideAbsorption());
reflected.attenuate(reflectedColor, iRefl.location);
}
reflectedColor.scale(R);
outIntensity.add(reflectedColor);
Vector3 rDirection = new Vector3(newDirection);
rDirection.scale(nAir/nGlass);
rDirection.scaleAdd(-1*(nAir/nGlass)*newDirection.dot(record.normal), record.normal);
rDirection.scaleAdd(-1*Math.sqrt(number),record.normal);
rDirection.normalize();
refracted = new Ray(record.location, rDirection);
refracted.makeOffsetRay();
IntersectionRecord iRefr = new IntersectionRecord();
RayTracer.shadeRay(refractedColor, scene, refracted, depth+1);
scene.getFirstIntersection(iRefr, refracted);
if (iRefr.surface != null){
refracted.setAbsorption(iRefr.surface.getInsideAbsorption());
refracted.attenuate(refractedColor, iRefr.location);
}
refractedColor.scale(1-R);
outIntensity.add(refractedColor);
}
} else if (outgoing.dot(record.normal) < 0){ //glass to air
Vector3 negNorm = new Vector3(record.normal);
negNorm.scale(-1);
//Schlick's Approximation
double R0 = Math.pow((nAir-nGlass)/(nGlass+nAir),2);
double R = R0 + (1-R0)*(Math.pow(1-Math.cos(theta2), 5));
double number = 1 - (Math.pow(nGlass, 2)*(1-Math.pow(newDirection.dot(negNorm), 2))/Math.pow(nAir, 2));
reflected = new Ray(record.location, newDirection);
reflected.makeOffsetRay();
IntersectionRecord iRefl = new IntersectionRecord();
if (number<0) {
RayTracer.shadeRay(reflectedColor, scene, reflected, depth+1);
} else {
RayTracer.shadeRay(reflectedColor, scene, reflected, depth+1);
scene.getFirstIntersection(iRefl, reflected);
if (iRefl.surface != null){
reflected.setAbsorption(iRefl.surface.getInsideAbsorption());
reflected.attenuate(reflectedColor, iRefl.location);
}
reflectedColor.scale(R);
outIntensity.add(reflectedColor);
Vector3 rDirection = new Vector3(newDirection);
rDirection.scale(nGlass/nAir);
rDirection.scaleAdd(-1*(nGlass/nAir)*newDirection.dot(negNorm), negNorm);
rDirection.scaleAdd(-1*Math.sqrt(number),negNorm);
rDirection.normalize();
refracted = new Ray(record.location, rDirection);
refracted.makeOffsetRay();
IntersectionRecord iRefr = new IntersectionRecord();
RayTracer.shadeRay(refractedColor, scene, refracted, depth+1);
scene.getFirstIntersection(iRefr, refracted);
if (iRefr.surface != null){
refracted.setAbsorption(iRefr.surface.getOutsideAbsorption());
refracted.attenuate(refractedColor, iRefr.location);
}
refractedColor.scale(1-R);
outIntensity.add(refractedColor);
}
}
} |
423dafe8-8331-4a10-9701-4ab2159b693c | 9 | public void processFire(Bullet bullet) throws Exception {
this.bullet = bullet;
int step = 1;
while ((bullet.getX() > -14 && bullet.getX() < 590) && (bullet.getY() > -14 && bullet.getY() < 590)) {
if (bullet.getDirection() == Direction.UP) {
bullet.updateY(-step);
} else if (bullet.getDirection() == Direction.DOWN) {
bullet.updateY(step);
} else if (bullet.getDirection() == Direction.LEFT) {
bullet.updateX(-step);
} else if (bullet.getDirection() == Direction.RIGHT) {
bullet.updateX(step);
}
if (processInterseption()) {
bullet.destroy();
}
repaint();
Thread.sleep(bullet.getSpeed());
}
} |
30f7724b-f160-48e8-93eb-ddf51a4f40a1 | 5 | public boolean checkNeighbors(mxGraph graph, Object edge, Object source,
Object target)
{
mxIGraphModel model = graph.getModel();
Object sourceValue = model.getValue(source);
Object targetValue = model.getValue(target);
boolean isValid = !validNeighborsAllowed;
Iterator<String> it = validNeighbors.iterator();
while (it.hasNext())
{
String tmp = it.next();
if (this.source && checkType(graph, targetValue, tmp))
{
isValid = validNeighborsAllowed;
break;
}
else if (!this.source && checkType(graph, sourceValue, tmp))
{
isValid = validNeighborsAllowed;
break;
}
}
return isValid;
} |
c34ef886-7dfb-46bd-b7e3-edfacee26d1a | 6 | public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {// parcour par colonne
case 0://colonne id_Stock
return medicaments.get(rowIndex).getId_mdc();
case 1://colonne id_Stock
return medicaments.get(rowIndex).getRef();
case 2://colonne type_vetement
return medicaments.get(rowIndex).getLibelle();
case 3://colonne g
return medicaments.get(rowIndex).getType();
case 4://colonne adresse depot
return medicaments.get(rowIndex).getPrix();
case 5://colonne adresse depot
return medicaments.get(rowIndex).getId_ph();
default:
return null;
}
} |
d9aca9ae-cb3f-4bfd-8701-eba91d0a3fb7 | 3 | public boolean removeClientConnected(ServerHandleConnect serverHandleConnect) {
for (int i = 0; i < this.serverHandleConnectList.size(); i++) {
if (serverHandleConnectList.get(i) == serverHandleConnect) {
serverHandleConnectList.remove(i);
this.curconnected--;
}
}
if (this.curconnected <= 0) {
return true;
} else {
return false;
}
} |
39ce1aac-c092-4e00-b293-87997107dd67 | 8 | private char[] generatePasswd(char []inputval) throws IOException {
char[] lineBuffer;
char[] buf;
int i;
buf = lineBuffer = new char[128];
int room = buf.length;
int offset = 0;
int c;
int index = 0;
int lenofinputval = inputval.length;
System.out.println("Debug:inputval: " + inputval);
System.out.println("Debug:lenofinputval: " + lenofinputval);
loop:
//while (true) {
while (index < lenofinputval) {
//switch (c = in.read()) {
switch (c = inputval[index] ) {
case -1:
case '\n':
System.out.println("Debug::Iam in NewLine or -1");
break loop;
case '\r':
System.out.println("Debug::Iam in Carriage Return");
index ++;
int c2 = inputval[index];
if ((c2 != '\n') && (c2 != -1)) {
/*
if (!(in instanceof PushbackInputStream)) {
in = new PushbackInputStream(in);
}
((PushbackInputStream)in).unread(c2);
*/
index --;
System.out.println("Debug::Iam in Carriage Return IF Block");
} else
break loop;
default:
if (--room < 0) {
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
Arrays.fill(lineBuffer, ' ');
lineBuffer = buf;
}
buf[offset++] = (char) c;
break;
}//switch
index ++;
}//While
if (offset == 0) {
return null;
}
char[] ret = new char[offset];
System.arraycopy(buf, 0, ret, 0, offset);
Arrays.fill(buf, ' ');
System.out.println("$$$$$$$$$$::::...... Password Generated: " + ret);
return ret;
} |
4e358f4f-862c-4ced-b967-5979473857d7 | 6 | @Test
public void testLexer()
{
Random rand = new Random();
List<TokenType> types = new ArrayList<TokenType>();
StringBuilder sb = new StringBuilder();
final int max = TokenType.values().length;
for(int i = 0; i < 10000; i++)
{
TokenType type = TokenType.values()[rand.nextInt(max)];
types.add(type);
if(type == TokenType.IDENT)
{
sb.append("swag213");
}
else if(type == TokenType.NUMBER)
{
sb.append("420");
}
else if(type == TokenType.STRING)
{
sb.append("\"swaglol35\"");
}
else
{
sb.append(type.identifier);
}
sb.append(" ");
sb.append(TokenType.RBRACE);
sb.append(" } ");
}
Lexer lexer = Lexer.newInstance();
lexer.reset(sb.toString());
List<Token> tokens = lexer.tokenize();
for(int i = 0; i < tokens.size(); i++)
{
if(tokens.get(i).type != types.get(i))
fail(tokens.get(i).type + " " + types.get(i));
}
} |
14c24648-e7d0-421a-8635-9ee65b83d5b8 | 0 | public String getDate() {
return date;
} |
91cee135-301a-471e-9685-81ee174ef34b | 5 | private static void loadEventsFromFile() throws FileNotFoundException, IOException {
File eventsTxt = new File("events.txt");
if(!eventsTxt.exists()){
eventsTxt.createNewFile();
}
try(BufferedReader br = new BufferedReader(new FileReader("events.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
String[] objects = line.split(",");
for(int x = 0; x < 4; x++){
}
int monthIndex = 0;
int dayIndex = 0;
if(objects[1].equalsIgnoreCase("sept")){
monthIndex = 0;
} else if(objects[1].equalsIgnoreCase("oct")){
monthIndex = 1;
} else {
monthIndex = 2;
}
dayIndex = Integer.parseInt(objects[0]);
months.get(monthIndex).getDays().get(dayIndex).addEvent(new Event(objects[2], objects[3]));
line = br.readLine();
}
}
} |
a2330b26-8a6a-40f5-8f46-18c4f843d9d3 | 6 | public boolean stop() {
if (!(started)) {
return false;
}
started = false;
plugin.getBroadcaster().alertEveryone(this, "The game is over!");
if (taskId != -1) {
plugin.getServer().getScheduler().cancelTask(taskId);
taskId = -1;
}
for (String player : deadPlayers) {
Player p = plugin.getServer().getPlayer(player);
if (p == null) {
continue;
}
p.setAllowFlight(false);
for (Player ply : plugin.getServer().getOnlinePlayers()) {
p.showPlayer(ply);
}
}
for (String player : getAllPlayers()) {
removePlayer(player);
}
return true;
} |
1b817be6-b677-4eec-8c24-5fab67a8ce93 | 7 | private void populateData() {
String sharedDir = Configuration.getConfig(Configuration.CONFIG_SHARED_FILESYSTEM_PATH);
String cluster = Configuration.getConfig(Configuration.CONFIG_SGE_CLUSTER);
String location = Configuration.getConfig(Configuration.CONFIG_SGE_ROOT);
String spoolDir = Configuration.getConfig(Configuration.CONFIG_SGE_SPOOL_DIR);
String hosts = Configuration.getConfig(Configuration.CONFIG_SGE_EXEC_HOSTS);
String admin = Configuration.getConfig(Configuration.CONFIG_SGE_ADMIN_USER);
if (cluster == null) {
cluster = "cluster";
}
if (location == null) {
location = sharedDir + "sge";
}
if (spoolDir == null) {
spoolDir = location + File.separator + "spool";
}
if (hosts == null) {
hosts = "";
} else {
hosts = hosts.replaceAll(",", "\n");
}
if ( admin != null ) {
sgeAdminLabel.setVisible(true);
sgeAdminField.setVisible(true);
sgeAdminField.setText(admin);
sgeAdminCheckbox.setSelected(true);
} else {
sgeAdminLabel.setVisible(false);
sgeAdminField.setVisible(false);
sgeAdminField.setText("");
sgeAdminCheckbox.setSelected(false);
}
sgeClusterField.setText(cluster);
sgeLocationField.setText(location);
sgeSpoolDirField.setText(spoolDir);
sgeExecHostsArea.setText(hosts);
int index = hostname.indexOf(".");
if ( index != -1 ) {
String domainName = hostname.substring(index);
StringBuilder exampleBuilder = new StringBuilder();
for ( int i = 1; i <= 3; i++ ) {
exampleBuilder.append(" host-");
exampleBuilder.append(i);
exampleBuilder.append(domainName);
exampleBuilder.append("\n");
}
sgeExecHostsExampleArea.setText(exampleBuilder.toString());
} else {
sgeExecHostsExampleArea.setText(" cluster-1.loni.ucla.edu\n cluster-2.loni.ucla.edu\n cluster-n.loni.ucla.edu");
}
} |
aa532961-ce55-48a3-9460-974382a939a4 | 2 | public final void reserve(int count) throws VerifyException {
if (stackHeight + count > maxHeight) {
maxHeight = stackHeight + count;
if (maxHeight > stack.length)
throw new VerifyException("stack overflow");
}
} |
61efa919-1d48-4cb6-b9be-c204330e6a83 | 8 | public void drawPalette(int spanInPixels, TerrainTypes terrain, Vector<Boolean> desiredFeatures) {
String[] features = {"Bonus","Road","Railroad","Irrigation","Village","City"};
String[] abbr = {"+", "", "", "i", "V", "1"};
features[0] = terrain.getBonusDescription();
boolean[] valid = {true, true, true, terrain.isIrrigable(),
terrain.isLand(), terrain.isLand()};
int numCells = features.length;
int internalMarginInPixels = (spanInPixels - numCells * 2 * hexSideInPixels) / (numCells - 1);
for (int i = 0; i < desiredFeatures.size(); i++) {
if (desiredFeatures.get(i)) {
Polygon highlight = new Polygon();
int xLeft = 3;
int xRight = xLeft + margins.width + 7;
int yAtTopPointOfHex = getTopMargin() + i * (internalMarginInPixels + 2 * hexSideInPixels);
int yTop = yAtTopPointOfHex - internalMarginInPixels / 2;
int yBottom = yTop + internalMarginInPixels + 2 * hexSideInPixels;
if (i == 0) {
yTop = 3;
}
if (i == desiredFeatures.size() - 1) {
yBottom = spanInPixels + 11;
}
highlight.addPoint(xLeft, yTop);
highlight.addPoint(xRight, yTop);
highlight.addPoint(xRight, yBottom);
highlight.addPoint(xLeft, yBottom);
Color highlightColor = new Color(255, 255, 153);
fillPolygon(highlight, highlightColor);
}
}
for (int i = 0; i < numCells; i++) {
if (valid[i]) {
String feature = features[i];
int xAtLeftEdgeOfHex = getLeftMargin();
int yAtTopPointOfHex = getTopMargin() + i * (internalMarginInPixels + 2 * hexSideInPixels);
Polygon hex = getHex(xAtLeftEdgeOfHex, yAtTopPointOfHex);
Color color = terrain.getColor();
fillPolygon(hex, color);
if (i == 1) {
Point center = new Point(xAtLeftEdgeOfHex + hexWidthInPixels / 2,
yAtTopPointOfHex + hexSideInPixels);
drawSampleRoad(center);
} else if (i == 2) {
Point center = new Point(xAtLeftEdgeOfHex + hexWidthInPixels / 2,
yAtTopPointOfHex + hexSideInPixels);
drawSampleRailroad(center);
}
int abbrWidth = getWidthInPixels(abbr[i]);
int x1 = xAtLeftEdgeOfHex + (hexWidthInPixels - abbrWidth) / 2;
int x2 = xAtLeftEdgeOfHex + hexWidthInPixels + 5;
int y = yAtTopPointOfHex + (hexSideInPixels * 3 / 2) - getHeightInPixels(feature) / 3;
textDisplayer.beginUsing(comp2D, x1, y, 12);
textDisplayer.typeLine(abbr[i]);
textDisplayer.finishUsing();
textDisplayer.beginUsing(comp2D, x2, y, 12);
textDisplayer.typeLine(feature);
textDisplayer.finishUsing();
}
}
} |
8b27f0d3-4f8a-4779-b2cb-2a13374099c9 | 5 | public static List<Class<?>> getAllInterfacesIncludingSuper(Class<?> c)
{
ArrayList<Class<?>> res = new ArrayList<Class<?>>();
while (c != null)
{
res.addAll(getAllInterfaces(c));
c = c.getSuperclass();
}
return res;
} |
d022b014-99b9-49a0-a33a-a8fc22ab9974 | 4 | public void setState(ShotType shotType)
{
type = shotType;
switch(type)
{
case PISTOL:
body.setMass(1.5d);
body.setVelocity(new Vector3d(0.0d, 0.0d, 20.0d));
body.setAcceleration(new Vector3d(0.0d, -0.5d, 0.0d));
body.setDamping(0.99d, 0.8d);
radius = 0.2d;
break;
case ARTILLERY:
body.setMass(200.0d);
body.setVelocity(new Vector3d(0.0d, 30.0d, 40.0d));
body.setAcceleration(new Vector3d(0.0d, -21.0d, 0.0d));
body.setDamping(0.99d, 0.8d);
radius = 0.4d;
break;
case FIREBALL:
body.setMass(4.0d);
body.setVelocity(new Vector3d(0.0d, -0.5d, 10.0d));
body.setAcceleration(new Vector3d(0.0d, 0.3d, 0.0d));
body.setDamping(0.9d, 0.8d);
radius = 0.6d;
break;
case LASER:
body.setMass(0.1d);
body.setVelocity(new Vector3d(0.0d, 0.0d, 100.0d));
body.setAcceleration(new Vector3d(0.0d, 0.0d, 0.0d));
body.setDamping(0.99d, 0.8d);
radius = 0.2d;
break;
}
body.setCanSleep(false);
body.setAwake(true);
Matrix3d tensor = new Matrix3d();
double coeff = 0.4d*body.getMass()*radius*radius;
tensor.SetInertiaTensorCoeffs(coeff, coeff, coeff);
body.setInertiaTensor(tensor);
body.setPosition(new Vector3d(0.0d, 1.5d, 0.0d));
//startTime =
body.CalculateDerivedData();
calculateInternals();
} |
19a382ee-e5ce-4861-941d-d09027b2e425 | 1 | private static ArrayList<int[]> rleToList(RunLengthEncoding rle) {
ArrayList<int[]> runs = new ArrayList<int[]>();
for (RunIterator it = rle.iterator(); it.hasNext();)
runs.add(it.next());
return runs;
} |
752da015-336f-42d7-baee-e8273c207e2d | 0 | public SchlangenGlied getPreviousGlied() {
return previousGlied;
} |
764351b6-f7b3-4c5b-82c8-cee24d498478 | 7 | public boolean nonIPnonMonsterWithMe(MOB me)
{
if((me.location()!=null)&&(me.session()!=null))
{
final Room R=me.location();
for(int i=0;i<R.numInhabitants();i++)
{
final MOB M=R.fetchInhabitant(i);
if((M==null)||(M==me))
continue;
if((M.session()!=null)&&(M.session().getAddress().equals(me.session().getAddress())))
return true;
}
}
return false;
} |
314c9b09-3b9b-4b7a-ab8c-d73ff4bd2b66 | 5 | @Override
public void render(Graphics g) {
for(int y = 0; y < tiles[0].length; y++)
for(int x = 0; x < tiles.length; x++)
perspective.render(g, tiles[x][y]);
for(int y = 0; y < tiles[0].length; y++)
for(int x = 0; x < tiles.length; x++)
for(Entity entity : tiles[x][y].getEntities())
perspective.render(g, entity);
} |
dff023f5-0454-4cb4-ab60-e14fd484ff75 | 0 | public JButton getjButtonPrevious() {
return jButtonPrevious;
} |
388e9043-0823-4c4e-a786-6ff9b98ae901 | 0 | @Override
public boolean isManagingFocus() {return true;} |
0a44c461-aa95-4c40-ba6d-85a2564eaa84 | 8 | private void profileListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_profileListMouseClicked
// Handles right clicks and double clicks on the Profile List
if(evt.getClickCount() == 2){
try {
if(evt.getX() <= 16){
// Clicked on the icon
if(dbIconActivates)
activateProfile();
else
launchGame();
} else {
// Clicked on the text
if(dbTextAction == 2){
launchGame();
} else if(dbTextAction == 1){
activateProfile();
} else {
// Rename the profile
showRenamePopup();
}
}
} catch(Exception ex){
// Log the error and inform the user
Main.handleException(null, ex, Main.LOG_LEVEL);
infoTxt.setText("An error has occured.");
}
} else if(javax.swing.SwingUtilities.isRightMouseButton(evt)){
// Set the selected index to the item being righ clicked on
profileList.setSelectedIndex(
profileList.locationToIndex(evt.getPoint()));
// Show the right click menu (Only when something is selected).
if( !profileList.isSelectionEmpty() )
profilePopupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
}
}//GEN-LAST:event_profileListMouseClicked |
c5e8f205-b84e-4ff7-a9f5-fb0cb4334065 | 6 | public void mouseMoved(MouseEvent e)
{
if (!gameWon && board.getWhoseTurn() == 2)
{
mouseX = e.getX();
mouseY = e.getY();
if (mouseX > grid.getGridX() + grid.getDiameter()/2 && mouseX < grid.getGridX() + grid.getGridWidth() - grid.getDiameter()/2
&& mouseY > grid.getGridY() && mouseY < grid.getGridY() + grid.getGridHeight() )
{
repaint();
}
}
} |
19dbb4ff-2ec7-4ca0-9ff8-aec30927ccb6 | 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(AddAssignment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddAssignment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddAssignment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddAssignment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new AddAssignment().setVisible(true);
}
});
} |
ea871754-3732-4581-9645-1093561867c5 | 4 | private byte[] get_img_stream(File dot, String type)
{
File img;
byte[] img_stream = null;
try {
img = File.createTempFile("graph_", "."+type, new File(GraphViz.TEMP_DIR));
Runtime rt = Runtime.getRuntime();
// patch by Mike Chenault
String[] args = {DOT, "-T"+type, dot.getAbsolutePath(), "-o", img.getAbsolutePath()};
Process p = rt.exec(args);
p.waitFor();
FileInputStream in = new FileInputStream(img.getAbsolutePath());
img_stream = new byte[in.available()];
in.read(img_stream);
// Close it if we need to
if( in != null ) in.close();
if (img.delete() == false)
System.err.println("Warning: " + img.getAbsolutePath() + " could not be deleted!");
}
catch (java.io.IOException ioe) {
System.err.println("Error: in I/O processing of tempfile in dir " + GraphViz.TEMP_DIR+"\n");
System.err.println(" or in calling external command");
ioe.printStackTrace();
}
catch (java.lang.InterruptedException ie) {
System.err.println("Error: the execution of the external program was interrupted");
ie.printStackTrace();
}
return img_stream;
} |
3977afd1-fec0-439c-87bc-80273f388851 | 8 | public void installEditPolicy(Object key, EditPolicy editPolicy) {
Assert.isNotNull(key, "Edit Policies must be installed with keys");//$NON-NLS-1$
if (policies == null) {
policies = new Object[2];
policies[0] = key;
policies[1] = editPolicy;
} else {
int index = 0;
while (index < policies.length && !key.equals(policies[index]))
index += 2;
if (index < policies.length) {
index++;
EditPolicy old = (EditPolicy) policies[index];
if (old != null && isActive())
old.deactivate();
policies[index] = editPolicy;
} else {
Object newPolicies[] = new Object[policies.length + 2];
System.arraycopy(policies, 0, newPolicies, 0, policies.length);
policies = newPolicies;
policies[index] = key;
policies[index + 1] = editPolicy;
}
}
if (editPolicy != null) {
editPolicy.setHost(this);
if (isActive())
editPolicy.activate();
}
} |
b6fada41-031f-4972-9df8-1623786db784 | 2 | private Class getCommandClass(HttpServletRequest request) {
final String CLASS_PATH = "com.study.vital.webApp.commands.";
Class result;
final String commandClassName;
if(request.getParameter(Attributes.COMMAND)==null){
commandClassName = CLASS_PATH;
} else {
commandClassName = CLASS_PATH + request.getParameter(Attributes.COMMAND) + "Command";
}
try {
result = Class.forName(commandClassName);
} catch (Exception e) {
result = IndexCommand.class;
}
return result;
} |
226246a9-77d4-44aa-8989-63a86f4cf077 | 3 | @Override
public void updateLong() {
super.updateLong();
if(generationTimerEnd == 0) {
resetGenerationTimer();
}
if(generationTimerEnd <= System.currentTimeMillis() && this.isActivated()) {
placeableManager.playerAddItem("Platinum", 1);
registry.getIndicatorManager().createImageIndicator(mapX + (width / 2), mapY + height + 32, "Platinum");
registry.showMessage("Success", type + " has generated Platinum");
resetGenerationTimer();
}
} |
57d9e1e2-e69a-44ee-b04b-065f8449a752 | 5 | private void attemptLogin(){
name = tfUsername.getText();
password = new String(pfPassword.getPassword());
if(name.isEmpty()||password.isEmpty()){
tfUsername.setText("");
lblLoginError.setText("Incorrect Login Credentials");
}
else{
ip = tfServerIp.getText();
int connected = controller.connectServer(ip,name,password);
if(connected==0){
window.launchChatWindow();
}
else if(connected==1){
tfUsername.setText("");
lblLoginError.setText("Wrong username or password");
}
else if(connected==2){
tfUsername.setText("");
lblLoginError.setText("This user has logged in already");
}
else{
tfServerIp.setText("");
lblLoginError.setText("Server unavailable on this IP address");
}
}
} |
ef3f68e9-bcb1-4ec5-b829-ea6552d5a5e3 | 5 | private void registerActionListeners() {
view.btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean written = false;
Object[] options = { "Yes", "No" };
int result = JOptionPane.showOptionDialog(null, "Would you like to save your level?", "Save", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
if (result == JOptionPane.YES_OPTION) {
writeToFile(view.levelname.getText());
written = true;
}
if (written) {
result = JOptionPane.showOptionDialog(null, "Would you like to start a new game in your level?", "New Game", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
if (result == JOptionPane.YES_OPTION) {
try {
view.dispose();
new Game("src/Maps/" + view.levelname.getText() + ".txt");
} catch (Exception exc) {
exc.printStackTrace();
}
} else {
System.exit(0);
}
}
}
});
view.btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = { "Yes", "No" };
int result = JOptionPane.showOptionDialog(null, "Would you really like to cancel?", "Cancel", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
} |
3726faa6-5f96-4e95-8b54-0170420d9443 | 8 | private void deleteCase5(RBTreeNode<K,V> node) {
if (node == node.parent.left &&
nodeColor(node.sibling()) == Color.BLACK &&
nodeColor(node.sibling().left) == Color.RED &&
nodeColor(node.sibling().right) == Color.BLACK) {
node.sibling().color = Color.RED;
node.sibling().left.color = Color.BLACK;
rotateRight(node.sibling());
} else if (node == node.parent.right &&
nodeColor(node.sibling()) == Color.BLACK &&
nodeColor(node.sibling().right) == Color.RED &&
nodeColor(node.sibling().left) == Color.BLACK) {
node.sibling().color = Color.RED;
node.sibling().right.color = Color.BLACK;
rotateLeft(node.sibling());
}
deleteCase6(node);
} |
38d24879-16dc-4995-b736-74171de45502 | 9 | private void processNodeTag(Attributes attributes) {
byte[] node = null;
long lastTS = 0;
short lastClockSeq = 0;
for (int i = 0; i < attributes.getLength(); i++) {
String attributeName = attributes.getLocalName(i);
if ("".equals(attributeName)) {
attributeName = attributes.getQName(i);
}
String attributeValue = attributes.getValue(i);
if (attributeName.equalsIgnoreCase(ATTR_ID_STR)) {
node = StateHelper.decodeMACAddress(attributeValue);
} else if (attributeName.equalsIgnoreCase(ATTR_CLOCKSEQ_STR)) {
try {
lastClockSeq = Short.parseShort(attributeValue);
} catch (NumberFormatException nfe) {
lastClockSeq = 0;
}
} else if ( attributeName.equalsIgnoreCase(ATTR_LASTIMESTAMP_STR)) {
try {
lastTS = Long.parseLong(attributeValue);
} catch (NumberFormatException nfe) {
lastTS = 0;
}
}
}
if (node != null) {
if (lastClockSeq != 0) {
nodes.add(new Node(node, lastTS, lastClockSeq));
} else {
nodes.add(new Node(node));
}
}
} |
6a6df21d-eaa5-47cc-9686-68a880e6e6e1 | 3 | public SynchronizedLyric(String text, int timeStamp)
{
if (text == null || text.trim().length() == 0)
throw new IllegalArgumentException("The text field in a synchronized lyric, " + text + ", in the " + FrameType.SYNCHRONIZED_LYRIC_TEXT.getId() + " frame may not be empty.");
if (timeStamp < 0)
throw new IllegalArgumentException("The time stamp field in a synchronized lyric, " + text + ", in the " + FrameType.SYNCHRONIZED_LYRIC_TEXT.getId() + " frame contains an invalid value, " + timeStamp + ". It must be >= 0.");
this.text = text;
this.timeStamp = timeStamp;
} |
49aa5607-b79b-4e95-aaf2-0f9c1862b810 | 7 | public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String input= userNameField.getText();
if (OK.equals(cmd) && !input.trim().equals("")) {
if (checkAccount(input)==true) { //if account exists
controllingFrame.setVisible(false);
globalAccount=input.toUpperCase();
MyLibraryManager_User user= new MyLibraryManager_User(); //initiates the main user database interface
resetFocus();
JOptionPane.showMessageDialog(controllingFrame, //output welcome message
"Welcome back, "+input.toUpperCase()+"!");
}
else if (checkAccount(input)==false && input.equalsIgnoreCase("Admin")) { //if logged in as admin
controllingFrame.setVisible(false);
globalAccount=input.toUpperCase();
MyLibraryManager_Administrator admin=new MyLibraryManager_Administrator(); //initiates the main admin database interface
JOptionPane.showMessageDialog(controllingFrame, //output welcome message
"Welcome back, Administrator!");
}
else if (checkAccount(input)==false) { //output message if the user account does not exist
JOptionPane.showMessageDialog(controllingFrame,
"The user name entered does not exist. Please try again.",
"Error Message",
JOptionPane.ERROR_MESSAGE);
userNameField.setText("");
}
}
else if (CREATEACCOUNT.equals(cmd)) { //if user clicks Create Account
MyLibraryManager_CreateAccount.createAndShowGUI(); //show GUI for create account window
}
else {
JOptionPane.showMessageDialog(controllingFrame, //output message if the text field is blank.
"The user name field is blank. Please try again.",
"Error Message",
JOptionPane.ERROR_MESSAGE);
userNameField.setText("");
}
} |
bc64d49a-7d0e-4ef4-89c0-db58506a3d35 | 4 | public static void merge(int[] result, int[] left, int[] right) {
int i1 = 0; // index into left array
int i2 = 0; // index into right array
for (int i = 0; i < result.length; i++) {
if (i2 >= right.length || (i1 < left.length &&
left[i1] <= right[i2])) {
result[i] = left[i1]; // take from left
i1++;
} else {
result[i] = right[i2]; // take from right
i2++;
}
}
} |
85b8b4c2-a398-489a-bf3a-6aad0db55dce | 9 | void addTriangle(int vertexA, int vertexB, int vertexC) {
if (vertexValues != null
&& (Float.isNaN(vertexValues[vertexA]) || Float.isNaN(vertexValues[vertexB]) || Float
.isNaN(vertexValues[vertexC])))
return;
if (Float.isNaN(vertices[vertexA].x) || Float.isNaN(vertices[vertexB].x) || Float.isNaN(vertices[vertexC].x))
return;
if (polygonCount == 0)
polygonIndexes = new int[SEED_COUNT][];
else if (polygonCount == polygonIndexes.length)
polygonIndexes = (int[][]) ArrayUtil.doubleLength(polygonIndexes);
polygonIndexes[polygonCount++] = new int[] { vertexA, vertexB, vertexC };
} |
d06af24d-15c0-4f19-8657-05adb5db1b26 | 0 | @Override
public String toString()
{
return String.format( "or(%s, %s)", this.a, this.b );
} |
10478b73-1ef0-469b-ab1c-eadd4285c530 | 7 | public boolean shellCollideCheck(Shell shell)
{
if (deadTime != 0) return false;
float xD = shell.x - x;
float yD = shell.y - y;
if (xD > -16 && xD < 16)
{
if (yD > -height && yD < shell.height)
{
world.sound.play(Art.samples[Art.SAMPLE_MARIO_KICK], this, 1, 1, 1);
if (world.mario.carried == shell || world.mario.carried == this)
{
world.mario.carried = null;
}
die();
shell.die();
return true;
}
}
return false;
} |
fcce2382-f3fd-41af-9450-076361c68bf2 | 8 | public void generateTerrain(int par1, int par2, byte[] par3ArrayOfByte) {
byte b0 = 4;
byte b1 = 16;
byte b2 = 63;
int k = b0 + 1;
byte b3 = 17;
int l = b0 + 1;
this.biomesForGeneration = this.worldObj.getWorldChunkManager().getBiomesForGeneration(this.biomesForGeneration, par1 * 4 - 2, par2 * 4 - 2, k + 5, l + 5);
this.noiseArray = this.initializeNoiseField(this.noiseArray, par1 * b0, 0, par2 * b0, k, b3, l);
for (int i1 = 0; i1 < b0; ++i1) {
for (int j1 = 0; j1 < b0; ++j1) {
for (int k1 = 0; k1 < b1; ++k1) {
double d0 = 0.125D;
double d1 = this.noiseArray[((i1 + 0) * l + j1 + 0) * b3 + k1 + 0];
double d2 = this.noiseArray[((i1 + 0) * l + j1 + 1) * b3 + k1 + 0];
double d3 = this.noiseArray[((i1 + 1) * l + j1 + 0) * b3 + k1 + 0];
double d4 = this.noiseArray[((i1 + 1) * l + j1 + 1) * b3 + k1 + 0];
double d5 = (this.noiseArray[((i1 + 0) * l + j1 + 0) * b3 + k1 + 1] - d1) * d0;
double d6 = (this.noiseArray[((i1 + 0) * l + j1 + 1) * b3 + k1 + 1] - d2) * d0;
double d7 = (this.noiseArray[((i1 + 1) * l + j1 + 0) * b3 + k1 + 1] - d3) * d0;
double d8 = (this.noiseArray[((i1 + 1) * l + j1 + 1) * b3 + k1 + 1] - d4) * d0;
for (int l1 = 0; l1 < 8; ++l1) {
double d9 = 0.25D;
double d10 = d1;
double d11 = d2;
double d12 = (d3 - d1) * d9;
double d13 = (d4 - d2) * d9;
for (int i2 = 0; i2 < 4; ++i2) {
int j2 = i2 + i1 * 4 << 11 | 0 + j1 * 4 << 7 | k1 * 8 + l1;
short short1 = 128;
j2 -= short1;
double d14 = 0.25D;
double d15 = (d11 - d10) * d14;
double d16 = d10 - d15;
for (int k2 = 0; k2 < 4; ++k2) {
if ((d16 += d15) > 0.0D) {
par3ArrayOfByte[j2 += short1] = (byte) Block.stone.blockID;
} else if (k1 * 8 + l1 < b2) {
par3ArrayOfByte[j2 += short1] = (byte) Block.waterStill.blockID;
} else {
par3ArrayOfByte[j2 += short1] = 0;
}
}
d10 += d12;
d11 += d13;
}
d1 += d5;
d2 += d6;
d3 += d7;
d4 += d8;
}
}
}
}
} |
cb70e920-ddc1-4da6-8f9b-5503b2ec90f5 | 9 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CarsModel carsModel = (CarsModel) o;
if (idCars != carsModel.idCars) return false;
if (makeId != carsModel.makeId) return false;
if (modelId != carsModel.modelId) return false;
if (subModelId != carsModel.subModelId) return false;
if (userId != carsModel.userId) return false;
if (year != carsModel.year) return false;
return true;
} |
555eaed2-8d82-411f-bf2e-88a628e3b687 | 6 | public Vector findPointForWall(double x, double y){
double xRes = -1, yRes = -1,r = 100000;
for (Wall wall:walls){
if (sqrt((x - wall.getX1()) * (x - wall.getX1()) + (y - wall.getY1()) * (y - wall.getY1())) < RADIUS_TO_DETECT_WALL_POINT &&
r > sqrt((x - wall.getX1()) * (x - wall.getX1()) + (y - wall.getY1()) * (y - wall.getY1()))){
r = sqrt((x - wall.getX1()) * (x - wall.getX1()) + (y - wall.getY1()) * (y - wall.getY1()));
xRes = wall.getX1();
yRes = wall.getY1();
}
if (sqrt((x - wall.getX2()) * (x - wall.getX2()) + (y - wall.getY2()) * (y - wall.getY2())) < RADIUS_TO_DETECT_WALL_POINT &&
r > sqrt((x - wall.getX2()) * (x - wall.getX2()) + (y - wall.getY2()) * (y - wall.getY2()))){
xRes = wall.getX2();
yRes = wall.getY2();
}
}
if (xRes != -1){
return new Vector(xRes, yRes);
}
return null;
} |
9969ba6b-cd56-4bd6-932e-e655dfa82b08 | 0 | public IBomber getOwner() {
return owner;
} |
7dce4653-f1e7-4b76-ae2b-c09f60845fb7 | 5 | private long getNext() {
boolean primeFound = false;
if (numPrimesFound == 0) {
primesFound.add(2l);
maxPrimeFound = 2;
numPrimesFound = 1;
maxNumberSearched = 2;
return (long) 2;
}
for (long i = maxNumberSearched+1; !primeFound; i++) {
// test if i is prime
// divide by all primes <= sqrt(i)
// if one divides evenly, then i is composite
// but if we get to sqrt, then i is prime
boolean divisorFound = false;
long stoppingPoint = ((long) Math.sqrt(i)) + 1;
for (int k = 1; primesFound.get(k) < stoppingPoint; k++) {
if (i % primesFound.get(k) == 0) {
divisorFound = true;
break;
}
}
if (!divisorFound) {
numPrimesFound += 1;
primeFound = true;
maxPrimeFound = i;
primesFound.add(i);
}
maxNumberSearched += 1;
}
return primesFound.get(numPrimesFound);
} |
3a4ddb49-a8be-4d93-be3e-35da3d4c3c73 | 1 | public void makePlain() {
if (this.isDisposed()) {
return;
}
isBold = false;
setFont(null);
} |
12d9e9c0-4b00-4804-bdd1-ed8c0a8706a0 | 0 | public SizedStack(int size) {
super();
this.maxSize = size;
} |
a18e133e-d49a-418a-a15d-63b3d26644b1 | 1 | public static void main(String[] args) {
TransferQueue<String> stringTransferQueue = new LinkedTransferQueue<>();
try {
stringTransferQueue.put("Await receipt");
} catch (InterruptedException e) {
e.printStackTrace();
}
TransferQueueExample transferQueue = new TransferQueueExample(stringTransferQueue);
transferQueue.run();
} |
90c4073f-f41d-44af-8f3b-1daa8a3b6bdf | 2 | public static void main( String[] args )
{
int loopLimit = 100;
int count = 0;
while ( count < loopLimit )
{
if ( count % 2 == 0 )// check if the "count" is completely divisible by 2
{
System.out.println( count );
}
count++;// count= count+1
}
} |
6842bfa6-c361-4688-bb9a-95a881672f85 | 9 | public static Cons cppGetMethodDefinitions(Stella_Class renamed_Class, Object [] MV_returnarray) {
{ Cons publicmemberfuncdefs = Stella.NIL;
Cons protectedmemberfuncdefs = Stella.NIL;
{ Slot slot = null;
Cons iter000 = renamed_Class.classLocalSlots.theConsList;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
slot = ((Slot)(iter000.value));
if (Surrogate.subtypeOfMethodSlotP(Stella_Object.safePrimaryType(slot))) {
{ MethodSlot slot000 = ((MethodSlot)(slot));
if ((!slot000.slotMarkedP) &&
(MethodSlot.nativeMethodP(slot000) &&
((!MethodSlot.cppConstructorP(slot000)) &&
(!MethodSlot.cppNativeMethodP(slot000))))) {
if (slot000.slotPublicP) {
publicmemberfuncdefs = Cons.cons(MethodSlot.cppYieldMemberFuncSignatureTree(slot000), publicmemberfuncdefs);
}
else {
protectedmemberfuncdefs = Cons.cons(MethodSlot.cppYieldMemberFuncSignatureTree(slot000), protectedmemberfuncdefs);
}
}
}
}
else {
}
}
}
{ MethodSlot method = null;
Cons iter001 = renamed_Class.classAuxiliaryMethods().theConsList;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
method = ((MethodSlot)(iter001.value));
if (method.slotPublicP) {
publicmemberfuncdefs = Cons.cons(MethodSlot.cppYieldMemberFuncSignatureTree(method), publicmemberfuncdefs);
}
else {
protectedmemberfuncdefs = Cons.cons(MethodSlot.cppYieldMemberFuncSignatureTree(method), protectedmemberfuncdefs);
}
}
}
{ Cons _return_temp = publicmemberfuncdefs.reverse();
MV_returnarray[0] = protectedmemberfuncdefs.reverse();
return (_return_temp);
}
}
} |
2234d6f5-c6be-4217-804d-1390e6ad8d24 | 8 | public void settime (String s)
{
StringParser p = new StringParser(s);
if ( !p.skip("Game")) return;
int g = p.parseint();
if (p.error()) return;
p.skipblanks();
if ( !p.skip("I:")) return;
String w = p.parseword();
p.skipblanks();
if ( !p.skip("(")) return;
int w1 = p.parseint();
int w2 = p.parseint();
int w3 = p.parseint(')');
p.skip(")");
if (p.error()) return;
p.skipblanks();
if ( !p.skip("vs")) return;
String b = p.parseword();
p.skipblanks();
if ( !p.skip("(")) return;
int b1 = p.parseint();
int b2 = p.parseint();
int b3 = p.parseint(')');
if ( !p.skip(")")) return;
BlackName = b;
WhiteName = w;
BlackTime = b2;
BlackMoves = b3;
WhiteTime = w2;
WhiteMoves = w3;
GameNumber = g;
BlackRun = 0;
WhiteRun = 0;
CurrentTime = System.currentTimeMillis();
HaveTime = true;
settitle1();
} |
56dbc6b4-71c0-4590-a559-16c7cb87c3dc | 9 | @Override
public String toString() {
final int maxNumber = m.length * m.length - 1;
final int fieldLength =
Math.max(5, (int)(Math.floor(Math.log10(maxNumber))) + 1);
final StringBuilder sb = new StringBuilder();
final StringBuilder ALL = new StringBuilder(8192);
String smallBar = "+-";
String filler = "| ";
for (int i = 0; i != fieldLength + 1; ++i) {
smallBar += '-';
filler += ' ';
}
for (int i = 0; i != m.length; ++i) {
sb.append(smallBar);
}
sb.append('+')
.append('\n');
final String horizontalBar = sb.toString();
for (int yy = 0; yy != m.length; ++yy) {
ALL.append(horizontalBar);;
for (int xx = 0; xx != m.length; ++xx) {
ALL.append(filler);
}
ALL.append("|\n");
for (int xx = 0; xx != m.length; ++xx) {
int fl;
if (m[yy][xx] == 0) {
fl = 1;
} else {
fl = (int)(Math.floor(Math.log10(m[yy][xx]))) + 1;
}
int tmp = fieldLength - fl;
int after = tmp / 2;
int before = tmp - after;
String skip = "";
String skip2 = "";
for (int i = 0; i != before; ++i) {
skip += ' ';
}
for (int i = 0; i != after; ++i) {
skip2 += ' ';
}
ALL.append("| ")
.append(String.format(skip + "%d" + skip2 + " ", m[yy][xx]));
}
ALL.append("|\n");
for (int xx = 0; xx != m.length; ++xx) {
ALL.append(filler);
}
ALL.append("|\n");
}
ALL.append(horizontalBar);
return ALL.toString();
} |
04a188f8-a5cf-4bd6-ab34-465a95c04347 | 1 | private TrainNumber CreateK600K597() {
TrainNumber rs = new TrainNumber();
rs.setId(UUID.randomUUID());
rs.setName("K600/K597");
Route route = new Route();
route.setId(UUID.randomUUID());
route.setStartDate(new LocalDate(0L));
route.setEndDate(LocalDate.now().plusYears(10));
rs.getRoutes().add(route);
Station[] stations = Arrays.copyOfRange(this._stations, 8, this._stations.length);
for(int i = 0; i <stations.length; i ++)
{
RouteStop stop = new RouteStop();
stop.setId(UUID.randomUUID());
stop.setSequence(i);
stop.setStation(stations[i]);
route.getStops().add(stop);
}
return rs;
} |
db3d3437-61d9-4831-b47c-62b9b9992bcd | 5 | public String toString() {
int reporterGroupSize = -1;
if (reporterGroup != null) {
reporterGroupSize = reporterGroup.size();
}
int blGroupSize = -1;
SampleGroup baselineGroup = getBaselineGroup();
if (baselineGroup!=null) {
blGroupSize = baselineGroup.size();
}
SampleGroup group1 = getGroup1();
int group1Size = -1;
if (group1 !=null) {
group1Size = group1.size();
}
String retStr = "ClassComparisonAnalysisLookupRequest: sessionId=" + getSessionId() + " taskId=" + getTaskId() + " reporterGroupSize=" + reporterGroupSize + " blGroupSize=" + blGroupSize + " group1Szie=" + group1Size;
if (group1 != null) {
retStr += " GRP1=" + group1.getGroupName();
}
if (baselineGroup != null) {
retStr += " baselineGroup=" + baselineGroup.getGroupName();
}
return retStr;
} |
95849ea2-3e2c-4559-9d22-ac8a6830cf98 | 3 | private static void fw_write(String msg, String file)
{
//System.out.print(msg);
FileWriter fwriter = null;
try
{
fwriter = new FileWriter(file, true);
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Unwanted errors while opening file " + file);
}
try
{
fwriter.write(msg);
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Unwanted errors while writing on file " + file);
}
try
{
fwriter.close();
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Unwanted errors while closing file " + file);
}
} |
194844b7-0bc2-4d92-89d2-78c7ce7d9e20 | 6 | FormAttachment setAttachment (String attachment) {
String control, align;
int position, offset;
int comma = attachment.indexOf (',');
char first = attachment.charAt (0);
if (Character.isLetter(first)) {
/* Case where there is a control */
control = attachment.substring (0, comma);
int i = 0;
while (i < control.length () && !Character.isDigit (control.charAt (i))) {
i++;
}
String end = control.substring (i);
int index = new Integer (end).intValue ();
Control attachControl = children [index];
int colon = attachment.indexOf (':');
try {
offset = new Integer (attachment.substring (comma + 1, colon)).intValue ();
} catch (NumberFormatException e) {
offset = 0;
}
align = attachment.substring (colon + 1);
return new FormAttachment (attachControl, offset, alignmentConstant (align));
} else {
/* Case where there is a position */
try {
position = new Integer (attachment.substring (0,comma)).intValue ();
} catch (NumberFormatException e) {
position = 0;
}
try {
offset = new Integer (attachment.substring (comma + 1)).intValue ();
} catch (NumberFormatException e) {
offset = 0;
}
return new FormAttachment (position, offset);
}
} |
9388124f-0d65-45d2-bde4-c7c1d709bae0 | 4 | @Override
public void disablePlugin(Plugin plugin) {
Validate.isTrue(plugin instanceof InjectablePlugin, "Plugin is not associated with this PluginLoader");
if (plugin.isEnabled()) {
String message = String.format("Disabling %s", plugin.getName());
plugin.getLogger().info(message);
Bukkit.getPluginManager().callEvent(new PluginDisableEvent(plugin));
InjectablePlugin iPlugin = (InjectablePlugin) plugin;
ClassLoader cLoader = iPlugin.getClass().getClassLoader();
try {
iPlugin.setEnabled(true);
} catch (Throwable ex) {
Injector.getLogger().log(Level.SEVERE, "Error occurred while disabling " + plugin.getName());
}
loaders.remove(plugin.getName());
if (cLoader instanceof InjectorClassLoader) {
InjectorClassLoader loader = (InjectorClassLoader) cLoader;
Set<String> names = loader.getClasses();
for (String name : names) {
removeClass(name);
}
}
}
} |
efc38b38-6820-41d7-9b64-d64427df4956 | 8 | private void saveLibraryEntry(LibraryEntry libraryEntry, List<SlateObject> filterList, boolean saveChallengeMonster)
{
List<Piece> pieces = new ArrayList<Piece>();
Iterator<Entry<Integer,Map<Long,SlateObject>>> iterator = slateComponent.getObjectMap().entrySet().iterator();
while (iterator.hasNext())
{
Entry<Integer,Map<Long,SlateObject>> entry = iterator.next();
Integer symbolId = entry.getKey();
if (!slateComponent.isTangible(symbolId)) continue;
Map<Long,SlateObject> map = entry.getValue();
Iterator<Entry<Long,SlateObject>> mapIterator = map.entrySet().iterator();
while (mapIterator.hasNext())
{
Entry<Long,SlateObject> mapEntry = mapIterator.next();
SlateObject slateObject = mapEntry.getValue();
if ((filterList != null) &&
slateComponent.isInFilterList(slateObject, filterList)) {
continue;
}
Piece piece = slateComponent.getPiece(slateObject);
pieces.add(piece);
}
}
// save challenge monster
Logger.info(saveChallengeMonster + "," + (challengeMonster != null));
if (saveChallengeMonster && (challengeMonster != null))
{
Piece piece = slateComponent.getPiece(challengeMonster);
pieces.add(piece);
}
if (pieces.size() > 0) {
libraryEntry.setPieces(pieces);
slateComponent.getLibrary().addLibraryEntry(libraryEntry);
}
} |
95cf8dc2-8dd3-4f68-bff5-a7990efd001c | 9 | private static Cell construct(Sequence s1, Sequence s2, float[][] matrix,
float o, float e, byte[] pointers, short[] lengths) {
logger.info("Started...");
char[] a1 = s1.toArray();
char[] a2 = s2.toArray();
int m = s1.length() + 1; // number of rows in similarity matrix
int n = s2.length() + 1; // number of columns in similarity matrix
float[] v = new float[n];
float vDiagonal = 0;// Float.NEGATIVE_INFINITY; // best score in cell
float f = Float.NEGATIVE_INFINITY; // score from diagonal
float h = Float.NEGATIVE_INFINITY; // best score ending with gap from
// left
float[] g = new float[n]; // best score ending with gap from above
// Initialization of v and g
g[0] = Float.NEGATIVE_INFINITY;
for (int j = 1; j < n; j++) {
v[j] = 0;// -o - (j - 1) * e;
g[j] = Float.NEGATIVE_INFINITY;
}
int lengthOfHorizontalGap = 0;
int[] lengthOfVerticalGap = new int[n];
float similarityScore;
float maximumScore = Float.NEGATIVE_INFINITY;
int maxi = 0;
int maxj = 0;
// Fill the matrices
for (int i = 1, k = n; i < m; i++, k += n) { // for all rows
v[0] = -o - (i - 1) * e;
for (int j = 1, l = k + 1; j < n; j++, l++) { // for all columns
similarityScore = matrix[a1[i - 1]][a2[j - 1]];
f = vDiagonal + similarityScore;// from diagonal
// Which cell from the left?
if (h - e >= v[j - 1] - o) {
h -= e;
lengthOfHorizontalGap++;
} else {
h = v[j - 1] - o;
lengthOfHorizontalGap = 1;
}
// Which cell from above?
if (g[j] - e >= v[j] - o) {
g[j] = g[j] - e;
lengthOfVerticalGap[j] = lengthOfVerticalGap[j] + 1;
} else {
g[j] = v[j] - o;
lengthOfVerticalGap[j] = 1;
}
vDiagonal = v[j];
v[j] = maximum(f, g[j], h); // best one
if (v[j] > maximumScore) {
maximumScore = v[j];
maxi = i;
maxj = j;
}
// Determine the traceback direction
if (v[j] == f) {
pointers[l] = Directions.DIAGONAL;
} else if (v[j] == g[j]) {
pointers[l] = Directions.UP;
lengths[l] = (short) lengthOfVerticalGap[j];
} else if (v[j] == h) {
pointers[l] = Directions.LEFT;
lengths[l] = (short) lengthOfHorizontalGap;
}
} // loop columns
// Reset
h = Float.NEGATIVE_INFINITY;
vDiagonal = 0;// -o - (i - 1) * e;
lengthOfHorizontalGap = 0;
} // loop rows
Cell cell = new Cell();
cell.set(maxi, maxj, v[n - 1]);
logger.info("Finished.");
return cell;
} |
85885370-506c-430c-8891-3ec2e5d3940b | 3 | public ByteBuffer getBuffer(){
if(this.currentBufferQueue == null){
this.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>();// 当前正在处理的缓冲区队列
}
if(this.currentByteBuffer == null || this.currentByteBuffer.remaining() <= 0){
this.currentByteBuffer = BufferPool.getInstance().getBuffer();
this.currentBufferQueue.add(this.currentByteBuffer);
}
return this.currentByteBuffer;
} |
d1601f9f-bfd5-46af-84d3-ef553a16b122 | 3 | public List<Integer> determinePrizePool() {
List<Integer> tempList = new ArrayList<Integer>();
int numu = getAllUsers().size();
if (numu <= 0) { // no users
return null;
} else if (numu == 1) {
// one user, he gets the whole pool
tempList.add(getTotalAmount());
} else if (numu == 2) {
// two users, first user gets 65% of the
// winnings, the rest goes to the second
tempList.add((int) (getTotalAmount() * 0.65)); // first 65
tempList.add(getTotalAmount() - tempList.get(0)); // the rest
} else {
// three or more users
// split is 60/30/10
tempList.add((int) (getTotalAmount() * 0.60)); // first 60
// total amount - the first amount, which leaves 40% of the original
// amount
// 30% is now equivalent to 75% of the new amount
tempList.add((int) ((getTotalAmount() - tempList.get(0)) * 0.75));
// the total minus the first and second place winnings
tempList.add(getTotalAmount() - tempList.get(0) - tempList.get(1));
}
return tempList;
} |
a98aa54d-2b76-4ffc-8e33-2dde36b61c60 | 8 | public void visit_dload(final Instruction inst) {
final int index = ((LocalVariable) inst.operand()).index();
if (index + 2 > maxLocals) {
maxLocals = index + 2;
}
if (inst.useSlow()) {
if (index < 256) {
addOpcode(Opcode.opc_dload);
addByte(index);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_dload);
addShort(index);
}
stackHeight += 2;
return;
}
switch (index) {
case 0:
addOpcode(Opcode.opc_dload_0);
break;
case 1:
addOpcode(Opcode.opc_dload_1);
break;
case 2:
addOpcode(Opcode.opc_dload_2);
break;
case 3:
addOpcode(Opcode.opc_dload_3);
break;
default:
if (index < 256) {
addOpcode(Opcode.opc_dload);
addByte(index);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_dload);
addShort(index);
}
break;
}
stackHeight += 2;
} |
fb49dec9-08bf-4e04-a1d5-e6cfb6185181 | 8 | public int removeDuplicates(int[] A) {
int length = A.length;
int i =0;
while (i < length)
{
if (i < length -1 && A[i] == A[i+1])
{
i++;
}
int j = i + 1;
while (j <= length -1 && A[j] == A[j-1])
{
j++;
}
if (j == length)
{
length = i + 1;
break;
}
int deta = j- i-1;
if (deta !=0)
{
length -= deta;
for (int k = i +1 ;k<length;k++)
{
A[k] = A[k+ deta];
}
}
i++;
}
return length;
} |
748f6099-850a-42af-a373-755018b635bb | 8 | private void setupDocumentLayer ( )
{
documentPresentationLayer = new DefaultStyledDocument()
{
private static final long serialVersionUID = 1L;
public void insertString (int offset, String str, AttributeSet a) throws BadLocationException {
super.insertString(offset, str, a);
String text = getText(0, getLength());
int before = Grammer.findLastNonWordChar(text, offset);
if (before < 0) before = 0;
int after = Grammer.findFirstNonWordChar(text, offset + str.length());
int wordL = before, wordR = before;
while (wordR <= after) {
if (wordR == after || String.valueOf(text.charAt(wordR)).matches("\\W"))
{
if (text.substring(wordL, wordR).matches("(\\W)*" + Grammer.computationalUnitsRegEx) && "isf" == fileFormat)
setCharacterAttributes(wordL, wordR - wordL, Grammer.attr, false);
else
setCharacterAttributes(wordL, wordR - wordL, Grammer.attrBlack, false);
wordL = wordR;
}
wordR++;
}
}
public void remove (int offs, int len) throws BadLocationException {
super.remove(offs, len);
String text = getText(0, getLength());
int before = Grammer.findLastNonWordChar(text, offs);
if (before < 0) before = 0;
int after = Grammer.findFirstNonWordChar(text, offs);
if (text.substring(before, after).matches("(\\W)*" + Grammer.computationalUnitsRegEx)) {
setCharacterAttributes(before, after - before, Grammer.attr, false);
} else {
setCharacterAttributes(before, after - before, Grammer.attrBlack, false);
}
}
};
} |
ba883f58-338b-4225-80c5-5c383ca3ff85 | 3 | public ArrayList getAttributeList(Filter filter)
{
// check for errors first
int rcID = getReplicaCatalogueID();
if (filter == null || rcID == -1) {
return null;
}
ArrayList attrList = null;
int eventTag = DataGridTags.CTLG_FILTER;
Object[] packet = new Object[2];
packet[0] = filter;
packet[1] = myID_;
// send an event message
super.send(super.output, 0, eventTag,
new IO_data(packet, DataGridTags.PKT_SIZE, rcID));
// waiting for a response from the RC
Sim_type_p tag = new Sim_type_p(DataGridTags.CTLG_FILTER_DELIVERY);
Sim_event ev = new Sim_event();
super.sim_get_next(tag, ev); // only look for this type of ack
try {
attrList = (ArrayList) ev.get_data();
}
catch (Exception e) {
attrList = null;
System.out.println(super.get_name() +
".getAttributeList(): Exception");
}
return attrList;
} |
a44f9257-7533-4b70-b833-35d3d26f2694 | 3 | public static int pideInt(String texto) {
InputStreamReader flujo=new InputStreamReader(System.in);
BufferedReader teclado=new BufferedReader(flujo);
String cadnum;
int numero=0;
boolean correcto;
do {
try {
correcto=true;
System.out.print(texto);
cadnum=teclado.readLine();
numero=Integer.parseInt(cadnum);
}
catch (NumberFormatException e) {
System.out.println("\t\tTienes que introducir un nº: " + e);
correcto=false;
}
catch (IOException e) {
System.out.println("\t\tSe ha producido un error: " + e);
correcto=false;
}
}while (!correcto);
return numero;
} |
a3e07c26-d93b-4c00-96b4-9adb1580fa7b | 4 | void radb3(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
final double taur=-0.5D;
final double taui=0.866025403784439D;
int i, k, ic;
double ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2;
int iw1, iw2;
iw1 = offset;
iw2 = iw1 + ido;
for(k=0; k<l1; k++)
{
tr2=2*cc[ido-1+(3*k+1)*ido];
cr2=cc[3*k*ido]+taur*tr2;
ch[k*ido]=cc[3*k*ido]+tr2;
ci3=2*taui*cc[(3*k+2)*ido];
ch[(k+l1)*ido]=cr2-ci3;
ch[(k+2*l1)*ido]=cr2+ci3;
}
if(ido==1) return;
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
tr2=cc[i-1+(3*k+2)*ido]+cc[ic-1+(3*k+1)*ido];
cr2=cc[i-1+3*k*ido]+taur*tr2;
ch[i-1+k*ido]=cc[i-1+3*k*ido]+tr2;
ti2=cc[i+(3*k+2)*ido]-cc[ic+(3*k+1)*ido];
ci2=cc[i+3*k*ido]+taur*ti2;
ch[i+k*ido]=cc[i+3*k*ido]+ti2;
cr3=taui*(cc[i-1+(3*k+2)*ido]-cc[ic-1+(3*k+1)*ido]);
ci3=taui*(cc[i+(3*k+2)*ido]+cc[ic+(3*k+1)*ido]);
dr2=cr2-ci3;
dr3=cr2+ci3;
di2=ci2+cr3;
di3=ci2-cr3;
ch[i-1+(k+l1)*ido] = wtable[i-2+iw1]*dr2
-wtable[i-1+iw1]*di2;
ch[i+(k+l1)*ido] = wtable[i-2+iw1]*di2
+wtable[i-1+iw1]*dr2;
ch[i-1+(k+2*l1)*ido] = wtable[i-2+iw2]*dr3
-wtable[i-1+iw2]*di3;
ch[i+(k+2*l1)*ido] = wtable[i-2+iw2]*di3
+wtable[i-1+iw2]*dr3;
}
}
} |
be8ebef9-62ac-43bd-9114-2b6b3516b09f | 0 | public IntegerGenerator(String tableName, String columnName, int start) {
super(tableName, columnName);
this.start = start;
this.current = start;
} |
e676f5b2-d6f6-4de0-a0d6-54a393c4e637 | 5 | @Override
public float millisecondsPlayed()
{
// get number of samples played in current buffer
float offset = (float)AL10.alGetSourcei( ALSource.get( 0 ),
AL11.AL_BYTE_OFFSET );
float bytesPerFrame = 1f;
switch( ALformat )
{
case AL10.AL_FORMAT_MONO8 :
bytesPerFrame = 1f;
break;
case AL10.AL_FORMAT_MONO16 :
bytesPerFrame = 2f;
break;
case AL10.AL_FORMAT_STEREO8 :
bytesPerFrame = 2f;
break;
case AL10.AL_FORMAT_STEREO16 :
bytesPerFrame = 4f;
break;
default :
break;
}
offset = ( ( (float) offset / bytesPerFrame ) / (float) sampleRate )
* 1000;
// add the milliseconds from stream-buffers that played previously
if( channelType == SoundSystemConfig.TYPE_STREAMING )
offset += millisPreviouslyPlayed;
// Return millis played:
return( offset );
} |
2ba50814-fbcf-4ad5-844e-66f5ef668f88 | 6 | private void infect() {
for (int i = 0; i < Integer.parseInt(Config
.getProperty("Grid.Infected")); i++) {
// Position x
int x = (int) (grid.getWidth() * Math.random());
// Position y
int y = (int) (grid.getDepth() * Math.random());
// Infects the subject
if (getSubject(x, y) != null) {
switch (getSubject(x, y).toString()) {
// Human starts healthy
case "Human":
break;
case "Chicken":
getSubject(x, y).setDisease(new H5N1());
break;
case "Duck":
getSubject(x, y).setDisease(new H5N1());
break;
case "Pig":
getSubject(x, y).setDisease(new H1N1());
break;
// Empty space
default:
i--;
break;
}
}
}
} |
8aee5bfe-8911-4e88-b98e-8c038331adef | 9 | public boolean isWalls(){
if(this.heading%(Math.PI/2)!=0) return false;
if((this.x>=17 && this.x<=19) || (this.x>=781 && this.x<=783) || (this.y>=17 && this.y<=19) || (this.y>=581 && this.y<=583) ) return true;
return false;
} |
96dff2b6-454b-4711-9477-fa4b4fbccb4b | 9 | public void traverseTree(IHuffmanNode node, int[] word, int depth, HeaderInfo headerInfo) {
//empty node
if (node == null)
return;
//Node is leaf, attach code
if (node.isLeaf()) {
((Word) node.getWord()).setOutputParam(
word,
depth);
updateHeaderInfoForLeaf(
node.getWord(),
depth,
headerInfo);
//Node is already a leaf (only one word in the whole chunk) - return!
return;
//Node is no leaf, recursive method call of @see generateHuffmanCode, to generate hoffman code for the branches
} else {
//Split level is reached
if (Math.pow(2, depth + 1) == _branchTasks.size()) {
//supply all TraverseTreeTask-Branches with a node to start traversing
for (int i = 0; i < 2; i++) {
//first child of node
if (i == 0) {
//get empty branch
for (TraverseTreeTask task : _branchTasks) {
if (task.getBranchNode() == null) {
task.setParams(node.getLeft(),
shiftWord(
word.clone(),
depth,
0),
depth + 1);
break;
}
}
//second child of node
} else {
//get empty branch
for (TraverseTreeTask task : _branchTasks) {
if (task.getBranchNode() == null) {
task.setParams(node.getRight(),
shiftWord(
word.clone(),
depth,
1),
depth + 1);
break;
}
}
}
}
return;
}
//go to next level of the tree
traverseTree(
node.getLeft(),
shiftWord(
word.clone(),
depth,
0),
depth + 1, headerInfo);
traverseTree(node.getRight(),
shiftWord(
word.clone(),
depth,
1),
depth + 1
, headerInfo);
}
} |
fe37f935-98dd-4efb-b3d9-3df6688e960f | 8 | @Override
public void changeImage(ImageMovementState movementState, ImageRotationState rotationState)
{
switch (movementState)
{
case Idle:
imageMovementState = ImageMovementState.Idle;
switch (rotationState)
{
case Idle:
imageRotationState = ImageRotationState.Idle;
activeImage = images.get(IDLE);
break;
case rotatingLeft:
imageRotationState = ImageRotationState.rotatingLeft;
activeImage = images.get(TURNINGLEFT);
break;
case rotatingRight:
imageRotationState = ImageRotationState.rotatingRight;
activeImage = images.get(TURNINGRIGHT);
break;
}
break;
case Thrusting:
imageMovementState = ImageMovementState.Thrusting;
switch (rotationState)
{
case Idle:
imageRotationState = ImageRotationState.Idle;
activeImage = images.get(THRUSTING);
break;
case rotatingLeft:
imageRotationState = ImageRotationState.rotatingLeft;
activeImage = images.get(TURNINGLEFTTHRUSTING);
break;
case rotatingRight:
imageRotationState = ImageRotationState.rotatingRight;
activeImage = images.get(TURNINGRIGHTTHRUSTING);
break;
}
break;
}
} |
a286d001-6a74-447e-adc2-c8baaa5105c8 | 0 | public void setDetermineImageNumber(boolean newValue)
{
determineNumberOfImages = newValue;
} |
075ed919-0a97-467c-87ad-2da84ea55b82 | 5 | public int getEncodedMotorPosition(int motor)
{
if (!isConnected())
{
error("Robot is not connected!", "RXTXRobot", "getEncodedMotorPosition");
return -1;
}
if (!getOverrideValidation() && (motor < RXTXRobot.MOTOR1 || motor > RXTXRobot.MOTOR2))
{
error("getEncodedMotorPosition was not given a correct motor argument", "RXTXRobot", "getEncodedMotorPosition");
return -1;
}
debug("Checking tick position for encoder " + motor);
this.attemptTryAgain = true;
String[] split = sendRaw("p " + motor).split("\\s+");
this.attemptTryAgain = false;
if (split.length != 3)
{
error("Incorrect length returned: " + split.length, "RXTXRobot", "getEncodedMotorPosition");
return -1;
}
return Integer.parseInt(split[2]);
} |
c0127fe3-6af7-48f6-8099-f77a145fffdf | 4 | public void testDajZauzeteSobe() {
java.util.Date datumOD= new java.util.Date();
java.util.Date datumDO= new java.util.Date();
java.util.Date rezervisanoOD= new java.util.Date();
java.util.Date rezervisanoDO= new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
try
{
datumOD=sdf.parse("2014-08-15");
}
catch(java.text.ParseException p)
{
System.out.println(p.toString());
}
try
{
datumDO=sdf.parse("2014-08-20");
}
catch(java.text.ParseException p1)
{
System.out.println(p1.toString());
}
try
{
rezervisanoOD=sdf.parse("2014-08-10");
}
catch(java.text.ParseException p)
{
System.out.println(p.toString());
}
try
{
rezervisanoDO=sdf.parse("2014-08-20");
}
catch(java.text.ParseException p1)
{
System.out.println(p1.toString());
}
Soba s= new Soba();
Rezervacija r=new Rezervacija();
s.setBrojSobe(10);
//s.setBalkon(true);
s.setBrojKreveta(2);
s.setSprat(2);
DBManager.spasiSobu(s);
r.setSoba(s);
r.setRezervisanoOd(rezervisanoOD);
r.setRezervisanoDo(rezervisanoDO);
DBManager.spasiRezervaciju(r);
java.util.List tempListaSoba =DBManager.dajZauzeteSobe(datumOD, datumDO);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t1 = session.beginTransaction();
session.delete(s);
session.delete(r);
t1.commit();
session.close();
assertTrue(tempListaSoba.contains(10));
} |
fdd656bf-3798-4fe5-b494-3a707dd1db1c | 8 | public static Class<?> findCommonElementType(Collection<?> collection) {
if (isEmpty(collection)) {
return null;
}
Class<?> candidate = null;
for (Object val : collection) {
if (val != null) {
if (candidate == null) {
candidate = val.getClass();
} else if (candidate != val.getClass()) {
return null;
}
}
}
return candidate;
} |
0312cd66-fc28-4206-a1cd-b75e294a22db | 4 | @Override
public void nodeDataChanged(ZVNode node) {
boolean updateView = false;
if (nodes != null) {
for (int i = 0; i < nodes.length; i++) {
if ((nodes[i] == node)) {
updateView = true;
}
}
}
if (updateView) {
updateView();
}
} |
09614c62-7f18-4245-b22f-60fdcfd844b2 | 3 | public List getNextElements(int count)
throws IteratorException {
int i = 0;
Object object = null;
LinkedList list = new LinkedList();
if (listIterator != null) {
while (listIterator.hasNext() && (i < count)) {
object = listIterator.next();
list.add(object);
i++;
}
} // end if
else {
throw new IteratorException(); // No data
}
return list;
} |
4f4611f6-041a-4ad3-abc1-42110d199e11 | 8 | private TextBlock getCircledCharacter(ILeaf entity, ISkinParam skinParam) {
final Stereotype stereotype = entity.getStereotype();
if (stereotype != null && stereotype.getSprite() != null) {
return skinParam.getSprite(stereotype.getSprite()).asTextBlock(stereotype.getHtmlColor());
}
if (stereotype != null && stereotype.getCharacter() != 0) {
final HtmlColor classBorder = getColor(ColorParam.classBorder, stereotype);
final UFont font = getFont(FontParam.CIRCLED_CHARACTER, null);
return new CircledCharacter(stereotype.getCharacter(), getSkinParam().getCircledCharacterRadius(), font,
stereotype.getHtmlColor(), classBorder, getFontColor(FontParam.CIRCLED_CHARACTER, null));
}
if (entity.getEntityType() == LeafType.ABSTRACT_CLASS) {
return new CircledCharacter('A', getSkinParam().getCircledCharacterRadius(), getFont(
FontParam.CIRCLED_CHARACTER, null), getColor(ColorParam.stereotypeABackground, stereotype),
getColor(ColorParam.classBorder, stereotype), getFontColor(FontParam.CIRCLED_CHARACTER, null));
}
if (entity.getEntityType() == LeafType.CLASS) {
return new CircledCharacter('C', getSkinParam().getCircledCharacterRadius(), getFont(
FontParam.CIRCLED_CHARACTER, null), getColor(ColorParam.stereotypeCBackground, stereotype),
getColor(ColorParam.classBorder, stereotype), getFontColor(FontParam.CIRCLED_CHARACTER, null));
}
if (entity.getEntityType() == LeafType.INTERFACE) {
return new CircledCharacter('I', getSkinParam().getCircledCharacterRadius(), getFont(
FontParam.CIRCLED_CHARACTER, null), getColor(ColorParam.stereotypeIBackground, stereotype),
getColor(ColorParam.classBorder, stereotype), getFontColor(FontParam.CIRCLED_CHARACTER, null));
}
if (entity.getEntityType() == LeafType.ENUM) {
return new CircledCharacter('E', getSkinParam().getCircledCharacterRadius(), getFont(
FontParam.CIRCLED_CHARACTER, null), getColor(ColorParam.stereotypeEBackground, stereotype),
getColor(ColorParam.classBorder, stereotype), getFontColor(FontParam.CIRCLED_CHARACTER, null));
}
assert false;
return null;
} |
15440c1c-bd89-49d6-8a14-69fb747d7f7a | 0 | private NamesManager()
{
} |
a5f32112-1e13-4045-bf8f-03ae99dd86da | 1 | public static void main(String[] args) {
for (int i = 0; i < 5; i++)
new Thread(new LiftOff()).start();
System.out.println("Waiting for LiftOff");
} |
dee188d7-9a48-48b7-a6f0-8ff4eaba6d9a | 2 | public void forceClose(){
try{
this.fileChannel.close();
this.fileOutputStream.close();
}catch(Exception e){
e.printStackTrace();
try{
this.fileChannel.close();
this.fileOutputStream.close();
}catch(Exception e1){
e1.printStackTrace();
}
}finally{
this.file.delete();// 丢弃损害的文件
}
} |
7f5779ca-440b-4693-a2a4-821a4e9cf02b | 5 | private void saveImage(){
if (this.jLabelImage.getIcon()!=null){
ImageProcessing.imageFormat extension;
switch(this.jComboBox1.getSelectedItem().toString()){
case "BMP":
extension= ImageProcessing.imageFormat.bmp;
break;
case "GIF":
extension=ImageProcessing.imageFormat.gif;
break;
case "JPG":
extension=ImageProcessing.imageFormat.jpg;
break;
case "PNG":
extension=ImageProcessing.imageFormat.png;
break;
default:
extension=ImageProcessing.imageFormat.jpg;
break;
}
ObjSaveImage.saveFile((BufferedImage)ObjTransformFormats.iconToImage(jLabelImage.getIcon()),extension);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.