method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
f11c7192-c3b7-4f30-9913-6f38afbf6edc
| 7
|
public List<InetAddress> discoverHosts (int udpPort, int timeoutMillis) {
List<InetAddress> hosts = new ArrayList<InetAddress>();
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
broadcast(udpPort, socket);
socket.setSoTimeout(timeoutMillis);
while (true) {
DatagramPacket packet = new DatagramPacket(new byte[0], 0);
try {
socket.receive(packet);
} catch (SocketTimeoutException ex) {
if (INFO) info("kryonet", "Host discovery timed out.");
return hosts;
}
if (INFO) info("kryonet", "Discovered server: " + packet.getAddress());
hosts.add(packet.getAddress());
}
} catch (IOException ex) {
if (ERROR) error("kryonet", "Host discovery failed.", ex);
return hosts;
} finally {
if (socket != null) socket.close();
}
}
|
206252ac-6c91-47d9-8b20-12ca17743418
| 9
|
protected ProtocolPacket[] receivePacket(Tcp tcp, Ip4 ip)
throws InvalidPacketProtocolParserException,
UnknownPacketProtocolParserException,
UnknownPartTypeProtocolParserException {
// since only clients starts connections, we can use this to match the
// client IP and it is not necessary to ask the user which IP is client
if (clientAddress == null) {
if (!tcp.flags_SYN())
return null;
try {
clientAddress = Inet4Address.getByAddress(ip.source());
} catch (UnknownHostException e) {
return null;
}
}
final byte[] data = tcp.getPayload();
if (data.length == 0)
return null;
final List<ProtocolPacket> packets = new ArrayList<ProtocolPacket>(1);
ProtocolPacket protocolPacket;
if (isClientPacket(ip)) {
try {
clientBuffer.put(data).flip();
while (isPacketComplete(PacketDirection.CLIENT)) {
protocolPacket = readPacket(PacketDirection.CLIENT);
trySetKey(protocolPacket);
packets.add(protocolPacket);
}
clientBuffer.compact();
} catch (BufferOverflowException e) {
clientBuffer.clear();
clientBuffer.put(new byte[clientBuffer.remaining()]);
serverBuffer.clear();
throw e;
}
} else {
try {
serverBuffer.put(data).flip();
while (isPacketComplete(PacketDirection.SERVER)) {
protocolPacket = readPacket(PacketDirection.SERVER);
trySetKey(protocolPacket);
packets.add(protocolPacket);
}
serverBuffer.compact();
} catch (BufferOverflowException e) {
serverBuffer.clear();
serverBuffer.put(new byte[serverBuffer.remaining()]);
serverBuffer.clear();
throw e;
}
}
return packets.toArray(new ProtocolPacket[packets.size()]);
}
|
2b4d2d59-32f7-4af5-858e-0a8b0d07c483
| 1
|
public SAXCodeAdapter(final ContentHandler h, final int access) {
super(h);
labelNames = new HashMap();
if ((access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE | Opcodes.ACC_NATIVE)) == 0)
{
addStart("code", new AttributesImpl());
}
}
|
47dc347c-3e23-4fe8-9ce0-acf708945422
| 3
|
public void setBounds(int x, int y) {
setBoundsDoor(x, y);
if (direction == 1) {
doorBounds.x = x;
doorBounds.y = y;
}
if (direction == 2 || direction == 3) {
doorBounds.x = x;
doorBounds.y = y;
}
}
|
321d0685-31be-483c-9333-2e48434e7767
| 4
|
public void repaintNewTheme()
{
char currentDirection = this.direction;
String directionString=null;
switch(currentDirection)
{
case 'v': directionString = "down"; break;
case '^': directionString = "up"; break;
case '>': directionString = "right"; break;
case '<': directionString = "left"; break;
}
URL loc = this.getClass().getResource("/karel/themes/" +themeName+directionString +".png");
ImageIcon iia = new ImageIcon(loc);
Image image = iia.getImage();
this.setImage(image);
}
|
f60c8cdc-54c4-4d4e-9a18-206dd1e39f64
| 6
|
public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len &&
bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
|
9bc13423-0d70-45d8-9852-3cecbb764665
| 4
|
public <T extends Interactive & Locatable> boolean combineCamera(final T entity, final int pitch) {
if (!entity.valid()) {
return false;
}
if (entity.inViewport()) {
return true;
}
final Thread angleThread = new Thread(new Runnable() {
@Override
public void run() {
ctx.camera.turnTo(entity);
}
});
final Thread pitchThread = new Thread(new Runnable() {
@Override
public void run() {
ctx.camera.pitch(pitch);
}
});
if (Random.nextBoolean()) {
angleThread.start();
ctx.sleep(150); // my sleep does Thread.sleep(Math.max(5, (int) (millis * Random.nextDouble(0.75, 1.5))))
pitchThread.start();
} else {
pitchThread.start();
ctx.sleep(150);
angleThread.start();
}
try {
angleThread.join();
pitchThread.join();
} catch (InterruptedException ignored) {
}
return entity.inViewport();
}
|
8512f303-3580-4ecc-9f8a-9554a04fa6e9
| 4
|
public Topic parseTopic(Document dom) throws ParserConfigurationException, SAXException, IOException, XMLStreamException {
Topic topic = new Topic();
if(dom.getElementsByTagName("num").item(0).getFirstChild() != null){
String[] nums = dom.getElementsByTagName("num").item(0).getFirstChild().getNodeValue().split(": ");
topic.setDocnum(nums[1]);
}
if(dom.getElementsByTagName("title").item(0).getFirstChild() != null)
topic.setTitle(dom.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());
if(dom.getElementsByTagName("desc").item(0).getFirstChild() != null)
topic.setDesc(dom.getElementsByTagName("desc").item(0).getFirstChild().getNodeValue());
if(dom.getElementsByTagName("narr").item(0).getFirstChild() != null)
topic.setNarr(dom.getElementsByTagName("narr").item(0).getFirstChild().getNodeValue());
return topic;
}
|
91e480e5-77fa-4b33-81ae-8e0fcff91f0f
| 8
|
@SuppressWarnings("resource")
private void executaComando(String escolha) {
try {
Scanner linha = new Scanner(escolha.toLowerCase());
int cmd = converterComando(linha.next());
if (!linha.hasNext())
throw new Exception(
"COMANDO INCOMPLETO: esta faltando o segundo atributo");
String s = linha.next();
while (linha.hasNext())
s += " " + linha.next();
s = s.toLowerCase();
switch (cmd) {
case 1:
cmdMover(s);
break;
case 2:
cmdOlhar(s);
break;
case 3:
cmdAtacar(s);
break;
case 4:
cmdSoltarItem(s);
break;
case 5:
cmdPegarItem(s);
break;
}
} catch (Exception e) {
err.println(e.getMessage());
return;
}
}
|
636a5af1-a737-478a-bab9-7485e3372bd0
| 4
|
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!obj.getClass().isAssignableFrom(Vec.class)) return false;
Vec other = (Vec) obj;
return x == other.x && y == other.y && z == other.z;
}
|
b661d388-7e90-4d71-97f7-cae7ae55faac
| 3
|
private void pollInput() {
while (Keyboard.next()) {
if (Keyboard.getEventKeyState()) {
if (Keyboard.getEventKey() == Keyboard.KEY_SPACE) {
log.dbg("Key pressed: SPACE");
}
}
}
}
|
d61b1f73-582f-4e92-bb8a-39d363dd4ed5
| 2
|
public static boolean isTypePrimitive(Class<?> type) {
return (type != null && type.isPrimitive());
}
|
9645d8f1-cfe9-46d5-a51d-0f2ea06eaadc
| 0
|
public static void question2() {
/*
QUESTION PANEL SETUP
*/
questionLabel.setText("Do you feel like dressing fancy?");
questionNumberLabel.setText("2");
/*
ANSWERS PANEL SETUP
*/
//resetting
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
radioButton6.setSelected(false);
radioButton7.setSelected(false);
radioButton8.setSelected(false);
radioButton9.setSelected(false);
radioButton10.setSelected(false);
radioButton11.setSelected(false);
radioButton12.setSelected(false);
radioButton13.setSelected(false);
radioButton14.setSelected(false);
//enability
radioButton1.setEnabled(true);
radioButton2.setEnabled(true);
radioButton3.setEnabled(true);
radioButton4.setEnabled(true);
radioButton5.setEnabled(false);
radioButton6.setEnabled(false);
radioButton7.setEnabled(false);
radioButton8.setEnabled(false);
radioButton9.setEnabled(false);
radioButton10.setEnabled(false);
radioButton11.setEnabled(false);
radioButton12.setEnabled(false);
radioButton13.setEnabled(false);
radioButton14.setEnabled(false);
//setting the text
radioButton1.setText("No,not really.");
radioButton2.setText("Yes, I do.");
radioButton3.setText("I want to do something crazy.");
radioButton4.setText("I don't really care.");
radioButton5.setText("No used");
radioButton6.setText("No used");
radioButton7.setText("No used");
radioButton8.setText("No used");
radioButton9.setText("No used");
radioButton10.setText("No used");
radioButton11.setText("No used");
radioButton12.setText("No used");
radioButton13.setText("No used");
radioButton14.setText("No used");
// Calculating the best guesses and showing them.
Knowledge.calculateAndColorTheEvents();
}
|
17f8a0dd-6397-41e5-a764-23b18056a02a
| 9
|
public void move() {
lastX = x;
lastY = y;
/* If we can make a decision, pick a new direction randomly */
if (isChoiceDest()) {
direction = randomDirection();
}
/* If that direction is valid, move that way */
switch (direction) {
case 'L':
if (isValidDest(x - INCREMENT, y))
x -= INCREMENT;
break;
case 'R':
if (isValidDest(x + Pacman.TILE_SIZE, y))
x += INCREMENT;
break;
case 'U':
if (isValidDest(x, y - INCREMENT))
y -= INCREMENT;
break;
case 'D':
if (isValidDest(x, y + Pacman.TILE_SIZE))
y += INCREMENT;
break;
}
}
|
bade5176-1b99-4407-9c6d-351f0d6a4f37
| 0
|
public Game(){
startGame();
}
|
9e990142-93e3-4a1a-90e3-5840559f43e4
| 5
|
@Override
public void validarSemantica() {
Tipo cond=null;
try {
cond =expr1.validarSemantica();
} catch (Exception ex) {
Logger.getLogger(SentenciaWhile.class.getName()).log(Level.SEVERE, null, ex);
}
if(cond instanceof TipoBooleano){
Sentencia tmp= condicion;
while(tmp!=null){
tmp.validarSemantica();
tmp=tmp.getSiguiente();
}
tmp=conElse;
while(tmp!=null){
tmp.validarSemantica();
tmp=tmp.getSiguiente();
}
}
else{
try {
throw new Exception("Error Semantico -- La condicion tiene que ser booleana");
} catch (Exception ex) {
Logger.getLogger(SentenciaWhile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
8f99e242-4f8b-45bc-8ef8-955e1720da9e
| 7
|
public void move(int xa, int ya) {
if (xa != 0 && ya != 0) {
move(xa, 0);
move(0, ya);
numSteps--;
return;
}
numSteps++;
if (!hasCollided(xa, ya)) {
if (ya < 0)
movingDir = 0;
if (ya > 0)
movingDir = 1;
if (xa < 0)
movingDir = 2;
if (xa > 0)
movingDir = 3;
x += xa * speed;
y += ya * speed;
}
}
|
e7d5b543-983e-4867-b69e-950725a5810a
| 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(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Ventana.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 Ventana().setVisible(true);
}
});
}
|
934a14cd-b5fe-4e0e-954a-69ce85b55228
| 4
|
public void schrijf()
throws DbException{
// Create a XMLOutputFactory
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// Create XMLEventWriter
XMLEventWriter eventWriter;
try {
eventWriter = outputFactory
.createXMLEventWriter(new FileOutputStream(handler.getBestand()));
} catch (FileNotFoundException | XMLStreamException e1) {
throw new DbException("wrong file");
}
// Create a EventFactory
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument();
try{
eventWriter.add(startDocument);
eventWriter.add(end);
StartElement productenStartElement = eventFactory.createStartElement("","",XmlTags.PRODUCTEN);
eventWriter.add(productenStartElement);
eventWriter.add(end);
// Create product open tag
ArrayList<Product> producten = handler.getWinkel().getProducten();
for(Product product: producten)
{
if(product.getStaat().getClass().equals(VerwijderdState.class))
continue;
eventWriter.add(eventFactory.createStartElement("","",XmlTags.PRODUCT));
eventWriter.add(end);
// Write the different nodes
createNode(eventWriter, XmlTags.TYPE, product.getType());
createNode(eventWriter, XmlTags.ID, product.getId());
createNode(eventWriter, XmlTags.TITLE, product.getNaam());
createNode(eventWriter, XmlTags.BASEPRICE, "" + product.getBasisprijs());
createNode(eventWriter, XmlTags.STATE, product.getStaat().getClass().getCanonicalName());
eventWriter.add(eventFactory.createEndElement("", "",XmlTags.PRODUCT));
eventWriter.add(end);
}
eventWriter.add(eventFactory.createEndElement("", "",XmlTags.PRODUCTEN));
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();
} catch(XMLStreamException e){
throw new DbException("wrong format");
}
}
|
f2c42843-3b99-4ee0-a828-f124c82acd44
| 3
|
public ClassST parse() throws UnexpectedTokenException, SyntaxError
{
ClassST ret = null;
String _package = this._package();
List<String> imports = this.imports();
String signature = this.classSignature();
String name = this.getToken().data;
Type type = Type.parse(signature.toString());
this.nextToken();
switch (type)
{
case CLASS:
ret = this._class(_package, imports, signature, name);
break;
case INTERFACE:
break;
case ENUM:
break;
}
return ret;
}
|
8b0e7ef4-e093-4e63-a9ff-1d8eb513a326
| 2
|
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(1);
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("r1 running");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
System.out.println("r2 running");
}
};
Runnable r3 = new Runnable() {
@Override
public void run() {
System.out.println("r3 running");
}
};
ThreadPoolExecutor executor = new ThreadPoolExecutor(1,1,2, TimeUnit.SECONDS,workQueue);
RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(r.toString() + " rejected!sleep 3 sec and than run again");
try {
Thread.sleep(3000);
executor.execute(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executor.setRejectedExecutionHandler(rejectedExecutionHandler);
executor.execute(runnable);
executor.execute(r2);
executor.execute(r3);
executor.shutdown();
}
|
e4da5594-db02-4db0-b2a6-f638021cf522
| 8
|
public static void main(String[] args) {
Random gen = new Random();
for (int times = 0; times < 1000; ++times) {
int n;
if (args.length == 1) {
n = Integer.valueOf(args[0]);
} else {
n = gen.nextInt(100) + 1;
}
List<Integer> A = rand_vector(n);
int pivot_index = gen.nextInt(A.size());
int pivot = A.get(pivot_index);
dutch_flag_partition(A, pivot_index);
int i = 0;
while (i < A.size() && A.get(i) < pivot) {
System.out.print(A.get(i) + " ");
++i;
}
while (i < A.size() && A.get(i) == pivot) {
System.out.print(A.get(i) + " ");
++i;
}
while (i < A.size() && A.get(i) > pivot) {
System.out.print(A.get(i) + " ");
++i;
}
System.out.println();
assert (i == A.size());
}
}
|
3338cf92-2554-4d05-b950-93846c7ec09c
| 7
|
public boolean fireMedium(TableroDos enemy, int x, int y){
if(this.respaX!=0 && this.respaY!=0 && this.pasa){
return this.fireHard(enemy, x, y);
}
else if(enemy.shipMap[x][y]!=" " && this.map.fireMap[x][y]!="x" && this.map.fireMap[x][y]!="o"){
this.map.fireMap[x][y]="x";
this.enemy.posicionesMapaHome[x][y].setIcon(new ImageIcon(getClass().getResource("/imagenes/fire.gif")));
this.respaX=x;
this.respaY=y;
if(this.pasa)
this.pasa=false; // Que juege Normal el prox turno
else
this.pasa=true; // Que Busque en el prox turno
return true;
}else{
this.map.fireMap[x][y]="o";
return false;
}
}
|
9b33af0c-6d27-43f5-a9d8-2b9324fbc04f
| 1
|
@Override
public void testFinished(Description description) {
if (hasPassed()) {
final Xpp3Dom testCase = getCurrentTestCase();
testCase.addChild(createResult(TestState.passed));
testCase.addChild(createNotes(String.format("'%s' PASSED.", description.getDisplayName())));
}
}
|
7ccc5990-4e67-4eed-a3a8-8700baf3be5a
| 3
|
public void run() {
while (true) {
Object obj = receive();
if (obj instanceof ICamera)
deportedClient.update((ICamera) obj);
else if (obj instanceof IObject)
deportedClient.update((IObject) obj);
}
}
|
7b073020-ae60-4aed-babe-77d6b704ebf5
| 1
|
public void writeXml(DataCompiler p, String namefile) {
String to = System.getProperty("user.dir"); // recupero el directorio del proyecto
String separator = System.getProperty("file.separator"); //recupero el separador ex: Windows= '\' , Linux='/'
to = to + separator + "src" + separator + "src" + separator + namefile + ".xml"; // concateno la ruta destino
try {
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(to)));
encoder.writeObject(p);
encoder.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Serialize.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
1195ff88-6d11-4bff-8416-06cab3045d6b
| 5
|
*/
private void ionChange(boolean isChange) {
// Cookie情報用リスト
ArrayList<String> valueList = new ArrayList<String>();
for (Iterator i=isIonRadio.keySet().iterator(); i.hasNext(); ) {
String key = (String)i.next();
boolean before = (boolean)isIonRadio.get(key);
boolean after = ((JRadioButton)ionRadio.get(key)).isSelected();
if (before != after) {
if (isChange) {
isIonRadio.put(key, after);
}
else {
((JRadioButton)ionRadio.get(key)).setSelected(before);
}
}
if ( ((JRadioButton)ionRadio.get(key)).isSelected() ) {
valueList.add(key);
}
}
// イオン種別選択状態をCookieに設定
if (isChange) {
SystemProperties.setDefaultIonList(valueList);
// cm.setCookie(COOKIE_ION, valueList);
}
}
|
7bfbb2c6-4c0e-4920-8949-40d8b36e6c5d
| 0
|
public JTextField getjTextFieldCP() {
return jTextFieldCP;
}
|
b3334e1a-8d13-4625-9707-14580d372ed0
| 7
|
@EventHandler
public void SkeletonPoison(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("Skeleton.Poison.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof Arrow) {
Arrow a = (Arrow) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getSkeletonConfig().getBoolean("Skeleton.Poison.Enabled", true) && shooter instanceof Skeleton && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, plugin.getSkeletonConfig().getInt("Skeleton.Poison.Time"), plugin.getSkeletonConfig().getInt("Skeleton.Poison.Power")));
}
}
}
|
e5915023-5abb-477f-814e-fdb69a807153
| 9
|
@Override
public String get(int start, int end) {
StringBuilder sb = new StringBuilder(end-start+10);
Feature f = null;
int pos = start;
//Find the first overlapped structure variant.
int SVOffset = findFirstOverlappedSV(start, end);
if (SVOffset<0)
SVOffset = 0;
for (int i=SVOffset; i<sv.size(); ++i){
f = sv.get(i);
if (f.start < end && f.end > start) {
if ( pos < f.start )
sb.append(super.get(pos, f.start-1));
//If it is a deletion, then the next position will be
//the position after its end position.
if (f.getClass().getSimpleName().equals("Deletion")) {
pos = f.end+1;
}
//If it is an insertion, then the next position will be
//still its end position.
else if (f.getClass().getSimpleName().equals("Insertion")) {
sb.append(( (Insertion) f).getInserted());
pos = f.end+1;
}
else
throw(new RuntimeException("Unknown SV type."));
}
if (f.start > end) break;
}
if (pos<end)
sb.append(super.get(pos, end));
return sb.toString();
}
|
3d75f05a-0cca-4c71-a739-b991f52f28ce
| 6
|
public static int parseMultiplier(String value) {
value = value.toLowerCase();
if (value.contains("b") || value.contains("m") || value.contains("k")) {
return (int) (Double.parseDouble(value.substring(0, value.length() - 1))
* (value.endsWith("b") ? 1000000000D : value.endsWith("m") ? 1000000
: value.endsWith("k") ? 1000 : 1));
} else {
return Integer.parseInt(value);
}
}
|
72c3ee2c-8b9a-4bea-90e3-06cc157ae793
| 5
|
@PUT
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public TaskList modify(@PathParam("id") int id,
@FormParam("title") @DefaultValue("null") String title,
@FormParam("list_id") @DefaultValue("0") int list_id) {
if (OwnershipDatabase.userOwnsTask(
(String) sr.getAttribute("logged_user"), id)) {
Task formerTodo = TasksDatabase.retrieveTodo(id);
if (title.equals("null"))
title = formerTodo.getTitle();
;
if (list_id == 0)
list_id = formerTodo.getList_id();
Task updatedTodo = new Task(id, title, list_id);
TasksDatabase.updateTodo(updatedTodo);
return updatedTodo;
} else if (OwnershipDatabase.userOwnsList(
(String) sr.getAttribute("logged_user"), id)) {
Listw formerList = ListsDatabase.retrieveList(id);
if (title.equals("null"))
title = formerList.getTitle();
Listw updatedList = new Listw(id, title);
ListsDatabase.updateList(updatedList);
return updatedList;
} else
throw new RuntimeException("Put: Task/List with id " + id
+ " not found or not owned by you");
}
|
9a0429e2-ca37-4f2d-965d-7168c211e5c7
| 3
|
private String extractSessionKey() {
StringBuilder sb=new StringBuilder();
int a,o;
sb.append("Session Key is ");
for (a=44;a<(44+70);a=a+7) {
o=extractIntFromStart(a);
if (checkITA3Char(o)==true) {
sb.append("0x");
if (o<16) sb.append("0");
sb.append(Integer.toHexString(o)+" ");
}
else {
sb.append("<ERROR> ");
}
}
return sb.toString();
}
|
ea18a59d-e7bb-49d2-a02d-4235ba8811a1
| 6
|
public void handleOpenWindow(Packet100OpenWindow par1Packet100OpenWindow)
{
EntityPlayerSP var2 = this.mc.thePlayer;
switch (par1Packet100OpenWindow.inventoryType)
{
case 0:
var2.displayGUIChest(new InventoryBasic(par1Packet100OpenWindow.windowTitle, par1Packet100OpenWindow.slotsCount));
var2.craftingInventory.windowId = par1Packet100OpenWindow.windowId;
break;
case 1:
var2.displayWorkbenchGUI(MathHelper.floor_double(var2.posX), MathHelper.floor_double(var2.posY), MathHelper.floor_double(var2.posZ));
var2.craftingInventory.windowId = par1Packet100OpenWindow.windowId;
break;
case 2:
var2.displayGUIFurnace(new TileEntityFurnace());
var2.craftingInventory.windowId = par1Packet100OpenWindow.windowId;
break;
case 3:
var2.displayGUIDispenser(new TileEntityDispenser());
var2.craftingInventory.windowId = par1Packet100OpenWindow.windowId;
break;
case 4:
var2.displayGUIEnchantment(MathHelper.floor_double(var2.posX), MathHelper.floor_double(var2.posY), MathHelper.floor_double(var2.posZ));
var2.craftingInventory.windowId = par1Packet100OpenWindow.windowId;
break;
case 5:
var2.displayGUIBrewingStand(new TileEntityBrewingStand());
var2.craftingInventory.windowId = par1Packet100OpenWindow.windowId;
break;
default:
ModCompatibilityClient.mlmpOpenWindow(par1Packet100OpenWindow);
}
}
|
063e2a24-8edf-4026-89be-11c0ae5327be
| 1
|
public final Instruction getNextByAddr() {
if (nextByAddr.opcode == opc_impdep1)
return null;
return nextByAddr;
}
|
e3db71e1-bf35-4960-8ceb-64f8599dda82
| 7
|
@Override
public void controleEtAjoute(Entretien entretien) throws ValidationException {
if (entretien == null) {
throw new ValidationException("L'entretien est invalide");
}
if (entretien.getDescription() == null || !StringValidation.VerifString(entretien.getDescription())) {
throw new ValidationException("la description n'est pas valide");
}
Calendar joura = Calendar.getInstance();
joura.add(Calendar.DAY_OF_MONTH, 0);
joura.getTime();
if (entretien.getDateEntretien() == null || entretien.getDateEntretien().after(joura.getTime())) {
throw new ValidationException("Le date n'est pas valide");
}
if (entretien.getKmEntretienFait() == 0) {
throw new ValidationException("Le kilometrage n'est pas valide");
}
if(EntretienDao.addEntretien(entretien)) {
setChanged();
notifyObservers();
}
}
|
e3d33562-b1ce-4136-bcc9-b214d352f92d
| 6
|
public static String GameChoice()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Ask for user input
PrintSeparator('#');
System.out.println("Welcome To The Checkers Game developed by:");
System.out.println(" \t1. Ashish Prasad ashishp@iitrpr.ac.in");
System.out.println(" \t2. Apurv Verma apurvverma@iitrpr.ac.in");
PrintSeparator('-');
System.out.println("Enter 'w/W' if you want to play as white.");
System.out.println("Enter 'b/B' if you want to play as black.");
System.out.println("Enter 'a/A' for two player game.");
System.out.println("Enter 'n/N' for auto play.");
PrintSeparator('#');
String choice = new String();
while (true)
{
try {
System.out.print("Enter your Choice (w/W/b/B/a/A/n/N): ");
choice = br.readLine().toLowerCase();
if (choice.equals("w")||choice.equals("b")||choice.equals("a")||choice.equals("n")){
break;
}
} catch (Exception ex) {}
System.out.println("\nWrong Choice...Type again(0-7): ");
}
return choice;
}
|
e5b7e095-fb2e-48fa-972f-e55d1ac79a0d
| 6
|
@Override
public void execute(CommandSender sender, String[] arg1) {
if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) {
sender.sendMessage(plugin.NO_PERMISSION);
return;
}
ChatPlayer cp = plugin.getChatPlayer(sender.getName());
ArrayList<String> channelList = cp.getChannels();
String current = cp.getCurrentChannel().getName();
String message = ChatColor.DARK_AQUA
+ "Channels you are currently in: ";
for (String data : channelList) {
if (data.equals(current)) {
message += ChatColor.GOLD + data + ", ";
} else {
message += ChatColor.DARK_GRAY + data+", ";
}
}
message = message.substring(0, message.length() - 2);
sender.sendMessage(message);
if (CommandUtil.hasPermission(sender, PERMISSION_NODES_OVERRIDE)) {
message = ChatColor.DARK_AQUA + "All other channels: ";
Set<String> allChannels = plugin.chatChannels.keySet();
for (String data : allChannels) {
if (!channelList.contains(data)) {
message += ChatColor.DARK_GRAY + data + ", ";
}
}
message = message.substring(0, message.length() - 2);
sender.sendMessage(message);
}
}
|
9dda2ad9-a489-4e75-b1e4-c50bea4768a9
| 6
|
public static byte linear2ulaw(int sample) {
int sign, exponent, mantissa, ulawbyte;
if (sample>32767) sample=32767;
else if (sample<-32768) sample=-32768;
/* Get the sample into sign-magnitude. */
sign = (sample >> 8) & 0x80; /* set aside the sign */
if (sign != 0) sample = -sample; /* get magnitude */
if (sample > CLIP) sample = CLIP; /* clip the magnitude */
/* Convert from 16 bit linear to ulaw. */
sample = sample + BIAS;
exponent = exp_lut1[(sample >> 7) & 0xFF];
mantissa = (sample >> (exponent + 3)) & 0x0F;
ulawbyte = ~(sign | (exponent << 4) | mantissa);
if (ZEROTRAP)
if (ulawbyte == 0) ulawbyte = 0x02; /* optional CCITT trap */
return((byte) ulawbyte);
}
|
1bb6d8f7-b0fc-4324-b05a-75a6ae020d72
| 0
|
public CoffeescriptEditor() {
colorManager = new ColorManager();
setDocumentProvider( new CoffeescriptDocumentProvider() );
setSourceViewerConfiguration(new CoffeescriptConfiguration( colorManager ));
}
|
1e57d42b-3719-4a84-8bee-ca7801f548f6
| 0
|
public RouterWorker(Socket clientSocket) {
this.clientSocket = clientSocket;
Setup.println("[RoutingService.run] Conexion abierta desde: " + clientSocket.getInetAddress().getHostAddress());
}
|
972b513e-8664-496a-82cf-10f4ec923727
| 0
|
@Test
public void testDelete() {
fail("Not yet implemented");
}
|
676469a6-d90d-419b-9beb-641f4ea96b27
| 5
|
public static void main(String args[]) {
try {
if (args.length > 1) {
printUsage();
return;
}
PS3TestDriver td;
if (args.length == 0) {
td = new PS3TestDriver(new InputStreamReader(System.in),
new OutputStreamWriter(System.out));
} else {
String fileName = args[0];
File tests = new File (fileName);
if (tests.exists() || tests.canRead()) {
td = new PS3TestDriver(new FileReader(tests),
new OutputStreamWriter(System.out));
} else {
System.err.println("Cannot read from " + tests.toString());
printUsage();
return;
}
}
td.runTests();
} catch (IOException e) {
System.err.println(e.toString());
e.printStackTrace(System.err);
}
}
|
e086fb03-7812-4c68-ac03-35e7e84721b3
| 2
|
private void varDecl(boolean global) throws Exception
{
Type type = typeDecl(global);
Identifier varName = ident();
env.put(varName, defaultVariableValue(varName));
env.putType(varName, type);
while(scan.sym == Token.comma) {
scan.next();
varName = ident();
env.put(varName, defaultVariableValue(varName));
env.putType(varName, type);
}
// look for error
if(scan.sym == Token.semicolon)
scan.next();
else
throw new Exception("var declaration: no semicolon terminating declaration");
}
|
c6c1abb5-1da9-4ef8-96c9-73570c5020e7
| 6
|
public DefaultMutableTreeNode LoadDLLImport(DefaultMutableTreeNode IMPORT,VraReader b)
{
//get the phisical address to data drectory array links to dll import table
int pos2=((int)DataDir[2]);
System.out.println("DLL RVA ARRAY POSITION "+pos2+"");
Vector<JTable> v1=new Vector<JTable>();
//for dll names
Vector<String> v2=new Vector<String>();
Vector<Object> v4=new Vector<Object>();
IMPORT.add(new DefaultMutableTreeNode("DLL IMPORT ARRAY DECODE.H"));
String end="";int DLLS=0,ref=1;
JTable T[];
while(true)
{try{end=b.ReadHEX(pos2,20);}catch(Exception e){System.out.println(e+"");}
if(end.equals("00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ")){break;}
else{
v4.add(new Object[]{"","",""});
v4.add(new Object[]{"","",""});
v4.add(new Object[]{"","",""});
v4.add(new Object[]{"","",""});
v4.add(new Object[]{"","",""});
//unkowen resion whiy i have to do this to get it to read from lowcation corectly
//dec
long ArrayDataDec[]=new long[]{b.ReadDWORD((int)pos2),b.ReadDWORD((int)(pos2+4)),
b.ReadDWORD((int)(pos2+8)),b.ReadDWORD((int)(pos2+12)),b.ReadDWORD((int)(pos2+16))};
//hex
String ArrayDataHex[]=new String[]{b.ReadHEX((int)pos2,4),b.ReadHEX((int)(pos2+4),4),
b.ReadHEX((int)(pos2+8),4),b.ReadHEX((int)(pos2+12),4),b.ReadHEX((int)(pos2+16),4)};
((Object[])v4.get(DLLS))[0]="Original Array DLL Load Functions";
((Object[])v4.get(DLLS))[1]=ArrayDataHex[0];
((Object[])v4.get(DLLS))[2]=ArrayDataDec[0];
((Object[])v4.get(DLLS+1))[0]="Time Date Stamp";
((Object[])v4.get(DLLS+1))[1]=ArrayDataHex[1];
((Object[])v4.get(DLLS+1))[2]=ArrayDataDec[1];
((Object[])v4.get(DLLS+2))[0]="Forwarder Chain";
((Object[])v4.get(DLLS+2))[1]=ArrayDataHex[2];
((Object[])v4.get(DLLS+2))[2]=ArrayDataDec[2];
((Object[])v4.get(DLLS+3))[0]="DLL Name Ram Lowcation";
((Object[])v4.get(DLLS+3))[1]=ArrayDataHex[3];
((Object[])v4.get(DLLS+3))[2]=ArrayDataDec[3];
((Object[])v4.get(DLLS+4))[0]="First Array DLL Load Functions";
((Object[])v4.get(DLLS+4))[1]=ArrayDataHex[4];
((Object[])v4.get(DLLS+4))[2]=ArrayDataDec[4];
//decode to phisical addresses
int OriginalFirst=(int)ArrayDataDec[0];
T=ThunkArrayDecode(OriginalFirst,b);
v1.add(T[0]);v1.add(T[1]);
int namepos2=(int)ArrayDataDec[3];
int First=(int)ArrayDataDec[4];
T=ThunkArrayDecode(First,b);
v1.add(T[0]);v1.add(T[1]);
v2.add(b.ReadASCII(namepos2));
/*System.out.println("position VRA Name "+ArrayDataDec[3]+"");
System.out.println("File position Name "+namepos2+"");
System.out.println("DLL Name "+b.ReadASCII(namepos2));*/
DefaultMutableTreeNode I=new DefaultMutableTreeNode(b.ReadASCII(namepos2));
I.add(new DefaultMutableTreeNode("First Original Array Decode.H#D"+(ref)+""));
I.add(new DefaultMutableTreeNode("Secont Original Array Decode.H#D"+(ref+2)));
I.add(new DefaultMutableTreeNode("First Original Array Lowcation Of Function Names.dll#D"+(ref+1)+""));
I.add(new DefaultMutableTreeNode("Secont Original Array Lowcation Of Function Names.dll#D"+(ref+3)+""));
IMPORT.add(I);
pos2+=20;DLLS+=5;ref+=4;}}
//convert vector into the row data of the table of the decode of this array of the dll
Object RowData[][]=new Object[v4.size()][3];
for(int i=0;i<v4.size();i++)
{RowData[i][0]=((Object[])v4.get(i))[0];
RowData[i][1]=((Object[])v4.get(i))[1];
RowData[i][2]=((Object[])v4.get(i))[2];}
v4.clear();
v1.add(0,new JTable(RowData,new Object[]{"Useage","hex","dec"}));
DLLTable=new JTable[v1.size()];
for(int i=0;i<v1.size();i++){DLLTable[i]=v1.get(i);}
//create the dll name array
DLLName=new String[v2.size()];
for(int i=0;i<v2.size();i++){DLLName[i]=v2.get(i);}
v2.clear();
v1.clear();
return(IMPORT);}
|
f4c6421b-1e1e-45f1-8d97-003cbc69c7e0
| 1
|
public Interface(BufferedImage bg, Sprite sprite)
{
this.bg = bg;
this.sprite = sprite;
this.cX = Game.fieldWidth;
this.cY = Game.fieldHeight;
buttonMap = new HashMap<>();
barMap = new HashMap<>();
selectColor = new Color(255, 255, 255, 128);
line1 = line2 = line3 = line4 = line5 = "";
buttonArray = new Button[BCOUNT];
for(int i = 0; i < BCOUNT; i++)
{
//buttonMap.put(i, addButton("", i, i));
//buttonMap.get(i).disabled = true;
buttonArray[i] = addButton("", i, i);
buttonArray[i].disabled = true;
}
slot = -1;
battleWindow = new Window(125, 75, 450, 300);
}
|
c5e7c125-c086-41b2-adb7-3d38744bfeee
| 7
|
protected final void loadHandlers() {
for (Method m : this.getClass().getMethods()) {
InternalTask itask = m.getAnnotation(InternalTask.class);
if (itask == null)
continue;
Class<?> handledClass = itask.type();
if (handledClass == null)
continue;
if (m.getTypeParameters().length > 1 || m.getTypeParameters().length < 1)
continue;
if (!m.getTypeParameters()[0].getClass().equals(handledClass))
continue;
this.associatedMethods.put(handledClass, m);
}
}
|
0606c825-b9ce-4e84-8990-f474aefa375e
| 0
|
@Override
public int getAge() {
return age;
}
|
fa343270-8566-486c-8dbb-84916388ce5c
| 9
|
public List<Client> searchClient(String usernameOrName) {
Connection conn=null;
try{
conn = dbConnector.getConnection();
if (conn==null) //cannot connect to DB
return null;
Statement st;
ResultSet rs;
String sql;
boolean searchAll = false;
if (usernameOrName==null )
searchAll=true;
usernameOrName = usernameOrName.trim();
if (usernameOrName.isEmpty())
searchAll=true;
if (searchAll) {
sql = "select * from tbClient";
} else {
sql = "select * from tbClient where "
+ " username LIKE '%"+usernameOrName+"%' "
+ " OR fname LIKE '%"+usernameOrName+"%' "
+ " OR lname LIKE '%"+usernameOrName+"%' ";
}
// check does this client's username exist?
st = conn.createStatement();
rs = st.executeQuery(sql);
List<Client> lst = new ArrayList<Client>();
// if exist, return the Client objects
while (rs.next()){
Client client = getClientFromResultSet(rs);
lst.add(client);
}
if (lst.size()<=0)
return null;
else
return lst;
}
catch(Exception e){
e.printStackTrace();
}finally {
try {
if (conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
|
738b0408-62a2-4429-ba65-74aff1ad907f
| 8
|
private static void rsaDecrypterFile(CryptobyConsole console) {
// Input Path to File for decryption
scanner = new Scanner(System.in);
System.out.println("Enter Path to File for Decryption (Type '" + quit + "' to Escape):");
scanner.useDelimiter("\n");
if (scanner.hasNext(quit)) {
rsaCrypterFile(console);
}
cryptFilePath = scanner.next();
// Get Bytes from PlainFile
try {
cryptByte = CryptobyFileManager.getBytesFromFile(cryptFilePath);
} catch (IOException ex) {
CryptobyHelper.printIOExp();
rsaCrypterFile(console);
}
// Input Path saving Path
scanner = new Scanner(System.in);
System.out.println("Enter saving Path for decrypted File (Type '" + quit + "' to Escape):");
scanner.useDelimiter("\n");
if (scanner.hasNext(quit)) {
rsaCrypterFile(console);
}
plainFilePath = scanner.next();
// Input Path to Key File for decryption
scanner = new Scanner(System.in);
System.out.println("Enter Path to Private Key File (Type '" + quit + "' to Escape):");
scanner.useDelimiter("\n");
if (scanner.hasNext(quit)) {
rsaCrypterFile(console);
}
privateKeyPath = scanner.next();
// Get Bytes from Private Key File
try {
privateKeyByte = CryptobyFileManager.getKeyFromFile(privateKeyPath);
} catch (IOException ex) {
CryptobyHelper.printIOExp();
rsaCrypterFile(console);
} catch (NumberFormatException nfex) {
System.out.println("Key File format is not correct!");
rsaCrypterFile(console);
}
// Initial RSA Crypt Object
initRSAKeyGen(console);
// Encrypt the File with given Key
System.out.println("\nDecryption in progress...");
try {
plainByte = console.getCore().getCryptAsym().decrypt(cryptByte, privateKeyByte);
} catch (Exception e) {
System.out.println("\nUnable to decrypt this File!!");
plainByte = null;
// Press Return for Continues
CryptobyHelper.pressEnter();
rsaCrypterFile(console);
}
System.out.println("\nDecryption finished. Saving File now...");
try {
//Put encrypted Bytes to File
CryptobyFileManager.putBytesToFile(plainFilePath, plainByte);
} catch (IOException ex) {
CryptobyHelper.printIOExp();
rsaCrypterFile(console);
}
System.out.println("\nDecrypted File saved to this Path:");
System.out.println(plainFilePath);
// Reset Variables
initRSAKeyGen(console);
cryptByte = null;
plainByte = null;
publicKeyByte = null;
// Back to Menu rsaCrypter with Enter (Return) Key
System.out.println("\nGo back to RSA File Crypter Menu: Press Enter");
CryptobyHelper.pressEnter();
rsaCrypterFile(console);
}
|
45578044-f401-4483-bc51-fe5df18a3b8c
| 2
|
private Node decide() {
char c = input.charAt(offset);
if (c == '(') {
offset++;
return parseDecision();
}
else if (c == '[') {
offset++;
return parseRange();
}
else {
return parseLiteral(true);
}
}
|
f39ac15d-302f-46ca-bfe6-38b45b79fd7f
| 7
|
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(affected==null)
return false;
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
MOB diseaser=invoker;
if(diseaser==null)
diseaser=mob;
if((!mob.amDead())&&((--diseaseTick)<=0))
{
diseaseTick=DISEASE_DELAY();
mob.location().show(mob,null,CMMsg.MSG_NOISE,DISEASE_AFFECT());
int damage=CMLib.dice().roll(2,mob.phyStats().level()+1,1);
if(CMLib.dice().rollPercentage()==1)
damage+=CMLib.dice().roll(10,10,1);
CMLib.combat().postDamage(diseaser,mob,this,damage,CMMsg.MASK_ALWAYS|CMMsg.TYP_DISEASE,-1,null);
catchIt(mob);
return true;
}
return true;
}
|
91ca1e19-06b4-462b-b9c0-dc704cae1381
| 3
|
public synchronized void fileWriter(Quiz quiz)throws RemoteException{
String filePath = "C:/JavaFiles/QuizManager/QuizMasterFile.csv";
File file = new File(filePath);
Set<Question> questionListForNewQuiz=new HashSet<Question>();
BufferedWriter bufferedWriter = null;
//BufferedWriter bufferedWriterForQuestions=null;
try{
//set up the writer to append records to the QuizMasterFile
questionListForNewQuiz=quiz.getQuestionsList();
Iterator<Question> questionIterator = questionListForNewQuiz.iterator();
int totalQuestions=questionListForNewQuiz.size();
bufferedWriter = new BufferedWriter(new FileWriter(file,true));
bufferedWriter.append(quiz.getQuizId()+ "," + quiz.getQuizTitle()+ ","+ totalQuestions + '\n');
while(questionIterator.hasNext()){
Question nextQuestion = questionIterator.next();
String[] choices=nextQuestion.getAnswers();
String questionId= Integer.toString(nextQuestion.getQuestionId());
String questionTitle=nextQuestion.getQuestionTitle();
String choiceOne=choices[0];
String choiceTwo=choices[1];
String choiceThree=choices[2];
String choiceFour=choices[3];
String correctAnswer=Integer.toString(nextQuestion.getCorrectAnswer());
String quizId=Integer.toString(nextQuestion.getQuizId());
bufferedWriter.append(questionId + "," + questionTitle + "," + choiceOne + "," + choiceTwo + "," + choiceThree + "," + choiceFour + "," + correctAnswer + "," + quizId + '\n');
}
}
catch (FileNotFoundException ex) {
System.out.println("File " + file + " does not exist.");
}
catch (IOException ex) {
ex.printStackTrace();
}
finally{
//closeWriter(bufferedWriterForQuestions);
closeWriter(bufferedWriter);
}
}
|
f2c79687-1cab-4e2a-9601-ebde2d910587
| 4
|
public void setPlayer1Piece(JLabel label) {
boolean test = false;
if (test || m_test) {
System.out.println("Drawing :: setPlayer1Piece() BEGIN");
}
if (test || m_test)
System.out.println("Drawing:: setPlayer1Piece() - END");
m_player1Piece = label;
}
|
39e0b1e0-7695-4264-8773-e3f772ea6498
| 5
|
private void validarDatos(String usuario, String contrasenha) throws BusinessException {
String mensaje = "";
if(usuario == null || usuario.isEmpty())
mensaje += "El usuario no puede ser nulo o vacio\n";
if(contrasenha == null || contrasenha.isEmpty())
mensaje += "La contrasena no puede ser nula o vacia\n";
if (!mensaje.isEmpty())
throw new BusinessException(mensaje);
}
|
a1780cbf-1544-4e13-b6cc-4a3bc4167350
| 7
|
public void menu() {
String s;
Boolean exit = false;
Integer option = null;
while (!exit) {
UI.printHeader();
System.out.println("Selecciona una opción a continuación:");
System.out.println("1) Editar servicios");
System.out.println("2) Editar agentes");
System.out.println("3) Editar conexiones");
System.out.println("");
System.out.println("0) Salir");
System.out.println("");
System.out.print("Introduce una opción: ");
try {
BufferedReader bufferRead = new BufferedReader(
new InputStreamReader(System.in));
s = bufferRead.readLine();
option = Integer.parseInt(s);
switch (option) {
case 0:
System.out.print(CLS);
exit = true;
break;
case 1:
servicesUI.menu();
break;
case 2:
agentsUI.menu();
break;
case 3:
connectionsUI.menu();
break;
default:
UI.setError("Opción no válida");
break;
}
} catch (NumberFormatException e) {
UI.setError("Opción no válida");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
e9d9ccbf-25ac-4ef4-8a3d-7f8455eaa83a
| 4
|
private void updatePosition(Entity entity) {
int timePassed = entity.tickStart - tick;
int differenceX = entity.startX * 128 + entity.boundaryDimension * 64;
int differenceY = entity.startY * 128 + entity.boundaryDimension * 64;
entity.x += (differenceX - entity.x) / timePassed;
entity.y += (differenceY - entity.y) / timePassed;
entity.stepsDelayed = 0;
if (entity.direction == 0)
entity.turnDirection = 1024;
if (entity.direction == 1)
entity.turnDirection = 1536;
if (entity.direction == 2)
entity.turnDirection = 0;
if (entity.direction == 3)
entity.turnDirection = 512;
}
|
80ee830e-97d2-4fe6-896a-e86b54ee49be
| 5
|
public PercolationStats(int N, int T) {
if (T <= 0) {
throw new IllegalArgumentException("Provided number of experiments (" + T + ") is not positive.");
}
if (N <= 0) {
throw new IllegalArgumentException("Provided size (" + N + ") is not positive.");
}
if (Integer.MAX_VALUE / N < N) {
throw new IllegalArgumentException("Provided size (" + N + ") is too big for N*N to be indexed by integers.");
}
this.N = N;
this.T = T;
int[] open = new int[T];
for (int exp = 0; exp < T; exp++) {
open[exp] = percSim(N);
}
double totRatio = 1D / (N * N);
this.openFraction = new double[T];
for (int i = 0; i < open.length; i++) {
openFraction[i] = open[i] * totRatio;
}
// Calculate results
mean = meanCalc();
stdev = stdevCalc();
}
|
11466bf0-1dc8-4805-8e5f-689eea890c71
| 8
|
private void costruisciDamiera() //si occupa della costruzione della damiera del pannello.
{
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
{
damieraGrafica[i][j]=new Quadrato(damiera, i, j);
this.add(damieraGrafica[i][j]);
aggiungiListener(i, j, damieraGrafica[i][j]);
}
try //una volta costruita la damiera, con i listener adeguati, si verifica se l'utente può compiere almeno una mossa.
{
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
if(damiera.getPosizione(i, j).getPezzo()!=null && damiera.getPosizione(i, j).getColorePezzo())
if(new Mosse_Possibili(damiera, i, j, true).vuota()==false)
return;
throw new NoSuchElementException();
}
catch(NoSuchElementException e) //si attiva quando l'utente non può muovere (di conseguenza, perde).
{
new Finestra_Sconfitta();
return;
}
}
|
77098bfb-85ed-4f8e-9c24-36c938e4b67d
| 6
|
public Piece getDarkKing(Tile[][] board, boolean isWhite)
{
Piece darkKing = null;
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
//If the space isn't null
if(board[j][i] != null && board[j][i].getPiece() != null)
{
//Get a piece with the name "K" (which should be a king)
if(board[j][i].getPiece().getName().contains("K") && !board[j][i].getPiece().isPieceWhite())
{
darkKing = board[j][i].getPiece();
}
}
}
}
return darkKing;
}
|
494026b4-b8d2-4dac-8f9a-379b04925472
| 1
|
public TreeRow getFirstRow() {
List<TreeRow> children = mRoot.getChildren();
if (!children.isEmpty()) {
return children.get(0);
}
return null;
}
|
e16b2af8-8957-4a18-a4ce-0f69cc57ee5b
| 8
|
private static void diffImages(BufferedImage goodImage, PixImage studentPixImage) {
BufferedImage studentImage = ImageUtils.pixImage2buffer(studentPixImage);
int diffCount = 0;
System.out.println("The difference is:");
if (studentImage.getWidth() != goodImage.getWidth()) {
System.out.println("The width is " + studentImage.getWidth() + " but should be " + goodImage.getWidth());
diffCount++;
}
if (studentImage.getHeight() != goodImage.getHeight()) {
System.out.println("The height is " + studentImage.getHeight() + " but should be " + goodImage.getHeight());
diffCount++;
}
for (int y = 0; y < goodImage.getHeight() && y < studentImage.getHeight(); y++) {
for (int x = 0; x < goodImage.getWidth() && x < studentImage.getWidth(); x++) {
if (goodImage.getRGB(x, y) != studentImage.getRGB(x, y)) {
if (diffCount == MAX_PRINT_SIZE) {
System.out.println(" ...");
return;
}
System.out.println(" (" + x + "," + y + ") is " + new Color(studentImage.getRGB(x, y)) + " but should be " + new Color(goodImage.getRGB(x, y)));
diffCount++;
}
}
}
}
|
827f8f94-efc3-4816-bafa-814d6d2d4897
| 5
|
public TabButton(DataTabButton data) {
this.data = data;
setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_ACTIVE_HEIGHT));
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setLayout(null);
setOpaque(false);
label = new JLabel();
label.setForeground(new Color(200,200,100));
label.setSize(BUTTON_WIDTH-8*2, BUTTON_ACTIVE_HEIGHT);
label.setText(data.text);
label.setIcon(Mgr.icon.getTabIcon(data.iconFilename, false));
add(label);
focused = false;
dragging = false;
visible = true;
moving = false;
lastOrientation = -1;
addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON3){
dragStart(e);
}
}
public void mouseReleased(MouseEvent e) {
if(dragging && e.getButton() == MouseEvent.BUTTON3){
tabDrop();
}
else{
if(getMousePosition() != null && new Rectangle(0, 0, BUTTON_WIDTH, BUTTON_ACTIVE_HEIGHT).contains(getMousePosition())){
mouseClick(e);
}
}
}
public void mouseEntered(MouseEvent e) {
mouseEnter(e);
}
public void mouseExited(MouseEvent e) {
mouseExit(e);
}
});
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
tabDragging(e);
}
@Override
public void mouseMoved(MouseEvent e) {
mouseMove(e);
}
});
setSize(BUTTON_WIDTH, BUTTON_ACTIVE_HEIGHT);
setOrientation(data.orientation);
}
|
02f74bdc-54e2-410b-ac14-5cef2fb576a1
| 0
|
public void setExp(){
hero.setExperience(hero.getExperience() + 3);
}
|
47566413-46fa-4465-9f08-3327a86f0eae
| 4
|
public int getComboBox4 () {
if (jComboBox4.getSelectedIndex() == 0) return 70;
else if (jComboBox4.getSelectedIndex() == 1) return 75;
else if (jComboBox4.getSelectedIndex() == 2) return 80;
else if (jComboBox4.getSelectedIndex() == 3) return 85;
return 90;
}
|
8abda0c4-76b2-4dd2-88f4-b78d4023c4db
| 4
|
private void updateButton() {
// [srk] same protection added to updateColors
// make sure node is not null
if (node == null) {
return ;
} // end if
if (node.isAncestorSelected()) {
button.setSelected(true);
} else {
button.setSelected(false);
}
if (node.isLeaf()) {
button.setNode(false);
} else {
button.setNode(true);
if (node.isExpanded()) {
button.setOpen(true);
} else {
button.setOpen(false);
}
}
button.updateIcon();
}
|
58af45d9-104e-43ec-a51f-43dd8dbedfa3
| 8
|
@Override
public void addColumn(TableColumn column) {
super.addColumn(column);
switch (getColumnCount()) {
case 1:
column.setPreferredWidth(400);
break;
case 2:
column.setPreferredWidth(80);
break;
case 3:
column.setPreferredWidth(50);
break;
case 4:
column.setPreferredWidth(40);
break;
case 5:
column.setPreferredWidth(40);
break;
case 6:
column.setPreferredWidth(80);
break;
case 7:
column.setPreferredWidth(80);
break;
case 8:
column.setPreferredWidth(80);
break;
}
}
|
5f9e0849-0d85-4b03-9576-de7e38e908db
| 2
|
@Override
public void run() {
init();
while(running){
tick();
render();
try{
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
b753c58b-1cb3-4966-a9cc-c6fd2dc9baa5
| 1
|
public void disegnaAlbero(AlberoBin<Integer> a) {
if (a != null) {
altezzaAlbero = altezza(a);
setPreferredSize(new Dimension(NodoGrafico.WIDTH * Mat.pow(2, altezzaAlbero),
(altezzaAlbero + 1) * 3 * NodoGrafico.HEIGHT / 2 + 20));
assegnaNodiGrafici(a);
} else nodiGrafici.clear();
repaint();
select(null);
}
|
2c7ba2fb-61eb-44e6-8f0e-870c1d646539
| 7
|
public boolean addToPrintQueue(GCode code,boolean manual){
if(!state.connected){
// cons.appendText("Not connected");
try {
Thread.sleep(500); //test only
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
if(manual && state.printing){
// cons.appendText("Stop printing first");
return false;
}
if(!manual && !state.printing){
// cons.appendText("Printing stopped");
return false;
}
System.out.println("About to add code "+code.hashCode()+" to print queue:"+printQueue.size());
try {
printQueue.put(code);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
|
b1f7c66a-8f91-4d7e-8a92-11bdba1b0d84
| 7
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HostAndPort other = (HostAndPort) obj;
if (addr == null) {
if (other.addr != null)
return false;
} else if (!addr.equals(other.addr))
return false;
if (port != other.port)
return false;
return true;
}
|
c4d292cd-ad0b-44ad-9093-32c69af53e81
| 3
|
public static List<Dependency> applyIgnoreRules(List<Dependency> dependencies, Set<DependencyRule> ignoreRules) {
if (dependencies == null) {
return null;
}
List<Dependency> result = new ArrayList<Dependency>();
for (Dependency dependency: dependencies) {
if (dependency.findMatchingRule(ignoreRules) == null) {
result.add(new Dependency(dependency));
}
}
return result;
}
|
6d549a8f-568f-4303-8925-85df31bb8ac1
| 5
|
private void bfsTravel(TreeNode root, int level, List<List<Integer>> result){
Queue<TreeNode> maintain = new LinkedList<TreeNode>();
Queue<TreeNode> visited = new LinkedList<TreeNode>();
List<Integer> list = null;
TreeNode tmp = null;
maintain.offer(root);
while(!maintain.isEmpty()){
list = new ArrayList<Integer>();
//get out from maintain
while(!maintain.isEmpty()){
list.add(maintain.peek().val);
visited.offer(maintain.poll());
}
result.add(list);
//add sub-node to maintain
while(!visited.isEmpty()){
tmp = visited.poll();
if(tmp.left != null) maintain.offer(tmp.left);
if(tmp.right != null) maintain.offer(tmp.right);
}
}
}
|
b879922c-24cd-41ce-abae-5a3b1e2ba48d
| 5
|
public Object nextEntity(char ampersand) throws JSONException {
StringBuilder sb = new StringBuilder();
for (; ; ) {
char c = next();
if (Character.isLetterOrDigit(c) || c == '#') {
sb.append(Character.toLowerCase(c));
} else if (c == ';') {
break;
} else {
throw syntaxError("Missing ';' in XML entity: &" + sb);
}
}
String string = sb.toString();
Object object = entity.get(string);
return object != null ? object : ampersand + string + ";";
}
|
42d68120-ff99-4431-a6f3-64a7804e9549
| 5
|
private void leaveEssenceMine() {
if (Util.inEssenceMine() && !Players.getLocal().isMoving()) {
if (Util.walkToAndClick("Enter", Util.portalId)) {
int time = 0;
while (Util.inEssenceMine() && time <= 4000) {
time += 50;
Time.sleep(50);
}
}
}
}
|
bb9ef216-bc9d-47fa-9011-8e431ceb8ff9
| 3
|
public void showAll()
{
Graphics g = null;
long startTime = 0;
long endTime = 0;
int timeToSleep = 1000 / framesPerSec;
for (int i = 0; i < imageList.size(); i++)
{
startTime = System.currentTimeMillis();
this.currIndex = i;
g = this.getGraphics();
draw(g);
g.dispose();
endTime = System.currentTimeMillis();
// sleep
try {
if (endTime - startTime < timeToSleep)
Thread.sleep(timeToSleep-(endTime-startTime));
} catch (InterruptedException ex) {
}
// reset curr index
currIndex = imageList.size() - 1;
}
}
|
77ffe8f0-09c9-4071-ae7c-912841a5ec4c
| 6
|
public void paintComponent(Graphics g) {
// probably draws the tiles
for(int i = 0; i < tilesHeight; i++) {
for(int j = 0; j< tilesWidth; j++) {
g.drawImage(tiles.get(tilesWidth*i + j), j*50, i*50, null);
}
}
////////////////////ACTUAL TREASURES////////////////////////////////
for (int i = 0; i < theTreasures.size(); ++i){
if(theTreasures.get(i).getFound()) {
if (GameGui.debug) System.out.println("Drawing Treasure object " +
i + "\n" + "x = " +
theTreasures.get(i).getX() +
" y = " + theTreasures.get(i).getY());
g.drawImage(theTreasures.get(i).getImage(),
theTreasures.get(i).getX()*50,
theTreasures.get(i).getY()*50,
null);
}
}
////////////////////////////////////////////////////////////////////
// draw the actual player
g.drawImage(player.getCurrentImage(), player.getXPos(), player.getYPos(), null);
Graphics2D g2 = (Graphics2D) g;
if(!message.equals("")) {
g2.setColor(new Color(1f,0f,0f,.5f));
g2.fill(new Rectangle(100,0,250,100));
g2.setFont(new Font(null,Font.BOLD, 20));
g2.setColor(Color.BLACK);
g2.drawString(message, 110, 50);
}
}
|
b8f98369-fec6-4620-82ad-dff7f9962d45
| 1
|
private int jjMoveStringLiteralDfa0_1()
{
switch(curChar)
{
case 10:
return jjStopAtPos(0, 6);
default :
return 1;
}
}
|
336996c1-bd70-49c9-a241-504bec380a36
| 6
|
public static GsArtist[] parseArtists(String data,Gs parent) {
Pattern re=Pattern.compile("\\{result:\\[(.*)\\}");
Matcher m=re.matcher(data);
GsArtist[] res=new GsArtist[1];
if(!m.find()) {
res[0]=null;
return res;
}
String realData=m.group(1);
int size=0;
int pos=0;
for(;;) {
int start=realData.indexOf('{',pos);
if(start==-1)
break;
start=realData.indexOf('{',start+1);
int stop=realData.indexOf('}',start+1);
if(stop==-1)
break;
pos=stop;
GsArtist artist=new GsArtist(realData.substring(start+1,stop),parent,stdReg,stdOrder);
if(!artist.Ok)
continue;
if(size!=0) {
GsArtist[] newArr=new GsArtist[size+1];
System.arraycopy(res, 0, newArr, 0, size);
res=newArr;
}
res[size]=artist;
size++;
}
return res;
}
|
9805f2ba-009f-44cd-b047-e2f2d406450c
| 0
|
public String getName() {
return this.name;
}
|
501ff0fd-d487-4455-8c0d-0e3998c826b3
| 3
|
private String formatDoubleValue(double d)
{
String s;
if(Math.abs(d) > 1000)
{
s = " kJ";
d = d/1000;
if (Math.abs(d) > 1000)
{
s = " MJ";
d = d/1000;
if (Math.abs(d) > 1000)
{
s = " GJ";
d = d/1000;
}
}
}
else
{
s = " J";
}
s = String.format("%.2f", d) + s;
return s;
}
|
9fba56b6-aa88-49e5-98fe-2b1c2fe46f17
| 6
|
public boolean baca(String kode_buku){
boolean adaKesalahan = false;
Connection cn = null;
try{
Class.forName(Koneksi.driver);
} catch (Exception ex){
adaKesalahan = true;
JOptionPane.showMessageDialog(null,"JDBC Driver tidak ditemukan atau rusak\n"+ex,"Kesalahan",JOptionPane.ERROR_MESSAGE);
}
if (!adaKesalahan){
try {
cn = (Connection) DriverManager.getConnection(Koneksi.database+"?user="+Koneksi.user+"&password="+Koneksi.password+"");
} catch (Exception ex) {
adaKesalahan = true;
JOptionPane.showMessageDialog(null,"Koneksi ke"+Koneksi.database+" gagal\n"+ex,"Kesalahan",JOptionPane.ERROR_MESSAGE);
}
if (!adaKesalahan){
try {
String SQLStatemen = "select * from buku where kode_buku='"+kode_buku+"'";
Statement sta = (Statement) cn.createStatement();
ResultSet rset = sta.executeQuery(SQLStatemen);
rset.next();
if (rset.getRow()>0){
this.kodeBuku = rset.getString("kode_buku");
this.judulBuku = rset.getString("judul_buku");
this.Penerbit = rset.getString("penerbit");
sta.close();
rset.close();
} else {
sta.close();
rset.close();
adaKesalahan = true;
JOptionPane.showMessageDialog(null,"Kode Buku\""+kode_buku+"\" tidak ditemukan","Informasi",JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex){
adaKesalahan = true;
JOptionPane.showMessageDialog(null,"Tidak dapat membuka tabel buku\n"+ex,"Kesalahan",JOptionPane.ERROR_MESSAGE);
}
}
}
return !adaKesalahan;
}
|
c85023d0-e79b-46c5-9495-0a3d0789d659
| 0
|
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
|
9d662295-1f42-4724-ae58-2a2e7348f1e5
| 0
|
public static void main(String args[]) {
Color first = Color.black;
Color second = Color.red;
Comparator comp = new ColorComparator();
// //System.out.println(comp.compare(first, second));
}
|
f4c8c739-2c80-4ab0-86b3-e99ca3c8ce5f
| 9
|
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
}
|
ba813bb3-e8f7-43bf-9eae-30128eb7bd01
| 8
|
private ReportDefinition getReportDefinitions(Element documentRootElement) {
ReportDefinition reportDefinition = new ReportDefinition();
reportDefinition.setReportDirectory(AppConstants.REPORT_DIRECTORY);
reportDefinition.setReportType(ReportType.Both);
try {
NodeList reportList = documentRootElement
.getElementsByTagName(REPORT_NODE_NAME);
if (reportList != null && reportList.getLength() > 0) {
Node reportNode = reportList.item(0);
Node reportTypeNode = reportNode.getAttributes().getNamedItem(
ELEMENT_TYPE_ATTR);
String reportTypeName = null;
if (null != reportTypeNode) {
reportTypeName = reportTypeNode.getNodeValue();
}
if (reportTypeName.equalsIgnoreCase(ReportType.SideBySide
.toString()))
reportDefinition.setReportType(ReportType.SideBySide);
if (reportTypeName.equalsIgnoreCase(ReportType.Inline
.toString()))
reportDefinition.setReportType(ReportType.Inline);
if (reportTypeName.equalsIgnoreCase(ReportType.Both.toString()))
reportDefinition.setReportType(ReportType.Both);
// Report directory
Node reportDirectoryNode = reportNode.getAttributes()
.getNamedItem(DIRECTORY_ATTR);
if (null != reportDirectoryNode) {
reportDefinition.setReportDirectory(reportDirectoryNode.getNodeValue());
}
}
} catch (Exception ex) {
ex.printStackTrace();
logger.error(Utils.buildExceptionMessage(ex));
}
return reportDefinition;
}
|
3d041875-2c59-4d50-a706-ec318f201f23
| 0
|
public int getFunctionStartLine() {
return environmentStack.peek().getStartLineNumber();
}
|
f3eb3994-310d-433d-8c04-5dbb7c266be7
| 5
|
public int getRoadSpeed(int city1, int city2) {
for (int i = 0; i < roads.size(); i++) {
String[] s = (String[]) roads.get(i);
int c1 = Integer.valueOf(s[0]);
int c2 = Integer.valueOf(s[1]);
int spd = Integer.valueOf(s[2]);
if ((c1 == city1) && (c2 == city2)) {
return spd;
}
if ((c2 == city1) && (c1 == city2)) {
return spd;
}
}
return 0;
}
|
88f53b56-def3-4534-ab3c-6c71993bcdb4
| 5
|
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((flag == null) ? 0 : flag.hashCode());
result = prime * result + foundationYear;
result = prime * result + idTournament;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((teamSet == null) ? 0 : teamSet.hashCode());
result = prime * result + ((tournamentType == null) ? 0 : tournamentType.hashCode());
return result;
}
|
49527f34-c5d2-4d12-a937-3f6904ed16a8
| 3
|
static long [] getChunkByOffset(int []vsize, int []csize, long offset)
{
long []start = new long[vsize.length];
int [] volume = new int [vsize.length];
volume[0]=1;
for(int i = 1; i < volume.length; i++)
{
volume[i] = volume[i-1]*vsize[i-1];
}
int dsize = 1;
for(int i = volume.length - 1; i >= 0 ; i--)
{
start[i] = offset/(volume[i]*dsize);
start[i] -= start[i]%csize[i];
offset -=volume[i] * (start[i]*dsize);
dsize *= (vsize[i] - start[i]) > csize[i] ? (vsize[i] - start[i]) : csize[i];
}
return start;
}
|
e89d6070-536a-4789-bf8c-3a59cf075e32
| 8
|
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder();
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
this.config.addDefault("api-key", "PUT_API_KEY_HERE");
this.config.addDefault("disable", false);
if (!updaterFile.exists()) {
updaterFile.mkdir();
}
boolean createFile = !updaterConfigFile.exists();
try {
if (createFile) {
updaterConfigFile.createNewFile();
this.config.options().copyDefaults(true);
this.config.save(updaterConfigFile);
} else {
this.config.load(updaterConfigFile);
}
} catch (final Exception e) {
if (createFile) {
plugin.getLogger().severe("The updater could not create configuration at " + updaterFile.getAbsolutePath());
} else {
plugin.getLogger().severe("The updater could not load configuration at " + updaterFile.getAbsolutePath());
}
plugin.getLogger().log(Level.SEVERE, null, e);
}
if (this.config.getBoolean("disable")) {
this.result = UpdateResult.DISABLED;
return;
}
String key = this.config.getString("api-key");
if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e);
this.result = UpdateResult.FAIL_BADID;
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
}
|
e2d5243b-1de3-49bb-b1b7-047b7719b3a6
| 7
|
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if("exit".equals(cmd)) {
setVisible(false);
} else if("start".equals(cmd)) {
setVisible(false);
owner.startBattle();
} else if("add".equals(cmd)) {
addRobot(availableRobotList.getSelectedIndex());
} else if("remove".equals(cmd)) {
removeRobot(selectedRobotList.getSelectedIndex());
} else if("addall".equals(cmd)) {
int size = availableRobots.size();
for(int i = 0; i < size; ++i) {
selectedRobots.addElement(availableRobots.get(i));
}
okButton.setEnabled(true);
} else if("removeall".equals(cmd)) {
selectedRobots.removeAllElements();
okButton.setEnabled(false);
}
}
|
0d536293-7f2b-4118-9552-eeb2658ca215
| 5
|
public int kmeans(Data data) throws OutOfRangeSampleSize{
int numberOfIterations = 0;
C.initializeCentroids(data);
boolean changedCluster=false;
do{
numberOfIterations++;
changedCluster = false;
for(int i=0; i<data.getNumberOfExamples(); i++){
Cluster nearestCluster = C.nearestCluster(data.getItemSet(i));
Cluster oldCluster = C.currentCluster(i);
boolean currentChange=nearestCluster.addData(i);
if(currentChange)
changedCluster=true;
if(currentChange && oldCluster!=null)
oldCluster.removeTuple(i);
}
C.updateCentroids(data);
}while(changedCluster);
return numberOfIterations;
}
|
047aee8f-d247-4ba2-bdbe-13886f87bf81
| 8
|
public void drawCMaps(Graphics g)
{
Rectangle r = getBounds();
int elements = data3d.GetNumElements();
int elem = data3d.GetActiveElement();
double sizex = (r.width-1)/(double) elements;
int sizey = (r.height-1)/ 4;
for (int e=0;e < elements;e++)
{
for (int y=0;y < r.height;y++) // iterates through the y pixels
{
g.setColor(GetCMapColor(e,r.height-y-1,r.height));
g.drawLine((int) (e*sizex), y, (int) ((e+1)*sizex), y);
}
g.setColor(Color.white);
if (e == data3d.HistoX)
g.drawString("HX",(int)(e*sizex+5),(int)(1.0*sizey)); // +(1*sizex/3-10)
if (e == data3d.HistoY)
g.drawString("HY",(int)(e*sizex+5),(int)(1.33*sizey));
if (e == data3d.HistoZ)
g.drawString("HZ",(int)(e*sizex+5),(int)(1.66*sizey));
if (e == data3d.GateElem)
if (data3d.GateActive)
g.drawString("GA",(int)(e*sizex+5),(int) 3.0*sizey);
else
g.drawString("G",(int)(e*sizex+5),(int) 3.0*sizey);
if (data3d.InOverlayDispl(e))
g.drawString("Ov",(int)(e*sizex+0) ,(int) 4.0*sizey);
// g.drawString(mytitle,10,10);
}
g.setColor(Color.red);
g.drawRect(elem*r.width/elements,0,(int)sizex,r.height);
super.paint(g);
}
|
925e08e4-9dbc-4340-87cf-a29d99cf89d2
| 9
|
public void update(){
if(happen){
/* ウィンドウ更新 */
mes_window.update();
command_window.update();
/* 敵とエフェクト更新 */
enemy.update();
effect_manager.update();
/* 状態遷移 */
final STATE st = this.now_state;
if(this.mes_window.get_printing_message()) return;//メッセージ表示中は戦闘を進めない
switch(st){
case STATE_ATTACKING://プレイヤーが攻撃中
if(!attack_effect.get_active()){
/* エフェクト終了 */
this.enemy.state.HP -= enemy_damage;//被弾
String[] conv = {enemy.state.NAME + "に" + String.valueOf(enemy_damage) + "ポイントのダメージをあたえた!"};
this.mes_window.set_contents(conv);
this.now_state = STATE.STATE_ENEMY_TURN;
}
break;
case STATE_PLAYER_TURN://プレイヤーのターン
if(player != null) {
player.set_now_state(Player.STATE.STATE_BATTLE_EVENT);
}
break;
case STATE_ENEMY_TURN://敵のターン
System.out.println(enemy.state.HP);
if(this.enemy.state.HP <= 0){//勝利
String[] conv = {enemy.state.NAME + "をたおした!"};
this.enemy.state.HP = enemy.state.MAX_HP;
this.mes_window.set_contents(conv);
this.now_state = STATE.STATE_NONE;
this.enemy_damage = 0;
player.LEVEL_UP(enemy.level);
player.set_now_state(Player.STATE.STATE_BATTLE_WIN);
}
else{
/* 敵の攻撃 */
int player_damage = Math.max(this.enemy.state.ATTACK / 2 - player.status.DEFFENCE / 4,0);
String[] conv = {enemy.state.NAME + "のこうげき!" + player.status.NAME + "は" + player_damage + "ポイントのダメージをうけた!"};
this.mes_window.set_contents(conv);
player.damaged(this.enemy,player_damage);
if(player.status.HP <= 0){
this.now_state = STATE.STATE_NONE;
this.enemy.state.HP = this.enemy.state.MAX_HP;
}
else this.now_state = STATE.STATE_PLAYER_TURN;
}
break;
default:
break;
}
}
}
|
4c68e074-d65e-498e-8e48-69de7b63bf07
| 5
|
@Override
public Role createRole(Role role) {
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
cn = ConnectionHelper.getConnection();
ps = cn.prepareStatement(QTPL_INSERT_ROLE,
new String[] { "role_id" });
ps.setString(1, role.getName());
ps.setString(2, role.getDescription());
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
int roleId = rs.getInt(1);
role.setRoleId(roleId);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { ps.close(); } catch (SQLException e) { e.printStackTrace(); }
try { cn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
return role;
}
|
14e06e1c-a084-4179-820d-b3d7796b76a8
| 3
|
public int numOwned() {
int ret = 0;
final String tag = getTag();
for (int i = 1; /* loop until broken */; i++) {
GenericObject prov = dataSource.getProvince(i);
if (prov == null)
break;
if (prov.getString("owner").equals(tag))
ret++;
}
return ret;
}
|
9b36961f-cb66-429a-aa27-8e5a796d4215
| 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(Frm_CadCidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_CadCidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_CadCidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_CadCidade.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 Frm_CadCidade().setVisible(true);
}
});
}
|
e1555a56-112e-43db-89d9-1044fa22a183
| 6
|
public static void main(String[] args)
{
int i;// only used in first loop. Other variables are declared in the for statements
Scanner keyboard = new Scanner(System.in);
do{
System.out.println();
System.out.print("Enter a positive integer that is no greater than 15: ");
i = keyboard.nextInt();
if(i < 1 || i > 15)
{
System.out.println("Number not in accepted range (Positive AND less than or equal to 15)"); // This first loop just makes the user enter the right value
}
}while(i < 1 || i > 15);
System.out.println();
for(int x = 1; x <= i; x++)
{
for(int y = 1; y <= i; y++) // Nested for-loop was easiest to construct, in my opinion. Others didn't look so concise
{
System.out.print("X");
}
System.out.println();
}
}
|
531f81c1-1002-4789-a57c-561e4c508f58
| 8
|
public boolean canJump(int[] A) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int maxr = 0;
int i = 0;
while (i < A.length) {
maxr = A[i];
if (A[i] == 0 && i < A.length-1) return false;
if (i+A[i] >= A.length-1) return true;
else {
int nextmaxindex = i;
for (int j = i; j <= i+A[i]; j++) {
if (j+A[j] > nextmaxindex) {
nextmaxindex = j+A[j];
}
}
if (nextmaxindex >= A.length) {
return true;
} else if (A[nextmaxindex] == 0) {
return false;
}
i = nextmaxindex;
}
}
return true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.