method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
b3935a72-169e-411b-802e-eaaa4524263c
| 4
|
private List<N> searchConnections(N current, List<N> nodes, List<N> found) {
List<Edge<N>> edges = edgesFrom(current);
for(Edge<N> edge : edges) {
if(nodes.contains(edge.to)) {
nodes.remove(edge.to);
found.add(edge.to);
found = searchConnections(edge.to, nodes, found);
}
}
edges = edgesTo(current);
for(Edge<N> edge : edges) {
if(nodes.contains(edge.from)) {
nodes.remove(edge.from);
found.add(edge.from);
found = searchConnections(edge.from, nodes, found);
}
}
return found;
}
|
bb9d2bf2-f9c6-4904-86e3-4940fcb20923
| 9
|
public void traiter(LigneDeCaisses ligneDeCaisses, Echeancier echeancier) {
nbEssais++;
Evenement e;
Caisse nCaisse;
long d;
if(direction == -1){
nCaisse = ligneDeCaisses.caisseAGaucheDe(caisse.numero());
}else{
nCaisse = ligneDeCaisses.caisseADroiteDe(caisse.numero());
}
if ( ! caisse.estOuverteEtaccepte(client) ) {
// On en essaye une autre:
if(direction == -1){
nCaisse = ligneDeCaisses.caisseAGaucheDe(caisse.numero());
}else{
nCaisse = ligneDeCaisses.caisseADroiteDe(caisse.numero());
}
this.date+=tempsPourChangerDeCaisse;
this.caisse=nCaisse;
echeancier.ajouter(this);
} else if ( nbEssais <= 5 ) {
// On est exigeant et on cherche une caisse vide:
if ( caisse.fileVide() ) {
caisse.ajouter(client);
e = new EvenementFinServiceClient(date + tempsDePaimentCBouMonnaie + tempsPourScannerUnArticle*client.getNbArticles(), client, caisse);
echeancier.ajouter(e);
} else {
if(direction == -1){
nCaisse = ligneDeCaisses.caisseAGaucheDe(caisse.numero());
}else{
nCaisse = ligneDeCaisses.caisseADroiteDe(caisse.numero());
}
this.date+=tempsPourChangerDeCaisse;
this.caisse=nCaisse;
echeancier.ajouter(this);
}
}
else if ( nbEssais <= 10 ) {
// On est moins exigeant et on cherche une caisse pas trop longue:
if ( caisse.longueurFile() <= 2 ) {
caisse.ajouter(client);
e = new EvenementFinServiceClient(date + tempsDePaimentCBouMonnaie + tempsPourScannerUnArticle*client.getNbArticles(), client, caisse);
echeancier.ajouter(e);
} else {
if(direction == -1){
nCaisse = ligneDeCaisses.caisseAGaucheDe(caisse.numero());
}else{
nCaisse = ligneDeCaisses.caisseADroiteDe(caisse.numero());
}
this.date+=tempsPourChangerDeCaisse;
this.caisse=nCaisse;
echeancier.ajouter(this);
}
} else {
// On est encore moins exigeant et on prend tout de suite:
caisse.ajouter(client);
e = new EvenementFinServiceClient(date + tempsDePaimentCBouMonnaie + tempsPourScannerUnArticle*client.getNbArticles(), client, caisse);
echeancier.ajouter(e);
}
}
|
5cd7f282-6b17-4c24-b319-3a81203fc26f
| 0
|
public void setHiddenWithPanel(boolean hiddenWithPanel) {
this.hiddenWithPanel = hiddenWithPanel;
}
|
9b104b56-773b-4c1f-8957-d6726ef11aa4
| 5
|
public void initialise(boolean[][] world) throws PatternFormatException
{
String[] cellParts = cells.split(" ");
for (int i=0;i<cellParts.length;i++)
{
char[] currCells = cellParts[i].toCharArray();
for (int j=0;j<currCells.length;j++)
{
if (currCells[j] != '1' && currCells[j] != '0') throw new PatternFormatException("Error: incorrect format of cell description");
if (currCells[j] == '1') world[i+startRow][j+startCol] = true;
}
}
}
|
d9c6ac12-e62e-4714-8380-d51897b67493
| 8
|
public void fireEnemiesLasers(){
for(Munchkin enemy : munchkins){
if(enemy != null){
if(enemy.getCenterPointX() >= player.posX - player.width / 2 && enemy.getCenterPointX() <= player.posX + player.width){
enemy.shoot(this);
}
}
}
for(UFO enemy : ufos){
if(enemy != null){
if(enemy.getCenterPointX() >= player.posX - player.width / 2 && enemy.getCenterPointX() <= player.posX + player.width){
enemy.shoot(this);
}
}
}
}
|
162fd269-329a-4736-af77-635e191e6fa1
| 2
|
public boolean actualizaEquipo(int id_equipo, int numeroInveInterInfo, int numInvUnam, String descrip,
String modelo, String marca, String serie, String familia, String tipo, String prove, String clase, String uso,
String nivel, String edoFisico, String area, String institu, String fecha, String responsable) {
boolean res = false;
Statement statement;
ResultSet resultSet;
try {
Connection con = DriverManager.getConnection(connectString, user, password);
statement = con.createStatement();
resultSet = statement.executeQuery("SELECT * from actualizaEquipo(" + id_equipo + "," + numeroInveInterInfo + " , "
+ numInvUnam + "," + "'" + descrip + "','" + modelo + "','" + marca + "','" + serie
+ "','" + familia + "','" + tipo + "','" + prove + "','" + clase + "','" + uso + "','" + nivel
+ "','" + edoFisico + "','" + area + "','" + institu + "','" + fecha + "','" + responsable + "');");
while (resultSet.next()) {
res = resultSet.getBoolean(1);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return res;
}
|
7bb9ff7b-4b06-481a-903c-146a7f31c607
| 6
|
protected void printSigners(Class<?> clazz) {
print("clazz.getSigners(): ");
if(clazz.getSigners() == null)
print(clazz.getSigners());
if(clazz.getSigners() != null) {
print();
if(clazz.getSigners().length == 0)
print("none");
if(clazz.getSigners().length > 0) {
for(Object s : clazz.getSigners())
print(s);
}
}
}
|
fcfb63e9-6274-41cf-9792-7daf5e0a02bd
| 3
|
private DefaultTableModel tableCreate(int tempMonths, int currentYear) {
DefaultTableModel table = new DefaultTableModel(new Object[0][0],new String[0][0]);
this.cal = new GregorianCalendar(currentYear, tempMonths - 1, 1);
while (tempMonths == this.cal.get(Calendar.MONTH) + 1) {
String tempKey = this.cal.get(Calendar.YEAR)
+ "/"+ String.format("%02d",(this.cal.get(Calendar.MONTH) + 1))
+ "/"+ String.format("%02d",this.cal.get(Calendar.DAY_OF_MONTH));
if (this.scheduleMap.containsKey(tempKey)) {
int numOfJobs = this.scheduleMap.get(tempKey).size();
String[] colData = new String[numOfJobs];
int i = 0;
for (String key : this.scheduleMap.get(tempKey).keySet()) {
colData[i] = key + ": "+ this.scheduleMap.get(tempKey).get(key).getName();
i++;
}
String numDate = String.format("%02d",(this.cal.get(Calendar.MONTH) + 1))
+ "/"+ String.format("%02d",this.cal.get(Calendar.DAY_OF_MONTH))
+ "/"+ this.cal.get(Calendar.YEAR);
String colTitle = this.getNameforNum(this.cal.get(Calendar.DAY_OF_WEEK)) + " (" + numDate + ")";
table.addColumn(colTitle, colData);
}
this.cal.add(Calendar.DATE, 1);
}
return table;
}
|
9f3900db-d922-4572-bf4e-e77545e4c6c4
| 2
|
public DiceHand(String rawInput, String rollee, int modifier, ArrayList<Die> dice) {
this.dice = dice;
this.modifier = modifier;
this.rollee = rollee;
this.rawInput = rawInput;
this.result = modifier;
for (int i=0; i<dice.size(); i++) {
if (dice.get(i).getSign()) { // positive or negative?
this.result += dice.get(i).getResult();
} else {
this.result -= dice.get(i).getResult();
}
}
}
|
b924315a-45cc-442b-a097-e6d4a5e1037a
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TradeStop other = (TradeStop) obj;
if (orders == null) {
if (other.orders != null)
return false;
} else if (!orders.equals(other.orders))
return false;
if (planet == null) {
if (other.planet != null)
return false;
} else if (!planet.equals(other.planet))
return false;
return true;
}
|
5bbb3396-fa67-493e-b17d-1b425b3bfaaf
| 8
|
@Override
public void run()
{
/*
* refreshing the Audio Panel
*/
sf.audioPanel.removeAll();
sf.studentPanel.removeAll();
sf.studentPanel=new JPanel();
sf.studentPanel.setBackground(Color.WHITE);
if(Integer.parseInt(sf.studentNumberComboBox.getSelectedItem().toString())<5 || Student.studentListAudio.size()<=5)
sf.studentPanel.setLayout(new GridLayout(5,1,10,5));
else
sf.studentPanel.setLayout(new BoxLayout(sf.studentPanel, BoxLayout.Y_AXIS));
for(int i=0;i<Integer.parseInt(sf.studentNumberComboBox.getSelectedItem().toString()) && i<Student.studentListAudio.size();i++)
{
sf.studentPanel.add(sf.createStudentPanel(i,Student.studentListAudio.get(i)));
}
sf.audioPanel.add(new JScrollPane(sf.studentPanel),BorderLayout.CENTER);
sf.audioPanel.setBackground(Color.WHITE);
/*
* refreshing the Text panel
*/
sf.textPanel.removeAll();
sf.studentMsg.removeAll();
sf.studentMsg=new JPanel();
sf.studentMsg.setBackground(Color.WHITE);
if(Integer.parseInt(sf.studentNumberComboBox.getSelectedItem().toString())<5 || Student.studentListText.size()<=5)
{
System.out.println("int the if statement");
sf.studentMsg.setLayout(new GridLayout(5,1,5,5));
}else
sf.studentMsg.setLayout(new BoxLayout(sf.studentMsg, BoxLayout.Y_AXIS));
System.out.println("came to the refreshing thread");
for(int i=0;i<Integer.parseInt(sf.studentNumberComboBox.getSelectedItem().toString()) && i<Student.studentListText.size();i++)
{
sf.studentMsg.add(sf.createStudentTextMsgPanel(i,Student.studentListText.get(i)));
}
sf.textPanel.add(new JScrollPane(sf.studentMsg),BorderLayout.CENTER);
/*
* Now revalidating both the audio and the text panels
*/
sf.audioPanel.revalidate();
sf.textPanel.revalidate();
}
|
fdee6dba-705f-4488-b421-e9f79c62bff0
| 3
|
public static Grammar getUselessProductionlessGrammar(Grammar grammar) {
Grammar g = new ContextFreeGrammar();
g.setStartVariable(grammar.getStartVariable());
if (!getCompleteUsefulVariableSet(grammar).contains(
grammar.getStartVariable()))
return g;
grammar = getTerminalGrammar(grammar);
VariableDependencyGraph graph = getVariableDependencyGraph(grammar);
Set useless = new HashSet(Arrays.asList(getUselessVariables(g, graph)));
Production[] p = grammar.getProductions();
for (int i = 0; i < p.length; i++) {
Set variables = new HashSet(Arrays.asList(p[i].getVariables()));
variables.retainAll(useless);
if (variables.size() > 0)
continue;
g.addProduction(p[i]);
}
return g;
}
|
b705521b-9521-40db-a1cf-2b79a44405ca
| 7
|
public List<Instance> readData() {
ArrayList<Instance> instances = new ArrayList<Instance>();
while (this._scanner.hasNextLine()) {
String line = this._scanner.nextLine();
if (line.trim().length() == 0)
continue;
FeatureVector feature_vector = new FeatureVector();
// Divide the line into features and label.
String[] split_line = line.split(" ");
String label_string = split_line[0];
Label label = null;
if (this._classification) {
int int_label = Integer.parseInt(label_string);
if (int_label != -1) {
label = new ClassificationLabel(int_label);
}
} else {
try {
double double_label = Double.parseDouble(label_string);
label = new RegressionLabel(double_label);
} catch (Exception e) {
}
}
for (int ii = 1; ii < split_line.length; ii++) {
String item = split_line[ii];
String name = item.split(":")[0];
int index = Integer.parseInt(name);
double value = Double.parseDouble(item.split(":")[1]);
if (value != 0)
feature_vector.add(index, value);
}
Instance instance = new Instance(feature_vector, label);
instances.add(instance);
}
return instances;
}
|
e56bbd2e-8a48-448b-bc4b-1cbb91435eb4
| 6
|
public static List search(TagState state, Expression queryRoot) {
int docCount = 0;
int imgCount = 0;
int tagCount = 0;
//TODO Add support for scope
List results = new ArrayList(32);
List docs = state.getDocuments();
for (Iterator docIt = docs.iterator(); docIt.hasNext();) {
docCount++;
DocumentResult docRes = null;
TaggedDocument td = (TaggedDocument) docIt.next();
List images = td.getImages();
for (Iterator imIt = images.iterator(); imIt.hasNext();) {
imgCount++;
boolean imageInResults = false;
TaggedImage ti = (TaggedImage) imIt.next();
List tags = ti.getTags();
for (Iterator tagIt = tags.iterator(); tagIt.hasNext();) {
tagCount++;
String tag = (String) tagIt.next();
if (queryRoot.matches(td, ti, tag)) {
if (docRes == null) {
docRes = new DocumentResult(td, ti);
imageInResults = true;
results.add(docRes);
}
else if (!imageInResults) {
docRes.addImage(ti);
imageInResults = true;
}
}
}
}
}
System.out.println("Searched " + docCount + " documents, " + imgCount + " images, " + tagCount + " tags. Found " + results.size() + " matching documents.");
return results;
}
|
96a7e410-e4c3-465c-85a0-9f463ea324ac
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TypeName other = (TypeName) obj;
if (packageName == null) {
if (other.packageName != null) return false;
} else if (!packageName.equals(other.packageName)) return false;
if (typeSimpleName == null) {
if (other.typeSimpleName != null) return false;
} else if (!typeSimpleName.equals(other.typeSimpleName)) return false;
return true;
}
|
2d08147b-a5e3-4a0b-9e6d-39ccec6fc5a5
| 1
|
public void createQuestion()
{
// Set Values
questionText = QuestionTxt_txtbx.getText();
Answer1Text = Answer1_txtbx.getText();
Answer2Text = Answer2_txtbx.getText();
Answer3Text = Answer3_txtbx.getText();
Answer4Text = Answer4_txtbx.getText();
// Create question
Question q = new Question();
q.AuthorId = 1341131;
q.isRejected = false;
q.questionText = questionText;
q.answers.add(new Answer(Answer1Text, Answer1Correct));
q.answers.add(new Answer(Answer2Text, Answer2Correct));
q.answers.add(new Answer(Answer3Text, Answer3Correct));
q.answers.add(new Answer(Answer4Text, Answer4Correct));
// Update database
int newId = DbAccess.StoreNewQuestion(q);
if (newId > 0)
{
//SUCCESS
q.dbId = newId;
// Message box pop up to say please select correct answer
JOptionPane.showMessageDialog(null,"Your Question has been submitted.",
"Question Submitted",JOptionPane.WARNING_MESSAGE);
// Set Values
QuestionTxt_txtbx.setText("");
Answer1_txtbx.setText("");
Answer2_txtbx.setText("");
Answer3_txtbx.setText("");
Answer4_txtbx.setText("");
Answer1Correct = false;
Answer2Correct = false;
Answer3Correct = false;
Answer4Correct = false;
}
else
{
//FAIL
JOptionPane.showMessageDialog(null,"Unable to add question, please check text fields."
,"Error",JOptionPane.WARNING_MESSAGE);
}
}
|
ee1a1867-9003-49da-b5ad-0fac0aa28b6e
| 1
|
public static Locale findLocale(String filename) {
String regex = "_[a-z]{2}(_[A-Z]{2}){0,1}\\.";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(filename);
if (m.find()) {
String l = m.group(0);
l = l.substring(1, l.length() - 1);
return LocaleUtils.toLocale(l);
}
return null;
}
|
a75fbbe3-de86-477f-b23a-4bb369ebca01
| 1
|
@Test
public void WhenLocalhostReducesPath_ExpectRemovedLevels() throws UnknownHostException {
int refMax = Integer.MAX_VALUE;
Host localhost = new PGridHost("127.0.0.1", 3000);
localhost.setHostPath("0010");
RoutingTable routingTable = new RoutingTable();
routingTable.setLocalhost(localhost);
Host host1 = new PGridHost("127.0.0.1", 1111);
host1.setHostPath("1");
Host host2 = new PGridHost("127.0.0.1", 2222);
host2.setHostPath("01");
Host host3 = new PGridHost("127.0.0.1", 3333);
host3.setHostPath("0000");
Host host4 = new PGridHost("127.0.0.1", 4444);
host4.setHostPath("0001");
Host host5 = new PGridHost("127.0.0.1", 5555);
host5.setHostPath("00110");
Host host6 = new PGridHost("127.0.0.1", 6666);
host6.setHostPath("00111");
routingTable.addReference(0, host1);
routingTable.addReference(1, host2);
routingTable.addReference(2, host3);
routingTable.addReference(2, host4);
routingTable.addReference(3, host5);
routingTable.addReference(3, host6);
localhost.setHostPath("001");
routingTable.refresh(refMax);
int expectedLevels = 3;
int expected0levelSize = 1; // "1"
int expected1levelSize = 1; // "01"
int expected2levelSize = 2; // "000"
Assert.assertTrue(routingTable.levelNumber() == expectedLevels);
Assert.assertTrue(routingTable.getLevel(0).size() == expected0levelSize);
Assert.assertTrue(routingTable.getLevel(1).size() == expected1levelSize);
Assert.assertTrue(routingTable.getLevel(2).size() == expected2levelSize);
Assert.assertTrue(routingTable.getLevel(0).contains(host1));
Assert.assertTrue(routingTable.getLevel(1).contains(host2));
Assert.assertTrue(routingTable.getLevel(2).contains(host3));
Assert.assertTrue(routingTable.getLevel(2).contains(host4));
Assert.assertFalse(routingTable.contains(host5) && routingTable.contains(host6));
}
|
f859742f-ccc0-442e-81b2-1386cbf79790
| 6
|
public static void handlePawnPromotion(int myXCoor, int myYCoor){
int targetRank;
if (userColor.equals("W")){
targetRank = 0;
}
else{
targetRank = 7;
}
if (myYCoor == targetRank){
System.out.println(clearScreen() + "What would you like to promote your pawn to?");
System.out.println("[1] Bishop\n[2] Rook\n[3] Knight\n[4] Queen\n");
System.out.print("Number of your selection: ");
int choice = InputValidator.nextValidInt(scanInt, 1, 4);
switch (choice){
case 1:
board.set(myXCoor, myYCoor, new Bishop(userColor));
break;
case 2:
board.set(myXCoor, myYCoor, new Rook(userColor));
break;
case 3:
board.set(myXCoor, myYCoor, new Knight(userColor));
break;
case 4:
board.set(myXCoor, myYCoor, new Queen(userColor));
break;
default:
break;
}
}
}
|
b0ab6712-00af-4404-9b1b-8fc893067c4c
| 8
|
protected void generateOperationLines(List<AssemblyLine> lines, int op,
Data dest, Data value)
{
switch (op)
{
case Token.ASSIGN:
lines.add(new Instruction(Opcode.SET, dest, value));
break;
case Token.PLUSASSIGN:
case Token.PLUSPLUS:
lines.add(new Instruction(Opcode.ADD, dest, value));
break;
case Token.MINUSASSIGN:
case Token.MINUSMINUS:
lines.add(new Instruction(Opcode.SUB, dest, value));
break;
case Token.TIMESASSIGN:
lines.add(new Instruction(Opcode.MUL, dest, value));
break;
case Token.DIVIDEASSIGN:
lines.add(new Instruction(Opcode.DIV, dest, value));
break;
case Token.MODASSIGN:
lines.add(new Instruction(Opcode.MOD, dest, value));
break;
}
}
|
77fbddd5-b35c-4d30-9218-d0a5388b1d69
| 5
|
@Override
public void stateChanged(ChangeEvent e) {
IntSpinner sp = (IntSpinner) e.getSource();
int dim = sp.getInt();
if (formula == null || dim != formula.length) {
String[] newFormula = new String[dim];
int md = Math.min(formula == null ? 1 : formula.length,
newFormula.length);
for (int i = 0; i < md; i++)
newFormula[i] = formula[i];
for (int i = md; i < newFormula.length; i++)
newFormula[i] = "0";
formula = newFormula;
}
display();
}
|
70ca433e-1317-4362-a4bf-42c7465f3436
| 7
|
public static Cons walkADeclaration(Symbol variable, Stella_Object typetree, Stella_Object value, boolean inputparameterP) {
{ StandardObject sourcetype = null;
StandardObject targettype = Stella_Object.safeYieldTypeSpecifier(typetree);
Surrogate methodownertype = ((((MethodSlot)(Stella.$METHODBEINGWALKED$.get())) != null) ? ((MethodSlot)(Stella.$METHODBEINGWALKED$.get())).slotOwner : ((Surrogate)(null)));
Stella_Object ovalue = null;
if ((targettype != null) &&
((methodownertype != null) &&
(!StandardObject.voidP(methodownertype)))) {
targettype = StandardObject.computeRelativeTypeSpec(targettype, methodownertype);
}
if (!(inputparameterP)) {
Symbol.pushVariableBinding(variable, Stella.SGT_STELLA_UNINITIALIZED);
{ Object [] caller_MV_returnarray = new Object[1];
ovalue = Stella_Object.walkExpressionTree(value, targettype, Stella.SYM_STELLA_VARIABLE_DECLARATION, true, caller_MV_returnarray);
sourcetype = ((StandardObject)(caller_MV_returnarray[0]));
}
if (targettype == null) {
targettype = sourcetype;
}
Stella.popVariableBinding();
}
Symbol.pushVariableBinding(variable, targettype);
if (inputparameterP) {
return (Cons.cons(variable, Cons.cons(targettype, Stella.NIL)));
}
else {
return (Cons.cons(Symbol.trueVariableName(variable), Cons.cons(targettype, Cons.cons(ovalue, Stella.NIL))));
}
}
}
|
96a1d25f-4028-44f5-9992-4264df902eb3
| 6
|
public static int[] lcp(int[] sa) {
int n = sa.length;
int[] rank = new int[n];
for (int i = 0; i < n; i++)
rank[sa[i]] = i;
int[] lcp = new int[n - 1];
for (int i = 0, h = 0; i < n; i++) {
if (rank[i] < n - 1) {
for (int j = sa[rank[i] + 1]; Math.max(i, j) + h < cad.length
&& cad[i + h] == cad[j + h]; ++h)
;
lcp[rank[i]] = h;
if (h > 0)
--h;
}
}
return lcp;
}
|
77957b00-2050-487d-b109-93448abd5d10
| 5
|
public Buffer getReadOnlyData() {
if (bufferData == null) {
return null;
}
// Create a read-only duplicate(). Note: this does not copy
// the underlying memory, it just creates a new read-only wrapper
// with its own buffer position state.
// Unfortunately, this is not 100% straight forward since Buffer
// does not have an asReadOnlyBuffer() method.
Buffer result;
if( bufferData instanceof ByteBuffer ) {
result = ((ByteBuffer)bufferData).asReadOnlyBuffer();
} else if( bufferData instanceof FloatBuffer ) {
result = ((FloatBuffer)bufferData).asReadOnlyBuffer();
} else if( bufferData instanceof ShortBuffer ) {
result = ((ShortBuffer)bufferData).asReadOnlyBuffer();
} else if( bufferData instanceof IntBuffer ) {
result = ((IntBuffer)bufferData).asReadOnlyBuffer();
} else {
throw new UnsupportedOperationException( "Cannot get read-only view of buffer type:" + bufferData );
}
// Make sure the caller gets a consistent view since we may
// have grabbed this buffer while another thread was reading
// the raw data.
result.rewind();
return result;
}
|
483ec96d-343d-4648-a86a-4609ae9ebc1a
| 4
|
public void showBoard() {
for (int i = 0; i < 8; i++) {
if (i == 0) {
System.out.print(" ");
}
System.out.print(" " + this.lettersV[i] + " ");
}
System.out.println("");
for (int i = 0; i < 8; i++) {
System.out.print(this.numberH[i] + " ");
for (int j = 0; j < 8; j++) {
System.out.print(this.bordaCell[i][j].visibleText + " ");
}
System.out.println("");
}
return;
}
|
af76f52d-bd41-44b3-a763-dd283da3e0d1
| 1
|
@Override
public void startServer() {
StartGameController controller = new StartGameController(this, players);
SocketServer server = new SocketServer(1234, new NewConnectionListener(controller));
if (controller.start(server))
controller.bind(new StartGameScreen(mainFrame, controller));
}
|
5dbf8ec5-b709-4412-927b-0d6c2599144a
| 9
|
public Double getElevationFor(Double longitude, Double latitude) throws IOException {
if (elevationFile == null)
return null;
double dElevation;
double dLon = longitude;
double dLat = latitude;
int nLon = (int) dLon; // Cut off the decimal places
int nLat = (int) dLat; // Cut off the decimal places
int nAS = 1200; // 1200 Intervals (means 1201 positions per line and column)
if (dLon < 0) { // If it's west longitude (negative value)
nLon = (nLon - 1) * -1; // Make a positive number (left edge)
dLon = ((double) nLon + dLon) + (double) nLon; // Make positive double longitude (needed for later calculation)
}
if (dLat < 0) { // If it's a south latitude (negative value)
nLat = (nLat - 1) * -1; // Make a positive number (bottom edge)
dLat = ((double) nLat + dLat) + (double) nLat; // Make positive double latitude (needed for later calculation)
}
int nLonIndex = (int) ((dLon - (double) nLon) * nAS); // Calculate the interval index for longitude
int nLatIndex = (int) ((dLat - (double) nLat) * nAS); // Calculate the interval index for latitude
if (nLonIndex >= nAS) {
nLonIndex = nAS - 1;
}
if (nLatIndex >= nAS) {
nLatIndex = nAS - 1;
}
double dOffLon = dLon - (double) nLon; // The lon value offset within a tile
double dOffLat = dLat - (double) nLat; // The lat value offset within a tile
double dLeftTop; // The left top position of a sub tile
double dLeftBottom; // The left bottom position of a sub tile
double dRightTop; // The right top position of a sub tile
double dRightBottom; // The right bootm position of a sub tile
int pos; // The index of the elevation into the hgt file
pos = (((nAS - nLatIndex) - 1) * (nAS + 1)) + nLonIndex; // The index for the left top elevation
elevationFile.seek(pos * 2); // We have 16-bit values for elevation, so multiply by 2
dLeftTop = elevationFile.readShort(); // Now read the left top elevation from hgt file
pos = ((nAS - nLatIndex) * (nAS + 1)) + nLonIndex; // The index for the left bottom elevation
elevationFile.seek(pos * 2); // We have 16-bit values for elevation, so multiply by 2
dLeftBottom = elevationFile.readShort(); // Now read the left bottom elevation from hgt file
pos = (((nAS - nLatIndex) - 1) * (nAS + 1)) + nLonIndex + 1;// The index for the right top elevation
elevationFile.seek(pos * 2); // We have 16-bit values for elevation, so multiply by 2
dRightTop = elevationFile.readShort(); // Now read the right top elevation from hgt file
pos = ((nAS - nLatIndex) * (nAS + 1)) + nLonIndex + 1; // The index for the right bottom elevation
elevationFile.seek(pos * 2); // We have 16-bit values for elevation, so multiply by 2
dRightBottom = elevationFile.readShort(); // Now read the right bottom top elevation from hgt file
if ((dLeftTop < 0) || // If one of the elevation values
(dLeftBottom < 0) || // we read from
(dRightTop < 0) || // the hgt file is
(dRightBottom < 0)) { // not valid
return null; // we can't interpolate
}
double dDeltaLat; // The delta between top lat value and wanted lat (delta within a sub tile)
double dDeltaLon; // The delta between left lon value and wanted lon (delta within a sub tile)
dDeltaLon = dOffLon - (double) nLonIndex * (1.0 / (double) nAS); // The delta (offset) from left point to wanted point
dDeltaLat = dOffLat - (double) nLatIndex * (1.0 / (double) nAS); // The delta (offset) from bottom point to wanted point
double dLonHeightLeft; // The interpolated elevation calculated from left top to left bottom
double dLonHeightRight; // The interpolated elevation calculated from right top to right bottom
dLonHeightLeft = dLeftBottom - calculateElevation(dLeftBottom - dLeftTop, 1.0 / (double) nAS, dDeltaLat);
dLonHeightRight = dRightBottom - calculateElevation(dRightBottom - dRightTop, 1.0 / (double) nAS, dDeltaLat);
// Interpolate between the interpolated left elevation and interpolated right elevation
dElevation = dLonHeightLeft - calculateElevation(dLonHeightLeft - dLonHeightRight, 1.0 / (double) nAS, dDeltaLon);
return dElevation + 0.5; // Do a rounding of the calculated elevation
}
|
cc2b5f55-234e-4c42-9d2a-7ba80e2c38e0
| 4
|
@Override
public void run() {
init();
int frames = 0;
double nsPerFrame = 1000000000.0 / 60.0;
long lastFrameTime = System.nanoTime();
long lastFrame = System.currentTimeMillis();
double unProcessedTime = 0;
running = true;
while(running){
long now = System.nanoTime();
unProcessedTime += (now - lastFrameTime) / nsPerFrame;
lastFrameTime = now;
while(unProcessedTime >= 1){
unProcessedTime -= 1;
tick();
render();
frames++;
}
if(System.currentTimeMillis() >= lastFrame + 1000){
System.out.println("fps: "+ frames);
lastFrame += 1000;
frames = 0;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
swap();
}
destroy();
}
|
a43e3285-2263-468d-a787-692005b6c47e
| 6
|
@EventHandler(ignoreCancelled=true)
public void onPlayerLogin(PlayerLoginEvent event) {
if (event.getPlayer().hasPermission("enhancedfishing.admin")) {
final String playerName = event.getPlayer().getName();
if (updater == null) return;
getServer().getScheduler().runTaskLaterAsynchronously(this, new Runnable() {
public void run() {
Player player = getServer().getPlayer(playerName);
if (player != null && player.isOnline()) {
switch (updater.getResult()) {
case UPDATE_AVAILABLE:
player.sendMessage("An update is available at http://dev.bukkit.org/server-mods/enhancedfishing/");
break;
case SUCCESS:
player.sendMessage("An update has been downloaded and will take effect when the server restarts.");
break;
default:
// nothing
}
}
}
}, random.nextInt(20)+20);
}
}
|
96f57f2b-67a9-4542-a604-28b0189cac5c
| 9
|
private Key decodeKey(
DataInputStream dIn)
throws IOException
{
int keyType = dIn.read();
String format = dIn.readUTF();
String algorithm = dIn.readUTF();
byte[] enc = new byte[dIn.readInt()];
KeySpec spec;
dIn.readFully(enc);
if (format.equals("PKCS#8") || format.equals("PKCS8"))
{
spec = new PKCS8EncodedKeySpec(enc);
}
else if (format.equals("X.509") || format.equals("X509"))
{
spec = new X509EncodedKeySpec(enc);
}
else if (format.equals("RAW"))
{
return new SecretKeySpec(enc, algorithm);
}
else
{
throw new IOException("Key format " + format + " not recognised!");
}
try
{
switch (keyType)
{
case KEY_PRIVATE:
return KeyFactory.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME).generatePrivate(spec);
case KEY_PUBLIC:
return KeyFactory.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME).generatePublic(spec);
case KEY_SECRET:
return SecretKeyFactory.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME).generateSecret(spec);
default:
throw new IOException("Key type " + keyType + " not recognised!");
}
}
catch (Exception e)
{
throw new IOException("Exception creating key: " + e.toString());
}
}
|
f5996d72-6f9c-42e6-99d0-efb2c7e574c8
| 4
|
private void setRegressionArrays(){
this.xRegression = new double[this.numberOfFrequencies];
this.yRegression = new double[2][this.numberOfFrequencies];
if(this.weightsSet)this.wRegression = new double[2][this.numberOfFrequencies];
for(int i=0; i<this.numberOfFrequencies; i++){
xRegression[i] = this.omegas[i];
yRegression[0][i] = this.realZ[i];
yRegression[1][i] = this.imagZ[i];
}
if(this.weightsSet){
for(int i=0; i<this.numberOfFrequencies; i++){
wRegression[0][i] = this.realZweights[i];
wRegression[1][i] = this.imagZweights[i];
}
}
}
|
8a5f2c9b-08d5-4a81-8e8c-2a0c7815b7c0
| 4
|
public void paint(Graphics g) {
if (dir == 0 || dir == 2) {
g.drawImage(image, x, y, 8, 20, gameScreen);
} else if (dir == 1 || dir == 3) {
g.drawImage(image, x, y, 20, 8, gameScreen);
}
}
|
c2a0b4d7-9c86-41b1-a51d-e64a6450bc72
| 0
|
public static void main(String[] args) {
new MicroScope();
}
|
6cd9a10b-1425-4ab1-b441-ca5fbc918690
| 6
|
public Component getListComponentForDataSection(TaskObserver taskObserver, String dataSectionName, List list, Iterator indexIterator) throws InterruptedException
{
if (dataSectionName == DATA_SECTION_UNKNOWN0) { return getGeneralPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_VISIBLE_MAP) { return getVisibleMapPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_FACET_ATTRIBUTES) { return getFacetAttributesPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_SPRITE_ATTRIBUTES) { return getSpriteAttributesPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_MAP_BITS) { return getMapBitsPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_REMAINING_DATA) { return getRemainingDataPanel(taskObserver); }
else return super.getListComponent(dataSectionName, taskObserver, list, indexIterator);
}
|
abb9a073-cc7e-411d-9daa-62d24b770ad0
| 5
|
public void updateStatsDates(User user)
{
String lastDate = (String) this.statsDateModel.getSelectedItem();
this.statsDateModel.removeAllElements();
for(String date : user.getAvalidbleStatsDates(getSelectedMode()))
this.statsDateModel.addElement(date);
this.statsDateModel.addElement(Utils.resourceBundle.getString("last_date_saved"));
if(Utils.config.getBoolean(Configuration.KEEPDATE, false) && lastDate != null && !lastDate.equalsIgnoreCase("") && !lastDate.equalsIgnoreCase("null"))
this.lastStatsDateBox.setSelectedItem(lastDate);
else
this.lastStatsDateBox.setSelectedIndex(this.statsDateModel.getSize() - 1);
}
|
d582842e-d12e-41a5-8bd8-f955b883010b
| 7
|
public Token molDivMod() throws OperazioneNonValidaException, ParentesiParsingException
{
Token x = menoUnario();
if(!(point>text.size()-1))
while(peek().ritornaTipoToken().equals(Tok.MODULO)||peek().ritornaTipoToken().equals(Tok.PER)||peek().ritornaTipoToken().equals(Tok.DIVISO))
{
Token op = peek();
consume();
Token y = menoUnario();
int n1 = (int)x.ritornaValore();
int n2 = (int)y.ritornaValore();
if(op.ritornaTipoToken().equals(Tok.PER)) x = new Intero(n1*n2);
else if(op.ritornaTipoToken().equals(Tok.DIVISO)) x = new Intero(n1/n2);
else x = new Intero(n1%n2);
if(point>text.size()-1) break;
}
return x;
}
|
be7a802d-3ca9-450d-9499-8a023fc10c3e
| 7
|
protected int approxBusyTime(long time)
{
int SECOND = 1;
int MINUTE = 60 * SECOND; // 1 minute = 60 secs
int HOUR = 60 * MINUTE; // 1 hour = 60 minute
int busy = (int) time / MILLI_SEC; // already in seconds
// find one of the type: sec or min or hour
int type = 0;
if (busy < MINUTE) {
type = SECOND;
}
else if (busy < HOUR) {
type = MINUTE;
}
else {
type = HOUR;
}
// then do a loop to find the nearest time interval. Always rounding
// up, e.g. time is 6 minutes, so nearest time would be 10 minutes.
int temp = 0;
int i = 0;
for (i = 0; i < timeArray_.length; i++)
{
temp = timeArray_[i] * type;
if (busy <= temp) {
break;
}
}
// make sure i is not out of range, since array starts at 0
if (i == timeArray_.length) {
i = timeArray_.length - 1;
}
// then find the exact location to determine the correct tag value
// tag[0 ... (TAG_SIZE-1)] = time interval for seconds
if (type == SECOND) {
temp = 0;
}
// tag[TAG_SIZE ... (TAG_SIZE+TAG_SIZE - 1)] = time interval for minutes
else if (type == MINUTE) {
temp = TAG_SIZE;
}
// the rests are for hour intervals
else {
temp = TAG_SIZE + TAG_SIZE;
}
return tagArray_[i + temp];
}
|
675b4156-42a7-4cf3-8af3-715d9d9a205e
| 6
|
public void checkPlaceableDamageAgainstMob(Monster m) {
if (gameController.multiplayerMode != gameController.multiplayerMode.CLIENT) {
Placeable placeable = null;
try {
for (String key : placeables.keySet()) {
placeable = (Placeable) placeables.get(key);
if (placeable.canDestroy()) {
if (placeable.getPerimeter().intersects(m.getPerimeter()) && placeable.isActivated()) {
m.applyDamage(placeable.getTouchDamage(), registry.getPlayerManager().getCurrentPlayer(), true);
}
}
}
} catch (ConcurrentModificationException concEx) {
//another thread was trying to modify placeables while iterating
//we'll continue and the new item can be grabbed on the next update
}
}
}
|
a6baac01-5ecd-4d0c-a335-d09e7caafe4e
| 8
|
public static void quickSort(int[] toBeSorted, int start, int end) {
if (start < end) {
int key = toBeSorted[start];
int i = start, j = end;
while (i < j) {
while (i < j && toBeSorted[j] >= key) {
j--;
}
if (toBeSorted[j] < key) {
int tmp = toBeSorted[j];
toBeSorted[j] = toBeSorted[i];
toBeSorted[i] = tmp;
}
while (i < j && toBeSorted[i] <= key) {
i++;
}
if (toBeSorted[i] > key) {
int tmp = toBeSorted[i];
toBeSorted[i] = toBeSorted[j];
toBeSorted[j] = tmp;
}
quickSort(toBeSorted, 0, i);
quickSort(toBeSorted, i+1, end);
}
}
}
|
611f4aa9-96a6-4686-ac54-f1f77c595d82
| 0
|
public static BeerEntity createBeerWithNameAndDescription(String name, String description) {
BeerEntity entity = new BeerEntity();
entity.setName(name);
entity.setDescription(description);
return entity;
}
|
12ab81fa-cb75-4d01-9334-3293c692953c
| 1
|
public synchronized boolean login(String robot_name, RobotServerHandler handler) {
if (isOnline(robot_name)) {
return false;
}
robots.put(robot_name, new Robot(robot_name, handler));
return true;
}
|
82e6ae3c-cd47-4ce6-987d-a6f0a80b9394
| 1
|
public Builder id(int receivedId) {
if (receivedId < 0) {
log.warn("Wrong ID. receivedId ={}", id);
throw new IllegalArgumentException("Id must be integer value more than 0. Received value =" + receivedId);
}
this.id = receivedId;
return this;
}
|
f1896d13-252a-48fa-a552-6ebe58806444
| 5
|
private static void startFolkRankCreation(BookmarkReader reader, int sampleSize) {
timeString = "";
System.out.println("\nStart FolkRank Calculation for Tags");
frResults = new ArrayList<int[]>();
prResults = new ArrayList<int[]>();
int size = reader.getBookmarks().size();
int trainSize = size - sampleSize;
Stopwatch timer = new Stopwatch();
timer.start();
FactReader factReader = new WikipediaFactReader(reader, trainSize, 3);
FactPreprocessor prep = new FactReaderFactPreprocessor(factReader);
prep.process();
FolkRankData facts = prep.getFolkRankData();
FolkRankParam param = new FolkRankParam();
FolkRankPref pref = new FolkRankPref(new double[] {1.0, 1.0, 1.0});
int usrCounts = facts.getCounts()[1].length;
System.out.println("Users: " + usrCounts);
int resCounts = facts.getCounts()[2].length;
System.out.println("Resources: " + resCounts);
double[][] prefWeights = new double[][]{new double[]{}, new double[]{usrCounts}, new double[]{resCounts}};
FolkRankAlgorithm folk = new FolkRankAlgorithm(param);
timer.stop();
long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
timer = new Stopwatch();
// start FolkRank
for (int i = trainSize; i < size; i++) {
timer.start();
Bookmark data = reader.getBookmarks().get(i);
int u = data.getUserID();
int[] uPrefs = (u < usrCounts ? new int[]{u} : new int[]{});
int r = data.getWikiID();
int[] rPrefs = (r < resCounts ? new int[]{r} : new int[]{});
pref.setPreference(new int[][]{new int[]{}, uPrefs, rPrefs}, prefWeights);
FolkRankResult result = folk.computeFolkRank(facts, pref);
int[] topTags = new int[10];
SortedSet<ItemWithWeight> topKTags = ItemWithWeight.getTopK(facts, result.getWeights(), 10, 0);
int count = 0;
for (ItemWithWeight item : topKTags) {
topTags[count++] = item.getItem();
}
frResults.add(topTags);
timer.stop();
int[] topTagsPr = new int[10];
SortedSet<ItemWithWeight> topKTagsPr = ItemWithWeight.getTopK(facts, result.getAPRWeights(), 10, 0);
count = 0;
for (ItemWithWeight item : topKTagsPr) {
topTagsPr[count++] = item.getItem();
}
prResults.add(topTagsPr);
//System.out.println(u + "|" + data.getTags().toString().replace("[", "").replace("]", "") +
// "|" + Arrays.toString(topTags).replace("[", "").replace("]", "") +
// "|" + Arrays.toString(topTagsPr).replace("[", "").replace("]", ""));
}
long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
timeString += ("Full training time: " + trainingTime + "\n");
timeString += ("Full test time: " + testTime + "\n");
timeString += ("Average test time: " + testTime / (double)sampleSize) + "\n";
timeString += ("Total time: " + (trainingTime + testTime) + "\n");
}
|
fded2302-7a5b-4115-944d-e764a16495d7
| 0
|
private HaveMessage(ByteBuffer buffer, int piece) {
super(Type.HAVE, buffer);
this.piece = piece;
}
|
eb5d0e39-953b-4ddf-b9e3-e19ed26746cf
| 9
|
private static EnviroEffect engage(EnviroEffect result, Ship ship, String argument){
int moveForward = 0;
int moveSide = 0;
double throttle = 1;
if (argument.contains("half-power")){
throttle = .5;
} else if (argument.contains("third-power")){
throttle = .33;
} else if (argument.contains("quarter-power")){
throttle = .25;
}
if (argument.contains("thrusters")){
moveForward = (int) ((ship.enginePower()) * throttle);
ship.input().sendMessage("we are on the move");
} else if (argument.contains("sidekicks") && argument.contains("left")){
moveForward = (int) ((ship.enginePower() / 2) * throttle);
moveSide = (int) ((ship.enginePower() / 2) * throttle);
ship.input().sendMessage("we are on the move");
} else if (argument.contains("sidekicks") && argument.contains("right")){
moveForward = (int) ((ship.enginePower() / 2) * throttle);
moveSide = (int) ((ship.enginePower() / 2) * throttle);
ship.input().sendMessage("we are on the move");
} else if (argument.contains("halters")){
moveForward = (int) (((ship.enginePower() / 2) * -1) * throttle);
ship.input().sendMessage("we are on the move");
}else{
ship.input().sendMessage("What engines do you want to activate?");
}
//int[] coord = Utils.giveMovement(moveForward, moveSide, ship.facing());
int[] coord = Utils.giveMovement(moveSide, moveForward, ship.facing());
ship.addPosX(coord[0]);
ship.addPosY(coord[1]);
return result;
}
|
cb61d6a3-4ecd-4d63-8673-77fc33c01a07
| 0
|
public VenueRemovalInitiated(Venue venue)
{
this.venue = venue;
}
|
d2826d28-0870-4f3e-91f0-41f94d1717c6
| 0
|
private GetQuestionsFromMySqlDatabase getMySQLQuestionsStrategy()
{
return new GetQuestionsFromMySqlDatabase(hostnameTextField.getText(),
databaseNameTextField.getText(), usernameTextField.getText(), passwordTextField.getText());
}
|
244d41dd-d617-443a-96e4-66ef93200bc7
| 8
|
void output(int code, OutputStream outs) throws IOException {
cur_accum &= masks[cur_bits];
if (cur_bits > 0)
cur_accum |= (code << cur_bits);
else
cur_accum = code;
cur_bits += n_bits;
while (cur_bits >= 8) {
char_out((byte) (cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg) {
if (clear_flg) {
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
} else {
++n_bits;
if (n_bits == maxbits)
maxcode = maxmaxcode;
else
maxcode = MAXCODE(n_bits);
}
}
if (code == EOFCode) {
// At EOF, write the rest of the buffer.
while (cur_bits > 0) {
char_out((byte) (cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
flush_char(outs);
}
}
|
f962ba23-184d-4928-b693-6dc2c2987630
| 2
|
public void removeHuff(){
IteratorOnPieces iterator = (IteratorOnPieces) player.iterator();
while (iterator.hasNext()){
iterator.next();
Position position = iterator.getPosition();
if(player.getBoard().getPiece(position).getHuff())
player.getBoard().getPiece(position).setHuff(false);
}
}
|
05ed3891-2e34-490a-970f-f62bd902d821
| 8
|
private int GenerateRepot()
{
//String str = "" + GetHead();
try {
//System.setProperty("file.encoding", "UTF-8");
//Charset.
//FileWriter fw = new FileWriter(Adapter_to_config.getInstance().GetReportFileName());
OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(Adapter_to_config.getInstance().GetReportFileName()), "UTF-8");
//Writer writer = new OutputStreamWriter()
//OutputStreamWriter osw = new OutputStreamWriter()
fw.write(HTMLGenerator.GetHead());
//for(record lr : log_list)
String str = "";
boolean is_print_start = false;
Date begin_print = new Date();
Date end_print = new Date();
double sizeX = 0, sizeY = 0;
String user_name = "" , file_name = "";
Ink_Calculator ink_calculator = new Ink_Calculator(null);
for(int i = 0; i < log_list.size(); i++)
{
Log_record lr = log_list.get(i);
//if(lr.GetStrValue())
//System.out.println(lr.GetDate().toString());
//record_name rn = record_name.print_job_start;
switch (lr.GetName())
{
case print_job_start:
begin_print = lr.GetDate();
sizeX = new Double(lr.GetParamValue("sizeX"));
sizeY = new Double(lr.GetParamValue("sizeY"));
user_name = lr.GetParamValue("user_name");
file_name = lr.GetParamValue("file_name");
is_print_start = true;
ink_calculator = new Ink_Calculator(lr.GetParams());
break;
case print_job_done:
end_print = lr.GetDate();
fw.write(MessageAboutOnePrint(begin_print, end_print, 0, sizeX, sizeY, user_name, file_name, ink_calculator.CalcInkRashod(lr.GetParams())));
is_print_start = false;
break;
case print_job_abort:
is_print_start = false;
end_print = lr.GetDate();
fw.write(MessageAboutOnePrint(begin_print, end_print, 1, sizeX, sizeY, user_name, file_name, ""));
break;
case print_job_pause:
break;
case print_job_continue:
break;
}
//fw.write(HTMLGenerator.GetTableRow(lr.GetDate().toString(), lr.GetType().toString(), lr.GetStrValue()));
}
if(is_print_start)
{
fw.write(MessageAboutOnePrint(begin_print, begin_print, 2, sizeX, sizeY, user_name, file_name, ""));
is_print_start = false;
}
fw.write(HTMLGenerator.GetTail());
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
|
97ee19ab-5f93-40d1-9a6f-c2c2eed39c0e
| 5
|
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Digite o inicio do cpf:");
int cpf = scan.nextInt();
int cpfTemp = cpf;
int d1 = 0, d2 = 0;
for (int i = 9; i >= 1; i--) {
int digit = cpf % 10;
System.out.println(digit);
d1 += digit * i;
cpfTemp -= digit;
cpfTemp /= 10;
}
d1 %= 11;
if (d1 == 10) {
d1 = 0;
}
cpfTemp = cpf;
for (int i = 9; i >= 0; i--) {
if (i == 9) {
d2 += d1 * i;
} else {
int digit = cpf % 10;
System.out.println(digit);
d2 += digit * i;
cpfTemp -= digit;
cpfTemp /= 10;
}
}
d2 %=11;
if (d2 == 10) {
d2 = 0;
}
System.out.println(d1);
System.out.println(d2);
}
|
392e87ed-dfc2-4df7-b8d1-ee8bf722cd0a
| 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(MultiTab.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MultiTab.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MultiTab.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MultiTab.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 MultiTab().setVisible(true);
}
});
}
|
1b5479da-2070-4b86-8c12-c75aca2a7601
| 9
|
public static String whoCheck(TelnetService TN) throws InterruptedException, IOException{
String rtn="";
TN.write("sys list users");
String line=TN.readit("There are", "skjafhdkhfaldsfh");
String[] b=line.split("\n");
for (String value:b){
if (!value.trim().startsWith(">sys list")&&!value.trim().startsWith("Userid")&&!value.trim().startsWith("There are")&&!value.trim().startsWith("=-=-=-")){
value=value.replace("", "").trim();
while (value.contains(" ")){
value=value.replaceAll(" ", " ");
}
String[] v=value.split(" ");
if (v.length>2&&!v[1].equals(GosLink2.prps("muser2"))){rtn=rtn+","+v[1];}
}
}
if (rtn.startsWith(",")){rtn=rtn.substring(1);}
return rtn;
}
|
42c9c63e-596b-4f56-acad-6c1079e735a0
| 4
|
public static void writeToFile(File dest, InputStream input) {
if(dest != null && dest.exists() && dest.isFile() && input != null) {
} else {
throw new IllegalArgumentException();
}
}
|
8a1890af-653f-4fbb-87ad-962646356c5a
| 1
|
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num1 = Integer.parseInt(in.next());
double num2 = Integer.parseInt(in.next());
if (num2 == 0) {
System.out.println("Error: divide by zero!");
} else {
System.out.println(num1 / num2);
}
}
|
ebc56943-7693-4783-a8bf-7b4b1f76df72
| 4
|
protected boolean out_grouping(char [] s, int min, int max)
{
if (cursor >= limit) return false;
char ch = current.charAt(cursor);
if (ch > max || ch < min) {
cursor++;
return true;
}
ch -= min;
if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) {
cursor ++;
return true;
}
return false;
}
|
103841df-fc2d-4581-96d8-e81f6ca3d79c
| 0
|
public void addText( String txt ) {
taskOutput.setText( taskOutput.getText() + txt + "\n" );
scrollTask.getVerticalScrollBar().setValue(scrollTask.getVerticalScrollBar().getMaximum());
}
|
f3a94d89-274e-46e7-a229-881124666a9c
| 2
|
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// System.out.println("Starting element: " + qName + "...");
if(stack.peek().equals("tracks")) {
if(qName.equals("dict")) {
stack.push("newSong");
currentSong = new Song();
}
}
}
|
61b998a1-ef2c-4f71-b370-28fa044def8a
| 9
|
private Location findTarget2(Location location) {
List<Location> adjacent = getField().adjacentLocations(location);
Iterator<Location> it = adjacent.iterator();
while (it.hasNext()) {
Location where = it.next();
Object character = getField().getObjectAt(where);
if(weapon == null){
haveWeapon = false;
}
else{
if ((character instanceof Vampire) &&
(weapon.GetTypeTarget()==1)) {
Vampire v = (Vampire) character;
if (v.getAlive()) {
weapon.attackWeap(this,v);
}
}
if ((character instanceof Zombie) &&
((weapon.GetTypeTarget()==2)||(weapon.GetTypeTarget()==3))) {
Zombie z = (Zombie) character;
if (z.getAlive()) {
weapon.attackWeap(this,z);
}
}
}
}
return null;
}
|
3855f4f4-04d9-42b6-a459-16ac7cc0d134
| 6
|
protected boolean AnalyzeDocByStn(_Doc doc, String[] sentences) {
TokenizeResult result;
int y = doc.getYLabel(), index = 0;
HashMap<Integer, Double> spVct = new HashMap<Integer, Double>(); // Collect the index and counts of features.
ArrayList<_Stn> stnList = new ArrayList<_Stn>(); // sparse sentence feature vectors
double stopwordCnt = 0, rawCnt = 0;
for(String sentence : sentences) {
result = TokenizerNormalizeStemmer(sentence);// Three-step analysis.
HashMap<Integer, Double> sentence_vector = constructSpVct(result.getTokens(), y, spVct);// construct bag-of-word vector based on normalized tokens
if (sentence_vector.size()>2) {//avoid empty sentence
String[] posTags;
if(m_tagger==null)
posTags = null;
else
posTags = m_tagger.tag(result.getRawTokens());
stnList.add(new _Stn(index, Utils.createSpVct(sentence_vector), result.getRawTokens(), posTags, sentence));
Utils.mergeVectors(sentence_vector, spVct);
stopwordCnt += result.getStopwordCnt();
rawCnt += result.getRawCnt();
}
index ++;
} // End For loop for sentence
//the document should be long enough
if (spVct.size()>=m_lengthThreshold && stnList.size()>=m_stnSizeThreshold) {
doc.createSpVct(spVct);
doc.setStopwordProportion(stopwordCnt/rawCnt);
doc.setSentences(stnList);
m_corpus.addDoc(doc);
m_classMemberNo[y] ++;
if (m_releaseContent)
doc.clearSource();
return true;
} else {
/****Roll back here!!******/
rollBack(spVct, y);
return false;
}
}
|
1f968624-4588-45e4-a068-3cac9afe365b
| 0
|
protected void execute() {}
|
d0fd60f7-8715-4e82-bdb9-463285924eef
| 5
|
private void nameCmbxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameCmbxActionPerformed
tableModel.setRowCount(0);
String name = "";
if (nameCmbx.getSelectedItem() != null && nameCmbx.getSelectedIndex() != 0) {
name = nameCmbx.getSelectedItem().toString();
try {
Student student = controller.searchStudentByName(name);
addTxt.setText(student.getAddress());
phoneTxt.setText(student.getMobileNumber());
genderTxt.setText(student.isMale()? "Male" : "Female");
gurdNameTxt.setText(student.getGuardianName());
guardPhnTxt.setText(student.getGuardianNumber());
guardPhnTxt.setText(student.getGuardianNumber());
idCmbx.setSelectedItem(student.getStudentID());
imgLbl.setIcon(student.getImage());
ResultSet rst = controller.getClassDetailsByName(nameCmbx.getSelectedItem().toString());
while(rst.next()){
tableModel.addRow(new String[] {rst.getString(1), rst.getString(2), rst.getString(3), rst.getString(4)});
}
} catch (SQLException ex) {
}
}
}//GEN-LAST:event_nameCmbxActionPerformed
|
624644b4-5f1e-4f61-95a1-454074c1f5ef
| 8
|
private void setLeaf() throws Exception {
//this will fill the ranges array with the number of times
//each class type occurs for the instances.
//System.out.println("ihere");
if (m_training != null ) {
if (m_training.classAttribute().isNominal()) {
FastVector tmp;
//System.out.println("ehlpe");
m_ranges = new FastVector(1);
m_ranges.addElement(new FastVector(m_training.numClasses() + 1));
tmp = (FastVector)m_ranges.elementAt(0);
tmp.addElement(new Double(0));
for (int noa = 0; noa < m_training.numClasses(); noa++) {
tmp.addElement(new Double(0));
}
for (int noa = 0; noa < m_training.numInstances(); noa++) {
tmp.setElementAt(new Double(((Double)tmp.elementAt
((int)m_training.instance(noa).
classValue() + 1)).doubleValue() +
m_training.instance(noa).weight()),
(int)m_training.instance(noa).classValue() + 1);
//this gets the current class val and alters it and replaces it
}
}
else {
//then calc the standard deviation.
m_ranges = new FastVector(1);
double t1 = 0;
for (int noa = 0; noa < m_training.numInstances(); noa++) {
t1 += m_training.instance(noa).classValue();
}
if (m_training.numInstances() != 0) {
t1 /= m_training.numInstances();
}
double t2 = 0;
for (int noa = 0; noa < m_training.numInstances(); noa++) {
t2 += Math.pow(m_training.instance(noa).classValue() - t1, 2);
}
FastVector tmp;
if (m_training.numInstances() != 0) {
t1 = Math.sqrt(t2 / m_training.numInstances());
m_ranges.addElement(new FastVector(2));
tmp = (FastVector)m_ranges.elementAt(0);
tmp.addElement(new Double(0));
tmp.addElement(new Double(t1));
}
else {
m_ranges.addElement(new FastVector(2));
tmp = (FastVector)m_ranges.elementAt(0);
tmp.addElement(new Double(0));
tmp.addElement(new Double(Double.NaN));
}
}
}
}
|
b7657261-0744-4512-af95-a2867263d174
| 2
|
public int compare(final Object o1, final Object o2) {
Assert.isTrue(o1 instanceof Type, o1 + " is not a Type");
Assert.isTrue(o2 instanceof Type, o2 + " is not a Type");
final Type t1 = (Type) o1;
final Type t2 = (Type) o2;
TypeComparator.db("Comparing " + t1 + " to " + t2);
final ClassHierarchy hier = context.getHierarchy();
if (hier.subclassOf(t1, t2)) {
TypeComparator.db(" " + t1 + " is a subclass of " + t2);
return (-1);
} else if (hier.subclassOf(t2, t1)) {
TypeComparator.db(" " + t2 + " is a subclass of " + t1);
return (1);
} else {
TypeComparator.db(" " + t1 + " and " + t2 + " are unrelated");
// Don't return 0. If you do, the type will not get included in
// the sorted set. Weird.
return (1);
}
}
|
759f80ca-6e99-47ef-bf6a-0eafa65330cc
| 6
|
@EventHandler
public void EndermanFireResistance(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.getEndermanConfig().getDouble("Enderman.FireResistance.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}dodged = true;
if (plugin.getEndermanConfig().getBoolean("Enderman.FireResistance.Enabled", true) && damager instanceof Enderman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, plugin.getEndermanConfig().getInt("Enderman.FireResistance.Time"), plugin.getEndermanConfig().getInt("Enderman.FireResistance.Power")));
}
}
|
9df510de-e580-4593-ae9e-1f98d6d11f15
| 3
|
public static void mouseToggle(MouseEvent e, boolean toggle)
{
if(e.getButton() == MouseEvent.BUTTON1) //left click
Main.isMouseLeft = toggle;
else if(e.getButton() == MouseEvent.BUTTON2) //middle click
Main.isMouseMiddle = toggle;
else if(e.getButton() == MouseEvent.BUTTON3) //right click
Main.isMouseRight = toggle;
}
|
48d63158-4056-47ed-ac9e-840b9a4370f1
| 1
|
public void show(FindReplaceResultsModel model) {
// Lazy Instantiation
if (!initialized) {
initialize();
initialized = true;
}
this.model = model;
model.setView(this);
// Setup the JTable
table.setModel(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
TableColumn column = null;
// Document column
column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(220);
// Line column
column = table.getColumnModel().getColumn(1);
column.setPreferredWidth(35);
column.setMaxWidth(60);
// Column column
column = table.getColumnModel().getColumn(2);
column.setPreferredWidth(35);
column.setMaxWidth(45);
// Match column
column = table.getColumnModel().getColumn(3);
column.setPreferredWidth(55);
// Replacement column
column = table.getColumnModel().getColumn(4);
column.setPreferredWidth(95);
updateTotalMatches();
show();
SwingUtilities.invokeLater(new Runnable(){@Override
public void run(){Outliner.outliner.requestFocus();}});
}
|
9e08ccb5-6cde-472a-adcd-31e890b902f4
| 0
|
public TaskQueueStatistics(TaskAcceptor<T> taskAcceptor, TaskSupplier<T> taskSupplier) {
this.taskAcceptor = taskAcceptor;
this.taskSupplier = taskSupplier;
}
|
6b63fd56-40e2-4d0a-b1d6-f3fd9723426b
| 0
|
public void setCounter(LongDataType value) {
this.counter = value;
}
|
38a99eea-d408-45a1-8e5c-8ddc87b81d68
| 4
|
public
<T extends Data> void addDataToEntity( long someEntityId, T someData )
throws EntityAlreadHasDataException, NoSuchEntityException {
//local vars
DataCore db = _dataCenter.getDataCore();
Map<Class<? extends Data>, Data> entityData = db.getEntity_Data_Table().get( someEntityId );
//check whether there is no entry, there is no entity with the given id
if( entityData == null ) {
//if so throw an exception
throw new NoSuchEntityException( someEntityId );
}
//check whether this entity already holds data of this type
if( entityData.containsKey( someData.getClass() ) ) {
//if so throw an exception
throw new EntityAlreadHasDataException( someData.getClass(), someEntityId );
}
//store the data in the storage for this entity
entityData.put( someData.getClass(), someData );
//if this type of data hasnt been used before
if( db.getData_Entity_Table().get( someData.getClass() ) == null ) {
//create a new entry for it
db.getData_Entity_Table().put( someData.getClass(), new TLongArrayList() );
}
//add this entity to the list of entities that use this type of data
db.getData_Entity_Table().get( someData.getClass() ).add( someEntityId );
}
|
4dd47d53-07e0-4cd3-8a09-702ee00f3177
| 8
|
private void accumulate(ArcState state, double value) throws IOException {
if (Double.isNaN(value)) {
state.setNanSteps(state.getNanSteps() + 1);
} else {
switch (ConsolFun.valueOf(consolFun.get())) {
case MIN:
state.setAccumValue(Util.min(state.getAccumValue(), value));
break;
case MAX:
state.setAccumValue(Util.max(state.getAccumValue(), value));
break;
case FIRST:
if (Double.isNaN(state.getAccumValue())) {
state.setAccumValue(value);
}
break;
case LAST:
state.setAccumValue(value);
break;
case AVERAGE:
case TOTAL:
state.setAccumValue(Util.sum(state.getAccumValue(), value));
break;
}
}
}
|
fffced01-d324-4fe3-a958-e2e902c83a74
| 3
|
public boolean execute() {
// If the input is invalid, don't bother with processing
if(variables.errorFlag) {return false;}
// Initialize Variables
int aNot=1;
variables.coeff2=1;
variables.coeff1=0;
int bNot=0;
int c=variables.input1;
variables.gcd=variables.input2;
// Main loop
while(true) {
// Is remainder zero?
int r = c%variables.gcd;
if(r==0) {return true;}
int q = c/variables.gcd;
c=variables.gcd;
variables.gcd=r;
int t = aNot;
aNot = variables.coeff1;
variables.coeff1 = t-q*variables.coeff1;
t = bNot;
bNot = variables.coeff2;
variables.coeff2 = t-q*variables.coeff2;
}
}
|
2c6ea1bf-ca30-465c-a2f3-70b9a5d3282d
| 2
|
public void ajustmentWeigth() {
//errors and weigth adjustment for output layer
for (int i = 0; i < outNodes.size(); i++) {
outNodes.get(i).ajErrorOutputNode();
}
Set<Node> doneNodes = new HashSet<Node>();
doneNodes.addAll(outNodes);
//errors and weigth adjustment for hidden layers
for (int i = hiddenNodes.size() - 1; i >= 0; i--) {
calculateMisalignmentWeigth(hiddenNodes.get(i), doneNodes);
}
}
|
bfe7c023-916a-43e6-b31a-460c68a0502c
| 8
|
@Override
public void render(Graphics2D g2d, int width, int height) {
drawBackground(g2d, width, height);
Font f = Client.instance.translation.font.deriveFont(Font.BOLD, 80F);
g2d.setFont(f);
String title = Client.instance.translation.translate("gui.options" + (section != Section.MAIN ? "." + section.name().toLowerCase() : ""));
Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(title, g2d);
int titleX = (int) (width / 2 - bounds.getCenterX());
int titleY = (int) (80 + bounds.getMaxY());
g2d.setColor(Color.WHITE);
g2d.drawString(title, titleX, titleY);
int buttonWidth = width - width / 4;
int buttonHeight = height / 10;
int buttonSpacing = buttonHeight / 4;
int topMargin = 150;
int leftMargin = width / 2 - buttonWidth / 2;
int buttonWidthSmall = (buttonWidth - buttonSpacing) / 2;
backButton.setX(leftMargin);
backButton.setY(height - buttonSpacing - buttonHeight);
backButton.setWidth(buttonWidth);
backButton.setHeight(buttonHeight);
if (section == Section.MAIN) {
videoButton.setX(leftMargin);
videoButton.setY(topMargin);
videoButton.setWidth(buttonWidthSmall);
videoButton.setHeight(buttonHeight);
languageButton.setX(leftMargin + buttonWidthSmall + buttonSpacing);
languageButton.setY(topMargin);
languageButton.setWidth(buttonWidthSmall);
languageButton.setHeight(buttonHeight);
gameButton.setX(leftMargin);
gameButton.setY(topMargin + buttonHeight + buttonSpacing);
gameButton.setWidth(buttonWidthSmall);
gameButton.setHeight(buttonHeight);
} else if (section == Section.VIDEO) {
videoVsyncButton.setX(leftMargin);
videoVsyncButton.setY(topMargin);
videoVsyncButton.setWidth(buttonWidthSmall);
videoVsyncButton.setHeight(buttonHeight);
videoFullscreenButton.setX(leftMargin + buttonWidthSmall + buttonSpacing);
videoFullscreenButton.setY(topMargin);
videoFullscreenButton.setWidth(buttonWidthSmall);
videoFullscreenButton.setHeight(buttonHeight);
} else if (section == Section.LANGUAGE) {
int i = 0;
for (GuiButton b : languageButtons) {
b.setX(leftMargin);
b.setY(topMargin + (i++) * (buttonHeight + buttonSpacing));
b.setWidth(buttonWidth);
b.setHeight(buttonHeight);
}
} else if (section == Section.GAME) {
gameArrowButton.setX(leftMargin);
gameArrowButton.setY(topMargin);
gameArrowButton.setWidth(buttonWidthSmall);
gameArrowButton.setHeight(buttonHeight);
gameZoomButton.setX(leftMargin + buttonWidthSmall + buttonSpacing);
gameZoomButton.setY(topMargin);
gameZoomButton.setWidth(buttonWidthSmall);
gameZoomButton.setHeight(buttonHeight);
} else if (section == Section.ARROWS) {
int i = 0;
for (GuiButton b : arrowButtons) {
b.setX((int) (width / 2 - buttonHeight * 2 - buttonSpacing * 7.5 + (i % 4) * (buttonHeight + buttonSpacing * 5)));
b.setY(topMargin + (i / 4) * (buttonHeight + buttonSpacing * 5));
b.setWidth(buttonHeight);
b.setHeight(buttonHeight);
i++;
}
}
super.render(g2d, width, height);
}
|
92e13a41-5658-4d43-886b-95aaa40afee9
| 4
|
public static void main(String[] args)
{
SeparateChainingHashST<String, Integer> st = new SeparateChainingHashST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++)
{
String key = StdIn.readString();
st.put(key, i);
}
// print keys
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
for (String s : st.keys())
st.delete(s);
if (st.isEmpty())
System.out.println("Successfully deleted all items");
else
System.out.println("Unsuccessful in deleting all items");
}
|
8f475e30-8bf2-4d01-af0d-84389fdb398e
| 2
|
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append(this.getClass().getSimpleName());
sb.append("[" + id + "]: ");
for(int i = 0; i < arguments.size(); i++){
if(i > 0){
sb.append(", ");
}
sb.append(arguments.get(i));
}
return sb.toString();
}
|
3225bfda-aa43-493f-a889-13a7b1f83238
| 8
|
public static void start() {
isRunning = true;
status = Constant.MAIN;
window = new MainWindow();
windowThread = new Thread(window);
winSize = window.getWinSize();
player = new Player(0, 0);
map = new TestMap();
personList = map.getPersonList();
worldList = map.getWorldList();
windowThread.start();
scheduler = Executors.newScheduledThreadPool(1);
Runnable run = new Runnable() {
@Override
public void run() {
prevFrameStart = curFrameStart;
curFrameStart = System.nanoTime();
prevTickLength = curFrameStart - prevFrameStart;
Controller.processKeys();
// for (int a = 0; a < 4; a++) {
// System.out.print(player.getCanMove()[a] + ", ");
// }
// System.out.println();
if (status.compareTo(Constant.PLAY) == 0) {
for (Person i : personList) {
i.update();
if (i != player && sphereCollide(player, i)) {
i.setAlive(Constant.DEAD);
}
if (i.getAlive() == Constant.DEAD) {
personList.remove(i);
}
}
player.setCanMove(true);
for (WorldObject i : worldList) {
if (sphereCollide(player, i)) {
player.setCanMove(getDirCode(i), false);
}
}
}
tickCount++;
timeElapse += prevTickLength;
if (tickCount % (tickTarget / 2) == 0) {
ups = (int) (1_000_000_000 * ((double) tickCount / timeElapse));
tickCount = 0;
timeElapse = 0;
}
}
};
prevFrameStart = 0;
curFrameStart = System.nanoTime();
scheduler.scheduleAtFixedRate(run, 0, tickTarget, TimeUnit.MILLISECONDS);
}
|
f1041eb4-be6a-4353-b62c-997a41bbae24
| 0
|
@Override
public String toString() {
return "Move from " + getStart() + " to " + getDestination();
}
|
7bcf888c-3ad0-4de8-a71f-01ffcb1dea5e
| 3
|
public <T> T createBean(Class<T> iface) {
try {
Class<? extends T> impl = (Class<? extends T>) registry.get(iface);
BeanInvocationHandler handler = new BeanInvocationHandler(impl.newInstance(), interceptors);
T newProxyInstance = (T) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[] {iface},
handler);
return newProxyInstance;
} catch (Exception e) {
throw new ContainerException(e.getMessage());
}
}
|
16c42aca-1100-451d-b510-d21b7a3ad72c
| 5
|
@Override
public void run() {
while (Check.keepPinging) {
Check.attempts += 1;
try {
pingSum = (int) (pingSum + Check.ping());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Check.setMediaPing(pingSum / Check.attempts);
if (times > 0 && Check.attempts == times){
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
c87556c7-5b88-4082-ba1f-e8167d76105c
| 9
|
Page readPageData(RandomAccessFile raf) throws IOException {
PageId pid;
Page newPage = null;
String pageClassName = raf.readUTF();
String idClassName = raf.readUTF();
try {
Class<?> idClass = Class.forName(idClassName);
Class<?> pageClass = Class.forName(pageClassName);
Constructor<?>[] idConsts = idClass.getDeclaredConstructors();
int numIdArgs = raf.readInt();
Object idArgs[] = new Object[numIdArgs];
for (int i = 0; i<numIdArgs;i++) {
idArgs[i] = new Integer(raf.readInt());
}
pid = (PageId)idConsts[0].newInstance(idArgs);
Constructor<?>[] pageConsts = pageClass.getDeclaredConstructors();
int pageSize = raf.readInt();
byte[] pageData = new byte[pageSize];
raf.read(pageData); //read before image
Object[] pageArgs = new Object[2];
pageArgs[0] = pid;
pageArgs[1] = pageData;
newPage = (Page)pageConsts[0].newInstance(pageArgs);
// Debug.log("READ PAGE OF TYPE " + pageClassName + ", table = " + newPage.getId().getTableId() + ", page = " + newPage.getId().pageno());
} catch (ClassNotFoundException e){
e.printStackTrace();
throw new IOException();
} catch (InstantiationException e) {
e.printStackTrace();
throw new IOException();
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IOException();
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IOException();
}
return newPage;
}
|
fa63876d-de31-40e8-b0c6-ef618f24a997
| 6
|
private int createInt2CFromBinaryString(String s, int nbBits){
int ret = 0;
boolean isNegative = (s.length() == nbBits && s.charAt(0) == '1') ? true : false;
for(int i = 32; i > s.length(); i--){
ret <<= 1;
ret |= (isNegative) ? 1 : 0;
}
for(int i = 0; i < s.length(); i++){
ret <<= 1;
ret |= (s.charAt(i) == '1') ? 1 : 0;
}
return ret;
}
|
929d5520-7b5d-4dfb-b68c-c7c375e6e5e0
| 5
|
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char grade = in.next().charAt(0);
switch (grade) {
case 'A':
System.out.println("Excellent");
case 'B':
System.out.println("Good");
case 'C':
System.out.println("So so");
case 'D':
System.out.println("Fails");
case 'F':
System.out.println("Get lost");
default:
System.out.println("Invalid");
}
}
|
7abd19c4-ccdc-4157-90c1-13d6c3d345bd
| 8
|
private Matrix swapLines(Matrix matrix, int row1, int row2) {
Matrix result = new Matrix(matrix.getRows(), matrix.getColumns());
for (int x = 0; x < matrix.getRows(); x++) {
if (x == row1) {
for (int y = 0; y < matrix.getColumns(); y++) {
result.setElement(row1, y, matrix.getElement(row2, y));
}
}
if (x == row2) {
for (int y = 0; y < matrix.getColumns(); y++) {
result.setElement(row2, y, matrix.getElement(row1, y));
}
}
if (x != row1 && x != row2) {
for (int y = 0; y < matrix.getColumns(); y++) {
result.setElement(x, y, matrix.getElement(x, y));
}
}
}
return result;
}
|
5f1a6b76-7fa0-4732-8af3-fb09be35a586
| 3
|
public void insertMatchRecord() {
PreparedStatement st = null;
ResultSet rs = null;
String q = "INSERT INTO match_record_2013 SET " +
"user = ?, team_id = ?, event_id = ?, match_number = ?, color = ?, " +
"auton_top = ?, auton_middle = ?, auton_bottom = ?, " +
"teleop_top = ?, teleop_middle = ?, teleop_bottom = ?, " +
"teleop_pyramid = ?, pyramid_level = ?, play_style = ?, " +
"confidence = ?, ability = ?, fouls = ?, " +
"technical_fouls = ?, comments = ?, path = ?;";
try {
conn = dbconn.getConnection();
st = conn.prepareStatement(q, PreparedStatement.RETURN_GENERATED_KEYS);
st.setString(1, this.user);
st.setInt(2, this.teamId);
st.setInt(3, this.eventId);
st.setInt(4, this.matchId);
st.setString(5, this.color);
st.setInt(6, this.autonTop);
st.setInt(7, this.autonMiddle);
st.setInt(8, this.autonBottom);
st.setInt(9, this.teleopTop);
st.setInt(10, this.teleopMiddle);
st.setInt(11, this.teleopBottom);
st.setInt(12, this.teleopPyramid);
st.setInt(13, this.pyramidLevel);
st.setString(14, this.playStyle);
st.setInt(15, this.confidence);
st.setInt(16, this.ability);
st.setBoolean(17, this.fouls);
st.setBoolean(18, this.technicalFouls);
st.setString(19, this.comments);
st.setString(20, this.path); // TODO path
st.executeUpdate();
rs = st.getGeneratedKeys();
if (rs.next()) {
setId(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("Unable to close connection");
}
}
}
|
1a5451bc-9cfc-40aa-a046-52c66404b534
| 0
|
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
HelloBean helloBean = (HelloBean) context.getBean("helloBean");
log.debug(helloBean.toString());
}
|
a1c644e8-0e7e-4314-bf5d-5aa7db5033ff
| 5
|
private BencNode readUnknownTypeNode() {
if (pos >= data.length) {
throw unexpectedEnd();
}
if (data[pos] == 'i') {
return readIntNode();
} else if (data[pos] == 'l') {
return readListNode();
} else if (data[pos] == 'd') {
return readDictNode();
} else if (Character.isDigit(data[pos])) {
return readBytesNode();
} else {
throw new ParseException(String.format("Unknown type prefix %02h at pos %d", data[pos], pos));
}
}
|
e08cc896-8be5-4fb9-8dc9-062333de91c6
| 5
|
public static char five(int r, int c, int f) {
if (s1(r, c, f) || s4(r, c, f))
return '|';
else if (s3(r, c, f) || s6(r, c, f) || s7(r, c, f))
return '_';
return '.';
}
|
6850824f-4d1e-48db-a45d-a70aa6f525c4
| 0
|
public ArrayList <Production> getTrace()
{
myAnswerProductions=new ArrayList <Production>();
myOrderComparator=new OrderCorrectly();
// System.out.println("WHOLE MAP = "+myMap);
getMoreProductions(START_VARIABLE, "0,"+(myTargetLength-1));
// System.out.println(myAnswerProductions);
return myAnswerProductions;
}
|
c605e254-26e5-4182-b541-1048fbe74e01
| 4
|
public void run()
{
try
{
this.ssck = new ServerSocket();
this.ssck.bind
(
new InetSocketAddress
(
EzimNetwork.localAddress
, EzimNetwork.localDtxPort
)
);
this.loop();
}
catch(Exception e)
{
EzimLogger.getInstance().severe(e.getMessage(), e);
EzimMain.showError(EzimLang.DtxPort + "\n" + e.getMessage());
EzimMain.getInstance().panic(1);
}
finally
{
try
{
if (this.ssck != null && ! this.ssck.isClosed())
this.ssck.close();
}
catch(Exception exp)
{
EzimLogger.getInstance().severe(exp.getMessage(), exp);
}
}
}
|
a3b00920-d7ee-4888-b211-550354b74db8
| 9
|
*/
public static void setPowerloomFeature(Keyword feature) {
if (!(Logic.$CURRENT_POWERLOOM_FEATURES$.memberP(feature))) {
if (feature == Logic.KWD_TRACE_SUBGOALS) {
Logic.clearCaches();
Stella.addTrace(Cons.cons(Logic.KWD_GOAL_TREE, Stella.NIL));
}
else if (feature == Logic.KWD_TRACE_SOLUTIONS) {
Logic.clearCaches();
Stella.addTrace(Cons.cons(Logic.KWD_TRACE_SOLUTIONS, Stella.NIL));
}
else if (feature == Logic.KWD_TRACE_CLASSIFIER) {
Logic.clearCaches();
Stella.addTrace(Cons.cons(Logic.KWD_CLASSIFIER_INFERENCES, Stella.NIL));
}
else if (feature == Logic.KWD_CLOSED_WORLD) {
}
else if (feature == Logic.KWD_ITERATIVE_DEEPENING) {
Logic.$ITERATIVE_DEEPENING_MODEp$ = true;
}
else if (feature == Logic.KWD_JUSTIFICATIONS) {
Native.setBooleanSpecial(Logic.$RECORD_JUSTIFICATIONSp$, true);
}
else if (feature == Logic.KWD_JUST_IN_TIME_INFERENCE) {
Logic.$JUST_IN_TIME_FORWARD_INFERENCEp$ = true;
}
else if (feature == Logic.KWD_EMIT_THINKING_DOTS) {
Logic.$EMIT_THINKING_DOTSp$ = true;
}
else {
Stella.STANDARD_WARNING.nativeStream.println("Warning: No such PowerLoom environment feature: `" + feature + "'");
Logic.printFeatures();
return;
}
Logic.$CURRENT_POWERLOOM_FEATURES$.insert(feature);
}
}
|
a0b54cb6-1cc1-4cb8-9e35-bd15aca39ca0
| 4
|
public MainMenu() throws IOException {
setIconImage(ResourceUtil.getIcon(ResourceUtil.RESOURCE_GAME_ICON)
.getImage());
setResizable(false);
setBounds(100, 100, 825, DEFAULT_WIDTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
player = new Player();
setTitle(APP_NAME + ": " + Player.getNickname() + Player.getPostName());
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnStart = new JMenu("Start");
menuBar.add(mnStart);
JMenuItem mntmChangeNickname = new JMenuItem("Change nickname");
mntmChangeNickname.setIcon(ResourceUtil
.getIcon(ResourceUtil.RESOURCE_ADDRESSBOOK));
mntmChangeNickname.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame changeNick = new ChangenickFrame();
changeNick.setVisible(true);
}
});
mnStart.add(mntmChangeNickname);
JMenuItem mntmConnect = new JMenuItem("Connect");
mntmConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame connFrame = new ConnectionFrame();
connFrame.setVisible(true);
}
});
mntmConnect.setIcon(ResourceUtil.getIcon(ResourceUtil.RESOURCE_RADAR));
mnStart.add(mntmConnect);
JMenu mnAbout = new JMenu("About");
menuBar.add(mnAbout);
JMenuItem mntmFeedback = new JMenuItem("Feedback");
mntmFeedback.setIcon(ResourceUtil
.getIcon(ResourceUtil.RESOURCE_FEEDBACK_ICON));
mntmFeedback.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(
MainMenu.getMainFrame(),
"Made by Alexandr Kutashov\nIf you find any bugs, please mail me to kutashov.alexandr@yandex.ru",
"About", 1);
}
});
mnAbout.add(mntmFeedback);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
log = new Log();
BattleField battleField = new BattleField(true);
Player.setMyBattleField(battleField);
BattleField battleField_1 = new BattleField(false);
Player.setEnemyBattleField(battleField_1);
lblYourTurn = new JLabel("Your turn: ");
lblYourTurn.setVisible(false);
lblYourTurn.setFont(new Font("Times New Roman", Font.PLAIN, 24));
yourTurnLabel = new JLabel();
yourTurnLabel.setLabelFor(lblYourTurn);
yourTurnLabel.setPreferredSize(new Dimension(24, 24));
randomButton = new JButton("Random me!");
randomButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Player.randomShips();
}
});
randomButton.setVisible(false);
readyButton = new JButton("I'm ready!");
readyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Player.areShipsSetted()) {
try {
Player.sendMessage(Message.BODY_GAME_READY);
Player.setMyReadiness(true);
if (Player.isEnemyReadiness() && Player.isMyReadiness()) {
Player.startGame();
MainMenu.getRandomButton().setVisible(false);
MainMenu.getReadyButton().setVisible(false);
MainMenu.getLblYourTurn().setVisible(true);
MainMenu.getYourTurnLabel().setVisible(true);
Player.setMyTurn(false);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
readyButton.setVisible(false);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane
.setHorizontalGroup(gl_contentPane
.createParallelGroup(Alignment.TRAILING)
.addGroup(
gl_contentPane
.createSequentialGroup()
.addContainerGap()
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.LEADING)
.addComponent(
battleField,
GroupLayout.PREFERRED_SIZE,
274,
GroupLayout.PREFERRED_SIZE)
.addGroup(
gl_contentPane
.createSequentialGroup()
.addComponent(
randomButton,
GroupLayout.PREFERRED_SIZE,
105,
GroupLayout.PREFERRED_SIZE)
.addGap(33)
.addComponent(
readyButton,
GroupLayout.PREFERRED_SIZE,
106,
GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(
ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.LEADING)
.addGroup(
gl_contentPane
.createSequentialGroup()
.addGap(10)
.addComponent(
lblYourTurn,
GroupLayout.PREFERRED_SIZE,
111,
GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addComponent(
yourTurnLabel,
GroupLayout.PREFERRED_SIZE,
81,
GroupLayout.PREFERRED_SIZE))
.addComponent(
log,
GroupLayout.PREFERRED_SIZE,
232,
GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
ComponentPlacement.UNRELATED)
.addComponent(battleField_1,
GroupLayout.PREFERRED_SIZE,
272, GroupLayout.PREFERRED_SIZE)
.addContainerGap()));
gl_contentPane
.setVerticalGroup(gl_contentPane
.createParallelGroup(Alignment.LEADING)
.addGroup(
gl_contentPane
.createSequentialGroup()
.addContainerGap()
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.LEADING)
.addComponent(
log,
GroupLayout.PREFERRED_SIZE,
256,
GroupLayout.PREFERRED_SIZE)
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.LEADING,
false)
.addComponent(
battleField,
GroupLayout.PREFERRED_SIZE,
256,
Short.MAX_VALUE)
.addComponent(
battleField_1,
0,
0,
Short.MAX_VALUE)))
.addPreferredGap(
ComponentPlacement.UNRELATED)
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.LEADING)
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.BASELINE)
.addComponent(
lblYourTurn,
GroupLayout.DEFAULT_SIZE,
40,
Short.MAX_VALUE)
.addComponent(
randomButton,
GroupLayout.PREFERRED_SIZE,
42,
GroupLayout.PREFERRED_SIZE)
.addComponent(
readyButton,
GroupLayout.PREFERRED_SIZE,
42,
GroupLayout.PREFERRED_SIZE))
.addComponent(
yourTurnLabel,
GroupLayout.PREFERRED_SIZE,
40,
GroupLayout.PREFERRED_SIZE))
.addContainerGap()));
contentPane.setLayout(gl_contentPane);
setVisible(true);
server = new ServerSocket(Player.getPort());
server.setSoTimeout(5000);
}
|
b1e89337-7c98-4944-a2ff-d24bb4875dcf
| 9
|
@Override
public void run()
{
try
{
// Ϣ
String msgStr = "";
// ַָеλ
int separatorIndex = 0;
// ǷϢ
isListen = true;
while(isListen)
{
// Ϣ
msgStr = dis.readUTF();
// ȷַָеλ
separatorIndex = msgStr.indexOf(separatorStr);
// ȡϢ
MessageTypeEnum msgType = MessageTypeEnum.valueOf(msgStr.substring(0, separatorIndex));
switch (msgType)
{
/***************** Login ******************/
case LoginReturn:
{
// bizд
LoginHandleBiz.getLoginHandleBiz().loginHandle(msgStr.substring(separatorIndex + 3));
break;
}
/***************** ûϢ ******************/
case AllOnlineUserDetailReturn:
{
// bizд
LoginHandleBiz.getLoginHandleBiz().onlineUserDetailReturnHandle(msgStr.substring(separatorIndex + 3));
break;
}
/***************** û ******************/
case NewClientConnect:
{
// bizд
LoginHandleBiz.getLoginHandleBiz().newClientConnectHandle(msgStr.substring(separatorIndex + 3));
break;
}
/***************** û ******************/
case ClientOffLine:
{
// bizд
LoginHandleBiz.getLoginHandleBiz().ClientOffLineHandle(msgStr.substring(separatorIndex + 3));
break;
}
/***************** ȺϢ ******************/
case GroupChat:
{
// bizд
ChatHandleBiz.getChatHandleBiz().groupChatHandle(msgStr.substring(separatorIndex + 3));
break;
}
/***************** һһϢ ******************/
case SingleChat:
{
// bizд
ChatHandleBiz.getChatHandleBiz().singleChatHandle(msgStr.substring(separatorIndex + 3));
break;
}
default:
break;
}
}
}
catch(SocketException e)
{
System.err.println("Ͽӣ");
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
|
29c94a4e-9839-4fbe-a230-d7cb29eadfe8
| 5
|
@Override
public ArrayList<Integer> getMove() {
Path bestPath = null;
Path bestPath1 = null;
Path bestPath2 = null;
/*
* For 2 and 3 player games the AI needs to check 2 colors, those are
* assigned here. 4 Player games only let each player have one color.
*/
if (playerCount == 2) {
bestPath1 = getBestMove(player.getColor());
bestPath2 = getBestMove(player.getColor() + 1);
bestPath = BestPath(bestPath1, bestPath2);
} else if (playerCount == 3) {
bestPath1 = getBestMove(player.getColor());
bestPath2 = getBestMove(3);
bestPath = BestPath(bestPath1, bestPath2);
} else if (playerCount == 4) {
bestPath = getBestMove(player.getColor());
} else {
System.out.println("PlayerCount invalid");
}
System.out.println(bestPath);
if (bestPath == null) {
/*
* It should never come to this, nonetheless it will print some
* information about the board. In case it goes wrong.
*/
System.out.println("No more moves possible");
System.out.println(cellsAvailable);
System.out.println(bestPath1);
System.out.println(bestPath2);
System.out.println(player.getPieces());
System.out.println(game.isGameOver());
System.out.println(game.canDoMove(player));
}
Piece piece = null;
int x = bestPath.get(0).x;
int y = bestPath.get(0).y;
try {
piece = player.getPiece(bestPath.get(0).getBestType(), bestPath
.get(0).getBestColor());
} catch (InvalidPieceException e) {
e.printStackTrace();
System.out
.println("SMART AI BUG, wil niet bestaand Piece gebruiken");
}
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(x);
arr.add(y);
arr.add(piece.getType());
arr.add(piece.getColor());
return arr;
}
|
627d96ec-9539-47ad-8645-4c4fa29da61b
| 6
|
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
//;
//;
boolean bDebug = false;
String sAction = getParam( request, "FormAction");
String sForm = getParam( request, "FormName");
String sFooterErr = "";
java.sql.Connection conn = null;
java.sql.Statement stat = null;
conn = cn();
stat = conn.createStatement();
out.write("<center>\r\n");
out.write("<hr size=1 width=60%>\r\n");
out.write(" <table>\r\n");
out.write(" <tr>\r\n");
out.write(" <td valign=\"top\">\r\n");
Footer_Show(request, response, session, out, sFooterErr, sForm, sAction, conn, stat);
out.write(" </td>\r\n");
out.write(" \r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.write(" \r\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
|
94ba6ef5-2fbc-45cf-9275-3369ff428178
| 7
|
private void generateRandomMap() {
mapGrid = new Entity[width][height];
setColumnCount(width);
setRowCount(height);
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
int rand = (int) (Math.random() * 100);
if (rand < 15) { //15% of map is walls
putWallIn(x, y);
} else if (rand >= 15 && rand < 35) { // 20% of map is boxes
putBoxIn(x, y);
} else if (rand >=35 && rand <= 100) { // 65% of the map will be path
putPathIn(x, y);
hideExitIn(x, y, pathIcon); // only one door will be created at a path
} else {
putPathIn(x, y);
}
}
}
}
|
b85d659c-ff54-4245-8f1c-450b58a98d35
| 6
|
public void load(DataInputStream in, String name, World w) {
this.name = name;
try {
world = w;
try {
while (true) {
int d = in.readInt();
if (d == Material.CHEST.getId()) {
blocks.add(new BlocksChest(in, world));
} else if (d == Material.SIGN.getId() || d == Material.SIGN_POST.getId()) {
blocks.add(new BlocksSign(in, world));
} else {
blocks.add(new Blocks(in, world));
}
}
} catch (EOFException d) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
e128db4e-fb52-48a0-b6e7-7c8321877f0c
| 4
|
private double getCost2(Node parent, String[] ngram, int length) {
if(parent.value.equals(EMPTY_PUNCT)) {
if(parent.parent!=null) {
return getCost2(parent.parent, ngram, length);
} else {
return 1.0D;
}
}
ngram[length] = parent.value.trim();
if(length==0) {
return nGram.getCostOfNGram(ngram);
} else if(parent.parent!=null) {
return getCost2(parent.parent, ngram, length-1);
} else {
/*
if(nGram.getNGramLength()>3) {
System.err.println("THIS WILL CRASH!");
throw new IllegalArgumentException();
}
*/
return 1.0D;
//This really should be 1.0D... right ?...
//return nGram.getCostOfNGram(Arrays.copyOfRange(ngram, length, ngram.length-length));
}
}
|
dd6b25eb-0d06-45d3-8049-1dccc74c3462
| 5
|
public void buildBarracks(Map map, Cell c, Boolean aiMove) {
if (aiMove || Teams.comparePlayers(this.getOwner(),game.getCurrentPlayer())) {
if (game.getCurrentPlayer().canAfford(Barracks.cost)) {
if (getBuildableCells(map).contains(c)) {
Barracks b = new Barracks(c, this.getOwner(), this.game);
b.placeBuilding(b, c);
game.getCurrentPlayer().subMoney(Barracks.cost);
} else {
game.mapPanel.Notify("You cannot place a Barrack there!");
}
} else {
if (!aiMove) {
game.mapPanel.Notify("You cannot afford to purchace a Barrack!");
}
}
} else {
game.mapPanel.Notify("You can only control your own Base!");
}
}
|
a63921ae-3ad4-42a7-9ae1-bee4836c984a
| 4
|
public void runecraftingComplex(int screen) {
if (screen == 1) {
clearMenu();
menuLine("1", "Air runes", 556, 0);
menuLine("2", "Mind runes", 558, 1);
menuLine("5", "Water runes", 555, 2);
menuLine("6", "Mist runes", 4695, 3);
menuLine("9", "Earth runes", 557, 4);
menuLine("10", "Dust runes", 4696, 5);
menuLine("13", "Mud runes", 4698, 6);
menuLine("14", "Fire runes", 554, 7);
menuLine("15", "Smoke runes", 4697, 8);
menuLine("19", "Steam runes", 4694, 9);
menuLine("20", "Body runes", 559, 10);
menuLine("23", "Lava runes", 4699, 11);
menuLine("27", "Cosmic runes", 564, 12);
menuLine("35", "Chaos runes", 562, 13);
menuLine("44", "Nature runes", 561, 14);
menuLine("54", "Law runes", 563, 15);
menuLine("65", "Death runes", 560, 16);
menuLine("77", "Blood runes", 565, 17);
optionTab("RuneCrafting", "Runes", "Runes", "Multiples",
"Equipment", "Milestones", "", "", "", "", "", "", "", "",
"");
}
else if (screen == 2) {
clearMenu();
menuLine("11", "2 Air runes per essence", 556, 0);
menuLine("14", "2 Mind runes per essence", 558, 1);
menuLine("19", "2 Water runes per essence", 555, 2);
menuLine("22", "3 Air runes per essence", 556, 3);
menuLine("26", "2 Earth runes per essence", 557, 4);
menuLine("28", "3 Mind runes per essence", 558, 5);
menuLine("33", "4 Air runes per essence", 556, 6);
menuLine("35", "2 Fire runes per essence", 554, 7);
menuLine("38", "3 Water runes per essence", 555, 8);
menuLine("42", "4 Mind runes per essence", 558, 9);
menuLine("44", "5 Air runes per essence", 556, 10);
menuLine("46", "2 Body runes per essence", 559, 11);
menuLine("52", "3 Earth runes per essence", 557, 12);
menuLine("55", "6 Air runes per essence", 556, 13);
menuLine("56", "5 Mind runes per essence", 558, 14);
menuLine("57", "4 Water runes per essence", 555, 15);
menuLine("59", "2 Cosmic runes per essence", 564, 16);
menuLine("66", "7 Air runes per essence", 556, 17);
menuLine("70", "6 Mind runes per essence", 558, 18);
menuLine("74", "3 Fire runes per essence", 554, 19);
menuLine("76", "2 Chaos runes per essence", 562, 20);
menuLine("77", "5 Water runes per essence", 555, 21);
menuLine("78", "8 Air runes per essence", 556, 22);
menuLine("82", "4 Earth runes per essence", 557, 23);
menuLine("84", "7 Mind runes per essence", 558, 24);
menuLine("88", "9 Air runes per essence", 556, 25);
menuLine("91", "2 Nature runes per essence", 561, 26);
menuLine("92", "3 Body runes per essence", 559, 27);
menuLine("95", "6 Water runes per essence", 555, 28);
menuLine("98", "8 Mind runes per essence", 558, 29);
menuLine("99", "10 Air runes per essence", 556, 30);
optionTab("RuneCrafting", "Multiples", "Runes", "Multiples",
"Equipment", "Milestones", "", "", "", "", "", "", "", "",
"");
}
else if (screen == 3) {
clearMenu();
menuLine("1", "Small Pouch(3 Essence)", 5509, 0);
menuLine("25", "Medium Pouch(6 Essence)", 5510, 1);
menuLine("50", "Large Pouch(9 Essence)", 5512, 2);
menuLine("75", "Giant Pouch(12 Essence)", 5514, 3);
optionTab("RuneCrafting", "Equipment", "Runes", "Multiples",
"Equipment", "Milestones", "", "", "", "", "", "", "", "",
"");
}
else if (screen == 4) {
clearMenu();
menuLine("99", "Skill Mastery", c.getItems().skillcapes[c.playerRunecrafting][0], 0);
optionTab("RuneCrafting", "Milestones", "Runes", "Multiples",
"Equipment", "Milestones", "", "", "", "", "", "", "", "",
"");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.