text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void calcular(boolean diagonales)
{
nodosEvaluados= new HashSet<>(); //set de nodos evaluados
PriorityQueue<Nodo> nodosPorEvaluar = new PriorityQueue<>();//set de nodos por evaluar, contiene inicialmente al nodo inicial
inicio.setFuncionG(0); //costo desde el inicio hasta el mejor camino conocido
inicio.setFuncionHeursitica(calcularHeuristica(inicio, destino,diagonales));
nodosPorEvaluar.add(inicio);
int contadorIteraciones=0;
while (!nodosPorEvaluar.isEmpty()) {
Nodo actual = nodosPorEvaluar.poll();//obtener el nodo con menor funcion f
if (actual.equals(destino))
{
System.out.println("Iteraciones totales-> " + contadorIteraciones);
System.out.println("Costo Total-> " + actual.getFuncionG()+actual.getFuncionHeursitica());
reconstruirCamino(actual);
break;
}
System.out.println("nodos por evaluar (frontera)"+ contadorIteraciones);
System.out.println(nodosPorEvaluar);
System.out.println("nodos evaluados");
System.out.println(nodosEvaluados);
nodosPorEvaluar.remove(actual);
nodosEvaluados.add(actual);
for (Nodo adyacente : actual.getNodosAdyacente(diagonales)) {
/************************************
int contN = 0;
int diagonalN = arregloDiagonales.indexOf(contN);
adyacente.setDistribuicion(diagonalN);
contN++;
***********************************/
boolean adyacenteIsMejor;
if (nodosEvaluados.contains(adyacente))
continue; //se salta una iteracion
if (!adyacente.isObstaculo()) {
double nuevoCosto = actual.getFuncionG() + getDistanciaEntre(actual, adyacente);
if (!nodosPorEvaluar.contains(adyacente)){
//Collections.sort(nodosPorEvaluar);
//equivale a cambiar la prioridad a una cola
nodosPorEvaluar.add(adyacente);
adyacenteIsMejor = true;
}
else if (nuevoCosto < adyacente.getFuncionG())
adyacenteIsMejor = true;
else{
adyacenteIsMejor =false;
//nodosPorEvaluar.remove(adyacente);
}
if (adyacenteIsMejor){
adyacente.setRaiz(actual); //añadir el camino
//System.out.println("n: " + nuevoCosto);
adyacente.setFuncionG(nuevoCosto);
adyacente.setFuncionHeursitica(calcularHeuristica(adyacente, destino,diagonales));
}
}
}//cierra for adyacente
contadorIteraciones++;
}//cierra while
}//cierra calcular | 8 |
public void initUndoKeeper(){
myKeeper = new UndoKeeper(getAutomaton());
} | 0 |
@Override
public DisplayState getDisplayState() {
File stateFile = new File(directory, ".displaystate");
if(stateFile.exists())
try {
return (DisplayState)DisplayState.deSerialize(stateFile.getPath());
} catch (IOException ex) {
Logger.getLogger(LocalStudy.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (ClassNotFoundException ex) {
Logger.getLogger(LocalStudy.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
else
return null;
} | 3 |
private static void drawCircle(double x, double y, double radius){
//filled circle
double x1,y1,x2,y2;
double angle;
GL11.glColor3f(0.7f, 0.7f, 0.7f);
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
GL11.glVertex2d(x,y);
for (angle=1.0f;angle<361.0f;angle+=0.2)
{
x2 = x+Math.sin(angle)*radius;
y2 = y+Math.cos(angle)*radius;
GL11.glVertex2d(x2,y2);
}
GL11.glEnd();
} | 1 |
public String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int i = 0; i < b.length; i++) {
stmp = Integer.toHexString(b[i] & 0xFF);
if (stmp.length() == 1) {
hs += "0" + stmp;
}
else {
hs += stmp;
}
}
return hs.toUpperCase();
} | 2 |
public void enqueueMessage(int queueId, Message message) throws MessageEnqueueException, MessageEnqueueSenderDoesNotExistException, MessageEnqueueQueueDoesNotExistException {
try {
_out.writeInt(20 + message.getMessage().getBytes().length); //Size
_out.writeInt(Response.MSG_QUEUE_ENQUEUE);
_out.writeInt(_clientId); //Sender
_out.writeInt(message.getReceiver()); //Receiver
_out.writeInt(queueId); //Queue
_out.writeInt(message.getMessage().getBytes().length);
_out.write(message.getMessage().getBytes());
_out.flush();
int messageType = _in.readInt();
if(messageType != Response.STATUS_OK) {
int errorCode = _in.readInt();
if(errorCode == Response.ERR_MESSAGE_ENQUEUE_EXCEPTION) {
throw new MessageEnqueueException(new Exception());
} else if(errorCode == Response.ERR_SENDER_DOES_NOT_EXIST_EXCEPTION) {
throw new MessageEnqueueSenderDoesNotExistException(new Exception());
} else if(errorCode == Response.ERR_QUEUE_DOES_NOT_EXIST_EXCEPTION) {
throw new MessageEnqueueQueueDoesNotExistException(new Exception());
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} | 5 |
@Override
public String makeMove(CardGame game, CardPanel panel) {
List<List<Card>> board = game.getBoard();
List<Card> pack = game.getPack();
Stack<Card> deck = game.getDeck();
game.setCanAddToDeckFromBoard(false);
for (int j = 0; j < 12; j++) {
//Want them all unrevealed
board.get(j).add(pack.remove(0));
CardGame.repaintWhileDealing(panel);
}
//Get the user to check for adding to the deck
game.setCanAddToDeckFromBoard(true);
String msg = pack.size() == 2 ? "Hit Enter/click the pack to finish dealing" : "Hit Enter/click the pack to continue dealing";
panel.storeMessage(new RenderMessage(msg, false));
CardGame.repaintWhileDealing(panel);
game.waitForNextDealConfirmation();
// if (deck.size() == board.get(0).size() - 1) {
//Only add to the deck if they didn't undo.
deck.push(pack.remove(0));
if (pack.size() == 1) {
deck.push(pack.remove(0));
}
// }
System.out.println("DECK ADDED: " + deck);
CardGame.repaintWhileDealing(panel);
System.out.println("PACK:" + pack);
System.out.println("---------------------------");
return "";
} | 3 |
public String getRunButtonImageName() {
if(Configuration.handleEmptyEventQueue && Configuration.asynchronousMode) {
if(appConfig.guiRunOperationIsLimited) {
return "refillrun.gif";
} else {
return "refillrunforever.gif";
}
} else {
if(appConfig.guiRunOperationIsLimited) {
return "run.gif";
} else {
return "runforever.gif";
}
}
} | 4 |
static public Spell getLightningSpell(int i)
{
switch (i)
{
default:
case 0:
return new Lightning();
case 1:
return new LightningStorm();
case 2:
return new LightningBall();
case 3:
return new LightningMine();
case 5:
return new LightningRod();
case 6:
return new LightningShield();
case 7:
return new LightningOvercharge();
}
} | 7 |
@Override
public boolean createUser(String login, String password, String firstName, String lastName, String passportInfo) {
//заполнение sql скрипта
Map<String, Object> pageVariables = dataToKey(new String [] { "login", "password", "firstName", "lastName", "passportInfo" },
login, password, firstName, lastName, passportInfo);
try {
if (!this.checkIsUserExist(login))
{
if (execUpdate(this.connect, generateSQL("create_user.sql", pageVariables)) == 1)
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
} | 3 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mediaName == null) ? 0 : mediaName.hashCode());
result = prime * result + ((date == null) ? 0 : date.get(Calendar.MONTH));
result = prime * result + ((date == null) ? 0 : date.get(Calendar.YEAR));
result = prime * result + ((artName == null) ? 0 : artName.hashCode());
return result;
} | 4 |
private void doHandshake() throws IOException
{
// C0
byte C0 = 0x03;
out.write(C0);
// C1
long timestampC1 = System.currentTimeMillis();
byte[] randC1 = new byte[1528];
rand.nextBytes(randC1);
out.writeInt((int)timestampC1);
out.writeInt(0);
out.write(randC1, 0, 1528);
out.flush();
// S0
byte S0 = (byte)in.read();
if (S0 != 0x03)
throw new IOException("Server returned incorrect version in handshake: " + S0);
// S1
byte[] S1 = new byte[1536];
in.read(S1, 0, 1536);
// C2
long timestampS1 = System.currentTimeMillis();
out.write(S1, 0, 4);
out.writeInt((int)timestampS1);
out.write(S1, 8, 1528);
out.flush();
// S2
byte[] S2 = new byte[1536];
in.read(S2, 0, 1536);
// Validate handshake
boolean valid = true;
for (int i = 8; i < 1536; i++)
{
if (randC1[i - 8] != S2[i])
{
valid = false;
break;
}
}
if (!valid)
throw new IOException("Server returned invalid handshake");
} | 4 |
public void run(String arg) {
if (IJ.versionLessThan("1.37f")) return;
int[] wList = WindowManager.getIDList();
// 1 - Obtain the currently active image if necessary:
// 2 - Ask for parameters:
boolean whiteParticles =Prefs.blackBackground, connect4=false;
GenericDialog gd = new GenericDialog("Binary Label");
gd.addMessage("Binary Label v 1.0");
gd.addCheckbox("White particles on black background", whiteParticles);
gd.addCheckbox("4 connected", false);
gd.showDialog();
if (gd.wasCanceled()) return
;
// 3 - Retrieve parameters from the dialog
whiteParticles = gd.getNextBoolean();
connect4 = gd.getNextBoolean();
ImagePlus imp1 = WindowManager.getCurrentImage();
//if (imp1.getStackSize()>1 || imp2.getStackSize()>1) {
// IJ.showMessage("Error", "Stacks not supported");
// return;
//}
if (imp1.getBitDepth()!=8 ) {
IJ.showMessage("Error", "Only 8-bit images are supported");
return;
}
ImageStatistics stats;
// Check images are binary. You must check this before calling the exec method.
//
stats = imp1.getStatistics();
if (stats.histogram[0] + stats.histogram[255] != stats.pixelCount){
IJ.error("8-bit binary mask image (0 and 255) required.");
return;
}
String name = "Labelled";
// 4 - Execute!
Object[] result = exec(imp1, name, whiteParticles, connect4);
// 5 - If all went well, show the image:
if (null != result) {
ImagePlus resultImage = (ImagePlus) result[1];
resultImage.show();
//IJ.log(""+result[2]);
}
} | 5 |
@Override
public void setValueAt(Object value, int row, int column) {
Variable variableToChange = variableList.get(row);
if (column == 1) {
variableToChange.setReplacementName((String)value);
} else if (column == 2) {
variableToChange.setObfuscate((Boolean)value);
}
} | 2 |
public boolean start() {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
IJobProcessingService stub = (IJobProcessingService) UnicastRemoteObject
.exportObject(this, 0);
// LocateRegistry.getRegistry(JobUtility.getPort());
registry = LocateRegistry.getRegistry(JobUtility.getPort());
registry.rebind(serverName, stub);
System.out.println(serverName + " bound");
IDispatcherService dispatcher = (IDispatcherService) registry
.lookup(JobUtility.getDispatcherExecutionName());
dispatcher.register(serverName);
return true;
} catch (RemoteException e) {
System.err.println("Failed to start service: " + e.getMessage());
try {
shutDown();
} catch (RemoteException e1) {
// bad luck
}
return false;
} catch (NotBoundException e) {
System.err.println("Failed to connect to dispatcher: "
+ e.getMessage());
try {
shutDown();
} catch (RemoteException e1) {
// bad luck
}
return false;
}
} | 5 |
public void update(GameContainer gcan, StateBasedGame state, int dtime) throws SlickException
{
a.update();
b.update();
c.update();
d.update();
e.update();
f.update();
gb.update();
if(b.activated())
{
SessionSettings.ingame = true;
state.enterState(1, new FadeOutTransition(Color.black, 250), new FadeInTransition(Color.black, 250));
}
if(c.activated())
state.enterState(2, new FadeOutTransition(Color.black, 250), new FadeInTransition(Color.black, 250));
if(d.activated())
state.enterState(3, new FadeOutTransition(Color.black, 250), new FadeInTransition(Color.black, 250));
if(e.activated())
try {
Thread.sleep(1000);
FileOps.accessReadMe();
Thread.sleep(1000);
}catch (InterruptedException e1){
e1.printStackTrace();
}
if(f.activated())
state.enterState(4, new FadeOutTransition(Color.black, 250), new FadeInTransition(Color.black, 250));
if(gb.activated())
Util.terminate();
} | 7 |
public final List<Pair<Integer, String>> getAllItems() {
if (itemNameCache.size() != 0) {
return itemNameCache;
}
final List<Pair<Integer, String>> itemPairs = new ArrayList<Pair<Integer, String>>();
MapleData itemsData;
itemsData = stringData.getData("Cash.img");
for (final MapleData itemFolder : itemsData.getChildren()) {
itemPairs.add(new Pair<Integer, String>(Integer.parseInt(itemFolder.getName()), MapleDataTool.getString("name", itemFolder, "NO-NAME")));
}
itemsData = stringData.getData("Consume.img");
for (final MapleData itemFolder : itemsData.getChildren()) {
itemPairs.add(new Pair<Integer, String>(Integer.parseInt(itemFolder.getName()), MapleDataTool.getString("name", itemFolder, "NO-NAME")));
}
itemsData = stringData.getData("Eqp.img").getChildByPath("Eqp");
for (final MapleData eqpType : itemsData.getChildren()) {
for (final MapleData itemFolder : eqpType.getChildren()) {
itemPairs.add(new Pair<Integer, String>(Integer.parseInt(itemFolder.getName()), MapleDataTool.getString("name", itemFolder, "NO-NAME")));
}
}
itemsData = stringData.getData("Etc.img").getChildByPath("Etc");
for (final MapleData itemFolder : itemsData.getChildren()) {
itemPairs.add(new Pair<Integer, String>(Integer.parseInt(itemFolder.getName()), MapleDataTool.getString("name", itemFolder, "NO-NAME")));
}
itemsData = stringData.getData("Ins.img");
for (final MapleData itemFolder : itemsData.getChildren()) {
itemPairs.add(new Pair<Integer, String>(Integer.parseInt(itemFolder.getName()), MapleDataTool.getString("name", itemFolder, "NO-NAME")));
}
itemsData = stringData.getData("Pet.img");
for (final MapleData itemFolder : itemsData.getChildren()) {
itemPairs.add(new Pair<Integer, String>(Integer.parseInt(itemFolder.getName()), MapleDataTool.getString("name", itemFolder, "NO-NAME")));
}
return itemPairs;
} | 8 |
public String longestCommonSubstring(String s, String t) {
int[][] matrix = new int[s.length()][t.length()];
int maxLen = 0;
int lastSubStart = 0;
int currentSubStart = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < t.length(); j++) {
if (s.charAt(i) == t.charAt(j)) {// character matching
if (i == 0 || j == 0) {// initialize the first row and
// column to 1
matrix[i][j] = 1;
} else {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
}
if (matrix[i][j] > maxLen) {
maxLen = matrix[i][j];// update maxLen
currentSubStart = i - matrix[i][j] + 1;
if (currentSubStart == lastSubStart) {// if we are in
// the same
// substring
sb.append(s.charAt(i));
} else {// we are creating a new substring, so we need
// to clear sb first
sb = new StringBuilder();// clear sb
lastSubStart = currentSubStart;
sb.append(s.subSequence(currentSubStart, i + 1));// append
// current
// longest
// substring
}
}
}
}
}
return sb.toString();
} | 7 |
@Override
public void run() {
for (Citation c : citations.getCitations()) {
io.println(c.getId() + ": " + c.getTitle());
}
Integer command = -5;
try {
command = io.getInteger("Give id of the article to tag (or -1 to cancel): ");
}
catch (NumberFormatException e) {
System.out.println("Error: id's are integers.");
}
if (command >= 0) {
Citation c = null;
try {
c = citations.getCitation(command);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage() + "\nTagging cancelled.");
return;
}
String tag = io.getString("Type tag: ");
if (c.addTag(tag)) {
io.println("Citation was tagged succesfully!");
} else {
io.println("Citation already contains this tag!");
}
} else {
io.println("Tagging cancelled.");
}
} | 5 |
private static void prepareMenu() {
menu = new HashMap<Integer, String>();
menu.put(1, "Coffee");
menu.put(2, "Tea");
menu.put(3, "Lemonade");
menu.put(4, "GrilledSandwich");
menu.put(5, "PeanutButterSandwich");
menu.put(6, "CheeseSandwich");
} | 0 |
public int getFirewallId2() {
return firewallId2;
} | 0 |
public void map() {
//points is start, controls, end
double[][][] V = new double[points.length-1][intervals+1][2];
for (int c = 0; c < V.length; c++) {
for (int i = 0; i < V[c].length; i++) {
V[c][i][0] = (1 - (double)i/intervals)*points[c][0] + ((double)i/intervals)*points[c+1][0];
V[c][i][1] = (1 - (double)i/intervals)*points[c][1] + ((double)i/intervals)*points[c+1][1];
}
}
while (V.length > 1) {
double[][][] VV = new double[V.length - 1][intervals+1][2];
for (int c = 0; c < VV.length; c++) {
for (int i = 0; i < VV[c].length; i++) {
VV[c][i][0] = (1 - (double)i/intervals)*V[c][i][0] + ((double)i/intervals)*V[c+1][i][0];
VV[c][i][1] = (1 - (double)i/intervals)*V[c][i][1] + ((double)i/intervals)*V[c+1][i][1];
}
}
V = VV;
}
XY = new int[2][V[0].length];
for(int i = 0; i < XY[0].length; i++) {
XY[0][i] = (int) Math.round(V[0][i][0]);
XY[1][i] = (int) Math.round(V[0][i][1]);
}
} | 6 |
public void resetAllGameActions() {
for (int i=0; i<keyActions.length; i++) {
if (keyActions[i] != null) {
keyActions[i].reset();
}
}
for (int i=0; i<mouseActions.length; i++) {
if (mouseActions[i] != null) {
mouseActions[i].reset();
}
}
} | 4 |
private void mouseHelper(int codeNeg, int codePos,
int amount)
{
GameAction gameAction;
if (amount < 0) {
gameAction = mouseActions[codeNeg];
}
else {
gameAction = mouseActions[codePos];
}
if (gameAction != null) {
gameAction.press(Math.abs(amount));
gameAction.release();
}
} | 2 |
public ArrayList subledger1(String type, String loanid, float amount)
{ //get all details subledger needs
arrayTemp= new ArrayList();
String query = "select * from loan_dtl where loanid="+loanid+" and amordate between to_date('"+startDate.substring(0, 10) +"','yyyy-mm-dd') and to_date('"+endDate.substring(0, 10)+"','yyyy-mm-dd') ";
ResultSet rs;
this.connect();
Statement stmt = null;
String premium_prev, interest_prev, penalty_prev;
float premium, interest, penalty ;
try
{
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
rs.next();
System.out.println("in sub1 while"+loanid+" "+rs.getString("mon_interest"));
interest_prev=rs.getString("mon_interest");
premium_prev=rs.getString("mon_premium");
interest=rs.getFloat("mon_interest");
premium=rs.getFloat("mon_premium");
//penalty_prev=rs.getString("mon_penalty_prev");
if(amount-rs.getFloat("mon_interest")-rs.getFloat("mon_premium")==0)
{
premium=0;
interest=0;
}
else if(interest+premium>amount)
{
//interest=-amount;
if(amount-interest==0){//equals intereset
premium=rs.getFloat("mon_premium");
interest=0;
}
else if (amount-interest<0)//less than interest
{
premium=rs.getFloat("mon_premium");;
interest-=amount;
}
else if (amount-interest>0)//greater than interest
{
interest=0;
if(amount-interest<premium)//less than premium
premium-=(amount-interest);
}
}
arrayTemp.add(type);
//arrayTemp.add(ordtlid);
arrayTemp.add(rs.getString("loanid"));
arrayTemp.add(rs.getString("loandtlid"));
arrayTemp.add(rs.getString("mon_premium"));
arrayTemp.add(rs.getString("mon_interest"));
//arrayTemp.add(rs.getString("mon_penalty"));
arrayTemp.add(String.valueOf(premium));
arrayTemp.add(String.valueOf(interest));
//arrayTemp.add(String.valueOf(penalty));
}
catch (SQLException e)
{
e.printStackTrace();
}
finally{
this.disconnect();
}
return arrayTemp;
} | 7 |
private void byAttribute() {
TokenQueue cq = new TokenQueue(tq.chompBalanced('[', ']')); // content queue
String key = cq.consumeToAny(AttributeEvals); // eq, not, start, end, contain, match, (no val)
Validate.notEmpty(key);
cq.consumeWhitespace();
if (cq.isEmpty()) {
if (key.startsWith("^"))
evals.add(new Evaluator.AttributeStarting(key.substring(1)));
else
evals.add(new Evaluator.Attribute(key));
} else {
if (cq.matchChomp("="))
evals.add(new Evaluator.AttributeWithValue(key, cq.remainder()));
else if (cq.matchChomp("!="))
evals.add(new Evaluator.AttributeWithValueNot(key, cq.remainder()));
else if (cq.matchChomp("^="))
evals.add(new Evaluator.AttributeWithValueStarting(key, cq.remainder()));
else if (cq.matchChomp("$="))
evals.add(new Evaluator.AttributeWithValueEnding(key, cq.remainder()));
else if (cq.matchChomp("*="))
evals.add(new Evaluator.AttributeWithValueContaining(key, cq.remainder()));
else if (cq.matchChomp("~="))
evals.add(new Evaluator.AttributeWithValueMatching(key, Pattern.compile(cq.remainder())));
else
throw new Selector.SelectorParseException("Could not parse attribute query '%s': unexpected token at '%s'", query, cq.remainder());
}
} | 8 |
public boolean isMoreOuterThan(ClassDeclarer declarer) {
ClassDeclarer ancestor = declarer;
while (ancestor != null) {
if (ancestor == this)
return true;
ancestor = ancestor.getParent();
}
return false;
} | 2 |
public void run() throws IOException, NoSuchAlgorithmException, InvalidPvidException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException
{
try{
//Displaying choices that the voter has
Voter.displayMainMenu();
System.out.println("Please enter your choice");
int choice = Integer.parseInt(reader.readLine());
switch(choice) {
case 1 ://generate PVID
System.out.println("Generate PVID option selected");
System.out.println("Enter your email ID ");
String email_id = reader.readLine();
System.out.println("Enter your pin/passkey");
String pin = reader.readLine();
String PVID = pvidGenerator.generatePVID(email_id, pin);
System.out.println("Your PVID for the voting process is : " + PVID);
break;
case 2 ://Vote
System.out.println("VOTE option selected");
System.out.println("Enter your PVID");
String PVID1 = reader.readLine();
List<String> ballot=ballotGenerator.requestBallot(PVID1);
this.displayBallot(ballot);
System.out.println("Enter your Vote");
int vote= Integer.parseInt(reader.readLine());
collector.recordVote(PVID1,encryptVote(keyGenerator.generateKey(PVID1),vote));
break;
case 3 ://Verify
System.out.println("Verify option selected");
System.out.println("Enter PVID");
String PVID11 = reader.readLine();
if(!collectorBullettinBoard.containsPVID(PVID11))
System.out.println("You have not voted");
else
{
System.out.println("Enter Your Vote");
int voteToVerify=Integer.parseInt(reader.readLine());
if(collectorBullettinBoard.verify(PVID11, Essentials.hashOf(encryptVote(keyGenerator.getKey(PVID11),voteToVerify))))
System.out.println("Your Vote has been recorded correctly");
else
System.out.println("Your Vote is not recorded correctly");
}
break;
default : //Invalid input
System.out.println("Invalid Input");
}
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvalidPinException ex) {
System.out.println("The PIN you entered is invalid");
}
} | 7 |
public static ByteBuffer outputBufferFrom(final Object object) throws IOException {
if (object instanceof ByteBuffer) return (ByteBuffer)object;
if (object instanceof File) return IO._outputBufferFrom_((File)object);
if (object instanceof FileChannel) return IO._outputBufferFrom_((FileChannel)object);
if (object instanceof RandomAccessFile) return IO._outputBufferFrom_((RandomAccessFile)object);
if (object instanceof ByteArraySection) return IO._outputBufferFrom_((ByteArraySection)object);
if (object instanceof ByteArray) return IO._outputBufferFrom_((ByteArray)object);
if (object instanceof byte[]) return IO._outputBufferFrom_((byte[])object);
throw new IOException();
} | 7 |
@EventHandler
public void GhastMiningFatigue(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Ghast.MiningFatigue.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof Fireball) {
Fireball a = (Fireball) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getGhastConfig().getBoolean("Ghast.MiningFatigue.Enabled", true) && shooter instanceof Ghast && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, plugin.getGhastConfig().getInt("Ghast.MiningFatigue.Time"), plugin.getGhastConfig().getInt("Ghast.MiningFatigue.Power")));
}
}
} | 7 |
private void permuteHelper(int size, int usedIndex) {
if (size == k) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < ans.length; i++) {
list.add(ans[i]);
}
result.add(list);
return;
}
for (int i = usedIndex; i < num.length; i++) {
if (used[i])
continue;
used[i] = true;
ans[size] = num[i];
permuteHelper(size + 1, i + 1);
used[i] = false;
}
} | 4 |
public Iterator<Integer> calculateWinningScores(int numberOfTurns){
int numberOfScores = (numberOfTurns%2==0)? (numberOfTurns/2):((numberOfTurns/2) -1);
ArrayList<Integer> scores = new ArrayList<Integer>();
int multiplier = -1;
return scores.iterator();
} | 1 |
public void deplacementDroite() {
if (!pause) {
plateau.updatePosition(1, 0);
updateObservers();
}
} | 1 |
@XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "KA-Nonce", scope = AgreementMethodType.class)
public JAXBElement<byte[]> createAgreementMethodTypeKANonce(byte[] value) {
return new JAXBElement<byte[]>(_AgreementMethodTypeKANonce_QNAME, byte[].class, AgreementMethodType.class, ((byte[]) value));
} | 0 |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode reNode = new ListNode(0);
ListNode tail = reNode;
int carry = 0;
while(l1 != null || l2 != null){
ListNode temp = new ListNode((carry+(l1 == null?0:l1.val)+(l2==null?0:l2.val))%10);
carry = (carry+(l1 == null?0:l1.val)+(l2==null?0:l2.val))/10;
tail.next = temp;
tail = tail.next;
if(l1 != null){
l1 = l1.next;
}
if(l2 != null){
l2 = l2.next;
}
}
if(carry != 0){
tail.next = new ListNode(carry);
}
return reNode.next;
} | 9 |
public static void testVerifierLoginMdp(){
EntityManager em;
boolean resultat;
String nomVisiteur;
String mdpVisiteur;
System.out.println("\nDEBUT DES TESTS");
// Instanciation du gestionnaire d'entités (contexte de persistance)
em = EntityManagerFactorySingleton.getInstance().createEntityManager();
EntityTransaction tx = em.getTransaction();
// Début de la transaction
tx.begin();
nomVisiteur = "swiss";
mdpVisiteur = "18-jun-2003";
System.out.println("\nTest 1-1 - Se connecter sous le login : " + nomVisiteur+" mdp : "+mdpVisiteur);
resultat = DaoVisiteurJPA.verifierLoginMdp(em, nomVisiteur, mdpVisiteur);
System.out.print("\tRésultat : " + resultat );
System.out.println("Test 1-1 effectué");
} | 0 |
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, Exception {
//retardo debug
// try {
// Thread.sleep(80);
// } catch (InterruptedException ex) {
// Thread.currentThread().interrupt();
// }
//control de autenticación
if (request.getSession().getAttribute("usuarioBean") == null) {
Gson gson = new Gson();
Map<String, String> data = new HashMap<>();
data.put("status", "401");
data.put("message", "error de autenticación");
String resultado = gson.toJson(data);
request.setAttribute("contenido", resultado);
getServletContext().getRequestDispatcher("/jsp/messageAjax.jsp").forward(request, response);
} else {
String op = request.getParameter("op");
String ob = request.getParameter("ob");
String callop = Character.toUpperCase(ob.charAt(0)) + ob.substring(1) + Character.toUpperCase(op.charAt(0)) + op.substring(1);
try {
try {
GenericOperation operation = (GenericOperation) Class.forName("net.anariquelme.operaciones." + callop).newInstance();
String data = operation.execute(request, response);
request.setAttribute("contenido", data);
getServletContext().getRequestDispatcher("/jsp/messageAjax.jsp").forward(request, response);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ControlJson.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(ControlJson.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 3 |
void init(byte[] input, int windowStart, int from, int to) {
int[] hashVal = this.hashVal;
int[] head = this.head;
int[] same = this.same;
int[] prev = this.prev;
int[] hashVal2 = this.hashVal2;
int[] head2 = this.head2;
int[] prev2 = this.prev2;
System.arraycopy(Cookie.intMOnes, 0, head, 0, 0x10000);
System.arraycopy(Cookie.intMOnes, 0, hashVal, 0, 0x8000);
System.arraycopy(Cookie.intZeroes, 0, same, 0x8000, 0);
System.arraycopy(seq, 0, prev, 0, 0x8000);
System.arraycopy(Cookie.intMOnes, 0, head2, 0, 0x10000);
System.arraycopy(Cookie.intMOnes, 0, hashVal2, 0, 0x8000);
System.arraycopy(seq, 0, prev2, 0, 0x8000);
int val = (((input[windowStart] & 0xFF) << 5) ^ input[windowStart + 1] & 0xFF) & 0x7FFF;
for (int i = windowStart; i < from; ++i) {
int hPos = i & 0x7FFF;
val = ((val << 5) ^ (i + 2 < to ? input[i + 2] & 0xFF : 0)) & 0x7FFF;
hashVal[hPos] = val;
int tmp = head[val];
prev[hPos] = tmp != -1 && hashVal[tmp] == val ? tmp : hPos;
head[val] = hPos;
tmp = same[(i - 1) & 0x7FFF];
if (tmp < 1) {
tmp = 1;
}
tmp += i;
byte b = input[i];
while (tmp < to && b == input[tmp]) {
tmp++;
}
tmp -= i;
tmp--;
same[hPos] = tmp;
tmp = ((tmp - 3) & 0xFF) ^ val;
hashVal2[hPos] = tmp;
int h = head2[tmp];
prev2[hPos] = h != -1 && hashVal2[h] == tmp ? h : hPos;
head2[tmp] = hPos;
}
this.val = val;
} | 9 |
@Override
public void unInvoke()
{
// undo the affects of this spell
if((affected!=null)&&(canBeUninvoked()))
{
if(affected instanceof Room)
{
final Room room=(Room)affected;
room.showHappens(CMMsg.MSG_OK_VISUAL, L("Time starts moving again..."));
if(invoker!=null)
{
final Ability me=invoker.fetchEffect(ID());
if(me!=null)
me.unInvoke();
}
CMLib.threads().resumeTicking(room,-1);
for(int i=0;i<fixed.size();i++)
{
final MOB mob2=fixed.elementAt(i);
CMLib.threads().resumeTicking(mob2,-1);
}
fixed=new Vector<MOB>();
}
else
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
CMLib.threads().resumeTicking(mob,-1);
if(mob.location()!=null)
{
mob.location().show(mob, null, CMMsg.MSG_OK_VISUAL, L("Time starts moving again..."));
final Ability me=mob.location().fetchEffect(ID());
if(me!=null)
me.unInvoke();
}
}
}
super.unInvoke();
} | 9 |
private void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
int width = 0;
int height = 0;
BufferedReader reader = new BufferedReader(new FileReader(filename));
while(true){
String line = reader.readLine();
if(line == null){
reader.close();
break;
}
if (!line.startsWith("!")){
lines.add(line);
width = Math.max(width, line.length());
}
}
height = lines.size();
for(int j = 0; j < 12; j++){
String line = (String) lines.get(j);
for(int i = 0; i < width; i++){
if(i < line.length()){
char ch = line.charAt(i);
Tile t = new Tile(i, j, Character.getNumericValue(ch));
tilearray.add(t);
}
}
}
} | 6 |
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
} | 8 |
@Test
public void testGetTransaction() {
Gateway beanstream = new Gateway("v1", 300200578,
"4BaD82D9197b4cc4b70a221911eE9f70", // payments API passcode
"D97D3BE1EE964A6193D17A571D9FBC80", // profiles API passcode
"4e6Ff318bee64EA391609de89aD4CF5d");// reporting API passcode
CardPaymentRequest paymentRequest = new CardPaymentRequest();
paymentRequest.setAmount(30.00)
.setOrderNumber(getRandomOrderId("get"));
paymentRequest.getCard()
.setName("John Doe")
.setNumber("5100000010001004")
.setExpiryMonth("12")
.setExpiryYear("18")
.setCvd("123");
try {
PaymentResponse response = beanstream.payments().makePayment(paymentRequest);
Assert.assertTrue(response.isApproved());
if (response.isApproved()) {
Transaction transaction = beanstream.reports().getTransaction(response.id);
System.out.println("Transaction: " + transaction.getAmount()+ " approved? " + transaction.getApproved());
}
} catch (BeanstreamApiException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,"An error occurred", ex);
Assert.fail(ex.getMessage());
}
} | 2 |
@Override
public void mouseDragged(MouseEvent e) {
this.diagramPanel.setMoveHandCursor();
if (SwingUtilities.isLeftMouseButton(e)&&e.isControlDown()) {
int scrollPositionX = this.diagramScrollPane.getViewport().getViewPosition().x;
int scrollPositionY = this.diagramScrollPane.getViewport().getViewPosition().y;
int offsetX = (getX() - e.getX()+scrollPositionX);
int offsetY = (getY() - e.getY()+scrollPositionY);
if(offsetY > 0 && offsetX > 0){
this.diagramScrollPane.getViewport().setViewPosition(new java.awt.Point(offsetX,offsetY));
}
}
// Left
else if (SwingUtilities.isLeftMouseButton(e)) {
this.diagramPanel.mouseLeftDragged(e.getX(), e.getY());
}
} | 5 |
private JLabel getJLabel1() {
if (jLabel1 == null) {
jLabel1 = new JLabel();
jLabel1.setText("seporator:");
}
return jLabel1;
} | 1 |
public void update(Graphics g) {
// setup the graphics environment
Graphics2D g2 = (Graphics2D)g;
if (manager.antialiasing) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} else {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
// paint the cursors
Enumeration<Finger> cursorList = manager.cursorList.elements();
while (cursorList.hasMoreElements()) {
Finger cursor = cursorList.nextElement();
Vector<Point> gesture = cursor.getPath();
if (gesture.size()>0) {
g2.setPaint(Color.blue);
g2.setStroke(gestureStroke);
Point start = gesture.elementAt(0);
for (int i=0;i<gesture.size();i++) {
Point end = gesture.elementAt(i);
g2.draw(new Line2D.Double(start.getX(),start.getY(),end.getX(),end.getY()));
start = end;
}
if (jointCursors.contains(cursor.session_id)) g2.setPaint(Color.darkGray);
else g2.setPaint(Color.lightGray);
g2.fill(new Ellipse2D.Double(start.getX()-5,start.getY()-5,10,10));
}
}
} | 5 |
public ServerController()
{
this.observers = new LinkedList<IClientObserver>();
game = new Game();
CallHandler callHandler = new CallHandler();
try
{
callHandler.registerGlobal(IServerObserver.class, this);
this.addServerListener(new MyServerListener());
this.bind(ServerPort, callHandler);
System.out.println("Server listening...");
while (true)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
catch (LipeRMIException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
} | 4 |
public void setHealth(double health) {
if(health < 0)
this.health = 0;
else
this.health = health;
} | 1 |
public void actualiza() {
long tiempoTranscurrido = System.currentTimeMillis() - tiempoActual;
granada.avanza();
if (canasta.getMoveLeft()) {
canasta.setPosX(canasta.getPosX() - 6);
}
if (canasta.getMoveRight()) {
canasta.setPosX(canasta.getPosX() + 6);
}
if (granada.getMovimiento()) {
granada.actualiza(tiempoTranscurrido);
}
canasta.actualiza(tiempoTranscurrido);
} | 3 |
public void writeNumbers (int pTamano) {
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
for(int i = 0 ; i < pTamano; i++){
int ram = (int) (Math.random() * 100000);
list.add(ram + "");
}
obj.put("Tags", list);
try {
System.out.println("Guardando");
FileWriter file = new FileWriter("src/Numeros.json");
System.out.println("Guardado");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
//manejar error
}
//System.out.print(obj);
} | 2 |
public void initialize(FlowChartInstance flowChartinstance, ChartItemSpecification chartItemSpecification) throws MaltChainedException {
super.initialize(flowChartinstance, chartItemSpecification);
for (String key : chartItemSpecification.getChartItemAttributes().keySet()) {
if (key.equals("id")) {
idName = chartItemSpecification.getChartItemAttributes().get(key);
} else if (key.equals("structure")) {
structureName = chartItemSpecification.getChartItemAttributes().get(key);
} else if (key.equals("task")) {
taskName = chartItemSpecification.getChartItemAttributes().get(key);
}
}
if (idName == null) {
idName = getChartElement("graph").getAttributes().get("id").getDefaultValue();
} else if (structureName == null) {
structureName = getChartElement("graph").getAttributes().get("structure").getDefaultValue();
} else if (taskName == null) {
taskName = getChartElement("graph").getAttributes().get("task").getDefaultValue();
}
} | 7 |
public ComplexMatrix getABCDmatrix(){
if(this.segmentLength==-1)throw new IllegalArgumentException("No distance along the line as been entered");
if(this.distributedResistance==0.0D && this.distributedConductance==0.0D){
this.generalABCDmatrix = this.getIdealABCDmatrix();
}
else{
this.generalABCDmatrix = new ComplexMatrix(2,2);
Complex gammal = this.getPropagationConstant().times(this.segmentLength);
Complex zed0 = this.getCharacteristicImpedance();
this.generalABCDmatrix.setElement(0, 0, Complex.cosh(gammal));
this.generalABCDmatrix.setElement(0, 1, Complex.sinh(gammal).times(zed0));
this.generalABCDmatrix.setElement(1, 0, Complex.sinh(gammal).over(zed0));
this.generalABCDmatrix.setElement(1, 1, Complex.cosh(gammal));
}
return this.generalABCDmatrix;
} | 3 |
public static boolean readBoolean() {
String line = null;
try {
BufferedReader is = new BufferedReader(new InputStreamReader(
System.in));
line = is.readLine();
} catch (NumberFormatException ex) {
System.err.println("Not a valid number: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
if (line.equalsIgnoreCase("true")) {
return true;
} else {
return false;
}
} | 3 |
public void placeObjectOnBoard(Placeable object) {
if (isValidPositions(object)) {
setPriority(object);
}
} | 1 |
public void testConstructor_ObjectStringEx2() throws Throwable {
try {
new YearMonth("T10:20:30.040+14:00");
fail();
} catch (IllegalArgumentException ex) {
// expected
}
} | 1 |
public static void main(String args[]){
int[] reactantsA = {43, 18};
int[] productsA = {4, 52, 1};
int[] reactantsB = {12, 18};
int[] productsB = {6, 1, 52};
int[] reactantsC = {18, 43};
int[] productsC = {52, 4, 1};
int[] reactantsD = {18, 43};
int[] productsD = {52, 4, 1, 4};
Reaction A = new Reaction(reactantsA, productsA);
Reaction B = new Reaction(reactantsB, productsB);
Reaction C = new Reaction(reactantsC, productsC);
Reaction D = new Reaction(reactantsD, productsD);
boolean AequalsB = A.equals(B);
boolean AequalsC = A.equals(C);
boolean CequalsA = C.equals(A);
boolean AequalsD = A.equals(D);
if(AequalsB){
System.out.printf("A equals B\n");
}
if(AequalsC){
System.out.printf("A equals C\n");
}
if(CequalsA){
System.out.printf("C equals A\n");
}
if(AequalsD){
System.out.printf("A equals D\n");
}
System.out.printf(""+A.getID()+"\n");
System.out.printf(""+B.getID()+"\n");
System.out.printf(""+C.getID()+"\n");
System.out.printf(""+D.getID()+"\n");
} | 4 |
public void handleConf(CSTAEvent event) {
if ((event == null) || (event.getEventHeader().getEventClass() != 5)
|| (event.getEventHeader().getEventType() != this.pdu)) {
return;
}
if (this.pdu == 28) {
boolean enable = ((CSTAQueryMwiConfEvent) event.getEvent())
.isMessages();
if ((event.getPrivData() instanceof LucentQueryMwiConfEvent)) {
LucentQueryMwiConfEvent luPrivData = (LucentQueryMwiConfEvent) event
.getPrivData();
this.bits = luPrivData.getApplicationType();
} else if (enable) {
this.bits = -1;
} else {
this.bits = 0;
}
}
this.device.replyAddrPriv = event.getPrivData();
Vector<TSEvent> eventList = new Vector<TSEvent>();
this.device.updateMessageWaitingBits(this.bits, eventList);
if (eventList.size() > 0) {
Vector<?> observers = this.device.getAddressObservers();
for (int j = 0; j < observers.size(); j++) {
TsapiAddressMonitor callback = (TsapiAddressMonitor) observers
.elementAt(j);
callback.deliverEvents(eventList, false);
}
}
} | 9 |
public static JIPMainWindow getInstance() {
if (instance_ == null) instance_ = new JIPMainWindow();
return instance_;
} | 1 |
public Map toMap(){
Map<String,Object> root = new HashMap<String,Object>();
// for(String key : sys_properties.stringPropertyNames()){
// String value = sys_properties.getProperty(key);
// if(key.contains(".")){
// parseComplexKey(key,root,parseValue(value));
// }else{
// root.put(key, parseValue(value));
// }
// }
for(String key : properties.stringPropertyNames()){
String value = properties.getProperty(key);
if(key.contains(".")){
parseComplexKey(key,root,parseValue(value));
}else{
root.put(key, parseValue(value));
}
}
return root;
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Leerling other = (Leerling) obj;
if (leerjaar != other.leerjaar)
return false;
if (leerlingNaam == null) {
if (other.leerlingNaam != null)
return false;
} else if (!leerlingNaam.equals(other.leerlingNaam))
return false;
return true;
} | 7 |
public void alimentaTabela(String SQL){
ArrayList dados = new ArrayList();
String [] Colunas = new String[]{"ID","Nome","CPF","RG","CNH","Cat","Contato","Parent","Telefone","Tel2","TeleContato"};
conecta.executaSQL(SQL);
try {
conecta.rs.first();
do{
dados.add(new Object[]{conecta.rs.getInt("id_cliente"),conecta.rs.getString("nome"),conecta.rs.getString("cpf"),
conecta.rs.getInt("rg"),conecta.rs.getInt("cnh"),conecta.rs.getString("categoria"),
conecta.rs.getString("contato"),conecta.rs.getString("paretesco"),conecta.rs.getString("telefone"),
conecta.rs.getString("telefone_2"),conecta.rs.getString("telefone_3")});
}while(conecta.rs.next());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao Preencher o ArrayList!\n"+ex);
}
TabelaModelo modelo = new TabelaModelo(dados, Colunas);
jTableCliente.setModel(modelo);
jTableCliente.getColumnModel().getColumn(0).setPreferredWidth(80);
jTableCliente.getColumnModel().getColumn(0).setResizable(false);
jTableCliente.getColumnModel().getColumn(1).setPreferredWidth(180);
jTableCliente.getColumnModel().getColumn(1).setResizable(false);
jTableCliente.getColumnModel().getColumn(2).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(2).setResizable(false);
jTableCliente.getColumnModel().getColumn(3).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(3).setResizable(false);
jTableCliente.getColumnModel().getColumn(4).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(4).setResizable(false);
jTableCliente.getColumnModel().getColumn(5).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(5).setResizable(false);
jTableCliente.getColumnModel().getColumn(6).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(6).setResizable(false);
jTableCliente.getColumnModel().getColumn(7).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(7).setResizable(false);
jTableCliente.getColumnModel().getColumn(8).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(8).setResizable(false);
jTableCliente.getColumnModel().getColumn(9).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(9).setResizable(false);
jTableCliente.getColumnModel().getColumn(10).setPreferredWidth(100);
jTableCliente.getColumnModel().getColumn(10).setResizable(false);
jTableCliente.getTableHeader().setReorderingAllowed(false);
jTableCliente.setAutoResizeMode(jTableCliente.AUTO_RESIZE_OFF);
jTableCliente.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
} | 2 |
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (!(o instanceof Pair))
return false;
Pair<?, ?> pairo = (Pair<?, ?>) o;
return this.left.equals(pairo.getLeft())
&& this.right.equals(pairo.getRight());
} | 7 |
public IRCResponse getResponseByNumber(int number){
for(IRCResponse response: IRCResponse.values()){
if (number == response.getNumeric())
return response;
}
return null;
} | 2 |
private void parseVersionNumbers(XMLEventReader xmlReader) throws XMLStreamException {
CompareVersionNumbers versionNumberComparator = new CompareVersionNumbers();
while (xmlReader.hasNext()) {
XMLEvent = xmlReader.nextEvent();
if (XMLEvent.isStartElement()) {
if (XMLEvent.asStartElement().getName().getLocalPart().equalsIgnoreCase("version")) {
if (highestVersionNumber == null) {
highestVersionNumber = xmlReader.nextEvent().asCharacters().getData();
} else {
String versionNumberToCompareWith = xmlReader.nextEvent().asCharacters().getData();
if (versionNumberComparator.compare(highestVersionNumber, versionNumberToCompareWith) == 1) {
highestVersionNumber = versionNumberToCompareWith;
}
}
}
} else if (XMLEvent.isEndElement()) {
if (XMLEvent.asEndElement().getName().getLocalPart().equalsIgnoreCase("versions")) {
break;
}
}
}
} | 7 |
public boolean isBlocked(Account account){ return account.isBlocked(); } | 0 |
@EventHandler(priority = EventPriority.HIGHEST)
public void onBreak(BlockBreakEvent e) {
long time = System.nanoTime();
if (BlockTools.isSign(e.getBlock())) {
this.plugin.getLoggerUtility().log("Block is sign", LoggerUtility.Level.DEBUG);
if (((Sign) e.getBlock().getState()).getLine(0).equalsIgnoreCase("[" + plugin.getConfig().getString("sign_headline") + "]")) {
final BlockBreakEvent event = e;
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
if (!plugin.getDatabaseUtility().isindb(event.getBlock().getLocation())) {
return;
} else {
PPSign sign = plugin.getDatabaseUtility().getSign(event.getBlock().getLocation());
if (!event.getPlayer().getName().equals(sign.getOwner())) {
if (!plugin.getPermissions().checkpermissions(event.getPlayer(), "Paypassage.admin")) {
event.setCancelled(true);
return;
}
}
plugin.getDatabaseUtility().deleteSign(event.getBlock().getLocation());
plugin.getLoggerUtility().log(event.getPlayer(), "PP Sign deleted", LoggerUtility.Level.INFO);
}
} catch (SQLException ex) {
Logger.getLogger(PPListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
this.plugin.getLoggerUtility().log("PlayerInteractEvent handled in " + (System.nanoTime() - time) / 1000000 + " ms", LoggerUtility.Level.DEBUG);
} | 6 |
@Override
public String toString() {
return "ImageMap [" + (name != null ? "name=" + name + ", " : "")
+ (src != null ? "src=" + src + ", " : "")
+ (dimension != null ? "dimension=" + dimension + ", " : "")
+ "]";
} | 3 |
@Id
@Column(name = "FUN_CEDULA")
public Long getFunCedula() {
return funCedula;
} | 0 |
private static BufferedImage delegateRendering(Algebra algebra) {
if(algebra instanceof Equation) return renderEquation((Equation)algebra);
else {
BufferedImage rendered = null;
if(algebra instanceof Expression) rendered = renderExpression((Expression)algebra);
else if(algebra instanceof Term) rendered = renderTerm((Term) algebra);
else if(algebra instanceof Fraction) rendered = renderFraction((Fraction) algebra);
else if(algebra instanceof Number) rendered = renderNumber((Number) algebra);
else if(algebra instanceof MixedNumber) rendered = renderMixedNumber((MixedNumber) algebra);
else if(algebra instanceof Root) rendered = renderRoot((Root)algebra);
else rendered = renderVariable((Variable) algebra);
return wrapWithSignAndExponent(rendered, (AlgebraicParticle) algebra);
}
} | 7 |
public static int romanToInt(String s) {
Character[] metric = {'I','V','X','L','C','D','M'};
int[] a = {1,5,10,50,100,500,1000};
Map<Character, Integer> smap = new HashMap<Character, Integer>();
for (int i = 0; i < metric.length; i++) {
smap.put(metric[i], a[i]);
}
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (i == s.length() - 1) res = res + smap.get(s.charAt(i));
else {
int ai = smap.get(s.charAt(i));
int bi = smap.get(s.charAt(i + 1));
if (ai < bi) {
res = res + bi - ai;
i = i + 1;
} else {
res = res + ai;
}
}
}
return res;
} | 4 |
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} | 1 |
public PolyLinje[] sortPolylinjer(PolyLinje[] randomPolylinje) throws NullPointerException
{
int antalGula = 0;
// Räknar antalet gula Polylinjer av dem slump-
// mässigt genererade.
for(int i = 0; i < randomPolylinje.length; i++)
{
if(randomPolylinje[i].getFarg() == "gul")
{
antalGula++;
}
}
if(antalGula == 0)
{
throw new NullPointerException("\n Inga gula Polylinjer!");
}
PolyLinje[] gulaPolylinjer = new PolyLinje[antalGula];
int i2 = 0;
// Fyller den gulaPolylinjer vektorn med gula polylinjer
for(int i = 0; i < randomPolylinje.length; i++)
{
if(randomPolylinje[i].getFarg() == "gul")
{
gulaPolylinjer[i2] = randomPolylinje[i];
i2++;
}
}
return gulaPolylinjer;
} | 5 |
public static List<Field> outVars(Class<?> comp) {
List<Field> f = new ArrayList<Field>();
for (Field field : comp.getFields()) {
Out out = field.getAnnotation(Out.class);
if (out != null) {
f.add(field);
}
}
return f;
} | 3 |
public void setComponents(double[][] values) {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
m[i][j] = values[i][j];
} | 2 |
public List<Event> getPickingInfo(String picikingId) {
List<Event> events = new ArrayList<Event>();
for (Event e : eventLog) {
EventType type = e.getEventType();
String picId = splitMetaData(e.getMetaData())[0];
if (picId.equals(picikingId)) {
if (type == EventType.NEW_PICKING
|| type == EventType.DISPATCH_PICKING
|| type == EventType.TAKE_PICKING) {
events.add(e);
}
}
}
return events;
} | 5 |
private boolean checkSetting() {
if (DoSetting.tmpUserName.getText().isEmpty())
return false;
if (new String(DoSetting.tmpPassWord.getPassword()).isEmpty())
return false;
if (DoSetting.tmpKeyPath.getText().isEmpty())
return false;
if (DoSetting.tmpHostName.getText().isEmpty())
return false;
if (DoSetting.tmpPortNumber.getText().isEmpty())
return false;
if (DoSetting.tmpUploadPath.getText().isEmpty())
return false;
return true;
} | 6 |
protected void demo17() throws IOException, UnknownHostException, CycApiException {
if (cycAccess.isOpenCyc()) {
Log.current.println("\nThis demo is not available in OpenCyc");
}
else {
Log.current.println("Demonstrating usage of the generateDisambiguationPhraseAndTypes api function.\n");
CycFort mt = cycAccess.getKnownConstantByName("PeopleDataMt");
CycList objects = cycAccess.makeCycList("(#$Penguin #$PittsburghPenguins)");
CycList disambiguationExpression = cycAccess.generateDisambiguationPhraseAndTypes(objects);
Log.current.println("the result of disambiguating the objects \"" + objects.cyclify() + "\" is\n" +
disambiguationExpression);
}
} | 1 |
public void save()
{
try
{
File file = new File(this.absoluteFileName);
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
Document document = factory.newDocumentBuilder().newDocument();
Element unisensElement = this.createElement(document);
document.appendChild(unisensElement);
DOMSource source = new DOMSource(document);
String validate = System.getProperty(PROPERTIE_VALIDATION);
if (validate != null && validate.equalsIgnoreCase("true"))
validate(document);
FileOutputStream out = new FileOutputStream(file);
StreamResult result = new StreamResult(out);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
transformer
.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(source, result);
out.flush();
out.close();
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch (TransformerConfigurationException tce)
{
tce.printStackTrace();
}
catch (TransformerException te)
{
te.printStackTrace();
}
catch (FileNotFoundException fnfe)
{
fnfe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
} | 7 |
protected void appendImage(String text) {
String[] link=split(text, '|');
URI uri=null;
try { // validate URI
uri=new URI(link[0].trim());
}
catch (URISyntaxException e) {
}
if (uri!=null && uri.isAbsolute() && !uri.isOpaque()) {
String alt=escapeHTML(unescapeHTML(link.length>=2 && !isEmpty(link[1].trim())? link[1]:link[0]));
sb.append("<img src=\""+escapeHTML(uri.toString())+"\" alt=\""+alt+"\" title=\""+alt+"\" />");
}
else {
sb.append("<<<Internal image(?): ");
sb.append(escapeHTML(unescapeHTML(text)));
sb.append(">>>");
}
} | 6 |
public int getPort() {
return this.port;
} | 0 |
@Override
public void run() {
while (true) {
player.update();
currentSprite = anim.getImage();
if (playerState == PlayerState.Combat) {
if (!player.getLocation().combat(player)){
playerState = PlayerState.Dead;
} else playerState = PlayerState.Alive;
}
else if (player.getLocation().isOccupied() && player.isAlive()) {
playerState = PlayerState.Seen;
player.stopAll();
}
try {
updateBackground();
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.print(e1.getMessage());
}
updateTiles();
bg1.update();
animate();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} | 7 |
public int NumberParser(String str){
// Parses valid number for different formats from Strings
// used for parsing numerical arguments like immediate values and
// address jumps and memory initializations
int x=0;
String temp="";
if(str.length()>2)
temp=str.substring(0,2);
// System.out.println("temp parsing "+temp);
if(isNumeric(str)){
try{
x=Integer.parseInt(str,10);
}catch (NumberFormatException e){
return ErrorManager.INVALID_NUMERAL;
}
}
else if(temp.equals("0x"))
{
temp=str.substring(2);
try{
x=Integer.parseInt(temp,16);
}catch (NumberFormatException e){
// System.out.println("Temp="+temp);
return ErrorManager.INVALID_NUMERAL;
}
}else if(temp.equals("0b")){
temp=str.substring(2);
try{
x=Integer.parseInt(temp,2);
}catch (NumberFormatException e){
return ErrorManager.INVALID_NUMERAL;
}
}else if(temp.equals("0d")){
temp=str.substring(2);
try{
x=Integer.parseInt(temp,10);
}catch (NumberFormatException e){
return ErrorManager.INVALID_NUMERAL;
}
}
else return ErrorManager.INVALID_NUMERAL;
return x; //return the 16 bit instruction word
} | 9 |
public boolean equals( Object other )
{
Match m = ((Match)other);
if ( m.length == this.length
&& this.data != null
&& ((Match)other).data != null )
{
for ( int i=0;i<length;i++ )
{
if ( m.data[i] != this.data[i] )
return false;
}
return true;
}
return false;
} | 5 |
public Icon loadIconIfNonEmpty(String url) {
if (url != null && !url.isEmpty()) {
try {
return ImageSupporter.loadImageIcon(url);
} catch (MalformedURLException ignored) {}
}
return null;
} | 3 |
public static void testVersion(boolean testIfEnabled, boolean displayIfVersionMatch) {
displayIfOK = displayIfVersionMatch;
if(isRunning) {
return;
}
if(testIfEnabled) {
if(!AppConfig.getAppConfig().checkForSinalgoUpdate) {
return;
}
long last = AppConfig.getAppConfig().timeStampOfLastUpdateCheck;
if(last + 86400000 > System.currentTimeMillis()) {
return;
}
}
VersionTester vt = new VersionTester();
vt.start();
} | 4 |
public static void main(String[] args)
{
int a = 3;
int c = 0;
/**
* if b = 0;
* Exception in thread "main" java.lang.ArithmeticException: / by zero
* at exceptionTest.ExceptionTest.main(ExceptionTest.java:10)
*/
try{
int b = 0;
System.out.println("From Main Before!");
c = a / b;
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
finally
{
System.out.println("From Main Finally !");
}
System.out.println("From Main After!");
System.out.println(c);
} | 1 |
public void saveCache() throws IOException {
if (xmlFile != null)
synchronized (doc) {
try (OutputStream outStream = Files.newOutputStream(xmlFile)) {
outputter.output(doc, outStream);
}
}
} | 1 |
public boolean chooseOptionFromMenu() {
int userChoice= Program.getUserInput();
if (userChoice == 1) {
Program.displayBookList();
}
else if (userChoice == 2) {
user.reserveBook();
}
else if (userChoice == 3) {
if (User.loggedIn()) {
System.out.println("\n");
System.out.println("Your library number is " + Program.savedLibraryNumber);
} else {
System.out.println("\n");
System.out.println("Please talk to Librarian. Thank you.");
}
}
else if (userChoice == 4) {
Program.displayMovieList();
}
else if (userChoice == 5) {
Program.clearLogin();
user.login();
} else if (userChoice == 9) {
System.out.println("Quitting...");
return true;
} else {
System.out.println("\n");
System.out.println("Enter a valid integer!!");
}
return false;
} | 7 |
protected synchronized WebPage processHtml(final String url, final int depth) //
throws ParserException, Exception {
this.cobweb.addSearchedSites(url);
//
Parser parser = new Parser();
parser.setURL(url);
URLConnection uc = parser.getConnection();
uc.connect();
//
WebPage wp = new WebPage();
wp.setDepth(depth);
wp.setUrl(url);
wp.setCharSet(parser.getEncoding());
NodeIterator nit = parser.elements();
while (nit.hasMoreNodes()) {
parserNode((Node)nit.nextNode(), wp);
}
parser = null;
uc = null;
nit = null;
return wp;
} | 1 |
private void setupKeys(EntityRegistry registry) {
// for (Field f : keyRegistry.getDeclaredFields()) {
// FieldId ann = f.getAnnotation(FieldId.class);
// if (ann != null) {
// Object okey;
// try {
// okey = f.get(TKey.class);
// } catch (IllegalAccessException | IllegalArgumentException ex) {
// okey = null;
// }
// if (okey == null || !(okey instanceof TKey)) {
// continue;
// }
//
// TKey key = (TKey) okey;
//
// elementNames.put(key.getName(), key);
// if (!baseTypeConverters.containsKey(key.getType()) && !converters.containsKey(key.getType())) {
// converters.put(key.getType(), new AnnotationBasedXmlConverter(key.getType()));
// }
// }
// }
Set<TKey<?, ?>> keys = registry.getAvailableKeys();
for (TKey<?, ?> key : keys) {
elementNames.put(key.getName(), key);
if (!baseTypeConverters.containsKey(key.getType()) && !converters.containsKey(key.getType())) {
// if (Enum.class.isAssignableFrom(key.getType())) {
// converters.put(key.getType(), new BaseTypeEncoderBasedXmlSerializer<String>(new EnumEncoder((Class<? extends Enum>) key.getType())));
// } else {
converters.put(key.getType(), new AnnotationBasedXmlConverter(key.getType()));
// }
}
}
} | 7 |
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ByteOrderMark)) {
return false;
}
ByteOrderMark bom = (ByteOrderMark)obj;
if (bytes.length != bom.length()) {
return false;
}
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != bom.get(i)) {
return false;
}
}
return true;
} | 4 |
public void SetNumebrOfPackets(int packets)
{
NumberOfPackets = packets;
//UDarray = new int[NumberOfPackets];
} | 0 |
public void mouseMoved(MouseEvent e) // used to show where the piece will be placed
{
for (Square[] a : squares)
{
for (Square s : a)
{
if (s.rect.contains(e.getPoint()))
{
x = s.x + 40;
y = s.y + 40;
}
}
}
} | 3 |
private boolean importFile() {
File lastFile = fileChooser.getSelectedFile();
boolean success = false;
final Frame frame = JOptionPane.getFrameForComponent(this);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilters(new String[] { "html", "txt" });
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setDialogTitle("Import");
fileChooser.setApproveButtonMnemonic('O');
String latestPath = fileChooser.getLastVisitedPath();
if (latestPath != null)
fileChooser.setCurrentDirectory(new File(latestPath));
if (lastFile != null && !lastFile.isDirectory())
fileChooser.handleFileTypeSwitching(lastFile);
fileChooser.setAccessory(null);
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
final File file = fileChooser.getSelectedFile();
File dir = fileChooser.getCurrentDirectory();
if (file.exists()) {
if (FileFilterFactory.getFilter("html").accept(file)) {
JOptionPane.showMessageDialog(frame, "Some HTML content may not be converted.", "Import HTML File", JOptionPane.INFORMATION_MESSAGE);
HTMLConverter.insertHTMLFile(getStyledDocument(), getCaretPosition(), file);
} else if (FileFilterFactory.getFilter("txt").accept(file)) {
try {
readPlainTextFile(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
fileChooser.rememberPath(dir.toString());
success = true;
} else {
JOptionPane.showMessageDialog(frame, file + " does not exist.", "File does not exist", JOptionPane.ERROR_MESSAGE);
fileChooser.resetChoosableFileFilters();
return false;
}
}
fileChooser.resetChoosableFileFilters();
return success;
} | 8 |
private void printBoard(Board board, Engine engine)
{
//System.out.println("Current Board:");
// Print Header
System.out.println(" X ");
System.out.println(" 0|1|2");
// Iterate over the rows, y.
for (int y=0; y<3; y++)
{
if (y==1)
{
System.out.print("Y");
}
else
{
System.out.print(" ");
}
System.out.print(" "+y);
// Iterate over the columns, x.
for (int x=0; x<3; x++)
{
int[] pos = {x,y};
Player curr = board.getPlayerAtPosition(pos);
System.out.print("|"+engine.getLetterForPlayer(curr));
}
System.out.println("");
}
} | 3 |
public void loadFromObject() { try {
if (cls==null) return;
for (int i=0; i<fields.size(); i++) {
String fieldname = (String)fields.get(i);
String fieldtype = (String)fieldtypes.get(fieldname);
//System.out.println("<field "+fieldname+" "+fieldvalue);
if (fieldtype.equals("key")
|| fieldtype.equals("int")
|| fieldtype.equals("double")
|| fieldtype.equals("boolean")
|| fieldtype.equals("String") ) {
Field field = cls.getField(fieldname);
// if obj==null we get a static field
fieldvalues.put(fieldname, field.get(obj));
} else {
System.out.println("not implemented!");
}
}
} catch (NoSuchFieldException e) {
throw new JGameError("Field not found.");
} catch (IllegalAccessException e) {
throw new JGameError("Field cannot be accessed.");
} } | 9 |
@Override
public void registerToken(NotificationToken token) {
String logData = "";
if (token.getType() == null) { // result
logData += "Result of access request:\n";
logData += "Time: "+token.getTimestamp()+"\n";
logData += "Controller: "+token.getController()+"\n";
logData += "AccessPoint: "+token.getAccessPoint()+"\n";
logData += "Result: "+token.getResult()+"\n\n";
}
else { // request
logData += "Access request:\n";
logData += "Time: "+token.getTimestamp()+"\n";
logData += "Controller: "+token.getController()+"\n";
logData += "AccessPoint: "+token.getAccessPoint()+"\n";
logData += "Authorization type: "+token.getType().name()+"\n";
if (token.getValue() != null) {
logData += "Authorization data: "+token.getValue()+"\n\n";
}
else {
logData += "ID: "+token.getId()+"\n";
logData += "Passcode: "+token.getPasscode()+"\n\n";
}
}
//System.out.println("Logging data: \n"+logData);
try {
output.write(logData);
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 3 |
public void setjTextFieldMotifVis(JTextField jTextFieldMotifVis) {
this.jTextFieldMotifVis = jTextFieldMotifVis;
} | 0 |
private void constraint_31A() throws IOException {
for (int k = 1; k <= NUM_VARS; k++) {
for (int m = 1; m <= SQUARE_SIZE; m += 3) {
for (int n = 1; n <= SQUARE_SIZE; n += 3) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
out.append((m + i) + "" + (n + j) + "" + k + " ");
}
}
out.append("0\n");
}
}
}
} | 5 |
private static String[] getInitialData() {
File file = new File(INPUT_FILE_NAME);
if (!file.exists()) {
return InitialDataGeneratorHelper.
generateInitialData(DEFAULT_TOWERS_NUMBER, DEFAULT_CALLS_NUMBER);
}
String[] result = new String[2];
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream( file.getPath() ), "utf-8"))) {
String line = null;
for (int i = 0; (line = reader.readLine()) != null; i++) {
if (i > 1)
return InitialDataGeneratorHelper.
generateInitialData(DEFAULT_TOWERS_NUMBER, DEFAULT_CALLS_NUMBER);
result[i] = line;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
} | 4 |
private void initialize(Header header)
throws DecoderException
{
// REVIEW: allow customizable scale factor
float scalefactor = 32700.0f;
int mode = header.mode();
int layer = header.layer();
int channels = mode==Header.SINGLE_CHANNEL ? 1 : 2;
// set up output buffer if not set up by client.
if (output==null)
output = new SampleBuffer(header.frequency(), channels);
float[] factors = equalizer.getBandFactors();
filter1 = new SynthesisFilter(0, scalefactor, factors);
// REVIEW: allow mono output for stereo
if (channels==2)
filter2 = new SynthesisFilter(1, scalefactor, factors);
outputChannels = channels;
outputFrequency = header.frequency();
initialized = true;
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.