text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
protected void processInput() {
/*==================================================================
* PROCESS INPUT HERE
*===================================================================*/
if(board.keyDownOnce(KeyEvent.VK_ESCAPE)) {
System.exit(0);
}
//==================================================================
} | 1 |
void mergeSuccessors(FlowBlock succ) {
/*
* Merge the successors from the successing flow block
*/
Iterator iter = succ.successors.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
FlowBlock dest = (FlowBlock) entry.getKey();
SuccessorInfo hisInfo = (SuccessorInfo) entry.getValue();
SuccessorInfo myInfo = (SuccessorInfo) successors.get(dest);
if (dest != END_OF_METHOD)
dest.predecessors.remove(succ);
if (myInfo == null) {
if (dest != END_OF_METHOD)
dest.predecessors.add(this);
successors.put(dest, hisInfo);
} else {
myInfo.gen.addAll(hisInfo.gen);
myInfo.kill.retainAll(hisInfo.kill);
Jump myJumps = myInfo.jumps;
while (myJumps.next != null)
myJumps = myJumps.next;
myJumps.next = hisInfo.jumps;
}
}
} | 5 |
void getPersonList(ArrayList<Person> sendingList)
{
Date today = new Date();
String name, zodiac;
int age;
// DefaultTableModel dtModel = new DefaultTableModel();
// Object[] convertedObjects = new Object[4];
// Object[] columnNames = new Object[4];
Object[] convertedObjects = new Object[3];
Object[] columnNames = new Object[3];
columnNames[0] = "Name";
columnNames[1] = "Age";
columnNames[2] = "Zodiac Sign";
dtModel.setColumnIdentifiers(columnNames);
//Define objects by Malinda
ZodiacOperation zodi =new ZodiacOperation();
ArrayList<Player> playerList=new ArrayList<>();
for(Person p : sendingList)
{
name = p.getName();
//Get the DOB and calculate the age
Date bdate = p.getDOB();
int bd = bdate.getYear();
int now = today.getYear();
age = now - bd;
if (bdate.getMonth() > today.getMonth()) { age = age - 1; }
if (bdate.getMonth() == today.getMonth()) { if (bdate.getDate() > today.getDate()) { age = age - 1; } }
//Add Zodiac and Horosscope details of the Person.
int bd_month = bdate.getMonth() + 1;
int bd_date = bdate.getDate();
//Operations by Malinda
Player player=new Player();
player.setName(name);
player.setAge(age);
player.setMonth(bd_month);
player.setDay(bd_date);
playerList.add(player);
}
//Connecting to prolog logic by Malinda
ArrayList<Player> resultPlayer=zodi.getZodiacResult(playerList);
for (Player player : resultPlayer)
{
//Display Person in the Table
convertedObjects[0] = player.getName();
convertedObjects[1] = player.getAge();
convertedObjects[2] = player.getZodiacSign();
dtModel.addRow(convertedObjects);
}
this.tbl_Display.setModel(dtModel);
} | 5 |
public String generate() {
String error = "No errors.";
if (details)
System.out.println("Biomes flags: PRODUCE="+ioflags.PRODUCE+", SAVE="+ioflags.SAVE+", LOAD="+ioflags.LOAD);
if (Utils.flagsCheck(ioflags) != 0) {
System.out.println("ERROR: IOFlags object is corrupted, error: "+Utils.flagsCheck(ioflags));
return "BiomesGenerator critical error - read above.";
}
if (ioflags.PRODUCE)
error = produceBiomes();
if (ioflags.LOAD)
error = loadBiomes();
return error;
} | 4 |
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
boolean[] self = new boolean[1000001];
for (int i = 1; i <= 1000000; i++) {
int tot = 0, x = i;
while (x / 10 > 0) {
tot += x % 10;
x /= 10;
}
String ret = "";
if (tot == 0 && x == i) {
ret = i + "";
for (int j = 0; j < ret.length(); j++) {
tot += ret.charAt(j) - '0';
}
} else {
tot += x;
}
tot += i;
if (tot <= 1000000) {
self[tot] = true;
}
}
for (int i = 1; i <= 1000000; i++) {
if (!self[i]) {
System.out.println(i);
}
}
} | 8 |
public void Unload()
{
currentlyReading = true;
if(hashTable)
hashtable.clear();
else if(hashList)
hashlist.clear();
else if(binaryTree)
binarytree.clear();
else if(naryTree)
narytree.clear();
System.gc();
currentlyReading = false;
} | 4 |
public MenuThing(){
super();
if (System.getProperty("os.name").contains("Mac")) {
System.out.println("The game knows that it is running on Mac OS.");
System.setProperty("apple.laf.useScreenMenuBar", "true"); //make JMenuBars appear at the top in Mac OS X
}
else if (System.getProperty("os.name").contains("Windows")){
System.out.println("The game knows that it is running on Windows.");
}
else {
System.out.println("The game does not know what system it is running on. Unless you are running Linux or something obscure (in which case this is fine), this is a minor problem.");
}
JMenuBar menus = new JMenuBar();
JMenu sound = new JMenu("Sound");
JMenuItem toggleMusic = new JMenuItem("Toggle music");
JMenuItem toggleSound = new JMenuItem("Toggle sound effects");
JMenuItem changeMusic = new JMenuItem("Change music...");
sound.add(toggleMusic); sound.add(toggleSound); sound.add(changeMusic);
menus.add(sound);
menus.validate();
this.setJMenuBar(menus);
this.validate();
this.setVisible(true);
} | 2 |
public static Integer[] graySuccessor(Integer[] e) {
Integer[] copy = Arrays.copyOf(e, e.length);
if (hammingDist(copy) % 2 == 0) {
copy[0] = 1 - copy[0];
return copy;
} else {
for (int i = 0; i <= e.length - 2; i++) {
if (copy[i] != 0) {
copy[i + 1] = 1 - copy[i + 1];
return copy;
}
}
}
return null;
} | 3 |
private List<T> getResults(ResultSet rs) throws SQLException {
List<T> results = new ArrayList<T>();
while (rs.next()) {
T t = fillFrom(rs);
//a.setId(rs.getInt("id"));
//a.setDescr(rs.getString("descr"));
//a.setCh(rs.getInt("ch"));
results.add(t);
}
return results;
} | 1 |
private Rule renameVariables(Rule rule) {
int uniqueVariableId = variableIdGenerator.incrementAndGet();
Set<Variable> variables = new HashSet<Variable>();
// At first I'll get a list of all variables that appear in the head of the rule.
for (Term term : rule.getHead().getArgs()) {
if (term instanceof Variable) {
variables.add((Variable) term);
}
}
List<Predicate> newConditions = new ArrayList<Predicate>(rule.getConditions().size());
// The next step is to go through all conditions and see whether they use variables
// that don't appear in the head of the rule. If that's the case, rename those
// variables to ensure that they won't be captured later on.
for (Predicate condition : rule.getConditions()) {
for (Term term : condition.getArgs()) {
if (term instanceof Variable && !variables.contains(term)) {
// If this is true, then we'll better rename this variable to some unique thing.
// In this case, I'll just prepend the prefix "__$$__" and a unique ID in front
// of the variable name.
Variable variable = (Variable) term;
condition = (Predicate) condition.substitute(
variable, new Variable("__$$__" +
uniqueVariableId + "_" + variable.getName()));
}
}
newConditions.add(condition);
}
return new Rule(rule.getHead(), newConditions);
} | 6 |
public String extend(String s, int l, int r){
if(l == r){
for(;l-1 >= 0 && r+1 < s.length(); --l, ++r){
if(s.charAt(l-1) != s.charAt(r+1)) break;
}
return s.substring(l, r+1);
}else{
for(; l >= 0 && r < s.length(); --l, ++r){
if(s.charAt(l) != s.charAt(r)) break;
}
return r-1 < l+1 ? "" : s.substring(l+1, r-1+1);
}
} | 8 |
private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers)
throws ResponseException {
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) {
return;
}
StringTokenizer st = new StringTokenizer(inLine);
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
}
pre.put("method", st.nextToken());
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
}
String uri = st.nextToken();
// Decode parameters from the URI
int qmi = uri.indexOf('?');
if (qmi >= 0) {
decodeParms(uri.substring(qmi + 1), parms);
uri = decodePercent(uri.substring(0, qmi));
} else {
uri = decodePercent(uri);
}
// If there's another token, it's protocol version,
// followed by HTTP headers. Ignore version but parse headers.
// NOTE: this now forces header names lowercase since they are
// case insensitive and vary by client.
if (st.hasMoreTokens()) {
String line = in.readLine();
while (line != null && line.trim().length() > 0) {
int p = line.indexOf(':');
if (p >= 0)
headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
line = in.readLine();
}
}
pre.put("uri", uri);
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
} | 9 |
public void menuPanelUpdate() {
playerHealth.setText("Health: " + theGame.getPlayer(0).getHealth());
money.setText("Moneys: $" + theGame.getPlayer(0).getMoney());
time.setText("Time: " + theGame.getTime() + "\n Round: " + theGame.getCurrentMap().getCurrentLevel());
if (theGame.getCurrentTowerInfo() != null) {
info.setText(" "
+ theGame.getCurrentTowerInfo().getName()
+ " "
+ "\n"
+ "Attacks: "
+ theGame.getCurrentTowerInfo().getAttacks().get(0)
.getName());
if (theGame.getCurrentTowerInfo().getUpgraded() != null) {
infoPanel.add(evolveButton);
} else
infoPanel.remove(evolveButton);
} else if (theGame.getCurrentMobsInfo() != null) {
for (Mob mob : theGame.getCurrentMobsInfo()) {
if (mob.getHealth() > 0)
info.setText(mob.getName() + ": " + mob.getHealth() + "\n");
}
} else {
info.setText("");
infoPanel.remove(evolveButton);
}
if (theGame.betweenRounds()) {
switchButtons(pauseButton.getText());
}
} | 6 |
@Override
public String getName() {
return NAME;
} | 0 |
private Object readBigInteger() {
byte[] longintBytes = new byte[8];
longintBytes[0] = bytes[streamPosition++];
longintBytes[1] = bytes[streamPosition++];
longintBytes[2] = bytes[streamPosition++];
longintBytes[3] = bytes[streamPosition++];
longintBytes[4] = bytes[streamPosition++];
longintBytes[5] = bytes[streamPosition++];
longintBytes[6] = bytes[streamPosition++];
longintBytes[7] = bytes[streamPosition++];
return new BigInteger(longintBytes);
} | 0 |
public void wakeUpPlayer(boolean par1, boolean par2, boolean par3)
{
this.setSize(0.6F, 1.8F);
this.resetHeight();
ChunkCoordinates var4 = this.playerLocation;
ChunkCoordinates var5 = this.playerLocation;
Block block = (var4 == null ? null : Block.blocksList[worldObj.getBlockId(var4.posX, var4.posY, var4.posZ)]);
if (var4 != null && block != null && block.isBed(worldObj, var4.posX, var4.posY, var4.posZ, this))
{
block.setBedOccupied(this.worldObj, var4.posX, var4.posY, var4.posZ, this, false);
var5 = block.getBedSpawnPosition(worldObj, var4.posX, var4.posY, var4.posZ, this);
if (var5 == null)
{
var5 = new ChunkCoordinates(var4.posX, var4.posY + 1, var4.posZ);
}
this.setPosition((double)((float)var5.posX + 0.5F), (double)((float)var5.posY + this.yOffset + 0.1F), (double)((float)var5.posZ + 0.5F));
}
this.sleeping = false;
if (!this.worldObj.isRemote && par2)
{
this.worldObj.updateAllPlayersSleepingFlag();
}
if (par1)
{
this.sleepTimer = 0;
}
else
{
this.sleepTimer = 100;
}
if (par3)
{
this.setSpawnChunk(this.playerLocation);
}
} | 9 |
public Set<Map.Entry<Byte,Long>> entrySet() {
return new AbstractSet<Map.Entry<Byte,Long>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TByteLongMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TByteLongMapDecorator.this.containsKey(k)
&& TByteLongMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Byte,Long>> iterator() {
return new Iterator<Map.Entry<Byte,Long>>() {
private final TByteLongIterator it = _map.iterator();
public Map.Entry<Byte,Long> next() {
it.advance();
byte ik = it.key();
final Byte key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
long iv = it.value();
final Long v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Byte,Long>() {
private Long val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Byte getKey() {
return key;
}
public Long getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Long setValue( Long value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Byte,Long> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Byte key = ( ( Map.Entry<Byte,Long> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Byte, Long>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TByteLongMapDecorator.this.clear();
}
};
} | 8 |
public Equivalence deserialize(JsonElement json,
Type type,
JsonDeserializationContext context) throws JsonParseException {
return this.getEquivalence(json.getAsJsonArray().get(0));
} | 0 |
@Override
public Container getCurrentContainer() {
if (containerStack.size() > 0) {
return (Container) containerStack.get(containerStack.size() - 1);
} else {
return this;
}
} | 1 |
public CheckResultMessage check10(int day) {
return checkReport.check10(day);
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FileRights other = (FileRights) obj;
if (!Arrays.equals(groupRights, other.groupRights)) {
return false;
}
if (!Arrays.equals(othersRights, other.othersRights)) {
return false;
}
if (!Arrays.equals(ownerRights, other.ownerRights)) {
return false;
}
return true;
} | 6 |
private Enemy createRandomEnemy()
{
int random = new Random().nextInt(4);
switch (random) {
case 0:
return new Dwarf(this);
case 1:
return new Elf(this);
case 2:
return new Hobbit(this);
case 3:
return new Human(this);
}
return null;
} | 4 |
@RequestMapping(value = {"/SucursalBancaria/{idSucursalBancaria}"}, method = RequestMethod.DELETE)
public void delete(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idSucursalBancaria") int idSucursalBancaria) {
try {
sucursalBancariaDAO.delete(idSucursalBancaria);
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
} catch (Exception ex) {
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
httpServletResponse.setContentType("text/plain; charset=UTF-8");
try {
noCache(httpServletResponse);
ex.printStackTrace(httpServletResponse.getWriter());
} catch (Exception ex1) {
noCache(httpServletResponse);
}
}
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof OFPortMod)) {
return false;
}
OFPortMod other = (OFPortMod) obj;
if (advertise != other.advertise) {
return false;
}
if (config != other.config) {
return false;
}
if (!Arrays.equals(hardwareAddress, other.hardwareAddress)) {
return false;
}
if (mask != other.mask) {
return false;
}
if (portNumber != other.portNumber) {
return false;
}
return true;
} | 8 |
public EmptyStringCharacterAction() {
//super("Test Turing Machines", null);
super("Set the Empty String Character", null);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P,
MAIN_MENU_MASK));
this.fileChooser = Universe.CHOOSER;
} | 0 |
public boolean isPalindrome(String s) {
if (s.length() == 0) {
return true;
}
s = s.toLowerCase();
int start = 0;
int end = s.length() - 1;
while (start <= end) {
while (start < s.length() && !isCharNum(s.charAt(start))) {
start++;
}
while (end >= 0 && !isCharNum(s.charAt(end))) {
end--;
}
if (start <= end) {
if (s.charAt(start) == s.charAt(end)) {
start++;
end--;
} else {
return false;
}
} else {
return true;
}
}
return true;
} | 8 |
public static void main(String[] args) {
// test divide by zero - should print an error and exit
new Fraction(1, 0);
// test multiply
Fraction f = new Fraction(3,10);
Fraction g = new Fraction(1,2);
Fraction h = new Fraction(3,5);
if (!f.equals(g.multiply(h))) System.out.println("Multiply failed");
// test equals
test(new Fraction(1, 2),new Fraction(1, 2),"error test 1");
test(new Fraction(1, 2),new Fraction(3, 6),"error test 2");
test(new Fraction(-1, 2),new Fraction(1, -2),"error test 3");
test(new Fraction(-1, -2),new Fraction(1, 2),"error test 4");
test(new Fraction(4, -8),new Fraction(1, 2),"error test 5");
// extend with extra tests
// test add
Fraction i = new Fraction(19,15);
Fraction j = new Fraction(3,5);
Fraction k = new Fraction(2,3);
if(!i.equals(j.add(k))) System.out.println("Add failed");
// test subtract
Fraction l = new Fraction(1,6);
Fraction m = new Fraction(2,3);
Fraction n = new Fraction(1,2);
if(!l.equals(m.subtract(n))) System.out.println("Sub failed");
// test divide
Fraction o = new Fraction(6,2);
Fraction p = new Fraction(1,2);
Fraction q = new Fraction(1,6);
if(!o.equals(p.divide(q))) System.out.println("Divide failed");
// test absolute
Fraction r = new Fraction(-3,7);
Fraction s = new Fraction(3,7);
if(!s.equals(r.absolute())) System.out.println("Absolute failed");
// test negative
Fraction t = new Fraction(-3,7);
if(!t.equals(r.negative())) System.out.println("Negative failed");
Fraction u = r.negative();
System.out.println(u.getNumerator() + "," + u.getDenominator());
// test toString
Fraction v = new Fraction(3, 1);
System.out.println(v.toString());
System.out.println(u.toString());
} | 6 |
protected void doTestCycAccess10(CycAccess cycAccess) {
long startMilliseconds = System.currentTimeMillis();
try {
// demonstrate quoted strings
//cycAccess.traceOn();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("a");
stringBuffer.append('"');
stringBuffer.append("b");
stringBuffer.append('"');
stringBuffer.append("c");
String expectedString = stringBuffer.toString();
CycList command = new CycList();
command.add(makeCycSymbol("identity"));
command.add(expectedString);
String resultString = cycAccess.converseString(command);
assertEquals(expectedString, resultString);
CycList cycList53 = cycAccess.makeCycList("(\"abc\")");
assertEquals(1,
cycAccess.converseInt("(length '" + cycList53.cycListApiValue() + ")"));
assertEquals(3,
cycAccess.converseInt("(length (first '" + cycList53.cycListApiValue() + "))"));
String string = "abc";
CycList cycList54 = new CycList();
cycList54.add(makeCycSymbol("length"));
cycList54.add(string);
assertEquals(3, cycAccess.converseInt(cycList54));
String quotedString = "\"abc\" def";
CycList cycList55 = new CycList();
cycList55.add(makeCycSymbol("length"));
cycList55.add(quotedString);
// Note that in binary mode, that Cyc's cfasl input will insert the required escape
// chars for embedded quotes.
// And in ascii mode note that CycConnection will insert the required escape
// chars for embedded quotes. While in binary mode, CfaslOutputStream will insert
// the required escapes.
//
// Cyc should see (length "\"abc\" def") and return 9
assertEquals(9, cycAccess.converseInt(cycList55));
// demonstrate quoted strings with the CycListParser
CycList cycList56 = cycAccess.makeCycList("(\"" + string + "\")");
assertEquals(1, cycAccess.converseInt("(length " + cycList56.stringApiValue() + ")"));
assertEquals(3, cycAccess.converseInt("(length (first " + cycList56.stringApiValue() + "))"));
String embeddedQuotesString = "(" + "\"\\\"abc\\\" def\"" + ")";
CycList cycList57 = cycAccess.makeCycList(embeddedQuotesString);
String script = "(length " + cycList57.stringApiValue() + ")";
int actualLen = cycAccess.converseInt(script);
assertEquals(1, actualLen);
assertEquals(9, cycAccess.converseInt("(length (first " + cycList57.stringApiValue() + "))"));
script = "(identity (quote (#$givenNames #$Guest \"\\\"The\\\" Guest\")))";
String script1 = "(IDENTITY (QUOTE (#$givenNames #$Guest \"\"The\" Guest\")))";
//CycListParser.verbosity = 3;
CycList scriptCycList = cycAccess.makeCycList(script);
// Java strings do not escape embedded quote chars
assertEquals(script1, scriptCycList.cyclify());
CycList answer = cycAccess.converseList(script);
Object third = answer.third();
assertTrue(third instanceof String);
assertEquals(11, ((String) third).length());
answer = cycAccess.converseList(scriptCycList);
third = answer.third();
assertTrue(third instanceof String);
assertEquals(11, ((String) third).length());
// isFormulaWellFormed
if (!cycAccess.isOpenCyc()) {
CycFormulaSentence formula1 = cycAccess.makeCycSentence("(#$isa #$Brazil #$IndependentCountry)");
CycConstant mt = cycAccess.getKnownConstantByName("WorldPoliticalGeographyDataVocabularyMt");
assertTrue(cycAccess.isFormulaWellFormed(formula1, mt));
CycFormulaSentence formula2 = cycAccess.makeCycSentence("(#$genls #$Brazil #$Collection)");
assertTrue(!cycAccess.isFormulaWellFormed(formula2, mt));
}
// isCycLNonAtomicReifableTerm
CycNaut formula3 = cycAccess.makeCycNaut("(#$TheCovering #$Watercraft-Surface #$Watercraft-Subsurface)");
assertTrue(cycAccess.isCycLNonAtomicReifableTerm(formula3));
CycFormulaSentence formula4 = cycAccess.makeCycSentence("(#$isa #$Plant #$Animal)");
assertTrue(!cycAccess.isCycLNonAtomicReifableTerm(formula4));
CycNaut formula5 = cycAccess.makeCycNaut("(#$PlusFn 1)");
assertTrue(!cycAccess.isCycLNonAtomicReifableTerm(formula5));
// isCycLNonAtomicUnreifableTerm
CycNaut formula6 = cycAccess.makeCycNaut("(#$TheCovering #$Watercraft-Surface #$Watercraft-Subsurface)");
assertTrue(!cycAccess.isCycLNonAtomicUnreifableTerm(formula6));
CycFormulaSentence formula7 = cycAccess.makeCycSentence("(#$isa #$Plant #$Animal)");
assertTrue(!cycAccess.isCycLNonAtomicUnreifableTerm(formula7));
CycNaut formula8 = cycAccess.makeCycNaut("(#$PlusFn 1)");
assertTrue(cycAccess.isCycLNonAtomicUnreifableTerm(formula8));
} catch (Throwable e) {
e.printStackTrace();
fail(e.toString());
}
long endMilliseconds = System.currentTimeMillis();
System.out.println(" " + (endMilliseconds - startMilliseconds) + " milliseconds");
} | 2 |
public Rating addRatings(HashMap<String, Object> rat) {
@SuppressWarnings("unchecked")
HashMap<String, String> holder = (HashMap<String, String>)rat.get("rating");
if(holder.containsKey("authorsId")) this.authorsId = holder.get("authorsId");
if(holder.containsKey("comment")) this.comment = holder.get("comment");
if(holder.containsKey("date")) this.date = Date.valueOf(holder.get("date"));
if(holder.containsKey("stars")) this.stars = Integer.parseInt(holder.get("stars"));
return this;
} | 4 |
public static User findOneAdmin() {
try
{
return User.findOne("isAdmin", "1");
} catch (SQLException e)
{
e.printStackTrace();
return null;
}
} | 1 |
public HospitalFacade() {
super(Hospital.class);
} | 0 |
public IndexedModel toIndexedModel()
{
IndexedModel result = new IndexedModel();
IndexedModel normalModel = new IndexedModel();
HashMap<OBJIndex, Integer> resultIndexMap = new HashMap<OBJIndex, Integer>();
HashMap<Integer, Integer> normalIndexMap = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
for(int i=0; i < indices.size(); i++)
{
OBJIndex currentIndex = indices.get(i);
Vector3f currentPos = positions.get(currentIndex.vertexIndex);
Vector2f currentTexCoord;
Vector3f currentNormal;
if(hasTexCoords)
currentTexCoord = texCoords.get(currentIndex.texCoordIndex);
else
currentTexCoord = new Vector2f(0,0);
if(hasNormals)
currentNormal = normals.get(currentIndex.normalIndex);
else
currentNormal = new Vector3f(0, 0, 0);
Integer modelVertexIndex = resultIndexMap.get(currentIndex);
if(modelVertexIndex == null)
{
modelVertexIndex = result.getPositions().size();
resultIndexMap.put(currentIndex, result.getPositions().size());
result.getPositions().add(currentPos);
result.getTexCoords().add(currentTexCoord);
if(hasNormals)
result.getNormals().add(currentNormal);
}
Integer normalModelIndex = normalIndexMap.get(currentIndex.vertexIndex);
if(normalModelIndex == null)
{
normalModelIndex = normalModel.getPositions().size();
normalIndexMap.put(currentIndex.vertexIndex, normalModel.getPositions().size());
normalModel.getPositions().add(currentPos);
normalModel.getTexCoords().add(currentTexCoord);
normalModel.getNormals().add(currentNormal);
}
result.getIndices().add(modelVertexIndex);
normalModel.getIndices().add(normalModelIndex);
indexMap.put(modelVertexIndex, normalModelIndex);
}
if(!hasNormals)
{
normalModel.calcNormals();
for(int i=0; i<result.getPositions().size(); i++)
result.getNormals().add(normalModel.getNormals().get(indexMap.get(i)));
}
return result;
} | 8 |
private void logout() {
try {
sendToServer(Packet.getLogoutPacket());
PacketManager.readPacketFromStream(in);
} catch(Exception e) {}
try {
out.close();
} catch(Exception e) {}
try {
in.close();
} catch(Exception e) {}
try {
socket.close();
} catch(Exception e) {}
dispose();
} | 4 |
public static Description coerceToDescription(Stella_Object self, Stella_Object original) {
if (original == null) {
original = self;
}
if (self == null) {
System.out.println("Can't find a description for the object `" + original + "'.");
return (null);
}
{ Surrogate testValue000 = Stella_Object.safePrimaryType(self);
if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_DESCRIPTION)) {
{ Description self000 = ((Description)(self));
return (self000);
}
}
else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_RELATION)) {
{ Relation self000 = ((Relation)(self));
return (Logic.getDescription(self000));
}
}
else if (Surrogate.subtypeOfSurrogateP(testValue000)) {
{ Surrogate self000 = ((Surrogate)(self));
return (Logic.coerceToDescription(self000.surrogateValue, original));
}
}
else if (Surrogate.subtypeOfSymbolP(testValue000)) {
{ Symbol self000 = ((Symbol)(self));
return (Logic.coerceToDescription(Surrogate.lookupSurrogateInModule(self000.symbolName, ((Module)(self000.homeContext)), false), original));
}
}
else if (Surrogate.subtypeOfKeywordP(testValue000)) {
{ Keyword self000 = ((Keyword)(self));
return (Logic.coerceToDescription(Surrogate.lookupSurrogate(self000.symbolName), original));
}
}
else if (Surrogate.subtypeOfStringP(testValue000)) {
{ StringWrapper self000 = ((StringWrapper)(self));
return (Logic.coerceToDescription(Surrogate.lookupSurrogate(self000.wrapperValue), original));
}
}
else {
return (Logic.coerceToDescription(null, original));
}
}
} | 8 |
private static boolean isNoneHexChar(char c) {
// make sure the char is the following
return !(((c >= 48) && (c <= 57)) || // 0-9
((c >= 65) && (c <= 70)) || // A-F
((c >= 97) && (c <= 102))); // a-f
} | 5 |
public SelectTaskXmlDriver(String xmlStr) throws DocumentException,
XmlTypeErrorException {
super();
if (!isSelectTaskXml(xmlStr)) {
throw new XmlTypeErrorException("not a valid selectTask Xml");
}
document = DocumentHelper.parseText(xmlStr);
timestamp = document.selectSingleNode("//properties/timestamp")
.getText();
aggregation = document.selectSingleNode(
"//properties/operation/aggregation").getText();
fromCubeIdentifier = document.selectSingleNode(
"//properties/operation/from").getText();
Element root = this.document.getRootElement();
List<?> list = root
.selectNodes("//properties/operation/conditions/condition");
String dimensionName;
String levelName;
String start;
String end;
ConditionBean conditionBean;
Node tmpNode;
for (Iterator<?> iter = list.iterator(); iter.hasNext(); ) {
Node node = (Node) iter.next();
dimensionName = node.selectSingleNode("dimensionName").getText();
levelName = node.selectSingleNode("levelName").getText();
if (null == (tmpNode = node.selectSingleNode("start"))) {
start = "";
} else {
start = tmpNode.getText();
}
if (null == (tmpNode = node.selectSingleNode("end"))) {
end = "";
} else {
end = tmpNode.getText();
}
conditionBean = new ConditionBean(dimensionName, levelName, start,
end);
conditionBeans.add(conditionBean);
}
} | 6 |
private void compareFrames()
{
int r, g, b,
refDataInt, inDataInt,
ip = 0, op = 0,
x = 0, y = 0;
byte result;
while (ip < refData.length)
{
refDataInt = (int) refData[ip] & 255;
inDataInt = (int) this.inData[ip++] & 255;
r = refDataInt - inDataInt;
refDataInt = (int) refData[ip] & 255;
inDataInt = (int) this.inData[ip++] & 255;
g = refDataInt - inDataInt;
refDataInt = (int) refData[ip] & 255;
inDataInt = (int) this.inData[ip++] & 255;
b = refDataInt - inDataInt;
result = (byte) (Math.sqrt((double) ((r * r) + (g * g) + (b * b)) / 3.0));
//black/white image now.
if (result > (byte) this.threshold)
{
if (validateActionSection(x, y))
{
detectionScreen[op++] = (byte) 255;
detectionScreen[op++] = (byte) 0;
detectionScreen[op++] = (byte) 0;
}
else
{
detectionScreen[op++] = (byte) 0;
detectionScreen[op++] = (byte) 255;
detectionScreen[op++] = (byte) 0;
}
}
else
{
detectionScreen[op++] = (byte) result;
detectionScreen[op++] = (byte) result;
detectionScreen[op++] = (byte) result;
}
y = x == this.sizeIn.width ? y + 1 : y;
x = x == this.sizeIn.width ? 0 : x + 1;
}
} | 5 |
private ClusterList beginBottomUp() {
Cluster newCluster;
ClusterList firstClusterList = new ClusterList();
for (int i = 0; i < this.instances.numInstances(); i++) {
newCluster = new Cluster(this.instances.instance(i));
firstClusterList.add(newCluster);
}
return firstClusterList;
} | 1 |
public void pad(int width) throws IOException {
int gap = (int) this.nrBits % width;
if (gap < 0) {
gap += width;
}
if (gap != 0) {
int padding = width - gap;
while (padding > 0) {
this.zero();
padding -= 1;
}
}
this.out.flush();
} | 3 |
public List<String> getLinks() {
Pattern pattern = Pattern.compile("(?i)(?s)<\\s*?iframe.*?href=\"(.*?)\".*?>");
Matcher matcher = pattern.matcher(content);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group(1));
}
return list;
} | 1 |
public String isInteresting(String x){
int n = x.length();
boolean[] visited = new boolean[n];
for(int i=0; i<n-1; i++){
if(!visited[i]){
visited[i]=true;
boolean found=false;
for(int j=i+1; j<n; j++){
if(!visited[j] && x.charAt(i)==x.charAt(j) && j-i-1==Integer.parseInt(x.charAt(i)+"")){
found=true;
visited[j]=true;
}
}
if(!found) return "Not interesting";
}
}
return visited[n-1] ? "Interesting" : "Not interesting";
} | 8 |
public boolean[] getMarkers(boolean colour) {
if (colour) {
return markersBlack;
} else {
return markersRed;
}
} | 1 |
@Override
public String niceCommaList(List<?> V, boolean andTOrF)
{
String id="";
for(int v=0;v<V.size();v++)
{
String s=null;
if(V.get(v) instanceof Environmental)
s=((Environmental)V.get(v)).name();
else
if(V.get(v) instanceof String)
s=(String)V.get(v);
else
continue;
if(V.size()==1)
id+=s;
else
if(v==(V.size()-1))
id+=((andTOrF)?"and ":"or ")+s;
else
id+=s+", ";
}
return id;
} | 7 |
@Override
public ExecutionContext run(ExecutionContext context) throws InterpretationException {
int x = DrawingZone.turtle.getPosX();
int y = DrawingZone.turtle.getPosY();
Value value = ((AbsValueNode) this.getChildAt(0)).evaluate(context);
if (value.getType() == VariableType.NUMBER) {
Number num = (Number) value.getValue();
int _X = (int) (num.intValue() * Math.cos((double) Math.toRadians(DrawingZone.turtle.getHeading())));
int _Y = -(int) (num.intValue() * Math.sin((double) Math.toRadians(DrawingZone.turtle.getHeading())));
DrawingZone.turtle.setPos(x + _X, y + _Y);
Color color;
if(DrawingZone.turtle.getErase())
color = UserInterface.dw.getBackground();
else
color = UserInterface.dw.getCurrentColor();
if (DrawingZone.turtle.getPen())
UserInterface.dw.toDraw.add(new Shape(new Line2D.Float(x, y, x + _X, y + _Y), color));
UserInterface.dw.revalidate();
} else
throw new InterpretationException(InterpretationErrorType.INVALID_ARGUMENT, line, null);
return context;
} | 3 |
@Test
public void testLoadFile()
{
// String ergebnisstring1 = "";
// String ergebnisstring2 = "Hallo, ich bin ein\nZeilenumbruch ";
// String ergebnisstring3 = "Gesperrtes File";
// // // String ergebnisstring4 =
// // // "D�ner mit So�e & einer b�rigen t�rkischen Bananen & Co KG";
// //
// assertEquals(ergebnisstring1,
// SourceLoader.loadFile("/var/www/testfiles/testfile1.txt"));
//// assertEquals(ergebnisstring2,
//// SourceLoader.loadFile("/var/www/testfiles/testfile2.txt"));
// assertEquals(ergebnisstring3,
// SourceLoader.loadFile("/var/www/testfiles/testfile3.txt"));
//
// assertTrue(SourceLoader.loadFile("/var/www/testfiles/fehlendesfile.txt").contains("FAIL FileNotFoundException"));
} | 0 |
public void setFrontLeftThrottle(int frontLeftThrottle) {
this.frontLeftThrottle = frontLeftThrottle;
if ( ccDialog != null ) {
ccDialog.getThrottle1().setText(Integer.toString(frontLeftThrottle) );
}
} | 1 |
@Override
public void run() {
ClientHandler c;
stop = false;
if (!isConnected())
throw new IllegalStateException("Service not connected!");
pool = Executors.newCachedThreadPool(new ClientThreadFactory(
getUncaughtExceptionHandler()));
try {
try {
while (!stop) {
c = new ClientHandler(ns.accept(), as, this.keyDirectory, this.privateKeyServer);
clientHandlerList.add(c);
pool.execute(c);
}
} finally {
if (pool != null)
shutdownAndAwaitTermination(pool);
if (ns != null)
ns.close();
}
} catch (IOException e) {
// The if-clause down here is because of what is described in
// http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
// under "What if a thread doesn't respond to Thread.interrupt?"
// So the socket is closed when the ClientNetworkService is
// closed and in that special case no error should be
// propagated.
if (!stop) {
UncaughtExceptionHandler eh = this
.getUncaughtExceptionHandler();
if (eh != null)
eh.uncaughtException(this, e);
}
}
} | 7 |
private void move() {
xa = 0;
ya = 0;
List<Player> players = level.getPlayers(this, 50);
if (players.size() > -0) {
Player player = players.get(0);
if (x < player.getX()) xa += speed;
if (x > player.getX()) xa -= speed;
if (y < player.getY()) ya += speed;
if (y > player.getY()) ya -= speed;
}
if (xa != 0 || ya != 0) {
move(xa, ya);
walking = true;
} else {
walking = false;
}
} | 7 |
public boolean subst(ASTree newObj, ASTree oldObj) {
for (ASTList list = this; list != null; list = list.right)
if (list.left == oldObj) {
list.left = newObj;
return true;
}
return false;
} | 2 |
@EventHandler
public void MagmaCubeRegeneration(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.getMagmaCubeConfig().getDouble("MagmaCube.Regeneration.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getMagmaCubeConfig().getBoolean("MagmaCube.Regeneration.Enabled", true) && damager instanceof MagmaCube && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, plugin.getMagmaCubeConfig().getInt("MagmaCube.Regeneration.Time"), plugin.getMagmaCubeConfig().getInt("MagmaCube.Regeneration.Power")));
}
} | 6 |
public HandlerQueue buildHandlerQueue (Class<? extends IEvent> event) {
// create handler queue
HandlerQueue queue = new HandlerQueue ();
// append queues
if (this.handlerMap.containsKey (event)) queue.addAll (this.handlerMap.get (event));
// search for child
if (event.getSuperclass () != null) {
Class<?> superEvent = event.getSuperclass ();
// cast
try {
queue.addAll (this.buildHandlerQueue (superEvent.asSubclass (IEvent.class)));
} catch (ClassCastException ex) { }
}
// return finished queue
return queue;
} | 5 |
public static void ShowEnumSet(EnumSet<FontConstant> enumset)
{
for(Iterator<FontConstant> iter = enumset.iterator();iter.hasNext();)
{
System.out.println(iter.next());
}
} | 1 |
public void train(StringWrapperIterator i0)
{
SourcedStringWrapperIterator i = (SourcedStringWrapperIterator)i0;
Set seenTokens = new HashSet();
while (i.hasNext()) {
BagOfSourcedTokens bag = asBagOfSourcedTokens(i.nextSourcedStringWrapper());
seenTokens.clear();
for (Iterator j=bag.tokenIterator(); j.hasNext(); ) {
totalTokenCount++;
Token tokj = (Token)j.next();
if (!seenTokens.contains(tokj)) {
seenTokens.add(tokj);
// increment documentFrequency counts
Integer df = (Integer)documentFrequency.get(tokj);
if (df==null) documentFrequency.put(tokj,ONE);
else if (df==ONE) documentFrequency.put(tokj,TWO);
else if (df==TWO) documentFrequency.put(tokj,THREE);
else documentFrequency.put(tokj, new Integer(df.intValue()+1));
}
}
collectionSize++;
}
} | 6 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (!creationdate.equals(user.creationdate)) return false;
if (!email.equals(user.email)) return false;
if (!id.equals(user.id)) return false;
if (!lastupdate.equals(user.lastupdate)) return false;
if (!password.equals(user.password)) return false;
if (!username.equals(user.username)) return false;
return true;
} | 8 |
public void terminate() {
// If we have any branches which should not be taken,
// we need to create a failure handler for if they were taken.
if (generateGlobalNotTaken) {
// XXX: In the future, if we want to set specific flags here,
// can add more instructions after the label and add an
// unconditional branch above it to avoid executing the block at
// the end of the program.
instructions.add(new Instruction(new Label("nottaken")));
instructions.get(instructions.size() - 1).appendComment("failure " +
"case for wrongly taken branches");
}
instructions.add(new Instruction(new HLT()));
String finalState = "\n";
// Summarize registers
for (int i = 0; i < registerFile.length; i++) {
finalState += "\n# R" + i + " = " + (isRegisterValid
(registerFromNumber(i)) ? registerFile[i] : "xxxx");
}
// Summarize flags
finalState += "\n\n# Z = " + (isFlag_z() ? "1" : "0") + " N = " +
(isFlag_n()
? "1" : "0") + " V = " + (isFlag_v() ? "1" : "0");
// Summarize memory:
finalState += "\n\n# Valid memory addresses:";
for (int i : validMemory) {
finalState += "\n# mem[" + i + "] = " + memory[i];
}
instructions.get(instructions.size() - 1).appendComment(finalState);
} | 7 |
public Address getIndirizzo() {
return indirizzo;
} | 0 |
public void getBusiness() throws IOException{
while (true) {
String line = reader1.readLine();
if (line==null) break;
try{
JSONObject business = new JSONObject(line);
String b_id = business.getString("business_id");
List<String> categories = new ArrayList<String>();
JSONArray rawcategories = business.getJSONArray("categories");
for(int i=0; i<rawcategories.length();i++){
categories.add(rawcategories.getString(i));
}
int review_count = business.getInt("review_count");
double stars = business.getDouble("stars");
Business b = new Business(b_id, categories, review_count, stars);
businessMap.put(b_id, b);
}catch(JSONException e) {
e.printStackTrace();
System.out.print(line + System.getProperty("line.separator"));
}
}
} | 4 |
public static void copyFile(File inF, File outF) throws IOException {
// TODO Auto-generated method stub
//System.out.println("Copying");
@SuppressWarnings("resource")
FileChannel inChannel = new FileInputStream(inF).getChannel();
@SuppressWarnings("resource")
FileChannel outChannel = new FileOutputStream(outF).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
Misc.ErrorMessage();
throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
} | 3 |
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0) return 0;
int row = obstacleGrid.length, col = obstacleGrid[0].length;
int hash[][] = new int[row][col];
for (int i = 0; i < col; i++) {
if (obstacleGrid[0][i] == 1) {
break;
}
hash[0][i] = 1;
}
for (int i = 0; i < row; i++) {
if (obstacleGrid[i][0] == 1) {
break;
}
hash[i][0] = 1;
}
for (int x = 1; x < row; x++) {
for (int y = 1; y < col; y++) {
if (obstacleGrid[x][y] == 0) {
hash[x][y] = hash[x - 1][y] + hash[x][y - 1];
} else {
hash[x][y] = 0;
}
}
}
return hash[row - 1][col - 1];
} | 9 |
public static Hand getBestHand(Card[] hole, Card[] communalCards) {
assert hole.length == 2;
assert communalCards.length == 5;
Hand[] allHands = new Hand[21];
Card[] available = new Card[]{hole[0],hole[1],communalCards[0], communalCards[1],communalCards[2],communalCards[3],communalCards[4]};
int counter = 0;
for (int i = 0; i < 7; i++) {
for (int j = i+1; j < 7; j++) {
Hand hand = generateHand(available,i, j);
if(hand != null){
allHands[counter++] = hand;
}
}
}
if(counter > 0){
List<Hand> temp = Arrays.asList(allHands).subList(0, counter);
Collections.sort(temp);
return temp.get(temp.size()-1);
}else{
return null;
}
} | 4 |
public static Boolean readFile(ByteBuffer buffer, FileTransfer fileReceiver){
ByteBuffer readBuffer = buffer.asReadOnlyBuffer();
buffer.limit(50);// 读取50个字节,解析获取内容的长度,内容长度最大为4个FFFF(4个字节),再加上2个字节\r\n
String msg = CoderUtils.decode(buffer);
if(!MyStringUtil.isBlank(msg)){// 上传文件的请求头
if(fileReceiver.isReadHead()){
fileReceiver.writeBody(readBuffer, 0, fileReceiver.getSizeWithHead());// 读取文件内容
fileReceiver.setReadHead(false);
fileReceiver.setSizeWithHead(0);
}else{
String packageHead = msg.split((HttpConstants.RetentionWord.CRLF_STR))[0];
try{
Integer length = Integer.parseInt(packageHead, 16);
Integer btyeLength = packageHead.getBytes().length + 2;// 加上2个回车换行符
fileReceiver.writeBody(readBuffer, btyeLength, length);// 读取文件内容
}catch(NumberFormatException nfe){// 读取不带包头信息的文件
fileReceiver.writeBody(readBuffer, 0);// 读取文件内容
}
}
}
return null;
} | 3 |
public void tagVirts() {
for (Clazz clazz : classes.values()) {
clazz.tagVirts(this);
}
for (DirManager dir : subDirs) {
dir.tagVirts();
}
} | 2 |
public void setCoef(String coef) {
this.coef = coef;
} | 0 |
@Override
public String toString() {
return this.nodeString(0);
} | 0 |
public void alertNext() {
scenesCounter++;
if(scenesCounter<scenePics.size()){
scene=scenePics.get(scenesCounter);
}else{
if(nextLevel.startsWith("b")){
getKarpfenGame().setLvl(new BossLevel(nextLevel, getKarpfenGame()));
}else if(nextLevel.startsWith("s")){
getKarpfenGame().setStory(new Storyline(nextLevel, getKarpfenGame()));
}else{
getKarpfenGame().setLvl(new Level(nextLevel, karpfenGame));
}
scenePics.clear();
karpfenGame.setStory(null);
}
} | 3 |
public void showValues() {
String attribute;
ArffSortedTableModel model;
ArffTable table;
HashSet values;
Vector items;
Iterator iter;
ListSelectorDialog dialog;
int i;
int col;
// choose attribute to retrieve values for
attribute = showAttributes();
if (attribute == null)
return;
table = (ArffTable) getCurrentPanel().getTable();
model = (ArffSortedTableModel) table.getModel();
// get column index
col = -1;
for (i = 0; i < table.getColumnCount(); i++) {
if (table.getPlainColumnName(i).equals(attribute)) {
col = i;
break;
}
}
// not found?
if (col == -1)
return;
// get values
values = new HashSet();
items = new Vector();
for (i = 0; i < model.getRowCount(); i++)
values.add(model.getValueAt(i, col).toString());
if (values.isEmpty())
return;
iter = values.iterator();
while (iter.hasNext())
items.add(iter.next());
Collections.sort(items);
dialog = new ListSelectorDialog(getParentFrame(), new JList(items));
dialog.showDialog();
} | 7 |
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (!(o instanceof FilterSet)) return false;
FilterSet filterSet = (FilterSet) o;
if (filters != null ? !filters.equals(filterSet.filters) : filterSet.filters != null) return false;
return true;
} | 4 |
public boolean instanceOf(Object obj, String className)
throws InterpreterException {
Class clazz;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException ex) {
throw new InterpreterException("Class " + ex.getMessage()
+ " not found");
}
return obj != null && clazz.isInstance(obj);
} | 2 |
private void addListener() {
final MainViewController mainViewController = this;
mainView.setAboutMenuListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new AboutPanel();
}
});
mainView.setServerConfigMenuListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// Show settings window
settingsViewController = new SettingsViewController(mainView);
}
});
mainView.setOpenPadMenuListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String padId = JOptionPane.showInputDialog("Pad ID");
if (padId == null) {
return;
}
try {
openPad(padId);
} catch (EPLiteException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mainView, "Error: " + e.getMessage() + ". Are you sure you entered the correct padId?",
"Error loading pad", JOptionPane.ERROR_MESSAGE);
}
}
});
mainView.setCreatePadMenuListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String padId = JOptionPane.showInputDialog("Pad ID");
if (padId == null) {
return;
}
try {
if (isGroupPad()) {
int reply = JOptionPane.showConfirmDialog(null, "Create pad for this group?", "", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
createGroupPad(padId);
} else {
createPublicPad(padId);
}
} else {
createPublicPad(padId);
}
} catch (EPLiteException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mainView, "Error: " + e.getMessage(), "Error creating pad", JOptionPane.ERROR_MESSAGE);
}
}
});
mainView.setManagePadsMenuListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new ManagePadsController(epLite.getAllGroups(), mainViewController);
}
});
mainView.setOpenGroupMenuListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String groupId = JOptionPane.showInputDialog("Group ID");
if (groupId == null) {
return;
}
try {
openGroup(groupId);
} catch (EPLiteException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mainView, "Error: " + e.getMessage(), "Error opening group", JOptionPane.ERROR_MESSAGE);
}
}
});
mainView.setCreateGroupMenuListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
openGroup(epLite.createGroup());
}
});
/*
* mainView.setDeleteGroupMenuListener(new ActionListener() {
*
* @Override public void actionPerformed(ActionEvent arg0) {
* epLite.deleteGroup(actualGroupId); } });
*/
mainView.setListAllGroupsMenuListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
new GroupListController(epLite.getAllGroups(), mainViewController);
} catch (EPLiteException epEx) {
epEx.printStackTrace();
JOptionPane.showMessageDialog(mainView, "Error: " + epEx.getMessage(), "Error listing groups", JOptionPane.ERROR_MESSAGE);
}
}
});
} | 9 |
@Override
public void executeCurrentTasks() {
System.out.println("Thread: " + threadId + " is executing a task");
setThreadState(THREAD_STATE.RUNNING);
// System.out.println("Task list size: " + taskList.size());
for (int i = 0; i < taskList.size(); i++) {
Task task = taskList.remove(i);
// System.out.println("Executing task " + task.getTaskId()
// + " on thread " + getThreadId());
taskCallback = task.getTaskCallback();
if (taskCallback != null) {
taskCallback.onTaskStart(task);
}
task.beginTask(this);
task.stopTask();
do {
if (getThreadState() == THREAD_STATE.FINISHED) {
stopThread();
}
} while (getThreadState() != THREAD_STATE.READY_FOR_NEXT_TASK
|| getThreadState() != THREAD_STATE.FINISHED);
}
} | 5 |
static void maybeDebugWarn(final String message, final boolean force) {
if (DEBUG_ALL || force) {
System.err.println(getTimestamp() + " " + message);
}
} | 2 |
public void closePanel(String chan) {
int index = indexOfTab(chan);
if (index != -1) {
tabs.removeTabAt(index);
if (index <= lastChanIndex)
lastChanIndex--;
}
setSelectedTab();
tabs.revalidate();
} | 2 |
@Before
public void setUp() throws Exception {
words = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
words.add("Eric");
}
for (int i = 0; i < 30; i++) {
words.add(String.valueOf(i));
}
for (int i = 0; i < 50; i++) {
words.add("Gonzalez");
}
} | 3 |
public void setPersonId(int personId) {
this.personId = personId;
} | 0 |
private void initGui(Stage primaryStage) {
this.stage = primaryStage;
// splitPaneHoriz = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, splitPaneVerti);
// splitPaneHoriz.setResizeWeight(0);
// splitPaneHoriz.setDividerLocation(250);
// splitPaneHoriz.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() {
// @Override
// public void propertyChange(PropertyChangeEvent evt) {
// if (!leftPanelVisible && (int) evt.getNewValue() > (int) evt.getOldValue()) {
// hideLeftPanel.setText(" < ");
// leftPanelVisible = true;
// }
// }
// });
// BUILD VERTICAL SPLIT PANE =========================================
verticalSplitPane = new SplitPane();
verticalSplitPane.setOrientation(Orientation.VERTICAL);
verticalSplitPane.getItems().addAll(
RegionBuilder.create().build(),
RegionBuilder.create().build());
verticalSplitPane.setDividerPositions(0.2);
// BUILD LEFT AREA ===================================================
TreeItem<ImgEvent> eventRootNode = new TreeItem<ImgEvent>(new ImgEvent("", 0, 0));
TreeView<ImgEvent> eventTree = new TreeView<ImgEvent>();
eventTree.setShowRoot(false);
eventTree.setRoot(eventRootNode);
for (int i=0; i<40; i++) {
TreeItem<ImgEvent> item = new TreeItem<ImgEvent>(new ImgEvent("Element " + i, 0, 0));
eventRootNode.getChildren().add(item);
TreeItem<ImgEvent> child = new TreeItem<ImgEvent>(new ImgEvent("Child " + i, 0, 0));
item.getChildren().add(child);
}
Tab eventTab = new Tab("Events");
eventTab.setContent(eventTree);
TreeItem<String> dateRootNode = new TreeItem<String>("Dates");
TreeView<String> dateTree = new TreeView<String>();
dateTree.setShowRoot(false);
dateTree.setRoot(dateRootNode);
for (int i=0; i<40; i++) {
TreeItem<String> item = new TreeItem<String>("Element " + i);
dateRootNode.getChildren().add(item);
TreeItem<String> child = new TreeItem<String>("Child " + i);
item.getChildren().add(child);
}
Tab dateTab = new Tab("Dates");
dateTab.setContent(dateTree);
TabPane leftTabPane = new TabPane();
leftTabPane.setSide(Side.TOP);
leftTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
leftTabPane.getTabs().addAll(dateTab, eventTab);
// leftTabbedPane.addChangeListener(new ChangeListener() {
// @Override
// public void stateChanged(ChangeEvent e) {
// if (leftTabbedPane.getSelectedComponent().equals(eventScrollPane)) {
// dateTree.setSelectionInterval(-10, -1);
// imageBrowser.clearDates();
// }
// else if (leftTabbedPane.getSelectedComponent().equals(dateScrollPane)) {
// eventTree.setSelectionInterval(-10, -1);
// imageBrowser.clearEvent();
// }
// loadImages();
// }
// });
BorderPane leftPane = new BorderPane();
leftPane.setCenter(leftTabPane);
hideLeftPane = new Label(" < ");
BorderPane.setAlignment(hideLeftPane, Pos.CENTER);
hideLeftPane.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
if (leftPaneVisible) {
horizontalSplitPaneDivPos = horizontalSplitPane.getDividerPositions()[0];
// ;
horizontalSplitPane.setDividerPosition(0, (hideLeftPane.getWidth() +6) / stage.getWidth());
// horizontalSplitPane.set
hideLeftPane.setText(" > ");
leftPaneVisible = false;
}
else {
horizontalSplitPane.setDividerPosition(0, horizontalSplitPaneDivPos);
hideLeftPane.setText(" < ");
leftPaneVisible = true;
}
}
});
leftPane.setRight(hideLeftPane);
// BUILD HORIZONTAL SPLIT PANE =======================================
horizontalSplitPane = new SplitPane();
horizontalSplitPane.setOrientation(Orientation.HORIZONTAL);
horizontalSplitPane.getItems().addAll(
leftPane,
verticalSplitPane);
horizontalSplitPane.setDividerPositions(0.2);
SplitPane.setResizableWithParent(verticalSplitPane, false);
// BUILD THE FRAME ===================================================
stage.setScene(new Scene(horizontalSplitPane));
Point defaultSize = new Point(750, 600);
Point size = guiProperties.getPropPoint("gui_frame_size", defaultSize);
Point defaultPos = new Point(-10000, -10000);
Point pos = guiProperties.getPropPoint("gui_frame_position", defaultPos);
if (isWindowInScreenBounds(pos, size)) {
stage.setWidth(size.x);
stage.setHeight(size.y);
stage.setX(pos.x);
stage.setY(pos.y);
}
else {
stage.setWidth(defaultSize.x);
stage.setHeight(defaultSize.y);
}
stage.setMinWidth(500);
stage.setMinHeight(500);
stage.setTitle("Image Browser");
stage.show();
} | 4 |
private void humanMove(int playerNumber){
boolean setCell = false;
while (true){
int x = 0,y = 0;
while (!setCell) {
x = GetData.GetXCoordinateOfCell(field);
y = GetData.GetYCoordinateOfCell(field);
if (playerNumber == FIRST_PLAYER_NUMBER){
setCell = field.setCellFirstPlayer(x,y);
}else if (playerNumber == SECOND_PLAYER_NUMBER){
setCell = field.setCellSecondPlayer(x,y);
}
}
System.out.println("Do you want to change your choose?");
if(GetData.getYesOrNoAnswer()){
field.setDefaultCellValue(x,y);
setCell = false;
} else {
if(gameRegime == TWO_PLAYERS_ONLINE_GAME_REGIME){
gameInternet.sentMove(x,y);
}
return;
}
}
} | 6 |
public String [] getOptions() {
String [] options = new String [16];
int current = 0;
if (m_noCleanup) {
options[current++] = "-L";
}
if (!m_collapseTree) {
options[current++] = "-O";
}
if (m_unpruned) {
options[current++] = "-U";
} else {
if (!m_subtreeRaising) {
options[current++] = "-S";
}
if (m_reducedErrorPruning) {
options[current++] = "-R";
options[current++] = "-N"; options[current++] = "" + m_numFolds;
options[current++] = "-Q"; options[current++] = "" + m_Seed;
} else {
options[current++] = "-C"; options[current++] = "" + m_CF;
}
}
if (m_binarySplits) {
options[current++] = "-B";
}
options[current++] = "-M"; options[current++] = "" + m_minNumObj;
if (m_useLaplace) {
options[current++] = "-A";
}
if (!m_useMDLcorrection) {
options[current++] = "-J";
}
while (current < options.length) {
options[current++] = "";
}
return options;
} | 9 |
private void logErrorsFile(byte[] data) throws IOException {
if (ProduceCSV.produceLog) {
if (errorsFile.size() == 0) {
return;
}
if (fileErrorLog == null) {
openErrorLogFile();
}
fileErrorLog.println("------");
fileErrorLog.println(parameterData.jobName);
for (String error : errorsFile) {
fileErrorLog.println(error);
}
fileErrorLog.println(new String(data));
fileErrorLog.flush();
}
} | 4 |
private Boolean potEqual(Table table) {
boolean allEqual = true;
int max = 0;
for (Player player : table.getPlayers()) {
if (player == null) {
continue;
}
System.out.println("player : " + player.getName() + " : status : " + player.getStatus() + " : " + player.getBet() + " max: " + max);
if (player.getStatus().equals(Player.ACTIVE) || player.getStatus().equals(Player.INACTIVE)) {
if (max == 0) {
max = player.getBet();
} else if (player.getBet() != max) {
return false;
}
}
}
return allEqual;
} | 6 |
public void buttonListener(int cell){
switch (cell){
case 1: _x = 1; _y = 1; break;
case 2: _x = 2; _y = 1; break;
case 3: _x = 3; _y = 1; break;
case 4: _x = 1; _y = 2; break;
case 5: _x = 2; _y = 2; break;
case 6: _x = 3; _y = 2; break;
case 7: _x = 1; _y = 3; break;
case 8: _x = 2; _y = 3; break;
case 9: _x = 3; _y = 3; break;
}
doInput = true;
} | 9 |
public byte[] toByteArray() {
return cw == null ? null : cw.toByteArray();
} | 1 |
public static void main(String[] args) {
logger.setLevel(Level.SEVERE);
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.SEVERE);
logger.addHandler(handler);
if (args.length == 0) {
logger.warning("Invalid arguments count.");
return;
}
try {
String key = args[0];
String alphabet = args[1];
String file = args[2];
String dir=args[3];
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.ready()) {
if (dir.equals("0")) {
String ret = encrypt(key, in.readLine(), alphabet);
System.out.println(ret);
} else if (dir.equals("1")){
String ret = decrypt(key, in.readLine(), alphabet);
System.out.println(ret);
}else{
String ret = encrypt(key, in.readLine(), alphabet);
System.out.println(ret);
ret = decrypt(key, ret, alphabet);
System.out.println(ret);
}
}
} catch (NumberFormatException | FileNotFoundException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
} | 6 |
public Object nextValue() throws JSONException {
char c = nextClean();
String s;
switch (c) {
case '"':
case '\'':
return nextString(c);
case '{':
back();
return new JSONObject(this);
case '[':
case '(':
back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = next();
}
back();
s = sb.toString().trim();
if (s.equals("")) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(s);
} | 8 |
public static void omniData(Object m){
rover = head;
while(rover != null){
if(rover.status == 1){
rover.sendObject(m);
}
rover = rover.next;
}
} | 2 |
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
session.removeAttribute("error");
session.removeAttribute("sucesso");
String valor = request.getParameter("oferta");
try {
Leitor leitor = (Leitor) session.getAttribute("user");
if(leitor == null){
session.setAttribute("error", "Leitor nao está logado.");
response.sendRedirect(request.getContextPath() + "/index.jsp");
}else if(valor == null || valor.trim().equals("")){
session.setAttribute("error", "Preencha todos os campos.");
response.sendRedirect(request.getContextPath() + "/mostrarClassificado.jsp");
}else{
ClassificadoDAO dao = new ClassificadoDAO();
double oferta = Double.parseDouble(valor);
Classificado classificado = (Classificado)session.getAttribute("classificado");
if(oferta > classificado.getPreco() && oferta > classificado.getMelhorOferta()){
classificado.setUsuario(leitor);
classificado.setDataOferta(new Date());
classificado.setMelhorOferta(oferta);
dao.atualizar(classificado);
session.setAttribute("classificado", classificado);
response.sendRedirect(request.getContextPath() + "/mostrarClassificado.jsp");
} else {
session.setAttribute("error", "Oferta menor que ultimo lance dado.");
response.sendRedirect(request.getContextPath() + "/mostrarClassificado.jsp");
}
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
} | 7 |
long largestPrimeFactor(long number){
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=2;i<number;i++){
boolean isPrime=false;
for(Integer prime:list){
if(i%prime==0){
isPrime=true;
break;
}
}
if(isPrime)
continue;
list.add(i);
if(number%i==0){
while(number%i==0){
number=number/i;
}
if(number==i)
return number;
}
}
return number;
} | 7 |
public void openRd(String filename) {
try {
this.close();
this.filename = filename;
inf = true;
file = new File(this.filename);
sc = new Scanner(file);
} catch (FileNotFoundException e) {
ExceptionLog.println("Ошибка открытия файла " + this.filename + " для чтения");
} catch(Exception e) {
ExceptionLog.println("Ошибка в блоке открытия файла " + this.filename + " для чтения");
ExceptionLog.println(e);
}
} | 2 |
private void connect() throws Exception {
// // 创建SSLContext对象,并使用我们指定的信任管理器初始化
// TrustManager[] tm = { new MyX509TrustManager() };
// SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
// sslContext.init(null, tm, new java.security.SecureRandom());
// // 从上述SSLContext对象中得到SSLSocketFactory对象
// SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url2 = new URL("https://kyfw.12306.cn/otn/queryOrder/queryMyOrderNoComplete");
HttpsURLConnection con2 = (HttpsURLConnection) url2.openConnection();
con2.setSSLSocketFactory(Utils.getSsf());
InputStream is2 = con2.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is2, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.indexOf("用户未登录") != -1)
System.out.println(line);
}
reader.close();
login("[email protected]", "lichao258", "test");
} | 2 |
public boolean treeContains(CoreInterface ci){
if(ci.getClass() == Dvd.class){
if(dvdTree.contains(ci)){
return true;
}
return false;
}else if(ci.getClass() == Location.class){
if(locationTree.contains(ci)){
return true;
}
return false;
}else if(ci.getClass() == Genre.class){
if(genreTree.contains(ci)){
return true;
}
return false;
}
return false;
} | 6 |
private boolean isLocationInPicture(final int x, final int y) {
boolean result = false; // the default is false
if ((x >= 0) && (x < this.picture.getWidth()) && (y >= 0)
&& (y < this.picture.getHeight())) {
result = true;
}
return result;
} | 4 |
@EventHandler
public void WitherMiningFatigue(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.getZombieConfig().getDouble("Wither.MiningFatigue.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof WitherSkull) {
WitherSkull a = (WitherSkull) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getWitherConfig().getBoolean("Wither.MiningFatigue.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, plugin.getWitherConfig().getInt("Wither.MiningFatigue.Time"), plugin.getWitherConfig().getInt("Wither.MiningFatigue.Power")));
}
}
} | 7 |
public void configQuickstart(Object args[]) {
//
//
final TerrainGen TG = new TerrainGen(
64, 0.0f,
Habitat.ESTUARY, 0.15f,
Habitat.MEADOW , 0.35f,
Habitat.BARRENS, 0.35f,
Habitat.DUNE , 0.15f
) ;
final World world = new World(TG.generateTerrain()) ;
TG.setupMinerals(world, 0, 0, 0) ;
TG.setupOutcrops(world) ;
final Base base = Base.createFor(world, false) ;
//
//
final Human ruler = new Human(new Career(
Rand.yes(), Background.KNIGHTED, Background.HIGH_BIRTH,
(Background) Rand.pickFrom(Background.ALL_PLANETS)
), base) ;
final Human consort = new Human(new Career(
ruler.traits.female(), Background.FIRST_CONSORT,
Background.HIGH_BIRTH, ruler.career().homeworld()
), base) ;
final List <Human> advisors = new List <Human> () ;
advisors.add(ruler) ;
advisors.add(consort) ;
final List <Human> colonists = new List <Human> () ;
for (int n = 2 ; n-- > 0 ;) {
colonists.add(new Human(Background.VOLUNTEER , base)) ;
colonists.add(new Human(Background.SUPPLY_CORPS, base)) ;
colonists.add(new Human(Background.TECHNICIAN , base)) ;
}
for (int n = 3 ; n-- > 0 ;) {
final Background b = (Background) Rand.pickFrom(COLONIST_BACKGROUNDS) ;
colonists.add(new Human(b, base)) ;
}
for (Human c : colonists) {
for (Skill s : house.skills()) if (c.traits.traitLevel(s) > 0) {
c.traits.incLevel(s, 5) ;
}
}
base.incCredits(10000) ;
base.commerce.assignHomeworld((System) house) ;
base.setInterestPaid(2) ;
base.commerce.assignHomeworld((System) ruler.career().homeworld()) ;
final Bastion bastion = establishBastion(
world, base, ruler, advisors, colonists
) ;
beginGame(world, base, bastion) ;
} | 5 |
public boolean sabotiere( int auswahl )
{
boolean erfolgreich = false;
switch ( auswahl )
{
case 1:
erfolgreich = goldStehlen();
break;
case 2:
erfolgreich = gebaeudeZerstoeren();
break;
case 3:
erfolgreich = kornVergiften();
break;
case 4:
erfolgreich = zufriedenheitVerringern();
break;
}
return erfolgreich;
} | 4 |
public String prepareURL(String method, HashMap<String, String> params)
throws IllegalArgumentException {
String ret = Connection.baseURL + method + "?";
boolean first = true;
boolean illegalMethod = true;
// Validate given method is a supported method
for (final String s : Connection.methods) {
if (s.equals(method)) {
illegalMethod = false;
break;
}
}
if (illegalMethod) {
throw new IllegalArgumentException(
String.format("Invalid method |%s|", method));
}
for (final Map.Entry<String, String> entry : params.entrySet()) {
try {
// Skip null
if ((entry.getValue() == null) || (entry.getKey() == null)) {
continue;
}
if (entry.getValue().length() == 0) {
continue;
}
if (first) {
first = false;
} else {
ret += "&";
}
ret += String.format(
"%s=%s",
URLEncoder.encode(entry.getKey(), "UTF-8"),
URLEncoder.encode(entry.getValue(), "UTF-8")
);
} catch (final UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
}
return ret;
} | 9 |
public static void continueDealing(long currentTime) {
if (!isDealing) {
return;
}
if (numCardsDealt >= Game.NUM_INITIAL_CARDS) {
Game.linkedGet().flipCard();
isDealing = false;
return;
}
if (currentTime - initialTime >= DEAL_DELAY) {
Game.linkedGet().drawCard(Game.linkedGet().getPlayers().get(currentPlayerIndex));
initialTime = currentTime;
currentPlayerIndex++;
if (currentPlayerIndex >= Game.linkedGet().getNumPlayers()) {
currentPlayerIndex = 0;
numCardsDealt++;
}
}
} | 4 |
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// Draw the ghost Tetromino
g2d.setColor(Color.LIGHT_GRAY);
for (Point p : myWorld.generateGhostBlockCoordinates()) {
g2d.drawRect(p.x * blockSize + 3, p.y * blockSize + 3,
blockSize - 6, blockSize - 6);
}
// Draw each Block
IIterator iter = (myWorld.getBlockCollection()).getIterator();
while (iter.hasNext()) {
(iter.getNext()).draw(g2d);
}
Color lastColor = g2d.getColor();
// Draw the board
g2d.setColor(Color.DARK_GRAY);
for (int i = 0; i <= boardSizeY; i++) {
g2d.drawLine(0, i * blockSize, boardSizeX * blockSize, i
* blockSize);
}
for (int i = 0; i <= boardSizeX; i++) {
g2d.drawLine(i * blockSize, 0, i * blockSize, boardSizeY
* blockSize);
}
// Tint the board if paused
if (!myWorld.getPlayStatus()) {
g2d.setColor(new Color(lastColor.getRed(), lastColor.getGreen(),
lastColor.getBlue(), 50));
g2d.fillRect(1, 1, boardSizeX * blockSize - 1, boardSizeY
* blockSize - 1);
g2d.setColor(Color.WHITE);
g2d.drawString("Paused", boardSizeX * blockSize - 55, 20);
}
} | 5 |
private void startup() {
HSSettings settings = HSSettings.getInstance();
// The channel store loads its current set of channels. If no channel
// list is found then a default set of channels will be loaded into the
// list.
channelStore.setItemHistory(itemHistory);
channelStore.load(settings.getChannelStoreFile());
itemStore.load(settings.getItemStoreFile());
itemHistory.load(settings.getItemHistoryFile());
// Set up the listeners.
itemStore.addItemStoreListener(itemStoreListener);
channelStore.addChannelStoreListener(channelStoreListener);
try {
bsfManager.declareBean("channelStore", channelStore, ChannelStore.class);
bsfManager.declareBean("itemStore", itemStore, ItemStore.class);
} catch (BSFException bsfe) {
cat.error("Unable to declare beans for scripting due to " + bsfe);
}
// Normally Java Web Start handles a proxy for us, even if it is a proxy
// that requires authentication. However, if HotSheet is run from the
// command line the proxy has to be set manually so we have properties
// to set us up for proxy operation (though it is not good enough for
// an authenticated proxy.
//
// Note that the default value of this is false so unless the user sets
// something it will not be used.
boolean useProxy = new Boolean(
settings.getProperties().getProperty("http.proxySet",
"false")).booleanValue();
if (useProxy) {
System.setProperty("http.proxySet", "true");
System.setProperty("http.proxyHost",
settings.getProperties().getProperty("http.proxyHost"));
System.setProperty("http.proxyPort",
settings.getProperties().getProperty("http.proxyPort"));
// See if we have an authentication name for authenticating proxies.
boolean useAuth = new Boolean(
settings.getProperties().getProperty("http.authSet",
"false")).booleanValue();
if (useAuth) {
final String authenticationName =
settings.getProperties().getProperty("http.authName");
final String authenticationPassword =
settings.getProperties().getProperty("http.authPass");
try {
//registering with the system.
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
authenticationName,
authenticationPassword.toCharArray());
}
});
} catch (SecurityException se) {
cat.error("Security exception while registering Authenticator with system: ",
se);
}
}
}
// If the user wants to have refresh occur automatically then the number
// of seconds to wait between refreshes will be set in the properties
// file.
int refreshInterval = (new Integer(
settings.getProperties().getProperty("refresh.interval",
"0"))).intValue();
if (refreshInterval > 0) {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
channelStore.retrieve(true);
}
}, refreshInterval * 1000, refreshInterval * 1000);
}
// If the item store is empty query the user about going ahead and doing
// a refresh now.
if (itemStore.size() == 0) {
int answer = JOptionPane.showConfirmDialog(this,
"Would you like to refresh all channels? (New HotSheet users should always say yes)",
"Refresh Now?", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
refreshAllChannels();
}
} else {
updateItemList();
}
} | 7 |
private static void removeEmptyComments(File directory) throws IOException {
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
removeEmptyComments(file);
} else {
for (String currentEnding : CONFIG.getFileEndingsToCheck()) {
if (file.getAbsolutePath().endsWith(currentEnding) && !ignoreFile(file)) {
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String fileContent = new String(data, "UTF-8");
boolean foundInFile = false;
String emptyComment = "/**" + (char) 10 + " */";
while (fileContent.contains(emptyComment)) {
foundInFile = true;
fileContent = fileContent.replace(emptyComment, "");
}
if (foundInFile) {
PrintWriter out = new PrintWriter(file);
out.print(fileContent);
out.close();
System.out.println("file: " + file.getAbsolutePath()
+ " modified by removing double empty comment");
COUNTER++;
}
}
}
}
}
} | 7 |
public String mapMethodName(String owner, String name, String desc) {
String s = map(owner + '.' + name + desc);
return s == null ? name : s;
} | 1 |
public Key delMin() {
if (isEmpty())
throw new java.util.NoSuchElementException();
Key min = pq[1];
exch(1, N--);
sink(1);
pq[N + 1] = null;
if (N == pq.length / 4)
resize(pq.length / 2);
return min;
} | 2 |