text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
@Override
public int compareTo(GeneratorTask o)
{
if (op < o.op)
return 1;
if (op > o.op)
return -1;
if (z < o.z)
return -1;
if (z > o.z)
return 1;
if (x < o.x)
return -1;
if (x > o.x)
return 1;
return 0;
} | 6 |
private void enableEvents(boolean b) {
enableAttachEvents(b && attachListeners.size() > 0);
enableDetachEvents(b && detachListeners.size() > 0);
enableErrorEvents(b && errorListeners.size() > 0);
enableServerConnectEvents(b && serverConnectListeners.size() > 0);
enableServerDisconnectEvents(b && serverDisconnectListeners.size() > 0);
enableDeviceSpecificEvents(b);
} | 5 |
public static void addUser(ConcordiaDatabase database){
Scanner myKey = new Scanner(System.in);
boolean successful = false;
//Prompts user for basic information
System.out.print("What is the first name of this individual? ");
String firstName=myKey.next();
System.out.print("What is the last name of " + firstName + "? ");
String lastName=myKey.next();
System.out.print("What is the Concordia ID of " + firstName + " " + lastName + "? ");
String concordiaID=myKey.next();
do{
System.out.println("\nNow Press\n1 If He/She is a Student\n2 If He/She is a Faculty Member\n3 If He/She is a Staff Member\n");
int userEntry = myKey.nextInt();
switch(userEntry){
case 1: // if Member that is to be added is Student
{
StudentStatus status = StudentStatus.valueOf(promptStudentStatus());
int contractHours =0;
if(status==StudentStatus.GRADUATE_TA || status==StudentStatus.UNDERGRADUATE_TA){
System.out.print("How many hours does this individual have in his contract? ");
contractHours = myKey.nextInt();
}
Students enteredStudent = new Students(firstName,lastName, concordiaID, status, contractHours);
database.addMember(enteredStudent);
successful = true;
break;
}
case 2: // if Member that is to be added is Faculty
{
FacultyStatus status = FacultyStatus.valueOf(promptFacultyStatus());
int contractHours =0;
int firstClassSize =0;
int secondClassSize =0;
if(status==FacultyStatus.PART_TIME){
System.out.print("How many hours does this individual have in his contract? ");
contractHours = myKey.nextInt();
System.out.print("How many students does this indivual have in his class? ");
firstClassSize = myKey.nextInt();
System.out.print("How many students does this indivual have in his second class?\n(If there isn't another class, input 0)");
secondClassSize = myKey.nextInt();
}
FacultyMembers enteredFaculty = new FacultyMembers(firstName, lastName, concordiaID, status, contractHours, firstClassSize, secondClassSize);
database.addMember(enteredFaculty);
successful = true;
break;
}
case 3: // if Member that is to be added is Staff
{
StaffStatus status = StaffStatus.valueOf(promptStaffStatus());
int contractHours =0;
if(status==StaffStatus.TEMP_STAFF){
System.out.print("How many hours does this individual have in his contract? ");
contractHours = myKey.nextInt();
}
StaffMembers enteredStaff = new StaffMembers(firstName, lastName, concordiaID, status, contractHours);
database.addMember(enteredStaff);
successful = true;
break;
}
default:{
System.out.println("Invalid Entry!\n");
}
}
}
while(successful==false);
} | 8 |
public static <T extends DC> Similarity getIndexedSim(Set<Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>>> done)
{ if(done!=null)
{ if(done.getNext()!=null)
{ return new Similarity(done.getFst().fst().delta(done.getFst().snd()).simi().getValue()+(getIndexedSim(done.getNext()).getValue()));
}
else
{ return new Similarity(done.getFst().fst().delta(done.getFst().snd()).simi().getValue());
}
}
else
{ return new Similarity(0.0);}
} | 2 |
public void freegame(String[] split, String command)
{
if (split.length != 6)
{
PrintMessage("Syntax:!freeplay [name] [eastplayer] [southplayer] [westplayer] [northplayer]");
return;
}
String name = split[1];
String east = split[2];
String south = split[3];
String west = split[4];
String north = split[5];
Player e = new Player(east, 25000, null, this);
Player s = new Player(south, 25000, null, this);
Player w = new Player(west, 25000, null, this);
Player n = new Player(north, 25000, null, this);
if (games.containsKey(name))
{
PrintMessage(name + " is a currently running game");
return;
}
SimpleDateFormat f = new SimpleDateFormat("yy-MM-dd-HHmm");
String filename = name + f.format(new Date()) + ".csv";
if (new File(filename).exists())
{
PrintMessage(filename + " already exists");
return;
}
File file = new File(filename);
try
{
file.createNewFile();
} catch (IOException ee)
{
PrintMessage("failed to create " + filename);
return;
}
file = new File(filename.substring(0, filename.length() - 4) + "detail.txt");
try
{
file.createNewFile();
} catch (IOException ee)
{
PrintMessage("failed to create " + filename.split(".")[0] + "detail.txt");
}
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(filename, true));
out.write("hand,East,South,West,North,Bonus,Riichi");
out.close();
} catch (IOException eee)
{
PrintMessage("failed to write to " + filename);
return;
}
TournyGame m = new NTGame(e, s, w, n, this, filename, false);
games.put(name, m);
m.updatedetail(command);
} | 6 |
@Override
public void actionPerformed(ActionEvent e) {
if(firstTime){
drawRandomNode();
drawSnake();
firstTime = false;
}
Node last;
if(e.getSource() == timer){
last = snake.move(food);
if(snake.getIsDead()){
stop();
System.out.println("snake was dead");
}else{
if(snake.eat(food)){
drawRandomNode();
}else{
drawSnake();
deleteNode(last);
}
}
}
System.out.println("蛇长:" + snake.size());
} | 4 |
public static String getColorLang(String langKey, String ... keyMap) {
String result = getLang(langKey);
if (result == null) {
result = langKey;
}
for (int i = 0; i < keyMap.length; i += 2) {
if (i+1 >= keyMap.length) {
break;
}
String key = keyMap[i];
String value = keyMap[i+1];
result = result.replaceAll("[<]"+key+"[>]", value);
}
return BuildingPlanner.color(result);
} | 3 |
private void drawYValues() {
mySketch.fill(0);
mySketch.textSize(valueSize);
mySketch.textAlign(PApplet.RIGHT);
float ySize = plotY2 - plotY1;
float nextYPlace = plotY1;
float fixedXPlace = plotX1 - 5;
float yValue = yMax;
float yInterval = (yMax - yMin) / valueDivisions;
DecimalFormat decimalForm = new DecimalFormat("#.#");
for (int i = 0; i < valueDivisions + 1; i++) {
float textOffset = mySketch.textAscent() / 2; // PApplet.CENTER
// vertically
if (i == valueDivisions) {
textOffset = 0; // Align by the bottom
} else if (i == 0) {
textOffset = mySketch.textAscent(); // Align by the top
}
mySketch.text(decimalForm.format(yValue), fixedXPlace, nextYPlace
+ textOffset);
mySketch.line(plotX1, nextYPlace, plotX2, nextYPlace);
yValue -= yInterval;
nextYPlace += ySize / valueDivisions;
}
} | 3 |
protected void handleControlPropertyChanged(final String PROPERTY) {
if ("RESIZE".equals(PROPERTY)) {
resize();
} else if ("STATUS".equals(PROPERTY)) {
updateStatus();
} else if ("COLOR".equals(PROPERTY)) {
icon.setBackground(new Background(new BackgroundFill(getSkinnable().getColor(), null, null)));
resize();
}
} | 3 |
@Override
public void mouseDragged(MouseEvent e) {
if (e.getPoint().x >= 0 && e.getPoint().x <= getWidth() && e.getPoint().y >= 0 && e.getPoint().y <= getHeight()) {
if (right) {
MapTile tile = getTile();
moveMap(start.getGX(mapLoc) - tile.getGX(mapLoc), start.getGY(mapLoc) - tile.getGY(mapLoc));
}
if (left) {
if (e.getPoint().distance(pathCursor) >= (dragSpacing * 2 * scale)) {
pathCursor = e.getPoint();
if(TILES.isEmpty() || !TILES.get(TILES.size()-1).equals(getTile()))
TILES.add(getTile());
}
} else {
pathCursor = e.getPoint();
}
mouse = e.getPoint();
getParent().repaint();
}
} | 9 |
public void clik() {
for (ClickListener l : listeners) {
l.doClick();
}
} | 1 |
public String getAsHiddenString() {
StringBuilder builder = new StringBuilder();
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
int value = fField[x][y];
if (value == VALUE_SHIP)
builder.append(VALUE_FREE);
else
builder.append(value);
}
}
return builder.toString();
} | 3 |
private void assertValidFields ()
{
if (_name == null) throw new IllegalArgumentException("The PackageName cannot be null.");
if (_version == null) throw new IllegalArgumentException("The PackageVersion cannot be null.");
if (_section == null) throw new IllegalArgumentException("The PackageSection cannot be null.");
if (_priority == null) throw new IllegalArgumentException("The PackagePriority cannot be null.");
if (_architecture == null) throw new IllegalArgumentException("The PackageArchitecture cannot be null.");
if (_maintainer == null) throw new IllegalArgumentException("The PackageMaintainer cannot be null.");
if (_description == null) throw new IllegalArgumentException("The PackageDescription cannot be null.");
} | 7 |
private boolean versionCheck(String title) {
if (this.type != UpdateType.NO_VERSION_CHECK) {
final String localVersion = this.plugin.getDescription().getVersion();
if (title.split(delimiter).length == 2) {
final String remoteVersion = title.split(delimiter)[1].split(" ")[0]; // Get
// the
// newest
// file's
// version
// number
if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) {
// We already have the latest version, or this build is
// tagged for no-update
this.result = Updater.UpdateResult.NO_UPDATE;
return false;
}
} else {
// The file's name did not contain the string 'vVersion'
final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " ("
+ this.plugin.getDescription().getAuthors().get(0) + ")";
this.plugin.getLogger().warning(
"The author of this plugin" + authorInfo + " has misconfigured their Auto Update system");
this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'");
this.plugin.getLogger().warning("Please notify the author of this error.");
this.result = Updater.UpdateResult.FAIL_NOVERSION;
return false;
}
}
return true;
} | 5 |
@Override
public void actionPerformed(ActionEvent e) {
// File Menu
if (e.getActionCommand().equals(CANCEL)) {
setCanceled(true);
}
} | 1 |
public static void start(String a_port)
{
port = Integer.parseInt(a_port);
ServerSocket ss = null;
try
{
InetAddress thisIp = null;
NetworkInterface ni = NetworkInterface.getByName("wlan0");
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress ia = inetAddresses.nextElement();
if(!ia.isLinkLocalAddress()) {
thisIp=ia;
}
}
ss = new ServerSocket(port, 0,thisIp);
try
{
for (;;)
{
Server t = new Server(ss.accept());
t.start();
}
}
catch (IOException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (IOException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
} | 5 |
public final Number parse(String text) throws TypeConversionException {
if (text == null || "".equals(text)) {
return null;
}
if (pattern == null) {
try {
return createNumber(text);
}
catch (NumberFormatException ex) {
throw new TypeConversionException("Invalid " + getType().getSimpleName() +
" value '" + text + "'", ex);
}
}
else {
// create a DecimaFormat for parsing the number
DecimalFormat df = format;
if (df == null) {
df = createDecimalFormat();
df.setParseBigDecimal(true);
}
// parse the number using the DecimalFormat
ParsePosition pp = new ParsePosition(0);
Number number = df.parse(text, pp);
if (pp.getErrorIndex() >= 0 ||
pp.getIndex() != text.length() ||
!(number instanceof BigDecimal))
{
throw new TypeConversionException("Number value '" + text +
"' does not match pattern '" + pattern + "'");
}
try {
// convert the BigDecimal to a number
return createNumber((BigDecimal)number);
}
catch (ArithmeticException ex) {
throw new TypeConversionException("Invalid " + getType().getSimpleName() +
" value '" + text + "'");
}
}
} | 9 |
private void moveForward() {
int newX = getPositionX();
int newY = getPositionY();
switch (getFacing()) {
case NORTH:
newY++;
break;
case EAST:
newX++;
break;
case SOUTH:
newY--;
break;
case WEST:
newX--;
break;
default:
}
//we want to check we aren't going off a cliff, or into another rover
if (checkValidPosition(newX, newY)) {
setPositionX(newX);
setPositionY(newY);
}
else {
System.err.println("Invalid position! Can't move to " + positionX + " " + positionY + " so staying put.");
}
} | 5 |
public boolean higher(String a, String b) {
int i = 0, limit = Math.min(a.length(), b.length());
while (i < limit - 1 && LOWER.to(a.charAt(i))
== LOWER.to(b.charAt(i)))
++i;
return a.charAt(i) < b.charAt(i) || a.length() <= b.length();
} | 3 |
public void actionPerformed(ActionEvent e) {
String[] args = getArgs(e);
String channel = args[0];
String sender = args[1];
String message = args[2];
if (message.contains("youtube.com/watch") || message.contains("youtu.be/"))
if (acebotCore.hasAccess(channel, sender, channelAccess, userAccess, accessExceptionMap) && !(sender.equalsIgnoreCase("idolmasterbot") || sender.equalsIgnoreCase("nightbot")))
acebotCore.addToQueue(channel, getYoutubeInfo(message), BotCore.OUTPUT_CHANNEL);
//if (message.contains("twitch.tv/") && (message.contains("/c/") || message.contains("/b/")))
// if (acebotCore.hasAccess(channel, sender, channelAccess, userAccess, accessExceptionMap) && !(sender.equalsIgnoreCase("idolmasterbot") || sender.equalsIgnoreCase("nightbot")))
// acebotCore.addToQueue(channel, getTwitchInfo(message), BotCore.OUTPUT_CHANNEL);
} | 5 |
private ArrayList<Object> chooseEquation(int flag){
ArrayList<Object> ret = new ArrayList<Object>();
String headerCommentP = null;
String[] commentsP = null;
String[] boxTitlesP = null;
switch(flag){
case 0: headerCommentP = "Choose a fitting equation";
commentsP = new String[15];
break;
case 1: headerCommentP = "Choose the first equation of the comparison";
commentsP = new String[13];
break;
case 2: headerCommentP = "Choose the second equation of the comparison";
commentsP = new String[13];
break;
}
commentsP[0] = "1. Five paramater logistic equation";
commentsP[1] = "2. Five paramater logistic equation (top & bottom fixed)";
commentsP[2] = "3. Four paramater logistic equation";
commentsP[3] = "4. Four paramater logistic equation (top & bottom fixed)";
commentsP[4] = "5. Best fit polynomial";
commentsP[5] = "6. Polynomial of user supplied degree";
commentsP[6] = "7. Non-integer polynomial";
commentsP[7] = "8. Sigmoid threshold function";
commentsP[8] = "9. Sips sigmoid function";
commentsP[9] = "10. Shifted rectangular hyperbola";
commentsP[10] = "11. Rectangular hyperbola";
commentsP[11] = "12. Amersham mass action model";
if(flag==0){
commentsP[12] = "13. Cubic spline";
commentsP[13] = "14. Linear interpolation\n\n";
commentsP[14] = "Click on the appropriate button below";
String[] hold1 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"};
boxTitlesP = hold1;
}
else{
commentsP[12] = "\nClick on the appropriate button below";
String[] hold2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
boxTitlesP = hold2;
}
int defaultBoxP = 0;
int ret0 = 1 + JOptionPane.showOptionDialog(null, commentsP, headerCommentP, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null, boxTitlesP, boxTitlesP[defaultBoxP]);
ret.add(new Integer(ret0));
int ret1 = 0;
if(ret0==6)ret1 = Db.readInt("enter polynomial degree");
if(ret0==7)ret1 = Db.readInt("enter non-integer polynomial number of terms");
ret.add(new Integer(ret1));
double ret2 = 0.0;
double ret3 = 0.0;
if(ret0==2){
ret2 = Db.readDouble("Enter five parameter logistic fixed bottom value");
ret3 = Db.readDouble("Enter five parameter logistic fixed top value");
}
if(ret0==4){
ret2 = Db.readDouble("Enter four parameter logistic fixed bottom value");
ret3 = Db.readDouble("Enter four parameter logistic fixed top value");
}
ret.add(new Double(ret2));
ret.add(new Double(ret3));
return ret;
} | 8 |
public static ArrayList<postInfo> getPosts(long offering_id, boolean privilegeFlag){
try{
PreparedStatement pstmt;
if (!privilegeFlag){
pstmt = conn.prepareStatement("select S.post_id, S.parent_post_id, S.student_id, student.name, S.mytime, "
+ "(select max(mytime) from post as T where T.parent_post_id = S.post_id) as maxTime, S.content "
+ "from post as S natural join student "
+ "where offering_id = ? and post_id = parent_post_id "
+ "order by maxTime desc");
}
else{
pstmt = conn.prepareStatement("select S.post_id, S.parent_post_id, S.student_id, student.name, S.mytime, "
+ "(select max(mytime) from post as T where T.parent_post_id = S.post_id) as maxTime, S.content "
+ "from post as S natural join student "
+ "where offering_id = ? and post_id = parent_post_id and privilege_flag = ? "
+ "order by maxTime desc");
pstmt.setBoolean(2, privilegeFlag);
}
pstmt.setLong(1, offering_id);
ResultSet rset = pstmt.executeQuery();
ArrayList<postInfo> primaryPostList = new ArrayList<postInfo>();
while(rset.next()){
postInfo newPost = new postInfo();
newPost.postId = rset.getLong("post_id");
newPost.parentPostId = rset.getLong("parent_post_id");
newPost.studentName = rset.getString("student.name");
newPost.studentId = rset.getString("student_id");
newPost.mytime = rset.getString("myTime");
newPost.content = rset.getString("content");
primaryPostList.add(newPost);
}
ArrayList<postInfo> postList = new ArrayList<postInfo>();
for (int i = 0; i < primaryPostList.size(); i++){
postList.add(primaryPostList.get(i));
pstmt = conn.prepareStatement("select post_id, parent_post_id, student_id, student.name, mytime, content "
+ "from post natural join student "
+ "where post_id != ? and parent_post_id = ? "
+ "order by mytime asc");
pstmt.setLong(1, primaryPostList.get(i).postId);
pstmt.setLong(2, primaryPostList.get(i).postId);
int numCommentsReqd = 3;
rset = pstmt.executeQuery();
rset.afterLast();
ArrayList<postInfo> tempCommentList = new ArrayList<postInfo>();
while(rset.previous() && numCommentsReqd > 0){
numCommentsReqd--;
postInfo newPost = new postInfo();
newPost.postId = rset.getLong("post_id");
newPost.parentPostId = rset.getLong("parent_post_id");
newPost.studentName = rset.getString("student.name");
newPost.studentId = rset.getString("student_id");
newPost.mytime = rset.getString("myTime");
newPost.content = rset.getString("content");
tempCommentList.add(newPost);
}
for (int j = tempCommentList.size() - 1; j >= 0; j--){
postList.add(tempCommentList.get(j));
}
}
return postList;
} catch (SQLException sqle) {
System.out.println("SQLException : " + sqle);
return null;
}
} | 7 |
public void recalculate(final double OFFSET) {
List<Stop> stops = new ArrayList<>(sortedStops.size());
for (Stop stop : sortedStops) {
double newOffset = (stop.getOffset() + OFFSET) % 1;
if(Double.compare(newOffset, 0d) == 0) {
newOffset = 1.0;
stops.add(new Stop(0.000001, stop.getColor()));
} else if (stop.getOffset() + OFFSET > 1d) {
newOffset -= 0.000001;
}
stops.add(new Stop(newOffset, stop.getColor()));
}
HashMap<Double, Color> stopMap = new LinkedHashMap<>(stops.size());
for (Stop stop : stops) {
stopMap.put(stop.getOffset(), stop.getColor());
}
List<Stop> sortedStops2 = new LinkedList<>();
SortedSet<Double> sortedFractions = new TreeSet<>(stopMap.keySet());
if (sortedFractions.last() < 1) {
stopMap.put(1.0, stopMap.get(sortedFractions.first()));
sortedFractions.add(1.0);
}
if (sortedFractions.first() > 0) {
stopMap.put(0.0, stopMap.get(sortedFractions.last()));
sortedFractions.add(0.0);
}
for (Double fraction : sortedFractions) {
sortedStops2.add(new Stop(fraction, stopMap.get(fraction)));
}
sortedStops.clear();
sortedStops.addAll(sortedStops2);
} | 7 |
@Test
public void TallennuksenKasittelijaLoytaaTasonNumeronArrayListista() {
ArrayList<String> rivit = new ArrayList();
rivit.add("Taso: 4");
int x = k.etsiTasonNumero(rivit);
assertTrue("taso oli väärä!", x == 4);
} | 0 |
private void attackCalculation(Player attacker, Player defender)
{
if (attacker.checkIfAlive() && defender.checkIfAlive())
{
// Defender HP lost = difference between attacker's strength and defender's constitution.
int attackCalc = attacker.getStrValue() - defender.getConValue();
// Defender takes 1 damage if constitution is higher than attacker's strength.
if (attackCalc <= 0)
{
attackCalc = 1;
}
// Attacker cannot miss if hit is greater than or equal to the defender's evasion.
if (attacker.getHitValue() >= defender.getEvdValue())
{
// Attacker cannot crit if luck is less than or equal to the defender's luck.
if (attacker.getLukValue() <= defender.getLukValue())
{
attackSuccessful(attacker, defender, attackCalc);
}
// Attacker can crit if luck is greater than defender's luck.
else
{
int randomNumber = random.nextInt(100);
// Attacker has a (x * 2)% crit chance depending on difference of luck.
int critChance = ((attacker.getLukValue() - defender.getLukValue()) * 2);
// Ex: critChance = ((70-50) * 2) = 40% chance to crit.
// So if randomNumber generates any number between 0-39 then the attack is a crit.
if (randomNumber <= critChance)
{
critSuccessful(attacker, defender, attackCalc);
}
// Enters statement if attacker did not crit.
else
{
attackSuccessful(attacker, defender, attackCalc);
}
}
}
// Attacker can miss if hit is less than defender's evasion.
else
{
int randomNumber = random.nextInt(100);
// Defender has a (x * 2)% dodge chance depending on difference.
int dodgeChance = ((defender.getEvdValue() - attacker.getHitValue()) * 2);
// Ex: dodgeChance = ((70-50) * 2) = 40% chance to dodge attack.
// So if randomNumber generates any number between 0-39 then the attack is evaded.
if (randomNumber <= dodgeChance)
{
String result = attacker.getName() + "'s attack has been evaded by " + defender.getName() + ".\n";
results.append(result);
}
// Enters statement if attack was not dodged by the defender.
else
{
// Attacker cannot crit if luck is less than or equal to the defender's luck.
if (attacker.getLukValue() <= defender.getLukValue())
{
attackSuccessful(attacker, defender, attackCalc);
}
// Attacker can crit if luck is greater than defender's luck.
else
{
int randomNumber2 = random.nextInt(100);
// Attacker has a (x * 2)% crit chance depending on difference of luck.
int critChance = ((attacker.getLukValue() - defender.getLukValue()) * 2);
// Ex: critChance = ((70-50) * 2) = 40% chance to crit.
// So if randomNumber generates any number between 0-39 then the attack is a crit.
if (randomNumber2 <= critChance)
{
critSuccessful(attacker, defender, attackCalc);
}
// Enters statement if attacker did not crit.
else
{
attackSuccessful(attacker, defender, attackCalc);
}
}
}
}
}
} | 9 |
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof RingPlot)) {
return false;
}
RingPlot that = (RingPlot) obj;
if (this.separatorsVisible != that.separatorsVisible) {
return false;
}
if (!ObjectUtilities.equal(this.separatorStroke,
that.separatorStroke)) {
return false;
}
if (!PaintUtilities.equal(this.separatorPaint, that.separatorPaint)) {
return false;
}
if (this.innerSeparatorExtension != that.innerSeparatorExtension) {
return false;
}
if (this.outerSeparatorExtension != that.outerSeparatorExtension) {
return false;
}
if (this.sectionDepth != that.sectionDepth) {
return false;
}
return super.equals(obj);
} | 8 |
public static int checkStage(int stage)
{
if(stage>6)
return 6;
else if(stage<-6)
return -6;
else
return stage;
} | 2 |
public JButton getjButtonClose() {
return jButtonClose;
} | 0 |
protected void processTraverseEvent(int columnIndex, ViewerRow row,
TraverseEvent event) {
ViewerCell cell2edit = null;
if (event.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
event.doit = false;
if ((event.stateMask & SWT.CTRL) == SWT.CTRL
&& (feature & TABBING_VERTICAL) == TABBING_VERTICAL) {
cell2edit = searchCellAboveBelow(row, viewer, columnIndex, true);
} else if ((feature & TABBING_HORIZONTAL) == TABBING_HORIZONTAL) {
cell2edit = searchPreviousCell(row, row.getCell(columnIndex),
row.getCell(columnIndex), viewer);
}
} else if (event.detail == SWT.TRAVERSE_TAB_NEXT) {
event.doit = false;
if ((event.stateMask & SWT.CTRL) == SWT.CTRL
&& (feature & TABBING_VERTICAL) == TABBING_VERTICAL) {
cell2edit = searchCellAboveBelow(row, viewer, columnIndex,
false);
} else if ((feature & TABBING_HORIZONTAL) == TABBING_HORIZONTAL) {
cell2edit = searchNextCell(row, row.getCell(columnIndex), row
.getCell(columnIndex), viewer);
}
}
if (cell2edit != null) {
viewer.getControl().setRedraw(false);
ColumnViewerEditorActivationEvent acEvent = new ColumnViewerEditorActivationEvent(
cell2edit, event);
viewer.triggerEditorActivationEvent(acEvent);
viewer.getControl().setRedraw(true);
}
} | 9 |
byte[] getBrushWithAA(CPBrushInfo brushInfo, float dx, float dy) {
byte[] nonAABrush = getBrush(brushInfo);
int intSize = (int) (brushInfo.curSize + .99f);
int intSizeAA = (int) (brushInfo.curSize + .99f) + 1;
for (int y = 0; y < intSizeAA; y++) {
for (int x = 0; x < intSizeAA; x++) {
brushAA[y * intSizeAA + x] = 0;
}
}
for (int y = 0; y < intSize; y++) {
for (int x = 0; x < intSize; x++) {
int brushAlpha = nonAABrush[y * intSize + x] & 0xff;
brushAA[y * intSizeAA + x] += (int) (brushAlpha * (1 - dx) * (1 - dy));
brushAA[y * intSizeAA + (x + 1)] += (int) (brushAlpha * dx * (1 - dy));
brushAA[(y + 1) * intSizeAA + x + 1] += (int) (brushAlpha * dx * dy);
brushAA[(y + 1) * intSizeAA + x] += (int) (brushAlpha * (1 - dx) * dy);
}
}
return brushAA;
} | 4 |
protected void parseHost() {
final int i = this.message.indexOf(' ');
String hostAddress = null;
String hostName = null;
if (i > -1) {
final String providedHost = this.message.substring(0,i).trim();
hostAddress = this.inetAddress.getHostAddress();
if (providedHost.equalsIgnoreCase(hostAddress)) {
this.host = hostAddress;
this.message = this.message.substring(i+1);
}
if (this.host == null) {
hostName = this.inetAddress.getHostName();
if (providedHost.equalsIgnoreCase(hostName)) {
this.host = hostName;
this.message = this.message.substring(i+1);
}
}
if (this.host == null) {
this.host = (hostName != null) ? hostName : hostAddress;
}
}
} | 6 |
private static void loadFEP() {
try {
FileInputStream fstream;
fstream = new FileInputStream("fep.conf");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
HashMap<String, Float> fep = new HashMap<String, Float>();
String[] tmp = strLine.split("=");
String name;
name = tmp[0].toLowerCase();
tmp = tmp[1].split(" ");
for (String itm : tmp) {
String tmp2[] = itm.split(":");
fep.put(tmp2[0], Float.valueOf(tmp2[1]).floatValue());
}
FEPMap.put(name, fep);
}
br.close();
in.close();
fstream.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
} | 4 |
public void walkRight() {
face = 1;
if (!(x == Realm.WORLD_WIDTH - 1) && !walkblockactive)
if (!Collision.check(new Position(x, y), face)) {
x += walkspeed;
setWalkBlock(walkblocktick);
}
} | 3 |
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
input.useLocale(Locale.US);
System.out.println("Inserisci un aggettivo :");
String aggettivo = input.next();
input.close();
//aggiungo la lettera maiuscola
aggettivo = aggettivo.toUpperCase().substring(0,1)+aggettivo.toLowerCase().substring(1);
String lastletter = aggettivo.substring(aggettivo.length()-1);
//allineo le stringhe
String frase1 = "Aggettivo inserito: ";
String frase2 = "Forma diminutiva:";
String frase3 = "Superlativo assoluto:";
while(frase1.length()>frase2.length() || frase1.length()>frase3.length())
{
if(frase1.length()>frase2.length())
{
frase2+=" ";
}
else if(frase1.length()>frase3.length())
{
frase3+=" ";
}
}
if(lastletter.equals("o"))
{
String diminutivo = aggettivo.substring(0,aggettivo.length()-1)+"ino";
String superlativo = aggettivo.substring(0,aggettivo.length()-1)+"issimo";
System.out.println(frase1+aggettivo);
System.out.println(frase2+diminutivo);
System.out.println(frase3+superlativo);
}
else if(lastletter.equals("a"))
{
String diminutivo = aggettivo.substring(0,aggettivo.length()-1)+"ina";
String superlativo = aggettivo.substring(0,aggettivo.length()-1)+"issima";
System.out.println(frase1+aggettivo);
System.out.println(frase2+diminutivo);
System.out.println(frase3+superlativo);
}
} | 6 |
public static boolean isReleased(int i) {
return !keyState[i] && prevKeyState[i];
} | 1 |
public void PKz() {
if(PlayerHandler.players[KillerId] != null) {
if(KillerId != playerId){
if(PlayerHandler.players[KillerId].combat > combat){
lnew = 1;
}
else if(PlayerHandler.players[KillerId].combat < combat){
lnew = 3;
}
else if(PlayerHandler.players[KillerId].combat == combat){
lnew = 2;
}
client killerz = (client) server.playerHandler.players[KillerId];
if(killerz != null) {
boolean givePoints = true;
if(killerz.lastKill.equalsIgnoreCase(playerName)) {
killerz.sendMessage("You recieve no pk points as you have pked "+playerName+" twice in a row");
givePoints = false;
}
if(givePoints) {
PlayerHandler.players[KillerId].pkpoints += lnew;
PlayerHandler.players[KillerId].killcount += 1;
otherpkps = PlayerHandler.players[KillerId].pkpoints;
otherkillc = PlayerHandler.players[KillerId].killcount;
killerz.sendMessage("You recieve "+lnew+" player-kill, you now have "+otherpkps+" player-kill points.");
killerz.sendMessage("You now have a total of "+otherkillc+" player kills.");
killerz.checkPKReward();
killerz.lastKill = playerName;
server.playerHandler.messageToAll = killerz.playerName+" has killed "+playerName+", "+killerz.playerName+" now has "+killerz.pkpoints+" pk points and "+killerz.killcount+" kills!";
}
}
} deathcount =+ 1;
}
} | 8 |
public String getConfigPath(String filename) {
if (eng.isApplet()) return null;
File jgamedir;
try {
jgamedir = new File(System.getProperty("user.home"), ".jgame");
} catch (Exception e) {
// probably AccessControlException of unsigned webstart
return null;
}
if (!jgamedir.exists()) {
// try to create ".jgame"
if (!jgamedir.mkdir()) {
// fail
return null;
}
}
if (!jgamedir.isDirectory()) return null;
File file = new File(jgamedir,filename);
// try to create file if it didn't exist
try {
file.createNewFile();
} catch (IOException e) {
return null;
}
if (!file.canRead()) return null;
if (!file.canWrite()) return null;
try {
return file.getCanonicalPath();
} catch (IOException e) {
return null;
}
} | 9 |
private final void method2855(int i, byte i_56_) {
anInt8927++;
if (i_56_ < -42) {
for (Class348_Sub43 class348_sub43
= ((Class348_Sub43)
((Class348_Sub16_Sub1) aClass348_Sub16_Sub1_8958)
.aClass262_8848.getFirst(4));
class348_sub43 != null;
class348_sub43
= ((Class348_Sub43)
((Class348_Sub16_Sub1) aClass348_Sub16_Sub1_8958)
.aClass262_8848.nextForward((byte) 60))) {
if ((i < 0 || (((Class348_Sub43) class348_sub43).anInt7067
^ 0xffffffff) == (i ^ 0xffffffff))
&& (((Class348_Sub43) class348_sub43).anInt7087
^ 0xffffffff) > -1) {
aClass348_Sub43ArrayArray8928
[((Class348_Sub43) class348_sub43).anInt7067]
[((Class348_Sub43) class348_sub43).anInt7071]
= null;
((Class348_Sub43) class348_sub43).anInt7087 = 0;
}
}
}
} | 5 |
public static double incompleteBetaFraction1( double a, double b, double x ) {
double xk, pk, pkm1, pkm2, qk, qkm1, qkm2;
double k1, k2, k3, k4, k5, k6, k7, k8;
double r, t, ans, thresh;
int n;
k1 = a;
k2 = a + b;
k3 = a;
k4 = a + 1.0;
k5 = 1.0;
k6 = b - 1.0;
k7 = k4;
k8 = a + 2.0;
pkm2 = 0.0;
qkm2 = 1.0;
pkm1 = 1.0;
qkm1 = 1.0;
ans = 1.0;
r = 1.0;
n = 0;
thresh = 3.0 * MACHEP;
do {
xk = -( x * k1 * k2 )/( k3 * k4 );
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
xk = ( x * k5 * k6 )/( k7 * k8 );
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if( qk != 0 ) r = pk/qk;
if( r != 0 ) {
t = Math.abs( (ans - r)/r );
ans = r;
} else
t = 1.0;
if( t < thresh ) return ans;
k1 += 1.0;
k2 += 1.0;
k3 += 2.0;
k4 += 2.0;
k5 += 1.0;
k6 -= 1.0;
k7 += 2.0;
k8 += 2.0;
if( (Math.abs(qk) + Math.abs(pk)) > big ) {
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
if( (Math.abs(qk) < biginv) || (Math.abs(pk) < biginv) ) {
pkm2 *= big;
pkm1 *= big;
qkm2 *= big;
qkm1 *= big;
}
} while( ++n < 300 );
return ans;
} | 7 |
@Test
public void randomShapeGeneration() {
RandomShapeGenerator rsg = new RandomShapeGenerator();
for (int i = 0; i < 1000; i++) {
Shape newShape = rsg.getNewShapeAtRandom();
for (Shape shape : shapeCount.keySet()) {
if (newShape.getClass().getName().equals(shape.getClass().getName())) {
Integer count = shapeCount.get(shape);
assertFalse("new shape " + newShape + " same object as key " + shape,
shape.equals(newShape));
shapeCount.put(shape, ++count);
}
}
}
//for a visual check that it looks sensible
System.out.println(shapeCount.toString());
//just make sure we've not missed any
assertFalse(shapeCount.containsValue(0));
} | 3 |
private List<Integer> getMailNumberList() {
String response;
List<String> responseList = new ArrayList<String>();
List<Integer> MailNumberList = new ArrayList<Integer>();
try {
sTrace.debug("Try Stat Command");
writeToServer("List");
response = readFromServer();
while(!response.equals(".")){
responseList.add(response);
response = readFromServer();
}
if (response.startsWith("-ERR")) {
// Server returned -ERR -> abort
throw new Exception("Server returned -ERR on \"STAT\" command");
}
for(int i = 1; i<responseList.size(); i++){
int Number = Integer.parseInt(responseList.get(i).split(" ")[0]);
MailNumberList.add(Number);
sTrace.debug("MailNumber: " + Number);
}
} catch (IOException e) {
error = true;
sTrace.error("Socket Error during Pop3Client.getNumberofMails()\n"
+ e.getMessage());
} catch (Exception e) {
error = true;
sTrace.error(e.getMessage());
}
return MailNumberList;
} | 5 |
public void addMissileToOrefPanel(String destination, int time, int flyTime) {
// exclude messages with # - to prevent showing interception alerts
if(!(destination.contains ("#"))){
// time % 2 - to make the alert blink every second
if (time < ALERT_DISPLAY_TIME && time % 2 == 0) {
topAlert.setText("Alert in " + destination);
validate();
setOrefImage(OREF_ALERT_IMAGE_PATH);
} else if (time < ALERT_DISPLAY_TIME) {
setOrefImage(OREF_ALERT_IMAGE_PATH);
topAlert.setText("");
} else {
// the alert is finished, free the topAlert Label
setOrefImage(OREF_IMAGE_PATH);
topAlert.setText("");
}
if (time == flyTime) {
// if missile flyTime is less then ALERT_DISPLAY_TIME
topAlert.setText("");
setOrefImage(OREF_IMAGE_PATH);
}
}
} | 5 |
@Override
protected void wildCardPlayed(TurnContext state) {
System.out.print("You have put down a wildcard. ");
if (state.selection == null && state.g.canDraw() && state.currentPlayable.isEmpty()) {
System.out.println("Since cards can be drawn, you must draw and you cannot put down any more cards.");
} else if (state.won) {
System.out.println();
}
} | 4 |
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(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.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 Login().setVisible(true);
}
});
} | 6 |
public void IncrementPersonsCreated()
{
personsCreated += 1;
} | 0 |
public synchronized DataInputStream getChunkDataInputStream(int x, int z) {
if (outOfBounds(x, z)) {
debugln("READ", x, z, "out of bounds");
return null;
}
try {
int offset = getOffset(x, z);
if (offset == 0) {
// debugln("READ", x, z, "miss");
return null;
}
int sectorNumber = offset >> 8;
int numSectors = offset & 0xFF;
if (sectorNumber + numSectors > sectorFree.size()) {
debugln("READ", x, z, "invalid sector");
return null;
}
file.seek(sectorNumber * SECTOR_BYTES);
int length = file.readInt();
if (length > SECTOR_BYTES * numSectors) {
debugln("READ", x, z, "invalid length: " + length + " > 4096 * " + numSectors);
return null;
}
byte version = file.readByte();
if (version == VERSION_GZIP) {
byte[] data = new byte[length - 1];
file.read(data);
DataInputStream ret = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data))));
// debug("READ", x, z, " = found");
return ret;
} else if (version == VERSION_DEFLATE) {
byte[] data = new byte[length - 1];
file.read(data);
DataInputStream ret = new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data))));
// debug("READ", x, z, " = found");
return ret;
}
debugln("READ", x, z, "unknown version " + version);
return null;
} catch (IOException e) {
debugln("READ", x, z, "exception");
return null;
}
} | 7 |
@Override
public void deleteIngredient(int i) {
Ingredient ingredient = getIngredient(i);
for(int parent : ingredient.getParentIngredients()){
for(Ingredient child : getChildrenIngredients(ingredient)){
child.addParent(parent);
updateIngredient(child);
}
}
try(Connection connection = DriverManager.getConnection(connectionString)){
PreparedStatement statement = connection.prepareStatement("delete from ingredient where id = ?");
statement.setInt(1, i);
statement.executeUpdate();
statement = connection.prepareStatement("delete from parent where idParent = ? or idIngredient = ?");
statement.setInt(1, i);
statement.setInt(2, i);
statement.executeUpdate();
}
catch(SQLException ex){
ex.printStackTrace();
}
} | 3 |
public void move(int dx, int dy) {
AffineTransform at = new AffineTransform();
at.translate(dx, dy);
((GeneralPath) shape).transform(at);
canvas.repaint();
} | 0 |
public static Cons mergeConsLists(Cons list1, Cons list2, java.lang.reflect.Method predicate) {
{ Cons cursor1 = list1;
Cons cursor2 = list2;
Cons result = Stella.NIL;
Cons tail = Stella.NIL;
Cons temp = Stella.NIL;
for (;;) {
if (cursor1 == Stella.NIL) {
if (tail == Stella.NIL) {
return (cursor2);
}
tail.rest = cursor2;
return (result);
}
if (cursor2 == Stella.NIL) {
if (tail == Stella.NIL) {
return (cursor1);
}
tail.rest = cursor1;
return (result);
}
if (((Boolean)(edu.isi.stella.javalib.Native.funcall(predicate, null, new java.lang.Object [] {cursor2.value, cursor1.value}))).booleanValue()) {
temp = cursor2;
cursor2 = cursor2.rest;
list2 = cursor2;
}
else {
temp = cursor1;
cursor1 = cursor1.rest;
list1 = cursor1;
}
if (tail == Stella.NIL) {
result = temp;
}
else {
tail.rest = temp;
}
tail = temp;
}
}
} | 7 |
public CheckResultMessage checkL6(int day){
int r1 = get(17,5);
int c1 = get(18,5);
int r2 = get(30,5);
int c2 = get(31,5);
if(checkVersion(file).equals("2003")){
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
if(0!=getValue(r2+6, c2+day, 10).compareTo(getValue(r1+2+day, c1+1, 6))){
return error("支付机构汇总报表<" + fileName + ">本期以自有资金先行赎回预付卡的金额 L6 = I02:" + day + "日错误");
}
in.close();
} catch (Exception e) {
}
}else{
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
if(0!=getValue(r2+6, c2+day, 10).compareTo(getValue(r1+2+day, c1+1, 6))){
return error("支付机构汇总报表<" + fileName + ">本期以自有资金先行赎回预付卡的金额 L6 = I02:" + day + "日错误");
}
in.close();
} catch (Exception e) {
}
}
return pass("支付机构汇总报表<" + fileName + ">本期以自有资金先行赎回预付卡的金额 L6 = I02:" + day + "日错误");
} | 5 |
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
} | 0 |
public static String formatPackets(long paramLong, boolean MB, boolean GB) {
if (paramLong >= 1000000000L && GB) {
return paramLong / 1000000000L + " B";
}
if (paramLong >= 10000000L && MB) {
return paramLong / 1000000L + " M";
}
if (paramLong >= 1000L) {
return paramLong / 1000L + " K";
}
return "" + paramLong;
} | 5 |
@Test
public void testSerialize() {
ThriftyList<Integer> list = new ThriftyList<Integer>();
int testCount = 10;
for (int j = 0; j < testCount; j++) {
list.add(j);
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
try {
os.writeObject(list);
} finally {
os.close();
}
ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(
out.toByteArray()));
try {
list = (ThriftyList<Integer>) is.readObject();
} finally {
is.close();
}
} catch (Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
Assert.fail(writer.toString());
}
for (int j = 0; j < testCount; j++) {
Assert.assertEquals(Integer.valueOf(j), list.get(j));
}
list = new ThriftyList<Integer>();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
try {
os.writeObject(list);
} finally {
os.close();
}
ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(
out.toByteArray()));
try {
list = (ThriftyList<Integer>) is.readObject();
} finally {
is.close();
}
} catch (Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
Assert.fail(writer.toString());
}
Assert.assertTrue(list.isEmpty());
} | 4 |
@Override
public ParserResult specialCheckAndGetParserResult(ParserResult result,
SyntaxAnalyser analyser) throws GrammarCheckException {
Map<String, String> dimensionLevelInfo = result.getDimensionLevelInfo();
boolean conditionIsOk = dimensionLevelInfo.size() == 2;
for (Iterator<String> iterator = dimensionLevelInfo.keySet().iterator(); iterator
.hasNext();) {
String key = (String) iterator.next();
conditionIsOk = conditionIsOk
&& (dimensionLevelInfo.get(key) == null);
}
boolean theOtherConditionIsOk = result.getAggregateFunctionName() == null
&& result.getConditions().size() == 0
&& result.getDimensionNicknames().size() == 0
&& result.getResultCube() == null;
if (!(conditionIsOk && theOtherConditionIsOk)) {
this.throwException(result.getOperationName(), null, analyser);
}
return result;
} | 7 |
private static boolean canBeAbundant(int n){
for(Integer a : abundant){
if (abundant.contains(n-a)) return true;
}
return false;
} | 2 |
public void atBat() throws PopFoul {
} | 0 |
public void setPrpMoaConsec(int prpMoaConsec) {
this.prpMoaConsec = prpMoaConsec;
} | 0 |
@Override
public void giveIMC2ChannelsList(MOB mob)
{
if((mob==null)||(!imc2online()))
return;
if(mob.isMonster())
return;
final StringBuffer buf=new StringBuffer("\n\rIMC2 Channels List:\n\r");
final Hashtable channels=imc2.query_channels();
buf.append(CMStrings.padRight(L("Name"), 22)+CMStrings.padRight(L("Policy"),25)+CMStrings.padRight(L("Owner"),20)+"\n\r");
final Enumeration e = channels.keys();
while (e.hasMoreElements())
{
final String key = (String) e.nextElement();
final IMC_CHANNEL r = (IMC_CHANNEL) channels.get(key);
if (r != null)
{
String policy = "final public";
if (r.policy == IMC2Driver.CHAN_PRIVATE)
policy = "(private)";
else
if (r.policy == IMC2Driver.CHAN_COPEN)
policy = "open";
else
if (r.policy == IMC2Driver.CHAN_CPRIVATE)
policy = "(cprivate)";
buf.append(CMStrings.padRight(key, 22)+
CMStrings.padRight(policy+"("+r.level+")",25)+
r.owner+"\n\r");
}
}
mob.session().wraplessPrintln(buf.toString());
} | 8 |
@Override
public void setHouseNumber(String houseNumber) {
super.setHouseNumber(houseNumber);
} | 0 |
public static boolean isValidDate(int day, int month, int year) {
if (isMonthWith31Days(month)) {
return (day >= 1) && (day <= 31);
} else if (month == 2) {
if (isLeapYear(year)) {
return (day >= 1) && (day <= 29);
} else {
return (day >= 1) && (day <= 28);
}
} else {
return (day >= 1) && (day <= 30);
}
} | 7 |
public StopwatchTimer(String author, long time, long period) {
this.author = author;
baseTime = time;
remainingTime = time;
if(period != 0 && baseTime > period)
this.period = period;
else if(baseTime > 60)
this.period = 60;
} | 3 |
public Integer convert(Object object,Integer defultValue,Object... args) throws HeraException{
if(object instanceof Double){
return new DoubleIntegerConverter().convert((Double)object, defultValue, args);
} else if(object instanceof Long){
return new LongIntegerConverter().convert((Long)object, defultValue, args);
} else {
try{
return Integer.valueOf(object.toString());
}catch (Exception e) {
if(defultValue!=null){
return defultValue;
}else{
throw new HeraException("Object to Ingeger 转化错误 :"+e.getMessage() );
}
}
}
} | 4 |
private static void viewAStudent(String first, String last) {
String allInfo = new String();
if (studentExists(first, last) >= 0) {
Student tempStudent = new Student(
(Student) Students.get(studentExists(first, last)));
allInfo = ("Name: " + tempStudent.getfName() + " " + tempStudent
.getlName());
allInfo += ("\n" + "ID Number: " + tempStudent.getID());
allInfo += ("\n" + "Gender: " + convertGender(tempStudent
.getGender()));
allInfo += ("\n" + "Grade: " + tempStudent.getGrade());
allInfo += ("\n" + "Advisor: " + tempStudent.getAdvisor());
allInfo += ("\n" + "Birthday: " + tempStudent.getBirthDay());
if(tempStudent.getTableNum() == 30)
allInfo += ("\n" + "Current Table Number: Unassigned");
else
allInfo += ("\n" + "Current Table Number: " + tempStudent
.getTableNum());
allInfo += ("\n" + "Last Three Tables: " + tempStudent
.getLastTableOne() + "->" + tempStudent.getLastTableTwo() + "->" + tempStudent.getLastTableThree());
}
JOptionPane.showMessageDialog(null, allInfo);
} | 2 |
public static void rullTilbake(Connection forbindelse) {
try {
if (forbindelse != null && !forbindelse.getAutoCommit()) {
forbindelse.rollback();
}
} catch (SQLException e) {
skrivMelding(e, "rollback()");
}
} | 3 |
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(VAuthor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VAuthor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VAuthor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VAuthor.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 VAuthor().setVisible(true);
}
});
} | 6 |
private BufferedImage getMaskedImage(BufferedImage bi) {
// get the color of the current paint
final Paint paint = state.fillPaint.getPaint();
if (!(paint instanceof Color)) {
// TODO - support other types of Paint
return bi;
}
Color col = (Color) paint;
// format as 8 bits each of ARGB
int paintColor = col.getAlpha() << 24;
paintColor |= col.getRed() << 16;
paintColor |= col.getGreen() << 8;
paintColor |= col.getBlue();
// transparent (alpha = 1)
int noColor = 0;
// get the coordinates of the source image
int startX = bi.getMinX();
int startY = bi.getMinY();
int width = bi.getWidth();
int height = bi.getHeight();
// create a destion image of the same size
BufferedImage dstImage =
new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// copy the pixels row by row
for (int i = 0; i < height; i++) {
int[] srcPixels = new int[width];
int[] dstPixels = new int[srcPixels.length];
// read a row of pixels from the source
bi.getRGB(startX, startY + i, width, 1, srcPixels, 0, height);
// figure out which ones should get painted
for (int j = 0; j < srcPixels.length; j++) {
if (srcPixels[j] == 0xff000000) {
dstPixels[j] = paintColor;
} else {
dstPixels[j] = noColor;
}
}
// write the destination image
dstImage.setRGB(startX, startY + i, width, 1, dstPixels, 0, height);
}
return dstImage;
} | 4 |
public static void main(String[] args) throws InterruptedException {
ApplicationContext context = new ClassPathXmlApplicationContext("main-context.xml");
WorldFactory worldFactory = context.getBean(ToroidalArrayWorldFactory.class);
UniverseFactory universeFactory = context.getBean(UniverseFactory.class);
GUIWorldViewerFactory viewerFactory = context.getBean(GUIWorldViewerFactory.class);
Queue<World> worlds = new LinkedList<World>();
int worldSize = 300;
World world = worldFactory.createRandomWorld(worldSize, worldSize);
// World world = worldFactory.createWorld(ManyWorlds.LWSS);
Universe universe = universeFactory.createUniverse(worldFactory, world);
GUIWorldViewer worldViewer = viewerFactory.createWorldViewer(universe);
while(true) {
if (worlds.size() > 4) {
worlds.poll();
}
World current = universe.tick();
if (worlds.contains(current)) {
world = worldFactory.createRandomWorld(worldSize, worldSize);
universe.setWorld(world);
}
worlds.add(current);
worldViewer.drawWorld();
Thread.sleep(100);
}
} | 3 |
public Checker getChecker(int x, int y)
{
for(Checker checker: redCheckers)
{
if( (checker.checkX(x)) && (checker.checkY(y)) )
{
return checker;
}
}
for(Checker checker: blackCheckers)
{
if( (checker.checkX(x)) && (checker.checkY(y)) )
{
return checker;
}
}
return null;
} | 6 |
private void addAttackers(int color, int target, int excludedSquare) {
// This function pushes the attackers found on top of the stack in MV (Move-value) order:
// e.g. king -> queens -> rooks and so on so we do NOT have to worry about AttackerStacks
// pushIntoPlace() until we begin to add hidden attackers.
int[] squares = board.getPiecesInMVOrder(color);
int square;
for (int index = 0; (square = squares[index]) != Square.NONE; index++) {
if (square == excludedSquare) {
continue;
}
int inc, next;
int piece = Square.getPiece(board.squares[square]);
if ((inc = Increment.getPieceIncrement(piece, square - target)) != 0) {
for (next = square + inc; Square.isEmpty(board.squares[next]); next += inc) ;
if (next == target) {
//System.out.printf("[added] piece: %s | square: %s (%d) | color: %s | inc: %d\n",
// Piece.getPieceName(piece), Square.getSquareName(square), square, (color == WHITE ? "W" : "B"), inc);
stacks[color].push(square);
}
}
}
// Pawns
int[] incs = (color == BLACK ? new int[]{NW, NE} : new int[]{SE, SW});
for (int inc : incs) {
square = target + inc;
if (square == excludedSquare) {
continue;
}
if (Square.isPieceAndColor(board.squares[square], PAWN, color)) {
assert !Square.isBorder(board.squares[square]);
//System.out.printf("[pawn ] piece: p | square: %s (%d) | color: %s\n", Square.getSquareName(square), square, (color == WHITE ? "W" : "B"));
stacks[color].push(square);
}
}
} | 9 |
private static List<Element> find(Node root, String nsUri, String localName, boolean recursive) {
List<Element> result = new ArrayList<Element>();
NodeList nl = root.getChildNodes();
if (nl != null) {
int len = nl.getLength();
for (int i = 0; i < len; i++) {
Node child = nl.item(i);
if (child instanceof Element) {
String childUri = child.getNamespaceURI();
String childLocalName = child.getLocalName();
if (("*".equals(nsUri) || nsUri == null && childUri == null || nsUri.equals(childUri))
&& localName.equals(childLocalName)) {
result.add((Element) child);
} else if (recursive) {
result.addAll(find(child, nsUri, localName, recursive));
}
}
}
}
return result;
} | 9 |
public void visitStackManipStmt(final StackManipStmt stmt) {
if (CodeGenerator.DEBUG) {
System.out.println("code for " + stmt);
}
genPostponed(stmt);
// All the children are stack variables, so don't so anything.
switch (stmt.kind()) {
case StackManipStmt.SWAP:
method.addInstruction(Opcode.opcx_swap);
break;
case StackManipStmt.DUP:
method.addInstruction(Opcode.opcx_dup);
stackHeight += 1;
break;
case StackManipStmt.DUP_X1:
method.addInstruction(Opcode.opcx_dup_x1);
stackHeight += 1;
break;
case StackManipStmt.DUP_X2:
method.addInstruction(Opcode.opcx_dup_x2);
stackHeight += 1;
break;
case StackManipStmt.DUP2:
method.addInstruction(Opcode.opcx_dup2);
stackHeight += 2;
break;
case StackManipStmt.DUP2_X1:
method.addInstruction(Opcode.opcx_dup2_x1);
stackHeight += 2;
break;
case StackManipStmt.DUP2_X2:
method.addInstruction(Opcode.opcx_dup2_x2);
stackHeight += 2;
break;
}
} | 8 |
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
Page page= new Page();
HttpSession session = request.getSession(getURI(request).indexOf("new")>0);
page.title("Session Dump Servlet: ");
TableForm tf = new TableForm(response.encodeURL(getURI(request)));
tf.method("POST");
if (session==null)
{
page.add("<H1>No Session</H1>");
tf.addButton("Action","New Session");
}
else
{
try
{
tf.addText("ID",session.getId());
tf.addText("State",session.isNew()?"NEW":"Valid");
tf.addText("Creation",
new Date(session.getCreationTime()).toString());
tf.addText("Last Access",
new Date(session.getLastAccessedTime()).toString());
tf.addText("Max Inactive",
""+session.getMaxInactiveInterval());
tf.addText("Context",""+session.getServletContext());
Enumeration keys=session.getAttributeNames();
while(keys.hasMoreElements())
{
String name=(String)keys.nextElement();
String value=session.getAttribute(name).toString();
tf.addText(name,value);
}
tf.addTextField("Name","Property Name",20,"name");
tf.addTextField("Value","Property Value",20,"value");
tf.addTextField("MaxAge","MaxAge(s)",5,"");
tf.addButtonArea();
tf.addButton("Action","Set");
tf.addButton("Action","Remove");
tf.addButton("Action","Invalidate");
page.add(tf);
tf=null;
if (request.isRequestedSessionIdFromCookie())
page.add("<P>Turn off cookies in your browser to try url encoding<BR>");
if (request.isRequestedSessionIdFromURL())
page.add("<P>Turn on cookies in your browser to try cookie encoding<BR>");
}
catch (IllegalStateException e)
{
log.debug(LogSupport.EXCEPTION,e);
page.add("<H1>INVALID Session</H1>");
tf=new TableForm(getURI(request));
tf.addButton("Action","New Session");
}
}
if (tf!=null)
page.add(tf);
Writer writer=response.getWriter();
page.write(writer);
writer.flush();
} | 7 |
private static void GetGraphlist() throws FileNotFoundException {
// TODO Auto-generated method stub
GraphList.clear();
File f = new File("src/kargerMinCut.txt");
Scanner s = new Scanner(f);
int i = 0;
int j = 0;
while (s.hasNext()) {
Scanner sl = new Scanner(s.nextLine());
sl.nextInt();
java.util.ArrayList<Integer> tempList = new ArrayList<Integer>();
while (sl.hasNext()) {
tempList.add(sl.nextInt());
}
GraphList.add(tempList);
i++;
}
} | 2 |
public Point getViewPosition() {
return (viewIsUnbounded() ? getPanCenterPoint() : super.getViewPosition());
} | 1 |
public static Mouse newMouseDialog()
{
JTextField mouseName = new JTextField(12);
JTextField mouseBirthDate = new JTextField(12);
JTextField mouseColour = new JTextField(12);
JPanel namePanel = new JPanel();
namePanel.add(new JLabel("Name:"));
namePanel.add(Box.createHorizontalStrut(22));
namePanel.add(mouseName);
JPanel birthPanel = new JPanel();
birthPanel.add(new JLabel("Geburtsdatum:"));
birthPanel.add(mouseBirthDate);
JPanel colourPanel = new JPanel();
colourPanel.add(new JLabel("Farbe:"));
colourPanel.add(Box.createHorizontalStrut(16));
colourPanel.add(mouseColour);
Object[] message = { "", namePanel, birthPanel, colourPanel };
int result = 0;
while (result != JOptionPane.CANCEL_OPTION)
{
result = JOptionPane.showConfirmDialog(null, message,
"Create new Mouse", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
try
{
Date birth = formatter.parse(mouseBirthDate.getText());
if (mouseName.getText().isEmpty())
{
message[0] = "Bitte gib einen namen ein. \nErlaubte Zeichen A-Z,a-z oder -";
} else if (mouseName.getText().matches("[A-Za-z-]+"))
{
return new Mouse(mouseName.getText(), birth,
mouseColour.getText());
} else
{
message[0] = "Unerlaubtes Zeichen \nErlaubte Zeichen A-Z,a-z oder -";
}
} catch (ParseException e)
{
// TODO Auto-generated catch block
message[0] = "Datum bitte im 19.01.1900 Format eingeben";
}
}
}
return null;
} | 5 |
public static String LFSR(String semSuc, String pol, int sizeOutput) {
int output = 0;
StringBuffer sucAux = new StringBuffer();
int[] vec = new int[sizeOutput]; //Se crea el vector que hace de buffer de tamaño pasado desde la interfaz o igual (2^n-1)*2 por defecto
//Copia la semilla inicial en el buffer
for (int i = 0; i < semSuc.length(); i++){
if(semSuc.charAt(i) == '1')
vec[i] = 1;
else
vec[i] = 0;
}
//Se crea el vector que hace de polinomio de conexion
int[] polCon = new int[pol.length()];
for (int i = 0; i < pol.length(); i++){
if(pol.charAt(i) == '1')
polCon[i] = 1;
else
polCon[i] = 0;
}
//Mientras no se rellene el vector a partir de la semilla ya introducida
for (int i = semSuc.length(); i < vec.length; i++){
//c(D) = D⁴ + D¹ + 1 --> 11001000......
output = 0;
for (int j = 0; j < polCon.length; j++){
output ^= polCon[j]*vec[j];
}
//Va insertando en el vector que contendra el (periodo dos veces)
//Desplaza los elementos anteriores a la derecha e inserta la salida al principio del buffer
for (int k = i; k > 0; k--)
vec[k] = vec[k-1];
vec[0] = output;
}
//Pasar el vector a un string para imprimir, pasandolo en orden invertido
for (int i = vec.length-1; i >= 0 ; i--){
if(vec[i] == 1)
sucAux.append('1');
else
sucAux.append('0');
}
return sucAux.toString();
} | 9 |
public String getDescription() {
return description;
} | 0 |
@Test
public void filtersByAuthorLastnameWorks2() {
citations.add(c1);
citations.add(c2);
citations.add(cnull);
filter.addFieldFilter("author", "Isoherra");
List<Citation> filtered = filter.getFilteredList();
assertTrue(filtered.contains(c2) && filtered.size() == 1);
} | 1 |
public void resolveSymbol() {
switch (m_lex.tok().type()) {
case INT:
case FLOAT:
case CHAR:
case STRING:
updateCurrent(m_symbols.get("{literal}"));
break;
case ID: {
Symbol smb = m_symbols.get(m_lex.tok().value());
if (smb == null) {
smb = m_scope.find(m_lex.tok().value());
}
updateCurrent(smb);
break;
}
case COP:
case OP: {
Symbol smb = m_symbols.get(m_lex.tok().value());
if (smb == null) {
m_lex.tok().error("Unexpected token.");
return;
}
updateCurrent(smb);
break;
}
default:
break;
}
} | 9 |
private void spawnResources(ResourceType rt, int count, int level) {
Point p;
int y;
for (int i = 0; i < count; i++) {
p = rt.getNewXY(gameController.getMapWidth(), level);
if (p.x > 0 && p.y > 0) {
Resource r = new Resource(registry, this, rt, p.x, p.y, 0);
y = findNextFloor(p.x + r.getWidth(), p.y, r.getHeight());
if (p.y == y) {
//make sure the resource isn't spawned in view
if (this.isInPlayerView(p) || this.isInFrontOfPlaceable(r.getPerimeter())) {
r = null;
} else {
registerResource(r);
if (gameController.multiplayerMode == gameController.multiplayerMode.SERVER && registry.getNetworkThread() != null) {
if (registry.getNetworkThread().readyForUpdates()) {
registry.getNetworkThread().sendData(r);
}
}
}
}
}
}
} | 9 |
private void accept(){
if (verifyAddress(Adress.getText())){
if (port.getText().matches("[0-9]+") && port.getText().length() > 0){
if(!Adress.getText().trim().equals("")){
try {
catalogue.setNameServer(InetAddress.getByName(Adress.getText()), Integer.parseInt(port.getText()));
catalogue.setName(nick.getText());
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
if(Manualconnect.isSelected()){
Gui = new startGui(true,Adress.getText(),Integer.parseInt(port.getText()));
}
else{
Gui = new startGui(false,Adress.getText(),Integer.parseInt(port.getText()));
}
catalogue.setGui(Gui);
frame1.dispose();
}
}
}
else {
label.setText(" Invalid port number");
}
} | 6 |
private void handleFileClick(FindReplaceResult result) {
try {
String filepath = result.getFile().getCanonicalPath();
Document doc = Outliner.documents.getDocument(filepath);
if (doc == null) {
// grab the file's extension
String extension = filepath.substring(filepath.lastIndexOf(".") + 1, filepath.length());
// use the extension to figure out the file's format
String fileFormat = Outliner.fileFormatManager.getOpenFileFormatNameForExtension(extension);
// crank up a fresh docInfo struct
DocumentInfo docInfo = new DocumentInfo();
PropertyContainerUtil.setPropertyAsString(docInfo, DocumentInfo.KEY_PATH, filepath);
PropertyContainerUtil.setPropertyAsString(docInfo, DocumentInfo.KEY_ENCODING_TYPE, Preferences.getPreferenceString(Preferences.OPEN_ENCODING).cur);
PropertyContainerUtil.setPropertyAsString(docInfo, DocumentInfo.KEY_FILE_FORMAT, fileFormat);
// try to open up the file
FileMenu.openFile(docInfo, Outliner.fileProtocolManager.getDefault());
doc = Outliner.documents.getDocument(filepath);
if (doc == null) {
// Something went wrong opening the file so abort.
return;
}
}
result.setDocument((OutlinerDocument) doc);
// Handle like an open document now
handleDocumentClick(result, FILE_MODE);
} catch (IOException e) {
System.out.println("IOException while handling click to open file: " + e.getMessage());
}
} | 3 |
private static int readIntNum(CompileInfo ci, String p, boolean decimal){
int radix = 10;
p = p.trim();
if(!decimal){
if(ci.replacements!=null){
Integer num = ci.replacements.get(p.toLowerCase());
if(num!=null)
return num;
}
if(p.startsWith("0x")){//$NON-NLS-1$
p = p.substring(2);
radix = 16;
}else if(p.startsWith("0b")){//$NON-NLS-1$
p = p.substring(2);
radix = 2;
}
}
try{
return Integer.parseInt(p, radix);
}catch(NumberFormatException e){
makeDiagnostic(ci, Kind.ERROR, "wrong.number.format", p);//$NON-NLS-1$
return 0;
}
} | 6 |
public void start() throws InterruptedException {
boolean test = false;
if (test || m_test) {
System.out.println("Othello :: start() BEGIN");
}
boolean m_Trace = false;
if(m_Trace) { System.out.println("Game::Start() - Game has started");}
setWindow(new GameWindow(this));
resetGame();
startTimer();
availableMove();
if (test || m_test) {
System.out.println("Othello :: start() END");
}
} | 5 |
public String getSessionCookie() {
if (sessionCookie == null) {
sessionCookie = "";
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals(SESSION_COOKIE)) {
sessionCookie = cookie.getValue();
}
}
}
return sessionCookie;
} | 3 |
public void exportManagementToCSV() throws FileNotFoundException
{
JFileChooser saveFileChooser = new JFileChooser();
int returnVal = saveFileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = saveFileChooser.getSelectedFile();
String filename = file.getName();
if(!filename.contains("."))
filename = file.getPath() + ".csv";
else
filename = file.getPath();
PrintWriter fileOut;
fileOut = new PrintWriter(filename);
String str = "Name,Wants,Classification,Attitude,Influence,"
+"Strategy,Method of Engagement,"
+"Last Engaged,Responsible Party,Notes,";
fileOut.println(str);
for(Stakeholder sh : Stakeholders)
{
sh.exportStakeholderCSV(fileOut);
}
fileOut.close();
}
} | 3 |
public static int goalHashCode(ControlFrame frame) {
{ Proposition proposition = frame.proposition;
Surrogate operator = Proposition.cachedGoalOperator(proposition);
Vector arguments = proposition.arguments;
int code = 0;
code = ((Context)(Stella.$CONTEXT$.get())).hashCode_();
if (frame.reversePolarityP) {
code = (((((code & 1) == 0) ? (code >>> 1) : (((code >> 1)) | Stella.$INTEGER_MSB_MASK$))) ^ 8312004);
}
code = (((((code & 1) == 0) ? (code >>> 1) : (((code >> 1)) | Stella.$INTEGER_MSB_MASK$))) ^ (Stella_Object.safeHashCode(operator)));
{ Stella_Object arg = null;
Vector vector000 = arguments;
int index000 = 0;
int length000 = vector000.length();
Stella_Object argvalue = null;
Cons iter000 = frame.goalBindings;
loop000 : for (;(index000 < length000) &&
(!(iter000 == Stella.NIL)); index000 = index000 + 1, iter000 = iter000.rest) {
arg = (vector000.theArray)[index000];
argvalue = iter000.value;
if (argvalue == null) {
argvalue = (((QueryIterator)(Logic.$QUERYITERATOR$.get())).currentPatternRecord.variableBindings.theArray)[(((PatternVariable)(arg)).boundToOffset)];
if (argvalue == null) {
code = PatternVariable.hashUnboundGoalVariable(((PatternVariable)(arg)), arguments, code);
continue loop000;
}
}
code = Logic.hashGoalArgument(argvalue, code);
}
}
return (code);
}
} | 7 |
@Override
public void run(int interfaceId, int componentId) {
switch(stage) {
case -1:
sendNPCDialogue(GRILLEGOATS, 9827, "Tee hee! You have never milked a cow before, have you?");
break;
case 0:
sendPlayerDialogue(9827, "Erm... no. How could you tell?");
break;
case 1:
sendNPCDialogue(GRILLEGOATS, 9827, "Because you're spilling milk all over the floor. What a waste! " +
"You need something to hold the milk.");
break;
case 2:
sendPlayerDialogue(9827, "Derp. Ah, yes, I really should have guessed that one, shouldn't I?");
break;
case 3:
sendNPCDialogue(GRILLEGOATS, 9827, "You're from the city, arent you? Try it again with an empty bucket.");
break;
case 4:
sendPlayerDialogue(9827, "Right, I'll do that.");
break;
case 5:
end();
break;
}
stage++;
} | 7 |
private static int checkAndAddFile(List<File> list, File f) {
if (Utilities.getFileExtention(f) != null && Utilities.getFileExtention(f).equalsIgnoreCase("PNG")) {
try {
BufferedImage image = ImageIO.read(f);
int w = image.getWidth(null);
int h = image.getHeight(null);
if (isPowerOfTwo(w) && isPowerOfTwo(h)) {
list.add(f);
return -1;
} else {
return 0;
}
} catch (IOException e) {
return 3;
}
} else {
return 1;
}
} | 5 |
private void renameRemote() {
final int select = remoteList.getSelectedIndex();
if (select < 0 || select > remotefiles.length || client == null) {
return;
}
showDialog(remotefiles[select].getFileName(), new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 27)
dialog.setVisible(false);
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\n') {
String oldname = remotefiles[select].getFileName();
String foldername = tf.getText();
try {
if (client != null && !oldname.equals(foldername) && client.rename(oldname, foldername))
refreshRemote();
} catch (IOException e1) {
e1.printStackTrace();
}
dialog.setVisible(false);
}
}
});
} | 9 |
public static void main(String[] args) {
new AntLabMain().printOutMessage();
} | 0 |
private final void method1065(ByteBuffer class348_sub49, int i,
int i_0_) {
if ((i_0_ ^ 0xffffffff) == -2)
((Class117) this).aChar1778
= Class50_Sub1.method462(class348_sub49.getByte(), -128);
else if ((i_0_ ^ 0xffffffff) == -3)
((Class117) this).aChar1779
= Class50_Sub1.method462(class348_sub49.getByte(),
-128);
else if ((i_0_ ^ 0xffffffff) == -4)
aString1774 = class348_sub49.getJstr();
else if (i_0_ == 4)
anInt1764 = class348_sub49.getDword();
else if (i_0_ == 5 || (i_0_ ^ 0xffffffff) == -7) {
int i_1_ = class348_sub49.getShort();
((Class117) this).aClass356_1767
= new HashTable(Class33.method340(i_1_, (byte) 108));
for (int i_2_ = 0; i_2_ < i_1_; i_2_++) {
int i_3_ = class348_sub49.getDword();
Node class348;
if (i_0_ != 5)
class348
= new Class348_Sub35(class348_sub49
.getDword());
else
class348 = new StringNode(class348_sub49
.getJstr());
((Class117) this).aClass356_1767
.putNode((long) i_3_, class348);
}
}
anInt1765++;
if (i != -21424)
method1068((byte) -15);
} | 9 |
public void feedDrink(int index)
{
DrinkObject drink = Drink.getDrink(index);
if (!canAfford(drink.getPrice()))
return;
thirst += drink.getAmount();
// money -= food.getMoney();
// "Purchased" + food.getName();
// TODO Add Food on the screen.
// TODO adding hunger is placeholder
} | 1 |
public Reader openStream(String publicID,
String systemID)
throws MalformedURLException,
FileNotFoundException,
IOException
{
URL url = new URL(this.currentReader.systemId, systemID);
if (url.getRef() != null) {
String ref = url.getRef();
if (url.getFile().length() > 0) {
url = new URL(url.getProtocol(), url.getHost(), url.getPort(),
url.getFile());
url = new URL("jar:" + url + '!' + ref);
} else {
url = StdXMLReader.class.getResource(ref);
}
}
this.currentReader.publicId = publicID;
this.currentReader.systemId = url;
StringBuffer charsRead = new StringBuffer();
Reader reader = this.stream2reader(url.openStream(), charsRead);
if (charsRead.length() == 0) {
return reader;
}
String charsReadStr = charsRead.toString();
PushbackReader pbreader = new PushbackReader(reader,
charsReadStr.length());
for (int i = charsReadStr.length() - 1; i >= 0; i--) {
pbreader.unread(charsReadStr.charAt(i));
}
return pbreader;
} | 4 |
private void censored(int row) {
if (!MyFactory.getResourceService().hasRight(MyFactory.getCurrentUser(), Resource.CENSORED)) {
return;
}
PaidDetail selectedRow = result == null ? null : result.get(row);
if (selectedRow != null) {
int result = JOptionPane.showConfirmDialog(null, "点击“是”审核通过,“否”审核不通过,“取消”则不作任何操作");
if (result != JOptionPane.CANCEL_OPTION) {
if (MyFactory.getPaidDetailService().censored(selectedRow.getId(),
result == JOptionPane.YES_OPTION ? true : false)) {
JOptionPane.showMessageDialog(null, "审核成功!");
refreshData();
;
}
}
}
} | 6 |
private void writeXRefTable() throws IOException {
// Link each deleted entry to the next deleted entry by iterating
// backwards through the entries, which are sorted by object number.
// End chain by pointing to head. If none del, chain back on itself.
int nextDeletedObjectNumber = 0;
for(int i = entries.size()-1; i >= 0; i--) {
Entry entry = entries.get(i);
if (entry.isDeleted()) {
entry.setNextDeletedObjectNumber(nextDeletedObjectNumber);
nextDeletedObjectNumber =
entry.getReference().getObjectNumber();
}
}
// Insert pseudo-entry for object number zero - the head of freed list
// The generation number is 65535, but we increment it when writing
Entry zero = new Entry(new Reference(0, 65534));
zero.setNextDeletedObjectNumber(nextDeletedObjectNumber);
entries.add(0, zero);
output.write(NEWLINE);
xrefPosition = startingPosition + output.getCount();
output.write(XREF);
for(int i = 0; i < entries.size();) {
i += writeXrefSubSection(i);
}
output.write(NEWLINE);
} | 3 |
public final void start(final MapleClient c, final int npc) {
try {
if (!(cms.containsKey(c) && scripts.containsKey(c))) {
final Invocable iv = getInvocable("npc/" + npc + ".js", c);
final ScriptEngine scriptengine = (ScriptEngine) iv;
if (iv == null) {
return;
}
final NPCConversationManager cm = new NPCConversationManager(c, npc, -1, (byte) -1);
cms.put(c, cm);
scriptengine.put("cm", cm);
c.getPlayer().setConversation(1);
scripts.put(c, iv);
try {
iv.invokeFunction("start"); // Temporary until I've removed all of start
} catch (NoSuchMethodException nsme) {
iv.invokeFunction("action", (byte) 1, (byte) 0, 0);
}
}
} catch (final Exception e) {
e.printStackTrace();
System.err.println("Error executing NPC script, NPC ID : " + npc + "." + e);
dispose(c);
}
} | 5 |
public void extractConfig(final String resource, final boolean replace) {
final File config = new File(this.getDataFolder(), resource);
if (config.exists() && !replace) return;
this.getLogger().log(Level.FINE, "Extracting configuration file {1} {0} as {2}", new Object[] { resource, CustomPlugin.CONFIGURATION_SOURCE.name(), CustomPlugin.CONFIGURATION_TARGET.name() });
config.getParentFile().mkdirs();
final char[] cbuf = new char[1024]; int read;
try {
final Reader in = new BufferedReader(new InputStreamReader(this.getResource(resource), CustomPlugin.CONFIGURATION_SOURCE));
final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(config), CustomPlugin.CONFIGURATION_TARGET));
while((read = in.read(cbuf)) > 0) out.write(cbuf, 0, read);
out.close(); in.close();
} catch (final Exception e) {
throw new IllegalArgumentException("Could not extract configuration file \"" + resource + "\" to " + config.getPath() + "\"", e);
}
} | 4 |
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(ProjectInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProjectInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProjectInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProjectInput.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 ProjectInput(gui).setVisible(true);
}
});
} | 6 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
while ((line = in.readLine()) != null && line.length() != 0) {
int size = Integer.parseInt(line.trim());
if (size == 0)
break;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(size);
int[] v = readInts(in.readLine());
for (int i = 0; i < v.length; i++)
pq.add(v[i]);
int ans = 0, a = 0, b = 0;
while (pq.size() >= 2) {
a = pq.poll();
b = pq.poll();
ans += a + b;
pq.add(a + b);
}
out.append(ans + "\n");
}
System.out.print(out);
} | 5 |