method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
da5bfffb-8c28-4c44-acb1-02e1a1972d8c | 0 | public PhpposPeopleEntity getPeopleEntity(int idPeople){
return (PhpposPeopleEntity) getHibernateTemplate().get(PhpposPeopleEntity.class, idPeople);
} |
a8861d4c-22bb-4cb9-b7a4-025a1bc1af64 | 2 | public void setNametextZoomedFontcolor(int[] fontcolor) {
if ((fontcolor == null) || (fontcolor.length != 4)) {
this.nametextZoomedFontColor = UIFontInits.NAMEZOOMED.getColor();
} else {
this.nametextZoomedFontColor = fontcolor;
}
somethingChanged();
} |
216a482c-2cfa-46f4-87f6-690111aecf34 | 3 | private void geteof()
{
if(recno>reccount)
{
recno = reccount+1;
if(Idx!=null) Idx.recno = recno;
else if(cdx_file) Cdx.recno = recno;
}
eof = (recno>reccount);
} |
53f2c61b-c7c4-4003-9e90-4c2af6bc8418 | 2 | public void sendMessage(Player player) {
Long lastTime = lastMessageTimes.get(player);
if (lastTime != null && System.currentTimeMillis() - lastTime <= coolDown)
return;
player.sendMessage(message);
lastMessageTimes.put(player, System.currentTimeMillis());
} |
685e586e-2357-4a27-a06e-1cfbb9baa395 | 1 | @Test
public void testMakePaymentsWithProfile() {
Gateway beanstream = new Gateway("v1", 300200578,
"4BaD82D9197b4cc4b70a221911eE9f70", // payments API passcode
"D97D3BE1EE964A6193D17A571D9FBC80", // profiles API passcode
"4e6Ff318bee64EA391609de89aD4CF5d");// reporting API passcode
Address billing = getTestCardValidAddress();
Card card = new Card().setName("JANE DOE")
.setNumber("5100000010001004")
.setExpiryMonth("12")
.setExpiryYear("18")
.setCvd("123");
try {
ProfileResponse profile = beanstream.profiles().createProfile(card, billing);
ProfilePaymentRequest paymentRequest = new ProfilePaymentRequest();
paymentRequest.setProfile(new ProfilePaymentRequestData()
.setCardId(1)
.setCustomerCode(profile.getId()));
paymentRequest.setAmount(13);
paymentRequest.setOrderNumber(getRandomOrderId("TEST"));
// make a regular payment
PaymentResponse result = beanstream.payments().makePayment(paymentRequest);
Assert.assertNotNull(result);
// run a pre-auth
paymentRequest.setAmount(100)
.setOrderNumber(getRandomOrderId("TEST"));
result = beanstream.payments().preAuth(paymentRequest);
Assert.assertNotNull(result);
Assert.assertTrue("PA".equals(result.type));
// complete the pre-auth
result = beanstream.payments().preAuthCompletion(result.id, 100);
Assert.assertNotNull(result);
Assert.assertTrue("PAC".equals(result.type));
} catch (BeanstreamApiException ex) {
Logger.getLogger(SampleTransactions.class.getName()).log(Level.SEVERE, null, ex);
Assert.fail(ex.getMessage());
}
} |
cc76b120-ed7c-4a63-9ff9-4f79d3eec471 | 5 | private void ValidarCampos() throws Exception{
if(jTextField_Codigo.getText().trim().length() == 0){
throw new Exception("Preencha o campo Código");
}
if(jTextField_Nome.getText().trim().length() == 0){
throw new Exception("Preencha o campo Nome");
}
if(jTextField_Preco.getText().trim().length() == 0){
throw new Exception("Preencha o campo Preço");
}
if(jTextField_Codigo.getText().trim().length() > 3){
throw(new Exception("O campo Código tem no máximo 3 caracteres"));
}
try{
Double.parseDouble(jTextField_Preco.getText());
}catch(Exception e){
throw new Exception("Preencha o campo Preço corretamente");
}
} |
9e64a258-26be-4f44-ba6b-291bed19329f | 0 | public void setjLabelVille(JLabel jLabelVille) {
this.jLabelVille = jLabelVille;
} |
2480a266-7c79-4a80-a5f6-3640ddae3587 | 7 | private int jjMoveStringLiteralDfa0_0()
{
switch(curChar)
{
case 40:
return jjStopAtPos(0, 10);
case 41:
return jjStopAtPos(0, 11);
case 42:
return jjStopAtPos(0, 6);
case 43:
return jjStopAtPos(0, 8);
case 45:
return jjStopAtPos(0, 9);
case 47:
return jjStopAtPos(0, 7);
case 61:
return jjStopAtPos(0, 5);
default :
return jjMoveNfa_0(0, 0);
}
} |
7be1a0a1-4254-40be-a3d6-ded47b6de855 | 5 | public static String removeFormatting(String line) {
int length = line.length();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
char ch = line.charAt(i);
if (ch == '\u000f' || ch == '\u0002' || ch == '\u001f' || ch == '\u0016') {
// Don't add this character.
}
else {
buffer.append(ch);
}
}
return buffer.toString();
} |
5bc9de9b-ee60-44be-be20-778d0447da4e | 0 | public Entradas getEntradasIdEntrada() {
return entradasIdEntrada;
} |
dbffede7-3594-4882-a28b-b44f993c82c9 | 1 | @Override
public void mouseClicked(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
GuiUtils.navigate(uri);
}
} |
d2b6f139-9d83-4180-9dde-91b3811a3d4f | 4 | private boolean initTemplateFile() {
String location = OnlineUsers.directory+OnlineUsers.flatfileTemplate;
if (!new File(location).exists()) {
FileWriter writer = null;
try {
writer = new FileWriter(location);
writer.write("#This is the template file for OnlineUsers\r\n");
writer.write("#Replacement Values Are:\r\n");
writer.write("#{username}, {timestamp}, {shorttime}, {longtime}, {online-true-false}, {online-offline}, {online-0-1}\r\n");
writer.write("#Be sure to leave the #beginusers and #endusers lines in!\r\n");
writer.write("Online Users Are:\r\n");
writer.write("#beginusers\r\n");
writer.write("{username} last logged on at {longtime}\r\n");
writer.write("#endusers\r\n");
} catch (Exception e) {
log.log(Level.SEVERE, "Exception while creating " + location, e);
} finally {
try {
if (writer != null) {
writer.close();
return true;
}
} catch (IOException e) {
log.log(Level.SEVERE, "Exception while closing writer for " + location, e);
}
}
} else {
return true;
}
return false;
} |
f68f1f0b-2c2e-4823-b8ed-7e7e5365681a | 0 | public int getNewMarkPosition() {
return this.newMarkPosition;
} |
6e73bc6f-446b-4e02-bcea-573fa56e7f66 | 3 | public int put(int key, int n) {
int pos, t = 1;
while (t < m) {
pos = toHash(key, t);
if (table[pos] == null) {
table[pos] = new HashEntry(key, t);
// ???????????????????????????????????????????????????????????????????????????????????? //
// ???????????????????????????????????????????????????????????????????????????????????? //
if (n % (Math.ceil(m / 50)) == 0) {
Stats stats = new Stats(m, n, t);
Main.statsDouble.add(stats);
}
// ???????????????????????????????????????????????????????????????????????????????????? //
// ???????????????????????????????????????????????????????????????????????????????????? //
return t;
}
t++;
}
return -1;
} |
27519a61-6ffc-40bd-b2af-d60dfd8ecc7b | 3 | private int getPlayerIDFromUser(String prompt, String[] arrplay) {
while(true){
try {
String Name = PlayerSelectFrame.choosePlayer(prompt, arrplay);
if (Name.equals("NONE")) return 0;
return RunFileGame.getPlayerIDFromName(Name);
} catch (WrongNameException e) {
displayError("FUCK OFF THATS NOT A NAME");
}
}
} |
9f89c0da-e053-43fc-8819-a10afa200fb9 | 1 | @Override
public int getNextPage() {
return (hasNextPage()) ? this.currPage+1 : this.pages;
} |
638bcc49-44d5-4f0a-990d-1691b89a4649 | 9 | public void evaluateParticles() {
for (Particle particle : particles) {
// evaluate all particles and update personal fitnesses
double fitness = fitnessEvaluation.evaluate(particle);
if (fitness > fitnessThreshold) {
particle.updatePersonalBestPosition(fitness);
particle.updateGlobalBestPosition(particle.position, fitness);
}
// evaluate all particles and update personal communication fitnesses
double communication = communicationEvaluation.evaluate(particle);
particle.updateCommunicationPersonalBestPosition(communication);
particle.updateCommunicationGlobalBestPosition(particle.position, communication);
}
// find the best position anyone knows about within communication range for each particle
for (Particle particle : particles) {
double globalBestFitness = particle.getGlobalBestFitness();
Particle globalBestParticle = particle;
double communicationGlobalBestFitness = particle.getCommunicationGlobalBestFitness();
Particle communicationGlobalBestParticle = particle;
List<Particle> neighbors = getNeighbors(particle);
//System.out.println(neighbors.size());
// force exploration if no solution found yet
double[] exploration = new double[particle.globalBestPosition.length];
for (int i = 0; i < exploration.length; i++)
exploration[i] = 1;
for (Particle neighbor : neighbors) {
if (neighbor.getGlobalBestFitness() > globalBestFitness) {
globalBestFitness = neighbor.getGlobalBestFitness();
globalBestParticle = neighbor;
}
if (neighbor.getCommunicationGlobalBestFitness() > communicationGlobalBestFitness) {
communicationGlobalBestFitness = neighbor.getCommunicationGlobalBestFitness();
communicationGlobalBestParticle = neighbor;
}
// force exploration if no solution found yet
for (int i = 0; i < neighbor.position.length; i++)
exploration[i] *= -neighbor.position[i];
}
/*
if (particle.globalBestFitness == 0)
for (int i = 0; i < exploration.length; i++)
particle.globalBestPosition[i] = exploration[i];
if (particle.globalBestFitness == 0)
for (int i = 0; i < exploration.length; i++)
particle.personalBestPosition[i] = exploration[i];
*/
// update global best solutions
particle.updateGlobalBestPosition(globalBestParticle.getGlobalBestPosition(), globalBestParticle.getGlobalBestFitness());
particle.updateCommunicationGlobalBestPosition(communicationGlobalBestParticle.getCommunicationGlobalBestPosition(),
communicationGlobalBestParticle.getCommunicationGlobalBestFitness());
// update server's belief of the solution
for (Particle neighbor : neighbors) {
neighbor.serverUpdateSolution(particle.globalBestPosition, particle.globalBestFitness, particle.timestep - particle.lastCommunicationTimestep + 1);
}
}
//System.out.println(particles.get(0).globalBestFitness+" vs "+particles.get(1).globalBestFitness+" vs "+particles.get(2).globalBestFitness);
//System.out.println(particles.get(0).globalBestFitness+" at ("+particles.get(0).globalBestPosition[0]+","+particles.get(0).globalBestPosition[1]+")");
} |
8f7706a1-a866-4303-b6a8-b80c895cc008 | 8 | @Override
public boolean onCommand(CommandSender sender, Command command, String lable, String[] args) {
sender.sendMessage(ChatColor.RED + "=====[ MonoBoxel v" + master.getDescription().getVersion()
+ " Info ] =====");
List<String> worldNames = new ArrayList<String>();
for (MultiverseWorld world : master.getMVCore().getMVWorldManager().getMVWorlds())
worldNames.add(world.getName());
for (String worldName : master.getMVCore().getMVWorldManager().getUnloadedWorlds())
worldNames.add(worldName);
int numBoxels = 0;
sender.sendMessage(ChatColor.WHITE + "Boxels:");
for (String worldName : worldNames) {
boolean[] boxResult = master.getMBWorldManager().isBoxel(worldName);
// not a loaded nor an unloaded Boxel
if (!boxResult[0] && !boxResult[1])
continue;
String msg = "";
numBoxels++;
if (boxResult[1])
msg += ChatColor.WHITE;
else
msg += ChatColor.GRAY;
msg += GenUtils.deboxelizeName(worldName, master) + " - ";
if (boxResult[1]) {
if (master.getMVCore().getMVWorldManager().getMVWorld(worldName).getCBWorld().getPlayers().size() == 0)
msg += ChatColor.AQUA + "No players inside. UnloadThread: "
+ master.getMBWorldManager().getUnloadId(worldName);
else
msg += ChatColor.GREEN + "Players inside.";
} else
msg += ChatColor.GOLD + "UNLOADED";
sender.sendMessage(msg);
}
sender.sendMessage(String.valueOf(numBoxels) + " Boxels are currently registered on this server.");
sender.sendMessage("The current Boxel prefix is: " + master.getBoxelPrefix());
sender.sendMessage("The current group Boxel prefix is: " + master.getBoxelGroupPrefix());
return true;
} |
b237c7ae-92a8-4eba-854e-90d39598d8bc | 1 | public void StartGameServer(String gameName)
{
if(broadcastServer.running)
broadcastServer.stopServer();
broadcastServer.startServer(gameName);
} |
7aabbeb7-0154-445f-b545-2b620cdb8c84 | 1 | public static void main(String[] args) throws Exception {
StaticDynamicUncertaintyWithADIULHSolver solver = new StaticDynamicUncertaintyWithADIULHSolver();
PrintStream filePrintStream = new PrintStream(new File("results/ADI-Cost-Experiment1b.csv"));
PrintStream[] printStreams = new PrintStream[2];
printStreams[0] = System.out;
printStreams[1] = filePrintStream;
MultiPrintStreamWrapper out = new MultiPrintStreamWrapper(printStreams);
out.println("l;0.25;0.5;0.75;1.0;1.25;1.5;1.75;2.0");
AbstractStochasticLotSizingProblem problem;
AbstractStochasticLotSizingSolution solution;
DecimalFormat lFormat = new DecimalFormat("00", new DecimalFormatSymbols(Locale.US));
DecimalFormat costFormat = new DecimalFormat("#####0.00000", new DecimalFormatSymbols(Locale.US));
//Fixed problem parameters
int T = 20;
float alpha = .95f;
double setupCost = 2500;
for(int l = 1; l < 21; l++){
out.print(lFormat.format(l));
TriangleDivisionNormalDistributedOrdersGenerator orderGenerator = new TriangleDivisionNormalDistributedOrdersGenerator(l, 0);
//Constant(100)
problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, 0.25, setupCost, alpha, orderGenerator);
solution = solver.solve(problem);
out.print(";"+costFormat.format(solution.getObjectiveValue()));
//Constant(100)
problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, 0.5, setupCost, alpha, orderGenerator);
solution = solver.solve(problem);
out.print(";"+costFormat.format(solution.getObjectiveValue()));
//Constant(100)
problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, 0.75, setupCost, alpha, orderGenerator);
solution = solver.solve(problem);
out.print(";"+costFormat.format(solution.getObjectiveValue()));
//Constant(100)
problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, 1.0, setupCost, alpha, orderGenerator);
solution = solver.solve(problem);
out.print(";"+costFormat.format(solution.getObjectiveValue()));
//Constant(100)
problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, 1.25, setupCost, alpha, orderGenerator);
solution = solver.solve(problem);
out.print(";"+costFormat.format(solution.getObjectiveValue()));
//Constant(100)
problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, 1.5, setupCost, alpha, orderGenerator);
solution = solver.solve(problem);
out.print(";"+costFormat.format(solution.getObjectiveValue()));
//Constant(100)
problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, 1.75, setupCost, alpha, orderGenerator);
solution = solver.solve(problem);
out.print(";"+costFormat.format(solution.getObjectiveValue()));
//Constant(100)
problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, 2.0, setupCost, alpha, orderGenerator);
solution = solver.solve(problem);
out.print(";"+costFormat.format(solution.getObjectiveValue()));
out.println();
}
filePrintStream.flush();
out.close();
} |
a5fe1190-b83d-4498-9a57-f22222f287fd | 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(KasiyerPencereV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(KasiyerPencereV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(KasiyerPencereV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(KasiyerPencereV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new KasiyerPencereV().setVisible(true);
}
});
} |
74d93bd9-3e2c-4eb1-af7f-c33afc79757c | 8 | @Override
public void action() {
block(delay);
ACLMessage mensagem = agente.receive();
if(mensagem != null){
System.out.println("Recebi mensagem AP");
// Se o protocolo for FIPA CONSTRACT NET
if(mensagem.getProtocol().equals(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET)){
// SE for do tipo CFP
if(mensagem.getPerformative() == ACLMessage.CFP ){
agente.addMensagemCFP(mensagem);
}else if(mensagem.getPerformative() == ACLMessage.ACCEPT_PROPOSAL){
System.out.println("ACLMessage.ACCEPT_PROPOSAL");
Random rand = new Random();
ACLMessage resposta = mensagem.createReply();
resposta.setProtocol(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET);
if(rand.nextInt(9) <= agente.getProbabilidadeDeAcerto()){
resposta.setPerformative(ACLMessage.INFORM);
try {
resposta.setContentObject(mensagem.getContentObject());
agente.send(resposta);
} catch (IOException | UnreadableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else{
resposta.setPerformative(ACLMessage.FAILURE);
try {
resposta.setContentObject(mensagem.getContentObject());
} catch (IOException | UnreadableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
agente.send(resposta);
}
}else if(mensagem.getPerformative() == ACLMessage.REJECT_PROPOSAL){
System.out.println("Minha proposta foi rejeitada" + agente.getLocalName());
}
} else{
block();
}
}else{
block();
}
} |
9708b18b-9777-4184-8d65-7b363e77b695 | 5 | public boolean comprar(final Precio precioAMejorar){
//comprobamos que tengamos suficientes puntos
int aGastar = puntos - precioAMejorar.getActual();
if(aGastar >= 0){
//incrementar nos devolverá la cantidad total que costó
// dicha incrementación
int aRestar = precioAMejorar.incrementarActual();
puntos -= aRestar;
String mejorar = precioAMejorar.getClave();
switch(mejorar){
case Precios.FUERZA: fuerza++;break;
case Precios.MUNICION: municionMax++;break;
case Precios.RESISTENCIA:saludTotal++;break;
case Precios.VIDAS: vidas++;break;
}
return true;
}
return false;
} |
3cba5856-4657-41e7-95f2-6391c627d7a5 | 1 | public synchronized void updateClients ()
{
for (int i = 0 ; i < flexclients.size () ; i++)
{
TcpThread currThread = (TcpThread) flexclients.get (i);
currThread.ID = i;
}
} |
a298e06a-f8c0-4d96-bf0c-92f07040a33c | 3 | @Override
public boolean authorize(AuthorizationToken token) {
if (token.getType().equals(getType())) {
if (userExists(token.getId()) && userAccess.get(token.getId())) {
return true;
}
System.out.println("Access denied.");
}
else {
System.out.println("Invalid AuthorizationToken.");
}
return false;
} |
5f41e628-b16a-47b1-bb47-38206fcee7fb | 7 | @Override
protected void calculateThumbLocation() {
// Call superclass method for lower thumb location.
super.calculateThumbLocation();
// Adjust upper value to snap to ticks if necessary.
if (slider.getSnapToTicks()) {
int upperValue = slider.getValue() + slider.getExtent();
int snappedValue = upperValue;
int majorTickSpacing = slider.getMajorTickSpacing();
int minorTickSpacing = slider.getMinorTickSpacing();
int tickSpacing = 0;
if (minorTickSpacing > 0) {
tickSpacing = minorTickSpacing;
} else if (majorTickSpacing > 0) {
tickSpacing = majorTickSpacing;
}
if (tickSpacing != 0) {
// If it's not on a tick, change the value
if ((upperValue - slider.getMinimum()) % tickSpacing != 0) {
float temp = (float)(upperValue - slider.getMinimum()) / (float)tickSpacing;
int whichTick = Math.round(temp);
snappedValue = slider.getMinimum() + (whichTick * tickSpacing);
}
if (snappedValue != upperValue) {
slider.setExtent(snappedValue - slider.getValue());
}
}
}
// Calculate upper thumb location. The thumb is centered over its
// value on the track.
if (slider.getOrientation() == JSlider.HORIZONTAL) {
int upperPosition = xPositionForValue(slider.getValue() + slider.getExtent());
upperThumbRect.x = upperPosition - (upperThumbRect.width / 2);
upperThumbRect.y = trackRect.y;
} else {
int upperPosition = yPositionForValue(slider.getValue() + slider.getExtent());
upperThumbRect.x = trackRect.x;
upperThumbRect.y = upperPosition - (upperThumbRect.height / 2);
}
} |
14db55fb-0ea7-4c49-b1d9-1bdf6195574a | 7 | public Field[] getFields(Class parentClass, boolean isDeclared, String... strings) throws NoSuchFieldException {
Field[] fields = new Field[strings.length];
for (int len = 0; len < strings.length; ++len) {
String string = strings[len];
if (string != null || string != "") {
if (isDeclared) {
fields[len] = parentClass.getDeclaredField(string);
} else {
fields[len] = parentClass.getField(string);
}
}
}
Field[] fields1 = null;
int length = 0;
for (int len = 0; len < fields.length; ++len) {
if (fields[len] != null) {
if (fields1 == null) fields1 = new Field[1];
else fields1 = new Field[length + 1];
fields1[length] = fields[len];
++length;
}
}
return fields1;
} |
7bd48e74-2ced-46f2-8a91-4c2d2c604068 | 4 | private static boolean isUpdateAvailable(URI remoteUri, File localFile)
{
URLConnection conn;
try
{
conn = remoteUri.toURL().openConnection();
}
catch (MalformedURLException ex)
{
//log.error("An exception occurred", ex);
return false;
}
catch (IOException ex)
{
//log.error("An exception occurred", ex);
return false;
}
if (!(conn instanceof HttpURLConnection))
{
// don't bother with non-http connections
return false;
}
long localLastMod = localFile.lastModified();
long remoteLastMod = 0L;
HttpURLConnection httpconn = (HttpURLConnection) conn;
// disable caching so we don't get in feedback loop with ResponseCache
httpconn.setUseCaches(false);
try
{
httpconn.connect();
remoteLastMod = httpconn.getLastModified();
}
catch (IOException ex)
{
// log.error("An exception occurred", ex);();
return false;
}
finally
{
httpconn.disconnect();
}
return (remoteLastMod > localLastMod);
} |
fdb04d8f-bf88-4287-a2f4-25a29158aad9 | 9 | public static Cons mostSpecificRelations(Cons relationrefs, boolean classifyfirstP) {
{ Cons relations = Stella.NIL;
{ Stella_Object r = null;
Cons iter000 = relationrefs;
Cons collect000 = null;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
r = iter000.value;
if (collect000 == null) {
{
collect000 = Cons.cons(Logic.getRelation(r), Stella.NIL);
if (relations == Stella.NIL) {
relations = collect000;
}
else {
Cons.addConsToEndOfConsList(relations, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(Logic.getRelation(r), Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
relations = relations.removeDuplicates();
if (relations.rest == Stella.NIL) {
return (relations);
}
if (classifyfirstP) {
{ Object old$Classificationsession$000 = Logic.$CLASSIFICATIONSESSION$.get();
try {
Native.setSpecial(Logic.$CLASSIFICATIONSESSION$, Logic.getClassificationSession(Logic.KWD_DESCRIPTION));
{ Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$CONTEXT$, Logic.getClassificationWorld());
{ Description youngestrelation = ((Description)(relations.value));
{ Description r = null;
Cons iter001 = relations.rest;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
r = ((Description)(iter001.value));
if (r.introductionTimestamp() > youngestrelation.introductionTimestamp()) {
youngestrelation = r;
}
}
}
{ Description r = null;
Cons iter002 = relations;
for (;!(iter002 == Stella.NIL); iter002 = iter002.rest) {
r = ((Description)(iter002.value));
if (!LogicObject.upclassifiedLaterThanP(r, youngestrelation)) {
LogicObject.upclassifyOneDescription(r);
}
}
}
return (Logic.mostSpecificNamedCollections(relations));
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
}
}
} finally {
Logic.$CLASSIFICATIONSESSION$.set(old$Classificationsession$000);
}
}
}
return (Logic.mostSpecificNamedCollections(relations));
}
} |
e3f86dae-5e55-434d-a89f-650956371e02 | 6 | void put(int key, int value) {
int bucket = key % buckets;
if(bucket < 0) {
bucket = -bucket;
}
int[] data = content[bucket];
if(data == null) {
data = new int[33];
content[bucket] = data;
}
int off = data[0] * 2 + 1;
// eliminate duiplicates
if(off == 1 || data[off-2] != key || data[off-1] != value) {
if(off >= data.length) {
int[] ndata = new int[(data.length - 1) * 2 + 1];
System.arraycopy(data, 0, ndata, 0, off);
data = ndata;
content[bucket] = data;
}
data[off++] = key;
data[off++] = value;
data[0]++;
}
} |
ac1a1b51-f7a5-480b-a0ae-8498c2401514 | 4 | @Override
public void windowClosing(WindowEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
if ((this.currentState == State.INITIAL)
|| (this.currentState == State.PREPARED)
|| (this.currentState == State.PROCESSED))
{
if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
this.frame,
"Are you sure to exit now?",
"Exitting",
JOptionPane.YES_NO_OPTION))
{
System.exit(0);
}
}
else
{
this.text.append("For exit stop current action.\n");
}
} |
a37c594f-5343-4c02-8cdc-d3f9b666c4ff | 9 | public void update() throws MaltChainedException {
// Retrieve the address value
final AddressValue arg1 = addressFunction1.getAddressValue();
final AddressValue arg2 = addressFunction2.getAddressValue();
try {
if (arg1.getAddress() == null || arg2.getAddress() == null) {
featureValue.setIndexCode(table.getNullValueCode(NullValueId.NO_NODE));
featureValue.setSymbol(table.getNullValueSymbol(NullValueId.NO_NODE));
featureValue.setNullValue(true);
} else {
final DependencyNode node1 = (DependencyNode)arg1.getAddress();
final DependencyNode node2 = (DependencyNode)arg2.getAddress();
int head1 = -1;
int head2 = -1;
if ( node1.hasHead() )
{
head1 = node1.getHead().getIndex(); //lines below don't seem to work
//head1 = Integer.parseInt(node1.getHeadEdgeLabelSymbol(column.getSymbolTable()));
//if ( node1.hasHeadEdgeLabel(column.getSymbolTable()) )
// head1 = Integer.parseInt(node1.getHeadEdgeLabelSymbol(column.getSymbolTable()));
}
if ( node2.hasHead() )
{
head2 = node2.getHead().getIndex(); //lines below don't seem to work
//head2 = Integer.parseInt(node2.getHeadEdgeLabelSymbol(column.getSymbolTable()));
//if ( node2.hasHeadEdgeLabel(column.getSymbolTable()) )
// head2 = Integer.parseInt(node2.getHeadEdgeLabelSymbol(column.getSymbolTable()));
}
if (!node1.isRoot() && head1 == node2.getIndex()) {
featureValue.setIndexCode(table.getSymbolStringToCode("LEFT"));
featureValue.setSymbol("LEFT");
featureValue.setNullValue(false);
} else if (!node2.isRoot() && head2 == node1.getIndex()) {
featureValue.setIndexCode(table.getSymbolStringToCode("RIGHT"));
featureValue.setSymbol("RIGHT");
featureValue.setNullValue(false);
} else {
featureValue.setIndexCode(table.getNullValueCode(NullValueId.NO_NODE));
featureValue.setSymbol(table.getNullValueSymbol(NullValueId.NO_NODE));
featureValue.setNullValue(true);
}
}
} catch (NumberFormatException e) {
throw new FeatureException("The index of the feature must be an integer value. ", e);
}
// featureValue.setKnown(true);
featureValue.setValue(1);
} |
e5c171f3-067f-4f3b-b312-7f2748738792 | 9 | public static Map<String, Object> generateSchema(DateType anno) {
// Make sure annotation is valid
if (anno == null) { return null; }
Map<String, Object> map = new HashMap<String, Object>();
map.put(Field.TYPE.getName(), Type.DATE.getName());
if (! anno.index_name().isEmpty()) {
map.put(Field.INDEX_NAME.getName(), anno.index_name());
}
if (! anno.format().equals("dateOptionalTime")) {
map.put(Field.FORMAT.getName(), anno.format());
}
if (anno.store() != STORE.DEFAULT) {
map.put(Field.STORE.getName(), anno.store().name().toLowerCase());
}
if (anno.index() != INDEX.DEFAULT) {
map.put(Field.INDEX.getName(), anno.index().name().toLowerCase());
}
if (anno.precision_step() != 4) {
map.put(Field.PRECISION_STEP.getName(), new Integer(anno.precision_step()));
}
if (anno.boost() != 1.0f) {
map.put(Field.BOOST.getName(), new Float(anno.boost()));
}
if (! anno.null_value().isEmpty()) {
map.put(Field.NULL_VALUE.getName(), anno.null_value());
}
if (anno.include_in_all() != INCLUDE_IN_ALL.DEFAULT) {
map.put(Field.INCLUDE_IN_ALL.getName(), anno.include_in_all().name().toLowerCase());
}
return map;
} |
99d355fa-2ae0-4a0c-b5af-219017a3fea5 | 0 | public Dimension getUnit() {
return this.unit;
} |
2f2b3d10-101d-41ec-8fc7-e1b49fb065b9 | 0 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(buf);
return result;
} |
a7646ed3-4a46-493b-8984-8e458fbe1f98 | 8 | private Component cycle(Component currentComponent, int delta) {
int index = -1;
loop : for (int i = 0; i < m_Components.length; i++) {
Component component = m_Components[i];
for (Component c = currentComponent; c != null; c = c.getParent()) {
if (component == c) {
index = i;
break loop;
}
}
}
// try to find enabled component in "delta" direction
int initialIndex = index;
while (true) {
int newIndex = indexCycle(index, delta);
if (newIndex == initialIndex) {
break;
}
index = newIndex;
//
Component component = m_Components[newIndex];
if (component.isEnabled() && component.isVisible() && component.isFocusable()) {
return component;
}
}
// not found
return currentComponent;
} |
2da9708c-c3c5-4dad-a46e-4e857046198e | 7 | protected Instance mergeInstances(Instance source, Instance dest) {
Instances outputFormat = outputFormatPeek();
double[] vals = new double[outputFormat.numAttributes()];
for(int i = 0; i < vals.length; i++) {
if ((i != outputFormat.classIndex()) && (m_SelectedCols.isInRange(i))) {
if ((source != null) && !source.isMissing(i) && !dest.isMissing(i)) {
vals[i] = dest.value(i) - source.value(i);
} else {
vals[i] = Instance.missingValue();
}
} else {
vals[i] = dest.value(i);
}
}
Instance inst = null;
if (dest instanceof SparseInstance) {
inst = new SparseInstance(dest.weight(), vals);
} else {
inst = new Instance(dest.weight(), vals);
}
inst.setDataset(dest.dataset());
return inst;
} |
ef6ceb51-6e12-4642-97a2-75835049110f | 4 | public void onEnable() {
config = new Config(this);
debug = config.getDebug();
if (!setupSQL()) {
sendErr("SQL could not be setup, EndersGame will disable");
getPluginLoader().disablePlugin(this);
return;
}
int a = 0;
int l = 0;
send("Setting up arenas and lobbies");
try {
ResultSet ls = sql.query("SELECT lobbyid FROM lobbies");
while (ls.next()) {
int lobbyid = ls.getInt(1);
ResultSet lo = sql.query("SELECT * FROM lobbies WHERE lobbyid=" + ls.getInt(1));
ResultSet lospawn = sql.query("SELECT * FROM lobbyspawns WHERE lobbyid=" + ls.getInt(1));
lobbyList.put(lobbyid, new Lobby(this, lobbyid,
new Location(getServer().getWorld(lo.getString("world")), lo.getInt("x1"), lo.getInt("y1"), lo.getInt("z1")),
new Location(getServer().getWorld(lo.getString("world")), lo.getInt("x2"), lo.getInt("y2"), lo.getInt("z2")),
new Location(getServer().getWorld(lospawn.getString("world")), lospawn.getInt("coordX"), lospawn.getInt("coordY"), lospawn.getInt("coordZ"))));
l++;
}
ResultSet rs = sql.query("SELECT gameid FROM games");
while (rs.next()) {
ResultSet ga = sql.query("SELECT * FROM games WHERE gameid=" + rs.getInt(1));
int gameid = ga.getInt("gameid");
ResultSet si = sql.query("SELECT * FROM signs WHERE gameid=" + gameid);
ResultSet gaspawn = sql.query("SELECT * FROM gamespawns WHERE gameid=" + gameid);
ArrayList<Location> gamespawns = new ArrayList<Location>();
gamespawns.add(new Location(getServer().getWorld(gaspawn.getString("world")), gaspawn.getInt("x1"), gaspawn.getInt("y1"), gaspawn.getInt("z1")));
gamespawns.add(new Location(getServer().getWorld(gaspawn.getString("world")), gaspawn.getInt("x2"), gaspawn.getInt("y2"), gaspawn.getInt("z2")));
Game game = new Game(this, gameid, lobbyList.get(ga.getInt("lobbyid")),
getServer().getWorld(si.getString("world")).getBlockAt(si.getInt("coordX"), si.getInt("coordY"), si.getInt("coordZ")).getLocation(),
new Location(getServer().getWorld(ga.getString("world")), ga.getInt("x1"), ga.getInt("y1"), ga.getInt("z1")),
new Location(getServer().getWorld(ga.getString("world")), ga.getInt("x2"), ga.getInt("y2"), ga.getInt("z2")), gamespawns);
game.setId(getServer().getScheduler().scheduleSyncRepeatingTask(this, game, 20L, 20L));
runningGames.put(gameid, game);
a++;
}
} catch (SQLException e) {
sendErr("Games could not be setup, plugin is disabling");
getServer().getPluginManager().disablePlugin(this);
e.printStackTrace();
return;
}
send("Sucessfully setup " + a + " arenas and " + l + " lobbies");
getServer().getPluginManager().registerEvents(new GameListener(this), this);
getServer().getPluginManager().registerEvents(new DebugListener(), this);
send("Checking for new version(s)");
update();
} |
a5828f5d-afb0-48e1-a526-cde5fa2cb8d5 | 7 | public static List mostSpecificTypes(List types) {
if (types.rest() == null) {
return (types);
}
{ Cons cursor1 = types.theConsList;
Cons cursor2 = null;
Stella_Object value1 = null;
Stella_Object value2 = null;
while (!(cursor1 == Stella.NIL)) {
value1 = ((Surrogate)(cursor1.value));
if (((Surrogate)(cursor1.value)) != null) {
cursor2 = cursor1.rest;
loop001 : while (!(cursor2 == Stella.NIL)) {
value2 = cursor2.value;
if (value2 != null) {
if (Logic.logicalSubtypeOfP(((Surrogate)(value1)), ((Surrogate)(value2)))) {
cursor2.value = null;
}
else {
if (Logic.logicalSubtypeOfP(((Surrogate)(value2)), ((Surrogate)(value1)))) {
cursor1.value = null;
break loop001;
}
}
}
cursor2 = cursor2.rest;
}
}
cursor1 = cursor1.rest;
}
}
types.remove(null);
return (types);
} |
ce1f79bc-4084-4f33-ac92-46dc29feeeb0 | 4 | @Override
public int indeksTil(T verdi)
{
int indeks =-1;
Node<T> sjekk = hode;
if(verdi==null){
indeks=-1;
}
else if(sjekk==null){
indeks=-1;
}
else{
for(int i=0;i<antall;i++){
if(verdi.equals(sjekk.verdi)){
indeks = i;
break;
}
else
sjekk = sjekk.neste;
}
}
return indeks;
} |
28328fe5-35a7-4993-9728-d9d0889b25f1 | 3 | private void close() {
int result = JOptionPane.showConfirmDialog(
this,
"Are you sure you want to exit the application?",
"Exit Application",
JOptionPane.YES_NO_OPTION);
if(result == JOptionPane.YES_OPTION) {
if(getContentPane() == waitPanel || getContentPane() == gamePanel) {
leaveGame();
}
logout();
}
} |
e4922788-1578-4e8a-942a-1ff0e9aa56cb | 8 | public SolutionType[] decodeSolution(String str) throws DecodeException {
SolutionType[] res;
int i=0;
int beginning = i;
while (str.charAt(i) != '>') {
i++;
}
String type = str.substring(beginning, i);
i++;
beginning = i;
if (str.charAt(i) == '<') {
i++;
while (i < str.length()) {
i++;
}
String[] tab = str.substring(beginning+1, i).split(":");
res = (SolutionType[]) new Object[tab.length];
for (int x=0; x<tab.length; x++) {
switch(type) {
case "int":
res[x] = (SolutionType) Integer.valueOf(tab[x]);
break;
case "dbl":
res[x] = (SolutionType) Double.valueOf(tab[x]);
break;
case "str":
res[x] = (SolutionType) tab[x];
break;
case "chr":
res[x] = (SolutionType) ((Character) tab[x].charAt(0));
break;
default:
throw new DecodeException("non recognized type");
}
}
} else {
res = null;
throw new DecodeException();
}
return res;
} |
327a4649-507e-4e93-afd3-8eade0cfef78 | 8 | public void registerListener(String itemName, Integer strategy) throws RemoteException, IOException {
ser.registerListener(AuctionClient.authCode, this, itemName);
if(strategy == 1){
String bidderName = new String();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Put bidder name");
try {
bidderName = in.readLine();
} catch (IOException ex) {
Logger.getLogger(AuctionClient.class.getName()).log(Level.SEVERE, null, ex);
}
for(Item item: ser.getItems(AuctionClient.authCode)){
if(item.getItemName().equals(itemName)){
bidList.put(item.getItemName(),bidderName);
break;
}
}
}
if(strategy == 2){
String bidderName = new String();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Put bidder name");
try {
bidderName = in.readLine();
} catch (IOException ex) {
Logger.getLogger(AuctionClient.class.getName()).log(Level.SEVERE, null, ex);
}
for(Item item: ser.getItems(AuctionClient.authCode)){
if(item.getItemName().equals(itemName)){
new WaitAndBid(ser, item, bidderName);
break;
}
}
}
} |
17cff6ab-29c4-484b-a363-2d8525024700 | 9 | public static String unhtmlentities(String str) {
//initialize html translation maps table the first time is called
if (htmlentities_map.isEmpty()) {
initializeEntitiesTables();
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
if (ch == '&') {
int semi = str.indexOf(';', i + 1);
if ((semi == -1) || ((semi-i) > 7)){
buf.append(ch);
continue;
}
String entity = str.substring(i, semi + 1);
Integer iso;
if (entity.charAt(1) == ' ') {
buf.append(ch);
continue;
}
if (entity.charAt(1) == '#') {
if (entity.charAt(2) == 'x') {
iso = new Integer(Integer.parseInt(entity.substring(3, entity.length() - 1), 16));
}
else {
iso = new Integer(entity.substring(2, entity.length() - 1));
}
} else {
iso = (Integer) unhtmlentities_map.get(entity);
}
if (iso == null) {
buf.append(entity);
} else {
buf.append((char) (iso.intValue()));
}
i = semi;
} else {
buf.append(ch);
}
}
return buf.toString();
} |
999d6c2e-5fcb-4a90-9515-f312a798f64a | 7 | public float medium(float x) {
if (x <= a)
return 0;
else if (x > a && x <= b)
return (float) (1f / (b - a)) * x - ((float) a / (b - a));
else if (x > b && x <= c)
return 1;
else if (x > c && x <= d)
return (float) (1f / (c - d)) * x + ((float) d / (d - c));
else
return 0;
} |
24c76ce6-d8aa-4ffa-a360-7f80840e668a | 4 | public boolean readBoolean(String pSection, String pKey, boolean pDefault)
{
//if the ini file was never loaded from memory, return the default
if (buffer == null) {return pDefault;}
Parameters params = new Parameters();
//get the value associated with pSection and PKey
String valueText = getValue(pSection, pKey, params);
//if Section/Key not found, return the default
if (valueText.equals("")){return(pDefault);}
//return true if value is "true", false if it is "false", default if neither
if (valueText.equalsIgnoreCase("true")) {return true;}
if (valueText.equalsIgnoreCase("false")) {return false;}
return(pDefault);
}//end of IniFile::readString |
7d0d26b9-ecc3-4b8f-a51c-1a8ee98d68b4 | 1 | public void visit_d2i(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} |
29e3a458-c1a3-4eed-99a5-e58cc2911800 | 6 | private ImageIcon getImageFromValue(Value value, Relay.Direction direction)
{
//this logic taken from WPILib
switch(value)
{
case kOff:
return relayForwardNoReverseNo;
case kOn:
return relayForwardYesReverseYes;
case kForward:
if (direction == Direction.kReverse)
throw new RuntimeException("A relay configured for reverse cannot be set to forward");
return relayForwardYesReverseNo;
case kReverse:
if (direction == Direction.kForward)
throw new RuntimeException("A relay configured for forward cannot be set to reverse");
return relayForwardNoReverseYes;
default:
//Cannot hit this, limited by Value enum
}
return null;
} |
a6fa3e36-832b-4abf-a084-90cbc942cb9e | 3 | public void register(Class<? extends Command> c) {
CommandInfo info = c.getAnnotation(CommandInfo.class);
if (info == null) return;
try {
commands.put(info.pattern(), c.newInstance());
}
catch (Exception e) {
e.printStackTrace();
}
} |
cf448a68-c49a-4f39-a726-bbd8fae83c80 | 9 | @Override
public double calculate(double[] phenome) {
double score = 0;
double[] me = new double[phenome.length];
double[] you = new double[phenome.length];
for(Individual<?,double[]> individual : population){
System.arraycopy(phenome,0,me,0,me.length);
System.arraycopy(individual.getPhenome(),0,you,0,me.length);
double meStrength = 1.0;
double youStrength = 1.0;
int won = 0;
int lost = 0;
for(int i = 0; i < me.length; i++){
double checkWin = (me[i] * meStrength) - (you[i] * youStrength);
if(checkWin > 0){
won++;
for(int j = i+1; j < me.length; j++){
me[i] += Rf * (me[i] - you[i]);
}
youStrength -= Lf;
} else if (checkWin < 0){
lost++;
for(int j = i+1; j < you.length; j++){
you[i] += Rf * (you[i] - me[i]);
}
meStrength -= Lf;
}
}
if(won > lost){
score += 2;
} else if(won == lost){
score += 1;
}
}
return score / (population.size() * 2);
} |
4bb1f421-fe59-4acf-893d-97ed41b95e5e | 0 | public void setShareKey(String shareKey) {
this.shareKey = shareKey;
} |
8668e599-56a7-4e1a-a116-8cc459380d7b | 0 | public void setBlock(int x, int y, Block newBlock) {
blockSheet[x][y] = newBlock.getBlockID();
} |
9b6f9ca5-f625-4643-bebe-3c6c3e2ac144 | 4 | private void configureErrorDocuments() {
// Find default ERROR_DOCUMENT settings
for( int statusCode = 300; statusCode < 599; statusCode++ ) {
// Build key.
String ckey = Constants.CKEY_HTTPCONFIG_ERROR_DOCUMENT_BASE.replaceAll( "\\{STATUS_CODE\\}",
Integer.toString(statusCode) );
// Try to locate key
BasicType wrp_errorDocumentURI = this.getHandler().getGlobalConfiguration().get( ckey );
if( wrp_errorDocumentURI == null )
continue;
try {
String strURI = wrp_errorDocumentURI.getString(null);
if( strURI == null ) {
this.getHandler().getLogger().log( Level.SEVERE,
getClass().getName() + ".configureErrorDocuments(...)",
"Failed to init default error document map for key " + ckey + ": value is null." );
} else {
this.getHandler().getErrorDocumentMap().put( new Integer(statusCode),
new URI(strURI) );
this.getHandler().getLogger().log( Level.INFO,
getClass().getName() + ".configureErrorDocuments(...)",
"Error document for " + statusCode + " set to " + strURI );
}
} catch( java.net.URISyntaxException e ) {
this.getHandler().getLogger().log( Level.SEVERE,
getClass().getName() + ".configureErrorDocuments(...)",
"[URISyntaxException] Failed to init default error document map for key " + ckey + " '" + wrp_errorDocumentURI.getString() + "': " + e.getMessage() );
}
}
} |
1e46e706-fcb6-4159-b8a1-176db21fbb97 | 4 | public void run() {
ParserGetter kit = new ParserGetter();
HTMLEditorKit.Parser parser = kit.getParser();
while (mon.getNbrTraversed() < 2000) {
try {
String href = mon.getNext();
URL url = null;
if (href.startsWith("mailto")) {
s.add(href, true);
continue;
} else if (href.startsWith("http")) {
url = new URL(href);
} else {
url = new URL(new URL(getBaseURL()), href);
}
InputStream in = new BufferedInputStream(url.openStream());
InputStreamReader r = new InputStreamReader(in);
parser.parse(r, s, true);
s.add(href, true);
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
// System.out.println();
// System.out.println();
// for (String s : mailto)
// System.out.println(s);
// System.out.println();
// for (String s : urls) {
// System.out.println(s);
// }
} |
2c41d74b-9748-4017-9427-ad00f0ce6d08 | 3 | public void setExp(PExp node)
{
if(this._exp_ != null)
{
this._exp_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._exp_ = node;
} |
aad9225f-4b4a-43bd-9683-afabaae1a571 | 2 | public static void main(String[] args) {
int i;
float inputs06[] = {
20, 22, 21, 24, 24, 23, 25, 26, 20, 24,
26, 26, 25, 27, 28, 27, 29, 27, 25, 24
};
float inputs10[] = {
20, 22, 24, 25, 23, 26, 28, 26, 29, 27,
28, 30, 27, 29, 28
};
MovingAverageArray movingAverage;
System.out.println("Moving Average length 6:");
movingAverage = new MovingAverageArray(6);
for (i = 0; i < inputs06.length; ++i) {
System.out.println(movingAverage.movingAverage(inputs06[i]));
}
System.out.println("Moving Average length 10:");
movingAverage = new MovingAverageArray(10);
for (i = 0; i < inputs10.length; ++i) {
System.out.println(movingAverage.movingAverage(inputs10[i]));
}
} |
09ec17f2-56eb-4726-872b-e1e53ff27dc7 | 5 | public void AssignmentSymbolInImageSpace(String symbol){
//功能:
//找到激活强度最高的节点,对这个节点的Symbol属性进行赋值
//先找high
int high;
int imagespacesize=imagespace.size();
high=imagespace.get(0).ActivatedLevel;
for(int i=0;i<imagespacesize;i++){
if(imagespace.get(i).ActivatedLevel>high){
high=imagespace.get(i).ActivatedLevel;
}
}
for(int i=0;i<imagespacesize;i++)
{
if(imagespace.get(i).LinkedObject.equals("") && imagespace.get(i).ActivatedLevel==high)
{
imagespace.get(i).LinkedObject=symbol;
}
}
} |
7eac045b-8899-4658-8378-2eb8fc2b670b | 7 | public static void main(String[] args) {
while (true) {
System.out.print("Enter an id: ");
Scanner scanner = new Scanner(System.in);
int accountId = scanner.nextInt();
Account account1 = new Account(accountId);
if (!account1.isAccountIdValid(accountId)) {
System.out.println("The account Id you entered is invalid! Please try again.");
continue;
}
int choice = 0;
while(choice != 4){
account1.printMainMenu();
choice = scanner.nextInt();
switch(choice) {
case(1):
System.out.println("The balance is " + account1.checkBalance());
break;
case(2):
System.out.print("Enter an amount to withdraw: ");
double amountToWithDraw = scanner.nextDouble();
account1.withDraw(amountToWithDraw);
break;
case(3):
System.out.print("Enter an amount to deposit: ");
double amountToDeposit = scanner.nextDouble();
account1.deposit(amountToDeposit);
break;
case(4):
break;
}
}
}
} |
7112713e-db04-4eab-9757-5e333b0cbe36 | 7 | private boolean requirementsMetRemove(){
List<Enhancement> el = DDOCharacter.getTree(prestige).getEnhancementList();
int treePointsSpent = DDOCharacter.getTree(prestige).getPointsSpent();
int modTreeSpent = treePointsSpent;
for(Enhancement e : el){
if(e.requireAllOf.contains(this.id) && e.tiersTaken >= this.tiersTaken)//check to see if this is a pre req for something else
return false;
//find all enhancements higher in the tree then the one we are trying to remove
//add their points together and remove it from total tree spent, we then get the amount required
if(e.tiersTaken > 0 && e.treeTier > this.treeTier){
for(int i = 0; i < e.tiersTaken;i++){
modTreeSpent -= e.apPerTier.get(e.tiersTaken-1);
}
if(modTreeSpent <= e.requireApSpentTree)//make sure we didnt remove too many points fromthe tree
return false;
}
}
return true;//all checks passed
} |
e2237fc0-c327-4bb2-bc18-83ff97e70b46 | 5 | private int[][] generateSolution(int[][] game, int index) {
if (index > 80)
return game;
int x = index % 9;
int y = index / 9;
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i <= 9; i++) numbers.add(i);
Collections.shuffle(numbers);
while (numbers.size() > 0) {
int number = getNextPossibleNumber(game, x, y, numbers);
if (number == -1)
return null;
game[y][x] = number;
int[][] tmpGame = generateSolution(game, index + 1);
if (tmpGame != null)
return tmpGame;
game[y][x] = 0;
}
return null;
} |
148a7c67-1b69-4756-ad67-7b638405d6d6 | 2 | public void save() {
XStream s = new XStream();
FileOutputStream out;
try {
out = new FileOutputStream(new File("Player.xml"));
s.toXML(this, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} |
6f134cef-7fc5-48fd-a27f-07a468bf4e9d | 2 | public boolean removeRoom(String name){
if (name.equalsIgnoreCase("main")) return false;
ChatServerChatRoom room = chatRooms.remove(name.toLowerCase());
if (room==null) return false;
room.close();
//room.dealloc //oh wait no, we can't do that
System.out.println("Room killed: "+name);
return true;
} |
4104d351-2ddf-48ce-aefb-a14a6d1981c5 | 8 | public boolean isLegalMoveOne(int pieceNumber){
if (board.getBoard()[pieceNumber].getPieceType()==1 || board.getBoard()[pieceNumber].getPieceType()==2){
if (board.getBoard()[pieceNumber].getX()==0)
return false;
}
else{
if (board.getBoard()[pieceNumber].getY()==0)
return false;
}
int position = board.getBoard()[pieceNumber].getPositions()[0];
if (board.getBoard()[pieceNumber].getPieceType()==1 || board.getBoard()[pieceNumber].getPieceType()==2){
if (board.getPositions().contains(position-1))
return false;
}
else{
if (board.getPositions().contains(position-BOARDSIZE))
return false;
}
return true;
} |
ea13b678-69e0-4b4f-9cac-fcdffdb8aeb6 | 3 | private void relax(Vortex closestVortex, int pathId, int neighborId) {
double dayTravelLength = oergi.getTravelLength();
Corridor corridor = corridors.getCorridor(pathId);
if (!corridor.gainPassage(oergi)) {
return;
}
//oergi will make sure that travel length might be infinite
double corridorTravelLength = corridor.getTravelingLength(oergi);
//TODO check that the target room is accessable
if (corridorTravelLength > dayTravelLength) {
return;
}
Vortex nextVortex = vortexes[neighborId];
int newDayDistance = closestVortex.getDayDistance();
double newDayTravelLength = closestVortex.getDayTravelDistance();
if (newDayTravelLength + corridorTravelLength > dayTravelLength) {
newDayDistance++;
newDayTravelLength = corridorTravelLength;
}
else {
newDayTravelLength += corridorTravelLength;
}
vortexHeap.heapDecKey(nextVortex, newDayDistance, newDayTravelLength);
} |
5258b116-134f-4815-87ff-10846d782fdd | 3 | public static void init() throws IOException {
gui = new ArrayList<int[]>();
pro = new ArrayList<Thread>();
Twindow = new JFrame();
Twindow.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
Twindow.setSize(500, 500);
Twindow.setTitle("NXT-Projekt - Feld Anzeige - Marcel Link");
info = new JFrame();
info.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
info.setSize(200, 500);
info.setTitle("Roboter Status");
comp = new Component();
Twindow.getContentPane().add(comp);
Twindow.setVisible(true);
infotext = new JTextArea();
infotext.setLineWrap(true);
infotext.setWrapStyleWord(true);
infotext.setEditable(false);
JPanel topPanel = new JPanel();
JPanel btnPanel = new JPanel();
JPanel resPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
info.getContentPane().add(topPanel);
info.getContentPane().add(btnPanel);
info.getContentPane().add(resPanel);
stopButton = new JButton("Fortsetzen");
stopButton.addActionListener(new TheButton());
resetButton = new JButton("Reset");
resetButton.addActionListener(new TheButton());
btnPanel.add(stopButton);
resPanel.add(resetButton);
topPanel.add(infotext);
info.getContentPane().add(topPanel, BorderLayout.NORTH);
info.getContentPane().add(btnPanel, BorderLayout.EAST);
info.getContentPane().add(resPanel, BorderLayout.WEST);
info.setVisible(true);
info.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
System.out.println("main: visible info false");
if (Twindow.isVisible()) {Twindow.setVisible(false);}else{Status.stop_init();}
}
});
Twindow.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
System.out.println("main: visible Twindow false");
if (info.isVisible()) {info.setVisible(false);}else{Status.stop_init();}
}
});
try {
getScale();
around = Tools.scaleImage(ImageIO.read(new File(Brick.path+ "/icons/around.png")), scale_x,scale_y);
unknown = Tools.scaleImage(ImageIO.read(new File(Brick.path+ "/icons/unknown.png")), scale_x,scale_y);
free = Tools.scaleImage(ImageIO.read(new File(Brick.path+ "/icons/free.png")), scale_x,scale_y);
blocked = Tools.scaleImage(ImageIO.read(new File(Brick.path+ "/icons/blocked.png")), scale_x,scale_y);
arrow_right = Tools.scaleImage(ImageIO.read(new File(Brick.path+ "/icons/arrow.png")), scale_y,scale_y);
arrow_down = Tools.rotateImage(arrow_right, 90);
arrow_left = Tools.rotateImage(arrow_down, 90);
arrow_up = Tools.rotateImage(arrow_left, 90);
nxt = Tools.scaleImage(ImageIO.read(new File(Brick.path+ "/icons/nxt.png")), scale_y,scale_y);
} catch (IOException e) {e.printStackTrace();}
update();
} |
b234c5d8-e024-45e7-8bdb-df819893cc09 | 8 | private boolean isFallFromTable(Direction d, Position p) {
boolean result = true;
switch (d) {
case EAST:
if (p.getCoordinateX() + 1 < table.getLengthX()) {
result = false;
}
break;
case SOUTH:
if (p.getCoordinateY() - 1 >= 0) {
result = false;
}
break;
case WEST:
if (p.getCoordinateX() - 1 >= 0) {
result = false;
}
break;
case NORTH:
if (p.getCoordinateY() + 1 < table.getLengthY()) {
result = false;
}
break;
default:
break;
}
return result;
} |
7d269299-9a2e-4ce4-91ea-2a3e29d0f7c4 | 6 | public static Cons simplifyAntecedent(Cons antecedent, Cons outputVariables, List positive, List negative) {
{ Cons newAntecedent = Stella.NIL;
Cons candidate = Stella.NIL;
Cons discardedPotentialGenerators = Stella.NIL;
int coveredExamples = 0;
int previousCoveredExamples = 0;
int score = Logic.numExamplesCovered(antecedent, positive);
while (!(antecedent == Stella.NIL)) {
{ Cons head000 = ((Cons)(antecedent.value));
antecedent = antecedent.rest;
candidate = head000;
}
if (Logic.ruleCoversAnyExampleP(Cons.append(newAntecedent, antecedent), negative)) {
newAntecedent = Cons.cons(candidate, newAntecedent);
}
else {
{
System.out.println("Removing clause " + candidate);
if (Logic.containsOutputVariableP(candidate, outputVariables)) {
discardedPotentialGenerators = Cons.cons(candidate, discardedPotentialGenerators);
}
}
}
}
coveredExamples = Logic.numExamplesCovered(newAntecedent, positive);
while ((!(discardedPotentialGenerators == Stella.NIL)) &&
(coveredExamples < score)) {
{ Stella_Object head001 = discardedPotentialGenerators.value;
discardedPotentialGenerators = discardedPotentialGenerators.rest;
candidate = ((Cons)(head001));
}
previousCoveredExamples = coveredExamples;
coveredExamples = Logic.numExamplesCovered(Cons.cons(candidate, newAntecedent), positive);
if (coveredExamples > previousCoveredExamples) {
System.out.println("Reinserting clause " + candidate);
newAntecedent = Cons.cons(candidate, newAntecedent);
}
}
return (newAntecedent);
}
} |
8424c2b1-f795-4c31-abec-5affd58a53bb | 4 | public static void main (String args[]) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer line = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(line.nextToken());
int m = Integer.parseInt(line.nextToken());
IntArray intArray = new IntArray();
intArray.array = new int[n];
line = new StringTokenizer(reader.readLine());
for (int i=0; i<n; i++) {
String token = line.nextToken();
intArray.array[i] = Integer.parseInt(token);
}
for (int i=0; i<m; i++) {
line = new StringTokenizer(reader.readLine());
String operator = line.nextToken();
int number = Integer.parseInt(line.nextToken());
if (operator.equals("C")) {
intArray.add(number);
} else if (operator.equals("Q")) {
System.out.println(intArray.query(number));
}
}
} |
4226fd2c-e32f-4405-b62a-05b1002f3f3a | 5 | public boolean interact(Level level, int xt, int yt, Player player, Item item, int attackDir) {
if (item instanceof ToolItem) {
ToolItem tool = (ToolItem) item;
if (tool.type == ToolType.shovel) {
if (player.payStamina(4 - tool.level)) {
level.setTile(xt, yt, Tile.hole, 0);
level.add(new ItemEntity(new ResourceItem(Resource.dirt), xt * 16 + random.nextInt(10) + 3, yt * 16 + random.nextInt(10) + 3));
Sound.monsterHurt.play();
return true;
}
}
if (tool.type == ToolType.hoe) {
if (player.payStamina(4 - tool.level)) {
level.setTile(xt, yt, Tile.farmland, 0);
Sound.monsterHurt.play();
return true;
}
}
}
return false;
} |
ae6b4b97-039e-4c96-8233-5973aab0a26b | 8 | public static final boolean check(final File f) {
if (!f.isDirectory()) {
return false;
}
final String[] list = f.list();
if (list == null) {
return false;
}
for (final String s : list) {
if (s.startsWith("drum") && s.endsWith(".drummap.txt")) {
for (int i = 4; i < (s.length() - 12); i++) {
if ((s.charAt(i) < '0') || (s.charAt(i) > '9')) {
return false;
}
}
return true;
}
}
return false;
} |
55b3e62b-e676-4707-a651-c1a06eed906d | 4 | private String checkName(String s) {
if (s.compareTo("") == 0)
return "";
if (s.length() > 15)
return "Name is too long";
for (int i = 0; i < s.length(); i++) {
if (!checkChar(s.charAt(i)))
return "Only letters or numbers";
}
return null;
} |
ff808d4e-9723-48d4-a6c7-41079ab10503 | 0 | public void setNombre(String nombre) {
this.nombre = nombre;
} |
c1b4a848-87d5-4281-a0e5-fef25ad6fa7f | 7 | public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} |
6e2df81e-6fd1-48af-b72e-5d34662c08e7 | 0 | public int getHeight(){
return height;
} |
46d59457-6140-48e5-9066-e09292056516 | 9 | @Test(groups = {"create"})
@Parameters({"browser"})
@BeforeClass
public void beforeClass(String browser) throws IOException, InterruptedException
{
if (browser.equals("firefox")) {
driver=browserFirefox();
}
else if (browser.equals("chrome")) {
driver=browserChrome();
}
else if (browser.equals("safari")) {
driver=browserSafari();
}
else if (browser.equals("ie9")) {
driver=browserIE9();
}
else if (browser.equals("iPad")) {
driver=browserIpad();
}
else if (browser.equals("Android")) {
driver=browserAndroid();
}
String name=""+ browser+"/ContactUs/" + timeStamp + "_" + "Successful-Completed-ContactUS.png";
System.out.println("Let me see which one get tested " +browser);
System.out.println("Let me run get driver "+driver);
fail=""+ browser+"/Failed/" + timeStamp + "_" + "contact_us.png";
driver.get(baseUrl + "/Contact-Us.aspx");
WebDriverWait wait = new WebDriverWait(driver, 30);
Select droplist1 = new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddlReason")));
droplist1.selectByVisibleText("General Inquiry or Question");
wait = new WebDriverWait(driver, 30);
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtFirstName")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtFirstName")).sendKeys("PubmoTestFirst");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtLastName")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtLastName")).sendKeys("PubmoTestLast");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtEmail")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtEmail")).sendKeys("[email protected]");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtAddress1")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtAddress1")).sendKeys("75 W. 10th Street");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtAddress2")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtAddress2")).sendKeys("Apt. 3B");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtCity")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtCity")).sendKeys("New York");
Select droplist2 = new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddlStates")));
droplist2.selectByVisibleText("New York");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtZip")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtZip")).sendKeys("10003");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtHomePhone1")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtHomePhone1")).sendKeys("212");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtHomePhone2")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtHomePhone2")).sendKeys("222");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtHomePhone3")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtHomePhone3")).sendKeys("2222");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtWorkPhone1")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtWorkPhone1")).sendKeys("212");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtWorkPhone2")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtWorkPhone2")).sendKeys("456");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtWorkPhone3")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtWorkPhone3")).sendKeys("7890");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtComments")).clear();
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtComments")).sendKeys("Please do not contact this test account.");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_imgbtnSubmit")).click();
for (int second = 0;; second++) {
try { if (driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Thanks for taking the time to get in touch with us[\\s\\S]*$")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
takeScreen(name);
driver.quit();
} |
159fb0e5-4f38-4fa2-b05d-1bd49aef4348 | 6 | public void cleanup() {
try{
if(select != null)
select.close();
if(insert != null)
insert.close();
if(delete != null)
delete.close();
if(update != null)
update.close();
if(getMaxKey != null)
getMaxKey.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
7059511f-e1e1-4a56-ac2a-e36261bd1768 | 0 | public int getSuppliercode() {
return this.suppliercode;
} |
1d28e174-5acc-49e4-a189-1bbb3578cb21 | 6 | @Override
public List<PastMeeting> getPastMeetingList(Contact contact) {
if (!allContacts.contains(contact)) {
throw new IllegalArgumentException("Contact does not exist");
}
List<PastMeeting> pastMeetingsPerContact = new ArrayList<PastMeeting>();
//all meetings for a contact will be put in a tree set to sort by date and remove duplicates
Set<PastMeeting> interim = new TreeSet<PastMeeting>(new Comparator<Meeting>() {
@Override
public int compare(Meeting o1, Meeting o2) {
return o1.getDate().compareTo(o2.getDate());
}
});
for (Meeting curr : allMeetings) {
//only add past meetings to the list
if (curr instanceof PastMeeting) {
if (curr.getContacts().contains(contact)) {
interim.add((PastMeeting) curr);
}
}
}
//converting the tree to list
for (PastMeeting curr : interim) {
if (curr != null) {
pastMeetingsPerContact.add(curr);
}
}
return pastMeetingsPerContact;
} |
6fa31870-453d-4b2e-b324-d8d126254f65 | 8 | public KeyControl(Canvas3D canvas3D) {
KeyListener l = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// Ignore
}
@Override
public void keyReleased(KeyEvent e) {
// Ignore
}
@Override
public void keyPressed(KeyEvent e) {
char key = e.getKeyChar();
switch (key) {
case 'q':
posPlayer0.y += 0.1;
if (posPlayer0.y > 1.0)
posPlayer0.y = 1.0;
onChange(0, posPlayer0, orientation);
break;
case 'a':
posPlayer0.y -= 0.1;
if (posPlayer0.y < -1.0)
posPlayer0.y = -1.0;
onChange(0, posPlayer0, orientation);
break;
case 'p':
posPlayer1.y += 0.1;
if (posPlayer1.y > 1.0)
posPlayer1.y = 1.0;
onChange(1, posPlayer1, orientation);
break;
case 'l':
posPlayer1.y -= 0.1;
if (posPlayer1.y < -1.0)
posPlayer1.y = -1.0;
onChange(1, posPlayer1, orientation);
break;
}
}
};
canvas3D.addKeyListener(l);
} |
10c9d455-2fea-404d-a13b-dc9745468036 | 4 | private boolean mayOverwrite(File file) {
if (overwriteMode == Controller.OVERWRITE_ALL_NO) {
return false;
}
if (overwriteMode == Controller.OVERWRITE_ALL_YES) {
return true;
}
overwriteMode = Application.getController().shallOverwriteFile(file);
if (overwriteMode == Controller.OVERWRITE_ALL_YES || overwriteMode == Controller.OVERWRITE_ONCE_YES) {
return true;
} else {
return false;
}
} |
be39f5c6-670c-463c-bb23-9a491f3ec84e | 9 | public static void main(String[] args) {
In in = new In(args[0]);
while (true) {
int V = in.readInt();
if (V == 0)
break;
int E = in.readInt();
Digraph G = new Digraph(V);
for (int i = 0; i < E; i++) {
int v = in.readInt();
int w = in.readInt();
G.addEdge(v, w);
}
int[] color = new int[V];
Arrays.fill(color, 1);
// Check whether the graph is bipatrite
Queue<Integer> q = new Queue<Integer>();
q.enqueue(0);
color[0] = 0;
boolean isBipartite = true;
while (!q.isEmpty() && isBipartite) {
int v = q.dequeue();
for (int w : G.adj(v)) {
if (color[w] == 1) {
color[w] = 1 - color[v];
q.enqueue(w);
} else if (color[w] == color[v]) {
isBipartite = false;
break;
}
}
}
if (isBipartite) {
System.out.println("BICOLORABLE.");
} else {
System.out.println("NOT BICOLORABLE.");
}
}
} |
37cad17d-7666-4fca-97b5-cfdef65d81c0 | 8 | private final void method1747(byte byte0, int i, Stream stream) {
if (byte0 >= -8) {
method1750(-4);
}
if (i != 1) {
if (i != 2) {
if (i == 3) {
int j = stream.readUByte();
anIntArray4683 = new int[j];
anIntArrayArray4678 = new int[j][];
for (int l = 0; l < j; l++) {
int j1 = stream.readUShort();
anIntArray4683[l] = j1;
anIntArrayArray4678[l] = new int[Class142_Sub8_Sub31.anIntArray4399[j1]];
for (int k1 = 0; k1 < Class142_Sub8_Sub31.anIntArray4399[j1]; k1++) {
anIntArrayArray4678[l][k1] = stream.readUShort();
}
}
return;
}
if (i == 4) {
aBoolean4684 = false;
return;
}
} else {
int k = stream.readUByte();
anIntArray4690 = new int[k];
for (int i1 = 0; ~i1 > ~k; i1++) {
anIntArray4690[i1] = stream.readUShort();
}
}
return;
} else {
aStringArray4682 = Class20.method229((byte) 114, stream.readString(), '<');
return;
}
} |
0201e3d1-aa73-49cc-be7b-2c63c91d3634 | 9 | @Override
public Set<Map.Entry<String, Object>> entrySet() {
return new AbstractSet<Map.Entry<String, Object>>() {
@Override
public Iterator<Map.Entry<String, Object>> iterator() {
return new Iterator<Map.Entry<String, Object>>() {
private final Iterator<String> mPropIterator = keySet().iterator();
public boolean hasNext() {
return mPropIterator.hasNext();
}
public Map.Entry<String, Object> next() {
final String property = mPropIterator.next();
final Object value = get(property);
return new Map.Entry<String, Object>() {
Object mutableValue = value;
public String getKey() {
return property;
}
public Object getValue() {
return mutableValue;
}
public Object setValue(Object value) {
Object old = BeanMap.this.put(property, value);
mutableValue = value;
return old;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Map.Entry) {
Map.Entry other = (Map.Entry) obj;
return
(this.getKey() == null ?
other.getKey() == null
: this.getKey().equals(other.getKey()))
&&
(this.getValue() == null ?
other.getValue() == null
: this.getValue().equals(other.getValue()));
}
return false;
}
@Override
public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode()) ^
(getValue() == null ? 0 : getValue().hashCode());
}
@Override
public String toString() {
return property + "=" + mutableValue;
}
};
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return BeanMap.this.size();
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean contains(Object e) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) e;
String key = entry.getKey();
if (BeanMap.this.containsKey(key)) {
Object value = BeanMap.this.get(key);
return value == null ? entry.getValue() == null
: value.equals(entry.getValue());
}
return false;
}
@Override
public boolean add(Map.Entry<String, Object> e) {
BeanMap.this.put(e.getKey(), e.getValue());
return true;
}
@Override
public boolean remove(Object e) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
};
} |
ca5207c5-b9f6-45fa-bde4-3a039426bdb8 | 2 | private double countColumnsBetween(int beginning, int end) {
double columns = 0.0;
for (RoadGeometry roadGeometry : geometry) {
if (road.intervalContainsGeometry(roadGeometry, beginning, end)) {
columns = addColumnsFromGeometry(roadGeometry, beginning, end, columns);
}
}
return columns;
} |
e5bec92c-f376-49fc-9d82-58131e73d6b5 | 5 | @Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return filesList.get(rowIndex).getFileName();
case 1:
return filesList.get(rowIndex).getLastModificationDate();
case 2:
return (filesList.get(rowIndex).isDirectory() ? "Dossier de fichiers" : "Fichier");
case 3:
return filesList.get(rowIndex).getFileSize();
default:
throw new IllegalStateException("Ne devrait jamais arriver");
}
} |
2dfe5552-b7dd-4a72-82c9-e09bb81f284c | 0 | public final void setTopic(String channel, String topic) {
this.sendRawLine("TOPIC " + channel + " :" + topic);
} |
fe7bde35-a88c-47be-848a-7ce10487cec8 | 4 | @Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String ref = value.toString().substring(1);
String page = downloadPage(new Path(root + ref), context);
List<String> refList = new LinkedList<String>();
Matcher matcher = pattern.matcher(page);
while (matcher.find()) {
String obtainedRef = matcher.group(1);
obtainedRef = getValidRef(obtainedRef, ref);
if (obtainedRef != null) {
refList.add(obtainedRef);
}
}
double piece = refList.isEmpty() ? 0 : D * PAGE_RANK / refList.size();
piecePageRank.set(piece);
for (String reference : refList) {
refText.set(reference);
context.write(refText, piecePageRank);
}
} |
a1c7fe43-bdfb-4c48-bad6-0c2b6dff68a9 | 9 | public void recordGameSettings(){
BattleMap bm = map;
String a = "BattleMap\n";
a = a.concat(bm.getNumRows() + "," + bm.getNumCols() + "\n");
a=a.concat("Bases\n");
for(Base b : map.getBases()){
a = a.concat("player " + b.getOwnerId() + ": " + b.getLocation().getRow() + "," + b.getLocation().getCol() + "\n");
}
a = a.concat("Cities\n");
for(Structure c : map.getStructures()){
if(c instanceof City )
a = a.concat(c.getLocation().getRow() + "," + c.getLocation().getCol() + "\n");
}
a = a.concat("Barriers\n");
int barriers = 0;
for(Structure b : map.getStructures()){
if(b instanceof Barrier){
a = a.concat(b.getLocation().getRow() + "," + b.getLocation().getCol() + "\n");
barriers++;
}
}
if(barriers == 0){a = a.concat("there are no barriers!\n");}
// make the game state and set it
HashMap<String, List<BoardLocation>> gplayerShipLocations = new HashMap<String, List<BoardLocation>>();
HashMap<String, int[]> gplayerScoreMinerals = new HashMap<String, int[]>();
for (ServerPlayer p : players.values()) {
List<Ship> ships = p.getUnsunkenShips(p);
List<BoardLocation> locations = new ArrayList<BoardLocation>();
for(Ship s : ships){locations.add(new BoardLocation(s.getLocation()));}
gplayerShipLocations.put(String.valueOf(p.getId()), locations); // List of all players ships to send to each player
}
for (ServerPlayer p : players.values()) {
int[] scoreMineral = new int[2];
scoreMineral[0] = p.getScore();
scoreMineral[1] = p.getMinerals();
gplayerScoreMinerals.put(String.valueOf(p.getId()), scoreMineral); // List of all players ships to send to each player
}
GameState gs = new GameState(gplayerShipLocations,gplayerScoreMinerals);
// now call get game state string
initializeTranscriptFile();
writeTranscriptFile(a);
writeTranscriptFile("Initial Game State:\n" + gs.toString());
this.prevGameState = gs;
} |
1cb5ae5d-dfc6-4fa3-b4ac-1acb928bc983 | 8 | public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
TreeNode p = root.left;
TreeNode q = root.right;
if (p == null)
return q == null;
if (q == null)
return p == null;
TreeIterator ip = new TreeIterator(p);
TreeIterator iq = new TreeIterator(q);
while (ip.hasNext() && iq.hasNext()) {
if (!equalNode(ip.next(), iq.rightNext()))
return false;
}
if (ip.hasNext() || iq.hasNext())
return false;
return true;
} |
0367b12d-d56e-4c32-98fb-1a444d2c518e | 6 | public void keyPressed(KeyEvent e) {
int offset = (e.getKeyCode() == KeyEvent.VK_UP) ? (-7)
: ((e.getKeyCode() == KeyEvent.VK_DOWN)
? (+7)
: ((e.getKeyCode() == KeyEvent.VK_LEFT) ? (-1)
: ((e.getKeyCode() == KeyEvent.VK_RIGHT)
? (+1) : 0)));
int newDay = getDay() + offset;
if ((newDay >= 1) &&
(newDay <= calendar.getMaximum(Calendar.DAY_OF_MONTH))) {
setDay(newDay);
}
} |
27d16188-ad91-46bf-999a-2336a8cc9013 | 7 | private Value determineValue(final Token token) throws AssemblerSyntaxException {
Value value;
switch (token.getType()) {
case INTEGER:
value = Value.valueOf(parseToByte(token));
break;
case FLOAT:
value = Value.valueOf(parseToFloat(token));
break;
case LITERAL:
if ("nil".equals(token.getValue())) {
value = Value.getNil();
} else if ("true".equals(token.getValue())) {
value = Value.getTrue();
} else if ("false".equals(token.getValue())) {
value = Value.getFalse();
} else {
throw new AssemblerSyntaxException(String.format("Unsupported literal %s!", token.getValue()),
getCurrentLine());
}
break;
case STRING:
value = Value.valueOf(token.getValue());
break;
default:
throw new AssemblerSyntaxException(String.format("Unsupported constant type %s!", token.getType()),
getCurrentLine());
}
return value;
} |
a58c6270-3986-4b69-9dee-7691a0edfa1b | 5 | final void ia(short i, short i_626_) {
for (int i_627_ = 0; i_627_ < anInt5351; i_627_++) {
if (aShortArray5311[i_627_] == i)
aShortArray5311[i_627_] = i_626_;
}
if (aClass6Array5361 != null) {
for (int i_628_ = 0; i_628_ < amountPolygons; i_628_++) {
Class6 class6 = aClass6Array5361[i_628_];
Class350 class350 = aClass350Array5363[i_628_];
((Class350) class350).anInt4313
= (((Class350) class350).anInt4313 & ~0xffffff
| (Class126.hslColorTable
[Class25.method303((aShortArray5311
[((Class6) class6).anInt144]),
30) & 0xffff]) & 0xffffff);
}
}
if (anInt5354 == 2)
anInt5354 = 1;
} |
fc64c898-ee44-4bb9-a271-845fbc1b312b | 9 | public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = Integer.valueOf(scn.nextLine());
for (int tc = 1; tc <= t; tc++) {
String line = scn.nextLine();
StringTokenizer st = new StringTokenizer(line);
// Combinations
combinations = new HashMap<String, Character>();
int c = Integer.valueOf(st.nextToken());
for (int comb = 0; comb < c; comb++) {
String combination = st.nextToken();
addCombination(combination);
}
// Eliminations
eliminations = new HashMap<Character, List<Character>>();
int d = Integer.valueOf(st.nextToken());
for (int elim = 0; elim < d; elim++) {
String elimination = st.nextToken();
addElimination(elimination);
}
// Process invokations
int n = Integer.valueOf(st.nextToken());
char invokation[] = st.nextToken().toCharArray();
Deque<Character> result = new LinkedList<Character>();
char lastChar = '-';
int histogram[] = new int[26];
for (int i = 0; i < n; i++) {
char element = invokation[i];
// Tests for combination
Character combResult = combinations
.get("" + lastChar + element);
if (combResult != null) {
histogram[idx(lastChar)]--;
result.removeLast();
result.addLast(combResult);
lastChar = combResult;
histogram[idx(combResult)]++;
} else {
// Tests for elimination
List<Character> elimList = eliminations.get(element);
boolean hasCleared = false;
if (elimList != null) {
for (Character elim : elimList) {
if (histogram[idx(elim)] != 0) {
result.clear();
histogram = new int[26];
lastChar = '-';
hasCleared = true;
break;
}
}
}
if (!hasCleared) {
result.addLast(element);
lastChar = element;
histogram[idx(element)]++;
}
}
}
Character resultingArray[] = new Character[result.size()];
resultingArray = result.toArray(resultingArray);
System.out.println("Case #" + tc + ": "
+ Arrays.toString(resultingArray));
}
} |
1da52ee5-0ee1-4e03-8176-f94c447dd632 | 8 | private void humanAction(HumanCharacter theHumanCharacter,Monster theMonster){
System.out.println("What would you like to do?");
System.out.println("Type 'melee' to use melee attack");
System.out.println("Type 'magic' to use magic attack");
System.out.println("Type 'potion' to use a health, or mana potion.");
System.out.println("Type 'info' followed by either 'me' or 'monster' to see stats");
String choice;
Scanner input = new Scanner(System.in);
boolean isDead = false;
boolean combatDone = false;
while(!combatDone){
theHumanCharacter.deadCheck(isDead);
if(isDead){
System.exit(0);
}
System.out.print("Command: ");
choice = input.nextLine();
if(choice.compareTo("melee") == 0){
//Code is complete.
combatDone = theHumanCharacter.meleeAttack(theMonster);
isDead = this.willMonsterAttack(theHumanCharacter, theMonster);
}
else if(choice.compareTo("magic") == 0){
//Code is complete.
combatDone = theHumanCharacter.magicAttack(theMonster);
isDead = this.willMonsterAttack(theHumanCharacter, theMonster);
}
else if(choice.compareTo("potion") == 0){
theHumanCharacter.usePotion();
}
else if(choice.compareTo("info me") == 0){
theHumanCharacter.description();
}
else if(choice.compareTo("info monster") == 0){
theMonster.description();
}
else{
System.out.println("You've entered in a invalid command");
}
}
if(combatDone){
this.distributeLoot(theHumanCharacter, theMonster);
}
} |
c8842a00-6ac5-4427-99b4-91150212ea41 | 9 | private static void exportWay(final Way way, final BufferedWriter writer, final boolean force) throws IOException {
if (!way.isModified() && !force){
return;
}
for (Node node : way.getNodes()){
exportNode(node, writer,true);
}
final StringBuilder stringWay = new StringBuilder();
stringWay.append(" ");
stringWay.append("<way");
stringWay.append(" id='").append(way.getId()).append("'");
if (way.isModified()){
stringWay.append(" action='").append("modify").append("'");
}
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
stringWay.append(" timestamp='").append(sdf.format(new Date(way.getTimestamp()))).append("'");
if (way.getUser() != null) {
stringWay.append(" uid='").append(way.getUser().getId()).append("'");
stringWay.append(" user='").append(StringEscapeUtils.escapeXml(way.getUser().getName())).append("'");
}
stringWay.append(" visible='true'");
stringWay.append(" version='").append(way.getVersion()).append("'");
stringWay.append(" changeset='").append(way.getChangeset()).append("'");
if (way.getNodes().size() > 0 || way.getNumTags() > 0){
stringWay.append(">\n");
for (Node node: way.getNodes()){
stringWay.append(" ");
stringWay.append("<nd");
stringWay.append(" ref='").append(node.getId()).append("'");
stringWay.append(" />\n");
}
final Set<String> tags = way.getTagKeys();
for (String key: tags){
stringWay.append(" ");
stringWay.append("<tag");
stringWay.append(" k='").append(StringEscapeUtils.escapeXml(key)).append("'");
stringWay.append(" v='").append(StringEscapeUtils.escapeXml(way.getTag(key))).append("'");
stringWay.append(" />\n");
}
stringWay.append(" </way>\n");
}
else {
stringWay.append("/>\n");
}
writer.write(stringWay.toString());
} |
3d480e0e-bb79-4c2c-a738-6926adbbe737 | 3 | public static void main(String[] args) {
int m1,n1,m2,n2;
char again;
do{
print("Enter the dimensions of the first matrix: ");
n1 = scan.nextInt();
m1 = scan.nextInt();
print("Enter the dimensions of the second matrix: ");
n2 = scan.nextInt();
m2 = scan.nextInt();
if(m1 == n2){
double[][] matrix1 = new double[n1][m1];
double[][] matrix2 = new double[n2][m2];
double[][] matrix3 = new double[n1][m2];
print("Enter the data for the first matrix: \n");
input(matrix1);
print("\nEnter data for the second matrix: \n");
input(matrix2);
matrix3 = multiply(matrix1,matrix2);
print("The product matrix is: \n");
print(matrix3);
print("\n");
}
else{
print("The dimensions are invalid.\n");
}
print("Would you like to continue?(Y/N): ");
again = scan.next().charAt(0);
}while(again == 'y' || again == 'Y');
return;
} |
128e2864-b066-4c7b-96e7-16bf675cfc6f | 8 | protected static Element getModelElement(Document doc, ModelType modelType)
throws Exception {
NodeList temp = null;
Element model = null;
switch (modelType) {
case REGRESSION_MODEL:
temp = doc.getElementsByTagName("RegressionModel");
break;
case GENERAL_REGRESSION_MODEL:
temp = doc.getElementsByTagName("GeneralRegressionModel");
break;
case NEURAL_NETWORK_MODEL:
temp = doc.getElementsByTagName("NeuralNetwork");
break;
case TREE_MODEL:
temp = doc.getElementsByTagName("TreeModel");
break;
case RULESET_MODEL:
temp = doc.getElementsByTagName("RuleSetModel");
break;
default:
throw new Exception("[PMMLFactory] unknown/unsupported model type.");
}
if (temp != null && temp.getLength() > 0) {
Node modelNode = temp.item(0);
if (modelNode.getNodeType() == Node.ELEMENT_NODE) {
model = (Element)modelNode;
}
}
return model;
} |
f8e22ef9-fc31-4d6b-92ca-6b06f096a00d | 4 | public static void main(String[] args)throws IOException
{
double finalAnswer=0;
double finalR2=0;
double finalPeriod=0;
double finalPercDif=0;
for(int i = 2;i<=2;i++){
for(int j=6;j<=6;j++){
for(int k=3;k<=3;k++){
double R2=0;
int period=j;
double difPercent=k;
double answer=OptimiseParameters(R2,period,difPercent);
if(finalAnswer<answer){
finalAnswer=answer;
finalR2=R2;
finalPeriod=period;
finalPercDif=difPercent;
}
}
}
}
System.out.println("The best parameters are : ");
System.out.println("period : "+finalPeriod);
System.out.println("R2 : "+finalR2);
System.out.println("PercentDifferenceNeeded : "+finalPercDif);
System.out.println("The best effective annual return for these parameters is : "+finalAnswer);
} |
3ec56160-2778-4cc7-b10f-606c412f7ffa | 6 | public void moveOneFrame() {
for (int i = 0; i < speed; i++) {
if (direction == NORTH) {
move(0, -1);
} else if (direction == EAST) {
move(1, 0);
} else if (direction == SOUTH) {
move(0, 1);
} else if (direction == WEST) {
move(-1, 0);
}
if (tank.BulletExists()) {
bulletControl();
}
}
} |
7e2124e7-c85a-4c4f-b9aa-d153d5aae767 | 6 | protected static void tryOrdinaryActions(Unit unit) {
// =========================================================
// Act according to STRATEGY, attack strategic targets,
// define proper place for a unit.
UnitType unitType = unit.getType();
// GLOBAL ATTACK is active
if (StrategyManager.isGlobalAttackActive()) {
FrontLineManager.actOffensively(unit);
}
// DEFENSIVE STANCE is active
else {
ArmyRendezvousManager.act(unit);
}
// =========================================================
// SPECIFIC ACTIONS for units, but DON'T FULLY OVERRIDE standard
// behavior
// Tank
if (unitType.isTank()) {
SiegeTankManager.act(unit);
}
// Vulture
else if (unitType.isVulture()) {
if (TerranVulture.act(unit)) {
return;
}
}
// =========================================================
// OVERRIDE COMMANDS FOR SPECIFIC UNITS
// Medic
else if (unitType.isMedic()) {
TerranMedic.act(unit);
return;
}
// ===============================
// ATTACK CLOSE targets (Tactics phase)
if (AttackCloseTargets.tryAttackingCloseTargets(unit)) {
unit.setAiOrder("Attack close");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.