text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public static void divideLargeFile(final String filePath) throws IOException {
int fileIndex = 0;
File extractFile = new File("E://WDMRDB//Wiki//2009-11-5_LeavesNode_" + fileIndex + ".txt");
FileWriter extractFileWriter = new FileWriter(extractFile);
int count=0;
for(String tmp : leavesSet){
count++;
extractFileWriter.write(tmp + "\r\n");
if(count % 10000 == 0){ //每10,000筆就存成新檔,否則檔案太大之後處理擷取網頁JVM會爆掉
extractFileWriter.close();
extractFile = new File("E://WDMRDB//Wiki//2009-11-5_LeavesNode_" + (fileIndex++) + ".txt");
extractFileWriter = new FileWriter(extractFile);
}
}
} | 2 |
public String convertHarga(int harga){ // jadi tar kalo 50000 jadi 50.000 dst...
// harga = 444;
int ribuan[] = new int[10];
int counter=0;
String temphasil="";
while(harga/1000!=0){
ribuan[counter] = harga%1000;
counter++;
//temphasil = temphasil + ribuan+".";
harga = harga /1000; // dicari lagi sisanya
}
//dimasukin ke string
temphasil = harga + ".";
for (int i=counter-1;i>=0;i--){
//udah sisa ratusan
if(i!=0){
if (ribuan[i]==0){//sisa harga 0
temphasil = temphasil + "000"+".";
}else if (ribuan[i]<10){ // sisa harga satuan
temphasil = temphasil + "00"+ribuan[i]+".";
}else if (ribuan[i]<100){ //sisa harga puluhan
temphasil = temphasil +"0"+ ribuan[i]+".";
}else{//sisa harga ratusan
temphasil = temphasil + ribuan[i]+".";
}
}else{
if (ribuan[i]==0){//sisa harga 0
temphasil = temphasil + "000";
}else if (ribuan[i]<10){ // sisa harga satuan
temphasil = temphasil + "00"+ribuan[i];
}else if (ribuan[i]<100){ //sisa harga puluhan
temphasil = temphasil +"0"+ ribuan[i];
}else{//sisa harga ratusan
temphasil = temphasil + ribuan[i];
}
}
}
return temphasil;
} | 9 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SiteBoundaryAttribute)) {
return false;
}
SiteBoundaryAttribute other = (SiteBoundaryAttribute) object;
if ((this.siteBoundaryAttributePK == null && other.siteBoundaryAttributePK != null) || (this.siteBoundaryAttributePK != null && !this.siteBoundaryAttributePK.equals(other.siteBoundaryAttributePK))) {
return false;
}
return true;
} | 5 |
private void setBackgroundColor(int i) {
if (atom == null)
return;
String s = ((AtomisticView) atom.getHostModel().getView()).getColorCoding();
if ("Lego".equals(s)) {
if (AMINO_ACID[i].getCharge() > 0) {
mi[i].setBackground(new Color(ColorManager.LEGO_BASIC_COLOR));
}
else if (AMINO_ACID[i].getCharge() < 0) {
mi[i].setBackground(new Color(ColorManager.LEGO_ACID_COLOR));
}
else {
if (AMINO_ACID[i].getHydrophobicity() > 0) {
mi[i].setBackground(new Color(ColorManager.LEGO_HYDROPHOBIC_COLOR));
}
else {
mi[i].setBackground(new Color(ColorManager.LEGO_UNCHARGED_POLAR_COLOR));
}
}
}
else {
if (AMINO_ACID[i].getCharge() > 0) {
mi[i].setBackground(new Color(ColorManager.POSITIVE_CHARGE_COLOR));
}
else if (AMINO_ACID[i].getCharge() < 0) {
mi[i].setBackground(new Color(ColorManager.NEGATIVE_CHARGE_COLOR));
}
else {
if (AMINO_ACID[i].getHydrophobicity() > 0) {
mi[i].setBackground(new Color(ColorManager.HYDROPHOBIC_COLOR));
}
else {
mi[i].setBackground(new Color(ColorManager.HYDROPHILIC_COLOR));
}
}
}
} | 8 |
public static String getBinaryFloat (float f) {
assert ( 0.0 < f && f < 1.0) : " f in (0.0, 1.0)";
StringBuffer sb = new StringBuffer();
sb.append("0.");
f = f*2;
while ( f > 0 ) {
if ( sb.length() > 32 ) {
return "ERROR";
}
if ( f >= 1) {
sb.append( 1 );
f = ( f - 1 ) * 2;
} else if ( f < 1) {
sb.append( 0 );
f = f * 2;
}
}
return sb.toString();
} | 5 |
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in,
com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException {
super.loadFields(__in, __typeMapper);
__in.peekTag();
if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) {
setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, LastModifiedBy__typeInfo)) {
setLastModifiedBy((com.sforce.soap.enterprise.sobject.User)__typeMapper.readObject(__in, LastModifiedBy__typeInfo, com.sforce.soap.enterprise.sobject.User.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, LastModifiedById__typeInfo)) {
setLastModifiedById(__typeMapper.readString(__in, LastModifiedById__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, LastModifiedDate__typeInfo)) {
setLastModifiedDate((java.util.Calendar)__typeMapper.readObject(__in, LastModifiedDate__typeInfo, java.util.Calendar.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, Opportunity__typeInfo)) {
setOpportunity((com.sforce.soap.enterprise.sobject.Opportunity)__typeMapper.readObject(__in, Opportunity__typeInfo, com.sforce.soap.enterprise.sobject.Opportunity.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, OpportunityAccessLevel__typeInfo)) {
setOpportunityAccessLevel(__typeMapper.readString(__in, OpportunityAccessLevel__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, OpportunityId__typeInfo)) {
setOpportunityId(__typeMapper.readString(__in, OpportunityId__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, RowCause__typeInfo)) {
setRowCause(__typeMapper.readString(__in, RowCause__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, UserOrGroupId__typeInfo)) {
setUserOrGroupId(__typeMapper.readString(__in, UserOrGroupId__typeInfo, java.lang.String.class));
}
} | 9 |
* @param settlement The <code>Settlement</code> that is trading.
*/
private void attemptSellToSettlement(Unit unit, Settlement settlement) {
Goods goods = null;
for (;;) {
// Choose goods to sell
goods = gui.showSimpleChoiceDialog(unit.getTile(),
"sellProposition.text", "sellProposition.nothing",
unit.getGoodsList());
if (goods == null) break; // Trade aborted by the player
int gold = -1; // Initially ask for a price
for (;;) {
gold = askServer().sellProposition(unit, settlement,
goods, gold);
if (gold <= 0) {
showTradeFail(gold, settlement, goods);
return;
}
// Show dialog for sale proposal
switch (gui.showSellDialog(unit, settlement, goods, gold)) {
case CANCEL:
return;
case SELL: // Accepted price, make the sale
if (askServer().sellToSettlement(unit,
settlement, goods, gold)) {
gui.updateMenuBar(); // Assume success
}
return;
case HAGGLE: // Ask for more money
gold = (gold * 11) / 10;
break;
case GIFT: // Decide to make a gift of the goods
askServer().deliverGiftToSettlement(unit,
settlement, goods);
return;
default:
throw new IllegalStateException("showSellDialog fail");
}
}
}
} | 9 |
public Console() {
for(int i = 0; i < COUNT_OF_COMMANDS; i++) {
switch (i) {
case 0: {
COMMANDS_DESCRIPTION[i] = START_GAME_WITH_COMPUTER_COMMAND + " - start game with computer";
break;
}
case 1: {
COMMANDS_DESCRIPTION[i] = START_GAME_WITH_MAN_COMMAND +" - start game with man";
break;
}
case 2: {
COMMANDS_DESCRIPTION[i] = HELP_COMMAND + " - " + USE_HELP;
break;
}
case 3: {
COMMANDS_DESCRIPTION[i] = ABOUT_COMMAND + " - about developer";
break;
}
case 4: {
COMMANDS_DESCRIPTION[i] = EXIT_COMMAND+" - exit from the game";
break;
}
}
}
} | 6 |
private void setHeuristicValue()
{
if(this.map == null || this.heuristic == null)
return;
for(int i = 0; i < this.map.columnsCount(); i++)
{
for(int j = 0; j < this.map.rowsCount(); j++)
{
this.map.getState(i, j).setH(this.heuristic.getHeuricticValue(i, j,
this.map.getGoalState().getX(), this.map.getGoalState().getY()));
}
}
} | 4 |
@Test
public void esteKuuluukoPiste() {
assertTrue("Vasen yläkulma pieleen", e.kuuluukoPiste(p) != null);
p.siirra(10, 0);
assertTrue("Oikea yläkulma pieleen", e.kuuluukoPiste(p) != null);
p.siirra(0, 10);
assertTrue("Oikea alakulma pieleen", e.kuuluukoPiste(p) != null);
p.siirra(-10, 0);
assertTrue("Vasen alakulma pieleen", e.kuuluukoPiste(p) != null);
} | 0 |
@Override
public Map<String, String> getParsedResults() {
if (!resultingMap.isEmpty()) {
return resultingMap;
}
String[] lines = stringBuilder.toString().split("\n");
for (String line : lines) {
line = line.trim();
if (line.startsWith("活动时间:")) {
parseStartAndEndTime(line.substring("活动时间:".length()));
} else if (line.startsWith("活动地址:")) {
resultingMap.put("address", line.substring("活动地址:".length()));
}
}
return resultingMap;
} | 4 |
private void diffOffering(CourseRec oldRec, OffRec oldOff,
HashMap<String, Object> newOff, ArrayList<Change> changes) {
// Start date.
Date newDate = getStartDate(newOff);
if (oldOff.getStart() == null && newDate != null
|| oldOff.getStart() != null
&& !oldOff.getStart().equals(newDate)) {
changes.add(OfferingChange.setStart(oldOff, newDate));
}
// URL. With some clean up.
String newUrl = getCleanUrl(newOff);
if (Change.fieldChanged(newUrl, oldOff.getLink())) {
changes.add(OfferingChange.setLink(oldOff, newUrl));
}
// Active from availability.
Boolean active = getActiveStatus(newOff);
if (oldOff.isActive() != active) {
changes.add(OfferingChange.setActive(oldOff, active));
}
} | 6 |
public void send_TCP_packet(Packet app_pack) throws InterruptedException
{
//faz 3-way-handshake
if (!open_connection(app_pack))
return;
//constrói pacote TCP
Packet packet = build_TCP_packet(app_pack);
if (packet == null)
return;
int ACK = (int)Math.round(Math.random()*1000) + 2; //numero entre 2 e 1001
//mandando pacotes fragmentados
if (packet.getLength() > 1460)
{
int total = packet.get_data().length() / 1460 + 1;
int SEQ = 1;
Packet[] packets = new Packet[total];
for (int i = 0; i < total; i++)
{
Packet p = new Packet("TCP");
packet.clone_to_packet(p);
p.setApplication(null);
TCP transport = new TCP();
p.getTransport().clone_to(transport);
transport.setACK_number(ACK);
transport.setSequence_number(SEQ);
if (i == total-1)
{
transport.setFIN(true);
p.setApplication(app_pack.getApplication());
}
p.setTransport(transport);
p.set_data(packet.get_data());
SEQ = chop_data(p, SEQ);
packets[i] = p;
}
send_with_congestion_control(packets);
}
//mandando apenas um pacote
else
{
TCP transport = (TCP) packet.getTransport();
transport.setACK_number(ACK);
transport.setSequence_number(1);
transport.setFIN(true);
packet.setTransport(transport);
do
{
send_packet(packet);
synchronized (this)
{
wait(100); //timeout
}
}
while(!got_ACK(ACK));
}
} | 6 |
public Juoma haeJuoma(int id) throws DAOPoikkeus {
// luodaan olio johon juoman tiedot tallennetaan
Juoma juoma = new Juoma();
// haetaan hörpyn tiedot tietokannasta
try {
JuomaDAO jDao = new JuomaDAO();
juoma = jDao.haeJuoma(id);
} catch (DAOPoikkeus e) {
throw new DAOPoikkeus("Juoman hakeminen tietokannasta ei onnistunut");
}
return juoma;
} | 1 |
public static boolean canPlayerToggleToChannel( BSPlayer p, Channel channel ) {
if ( channel.isDefault() ) {
if ( p.getServerData().forcingChannel() ) {
String forcedChannel = p.getServerData().getForcedChannel();
if ( channel.getName().equals( forcedChannel ) ) {
return true;
} else {
return false;
}
}
return true;
}
return true;
} | 3 |
@Override
public String toString()
{
final int height = board.length;
final int width = board[ 0 ].length;
final StringBuilder sb = new StringBuilder( height * (width + 1) );
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if ( !traversable[y][x] )
{
sb.append(' ');
}
else if ( board[y][x] )
{
sb.append('X');
}
else
{
sb.append('O');
}
}
sb.append('\n');
}
return sb.toString();
} | 4 |
void print(Node t, int n, boolean p)
{
if (p)
{
printCond(t, n);
}
else
{
if (n > 0)
{
for (int i = 0; i < n; i++)
System.out.print(" ");
}
System.out.println("(cond ");
}
} | 3 |
public boolean isSyncCurrentPosition(int syncmode) throws BitstreamException
{
int read = readBytes(syncbuf, 0, 4);
int headerstring = ((syncbuf[0] << 24) & 0xFF000000) | ((syncbuf[1] << 16) & 0x00FF0000) | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF);
try
{
source.unread(syncbuf, 0, read);
}
catch (IOException ex)
{
}
boolean sync = false;
switch (read)
{
case 0:
sync = true;
break;
case 4:
sync = isSyncMark(headerstring, syncmode, syncword);
break;
}
return sync;
} | 3 |
void verifikasiBtnHapus(){
if(textSaldoA.getText().isEmpty() && textSaldoB.getText().isEmpty() && textOmset.getText().isEmpty()){
buttonHapus.setEnabled(false);
}
if(textSaldoA.getText().isEmpty() || textSaldoB.getText().isEmpty() || textOmset.getText().isEmpty()){
buttonHapus.setEnabled(true);
}
} | 6 |
public final void metodos() throws RecognitionException {
try {
// fontes/g/CanecaSemantico.g:236:2: ( ^( METODOS_ ( metodo )* ) )
// fontes/g/CanecaSemantico.g:236:4: ^( METODOS_ ( metodo )* )
{
match(input,METODOS_,FOLLOW_METODOS__in_metodos726); if (state.failed) return ;
if ( input.LA(1)==Token.DOWN ) {
match(input, Token.DOWN, null); if (state.failed) return ;
// fontes/g/CanecaSemantico.g:236:15: ( metodo )*
loop10:
do {
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0==METODO_) ) {
alt10=1;
}
switch (alt10) {
case 1 :
// fontes/g/CanecaSemantico.g:236:16: metodo
{
pushFollow(FOLLOW_metodo_in_metodos729);
metodo();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop10;
}
} while (true);
match(input, Token.UP, null); if (state.failed) return ;
}
}
}
catch (RecognitionException erro) {
throw erro;
}
finally {
// do for sure before leaving
}
return ;
} | 9 |
public static AbstractFactory getFactory(int factoryTag) {
switch(factoryTag) {
case 1: return new ConcreteFactory1();
case 2: return new ConcreteFactory2();
}
return null;
} | 2 |
public void mouseMoved(MouseEvent event) {
adapter.mouseMoved(event);
} | 0 |
public Credentials(String loc) throws IOException {
try {
stream = new FileInputStream(loc);
reader = new BufferedReader(new InputStreamReader(stream,
Charset.forName("UTF-8")));
} catch (FileNotFoundException e) {
System.out.println("File does not exist.");
return;
}
String[] lns = new String[2];
for (int i=0; i<2; lns[i]=reader.readLine(), ++i);
// validate our file
if (lns[0] == null || !Pattern.matches(ckRegex, lns[0])
|| lns[1] == null || !Pattern.matches(atRegex, lns[1])) {
System.out.println(lns[0]);
return;
}
secretConsumerKey = (lns[0]=lns[0].substring(17,lns[0].length()));
secretAccessToken = (lns[1]=lns[1].substring(21,lns[1].length()));
} | 6 |
public Effect(final String name, final int duration, final int delay) {
if (name == null) {
this.theName = "";
}
else {
this.theName = name;
}
if (duration < 0 && duration != Effect.PERMANENT_DURATION) {
this.theDuration = 0;
}
else {
this.theDuration = duration;
}
if (delay < 0) {
this.tickDelay = 0;
}
else {
this.tickDelay = delay;
}
} | 4 |
public static void main(String[] args){
ArrayList<Long> primes = new ArrayList<Long>();
long f = 600851475143L;
long i = 0;
do {
i = factorOf(f);
if(f % i == 0 && !primes.contains(i)){
primes.add(i);
f = f / i;
}
} while(i != f);
primes.add(f);
long largest = 0;
for(long p : primes){
if(p > largest){
largest = p;
}
}
System.out.println(largest);
} | 5 |
@Override
public void menu() {
out.println();
out.println("[1] Buscar");
out.println("[2] Cadastrar");
out.println("[3] Listar Todos");
out.println("[0] Sair");
switch(sc.nextInt()){
case 1: buscarPacientes(); break;
case 2: cadastraPaciente(); break;
case 3: mostraPacienteLista(); break;
case 0: return;
default: out.println("Opcao invalida"); break;
}
menu();
} | 4 |
public static int readIntValue() {
boolean isCorrectValue = false;
Scanner console = new Scanner(System.in);
int readValue = 0;
do {
if (console.hasNextInt()) {
readValue = console.nextInt();
isCorrectValue = true;
} else {
System.out.print("Please, enter integer value: ");
console.next();
}
} while (!(isCorrectValue));
return readValue;
} | 2 |
public boolean checkIntegrity() {
boolean ok = true;
for (AIObject ao : aiObjects.values()) {
if (!ao.checkIntegrity()) {
logger.warning("Invalid AIObject: " + ao.getId()
+ " (" + ao.getClass() + ")");
ok = false;
}
}
Iterator<FreeColGameObject> fit
= getGame().getFreeColGameObjectIterator();
while (fit.hasNext()) {
FreeColGameObject f = fit.next();
if ((f instanceof Unit
|| f instanceof Colony
|| (f instanceof Player && !((Player)f).isUnknownEnemy()))
&& !aiObjects.containsKey(f.getId())) {
logger.warning("Missing AIObject for: " + f.getId());
ok = false;
}
}
return ok;
} | 8 |
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
String key = button.getText();
Boolean command = StringUtils.indexOf("0123456789.",key) < 0;
if(!command){
if((number + key).matches("[0-9]*|[0-9]+.[0-9]*")){
if(number.equals("0") && StringUtils.isNumeric(key))
number = "";
number += key;
model.setValue(number);
}
}else{
switch (key){
case "C":
model.reset();
number = "0";
break;
case "=":
try {
model.doOperation();
number = "0";
} catch (ArithmeticException ex){
JOptionPane.showMessageDialog(view, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
break;
default:
if(model.testOperation()){
try {
model.doOperation();
} catch (ArithmeticException ex){
JOptionPane.showMessageDialog(view, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
model.reset();
}
}
model.pushOperation(key);
number = "0";
break;
}
}
view.setDisplay(model.getValue());
} | 9 |
public scoreboard() throws IOException{
super("A Hole in the Universe");
setSize(950,650);
setLocationRelativeTo(null);
//retrieves all player info
//format: "GET_PLAYER_INFO username character ready score comets deaths powerups max_spin max_vel"
allPlayerInfoP1 = Client.sendMsg(msg);
//splits all player info by whitespace into array
//format: [GET_PLAYER_INFO, username, character, ready, score, comets, deaths, powerups, max_spin, max_vel]
array1 = allPlayerInfoP1.split("\\s+");
System.out.println(allPlayerInfoP1);
//assign all values in the array to their respective score board values
usernames.add(array1[1]);
characters.add(array1[2]);
damages.add(array1[4]);
comets.add(array1[5]);
deaths.add(array1[6]);
powerups.add(array1[7]);
maxvels.add(array1[9]);
Scanner uScan;
//Get the index of the active game that the current player is in:
msg = Client.sendMsg("GET_PLAYER_GAME_INDEX");
while(msg.equals("GET_PLAYER_GAME_INDEX FAILURE")){
msg = Client.sendMsg("GET_PLAYER_GAME_INDEX");
System.out.println("GET_PLAYER_GAME_INDEX FAILURE");
continue;
}
uScan = new Scanner(msg);
uScan.next();
int nGameIndex = Integer.parseInt(uScan.next());
uScan.close();
// update enemy score
msg = Client.sendMsg("GET_PLAYER_INDEX " + nGameIndex);
while(msg.equals("GET_PLAYER_INDEX FAILURE")){
msg = Client.sendMsg("GET_PLAYER_INDEX " + nGameIndex);
System.out.println("GET_PLAYER_INDEX FAILURE");
continue;
}
uScan = new Scanner(msg);
uScan.next();
int nPlayerIndex = Integer.parseInt(uScan.next());
uScan.close();
//Get the number of players
msg = Client.sendMsg("GET_GAME_HISTORY_NUM_PLAYERS " + nGameIndex);
while(msg.equals("GET_GAME_HISTORY_NUM_PLAYERS FAILURE")){
msg = Client.sendMsg("GET_GAME_HISTORY_NUM_PLAYERS " + nGameIndex);
System.out.println("GET_GAME_HISTORY_NUM_PLAYERS FAILURE");
continue;
}
uScan = new Scanner(msg);
uScan.next();
int numPlayers = Integer.parseInt(uScan.next());
uScan.close();
for(int i=0; i<numPlayers; i++){
if(i != nPlayerIndex){
msg = Client.sendMsg("GET_GAME_HISTORY_PLAYER " + nGameIndex + " " + i);
System.out.println(i+ "th player : "+ msg);
while(msg.equals("GET_GAME_HISTORY_PLAYER FAILURE")){
msg = Client.sendMsg("GET_GAME_HISTORY_PLAYER " + nGameIndex + " " + i);
System.out.println("GET_GAME_HISTORY_PLAYER FAILURE");
continue;
}
array2 = msg.split("\\s+");
//Parse the message returned to get the score from the player info:
//username, character, bReady, nScore, nComets, nDeaths, nPowerUps, nMaxSpin, nMaxVel
usernames.add(array2[1]);
characters.add(array2[2]);
damages.add(array2[4]);
comets.add(array2[5]);
deaths.add(array2[6]);
powerups.add(array2[7]);
maxvels.add(array2[9]);
}
}
setTitle("A Hole in the Universe");
setSize(950,650);
setLocationRelativeTo(null);
//add instance of ImagePanel, which takes the name of an image as input to construct a background image.
//This class is also overriden by the paintComponent method to draw the table and title, and adds the
//Quit and Home JButtons.
add(new ImagePanel("Icons/space.jpg", this));
//Example code for vectors:
/*
rowData[][] = new String[vector.size()][10];
for(int i=0; i<vector.size; i++){
rowData[i][0] = scores.get(i);
rowData[i][1] = usernames.get(i);
rowData[i][2] = vector1.get(i);
}
*/
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
} | 6 |
public void run() {
try {
ObjectOutputStream outStream = new ObjectOutputStream(
new BufferedOutputStream(clientSocket.getOutputStream()));
//Game game = Game.getInstance();
while (true) {
Data data = dataQueue.take();
outStream.writeObject(data);
outStream.flush();
}
//System.out.println("Перед циклом");
/*
while (true) {
Iterator it = game.areas.entrySet().iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
GameArea area = (GameArea) m.getValue();
Iterator objIt = area.areaObjects.entrySet().iterator();
while (objIt.hasNext()) {
Map.Entry m2 = (Map.Entry) objIt.next();
AreaObject object = (AreaObject) m2.getValue();
ObjectData dataObj = new ObjectData();
dataObj.pos.setX(object.pos.getX());
dataObj.pos.setY(object.pos.getY());
dataObj.objectId = object.objectId;
outStream.write(dataObj.getBytes());
outStream.flush();
}
}
* */
} catch (Exception ex) {
System.out.println("Ошибка при сборе данных" + ex);
}
} | 2 |
public List<City> getCities() {
List<City> list = new ArrayList<>();
Connection con = null;
Statement stmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * From city order by cty_code");
while (rs.next()) {
City cit = new City();
cit.setId(rs.getInt(1));
cit.setShortName(rs.getString(2));
cit.setName(rs.getString(3));
cit.setprovince(rs.getInt(4));
list.add(cit);
}
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
return list;
} | 5 |
public void putAll( Map<? extends K, ? extends Long> map ) {
Iterator<? extends Entry<? extends K,? extends Long>> it = map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends K,? extends Long> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} | 8 |
private void flushAndCloseOutputStream(OutputStream stream) {
if (stream == null) {
return;
}
try {
stream.flush();
} catch (IOException ex) {
System.out.println(ex);
}
closeStream(stream);
} | 2 |
public boolean isValid(int x, int y)
{
//determines whether a particular location is a valid location to put someone/something
if(x > -1 && x < width && y > -1 && y < height)
{
if(theMap[x][y].getType() != 0)
{
return false;
}
else
{
return true;
}
}
return false;
} | 5 |
private void writeObject(ObjectOutputStream out) throws IOException {
purgeThread.interrupt();
processQueue();
HashMap<Object, Object> wcache = new HashMap<Object, Object>();
Iterator<String> it = map.keySet().iterator();
Object key = null;
Object value = null;
while(it.hasNext()) {
key = it.next();
SoftReference ref = (SoftReference) map.get(key);
if(ref == null) continue;
value = ref.get();
if(value!=null) {
wcache.put(key, value);
} else {
mapTtl.remove(key);
while(true) {
if(hardCache.remove(key)==false) {
break;
}
}
}
}
out.writeObject(wcache);
out.writeObject(mapTtl);
out.writeObject(hardCache);
} | 5 |
public boolean neljaSamaa(){
for(int i=0; i<2; i++){
if(nopat[i].getValue()==nopat[i+3].getValue()){
return true;
}
}
return false;
} | 2 |
public boolean checkifHasOwner(String uuid){
ArrayList<String> allAnimals = new ArrayList<String>();
if(!plugin.getAnimalData().contains("Farmer")){
return false;
}else{
Set<String> farmers = plugin.getAnimalData().getConfigurationSection("Farmer").getKeys(false);
//getting the farmers animals
for(String farmer : farmers){
if(plugin.getAnimalData().get("Farmer." + farmer + ".Animals") == null){
break;
}
Set<String> t = plugin.getAnimalData().getConfigurationSection("Farmer." + farmer + ".Animals").getKeys(false);
for(String FarmAnimals : t){
allAnimals.add(FarmAnimals);
}
}
if(allAnimals.contains(uuid)){
return true;
}else{
return false;
}
}
} | 5 |
public String[] whichPages(String word) {
word = word.toLowerCase();
ArrayList<String> pages = new ArrayList<String>();
for(Term term: termIndex){
if (term.getName().equals(word)){
for(Occurrence occ: term.getDocsList()){
pages.add(occ.getDocName());
}
}
}
return pages.toArray(new String[pages.size()]);
} | 3 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null && line.length() != 0) {
int[] v = readInts(line.trim());
if (v[0] == 0 && v[1] == 0 && v[2] == 0)
break;
boolean right = false;
for (int i = 0; i < p.length && !right; i++)
right |= s(v[p[i][0]]) == s(v[p[i][1]]) + s(v[p[i][2]]);
if (right)
out.append("right\n");
else
out.append("wrong\n");
}
System.out.print(out);
} | 8 |
public static String createWhoIsOnlineMessage(String myName) {
JSONObject jsonMsg = new JSONObject()
.element( "code", "1" )
.element( "name", myName )
;
return jsonMsg.toString();
} | 0 |
private void makeInputItems() {
boolean first = true;
for (Connector c : element.getConnectors()) {
if (c instanceof InputConnector) {
InputConnector ic = (InputConnector) c;
if (ic.isConnected()) {
if (first) {
first = false;
add(new JPopupMenu.Separator());
}
ComponentMenuItem item = new ComponentMenuItem(
"disconnect (" + ic.getName() + ") from "
+ ic.getSource(), ic);
add(item);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
InputConnector ic = (InputConnector) ((ComponentMenuItem) e
.getSource()).getConnector();
ic.disconnect();
setVisible(false);
panel.repaint();
}
});
}
}
}
} | 4 |
public int findIndex(char ch)
{
if(Character.getNumericValue(ch)==1) {return 0;}
if(Character.getNumericValue(ch)==2) {return 1;}
if(Character.getNumericValue(ch)==3) {return 2;}
if(Character.getNumericValue(ch)==4) {return 3;}
if(Character.getNumericValue(ch)==5) {return 4;}
if(Character.getNumericValue(ch)==6) {return 5;}
if(Character.getNumericValue(ch)==7) {return 6;}
if(Character.getNumericValue(ch)==8) {return 7;}
return -1;
} | 8 |
private boolean check(FlowNetwork G, int s, int t) {
// check that flow is feasible
if (!isFeasible(G, s, t)) {
System.err.println("Flow is infeasible");
return false;
}
// check that s is on the source side of min cut and that t is not on source side
if (!inCut(s)) {
System.err.println("source " + s + " is not on source side of min cut");
return false;
}
if (inCut(t)) {
System.err.println("sink " + t + " is on source side of min cut");
return false;
}
// check that value of min cut = value of max flow
double mincutValue = 0.0;
for (int v = 0; v < G.V(); v++) {
for (FlowEdge e : G.adj(v)) {
if ((v == e.from()) && inCut(e.from()) && !inCut(e.to()))
mincutValue += e.capacity();
}
}
double EPSILON = 1E-11;
if (Math.abs(mincutValue - value) > EPSILON) {
System.err.println("Max flow value = " + value + ", min cut value = " + mincutValue);
return false;
}
return true;
} | 9 |
public static void testFillTable() throws DatabaseException {
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
Random randomGenerator = new Random();
int uid, i;
String q = "INSERT INTO test(uid,bid,auctionID) VALUES(?,1,17)";
try {
conn = DBPool.getInstance().getConnection();
ps = conn.prepareStatement( q );
for ( i = 1; i < 100000; i++ ) {
uid = randomGenerator.nextInt( 1000 ) + 1;
ps.setInt( 1, uid );
ps.executeUpdate();
}
}
catch ( SQLException e ) {
System.out.println( "bridge " + e.toString() + e.getStackTrace() );
throw new DatabaseException( e.toString() );
}
finally {
try { if (rs != null) rs.close(); } catch(Exception e) { }
try { if (ps != null) ps.close(); } catch(Exception e) { }
try { if (conn != null) conn.close(); } catch(Exception e) { }
}
} | 8 |
public void load(String pedFileName) {
String pedBaseFileName = Gpr.removeExt(pedFileName);
String mapFile = pedBaseFileName + ".map";
PedFileIterator pedFile = new PedFileIterator(pedFileName, mapFile);
// Load all entries for this family
int count = 1;
for (PedEntry pe : pedFile) {
if (verbose) Gpr.showMarkStderr(count++, 1);
add(pe);
}
plinkMap = pedFile.getPlinkMap();
} | 2 |
protected Value runBlock(Block body, CodeBlock i) throws InterpreterException{
Block b = body;
Value last = null;
while (b != null && !__end && !__return) {
last = b.run(i);
if (b instanceof ReturnBlock) {
__return = true;
System.out.println("RETURN!");
} else
b = b.next();
}
return last;
} | 4 |
public int getWarnings(Account account){ return account.getWarnings(); } | 0 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
Physical target=mob;
if((auto)&&(givenTarget!=null))
target=givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(mob,target,null,L("<T-NAME> <T-IS-ARE> already affected by @x1.",name()));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> become(s) sanctimonious."):L("^S<S-NAME> @x1 for sanctimoniousness.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,null,L("<S-NAME> @x1 for sanctimoniousness, but there is no answer.",prayWord(mob)));
// return whether it worked
return success;
} | 7 |
public boolean initialize() {
CommPortIdentifier portID = null;
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
System.out.println("Trying ports:");
while(portID == null && ports.hasMoreElements()) {
CommPortIdentifier testPort = (CommPortIdentifier) ports.nextElement();
System.out.println(" " + testPort.getName());
if(testPort.getName().startsWith(portName)) {
try {
serialPort = (SerialPort) testPort.open(programName, 1000);
portID = testPort;
System.out.println("Connected on " + portID.getName());
break;
} catch(PortInUseException e){
System.out.println(e);
}
}
}
if(portID == null || serialPort == null) {
System.out.println("Could not connect to Arduino!");
return false;
}
try {
serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
Thread.sleep(2000);
return true;
} catch(Exception e) { System.out.println(e); }
return false;
} | 7 |
void doMovement(){
if(hitsObstacle(me())){
dead=true;
}
double currentSpeed=walkSpeed;
if(Display.left)xVel-=currentSpeed;
if(Display.right)xVel+=currentSpeed;
if(hitsObstacle(me(0,1))){
if(Display.up)yVel-=jumpHeight;
}else{
yVel+=2;
}
xVel*=walkDelay;
yVel*=gravity;
double uvx = xVel/precision;
double uvy = yVel/precision;
for(int i=0;i<=precision;i++){
if(!hitsObstacle(me(uvx,0))){
loc.setLocation(loc.getX()+uvx,loc.getY());
}else{
xVel=0;
}
if(!hitsObstacle(me(0,uvy))){
loc.setLocation(loc.getX(),loc.getY()+uvy);
}else{
yVel=0;
}
}
} | 8 |
public int compare(Object arg1, Object arg2)
{
Segment A = (Segment) arg1;
Segment B = (Segment) arg2;
Point Agauche = (A.a.x > A.b.x) ? A.b : A.a;
Point Adroite = (A.a.x > A.b.x) ? A.a : A.b;
Point Bgauche = (B.a.x > B.b.x) ? B.b : B.a;
Point Bdroite = (B.a.x > B.b.x) ? B.a : B.b;
if (Agauche.y < Bgauche.y) return 1;
else if (Agauche.y == Bgauche.y)
{
if (Adroite.y < Bdroite.y) return 1;
else if (Adroite.y == Bdroite.y) return 0;
}
return -1;
} | 8 |
private static String dozensContains( Map recordMap, String host, String ip )
{
if( !recordMap.containsKey( "record" ) )
{
return null;
}
List recordList = ( List )recordMap.get( "record" );
for( int i = 0; i < recordList.size(); ++i )
{
Map record = ( Map )recordList.get( i );
if( record.containsKey( "type" ) && record.get( "type" ).equals( "A" )
&& record.containsKey( "name" ) && record.get( "name" ).equals( host )
&& record.containsKey( "content" ) && record.get( "content" ).equals( ip )
)
{
return ( String )record.get( "id" );
}
}
return null;
} | 8 |
private void addHour(List<QlockWord> timeList, final int HOUR) {
if (HOUR == 12) {
timeList.add(QlockLanguage.EINS);
} else {
if (HOUR + 1 == 5) {
timeList.add(QlockLanguage.FÜNF2);
} else if (HOUR + 1 == 10) {
timeList.add(QlockLanguage.ZEHN1);
} else if (HOUR + 1 == 3) {
timeList.add(QlockLanguage.DREI1);
} else {
timeList.add(QlockLanguage.valueOf(LOOKUP.get(HOUR + 1)));
}
}
} | 4 |
public boolean suorita(String s) {
this.s = s;
ArrayList<String> edelliset = new ArrayList<String>();
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (grid[i][j].equals(Character.toString(s.charAt(0)))) {
//tN = tarkistaNaapurit
if (tarkistaNaapuri(i, j, 0, edelliset)) {
return true;
}
}
}
}
return false;
} | 4 |
public static void main(String[] arg) {
//this program determines whether user inputted horizontal and vertical line intersect in the x-y plane
double Hy, Hxl, Hxr, Vx, Vyt, Vyb;
boolean validVertical = false;
Scanner input = new Scanner(System.in);
for (;;){
System.out.print("Please enter the horizontal segment's coordinates (y-value, left x-value, right x-value or 0 0 0 to exit): ");
Hy = input.nextDouble();
Hxl = input.nextDouble();
Hxr = input.nextDouble();
if (Hy == 0 && Hxl == 0 && Hxr == 0) {
//terminal values
break;
} else if (Hxl > Hxr) {
//enforcing that the left and right values are entered in the correct order
System.out.println("The horizontal values entered are not valid.");
} else {
//if the horizontal values are valid, then get the vertical values
while (!validVertical) {
System.out.print("Please enter the vertical segment's coordinates (x-value, bottom y-value, top y-value: ");
Vx = input.nextDouble();
Vyb = input.nextDouble();
Vyt = input.nextDouble();
if (Vyb > Vyt) {
//similar to the horizontal values, if the vertical values are not entered in
//in the correct order, throw an error message
System.out.println("The vertical values entered are not valid.");
} else {
//if the vertical values are valid, pass the values to the check_intersect method
//and flag the boolean as true to loop back to the beginning of the program
validVertical = true;
check_intersect(Hy, Hxl, Hxr, Vx, Vyt, Vyb);
}
}
}
validVertical = false; //at the end, reset the boolean as false
}
input.close();
} | 7 |
public boolean checkBox(int row, int col)
{
int i = 0, j = 0, k = 0, count = 0;
for(k = 1; k < 10; k++)
{
for(i = row; i < row+3; i++)
{
for(j = col; j < col+3; j++)
{
count = 0;
if(k == Integer.parseInt(entries[i][j].getText()) )
{
count++;
}
if(count >= 2)
{
System.out.println("checkBox() returned false at i: " + i + " j: "+ j + " with " + entries[i][j].getText());
return false;
}
}
}
}
return true;
} | 5 |
public void discover() {
InetAddress pingAddr;
System.out.println("Attempting to resolve gateway...");
try {
pingAddr = InetAddress.getByName("www.google.com");
this.ARPListener.setFilter("tcp and dst host "+pingAddr.getHostAddress(),true);
this.ARPListener.getListener().setPacketReadTimeout(5000);
this.ARPListener.start();
while(true){
try {
new URL("http://www.google.com").openStream().close();
}catch (Exception e){
e.printStackTrace();
}
if(gatewaymac != null)
break;
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
//Thread.currentThread();
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
this.ARPListener.setFilter("arp", true);
for (String ipaddr : this.iplist) {
arp packet = new arp(device);
try {
//Thread.currentThread();
Thread.sleep(this.sleepy);
ARPPacket pack = packet.build_request_packet(ipaddr);
System.out.printf("\rInterrogating "+ipaddr);
this.ARPSender.send(pack);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println();
System.out.println("Hosts Found: "+ip_mac_list.size());
System.out.println(ip_mac_list.keySet().toString()+"\n");
if(gatewayip == null){
System.out.println("ERROR: No gateway found, try again later..");
System.exit(1);
}
//stop the thread listening to ARP PACKETS
this.ARPListener.finish();
} | 9 |
@Override
public boolean sendDeath() {
WorldTasksManager.schedule(new WorldTask() {
int loop;
@Override
public void run() {
if (loop == 0) {
player.setNextAnimation(new Animation(836));
} else if (loop == 1) {
player.getPackets().sendGameMessage(
"Oh dear, you have died.");
} else if (loop == 3) {
int weaponId = player.getEquipment().getWeaponId();
if (weaponId == 4037 || weaponId == 4039) {
CastleWars.setWeapon(player, null);
CastleWars.dropFlag(player,
weaponId == 4037 ? CastleWars.SARADOMIN
: CastleWars.ZAMORAK);
} else {
Player killer = player
.getMostDamageReceivedSourcePlayer();
if (killer != null)
killer.increaseKillCount(player);
}
player.reset();
player.setNextWorldTile(new WorldTile(
team == CastleWars.ZAMORAK ? CastleWars.ZAMO_BASE
: CastleWars.SARA_BASE, 1));
player.setNextAnimation(new Animation(-1));
} else if (loop == 4) {
player.getPackets().sendMusicEffect(90);
stop();
}
loop++;
}
}, 0, 1);
return false;
} | 9 |
@Test
public void shouldThrowErrorWhenBoardDimensionsWrong() throws IOException {
//given
File tmpFile = folder.newFile(FILENAME);
FileOutputStream fileOutputStream = new FileOutputStream(tmpFile, true);
CharsetEncoder charsetEncoder = Charset.forName(ENCODING).newEncoder();
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, charsetEncoder);
try {
writer.getEncoding();
writer.write("01");
writer.write(System.getProperty(LINESEPARATOR));
writer.write("010");
writer.flush();
} finally {
writer.close();
}
String filePathString = tmpFile.getAbsolutePath();
//when
try {
FileParser fileParser = new FileParser(filePathString);
fileParser.parse();
} catch (GOLException e) {
//then
String msg = "Das Spielbrett muss in jeder Zeile gleich viele Zellen haben.";
assertEquals(msg, e.getMessage());
}
} | 1 |
void simple2 (){
int counter = 0;
for (int i = 3; ; i++) {
for (int j = 2; j < i; j++) {
if (i % j != 0) {
if (j == i - 1) {
counter += 1;
System.out.print(i + " ");
}
} else {
break;
}
}
if (counter == 10) {
break;
}
}
} | 5 |
public static boolean placeRailAt(ItemStack stack, World world, int i, int j, int k) {
if (stack == null)
return false;
if (stack.getItem() instanceof ITrackItem)
return ((ITrackItem) stack.getItem()).placeTrack(stack.copy(), world, i, j, k);
if (stack.getItem() instanceof ItemBlock) {
Block block = ((ItemBlock) stack.getItem()).field_150939_a;
if (BlockRailBase.func_150051_a(block)) {
boolean success = world.setBlock(i, j, k, block);
if (success)
world.playSoundEffect((float) i + 0.5F, (float) j + 0.5F, (float) k + 0.5F, block.stepSound.func_150496_b(), (block.stepSound.getVolume() + 1.0F) / 2.0F, block.stepSound.getPitch() * 0.8F);
return success;
}
}
return false;
} | 5 |
public static void majority(Integer[] v) {
int median = getNthValue(v, 0, v.length - 1, v.length / 2);
int majorityCount = 0;
for (Integer value : v) {
if(value == median) majorityCount++;
}
if(majorityCount > v.length / 2) {
System.out.println(median);
} else {
System.out.println("None");
}
} | 3 |
public String createEdgeLabel(String vertex1, String vertex2) {
if(vertex1.substring(1).equals(vertex2.substring(0, vertex2.length()-1))){
String suffix="";
if(containsEdge(findEdge(vertex1,vertex2))){
Collection<String> fromV1 = getOutEdges(vertex1);
Collection<String> intoV2 = getInEdges(vertex2);
int nextNo=1;
for(String fv1:fromV1){
if(intoV2.contains(fv1)){
++nextNo;
}
}
suffix="("+nextNo+")";
}
if(vertex1.length()>vertex2.length()){
return vertex1+vertex2.substring(vertex2.length()-1, vertex2.length())+suffix;
}else{
return vertex1.substring(0,1)+vertex2+suffix;
}
}else{
return null;
}
} | 5 |
public boolean getSelectionOnly() {
return this.selectionOnly;
} | 0 |
private BufferedImage chooseImage(String title, String text,
boolean sameSize) {
List<String> imagens = getImageNames(sameSize);
imagens.remove(getSelectedFrame().getTitle());
if (imagens.size() == 0)
return null;
String imgName = (String) JOptionPane.showInputDialog(MainFrame.this,
text, title, JOptionPane.QUESTION_MESSAGE, null,
imagens.toArray(), imagens.get(0));
if (imgName == null)
return null;
BufferedImage img = null;
for (JInternalFrame frame : getDskCenter().getAllFrames())
if (frame instanceof ImagemIFrame
&& frame.getTitle().equals(imgName))
img = ((ImagemIFrame) frame).getImage();
return img;
} | 5 |
private CommucObj handleDoResEntropySlave(CommucObj cObj){
//TODO: understand what this function does and fix it for multiple strands
long startTime = System.currentTimeMillis();
//Set nonprotein strands as not present
for(int i=0; i<cObj.strandPresent.length;i++){
boolean isProtein = (new Boolean((String)cObj.params.getValue("STRANDAA"+i))).booleanValue();
if(!isProtein){
cObj.strandPresent[i] = false;
}
}
//Setup the molecule system
Molecule m = new Molecule();
//BAD CODE setupMolSystem(m,cObj.params,false,null); //the ligand is not used here
m = setupMolSystem(m,cObj.params,cObj.strandPresent,cObj.strandLimits, false);
if (cObj.compASdist){ //AS-AS distance computation
cObj.asDist = getProxAS(m,cObj.mutationNumber,cObj.dist,cObj.asDist);
cObj.compEE = new SamplingEEntries[0];
}
else { //AS-AS or INTRA energy computation
int numMutable = cObj.mutableSpots;
int resMut[] = new int[numMutable];
int strandMut[][] = new int[cObj.strandMut.length][];
for(int str=0;str<cObj.strandMut.length;str++)
strandMut[str] = new int[cObj.strandMut[str].length];
boolean shellRun = false; boolean ligPresent = false; boolean intraRun = false; boolean templateOnly = false;
if (cObj.flagMutType.compareTo("AS-AS")==0){ //AS-AS run
for (int i=0; i<cObj.mutableSpots; i++)
resMut[i] = 1;
m = getASASMolEntropy(m,cObj.strandMut[0]);
strandMut[0][0] = 0;
strandMut[0][1] = 1;
}
else if (cObj.flagMutType.compareTo("INTRA")==0){
intraRun = true;
m = getASASMolEntropy(m,cObj.strandMut[0]);
strandMut = new int[1][1];
strandMut[0][0] = 0;
resMut = new int[1];
resMut[0] = 1;
}
else {
System.out.println("ERROR: only AS-AS and INTRA runs allowed for the pairwise entropy matrix precomputation.");
System.exit(1);
}
//KER: there will only be one strand with the remade molecule
int strandsPresent = 1;
RotamerSearch rs = new RotamerSearch(m, cObj.mutableSpots, strandsPresent, hElect, hVDW, hSteric, true,
true, cObj.epsilon, cObj.stericThresh, cObj.softStericThresh, cObj.distDepDielect,
cObj.dielectConst, cObj.doDihedE,cObj.doSolvationE,cObj.solvScale,cObj.vdwMult, grl,
false, null, false, false, false, new EPICSettings());
for(int j=0; j<cObj.mutableSpots; j++) {
for(int q=0;q<rs.strandRot[0].rl.getAAtypesAllowed().length;q++)
rs.setAllowable(strandMut[0][j],rs.strandRot[0].rl.getAAtypesAllowed()[q],0);
}
//initialize the pairwise energy matrices (partial initialization - only for the residues involved in this computation, e.g., AS-AS)
PairwiseEnergyMatrix minEmatrix = new PairwiseEnergyMatrix(numMutable,resMut,strandMut,rs,shellRun,intraRun,false);
PairwiseEnergyMatrix maxEmatrix = minEmatrix.copy();
rs.simplePairwiseMutationAllRotamerSearch(strandMut,numMutable,cObj.doMinimization,shellRun,intraRun,
resMut,minEmatrix,maxEmatrix,cObj.minimizeBB,cObj.doBackrubs,templateOnly,cObj.backrubFile, false, cObj.strandDefault, false);
long stopTime = System.currentTimeMillis();
cObj.elapsedTime = Math.round((stopTime - startTime) / 1000.0f);
//Store the information in less space to allow the master node to buffer several cObj at once
cObj.compEE = minEmatrix.generateCompEE(maxEmatrix);
}
return cObj;
} | 9 |
public core.render.Texture getTexture(String resourceName,
int target,
int dstPixelFormat,
int minFilter,
int magFilter) throws IOException
{
int srcPixelFormat = 0;
// create the texture ID for this texture
int textureID = createTextureID();
core.render.Texture texture = new core.render.Texture(target,textureID);
// bind this texture
GL11.glBindTexture(target, textureID);
BufferedImage bufferedImage = loadImage(resourceName);
texture.setWidth(bufferedImage.getWidth());
texture.setHeight(bufferedImage.getHeight());
if (bufferedImage.getColorModel().hasAlpha()) {
srcPixelFormat = GL11.GL_RGBA;
} else {
srcPixelFormat = GL11.GL_RGB;
}
// convert that image into a byte buffer of texture data
ByteBuffer textureBuffer = convertImageData(bufferedImage,texture);
if (target == GL11.GL_TEXTURE_2D)
{
GL11.glTexParameteri(target, GL11.GL_TEXTURE_MIN_FILTER, minFilter);
GL11.glTexParameteri(target, GL11.GL_TEXTURE_MAG_FILTER, magFilter);
}
// produce a texture from the byte buffer
GL11.glTexImage2D(target,
0,
dstPixelFormat,
get2Fold(bufferedImage.getWidth()),
get2Fold(bufferedImage.getHeight()),
0,
srcPixelFormat,
GL11.GL_UNSIGNED_BYTE,
textureBuffer );
return texture;
} | 2 |
public static RunPhylipOutput consenseRootedTrees(String query, String consensusType)
{
GetAbsolutePath pt = new GetAbsolutePath();
String absolutePath = pt.getPath();
Runtime rt = Runtime.getRuntime();
String output = "";
String status = "Job Successfully Submitted";
RunPhylipOutput out = new RunPhylipOutput();
if (query.equals(""))
{
out.jobId = output;
status = "Job not Submitted: Query Cannot be Null";
out.status = status;
return out;
}
try
{
//Create a new Directory for Current request in tmp folder
String dirName = "PhylipConsense:" + UUID.randomUUID().toString();
String dirNamePath = absolutePath + dirName;
boolean success = (new File(dirNamePath)).mkdir();
if (success)
{
System.out.println("Directory: " + dirNamePath + " created");
}
FileWriter f = new FileWriter(dirNamePath + "/query.txt");
BufferedWriter w = new BufferedWriter(f);
w.write(query);
w.close();
//Create .sh file in the newly created Dir
String partCode = "";
if (consensusType.equalsIgnoreCase("MRe"))
{
partCode = "R\nY\n";
} else if (consensusType.equalsIgnoreCase("Strict"))
{
partCode = "C\nR\nY\n";
} else if (consensusType.equalsIgnoreCase("MR"))
{
partCode = "C\nC\nR\nY\n";
} else if (consensusType.equalsIgnoreCase("Ml"))
{
partCode = "C\nC\nC\nR\nY\n0.5\n";
} else
{
status = "consensusType takes only following values:\n"
+ "MRe : Majority rule (extended)\n, strict,\n MR : Majority rule,\n Ml";
}
String code = "#!/bin/bash\n"
+ "cd " + dirNamePath + "\n"
+ "phylip consense <<EOD\n"
+ "query.txt\n"
+ partCode
+ "EOD";
f = new FileWriter(dirNamePath + "/consense.sh");
BufferedWriter ww = new BufferedWriter(f);
ww.write(code);
ww.close();
Process p = rt.exec("sh " + dirNamePath + "/consense.sh");
output = dirName;
} catch (Exception ex)
{
System.out.println("Program failed due to : " + ex);
status = "Unexpected Error occured at server : " + ex;
} finally
{
out.jobId = output;
out.status = status;
return out;
}
}//consenseRootedTrees | 7 |
public NewItemDialog(JFrame frame) {
super(frame, true);
this.setTitle("Add new item to library");
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(240, 230));
jcbType = new JComboBox<Item.ItemType>();
for (Item.ItemType type : Item.ItemType.values())
jcbType.addItem(type);
jcbType = new JComboBox<Item.ItemType>();
for (Item.ItemType type : Item.ItemType.values())
jcbType.addItem(type);
JLabel jlTitle = new JLabel("Title:");
JLabel jlAuthor = new JLabel("Author:");
JLabel jlRating = new JLabel("Rating (0 - 5):");
final JLabel jlLength = new JLabel(getLengthString());
JLabel jlType = new JLabel("Type:");
JLabel jlGenre = new JLabel("Genre:");
jtfTitle = new JTextField();
jtfAuthor = new JTextField();
jtfGenre = new JTextField();
jtfRating = new JTextField();
jtfLength = new JTextField();
JTextField[] textfields = {jtfTitle, jtfAuthor, jtfGenre, jtfRating, jtfLength};
jcbType = new JComboBox<Item.ItemType>();
for (Item.ItemType type : Item.ItemType.values())
jcbType.addItem(type);
for (JTextField field : textfields) {
field.addKeyListener(new QuickAddListener());
}
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(6,2));
JPanel p2 = new JPanel();
JButton jbAdd = new JButton("Add");
JButton jbClose = new JButton("Close");
jbAdd.addActionListener(new AddListener());
jbAdd.setToolTipText("Quick Add (Ctrl+Enter)");
jbClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
jcbType.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent arg0) {
jlLength.setText(getLengthString());
}
});
p1.add(jlTitle);
p1.add(jtfTitle);
p1.add(jlAuthor);
p1.add(jtfAuthor);
p1.add(jlGenre);
p1.add(jtfGenre);
p1.add(jlLength);
p1.add(jtfLength);
p1.add(jlRating);
p1.add(jtfRating);
p1.add(jlType);
p1.add(jcbType);
p2.add(jbAdd);
p2.add(jbClose);
this.add(p1, BorderLayout.NORTH);
this.add(p2, BorderLayout.SOUTH);
this.pack();
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(frame);
this.setVisible(true);
} | 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(AirlineFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AirlineFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AirlineFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AirlineFrame.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 AirlineFrame().setVisible(true);
}
});
} | 6 |
public static void stop() {
if (task != null && !task.isDone()) {
task.cancel(true);
task = null;
BmLog.info("TestListController is stopped");
}
} | 2 |
public static void main(String[] args) {
System.out.print("Podaj tytul pierwszego utworu: ");
String tytulPiosenki1 = IO.readString();
System.out.print("Podaj czas trwania pierwszego utworu (minuty): ");
int pierwszyUtworMinuty = IO.readInt();
System.out.print("Podaj czas trwania pierwszego utworu (sekundy): ");
int pierwszyUtworSekundy = IO.readInt();
System.out.print("");
System.out.print("Podaj tytul drugiego utworu: ");
String tytulPiosenki2 = IO.readString();
System.out.print("Podaj czas trwania drugiego utworu (minuty): ");
int drugiUtworMinuty = IO.readInt();
System.out.print("Podaj czas trwania drugiego utworu (sekundy): ");
int drugiUtworSekundy = IO.readInt();
System.out.println("");
System.out.println("====================================================");
System.out.println("UTWORY: ");
if (pierwszyUtworMinuty >= drugiUtworMinuty || pierwszyUtworSekundy > drugiUtworSekundy) {
System.out.println("1. " + tytulPiosenki1 + " " + pierwszyUtworMinuty + ":"
+ pierwszyUtworSekundy);
System.out.println("2. " + tytulPiosenki2 + " " + drugiUtworMinuty + ":"
+ drugiUtworSekundy);
} else {
System.out.println("1. " + tytulPiosenki2 + " " + drugiUtworMinuty + ":"
+ drugiUtworSekundy);
System.out.println("2. " + tytulPiosenki1 + " " + pierwszyUtworMinuty + ":"
+ pierwszyUtworSekundy);
}
int lacznyCzasMinuty = pierwszyUtworMinuty + drugiUtworMinuty;
int lacznyCzasSekundy = pierwszyUtworSekundy + drugiUtworSekundy;
if (lacznyCzasSekundy >= 60 && (lacznyCzasSekundy - 60) < 10) {
System.out.println("LACZNY CZAS TRWANIA: " + (lacznyCzasMinuty + 1) + ":" + "0"
+ (lacznyCzasSekundy - 60));
} else if (lacznyCzasSekundy >= 60 && (lacznyCzasSekundy - 60) >= 10) {
System.out.println("LACZNYY CZAS TRWANIA: " + (lacznyCzasMinuty + 1) + ":"
+ (lacznyCzasSekundy - 60));
} else if (lacznyCzasSekundy < 10) {
System.out.println("LACZNY CZAS TRWANIA: " + lacznyCzasMinuty + ":" + "0"
+ lacznyCzasSekundy);
} else {
System.out
.println("LACZNY CZAS TRWANIA: " + lacznyCzasMinuty + ":" + lacznyCzasSekundy);
}
System.out.println("====================================================");
} | 7 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
State other = (State) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} | 6 |
public GregorianCalendar getFechaEncargo() {
return fechaEncargo;
} | 0 |
static public int get(int itemLevel, QualityT quality, ArmorT armor, EquipT equip) {
if (armor.armorTotalIndex < 0) {
if (armor == ArmorT.SHIELD) {
if (itemLevel < 1 && itemLevel > Shield.data.length) {
throw new IllegalArgumentException("Invalid Item Level: " + itemLevel);
}
return (int)(0.5 + quality.armorMod * Shield.data[(itemLevel - 1) * 7 + quality.index]);
}
return 0;
}
if (itemLevel < 1 || itemLevel > Total.data.length) {
throw new IllegalArgumentException("Invalid Item Level: " + itemLevel);
}
return (int)(0.5 + quality.armorMod * Total.data[((itemLevel - 1) << 2) | armor.armorTotalIndex] * equip.armorMod);
} | 6 |
public static boolean addEndAndStartOfSequenceAfterThisWord(String currentWord,
String prevWord, SpacingModel nextSpace,int lengthSinceLastBreak) {
//System.out.println("currentWord="+currentWord+" prev="+prevWord+" nextSpace="+nextSpace+" int="+lengthSinceLastBreak);
if (currentWord.equals(ENDER)) {
return false;
}
if (currentWord.equals(".") && (!prevWord.matches("^\\p{IsUpper}.*") && prevWord.length()>MAXACRONYM)) {
return true;
}
if (nextSpace==null || nextSpace.hasNonIndentTabsOrMultipleCarriageReturns()) {
return true;
}
if (lengthSinceLastBreak>=MAXLENGTHBETWEENBREAKS) {
return true;
}
return false;
} | 7 |
public void SetSmithing(int WriteFrame) {
outStream.createFrameVarSizeWord(53);
outStream.writeWord(WriteFrame);
outStream.writeWord(Item.SmithingItems.length);
for (int i = 0; i < Item.SmithingItems.length; i++) {
Item.SmithingItems[i][0] += 1;
if (Item.SmithingItems[i][1] > 254) {
outStream.writeByte(255); // item's stack count. if over 254, write byte 255
outStream.writeDWord_v2(Item.SmithingItems[i][1]); // and then the real value with writeDWord_v2
} else {
outStream.writeByte(Item.SmithingItems[i][1]);
}
if (Item.SmithingItems[i][0] > 20000 || Item.SmithingItems[i][0] < 0) {
playerItems[i] = 20000;
}
outStream.writeWordBigEndianA(Item.SmithingItems[i][0]); //item id
}
outStream.endFrameVarSizeWord();
} | 4 |
@Override
public void run()
{
Query currentQuery;
while(!Thread.interrupted())
{
synchronized(queries)
{
try
{
while(queries.isEmpty()) queries.wait();
}
catch(InterruptedException ex)
{
break;
}
currentQuery = queries.removeLast();
}
Dispatcher.DispatchQuery(currentQuery);
}
//Clearing remaining queries ...
Query query;
while(true)
{
synchronized(queries)
{
if(queries.isEmpty()) return;
query = queries.removeLast();
}
Response response = query.makeResponse();
response.setStatus(Response.Status.SERVER_STOPPED);
response.send();
}
} | 5 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Persona other = (Persona) obj;
if (!Objects.equals(this.nombre, other.nombre)) {
return false;
}
return true;
} | 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(ModifierClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ModifierClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ModifierClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ModifierClient.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 ModifierClient().setVisible(true);
}
});
} | 6 |
@Override
public void run()
{
Path path = new Path();
PathSource pathSource = new PathSourceLink(map);
int sx = player.location.x;
int sy = player.location.y;
int dx, dy;
while(go) {
// Find a random empty spot on the map
do {
dx = (int) (Math.random()*map.getWidth());
dy = (int) (Math.random()*map.getHeight());
} while(pathSource.isMoveAllowed(sx, sy, dx, dy) == false);
CoordinatePathDestination destination =
new CoordinatePathDestination(dx, dy);
// Try to find a path there
boolean ok = path.findPath(pathSource, destination, sx, sy);
// See if we found a path
if(ok) {
// mark destination with X on screen
if(player.location.x != dx || player.location.y != dy) {
map.set(LayerCodes.MOBILES, dx, dy, 'X' + ColorCodes.RED);
}
// now walk.
walkPath(path);
}
// pathing done
path.clear();
// update start for next pathdinfind call.
sx = player.location.x;
sy = player.location.y;
}
} | 5 |
public Queen(boolean isWhite, ImageIcon imgIcon) {
super(isWhite, imgIcon);
this.setIcon();
} | 0 |
private void jButtonSauvegarderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSauvegarderActionPerformed
//Récupération de la méthode contrôleur 'sauvegarderRapport'
ctrlCR.sauvegarderRapport();
}//GEN-LAST:event_jButtonSauvegarderActionPerformed | 0 |
public void write(Size size, int bank, int addr, int val) {
boolean fastrom = false;
// Determine speed by bank
if (bank >= 0x80) {
fastrom = true;
}
if ((bank == 0x00 || bank == 0x80) && addr >= 0x4000 && addr <= 0x41FF) {
Timing.cycle(12); // 12 master cycles to access these
set(size,bank,addr,val);
return;
}
if (fastrom){ // 6 cycles
Timing.cycle(6);
set(size,bank,addr,val);
return;
} else { // 8 cycles
Timing.cycle(8);
set(size,bank,addr,val);
return;
}
} | 6 |
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
if(login(usernameField.getText(),passwordField.getText())){
JOptionPane.showMessageDialog(null, "Logged in as " + account.getUsername());
this.dispose();
}
}//GEN-LAST:event_loginButtonActionPerformed | 1 |
public WidthChangeHandler(boolean increment) {
this.increment = increment;
} | 0 |
public static Reponse creerReponse(Sujet sujet, String message, Utilisateur utilisateur)
throws ChampInvalideException, ChampVideException {
if (!sujet.peutRepondre(utilisateur))
throw new InterditException("Vous n'avez pas les droits requis pour répondre");
EntityTransaction transaction = SujetRepo.get().transaction();
Reponse r;
try {
transaction.begin();
r = genererReponse(sujet, message, utilisateur);
ReponseRepo.get().creer(r);
SujetRepo.get().mettreAJour(r.getSujet());
transaction.commit();
}
catch(Exception e) {
if (transaction.isActive())
transaction.rollback();
if (e instanceof ChampVideException)
throw (ChampVideException)e;
else if (e instanceof ChampInvalideException)
throw (ChampInvalideException)e;
else
throw (RuntimeException)e;
}
return r;
} | 5 |
public boolean eq(Matrix B) {
Matrix A = this;
if (B.M != A.M || B.N != A.N)
throw new RuntimeException("Illegal matrix dimensions.");
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (A.data[i][j] != B.data[i][j])
return false;
return true;
} | 5 |
private Formula negotiate(int snum) {
Formula offer = null, prevOffer= null;
int step = 0;
Formula finalOffer = null;
System.out.println("");
System.out.println("************* Negotiation Starts *************");
while (true) {
step++;
//System.out.println("");
System.out.println("Step: " + step);
System.out.println("Buyer Agent: ");
prevOffer = offer;
offer = buyerAgent.generateOffer(offer, snum);
if (offer == null) {
System.out.println("*****No Agreement reached******");
break;
};
if (offer.isAccepted()) {
System.out.println("*****Agreement reached******");
System.out.println("===Chosen Offer: " + prevOffer);
finalOffer = prevOffer;
break;
}
System.out.println("===Chosen Offer: " + offer);
step++;
System.out.println("Step: " + step);
System.out.println("Seller Agent: ");
prevOffer = offer;
offer = sellerAgent.generateOffer(offer, snum);
if (offer == null) {
System.out.println("*****No Agreement reached******");
break;
};
if (offer.isAccepted()) {
System.out.println("*****Agreement reached******");
System.out.println("===Chosen Offer: " + prevOffer);
finalOffer = prevOffer;
break;
}
System.out.println("===Chosen Offer: " + offer);
if (step > 100) {
System.out.println("*****No Agreement reached after 100 steps******");
};
}
System.out.println("Took Step: " + step);
return finalOffer;
} | 6 |
public void visitFieldInsn(final int opcode, final String owner,
final String name, final String desc) {
buf.setLength(0);
buf.append(tab2).append(OPCODES[opcode]).append(' ');
appendDescriptor(INTERNAL_NAME, owner);
buf.append('.').append(name).append(" : ");
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('\n');
text.add(buf.toString());
if (mv != null) {
mv.visitFieldInsn(opcode, owner, name, desc);
}
} | 1 |
public boolean takeDamage(int amount, Living from) {
if (from != null && !from.living()) {
return false;
}
if (amount > 0) {
washurt.add(amount);
}
hp -= amount;
if (hp < 1) {
hp = 0;
dead = true;
return true;
}
return false;
} | 4 |
@Override
public String mover(int fila, int columna, int turno) {
if(this.columna==columna){
if((this.fila>=1&&this.fila<=6)&&(this.fila+1==fila||this.fila-1==fila))
return getPeon(turno);
else if((this.fila==6&&fila==4)||(this.fila==1&&fila==3))
return getPeon(turno);
}
return null;
} | 9 |
@SuppressWarnings("unchecked")
protected <C extends Component> C get(Entity entity,
Class<? extends Component> componentClass) {
int entityId = entity.getId();
int componentId = getId(componentClass);
Bag<Component> components = componentIdToComponents.get(componentId);
if (components == null) {
throw new NoSuchComponentException(String.format(
ExceptionStrings.NO_SUCH_COMPONENT_EXISTS,
componentClass.getSimpleName()));
}
Component component = components.get(entityId);
if (component == null) {
throw new NoSuchComponentException(
ExceptionStrings.NO_SUCH_COMPONENT_EXISTS_IN_ENTITY);
}
return (C) component;
} | 3 |
@Override
public void stateChanged(/*@NotNull*/ ChangeEvent<State> event) {
Util.checkNotNullArgument(event);
if (!isBackground(event)) {
return;
}
if (event.getNewValue() != null) {
State state = event.getNewValue();
int count = getBackgroundTaskCount();
updateLabel(count, null, event.getSource().getPhase());
if (count > 0 && state == State.STARTED) {
//new task came in
if (currentProgress == null) {
currentProgress = event.getSource().getContextId();
}
progressBar.setIndeterminate(true);
}
//noinspection ConstantConditions
if (count > 0 && state.isFinalState()) {
//some task finished, more to do
currentProgress = null;
progressBar.setIndeterminate(true);
}
//noinspection ConstantConditions
if (count == 0 && state.isFinalState()) {
//last task finished
currentProgress = null;
progressBar.setValue(0);
progressBar.setIndeterminate(false);
progressBar.setToolTipText(null);
}
}
} | 9 |
private void stopFileSender() {
while (this.fileSenderThread != null && this.fileSenderThread.isAlive()) {
this.fileSenderThread.interrupt();
try {
this.fileSenderThread.join();
System.out.println("fileSenderThread finish");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} | 3 |
public boolean[][] analyseData() {
// creates a 2D boolean array for each grade and period
boolean[][] checkboxBooleanArray = new boolean[totalGrades][perPerDay];
// for loop cycles through each one and checks to which checkboxes are
// selected and assigns that value to the sepcific position
for (int y = 0; y < checkboxBooleanArray.length; y++) {
for (int x = 0; x < checkboxBooleanArray[0].length; x++) {
if (y == 0) {
checkboxBooleanArray[y][x] = cb_09[x].isSelected();
} else if (y == 1) {
checkboxBooleanArray[y][x] = cb_10[x].isSelected();
} else if (y == 2) {
checkboxBooleanArray[y][x] = cb_11[x].isSelected();
} else if (y == 3) {
checkboxBooleanArray[y][x] = cb_12[x].isSelected();
}
}
}
// returns the 2D boolean array
return checkboxBooleanArray;
} | 6 |
public void carregaMusicas(File[] arquivos,Atualizador atualizador, ArrayList<Tags> listaTags)
throws ListaNulaException, ListaVaziaException {
// declara variaveis
String artista = ConstantesUI.STRING_VAZIA;
String album = ConstantesUI.STRING_VAZIA;
String ano = ConstantesUI.STRING_VAZIA;
String genero = ConstantesUI.STRING_VAZIA;
int discoNumero = ConstantesUI.NUMERO_1;
int discoTotal = ConstantesUI.NUMERO_1;
try {
// preenche valores gerais
if (listaTags.get(0) != null) {
artista = listaTags.get(0).getArtista();
album = listaTags.get(0).getAlbum();
ano = listaTags.get(0).getAno();
genero = listaTags.get(0).getGenero();
discoNumero = listaTags.get(0).getDiscoNumero();
discoTotal = listaTags.get(0).getDiscoTotal();
}
// cria listas
ArrayList<JLabel> listLabels = new ArrayList<JLabel>();
ArrayList<JTextField> listTextFieldNumero = new ArrayList<JTextField>();
ArrayList<JTextField> listTextFieldFaixas = new ArrayList<JTextField>();
ArrayList<JTextField> listTextFieldArtista = new ArrayList<JTextField>();
// declara variáveis para o conteúdo das listas
String nomeDoArquivo = ConstantesUI.STRING_VAZIA;
String numero = ConstantesUI.STRING_VAZIA;
String faixas = ConstantesUI.STRING_VAZIA;
String artistas = ConstantesUI.STRING_VAZIA;
// popula as listas
for (int i = 0; i < listaTags.size(); i++) {
listLabels.add(new JLabel());
listTextFieldNumero.add(new JTextField(3));
listTextFieldFaixas.add(new JTextField(15));
listTextFieldArtista.add(new JTextField(15));
}
for (int i = 0; i < listaTags.size(); i++) {
//pegas os valores, e seta nas listas
nomeDoArquivo = listaTags.get(i).getNomeDoArquivo();
numero = listaTags.get(i).getNumero();
faixas = listaTags.get(i).getNomeDaMusica();
artistas = listaTags.get(i).getArtista();
listLabels.get(i).setText(nomeDoArquivo);
listTextFieldNumero.get(i).setText(numero);
listTextFieldFaixas.get(i).setText(faixas);
listTextFieldArtista.get(i).setText(artistas);
}
// Ordenando a lista
int contador = 1;
do {
for (int i = 0; i < listTextFieldNumero.size() - 1; i++) {
int valor = Integer.parseInt(listTextFieldNumero.get(i)
.getText());
int next = Integer.parseInt(listTextFieldNumero.get(i + 1)
.getText());
if (valor > next) {
trocaValores(listTextFieldNumero, i);
trocaValores(listTextFieldFaixas, i);
trocaValores(listLabels, i);
}
}
contador++;
} while (contador < listTextFieldNumero.size());
byte[] image = listaTags.get(0).getImage();
tag.setImage(image);
// Atualizando a UI
atualizador.habilitarTodosOsComponentes();
atualizador.updateFaixas(listLabels, listTextFieldNumero,listTextFieldFaixas, listTextFieldArtista);
atualizador.updateImage(tag.getImage());
atualizador.updatetagsGerais(artista, album, ano, genero, discoNumero, discoTotal);
} catch (NullPointerException e) {
throw new ListaNulaException();
} catch (ArrayIndexOutOfBoundsException e) {
throw new ListaVaziaException();
} catch (IndexOutOfBoundsException e) {
throw new ListaVaziaException();
}
} | 9 |
@Override
public Iterable<? extends Position<T>> children(Position<T> p)
throws InvalidPositionException, BoundaryViolationException {
// focusing on a particular node, return 0, 1 or 2 children
ArrayList<Position<T>> children = new ArrayList<Position<T>>();
if (hasLeft(p))
children.add(left(p));
if (hasRight(p))
children.add(right(p));
return children;
} | 3 |
private static void vote(Desc desc) {
List<String> keywords = desc.keywords;
int[] votes = new int[N];
for (BookName bn : booknames) {
for (String kw : keywords) {
if (!ignoredKeywords.contains(kw) && bn.keywordSet.contains(kw)) {
votes[bn.index]++;
}
}
}
int maxVoteIndex = 0;
for (int i = 0; i < votes.length; i++) {
if (votes[i] > votes[maxVoteIndex]) {
maxVoteIndex = i;
}
}
if (votes[maxVoteIndex] > 0) {
getBookNameByIndex(maxVoteIndex).markVote(desc.index, votes[maxVoteIndex]);
}
} | 7 |
Subsets and Splits