method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
21fab283-01f4-46e6-9a57-d99985356d5e
| 9
|
public NodoG[] buscarHijos(boolean white, Board tablero) {
ArrayList<Board> listaTableros = new ArrayList<>();
ArrayList<Integer> ies = new ArrayList<>();
ArrayList<Integer> js = new ArrayList<>();
ArrayList<Integer> mov = new ArrayList<>();
for (int a = 0; a < size; a++) {
for (int b = 0; b < size; b++) {
if (tablero.values[a][b] < 15) {
if ((tablero.values[a][b] & Board.LEFT) != Board.LEFT) {
proceso(tablero, white, listaTableros, ies, js, mov, Board.LEFT, a, b, size);
}
if ((tablero.values[a][b] & Board.TOP) != Board.TOP) {
proceso(tablero, white, listaTableros, ies, js, mov, Board.TOP, a, b, size);
}
if ((tablero.values[a][b] & Board.RIGHT) != Board.RIGHT) {
proceso(tablero, white, listaTableros, ies, js, mov, Board.RIGHT, a, b, size);
}
if ((tablero.values[a][b] & Board.BOTTOM) != Board.BOTTOM) {
proceso(tablero, white, listaTableros, ies, js, mov, Board.BOTTOM, a, b, size);
}
}
}
}
// parche(tablero);
// return listaTableros;
NodoG[] nodos = new NodoG[listaTableros.size()];
if (nodos.length > 0) {
// System.out.println("*");
for (int a = 0; a < nodos.length; a++) {
//tal vez haya que clonar!
nodos[a] = new NodoG(size);
nodos[a].tablero = listaTableros.get(a);
// impVal(listaTableros.get(a).values);
nodos[a].i = ies.get(a);
nodos[a].j = js.get(a);
nodos[a].direccion = mov.get(a);
}
}
return nodos;
}
|
7f6ea911-abb1-4576-a2a9-287d339e3fe8
| 2
|
static public void random(CPLayer l, CPRect r) {
int[] data = l.getData();
CPRect rect = l.getSize();
rect.clip(r);
Random rnd = new Random();
for (int j = rect.top; j < rect.bottom; j++) {
for (int i = rect.left; i < rect.right; i++) {
data[i + j * l.getWidth()] = rnd.nextInt();
}
}
}
|
664c2167-361e-40e3-b752-6aab212d211b
| 1
|
public static void main(String[] args) throws InterruptedException {
Tetris tetris = new Tetris();
Kayttoliittyma kayttoliittyma = new Kayttoliittyma(tetris);
SwingUtilities.invokeLater(kayttoliittyma);
PegasusAI ai = new PegasusAI(tetris);
tetris.lisaaAI(ai);
while (true){
tetris.peliSykli();
}
}
|
bfc3e8a5-2ce8-4e1a-8a37-f0b361924a3b
| 1
|
public List<Double> getMaxValueList() {
List<Double> result= new ArrayList<Double>();
double[] values= this.getMaxValueArray();
for (int i= 0; i< values.length; ++i) {
result.add(Double.valueOf(values[i]));
}
return result;
}
|
a3b1456a-9d48-43f7-908a-9c11f4e17d9a
| 8
|
private ARG xmlToARG(org.w3c.dom.Document doc) throws FileParseException {
Node documentRoot = doc.getDocumentElement();
Node topLevelChild = documentRoot.getFirstChild();
//Search for (the first) element
while(topLevelChild != null) {
if (topLevelChild.getNodeType() == Node.ELEMENT_NODE && topLevelChild.getNodeName().equalsIgnoreCase(XML_GRAPH))
break;
topLevelChild = topLevelChild.getNextSibling();
}
//Child should now be 'pointing' at 'graph' element, if we're at the end it's an error
if (topLevelChild == null) {
throw new FileParseException("No phylogeny tag found in XML, cannot create tree");
}
String rangeMinStr = getAttributeForNode(topLevelChild, XML_RANGEMIN);
String rangeMaxStr = getAttributeForNode(topLevelChild, XML_RANGEMAX);
Integer rangeStart;
Integer rangeEnd;
try {
rangeStart = Integer.parseInt(rangeMinStr);
rangeEnd = Integer.parseInt(rangeMaxStr);
}
catch (NumberFormatException nfe) {
throw new FileParseException("Graph XML element must specify rangeMin and rangeMax attributes.");
}
catch (NullPointerException npe) {
throw new FileParseException("Graph XML element must specify rangeMin and rangeMax attributes.");
}
Node graphChild = topLevelChild.getFirstChild();
List<ARGNode> argNodes = new ArrayList<ARGNode>();
List<Edge> edges = new ArrayList<Edge>();
//First we read in all nodes, and then all the edges
while(graphChild != null) {
addNodeToARG(graphChild, argNodes);
graphChild = graphChild.getNextSibling();
}
graphChild = topLevelChild.getFirstChild();
while(graphChild != null) {
addEdgeToARG(graphChild, argNodes, edges, rangeStart, rangeEnd);
graphChild = graphChild.getNextSibling();
}
ARG arg = new ARG(argNodes, edges, rangeStart, rangeEnd);
return arg;
}
|
264dbca4-af83-4472-9c87-d98164d467ce
| 1
|
int sum1toN(int n){
int sum=0;
for(int i=0;i<=n;i++){
sum+=i;
}
return sum;
}
|
0b53a2ef-2a53-4b6b-a66b-9050c3920615
| 2
|
private int readTypeTable
(ResTable_Type typeTable,
byte[] data,
int offset) throws IOException {
typeTable.id = readUInt8(data, offset);
offset += 1;
typeTable.res0 = readUInt8(data, offset);
if (typeTable.res0 != 0)
throw new RuntimeException("File format error, res0 was not zero");
offset += 1;
typeTable.res1 = readUInt16(data, offset);
if (typeTable.res1 != 0)
throw new RuntimeException("File format error, res1 was not zero");
offset += 2;
typeTable.entryCount = readUInt32(data, offset);
offset += 4;
typeTable.entriesStart = readUInt32(data, offset);
offset += 4;
return readConfigTable(typeTable.config, data, offset);
}
|
ae4c6b15-c74d-46be-b967-4176df4cac2d
| 1
|
public synchronized void deleteWay(int pos, long wayId){
if (ways.size()>pos)
ways.remove(wayId);
}
|
88926b64-c395-4d13-98c8-2c82c0e5e3e4
| 1
|
public String convertToString(){
StringBuilder builder = new StringBuilder();
for(Record record: log.getRecords()){
builder.append(record.toString());
builder.append(NewL);
}
return builder.toString();
}
|
016f1e94-4d2a-40f0-b9d0-9ec125237a0e
| 7
|
private void factor() {
// System.out.println("factor " + data.get(0).getTokenType().name() + ":" + data.get(0).getValue());
Token t = popToken();
switch(t.getTokenType()) {
case SCONSTANT:
case SSTRING:
case SFALSE:
case STRUE:
// constant();
break;
case SIDENTIFIER:
pushToken(t);
variable();
break;
case SLPAREN:
expression();
expectToken(TokenType.SRPAREN);
break;
case SNOT:
factor();
break;
default:
fail(t);
}
}
|
99f36931-def4-485f-a04f-623010e7fbaa
| 6
|
@Override
public void b(PacketDataSerializer packetDataSerializer) throws IOException {
packetDataSerializer.b(action.ordinal());
if(action.ordinal() == Action.SET_SIZE.ordinal())
{
packetDataSerializer.writeDouble(newRadius);
}
if(action.ordinal() == Action.LERP_SIZE.ordinal())
{
packetDataSerializer.writeDouble(oldRadius);
packetDataSerializer.writeDouble(newRadius);
Var.writeVarLong(speed, packetDataSerializer);
}
if(action.ordinal() == Action.SET_CENTER.ordinal()) {
packetDataSerializer.writeDouble(x);
packetDataSerializer.writeDouble(z);
}
if(action.ordinal() == Action.INITIALIZE.ordinal())
{
packetDataSerializer.writeDouble(x);
packetDataSerializer.writeDouble(z);
packetDataSerializer.writeDouble(oldRadius);
packetDataSerializer.writeDouble(newRadius);
Var.writeVarLong(speed, packetDataSerializer);
packetDataSerializer.b(portalTeleportBoundary);
packetDataSerializer.b(warningTime);
packetDataSerializer.b(warningBlocks);
}
if(action.ordinal() == Action.SET_WARNING_TIME.ordinal())
{
packetDataSerializer.b(warningTime);
}
if(action.ordinal() == Action.SET_WARNING_BLOCKS.ordinal())
{
packetDataSerializer.b(warningBlocks);
}
}
|
59b0e1a0-d366-42fe-a56c-3604d0771634
| 7
|
@Override
public String getMessage() {
String msg = super.getMessage();
if (msg != null)
return msg;
msg = getProblem();
if (msg != null)
return msg;
Object response = getParameters().get(HTTP_RESPONSE);
if (response != null) {
msg = response.toString();
int eol = msg.indexOf("\n");
if (eol < 0) {
eol = msg.indexOf("\r");
}
if (eol >= 0) {
msg = msg.substring(0, eol);
}
msg = msg.trim();
if (msg.length() > 0) {
return msg;
}
}
response = getHttpStatusCode();
if (response != null) {
return HTTP_STATUS_CODE + " " + response;
}
return null;
}
|
8f7cbd07-ff91-4e2d-baf7-7dee7408d811
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ID3v2FrameSet other = (ID3v2FrameSet) obj;
if (frames == null) {
if (other.frames != null)
return false;
} else if (!frames.equals(other.frames))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
|
3f8687cd-887a-4c66-8d5f-0f64f4c0c971
| 8
|
static final void method168(Player player, int animationID, int animationDelay) {
if (((Mobile) (player)).animation == animationID && animationID != -1) {
Animation animation = Class66.animationForID(animationID);
int k = animation.anInt1647;
if (k == 1) {
player.anInt2888 = 1;
player.anInt2943 = 0;
player.anInt2909 = 0;
player.animationDelay = animationDelay;
player.anInt2936 = 0;
Class99.method972(((Mobile) (player)).posX, ((Mobile) (player)).anInt2943, Class26_Sub1.localPlayer == player, ((Mobile) (player)).posY, animation);
}
if (k == 2) {
player.anInt2909 = 0;
}
} else if (animationID == -1 || ((Mobile) (player)).animation == -1
|| Class66.animationForID(animationID).anInt1659 >= Class66.animationForID(((Mobile) (player)).animation).anInt1659) {
player.anInt2891 = ((Mobile) (player)).queueIndex;
player.anInt2909 = 0;
player.animationDelay = animationDelay;
player.animation = animationID;
player.anInt2943 = 0;
player.anInt2888 = 1;
player.anInt2936 = 0;
if (((Mobile) (player)).animation != -1) {
Class99.method972(((Mobile) (player)).posX, ((Mobile) (player)).anInt2943, Class26_Sub1.localPlayer == player, ((Mobile) (player)).posY, Class66.animationForID(((Mobile) (player)).animation));
}
}
}
|
e28c781a-35b2-450b-9353-1697c777de4b
| 3
|
public String toString()
{
// Adds on parent tables
StringBuffer sb = new StringBuffer();
if (this.parent!=null)
sb.append(parent.toString());
String indent = new String();
for (int i = 0; i < depth; i++) {
indent += " ";
}
for (Symbol s: symTable)
{
sb.append(indent + s.toString() + "\n");
}
return sb.toString();
}
|
eda780e1-f2e9-403f-a8bb-a94720b8991f
| 1
|
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((link == null) ? 0 : link.hashCode());
return result;
}
|
469111fe-d5c9-44fa-a6fd-06d0a65ba255
| 0
|
public void setId(String value) {
this.id = value;
}
|
34c9b002-d7b6-4cb0-b686-d2a13ab9acbb
| 5
|
protected void reindexFacesAndVertices() {
for (int i = 0; i < numPoints; i++) {
pointBuffer[i].index = -1;
}
// remove inactive faces and mark active vertices
numFaces = 0;
for (Iterator it = faces.iterator(); it.hasNext();) {
Face face = (Face) it.next();
if (face.mark != Face.VISIBLE) {
it.remove();
} else {
markFaceVertices(face, 0);
numFaces++;
}
}
// reindex vertices
numVertices = 0;
for (int i = 0; i < numPoints; i++) {
Vertex vtx = pointBuffer[i];
if (vtx.index == 0) {
vertexPointIndices[numVertices] = i;
vtx.index = numVertices++;
}
}
}
|
b796ea0e-7108-4fd9-8c73-a5803609e2c7
| 9
|
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node<K> other = (Node<K>) obj;
if (frequency == null) {
if (other.frequency != null)
return false;
} else if (!frequency.equals(other.frequency))
return false;
if (symbol == null) {
if (other.symbol != null)
return false;
} else if (!symbol.equals(other.symbol))
return false;
return true;
}
|
f4c412dc-992d-417a-92e7-b7546880db7a
| 4
|
public String Print()
{
String face = "";
for(int i = 0; i < 70; i ++)
{
for(int j = 0; j < 60; j++)
{
if(this.faceImage[i][j]==0){
face += " ";
}else if(this.faceImage[i][j]==1)
{
face += "#";
}
}
face += "\n";
}
return face;
}
|
be4e5edb-ff85-4e6c-b1f1-4e963b109dd6
| 4
|
private Coordinate getWallCoordinate(int dir) {
int xc = x, yc = y;
switch (dir) {
case Display.NORTH: //Check in front, not behind
case Display.EAST: //Check in front, not behind
break;
case Display.SOUTH: //Checking behind current location
yc--;
break;
case Display.WEST: //Checking behind current location
xc--;
break;
}
return new Coordinate(xc, yc);
}
|
c00be2d9-3c13-4d60-a104-583bee46ba61
| 5
|
private void reproduce() {
// List<Entity> test = new ArrayList<Entity>();
// for(Entity ent : entityList) {
// test.add(ent);
// }
int births = 0;
List<Entity> birthEnt = new ArrayList<Entity>();
for(Entity ent : new ArrayList<Entity>(entityList)) {
// System.out.println(entityList.size());
//int index = test.indexOf(ent);
Entity son = ent.nextIter();
if(son!=null) {
birthEnt.add(son);
births++;
}
//entityList.set(index, ent.clone());
}
entityList.addAll(birthEnt);
//test.removeAll(test);
int deaths = entityList.size();
List<Entity> deletion = new ArrayList<Entity>();
for(Entity ent : entityList) {
if(!ent.deletion()) {
deletion.add(ent);
deaths--;
}
}
entityList.removeAll(entityList);
entityList = new ArrayList<Entity>(deletion);
System.out.println(generation+","+entityList.size()+"/"+GlobalVars.aliveEntities+","+births+","+deaths+" - "+GlobalVars.entitiesCreated+"/"+((double)GlobalVars.entitieDeleted)+","+GlobalVars.entitiesCreated/((double)GlobalVars.entitieDeleted)+" - "+entityList.size()/((float)GlobalVars.aliveEntities)+" - "+(GlobalVars.entitiesCreated-((double)GlobalVars.entitieDeleted)));
// System.out.println(generation+"/"+GlobalVars.aliveEntities+" - "+GlobalVars.entitiesCreated+"/"+((double)GlobalVars.entitieDeleted)+","+GlobalVars.entitiesCreated/((double)GlobalVars.entitieDeleted)+" - ");
try {
out.write(entityList.size()+","+births+","+deaths+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
|
5244248a-94ad-4001-b4ad-fefa86ee911f
| 5
|
private boolean potDemanarPista()
{
elements_de_control_partida = PresentacioCtrl.getInstancia().getElementsDeControlPartida();
elements_de_control_jugadors = PresentacioCtrl.getInstancia().getElementsDeControlJugadors();
int i = ( Integer ) elements_de_control_partida[2] % 2;
return ( !processant_moviment && partida_en_curs && !pista_valida &&
PresentacioCtrl.getInstancia().esTornHuma() &&
PresentacioCtrl.getInstancia().consultaEstatPartida() == EstatPartida.NO_FINALITZADA &&
( ( Integer ) elements_de_control_partida[0] > ( Integer ) elements_de_control_jugadors[1][i] ) );
}
|
e6cccc00-5ca1-4659-94bb-b83bb6ca830a
| 0
|
@RequestMapping(value="{tripID}/detailsTravelTrip", method=RequestMethod.GET)
@ResponseBody
public TravelTrip API_detailsTravelTrip(@PathVariable("tripID") String tripID, Model model){
return travelTripDao.findById(Integer.parseInt(tripID));
}
|
f29586c5-fa3c-41df-a45c-3d113259b998
| 3
|
public static String poisson(ArrayList<String> parameters) throws ScriptException
{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
double lambda = (double)engine.eval(parameters.get(LAMBDA));
String k = parameters.get(K);
double time = Double.parseDouble(parameters.get(t));
// Check if K is a Range
boolean isARange = k.contains("..");
if(isARange)
{
int start = Integer.parseInt(k.split("\\.\\.")[0]);
int end = Integer.parseInt(k.split("\\.\\.")[1]);
String outputP="Probability = \n";
// Swap values if Range is backwards (E.g. 4..0)
if(start > end)
{
int temp = start;
start = end;
end = temp;
}
double sum = 0.0;
for(int i = start; i <= end; i++)
{
sum += (Math.exp(-lambda*time)*Math.pow(lambda*time, i)) / factorial(i);
outputP+="e^(-\u03BB*t)*(\u03BB*t)^"+i+"+\n";
}
outputP=outputP.substring(0,outputP.length()-2);
return outputP+"\n= " + round(sum);
}
else
return "Probability: " + round((Math.exp(-lambda*time)*Math.pow(lambda*time, Integer.parseInt(k))) / factorial(Integer.parseInt(k)));
}
|
51fc742b-35df-4772-8f35-7b02322b59d1
| 9
|
public void evolve(){
int numberOfGenerations = 0;
double bestSolution = Double.MAX_VALUE;
double worstSolution = Double.MIN_VALUE;
Individual bestSolInd=null;
int bestSolIndex=-1;
int worstFinalIndex=-1;//might not use
double lastSolution = 0;
double numberOfRepeats = 0;
long startTime = System.currentTimeMillis();
System.out.println("--------------------------------------------------------------------------");
System.out.println("GEN # ITER BEST ( POP BEST, POP AVG, POP WORST), TIME SINCE ITER START ( OVERALL TIME AVG, OVERALL TIME SUM)");
while (numberOfGenerations <= maxNumberOfGenerations){
Population offspring = population.clone();
Config config = Config.getInstance();
offspring = crossover.cross(offspring);
offspring = mutation.mutate(offspring);
if (config.generationMix){
population.population.addAll(offspring.population);
}
else{
population.population = offspring.population;
}
population = selection.select(population);
numberOfGenerations++;
/// calc data store best worst and avg
//bestF,avgF,worstF,bestInd,worstInd
Double[] data = population.getStats();
if (data[0] < bestSolution){
bestSolution = data[0];
bestSolInd=population.population.get(data[3].intValue());
}
if(bestSolution<best){
best=bestSolution;
bestInd=population.population.get(data[3].intValue());
}
if (data[2] > worstSolution){
worstSolution = data[2];
}
if (numberOfGenerations%100==0){
int time = (int) ((System.currentTimeMillis() - startTime) / 1000);
allTimes.add(time);
int totalTime = 0;
for (int times : allTimes){
totalTime += times;
}
int avgTime = totalTime / allTimes.size();
System.out.println("G: "+String.format("%5d",numberOfGenerations)+" "+String.format("%10.3f",bestSolution) + " ("+String.format("%10.2f",data[0])+", "+String.format("%10.2f",data[1])+", "+String.format("%10.2f",data[2])+"), "+time+" ("+String.format("%5d",avgTime)+", "+String.format("%5d",totalTime)+")");
}
}
System.out.println("--------------------------------------------------------------------------");
if (best!=Double.MAX_VALUE){
System.out.println("---------------------- ITERATTION BEST: "+ String.format("%10.3f",bestSolution)+" -----------------------");
System.out.println(bestSolInd);
}
System.out.println("--------------------------------------------------------------------------");
if (best!=Double.MAX_VALUE){
System.out.println("------------------------ OVERALL BEST: "+ String.format("%10.3f",best)+" ------------------------");
System.out.println(bestInd);
}
System.out.println("--------------------------------------------------------------------------");
System.out.println();
}
|
eae0bd93-bc46-467a-a055-34490c4b6db6
| 9
|
public boolean hasTraits(MonsterCard mc1, MonsterCard mc2, boolean strict) {
if(strict) {
MonsterType mt1 = MonsterType.fromString(this.t1.toString());
MonsterType mt2 = MonsterType.fromString(this.t2.toString());
if(mc1.type == mt1 && mc2.type == mt2)
return true;
if(mc1.type == mt2 && mc2.type == mt1)
return true;
return false;
}
if(mc1.hasTrait(this.t1) && mc2.hasTrait(this.t2))
return true;
if(mc1.hasTrait(this.t2) && mc2.hasTrait(this.t1))
return true;
return false;
}
|
596a2e95-7f02-4a48-9ce2-724eb09020e4
| 7
|
@Override
public StateDist search() {
stateDistQueue.clear();
StateDist result = null;
addState(getInitialState(), 0, 0);
int counter = 0;
while (!stateDistQueue.isEmpty()) {
StateDist stateDist = stateDistQueue.poll();
SearchState oldState = stateDist.state;
int oldDist = stateDistMap.get(oldState);
if (stateDist.dist > oldDist + h.estimateCostToGoal(oldState))
continue;
if (counter++ % 100 == 0)
System.out.println("Est: " + stateDist.dist + " Dist: " + oldDist + " size: " + stateDistMap.size() + " unexplored: " + stateDistQueue.size());
if (oldState.rowsToGo <= 0) {
if (result == null && isExpectedBoard(oldState.board))
result = stateDist;
if (rowsToClear > 0)
continue;
}
expandChildren(oldState, oldDist);
}
calcDistToGoal();
prune();
printDistStats();
return result;
}
|
04d38813-fcc1-4139-bf44-bb57e1eefb9b
| 7
|
public void findPieces(String fileName)
{
File file = new File(fileName);
BufferedReader buffer = null;
try
{
try
{
buffer = new BufferedReader(new FileReader(file));
}
catch(FileNotFoundException f)
{
System.out.println("The command line has an invalid file name! Please input a proper file arguement!");
}
while(buffer.ready())
{
String piece = "";
String color = "";
String placement = "";
String line = buffer.readLine();
Matcher placeVerifier = PIECE_PLACING_VERIFIER.matcher(line);
// Matcher movementCapture = PIECE_MOVEMENT_CAPTURING.matcher(line);
Matcher movementVerifier = PIECE_MOVEMENT_VERIFIER.matcher(line);
// Matcher castleMatcher = CASTLING_VERIFIER.matcher(line);
if(placeVerifier.matches())
{
Piece newPiece = new Piece(piece);
newPiece = pieceType(line, newPiece);
piece = newPiece.getPieceType();
color = pieceColor(line, newPiece);
placement = piecePosition(line);
String pieceType = placeVerifier.group("pieceType");
// placePiece(piece, color, placement, line);
char columnLetter = placeVerifier.group("columnPosition").charAt(0);
char rowNumber = placeVerifier.group("rowPosition").charAt(0);
int column = columnLetter - 'a';
int row = rowNumber - '1';
pieceType = (color == "White") ? pieceType.toLowerCase() : pieceType.toUpperCase();
newPiece.setPieceType(pieceType);
ChessGame.controller.addPieceToBoard(newPiece, column, row);
}
else if(movementVerifier.matches())
{
char startingColumnLetter = movementVerifier.group("startingColumn").charAt(0);
char startingRowNumber = movementVerifier.group("startingRow").charAt(0);
char endColumnLetter = movementVerifier.group("endColumn").charAt(0);
char endRowNumber = movementVerifier.group("endRow").charAt(0);
int startingColumn = startingColumnLetter - 'a';
int startingRow = startingRowNumber - '1';
int endColumn = endColumnLetter - 'a';
int endRow = endRowNumber - '1';
Position startingPosition = makeStartMovementPosition(startingColumn, startingRow);
Position endPosition = makeEndMovementPosition(endColumn, endRow);
ChessGame.controller.movePieceOnBoard(line, startingPosition, endPosition);
}
// else if(movementCapture.matches())
// {
// capturePiece(line);
// }
// else if(castleMatcher.matches())
// {
// notifyCastle(line);
// }
else
{
System.out.println();
System.out.println(line + " is an incorrect input! Please revise it!");
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
buffer.close();
}
catch(IOException e)
{
System.out.println("Buffer hasn't closed");
}
}
}
|
8e1cdd7b-6420-49e8-86f0-a52b02497e33
| 9
|
public void bounceOffPaddle(Paddle paddle, Player player) {
if (vx < 0) {
if (x < (paddle.getX() + PADDLE_WIDTH) && x > paddle.getX()
&& y < (paddle.getY() + paddle.getLength()) && y > paddle.getY()) {
changeAngle(paddle);
player.ballReturned();
}
} else {
if (x + 2 * r > (paddle.getX()) && x < (paddle.getX() + PADDLE_WIDTH)
&& y < (paddle.getY() + paddle.getLength()) && y > paddle.getY()) {
changeAngle(paddle);
player.ballReturned();
}
}
}
|
e2f74fc1-0c59-4b97-af52-249a50a20f8a
| 9
|
public boolean equals(Object p_other) {
if ( this == p_other ) {
return true;
}
else if ( p_other == null ) {
return false;
}
ComboLeg l_theOther = (ComboLeg)p_other;
if (m_conId != l_theOther.m_conId ||
m_ratio != l_theOther.m_ratio ||
m_openClose != l_theOther.m_openClose ||
m_shortSaleSlot != l_theOther.m_shortSaleSlot) {
return false;
}
if (Util.StringCompareIgnCase(m_action, l_theOther.m_action) != 0 ||
Util.StringCompareIgnCase(m_exchange, l_theOther.m_exchange) != 0 ||
Util.StringCompareIgnCase(m_designatedLocation, l_theOther.m_designatedLocation) != 0) {
return false;
}
return true;
}
|
ca90e963-3e26-4928-b5e7-6a0010230d56
| 2
|
public void visitMemExpr(final MemExpr expr) {
if (expr instanceof MemRefExpr) {
visitMemRefExpr((MemRefExpr) expr);
} else if (expr instanceof VarExpr) {
visitVarExpr((VarExpr) expr);
}
}
|
57f1d800-4456-44a5-9346-a83a03ba5948
| 7
|
@SuppressWarnings({"unchecked"})
IteratorImpl( int position ) {
if ( position < 0 || position > _size ) {
throw new IndexOutOfBoundsException();
}
_nextIndex = position;
if ( position == 0 ) {
_next = _head;
} else if ( position == _size ) {
_next = null;
} else if ( position < ( _size >> 1 ) ) {
int pos = 0;
for ( _next = _head; pos < position; pos++ ) {
_next = _next.getNext();
}
} else {
int pos = _size - 1;
for ( _next = _tail; pos > position; pos-- ) {
_next = _next.getPrevious();
}
}
}
|
bee3b8f8-cd6f-40ad-ae36-5db4c6cb18b5
| 5
|
public final void method43(AbstractToolkit var_ha, int i) {
if (i != -14218)
aClass30_10127 = null;
anInt10144++;
Object object = null;
r var_r;
if (aR10128 != null || !aBoolean10137) {
var_r = aR10128;
aR10128 = null;
} else {
Class2 class2 = method2491((byte) -51, true, 262144, var_ha);
var_r = class2 == null ? null : ((Class2) class2).aR118;
}
if (var_r != null)
Class169.method1301(var_r, ((Class318_Sub1) this).mapHeightLevel,
((Class318_Sub1) this).xHash,
((Class318_Sub1) this).anInt6388, null);
}
|
4863475d-4b94-4c65-bedd-70cf1285fcac
| 9
|
protected Object doInBackground(){
// Initialize the algorithm variables
Wavelet.init( Settings.waveletType );
DensityHelper.initializeTranslates();
DensityHelper.initializeCoefficients();
// Intialize the current sample index to 1.
int sampInd = 1;
// Buffer reader used to read the user-provided sample data file.
BufferedReader dataReader;
try
{
// Get samples from default file if datafile not specified by user.
if(Settings.dataFile.equals(""))
{
String filename = "/edu/fit/estimator2D/resources/datafiles/2dGauss.csv";
java.io.InputStream in = getClass().getResourceAsStream(filename);
dataReader = new BufferedReader( new InputStreamReader(in) );
}
// Get samples from user's file if specified.
else
{
// Read the user file.
dataReader = new BufferedReader( new FileReader( Settings.dataFile ) );
}
// Perform next calculations only if there is a data sample left and
// the density runner is not killed.
while( dataReader.ready() && !isCancelled() )
{
// Wait if user so requested.
while( paused )
{
// While pausing, close the buffer reader and stop if the user
// terminates the execution of the Density Runner.
if( terminated )
{
dataReader.close();
return null;
} // end if( terminated ).
try
{
// Sleep while the Runner is still on pause.
Thread.sleep( 500 );
} // end try Thread.sleep( 500 ).
catch(InterruptedException ex){ex.printStackTrace();}
} // end while( paused ).
// Get the next sample.
double[] sample = new double[2];
String lineContent = dataReader.readLine();
String[] parts = lineContent.split(",");
sample[0] = Double.parseDouble(parts[0]);
sample[1] = Double.parseDouble(parts[1]);
// Update the wavelet's coefficients using the new sample.
DensityHelper.updateCoefficients( sample );
// Display the current density at the user-specified frequency.
if( sampInd % Settings.updateFrequency == 0 )
{
// Update the density using the current coefficients.
DensityHelper.newDensity();
// Send the current sample index to the process method
// for updating the sample index label in the applet.
// !! the pubish method is defined in the SwingWorker class !!.
publish( sampInd );
} // end if( sampInd % Settings.updateFrequency == 0 ).
try
{
// Give some time to the event queue
// to handle the plot update.
Thread.sleep( 1 );
} // end try{ Thread.sleep ( 1 ) }
catch( InterruptedException ex){ex.printStackTrace();}
// Increment the sample index.
sampInd++;
} // end while( dataReader.ready() && !isCancelled() )
// Close the buffer reader when execution terminates.
dataReader.close();
} // end the main try{}
catch(Exception ex){ ex.printStackTrace();}
// doInBackground has to return an object.
// We return null as there is no meaningful object returned by this method.
return null;
} // end method public Object doInBackground().
|
9343230d-451e-49af-a88b-2b5d7cb7c37b
| 0
|
public void setJaar(int jaar) {
this.jaar = jaar;
}
|
d44c7f17-341d-4115-8910-b5fef66fb0a0
| 9
|
@Override
public void setValue(int newValue) {
if (head == null) {
return;
}
if (currentValue > newValue) {
// move down to new value using next values
while (currentValue > newValue && text.hasNext()) {
text = text.next();
currentValue--;
}
} else if (currentValue < newValue) {
// move up to new value using prev values;
while (currentValue < newValue && text.hasPrevious()) {
text = text.previous();
currentValue++;
}
}
currentValue = newValue;
if (currentValue >= maxValue) {
currentValue = maxValue - 1;
}
if (currentValue < 0) {
currentValue = 0;
}
// System.out.println(currentValue + " versus possible is: " +
// maxValue + " and extent is: " + extent);
fireChangeEvent();
}
|
e9f6fed6-d88c-4b73-9b15-7a58258e91c0
| 0
|
@Test
public void testCalcProductTotal() throws Exception {
BigDecimal bd1 = product.calcProductTotal(5);
BigDecimal bd2 = BigDecimal.valueOf(25.00);
bd2 = bd2.setScale(2,BigDecimal.ROUND_HALF_DOWN);
assertTrue(bd1.equals(bd2));
bd1 = product.calcProductTotal(9);
bd2 = BigDecimal.valueOf(70.00);
bd2 = bd2.setScale(2,BigDecimal.ROUND_HALF_DOWN);
assertTrue(bd1.equals(bd2));
}
|
577e7326-10fe-4cd3-88e1-c1551a3968d1
| 7
|
private Interface parseInterfaceContent(NodeList childNodes)
{
Interface interFace = new Interface();
for (int count = 0; count < childNodes.getLength(); count++)
{
Node node = childNodes.item(count);
if ("attribute".equals(node.getNodeName().toLowerCase()))
{
interFace.setName(parseNameAttribute(node));
}
if ("channel".equals(node.getNodeName().toLowerCase()))
{
Channel chan = new Channel();
for (int i = 0; i < node.getAttributes().getLength(); i++)
{
if ("name".equals(node.getAttributes().item(i).getNodeName()))
{
chan.setName(node.getAttributes().item(i).getNodeValue());
}
if ("type".equals(node.getAttributes().item(i).getNodeName()))
{
chan.setType(node.getAttributes().item(i).getNodeValue());
}
if ("direction".equals(node.getAttributes().item(i).getNodeName()))
{
chan.setDirection(node.getAttributes().item(i).getNodeValue());
}
}
interFace.setChannel(chan);
}
}
return interFace;
}
|
2faffaab-9817-4d43-9df3-e62a9a6233dd
| 4
|
public synchronized void gridletSubmit(Gridlet gl, boolean ack)
{
// update the current Gridlets in exec list up to this point in time
updateGridletProcessing();
// reset number of PE since at the moment, it is not supported
if (gl.getNumPE() > 1)
{
String userName = GridSim.getEntityName( gl.getUserID() );
System.out.println();
System.out.println(super.get_name() + ".gridletSubmit(): " +
" Gridlet #" + gl.getGridletID() + " from " + userName +
" user requires " + gl.getNumPE() + " PEs.");
System.out.println("--> Process this Gridlet to 1 PE only.");
System.out.println();
// also adjusted the length because the number of PEs are reduced
int numPE = gl.getNumPE();
double len = gl.getGridletLength();
gl.setGridletLength(len*numPE);
gl.setNumPE(1);
}
ResGridlet rgl = new ResGridlet(gl);
boolean success = false;
// if there is an available PE slot, then allocate immediately
if (gridletInExecList_.size() < super.totalPE_) {
success = allocatePEtoGridlet(rgl);
}
// if no available PE then put the ResGridlet into a Queue list
if (!success)
{
rgl.setGridletStatus(Gridlet.QUEUED);
gridletQueueList_.add(rgl);
}
// sends back an ack if required
if (ack)
{
super.sendAck(GridSimTags.GRIDLET_SUBMIT_ACK, true,
gl.getGridletID(), gl.getUserID()
);
}
}
|
70c930ed-1103-4f60-9806-9c3b282cde12
| 4
|
BlogResult(JSONObject jsonObject) {
this.Title = (String)jsonObject.get("title");
this.Abstract = (String)jsonObject.get("abstract");
this.Provider = (String)jsonObject.get("provider");
this.DisplayURL = (String)jsonObject.get("dispurl");
this.KeyTerms = (String)jsonObject.get("keyterms");
this.Author = (String)jsonObject.get("author");
this.IconURL = (String)jsonObject.get("icon");
this.ClickURL = (String)jsonObject.get("clickurl");
String dateString = (String)jsonObject.get("date");
if (dateString == null || dateString.length() == 0) {
this.Timestamp = 0;
this.Date = null;
}
else {
String[] splitDate = dateString.split("\\/");
int year = Integer.parseInt(splitDate[0]);
int month = Integer.parseInt(splitDate[1]);
int day = Integer.parseInt(splitDate[2]);
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, day);
this.Date = cal.getTime();
this.Timestamp = Math.round(this.Date.getTime() / 1000);
}
String scoreString = (String)jsonObject.get("score");
if (scoreString == null || scoreString.length() == 0) this.Score = 0;
else this.Score = Float.parseFloat(scoreString);
}
|
ae04ef9a-49d8-4d2b-aa37-c3e5bff498de
| 6
|
public void union(BinomiSolmu uusi) {
merge(uusi);
BinomiSolmu edellinen = null;
BinomiSolmu kasiteltava = juurilistanEka;
BinomiSolmu seuraava = kasiteltava.getSisarus();
while (seuraava != null) {
if ((kasiteltava.getAste() != seuraava.getAste()) ||
((seuraava.getSisarus() != null) &&
(seuraava.getSisarus().getAste() == kasiteltava.getAste()))) {
edellinen = kasiteltava;
kasiteltava = seuraava;
}
else { // samanasteiset puut yhdistetään
if (kasiteltava.getArvo() <= seuraava.getArvo()) {
kasiteltava.setSisarus(seuraava.getSisarus());
yhdistaPuut(kasiteltava, seuraava);
}
else {
yhdistaPuut(seuraava, kasiteltava);
if (edellinen == null) {
juurilistanEka = seuraava;
}
else edellinen.setSisarus(seuraava);
kasiteltava = seuraava;
}
}
seuraava = kasiteltava.getSisarus();
}
}
|
f387c083-e7d2-42ba-9f69-7116b105cf19
| 2
|
public Boolean preparate() {
if (this.txtcad.getText().length() != 0 && this.txtfilename.getSelectedItem().toString().length() != 0) {
return true;
}
return false;
}
|
4ba214cd-0a66-49da-a928-96d637a08d40
| 5
|
@Override
public int compare(JukeboxTrackRequest request1, JukeboxTrackRequest request2) {
boolean greaterThan = request1.getDateForState(state).getTime() > request1.getDateForState(state).getTime();
boolean lessThan = request1.getDateForState(state).getTime() < request1.getDateForState(state).getTime();
if (SortOrder.BY_DATE_ASC.equals(sortOrder)) {
return greaterThan ? 1 : (lessThan ? -1 : 0);
} else {
return lessThan ? 1 : (greaterThan ? -1 : 0);
}
}
|
0866e5d3-c33b-4349-b3e1-3efba0cbe959
| 6
|
public boolean getBoolean(String key) throws JSONException {
Object o = get(key);
if (o.equals(Boolean.FALSE) ||
(o instanceof String &&
((String) o).equalsIgnoreCase("false"))) {
return false;
} else if (o.equals(Boolean.TRUE) ||
(o instanceof String &&
((String) o).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a Boolean.");
}
|
59f8bcd7-9b14-4c92-ab5d-7858bf1b8d56
| 1
|
public void testFactory_FromDateFields_null() throws Exception {
try {
TimeOfDay.fromDateFields(null);
fail();
} catch (IllegalArgumentException ex) {}
}
|
156570b8-fa9c-4a8a-957a-4330d2861767
| 0
|
public int GetInternalMemorySize()
{
return internalMemory.size();
}
|
4050ec15-250c-4024-8bdf-fe5890065097
| 1
|
@SuppressWarnings("unused")
@Override
public void produceExcel(String fname, String savaPath) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fname));// 创建一个Excel表对象
cellStyle = new CellStyle(workbook);
excelUtils = new ExcelUtils();
HSSFSheet sheet = workbook.getSheetAt(0);// 获取第一个sheet表
Collections.sort(borrList);// 集合中借款信息按照账龄升序排序,注释掉就是不排序
int rid = 3, rid1 = 0, rid2 = 0, rid3 = 0;
rid1 = excelByAgingSort(0, 30, rid, borrList, workbook, sheet);
rid2 = excelByAgingSort(30, 60, rid1, borrList, workbook, sheet);
rid3 = excelByAgingSort(60, Integer.MAX_VALUE, rid2, borrList, workbook, sheet);
HSSFRow row = sheet.createRow(rid3++);// 新建一个空白行
setSubtotalRow("总计", rid3++, total, workbook, sheet);// 总计行
leaderSign(rid3, workbook, sheet);// 领导签字行
// 自动调节每列宽度
for (int i = 0; i < 10; i++) {
sheet.autoSizeColumn((short) i);
}
sheet.setColumnWidth(2, purposeColLength * 2 * 256);// 设置借款用途列宽度
excelUtils.exportExcel(workbook, savaPath + File.separator + "备用资金反馈表.xls");// 生成Excel
}
|
c8cfd3e0-81d1-434d-9b59-c5f1f8ba9946
| 7
|
@Override
public Room getRoomInDir(int direction)
{
if((direction<0)||(direction>=doors.length)||(amDestroyed))
return null;
Room nextRoom=rawDoors()[direction];
if(gridParent!=null)
nextRoom=gridParent.prepareGridLocale(this,nextRoom,direction);
if(nextRoom!=null)
{
nextRoom=nextRoom.prepareRoomInDir(this,direction);
if((nextRoom!=null)&&(nextRoom.amDestroyed()))
return null;
}
return nextRoom;
}
|
4c2ccbf6-1271-49cd-82b7-c45f3098a265
| 8
|
final boolean method1180(boolean flag, boolean flag1) {
int j = anInt2134;
int k = anInt2151;
int i = anInt2133;
if (flag) {
k = anInt2180;
j = anInt2171;
i = anInt2202;
}
if (i == -1) {
return true;
}
if (flag1) {
return true;
}
boolean flag2 = true;
if (!Class142_Sub27_Sub21_Sub1.aClass73_5010.method796(i, 0)) {
flag2 = false;
}
if (j != -1 && !Class142_Sub27_Sub21_Sub1.aClass73_5010.method796(j, 0)) {
flag2 = false;
}
if (k != -1 && !Class142_Sub27_Sub21_Sub1.aClass73_5010.method796(k, 0)) {
flag2 = false;
}
return flag2;
}
|
ab12508d-eaf5-41ad-b2cd-c94fff137a08
| 0
|
private void login(String[] accountinfo){
username = accountinfo[0];
System.out.println("User: " + username + " logged in");
reply("loggedin");
}
|
be03c2d6-0ee2-4f3d-a935-eafdcb07df5f
| 9
|
private LinkedList<Diff> diff_lineMode(String text1, String text2,
long deadline) {
// Scan the text on a line-by-line basis first.
LinesToCharsResult b = diff_linesToChars(text1, text2);
text1 = b.chars1;
text2 = b.chars2;
List<String> linearray = b.lineArray;
LinkedList<Diff> diffs = diff_main(text1, text2, false, deadline);
// Convert the diff back to original text.
diff_charsToLines(diffs, linearray);
// Eliminate freak matches (e.g. blank lines)
diff_cleanupSemantic(diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
diffs.add(new Diff(Operation.EQUAL, ""));
int count_delete = 0;
int count_insert = 0;
String text_delete = "";
String text_insert = "";
ListIterator<Diff> pointer = diffs.listIterator();
Diff thisDiff = pointer.next();
while (thisDiff != null) {
switch (thisDiff.operation) {
case INSERT:
count_insert++;
text_insert += thisDiff.text;
break;
case DELETE:
count_delete++;
text_delete += thisDiff.text;
break;
case EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (count_delete >= 1 && count_insert >= 1) {
// Delete the offending records and add the merged ones.
pointer.previous();
for (int j = 0; j < count_delete + count_insert; j++) {
pointer.previous();
pointer.remove();
}
for (Diff newDiff : diff_main(text_delete, text_insert, false,
deadline)) {
pointer.add(newDiff);
}
}
count_insert = 0;
count_delete = 0;
text_delete = "";
text_insert = "";
break;
}
thisDiff = pointer.hasNext() ? pointer.next() : null;
}
diffs.removeLast(); // Remove the dummy entry at the end.
return diffs;
}
|
279735bc-310c-47cf-9797-5822e669e0bd
| 0
|
public String getConcepto() {
return concepto;
}
|
485f415c-e5cf-4b36-868a-d73cbed4fe78
| 0
|
public truncate()
{
this.info = "truncate Appointment, Reminder and Venue tables";
}
|
55df91ea-e11c-4d02-ab26-199ed2308eb4
| 9
|
public void assignMuseumTickets(int day) {
// LIst to store interested clients and their respective values
List<ClientValuePair> museumInterest = new ArrayList<ClientValuePair>();
// Find each customer that could use an alligator ticket that day
for (int ii = 0; ii < 9; ii++) {
if (ii < 8) {
Client client = masterAgent.clientList.get(ii);
// If the customer could use the ticket
if (day >= client.arrivalDay && day < client.departureDay
&& client.museumStatus == itemStatus.requested
&& client.aligatorWrestlingDay != day
&& client.amusementParkDay != day) {
// add that customer to the list
ClientValuePair newPoint = new ClientValuePair(client,
client.museumValue);
museumInterest.add(newPoint);
}
} else {// Customer 8 is the open market
int auctionID = TACAgent.getAuctionFor(TACAgent.CAT_ENTERTAINMENT, TACAgent.TYPE_MUSEUM, day);
Quote currentPriceQuote = masterAgent.agent.getQuote(auctionID);
currentPriceQuote.getAskPrice();
}
}
// Sort the people with interest in the ticket, highest first
Collections.sort(museumInterest);
Collections.reverse(museumInterest);
// Assign the tickets
int museumTicketsHeld = museum[day];
int interestedParties = museumInterest.size();
for (int ii = 0; ii < Math.min(museumTicketsHeld, interestedParties); ii++) {
// If the client will pay more than the average ticket value, assign
// it to them
if (museumInterest.get(ii).client.amusementParkValue > ESTIMATED_CLOSE_PRICE) {
museumInterest.get(ii).client.museumStatus = itemStatus.purchased;
museumInterest.get(ii).client.museumDay = day;
museum[day] -= 1;
}
}
}
|
9d4ab1fb-d489-4d54-ac6f-fdc37fe28cf8
| 8
|
@Override
public boolean setWeapon(Wearable weapon) throws NoSuchItemException, WrongItemTypeException {
if (weapon != null) {
if (weapon instanceof Weapon) {
if (weapon.getLevelRequirement() > level || weapon.getStrengthRequirement() > stats[0]
|| weapon.getDexterityRequirement() > stats[1] || weapon.getMagicRequirement() > stats[2]) {
return false;
}
if (inventory.remove(weapon)) {
if (onPerson[2] != null) {
removeItem(2);
}
putOnItem(weapon, 2);
return true;
} else {
throw new NoSuchItemException();
}
}
throw new WrongItemTypeException();
} else {
removeItem(2);
return true;
}
}
|
e7d92b47-d4b1-4fca-b814-553a028b87a6
| 2
|
private boolean check()
{
if (!isSizeConsistent(root))
{
System.out.println("Size is not consistent");
return false;
}
if (!isRankConsistent(root))
{
System.out.println("Rank is not consistent");
return false;
}
return true;
}
|
4af09a5e-e55c-4440-bed0-42745d39c9b2
| 2
|
public void setGratingPitch(double pitch){
this.gratingPitch = pitch;
this.setGratingPitch = true;
if(this.setMeasurementsGrating && super.setWavelength)this.calcEffectiveRefractiveIndices();
}
|
59c23246-8f2e-4a2e-9d5b-9234dfb9efa8
| 0
|
public void setSatisfied(boolean satisfied) {
Satisfied = satisfied;
}
|
0c9b5b28-f040-4fe5-abb2-2f6ebe77e8c6
| 2
|
public static void main(String[] args) {
System.out.println("Apple price list:");
for (Apple apple : Apple.values()) {
System.out.println("\t" + apple + " costs " + apple.getPrice()
+ " cents.");
}
System.out.println("Apple ordinal values(its possiton in the list of constants):");
for (Apple apple : Apple.values()) {
System.out
.println("\t" + "[" + apple + "]" + ":" + apple.ordinal());
}
}
|
e1672083-2e87-4d15-9968-55e1c51e2003
| 1
|
public static final JsonObject createTemplateJsonFromNepticalConfiguration(final Configuration configuration){
Iterator<String> keyIter = configuration.getKeys();
JsonObject jsonModel = new JsonObject();
while(keyIter.hasNext()){
String key = keyIter.next();
appendPropertyToJsonTemplateModel(jsonModel, key, configuration);
}
return jsonModel;
}
|
cb600deb-5137-408e-a642-9aa0de080168
| 0
|
@Override
protected Void doInBackground() {
build(calculateFromScratch).display();
return null;
}
|
d011990b-e712-415c-9362-9af07abd60cb
| 2
|
private PkItem get(ConcurrentLinkedQueue<PkItem> list, int id) {
for (PkItem item : list)
if (item.id == id)
return item;
return null;
}
|
085fc698-40cc-420e-aef0-4f40bb093ca8
| 1
|
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
// Ignore static resources
if (!uri.contains(RESOURCES_URL)) {
imageService.removeOldImagesIfNecessary();
}
return true;
}
|
725a8335-b644-4fe2-9590-e955de76943a
| 2
|
public void getMouseEvent(int button) {
if (AIE != null){
AIE.getMouseEvent(button);
} else if (TE != null){
TE.getMouseEvent(button);
}
}
|
a8ba0125-1376-4764-8d7c-c270eff0ecce
| 1
|
public ClassInfo getClassInfo() {
if (classType instanceof ClassInterfacesType)
return ((ClassInterfacesType) classType).getClassInfo();
return null;
}
|
c62efaa7-df85-4f7b-877d-1f869e4f4d1c
| 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(AccountManagementView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AccountManagementView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AccountManagementView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AccountManagementView.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 AccountManagementView().setVisible(true);
}
});
}
|
31ce8fec-e730-48a7-b365-b5cdae39d92a
| 2
|
private void selectBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectBotonActionPerformed
int index = serverTable.getSelectedRow();
if(index>=0){
String server = (String)serverTable.getModel().getValueAt(index, 0);
conexion.principal.setCurrentServer(server);
serverTF.setText(server);
conexion.principal.estrategias.getServerTF().setText(server);
conexion.principal.estrategias.cargarArchivo(server+"_strategies.txt");
conexion.principal.estrategias.filtrarEstrategias();
conexion.principal.estrategias.cargarTabla();
conexion.principal.getTabPanel().setEnabledAt(1,true);
}
if(currentCheck.isSelected()){
conexion.principal.setCurrentServer(conexion.db);
serverTF.setText(conexion.db);
conexion.principal.estrategias.getServerTF().setText(conexion.db);
conexion.principal.estrategias.cargarArchivo(conexion.db+"_strategies.txt");
conexion.principal.estrategias.filtrarEstrategias();
conexion.principal.estrategias.cargarTabla();
conexion.principal.getTabPanel().setEnabledAt(1,true);
}
}//GEN-LAST:event_selectBotonActionPerformed
|
64f42a5f-8ee4-4b36-98b1-eb7e2f0c924f
| 8
|
@SuppressWarnings("unchecked")
protected static String[] split(String str, String sep) {
if (str == null) {
throw new NullPointerException("str");
}
if (sep == null) {
throw new NullPointerException("sep");
}
Vector l = new Vector();
int beginIndex = str.indexOf(sep);
String part;
while (beginIndex >= 0) {
if (beginIndex == 0) {
str = str.substring(beginIndex + sep.length());
} else
if (beginIndex > 0) {
part = str.substring(0, beginIndex);
if (part.length() != 0) {
l.add(part);
}
str = str.substring(beginIndex + sep.length());
}
beginIndex = str.indexOf(sep);
}
part = str;
if (part.length() != 0) {
l.add(part);
}
String[] aa = new String[l.size()];
for (int i = 0; i < l.size(); i++) {
aa[i] = (String) l.elementAt(i);
}
return aa;
}
|
959ae224-07cd-43f6-80b2-de6ef30e348c
| 6
|
public ModelAndView login(Usuario usuario, UsuarioDAO usuarioDAO) {
feedbacks.clear();
ModelAndView mav = new ModelAndView();
String retorno;
Usuario usuarioDB = usuario.existe(usuarioDAO);
if (isLogado() || usuarioDB != null) {
this.usuario = usuarioDB;
retorno = getPaginaDeRetorno();
} else {
String login = usuario.getLogin();
String senha = usuario.getSenha();
if ((login != null && !login.isEmpty())
|| (senha != null && !senha.isEmpty())) {
feedbacks.add("Login ou senha incorretos.");
mav.addObject("feedbacks", feedbacks);
}
retorno = getPaginaDeLogin();
}
mav.setViewName(retorno);
finaliza(mav);
return mav;
}
|
d96f1601-b8d4-47ba-b4b5-4491666a84c9
| 2
|
public IdentificadorVariavelRegistro(String nome, int deslocamento,
Collection<IdentificadorVariavelCampoRegistro> listaCampos) {
super(nome, deslocamento, Tipo.REGISTRO);
this.listaCampos = new HashMap<String, IdentificadorVariavelCampoRegistro>();
if(listaCampos != null)
for(IdentificadorVariavelCampoRegistro campo : listaCampos)
this.listaCampos.put(campo.getNome(), campo);
}
|
a5da5f01-f8e8-4138-b850-3d1264008de1
| 6
|
public static void main(String[] args)throws Exception {
//no parameter
Class noparams[] = {};
//String parameter
Class[] paramString = new Class[1];
paramString[0] = String.class;
//int parameter
Class[] paramInt = new Class[1];
paramInt[0] = Integer.TYPE;
try{
//load the AppTest at runtime
Class cls = Class.forName("corejava.reflection.AppTest");
Object obj = cls.newInstance();
//call the printIt method
Method method = cls.getDeclaredMethod("printIt", noparams);
method.invoke(obj, null);
//call the printItString method, pass a String param
method = cls.getDeclaredMethod("printItString", paramString);
method.invoke(obj, new String("Atul"));
//call the printItInt method, pass a int param
method = cls.getDeclaredMethod("printItInt", paramInt);
method.invoke(obj, 123);
//call the setCounter method, pass a int param
try {
method = cls.getDeclaredMethod("setCounter", paramInt);
method.setAccessible(true);
method.invoke(obj, 100);
}
catch(NoSuchMethodException e){
e.printStackTrace();
}
catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e) {
// TODO: handle exception
e.printStackTrace();
}
catch (InvocationTargetException e) {
// TODO: handle exception
e.printStackTrace();
}
catch (IllegalArgumentException e) {
// TODO: handle exception
e.printStackTrace();
}
//call the printCounter method
method = cls.getDeclaredMethod("printCounter", noparams);
method.invoke(obj, null);
}catch(Exception ex){
ex.printStackTrace();
}
}
|
1732f262-f46d-4729-bc1c-b5adbf25bcea
| 6
|
private void findNN(Node node, ResultSet resultSet, double[] query,
int[] checks, int maxChecks, PriorityQueue<Branch<Node>> heap) {
// Pruning. Ignore those clusters that are too far away -----
double bsq = metric.distance(query, node.pivot);
double rsq = node.radius;
double wsq = resultSet.worstDistance();
double val = bsq - rsq - wsq;
double val2 = val * val - 4 * rsq * wsq;
if (val > 0 && val2 > 0) {
return;
}
// ----------------------------------------------------------
// Terminal node.
if (node.children.isEmpty()) {
if (checks[0] >= maxChecks && resultSet.full())
return;
for (int i = 0; i < node.size; i++) {
PointInfo pointInfo = node.points.get(i);
int index = pointInfo.index;
double dist = metric.distance(pointInfo.point, query);
resultSet.addPoint(dist, index);
checks[0]++;
}
}
// Internal node.
else {
int closestCenter = exploreNodeBranches(node, query, heap);
findNN(node.children.get(closestCenter), resultSet, query, checks,
maxChecks, heap);
}
}
|
36e20fc5-5dd3-4841-a08d-45574cb8cb6d
| 6
|
public ArrayList<String> getArticleList() throws IOException {
ArrayList<String> articleList = new ArrayList<String>();
for (String pageUrl : pageList) {
String html = "error";
for (int i = 0; i < 5 && html.equals("error"); i++) {
System.out.print("in Board....."+pageUrl);
html = new GetHTML().getHtml(pageUrl, "UTF-8"); //方法内有标签检测装置
}
if(!html.equals("error")){
Document document = Jsoup.parse(html);
Elements elements = document.select("li.list");
for(Element el:elements){
String articleUrl = el.select("a").attr("href");
if(articleUrl.length()>0){
MyLog.logINFO("addURL:"+articleUrl);
articleList.add(articleUrl);
}
}
}
}
return articleList;
}
|
154de62e-af69-4d3c-9be6-9102561f6def
| 0
|
public int getCrawlStyle() {
return crawlStyle;
}
|
62ccc632-1e59-4466-a8be-3b8d82b56ff4
| 4
|
public TreeMap<TimeStamp, ArrayList<TileEntry>> getUsageEventMap() {
TreeMap<TimeStamp, ArrayList<TileEntry>> map = new TreeMap<>();
for (ArrayList<TileEntry> tiles : knownTiles.values())
for (TileEntry tile : tiles) {
for (TimeStamp usageEvent : tile.usages.getNonNullEventIndices()) {
if (!map.containsKey(usageEvent))
map.put(usageEvent, new ArrayList<>());
map.get(usageEvent).add(tile);
}
}
return map;
}
|
7f543a6b-2bfe-4d42-a50a-fda131e82ec3
| 2
|
public static void main(String[] args) {
ArrayList apples = new ArrayList();
for (int i = 0; i < 3; i++)
apples.add(new Apple());
// Not prevented from adding an Orange to apples:
apples.add(new Orange());
for (int i = 0; i < apples.size(); i++)
((Apple) apples.get(i)).id();
// Orange is detected only at run time
}
|
0e86f717-9ac0-4404-bd44-487151d50893
| 4
|
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
directionX = -1;
}
if (key == KeyEvent.VK_RIGHT) {
directionX = 1;
}
if (key == KeyEvent.VK_UP) {
directionY = -1;
}
if (key == KeyEvent.VK_DOWN) {
directionY = 1;
}
}
|
1f3659dd-34f2-4a15-aff2-5f86ac9fa1d0
| 0
|
public static void startUpdater(int time) {
Thread t = new Thread(new Updater(time));
t.start();
}
|
38f91a3d-b9bd-44ec-afad-f7d93dfd11ed
| 3
|
@Override
public void ejecutar(Stack<Valor> st, MemoriaDatos md, Cp cp)
throws Exception {
if (st.isEmpty())
throw new Exception("IR_V: pila vacia");
Valor op = st.pop();
if (op instanceof Booleano) {
if ((boolean) op.getValor())
cp.set((int) pd.getValor());
else
cp.incr();
}
else
throw new Exception("IR_V: operando no booleano");
}
|
ec00c939-4f91-4a0a-be55-dbf4537c2a58
| 6
|
@Override
public void mouseClicked(MouseEvent e) {
if (token == ' ') {
this.token = turn;
this.repaint();
if (winGame()) {
jlblStatus.setText(turn + " wins the game.");
removeListeners();
} else if (drawGame()) {
jlblStatus.setText("Draw game, reset to play again.");
} else {
if (turn == 'X') {
turn = 'O';
jlblStatus.setText(turn + "'s turn");
} else if (turn == 'O') {
turn = 'X';
jlblStatus.setText(turn + "'s turn");
}
if (turn == com) {
comTurn();
}
}
}
}
|
1fbe4202-5369-4a6b-8082-e77974054e5f
| 5
|
public final void method23(int i, int i_0_) {
if (i != 15959)
anInt8516 = -78;
anInt8516 = ((Class68) aClass68_8518).anInt1178 * i_0_;
if (anInt8521 < anInt8516) {
int i_1_ = 8;
int i_2_;
if (aBoolean8519) {
i_1_ |= 0x200;
i_2_ = 0;
} else
i_2_ = 1;
if (null != ((Class142) this).anIDirect3DIndexBuffer8517)
((Class142) this).anIDirect3DIndexBuffer8517.a(9275);
((Class142) this).anIDirect3DIndexBuffer8517
= (((DirectxToolkit) aClass378_8515).anIDirect3DDevice9810.a
(anInt8516, i_1_,
aClass68_8518 != Class68.aClass68_1184 ? 102 : 101, i_2_,
((Class142) this).anIDirect3DIndexBuffer8517));
anInt8521 = anInt8516;
}
}
|
5ee98f29-a11b-4865-a8e6-c9cbf382e932
| 9
|
boolean checkTrigger () {
int forwardGrab=0,backwardGrab=0;
// Description
String description=descriptionField.getText();
if ((description==null)||(description.length()<1)) {
JOptionPane.showMessageDialog(null,"You must enter a description for a trigger","Rivet", JOptionPane.INFORMATION_MESSAGE);
return false;
}
// Sequence
String sequence=sequenceField.getText();
if ((sequence==null)||(sequence.length()<4)) {
JOptionPane.showMessageDialog(null,"You must enter a binary sequence of 3 or more bits for a valid trigger","Rivet", JOptionPane.INFORMATION_MESSAGE);
return false;
}
// Only need to get the forward and backward values if the trigger is a grab
int triggerType=triggerTypeCombo.getSelectedIndex()+1;
if (triggerType==3) {
// Forward grab
String forward=forwardGrabField.getText();
try {
forwardGrab=Integer.parseInt(forward);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"A Grab Trigger must have a numeric forward grab value","Rivet", JOptionPane.INFORMATION_MESSAGE);
return false;
}
// Check the forward value is positive
if (forwardGrab<0) {
JOptionPane.showMessageDialog(null,"A Grab Trigger must not contain a negative numeric forward grab value","Rivet", JOptionPane.INFORMATION_MESSAGE);
return false;
}
// Backward grab
String backward=backwardGrabField.getText();
try {
backwardGrab=Integer.parseInt(backward);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"A Grab Trigger must have a numeric backward grab value","Rivet", JOptionPane.INFORMATION_MESSAGE);
return false;
}
// Check the forward value is positive
if (backwardGrab<0) {
JOptionPane.showMessageDialog(null,"A Grab Trigger must not contain a negative numeric backward grab value","Rivet", JOptionPane.INFORMATION_MESSAGE);
return false;
}
}
// Populate the trigger object
trigger.setTriggerDescription(description);
trigger.setTriggerSequence(sequence);
trigger.setTriggerType(triggerType);
trigger.setForwardGrab(forwardGrab);
trigger.setBackwardGrab(backwardGrab);
// All done
return true;
}
|
c1b5cdf9-4623-40ec-b7b1-2c460256813a
| 2
|
public void inserirLinkTratado(Produto pProduto)
{
StringBuilder sb = new StringBuilder();
ConexaoMySql cn = new ConexaoMySql();
sb.append("Insert Into etl_link_tratado "
+ "(Loja_Cliente_Id, Produto_Nome, Produto_Preco, Produto_Foto_URL, Produto_Descricao) "
+ "Values (");
sb.append(pProduto.getId());
sb.append(",");
sb.append("'");
sb.append(pProduto.getNomeProduto());
sb.append("' ,");
sb.append("'");
sb.append(pProduto.getPrecoProduto());
sb.append("' ,");
sb.append("'");
sb.append(pProduto.getFotoProduto());
sb.append("' ,");
sb.append("'");
sb.append(pProduto.getDescricaoProduto());
sb.append("');");
try {
cn.executarComando(sb.toString());
}
catch (SQLException e) {
//Não conseguindo se conectar ao banco
System.out.println("Nao foi possivel conectar ao Banco de Dados.");
}
catch(Exception ex){
System.out.println("Problemas para execuar inserção dos dados");
System.out.println(ex.getMessage());
}
finally{
cn.FecharConexao();
}
}
|
76b414f2-54f4-4461-b2ce-132f38b8ea70
| 1
|
public boolean confirm() {
int n = JOptionPane.showConfirmDialog(this,
srcname+"想要傳送檔案"+filename+"(大小"+filesize+"bytes),是否接收?",
"傳送檔案確認", JOptionPane.YES_NO_OPTION);
if( n==JOptionPane.YES_OPTION ) return true;
else return false;
}
|
aed41ea0-518f-46ae-b27f-706d6430a20a
| 9
|
public static Object add(Object v1, Object v2)
{
int type = getNumericType(v1, v2, true);
switch(type) {
case BIGINT:
return bigIntValue(v1).add(bigIntValue(v2));
case BIGDEC:
return bigDecValue(v1).add(bigDecValue(v2));
case FLOAT:
case DOUBLE:
return newReal(type, doubleValue(v1) + doubleValue(v2));
case NONNUMERIC:
int t1 = getNumericType(v1),
t2 = getNumericType(v2);
if (((t1 != NONNUMERIC) && (v2 == null)) || ((t2 != NONNUMERIC) && (v1 == null))) {
throw new NullPointerException("Can't add values " + v1 + " , " + v2);
}
return stringValue(v1) + stringValue(v2);
default:
return newInteger(type, longValue(v1) + longValue(v2));
}
}
|
44b8b685-84db-4ef2-bbf6-1201cf892197
| 4
|
public double rawPersonStandardDeviation(int index){
if(!this.dataPreprocessed)this.preprocessData();
if(index<1 || index>this.nPersons)throw new IllegalArgumentException("The person index, " + index + ", must lie between 1 and the number of persons," + this.nPersons + ", inclusive");
if(!this.variancesCalculated)this.meansAndVariances();
return this.rawPersonStandardDeviations[index-1];
}
|
8cec2809-d630-4074-9c4b-8847957dae12
| 7
|
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(TicketMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TicketMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TicketMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TicketMainFrame.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() {
try {
new TicketMainFrame(new CancelaFachada()).setVisible(true);
} catch (CancelaDAOException ex) {
Logger.getLogger(TicketMainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
|
32eec270-7058-47b2-b7c2-942ed26c3b05
| 3
|
public char nextClean() throws JSONException {
for (;;) {
char c = this.next();
if (c == 0 || c > ' ') {
return c;
}
}
}
|
4514e0c1-1e83-441f-a52b-e4ac3ba7c398
| 6
|
private void listSeries() {
Logger.getLogger(MainInterface.class.getName()).entering(MainInterface.class.getName(), "listSeries");
previewComponent.setNoPreviewImage();
Thread listSeriesThread = new Thread(() -> {
Logger.getLogger(MainInterface.class.getName()).log(Level.INFO, "Refreshing the serie list");
try {
serie = null;
album = null;
final DefaultTableModel seriesTableModel = (DefaultTableModel) seriesTable.getModel();
final DefaultTableModel albumsTableModel = (DefaultTableModel) albumsTable.getModel();
try {
SwingUtilities.invokeAndWait(() -> {
seriesTableModel.setRowCount(0);
albumsTableModel.setRowCount(0);
});
} catch (InterruptedException | InvocationTargetException ex) {
Logger.getLogger(MainInterface.class.getName()).log(Level.SEVERE, null, ex);
}
Object[][] seriesData = new BooksFolderAnalyser(booksDirectory).listSeries();
if (seriesData == null) {
Logger.getLogger(MainInterface.class.getName()).log(Level.WARNING, "The profile folder doesn't exist or can't be read : {0}", booksDirectory);
firstLaunch = false;
setActionInProgress(false, null);
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "listSeries");
return;
}
for (final Object[] serieData : seriesData) {
Thread tampon = new Thread(() -> {
seriesTableModel.addRow(new Object[]{serieData[0], serieData[1]});
});
try {
SwingUtilities.invokeAndWait(tampon);
} catch (InterruptedException | InvocationTargetException ex) {
Logger.getLogger(MainInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
firstLaunch = false;
} catch (Exception ex) {
Logger.getLogger(MainInterface.class.getName()).log(Level.SEVERE, "Unknown exception", ex);
new InfoInterface(InfoInterface.InfoLevel.ERROR, "unknown");
}
setActionInProgress(false, null);
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "listSeries");
});
setActionInProgress(true, listSeriesThread);
if (SwingUtilities.isEventDispatchThread()) {
listSeriesThread.start();
}
else {
listSeriesThread.run();
}
}
|
306722c5-f13a-469f-a996-99535fcb8d8d
| 9
|
public int calculate(int player,int moveType, int newVal, ArrayList<Field> pole)
{
this.moveable = 0;
this.player = player;
this.moveType = moveType;
this.pole = pole;
this.newVal = newVal;
moveEnable(pole,player,newVal); // vypocet moznosti tahu
if(moveable == 0)
return this.moveable;
switch(moveType)
{
case 0:
defRun();
break;
case 1:
longRun();
break;
case 2:
if(!newRun())
{
longRun();
}
break;
case 3:
if(!killRun())
{
longRun();
}
break;
case 4:
if(!homeRun())
{
longRun();
}
break;
}
return this.moveable;
}
|
a8e3b56f-ea83-4e54-8db8-3d415aa8c79c
| 5
|
public Object showStudentScoreList(String couId) {
String command = "show;course_student_list;" + couId;
ArrayList<String> list = null;
String[][] content = null;
try {
NetService client = initNetService();
client.sendCommand(command);
list = client.receiveList();
content = new String[list.size()][];
for (int i = 0; i < list.size(); i++) {
content[i] = list.get(i).split(";");
}
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content[i].length; j++) {
if (content[i][j].equals("-1")) {
content[i][j] = "";
}
}
}
client.shutDownConnection();
} catch (Exception e) {
e.printStackTrace();
return Feedback.INTERNET_ERROR;
}
return content;
}
|
352cb400-935a-451b-b0e7-17bd09905a54
| 1
|
public void addToConsole(String data) {
try {
Document doc = textPane.getDocument();
doc.insertString(doc.getLength(), data + "\n", null);
textPane.select(doc.getLength() - 1, doc.getLength() - 1);
} catch (Exception ex) {
}
}
|
8d0057c0-c94f-4ff5-9844-1b3b7b69b2d8
| 0
|
public MediaConfModel getMediaConfModel () {
MediaConfModel mediaConf = new MediaConfModel();
JsonNode node = rootNode.get("Media");
mediaConf.setExecute(node.get("execute").getBooleanValue());
return mediaConf;
}
|
5c4ffe68-0fd8-40c9-b180-43d69505e84c
| 8
|
public static void createAbilitySet(ConfigurationSection cfg)
{
// If there are no options return
if (cfg == null)
return;
// Fetch the Sets name from the map
String name = cfg.getName();
// If no name is given return
if (name == null)
{
MMComponent.getAbilities().warning("Must provide a name for every AbilitySet");
return;
}
// If the name already exists return
if (abilitySets.containsKey(name.toLowerCase()))
{
MMComponent.getAbilities().warning("AbilitySet with name " + name + " already exists");
return;
}
// Fetch the default mob type if it exists
ExtendedEntityType entityType = null;
if (cfg.contains("MobType"))
{
String key = cfg.getString("MobType");
if (key != null)
entityType = ExtendedEntityType.valueOf(key);
// Make sure the config is more specific
if (entityType == ExtendedEntityType.UNKNOWN)
{
entityType = null;
}
if (entityType == null)
{
MMComponent.getAbilities().warning("Invalid EntityType " + key + " in AbilitySets");
}
}
boolean protectFromDespawner = cfg.getBoolean("ProtectFromDespawner", false);
boolean applyNormalAbilities = cfg.getBoolean("ApplyNormalAbilities", false);
ConfigurationSection abilities = cfg.getConfigurationSection("Abilities");
if (abilities == null)
abilities = cfg.createSection("Abilities");
MobAbilityConfig setCfg = new MobAbilityConfig(name, entityType, abilities);
// Create the ability set
new AbilitySet(name.toLowerCase(), setCfg, entityType, protectFromDespawner, applyNormalAbilities);
}
|
45f11e28-18b6-49cb-90f6-abcbef3ea778
| 0
|
public double getPrice() {
return price;
}
|
386809af-3cdd-4e83-bb30-b717e517afbc
| 7
|
public void fusionWithOverlayFullAlpha(CPLayer fusion, CPRect rc) {
CPRect rect = new CPRect(0, 0, width, height);
rect.clip(rc);
for (int j = rect.top; j < rect.bottom; j++) {
int off = rect.left + j * width;
for (int i = rect.left; i < rect.right; i++, off++) {
int color1 = data[off];
int alpha1 = (color1 >>> 24) * alpha / 100;
if (alpha1 == 0) {
continue;
}
int color2 = fusion.data[off];
int alpha2 = (color2 >>> 24) * fusion.alpha / 100;
int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;
if (newAlpha > 0) {
int alpha12 = alpha1 * alpha2 / 255;
int alpha1n2 = alpha1 * (alpha2 ^ 0xff) / 255;
int alphan12 = (alpha1 ^ 0xff) * alpha2 / 255;
int color = newAlpha << 24;
int c1, c2;
c1 = (color1 >>> 16 & 0xff);
c2 = (color2 >>> 16 & 0xff);
color |= (alpha1n2 * c1 + alphan12 * c2 + ((c2 <= 127) ? (alpha12 * 2 * c1 * c2 / 255)
: (alpha12 * ((2 * (c1 ^ 0xff) * (c2 ^ 0xff) / 255) ^ 0xff))))
/ newAlpha << 16;
c1 = (color1 >>> 8 & 0xff);
c2 = (color2 >>> 8 & 0xff);
color |= (alpha1n2 * c1 + alphan12 * c2 + ((c2 <= 127) ? (alpha12 * 2 * c1 * c2 / 255)
: (alpha12 * ((2 * (c1 ^ 0xff) * (c2 ^ 0xff) / 255) ^ 0xff))))
/ newAlpha << 8;
c1 = color1 & 0xff;
c2 = color2 & 0xff;
color |= (alpha1n2 * c1 + alphan12 * c2 + ((c2 <= 127) ? (alpha12 * 2 * c1 * c2 / 255)
: (alpha12 * ((2 * (c1 ^ 0xff) * (c2 ^ 0xff) / 255) ^ 0xff))))
/ newAlpha;
fusion.data[off] = color;
}
}
}
fusion.alpha = 100;
}
|
c85399a9-2aea-4b73-9dc8-9dabc03075ce
| 8
|
public static void main(String args[]){
CMS cms = new CMS();
Scanner sc = new Scanner(System.in);
//sc.useDelimiter(System.getProperty("line.separator"));
int R = 0;
do{
try {
System.out.println("\n1. Agregar Autor");
System.out.println("2. Crear Articulo");
System.out.println("3. Blog");
System.out.println("4. Leer Articulo");
System.out.println("5. Salir");
System.out.println(" Seleccion: ");
R = sc.nextInt();
switch(R){
case 1:
int c;
System.out.println("Codigo del Autor: ");
c = sc.nextInt();
System.out.println("Nombre del Autor: ");
if( cms.agregarAutor(c, sc.next()) )
System.out.println("Agregado con Exito");
else
System.out.println("Fallo Agregar Autor");
break;
case 2:
System.out.println("Titulo del Articulo: ");
String titulo = sc.next();
System.out.println("Contenido");
String contenido = sc.next();
if( cms.crearArticulo(titulo, contenido) )
System.out.println("Articulo creado con Exito");
else
System.out.println("No se pudo Crear");
break;
case 3:
cms.blog();
break;
case 4:
System.out.println("Codigo del Articulo: ");
cms.leerArticulo(sc.nextInt());
}
} catch (IOException ex) {
System.out.println("Error. "+ex.getMessage());
}
}while(R!=5);
}
|
f6b7f4d6-cb1d-49a3-8083-64b3a6d7d34a
| 7
|
protected static boolean compareBiomesById(final int p_151616_0_, final int p_151616_1_)
{
if (p_151616_0_ == p_151616_1_)
{
return true;
}
else if (p_151616_0_ != BiomeGenBase.mesaPlateau_F.biomeID && p_151616_0_ != BiomeGenBase.mesaPlateau.biomeID)
{
try
{
return BiomeGenBase.getBiome(p_151616_0_) != null && BiomeGenBase.getBiome(p_151616_1_) != null ? BiomeGenBase.getBiome(p_151616_0_).equals(BiomeGenBase.getBiome(p_151616_1_)) : false;
}
catch (Throwable throwable)
{
throw new RuntimeException(throwable);
}
}
else
{
return p_151616_1_ == BiomeGenBase.mesaPlateau_F.biomeID || p_151616_1_ == BiomeGenBase.mesaPlateau.biomeID;
}
}
|
01187714-68f8-4bb9-ae2f-ce02496df478
| 0
|
public FireHeadArmor() {
this.name = Constants.FIRE_HEAD_ARMOR;
this.defenseScore = 11;
this.money = 350;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.