method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
1435efcb-9777-45b7-a634-fa72e1671cf3 | 0 | @Override
@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 1)
public String toString() {
return "Overriden toString method";
} |
3693fe91-4fb2-4efd-b4ab-c06e298fd77c | 9 | @Override
public boolean takeControl() {
double distance = Sputnik.opp.getPose().distanceTo(new Point(0, 0));
Thread.yield();
// System.out.println("distance: " + distance);
if (Localizing.cornerCount != 2) {
return false;
}
if (Sputnik.robotMap.getHeading() == 0
|| Sputnik.robotMap.getHeading() == 2) {
if (distance > Sputnik.intersectionDistance_height) {
return true;
}
}
if (Sputnik.robotMap.getHeading() == 1
|| Sputnik.robotMap.getHeading() == 3) {
if (distance > Sputnik.intersectionDistance_width) {
return true;
}
}
if (PathSweeping.intersection && Localizing.cornerCount == 2) {
return true;
}
return false;
} |
458aad3c-8a4f-41bf-8575-e496556a17cf | 4 | private void applyBackgrounds(Human actor) {
Background root = vocation ;
if (birth == null) {
final Batch <Float> weights = new Batch <Float> () ;
for (Background v : Background.OPEN_CLASSES) {
weights.add(ratePromotion(root, actor)) ;
}
birth = (Background) Rand.pickFrom(
Background.OPEN_CLASSES, weights.toArray()
) ;
}
if (homeworld == null) {
final Batch <Float> weights = new Batch <Float> () ;
for (Background v : Background.ALL_PLANETS) {
weights.add(ratePromotion(root, actor)) ;
}
homeworld = (Background) Rand.pickFrom(
Background.ALL_PLANETS, weights.toArray()
) ;
}
applyVocation(homeworld, actor) ;
applyVocation(birth , actor) ;
applyVocation(vocation , actor) ;
setupAttributes(actor) ;
} |
661236b3-bc38-4aa3-bbb4-495ac8241748 | 1 | private void createMenuOptions() {
String gameFontName = Configuration.GUI.Fonts.BUTTON_FONT;
// Load all of the game graphics from the GUI congfiguration
GameGraphic normalGraphic = GameAssetManager.getInstance().getObject(GameGraphic.class, Configuration.GUI.Graphics.GRAPHIC_BUTTON_NORMAL);
GameGraphic hoverGraphic = GameAssetManager.getInstance().getObject(GameGraphic.class, Configuration.GUI.Graphics.GRAPHIC_BUTTON_HOVER);
GameGraphic focusGraphic = GameAssetManager.getInstance().getObject(GameGraphic.class, Configuration.GUI.Graphics.GRAPHIC_BUTTON_FOCUS);
/**
* Calculate the target locations for the menu, and apply the settings
*/
verticalMenuSpacing = 20;
menuWidth = (int) normalGraphic.getWidth();
menuHeight = (int) normalGraphic.getHeight();
// Automatically position everything
menuStartYPos = (GameSettings.getGameHeight() / 2) - (((options.length - 1) * (menuHeight + menuHeight)) / 2);
endLocationX = GameSettings.getGameWidth() / 2 - menuWidth / 2;
menuVelocity = 15;
String fontName = Configuration.GUI.Fonts.BUTTON_FONT;
String menuName = null, menuLinksTo = null;
/**
* Iterate through each menu item and set the location to be below
* eachother with a spacing of verticalMenuSpacing
*/
for (int i = 0, x = -menuWidth, y = menuStartYPos + menuHeight + verticalMenuSpacing; i < options.length; i++, y += menuHeight + verticalMenuSpacing) {
menuName = options[i][0];
menuLinksTo = options[i][1];
GameButtonGraphical button = new GameButtonGraphical(Helpers.concat(menuName, "-", menuLinksTo),
GameAssetManager.getInstance().getClonedObject(GameFont.class, fontName), menuName, x, y,
normalGraphic, hoverGraphic, focusGraphic) {
@Override
public void mousePressed() {
super.mousePressed();
// Instead of using the name we could also have passed in
// the linkTo name in the constructor
GameEngine.getGameScreenManager().setGameScreen(getName().substring(getName().indexOf("-") + 1));
}
};
menuOptions.add(button);
}
} |
13693249-ce33-435d-b515-5c431997c4ff | 8 | private Object getMenu(Object component, Object part,
boolean forward, boolean popup) {
Object previous = null;
for (int i = 0; i < 2; i++) { // 0: next to last, 1: first to previous
for (Object item = (i == 0) ? get(part, ":next") :
get(popup ? get(component, "menu") : component, ":comp");
(i == 0) ? (item != null) : (item != part); item = get(item, ":next")) {
if ((getClass(item) != "separator") && getBoolean(item, "enabled", true)) {
if (forward) { return item; }
previous = item;
}
}
}
return previous;
} |
585e7304-79a1-424b-a03f-5da9db4ef7f6 | 4 | @Test
public void testEmptyArray() {
Conversions.debug = debug;
double[] arr = Conversions.convert("{}", double[].class);
Assert.assertTrue(arr != null && arr.length == 0);
arr = Conversions.convert(" { } ", double[].class);
Assert.assertTrue(arr != null && arr.length == 0);
arr = Conversions.convert(" {} ", double[].class);
Assert.assertTrue(arr != null && arr.length == 0);
arr = Conversions.convert(" {} \n", double[].class);
Assert.assertTrue(arr != null && arr.length == 0);
} |
b8d8f2c0-9c6d-459e-879c-1ad15f91ae2d | 6 | public void run() {
try {
InetAddress ipAddress = clientSocket.getInetAddress();
String remoteIP = ipAddress.getHostAddress();
player.setIPAddress(remoteIP);
if (!(player.getIPAddress().equals(null))) {
System.out.println("Player IP is: " + player.getIPAddress());
}
OutputStream registerStartOutput = clientSocket.getOutputStream();
new PrintWriter(registerStartOutput).println(ProtocolConstants.REGISTER_START);
BufferedReader registrationStringReader = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println(registrationStringReader.readLine());
String input = registrationStringReader.readLine();
while (input == null) {
input = registrationStringReader.readLine();
}
InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
player.setTeamName(receiveTeamInfo(stream).getTeamName().toString());
player.setTeamColor(receiveTeamInfo(stream).getColorHex().toString());
if (!(player.getTeamName().equals("") && player.getTeamColor().equals(""))) {
System.out.print("Player team name is: " + player.getTeamName());
System.out.print("Player color is: " + player.getTeamColor());
}
// registrationStringReader.close();
// stream.close();
OutputStream registerEndOutput = clientSocket.getOutputStream();
new PrintWriter(registerEndOutput).println(ProtocolConstants.REGISTER_END);
registerEndOutput.close();
System.out.println("Ended Registration. Closing Socket.");
clientSocket.close();
if (clientSocket.isClosed()) {
System.out.println("Socket closed");
}
} catch (IOException e) {
// report exception somewhere.
e.printStackTrace();
}
} |
d17b7736-d301-4739-ac97-8967c82b60a2 | 3 | public static String encodeFromFile( String filename )
{
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
length += numBytes;
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e )
{
System.err.println( "Error encoding from file " + filename );
} // end catch: IOException
finally
{
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile |
01a673b1-9a0e-40cb-82b6-f99199cab73c | 7 | public static String cppUnpointerizeNativeType(String nativetype) {
{ int length = nativetype.length();
{ int i = Stella.NULL_INTEGER;
int iter000 = 1;
int upperBound000 = length;
boolean unboundedP000 = upperBound000 == Stella.NULL_INTEGER;
loop000 : for (;unboundedP000 ||
(iter000 <= upperBound000); iter000 = iter000 + 1) {
i = iter000;
switch (nativetype.charAt((length - i))) {
case ' ':
case '\t':
case '\n':
case '\r':
continue loop000;
case '*':
return (Native.string_subsequence(nativetype, 0, length - i));
default:
break loop000;
}
}
}
return (nativetype);
}
} |
a064c104-86d6-4c2d-b7ff-4f9f1e78435a | 4 | public NewVariableEditor() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("Create new variable");
setBounds(100, 100, 450, 235);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
JLabel lblName = new JLabel("Name");
lblName.setBounds(10, 11, 46, 14);
contentPanel.add(lblName);
nameField = new JTextField();
nameField.setBounds(10, 36, 86, 20);
contentPanel.add(nameField);
nameField.setColumns(10);
rdbtnString = new JRadioButton("String");
rdbtnString.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(rdbtnString.isSelected()) {
spinner.setEnabled(false);
textField_1.setEnabled(true);
chckbxTrue.setEnabled(false);
spinner_1.setEnabled(false);
} else
textField_1.setEnabled(false);
}
});
buttonGroup.add(rdbtnString);
rdbtnString.setSelected(true);
rdbtnString.setBounds(10, 63, 97, 23);
contentPanel.add(rdbtnString);
JLabel lblValue = new JLabel("Value:");
lblValue.setBounds(10, 93, 46, 14);
contentPanel.add(lblValue);
textField_1 = new JTextField();
textField_1.setBounds(10, 118, 86, 20);
contentPanel.add(textField_1);
textField_1.setColumns(10);
rdbtnInteger = new JRadioButton("Integer");
rdbtnInteger.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(rdbtnInteger.isSelected()) {
spinner.setEnabled(true);
textField_1.setEnabled(false);
chckbxTrue.setEnabled(false);
spinner_1.setEnabled(false);
} else
spinner.setEnabled(false);
}
});
buttonGroup.add(rdbtnInteger);
rdbtnInteger.setBounds(109, 63, 97, 23);
contentPanel.add(rdbtnInteger);
spinner = new JSpinner();
spinner.setEnabled(false);
spinner.setModel(new SpinnerNumberModel(new Integer(0), null, null, new Integer(1)));
spinner.setBounds(109, 118, 86, 20);
contentPanel.add(spinner);
JLabel lblValue_1 = new JLabel("Value:");
lblValue_1.setBounds(109, 93, 46, 14);
contentPanel.add(lblValue_1);
rdbtnBoolean = new JRadioButton("Boolean");
rdbtnBoolean.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(rdbtnBoolean.isSelected()) {
spinner.setEnabled(false);
textField_1.setEnabled(false);
chckbxTrue.setEnabled(true);
spinner_1.setEnabled(false);
} else
chckbxTrue.setEnabled(false);
}
});
buttonGroup.add(rdbtnBoolean);
rdbtnBoolean.setBounds(208, 64, 97, 23);
contentPanel.add(rdbtnBoolean);
chckbxTrue = new JCheckBox("True");
chckbxTrue.setEnabled(false);
chckbxTrue.setBounds(208, 89, 97, 23);
contentPanel.add(chckbxTrue);
rdbtnFloat = new JRadioButton("Float");
rdbtnFloat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnFloat.isSelected()) {
spinner.setEnabled(false);
textField_1.setEnabled(false);
chckbxTrue.setEnabled(true);
spinner_1.setEnabled(true);
} else
spinner_1.setEnabled(false);
}
});
buttonGroup.add(rdbtnFloat);
rdbtnFloat.setBounds(309, 62, 86, 25);
contentPanel.add(rdbtnFloat);
JLabel lblValue_2 = new JLabel("Value:");
lblValue_2.setBounds(309, 94, 46, 14);
contentPanel.add(lblValue_2);
spinner_1 = new JSpinner();
spinner_1.setEnabled(false);
spinner_1.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1)));
spinner_1.setBounds(309, 119, 86, 20);
contentPanel.add(spinner_1);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveVariable();
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setModalityType(ModalityType.APPLICATION_MODAL);
setVisible(true);
} |
8732501b-bed2-4062-986a-3df1a4325a0b | 6 | public CodeMap42 set(final int index, final int value) {
int[][] map2;
if ((index >>> 16) != 0) {
if (map == null)
map = new int[MAX_INDEX][][][];
final int i0 = index >>> 24;
int[][][] map1 = map[i0];
if (map1 == null)
map[i0] = map1 = new int[MAX_INDEX][][];
final int i1 = (index >>> 16) & 0xff;
map2 = map1[i1];
if (map2 == null)
map1[i1] = map2 = new int[MAX_INDEX][];
} else
map2 = map200;
final int i2 = (index >>> 8) & 0xff;
int[] map3 = map2[i2];
if (map3 == null) {
map2[i2] = map3 = new int[MAX_INDEX];
for (int i = 0; i < MAX_INDEX; ++i)
map3[i] = NOT_FOUND;
}
map3[index & 0xff] = value;
return this;
} |
00adb2cf-597a-4336-b8d2-53d6d707c4c4 | 4 | @EventHandler
public void onInventoryClose( InventoryCloseEvent e ){
Player p = (Player) e.getPlayer();
if( p.getInventory().getChestplate() != null ){
if (String.valueOf(p.getInventory().getChestplate().getItemMeta().getLore()).contains("Life Touch III")) {
p.setHealthScale(32);
} else if (String.valueOf(p.getInventory().getChestplate().getItemMeta().getLore()).contains("Life Touch II")) {
p.setHealthScale(28);
} else if (String.valueOf(p.getInventory().getChestplate().getItemMeta().getLore()).contains("Life Touch I")) {
p.setHealthScale(24);
}
}
} |
97b6f539-75a6-4d73-a2ad-57b5ff0d4dbc | 9 | private void merge(T[] arValues, int left, int middle, int right) {
//
int nrTimes = (right - left) + 1;
//
int leftMoves = left;
T leftValue = null;
//
int middleMoves = middle + 1;
T middleValue = null;
Vector<T> arTemp = new Vector<T>(nrTimes);
for (int i = 0; i < nrTimes; i++) {
this.incOperations();
if (leftMoves <= middle) {
leftValue = arValues[leftMoves];
}
if (middleMoves <= right) {
middleValue = arValues[middleMoves];
}
if ((leftValue != null) && (middleValue == null)) {
arTemp.add(i, leftValue);
leftMoves++;
leftValue = null;
}
else if ((leftValue == null) && (middleValue != null)) {
arTemp.add(i, middleValue);
middleMoves++;
middleValue = null;
}
else if (leftValue.compareTo(middleValue) > 0) {
arTemp.add(i, leftValue);
leftMoves++;
leftValue = null;
}
else {
arTemp.add(i, middleValue);
middleMoves++;
middleValue = null;
}
}
// Transfer the sorted elements to the original array.
for (int i = 0; i < nrTimes; i++) {
this.incOperations();
arValues[left + i] = arTemp.get(i);
}
} |
1483eab3-91a2-4b3f-83a1-8ab41de6964c | 5 | public boolean hasChanged()
{
if(parent != null && parent.hasChanged())
return true;
if(!pos.equals(oldPos))
return true;
if(!rot.equals(oldRot))
return true;
if(!scale.equals(oldScale))
return true;
return false;
} |
c30ae8ba-43c8-44a9-97a6-3891f02f4b02 | 6 | public Move makeMove()
{
Move move;
//Keep looping and getting moves 'till we get a valid move
while (true)
{
move = getMove();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//If we're trying to move from positions that are actually in the board
if (!(move.getA().isOutOfBounds() || move.getB().isOutOfBounds()))
{
//If we're trying to move a non-existent piece
if (board.getBoard()[move.getA().getRow()][move.getA().getCollumn()] != null)
{
//If we're trying to move a piece that isn't ours
if (board.getBoard()[move.getA().getRow()][move.getA().getCollumn()].getColor() == this.color)
{
//Is the move valid?
if (PieceCanMove(board.getBoard()[move.getA().getRow()][move.getA().getCollumn()], move, board))
{
System.out.println("Move is valid, hooraayy!");
return move;
}
}
else
{
System.out.println("Sorry, that piece is not yours to move");
}
}
else
{
System.out.println("Sorry, there is no piece in the specified starting position");
}
}
else
{
System.out.println("Sorry, the position isn't within the board");
}
System.out.println("You must re-enter your move");
System.out.println(board.toString());
}
} |
b861bd59-dc1e-4200-9bf9-082860c17558 | 6 | public static boolean isValid(JsonNode track) {
LOG.debug("Checking validity of track : \n" + track);
boolean result = false;
if (track == null)
LOG.warn("Track is invalid: null.");
else if (!track.hasNonNull(ARTIST))
LOG.warn("Track is invalid: no artist attribute.");
else if (!track.get(ARTIST).has(TEXT_KEY))
LOG.warn("Track is invalid: artist had no text.");
else if (!track.hasNonNull(NAME))
LOG.warn("Track is invalid: no name attribute.");
else if (!track.hasNonNull(ALBUM))
LOG.warn("Track is invalid: no album attribute.");
else if (!track.get(ALBUM).has(TEXT_KEY))
LOG.warn("Track is invalid: album had no text.");
else {
result = true;
LOG.debug("Given track is valid.");
}
return result;
} |
d3821ca7-0c88-407f-ab59-31c4a4608178 | 2 | public void addIload(int n) {
if (n < 4)
addOpcode(26 + n); // iload_<n>
else if (n < 0x100) {
addOpcode(ILOAD); // iload
add(n);
}
else {
addOpcode(WIDE);
addOpcode(ILOAD);
addIndex(n);
}
} |
2caa8a86-4896-4813-9097-0b343979bfd0 | 7 | public NodeInfoDialog(GUI p, Node n){
super(p, "Edit Node "+n.ID, true);
GuiHelper.setWindowIcon(this);
parent = p;
node = n;
node.highlight(true);
this.setLayout(new BorderLayout());
JPanel nodeSelAndPosition = new JPanel();
nodeSelAndPosition.setLayout(new BorderLayout());
JPanel nodeSel = new JPanel();
//evaluate whether a node is the first or the last in the enumeration and thus has no
//previous respective next element.
boolean hasPrev = false;
Enumeration<Node> nodesEnumer = Runtime.nodes.getNodeEnumeration();
while(nodesEnumer.hasMoreElements()){
Node nd = nodesEnumer.nextElement();
if(nd.ID == n.ID){
if(!nodesEnumer.hasMoreElements()){
nextNode.setEnabled(false);
}
prevNode.setEnabled(hasPrev);
break;
}
hasPrev = true;
}
prevNode.addActionListener(this);
nodeNumber.setColumns(6);
nodeNumber.setValue(new Integer(node.ID));
nodeNumber.addPropertyChangeListener("value", this);
nextNode.addActionListener(this);
nodeSel.add(prevNode);
nodeSel.add(nodeNumber);
nodeSel.add(nextNode);
this.add(nodeSel);
Position pos = node.getPosition();
positionX.setText(String.valueOf(pos.xCoord));
positionY.setText(String.valueOf(pos.yCoord));
positionZ.setText(String.valueOf(pos.zCoord));
JPanel position = new JPanel();
position.setBorder(BorderFactory.createTitledBorder("Position"));
position.setLayout(new BoxLayout(position, BoxLayout.Y_AXIS));
position.setPreferredSize(new Dimension(80, 80));
position.add(positionX);
position.add(positionY);
if(Configuration.dimensions == 3){
position.add(positionZ);
}
nodeSelAndPosition.add(BorderLayout.NORTH, nodeSel);
nodeSelAndPosition.add(BorderLayout.SOUTH, position);
this.add(BorderLayout.NORTH, nodeSelAndPosition);
JPanel info = new JPanel();
info.setBorder(BorderFactory.createTitledBorder("Node Info"));
info.setLayout(new BoxLayout(info, BoxLayout.Y_AXIS));
this.add(BorderLayout.CENTER, info);
JPanel infoPanel = new JPanel();
NonRegularGridLayout nrgl = new NonRegularGridLayout(6, 2, 5, 5);
nrgl.setAlignToLeft(true);
infoPanel.setLayout(nrgl);
info.add(infoPanel);
UnborderedJTextField typeLabel = new UnborderedJTextField("Node Implementation:", Font.BOLD);
implementationText.setText(Global.toShortName(node.getClass().getName()));
implementationText.setEditable(false);
infoPanel.add(typeLabel);
infoPanel.add(implementationText);
UnborderedJTextField connectivityLabel = new UnborderedJTextField("Node Connectivity:", Font.BOLD);
connectivityText.setText(Global.toShortName(node.getConnectivityModel().getClass().getName()));
connectivityText.setEditable(false);
infoPanel.add(connectivityLabel);
infoPanel.add(connectivityText);
UnborderedJTextField interferenceLabel = new UnborderedJTextField("Node Interference:", Font.BOLD);
interferenceText.setText(Global.toShortName(node.getInterferenceModel().getClass().getName()));
interferenceText.setEditable(false);
infoPanel.add(interferenceLabel);
infoPanel.add(interferenceText);
UnborderedJTextField mobilityLabel = new UnborderedJTextField("Node Mobility:", Font.BOLD);
mobilityText.setText(Global.toShortName(node.getMobilityModel().getClass().getName()));
mobilityText.setEditable(false);
infoPanel.add(mobilityLabel);
infoPanel.add(mobilityText);
UnborderedJTextField reliabilityLabel = new UnborderedJTextField("Node Reliability:", Font.BOLD);
reliabilityText.setText(Global.toShortName(node.getReliabilityModel().getClass().getName()));
reliabilityText.setEditable(false);
infoPanel.add(reliabilityLabel);
infoPanel.add(reliabilityText);
infoText.setText(node.toString());
JLabel infoTextLabel = new JLabel("Info Text:");
infoText.setEditable(false);
infoText.setBackground(infoTextLabel.getBackground());
infoPanel.add(infoTextLabel);
infoPanel.add(infoText);
JPanel buttons = new JPanel();
ok.addActionListener(this);
buttons.add(ok);
cancel.addActionListener(this);
buttons.add(cancel);
this.add(BorderLayout.SOUTH, buttons);
WindowListener listener = new WindowAdapter(){
public void windowClosing(WindowEvent event){
node.highlight(false);
parent.redrawGUI();
}
};
this.addWindowListener(listener);
this.setResizable(true);
this.getRootPane().setDefaultButton(ok);
// Detect ESCAPE button
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
focusManager.addKeyEventPostProcessor(new KeyEventPostProcessor() {
public boolean postProcessKeyEvent(KeyEvent e) {
if(!e.isConsumed() && e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_ESCAPE) {
node.highlight(false);
NodeInfoDialog.this.setVisible(false);
parent.redrawGUINow(); // needs blocking redrawing
}
return false;
}
});
//Redraw the graph to have the selected node painted in the right color.
parent.redrawGUI();
this.pack();
this.setLocationRelativeTo(p);
this.setVisible(true);
} |
58c84e3a-6438-4af4-a645-ac209d9ec3c6 | 3 | public void addRulesInTable() {
try {
RulesManager.getInstance().loadRules(MainClass.RULES_DIR);
} catch (Exception ex) {
Logger.getLogger(NBFrame.class.getName()).log(Level.SEVERE, null, ex);
return;
}
DefaultTableModel model = (DefaultTableModel) tableRules.getModel();
int rows = model.getRowCount();
for (int i = rows - 1; i >= 0; i--) {
model.removeRow(i);
}
for (Rule r : RulesManager.getInstance().getRulesList()) {
model.addRow(new Object[]{(Boolean) r.isIsEnabled(), (String) r.getRuleName(), (String) r.getRuleURL(), (String) r.getRuleRegExpr()});
}
} |
58691845-bde7-46cc-8302-5e1f6afd5607 | 2 | public int sum (List<Integer> a){
if (a.size() > 0) {
int sum = 0;
for (Integer i : a) {
sum += i;
}
return sum;
}
return 0;
} |
c1d2e87a-dc3f-4d9f-9c2d-e67ca65de167 | 8 | @Override
public void keyReleased(KeyEvent event) {
int key = event.getKeyCode();
if(key == KeyEvent.VK_UP){
if(screen.checkRotate(current, currentCol, currentRow, orientation)) {
screen.removePiece(current, currentCol, currentRow, orientation);
orientation = (orientation+1)%4;
screen.addPiece(current, currentCol, currentRow, orientation);
}
screen.paintScreen();
} else if(key == KeyEvent.VK_DOWN){
if(screen.validate(current, currentCol, currentRow + 1, orientation)) {
screen.moveDown(current, currentCol, currentRow++, orientation);
}
screen.repaint();
} else if(key == KeyEvent.VK_LEFT) {
if(screen.checkLeft(current, currentCol, currentRow, orientation)){
screen.removePiece(current, currentCol, currentRow, orientation);
screen.moveLeft(current, currentCol--, currentRow, orientation);
}
screen.repaint();
} else if(key == KeyEvent.VK_RIGHT){
if(screen.checkRight(current, currentCol, currentRow, orientation)) {
screen.removePiece(current, currentCol, currentRow, orientation);
screen.moveRight(current, currentCol++, currentRow, orientation);
}
screen.repaint();
}
repaint();
} |
01853c69-895c-4ef5-b3a9-2473dca94bf2 | 3 | public static void IfCheatMessage() {
for (int i = 0; i < playerInventory.length; i++) {
Item playerInventoryVariable = playerInventory[i];
if (playerInventoryVariable != null) {
if (playerInventory[i].getId() == 5) {
System.out
.println(" How to Become Immortal");
System.out
.println("You cannot defeat the Witch with low health, you need health potions."
+ "\n"
+ "Go to the potion Room, and steal the container full of health potions. Each potion gives a 125 boost."
+ "\n" + "Press P to Drink the potion.");
System.out.println();
System.out
.println(" Secrets of attacking Monsters");
System.out
.println("You cannot attack anything unless you have a weapon, there is a sharp sword in the armory"
+ "\n"
+ "Aquire it so you may kill some monsters. The sword's power will increase with each strike by 10 points"
+ "\n"
+ "Hint1: If you kill the ghoul in the dungeon, your strength damage will increase by 25 points"
+ "\n"
+ "Hint2: If you kill the giant cat in the cellar below the dungeon your strength damage will increase by 75"
+ "\n"
+ "Hint3: Kill The witch to win the Game"
+ "\n" + "Good Luck on your mission!");
System.out.println();
}
}
}
System.out.println("You do not have the cheat sheet.");
} |
635966d5-ada7-449d-9ad6-935d7aa21c1c | 5 | @Override
public void tick(PlayField field) {
// super.tick(field);
xVel = xVel + xAcc / 10.F;
x += xVel;
if (x < width / 2) {
x = width / 2;
}
if (x > Game.WIDTH - width / 2) {
x = Game.WIDTH - width / 2;
}
y += yVel;
xVel = xVel / friction;
yVel = yVel / friction;
if (x <= 0 || x >= Game.WIDTH || y < -2) {
field.destroyEntity(this);
}
doCollision(field);
} |
1751e6a3-0d88-449c-9ce9-cabfe66c18e3 | 7 | public double calcMoment(String whichMoment){
Stack<Point> blob_copy = new Stack<Point>();
blob_copy.addAll(blob);
double moment = 0;
// NOTE: This code will only work with Java SE 7. Strings in
// switch statements were not supported in JDK<=6, apparently.
while (!blob_copy.empty()){
Point point = blob_copy.pop();
switch (whichMoment) {
case "M1": moment += point.weight(); break;
case "Mx": moment += point.x() * point.weight(); break;
case "My": moment += point.y() * point.weight(); break;
case "Mxx": moment += Math.pow(point.x(), 2) * point.weight(); break;
case "Myy": moment += Math.pow(point.y(), 2) * point.weight(); break;
case "Mxy": moment += point.x() * point.y() * point.weight(); break;
}
}
return moment;
} |
48b37552-73ea-4cf7-bac2-214aaae4ec96 | 1 | private String calc(String input) {
//Person 2 put your implementation here
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
int num = Math.abs(rand.nextInt()%input.length());
sb.append(input.charAt(num));
}
return sb.toString();
} |
2e5d018c-9a8a-4faf-991e-c1a22e7513e0 | 2 | public void StartCallTime()
{
callTimeTask = new TimerTask() {
@SuppressWarnings("deprecation")
public void run() {
second++;
if(second==60) {minute++;second=0;}
if(minute==60) {hour++;minute=0;}
time.setHours(hour);
time.setMinutes(minute);
time.setSeconds(second);
label1.setText("Время разговора: "+dateFormate.format(time));
container.validate();
container.repaint();
}
};
hour=0;minute=0;second=0;
callTimer.schedule(callTimeTask, 0, 1000);
} |
4ccacb33-51c3-4fdd-a8dc-a8765a6cd536 | 7 | public void createLifeForm(int x, int y, LifeForms lifeForm)
{
//System.out.println("Creating " + lifeForm.name());
boolean[][] pattern = PATTERNS[lifeForm.ordinal()];
int patternHeight = pattern.length,
patternWidth = pattern[0].length;
for (int i = 0; i < patternHeight; i++)
{
if ((y + i) > 0 && (y + i) < height)
{
for (int j = 0; j < patternWidth; j++)
{
if ((x + j) > 0 && (x + j) < width && pattern[i][j])
grid[y + i][x + j] = ALIVE;
}
}
}
} |
6abf1cbd-97ac-46d4-8fc6-b663b4641ab2 | 7 | public int generateTreshold(){
Collections.sort(valuesFaces);
int[] treshold = new int[2];
int countDownToUp = 0;
int countUpToDown = 0;
for(int i = 0; i < valuesFaces.size(); i++){
if(valuesFaces.get(i).face){
countDownToUp++;
} else {
if(i > 0){
treshold[0] = (valuesFaces.get(i).value - valuesFaces.get(i - 1).value) /2 + valuesFaces.get(i - 1).value;
}
break;
}
}
for(int i = valuesFaces.size() - 1; i >=0; i--){
if(valuesFaces.get(i).face){
countUpToDown++;
} else {
if(i < valuesFaces.size() - 1){
treshold[1] = (valuesFaces.get(i + 1).value - valuesFaces.get(i).value) /2 + valuesFaces.get(i).value;
}
break;
}
}
if(countDownToUp > countUpToDown){
this.polarity = 1;
this.treshold = treshold[0];
} else {
this.polarity = -1;
this.treshold = treshold[1];
}
return this.treshold;
} |
23e3e472-e9c4-4d08-a86b-54c424e4e556 | 2 | public GeneratorWebClient() {
isRunning = false;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
panel.setBackground(Color.LIGHT_GRAY);
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblMinimumSupportLevel = new JLabel("Minimum Support Level");
lblMinimumSupportLevel.setBounds(10, 11, 202, 43);
lblMinimumSupportLevel.setFont(new Font("Tahoma", Font.PLAIN, 18));
panel.add(lblMinimumSupportLevel);
JLabel lblNewLabel = new JLabel("Minimum Confidence Level");
lblNewLabel.setBounds(10, 60, 232, 41);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
panel.add(lblNewLabel);
mslTextField = new JTextField();
mslTextField.setText("0.0");
mslTextField.setFont(new Font("Tahoma", Font.PLAIN, 18));
mslTextField.setBounds(270, 23, 86, 31);
panel.add(mslTextField);
mslTextField.setColumns(10);
mclTextField = new JTextField();
mclTextField.setText("0.0");
mclTextField.setFont(new Font("Tahoma", Font.PLAIN, 18));
mclTextField.setBounds(270, 72, 86, 29);
panel.add(mclTextField);
mclTextField.setColumns(10);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 296, 370, 245);
panel.add(scrollPane);
final JTextPane textPane = new JTextPane();
scrollPane.setViewportView(textPane);
textPane.setEditable(false);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(394, 296, 370, 245);
panel.add(scrollPane_1);
final JTextPane textErrorPane = new JTextPane();
scrollPane_1.setViewportView(textErrorPane);
textErrorPane.setEditable(false);
JLabel lblInputFile = new JLabel("Input Transaction File");
lblInputFile.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblInputFile.setBounds(10, 109, 202, 36);
panel.add(lblInputFile);
JLabel lblOutputRuleFile = new JLabel("Output Rule File");
lblOutputRuleFile.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblOutputRuleFile.setBounds(10, 151, 157, 32);
panel.add(lblOutputRuleFile);
inputText = new JTextField();
lblInputFile.setLabelFor(inputText);
inputText.setFont(new Font("Tahoma", Font.PLAIN, 18));
inputText.setBounds(270, 112, 327, 33);
panel.add(inputText);
inputText.setColumns(10);
outputRuleText = new JTextField();
lblOutputRuleFile.setLabelFor(outputRuleText);
outputRuleText.setFont(new Font("Tahoma", Font.PLAIN, 18));
outputRuleText.setBounds(270, 154, 327, 29);
panel.add(outputRuleText);
outputRuleText.setColumns(10);
JButton btnPressMe = new JButton("Perform Apriori");
JButton btnReset = new JButton("Reset");
btnReset.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
inputText.setText("");
outputRuleText.setText("");
outputErrorText.setText("");
mslTextField.setText("0.0");
mclTextField.setText("0.0");
textPane.setText("");
textErrorPane.setText("");
textPane.repaint();
textErrorPane.repaint();
//outputDialog(textPane);
//outputErrorDialog(textErrorPane);
}
});
btnPressMe.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
inputFilePath = inputText.getText();
outputErrorFilePath = outputErrorText.getText();
outputRuleFilePath = outputRuleText.getText();
msl = Double.parseDouble(mslTextField.getText());
mcl = Double.parseDouble(mclTextField.getText());
//ClientResource clientResource = new ClientResource("http://localhost:8111/");
//TransactionSetResource proxy = clientResource.wrap(TransactionSetResource.class);
///proxy.store(transSet);
//newTransSet = proxy.retrieve();
if(isRunning == false){
isRunning = true;
thread = new Thread() {
public void run() {
//Function for what happens after mouse click
if(formatFilePaths()){
ClientResource clientResource = new ClientResource("http://localhost:8111/");
GeneratorResource proxy = clientResource.wrap(GeneratorResource.class);
System.out.println("IN IF of format file paths");
System.out.println(inputFilePath);
System.out.println(outputErrorFilePath);
System.out.println(outputRuleFilePath);
runTest(inputFilePath, outputRuleFilePath, msl, mcl, clientResource, proxy);
outputDialog(textPane);
//outputRuleDialog(textPane);
outputErrorDialog(textErrorPane);
isRunning = false;
}
}
};
thread.start();
}
}
});
btnPressMe.setBounds(100, 251, 139, 33);
btnReset.setBounds(500, 251, 139, 33);
panel.add(btnPressMe);
panel.add(btnReset);
JLabel lblOutputErrorFile = new JLabel("Output Error File");
lblOutputErrorFile.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblOutputErrorFile.setBounds(10, 197, 157, 32);
panel.add(lblOutputErrorFile);
outputErrorText = new JTextField();
lblOutputErrorFile.setLabelFor(outputErrorText);
outputErrorText.setFont(new Font("Tahoma", Font.PLAIN, 18));
outputErrorText.setColumns(10);
outputErrorText.setBounds(270, 200, 327, 29);
panel.add(outputErrorText);
} |
3645b886-143e-40f2-ac3d-40ef41b34faf | 0 | public void setAppPackageName(String appPackageName) {
this.appPackageName = appPackageName;
} |
3fc4b214-4649-4ee9-b700-d40e553b312f | 1 | private Node<T> setToNext(Node<T> node, T item) {
if (node.next != null) {
setToNext(node.next, item);
}
Node<T> nextNode = new Node<T>(null, item);
node.next = nextNode;
return nextNode;
} |
234e43e1-42bc-4209-9767-99731225d60c | 5 | @Override
public Set<int[]> threshold(int thresh) throws IllegalStateException {
if(!isDone) throw new IllegalStateException("accumulate() must be called before threshold(int)");
Set<int[]> circles = new HashSet<int[]>();
for(int r = 0; r < acc.length; ++r) {
for(int x = 0; x < acc[r].length; ++x) {
for(int y = 0; y < acc[r][x].length; ++y) {
if(acc[r][x][y] >= thresh) circles.add(new int[]{r +minR, x, y});
}
}
}
return circles;
} |
454f1d2d-9cdc-4d39-b3a9-b7f435a9cf97 | 8 | private int valorMax( Partida partida, EstatPartida estat_partida, int alfa, int beta, EstatCasella estat_casella,
int profunditat, int profunditat_maxima, EstatCasella fitxa_jugador )
{
Tauler tauler = partida.getTauler();
if ( profunditat == profunditat_maxima || estat_partida == EstatPartida.GUANYA_JUGADOR_A ||
estat_partida == EstatPartida.GUANYA_JUGADOR_B || estat_partida == EstatPartida.EMPAT )
{
return funcioAvaluacio( tauler, estat_partida, profunditat, fitxa_jugador );
}
else
{
int mida = tauler.getMida();
for ( int fila = 0; fila < mida; ++fila )
{
for ( int columna = 0; columna < mida; ++columna )
{
try
{
tauler.mouFitxa( estat_casella, fila, columna );
}
catch ( IllegalArgumentException excepcio )
{
continue;
}
EstatPartida estat_partida_aux = partida.comprovaEstatPartida( fila, columna );
estat_casella = intercanviaEstatCasella( estat_casella );
alfa = Math.max( alfa,
this.valorMin( partida, estat_partida_aux, alfa, beta, estat_casella, ( profunditat + 1 ),
profunditat_maxima, fitxa_jugador ) );
tauler.treuFitxa( fila, columna );
if ( alfa >= beta )
{
return beta;
}
estat_casella = intercanviaEstatCasella( estat_casella );
}
}
return alfa;
}
} |
3f918c4a-c085-499e-ad43-4e9280e0425f | 2 | @Override
public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
Contexto oContexto = (Contexto) request.getAttribute("contexto");
oContexto.setVista("jsp/mensaje.jsp");
HiloBean oHiloBean = new HiloBean();
HiloDao oHiloDao = new HiloDao(oContexto.getEnumTipoConexion());
String fecha = "";
ArrayList<String> titulo = new ArrayList<>();
titulo.add("Hilo50");
titulo.add("Hilo51");
titulo.add("Hilo82");
titulo.add("Hilo53");
titulo.add("Hilo74");
titulo.add("Hilo530");
titulo.add("Hilo450");
titulo.add("Hilo70");
SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
fecha = ("2013-10-25");
int index;
String nombre;
Iterator<String> iterador = titulo.listIterator();
Random generator;
while (iterador.hasNext()) {
nombre = iterador.next();
generator = new Random();
index = generator.nextInt(titulo.size());
oHiloBean.setId(0);
oHiloBean.setNombre(nombre);
oHiloBean.setFecha(oSimpleDateFormat.parse(fecha));
try {
oHiloDao.set(oHiloBean);
} catch (Exception e) {
throw new ServletException("HiloController: Update Error: Phase 2: " + e.getMessage());
}
}
return "OK- información generada.";
} |
1a69140c-c87e-47a0-ba32-40acfbb5f8fc | 8 | public String execute() throws CitysearchException {
log.info("Start review action");
reviewRequest.setAdUnitName(CommonConstants.AD_UNIT_NAME_REVIEW);
if (reviewRequest.getAdUnitSize() == null
|| reviewRequest.getAdUnitSize().trim().length() == 0) {
reviewRequest.setAdUnitSize(CommonConstants.MANTLE_AD_SIZE);
reviewRequest.setDisplaySize(CommonConstants.MANTLE_DISPLAY_SIZE);
}
if (reviewRequest.getDisplaySize() == null
|| reviewRequest.getDisplaySize() == 0) {
reviewRequest.setDisplaySize(CommonConstants.MANTLE_DISPLAY_SIZE);
}
try {
AbstractReviewFacade facade = ReviewFacadeFactory.getFacade(
reviewRequest.getPublisher(), getResourceRootPath(),
reviewRequest.getDisplaySize());
review = facade.getLatestReview(reviewRequest);
if (review == null) {
log.info("Returning backfill from review");
getHttpRequest().setAttribute(REQUEST_ATTRIBUTE_BACKFILL, true);
getHttpRequest().setAttribute(REQUEST_ATTRIBUTE_ADUNIT_SIZE,
reviewRequest.getAdUnitSize());
getHttpRequest().setAttribute(
REQUEST_ATTRIBUTE_ADUNIT_DISPLAY_SIZE,
reviewRequest.getDisplaySize());
getHttpRequest().setAttribute(REQUEST_ATTRIBUTE_LATITUDE,
reviewRequest.getLatitude());
getHttpRequest().setAttribute(REQUEST_ATTRIBUTE_LONGITUDE,
reviewRequest.getLongitude());
getHttpRequest().setAttribute(REQUEST_ATTRIBUTE_BACKFILL_FOR,
CommonConstants.AD_UNIT_NAME_REVIEW);
return "backfill";
}
log.info("End review action");
} catch (InvalidRequestParametersException ihre) {
log.error(ihre.getDetailedMessage());
houseAds = getHouseAds(reviewRequest.getDartClickTrackUrl(), 3);
} catch (Exception cse) {
log.error(cse.getMessage());
StackTraceElement[] elms = cse.getStackTrace();
for (int k = 0; k < elms.length; k++) {
log.error(elms[k]);
}
houseAds = getHouseAds(reviewRequest.getDartClickTrackUrl(), 3);
}
return Action.SUCCESS;
} |
75af09a6-0b1d-4b5f-8d42-05346156a6cf | 5 | public void refresh() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
content.removeAllChildren();
Enumeration<TreePath> paths = tree.getExpandedDescendants(tree.getPathForRow(0));
for(DialogCategory category : editor.controller.categories.values()){
DefaultMutableTreeNode parent = new DialogNode(category);
content.add(parent);
for(Dialog dialog : category.dialogs.values()){
DefaultMutableTreeNode child = new DialogNode(dialog);
parent.add(child);
for(DialogOption option : dialog.getOptions().values()){
child.add(new DialogNode(option));
}
}
}
DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
model.reload();
if(paths != null){
while(paths.hasMoreElements()){
TreePath path = paths.nextElement();
tree.expandPath(path);
}
}
}
});
} |
49c5b714-9c65-475a-bfa6-71235f5ed039 | 2 | public static String[] removeDuplicateStrings(String[] array) {
if (isEmpty(array)) {
return array;
}
Set<String> set = new TreeSet<String>();
for (String element : array) {
set.add(element);
}
return toStringArray(set);
} |
59e07572-6044-457a-b4fe-2cedcae473e3 | 1 | void doRun() throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_NUM);
for (int i = 0; i < THREAD_NUM; i++) {
Node n = new Node(threadPool);
threadPool.submit(n);
}
} |
3dba7fc1-674f-4c99-ac13-8616f2fc9e3a | 6 | public Node search(Problem problem, State initialState) {
// Make a node with the initial problem state
Node firstNode= new Node(initialState);
// Insert node into the frontier data structure
List<Node> frontier= new ArrayList<Node>();
frontier.add(firstNode);
// (Variables needed later on)
List<Node> successorNodes= null;
boolean solutionFound= false;
// WHILE final state not found AND frontier is NOT empty DO
while(!solutionFound && !frontier.isEmpty()){
// Remove first node from the frontier
firstNode= frontier.remove(0);
// IF node contains final state
if(problem.isFinalState(firstNode.getState()))
// THEN final state found
solutionFound= true;
// IF node does not contain final state
else
{
// EXPAND node's state
successorNodes = expand(firstNode, problem);
// Insert successor nodes into the frontier
if(successorNodes != null && !successorNodes.isEmpty())
frontier.addAll(successorNodes);
// Sort frontier in ascending order of f(n)
Collections.sort(frontier);
}
}
// IF final state found THEN return sequence of actions found
// ELSE return "solution not found"
return solutionFound ? firstNode : null;
} |
da60cc26-e9ca-44d4-9649-75b1e23e1f8c | 2 | public void visitNewMultiArrayExpr(final NewMultiArrayExpr expr) {
print("new " + expr.elementType());
if (expr.dimensions() != null) {
for (int i = 0; i < expr.dimensions().length; i++) {
print("[" + expr.dimensions()[i] + "]");
}
}
} |
d28573c5-3949-4d46-b0d1-2d211e0ed388 | 1 | public boolean maximumHuntersReached() {
if (world.getHunterList().size()<=10)
return false;
else
return true;
} |
1874875f-bde6-4436-a226-c2e145b6c4af | 4 | @Override
public void build(String dictName) {
BufferedReader reader = null;
StringBuffer stringBuffer = null;
String string = null;
try {
reader = new BufferedReader(new FileReader(new File(dictName)));
string = reader.readLine();
while (string != null) {
stringBuffer = new StringBuffer(string);
// System.out.println("read: " + stringBuffer);
while (stringBuffer.length() > 0) {
insert(stringBuffer.toString() + '$');
symbolAccount++;
stringBuffer.deleteCharAt(0);
}
string = reader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
8fc7bd9c-b036-4957-82fe-dee8490adcd2 | 6 | public synchronized int setTemplateDirectory(File dir) {
if (dir!=null && dir.isDirectory()) {
this.directory = dir;
File[] files = dir.listFiles(new XMLFileFilter());
int newCount = files==null ? 0 : files.length;
int oldCount = templates.size();
List temp = new ArrayList(oldCount+newCount);
temp.addAll(templates);
for (int i=0; i<newCount; i++) {
try {
XMLDecoder d = new XMLDecoder(new BufferedInputStream(
new FileInputStream(files[i])));
Object obj = d.readObject();
if (!(obj instanceof CodeTemplate)) {
throw new IOException("Not a CodeTemplate: " +
files[i].getAbsolutePath());
}
temp.add(obj);
d.close();
} catch (/*IO, NoSuchElement*/Exception e) {
// NoSuchElementException can be thrown when reading
// an XML file not in the format expected by XMLDecoder.
// (e.g. CodeTemplates in an old format).
e.printStackTrace();
}
}
templates = temp;
sortTemplates();
return getTemplateCount();
}
return -1;
} |
59e39069-ac8d-4682-927d-8d653b409351 | 5 | public void addBlocks(int b) {
debug("Adding " + b + " blocks to the game");
if (reset) {
debug("Blocks not added, middle of reset");
return;
}
int bS;
int rS;
int c = 0;
for (int i = 0; i < b; i++) {
bS = this.getBlueScoreFromBlocks();
rS = this.getRedScoreFromBlocks();
if (bS == rS) {
if (new Random().nextInt(1) == 1) {
addBlockToBlue();
} else {
addBlockToRed();
}
c++;
continue;
} else if (bS > rS) {
addBlockToRed();
c++;
continue;
} else {
addBlockToBlue();
c++;
continue;
}
}
debug("Added " + c + " blocks to the game");
} |
703ec9f7-1aac-4684-bcea-22b67f9dd427 | 5 | public void calcAdjacencies() {
adjMtx = new HashMap<Integer, LinkedList<Integer>>();
for(int i = 0; i < NUMBEROFSPACES; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
if(i > 3) {
temp.add(i - 4);
}
if(i % 4 != 0) {
temp.add(i - 1);
}
if(i % 4 != 3) {
temp.add(i + 1);
}
if(i < 12) {
temp.add(i + 4);
}
adjMtx.put(i, temp);
}
} |
1dc6c4f1-9b86-438a-b62c-4c7a08373771 | 2 | public void imprimir(Object[][] h) {
for (int i = 0; i < h.length; i++) {
for (int j = 0; j < h[0].length; j++) {
System.out.print(h[i][j] + " ");
}
System.out.println("");
}
} |
fa3c02d0-f463-4855-80b1-c9e066eb530d | 2 | public void affiche(){
if(this.catalogue.size() < 1)
System.out.println("Aucune questions...");
else{
for(int i=0; i < this.catalogue.size(); i++){
System.out.print("["+i+"] => ");
this.catalogue.get(i).affiche();
}
}
} |
08388e8b-a17c-450c-b686-ca065510256d | 1 | @SuppressWarnings({ "rawtypes", "unchecked" })
public JList getFontSizeList()
{
if (fontSizeList == null)
{
fontSizeList = new JList(this.fontSizeStrings);
fontSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fontSizeList.addListSelectionListener(
new ListSelectionHandler(getFontSizeTextField()));
fontSizeList.setSelectedIndex(0);
fontSizeList.setFont(DEFAULT_FONT);
fontSizeList.setFocusable(false);
}
return fontSizeList;
} |
026c2423-5998-4b6c-aaed-95e2d7f05c54 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ServicePK other = (ServicePK) obj;
if (client == null) {
if (other.client != null)
return false;
} else if (!client.equals(other.client))
return false;
if (serviceProvider == null) {
if (other.serviceProvider != null)
return false;
} else if (!serviceProvider.equals(other.serviceProvider))
return false;
return true;
} |
54f73dd5-03b1-456e-bf68-6cba4fadcbc1 | 5 | public static int[] getShortestEdge(int[][] nabomatrise, ArrayList<Integer> noder) {
int[] shortest = new int[] {-1, INF};
for (int fra = 0; fra < noder.size() ;fra++ ) {
for (int til = 0; til < nabomatrise.length; til++) {
int w = nabomatrise[noder.get(fra)][til];
if(w != INF && w < shortest[1] && !noder.contains(til)) {
shortest[0] = til;
shortest[1] = w;
}
}
}
return shortest;
} |
b045da91-84df-4935-ad3c-269b062a63a1 | 8 | public void putAll( Map<? extends Byte, ? extends Integer> map ) {
Iterator<? extends Entry<? extends Byte,? extends Integer>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Byte,? extends Integer> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} |
91416b3b-5d9e-46f5-9271-98baec8d1b08 | 1 | public static Connection connection(Server server, String dbName) {
Connection result = null;
try {
result = DriverManager.getConnection(server.getUrl(dbName), server.getUser(), server.getPassword());
logger.debug(result);
} catch (SQLException e) {
logger.error("Error in get connection for Server:" + server.getId() + " Database:" + dbName);
logger.error(e);
}
return result;
} |
6b212e97-e62b-46d8-b135-5edaabcaa9a2 | 1 | public static int randomized_partiton(int[] array, int start, int end){
Random r = new Random();
int a = r.nextInt(end);
while(a < start){
a = r.nextInt(end);
}
exchange(array,a,end);
return partition(array,start,end);
} |
9cc5710e-1d45-4df6-9856-45ac25a5c0cf | 7 | public static boolean joinGuild(String[] args, CommandSender s){
//Various checks
if(Util.isBannedFromGuilds(s) == true){
//Checking if they are banned from the guilds system
s.sendMessage(ChatColor.RED + "You are currently banned from interacting with the Guilds system. Talk to your server admin if you believe this is in error.");
return false;
}
if(!s.hasPermission("zguilds.player.join")){
//Checking if they have the permission node to proceed
s.sendMessage(ChatColor.RED + "You lack sufficient permissions to invite anyone to a guild. Talk to your server admin if you believe this is in error.");
return false;
}
if(Util.isInGuild(s) == true){
//Checking if they're already in a guild, dont let them join this one if so
s.sendMessage(ChatColor.RED + "You're already in a guild, you can't join a new one. Leave your old one first.");
return false;
}
if(args.length > 2 || args.length == 1){
//Checking if the create command has proper args
s.sendMessage(ChatColor.RED + "Incorrectly formatted guild join command! Proper syntax is: \"/guild join GuildName\"");
return false;
}
if(Main.guilds.getConfigurationSection("Guilds." + args[1].toLowerCase()) == null){
//Checking if that guild already exists
s.sendMessage(ChatColor.RED + "That guild doesn't exist. They must have disbanded before you accepted the invite.");
return false;
}
sendersPlayerName = s.getName().toLowerCase();
guildInvitedToInputted = args[1].toLowerCase();
sendersCurrentGuildInvitation = Main.players.getString("Players." + sendersPlayerName + ".Current_Invitation");
if(guildInvitedToInputted.matches(sendersCurrentGuildInvitation) == false){
//checking if their current guild invite matches the guild they put in their arg
s.sendMessage(ChatColor.RED + "You aren't currently invited to a guild called " + guildInvitedToInputted + ". If you are supposed to be, tell the guild leader of that guild to invite you.");
return false;
}
now = new Date();
date = now.toString();
currRosterSize = Main.guilds.getInt("Guilds." + guildInvitedToInputted + ".Roster_Size");
updRosterSize = currRosterSize + 1;
sendersTargetGuildNewMemberStartingRank = Main.guilds.getInt("Guilds." + guildInvitedToInputted + ".New_Member_Starting_Rank");
Main.players.set("Players." + sendersPlayerName + ".Current_Guild", guildInvitedToInputted);
Main.players.set("Players." + sendersPlayerName + ".Member_Since", date);
Main.players.set("Players." + sendersPlayerName + ".Guild_Leader", false);
Main.players.set("Players." + sendersPlayerName + ".Current_Rank", sendersTargetGuildNewMemberStartingRank);
Main.players.set("Players." + sendersPlayerName + ".Current_Invitation", "N/A");
Main.guilds.set("Guilds." + guildInvitedToInputted + ".Roster_Size", updRosterSize);
Main.saveYamls();
s.sendMessage(ChatColor.DARK_GREEN + "You joined the guild " + ChatColor.RED + guildInvitedToInputted + ChatColor.DARK_GREEN + "!");
return true;
} |
7d3d6348-af4e-4ad8-b2ab-9975437d6d4f | 0 | public String getText() {
return text;
} |
d90358ca-3eb4-47e2-8790-a8def13c3828 | 6 | public void setString() {
// An input window asking for a string
String txt = JOptionPane.showInputDialog("Ange en text med bokstäver, siffror och tecken");
// An array of Array7x7 object to hold characters.
// The size of the array must be at least 5.
if (txt.length() < 4) {
txtArray = new Array7x7[5];
} else {
// The last position in array shall contain a space sign
txtArray = new Array7x7[txt.length() + 1];
}
// Inserts the graphical counterpart for each character
// If the string is less than 4 it will be filled with space up to the
// fifth position.
if (txt.length() < 4) {
for (int i = 0; i < txt.length(); i++) {
txtArray[i] = new Array7x7(ArrayChars.getChar(txt.charAt(i)).getArray());
}
for (int j = txt.length(); j < txtArray.length; j++) {
txtArray[j] = new Array7x7(ArrayChars.getChar(' ').getArray());
}
} else {
for (int i = 0; i < txtArray.length; i++) {
txtArray[i] = new Array7x7(ArrayChars.getChar(txt.charAt(i)).getArray());
// Last position will contain a space sign
if (i == txtArray.length - 2) {
txtArray[i + 1] = new Array7x7(ArrayChars.getChar(' ').getArray());
i++;
}
}
}
} |
2264b689-4254-4d57-a744-2e9344e47eee | 1 | public String toString() {
if (instance == null)
return "new " + type;
else
return instance.toString();
} |
405ec273-c002-46f9-a1a9-8e8e89a5c003 | 4 | public boolean getButton(int which, int id){
switch(which){
case 1:
return leftDriveJoy.getRawButton(id);
case 2:
return rightDriveJoy.getRawButton(id);
case 3:
return leftJoy.getRawButton(id);
case 4:
return rightJoy.getRawButton(id);
}
return false;
} |
76821b0c-6d61-4e27-9847-a62a3ab9d867 | 4 | private void handleProcessClear(){
for(int i:processesMap.keySet()){
if((processesMap.get(i).getStatus() == Status.FINISHED.toString()) ||
(processesMap.get(i).getStatus() == Status.FAILED.toString())){
Message msg = new Message(Message.msgType.COMMAND);
msg.setCommandId(CommandType.REMOVEPROC);
msg.setProcessId(i);
int workerId = processesMap.get(i).getWorkerId();
try{
processServerMap.get(workerId).sendToWorker(msg);
}catch(IOException e){
System.out.println("remove Command sent failed, remove worker "+workerId);
removeNode(workerId);
}
processesMap.remove(i);
}
}
} |
bfc05b9d-471c-4254-a976-11211c85593b | 0 | public void lastStep(Context ctx) {
ctx.setState(new FirstState());
} |
0703d7dd-d28e-4f34-bc53-8f62310aa3e2 | 8 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!(myHost instanceof MOB))
return super.okMessage(myHost,msg);
final MOB myChar=(MOB)myHost;
if((msg.amISource(myChar))
&&(msg.sourceMinor()==CMMsg.TYP_CAST_SPELL)
&&(!CMLib.flags().isGood(myChar))
&&((msg.tool()==null)||((CMLib.ableMapper().getQualifyingLevel(ID(),true,msg.tool().ID())>0)
&&(myChar.isMine(msg.tool()))))
&&(CMLib.dice().rollPercentage()>myChar.charStats().getStat(CharStats.STAT_WISDOM)*2))
{
myChar.location().show(myChar,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> watch(es) <S-HIS-HER> angry god absorb <S-HIS-HER> magical energy!"));
return false;
}
return super.okMessage(myChar, msg);
} |
4fd4819f-eef1-4914-8469-51eddb525efe | 7 | @Override
public void actionPerformed(ActionEvent e) {
if (e == null || e.getSource() == clearButton) {
currState = game.getInitialState();
currState.rollDice();
}
else if (!game.isTerminal(currState)) {
if (e.getSource() == proposeButton) { //AI moves piece
proposeMove();
}
else if (e.getSource() instanceof GridElement) { //try to move a piece
GridElement el = (GridElement) e.getSource();
currState = game.getResult(currState, el.location, false);
}
else if (e.getSource() instanceof DieElement) { //select a different Die
DieElement el = (DieElement) e.getSource();
if (el.dieNumber != currState.getSelectedDie()) currState.changeSelectedDie();
}
}
repaint();
updateStatus();
} |
39893b17-ed44-4d9c-b19e-4ebdfbdd9213 | 6 | public static TreeSet<IdInt> topListInt(String baseFilename, int numVertices, final int topN) throws IOException{
final TreeSet<IdInt> topList = new TreeSet<IdInt>(new Comparator<IdInt>() {
public int compare(IdInt a, IdInt b) {
if (a.vertexId == b.vertexId) return 0;
return (a.value > b.value ? -1 : (a.value == b.value ? (a.vertexId < b.vertexId ? -1 : 1) : 1)); // Descending order
}
});
VertexAggregator.foreach(numVertices, baseFilename, new IntConverter(), new ForeachCallback<Integer>() {
IdInt least;
public void callback(int vertexId, Integer vertexValue) {
if (topList.size() < topN) {
topList.add(new IdInt(vertexId, vertexValue));
least = topList.last();
} else {
if (vertexValue > least.value) {
topList.remove(least);
topList.add(new IdInt(vertexId, vertexValue));
least = topList.last();
}
}
}
}
);
return topList;
} |
76dfda67-bad7-4c40-9597-ef18eaae14e0 | 1 | private void resize(int n) {
Type[] newArray = (Type[]) new Object[n];
for (int i = 0; i < size; i++) {
newArray[i] = stack[i];
}
stack = newArray;
} |
c8a08cb9-bf23-4af1-b259-833584595274 | 9 | public boolean isBlocked(Location l, boolean playersBlock){
if (playersBlock)
{
//Return true if occupied by any player
for (Player player : players)
{
if (l.equals(player.getLocation()))
return true;
}
}
//Return true if the location is beyond the edge of the map
if(l.getX() >= MAX_X || l.getX() < 0 || l.getY() >= MAX_Y || l.getY() < 0){
return true;
}
//Return true if the location is blocked
for(int i = 0; i < blockedLocs.size(); i++){
if(l.equals(blockedLocs.get(i))){
return true;
}
}
//Otherwise return false
return false;
} |
9553e0cb-6f47-4f78-a3f7-31831ea88e44 | 5 | public static String changeExtension(String fileName, String extension,
boolean gzipped) {
extension = (extension.startsWith(".")) ? extension : String.format(
"%s%s", ".", extension);
String rgxOne = "^(.+?)(?=((\\.tar)?\\.gz)$)";
String rgxTwo = "^(.+?)(?=\\.(.*)$)";
Matcher m = Pattern.compile(rgxOne).matcher(fileName);
boolean ok = (m.find() && gzipped);
String name = (ok) ? m.group(1) : fileName;
String gzip = (ok) ? GZIP_EXT : "";
m = Pattern.compile(rgxTwo).matcher(name);
ok = m.find();
name = (ok) ? m.group(1) : name;
String finalName = String.format("%s%s%s", name, extension, gzip);
return finalName;
} |
2a65096d-f0e1-4b0e-879b-cc9779fc5fbc | 7 | void TryToCookFood(Order o) {
print("Doing TryToCookFood");
log.add(new LoggedEvent("Doing TryToCookFood"));
int foodAmount = mRole.mItemInventory.get(Item.stringToEnum(o.choice));
if(foodAmount <= 0) {
o.waiter.msgOutOfFood(o.table, o.choice);
orders.remove(o);
return;
}
mRole.decreaseInventory(Item.stringToEnum(o.choice));
if(foodAmount <= FOOD_LOW && mRole.mHasCreatedOrder.get(Item.stringToEnum(o.choice))) {
mRole.mItemsDesired.put(Item.stringToEnum(o.choice), mRole.mItemsDesired.get(Item.stringToEnum(o.choice)) + FOOD_ORDER);
}
o.state = OrderState.Cooking;
for(int i = 0; i < cookHere.length; i++)
if(cookHere[i] == false) {
o.position = i;
cookHere[i] = true;
break;
}
cookGui.DoGoToFridge();
try {
atFridge.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
cookGui.setCurrentOrder(o.choice);
cookGui.DoCooking(o.position);
try {
atGrill.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
cookGui.DoGoWait();
o.cookThisOrder();
cookGui.setCurrentOrder("");
} |
2f27f9be-740d-4aa9-84b7-67284872f88e | 4 | private void start()
{
TcpCon con = new TcpCon();
if((login.getText().trim().length()==0)||passwd.getText().trim().length()==0)
{
login.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.red));
passwd.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.red));
}
else
{
if(con.login(login.getText(), passwd.getText())!=1)
{
String msg="Bład logowania";
Powiadomienia.w_msg(msg, null);
}
else
{
log.dispose();
oGlowne();
aktualizacjaTabeli();
if(flaga==true)
{
tabela.setRowSelectionInterval(0, 0);
}
llekarz.setText("dr."+con.getLekarz(login.getText()));
inext=(int)con.countPacjent();
sz = new ArrayList<PacjenciClass>();
sz=con.getPacjenci();
}
}
} |
7f8ca8f5-55d6-4708-9ab4-d4f3b7ccd2aa | 0 | public void setName(String name) {
this.name = name;
} |
f85f0f28-5c98-444f-a963-2b94d3736bba | 5 | public void sort(int[] array)
{
int length = array.length,
gap = length;
boolean swapped = false;
while (gap > 1 || swapped)
{
gap = (int)((double)gap / SHRINK_FACTOR);
if (gap < 0)
gap = 1;
swapped = false;
for (int i = 0; (gap + i) < length; i++)
{
if ((array[i] - array[i + gap]) > 0)
{
CommonMethods.swap(array, i, i + gap);
swapped = true;
}
}
}
} |
ddba1b53-fc27-4908-b541-8fd34e5aace3 | 7 | public void highlightLine(final int lineNum) {
final Highlighter high = getHighlighter();
final Document d = getDocument();
int line = 0;
int posStart = 0;
int pos = 0;
int lineTermLength = 0;
try {
while ( line < lineNum ) {
posStart = pos;
lineTermLength = 0;
// Find the end of a line (or end of string)
while ( pos < d.getLength() ) {
char c = d.getText(pos, 1).charAt(0);
pos++;
if ( c == '\r' ) {
lineTermLength = 1;
if ( pos < d.getLength() && d.getText(pos, 1).charAt(0) == '\n' ) {
pos++;
lineTermLength = 2;
}
break;
} else if ( c == '\n') {
lineTermLength = 1;
break;
}
}
line++;
}
pos -= lineTermLength;
assert posStart >= 0;
assert pos >= posStart;
assert pos <= d.getLength();
high.addHighlight(posStart, pos, painter);
repaint();
} catch (BadLocationException e1) {}
} |
9c1fa063-ecfe-4309-9e3f-d5f308af972b | 3 | private boolean AT3x04PilotToneHunt (double spectrum[]) {
int a,pbin;
// Look if a particular bin in startCarrierList1 also exists in startCarrierList2 and startCarrierList3
for (a=startCarrierList1.size()-1;a>=0;a--) {
pbin=startCarrierList1.get(a).getBinFFT();
if (checkBinExists(startCarrierList2,pbin)==true) {
if (checkBinExists(startCarrierList3,pbin)==true) {
// Store this bin and return true
pilotToneBin=pbin;
return true;
}
}
}
return false;
} |
732e85ac-4e4f-4526-bf09-7405a2fcab3b | 1 | private void writeIntAMF0(List<Byte> ret, int val)
{
ret.add((byte)0x00);
byte[] temp = new byte[8];
ByteBuffer.wrap(temp).putDouble((double)val);
for (byte b : temp)
ret.add(b);
} |
9aa6319d-8714-44d1-8600-ad0aed3ab132 | 5 | @Override
public int getPartition(Text key, DoubleWritable value,
int numberOfPartitions) {
String newSchemaStr = conf.get(SystemConf
.getNewSchemaForConfSetString());
if (null == newSchemaStr || "".equals(newSchemaStr)) {
try {
throw new NewSchemaNotSetException();
} catch (NewSchemaNotSetException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
}
}
Schema newSchema = null;
try {
newSchema = Schema.constructedFromString(newSchemaStr);
// System.err.println(newSchemaStr);
} catch (InvalidObjectStringException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
}
BigInteger elementNo = new BigInteger(key.toString());
// TODO numberOfPages cannot bigger than Integer.MAX_VALUE
int pageNo = (int) PageHelper.belongTo(elementNo, newSchema);
// System.err.println("pageNo: " + pageNo);
if (pageNo != 0) {
// System.err.println("*******************************************");
}
return pageNo;
} |
53fec754-fd9d-4c3c-822c-dc243e533dcc | 5 | private void addButtons() {
JPanel buttonHolder = new JPanel();
buttonHolder.setLayout(new BoxLayout(buttonHolder, BoxLayout.X_AXIS));
JButton process = new JButton("Create map");
final Gui gui = this;
process.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!mapData.getSelectedFile().exists()
|| !styleChooser.getSelectedFile().exists()) {
JOptionPane.showMessageDialog(gui,
"You need to select map data and a stylesheet.");
return;
}
if (!target.getSelectedFile().canWrite()) {
JOptionPane.showMessageDialog(gui,
"Target file is not writeable");
return;
} else {
int overwrite = JOptionPane.showConfirmDialog(gui,
"Overwrite the target file?", "",
JOptionPane.YES_NO_OPTION);
if (overwrite != JOptionPane.YES_OPTION) {
return;
}
}
ProcessMap processMap = new ProcessMap();
processMap.setMapData(mapData.getSelectedFile());
processMap.setStyleFile(styleChooser.getSelectedFile());
try {
processMap.createMap();
} catch (Exception e1) {
JOptionPane.showMessageDialog(gui,
"Could not generate map (see console for details): "
+ e1.getMessage());
e1.printStackTrace();
}
}
});
buttonHolder.add(process);
buttonHolder.add(new JButton("Create & display map"));
this.add(buttonHolder);
} |
7a0688c6-a82b-4628-85e5-0926e1486fb9 | 4 | public Currency[] search(String token){
ArrayList<Currency> list = new ArrayList<>();
for (Currency currency : this){
if (currency.getCode().equalsIgnoreCase(token))
list.add(currency);
else if (currency.getSymbol().equalsIgnoreCase(token))
list.add(currency);
else if (currency.getName().toLowerCase().contains(token.toLowerCase()));
list.add(currency);
}
return list.toArray(new Currency[list.size()]);
} |
7b2b2d33-e32f-4c15-b5ab-2d6d5ae1ea67 | 2 | public RainFall(String record, BufferedWriter out, String fn)
{
try {
String[] fields = record.split(",");
//System.out.println(record);
_stationId = fields[1];
_year = "" + Integer.parseInt(fields[2]);
_month = "" + Integer.parseInt(fields[3]);
_day = "" + Integer.parseInt(fields[4]);
if (fields.length >= 6) {
_rainfall = fields[5];
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(_year + ", " + _month + ", " + _day + ", " + _stationId + ", " + fn);
}
write(out);
} |
2452d59e-580c-4bf7-a697-0992403cfbeb | 8 | public MainFrame(final String title) throws IOException {
super(title);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel csvPanel = new JPanel();//new FlowLayout());
csvPanel.setLayout(new BoxLayout(csvPanel, BoxLayout.Y_AXIS));
csvPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel svgPanel = new JPanel();//new FlowLayout());
svgPanel.setLayout(new BoxLayout(svgPanel, BoxLayout.Y_AXIS));
svgPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel generatePanel = new JPanel();
generatePanel.setLayout(new BoxLayout(generatePanel, BoxLayout.X_AXIS));
generatePanel.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton buttonLoad = new JButton("Load CSV File");
buttonLoad.setAlignmentX(Component.CENTER_ALIGNMENT);
final JLabel csvFileLabel = new JLabel("CSV file...");
csvFileLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
final JLabel svgFileLabel = new JLabel("SVG file...");
svgFileLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = initOpenFileChooser();
int returnVal = fc.showOpenDialog(MainFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
csvFile = file.getAbsolutePath();
csvFileLabel.setText(csvFile);
if (validCsv()){
//This is where a real application would open the file.
//System.out.println("Opening: " + csvFile );
buttonLineChart.setEnabled(true);
buttonBarChart.setEnabled(true);
/*}
else{*/
svgFileLabel.setText("SVG file...");
}
} else {
System.out.println("Open command cancelled by user." );
}
}
});
//JButton buttonSave = new JButton("Save SVG File");
//buttonSave.setAlignmentX(Component.CENTER_ALIGNMENT);
/*buttonSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//showSaveDialog(svgFileLabel);
}
});*/
buttonBarChart.setEnabled(false);
buttonBarChart.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonBarChart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int dialog = showSaveDialog(svgFileLabel);
if (dialog == JFileChooser.APPROVE_OPTION){
try {
if (validFiles()){
createBarChart(csvFile, svgFile);
svgFileLabel.setText("Bar chart created succesfully in: " + "\n" + svgFile);
}
else{
svgFileLabel.setText("SVG file...");
//buttonLineChart.setEnabled(false);
//buttonBarChart.setEnabled(false);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(MainFrame.this, "Please verify the CSV file.");
e.printStackTrace();
}
}
}
});
buttonLineChart.setEnabled(false);
buttonLineChart.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonLineChart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int dialog = showSaveDialog(svgFileLabel);
if (dialog == JFileChooser.APPROVE_OPTION){
try {
if (validFiles()){
createLineChart(csvFile, svgFile);
svgFileLabel.setText("Line chart created succesfully in: " + "\n" + svgFile);
}
else{
svgFileLabel.setText("SVG file...");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(MainFrame.this, "Please verify the CSV file.");
e.printStackTrace();
}
}
}
});
csvPanel.add(buttonLoad);
csvPanel.add(csvFileLabel);
generatePanel.add(buttonBarChart);
generatePanel.add(buttonLineChart);
//svgPanel.add(buttonSave);
svgPanel.add(svgFileLabel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setMinimumSize(new Dimension(600, 270));
mainPanel.add(Box.createVerticalStrut(30));
mainPanel.add(csvPanel);
mainPanel.add(Box.createVerticalStrut(30));
mainPanel.add(generatePanel);
mainPanel.add(Box.createVerticalStrut(20));
mainPanel.add(svgPanel);
this.setContentPane(mainPanel);
} |
84f92d78-50a3-4988-972f-ee6adfd6ac44 | 8 | @Test
public void complicatedTest() throws Exception {
for (int i = 1; i <= 20; i++) {
heap.enqueue(i);
}
for (int i = 1; i <= 20; i++) { //heap should be 1 ... 20
assertIntWithObject(i, heap.dequeue());
}
for (int i = 1; i <= 20; i++) {
heap.enqueue(i);
}
for (int i = 1; i <= 10; i++) { //heap should be 1 ... 20
assertIntWithObject(i, heap.dequeue());
}
for (int i = 11; i <= 20; i++) { //heap should be 11 ... 20
heap.enqueue(i);
}
for (int i = 11; i <= 20; i++) { //heap should be duplicates 11,11,12,12 ... 20,20
assertIntWithObject(i, heap.dequeue());
assertIntWithObject(i, heap.dequeue());
}
for (int i = 20; i >= 1; i--) {
heap.enqueue(i);
}
for (int i = 1; i <= 20; i++) { //heap should be 1 ... 20
assertIntWithObject(i, heap.dequeue());
}
heap.enqueue(100);
heap.enqueue(200);
} |
e354563e-3f5a-44b2-b6d1-b7fc507487eb | 8 | @Override
public AudienceVotingResult vote(List<Answer> allAnswers, List<Answer> possibleAnswers, QuestionDifficulty difficulty) {
int answersCount = possibleAnswers.size();
if (answersCount != 2 && answersCount != 4) {
throw new RuntimeException("Unable to vote for " + possibleAnswers.size() + " answers (only 2 and 4 are supported)");
}
int[] percents;
switch (difficulty) {
case EASY:
if (answersCount == 4) {
// incorrect 0 - 20 => avg. 10 | correct: 40 - 100 => avg. 70
percents = generatePercents(possibleAnswers, 0, 20);
} else { // answersCount == 2
// incorrect 0 - 30 => avg. 15 | correct: 80 - 100 => avg. 90
percents = generatePercents(possibleAnswers, 0, 30);
}
break;
case MID:
if (answersCount == 4) {
// incorrect 10 - 26 => avg. 18 | correct: 22 - 70 => avg. 46
percents = generatePercents(possibleAnswers, 10, 26);
} else { // answersCount == 2
// incorrect 20 - 55 => avg. 37.5 | correct: 45 - 80 => avg. 62.5
percents = generatePercents(possibleAnswers, 20, 55);
}
break;
case HARD:
if (answersCount == 4) {
// incorrect 19 - 27 => avg. 23 | correct: 19 - 43 => avg. 31
percents = generatePercents(possibleAnswers, 19, 27);
} else { // answersCount == 2
// incorrect 35 - 55 => avg. 45 | correct: 45 - 65 => avg. 55
percents = generatePercents(possibleAnswers, 35, 55);
}
break;
default:
throw new RuntimeException("Unknown difficulty of question!");
}
return mergeToResult(allAnswers, possibleAnswers, percents);
} |
416ec568-b6d8-49ce-80e3-948195f9a15f | 2 | public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String actionCh = request.getParameter("Change");
String actionDel = request.getParameter("Delete");
if(actionCh != null) {
RequestDispatcher view = request.getRequestDispatcher("ChangeRec.jsp");
view.forward(request, response);
} else if (actionDel != null) {
RequestDispatcher view = request.getRequestDispatcher("isDelete.jsp");
view.forward(request, response);
}
} |
6320aca0-5df1-475f-8784-17d32b07d40e | 4 | int guess(String solution) {
int count = 0;
count++;
int a = getA(solution, "1234");
if (a == 4) {
return count;
}
int b = getB(solution, "1234");
reduce("1234", a, b);
for (int i = 0; i < validSet.length; i++) {
if (!validSet[i]) {
continue;
}
count++;
a = getA(solution, answerSet[i]);
if (a == 4) {
break;
}
b = getB(solution, answerSet[i]);
reduce(answerSet[i], a, b);
}
return count;
} |
53e4031d-1f02-4d05-a1b3-ed8e5c1c9848 | 6 | public int compareTo(Object o) {
if (o instanceof ArgPosition) {
ArgPosition other = (ArgPosition) o;
int i = 0;
while (this.path.size() > i && other.path.size() > i) {
final int result = this.path.get(i).compareTo(other.path.get(i));
if (result != 0) {
return result;
}
i++;
}
if (this.path.size() <= i) {
return -1;
} else if (other.path.size() <= i) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
} |
4ca205dd-5786-42de-a19f-60da78c8762e | 3 | private static Character createCharacter(String type, Scanner console) {
if(type.toLowerCase().startsWith("war")) {
Warrior character = new Warrior();
return character;
} else if(type.toLowerCase().startsWith("mag")) {
Mage character = new Mage();
return character;
} else if(type.toLowerCase().startsWith("rog")) {
Rogue character = new Rogue();
return character;
} else {
System.out.println("\"Hmm... I've never heard of one of THOSE before...");
System.out.println("Don't waste anymore of my time with your silly games.");
System.out.println("This arrow is itching to get let loose.\"");
System.out.println("");
System.out.print("Enter a class: ");
type = console.nextLine();
return createCharacter(type, console);
}
} |
ca4d55cc-868d-4eba-9ffd-7740df019f91 | 9 | public void checkBananas(ArrayList<EntityBanana> ba){
for(int i = 0; i < ba.size(); i++){
EntityBanana b = ba.get(i);
if(flying){
if(
b.getx() > x &&
b.getx() < x + (cwidth / 2) &&
b.gety() > y - height / 2 &&
b.gety() < y + height / 2
){
b.hit(1);
}
}
if(intersects(b) && !flying){
if(b.getHealth() > 0){
hit();
}
}
}
} |
71f6b7a9-2bf6-4d68-9e0a-a270d4d60f0d | 2 | public static byte[] toByte(String str){
if(str != null){
try {
return str.getBytes(UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
return null;
} |
f784f8bc-c77b-4c40-8e02-36fcf8f05674 | 8 | public void processEvent(Event event) {
try {
if (event.getType() == EventType.CLASS_OPEN || event.getType() == EventType.CLASS_REPARSE) {
this.cf = event.getClassFile();
}
if (event.getType() == EventType.CLASS_PARSE_ERROR) {
this.tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Class parse error.")));
}
if (event.getType() == EventType.CLASS_OPEN || event.getType() == EventType.CLASS_UPDATE || event.getType() == EventType.CLASS_REPARSE) {
this.upToDate = false;
if (this.isOpen) {
refresh();
}
}
} catch(Exception e) {
SystemFacade.getInstance().handleException(e);
}
} |
54581995-aa87-48c3-b26f-50b8a1304511 | 8 | public void updateReduceOutputPerMap(String jobID, String taskID, int mapId, int[] stat) {
Boolean retry = false;
int backoff = 1000;
String domainName;
if ( taskID.hashCode()<0 )
domainName = dbManagerDomain + (-taskID.hashCode())%Global.numSDBDomain;
else
domainName = dbManagerDomain + (taskID.hashCode())%Global.numSDBDomain;
long updateCompletedTime = perf.getStartTime();
int size = stat.length > MAXSTATPERROW ? MAXSTATPERROW+2 : stat.length+2;
ReplaceableAttribute[] attributes = new ReplaceableAttribute[size];
int i = 0;
do {
int start = i;
// add jobID attribute to easily identify and delete if needed
attributes[0] = new ReplaceableAttribute("jobid", jobID, true);
// add who updated the attribute for debugging purpose
attributes[1] = new ReplaceableAttribute("writtenby", taskID + "_map" + mapId, true);
// SimpleDB limits 256 attributes per item, have to split into multiple rows for large # of Qs
for ( ; i<stat.length && i<start+MAXSTATPERROW ; i++ ) {
attributes[i % MAXSTATPERROW + 2] = new ReplaceableAttribute("reduceQ" + i, Integer.toString(stat[i]), true);
}
// upload to SimpleDB
do {
retry = false; // assume success
try {
// row name contains jobID so that multiple jobs could run at the same time without violating the 256 attributes per row limit
PutAttributesRequest request = new PutAttributesRequest().withItemName(jobID + "_" + taskID + "_map" + mapId + "_" + Math.round(i/MAXSTATPERROW)).withAttribute(attributes);
PutAttributesResponse response = service.putAttributes(request.withDomainName(domainName));
} catch (AmazonSimpleDBException ex) {
logger.warn("Fail to update completed reduce. Will retry. " + ex.getMessage());
retry = true; // signal need to retry
try {Thread.sleep(backoff + (new Random()).nextInt(2000));} catch (Exception ex2) {}
backoff *= 2;
}
} while (retry);
} while ( i < stat.length ) ;
perf.stopTimer("dbUpdateCompletedReduce", updateCompletedTime);
} |
89449d7d-559a-48ec-9613-ae7e4a47d1cf | 0 | @Test
public void findHandFromCardSet_whenFourJacks_returnsFourOfaKind() {
Hand hand = findHandFromCardSet(quadsJacksWithTenKicker());
assertEquals(HandRank.FourOfAKind, hand.handRank);
assertEquals(Rank.Jack, hand.ranks.get(0));
assertEquals(Rank.Ten, hand.ranks.get(1));
} |
7af6bb18-9e13-4c87-98e5-51c9c012c06c | 3 | private void playVote() {
Vector<Integer> hasNotVoted = votes2.notVoted(2);
for (Integer player : hasNotVoted) {
if (!players2.isDead(player)) {
players2.kill(player);
bot.sendMessage(gameChan, getFromFile("NOT-VOTED", players2.get(player), NARRATION));
sendNotice(players2.get(player), getFromFile("NOT-VOTED-NOTICE", NOTICE));
bot.setMode(gameChan, "-v " + players2.get(player));
}
}
if (checkWin())
return;
bot.sendMessage(gameChan, getFromFile("VOTETIME", null, voteTime, GAME, null));
waitForOutgoingQueueSizeIsZero();
gameTimer.schedule(new WereTask(), voteTime * 1000);
} |
d5992a12-d2c1-46ab-8713-0337bbe895f9 | 4 | public OverwriteDialog(final JFrame parent) {
super(parent, "", true);
bundle = Application.getResourceBundle();
this.setTitle(bundle.getString("overwrite_title"));
// Closing the window is equal to pressing the No-Button
WindowListener windowListener = (new WindowAdapter() {
@Override
public void windowClosing(WindowEvent evt) {
pressedNo();
}
});
addWindowListener(windowListener);
ActionListener actionListener = (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(evt.getSource() == btYes)
pressedYes();
else if(evt.getSource() == btNo)
pressedNo();
}
});
// Enter is equal to pressing the Yes-Button and
// Escape is equal to pressing the No-Button
KeyListener keyListener = (new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
if(evt.getKeyCode() == KeyEvent.VK_ENTER)
pressedYes();
else if(evt.getKeyCode() == KeyEvent.VK_ESCAPE)
pressedNo();
}
});
addKeyListener(keyListener);
lbFile = new JLabel("");
cbAllFiles = new JCheckBox();
cbAllFiles.setSelected(forAllfiles);
cbAllFiles.setText(bundle.getString("overwrite_all_existing"));
btYes = new JButton(bundle.getString("yes"));
btNo = new JButton(bundle.getString("no"));
btNo.setSelected(true);
cbAllFiles.addKeyListener(keyListener);
btYes.addActionListener(actionListener);
btYes.addKeyListener(keyListener);
btNo.addActionListener(actionListener);
btNo.addKeyListener(keyListener);
JPanel pnlMain = new JPanel();
pnlMain.setBorder(BorderFactory.createEmptyBorder(8, 8, 10, 8));
//pnlMain.setLayout(new GridBagLayout(3, 2, 4, 4));
pnlMain.setLayout(new GridBagLayout());
pnlMain.add(lbFile, new GridBagConstraints(
0, 0, 1, 1, 1.0, 3.0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
pnlMain.add(cbAllFiles, new GridBagConstraints(
0, 1, 1, 1, 1.0, 3.0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
pnlMain.add(btNo, new GridBagConstraints(
0, 2, 1, 1, 1.0, 3.0, GridBagConstraints.LINE_END,
GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
pnlMain.add(btYes, new GridBagConstraints(
1, 2, 1, 1, 1.0, 3.0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
Container contFrame = getContentPane();
contFrame.setLayout(new BorderLayout());
contFrame.add(pnlMain, "Center");
pack();
setSize(new Dimension(500,120));
} |
886377c4-ca9c-467d-9591-29ec6084a8a7 | 4 | private void experiment() {
//wait for all the entities to register
super.gridSimHold(50.0);
int location;
File f1 = null;
File f2 = null;
//1. create new files
try {
f1 = new File("file1", 5);
f2 = new File("file2", 1);
} catch (ParameterException e) {
System.out.println("Error creating files");
}
//2. add files to a resource
addMaster(f1, GridSim.getEntityId("Res_0"));
addMaster(f2, GridSim.getEntityId("Res_1"));
//3. create 3 data gridlets
for(int i=0; i < 3; i++){
// set the ID of this gridlet, the gridlet length in MI, the size of
// the file before and after execution and whether we would like to
// log the history of this object
DataGridlet g = new DataGridlet(i, 1000, 10, 10, false);
//the gridlet requires two files in order to execute
g.addRequiredFile(f1.getName());
g.addRequiredFile(f2.getName());
// the gridlet needs the user id, so that the resource will be able
// to send it back when finished
g.setUserID(this.get_id());
this.outList.add(g);
}
//4. submit the data gridlets
for(int i=0; i<3;i++){
DataGridlet g = (DataGridlet)outList.get(i);
System.out.println("Submitting gridlet "+i+" to resource "+i);
super.send(GridSim.getEntityId("Res_"+i), 0,
DataGridTags.DATAGRIDLET_SUBMIT, g);
}
//5. wait for the gridlets to finish the execution
for(int i=0; i<3;i++){
Sim_type_p tag = new Sim_type_p(GridSimTags.GRIDLET_RETURN);
Sim_event ev = new Sim_event();
// only look for this type of ack
super.sim_get_next(tag, ev);
DataGridlet dg = (DataGridlet)ev.get_data();
this.receiveList.add(dg);
System.out.println("Received back gridlet "+dg.getGridletID());
}
} |
9835ffe1-d3fc-44d1-9126-6ef60353f4d2 | 9 | public static String buildOutputCalendar(Calendar calendar) {
String res = " " + calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()) + " " +
calendar.get(Calendar.YEAR) + '\n' +
(argsAnalizer.getIsWeekNumber() ? " " : "") + "Mo Tu We Th Fr Sa Su" + '\n';
if (argsAnalizer.getIsWeekNumber()) {
res += String.valueOf(calendar.get(Calendar.WEEK_OF_YEAR) - 1);
if (String.valueOf(calendar.get(Calendar.WEEK_OF_YEAR) - 1).length() == 1) {
res += " ";
} else {
res += " ";
}
}
for (int i = 1; i < calendar.get(Calendar.DAY_OF_WEEK) - 1; i++) {
res += " ";
}
int currMonth = calendar.get(Calendar.MONTH);
int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
while (currMonth == calendar.get((Calendar.MONTH))) {
String temp = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
if (temp.length() == 1) {
temp += " ";
} else {
temp += " ";
}
res += temp;
i++;
calendar.add(Calendar.DATE, 1);
if (i % 7 == 1) {
res += "\n";
if (argsAnalizer.getIsWeekNumber()) {
res += String.valueOf(calendar.get(Calendar.WEEK_OF_YEAR) - 1);
if (String.valueOf(calendar.get(Calendar.WEEK_OF_YEAR) - 1).length() == 1) {
res += " ";
} else {
res += " ";
}
}
}
}
return res;
} |
6a1901a6-b4ac-46fc-9898-fc83a011c171 | 3 | @Override
public void caseAProgramas(AProgramas node)
{
inAProgramas(node);
if(node.getIdentificador() != null)
{
node.getIdentificador().apply(this);
}
{
List<PDeclaracao> copy = new ArrayList<PDeclaracao>(node.getDeclaracao());
for(PDeclaracao e : copy)
{
e.apply(this);
}
}
{
List<PComando> copy = new ArrayList<PComando>(node.getComando());
for(PComando e : copy)
{
e.apply(this);
}
}
outAProgramas(node);
} |
6da7001b-6509-4904-87e1-3564dd257f53 | 2 | public void dbConnect(String db_connect_string,
String db_userid,
String db_password) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String query = "SELECT DNOrPattern AS SDA, CalledPartyTransformationMask AS DirectoryNumber\n"
+ "FROM dbo.NumPlan \n"
+ "Where tkPatternUsage = '3' and len(DNOrPattern) = 3";
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
System.out.println(
"\t" + rs.getString("SDA")
+ "\t" + rs.getString("DirectoryNumber"));
dbInsert(rs.getString("SDA"), rs.getString("DirectoryNumber"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
} |
3c33a6fc-f047-4431-a470-e70c0e19d82a | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Townshipbusiness)) {
return false;
}
Townshipbusiness other = (Townshipbusiness) object;
if ((this.townshipBusinessID == null && other.townshipBusinessID != null) || (this.townshipBusinessID != null && !this.townshipBusinessID.equals(other.townshipBusinessID))) {
return false;
}
return true;
} |
2e7afbcf-c97f-4c7e-9996-c57d8df950d6 | 4 | private void outputHelper() throws IOException
{
miscInfo = new PrintWriter(new FileWriter(JPEGFileName.replace(".JPG", "_miscInfo.txt")));
outline = new PrintWriter(new FileWriter(JPEGFileName.replace(".JPG", "_outline.txt")));
controlPoints = new PrintWriter(new FileWriter(JPEGFileName.replace(".JPG", "_controlpoints.txt")));
squareCorners = new PrintWriter(new FileWriter(JPEGFileName.replace(".JPG", "_corners.txt")));
miscInfo.println("JPG Filename: " + JPEGFileName);
miscInfo.println("Image Height, Width: " + pointsImage.getHeight() + ", "
+ pointsImage.getWidth());
miscInfo.println("CornerA (X,Y): " + cornerAXText.getText()
+ ", " + cornerAYText.getText());
miscInfo.println("CornerB (X,Y): " + cornerBXText.getText()
+ ", " + cornerBYText.getText());
miscInfo.println("CornerC (X,Y): " + cornerCXText.getText()
+ ", " + cornerCYText.getText());
miscInfo.println("CornerD (X,Y): " + cornerDXText.getText()
+ ", " + cornerDYText.getText());
miscInfo.println("Square Side Length: " + sideLengthText.getText());
miscInfo.println("HFOV: " + hfovText.getText());
// Output the four corner coordinates.
squareCorners.println(cornerAXText.getText() + "," + cornerAYText.getText());
squareCorners.println(cornerBXText.getText() + "," + cornerBYText.getText());
squareCorners.println(cornerCXText.getText() + "," + cornerCYText.getText());
squareCorners.println(cornerDXText.getText() + "," + cornerDYText.getText());
// Output the control point IDs and coordinates
for (ImageMarker marker: cornerAndControlMarkers)
{
if (marker.getType() == ImageMarker.MarkerType.CONTROL_POINT)
{
controlPoints.println(marker.getID() + "," + (marker.getLocation().x + 0.5)
+ "," + (marker.getLocation().y + 0.5));
}
}
// Output the stream outline data
for (ImageMarker marker: outlineMarkers)
{
if(marker.getType() == ImageMarker.MarkerType.OUTLINE_POINT)
{
outline.println((marker.getLocation().x + 0.5) + "," + (marker.getLocation().y +0.5));
}
}
miscInfo.close();
controlPoints.close();
squareCorners.close();
outline.close();
} |
1218b430-b313-4bae-8b9d-d8b8f894e42c | 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(StartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartMenu.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 StartMenu().setVisible(true);
}
});
} |
e64eafa6-67d2-4f9b-8e15-55cf93388d3b | 6 | public static HashMap<String, HashMap<String, Integer>> getMap(String filePath) throws Exception
{
HashMap<String, HashMap<String, Integer>> map =
new HashMap<String, HashMap<String,Integer>>();
BufferedReader reader = filePath.toLowerCase().endsWith("gz") ?
new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( filePath)))) :
new BufferedReader(new FileReader(new File(filePath
)));
String nextLine = reader.readLine();
int numDone =0;
while(nextLine != null)
{
StringTokenizer sToken = new StringTokenizer(nextLine, "\t");
String sample = sToken.nextToken().replace(".fastatoRDP.txt.gz", "");
String taxa= sToken.nextToken();
int count = Integer.parseInt(sToken.nextToken());
if( sToken.hasMoreTokens())
throw new Exception("No");
HashMap<String, Integer> innerMap = map.get(sample);
if( innerMap == null)
{
innerMap = new HashMap<String, Integer>();
map.put(sample, innerMap);
}
if( innerMap.containsKey(taxa))
throw new Exception("parsing error " + taxa);
innerMap.put(taxa, count);
nextLine = reader.readLine();
numDone++;
if( numDone % 1000000 == 0 )
System.out.println(numDone);
}
return map;
} |
716195ef-b10c-43a7-89ba-312e50a17a59 | 9 | @Override
public void unInvoke()
{
final Physical affected=super.affected;
// undo the affects of this spell
if(affected==null)
return;
if(canBeUninvoked())
{
if((invoker()!=null)
&&((targetM == null)||(!CMLib.flags().isInTheGame(targetM, true))||(targetM.location()!=invoker().location())))
invoker().tell(L("The helping hand for @x1 has given up.",targetName));
final Room R=CMLib.map().roomLocation(affected);
if(R.isHere(affected))
R.showHappens(CMMsg.MSG_OK_VISUAL,L("The helping hand vanishes."));
}
super.unInvoke();
if(canBeUninvoked() && (!affected.amDestroyed()))
affected.destroy();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.