method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
226db4bb-cfb2-46e5-b0f6-5bf29b510c0b | 6 | public int findMin(List<Integer> l){
if(l==null){
return 0;
}
if(l.size()==0){
return 0;
}
if(l.size()==1){
return l.get(0);
}
int min = -1;
int tmp;
for(int i=0;i<l.size();i++){
if(i==0){
min = i;
}else{
tmp = l.get(i);
if(tmp <min){
min = tmp;
}
}
}
return min;
} |
279e69d6-a6ae-4e6e-91a6-34915b17e743 | 9 | public static void main(String[] args)
{
System.out.println("Hello and welcome to team 3-3's 449 a1, java version!" + '\n' );
// check if the correct arguments are being used
// myProgram myInput myOutput
_args = args;
if (args.length != 2)
{
System.out.println("Usage: <input file> <output file>");
System.exit(0);
}
// run initial io class to obtain data for processing, stores data
// parse the input file with the first argument
io.readInputFile(args[0]);
//System.out.println(args[0] + " file has been read");
Assignment[] lowestSolution = new Assignment[8];
// put the best possible tasks in the unassigned lowestSolution[] elements
for(int i = 0; i < lowestSolution.length; i++)
{
Assignment tempAssign = new Assignment();
// find the lowest penalty for the machine
int least = io.machinePenaltiesArray.get(i)[0];
int n = 0; // n is the column number (task) with the smallest penalty
for (int j = 1; j < io.machinePenaltiesArray.size(); j++)
{
//try{
if(least > io.machinePenaltiesArray.get(i)[j])
{
least = io.machinePenaltiesArray.get(i)[j];
n = j;
}
//}
//catch (ArrayIndexOutOfBoundsException e){
// main.displayError(2);
// }
}
tempAssign.mTask = Character.toString((char) (n+65)); //ascii value of n
tempAssign.mForced = false;
lowestSolution[i] = tempAssign;
}
// replace the forced assignments in lowestSolution[], if applicable
for(int i = 0; i < io.forcedPartialAssignArray.size(); i++)
{
Assignment tempAssign = new Assignment();
tempAssign.mTask = io.forcedPartialAssignArray.get(i).getRight();
tempAssign.mForced = true;
lowestSolution[io.forcedPartialAssignArray.get(i).getLeft()-1] = tempAssign;
}
Node node = new Node();
node.mAssignnments = lowestSolution;
Tree tree = new Tree();
//YOU WANT THIS!!!!
bestSolution = tree.CalculateBestSolution(node, 0);
int bestCost = Calcs.CalculateFinalCost(bestSolution);
//^^THATS WHAT YOU WANT
if(bestSolution == null)
{
// this means there is no solution
makeOutputFile(args[1], "No valid solution possible!");
//System.out.println(args[1] + " outfile made");
return;
}
//For debugging
for(int m = 0; m < lowestSolution.length; m++)
{
//System.out.println("Final Solution[" + m + "] = (" + bestSolution[m].mTask + "," + bestSolution[m].mForced + ")");
tasks.add(bestSolution[m].mTask);
}
// The lowest possible solution (taking into account forcedPartials and machine/task penalties is done. */
// create the root node with lowestSolution[], an array of length lowestSolution for the child node pointers and caluclate the cost
//System.out.println(bestCost);
quality = bestCost;
String tempSolution = null;
if(bestSolution !=null)
{
tempSolution = ("Solution");
for (int i=0; i<tasks.size(); i++)
{
tempSolution = tempSolution.concat(" " + tasks.get(i));
}
tempSolution = tempSolution.concat("; Quality: " + quality);
}
else
{
//System.out.println("TESTSETSETSETSETSET");
tempSolution = ("No valid solution possible!");
}
//create an output file named after the second argument
makeOutputFile(args[1], tempSolution);
//System.out.println(args[1] + " output file created.");
} |
cc580a6c-4946-4611-9136-8e66a3f5c5e1 | 5 | @EventHandler(ignoreCancelled = true)
public void handle(BlockPlaceEvent event) {
Player player = event.getPlayer();
GameSession session = plugin.getGameManager().getGameSessionOfPlayer(
player);
if (session == null) {
return;
}
if (!(session.isStarted()) && !(session.isAdmin(player))) {
event.setCancelled(true);
}
if (session.isStarted() && session.getDeadPlayers().contains(player)) {
event.setCancelled(true);
}
} |
313b6d0c-0d6d-4a47-b90f-c9ce4016d2ec | 9 | public void move()
{
String snarkyComment = "Can't do that! *mumbles under breath* dummy";
System.out.println("Where to?");
String dir = Driver.getScanner().nextLine();
if(dir.equalsIgnoreCase("up"))
{
if(getCurrentRoom().moveUp())
{
leftLastTime = false;
return;
}
else
{
System.out.println(snarkyComment);
}
}
if(dir.equalsIgnoreCase("down"))
{
if(getCurrentRoom().moveDown())
{
leftLastTime = false;
return;
}
else
{
System.out.println(snarkyComment);
}
}
if(dir.equalsIgnoreCase("right"))
{
if(getCurrentRoom().moveRight())
{
leftLastTime = false;
return;
}
else
{
System.out.println(snarkyComment);
}
}
if(dir.equalsIgnoreCase("left"))
{
if(getCurrentRoom().moveLeft())
{
if(leftLastTime)
{
System.out.println("http://en.wikipedia.org/wiki/Irreplaceable");
leftLastTime = false;
}
else
{ leftLastTime = true; }
return;
}
else
{
System.out.println(snarkyComment);
}
}
getCurrentRoom().visualize();
} |
e4ff52f3-7431-4d94-906a-9dbdee63e75c | 7 | private static TspPopulation[] generate(){
Graph g = new Graph(INDIVIDUAL_SIZE);
TspPopulation[] h = new TspPopulation[GLOBAL_STEPS];
for (int i = 0; i < GLOBAL_STEPS; ++i){
h[i] = new TspPopulation(POPULATION_SIZE, INDIVIDUAL_SIZE, g.getGraph());
}
resultsRandom = new long[GLOBAL_STEPS];
Arrays.fill(resultsRandom, Long.MAX_VALUE);
for (int i = 0; i < GLOBAL_STEPS; ++i){
if (i % 100 == 0){
System.out.println("random " + i);
}
TspPopulation populationRandom = new TspPopulation(h[i]);
InverseOperator randomIO = new InverseOperator(populationRandom, RNG);
SwapOperator randomSWO = new SwapOperator(populationRandom, RNG);
ScrambleOperator randomSCO = new ScrambleOperator(populationRandom, RNG);
MPX1 randomMPX1 = new MPX1(populationRandom, RNG);
MPX2 randomMPX2 = new MPX2(populationRandom, RNG);
for (int step = 0; step < MAX_STEPS; ++step){
double r;
synchronized (RNG){
r = RNG.nextDouble();
}
if (r < 0.33) {
randomIO.mutate();
} else if (r < 0.66) {
randomSWO.mutate();
} else if (r < 1.1) {
randomSCO.mutate();
}// else if (r < 0.8) {
// randomMPX1.mutate();
// } else {
// randomMPX2.mutate();
// }
}
resultsRandom[i] = populationRandom.getFittest();
}
Arrays.sort(resultsRandom);
return h;
} |
7690a2c4-4821-4125-bf69-2e1eb6c0dafd | 1 | protected JPanel getFontFamilyPanel()
{
if (fontNamePanel == null)
{
fontNamePanel = new JPanel();
fontNamePanel.setLayout(new BorderLayout());
fontNamePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
fontNamePanel.setPreferredSize(new Dimension(180, 130));
JScrollPane scrollPane = new JScrollPane(getFontFamilyList());
scrollPane.getVerticalScrollBar().setFocusable(false);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(getFontFamilyTextField(), BorderLayout.NORTH);
p.add(scrollPane, BorderLayout.CENTER);
JLabel label = new JLabel(("Font Name"));
label.setHorizontalAlignment(JLabel.LEFT);
label.setHorizontalTextPosition(JLabel.LEFT);
label.setLabelFor(getFontFamilyTextField());
label.setDisplayedMnemonic('F');
fontNamePanel.add(label, BorderLayout.NORTH);
fontNamePanel.add(p, BorderLayout.CENTER);
}
return fontNamePanel;
} |
0f0ee9be-9474-42dd-936b-247ec14b0994 | 5 | @Override
public void ParseIn(Connection Main, Server Environment)
{
Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom);
if (Room == null)
{
return;
}
if (Main.Data.RatedRooms.contains(Room.Id) || Room.CheckRights(Main.Data, true))
{
return;
}
int Rating = Main.DecodeInt();
switch (Rating)
{
case -1:
Room.Score--;
break;
case 1:
Room.Score++;
break;
default:
return;
}
Main.Data.RatedRooms.add(Room.Id);
Environment.InitPacket(345, Main.ClientMessage);
Environment.Append(Room.Score, Main.ClientMessage);
Environment.EndPacket(Main.Socket, Main.ClientMessage);
} |
30bcb7f5-e3ba-4bac-9afb-ca93df006b1b | 7 | public void ChangeStatus(){
if (x.textfieldStartStop.getText().equals("Working")){
x.textfieldStartStop.setText("WaitingForProcessor");
} else if (x.textfieldLoader.getText().equals("Working")){
x.textfieldLoader.setText("WaitingForProcessor");
}else if (x.textfieldMainProc.getText().equals("Working")){
x.textfieldMainProc.setText("WaitingForProcessor");
}else if (x.textfieldJobGovernor.getText().equals("Working")){
x.textfieldJobGovernor.setText("WaitingForProcessor");
} else if (x.textfieldVirtualMachine.getText().equals("Working")){
x.textfieldVirtualMachine.setText("WaitingForProcessor");
} else if (x.textfieldInterrupt.getText().equals("Working")){
x.textfieldInterrupt.setText("WaitingForProcessor");
}else if (x.textfieldSendToPrinter.getText().equals("Working")){
x.textfieldSendToPrinter.setText("WaitingForProcessor");
}
} |
9dc94d9c-ab54-40ae-91e8-805c0cdbb490 | 2 | private void addOutsideCurve(int end, int newRadius) {
if (restricted.isSelected()) {
int sectionBeginning = road.sectionBeginning();
road.addOutsideCurve(end, false, newRadius);
if (sectionLongerThanSmax(end, sectionBeginning)) return;
} else {
road.addOutsideCurve(end, true, newRadius);
}
} |
ed535b87-e398-49f8-b2b0-1bb902208d81 | 2 | private static DecimalImpl safeAdd(final long d1, final long d2, final int factor)
{
final long sum = d1 + d2;
if (DPU.isSameSign(d1, d2) && !DPU.isSameSign(sum, d1))
{
final long shrinkedSum = d1 / 10 + d2 / 10;
return safegetInstance(shrinkedSum, factor - 1);
}
else
{
return safegetInstance(sum, factor);
}
} |
d4fd6d99-25e2-4d73-9382-684f54853e9f | 4 | public void makeSidePanel() {
JPanel sideBar = new JPanel(new GridLayout(3,1,20,20));
// Buttons
JPanel sideBarButtons = new JPanel(new GridLayout(2,1));
JButton add = new JButton("Add");
add.setPreferredSize( new Dimension(80, 30) );
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String met = MetSearch.getText();
String con = ConSearch.getText();
String pop = PopSearch.getText();
// in case of incomplete entry
if (fieldEmpty()) {
errorMessage.setText("Enter a value in all fields!");
}else {
model.add(met, con, pop);
errorMessage.setText("");
model.Search(met, con, pop, false, true);
}
clearSearchBar();
}
});
// search button
JButton search = new JButton("Search");
search.setPreferredSize( new Dimension(80, 30) );
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (fieldsEmpty()) {
model.getDatabase();
}else {
String met = MetSearch.getText();
String con = ConSearch.getText();
String pop = PopSearch.getText();
model.Search(met, con, pop, greater, exact);
}
clearSearchBar();
}
});
// add buttons to sidebar
sideBarButtons.add(add);
sideBarButtons.add(search);
sideBar.add(sideBarButtons);
// Dropdowns
final String[] popStrings = { "Population larger than",
"Population smaller than or equal to"};
final String[] searchStrings = {"Exact Search", "Partial Search"};
//Create the dropdowns
JPanel sideBarDropDowns = new JPanel(new GridLayout(3,1));
popList = new JComboBox(popStrings);
popList.setSelectedIndex(0);
popList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = popList.getSelectedItem().toString();
if (str.equals(popStrings[0])) {
greater = true;
}else {
greater = false;
}
}
});
greater = true;
searchList = new JComboBox(searchStrings);
searchList.setSelectedIndex(0);
searchList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = searchList.getSelectedItem().toString();
if (str.equals(searchStrings[0])) {
exact = true;
}else {
exact = false;
}
}
});
exact = true;
sideBarDropDowns.add(popList, BorderLayout.NORTH);
sideBarDropDowns.add(searchList, BorderLayout.SOUTH);
sideBarDropDowns.setBorder(new TitledBorder("Search Options"));
sideBar.add(sideBarDropDowns);
// error message space
errorMessage = new JLabel("");
errorMessage.setPreferredSize( new Dimension(175, 30) );
sideBar.add(errorMessage);
// add our beautiful panel to GUI
this.add(sideBar, BorderLayout.EAST);
} |
cb0c9e99-da04-46ae-9654-03856a6e026d | 5 | private void connectConnection(String host, int port)
throws ChannelError {
if (HydnaDebug.HYDNADEBUG) {
DebugHelper.debugPrint("Connection", 0, "Connecting, attempt ");
}
try {
SocketAddress address = new InetSocketAddress(host, port);
m_socketChannel = SocketChannel.open(address);
m_socket = m_socketChannel.socket();
try {
m_socket.setTcpNoDelay(true);
} catch (SocketException e) {
System.err.println("WARNING: Could not set TCP_NODELAY");
}
m_outStream = new DataOutputStream(m_socket.getOutputStream());
m_inStreamReader = new BufferedReader(new InputStreamReader(m_socket.getInputStream()));
if (HydnaDebug.HYDNADEBUG) {
DebugHelper.debugPrint("Connection", 0, "Connected, sending HTTP upgrade request");
}
m_connecting = false;
m_connected = true;
connectHandler();
} catch (UnresolvedAddressException e) {
m_connecting = false;
throw new ChannelError("The host \"" + host + "\" could not be resolved");
} catch (IOException e) {
m_connecting = false;
throw new ChannelError("Could not connect to the host \"" + host + "\" on the port " + port);
}
} |
f1ed2761-b844-4ff6-86be-a6d8d70a7e4b | 1 | static int[] calculateVendingMachineChange(int[] coin_totals, BigDecimal balance) {
String[] change_denomination = {"1.0", "0.5", "0.2", "0.1"};
for(int i = 0; i < coin_totals.length; i++) {
balance = change(coin_totals, balance, change_denomination[i], i);
}
return coin_totals;
} |
0ac7073b-39bb-46f2-b6ae-5bded4c7f197 | 6 | private void initBorderMaze() {
for (int x = 0; x < bufferedImage.getWidth(); x++) {
for (int y = 0; y < bufferedImage.getHeight(); y++) {
if (x == 0 || x == bufferedImage.getWidth() - 1 || y == 0
|| y == bufferedImage.getHeight() - 1) {
bufferedImage.setRGB(x, y, Color.BLACK.getRGB());
continue;
}
bufferedImage.setRGB(x, y, Color.WHITE.getRGB());
}
}
} |
231adc1c-c1d2-418a-a7ef-9005fc85bd2a | 2 | public synchronized void close() {
AudioDevice out = audio;
if (out != null) {
closed = true;
audio = null;
// this may fail, so ensure object state is set up before
// calling this method.
out.close();
lastPosition = out.getPosition();
try {
bitstream.close();
} catch (BitstreamException ex) {
}
}
} |
150b082b-b85a-45b1-a745-63bf6f1f83c7 | 2 | private void fireServerEvent(ServerEvent evt) {
Object[] listeners = serverEventListenerList.getListenerList();
for (int i=0; i<listeners.length; i+=2) {
if (listeners[i]==IServerEventListener.class) {
((IServerEventListener)listeners[i+1]).OnServerEvent(evt);
}
}
} |
32b1167e-8a78-414d-986d-c59ed5136bfb | 3 | private void changeLead() {
Anstalld selAnst = (Anstalld) cbLead.getSelectedItem();
if (selAnst.getAid() != -1) { //if not no predefined lead
try {
String query = "update spelprojekt set aid=" + selAnst.getAid() + " where sid=" + selectedSpelprojekt;
DB.update(query);
} catch (InfException e) {
e.getMessage();
}
} else { //if no predefined lead, set to null
try {
String query = "update spelprojekt set aid=null where sid=" + selectedSpelprojekt;
DB.update(query);
} catch (InfException e) {
e.getMessage();
}
}
} |
3fc90ae7-b9fb-489c-83fc-b14f60402594 | 9 | public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return listMembre.get(rowIndex).getId();
case 1:
return listMembre.get(rowIndex).getNom();
case 2:
return listMembre.get(rowIndex).getPrenom();
case 3:
return listMembre.get(rowIndex).getAdresse();
case 4:
return listMembre.get(rowIndex).getDate_naissance();
case 5:
return listMembre.get(rowIndex).getDate_inscription();
case 6:
return listMembre.get(rowIndex).getNum_telephone();
case 7:
return listMembre.get(rowIndex).getMail();
case 8:
return listMembre.get(rowIndex).getEvaluation();
default:
return null;
}
} |
621fce54-2781-4ca1-83e6-f23486dfeba2 | 4 | private void findNegativeCycle(EdgeWeightedDigraph G)
{
// Create a Digraph from edgeTo[]
Digraph spt = new Digraph(G.V());
try
{
for (int v = 0; v < G.V(); v++)
if (vertex[v].edgeTo != null)
spt.addEdge(vertex[v].edgeTo.from(), vertex[v].edgeTo.to());
}
catch (Exception e)
{
System.out.println(e);
System.exit(1);
}
DirectedCycle cycle = new DirectedCycle(spt);
if (cycle.hasCycle())
negativeCycle = cycle.cycle();
} |
ff2cc514-643c-4ca6-ac1b-aba5bf869266 | 6 | public static JInternalFrame createHeirarchyFrame(final JFrame frame)
{
BasicFrames.removeDropdown(internalFrame);
internalFrame.setVisible(true);
internalFrame.setBounds(200, 200, 518, 352);
internalFrame.setFocusable(true);
try {
internalFrame.setSelected(true);
tree.setModel(new DefaultTreeModel(
new DefaultMutableTreeNode("Loading Tree... Wait for Engine To Initialize") {
private static final long serialVersionUID = 1L;
{
}
}
));
root.removeAllChildren();
model.reload(root);
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 2 && isGameObject((DefaultMutableTreeNode)tree.getLastSelectedPathComponent())) {
ObjectInfoFrame frameTAdd = new ObjectInfoFrame();
synchronized(infoFrames)
{
infoFrames.add(frameTAdd);
}
internalFrame.getParent().add(frameTAdd.createInfoFrame(frame, selPath.getLastPathComponent().toString(), CoreEngine.game.getRootObject()));
}
}
}
};
tree.addMouseListener(ml);
internalFrame.getContentPane().add(tree, BorderLayout.CENTER);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
internalFrame.invalidate();
new Thread() {
public void run() {
while (true) {
synchronized(infoFrames)
{
for(ObjectInfoFrame frome : infoFrames)
{
frome.update();
}
}
}
}
}.start();
return internalFrame;
} |
4ce16e4e-c7d5-4ac9-8d7e-fb97b5f2e432 | 4 | public boolean isConjugateTo(PGridPath path) {
if (path == null) {
throw new NullPointerException();
}
String common = commonPrefix(path);
if (path.length() == path_.length()) {
int otherLen = path.length() - common.length();
int thisLen = path_.length() - common.length();
if (otherLen == 1 && thisLen == 1) {
return true;
}
}
return false;
} |
b49f8ba7-496c-4754-a7c7-a2f270369818 | 0 | protected Icon getIcon() {
java.net.URL url = getClass().getResource("/ICON/blockTransition.gif");
return new javax.swing.ImageIcon(url);
} |
19b35d8b-925a-40e3-9772-7846d9fabf44 | 3 | private int trMedian3 (final int ISA, final int ISAd, final int ISAn, int v1, int v2, int v3) {
final int[] SA = this.SA;
int SA_v1 = trGetC (ISA, ISAd, ISAn, SA[v1]);
int SA_v2 = trGetC (ISA, ISAd, ISAn, SA[v2]);
int SA_v3 = trGetC (ISA, ISAd, ISAn, SA[v3]);
if (SA_v1 > SA_v2) {
final int temp = v1;
v1 = v2;
v2 = temp;
final int SA_vtemp = SA_v1;
SA_v1 = SA_v2;
SA_v2 = SA_vtemp;
}
if (SA_v2 > SA_v3) {
if (SA_v1 > SA_v3) {
return v1;
}
return v3;
}
return v2;
} |
c3a8b2b2-6fe8-404a-a965-ec1b053b131e | 9 | private void loadLayout(){
//Do a random layout for now...
if(texturePack == null || texturePack.floor == null || texturePack.wall == null || texturePack.brick == null)
System.out.println("ERROR: Broken texture pack!");
Random rand = new Random();
for(int x=0; x<size.width; x++){
for(int y=0; y<size.height; y++){
if( (x%2)==1 && (y%2)==1 ){
grid[x][y]= new Wall(x*32, y*32, texturePack.wall);
} else if (rand.nextFloat() < .15 ){
grid[x][y]= new Brick(x*32, y*32, texturePack.brick);
}
}
}// */
} |
c9d72dac-6e5d-4382-b51b-b6440fd4e220 | 0 | public void setId(int id) {
this.id = id;
} |
6327a7a0-c8f5-40ce-ac9d-e7056f63423b | 9 | private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
int servicePort = new Integer(bootstrapServicePortTextField.getText()).intValue();
int registryPort = new Integer(registryPortTextField.getText()).intValue();
bootstrapServer = new BootstrapServer(servicePort, logArea);
bootstrapServer.start();
while (!bootstrapServer.getInitDone()) {
}
if (!bootstrapServer.isRunning()) {
logArea.appendError("Problemi a far partire il bootstrap server");
return;
}
if (registerCheckBox.isSelected()) {
if (startRegistryCheckBox.isSelected())
try {
registry = LocateRegistry.createRegistry(registryPort);
logArea.appendMessage("Registry RMI locale avviato e pronto all'uso");
} catch (RemoteException e) {
logArea.appendError("Non è stato possibile avviare un registry RMI locale", e);
bootstrapServer.shutdown();
return;
}
else
try {
registry = LocateRegistry.getRegistry(registryHostTextField.getText(),
registryPort);
} catch (RemoteException e) {
logArea.appendError("Impossibile reperire il registry RMI specificato", e);
bootstrapServer.shutdown();
return;
}
try {
registry.rebind(serviceNameTextField.getText(), bootstrapServer.getRemote());
} catch (RemoteException e) {
logArea.appendError("Impossibile registrare il server di " +
"bootstrap presso il registry RMI specificato", e);
bootstrapServer.shutdown();
return;
}
}
Component[] components = optionsPanel.getComponents();
registerCheckBox.setSelected(false);
registerCheckBoxActionPerformed(evt);
for (int i = 0; i < components.length; i++)
components[i].setEnabled(false);
components = servantsPanel.getComponents();
for (int i = 0; i < components.length; i++)
components[i].setEnabled(true);
listTimer.start();
stopButton.setEnabled(true);
startButton.setEnabled(false);
statusLabel.setText("In esecuzione");
logArea.appendMessage("Server di bootstrap avviato con successo");
}//GEN-LAST:event_startButtonActionPerformed |
2341a693-5f16-4626-a5ac-373ae4d7b29d | 6 | private void processTile(ArrayList<ArrayList<DataTile>> tiles, float lat,
float lon) throws InterruptedException {
int rankAverage;
int rankTotal = 0;
Double finalHeight;
Double heightTotal = 0d;
ArrayList<Integer> rankArray = new ArrayList<Integer>();
ArrayList<Float> heightArray = new ArrayList<Float>();
for (int x = 0; x < tiles.size() - 1; x++) {
ArrayList<DataTile> tileRow = tiles.get(x);
for (int y = 0; y < tileRow.size() - 1; y++) {
float slope;
float opp;
float centre = tileRow.get(y).getHeight().floatValue();
float right = tileRow.get(y + 1).getHeight().floatValue();
float below = tiles.get(x).get(y).getHeight().floatValue();
heightArray.add(centre);
// Calc right slope first
opp = centre - right;
if (opp < 0) {
opp *= -1;
}
slope = (float) Math.toDegrees(Math.atan((opp / distance)));
rankArray.add(calcSlopeRank(slope));
// Calc below slope
opp = centre - below;
if (opp < 0) {
opp *= -1;
}
slope = (float) Math.toDegrees(Math.atan((opp / distance)));
rankArray.add(calcSlopeRank(slope));
}
}
// Calculate rank
for (Integer rank : rankArray) {
rankTotal += rank;
}
rankAverage = rankTotal / rankArray.size();
for (Float height : heightArray) {
heightTotal += height;
}
finalHeight = heightTotal / heightArray.size();
DataTile dataTile = new DataTile(lat, lon, rankAverage, finalHeight);
ThreadStorage.putProcessedTile(dataTile);
System.out.printf("Data Tile processed. Lat: %s, Lon: %s \n", lat, lon);
// Clean up
dataTile = null;
heightArray = null;
rankArray = null;
} |
184f9766-4172-4e8d-8f59-2a3367171ec8 | 9 | private ArrayList<EziInfo> indexFolder(File filesFolder, File eziFolder, ArrayList<EziInfo> eziFiles) {
try {
for (File file : filesFolder.listFiles()) {
if (file.isDirectory()) {
eziFiles = indexFolder(file, eziFolder, eziFiles);
} else {
if (!file.getName().endsWith(".ezi")) {
boolean existsInList = false;
for (EziInfo eziInfo : eziFiles) {
EziInfo temp = new EziInfo(file.length(), file);
if (eziInfo.getEziId().equals(temp.getEziId())) {
String originalChecksum = eziInfo.generateCheckSum();
String newFileChecksum = temp.generateCheckSum();
if (originalChecksum.equals(newFileChecksum)) {
eziInfo.addFile(file);
updateEziInfoFile(eziFolder, eziInfo);
existsInList = true;
}
else{
existsInList = false;
}
break;
}
}
if (!existsInList) {
EziInfo eziInfo = createEziInfoFile(file, eziFolder);
if (eziInfo != null) {
eziFiles.add(eziInfo);
}
}
}
}
}
} catch (NullPointerException exc) {
System.out.println("No such directory");
}
return eziFiles;
} |
834249b6-16b3-44d8-92c4-02096566a214 | 3 | private void classNotInEditorFolder(File file)
{
String filePath;
File fileDir;
filePath = file.getParent();
fileDir = new File(filePath);
if(fileDir.exists() && fileDir.isDirectory())
{
System.out.println("Class Not in editor");
if(isClassInDir(fileDir))
{
file = new File(file.getAbsolutePath().replace(".java", ".class"));
//copy file to the class folder
FileCopier.copyTo(file, this.folderPath.concat("\\"+this.className));
this.classExecutionPath = this.folderPath.concat(" "+this.className.replace(".class", " ").trim());
}
}
} |
0e6ad248-d867-48e9-9b99-028dca8df6e1 | 4 | int getB(String s1, String s2) {
int b = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i == j) {
continue;
}
if (s1.charAt(i) == s2.charAt(j)) {
b++;
}
}
}
return b;
} |
3fe7137f-55ee-431f-9933-ac05c9c6854c | 7 | @Override
public boolean accept(File f) {
if (f.isDirectory())
return true;
String s = f.getName();
int index = s.lastIndexOf('.');
if (index > 0 && index < s.length() - 1) {
String ext = s.substring(index+1).toLowerCase();
return (ext.equals("exe") ||
ext.equals("bat") ||
ext.equals("cmd") ||
ext.equals("com") ||
ext.equals("jar"));
}
return false;
} |
8087916b-5f84-4038-8f70-a696adca49ae | 0 | public void cleanStop() {
this.running = false;
}//stop |
1d9e051b-0097-468f-b856-ceafeee17b03 | 3 | public boolean match(ScheduleItem item) {
long runtime = 0;
if(item instanceof SSGridlet) {
runtime = forecastExecutionTime((SSGridlet)item);
} else {
runtime = ((ServerReservation)item).getDurationTime();
}
if(runtime < minRuntime || runtime >= maxRuntime) {
return false;
}
return true;
} |
7aa2acb1-ea33-4b4d-b79e-f3102f98e8ff | 0 | @Override
public String getDesc() {
return "EarthSpike";
} |
dc5a360f-4791-44e8-8ce8-1dd950e4768c | 1 | private void firePieceSent(Piece piece) {
for (PeerActivityListener listener : this.listeners) {
listener.handlePieceSent(this, piece);
}
} |
1427d63d-7fb2-4e09-b289-f2f201ea1d38 | 8 | protected void onImpact(MovingObjectPosition par1MovingObjectPosition)
{
if (par1MovingObjectPosition.entityHit != null && par1MovingObjectPosition.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, this.thrower), 0))
{
;
}
if (!this.worldObj.isRemote && this.rand.nextInt(8) == 0)
{
byte var2 = 1;
if (this.rand.nextInt(32) == 0)
{
var2 = 4;
}
for (int var3 = 0; var3 < var2; ++var3)
{
EntityChicken var4 = new EntityChicken(this.worldObj);
var4.setGrowingAge(-24000);
var4.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, 0.0F);
this.worldObj.spawnEntityInWorld(var4);
}
}
for (int var5 = 0; var5 < 8; ++var5)
{
this.worldObj.spawnParticle("snowballpoof", this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D);
}
if (!this.worldObj.isRemote)
{
this.setDead();
}
} |
df6582db-1d44-49f4-9db3-b1e91d6e3b06 | 2 | public void set(Integer key, Integer value) {
if(!super.containsKey(key)){
if(count == capacity){
--count;
Integer keyDel = super.keySet().iterator().next();
super.remove(keyDel);
}
super.put(key, value);
++count;
}else{
super.put(key, value);
}
} |
ab1defc7-c430-4754-a22f-f09385567cfd | 6 | public void addAtIndex(int index, int item)
{
if(index > size || index < 0)
{
System.out.println("Index out of boundary");
}
else
{
if(index == 0)
{
addFirst(item);
}
else if(index == size)
{
addLast(item);
}
else
{
int i = 0;
Node node = head;
while(i < (index-1) && node.next != null)
{
node = node.next;
i++;
}
Node temp = new Node(item);
temp.next = node.next;
node.next = temp;
}
}
} |
ce23827a-40f8-461f-90bd-2cfd241a723e | 9 | public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
int result = 0;
for (String t : tokens) {
if ((t.charAt(0) == '-' && t.length() > 1) || (t.charAt(0) >= '0' && t.charAt(0) <= '9')) {
stack.push(Integer.parseInt(t));
} else {
int a = stack.pop();
int b = stack.pop();
switch (t.charAt(0)) {
case '+':
result = (b + a);
break;
case '-':
result = (b - a);
break;
case '*':
result = (b * a);
break;
case '/':
result = (b / a);
break;
}
stack.push(result);
}
}
return stack.pop();
} |
cc569ae7-2f30-43f5-9543-19b830259b5a | 4 | public boolean setPlayer2(Player p) {
boolean test = false;
if (test || m_test) {
System.out.println("FileManager :: setPlayer2() BEGIN");
}
m_player2 = p;
if (test || m_test) {
System.out.println("FileManager :: setPlayer2() END");
}
return true;
} |
175bb2bd-bf47-4f05-bbd6-5280aec5c6f5 | 5 | private boolean verticalLineTo(Graphics2D g, Connector c, Point ep) {
Point p = c.getDirectP();
Point tp;
if (c.isVertical())
tp = new Point(ep.x, p.y);
else
tp = new Point(p.x, ep.y);
if (eFrom.intersects(tp, p) || eTo.intersects(tp, p)
|| eFrom.intersects(tp, ep) || eTo.intersects(tp, ep))
return false;
drawLine(g, p, tp);
drawLine(g, tp, ep);
return true;
} |
a6fdcbfa-9320-412c-a47e-9dc778729039 | 5 | private JPanel getSaveConfigurationsPanel(){
JPanel saveConfigurationPanel = new JPanel(new BorderLayout());
// Create the check box that will enable/disable the user to modify the file
JCheckBox enableSphinxConfiguration = new JCheckBox("Disable modifications");
enableSphinxConfiguration.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int state = e.getStateChange();
// Checked - 1
if(state == 1){
// If the checkbox is check then disable the window
sphinxPropertyPane.setEnabled(false);
undoButton.setEnabled(false);
redoButton.setEnabled(false);
}
// Unchecked - 2
if(state == 2){
sphinxPropertyPane.setEnabled(true);
if(undoManager.canUndo()){
undoButton.setEnabled(true);
}
if(undoManager.canRedo()){
redoButton.setEnabled(true);
}
}
}
});
saveConfigurationPanel.add(enableSphinxConfiguration, BorderLayout.WEST);
// Create the Text that will display the name of the current file
final JTextField configurationFileName = new JTextField(30);
// TODO: Add an event listener to the button that when it types a name, the property in the xml file will change as well
// TODO: Set a method that changes along with the name. Those methods cannot be deleted or modified.
// Remove the suffix from the name
configurationFileName.setHorizontalAlignment(JTextField.RIGHT);
configurationFileName.setText(sphinxPropertyFile);
JLabel configurationSuffixLabel = new JLabel(SphinxConfigurationSuffix);
JPanel fileNamePanel = new JPanel(new FlowLayout());
fileNamePanel.add(configurationFileName);
fileNamePanel.add(configurationSuffixLabel);
saveConfigurationPanel.add(fileNamePanel, BorderLayout.CENTER);
// Create the save button
saveModifications.setEnabled(false);
saveModifications.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Save the configuration file
if(saveFile(configurationFileName.getText())){
// If save was successful then disable the save button
saveModifications.setEnabled(false);
}
}
});
saveConfigurationPanel.add(saveModifications, BorderLayout.EAST);
// Return this panel
return saveConfigurationPanel;
} |
aa770608-64ee-4e55-b6f6-a29eeeb42b89 | 0 | public double getRelativeY() {return pos.getY();} |
0e47b3f9-c2f3-4f72-9930-223fc92e8d7f | 3 | protected boolean isIntervalEditable(Interval interval)
{
if (editedBy != null)
return true;
for (Interval i : editedIntervals)
if (i.contains(interval))
return true;
return false;
} |
d5f839ac-5f43-4ff4-8149-38dc7ebe17ac | 0 | @Test
public void itSetsWarmerPlateStatus() {
maker.setWarmerPlateStatus(CoffeeMakerAPI.WARMER_ON);
assertEquals(CoffeeMakerAPI.WARMER_ON, maker.getWarmerPlateStatus());
maker.setWarmerPlateStatus(CoffeeMakerAPI.WARMER_OFF);
assertEquals(CoffeeMakerAPI.WARMER_OFF, maker.getWarmerPlateStatus());
} |
c0ef3338-30d1-4489-a305-f170ff663286 | 8 | private boolean destroyBlocksInAABB(AxisAlignedBB par1AxisAlignedBB)
{
int var2 = MathHelper.floor_double(par1AxisAlignedBB.minX);
int var3 = MathHelper.floor_double(par1AxisAlignedBB.minY);
int var4 = MathHelper.floor_double(par1AxisAlignedBB.minZ);
int var5 = MathHelper.floor_double(par1AxisAlignedBB.maxX);
int var6 = MathHelper.floor_double(par1AxisAlignedBB.maxY);
int var7 = MathHelper.floor_double(par1AxisAlignedBB.maxZ);
boolean var8 = false;
boolean var9 = false;
for (int var10 = var2; var10 <= var5; ++var10)
{
for (int var11 = var3; var11 <= var6; ++var11)
{
for (int var12 = var4; var12 <= var7; ++var12)
{
int var13 = this.worldObj.getBlockId(var10, var11, var12);
if (var13 != 0)
{
if (var13 != Block.obsidian.blockID && var13 != Block.whiteStone.blockID && var13 != Block.bedrock.blockID)
{
var9 = true;
this.worldObj.setBlockWithNotify(var10, var11, var12, 0);
}
else
{
var8 = true;
}
}
}
}
}
if (var9)
{
double var16 = par1AxisAlignedBB.minX + (par1AxisAlignedBB.maxX - par1AxisAlignedBB.minX) * (double)this.rand.nextFloat();
double var17 = par1AxisAlignedBB.minY + (par1AxisAlignedBB.maxY - par1AxisAlignedBB.minY) * (double)this.rand.nextFloat();
double var14 = par1AxisAlignedBB.minZ + (par1AxisAlignedBB.maxZ - par1AxisAlignedBB.minZ) * (double)this.rand.nextFloat();
this.worldObj.spawnParticle("largeexplode", var16, var17, var14, 0.0D, 0.0D, 0.0D);
}
return var8;
} |
5797b70a-0a78-4cc6-bfb6-bdb9e9b01f08 | 3 | public static void main(String[] arg)
{
if (arg.length != 2) {
System.out.println("Usage:\n java Reorganize [source] [target]");
return;
}
BufferedImage source = null;
try {
source = ImageIO.read(new File(arg[0]));
} catch (IOException e) {
System.out.println("Error while trying to read " + arg[0] + ".");
e.printStackTrace();
System.exit(1);
}
// Read the existing frames into a vector
Vector<BufferedImage> spriteSet = gridCut(source,
HAIR_SPRITE_WIDTH, HAIR_SPRITE_HEIGHT,
HAIR_FRAMES, 1);
// Determine minimal rectangle that can still contain the contents of
// any frame
/*
Rectangle cropRect = minimumCropRect(spriteSet);
if (cropRect == null) {
System.out.println(
"Error: no optimal crop rect could be determined.");
System.exit(1);
}
System.out.println(arg[0] + ": width=\"" +
cropRect.width + "\" height=\"" + cropRect.height + "\"");
*/
filterHeadgear(spriteSet);
BufferedImage target = gridDraw(
spriteSet,
new Rectangle(0, 0, HAIR_SPRITE_WIDTH, HAIR_SPRITE_HEIGHT),
HAIR_FRAMES - 4, 1);
// Save the target image
try {
ImageIO.write(target, "png", new File(arg[1]));
} catch (IOException e) {
System.out.println("Error while trying to write " + arg[1] + ".");
e.printStackTrace();
System.exit(1);
}
} |
5179e584-3824-42b2-9478-9bdb5e728def | 5 | @BeforeClass
public static void setUpBeforeClass() {
try { new MySQLConnection(); }
catch (InstantiationException e) { e.printStackTrace(); }
catch (IllegalAccessException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
catch (SQLException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
} |
aba9a7eb-9a21-465e-a223-5518eb2aca09 | 6 | public int alphaBetaNegamax( Board board, int depth, int alpha, int beta ) {
if ( board.isCheckmate() ) {
return ( Integer.MIN_VALUE + 1 + this.depth - depth );
} else if ( board.isStalemate() ) {
return 0;
} else if ( depth <= 0 ) {
return ( evaluator.evaluate( board ) );
}
int score = Integer.MIN_VALUE + 1;
for ( Move move : board.getValidMoves() ) {
Board child = new Board( board );
child.makeMove( move );
score = -alphaBetaNegamax( child, depth - 1, -beta, -alpha );
if ( score >= beta ) return ( score );
if ( score > alpha ) alpha = score;
}
return ( alpha );
} |
4575a092-a630-4c1f-b959-556055546f8c | 5 | public Locus(String locusName, double position, String[] alleleNames,
PopulationData popdata) {
if (locusName==null || locusName.trim().isEmpty()) {
DecimalFormat fix3 = new DecimalFormat("#0.000");
locusName = fix3.format(position);
} else {
this.locusName = locusName;
}
this.position = position;
this.chrom = null;
alleleName = new String[popdata.founderAlleleCount];
if (alleleNames==null) {
for (int i=0; i<popdata.founderAlleleCount; i++) {
alleleName[i] = ""+i;
}
} else { //copy the correct number of alleleNames
int minn = Math.min(alleleNames.length, this.alleleName.length);
System.arraycopy(alleleNames, 0, this.alleleName, 0, minn);
//add extra alleleNames if list not long enough:
for (int i=minn; i<this.alleleName.length; i++) {
this.alleleName[i] = ""+i;
}
}
} |
7cf293eb-169f-4924-aa36-58ee25a7582c | 4 | public void mouseDragged(MouseEvent arg0) {
// MOUSE_MOVED sluzy do przesuwania wzgledem x, a dragged y
boolean isChanged = false;
int centerX = Application.getWindow().getWidth() / 2
+ Application.getWindow().getXposition();
int centerY = Application.getWindow().getHeight() / 2
+ Application.getWindow().getYposition();
double xChange = arg0.getXOnScreen() - centerX;
double yChange = centerY - arg0.getYOnScreen();
if (xChange != 0) {
_sortedEvents.add(new InputEvent(MouseEvent.MOUSE_MOVED, xChange,
System.currentTimeMillis()));
isChanged = true;
}
if (yChange != 0) {
_sortedEvents.add(new InputEvent(MouseEvent.MOUSE_DRAGGED, yChange,
System.currentTimeMillis()));
isChanged = true;
}
if (isChanged) {
try {
Robot robot = new Robot();
robot.mouseMove(centerX, centerY);
} catch (AWTException e) {
// TODO Auto-generated catch block
}
}
} |
30673c69-463f-4ddd-81ed-09a4f7664611 | 3 | public Scanner(String rootDir, int interval) {
if (StrKit.isBlank(rootDir)) {
throw new IllegalArgumentException("the rootDir can not be blank");
}
this.rootDir = new File(rootDir);
if (!this.rootDir.isDirectory()) {
throw new IllegalArgumentException("the "+rootDir+"is not a directory");
}
if (interval < 0) {
throw new IllegalArgumentException("interval must bigger than zear");
}
this.interval = interval;
} |
9812138b-6a72-4ef5-899e-c32689acb18c | 4 | public void put(final E element) {
int index = 0;
boolean added = false;
while (!added) {
// #1
// To set or not to set...
if (array.getElement(index) == null) {
array.setElement(index, element);
added = true;
currentSize++;
break;
// NO break ! See #3
}
// #2
// Choose between left and right positions, increasing the index
if (array.getElement(index).compareTo(element) > 0) {
index = getLeftChildIndex(index);
} else {
index = getRightChildIndex(index);
}
// #3
// If there is no break in #1 the capacity is increased for the next
// layer due to #2 and new element can be safely added
if (index >= array.getSize()) {
addCapacityLayer();
}
}
rebalance();
} |
a8bfb6ab-0c2b-42f7-b9c1-0626f70757bc | 4 | public Population stochasticUniversalSampling(Population pop, int outSize){
Individual [] subset = new Individual[outSize];
double[] maxFitScores = new double[pop.population.size()];
double populationFitness = pop.calculateTotalFitness();
for (int i = 0; i<pop.population.size(); i++){//calculate the max fitness proportion space for each individual
if(i==0){
maxFitScores[i]=Config.getInstance().calculateFitness(pop.population.get(i))/populationFitness;
}else{
maxFitScores[i]=maxFitScores[i-1]+Config.getInstance().calculateFitness(pop.population.get(i))/populationFitness;
}
}
double index = rand.nextDouble()*(1.0/outSize);//get random start index between 0 and 1/outSize
int i = 0;
int outCount=0;
while (i<pop.population.size()){
if (index<=maxFitScores[i]){
subset[outCount]=pop.population.get(i);
outCount++;
index+=1.0/outSize;
}else{
i++;
}
}
return new Population(subset);
} |
9a2f3a65-a4fe-4f47-b37f-52cbe4d30e9e | 1 | public boolean fromDiscardForReal(Game g, Rack r)
{
int index = indexer.index(g, r);
int newDrawAction = drawStates[index].getBestReward();
if (newDrawAction == 0)
return false;
else
return true;
} |
0ba17ebd-0621-4349-a3f6-7d31a9f351e0 | 7 | public Behavior getSailor()
{
if(affected instanceof PhysicalAgent)
{
PhysicalAgent agent=(PhysicalAgent)affected;
if((sailor == null)||(agent.fetchBehavior("Sailor")!=sailor))
{
final Behavior B=agent.fetchBehavior("Sailor");
if(B!=null)
agent.delBehavior(B);
sailor = CMClass.getBehavior("Sailor");
switch(type)
{
case GUNNER:
sailor.setParms("FIGHTTECH=true FIGHTMOVER=false TICKBONUS="+abilityCode());
break;
case DEFENDER:
sailor.setParms("DEFENDER=true FIGHTMOVER=false FIGHTTECH=false TICKBONUS="+abilityCode());
break;
case BOARDER:
sailor.setParms("BOARDER=true FIGHTMOVER=false FIGHTTECH=false TICKBONUS="+abilityCode());
break;
}
sailor.setSavable(false);
((PhysicalAgent)affected).addBehavior(sailor);
}
}
return sailor;
} |
156ac8df-13ef-4b52-b3b2-cc1ec34e55ec | 1 | public ResponseList<UserList> getLists() {
try {
return getTwitter().getUserLists(-1);
} catch (TwitterException e) {
e.printStackTrace();
return null;
}
} |
e3d0ea11-39ab-4642-bdea-43a15b658dfc | 2 | public Document getDocument() throws Exception {
Document doc = Utilities.createDocument();
Map<String, String> namespaces = this.initializeDocument(doc);
Element root = this.createTransactionElement(doc, namespaces);
Element payloadElem = doc.createElementNS(DEFAULT_NAMESPACE, XMLLabels.ELEM_SERVICE_GETDATABYSUBJECT);
root.appendChild(payloadElem);
Element subjectsElem = doc.createElementNS(DEFAULT_NAMESPACE, XMLLabels.ELEM_SUBJECTIDS);
payloadElem.appendChild(subjectsElem);
for(SubjectID subject : this.subjects) {
Contributor contributor = subject.getContributor();
if(contributor != null) {
Element subjectElem = doc.createElementNS(DEFAULT_NAMESPACE, XMLLabels.ELEM_SUBJECTID);
subjectElem.setTextContent(subject.getValue());
Attr attr = doc.createAttribute(XMLLabels.ATTR_TYPE);
attr.setValue(contributor.getDomain());
subjectElem.setAttributeNodeNS(attr);
subjectsElem.appendChild(subjectElem);
} else {
logger.warn("Unable to add subject \'" + subject.getValue() + "\', due to unknown contributor.");
}
}
this.injectLogs(doc, payloadElem);
this.injectParameters(doc, payloadElem);
return doc;
} |
ea2560e5-0a43-44a4-a5b2-b7af7f52829c | 9 | private void generate(Class c) {
if (generated(c)) {
return;
}
Class super_ = c.getSuperclass();
boolean extendSuper = super_.isAnnotationPresent(GenerateWrapper.class);
if (extendSuper) {
generate(super_);
}
System.out.println("Generating wrapper for: " + c);
String wrapperPackageName = getGeneratedPackageName(c);
String wrapperSimpleName = getGeneratedSimpleName(c);
boolean isAbstract = Modifier.isAbstract(c.getModifiers());
String wrapperClassComment
= "/**\n"
+ " *This is a generated artifact for " + c.getName() + "\n"
+ " */";
String wrapperClassDecl = "public " + (isAbstract ? "abstract" : "") + " class "
+ wrapperSimpleName + (extendSuper ? (" extends " + getGeneratedFullName(super_)) : "");
if (((GenerateWrapper) c.getAnnotation(GenerateWrapper.class)).serializable()) {
wrapperClassDecl += " implements java.io.Serializable ";
}
List<FieldInformation> fieldDecls = new ArrayList<>();
//get the declared fields only.
Field[] declFields = c.getDeclaredFields();
for (Field f : declFields) {
if (Modifier.isFinal(f.getModifiers())
|| Modifier.isStatic(f.getModifiers())
|| f.isAnnotationPresent(Transient.class)) {
continue;
}
fieldDecls.add(getField(f));
}
processSource(wrapperSimpleName, wrapperClassComment, wrapperPackageName, wrapperClassDecl, fieldDecls);
} |
4de97d6c-5be2-43ac-8231-d2edff5bd4c8 | 5 | private boolean findUnexploredCellWithDist(int rowCount, int colCount) {
boolean foundMin = false;
for(int rowID = 0;rowID < rowCount ; rowID++){
for(int colID = 0;colID < colCount;colID++){
for(int drcID = OREITATION_MIN;drcID <= OREITATION_MAX;drcID ++){
if(!explored[rowID][colID][drcID] &&
distance[rowID][colID][drcID] < minDist){
minRowID = rowID;
minColID = colID;
minDrcID = drcID;
minDist = distance[rowID][colID][drcID];
foundMin = true;
}
}//END of loop on orientation
}// END of loop on columns
}//End of loop on rows
return foundMin;
} |
85302df8-e006-46dc-a6a4-6e769b6907c0 | 5 | private boolean existsCellOnOrientaion(Robot robot, Orientation ori,CellState state){
Boolean needExplore = null;
if(robotOnArenaEdge(robot, ori)) return false;
if(ori.equals(Orientation.NORTH)) needExplore = existsCellOnTheNorth(robot,state);
if(ori.equals(Orientation.WEST)) needExplore = existsCellOnTheWest(robot,state);
if(ori.equals(Orientation.SOUTH)) needExplore = existsCellOnTheSouth(robot,state);
if(ori.equals(Orientation.EAST)) needExplore = existsCellOnTheEast(robot,state);
return needExplore;
} |
c40bdecd-777b-4b8c-aec2-8edfb78badf6 | 8 | private void mayor() throws Exception{
op2 = pila.pop();
if (op2.getValor().equals("null"))
throw new Exception("Una de las variables esta sin inicializar!");
op1 = pila.pop();
if (op1.getValor().equals("null"))
throw new Exception("Una de las variables esta sin inicializar!");
Elem resultado = new Elem("boolean");
if(op1.getTipo().equals("boolean"))
{
int b1 = ((Boolean)op1.getValor()).booleanValue() ? 1 : 0;
int b2 = ((Boolean)op2.getValor()).booleanValue() ? 1 : 0;
resultado.setValor(b1 > b2);
}
else if(op1.getTipo().equals("character"))
resultado.setValor((((Character)op1.getValor()).charValue() > ((Character)op2.getValor()).charValue()));
else //Real, Entero o Natural
{
double f1 = op1.getTipo().equals("float")? (Double)op1.getValor() : ((Integer)op1.getValor()).doubleValue();
double f2 = op2.getTipo().equals("float")? (Double)op2.getValor() : ((Integer)op2.getValor()).doubleValue();
resultado.setValor(f1 > f2);
}
pila.push(resultado);
} |
704fcfe3-8647-481e-acef-e16f78afa155 | 7 | public void setManaTypes(String manaTypes) {
if (manaTypes.equals("")) {
this.manaTypes = "";
if (this.cardText.contains("{R}"))
this.manaTypes += "R";
if (this.cardText.contains("{U}"))
this.manaTypes += "U";
if (this.cardText.contains("{B}"))
this.manaTypes += "B";
if (this.cardText.contains("{W}"))
this.manaTypes += "W";
if (this.cardText.contains("{G}"))
this.manaTypes += "G";
if (this.cardText.contains("{1}"))
this.manaTypes += "1";
} else
this.manaTypes = manaTypes;
} |
662a95ae-8e08-4e35-a5ee-541711e9df8d | 9 | private boolean GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a, IntPoint pt2b, final AtomicReference<IntPoint> pt1, final AtomicReference<IntPoint> pt2) {
// precondition: segments are colinear.
if(Math.abs(pt1a.x - pt1b.x) > Math.abs(pt1a.y - pt1b.y)) {
if(pt1a.x > pt1b.x) {
IntPoint t = pt1a;
pt1a = pt1b;
pt1b = t;
}
if(pt2a.x > pt2b.x) {
IntPoint t = pt2a;
pt2a = pt2b;
pt2b = t;
}
if(pt1a.x > pt2a.x)
pt1.set(pt1a);
else
pt1.set(pt2a);
if(pt1b.x < pt2b.x)
pt2.set(pt1b);
else
pt2.set(pt2b);
return pt1.get().x < pt2.get().x;
} else {
if(pt1a.y < pt1b.y) {
IntPoint t = pt1a;
pt1a = pt1b;
pt1b = t;
}
if(pt2a.y < pt2b.y) {
IntPoint t = pt2a;
pt2a = pt2b;
pt2b = t;
}
if(pt1a.y < pt2a.y)
pt1.set(pt1a);
else
pt1.set(pt2a);
if(pt1b.y > pt2b.y)
pt2.set(pt1b);
else
pt2.set(pt2b);
return pt1.get().y > pt2.get().y;
}
} |
ec42e232-bcd5-4176-a0a6-4e05d84481c0 | 6 | public void actionPerformed(ActionEvent e) {
Object s = e.getSource();
if (s instanceof JButton && (JButton)s == clearButton) {
current = "";
textArea.setText(current);
} else if (s instanceof JButton && (JButton)s == sendButton) {
current = textArea.getText();
cc.writeClientCutText(current, current.length());
endDialog();
} else if (s instanceof JButton && (JButton)s == cancelButton) {
endDialog();
}
} |
7c8a1146-16e0-4a81-abc1-81f165821b6f | 4 | public Select tables(String... tables) {
int counter = 0;
//int added = 0;
for (String table : tables) {
if (table != null && !table.isEmpty()) {
if (!table.contains("`")) {
this.tables.add(table);
//added++;
} else {
db.writeError("Skipping table " + table + " in SELECT statement that has backticks.", false);
}
} else {
db.writeError("Skipping table in SELECT statement at position " + counter + " for being null or empty.", false);
}
counter++;
}
return this;
} |
cbad0fc8-d5b7-4060-a3a6-33c5fe847d4c | 8 | public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Constructor<?> c : clazz.getConstructors()) {
Class<?>[] types = toPrimitiveTypeArray(c.getParameterTypes());
if (equalsTypeArray(types, t)) {
return c;
}
}
return null;
} |
4508814d-9c75-4032-9035-bf0ea41f94da | 1 | public ArrayList viewMyBookingPayment() {
ArrayList temp = new ArrayList();
Query q = em.createQuery("SELECT t from BookingEntity t");
for (Object o : q.getResultList()) {
BookingEntity p = (BookingEntity) o;
temp.add(String.valueOf(p.getPayment().getAmountPaid()));
//System.out.println("viewbooking: " + temp.size());
}
return temp;
} |
dd440767-1de0-4afb-bc06-52104b814180 | 7 | protected boolean hasIndirectValueForTargetType(int targetType) {
switch (targetType)
{
case TARGET_TYPE__AWARD:
case TARGET_TYPE__ITEM:
case TARGET_TYPE__NPC_IN_PARTY:
case TARGET_TYPE__NPC_PROFESSION_IN_PARTY:
case TARGET_TYPE__EVENT_AUTONOTE:
case TARGET_TYPE__CLASS:
case TARGET_TYPE__QUEST_BIT:
return true;
default:
return false;
}
} |
26a86ab2-90cf-4631-8c11-8461dac15855 | 7 | public void draw(Graphics2D graphics, int width, int height) {
// Convert text if needed
String drawnText = text;
int start, end;
boolean found;
do {
found = false;
start = drawnText.indexOf("$date{");
if (start != -1) {
end = drawnText.indexOf('}', start);
if (end != -1) {
found = true;
// Parse the date format
String format = drawnText.substring(start + 6, end);
if (format.length() == 0) {
format = "dd-MM-yyyy";
}
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
String dateText = sdf.format(new Date(System.currentTimeMillis()));
drawnText = drawnText.substring(0, start) + dateText + drawnText.substring(end + 1);
} catch (IllegalArgumentException ex) {
}
}
}
} while (found);
// Font
font.apply(graphics);
// Color
graphics.setColor(getColor());
// Calculate the offset to use
int textWidth = graphics.getFontMetrics().stringWidth(drawnText);
int textOffset = 0;
if (align == Align.LEFT) {
textOffset = textWidth;
} else if (align == Align.CENTER) {
textOffset = textWidth / 2;
}
// Draw the text
graphics.drawString(drawnText, posX - textOffset, posY);
} |
3d58d9a1-38e3-48ff-8020-8daa6668ded3 | 0 | @Override
public void startSetup(Attributes atts) {
JCheckBox component = new JCheckBox();
setComponent(component);
super.startSetup(atts);
component.addActionListener(new CheckboxListener(component, getPreference()));
} |
6c86c3b3-3193-4db6-b0a7-2c28cbbae002 | 1 | protected void newPurchaseButtonClicked() {
log.info("New purchase started");
try {
domainController.startNewPurchase();
startNewSale();
} catch (VerificationFailedException e1) {
log.error(e1.getMessage());
}
} |
de901c06-1862-4d7d-b83d-790c01548f8d | 5 | public void charger(Element deSixFace)
{
valeur = Integer.valueOf(deSixFace.getChildText("valeur"));
switch(deSixFace.getChildText("isUtilise")){
case "oui":isUtilise = true;break;
case "non":isUtilise = false;
}
switch(deSixFace.getChildText("couleurDe")){
case "BLANC":couleurDe = CouleurCase.BLANC;break;
case "NOIR":couleurDe = CouleurCase.NOIR;break;
case "VIDE":couleurDe = CouleurCase.VIDE;
}
} |
90d4a498-06e3-43b6-9688-d7793d30a2e6 | 4 | public Neuneu getInstanceNeuneu(String name, Loft loft) {
if(this.getClassNom().equals(Lapin.class.getName())) {
return new Lapin(name, this.energie, this.caseDeplacement, loft);
} else if(this.getClassNom().equals(Cannibale.class.getName())) {
return new Cannibale(name, this.energie, this.caseDeplacement, loft);
} else if(this.getClassNom().equals(Vorace.class.getName())) {
return new Vorace(name, this.energie, this.caseDeplacement, loft);
} else if(this.getClassNom().equals(Erratique.class.getName())) {
return new Erratique(name, this.energie, this.caseDeplacement, loft);
} else {
return new Neuneu(name, this.energie, this.caseDeplacement, loft);
}
} |
5e5e5c7e-34f9-45cc-ae8c-090a5ed26f41 | 9 | public static boolean validDate(String date){
boolean valid = true;
String strDay = date.substring(0,date.indexOf("/"));
date = date.substring(strDay.length() + 1, date.length());
String strMonth = date.substring(0,date.indexOf("/"));
String strYear = date.substring(strMonth.length() + 1, date.length());
int intDay = Integer.valueOf(strDay).intValue();
int intMonth =Integer.valueOf(strMonth).intValue();
int intYear = Integer.valueOf(strYear).intValue();
if(intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) {
if(intDay ==31){
valid = false;
}
}
if(intMonth == 2 ){
if(intYear%4==0){
if(intDay >29){
valid = false;
}
}else if(intDay >28){
valid = false;
}
}
return valid;
} |
2ecafb06-dcc9-4308-b26a-173778866433 | 5 | public static boolean canAccess(String position, String subsystem){
if(position.equals("manager"))
return true;
if(position.equals("pharmacist")&&!subsystem.equals("employee"))
return true;
if(position.equals("tech")&&subsystem.equals("patient"))
return true;
return false;
} |
6c9ed878-a037-4255-9a88-40034c55a466 | 5 | public boolean check_any_marker_at(int[] pos, Colour colour){
boolean bool = false;
int i = 0;
Cell c = world.getCell(pos[0],pos[1]);
if (colour==Colour.RED){
while(!bool && i <6){
bool = c.getRMarker()[i];
i++;
}
}
else{
while(!bool && i <6){
bool = c.getBMarker()[i];
i++;
}
}
return bool;
} |
1007069b-63b7-4b0b-9298-b876f85bc6c2 | 3 | public static Stock QueryOne(String code) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
Stock s = null;
String urlStr = "http://finance.yahoo.com/d/quotes.csv?s=" + code + "&f=nsl1";
try {
url = new URL(urlStr);
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
line = br.readLine();
s = parseStock(line);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException ioe) {
}
}
return s;
} |
ad1fd67d-cad6-4d9e-b528-12a9ee11e9e4 | 5 | @Override
public void validate(Object target, Errors errors) {
GameInfoWrapper gameInfo = (GameInfoWrapper) target;
if(gameInfo.getMaxRounds() > MAX_ROUND_NUM_VALUE) {
errors.rejectValue("maxRounds", "Max.gameInfoWrapper.maxRounds", new Integer[]{MAX_ROUND_NUM_VALUE}, "");
}
if(gameInfo.getMaxRounds() < MIN_ROUND_NUM_VALUE) {
errors.rejectValue("maxRounds", "Min.gameInfoWrapper.maxRounds", new Integer[]{MIN_ROUND_NUM_VALUE}, "");
}
for(String name : gameInfo.getPlayersInfoMap().keySet()) {
if(gameInfo.getPlayersInfoMap().get(name) > MAX_PLAYER_COUNT) {
errors.rejectValue("playersInfoMap", "Max.gameInfoWrapper.playerNumber", new Integer[]{MAX_PLAYER_COUNT}, "");
}
if(gameInfo.getPlayersInfoMap().get(name) < MIN_PLAYER_COUNT) {
errors.rejectValue("playersInfoMap", "Min.gameInfoWrapper.playerNumber", new Integer[]{MIN_PLAYER_COUNT}, "");
}
}
} |
3ea9a8bc-a758-4c9b-8175-efd7c41185be | 7 | public static BufferedImage HistogramEqualization(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[] H = new int[256];
BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
for(int i = 0; i < 256; i++)
H[i] = 0;
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
int pixel = image.getRGB(x, y) & 0x000000FF;
H[pixel] += 1;
}
}
for(int i = 1; i < 256; i++)
H[i] = H[i-1] + H[i];
for(int i = 0; i < 256; i++)
H[i] = H[i]*255/(width*height);
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
int pixel = image.getRGB(x, y) & 0x000000FF;
int result = 0;
int pVal = H[pixel];
result = result | 0xFF000000;
result = result | (pVal << 16);
result = result | (pVal << 8);
result = result | (pVal);
temp.setRGB(x, y, result);
}
}
return temp;
} |
59b76b20-a24a-476c-a612-b5214ba08556 | 4 | private void takeItem(Command command){
if(!command.hasNthWord(2)){
System.out.println("Take what?");
} else {
Item i = rooms.get(currentRoom).removeItem(command.getNthSegment(1));
if(i == null){
System.out.println("There is no " + command.getNthSegment(1));
} else if(i.getName().equals("key")){
hasKey = true;
System.out.println("You found the key to the final floor");
} else if(!bag.addItem(i)){
rooms.get(currentRoom).addItem(i);
System.out.println("That is too heavy to carry");
} else {
System.out.println("You take the " + i.getName());
}
}
} |
97fe255b-4854-41a1-952c-3d06cc9c4cef | 5 | public static boolean valida_contrasenia(String contraseniaUno, String contraseniaDos) {
String contrasenia_pat = "^[^';]+$";
if (contraseniaUno == null || contraseniaDos == null) {
return false;
}
return contraseniaUno.matches(contrasenia_pat) && contraseniaUno.length() >= 5 && contraseniaUno.length() <= 15
&& contraseniaUno.equals(contraseniaDos);
} |
14b1b85a-9c7d-4fc0-a0ff-3ff126b815c6 | 5 | private boolean valid() {
if (actors == null) {
return false;
}
if ((spawningPositions == null) || (spawningPositions.size() < 1)) {
return false;
}
if (name == null) {
return false;
}
if (skybox == null) {
return false;
}
return true;
} |
e5863082-b5e3-40da-aa67-6ff35506618c | 2 | @Override
public double getAverageClientWaitTime() {
int clients = 0;
int totalWaitTime = 0;
for(int i = 0; i < cashiers; i++){
for(int j = 0; j < lines[i].size(); j++){
clients++;
totalWaitTime += lines[i].get(j).getExpectedServiceTime();
}
}
return totalWaitTime/clients;
} |
f418e5c4-389d-46c7-84dd-a45ccc286e67 | 3 | @Override
public int stepThrough() {
if(ptr==0){
if(isCompileClicked()){
setCompileClicked(false);
this.setViewToDefault();
}
else{
refreshOutputs();
this.setViewToDefault();
}
this.runner = new Runner(this.compiler);
}
else {
this.runner = new Runner(this.compiler, this.sim40, this.errorStream, this.stdStream);
}
ptr = this.runner.stepthrough(ptr);
if(this.runner.isProgramTerminated()) {
this.controller.setButtonsEnabled(false);
}
this.sim40 = this.runner.getSimulator();
this.errorStream = this.runner.getErrorStream();
this.stdStream = this.runner.getStdStream();
return this.sim40.lines[linePtr];
} |
d3ef802e-8f27-4f5c-8bcf-2f496a087683 | 0 | @Override
public void execute(VirtualMachine vm) {
DebuggerVirtualMachine dvm = (DebuggerVirtualMachine) vm;
dvm.setFunctionInfo(functionName, startLineNumber, endLineNumber);
} |
b15034e8-8968-4863-b1da-a9fff1cf00e9 | 0 | public remove()
{
this.requireLogin = true;
this.info = "remove an appointment";
this.addParamConstraint("id", ParamCons.INTEGER);
this.addRtnCode(405, "appointment not found");
this.addRtnCode(406, "permission denied");
this.addRtnCode(407, "illegal time");
} |
c2452787-fd5b-4ea7-b6fe-cb1b5df1b816 | 9 | public boolean isCheckMate() {
if (
(this.board.getBlackTime() == 0 || this.board.getWhiteTime() == 0) &&
this.hasTimer()
) {
this.cancelTimer();
return true;
}
boolean possibleCheckmate = false;
for (Piece p : this.board.getPieces()) {
if (p.isWhite() == this.board.isWhiteTurn()) {
if (!p.getPossibleTiles(this.board).isEmpty()) {
return false;
}
if (p instanceof King) {
King k = (King) p;
possibleCheckmate = k.inCheck(this.board);
}
}
}
if (possibleCheckmate && this.hasTimer()) {
this.cancelTimer();
}
return possibleCheckmate;
} |
83ed230e-8c09-4cca-a7fe-c8642866b551 | 5 | public boolean hitSquare(){
World myWorld = getWorld();
int x = getX();
int y = getY();
switch(direction) {
case SOUTH :
y++;
break;
case EAST :
x++;
break;
case NORTH :
y--;
break;
case WEST :
x--;
break;
}
List<Square> ofSquares = myWorld.getObjectsAt( x, y, Square.class );
if( !ofSquares.isEmpty() ){
return true;
}
else{
return false;
}
} |
f980ce79-f259-434d-aefa-b08659075f99 | 6 | private int getMaxidUsuario(){
int max = 0;
try {
conn = PaginaWebConnectionFactory.getInstance().getConnection();
String sql = "select MAX(id_usuario) as maximo from usuario";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()){
max = rs.getInt("maximo");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if (conn != null)
conn.close();
if (ps != null)
ps.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return max;
} |
eb237b0b-42ec-4334-8320-0843b9bd548d | 7 | @Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if(!sender.hasPermission(pluginMain.pluginManager.getPermission("thf.ban"))){
sender.sendMessage(ChatColor.DARK_RED + "You cannot BAN ME!");
return true;
}
if(args.length == 0){
sender.sendMessage(ChatColor.DARK_AQUA + "You need arguments! Argue!");
return true;
}
if(args.length == 1){
Player player = Bukkit.getPlayer(args[0]);
if(player == null){
sender.sendMessage(ChatColor.DARK_RED + "FAIL! /ban [Player] [Reason]");
return true;
}
if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.ban.exempt"))){
sender.sendMessage(ChatColor.DARK_RED + "He can't be banned! Noooooooo!");
return true;
}
player.kickPlayer("[THF] you have been banned by " + sender.getName());
pluginMain.getConfig().set("banned." + player.getName(), "[THF] you have been banned by " + sender.getName());
pluginMain.saveConfig();
}else{
Player player = Bukkit.getPlayer(args[0]);
if(player == null){
sender.sendMessage(ChatColor.DARK_RED + "There not here!");
return true;
}
if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.ban.exempt"))){
sender.sendMessage(ChatColor.DARK_RED + "You can't ban me! I'm exempt!");
return true;
}
player.kickPlayer(ChatColor.stripColor("[THF] Banned: " + convertArgs(args)));
pluginMain.getConfig().set("banned." + player.getName(), "[THF] Banned: " + convertArgs(args));
}
return true;
} |
0a15a9b0-b154-4bad-85fd-8e60403a1950 | 6 | @EventHandler
public void SnowmanJump(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.getsnowgolemConfig().getDouble("Snowman.Jump.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getsnowgolemConfig().getBoolean("Snowman.Jump.Enabled", true) && damager instanceof Snowman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, plugin.getsnowgolemConfig().getInt("Snowman.Jump.Time"), plugin.getsnowgolemConfig().getInt("Snowman.Jump.Power")));
}
} |
5a0cdf2b-644a-486e-8d08-eac068f23761 | 1 | private static void setEmptyTile(TileType[][] data, int x, int y, TileType type) {
if (data[x][y] == TileType.NONE)
data[x][y] = type;
} |
15eaf6da-feb2-45ba-a4d0-e4560d983deb | 5 | private int stripMultipartHeaders(ByteBuffer b, int offset) {
int i;
for (i = offset; i < b.limit(); i++) {
if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') {
break;
}
}
return i + 1;
} |
a1dab3e2-8961-468d-b22e-596652766028 | 7 | public void updateItems()
{
try
{
String strResult = ""+(char)6,
strStore;
int i;
Item itmStore;
LifoQueue qStore;
Iterator iter=vctItems.keySet().iterator();
while(iter.hasNext())
{
qStore = (LifoQueue)vctItems.get(iter.next());
if (qStore.size() > 0)
{
itmStore = (Item)qStore.firstElement();
if(itmStore.isArmor())
{
strResult += (2+itmStore.intKind)+"\n";
}else if (itmStore.isWeapon())
{
strResult += "1\n";
}else
{
strResult += "0\n";
}
strResult += itmStore.strName+"\n";
}
}
strResult += ".\n";
send(strResult);
if (engGame.overMerchant(intLocX,intLocY)!= null)
updateSell();
if (engGame.overPlayerMerchant(intLocX,intLocY)!= null)
updateSell();
}catch(Exception e)
{
engGame.log.printError("updateItems():"+strName+" disconnected", e);
blnStopThread = true;
}
blnShouldSave = true;
} |
5a8f1aaf-f2a3-47fb-89e6-1b90dda78aad | 7 | protected boolean checkXObstacle(CommonObject so, double time) {
return (((this.currentCoord.getX() + this.currentWidth + currentHorizontalSpeed * time >= so.getCurrentCoordinates().getX()
&& currentHorizontalSpeed > 0 && this.currentCoord.getX() < so.getCurrentCoordinates().getX())
|| ((this.currentCoord.getX() + currentHorizontalSpeed * time <= so.getCurrentCoordinates().getX() + so.getLength())
&& currentHorizontalSpeed < 0 && this.currentCoord.getX() + this.currentWidth >= so.getCurrentCoordinates().getX() + so.getLength()))
&& (this.currentCoord.getY() + this.currentHeight > so.getCurrentCoordinates().getY())
&& (this.currentCoord.getY() < so.getCurrentCoordinates().getY() + so.getHeight()));
} |
7f99f9fa-8fe5-47a3-94cf-a3e17efabb6a | 9 | public void setStatge(int stageID, Map<String, String> data) {
if(this.mouseListener != null){
gamePanel.removeMouseListener(this.mouseListener);
}
startedLoadingTime = System.nanoTime();
if (stage != null) {
Stage s = stage;
stage = null;
s.close();
}
if (stageID == STAGE_WELCOME) {
stage = new StageWelcome(this, data);
} else if (stageID == STAGE_MENUE) {
stage = new StageMenue(this, data);
} else if (stageID == STAGE_LEVEL) {
stage = new StageLevel(this, data);
} else if (stageID == STAGE_SHOP) {
stage = new StageShop(this, data);
} else if (stageID == STAGE_SHOP_BACKGROUNDS) {
stage = new StagShopBackgrounds(this, data);
} else if (stageID == STAGE_SHOP_PLAYER) {
stage = new StagShopPlayer(this, data);
} else if (stageID == STAGE_LEVELEDITOR) {
stage = new StageLevelEditor(this, data);
}
System.out.println("[StageManager] Stage " + stageID + " took " + ((double) (System.nanoTime() - startedLoadingTime) / 1000000000)
+ " Seconds to load!");
} |
cecd7814-90f8-4cd8-8e71-b5b7eea55528 | 6 | public static int getStateMetric(State s) {
switch(STATE_METRIC) {
case DIV:
return (((s.rngState>>16)&0x3F)<<8) + ((s.rngState>>22)&0xFF);
case DSum:
return (((s.rngState>>8)&0xFF) + (s.rngState&0xFF))&0xFF;
case RNG:
return s.rngState & 0xFFFF;
case RNG1:
return s.rngState & 0xFF;
case RNG2:
return (s.rngState >> 8) & 0xFF;
case RANDOM:
default:
return (int)(Math.random()*0x100);
}
} |
4ca3204b-6b66-474a-b944-3e42b05dfebe | 6 | @Test
public void testServerClientDisconnectWithHash() {
LOGGER.log(Level.INFO, "----- STARTING TEST testServerClientDisconnectWithHash -----");
String client_hash = "";
String server_hash = "";
server1.setUseDisconnectedSockets(true);
try {
server1.startThread();
} catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) {
exception = true;
}
waitListenThreadStart(server1);
try {
client_hash = server2.addSocket("127.0.0.1");
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadAddNotEmpty(server2);
waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED);
waitSocketThreadAddNotEmpty(server1);
server_hash = getServerLastSocketHash(server1);
waitSocketThreadState(server1, server_hash, SocketThread.CONFIRMED);
try {
server2.close();
} catch (IOException | ServerSocketCloseException | TimeoutException e) {
exception = true;
}
waitServerState(server2, Server.CLOSED);
boolean loop = true;
Timing new_timer = new Timing();
while (loop) {
if (!server1.getDisconnectedSockets().isEmpty() || new_timer.getTime() > timeout) {
loop = false;
}
}
Assert.assertFalse(server1.getDisconnectedSockets().isEmpty(), "Hash not added to disconnected_sockets");
Assert.assertFalse(exception, "Exception found");
Assert.assertEquals(server1.getDisconnectedSockets().get(0), server_hash, "Disconnected sockets hash not logged");
LOGGER.log(Level.INFO, "----- TEST testServerClientDisconnectWithHash COMPLETED -----");
} |
a8bb4e2b-f4ef-4d84-b47e-ec37586129a0 | 9 | @Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Tag)) {
return false;
}
Tag o = (Tag) obj;
if (getId() != o.getId()) {
return false;
}
if (name == null && o.name != null || name != null && o.name == null) {
return false;
}
if (name != null && !name.equals(o.name)) {
return false;
}
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.