method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
c5d0aa93-8204-45ac-b168-14e61e8a4cf6 | 4 | private void addWorker() {
this.days = Main.getDays();
javax.swing.JTabbedPane tempWorkerDays = new javax.swing.JTabbedPane();
javax.swing.JTextField tempWorkerName = new javax.swing.JTextField();
javax.swing.JPanel tempWorkerTab = new javax.swing.JPanel();
// Makes a tab for each day and a check box for each job.
for (Day day : this.days) {
JCheckBox[] jobs = new JCheckBox[day.getJobs().size()];
for (int i = 0; i < day.getJobs().size(); i++) {
jobs[i] = new JCheckBox(day.getJobs().get(i));
}
// SWAP 1 TEAM 5
//Added in a Rotate monthly checkbox that ensures that this job
//will be rotated back to this specific worker the next month.
JCheckBox rotation = new JCheckBox("Rotate Monthly?");
// Put Check Boxes in a scrollPane for dynamics
JScrollPane tempDayJobPane = new JScrollPane();
JPanel tempPanel = new JPanel();
tempPanel.setLayout(new GridLayout(jobs.length, 1));
for (JCheckBox job : jobs) {
tempPanel.add(job);
}
tempPanel.add(rotation);
tempDayJobPane.setViewportView(tempPanel);
// Label the Pane
JLabel jobLabel = new JLabel("Preferred Jobs:");
// Create a tab Panel for the Worker Tab and add the inputs.
JPanel dayTab = new JPanel();
// Set veritcal and horizontal layouts.
javax.swing.GroupLayout sundayTab1Layout = new javax.swing.GroupLayout(
dayTab);
dayTab.setLayout(sundayTab1Layout);
sundayTab1Layout
.setHorizontalGroup(sundayTab1Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
sundayTab1Layout
.createSequentialGroup()
.addGap(63, 63, 63)
.addGroup(
sundayTab1Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(
tempDayJobPane,
javax.swing.GroupLayout.PREFERRED_SIZE,
198,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(
jobLabel))
.addContainerGap(73,
Short.MAX_VALUE)));
sundayTab1Layout
.setVerticalGroup(sundayTab1Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
sundayTab1Layout
.createSequentialGroup()
.addContainerGap()
.addComponent(jobLabel)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(
tempDayJobPane,
javax.swing.GroupLayout.DEFAULT_SIZE,
179, Short.MAX_VALUE)
.addContainerGap()));
tempWorkerDays.addTab(day.getNameOfDay(), dayTab);
}
// Add a section for the worker's name
JLabel workerNameLabel = new JLabel("Worker's Name:");
// SWAP 1, TEAM 5
/*
* SMELL: Shotgun Surgery - Every time you want to add a label or a button
* you have to go through so many groups and methods.
*/
javax.swing.GroupLayout workerTab1Layout = new javax.swing.GroupLayout(
tempWorkerTab);
tempWorkerTab.setLayout(workerTab1Layout);
workerTab1Layout
.setHorizontalGroup(workerTab1Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
workerTab1Layout
.createSequentialGroup()
.addContainerGap()
.addGroup(
workerTab1Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(
tempWorkerDays)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
workerTab1Layout
.createSequentialGroup()
.addGap(0,
0,
Short.MAX_VALUE)
.addComponent(
workerNameLabel)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(
tempWorkerName,
javax.swing.GroupLayout.PREFERRED_SIZE,
150,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(49,
49,
49)))
.addContainerGap()));
// Adds text area and label for name then tab area for days.
workerTab1Layout
.setVerticalGroup(workerTab1Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
workerTab1Layout
.createSequentialGroup()
.addContainerGap()
.addGroup(
workerTab1Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
workerNameLabel)
.addComponent(
tempWorkerName,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(
tempWorkerDays,
javax.swing.GroupLayout.PREFERRED_SIZE,
249,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
// Prevents a nullPointer
if (this.workerTabs.size() == 0) {
this.workerTabs.add(tempWorkerTab);
this.workerTabPanel.addTab("Worker 1", null, tempWorkerTab, "");
} else {
this.workerTabs.add(tempWorkerTab);
this.workerTabPanel.addTab(
"Worker " + String.valueOf(this.workerTabs.size()), null,
tempWorkerTab, "");
}
} |
4a5836bd-d3a4-4129-adce-4ae16faa1ef9 | 1 | public static void room2()
{
EnemyRat enemy = new EnemyRat();
if (combatDone = false) {
System.out.printf("\n > You step in to a large room with high ceilings supported by stone arches.\n");
System.out.printf("\n > You see a rat!\n");
enemy.combatinitialize();
}
else
Room2.afterCombat();
} |
b29fecf0-9f56-4065-b5cc-fca280e4dd9b | 4 | public void listenerPrincipal(final DiabetesPerceptronContainer diabetesPerceptronGui){
diabetesPerceptronGui.btnAgregarSetAprendizaje.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel temp = (DefaultTableModel) diabetesPerceptronGui.tablaSetAprendizaje.getModel();
Object nuevo[]= {"0","0", "0", "0", "0", "0", "0", "0", "0"};
temp.addRow(nuevo);
}
});
diabetesPerceptronGui.btnEliminarSetAprendizaje.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel temp = (DefaultTableModel) diabetesPerceptronGui.tablaSetAprendizaje.getModel();
if(temp.getRowCount() > 0){
temp.removeRow(temp.getRowCount()-1);
}
}
});
diabetesPerceptronGui.btnAgregarSetPrueba.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel temp = (DefaultTableModel) diabetesPerceptronGui.tablaSetPruebas.getModel();
Object nuevo[]= {"0","0", "0", "0", "0", "0", "0", "0", "-"};
temp.addRow(nuevo);
}
});
diabetesPerceptronGui.btnEliminarSetPrueba.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel temp = (DefaultTableModel) diabetesPerceptronGui.tablaSetPruebas.getModel();
if(temp.getRowCount() > 0){
temp.removeRow(temp.getRowCount()-1);
}
}
});
diabetesPerceptronGui.btnEntrenar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
diabetesPerceptronGui.visibleSalida(false);
diabetesPerceptronGui.lblNoEntrenada.setVisible(true);
diabetesPerceptronGui.lblNoEntrenada.setText("<html><b>Entrenando...</b></html>");
perceptron.setRazonAprendizaje(Double.valueOf(diabetesPerceptronGui.txtRazonAprendizaje.getText()));
perceptron.setLimiteEpocas(Integer.valueOf(diabetesPerceptronGui.txtLimiteEpocasInicial.getText()));
perceptron.setUmbralInicial(Double.valueOf(diabetesPerceptronGui.txtUmbral.getText()));
perceptron.setUmbralFinal(Double.valueOf(diabetesPerceptronGui.txtUmbral.getText()));
perceptron.pesos.put(perceptron.EMBARAZOS, Double.valueOf(diabetesPerceptronGui.txtPesoEmbarazo.getText()));
perceptron.pesos.put(perceptron.CONCENTRACION_GLUCOSA, Double.valueOf(diabetesPerceptronGui.txtPesoConcentracionGlucosa.getText()));
perceptron.pesos.put(perceptron.PRESION_ARTERIAL, Double.valueOf(diabetesPerceptronGui.txtPesoPresionArterial.getText()));
perceptron.pesos.put(perceptron.GROSOR_TRICEPS, Double.valueOf(diabetesPerceptronGui.txtPesoGrosorTriceps.getText()));
perceptron.pesos.put(perceptron.INSULINA, Double.valueOf(diabetesPerceptronGui.txtPesoInsulina.getText()));
perceptron.pesos.put(perceptron.MASA_CORPORAL, Double.valueOf(diabetesPerceptronGui.txtPesoMasaCorporal.getText()));
perceptron.pesos.put(perceptron.FUNCION, Double.valueOf(diabetesPerceptronGui.txtPesoFuncion.getText()));
perceptron.pesos.put(perceptron.EDAD, Double.valueOf(diabetesPerceptronGui.txtPesoEdad.getText()));
perceptron.entrenar(getData(diabetesPerceptronGui.tablaSetAprendizaje.getModel()));
diabetesPerceptronGui.lblNoEntrenada.setVisible(false);
diabetesPerceptronGui.visibleSalida(true);
//Valores finales
DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
simbolos.setDecimalSeparator('.');
DecimalFormat formato = new DecimalFormat("#####.##",simbolos);
diabetesPerceptronGui.lblPesoEmbarazoValor.setText("<html><b>"+formato.format(perceptron.getPeso(perceptron.EMBARAZOS))+"</b></html>");
diabetesPerceptronGui.lblPesoConcentracionGlucosaValor.setText("<html><b>"+formato.format(perceptron.getPeso(perceptron.CONCENTRACION_GLUCOSA))+"</b></html>");
diabetesPerceptronGui.lblPesoPresionArterialValor.setText("<html><b>"+formato.format(perceptron.getPeso(perceptron.PRESION_ARTERIAL))+"</b></html>");
diabetesPerceptronGui.lblPesoGrosorTricepsValor.setText("<html><b>"+formato.format(perceptron.getPeso(perceptron.GROSOR_TRICEPS))+"</b></html>");
diabetesPerceptronGui.lblPesoInsulinaValor.setText("<html><b>"+formato.format(perceptron.getPeso(perceptron.INSULINA))+"</b></html>");
diabetesPerceptronGui.lblPesoMasaCorporalValor.setText("<html><b>"+formato.format(perceptron.getPeso(perceptron.MASA_CORPORAL))+"</b></html>");
diabetesPerceptronGui.lblPesoFuncionValor.setText("<html><b>"+formato.format(perceptron.getPeso(perceptron.FUNCION))+"</b></html>");
diabetesPerceptronGui.lblPesoEdadValor.setText("<html><b>"+formato.format(perceptron.getPeso(perceptron.EDAD))+"</b></html>");
diabetesPerceptronGui.lblUmbralValor.setText("<html><b>"+formato.format(perceptron.getUmbralFinal())+"</b></html>");
diabetesPerceptronGui.lblEpocasValor.setText("<html><b>"+formato.format(perceptron.getNumeroEpocasFinal())+"</b></html>");
}
});
diabetesPerceptronGui.btnClasificar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
diabetesPerceptronGui.ventanaClasificaciones();
}
});
diabetesPerceptronGui.btnClasificarPrueba.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[][] clasificados = perceptron.clasificar(getData(diabetesPerceptronGui.tablaSetPruebas.getModel()));
DefaultTableModel resultModel = (DefaultTableModel) diabetesPerceptronGui.tablaSetPruebas.getModel();
DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
simbolos.setDecimalSeparator('.');
DecimalFormat formato = new DecimalFormat("#####.##",simbolos);
double efectividad = 0;
double porcentaje = 0;
//Obtener las respuestas correctas
String [] respuestas = diabetesPerceptronGui.obtenerRespuestasCorrectas(clasificados.length);
for(int j=0; j<clasificados.length; j++){
resultModel.setValueAt(clasificados[j][8], j, 8);
if(clasificados[j][8].equals(respuestas[j]))
efectividad++;
}
porcentaje = efectividad/clasificados.length;
diabetesPerceptronGui.lblEfectividad.setText("Porcentaje de efectividad: " + formato.format(porcentaje*100) + "%");
}
});
} |
9c50c0a9-48c9-4f01-9bc5-90053ccb7ebe | 6 | public boolean blockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer)
{
if (par1World.isRemote)
{
return true;
}
else
{
int var6 = par1World.getBlockMetadata(par2, par3, par4);
int var7 = var6 & 7;
int var8 = 8 - (var6 & 8);
par1World.setBlockMetadataWithNotify(par2, par3, par4, var7 + var8);
par1World.markBlocksDirty(par2, par3, par4, par2, par3, par4);
par1World.playSoundEffect((double)par2 + 0.5D, (double)par3 + 0.5D, (double)par4 + 0.5D, "random.click", 0.3F, var8 > 0 ? 0.6F : 0.5F);
par1World.notifyBlocksOfNeighborChange(par2, par3, par4, this.blockID);
if (var7 == 1)
{
par1World.notifyBlocksOfNeighborChange(par2 - 1, par3, par4, this.blockID);
}
else if (var7 == 2)
{
par1World.notifyBlocksOfNeighborChange(par2 + 1, par3, par4, this.blockID);
}
else if (var7 == 3)
{
par1World.notifyBlocksOfNeighborChange(par2, par3, par4 - 1, this.blockID);
}
else if (var7 == 4)
{
par1World.notifyBlocksOfNeighborChange(par2, par3, par4 + 1, this.blockID);
}
else
{
par1World.notifyBlocksOfNeighborChange(par2, par3 - 1, par4, this.blockID);
}
return true;
}
} |
c79b8df1-dcf4-4871-8cce-fd51994d3c3b | 0 | public Integer save(Step step) {
return (Integer) sessionFactory.getCurrentSession().save(step);
} |
1b5bf01a-06af-49d9-8689-3d328b020e92 | 7 | public int buscar(String str, int pos) {
String nom, cuen;
if (str == null) {
return -1;
}
if (pos < 0) {
pos = 0;
}
for (int i = pos; i < nElementos; i++) {
nom = clientes[i].obtenerNombre();
if (nom == null) {
continue;
}
if (nom.indexOf(str) > -1) {
return i;
}
cuen = clientes[i].obtenerCuenta();
if (cuen == null) {
continue;
}
if (cuen.indexOf(str) > -1) {
return i;
}
}
return -1;
} |
332e1f18-e396-4f31-ab22-2310e69b7eb6 | 0 | public World()
{
initWorld();
} |
5cd80df9-f635-458a-aec0-3e95048eb187 | 7 | public static int getVerticalDistance(ParserNode node, int childIndex,
int symbolSize) {
List<ParserNode> children = node.getChildren();
int childrenSize = children.size();
// vertikalna udaljenost najnižih sklopova i čvorova sa samo jednim
// djetetom je 0
if (node.getHeight() <= 2 || childrenSize == 1)
return 0;
int height = 0;
if (childIndex < childrenSize / 2) {
// dijete se nalazi u lijevim(gornjim) podstablima, pa je relativna
// udaljenost negativna
for (int i = childIndex + 1; i < childrenSize / 2; i++) {
// na relativnu udaljenost se dodaju visine svih podstabala od
// i+1 do srednjeg
height -= getTreeHeight(children.get(i), symbolSize);
// Ako je i-to dijete operacija, još je potrebno dodati razmak
// između podstabala
if (children.get(i).isOp())
height -= symbolSize;
}
// na relativnu udaljenost se dodaje desna visina podstabla djeteta
height -= getTreeHeightRight(children.get(childIndex), symbolSize);
// na relativnu udaljenost se dodaje razmak od gornjeg ruba zadanog
// čvora do linije ulaza zadanog djeteta
height -= (childIndex + 1) * symbolSize / (childrenSize + 1);
} else {
// dijete se nalazi u desnim (donjim) podstablima, pa je relativna
// udaljenost pozitivna
for (int i = childIndex - 1; i >= childrenSize / 2; i--) {
// na relativnu udaljenost se dodaju visine svih podstabala od
// i-1 do srednjeg
height += getTreeHeight(children.get(i), symbolSize);
// Ako je i-to dijete operacija, još je potrebno dodati razmak
// između podstabala
if (children.get(i).isOp())
height += symbolSize;
}
// na relativnu udaljenost se dodaje lijeva visina podstabla djeteta
height += getTreeHeightLeft(children.get(childIndex), symbolSize);
// na relativnu udaljenost se dodaje razmak od donjeg ruba zadanog
// čvora do linije ulaza zadanog djeteta
height += (childrenSize - childIndex) * symbolSize
/ (childrenSize + 1);
}
return height;
} |
3d11bae2-f4fe-4501-adf6-52ef632fad06 | 7 | private void createSnapshotImage() throws IOException {
File outputfile = new File(snapshotimage);
System.out.println("Save snapshot of gcode to "+snapshotimage);
long time = System.currentTimeMillis();
gp.setSnapshotMode();
gp.jumptoLayer(10000);
gp.togglePause();
gp.setPainttravel(Travel.NOT_PAINTED);
int lc = gp.model.getLayercount(true);
System.out.println("Layers:"+lc);
if(lc==0) System.exit(2);
if(snapmode==1){
//Paint 5 layers only to speed up time
lc = Math.min(lc, 5);
}
int retry=0;
while(gp.getCurrentLayer() == null){
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
retry++;
if(retry > 20){
System.err.println("Timeout waiting for painter");
System.exit(3);
}
}
int ln=0;
while( (ln=gp.getCurrentLayer().getNumber()) < (lc-1) ){
try {
Thread.sleep(500);
System.out.print(".");
} catch (InterruptedException e) {
}
}
int[] sz = gp.getSize(false);
BufferedImage dest = awt.offimg.getSubimage(0, 0, sz[0]-gp.getGap(), sz[1]);
ImageIO.write(dest, "jpg", outputfile);
System.out.println("\nDone (Time: "+ (System.currentTimeMillis()-time)+")");
System.exit(0);
} |
800efe0e-82c5-4a76-a3a6-17fd21da79b2 | 8 | private String getPatternAsFixedString(Class<?> aTargetClass){
String result = null;
if ( BigDecimal.class == aTargetClass || Decimal.class == aTargetClass ) {
result = "_1_ is not in the expected format/range : '_2_'";
}
else if ( Integer.class == aTargetClass ) {
result = "_1_ is not an integer : '_2_'";
}
else if ( hirondelle.web4j.model.DateTime.class == aTargetClass ) {
result = "_1_ is not in the expected date format 'YYYYMMDD' : '_2_'";
}
else if ( SafeText.class == aTargetClass ) {
result = "_1_ contains unpermitted character(s).";
}
else if ( TimeZone.class == aTargetClass ) {
result = "_1_ is not a valid Time Zone identifier: '_2_'";
}
else if ( Locale.class == aTargetClass ) {
result = "_1_ is not a valid Locale identifier: '_2_'";
}
else {
throw new AssertionError("Unexpected case for target base class: " + aTargetClass);
}
return result;
} |
2a3847a3-2b3d-489f-ae59-ab76e54ebfc0 | 3 | protected final void drawCan() {
Graphics pen = null;
final BufferStrategy b = this.getBufferStrategy();
if (b != null) {
pen = b.getDrawGraphics();
}
if (pen != null) {
myPen.simplePen.pen = (Graphics2D) pen;
pen.setColor(background);
pen.fillRect(0, 0, panelWidth, panelHeight);
pen.setColor(Color.BLACK);
try {
that.draw(myPen);
} catch (final Exception e) {
e.printStackTrace();
System.exit(1);
}
}
} |
683f62a6-73ab-4a16-aa88-3a3d6d073591 | 2 | public static final boolean isCPP(String fileName) {
for (String file : CPP) {
if (file.equals(fileName)) {
return true;
}
}
return false;
} |
ea624713-8086-4b2a-a87e-c867ed1c50ff | 8 | public boolean validate(UnitStats unit, PhysicalGameState pgs) {
if (isValidated) {
return true;
}
is_ready = true;
if (unit.id == unitID) {
cooldown = DEFAULT_COOLDOWN;
switch (type) {
case MOVE:
cooldown = unit.definition.move_speed;
isValidated = true;
break;
case ATTACK:
cooldown = unit.definition.attack_speed;
isValidated = true;
break;
case HARVEST:
cooldown = pgs.harvestTime(targetX, targetY);
isValidated = true;
break;
case RETURN:
isValidated = true;
break;
case BUILD:
cooldown = pgs.buildTime(unit.player, !unit.definition.is_building, build);
isValidated = true;
break;
case UPGRADE:
cooldown = pgs.upgradeTime(unit.player, build);
isValidated = true;
break;
}
}
return isValidated;
} |
08edfde2-4e52-4dea-a20c-75faf07dcfca | 1 | private void endGame(String message, int points) {
spielfeld.stopGameLoop();
setTitle(message + "! [" + points + " PUNKT" + (points > 1 ? "E" : "") + "]");
} |
287fdf29-ca0c-4e97-a63a-e1b90238ad98 | 3 | private Set<Particle> getSingleChunck(Particle current) {
Set<Particle> impacting = new HashSet<Particle>();
impacting.add(current);
while (true) {
Set<Particle> tmp = new HashSet<Particle>();
for (Particle pi : impacting) {
tmp.addAll(pi.impacting);
}
boolean changed = impacting.addAll(tmp);
if (!changed) {
break;
}
}
// now impacting have all the chunk of collapsing particles
return impacting;
} |
468acb59-d3d1-4799-a7bf-854cbf341cf7 | 6 | public static ResultSet query(Statement stat, String table, long uid, String... field) throws SQLException {
ResultSet rs = null;
StringBuffer sb = new StringBuffer();
sb.append("select ");
boolean bool = false;
if (field == null || field.length == 0 || field[0].equals("")) {
sb.append(" * ");
bool = true;
}
if (!bool) {
for (int i = 0; i < field.length; i++) {
if (i == field.length - 1) {
sb.append(field[i]);
break;
}
sb.append(field[i]).append(",");
}
}
sb.append(" from ")
.append(table)
.append(" where UID=")
.append(uid);
rs = stat.executeQuery(sb.toString());
return rs;
} |
ea506ea8-db05-41ea-882d-3b0b5a3b7b65 | 0 | public void setNovAaaamm(Integer novAaaamm) {
this.novAaaamm = novAaaamm;
} |
d181f8ff-1c81-4cce-817f-2422478365ff | 2 | public void creer_message(ParseXML monFichier) {
for(int i = 0; i< monFichier.getTrame().length;i++){
int id = monFichier.getTrame()[i].getId();
int taille = monFichier.getTrame()[i].getDlc();
int date = 0;
if(filemessages.isEmpty()){
debut = monFichier.getTrame()[i].getDate();
}
else{
date = (int)(monFichier.getTrame()[i].getDate()-debut);
}
mess_en_cours = message_en_cours(id, date, taille);
filemessages.add(mess_en_cours);
mess_en_cours.decoder(monFichier.getTrame()[i].getData());
}
System.out.println(monFichier.getTrame().length);
System.out.println(filemessages.size());
} |
1070bb52-0f6e-41c8-b0ac-ee30ffaef0be | 1 | public String getSimpleCode(){
String str = item.getSimpleCode();
if(this.items != null)
str += this.items.getSimpleCode();
return str;
} |
034df972-b8ec-4288-9a5f-39956a881b56 | 0 | public void addSink(Set<AndroidMethod> sinks) {
this.sinkMethods.addAll(sinks);
} |
9a402411-4355-4cb6-bf60-fe98294aecd3 | 6 | public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (end()) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
} |
2c2f3ed8-6fa9-4f42-9937-74ff52d91174 | 1 | public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " +
hm.get("Zara"));
} |
6b8852fc-8817-4457-a305-90c476f490e0 | 2 | public static Sprite getSprite(String filename)
{
// Try to load the sprite from the cache
Sprite rval = (Sprite) resourceByString.get(filename);
// If it's not in the cache, try to load it from disk
if(rval == null)
{
try {
rval = new Sprite(filename);
resourceByString.put(filename, rval);
} catch (IOException e) {
// File not there/wrong format, return null
return null;
}
}
return rval;
} |
6e4fb1f0-5d93-45c3-a65a-f95586a9566d | 9 | public static void doSmallSteps(int cases, DataInputStream in, DataOutputStream out) throws IOException {
for (int i = 1; i <= cases; i++) {
String[] input = in.readLine().split("\\ ");
int r = Integer.parseInt(input[0]); // rides
int k = Integer.parseInt(input[1]); // seats
int n = Integer.parseInt(input[2]); // nr of groups
int[] groups = new int[n]; // groups for this case
// groups
input = in.readLine().split("\\ ");
for (int j = 0; j < input.length; j++) {
groups[j] = Integer.parseInt(input[j]);
}
long income = 0;
int groupPosition = 0;
int seatsTaken = 0;
int rides = 0;
int groupsInRide = 0;
// start position, and in array end position [0] and income[1]
Map<Integer, Integer[]> groupStore = new HashMap<Integer, Integer[]>();
boolean allCombinationsFound = false;
// find all combinations, while doing so also calculate the income
// and rides
while (!allCombinationsFound && (rides < r)) {
int startPosition = groupPosition;
// start riding
while (!allCombinationsFound && (seatsTaken + groups[groupPosition % n]) <= k && groupsInRide < n) {
seatsTaken += groups[groupPosition % n];
groupPosition++;
groupsInRide++;
}
rides++;
income += seatsTaken;
groupPosition = groupPosition % n;
if (groupStore.get(startPosition) != null) {
allCombinationsFound = true;
} else {
groupStore.put(startPosition, new Integer[] { groupPosition, seatsTaken });
}
// reset
seatsTaken = 0;
groupsInRide = 0;
}
// now we found all combinations, just read from the map
while (rides < r) {
Integer[] thisRide = groupStore.get(groupPosition);
income += thisRide[1];
groupPosition = thisRide[0];
rides++;
}
String result = ("Case #" + i + ": " + income);
System.out.println(result);
out.writeBytes(result + "\n");
}
} |
9960242a-7e06-4603-80e5-a784deece3b4 | 8 | private static void createTestCase(String name, double bandwidth,
double delay, int totalGridlet, int[] glLength,
int testNum) throws Exception
{
switch(testNum)
{
case 1:
new TestCase1(name, bandwidth, delay, totalGridlet, glLength);
break;
case 2:
new TestCase2(name, bandwidth, delay, totalGridlet, glLength);
break;
case 3:
new TestCase3(name, bandwidth, delay, totalGridlet, glLength);
break;
case 4:
new TestCase4(name, bandwidth, delay, totalGridlet, glLength);
break;
case 5:
new TestCase5(name, bandwidth, delay, totalGridlet, glLength);
break;
case 6:
new TestCase6(name, bandwidth, delay, totalGridlet, glLength);
break;
case 7:
new TestCase7(name, bandwidth, delay, totalGridlet, glLength);
break;
case 8:
new TestCase8(name, bandwidth, delay, totalGridlet, glLength);
break;
default:
System.out.println("Not a recognized test case.");
break;
}
} |
487e2622-ac4a-47c4-94a4-a0697bebd685 | 5 | private String escapeHTML(String source) {
String strResult = "";
String sourceText = "";
int k;
Integer srcLen = source.length();
// Cycle through each input character.
if (srcLen > 0) {
for (int i = 0; i < srcLen; i++) {
sourceText = source.substring(i, i + 1);
// search in htmlEscape[][] if sourceText is there
k = 0;
while (k < htmlEscape.length) {
if (htmlEscape[k][1].equals(sourceText)) {
break;
} else {
k++;
}
}
if (k < htmlEscape.length) {
strResult += htmlEscape[k][0];
} else {
strResult += source.substring(i, i + 1);
}
}
}
return strResult;
} |
2236338e-9eef-467d-987d-3dd9699f10bc | 2 | @Override
public void huolehdi(){
if (tormaavatko()){
kimmotusehto++;
} else {
kimmotusehto = 0;
}
if (kimmotusehto == 1){
kimmota();
vahentaja.huolehdi();
}
} |
d9c163ce-be6f-4e64-b573-b2c01253159a | 9 | private void processTokenFile(String fileName, boolean reversed) throws IOException {
XMLStreamReader reader = resourceGetter.getXMLStreamReader(fileName);
try {
while (reader.hasNext()) {
if (reader.next() == XMLStreamConstants.START_ELEMENT) {
String tagName = reader.getLocalName();
if (tagName.equals("tokenLists")) {
while (reader.hasNext()) {
switch (reader.next()) {
case XMLStreamConstants.START_ELEMENT:
if (reader.getLocalName().equals("tokenList")) {
processTokenList(reader, reversed);
}
break;
}
}
}
else if (tagName.equals("tokenList")) {
processTokenList(reader, reversed);
}
}
}
}
catch (XMLStreamException e) {
throw new IOException("Parsing exception occurred while reading " + fileName, e);
}
finally {
try {
reader.close();
} catch (XMLStreamException e) {
throw new IOException("Parsing exception occurred while reading " + fileName, e);
}
}
} |
bba9bc59-4db2-4e66-a485-feab9f4c6521 | 6 | public Color luoVari(int k1, int k2, int k3){
int a = lueKentta(k1);
int b = lueKentta(k2);
int c = lueKentta(k3);
if(a<0 || b<0 || c<0 || a>255 || b>255 || c>255){
return null;
}
Color co = new Color(a,b,c);
return co;
} |
eca41f75-38f1-4b07-9622-ea5514d0d205 | 8 | private Map<String, String> convertGetAccountActivity(GetAccountActivityRequest request) {
Map<String, String> params = new HashMap<String, String>();
params.put("Action", "GetAccountActivity");
if (request.isSetMaxBatchSize()) {
params.put("MaxBatchSize", request.getMaxBatchSize() + "");
}
if (request.isSetStartDate()) {
params.put("StartDate", request.getStartDate() + "");
}
if (request.isSetEndDate()) {
params.put("EndDate", request.getEndDate() + "");
}
if (request.isSetSortOrderByDate()) {
params.put("SortOrderByDate", request.getSortOrderByDate().value());
}
if (request.isSetFPSOperation()) {
params.put("FPSOperation", request.getFPSOperation().value());
}
if (request.isSetPaymentMethod()) {
params.put("PaymentMethod", request.getPaymentMethod().value());
}
java.util.List<TransactionalRole> roleList = request.getRole();
int roleListIndex = 1;
for (TransactionalRole role : roleList) {
params.put("Role" + "." + roleListIndex, role.value());
roleListIndex++;
}
if (request.isSetTransactionStatus()) {
params.put("TransactionStatus", request.getTransactionStatus().value());
}
return params;
} |
636f0545-99a3-4d18-9e53-29f8a18154e4 | 2 | private static String sendHttpPost(String url,
List<NameValuePair> parameters) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
String output = "";
String line = "";
try {
// sets parameters
List<NameValuePair> nameValuePairs = parameters;
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// executes post
HttpResponse response = client.execute(post);
// returns output as stream
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
while ((line = rd.readLine()) != null) {
output = output + line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
return output;
} |
6fb2ebd8-f406-44af-90ad-a49ebf5dacda | 7 | private int getHeight(TreeNode root)
{
if(root==null) return 0;
if(root.left == null && root.right ==null) return 1;
if(root.left == null && root.right !=null) return getHeight(root.right) + 1;
if(root.left != null && root.right ==null) return getHeight(root.left) + 1;
return Math.max(getHeight(root.right), getHeight(root.left)) +1;
} |
ac22e9b1-cf22-4b0e-bb35-e2e9a611b61d | 2 | private void putCardInToStack() {
if(cardStackTo != null && card != null) {
//card.setSeen(true);
cardStackTo.addCard(card);
cardStackToPanel.setCurrentCount(cardStackTo.getCount());
card = null;
modified = true;
}
} |
48b1a626-8a50-4c3c-b2de-df93bdd5827a | 0 | @Override
public void redo() {
node.setCommentState(newState);
} |
28d0d647-64e1-41c9-aa56-cc5466af490f | 8 | public static String typeof(Object value)
{
if (value == null)
return "object";
if (value == Undefined.instance)
return "undefined";
if (value instanceof Scriptable)
{
if (value instanceof XMLObject)
return "xml";
return (value instanceof Callable) ? "function" : "object";
}
if (value instanceof String)
return "string";
if (value instanceof Number)
return "number";
if (value instanceof Boolean)
return "boolean";
throw errorWithClassName("msg.invalid.type", value);
} |
4ad4ac67-ab1f-43bc-bb6e-e15811e0d651 | 6 | private void restoreValues() {
for (StorageKey key : StorageKey.values()) {
if (!storageValues.containsKey(key.toString())) {
continue;
}
switch (key) {
case outputPath:
springLenghtsTextField.setText(storageValues.get(key.toString()));
Components.moveCurserToEndOfTextField(springLenghtsTextField);
break;
case offset:
offsetTextField.setText(storageValues.get(key.toString()));
Components.moveCurserToEndOfTextField(offsetTextField);
break;
case anglesPath:
anglesFileTextField.setText(storageValues.get(key.toString()));
Components.moveCurserToEndOfTextField(anglesFileTextField);
break;
case weightsPath:
outputFileTextField.setText(storageValues.get(key.toString()));
Components.moveCurserToEndOfTextField(outputFileTextField);
break;
}
}
} |
1bd7074d-f5b6-4695-9bd1-0c05dc61da41 | 3 | private void calcTangents(Vertex[] vertices, int[] indices) {
for (int i = 0; i < indices.length; i += 3) {
int i0 = indices[i];
int i1 = indices[i + 1];
int i2 = indices[i + 2];
Vector3f edge1 = vertices[i1].getPos().sub(vertices[i0].getPos());
Vector3f edge2 = vertices[i2].getPos().sub(vertices[i0].getPos());
float deltaU1 = vertices[i1].getTexCoord().getX() - vertices[i0].getTexCoord().getX();
float deltaV1 = vertices[i1].getTexCoord().getY() - vertices[i0].getTexCoord().getY();
float deltaU2 = vertices[i2].getTexCoord().getX() - vertices[i0].getTexCoord().getX();
float deltaV2 = vertices[i2].getTexCoord().getY() - vertices[i0].getTexCoord().getY();
float fDividend = (deltaU1 * deltaV2 - deltaU2 * deltaV1);
float f = fDividend == 0 ? 0.1f : 1.0f / fDividend;
Vector3f tangent = new Vector3f(0, 0, 0);
tangent.setX(f * (deltaV2 * edge1.getX() - deltaV1 * edge2.getX()));
tangent.setY(f * (deltaV2 * edge1.getY() - deltaV1 * edge2.getY()));
tangent.setZ(f * (deltaV2 * edge1.getZ() - deltaV1 * edge2.getZ()));
vertices[i0].getTangent().set(tangent);
vertices[i1].getTangent().set(tangent);
vertices[i2].getTangent().set(tangent);
}
for (int i = 0; i < vertices.length; i++)
vertices[i].getTangent().set(vertices[i].getTangent().normalized());
} |
dd091f4f-e57b-4c96-a386-a8ef6423170b | 1 | private void warChecker() {
war.checker(playerData);
if (war.warzone) {
ward.setAttackers(player.team);
ward.update();
// war.checker(playerData);
}
} |
948115ac-0534-498c-9697-814fa3daf96f | 8 | @Override
public void onPacket(SendClientHandshakePacket packet) throws ProtocolException {
log.info("Player[" + packet.nickname + "] tries to login...");
boolean passwordCorrect = ssparams.getHashedServerPassword() == null
|| (packet.hashedPassword != null && Hasher.isEqual(ssparams.getHashedServerPassword(), packet.hashedPassword));
sendHandshakeResponse(passwordCorrect);
if(passwordCorrect && !tooManyPlayer) {
accepted = true;
}else{
log.info("Password is " + (passwordCorrect? "correct" : "incorrect") + "!");
if(tooManyPlayer)
log.info("But server is full!");
}
if(!passwordCorrect) {
throw new SecurityException("Wrong password!");
}
if(!accepted) {
throw new ProtocolException("Player not accepted!");
}
playerName = packet.nickname;
} |
1e3aa66a-f3d0-43c1-985f-4a2ce62086c9 | 8 | public static HDRExposure scaleTo( HDRExposure exp, int width, int height ) {
if( !aspectRatioPreserved(exp.width, exp.height, width, height) ) {
throw new UnsupportedOperationException("Cannot change aspect ratio");
}
double scale = width / exp.width;
if( scale == 0 ) {
return new HDRExposure(0, 0);
} else if( scale < 1 ) {
double ratio = exp.width / width;
if( (int)ratio != ratio ) {
throw new UnsupportedOperationException("Cannot scale down by non-integer ratio "+scale);
}
return scaleDown( exp, (int)ratio );
} else {
int iScale = (int)scale;
if( iScale != scale ) {
throw new UnsupportedOperationException("Cannot scale by non-integer "+scale);
}
while( iScale > 0 && (iScale & 1) == 0) {
exp = scaleUp(exp);
iScale >>= 1;
}
if( iScale != 1 ) {
throw new UnsupportedOperationException("Cannot scale by non-power-of-2 "+scale);
}
return exp;
}
} |
09e689ef-7d77-49be-a099-84979daab840 | 3 | public String getTypeDescription() {
if (this.triggerType==1) return " (START)";
else if (this.triggerType==2) return " (END)";
else if (this.triggerType==3) return " (GRAB)";
else return " (UNKNOWN)";
} |
76727d0d-73ce-4d64-85b2-4103682aefe3 | 3 | public ArrayList<Integer> seach(String str) {
ArrayList<Integer> ends = new ArrayList<Integer>();
int i = 0;
Trie[] trieArray = sons;
while (i < str.length() && trieArray[str.charAt(i) - 'a'] != null) {
if (trieArray[str.charAt(i) - 'a'].finish) {
ends.add(i + 1);
}
trieArray = trieArray[str.charAt(i) - 'a'].sons;
++i;
}
return ends;
} |
6b2dabb6-62ac-4289-afa7-2eec23205671 | 4 | public void init(int mode, byte[] key, byte[] iv) throws Exception{
String pad="NoPadding";
byte[] tmp;
if(iv.length>ivsize){
tmp=new byte[ivsize];
System.arraycopy(iv, 0, tmp, 0, tmp.length);
iv=tmp;
}
if(key.length>bsize){
tmp=new byte[bsize];
System.arraycopy(key, 0, tmp, 0, tmp.length);
key=tmp;
}
try{
SecretKeySpec keyspec=new SecretKeySpec(key, "AES");
cipher=javax.crypto.Cipher.getInstance("AES/CBC/"+pad);
cipher.init((mode==ENCRYPT_MODE?
javax.crypto.Cipher.ENCRYPT_MODE:
javax.crypto.Cipher.DECRYPT_MODE),
keyspec, new IvParameterSpec(iv));
}
catch(Exception e){
cipher=null;
throw e;
}
} |
280fa37e-941f-4e58-af44-f50842763a3b | 3 | public final void premultiply(Matrix matrix) {
entry2[3][0] = entry[3][1] = entry[3][2] = 0.0;
entry2[3][3] = 1.0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++) {
entry2[i][j] = 0.0;
for (int k = 0; k < 4; k++)
entry2[i][j] += matrix.entry[i][k] * entry[k][j];
}
// Swap!
double[][] oldentry = entry;
entry = entry2;
entry2 = oldentry;
} |
5518aabb-de47-4624-8f2b-94146a15e6fd | 3 | public void fillArr(int x, int y) {
ArrayList<Delta> changes = currentTool.apply(curColor, x, y, currentLayer.colorArr);
ArrayList<Delta> accepted = new ArrayList<>();
for (Delta d : changes) {
if (!d.amUseless()) {
accepted.add(d);
}
}
currentLayer.redo = new Stack<>();
if (accepted.size() > 0) {
currentLayer.undo.push(accepted);
}
} |
45ee4230-1cd2-4a4f-bcc3-ee772676c1a2 | 4 | @SafeVarargs
public static <T> List<T> concat(T[]... ts)
{
int size = 0;
for (T[] ta : ts)
{
if (ta == null)
{
continue;
}
size += ta.length;
}
List<T> l = new ArrayList<T>(size);
for (T[] ta : ts)
{
for (T t : ta)
{
l.add(t);
}
}
return l;
} |
63a3ad97-1fe9-4bee-8b7a-22532058b544 | 6 | @Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors erros = new ActionErrors();
if(contato.getNome() == null || contato.getNome().isEmpty()) {
erros.add("nome", new ActionMessage("erro.campoNome"));
}
if(contato.getEndereco() == null || contato.getEndereco().isEmpty()) {
erros.add("endereco", new ActionMessage("erro.campoEndereco"));
}
if(contato.getEmail() == null || contato.getEmail().isEmpty()) {
erros.add("email", new ActionMessage("erro.campoEmail"));
}
return erros;
} |
d7d37dd0-a28b-498f-8633-6632927a49c8 | 4 | @SuppressWarnings("deprecation")
@EventHandler
public void onPlayerInteractEvent(PlayerInteractEvent event) {
Player p = event.getPlayer();
Action eAction = event.getAction();
if (p.hasPermission("spectacle.create")
&& p.getItemInHand().getTypeId() == Spectacles.toolID) {
if (eAction == Action.LEFT_CLICK_BLOCK) {
instance.setFirstLoc(event.getClickedBlock().getLocation());
p.sendMessage(ChatColor.GREEN + "First point for Spectacle region set!");
event.setCancelled(true);
} else if (eAction == Action.RIGHT_CLICK_BLOCK) {
instance.setSecondLoc(event.getClickedBlock().getLocation());
p.sendMessage(ChatColor.GREEN + "Second point for Spectacle region set!");
event.setCancelled(true);
}
}
} |
ea25b3c3-de81-4f2e-802a-cf732bb7aaf0 | 3 | @Override
public boolean updateCustomer(Customer customer) {
if (doc == null)
return false;
Element currRoot = doc.getRootElement();
Element parrentCusto = currRoot.getChild("customers");
List<Element> listCusto = parrentCusto.getChildren();
for (Element currCusto : listCusto) {
int custoID = Integer.parseInt(currCusto.getChild("customerID")
.getText());
if (customer.getCustomerID() == custoID) {
currCusto.getChild("name").setText(customer.getName());
currCusto.getChild("surename").setText(customer.getSurname());
currCusto.getChild("address").setText(customer.getAddress());
return true;
}
}
return false;
} |
4ae5b386-a3c8-4906-8143-e32a248ad8d7 | 0 | public void setDefaultPoints(int defaultPoints) {
this.defaultPoints = defaultPoints;
} |
926db10d-7231-48f7-a454-cbca6a401355 | 7 | public void update(){
if(ticksScared >= MAX_TICKS_SCARED)scared = false;
if(scared) {
ticksScared++;
}
super.update();
if(scared)if(!isMoving() && Util.RANDOM.nextInt(1000) < WALK_CHANGE_SCARED) moveRandomLocation(WALK_RANGE);
else if(!isMoving() && Util.RANDOM.nextInt(1000) < WALK_CHANGE_NORMAL) moveRandomLocation(WALK_RANGE);
} |
17a434f1-afc1-4ca5-93d1-8e7d63ea52df | 2 | private boolean pluginFile(String name)
{
for (final File file : new File("plugins").listFiles()) {
if (file.getName().equals(name)) {
return true;
}
}
return false;
} |
c94181b8-b228-4c08-b76d-f491b2c98a90 | 9 | static void plot(int x, int y, int z, int argb, int argbBackground,
String text, Font3D font3d, Graphics3D g3d) {
if (text.length() == 0)
return;
Text3D text3d = getText3D(text, font3d, g3d.platform);
int[] bitmap = text3d.bitmap;
int textWidth = text3d.width;
int textHeight = text3d.height;
if (x + textWidth < 0 || x > g3d.width ||
y + textHeight < 0 || y > g3d.height)
return;
if (x < 0 || x + textWidth > g3d.width ||
y < 0 || y + textHeight > g3d.height)
plotClipped(x, y, z, argb, argbBackground,
g3d, textWidth, textHeight, bitmap);
else
plotUnclipped(x, y, z, argb, argbBackground,
g3d, textWidth, textHeight, bitmap);
} |
2ef28dac-7d8b-4d3f-984e-269753f99e37 | 3 | public double median_as_double() {
double median = 0.0D;
switch (type) {
case 1:
double[] dd = this.getArray_as_double();
median = Stat.median(dd);
break;
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
median = Stat.median(bd).doubleValue();
bd = null;
break;
case 14:
throw new IllegalArgumentException("Complex median value not supported");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
return median;
} |
cc9fad8e-270b-41f0-9e06-9e08859eee9f | 6 | public static List<Integer> intersectSortedArraysThree(int[] a, int[] b) {
ArrayList<Integer> result = new ArrayList<Integer>();
int i = 0;
int j = 0;
while (i < a.length && j < b.length) {
if ((i == 0 || a[i] != a[i - 1]) && (a[i] == b[j])) {
result.add(a[i]);
i++;
j++;
continue;
}
if (a[i] < b[j]) {
i++;
}else {
j++;
}
}
return result;
} |
076ef867-7289-4694-abd4-41eb74fb58f7 | 5 | private String buildNUM() {
int k = 0;
String str = "";
do {
str += (char) c;
k++;
c = getchar();
} while( myisdigit((char) c) && k < MAXLEN_ID );
putback = true;
if( myisdigit((char) c) && k == MAXLEN_ID ) {
do { c = getchar(); } while(myisdigit((char) c));
System.err.println("scan: number too long -- truncated to "
+ str);
}
return str;
} |
d981e843-aabf-46ea-9a6e-3694a07c5755 | 5 | static final void method2280(byte i, int i_20_) {
anInt3826++;
if (Class289.aByteArrayArrayArray3700 == null)
Class289.aByteArrayArrayArray3700
= (new byte[4][Class367_Sub4.mapSizeX]
[Class348_Sub40_Sub3.mapSizeY]);
if (i_20_ != 28587)
method2278(35, -47, (byte) 56, -93);
for (int i_21_ = 0; (i_21_ ^ 0xffffffff) > -5; i_21_++) {
for (int i_22_ = 0; Class367_Sub4.mapSizeX > i_22_; i_22_++) {
for (int i_23_ = 0;
((i_23_ ^ 0xffffffff)
> (Class348_Sub40_Sub3.mapSizeY ^ 0xffffffff));
i_23_++)
Class289.aByteArrayArrayArray3700[i_21_][i_22_][i_23_] = i;
}
}
} |
73c05477-812f-4f22-b415-74e73ad3e0cf | 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(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InfoDialog.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 InfoDialog().setVisible(true);
}
});
} |
aba372a4-ec27-4c64-b602-4eb36606b054 | 1 | @Override
public Label predict(Instance instance) {
if (linkFunction(this.innerProduct(instance)) >= 0.5) {
return new ClassificationLabel(1);
}
return new ClassificationLabel(0);
} |
ec47739c-c182-41a2-9d15-2db58a3a06a8 | 8 | public void windowDeactivated(WindowEvent arg0) {
areax = game.getColumns()*2;
areay = game.getRows();
ships = game.getBoats();
player1 = game.playerOne();
player2 = game.playerTwo();
placement = game.gameType();
diagonal = game.levelType();
marked = game.gameMode();
grid1 = new TheGrid(areax/2, areay);
grid2 = new TheGrid(areax/2, areay);
grid1.resetGridOffset();
grid2.resetGridOffset();
if(placement != true && !player2.equals("Rofongo")) {
JOptionPane.showMessageDialog(null, player2 + " enter your coordinates. \nExample: a1-b1");
grid1.placeTheBoats(ships, diagonal);
JOptionPane.showMessageDialog(null, player1 + " enter your coordinates. \nExample: a1-b1");
grid2.placeTheBoats(ships, diagonal);
}
else if(placement == true && !player2.equals("Rofongo")) {
RandomBoats.placeBoats(areax/2, areay, diagonal, ships, grid1);
RandomBoats.placeBoats(areax/2, areay, diagonal, ships, grid2);
}
else if (placement == true && player2.equals("Rofongo")) {
RandomBoats.placeBoats(areax/2, areay, diagonal, ships, grid1);
RandomBoats.placeBoats(areax/2, areay, diagonal, ships, grid2);
}
else if (placement != true && player2.equals("Rofongo")) {
RandomBoats.placeBoats(areax/2, areay, diagonal, ships, grid1);
JOptionPane.showMessageDialog(null, player1 + " enter your coordinates. \nExample: a1-b1");
grid2.placeTheBoats(ships, diagonal);
}
status = new Status(player1, player2);
reset = true;
repaint();
} |
54fc74c4-0d24-4176-9985-d8508f32e7e8 | 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(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Client.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 Client().setVisible(true);
}
});
} |
091537f9-8c50-429c-951f-cdbf3a491b9c | 4 | public void saveGraphFile()
{
//==== Initialize the filechooser, using the user's home dir, or the last working dir
if(this.currentDirectory.equals(""))
{ this.fc = new JFileChooser(); }
else
{ this.fc = new JFileChooser(this.currentDirectory); }
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
//==== Get the file object, and its filename
File file = fc.getSelectedFile();
final String fileName = file.getAbsolutePath();
//==== if the file already exists, warn the user before overwriting
if(file.exists())
{
//==== Create a frame with the message
final JFrame overwriteMessage = new JFrame();
overwriteMessage.setTitle("Overwrite file?");
overwriteMessage.setLocationRelativeTo(fc);
JLabel title = new JLabel(" " + fileName);
title.setFont(new Font("Tahoma", 0, 12));
JLabel title2 = new JLabel(" File already exists, overwrite it?");
title.setFont(new Font("Tahoma", 0, 12));
//==== Create the button for overwriting the file
JButton saveButton = new JButton();
saveButton.setText("Yes");
saveButton.setToolTipText("Overwrite file?");
saveButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
//TODO ResultXML xml = new ResultXML();
// xml.writeFile(graph.getGraph(), fileName);
overwriteMessage.setVisible(false);
}
});
//==== Create the button for not overwriting the file
JButton noButton = new JButton();
noButton.setText("No");
noButton.setToolTipText("Overwrite file");
noButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
overwriteMessage.setVisible(false);
}
});
//==== Add the buttons to a panel, and setup the layout
JPanel buttons = new JPanel();
GridLayout buttonLayout = new GridLayout(1,2);
buttonLayout.addLayoutComponent("savebutton", saveButton);
buttonLayout.addLayoutComponent("nobutton", noButton);
buttons.add(saveButton);
buttons.add(noButton);
buttons.setLayout(buttonLayout);
//==== Add the label, and the button panel, to another panel and setup the layout
JPanel complete = new JPanel();
GridLayout layout = new GridLayout(3,1);
layout.addLayoutComponent("title", title);
layout.addLayoutComponent("title2", title2);
layout.addLayoutComponent("buttons", buttons);
complete.add(title);
complete.add(title2);
complete.add(buttons);
complete.setLayout(layout);
Dimension d = new Dimension(450, 100);
overwriteMessage.setSize(d);
overwriteMessage.setContentPane(complete);
overwriteMessage.setVisible(true);
}
//==== file doesn't already exist, so just write it
else
{
//==== If it doesn't already have the .xml extension, add it
String xmlExtension = ".xml";
String fileName2 = fileName;
if (!fileName.contains(xmlExtension))
fileName2 = file.getAbsolutePath() + xmlExtension;
// TODO ResultXML xml = new ResultXML();
// xml.writeFile(this.graph.getGraph(), fileName2);
}
this.currentDirectory = file.getPath();
}
} |
ec026df1-6a64-4ed4-b2ca-78de8f977544 | 9 | public static void main(String[] args) throws Exception {
System.out.println("Please select a folder with your tiled pictures");
System.out.println("Your pictures will be stiched together from left to right \n in alphabetical order.");
File file = new File(FileChooser.pickADirectory());
if(file.listFiles() == null) {
System.out.println("Please restart, but pick something this time.");
throw new IllegalArgumentException("Please pick a file");
}
List<Picture> pictures = new ArrayList<>();
List<File> childrenFiles = Arrays.asList(file.listFiles());
List<String> childrenPaths = new ArrayList<>();
for (File f : childrenFiles) {
childrenPaths.add(f.getPath());
}
Collections.sort(childrenPaths);
for (String s : childrenPaths) {
if(s.toLowerCase().endsWith(".jpg") || s.toLowerCase().endsWith(".jpeg")) {
pictures.add(new Picture(s));
}
}
int maxHeight = 0;
int Width = 0;
for(Picture pic : pictures) {
if (pic.getHeight() > maxHeight) {
maxHeight = pic.getHeight();
}
Width += pic.getWidth();
}
Picture panorama = new Picture(Width, maxHeight);
panorama.setAllPixelsToAColor(Color.WHITE);
int xLoc = 0;
for(Picture pic : pictures) {
System.out.println("Amending picture @ " + pic.getFileName());
for(Pixel picPix : pic.getPixels()) {
panorama.setBasicPixel(xLoc + picPix.getX(), picPix.getY(), picPix.getColor().getRGB());
}
xLoc += pic.getWidth();
}
System.out.printf("Showing the final stiched picture made from %d originals", pictures.size());
panorama.show();
} |
a902b819-8429-4c01-a57f-32ba8054ffb9 | 2 | public static StdImage getImage(JComponent component) {
StdImage offscreen = null;
synchronized (component.getTreeLock()) {
Graphics2D gc = null;
try {
Rectangle bounds = component.getVisibleRect();
offscreen = StdImage.createTransparent(component.getGraphicsConfiguration(), bounds.width, bounds.height);
gc = offscreen.getGraphics();
gc.translate(-bounds.x, -bounds.y);
component.paint(gc);
} catch (Exception exception) {
Log.error(exception);
} finally {
if (gc != null) {
gc.dispose();
}
}
}
return offscreen;
} |
d10f12d2-1c11-45cd-afe1-e53de0f09749 | 6 | private void jBListarIncidentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBListarIncidentesActionPerformed
// TODO add your handling code here:
int tipo = combo_tipo_reporte.getSelectedIndex();
if (tipo != 0) {
TipoInscidente codigotipo = controlador.buscarTipoIncidente(combo_tipo_reporte.getSelectedItem().toString());
getControlador().cargarIncidentesPorTipo(codigotipo.getTipinc_codigo());
DefaultTableModel lstIncidente = (DefaultTableModel) tableListaIncidente.getModel();
if (!getControlador().getListaInciTipo().isEmpty()) {
JOptionPane.showMessageDialog(null, "Se tienen " + getControlador().getListaInciTipo().size() + " Incidentes Registrados de Tipo: " + codigotipo.getTipinc_descripcion());
tableListaIncidente.removeAll();
int rowCount = lstIncidente.getRowCount();
for (int i = 0; i < rowCount; i++) {
lstIncidente.removeRow(i);
}
for (int i = 0; i < getControlador().getListaInciTipo().size(); i++) {
lstIncidente.addRow(new Object[]{getControlador().getListaInciTipo().get(i).getTipo_incidente().getTipinc_descripcion(), getControlador().getListaInciTipo().get(i).getInc_codigoIncidente(), getControlador().getListaInciTipo().get(i).getInc_descripcionIncidente(), getControlador().getListaInciTipo().get(i).getInc_fechaIncidente(), getControlador().getListaInciTipo().get(i).getUsuario().getTelefono(), getControlador().getListaInciTipo().get(i).getBarrio().getBar_nombre()});
}
} else {
JOptionPane.showMessageDialog(null, "No tiene Se Tienen Incidentes de Tipo: " + codigotipo.getTipinc_descripcion());
int rowCount = lstIncidente.getRowCount();
for (int i = 0; i < rowCount; i++) {
lstIncidente.removeRow(i);
}
if (lstIncidente.getRowCount() > 0) {
lstIncidente.removeRow(tableListaIncidente.getSelectedRow());
}
}
} else {
JOptionPane.showMessageDialog(null, "Debe Seleccionar Un Tipo De Incidente");
}
}//GEN-LAST:event_jBListarIncidentesActionPerformed |
377f589e-62d6-4c1f-a0f2-6038e4b1e1b1 | 9 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!(myHost instanceof MOB))
return super.okMessage(myHost,msg);
final MOB myChar=(MOB)myHost;
if((msg.tool()==null)||(!(msg.tool() instanceof Ability)))
return super.okMessage(myChar,msg);
if(msg.amISource(myChar)
&&(myChar.isMine(msg.tool())))
{
if((msg.sourceMinor()==CMMsg.TYP_CAST_SPELL)
&&(!CMLib.ableMapper().getDefaultGain(ID(),true,msg.tool().ID())))
{
if(CMLib.dice().rollPercentage()>
(myChar.charStats().getStat(CharStats.STAT_INTELLIGENCE)*((myChar.charStats().getCurrentClass().ID().equals(ID()))?1:2)))
{
myChar.location().show(myChar,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> fizzle(s) a spell."));
return false;
}
}
}
return super.okMessage(myChar,msg);
} |
c6c56932-ae28-4991-8ff6-c86ca6c53bf8 | 8 | @Override
public String intercept(ActionInvocation invocation) throws Exception {
Map<String, Object> session = invocation.getInvocationContext()
.getSession();
// 获取action
String actionNameString = invocation.getInvocationContext().getName();
// System.out.println(actionNameString);
// 获取用户等级
String level = (String) session.get("USER_LEVEL");
// 过滤需要登陆的界面
if (actionNameString != null && level != null) {
int levelint = Integer.parseInt(level);
if (actionNameString.startsWith("admin_") && levelint != 4) {
// 用户权限为4才能访问admin_开头的action
return result;
}
if (actionNameString.startsWith("tch_") && levelint != 2) {
// 用户权限为2才能访问tch_开头的action
return result;
}
if (actionNameString.startsWith("stu_") && levelint != 1) {
// 用户权限为1才能访问stu_开头的action
return result;
}
}
// 不需要登陆的界面不过滤直接放行
String resultCode = invocation.invoke();
return resultCode;
} |
4c5b1781-fc1f-45ae-97c8-1cb25c3df25a | 6 | public ShipChassis getShipChassis(String id) {
ShipChassis result = shipChassisMap.get(id);
if ( result == null ) { // Wasn't cached; try parsing it.
InputStream in = null;
try {
in = getDataInputStream("data/"+ id +".xml");
result = dataParser.readChassis(in);
shipChassisMap.put( id, result );
} catch (JAXBException e) {
log.error( "Parsing XML failed for ShipChassis id: "+ id );
} catch (FileNotFoundException e) {
log.error( "No ShipChassis found for id: "+ id );
} catch (IOException e) {
log.error( "An error occurred while parsing ShipChassis: "+ id, e );
} finally {
try {if (in != null) in.close();}
catch (IOException f) {}
}
}
return result;
} |
77f9b293-f060-4f43-9146-9528bf7ccb4b | 1 | public static void Eliminar(Object o) {
Transaction t = cx.beginTransaction();
try {
cx.delete(o);
t.commit();
cx.flush();
} catch (Exception e) {
System.out.println("no se inserto");
t.rollback();
}
} |
cc075d35-6109-4765-ac85-b70f33b22a03 | 8 | public void iterativePostOrder(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode currentNode = root;
while (currentNode != null) {
if (currentNode.getLeft() != null) {
stack.push(currentNode);
currentNode = currentNode.getLeft();
} else if (currentNode.getRight() != null) {
stack.push(currentNode);
currentNode = currentNode.getRight();
} else {
System.out.println(currentNode.getData());
// iterate while either right != current node or right is not
// null, and stack should not be empty
while (!stack.isEmpty()
&& (stack.peek().getRight() == currentNode || stack
.peek().getRight() == null)) {
currentNode = stack.pop();
System.out.println(currentNode.getData());
}
if (!stack.isEmpty()) {
currentNode = stack.peek().getRight();
} else {
break;
}
}
}
} |
856883ca-6b77-4a24-a2a6-2ec83d8ba80a | 2 | public boolean checkShapeDate(long fechaDesde, long fechaHasta){
return (fechaAlta >= fechaDesde && fechaAlta < fechaHasta && fechaBaja >= fechaHasta);
} |
ca63dd68-3b95-4141-a43d-bc3545bf5441 | 0 | public void removeCompleteListener(ActionListener listener){
completeListeners.remove(listener);
} |
6695b56a-e8d8-4bb9-815c-7d42974c130b | 2 | private static int createOldStyleIcon(StdImage image, List<byte[]> imageData, List<Integer> imageType, int type) {
int size = image.getWidth();
byte[] bytes = new byte[size * size * 4];
int i = 0;
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
EndianUtils.writeBEInt(image.getRGB(x, y), bytes, 4 * i++);
}
}
imageData.add(bytes);
imageType.add(Integer.valueOf(type));
return 8 + bytes.length;
} |
138d5b40-4cfa-4a4d-a3de-7be81a8c3f07 | 7 | @Override
public V put( K key, V value ) {
Node node = mRoot;
Node newNode = new Node( key, value );
if( node == null ) {
insertNode( newNode, node, false );
return null;
}
while( true ) {
if( mComp.compareMaxes( key, node.mMaxStop.mKey ) > 0 ) {
node.mMaxStop = newNode;
}
int c = mComp.compareMins( key, node.mKey );
if( c == 0 ) {
c = mComp.compareMaxes( key, node.mKey );
}
if( c < 0 ) {
if( node.mLeft == null ) {
insertNode( newNode, node, true );
break;
}
node = node.mLeft;
} else {
if( node.mRight == null ) {
insertNode( newNode, node, false );
break;
}
node = node.mRight;
}
}
return null;
} |
d9aa4f6f-5188-4e15-8331-c04cbab24545 | 3 | @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("POST = ");
FacDAO usuarioDAO = (FacDAO) getServletContext().getAttribute("smsManager");
String login = request.getParameter("login");
// System.out.println("login = " + login);
String password = request.getParameter("pass");
// System.out.println("password = " + password);
String stats = request.getParameter("stats");
System.out.println("stats = " + stats);
String portlet = request.getParameter("portlet");
HttpSession session = request.getSession(true);
String nextJSP;
/*Usuario user = (Usuario) session.getAttribute("user");
if (user == null || portlet!= null) {
user = usuarioDAO.getUsuario(login, password);
if (user!=null) {
System.out.println("user.getCompleteName() = " + user.getNombreUsuario());
}
}*/
String miIP = request.getRequestURL().toString();
String uri = request.getRequestURI();
logger.info("uri = " + uri);
logger.info("miIP antes = " + miIP);
int inicioUrl = 0;
String httpS = "http://";
if (miIP.contains(httpS)) {
inicioUrl = miIP.indexOf(httpS)+httpS.length();
}
miIP = miIP.substring(inicioUrl, miIP.indexOf(uri));
String conPuerto = ":";
if(miIP.contains(conPuerto)){
miIP = miIP.substring(0, miIP.indexOf(conPuerto));
}
logger.info("miIP despues = " + miIP);
if(request.getQueryString() != null){
}
/*if(user == null){
if (login != null) {
request.setAttribute("msg", "Error en el Usuario");
}
nextJSP = "/indexOld.jsp";
} else if(user.getEstadoUsuario() == 0){
request.setAttribute("msg", "Usuario Inactivo");
nextJSP = "/indexOld.jsp";
} else if(user.getMaquinaByIdMaquina() == null){
request.setAttribute("msg", "Usuario No Tiene Máquina registrada");
nextJSP = "/indexOld.jsp";
} else if(!user.getMaquinaByIdMaquina().getIpMaquina().equals(miIP)){ // NO DE LA MAQUINA
FacDAO smsDAO = (FacDAO) getServletContext().getAttribute("smsManager");
Maquina maquina = smsDAO.getMaquinaByIP(miIP);
String errorMaquina = "Usuario No Pertenece a esta Máquina";
if(maquina != null){
errorMaquina += ": " +maquina.getNombreMaquina();
} else {
errorMaquina = "Esta Máquina con IP: "+ miIP +" no está Registrada";
}
request.setAttribute("msg", errorMaquina);
nextJSP = "/indexOld.jsp";
} else {
int idRol = user.getRolByIdRole().getIdRol();
System.out.println("user = " + user + " idRol = " + idRol);
if (idRol == 1) {
nextJSP = "/p1_admin.jsp";
} else if (idRol == 2) {
nextJSP = "/p2_op.jsp";
} else if (idRol == 3) {
nextJSP = "/p3_sup.jsp";
} else if (idRol == 4) {
nextJSP = "/p4_ger.jsp";
if(stats!=null){
nextJSP = "/stats.jsp";
}
} else if (idRol == 6) {
nextJSP = "/stats.jsp";
} else {
nextJSP = "/indexOld.jsp";
}
session.setAttribute("user", user);
}*/
// RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
// dispatcher.forward(request, response);
} |
c77de777-71d0-4263-9303-b085f76e08b6 | 6 | public void update(GameContainer container) {
timeout--;
if(timeout == 0 && current == images.size() - 1) {
Board.menuStack.pop();
Board.menuStack.add(new StartMenu());
} else if(timeout == 0) {
timeout = 150;
current++;
} else if((Mouse.isButtonDown(0) || Keyboard.isKeyDown(Keyboard.KEY_SPACE)) && !skipped) {
skipped = true;
timeout = 30;
current = images.size() - 1;
}
} |
d15f0ddc-0733-4838-adc6-f99c6cffc74f | 4 | public void setPixel(int x, int y, short red, short green, short blue) {
// Your solution here.
assert (x < height && y < width);
assert (0 <= red && red <= 255);
assert (0 <= blue && blue <= 255);
assert (0 <= green && green <= 255);
pixel[y][x].red = red;
pixel[y][x].blue = blue;
pixel[y][x].green = green;
} |
9771a1a4-bdd4-492f-a655-f7608d6bd5a8 | 7 | public static void materializePrimitiveDescriptionBody(NamedDescription description) {
{ boolean nativeP = description.nativeRelation() != null;
Symbol name = (nativeP ? Symbol.internSymbolInModule(description.nativeRelation().name(), description.nativeRelation().homeModule(), true) : description.descriptionName());
List variabletypes = description.ioVariableTypes;
int arity = variabletypes.length();
Cons tree = null;
Cons variables = Stella.NIL;
Cons arguments = Stella.NIL;
{ IntegerIntervalIterator i = Stella.interval(1, arity);
Symbol name000 = null;
Cons iter000 = Logic.SYSTEM_DEFINED_ARGUMENT_NAMES;
Cons collect000 = null;
for (;i.nextP() &&
(!(iter000 == Stella.NIL)); iter000 = iter000.rest) {
name000 = ((Symbol)(iter000.value));
if (collect000 == null) {
{
collect000 = Cons.cons(name000, Stella.NIL);
if (variables == Stella.NIL) {
variables = collect000;
}
else {
Cons.addConsToEndOfConsList(variables, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(name000, Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
arguments = Cons.copyConsList(variables);
if (nativeP &&
(arity > 1)) {
variables.firstSetter(Cons.list$(Cons.cons(Logic.SYM_STELLA_ISA, Cons.cons(variables.value, Cons.cons(Cons.cons(Surrogate.typeToSymbol(((Surrogate)(variabletypes.first()))), Stella.NIL), Stella.NIL)))));
}
tree = Cons.list$(Cons.cons(Logic.SYM_LOGIC_KAPPA, Cons.cons(variables, Cons.cons(Cons.cons(Cons.cons(name, arguments.concatenate(Stella.NIL, Stella.NIL)), Stella.NIL), Stella.NIL))));
{ Object old$LogicDialect$000 = Logic.$LOGIC_DIALECT$.get();
Object old$Logicvariabletable$000 = Logic.$LOGICVARIABLETABLE$.get();
Object old$Termunderconstruction$000 = Logic.$TERMUNDERCONSTRUCTION$.get();
Object old$Evaluationmode$000 = Logic.$EVALUATIONMODE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Logic.$LOGIC_DIALECT$, Logic.KWD_KIF);
Native.setSpecial(Logic.$LOGICVARIABLETABLE$, Stella.NIL);
Native.setSpecial(Logic.$TERMUNDERCONSTRUCTION$, tree);
Native.setSpecial(Logic.$EVALUATIONMODE$, Logic.KWD_DESCRIPTION);
Native.setSpecial(Stella.$CONTEXT$, description.homeContext);
{ Description sacrificialdescription = Logic.evaluateDescriptionTerm(tree, false);
description.ioVariables = sacrificialdescription.ioVariables;
description.proposition = sacrificialdescription.proposition;
sacrificialdescription.deletedPSetter(true);
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Logic.$EVALUATIONMODE$.set(old$Evaluationmode$000);
Logic.$TERMUNDERCONSTRUCTION$.set(old$Termunderconstruction$000);
Logic.$LOGICVARIABLETABLE$.set(old$Logicvariabletable$000);
Logic.$LOGIC_DIALECT$.set(old$LogicDialect$000);
}
}
}
} |
cd112ac4-f3e3-4136-9b3e-78d6c47b8fa6 | 7 | public static ArrayList<Electrodomestico> getAllElectrodomestico(int montoMin,int montoMax,char consumo)
{
ArrayList<Electrodomestico> colElectrodomestico=new ArrayList<Electrodomestico>();
String sqlFiltros="";
if(montoMin>0)
sqlFiltros=sqlFiltros.concat(" and preciobase>"+montoMin+" ");
if(montoMax>0)
sqlFiltros=sqlFiltros.concat(" and preciobase<"+montoMax+" ");
if(consumo!=' ')
{
sqlFiltros=sqlFiltros.concat(" and consumo='"+consumo+"' ");
}
try {
Connection con = conexion.conectarDB();
Statement sql = con.createStatement();
ResultSet cmd=sql.executeQuery("Select * from electrodomestico where tipo is not null "+sqlFiltros+" order by descripcion;");
while(cmd.next())
{
if(cmd.getString("Tipo").equals("Lavarropas"))
{
Lavarropas lav = new Lavarropas(cmd.getInt("carga"), cmd.getInt("preciobase"), cmd.getString("color"), cmd.getString("consumo").charAt(0), cmd.getInt("peso"));
lav.setCodElectrodomestico(cmd.getInt("idelectrodomestico"));
lav.setDescripcion(cmd.getString("descripcion"));
lav.setTipo(cmd.getString("Tipo"));
colElectrodomestico.add(lav);
}
else
{
Boolean sin=false;
if(cmd.getInt("tdt")>0)
sin=true;
Television tel = new Television(cmd.getInt("pulgadas"), sin, cmd.getInt("preciobase"), cmd.getString("color"), cmd.getString("consumo").charAt(0), cmd.getInt("peso"));
tel.setCodElectrodomestico(cmd.getInt("idelectrodomestico"));
tel.setDescripcion(cmd.getString("descripcion"));
tel.setTipo(cmd.getString("Tipo"));
colElectrodomestico.add(tel);
}
}
} catch (Exception ex) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null,ex.getMessage());
}
return colElectrodomestico;
} |
175d09d6-abb6-46d2-b259-14d49333bf87 | 7 | void menuSave() {
if (image == null) return;
animate = false; // stop any animation in progress
// If the image file type is unknown, we can't 'Save',
// so we have to use 'Save As...'.
if (imageData.type == SWT.IMAGE_UNDEFINED || fileName == null) {
menuSaveAs();
return;
}
Cursor waitCursor = display.getSystemCursor(SWT.CURSOR_WAIT);
shell.setCursor(waitCursor);
imageCanvas.setCursor(waitCursor);
try {
// Save the current image to the current file.
loader.data = new ImageData[] {imageData};
if (imageData.type == SWT.IMAGE_JPEG) loader.compression = compressionCombo.indexOf(compressionCombo.getText()) + 1;
if (imageData.type == SWT.IMAGE_PNG) loader.compression = compressionCombo.indexOf(compressionCombo.getText());
loader.save(fileName, imageData.type);
} catch (SWTException e) {
showErrorDialog(bundle.getString("Saving_lc"), fileName, e);
} catch (SWTError e) {
showErrorDialog(bundle.getString("Saving_lc"), fileName, e);
} finally {
shell.setCursor(null);
imageCanvas.setCursor(crossCursor);
}
} |
46e95dd2-490d-4248-b8df-6b939717be71 | 9 | public void validate() throws XPathException {
checkSortComesFirst(false);
select = typeCheck("select", select);
ExpressionLocation locator = new ExpressionLocation(this);
ExpressionVisitor visitor = makeExpressionVisitor();
if (groupBy != null) {
groupBy = typeCheck("group-by", groupBy);
try {
RoleLocator role =
new RoleLocator(RoleLocator.INSTRUCTION, "xsl:for-each-group/group-by", 0);
//role.setSourceLocator(locator);
groupBy = TypeChecker.staticTypeCheck(groupBy,
SequenceType.ATOMIC_SEQUENCE,
false, role, visitor);
} catch (XPathException err) {
compileError(err);
}
} else if (groupAdjacent != null) {
groupAdjacent = typeCheck("group-adjacent", groupAdjacent);
try {
RoleLocator role =
new RoleLocator(RoleLocator.INSTRUCTION, "xsl:for-each-group/group-adjacent", 0);
//role.setSourceLocator(locator);
role.setErrorCode("XTTE1100");
groupAdjacent = TypeChecker.staticTypeCheck(groupAdjacent,
SequenceType.SINGLE_ATOMIC,
false, role, visitor);
} catch (XPathException err) {
compileError(err);
}
}
starting = typeCheck("starting", starting);
ending = typeCheck("ending", ending);
if (starting != null || ending != null) {
try {
RoleLocator role =
new RoleLocator(RoleLocator.INSTRUCTION, "xsl:for-each-group/select", 0);
//role.setSourceLocator(locator);
role.setErrorCode("XTTE1120");
select = TypeChecker.staticTypeCheck(select,
SequenceType.NODE_SEQUENCE,
false, role, visitor);
} catch (XPathException err) {
String prefix = (starting != null ?
"With group-starting-with attribute: " :
"With group-ending-with attribute: ");
compileError(prefix + err.getMessage(), err.getErrorCodeQName());
}
}
if (!hasChildNodes()) {
compileWarning("An empty xsl:for-each-group instruction has no effect", SaxonErrorCode.SXWN9009);
}
} |
4f445b6b-9c41-4478-bdf9-9177d8395682 | 0 | public static String getPassword() {
return password;
} |
28b98d06-1005-4d7c-82a6-5aa115a7fd82 | 1 | public ListenerManager(LogOre plugin) {
this.plugin = plugin;
this.listeners.put("block", new BlockListener(this.plugin));
for (Listener l : this.listeners.values()) {
this.plugin.getServer().getPluginManager().registerEvents(l, this.plugin);
}
} |
0f9526bb-ee30-45eb-97bb-f2591da46d5f | 4 | public void setSlot(int slot, ItemStack item) {
if (item != null && item.getType() == Material.AIR) {
item = null;
}
if (slot < 0 || slot >= this.items.length) {
return;
}
this.items[slot] = item;
} |
b79aeea5-6acf-4a2e-ba2b-1ddc4ed7f9c0 | 1 | public int compareTo(Object o) {
if (o.getClass() == MmsParameter.class) {
return name.compareTo(((MmsParameter)o).getName());
}
return name.compareTo((String)o);
} |
328d8429-3406-4b11-8d52-d48439968126 | 5 | public boolean canDraw() {
ArrayList<int[]> moves = board.getMoves();
if (moves.size() >= 5) {
int[] currentMove = moves.get(moves.size()-1);
int[] prevMove = moves.get(moves.size()-5);
if (
currentMove[0] == prevMove[0] &&
currentMove[1] == prevMove[1] &&
currentMove[2] == prevMove[2]
) {
return true;
}
}
return moveRule % 50 == 0 && moveRule != 0;
} |
5573963f-3e67-4dcc-9017-5fbf6ef57a97 | 8 | /* */ public Object getMetaPacket(Object watcher)
/* */ {
/* 108 */ Class<?> DataWatcher = Util.getCraftClass("DataWatcher");
/* */
/* 110 */ Class<?> PacketPlayOutEntityMetadata = Util.getCraftClass("PacketPlayOutEntityMetadata");
/* */
/* 112 */ Object packet = null;
/* */ try {
/* 114 */ packet = PacketPlayOutEntityMetadata.getConstructor(new Class[] { Integer.TYPE, DataWatcher, Boolean.TYPE }).newInstance(new Object[] { Integer.valueOf(this.id), watcher, Boolean.valueOf(true) });
/* */ } catch (IllegalArgumentException e) {
/* 116 */ e.printStackTrace();
/* */ } catch (SecurityException e) {
/* 118 */ e.printStackTrace();
/* */ } catch (InstantiationException e) {
/* 120 */ e.printStackTrace();
/* */ } catch (IllegalAccessException e) {
/* 122 */ e.printStackTrace();
/* */ } catch (InvocationTargetException e) {
/* 124 */ e.printStackTrace();
/* */ } catch (NoSuchMethodException e) {
/* 126 */ e.printStackTrace();
/* */ }
/* */
/* 129 */ return packet;
/* */ } |
db265736-6018-4dd4-83aa-3e96e053c0ea | 5 | public void setManager(Manager manager) {
if (manager != this.manager) {
Manager vorigeManager = this.manager;
this.manager = manager;
if (vorigeManager != null && vorigeManager.getCampus() == this) {
vorigeManager.setCampus(null);
}
if (manager != null && manager.getCampus() != this) {
this.manager.setCampus(this);
}
}
} |
4f9652d7-3f66-4e6a-b72b-065520441020 | 8 | public static int[] quickSort(int[] candidates, int start, int end) {
if(start >= end) {
return candidates;
}
int i = start;
int j =end;
int mid = candidates[start];
while(i < j) {
while(j>=start &&candidates[j] > mid) {
j--;
}
if(i>=j) {
break;
}else {
int tmp = candidates[i];
candidates[i] = candidates[j];
candidates[j] = tmp;
}
while( i<=end && candidates[i] < mid) {
i++;
}
if(i>=j) {
break;
}else {
int tmp = candidates[i];
candidates[i] = candidates[j];
candidates[j] = tmp;
}
}
candidates = quickSort(candidates, i+1, end);
candidates = quickSort(candidates, start, i-1);
return candidates;
} |
26c963ab-2c9a-49fc-aa62-085bc8412a4d | 3 | public static void main(String[] args) {
//generateData();
//Feat.Save();
Feat.Load();
if(Feat.getFeats().isEmpty()) {
generateData();
}
Collection<Feat> feats = Feat.getFeats().values();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e ){
e.printStackTrace();
}
Connection c = null;
try {
c = DriverManager.getConnection(
"jdbc:mysql://famalis.no-ip.biz:3306/rpg","Sergio", "quovadis1");
} catch (Exception e) {
e.printStackTrace();
}
} |
ed8a87e6-cc40-4133-ab28-7de3cb3847a6 | 6 | @EventHandler
public void ZombieSlow(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("Zombie.Slow.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getZombieConfig().getBoolean("Zombie.Slow.Enabled", true) && damager instanceof Zombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, plugin.getZombieConfig().getInt("Zombie.Slow.Time"), plugin.getZombieConfig().getInt("Zombie.Slow.Power")));
}
} |
a04a853c-3849-406c-8994-66ae5d697a71 | 3 | public BufferedImage getImage() {
try {
BufferedImage bi = (BufferedImage) imageObj.getCache();
if (bi == null) {
byte[] data = null;
ByteBuffer jpegBytes = null;
final boolean jpegDecode = PDFDecoder.isLastFilter(imageObj, PDFDecoder.DCT_FILTERS);
if (jpegDecode) {
// if we're lucky, the stream will have just the DCT
// filter applied to it, and we'll have a reference to
// an underlying mapped file, so we'll manage to avoid
// a copy of the encoded JPEG bytes
jpegBytes = imageObj.getStreamBuffer(PDFDecoder.DCT_FILTERS);
} else {
data = imageObj.getStream();
}
// parse the stream data into an actual image
bi = parseData(data, jpegBytes);
imageObj.setCache(bi);
}
// if(bi != null)
// ImageIO.write(bi, "png", new File("/tmp/test/" + System.identityHashCode(this) + ".png"));
return bi;
} catch (IOException ioe) {
System.out.println("Error reading image");
ioe.printStackTrace();
return null;
}
} |
302f0b2a-84a4-41c1-ad89-87af1c682056 | 3 | public Car(int bornTime, int dest){
if (bornTime >= 0 && (dest == 1 || dest == 2)) {
this.bornTime = bornTime;
this.dest = dest;
}
else throw new IllegalArgumentException("bornTime >= 0 and dest [1,2]");
} |
f19b8e3b-6750-4dcb-9f4f-5a45fe534d9f | 2 | public void addRoom(Scanner sc) {
long roomID, typeID;
System.out.println("Add a room");
System.out.println("DO you want to add a new type of room or existing type room?");
System.out.println("Enter n/N for new Type and e/E for existing type");
System.out.print("Enter choice: ");
String name = sc.nextLine();
if (name.equalsIgnoreCase("n")) {
System.out.print("Enter room type name: ");
String nameType = sc.nextLine();
System.out.println();
System.out.print("Enter type price: ");
double price = Double.parseDouble(sc.nextLine());
System.out.println();
System.out.print("Enter Maximum number of guest: ");
int numOfGuest = Integer.parseInt(sc.nextLine());
typeID = shsmb.createRoomType(nameType, numOfGuest, price);
System.out.print("Enter room number: ");
int roomNum = Integer.parseInt(sc.nextLine());
System.out.println();
roomID = shsmb.createRoom(roomNum);
System.out.println("created a room");
shsmb.addRoom();
shsmb.persist();
//shsmb.associate(roomID, nameType);
System.out.println("Successfully added a new room");
} else if (name.equalsIgnoreCase("e")) {
System.out.print("Enter room type name: ");
String roomType = sc.nextLine();
System.out.println();
//shsmb.changeRoomType(roomType);
System.out.print("Enter room number: ");
int roomNum = Integer.parseInt(sc.nextLine());
System.out.println();
shsmb.associate(roomNum, roomType);
System.out.println("Successfully added a new room");
}
} |
2fffea7a-e192-41c2-902b-34ea6fd49080 | 2 | @Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
}
String nombrearchivo = pathname.getName().toLowerCase();
if (nombrearchivo.endsWith(extencion)) {
return true;
}
return false;
} |
3765b212-71ae-47da-8a8b-56df019fe05c | 4 | @Override
public int compare(Drillable one, Drillable two) {
if (one.getLastEdited() == null && two.getLastEdited() == null) {
return 0;
}
if (one.getLastEdited() == null) {
return -1;
}
if (two.getLastEdited() == null) {
return 1;
}
return one.getLastEdited().compareTo(two.getLastEdited());
} |
b108113f-8f08-4500-a5ea-7aba70a0dce3 | 9 | @Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Version other = (Version) obj;
if (this == ALL || other == ALL) {
return true;
}
if (major != other.major) {
return false;
}
if (minor != other.minor) {
return false;
}
if (modifier != other.modifier) {
return false;
}
if (revision != other.revision) {
return false;
}
return true;
} |
7956f5a0-dd2d-4a44-811c-121d90f46a8b | 2 | @Override
public void execute() {
System.out.println("Production Dialog is off..... Turning on");
Constants.PRODUCTION_WIDGET.interact("Toggle Production Dialog");
final Timer timeout = new Timer(2000);
while(timeout.isRunning() && Settings.get(1173)==1879048192) {
Task.sleep(50);
}
} |
9d673825-6af6-4f74-8f8e-e3dc860598c3 | 7 | private String logginUser() {
try {
parameterPart = stringParts[1];
udpPort = Integer.parseInt(stringParts[2]);
} catch (ArrayIndexOutOfBoundsException e) {
return answer = "Error: Please enter the log in command like this: !login <Username>";
} catch (NumberFormatException e) {
return answer = "Error: Please enter the log in command like this: !login <Username>";
}
if (user.isOnline()) {
return "Error: You have to log out first!";
}
// login successfully -> throw USER_LOGIN- Event
if ((user = userManagement.logginUser(parameterPart, inetAddress, tcpPort, udpPort)) != null) {
Timestamp logoutTimestamp = new Timestamp(System.currentTimeMillis());
long timestamp = logoutTimestamp.getTime();
try {
mClientHandler.processEvent(new UserEvent(UserEvent.USER_LOGIN, timestamp, parameterPart));
} catch (RemoteException e) {
logger.error("Failed to connect to the Analytics Server");
} catch (WrongEventTypeException e) {
logger.error("Wront type of Event");
} catch (NullPointerException e) {
logger.error("Failed to connect to the Analytics Server");
}
logger.info("User " + parameterPart + " logged in with Port: " + udpPort);
return answer = "Successfully logged in as " + parameterPart;
} else {
user = new User("",false,null,0,0);
return answer = "Error: User is already logged in!";
}
} |
a8fcec61-3091-4ade-858d-703253566b38 | 5 | public boolean wait_event (long timeout_) {
int rc = 0;
try {
if (timeout_ == 0) {
// wait_event(0) is called every read/send of SocketBase
// instant readiness is not strictly required
// On the other hand, we can save lots of system call and increase performance
if (rcursor < wcursor.get()) {
return true;
}
return false;
} else if (timeout_ < 0 ) {
rc = selector.select(0);
} else {
rc = selector.select(timeout_);
}
} catch (IOException e) {
throw new ZError.IOException(e);
}
if (rc == 0) {
return false;
}
selector.selectedKeys().clear();
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.