text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public int next() {
int n = -1;
if (start < cs.length()) {
n = cs.charAt(start++);
offset++;
if (n == '\r') {
lines++;
columns = 0;
} else if (n == '\n') {
if (offset < 2 || cs.charAt(offset-2) != '\r') {
lines++;
columns = 0;
}
} else {
columns++;
}
} else {
start++;
return -1;
}
return n;
} | 5 |
private static boolean linearSearch(Long number)
{
for(int j = 0; j < unsorted.length; j++)
{
if(unsorted[j] == number)
{
return true;
}
}
return false;
} | 2 |
@Test
public void isEmptyReturnsTrueAfterEnqueueDequeue() {
q.enqueue(0);
q.dequeue();
assertTrue(q.isEmpty());
} | 0 |
public static void setStartTime(CallInfo ci, Date start){
ci.setStart(start);
} | 0 |
public static void editMember(Member m){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Adress a = m.getAdress();
try{
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("UPDATE Members set name = ?, first_name = ?, phone_num = ?, address_id = ? WHERE member_id = ?");
stmnt.setString(1, m.getName());
stmnt.setString(2, m.getSurname());
stmnt.setString(3, m.getTelnr());
stmnt.setInt(4, a.getAdressID());
stmnt.setInt(5, m.getLidID());
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
System.out.println("update fail!! - " + e);
}
} | 4 |
public void teleport(LOGONode argx, LOGONode argy, boolean setX, boolean setY) {
if (!setX && !setY)
return;
if (setX && setY) {
Double retx = runAndCheckDouble(argx, "SETXY");
if (LOGOPP.errorhandler.error())
return;
Double rety = runAndCheckDouble(argy, "SETXY");
if (LOGOPP.errorhandler.error())
return;
double valuex = retx.doubleValue();
double valuey = rety.doubleValue();
LOGOPP.eventQueue.add(LOGOPP.canvas.getCurTurtle(), "TELE", valuex, valuey);
LOGOPP.eventQueue.clearPending(false);
}
else if (setX) {
Double ret = runAndCheckDouble(argx, "SETX");
if (LOGOPP.errorhandler.error())
return;
double value = ret.doubleValue();
LOGOPP.eventQueue.add(LOGOPP.canvas.getCurTurtle(), "TELE", value, LOGOPP.canvas.getCurTurtle().getYPos());
LOGOPP.eventQueue.clearPending(false);
}
else { //setY
Double ret = runAndCheckDouble(argy, "SETY");
if (LOGOPP.errorhandler.error())
return;
double value = ret.doubleValue();
LOGOPP.eventQueue.add(LOGOPP.canvas.getCurTurtle(), "TELE", LOGOPP.canvas.getCurTurtle().getXPos(), value);
LOGOPP.eventQueue.clearPending(false);
}
} | 9 |
public void setServerVersion(String serverVersion) {
this.serverVersion = serverVersion;
} | 0 |
public void clearArea(ImageFrame img_frame, int x, int y, int width, int height)
{
//clear this area from main picture
Image img = img_frame.getJIPTImage().getImage(); //get main image
int totalWidth = img.getWidth(main_frame); //get main picture width
int totalHeight = img.getHeight(main_frame); //get main picture height
int originImageData[] = new int[ totalWidth * totalHeight ]; //make image array for main picture
PixelGrabber pg = new PixelGrabber(img, 0, 0, -1, -1, true); //get main picture array
try
{
pg.grabPixels();
}
catch(Exception e)
{
// System.out.println(e.toString());
}
originImageData = (int []) pg.getPixels();
//get clearPixelColor from jipt_settings
int clearPixel = main_frame.getJIPTsettings().getClearPixelColor();
//traverse image array and clear out selected area (x,y, x+width, y+height)
int pos = 0;
for(int j=0; j<totalHeight; j++ )
for( int i=0; i<totalWidth; i++ )
{
if( ( (i>=x) && (i<(x+width)) ) && ( (j>=y) && (j<(y+height)) ) )
{
originImageData[pos] = clearPixel;
}
pos++;
}
//create image from imageData
img = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(totalWidth,
totalHeight,originImageData,0,totalWidth));
//apply new image
img_frame.setFrameImage( img, true );
} | 7 |
public static void binarySearch(int key, int lowerbound, int upperbound, List<Integer> list){
System.out.println("Key: "+ key);
int position = (lowerbound + upperbound)/2;
while(list.get(position) != key && lowerbound <= upperbound){
position = (lowerbound + upperbound)/2;
if(list.get(position) < key)
lowerbound = position + 1;
else if(list.get(position) > key)
upperbound = position - 1;
}
System.out.println("Found in index: "+position);
} | 4 |
private static void importGliderPosition() throws IOException, SQLException, ClassNotFoundException {
String s;
while((s = br.readLine()) != null) {
String[] gliderPositionData = s.split(",",-1);
GliderPosition importer = new GliderPosition(gliderPositionData[1], gliderPositionData[2], gliderPositionData[4], Float.parseFloat(gliderPositionData[6]),
Float.parseFloat(gliderPositionData[7]), Float.parseFloat(gliderPositionData[8]), gliderPositionData[9]);
importer.setId(gliderPositionData[0]);
importer.setAirfieldParentId(gliderPositionData[5]);
importer.setRunwayParentId(gliderPositionData[3]);
try {
DatabaseDataObjectUtilities.addGliderPositionToDB(importer);
} catch(SQLIntegrityConstraintViolationException e)
{ }
catch(Exception e) {
//e.printStackTrace();
}
}
} | 3 |
private void delete(RBNode z) {
RBNode x = factory.create(); // work node to contain the replacement node
RBNode y; // work node
// find the replacement node (the successor to x) - the node one with
// at *most* one child.
if(z.getLeft() == sentinelNode || z.getRight() == sentinelNode)
y = z; // node has sentinel as a child
else {
// z has two children, find replacement node which will
// be the leftmost node greater than z
y = z.getRight(); // traverse right subtree
while(y.getLeft() != sentinelNode) // to find next node in sequence
y = y.getLeft();
}
// at this point, y contains the replacement node. it's content will be copied
// to the valules in the node to be deleted
// x (y's only child) is the node that will be linked to y's old parent.
if(y.getLeft() != sentinelNode)
x = y.getLeft();
else
x = y.getRight();
// replace x's parent with y's parent and
// link x to proper subtree in parent
// this removes y from the chain
x.setParent(y.getParent());
if(y.getParent() != null)
if(y == y.getParent().getLeft())
y.getParent().setLeft(x);
else
y.getParent().setRight(x);
else
setRoot(x); // make x the root node
// copy the values from y (the replacement node) to the node being deleted.
// note: this effectively deletes the node.
if(y != z) {
z.setValue(y.getValue());
}
if(y.getColor() == Color.BLACK)
restoreAfterDelete(x);
} | 8 |
@Override
public ProductA factoryA() {
return new ProductA2();
} | 0 |
* @return <tt>true</tt> if CycFort GENL is a genl of CycFort SPEC
*
* @throws UnknownHostException if cyc server host not found on the network
* @throws IOException if a data communication error occurs
* @throws CycApiException if the api request results in a cyc server error
*/
public boolean isGenlOf_Cached(CycObject genl,
CycObject spec)
throws UnknownHostException, IOException, CycApiException {
final Pair args = new Pair(genl, spec);
Boolean isGenlOf = isGenlOfCache.get(args);
if (isGenlOf != null) {
return isGenlOf.booleanValue();
}
final boolean answer = isGenlOf(genl, spec);
isGenlOfCache.put(args, answer);
return answer;
} | 1 |
public static String getProcessOutput(String... command) {
String out = null;
try {
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process = pb.start();
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
final StringBuilder response=new StringBuilder();
new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line + "\n");
}
} catch (IOException ex) {
//Don't let other process' problems concern us
} finally {
IOUtils.closeQuietly(bufferedReader);
}
}
}).start();
process.waitFor();
if (response.toString().length() > 0) {
out = response.toString().trim();
}
}
catch (IOException e) {
//Some kind of problem running java -version or getting output, just assume the version is bad
return null;
} catch (InterruptedException ex) {
//Something booted us while we were waiting on java -version to complete, just assume
//this version is bad
return null;
}
return out;
} | 5 |
private String criarMetodoSalvarAtualizar(String tableName, ResultSetMetaData rsMetadata, String pkey) throws Exception {
StringBuilder insertUpdateMetodo = new StringBuilder();
insertUpdateMetodo.append("\n private void salvar" + tableName + "(List<" + tableName + "> lista" + tableName + ") throws Exception {");
insertUpdateMetodo.append("\n Connection con = null;");
insertUpdateMetodo.append("\n PreparedStatement pstInsert = null;");
insertUpdateMetodo.append("\n PreparedStatement pstUpdate = null;");
insertUpdateMetodo.append("\n Statement stm = null;");
insertUpdateMetodo.append("\n ResultSet rs = null;");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n try {");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n con = conectaBDerp();");
insertUpdateMetodo.append("\n stm = con.createStatement();");
insertUpdateMetodo.append("\n StringBuffer sql = new StringBuffer();");
insertUpdateMetodo.append("\n sql.append(\"insert into ").append(tableName).append("(\");");
String parametros = "";
for (int i = 1; i < rsMetadata.getColumnCount() + 1; i++) {
String separador = "";
parametros += "?";
if (i < rsMetadata.getColumnCount()) {
separador = ",";
parametros += ",";
}
insertUpdateMetodo.append("\n sql.append(\"" + rsMetadata.getColumnName(i)).append(separador + "\");");
}
insertUpdateMetodo.append("\n sql.append(\") values (" + parametros + ") \");");
insertUpdateMetodo.append("\n pstInsert = con.prepareStatement(sql.toString());");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n sql.delete(0, sql.length());");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n sql.append(\"update ").append(tableName).append(" set \");");
for (int i = 1; i < rsMetadata.getColumnCount() + 1; i++) {
if (!rsMetadata.getColumnName(i).equals(pkey)) {
String separador = "";
if (i < rsMetadata.getColumnCount()) {
separador = ",";
}
insertUpdateMetodo.append("\n sql.append(\"" + rsMetadata.getColumnName(i) + "=?" + separador + "\");");
}
}
insertUpdateMetodo.append("\n sql.append(\" where " + pkey + " = ? \");");
insertUpdateMetodo.append("\n pstUpdate = con.prepareStatement(sql.toString());");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n final int batchSize = 1000;");
insertUpdateMetodo.append("\n int count = 0;");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n for (" + tableName + " obj : lista" + tableName + ") {");
insertUpdateMetodo.append("\n if( obj.get" + pkey + "() == 0 ){");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n rs = stm.executeQuery(\"SELECT nextval(('" + tableName + "_" + pkey + "_seq'::text)::regclass) as id\");");
insertUpdateMetodo.append("\n if (rs.next()) {");
insertUpdateMetodo.append("\n obj.set" + pkey + "(rs.getInt(\"id\"));");
insertUpdateMetodo.append("\n }");
insertUpdateMetodo.append("\n");
int index = 0;
for (int i = 1; i < rsMetadata.getColumnCount() + 1; i++) {
if (!rsMetadata.getColumnName(i).equals(pkey)) {
insertUpdateMetodo.append("\n pstInsert.set" + setParam(rsMetadata.getColumnType(i)) + "(" + (++index) + ", obj.get" + rsMetadata.getColumnName(i) + "());");
}
}
insertUpdateMetodo.append("\n pstInsert.addBatch();");
insertUpdateMetodo.append("\n if(++count % batchSize == 0) {");
insertUpdateMetodo.append("\n pstInsert.executeBatch();");
insertUpdateMetodo.append("\n }");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n }else{");
insertUpdateMetodo.append("\n");
index = 0;
String where = "";
for (int i = 1; i < rsMetadata.getColumnCount() + 1; i++) {
if (!rsMetadata.getColumnName(i).equals(pkey)) {
insertUpdateMetodo.append("\n pstUpdate.set" + setParam(rsMetadata.getColumnType(i)) + "(" + (++index) + ", obj.get" + rsMetadata.getColumnName(i) + "());");
} else {
where = "\n pstUpdate.set" + setParam(rsMetadata.getColumnType(i)) + "(" + rsMetadata.getColumnCount() + ", obj.get" + rsMetadata.getColumnName(i) + "());";
}
}
insertUpdateMetodo.append(where);
insertUpdateMetodo.append("\n pstUpdate.addBatch();");
insertUpdateMetodo.append("\n if(++count % batchSize == 0) {");
insertUpdateMetodo.append("\n pstUpdate.executeBatch();");
insertUpdateMetodo.append("\n }");
insertUpdateMetodo.append("\n }");
insertUpdateMetodo.append("\n }");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n if(pstInsert != null){");
insertUpdateMetodo.append("\n pstInsert.executeBatch();");
insertUpdateMetodo.append("\n }");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n if(pstUpdate != null){");
insertUpdateMetodo.append("\n pstUpdate.executeBatch();");
insertUpdateMetodo.append("\n }");
insertUpdateMetodo.append("\n");
insertUpdateMetodo.append("\n }catch (Exception ex) {");
insertUpdateMetodo.append("\n throw new Exception(ex.getMessage()+\"\\n\"+this.getClass().getName()+\".salvar" + tableName + "()\");");
insertUpdateMetodo.append("\n } finally {");
insertUpdateMetodo.append("\n freeResources(rs, stm, null);");
insertUpdateMetodo.append("\n freeResources(null, pstUpdate, null);");
insertUpdateMetodo.append("\n freeResources(null, pstInsert, con);");
insertUpdateMetodo.append("\n }");
insertUpdateMetodo.append("\n }");
return insertUpdateMetodo.toString();
} | 9 |
public void testConstructorEx2_Type_int() throws Throwable {
try {
new Partial(DateTimeFieldType.dayOfYear(), 0);
fail();
} catch (IllegalArgumentException ex) {
// expected
}
} | 1 |
public void onKeyTyped(char c, int i)
{
if(i == KeyEvent.VK_ESCAPE || (int)c == KeyEvent.VK_ESCAPE)
{
if(this.currentGui == null)
this.setCurrentGui(new GuiMainMenu(null, 0, 0, this.getWidth(), this.getHeight()));
else
this.setCurrentGui(null);
}
if(this.currentGui != null)
this.currentGui.onKeyTyped(c, i);
} | 4 |
public void update(float dt) {
this.timeElapsed += dt;
if (timeElapsed > 1) {
this.canBeCaptured = true;
}
if (this.getBody() != null) {
Body body = this.getBody();
if (body.getPosition().x < 0 || body.getPosition().y < 0
|| body.getPosition().x > Gdx.graphics.getWidth() / Constants.WORLD_SCALE
|| body.getPosition().y > Gdx.graphics.getHeight() / Constants.WORLD_SCALE) {
body.setTransform(10 / Constants.WORLD_SCALE, 10 / Constants.WORLD_SCALE, body.getAngle());
}
}
} | 6 |
private static void handeClient() {
Socket link = null;
try {
/*
* Step 2: put the server into a waiting state
*/
link = serverSocket.accept();
/*
* Step 3 : set up input and output streams between the server and
* the client
*/
Scanner input = new Scanner(link.getInputStream());
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
int numMessages = 0;
String message = input.nextLine();
while (!message.equals("bye")) {
System.out.println("Message received.");
numMessages++;
/*
* Step 4 : Send and receive data
*/
// send data to output
output.println("Message " + numMessages + ": " + message);
// get data from input
input.nextLine();
}
output.println(numMessages + " messages received.");
} catch (IOException ioEx) {
ioEx.printStackTrace();
} finally {
try {
System.out.println("Closing connection...");
/*
* Step 5 : close the connection
*/
serverSocket.close();
} catch (Exception e) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
} | 3 |
public Connection getConnection()
{
if (conn == null) {
if (openConnection()) {
System.out.println("Connection opened");
return conn;
} else {
return null;
}
}
return conn;
} | 2 |
public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
if (fast != null) {
slow = slow.next;
}
}
ListNode prev = slow.next;
slow.next = null;
ListNode cur = null;
//reverse second half of the list
while (prev != null) {
ListNode next = prev.next;
prev.next = cur;
cur = prev;
prev = next;
}
ListNode first = head;
ListNode second = cur;
while (first != null && second != null && first != second) {
ListNode tmp = second.next;
second.next = first.next;
first.next = second;
first = second.next;
second = tmp;
}
} | 9 |
protected synchronized Runnable getTask()
throws InterruptedException
{
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable)taskQueue.removeFirst();
} | 2 |
private static boolean isPanlindrome(String s){
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(s.length()-i-1)) return false;
}
return true;
} | 2 |
public void setPriority(T item, double newPriority) throws NoSuchElementException {
int index;
try {
index = map.get(item);
} catch (NullPointerException npe) {
throw new NoSuchElementException();
}
PQElement<T> y = heap.get(index);
double oldPriority = y.priority;
y.priority = newPriority;
if ((orientation && newPriority < oldPriority) || (!orientation && newPriority > oldPriority)) {
rotateUp(index);
}
else
rotateDown(index);
} | 5 |
private boolean doesIntersectInternal(AbstractLineSegment other) {
final double d1 = direction(other.getP1(), other.getP2(), this.getP1());
final double d2 = direction(other.getP1(), other.getP2(), this.getP2());
final double d3 = direction(this.getP1(), this.getP2(), other.getP1());
final double d4 = direction(this.getP1(), this.getP2(), other.getP2());
if (d1 == 0 && isBetween(this.getP1(), other.getP1(), other.getP2())) {
return true;
}
if (d2 == 0 && isBetween(this.getP2(), other.getP1(), other.getP2())) {
return true;
}
if (d3 == 0 && isBetween(other.getP1(), this.getP1(), this.getP2())) {
return true;
}
if (d4 == 0 && isBetween(other.getP2(), this.getP1(), this.getP2())) {
return true;
}
final boolean result = signDiffers(d1, d2) && signDiffers(d3, d4);
assert this.intersectsLine(other) == result;
return result;
} | 9 |
public void add(K key, V value) {
List<V> values = this.map.get(key);
if (values == null) {
values = new LinkedList<V>();
this.map.put(key, values);
}
values.add(value);
} | 1 |
public void testMaximumValue() {
DateMidnight dt = new DateMidnight(1570, 1, 1, GJChronology.getInstance());
while (dt.getYear() < 1590) {
dt = dt.plusDays(1);
YearMonthDay ymd = dt.toYearMonthDay();
assertEquals(dt.year().getMaximumValue(), ymd.year().getMaximumValue());
assertEquals(dt.monthOfYear().getMaximumValue(), ymd.monthOfYear().getMaximumValue());
assertEquals(dt.dayOfMonth().getMaximumValue(), ymd.dayOfMonth().getMaximumValue());
}
} | 1 |
@Override
public void getResults(Course curr, StyledDocument doc) {
// TODO Auto-generated method stub
// Load the default style and add it as the "regular" text
Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
Style regular = doc.addStyle( "regular", def );
// Create a bold style
Style bold = doc.addStyle( "bold", regular );
StyleConstants.setBold( bold, true );
Map<String,Object> data = curr.getCourseInfo();
Set<String> keys = data.keySet();
Iterator<String> kIter = keys.iterator();
while(kIter.hasNext())
{
String key = kIter.next();
try {
if (key == CourseData.INSTRUCTOR.toString())
{
}
else
{
doc.insertString( doc.getLength(), key, bold);
doc.insertString(doc.getLength(), ": ",regular);
String val = curr.getValue(key).toString().replace("[", "");
val = val.replace("]", "");
doc.insertString(doc.getLength(), val + " ", regular);
}
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Object ins = curr.getValue(CourseData.INSTRUCTOR.toString());
if (ins != null)
{
try {
doc.insertString( doc.getLength(), CourseData.INSTRUCTOR.toString(), bold);
doc.insertString(doc.getLength(), ": ",regular);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String val = curr.getValue(CourseData.INSTRUCTOR.toString()).toString().replace("[", "");
val = val.replace("]", "");
ArrayList<String> names = (ArrayList<String>) ins;
for (int i = 0; i < names.size(); i++)
{
//ArrayList<String> names = parseNames(val);
//String text = names.get(i);
String text = parseNames(names.get(i));
String url = "http://google.com/search?btnI=1&q=site%3Ahttp%3A//www.ratemyprofessors.com/ShowRatings.jsp%3Ftid%3D%20%22York%20College%20of%20Pennsylvania%22" + text;
text = text.replace("%20", " ").trim();
try {
SimpleAttributeSet attr = new SimpleAttributeSet();
attr.addAttribute(StyleConstants.Underline, Boolean.TRUE);
attr.addAttribute(StyleConstants.Foreground, Color.BLUE);
SimpleAttributeSet hrefAttr = new SimpleAttributeSet();
hrefAttr.addAttribute(HTML.Attribute.HREF, url.toString());
SimpleAttributeSet attrs = new SimpleAttributeSet();
attrs.addAttribute(HTML.Tag.A, hrefAttr);
// Add the text along with its attributes.
int offset = doc.getLength();
int length = text.length();
doc.insertString(doc.getLength(), text, attr);
doc.setCharacterAttributes(offset, length, attrs, false);
//doc.setCharacterAttributes(offset, length, attr, false);
}
catch (BadLocationException e) {
e.printStackTrace(System.err);
}
}
try {
doc.insertString(doc.getLength(), " ", regular);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | 8 |
public void setAdditionalDisplay(JComponent additionalComponent) {
if (currentAdditionalDisplay == null && additionalComponent != null) {
if (flowLayout)
flowLayoutGatesPanel.setVisible(false);
else
nullLayoutGatesPanel.setVisible(false);
}
else if (currentAdditionalDisplay != null && additionalComponent == null) {
if (flowLayout)
flowLayoutGatesPanel.setVisible(true);
else
nullLayoutGatesPanel.setVisible(true);
}
super.setAdditionalDisplay(additionalComponent);
} | 6 |
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // paint background
// setBackground(Color.BLACK);
world.setUnit(player);
String report = "";
String victims = "";
for(AUnit u:player.getVictimList()){
victims = victims + " <br> " + u.getUnitName() + " was sunk !!! by " + player.getUnitName();
}
// victims = "<html>" + victims +"</html>";
for(Report r:player.getReports()){
report = report + " <br> " + r.getRangeReport() + " : " + r.getDirectionReport();
}
// report = "<html>" + report +"</html>";
String text = "<html>" + victims + "<br><br>" + report +"</html>";
reportLabel.setText(text);
Dimension size = reportLabel.getPreferredSize();
reportLabel.setBounds(10, 350,
size.width, size.height);
speedSlider.setMaximum((int)(player.getConfiguration().getMaxSpeedMs()/conversionFromKnotsToMs));
if(player.getType()==TYPE.DESTROER){
bombDepthLabel.setVisible(true);
bombDepthSlider.setVisible(true);
}else if(player.getType()==TYPE.SUBMARINE){
depthLabel.setVisible(true);
depthSlider.setVisible(true);
depthSlider.setValue(player.getCoordinates().getCoordinateH());
}
{
int num = 0;
Enumeration<AbstractButton> jREnum = targetGroup.getElements();
while(jREnum.hasMoreElements()){
remove(jREnum.nextElement());
}
for(AUnit u:player.getVisibleTargets()){
if(!u.isDestroyed()){
final JRadioButton button = new JRadioButton( u.getType().getDescription() + " : Position on " + (int)player.getPositionByTargetID(u.getUnitId()).getAnglePosition() + " : Distance : " + (int)player.getPositionByTargetID(u.getUnitId()).getDistance() + " meters");
button.setToolTipText(Long.toString(u.getUnitId()));
add(button);
targetGroup.add(button);
button.setVisible(true);
Dimension sizeButton = button.getPreferredSize();
if(num==0){
button.setSelected(true);
player.setUnderAttack(Game.getInstance().getUnitByID(u.getUnitId()));
}
button.setBounds(380, 100+num * 50,
sizeButton.width, sizeButton.height);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(((JRadioButton)e.getSource()).getToolTipText());
player.setUnderAttack(Game.getInstance().getUnitByID(Long.valueOf(((JRadioButton)e.getSource()).getToolTipText())));
}
});
num++;
}
}
}
} | 8 |
public WordProcessing()
{
} | 0 |
public int compare(String[] o1, String[] o2) {
int result = 0;
for (int i=0;i<o1.length && i<o2.length;i++) {
String s1 = o1[i];
String s2 = o2[i];
if (s1 == null) {
if (s2 == null) {
result = 0;
} else {
result = 1;
}
} else {
if (s2 == null) {
result = -1;
} else {
result = s1.compareTo(s2);
}
}
if (result != 0) {
break;
}
}
if (result == 0) {
if (o1.length < o2.length) {
result = -1;
} else if (o1.length > o2.length) {
result = 1;
}
}
return result;
} | 9 |
public UpgradeMenu(ProBotGame game) {
super(game);
bodypartPanel = new JPanel();
upgradePanel = new JPanel();
} | 0 |
public void setTransitionsFromTuringFinalStateAllowed(boolean t) {
transTuringFinal = t;
transTuringFinalCheckBox.setSelected(t);
} | 0 |
public JSONObject getQuestionsTag(int USER_ID)
{
try {
Class.forName(JDBC_DRIVER);
conn=DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmt2=conn.createStatement();
stmt=conn.createStatement();
json=new JSONObject();
json.put(SUCCESS, 1);
ResultSet rstemp=stmt2.executeQuery("select * from LOGIN_INFO where USER_ID="+USER_ID);
rs=stmt.executeQuery("Select * from QUESTIONS");
if(rstemp.isBeforeFirst())
{
if(rs.isBeforeFirst())
{
JSONArray questions=new JSONArray();
JSONObject object;
while(rs.next())
{
object=new JSONObject();
object.put("QUESTION_ASKED", rs.getString("QUESTION_ASKED"));
object.put("QUESTION_ID", rs.getInt("QUESTION_ID"));
questions.add(object);
}
json.put("QUESTIONS", questions);
rs.close();
}
else
{
json.put(SUCCESS, 0);
json.put(MESSAGE, "No Questions have been posted yet");
}
rstemp.close();
stmt2.close();
stmt.close();
}else
{
json.put(SUCCESS, 0);
json.put(MESSAGE, "Not a valid User");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally
{
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
return json;
} | 7 |
public boolean logar(String login,String senha) throws UnknownHostException, IOException{
if(!login.equals("") && !senha.equals("") && login!=null && senha!=null){
Usuario usuario = new Usuario();
usuario.setSenha(senha);
usuario.setUsuario(login);
Conexao conexao = new Conexao(12345);
conexao.conectar(usuario);
return true;
} else {
return false;
}
} | 4 |
@Override
protected List<URI> parseInternal(BufferedReader in) throws IOException {
try {
SAXSearchResultParser parser = new SAXSearchResultParser();
parser.parse(new InputSource(in));
List<String> resultStrings = parser.getResults();
List<URI> results = new ArrayList<>(resultStrings.size());
for (String result : resultStrings) {
try {
results.add(new URI(result));
} catch (URISyntaxException e) {
log.warn("Could not parse uri: " + result, e);
}
}
return results;
} catch (SAXException e) {
log.log(Level.ERROR, "Could not parse search results!", e);
return null;
}
} | 3 |
public int peek(boolean fromDiscard){
if (fromDiscard)
return discard_count == 0 ? 0 : discard[discard_count-1];
return draw_count == 0 ? 0 : draw[draw_count-1];
} | 3 |
public void outputReport() throws IOException
{
ListMultimap<String, String[]> commonMap =
Multimaps.newListMultimap( new TreeMap<String, Collection<String[]>>()
, new Supplier<ArrayList<String[]>>()
{
@Override
public ArrayList<String[]> get() {
return new ArrayList<String[]>();
}
}
);
PrintWriter reportOut = new PrintWriter(new File("target/output/report"));
for(PoliticalOrientation orientation : PoliticalOrientation.values())
{
File outputFile = new File("target/output/" + orientation);
PrintWriter out = new PrintWriter(new File("target/output/" + orientation + "/report"));
File[] parts = outputFile.listFiles(new FilenameFilter()
{
@Override
public boolean accept(File arg0, String arg1) {
if(arg1.startsWith("part-"))
{
return true;
}
return false;
}
}
);
final List<String> output = new ArrayList<String>();
Comparator<String> comparator = new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
ArrayList<String> firstSplit = Lists.newArrayList(Splitter.on('\t')
.split(o1));
ArrayList<String> secondSplit = Lists.newArrayList(Splitter.on('\t')
.split(o2));
return ComparisonChain.start()
.compare(Double.parseDouble(firstSplit.get(0)), Double.parseDouble(secondSplit.get(0)))
.compare(firstSplit.get(1), secondSplit.get(1))
.compare(firstSplit.get(2), secondSplit.get(2))
.result();
}
};
for(File part : parts)
{
Files.readLines( part
, Charsets.US_ASCII
, new LineProcessor<Void>()
{
@Override
public Void getResult() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean processLine(String line)
throws IOException
{
output.add(line);
return true;
}
}
);
}
Collections.sort(output, comparator);
int cnt = 0;
for(String line : output)
{
if(cnt++ < 200)
{
ArrayList<String> split = Lists.newArrayList(Splitter.on('\t')
.split(line));
commonMap.put(split.get(1), new String[] {orientation.toString() , line});
}
out.println(line);
}
out.close();
}
for(Entry<String, Collection<String[]>> entry : commonMap.asMap().entrySet())
{
if(entry.getValue().size() == 1)
{
String[] value = entry.getValue().iterator().next();
reportOut.println(value[0] + "\t" + value[1]);
}
}
reportOut.close();
} | 7 |
private static String getFileContents(String filename)
throws IOException, FileNotFoundException
{
File file = new File(filename);
StringBuilder contents = new StringBuilder();
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null;
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
return contents.toString();
} | 1 |
private double parseAngleFields(JTextField degrees, JTextField minutes,
JTextField seconds) {
double d, m, s;
try {
d = Double.parseDouble(degrees.getText());
} catch (NumberFormatException nfe) {
d = 0.0;
}
try {
m = Double.parseDouble(minutes.getText());
} catch (NumberFormatException nfe) {
m = 0.0;
}
try {
s = Double.parseDouble(seconds.getText());
} catch (NumberFormatException nfe) {
s = 0.0;
}
return d + m / 60.0 + s / 3600.0;
} | 3 |
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerDeathInArena(PlayerDeathInArenaEvent evt) {
Player victim = evt.getVictim();
if (evt.getCause() == DeathCause.ENVIRONMENT) {
String lastAttacker = SE.getStorage(victim.getName()).getLastHit();
@SuppressWarnings("deprecation")
Player killer = Bukkit.getServer().getPlayer(lastAttacker);
if (killer != null) {
Bukkit.getServer().getPluginManager().callEvent(new PlayerKilledPlayerInArenaEvent(victim, killer));
}
}
} | 2 |
public synchronized void addCommandLineListener(CommandLineListener listener){
List<CommandLineListener> listeners = new ArrayList<CommandLineListener>();
if (this.listeners != null){
listeners.addAll(this.listeners);
}
if (!listeners.contains(listener)){
listeners.add(listener);
}
this.listeners = listeners;
} | 2 |
@Test
public void testBigMerge() {
Random r = new Random(260379);
TreeMap<Integer, Integer> leftSet = new TreeMap<Integer, Integer>();
TreeMap<Integer, Integer> rightSet = new TreeMap<Integer, Integer>();
// There must be collisions and also some omissions
for(int i=0; i < 4001; i++) {
leftSet.put(r.nextInt(4000), r.nextInt(1000));
rightSet.put(r.nextInt(4000), r.nextInt(1000));
}
// Compose
ArrayList<Integer> leftArray = new ArrayList<Integer>(4000);
for(Map.Entry<Integer ,Integer> e : leftSet.entrySet()) {
for(int j=0; j<e.getValue(); j++) leftArray.add(e.getKey());
}
ArrayList<Integer> rightArray = new ArrayList<Integer>(4000);
for(Map.Entry<Integer ,Integer> e : rightSet.entrySet()) {
for(int j=0; j<e.getValue(); j++) rightArray.add(e.getKey());
}
DiscreteDistribution leftDist = new DiscreteDistribution(toIntArray(leftArray));
DiscreteDistribution rightDist = new DiscreteDistribution(toIntArray(rightArray));
DiscreteDistribution mergedDist1 = DiscreteDistribution.merge(leftDist, rightDist);
DiscreteDistribution mergedDist2 = DiscreteDistribution.merge(rightDist, leftDist);
for(int i=0; i < 5000; i++) {
int lc = (leftSet.containsKey(i) ? leftSet.get(i) : 0);
int rc = (rightSet.containsKey(i) ? rightSet.get(i) : 0);
assertEquals(lc, leftDist.getCount(i));
assertEquals(rc, rightDist.getCount(i));
assertEquals(lc + rc, mergedDist1.getCount(i));
assertEquals(lc + rc, mergedDist2.getCount(i));
}
} | 8 |
public Object newArray(String type, int[] dimensions)
throws InterpreterException, NegativeArraySizeException {
if (type.length() == dimensions.length + 1) {
Class clazz;
try {
clazz = TypeSignature.getClass(type
.substring(dimensions.length));
} catch (ClassNotFoundException ex) {
throw new InterpreterException("Class " + ex.getMessage()
+ " not found");
}
return Array.newInstance(clazz, dimensions);
}
throw new InterpreterException("Creating object array.");
} | 2 |
private void selectWord(MouseEvent e) {
if (selectedWordEvent != null
&& selectedWordEvent.getX() == e.getX()
&& selectedWordEvent.getY() == e.getY()) {
// We've already the done selection for this.
return;
}
Action a = null;
RTextArea textArea = getTextArea();
ActionMap map = textArea.getActionMap();
if (map != null) {
a = map.get(RTextAreaEditorKit.selectWordAction);
}
if (a == null) {
if (selectWord == null) {
selectWord = new RTextAreaEditorKit.SelectWordAction();
}
a = selectWord;
}
a.actionPerformed(new ActionEvent(textArea,
ActionEvent.ACTION_PERFORMED,
null, e.getWhen(), e.getModifiers()));
selectedWordEvent = e;
} | 6 |
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
if (i != 0) {
buf.append(this.delimiter);
}
buf.append("" + data[i]);
}
return buf.toString();
} | 2 |
public void addEdge(Vertex v, Vertex w) {
if (!adjMap.containsKey(v)) {
adjMap.put(v, new HashBag<Vertex>());
}
if (!adjMap.containsKey(w)) {
adjMap.put(w, new HashBag<Vertex>());
}
adjMap.get(v).add(w);
adjMap.get(w).add(v);
} | 2 |
public void draw(Graphics2D g) {
if (gameStates[currentState] != null)
gameStates[currentState].draw(g);
else {
g.setColor(Color.BLACK);
g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT);
}
} | 1 |
@Override
public String onAttack(L2Npc npc, L2PcInstance attacker, int damage, boolean isPet)
{
if (npc instanceof L2ChestInstance)
{
final L2ChestInstance chest = ((L2ChestInstance) npc);
// If this has already been interacted, no further AI decisions are needed.
if (!chest.isInteracted())
{
chest.setInteracted();
// If it was a box, cast a suicide type skill.
if (Rnd.get(100) < IS_BOX)
chest.doCast(SkillTable.getInstance().getInfo(4143, Math.min(10, Math.round(npc.getLevel() / 10))));
// Mimic behavior : attack the caster.
else
attack(chest, ((isPet) ? attacker.getPet() : attacker), ((damage * 100) / (chest.getLevel() + 7)));
}
}
return super.onAttack(npc, attacker, damage, isPet);
} | 4 |
public String getUniversity() {
return this.university;
} | 0 |
private PropertyDescriptor getWriteMethod(Field field) throws Exception {
PropertyDescriptor descriptor = null;
String fieldName = field.getName();
try {
PropertyDescriptor[] descriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : descriptors) {
if (propertyDescriptor.getWriteMethod() != null
&& fieldToDescriptor(propertyDescriptor, fieldName)) {
descriptor = propertyDescriptor;
break;
}
}
} catch (IntrospectionException ex) {
Logger.getLogger(EntityReadProperties.class.getName()).log(Level.SEVERE, null, ex);
}
return descriptor;
} | 4 |
public static void main(String[] args)
{
AccessRight accessRight = AccessRight.MANAGER;
AccessRight accessRight1 = AccessRight.valueOf("DEPARTMENT");
chechAccess(accessRight);
chechAccess(accessRight1);
} | 0 |
private void btnModificarEmpleadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarEmpleadoActionPerformed
//creamos un empleado temporal, a partir del renglón seleccionado en la tabla:
Empleado empleadoTemporal = obtenerInformacionDeRenglonSelecccionado();
/*Si el empleado temporal fue nulo, entonces no se seleccionó
alguno de la tabla, por eso nos interesa más cuando no
sea nulo, es el caso más común:*/
if (empleadoTemporal != null) {
//obtenemos la instancia de la ventana:
VtnAgrega_oModificaEmpleados vtnModificaEmpleado = VtnAgrega_oModificaEmpleados.getInstanciaVtnAgregaoModificaEmpleado();
//Obtenemos el id del empleado que se seleccionó en la tabla:
String id = Integer.toString(empleadoTemporal.getIdPersona());
/*El id del empleado que aparece en la tabla, lo ponemos
en el JTextField de la siguiente Ventana: */
vtnModificaEmpleado.getTxtIdEmpleado().setText(id);
//Obtenemos el nombre del empleado que se seleccionó en la tabla:
String nombre = empleadoTemporal.getNombrePersona();
/*El nombre del empleado que aparece en la tabla, lo ponemos
en el JTextField de la siguiente Ventana: */
vtnModificaEmpleado.getTxtNombreEmpleado().setText(nombre);
//Obtenemos la direccción del empleado que se seleccionó en la tabla:
String direccion = empleadoTemporal.getDireccionPersona();
/*La dirección del empleado que aparece en la tabla, lo ponemos
en el JTextField que le corresponde, de la siguiente Ventana: */
vtnModificaEmpleado.getTxtDireccionEmpleado().setText(direccion);
//Obtenemos el teléfono del empleado que se seleccionó en la tabla:
String telefono = empleadoTemporal.getTelefonoPersona();
/*El teléfono del empleado que aparece en la tabla, lo ponemos
en el JTextField que le corresponde, de la siguiente Ventana: */
vtnModificaEmpleado.getTxtTelefonoEmpleado().setText(telefono);
//Obtenemos el correo del empleado que se seleccionó en la tabla:
String correo = empleadoTemporal.getCorreoPersona();
/*El correo del empleado que aparece en la tabla, lo ponemos
en el JTextField que le corresponde, de la siguiente Ventana: */
vtnModificaEmpleado.getTxtCorreoEmpleado().setText(correo);
//Obtenemos el sueldo del empleado que se seleccionó en la tabla:
float sueldo = empleadoTemporal.getEmpSueldo();
/*El correo del empleado que aparece en la tabla, lo ponemos
en el JTextField que le corresponde, de la siguiente Ventana: */
vtnModificaEmpleado.getTxtSueldoEmpleado().setText(Float.toString(sueldo));
//Obtenemos el sueldo del empleado que se seleccionó en la tabla:
float desempenio = empleadoTemporal.getEmpDesempenio();
if (desempenio == vtnModificaEmpleado.getValCbDesempenio1()) {
vtnModificaEmpleado.getCbDesempenio1().setSelected(true);
}
if (desempenio == vtnModificaEmpleado.getValCbDesempenio2()) {
vtnModificaEmpleado.getCbDesempenio2().setSelected(true);
}
if (desempenio == vtnModificaEmpleado.getValCbDesempenio3()) {
vtnModificaEmpleado.getCbDesempenio3().setSelected(true);
}
if (desempenio == vtnModificaEmpleado.getValCbDesempenio4()) {
vtnModificaEmpleado.getCbDesempenio4().setSelected(true);
}
if (desempenio == vtnModificaEmpleado.getValCbDesempenio5()) {
vtnModificaEmpleado.getCbDesempenio5().setSelected(true);
}
//le ponemos el título a la ventana:
vtnModificaEmpleado.setTitle("Modificará la información de un empleado");
/*ponemos en verdadero un booleano, indicando que
se modificará un empleado: */
vtnModificaEmpleado.setSeModificaraEmpleado(true);
//hacemos visible la ventana:
vtnModificaEmpleado.setVisible(true);
vtnModificaEmpleado.setEmpleadoDeLaTabla(empleadoTemporal);
//cerramos esta ventana:
cerrarEstaVentana();
} else {
//quiere decir que el usuario no ha seleccionado algún empleado
//la tabla:
mostrarMensajeEnPantalla("No seleccionaste algún empleado de la tabla.");
}
}//GEN-LAST:event_btnModificarEmpleadoActionPerformed | 6 |
public int getAttemptsLeft(){ return ReconnectAttempts; } | 0 |
public void destroy() {
if (!stopped) {
try {
worker.join();
} catch (InterruptedException e) {
}
try {
selector.close();
} catch (IOException e) {
}
}
} | 3 |
public DisPane(){
super();
} | 0 |
@SuppressWarnings("unchecked")
private <T> TypedStringConverter<T> findConverterQuiet(final Class<T> cls) {
if (cls == null) {
throw new IllegalArgumentException("Class must not be null");
}
TypedStringConverter<T> conv = (TypedStringConverter<T>) registered.get(cls);
if (conv == CACHED_NULL) {
return null;
}
if (conv == null) {
try {
conv = findAnyConverter(cls);
} catch (RuntimeException ex) {
registered.putIfAbsent(cls, CACHED_NULL);
throw ex;
}
if (conv == null) {
registered.putIfAbsent(cls, CACHED_NULL);
return null;
}
registered.putIfAbsent(cls, conv);
}
return conv;
} | 5 |
private void writeSymbolMap() throws IOException {
BZip2BitOutputStream bitOutputStream = this.bitOutputStream;
final boolean[] blockValuesPresent = this.blockValuesPresent;
final boolean[] condensedInUse = new boolean[16];
for (int i = 0; i < 16; i++) {
for (int j = 0, k = i << 4; j < 16; j++, k++) {
if (blockValuesPresent[k]) {
condensedInUse[i] = true;
}
}
}
for (int i = 0; i < 16; i++) {
bitOutputStream.writeBoolean (condensedInUse[i]);
}
for (int i = 0; i < 16; i++) {
if (condensedInUse[i]) {
for (int j = 0, k = i * 16; j < 16; j++, k++) {
bitOutputStream.writeBoolean (blockValuesPresent[k]);
}
}
}
} | 7 |
public boolean checkRoom(int... pos) {
if (pos.length != 2)
return true;
if (openedRooms[pos[0]][pos[1]])
return false;
if (openedRoomsCount >= structure.getRoomsCount()) // cant happen
return true;
Room room = structure.getRooms()[pos[0]][pos[1]];
if (room == null)
return true;
openedRooms[pos[0]][pos[1]] = true;
openedRoomsCount++;
final int roomRegionX = mapBaseCoords[0] + (pos[0] * 2);
final int roomRegionY = mapBaseCoords[1] + (pos[1] * 2);
RegionBuilder.copy2RatioSquare(room.getRegionX(),
room.getRegionY(), roomRegionX, roomRegionY,
structure.getRotations()[pos[0]][pos[1]]);
int regionId = (((roomRegionX / 8) << 8) + (roomRegionY / 8));
for (Player player : team) {
if (!player.getMapRegionsIds().contains(regionId)) // if player
// is to
// far... no
// need to
// reload,
// he will
// reload
// when walk
// to that
// room
continue;
player.setForceNextMapLoadRefresh(true);
player.loadMapRegions();
}
return true;
} | 6 |
@Override
public int compareTo(final TPair64 p) {
return u == p.u ? 0 : ((u < p.u) ^ (u < 0) ^ (p.u < 0)) ? -1 : 1; // unsigned 64-bit comparison
} | 2 |
public void findBestSystem() {
for (SoftwareSystem softwareSystem : systems)
softwareSystem.refine();
bestSoftwareSystemEP = systems.get(0);
bestSoftwareSystemW = systems.get(0);
worstSoftwareSystemEP = systems.get(0);
worstSoftwareSystemW = systems.get(0);
for (SoftwareSystem softwareSystem : systems) {
if (softwareSystem.getSystemConsumptionEP() < bestSoftwareSystemEP.getSystemConsumptionEP())
bestSoftwareSystemEP = softwareSystem;
else if (softwareSystem.getSystemConsumptionEP() > worstSoftwareSystemEP.getSystemConsumptionEP())
worstSoftwareSystemEP = softwareSystem;
if (softwareSystem.getSystemConsumptionW() < bestSoftwareSystemW.getSystemConsumptionW())
bestSoftwareSystemW = softwareSystem;
else if (softwareSystem.getSystemConsumptionW() > worstSoftwareSystemW.getSystemConsumptionW())
worstSoftwareSystemW = softwareSystem;
}
} | 6 |
public boolean hasOverdueItems(){
boolean overdueItemFound = false;
for(Copy copy : itemsBorrowed){
if(copy.isOverdue()){
overdueItemFound = true;
}
}
for(Copy copy : booksBorrowed){
if(copy.isOverdue()){
overdueItemFound = true;
}
}
return overdueItemFound;
} | 4 |
public void setExtraData(String extraData) {
this.extraData=extraData;
} | 0 |
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int H, U, D, F;
while (true) {
H = sc.nextInt();
if (H == 0) {
break;
}
U = sc.nextInt();
D = sc.nextInt();
F = sc.nextInt();
F = U * F;
U *= 100;
D *= 100;
H *= 100;
int snailPosition = 0;
int daysCount = 0;
boolean reached = false;
while (true) {
daysCount++;
snailPosition += U;
if (snailPosition > H) {
reached = true;
break;
}
snailPosition -= D;
U -= F;
if(U<0)
U=0;
if (snailPosition < 0) {
break;
}
}
if (reached) {
System.out.print("success");
} else {
System.out.print("failure");
}
System.out.println(" on day " + daysCount);
}
} | 7 |
@EventHandler
public void IronGolemHunger(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.getIronGolemConfig().getDouble("IronGolem.Hunger.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if (plugin.getIronGolemConfig().getBoolean("IronGolem.Hunger.Enabled", true) && damager instanceof IronGolem && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, plugin.getIronGolemConfig().getInt("IronGolem.Hunger.Time"), plugin.getIronGolemConfig().getInt("IronGolem.Hunger.Power")));
}
} | 6 |
@Override
public void paintComponent(Graphics g) {
// couleur de fond pour le rectangle qui est affiche pour
// ne pas avoir de trainee mais un objet qui bouge
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
//on dessine flakboy
g.setColor(Color.RED);
g.fillOval((int)this.uneSimulation.getFlackBoy().getX(), (int)(this.uneSimulation.getDimensionTerrain().getHauteur() - this.uneSimulation.getFlackBoy().getY()), this.uneSimulation.getFlackBoy().getLargeur(), this.uneSimulation.getFlackBoy().getHauteur());
// coloration du mur gauche
g.setColor(Color.BLUE);
g.fillRect(0,0, 5,this.uneSimulation.getDimensionTerrain().getLargeur());
//System.out.println("COO DESSIN MUR GAUCHE");
//System.out.println(""+0+""+0+""+20+""+this.uneSimulation.getDimensionTerrain().getLargeur());
// coloration du mur droit
g.setColor(Color.BLUE);
g.fillRect(this.uneSimulation.getDimensionTerrain().getLargeur()-Para.EPAISSEUR_MUR,0,Para.EPAISSEUR_MUR,this.uneSimulation.getDimensionTerrain().getHauteur());
//System.out.println("COO DESSIN MUR DROIT");
//System.out.println(""+(this.uneSimulation.getDimensionTerrain().getLargeur()-20)+""+0+""+20+""+this.uneSimulation.getDimensionTerrain().getHauteur());
// coloration du plafond
g.setColor(Color.BLUE);
g.fillRect(0,0, this.uneSimulation.getDimensionTerrain().getLargeur(),Para.EPAISSEUR_MUR);
//System.out.println("COO DESSIN PLAFOND");
//System.out.println(""+0+""+0+""+this.uneSimulation.getDimensionTerrain().getLargeur()+""+20);
// coloration du sol
g.setColor(Color.BLUE);
g.fillRect(0,this.uneSimulation.getDimensionTerrain().getHauteur()-Para.MYSTERE_GRAPH-Para.EPAISSEUR_MUR,this.uneSimulation.getDimensionTerrain().getLargeur(),Para.EPAISSEUR_MUR);
//System.out.println("COO DESSIN SOL");
//System.out.println(""+0+""+(this.uneSimulation.getDimensionTerrain().getHauteur()-50)+""+this.uneSimulation.getDimensionTerrain().getLargeur()+""+20);
// x = super.getTerrain().getLargeur() - super.getEpaisseur() - 5;
// y = super.getDebut()+132;
// largeur = super.getEpaisseur();
// hauteur = super.getLongueurCoteBord();
//
// x = (int)this.getForme().getX()-100;
// y = (int)this.getForme().getY()+100;
// largeur = (int)this.getForme().getWidth()+100;
// hauteur = (int)this.getForme().getHeight()+100;
g.setColor(Color.MAGENTA);
g.drawRect(this.uneSimulation.getDimensionTerrain().getLargeur()-110-Para.EPAISSEUR_MUR, this.uneSimulation.getDimensionTerrain().getHauteur()-450-Para.MYSTERE_MOTEUR, 110, 200);
g.drawRect(Para.EPAISSEUR_MUR+110, this.uneSimulation.getDimensionTerrain().getHauteur()-450-Para.MYSTERE_MOTEUR, 110, 200);
//System.out.println("\n$$$$$$$$$$$$$$$X = "+(this.uneSimulation.getDimensionTerrain().getLargeur()-110-5)+" Y = "+(this.uneSimulation.getDimensionTerrain().getHauteur()-450-Para.MYSTERE_GRAPH)+" LARGEUR = "+110+" EPAISSEUR = "+200);
// boucle qui va dessiner les armes dynamiquement
for (int i=0 ; i<this.uneSimulation.getListeArmes().size() ; i++) {
//Couleur differente selon arme
if(this.uneSimulation.getListeArmes().get(i).getNom().equals("Mine")) {
g.setColor(Color.BLACK);
} else if(this.uneSimulation.getListeArmes().get(i).getNom().equals("Eksasaute")){
g.setColor(Color.PINK);
} else if(this.uneSimulation.getListeArmes().get(i).getNom().equals("Pique")){
g.setColor(Color.GREEN);
}
// pour savoir sur quel mur est posée l'amre
switch (this.uneSimulation.getListeArmes().get(i).getBord()) {
case haut:
g.fillRect(this.uneSimulation.getListeArmes().get(i).getDebut(),Para.EPAISSEUR_MUR,this.uneSimulation.getListeArmes().get(i).getLongueurCoteBord(),this.uneSimulation.getListeArmes().get(i).getEpaisseur());
break;
case bas:;
g.fillRect(this.uneSimulation.getListeArmes().get(i).getDebut(),(this.uneSimulation.getDimensionTerrain().getHauteur()-Para.MYSTERE_GRAPH-this.uneSimulation.getListeArmes().get(i).getEpaisseur()-Para.EPAISSEUR_MUR),this.uneSimulation.getListeArmes().get(i).getLongueurCoteBord(),this.uneSimulation.getListeArmes().get(i).getEpaisseur());
break;
case droit:
g.fillRect((this.uneSimulation.getDimensionTerrain().getLargeur()-this.uneSimulation.getListeArmes().get(i).getEpaisseur()-Para.EPAISSEUR_MUR),this.uneSimulation.getDimensionTerrain().getHauteur()-this.uneSimulation.getListeArmes().get(i).getDebut()-Para.MYSTERE_MOTEUR,this.uneSimulation.getListeArmes().get(i).getEpaisseur(),this.uneSimulation.getListeArmes().get(i).getLongueurCoteBord());
break;
case gauche:
g.fillRect(Para.EPAISSEUR_MUR,this.uneSimulation.getDimensionTerrain().getHauteur()-this.uneSimulation.getListeArmes().get(i).getDebut()-Para.MYSTERE_MOTEUR,this.uneSimulation.getListeArmes().get(i).getEpaisseur(),this.uneSimulation.getListeArmes().get(i).getLongueurCoteBord());
break;
default:
System.out.println("BUG OMG !");
}
}
} | 8 |
public void startWave() {
if(stage != Stages.RUNNING)
return;
int currentWave = getCurrentWave();
player.getInterfaceManager().sendTab(player.getInterfaceManager().hasRezizableScreen() ? 11 : 0, 316);
player.getPackets().sendConfig(639, currentWave);
if(currentWave > WAVES.length) {
if(currentWave == 37)
aliveNPCSCount = 1;
return;
}else if (currentWave == 0) {
exitCave(1);
return;
}
aliveNPCSCount = WAVES[currentWave-1].length;
for(int i = 0; i < WAVES[currentWave-1].length; i += 4) {
final int next = i;
CoresManager.fastExecutor.schedule(new TimerTask() {
@Override
public void run() {
try {
if(stage != Stages.RUNNING)
return;
spawn(next);
} catch (Throwable e) {
Logger.handle(e);
}
}
}, (next / 4) * 4000);
}
} | 8 |
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
if((buildingI!=null)&&(!aborted))
{
if(messedUp)
{
if(activity == CraftingActivity.LEARNING)
commonEmote(mob,L("<S-NAME> fail(s) to learn how to make @x1.",buildingI.name()));
else
commonTell(mob,L("@x1 explodes!",CMStrings.capitalizeAndLower(buildingI.name(mob))));
buildingI.destroy();
}
else
if(activity==CraftingActivity.LEARNING)
{
deconstructRecipeInto( buildingI, recipeHolder );
buildingI.destroy();
}
else
{
dropAWinner(mob,buildingI);
CMLib.achievements().possiblyBumpAchievement(mob, AchievementLibrary.Event.CRAFTING, 1, this);
}
}
buildingI=null;
}
}
super.unInvoke();
} | 7 |
public void keyReleased(KeyEvent e) {
//Para la entrega Alpha, una vez que se haya inicado el juego, se presiona la tecla 2 para ir al nivel 2, la tecla 3 para ir al nivel 3
// y la tecla G para terminar el juego
if (nivel > 0) {
if (e.getKeyCode() == KeyEvent.VK_G) {
gameOver = true;
nivel = 0;
}
if (e.getKeyCode() == KeyEvent.VK_2) {
resetNivel();
}
if (e.getKeyCode() == KeyEvent.VK_P) {
pausa = !pausa;
}
}
} | 4 |
public int getType() {
if (doc != null) {
return TYPE_DOC;
} else if (file != null) {
return TYPE_FILE;
} else {
return TYPE_UNKNOWN;
}
} | 2 |
public CheckResultMessage checkJ02(int day) {
return checkReport.checkJ02(day);
} | 0 |
public void resize(int x, int y){
Patch[][] newGrid = new Patch[y][x];
for (int i = 0; i<y; i++){
for (int j = 0; j<x; j++){
if (i<getHeight() && j<getWidth()){
newGrid[i][j] = _grid[i][j];
}
else
newGrid[i][j] = new Patch(this, j, i);
}
}
_grid = newGrid;
} | 4 |
public boolean isAuthorized(String password) {
if (encryptionDictionary.getRevisionNumber() < 5){
boolean value = standardEncryption.authenticateUserPassword(password);
// check password against user password
if (!value) {
// check password against owner password
value = standardEncryption.authenticateOwnerPassword(password);
// Get user, password, as it is used for generating encryption keys
if (value) {
this.password = standardEncryption.getUserPassword();
}
} else {
// assign password for future use
this.password = password;
}
return value;
}else if (encryptionDictionary.getRevisionNumber() == 5){
// try and calculate the document key.
byte[] encryptionKey = standardEncryption.encryptionKeyAlgorithm(
password,
encryptionDictionary.getKeyLength());
this.password = password;
return encryptionKey != null;
}else{
return false;
}
} | 4 |
@After
public void tearDown()
{
eventBus = null;
} | 0 |
@Override
public void run() {
final IdFactory _id = IdFactory.getInstance();
_idConection = _id.newId();
getLogger().log(Level.INFO, "Client Thread Started ...");
try {
_connection.sendPacket(new SHello(_idConection, "09928"));
boolean _while = true;
while (_while) {
// System.out.println("czekam na odpowiedz");
final byte[] decrypt = _connection.getPacket();
if (decrypt != null) {
_handler.handlePacket(decrypt);
} else {
_while = false;
}
// System.out.println("odebralem");
}
} catch (final IOException ex) {
getLogger().log(Level.SEVERE, null, ex);
} catch (final Throwable ex) {
getLogger().log(Level.SEVERE, null, ex);
} finally {
try {
try {
} catch (final Exception e2) {
// ignore any problems here
}
// _connection.close();
} catch (final Exception e1) {
getLogger().log(Level.WARNING, e1.getMessage());
} finally {
try {
if (_activeChar != null) // this should only happen on
// connection loss
{
// notify the world about our disconnect
_activeChar.deleteMe();
try {
saveCharToDataBase(_activeChar);
} catch (final Exception e2) {
// ignore any problems here
}
}
_connection.close();
} catch (final Exception e1) {
} finally {
// remove the account
}
}
// remove the account
}
IdFactory.getInstance().deleteId(_idConection);
getLogger().log(Level.INFO, "gameserver thread[C] stopped");
} | 9 |
public String mapSignature(String signature, boolean typeSignature) {
if (signature == null) {
return null;
}
SignatureReader r = new SignatureReader(signature);
SignatureWriter w = new SignatureWriter();
SignatureVisitor a = createRemappingSignatureAdapter(w);
if (typeSignature) {
r.acceptType(a);
} else {
r.accept(a);
}
return w.toString();
} | 2 |
public void setLastName(String lastName) {
LastName = lastName;
} | 0 |
public static void add(String playerUUID, String regionName) {
ArrayList<String> places = Spectacles.storedPlayerData.get(playerUUID);
if (!places.contains(regionName)) {
places.add(regionName);
}
Spectacles.storedPlayerData.put(playerUUID, places);
save(Spectacles.storedPlayerData, Spectacles.getInstance()
.getDataFolder() + File.separator + "playerdata.bin");
} | 1 |
public static void Severe(String s){ log.info("[AprilonIRC] " + s); } | 0 |
private void checkTypeName( String typeName ) {
if( !typeName.matches( "[a-zA-Z0-9]+" ) ) {
throw new IllegalArgumentException( "typeName contains not supported characters: " + typeName );
}
} | 1 |
public static void validateUser(UserTO userTO) throws ParameterValidationException{
System.out.println("Validating userTO");
//Evaluating name
System.out.println("Evaluating name");
String name = userTO.getName();
if(!name.matches("[a-zA-Z ]+")){
throw new ParameterValidationException("The name cannot contain numbers of special characters");
}
//Evaluating email
System.out.println("Evaluating email");
String email = userTO.getEmail();
if(!email.matches("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$")){
throw new ParameterValidationException("Invalid email ID");
}
//Evaluating DOB
System.out.println("Evaluating DOB");
String dob = userTO.getDob();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat databaseFormat = new SimpleDateFormat("dd-MMM-yyyy");
simpleDateFormat.setLenient(false);
try {
Date date = simpleDateFormat.parse(dob);
userTO.setDob(databaseFormat.format(date));
} catch (ParseException e) {
throw new ParameterValidationException("The Format of Date of Birth is invalid");
}
//Evaluating Mobile number
System.out.println("Evaluating mobile number");
String mobile = userTO.getMobile();
if(!mobile.matches("[0-9]{10}")){
throw new ParameterValidationException("Invalid mobile number");
}
//Evaluating AccountNo
System.out.println("Evaluating account number");
String accountNo = userTO.getAccountNo();
if(!accountNo.matches("[a-zA-Z0-9]+")){
throw new ParameterValidationException("Invalid Account Number");
}
//Evaluating IFSC Code
System.out.println("Evaluating IFSC Code");
String ifsc = userTO.getIfsc();
if(!ifsc.matches("[a-zA-Z0-9]+")){
throw new ParameterValidationException("Invalid IFSC Code");
}
} | 6 |
public double maxValue(KrakenState state, String player, double alpha, double beta) {
if (expandedNodes==maxNodesExpand || game.isTerminal(state)){
if (heuristics==null)
return heuristic.h(state);
else
return getHeuristicFusion(state);
}
expandedNodes++;
double value = Double.NEGATIVE_INFINITY;
for (KrakenMove KrakenMove : game.getActions(state)) {
value = Math.max(value, minValue( //
game.getResult(state.clone(), KrakenMove).clone(), player, alpha, beta));
if (value >= beta)
return value;
alpha = Math.max(alpha, value);
}
return value;
} | 5 |
public int getInt(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number)object).intValue()
: Integer.parseInt((String)object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not an int.");
}
} | 2 |
public static List<Integer> divisors(int n){
List<Integer> divisors = new ArrayList<Integer>();
for(int i =1;i<Math.sqrt(n);i++){
if(n%i == 0){
divisors.add(i);
if(i != 1)
divisors.add(n/i);
}
}
return divisors;
} | 3 |
@Override
public String strip(String s) throws Exception {
int length = s.length();
char[] oldChars = new char[length + 1];
s.getChars(0, length, oldChars, 0);
oldChars[length] = '\0'; // avoiding explicit bound check in while
// find first non-printable,
// if there are none it ends on the null char I appended
int newLen = -1;
while (oldChars[++newLen] >= ' ');
for (int j = newLen; j < length; j++) {
char ch = oldChars[j];
if (ch >= ' ') {
oldChars[newLen] = ch; // the while avoids repeated overwriting here when newLen==j
newLen++;
}
}
return new String(oldChars, 0, newLen);
} | 3 |
@Override
public void run() {
while(!manager.stopThreads){
try {
//Delay for interval amount of seconds
Thread.sleep(1000 * this.getInterval());
System.out.println("Sending HTTP GET to Tracker.");
generateTrackerURL();
getTrackerResponse();
if (manager.stopThreads)
break;
decodeTrackerResponse();
manager.populatePeers(peers);
manager.connectToPeers();
}
catch (IOException ioe) {
System.err.println("Unable to connect to tracker.");
ioe.printStackTrace();
}catch( BencodingException be){
System.err.println("Unable to decode tracker response.");
be.printStackTrace();
} catch (InterruptedException e) {
//This, in all likelihood will be called. It is best not to print a stack trace and worry the user.
}
}
} | 5 |
public Double evaluate(HashMap<String, Double> histogram) {
if (histogram == null) {
return null;
}
double total = 0.0;
for (Double value : histogram.values()) {
if (value != null) {
if (value >= 0) {
total += value;
} else {
return null;
}
}
}
if (total == 0) {
return Double.valueOf(0.0);
}
double entropy = 0.0;
for (Double value : histogram.values()) {
if (value != null && value > 0) {
entropy -= (value / total) * Math.log(value / total);
}
}
// Clip small negative values.
if (entropy < 0) {
entropy = 0;
} else {
entropy /= log2;
}
return Double.valueOf(entropy);
} | 9 |
@Override
public void setCanceled(boolean isCanceled) {
this.isCanceled = isCanceled;
} | 0 |
public Map<String, Object> getSymbolsFunctionEnvironmentRecord() {
return environmentStack.peek().getSymbolsSymbolTable();
} | 0 |
public void create(Usuario usuario) {
if (usuario.getVendaList() == null) {
usuario.setVendaList(new ArrayList<Venda>());
}
if (usuario.getReservaList() == null) {
usuario.setReservaList(new ArrayList<Reserva>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
List<Venda> attachedVendaList = new ArrayList<Venda>();
for (Venda vendaListVendaToAttach : usuario.getVendaList()) {
vendaListVendaToAttach = em.getReference(vendaListVendaToAttach.getClass(), vendaListVendaToAttach.getIdvenda());
attachedVendaList.add(vendaListVendaToAttach);
}
usuario.setVendaList(attachedVendaList);
List<Reserva> attachedReservaList = new ArrayList<Reserva>();
for (Reserva reservaListReservaToAttach : usuario.getReservaList()) {
reservaListReservaToAttach = em.getReference(reservaListReservaToAttach.getClass(), reservaListReservaToAttach.getIdreserva());
attachedReservaList.add(reservaListReservaToAttach);
}
usuario.setReservaList(attachedReservaList);
em.persist(usuario);
for (Venda vendaListVenda : usuario.getVendaList()) {
Usuario oldCodUsuarioOfVendaListVenda = vendaListVenda.getCodUsuario();
vendaListVenda.setCodUsuario(usuario);
vendaListVenda = em.merge(vendaListVenda);
if (oldCodUsuarioOfVendaListVenda != null) {
oldCodUsuarioOfVendaListVenda.getVendaList().remove(vendaListVenda);
oldCodUsuarioOfVendaListVenda = em.merge(oldCodUsuarioOfVendaListVenda);
}
}
for (Reserva reservaListReserva : usuario.getReservaList()) {
Usuario oldCodUsuarioOfReservaListReserva = reservaListReserva.getCodUsuario();
reservaListReserva.setCodUsuario(usuario);
reservaListReserva = em.merge(reservaListReserva);
if (oldCodUsuarioOfReservaListReserva != null) {
oldCodUsuarioOfReservaListReserva.getReservaList().remove(reservaListReserva);
oldCodUsuarioOfReservaListReserva = em.merge(oldCodUsuarioOfReservaListReserva);
}
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
} | 9 |
private void setupActionListeners() {
openBookListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
mainMenuShowing=false;
frame.requestFocusInWindow();
layers.setVisible(true);
String chosenBook = mainMenuPanel.getChosenBook();
if(chosenBook!=null)
{
setVisible(false);
XMLParser parser = new XMLParser(chosenBook);
collection = parser.getCollection();
slideList = collection.get(0);
//System.out.println("book = "+chosenBook);
bookMainPanelSetUp();
mainMenuPanel.setVisible(false);
}
}
};
previousSlideListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
frame.requestFocusInWindow();
showPreviousSlide();
}
};
nextSlideListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
frame.requestFocusInWindow();
showNextSlide();
}
};
cursorTimerTask = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
layers.setCursor (blankCursor);
mainMenuPanel.setCursor(blankCursor);
}
};
resizingTimerTask = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(slidePanel!=null && !mainMenuShowing){
resizeMainPanel();
}
if(mainMenuShowing){
resizeMainMenu();
}
}
};
layersMouseListener = new MouseAdapter(){
@Override
public void mouseMoved(MouseEvent e1){
layers.setCursor(swordCursor);
borderListenerProcess(e1,false,false,false);
mouseMovedOnSlide();
}
};
mainMenuMouseListener = new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
mainMenuPanel.setCursor(swordCursor);
if(cursorTimer.isRunning()){
cursorTimer.stop();
}
cursorTimer.start();
}
};
} | 5 |
public void updateOsoba(int index, Osoba newOsoba) {
data.set(index, newOsoba);
fireTableRowsUpdated(index, index);
} | 0 |
public void addDataType(String parameterCode){
String dataType = AirNowDataPoint.getDataTypeName(parameterCode);
if (dataType != null)
if (dataTypes.indexOf(dataType) == -1)
dataTypes.add(dataType);
} | 2 |
public static void main(String[] args)
{
int n=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el rango del vector"));
int[] arreglo=new int[n];
int c=0;
for (int i = 0; i < arreglo.length; i++)
{
int numero=Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero"));
arreglo[i]=numero;
}
for (int i = 0; i < arreglo.length; i++)
{
System.out.print(arreglo[i]);
}
System.out.println("");
int i, j, aux;
for(i=0;i<arreglo.length-1;i++)
{
for(j=0;j<arreglo.length-i-1;j++)
{
if(arreglo[j+1]<arreglo[j])
{
aux=arreglo[j+1];
arreglo[j+1]=arreglo[j];
arreglo[j]=aux;
}
}
}
for ( i = 0; i < arreglo.length; i++)
{
System.out.print(arreglo[i]);
}
System.out.println("Arreglo Sin Numeros Repetidos");
int a1;
for ( i = 0; i < arreglo.length; i++)
{
if (i==0)
{
System.out.print(arreglo[i]);
}
else
{
a1=i-1;
aux=arreglo[i];
if (aux==arreglo[a1])
{
}
else
{
System.out.print(arreglo[i]);
}
}
}
} | 9 |
public static Board parse(String filename) throws IOException {
Preconditions.checkNotNull(filename, "filename cannot be null");
String line;
StringBuilder boardBuilder = new StringBuilder();
// Read input file
BufferedReader reader = new BufferedReader(new FileReader(filename));
while ((line = reader.readLine()) != null) {
boardBuilder.append(line);
boardBuilder.append('\n');
}
reader.close();
// Convert to board representation
String[] rows = boardBuilder.toString().split("\n");
int size = rows.length;
int[][] newBoard = new int[size][size];
Point empty = null;
for (int i = 0; i < size; i++) {
String[] cols = rows[i].split(" ");
Preconditions.checkArgument(cols.length == size, "cols and rows must be of the same size");
for (int j = 0; j < size; j++) {
if (cols[j].equalsIgnoreCase("x")) {
// Found empty square
Preconditions.checkArgument(empty == null, "Found multiple start positions");
empty = new Point(j, i); // Switch params because array transposed later
newBoard[i][j] = -1;
} else {
newBoard[i][j] = Integer.parseInt(cols[j], 10);
}
}
}
// Transpose array to make it more intuitive
for (int i = 1; i < size; i++) {
for (int j = 0; j < i; j++) {
int tmp = newBoard[i][j];
newBoard[i][j] = newBoard[j][i];
newBoard[j][i] = tmp;
}
}
Preconditions.checkNotNull(empty, "Input must contain one empty square");
return new Board(newBoard, empty, null, null);
} | 6 |
@Override
public void onPacketSending(PacketEvent event) {
switch (event.getPacketID()) {
case 0x03:
PacketContainer packet = event.getPacket();
String message = packet.getSpecificModifier(String.class).read(0);
message = (PerPlayerChatFilter.getInstance().censoredForPlayer(event.getPlayer()))
? CensorUtil.censorString(event.getPlayer(), message) : message;
packet.getSpecificModifier(String.class).write(0, message);
break;
}
} | 2 |
public void paint(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
FontMetrics m = g.getFontMetrics();
int y = 0;
g.drawString("An error has occurred.", 0, y + m.getAscent());
y += m.getHeight();
g.drawString(status, 0, y + m.getAscent());
y += m.getHeight();
if(ar) {
g.drawString("Click to restart the game", 0, y + m.getAscent());
y += m.getHeight();
}
} | 1 |
public void kopioiKuvaUlosJarResourcesTiedostosta(String lahde, String maaranpaa) {
File kohdeTiedosto = new File(maaranpaa);
if (kohdeTiedosto.exists()) {
System.out.println("Tiedosto " + kohdeTiedosto.getPath() + " on jo tallennettuna");
} else {
try {
OutputStream ulosTallennus;
try (InputStream sisaanVirta = this.getClass().getResourceAsStream(lahde)) {
ulosTallennus = new FileOutputStream(kohdeTiedosto);
byte[] buf = new byte[1024];
int len;
while ((len = sisaanVirta.read(buf)) > 0) {
ulosTallennus.write(buf, 0, len);
}
}
System.out.println("Tiedosto " + ulosTallennus.toString());
ulosTallennus.close();
System.out.print(" tallennettu");
} catch (FileNotFoundException ex) {
TyokaluPakki.popUpViesti("Json tiedostoa ei saatu siirrettyä ulos jar tiedostosta. Kokeile siirrää Jar tiedosto henkilökohtaiseen kansioon ja avaa uudelleen", "Json tiedoston siirto");
} catch (IOException e) {
TyokaluPakki.popUpViesti("Json tiedostoa ei saatu siirrettyä ulos jar tiedostosta. Kokeile siirrää Jar tiedosto henkilökohtaiseen kansioon ja avaa uudelleen", "Json tiedoston siirto");
}
}
} | 4 |
@Override
public String getColumnName(int column){
String name = "??";
switch (column){
case 0:
name ="medArbId";
break;
case 1:
name ="Fornavn";
break;
case 2:
name ="EfterNavn";
break;
case 3:
name ="TelefonNr";
break;
case 4:
name ="Rolle Id";
break;
case 5:
name ="Funktion";
break;
case 6:
name ="Status";
break;
}
return name;
} | 7 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.