text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Test
public void testGcdHappyPath() {
// the base case means that q == 0, so return p
int q = 100;
int p = 75;
int result = BasicMath.gcd(p, q);
assertEquals(result, 25);
} | 0 |
private ExpressionList expression_list(int fallbackLineNumber, int fallbackCharPosition) throws RequiredTokenException
{
enterRule(NonTerminal.EXPRESSION_LIST);
ArrayList<Expression> expressions = new ArrayList<Expression>();
if(firstSetSatisfied(NonTerminal.EXPRESSION0))
{
expressions.add(expression0());
while(accept(Token.Kind.COMMA))
expressions.add(expression0());
}
exitRule();
return new ExpressionList(
expressions.size() > 0 ? ((Command)expressions.get(0)).lineNumber() : fallbackLineNumber,
expressions.size() > 0 ? expressions.get(0).getLeftmostCharPos(): fallbackCharPosition,
expressions);
} | 4 |
@Override
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if (cs instanceof Player) {
final Player player = (Player) cs;
if (Lobby.started && !Game.started) {
if (DatabaseHandler.isPremium(player)) {
//TODO START PARTY
} else {
player.sendMessage(MessagesHandler.convert("Party.OnlyPremiums"));
}
} else {
player.sendMessage(MessagesHandler.convert("Party.OnlyInLobby"));
}
} else {
cs.sendMessage(MessagesHandler.noPlayer());
}
return true;
} | 4 |
public Collection<Entidad> ordenar(final String nombreCampo) {
final Collection<Entidad> tmp = new TreeSet<Entidad>( // Crea una coleccion de entidades a partir de un TreeSet
new Comparator<Entidad>() { // Es necesario crear un comparador de entidades para el TreeSet
@Override
public int compare(final Entidad o1, final Entidad o2) { // Se sobreescribe el metodo compare para organizar el TreeSet
int ret = 0;
try {
/*
* Obtiene el metodo con el nombre de campo proporcionado,
agregando get y conviertiendo la primer letra a Mayuscula y le agrega el resto de la cadena*/
final Method method = Entidad.class.getMethod("get" + nombreCampo.substring(0, 1).toUpperCase() + nombreCampo.substring(1));
final Object val1 = method.invoke(o1); //Invoca los metodos para obtener el atributo de las entidades segun el atributo ingresado
final Object val2 = method.invoke(o2);
if (val1 instanceof Long) {
ret = ((Long) val1).compareTo((Long) val2); // Si es instancia de Long los compara segun el atributo cantidad
} else if (val1 instanceof Double) {
ret = ((Double) val1).compareTo((Double) val2); // Si es instancia de Double los compara segun el atributo precio
} else if (val1 instanceof String) {
ret = ((String) val1).compareTo((String) val2); // Si es instancia de String los compara segun el atributo nombre
}
} catch (final Exception e) {
e.printStackTrace();
}
return ret;
}
});
tmp.addAll(DAO.listarEntidades()); // Agrega las entidades del DAO al TreeSet
return tmp;
} | 4 |
public void run() {
System.out.println("taskLauncher run");
while (!Thread.interrupted()) {
try {
TaskInstance taskIns;
synchronized (tasksToLaunch) {
while (tasksToLaunch.isEmpty()) {
tasksToLaunch.wait();
}
//get the TIP
taskIns = tasksToLaunch.remove(0);
System.out.println("taskLauncher get new task "+taskIns.getTask().getTaskId());
}
//wait for a slot to run
woker.getFreeSlot();
//got a free slot. launch the task
startNewTask(taskIns);
} catch (InterruptedException e) {
return; // ALL DONE
} catch (Throwable th) {
}
}
} | 4 |
public Item next() throws NoSuchElementException
{
if(postingListMemoryMapped!=null &&
entry >=0 &&
entry < lexiconSize &&
currentPos >=0 &&
currentPos < toPos)
{
numOfReads++;
int o=postingListMemoryMapped.getInt();
while(currentPos>=postingListIndex[currentScore+1])
currentScore++;
int score=currentScore;
currentPos+=elementSize;
// System.out.println("Object:"+o+" Score:"+score);
return new Item(o,score);
}
synchronized(this){
// System.out.println("Releasing lock on posting list "+entry);
inUse=false;
this.notify(); //release exclusive access to the posting list
}
throw new NoSuchElementException("InvertedFile not Initialized, non valid entry, or no more elements in this posting list");
} | 6 |
protected static Ptg calcSlope( Ptg[] operands ) throws CalculationException
{
if( operands.length != 2 )
{
return new PtgErr( PtgErr.ERROR_VALUE );
}
double[] yvals = PtgCalculator.getDoubleValueArray( operands[0] );
double[] xvals = PtgCalculator.getDoubleValueArray( operands[1] );
if( (xvals == null) || (yvals == null) )
{
return new PtgErr( PtgErr.ERROR_NA );//20090130 KSC: propagate error
}
double sumXVals = 0;
for( double xval1 : xvals )
{
sumXVals += xval1;
}
double sumYVals = 0;
for( double yval : yvals )
{
sumYVals += yval;
}
double sumXYVals = 0;
for( int i = 0; i < yvals.length; i++ )
{
sumXYVals += xvals[i] * yvals[i];
}
double sqrXVals = 0;
for( double xval : xvals )
{
sqrXVals += xval * xval;
}
double toparg = (sumXVals * sumYVals) - (sumXYVals * yvals.length);
double bottomarg = (sumXVals * sumXVals) - (sqrXVals * xvals.length);
double res = toparg / bottomarg;
return new PtgNumber( res );
} | 7 |
public ResultMessage updUncheckedSend(ArrayList<SendCommodityPO> poList) {
SendCommodityPO po;
for(int i = 0; i < poList.size(); i ++) {
po = poList.get(i);
Iterator<SendCommodityPO> iter = sendList.iterator();
SendCommodityPO s;
while(iter.hasNext()) {
s = iter.next();
if(po.date.getTime() == s.date.getTime() && po.num == s.num && s.checked != po.checked) {
s.checked = po.checked;
break;
}
}
}
writeSendFile();
return ResultMessage.update_success;
} | 5 |
public JPanel setBoard(int n)
{
players[n].setMyBoard(new JPanel(new GridLayout(11,11)));//panel to store board
JTextField k;
for (i=0;i<11;i++)
{
for (j=0;j<11;j++)
{
if ((j!=0)&&(i!=0))
{
players[n].getBboard(i-1,j-1).addActionListener(new BoardListener());
players[n].getMyBoard().add(players[n].getBboard(i-1,j-1));
}
if (i==0)
{
if (j!=0)
{
//used to display row of numbers
k= new JTextField(Battleship.getCnumbers(j));
k.setEditable(false);
k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
}
else
{
//used to display column of numbers
k= new JTextField();
k.setEditable(false);
}
players[n].getMyBoard().add(k);
}
else if (j==0)
{
k= new JTextField(Battleship.getCletters(i));
k.setEditable(false);
k.setHorizontalAlignment((int)JFrame.CENTER_ALIGNMENT);
players[n].getMyBoard().add(k);
}
}
}
return players[n].getMyBoard();
} | 7 |
@Override
public void run(Player interact, Entity on, InteractionType interaction) {
if(interaction != InteractionType.LEFT && interaction != InteractionType.RIGHT) return;
String[] vote = new String[1];
vote[0] = this.vote;
Vote.instance.execute(interact, vote);
} | 2 |
static void revertMove(String cmd, int specialPiece) throws IOException {
int v[][] = Board.translatePosition(cmd.charAt(0) + "" + cmd.charAt(1) + "" + cmd.charAt(2) + "" + cmd.charAt(3));
Board.board[v[0][0]][v[0][1]] = Board.board[v[1][0]][v[1][1]];
Board.board[v[1][0]][v[1][1]] = specialPiece;
/* Verificam daca mutarea precedenta a transformat un pion in regina si schimbam totul cum trebuie */
if (cmd.equals(specialMove)) {
if (Board.isBlackPiece(v[0][0], v[0][1])) {
Board.board[v[0][0]][v[0][1]] = 'p';
}
if (Board.isWhitePiece(v[0][0], v[0][1])) {
Board.board[v[0][0]][v[0][1]] = 'P';
}
}
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
Logger.writeNNL((char) Board.board[i][j] + " ");
}
Logger.newLine();
}
} | 5 |
public static void main(String[] args){
String host;
int port;
String platform = null; //default name
boolean main = true;
host = "localhost";
port = -1; //default-port 1099
Runtime runtime = Runtime.instance();
Profile profile = null;
AgentContainer container = null;
profile = new ProfileImpl(host, port, platform, main);
//Container erzeugen
container = runtime.createMainContainer(profile);
// Agent rmagent = new jade.tools.rma.rma();
// // Remote Monitoring Agenten erzeugen
// try {
// AgentController rma = container.acceptNewAgent(
// "RMA",
// rmagent
// );
// rma.start();
// } catch(StaleProxyException e) {
// throw new RuntimeException(e);
// }
// Agenten erzeugen und startet - oder aussteigen.
try {
AgentController agent = container.createNewAgent(
"MyAgent",
MyAgent.class.getName(),
args);
agent.start();
} catch(StaleProxyException e) {
throw new RuntimeException(e);
}
} | 1 |
public HashMap<Integer, Integer[]> countOfPassengerOnEveryStation(Train train) {
log.debug("Start countOfPassengerOnEveryStation select");
List stationFrom = em.createQuery("select station.id, count(ticket.id), 0, schedule.seqNumber - 1 \n" +
"from Train train \n" +
"left join train.ticketsById ticket\n" +
"inner join ticket.stationByStationFrom station\n" +
"inner join train.routeByIdRoute route\n" +
"inner join route.schedulesById schedule\n" +
"inner join schedule.wayByIdWay way\n" +
"inner join way.stationByIdStation1 stationFrom\n" +
"where train.name = ?\n" +
"and stationFrom.id = station.id\n" +
" group by station.id")
.setParameter(1, train.getName())
.getResultList();
List stationTo = em.createQuery("select station.id, 0, count(ticket.id), schedule.seqNumber \n" +
"from Train train \n" +
"left join train.ticketsById ticket\n" +
"inner join ticket.stationByStationTo station\n" +
"inner join train.routeByIdRoute route\n" +
"inner join route.schedulesById schedule\n" +
"inner join schedule.wayByIdWay way\n" +
"inner join way.stationByIdStation2 stationTo\n" +
"where train.name = ?\n" +
"and stationTo.id = station.id\n" +
" group by station.id")
.setParameter(1, train.getName())
.getResultList();
HashMap<Integer, Integer[]> result = new HashMap<Integer, Integer[]>();
for (Object[] obj : (List<Object[]>) stationFrom) {
if (result.containsKey(obj[0])) {
Integer[] a = result.get(obj[0]);
a[0] += ((Long) obj[1]).intValue();
a[1] += (Integer) obj[2];
result.put((Integer) obj[0], new Integer[]{a[1], a[2], (Integer) obj[3]});
} else {
result.put((Integer) obj[0], new Integer[]{((Long) obj[1]).intValue(), (Integer) obj[2], (Integer) obj[3]});
}
}
for (Object[] obj : (List<Object[]>) stationTo) {
if (result.containsKey(obj[0])) {
Integer[] a = result.get(obj[0]);
a[0] += (Integer) obj[1];
a[1] += ((Long) obj[2]).intValue();
result.put((Integer) obj[0], new Integer[]{a[1], a[2], (Integer) obj[3]});
} else {
result.put((Integer) obj[0], new Integer[]{(Integer) obj[1], ((Long) obj[2]).intValue(), (Integer) obj[3]});
}
}
return result;
} | 4 |
public List<Integer> WolfTargets(int inWolf){
ArrayList<Integer> output = new ArrayList<Integer>();
for(PlayerAction Action : AllActions){
if(Action instanceof Attack){
if(Action.getPlayer() == inWolf) output.add(((Attack) Action).getTarget());
}
}
return output;
} | 3 |
public String getTextColorOfParticipant(String id) {
return participants.get(id).getTextColor();
} | 0 |
public static GameObjectType fromId(byte id) {
for (GameObjectType type : values()) {
if (type.id == id) return type;
}
return null;
} | 2 |
void DFS(String s, int start, ArrayList<String> tmp, ArrayList<ArrayList<String>> res) {
if (start == s.length()) {
res.add(new ArrayList(tmp));
}
for (int i = start; i < s.length(); ++i) {
if (isPalindrome(s, start, i)) {
tmp.add(s.substring(start, i + 1));
DFS(s, i + 1, tmp, res);
tmp.remove(tmp.size() - 1);
}
}
} | 3 |
public Object getProperty(String key) {
PreparedStatement pstmtGetProp = null;
Object result = null;
// build the query
StringBuffer query =
new StringBuffer("SELECT ").append(valueColumn).append(" FROM ");
query.append(table).append(" WHERE ");
query.append(keyColumn).append("=?");
try {
pstmtGetProp = con.prepareStatement(query.toString());
} catch (SQLException e) {
throw new RuntimeException("Not prepareStatement", e);
}
List results = new ArrayList();
try {
pstmtGetProp.setString(1, key);
ResultSet rs = pstmtGetProp.executeQuery();
while (rs.next()) {
Object value = rs.getObject(valueColumn);
if (isDelimiterParsingDisabled()) {
results.add(value);
} else {
Iterator it =
PropertyConverter.toIterator(value, getListDelimiter());
while (it.hasNext()) {
results.add(it.next());
}
}
}
pstmtGetProp.close();
} catch (SQLException e) {
throw new RuntimeException("Execute prepareStatement", e);
}
if (!results.isEmpty()) {
result = (results.size() > 1) ? results : results.get(0);
}
return result;
} | 7 |
public void siirra(Suunta suunta)
{
float x = siirtyma.x();
float y = siirtyma.y();
switch(suunta)
{
case OIKEA: siirtyma.aseta(x + 1, y); break;
case VASEN: siirtyma.aseta(x - 1, y); break;
case ALAS: siirtyma.aseta(x, y + 1); break;
case YLOS: siirtyma.aseta(x, y - 1); break;
}
} | 4 |
public void scriviTutto () {
System.out.println("Stato Iniziale: " + this.statoIniziale);
System.out.println("");
System.out.println("Configurazione stato:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.print("Stato[" + i + "][" + j + "]: " + stato[i][j]);
System.out.println(" - ");
}
}
System.out.println("");
System.out.println("Configurazione shift:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.print("Shift[" + i + "][" + j + "]: " + shift[i][j]);
System.out.println(" - ");
}
}
System.out.println("");
System.out.println("Configurazione Nastro:");
for (int i = 0; i < nastro.size(); i++) {
System.out.print(nastro.elementAt(i));
System.out.println(" - ");
}
System.out.println("");
} | 5 |
public SignatureVisitor visitInterfaceBound() {
separator = seenInterfaceBound ? ", " : " extends ";
seenInterfaceBound = true;
startType();
return this;
} | 1 |
private void createTablesIfNotExist(Connection cnn) {
if (tableExists("cb_users", cnn)) {
logger.info("table cb_users already exists");
} else {
logger.info("create table cb_users");
String sql =
"CREATE TABLE `cb_users` ( \n" +
" `username` varchar(255) NOT NULL, \n" +
" `password` varchar(255) DEFAULT NULL, \n" +
" PRIMARY KEY (`username`) \n" +
") \n";
executeStatement(sql, cnn);
}
if (tableExists("cb_groups", cnn)) {
logger.info("table cb_groups already exists");
} else {
logger.info("create table cb_groups");
String sql =
"CREATE TABLE `cb_groups` ( \n" +
" `groupname` varchar(255) NOT NULL, \n" +
" `username` varchar(255) NOT NULL, \n" +
" `ID` int(11) NOT NULL AUTO_INCREMENT, \n" +
" PRIMARY KEY (`ID`), \n" +
" UNIQUE KEY `ID_UNIQUE` (`ID`) \n" +
") \n";
executeStatement(sql, cnn);
}
} | 2 |
private void removeBlock(final Block block) {
trace.remove(block);
subroutines.remove(block);
catchBlocks.remove(block);
handlers.remove(block);
// edgeModCount is incremented by super.removeNode().
// Dominators will be recomputed automatically if needed, so just
// clear the pointers to let the GC work.
block.setDomParent(null);
block.setPdomParent(null);
block.domChildren().clear();
block.pdomChildren().clear();
block.domFrontier().clear();
block.pdomFrontier().clear();
Iterator iter = handlers.values().iterator();
while (iter.hasNext()) {
final Handler handler = (Handler) iter.next();
handler.protectedBlocks().remove(block);
}
iter = subroutines.values().iterator();
while (iter.hasNext()) {
final Subroutine sub = (Subroutine) iter.next();
sub.removePathsContaining(block);
if (sub.exit() == block) {
sub.setExit(null);
}
}
if (block.tree() != null) {
iter = block.tree().stmts().iterator();
while (iter.hasNext()) {
final Stmt s = (Stmt) iter.next();
if (s instanceof LabelStmt) {
final Label label = ((LabelStmt) s).label();
label.setStartsBlock(false);
iniBlock.tree().addStmt(new LabelStmt(label));
}
s.cleanup();
}
}
super.removeNode(block.label());
} | 6 |
public Version(final String version) {
this.original = version;
if (version == null) {
this.major = null;
this.minor = null;
this.revision = null;
this.type = null;
this.build = null;
return;
}
final Matcher m = Pattern.compile("(\\d+)\\.(\\d+).(\\d+)(a|b|rc|$)(\\d+)?").matcher(this.original);
if (!m.find())
throw new IllegalArgumentException("Unrecognized version format \"" + version + "\"; Expected <Major>.<Minor>.<Revision>[<Type><Build>]");
this.major = Integer.parseInt(m.group(1));
this.minor = Integer.parseInt(m.group(2));
this.revision = Integer.parseInt(m.group(3));
this.type = Type.parse(m.group(4));
this.build = (m.group(5) != null ? Integer.parseInt(m.group(5)) : null);
} | 3 |
public java.lang.String getLastMessage() throws java.rmi.RemoteException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[11]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("GetLastMessage");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("", "GetLastMessage"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (java.lang.String) _resp;
} catch (java.lang.Exception _exception) {
return (java.lang.String) org.apache.axis.utils.JavaUtils.convert(_resp, java.lang.String.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
throw axisFaultException;
}
} | 4 |
public void doTask() {
//
// Get the currently picked tile, fixture and mobile. See if they are
// valid as targets. If so, preview in green. Otherwise, preview in
// red. If the user clicks, perform the placement.
final Tile PT = UI.selection.pickedTile() ;
final Fixture PF = UI.selection.pickedFixture() ;
final Mobile PM = UI.selection.pickedMobile() ;
boolean valid = true ;
Target picked = null ;
if (validPick(PM)) picked = PM ;
else if (validPick(PF)) picked = PF ;
else if (validPick(PT)) picked = PT ;
else { picked = PT ; valid = false ; }
if (picked != null) {
previewAt(picked, valid) ;
if (UI.mouseClicked() && valid) {
performAt(picked) ;
UI.endCurrentTask() ;
}
}
} | 6 |
public static String toString(JSONObject jo) throws JSONException {
StringBuffer sb = new StringBuffer();
sb.append(escape(jo.getString("name")));
sb.append("=");
sb.append(escape(jo.getString("value")));
if (jo.has("expires")) {
sb.append(";expires=");
sb.append(jo.getString("expires"));
}
if (jo.has("domain")) {
sb.append(";domain=");
sb.append(escape(jo.getString("domain")));
}
if (jo.has("path")) {
sb.append(";path=");
sb.append(escape(jo.getString("path")));
}
if (jo.optBoolean("secure")) {
sb.append(";secure");
}
return sb.toString();
} | 4 |
@Override
public void doAnswer(AnswerSide answerSide)
{
AnswerSideManager answerSideManager = AnswerSideManager.getInstance();
answerSideManager.setAnswerSide(answerSide);
MessageDialog.getInstance().show(answerSideManager.getAnswersName() + ", фальстарт!");
answerSideManager.setAnswerSide(null);
FalseStartLabel.getInstance().setFalseStart(answerSide);
StateManager.getInstance().setState(new TimeIsRunningOut(answerSide));
startGame();
} | 0 |
public int up(){
int movedNr = 0;
for(int i=0;i<getY();i++){
ArrayList<Integer> merged = new ArrayList<Integer>(2); //list of all tiles which are already merged and are not allowed to be merged again
for(int u=0;u<getX()-1;u++){//go from left to right
int cv = u+1;
if(cells[cv][i] != 0){
Boolean moved = false;
for(int t=u;t>=0;t--){ //go from current right to left
//check if it could be merged and if we are allowed to merge
if(cells[t][i] == 0){
cells[t][i] = cells[cv][i];
cells[cv][i] = 0;
cv--;
moved = true;
}else{
if(cells[cv][i] == cells[t][i] && !merged.contains(t)){
cells[t][i] = cells[cv][i] * 2;
cells[cv][i] = 0;
merged.add(t);
moved = true;
}
break;
}
}
if(moved) movedNr++;
}
}
}
return movedNr;
} | 8 |
@Test
public void testGetName() throws IOException {
System.out.println("getName");
String antBrainFile = "cleverbrain1.brain";
AntBrain instance = new AntBrain(antBrainFile);
String expResult = antBrainFile;
String result = instance.getName();
assertEquals(expResult, result);
} | 0 |
public static void toFile(String stats, String filename) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(filename + ".dat"));
writer.write(stats);
} catch (IOException ignored) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException ignored) {
}
}
} | 3 |
public SQLTableModel(String sql, String connection) {
super();
Connection con = (Connection) Session.getCurrent().get(connection);
try {
Statement stat = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet res = stat.executeQuery(sql);
ResultSetMetaData meta = res.getMetaData();
ColumnDefinition[] cols = new ColumnDefinition[meta.getColumnCount()];
for(int i = 0; i < cols.length; i++) {
cols[i] = new ColumnDefinition(meta.getColumnName(i + 1));
}
this.definition = cols;
res.first();
do {
TableRow row = new TableRow(cols.length);
for(int i = 0; i < cols.length; i++) {
TableCell cell = new TableCell();
cell.setColumn(i);
cell.setRow(res.getRow());
cell.setValue(res.getString(i + 1));
row.getCells()[i] = cell;
}
this.rows.add(row);
} while (res.next());
} catch (SQLException e) {
Session.logger.warn("Couldn't create Data Table", e);
}
} | 4 |
public void recordValue(String name, long timeStamp, float value) throws IOException {
SensorData sd = (SensorData)paramStorage.get(name);
if (sd.list_bos != null && sd.list_bos.size() >= maxBulkSize){
adapter.storeRecord(sd.list_bos.getBuffer(), sd.list_bos.size());
sd.list_bos = null;
}
if (sd.list_bos == null){
sd.list_bos = new DirectBOS(maxBulkSize);
sd.list_dos = new DataOutputStream(sd.list_bos);
// ID of the current trip
sd.list_dos.writeLong(tripStamp);
// Sensor parameter name
sd.list_dos.writeUTF(name);
// Initiate timestamp
sd.list_dos.writeByte(0xFE);
sd.list_dos.writeLong(timeStamp);
// Initiate interval value
sd.currentInterval = 1 + sd.updateInterval/10;
if (sd.currentInterval > Short.MAX_VALUE)
sd.currentInterval = Short.MAX_VALUE;
sd.list_dos.writeByte(0xFF);
sd.list_dos.writeShort(sd.currentInterval);
// init data
sd.last_ts = timeStamp;
sd.currentAveraged = 0;
sd.averagedNo = 0;
}
long ts_diff = timeStamp-sd.last_ts;
// accumulate values
if (sd.optionAverage){
sd.currentAveraged = (sd.currentAveraged*sd.averagedNo + value)/(sd.averagedNo+1);
sd.averagedNo++;
}else{
sd.currentAveraged = value;
}
if (ts_diff >= sd.updateInterval || ts_diff == 0)
{
int ts_diff_adopted = (int)(ts_diff / sd.currentInterval);
/*
* May happen if sensor reading is delayed because of some issues
* and becomes outside of current coefficient
*/
if (ts_diff_adopted >= 0xFE){
sd.list_dos.writeByte(0xFE);
sd.list_dos.writeLong(sd.last_ts);
ts_diff_adopted = 0;
}
// Write sensor value
sd.list_dos.writeByte(ts_diff_adopted);
sd.list_dos.writeFloat(sd.currentAveraged);
sd.last_ts = timeStamp;
sd.currentAveraged = 0;
sd.averagedNo = 0;
}
} | 8 |
public byte[] getFileData() throws IOException {
byte[] data = source.getPayload();
CRC32 check=new CRC32();
// todo: see how much this crc check is slowing us down
check.update(data);
if(check.getValue() != this.crc32.getValue()) {
throw new IOException("CRC mismatch reloading file");
}
return data;
} | 1 |
public final void keyPressed(int keyCode)
{
switch (keyCode)
{
case (KEY_UP):
facing = NORTH;
break;
case (KEY_DOWN):
facing = SOUTH;
break;
case (KEY_LEFT):
facing = WEST;
break;
case (KEY_RIGHT):
facing = EAST;
break;
case (KEY_DELETE):
this.damageEntity(Tools.randPercent());
break;
}
} | 5 |
public static synchronized String[] getAzubuStreamList() {
//TODO ensure these streams are loaded up via text file
azubuStream.areStreamsUp();
ArrayList<String> streamList = AzubuStream.getStreamList(); //ids for stream
ArrayList<String> streamName = AzubuStream.getStreamName(); //name for streamer
ArrayList<Boolean> streamAlive = AzubuStream.getStreamAlive(); //whether the stream is up or not
ArrayList<String> finalList = new ArrayList<>();
ArrayList<String> onlineList = new ArrayList<>();
ArrayList<String> offlineList = new ArrayList<>();
try {
for(int i = 0; i < streamList.size(); i++) {
//checks if streamer is on
if (streamAlive.get(i)) {
onlineList.add(streamName.get(i) +" (ONLINE)");
} else {
offlineList.add(streamName.get(i));
}
}
} catch (Exception ignored) {
//multi threading can crash it here when adding/removing streams!
}
Collections.sort(onlineList);
Collections.sort(offlineList);
finalList.addAll(onlineList);
finalList.addAll(offlineList);
return finalList.toArray(new String[finalList.size()]);
} | 3 |
private void setPesoLlaveEntera(int capa, int neurona, int llave, double valor){
switch (llave) {
case 0:
this.setPeso(capa, neurona, THRESHOLD, valor);
break;
case 1:
this.setPeso(capa, neurona, EMBARAZOS, valor);
break;
case 2:
this.setPeso(capa, neurona, CONCENTRACION_GLUCOSA, valor);
break;
case 3:
this.setPeso(capa, neurona, PRESION_ARTERIAL, valor);
break;
case 4:
this.setPeso(capa, neurona, GROSOR_TRICEPS, valor);
break;
case 5:
this.setPeso(capa, neurona, INSULINA, valor);
break;
case 6:
this.setPeso(capa, neurona, MASA_CORPORAL, valor);
break;
case 7:
this.setPeso(capa, neurona, FUNCION, valor);
break;
case 8:
this.setPeso(capa, neurona, EDAD, valor);
break;
}
} | 9 |
@Test
public void testConcurrency1() {
final int clientThreadCount = 5;
int total = 0;
int count = 0;
for (int i = 0; i < mServerCount; i++) {
try {
mDhtClientArray[i].purge();
} catch (RemoteException e) {
e.printStackTrace();
System.out.println("dhtClient: " + e.getMessage());
}
}
ClientThreadExperiment1[] clientThreadArray = new ClientThreadExperiment1[clientThreadCount];
for (int i = 0; i < clientThreadCount; i++) {
try {
clientThreadArray[i] = new ClientThreadExperiment1(i, i * 1000 + 1, (i + 1) * 1000 + 1);
} catch (Exception e) {
e.printStackTrace();
}
clientThreadArray[i].start();
}
for (int i = 0; i < clientThreadCount; i++) {
try {
clientThreadArray[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < mServerCount; i++) {
try {
count = mDhtClientArray[i].count();
total += count;
System.out.println("DHTServer[" + (i + 1) + "] count " + count);
} catch (RemoteException e) {
e.printStackTrace();
System.out.println("dhtClient: " + e.getMessage());
}
}
assertTrue(total == 0);
} | 8 |
private void handleGameStatusUpdate(GameStatusUpdateEvent event) {
if (event.getStatus() == Status.DRAW || event.getStatus() == Status.OVER) {
this.startNewGame();
}
} | 2 |
@Override
public boolean checkLegal(String prev_pos, String new_pos)
{
String convert_old_pos = CUtil.pos_Finder(prev_pos);
String convert_new_pos = CUtil.pos_Finder(new_pos);
int pfile = Integer.parseInt(convert_old_pos.substring(0,1));
int prank = Integer.parseInt(convert_old_pos.substring(1));
int nfile = Integer.parseInt(convert_new_pos.substring(0,1));
int nrank = Integer.parseInt(convert_new_pos.substring(1));
if(Math.abs(pfile-nfile)==1&&Math.abs(prank-nrank)==2)
{
return true;
}
if(Math.abs(pfile-nfile)==2&&Math.abs(prank-nrank)==1)
{
return true;
}
return false;
} | 4 |
public double getHealth() {
return health;
} | 0 |
public void insertMedicineData(Medicine medicine) throws SQLException {
try {
databaseConnector = medicineConnector.getConnection();
SQLQuery = "INSERT INTO familydoctor.medicine " + "VALUES(?,?,?,?,?,?,?)";
PreparedStatement preparedStatement = databaseConnector.prepareStatement(SQLQuery);
preparedStatement.setLong(1, 0);
preparedStatement.setLong(2, medicine.getBarcodeNumber());
preparedStatement.setString(3, medicine.getMedicineName());
preparedStatement.setString(4, medicine.getMedicineBrand());
preparedStatement.setDouble(5, medicine.getPrice());
preparedStatement.setInt(6, medicine.getQuantity());
preparedStatement.setString(7, medicine.getSupplier());
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage() + " error");
} finally {
if (stmnt != null) {
stmnt.close();
}
if (databaseConnector != null) {
databaseConnector.close();
}
}
} | 3 |
public void checkCollisions() {
Rectangle rBase = base.getBounds();
for (Enemy e: getEnemyList()){
Rectangle rEnemy = e.getBounds();
if(rEnemy.intersects(rBase)){
doOnCollisions(e);
}
}
} | 2 |
public void loadFromFile(String filename)
{
// Detect FILE Format
String getExtension=filename.toLowerCase();
String extension="NONE";
if (getExtension.contains(".jpg")||getExtension.contains(".jpeg"))
{
extension="JPG";
}
else if (getExtension.contains(".png"))
{
extension="PNG";
}
else
{
System.out.println("Invalid File Format for File '"+filename+"'");
}
// Load the actual Texture
try
{
this.texture=TextureLoader.getTexture(extension,ResourceLoader.getResourceAsStream(filename));
}
catch (IOException e)
{
System.out.println("File '"+filename+"' could not be found!");
}
} | 4 |
public CommandState getCommandState(String uniqueID)
{
if(currentCommand != null && currentCommand.transactionID.equals(uniqueID))
{
return CommandState.RUNNING;
}
synchronized (toProcessCommands)
{
for(CommandRequestInfo commReq:toProcessCommands)
{
if(commReq.transactionID.equals(uniqueID))
{
return CommandState.INQUEUE;
}
}
}
synchronized (commandResults)
{
for(CommandResponseInfo comRes:commandResults.values())
{
if(comRes.transactionID.equals(uniqueID))
{
return CommandState.RESPONSE_READY;
}
}
}
return CommandState.UNKNOWN;
} | 6 |
@Override
public void update(Graphics g) {
if (seleccionado) {
g.drawRect(x, y, Longitud_Casilla, Longitud_Casilla);
g.fillRect(x, y, Longitud_Casilla, Longitud_Casilla);
} else {
g.drawRect(x, y, Longitud_Casilla, Longitud_Casilla);
}
switch (tipo) {
case 'J':
g.drawImage(jugador_uno, x, y, null);
break;
case 'H':
g.drawImage(jugador_dos, x, y, null);
break;
case 'E':
g.drawImage(enemigo, x, y, null);
break;
case 'P':
g.drawImage(pared, x, y, null);
break;
case 'V':
g.drawImage(piso, x, y, null);
break;
case 'F':
g.drawImage(premio, x, y, null);
break;
case 'M':
g.drawImage(fin, x, y, null);
break;
}
} | 8 |
public void onPlayerDamageBlock(int par1, int par2, int par3, int par4)
{
syncCurrentPlayItem();
if (blockHitDelay > 0)
{
blockHitDelay--;
return;
}
if (field_78779_k.func_77145_d())
{
blockHitDelay = 5;
netClientHandler.addToSendQueue(new Packet14BlockDig(0, par1, par2, par3, par4));
func_78744_a(field_78776_a, this, par1, par2, par3, par4);
return;
}
if (par1 == currentBlockX && par2 == currentBlockY && par3 == currentblockZ)
{
int i = field_78776_a.field_71441_e.getBlockId(par1, par2, par3);
if (i == 0)
{
isHittingBlock = false;
return;
}
Block block = Block.blocksList[i];
curBlockDamageMP += block.func_71908_a(field_78776_a.field_71439_g, field_78776_a.field_71439_g.worldObj, par1, par2, par3);
if (stepSoundTickCounter % 4F == 0.0F && block != null)
{
field_78776_a.sndManager.playSound(block.stepSound.getStepSound(), (float)par1 + 0.5F, (float)par2 + 0.5F, (float)par3 + 0.5F, (block.stepSound.getVolume() + 1.0F) / 8F, block.stepSound.getPitch() * 0.5F);
}
stepSoundTickCounter++;
if (curBlockDamageMP >= 1.0F)
{
isHittingBlock = false;
netClientHandler.addToSendQueue(new Packet14BlockDig(2, par1, par2, par3, par4));
onPlayerDestroyBlock(par1, par2, par3, par4);
curBlockDamageMP = 0.0F;
prevBlockDamageMP = 0.0F;
stepSoundTickCounter = 0.0F;
blockHitDelay = 5;
}
field_78776_a.field_71441_e.func_72888_f(field_78776_a.field_71439_g.entityId, currentBlockX, currentBlockY, currentblockZ, (int)(curBlockDamageMP * 10F) - 1);
}
else
{
clickBlock(par1, par2, par3, par4);
}
} | 9 |
@Override
public void update() {
if ((modify.get(PhysicsComponent.class)).getDirection() != Direction.DOWN) {
switch ((modify.get(PhysicsComponent.class)).getDirection()) {
case DOWN:
setCurrentAnimation("down_walk");
break;
case UP:
setCurrentAnimation("up_walk");
break;
case LEFT:
setCurrentAnimation("left_walk");
break;
case RIGHT:
setCurrentAnimation("right_walk");
break;
default:
setCurrentAnimation("default");
break;
}
}
} | 5 |
private void setOutliers() {
_minValue = Double.MAX_VALUE;
_maxValue = Double.MIN_VALUE;
_totalCount = 0;
_totalValue = 0d;
for (DMemeList dml : _grid) {
if (dml.Min() != null && dml.Max() != null) {
if (_minValue == null) {
_minValue = dml.Min();
}
if (_maxValue == null) {
_maxValue = dml.Max();
}
_minValue = (dml.Min() < _minValue) ? dml.Min() : _minValue;
_maxValue = (dml.Max() > _maxValue) ? dml.Max() : _maxValue;
}
_totalCount += dml.Counts();
_totalValue += dml.Sum() != null ? dml.Sum() : 0d;
}
} | 8 |
private boolean checaTipoRetornoFuncao(String tipoDoRetorno) {
if(!listaDeBlocos.isEmpty()){
for(int i=0 ; i< listaDeBlocos.size();i++){
String [] tabela = listaDeBlocos.get(i).split("~");
String ehFuncao = tabela[0];
if(ehFuncao.equals("Funcao")){
String nomeFuncao = tabela[1].split(";")[0];
String tipoFuncao = tabela[1].split(";")[1];
if(nomeFuncao.equals(tipoDoToken[1])){
if(tipoFuncao.equals(tipoDoRetorno)){
return true;
}
}
}
}
}
return false;
} | 5 |
public final WaiprParser.inval_return inval() throws RecognitionException {
WaiprParser.inval_return retval = new WaiprParser.inval_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token set68=null;
CommonTree set68_tree=null;
try { dbg.enterRule(getGrammarFileName(), "inval");
if ( getRuleLevel()==0 ) {dbg.commence();}
incRuleLevel();
dbg.location(61, 0);
try {
// C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:61:7: ( ( ID | NUMBER | TEXT ) )
dbg.enterAlt(1);
// C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:
{
root_0 = (CommonTree)adaptor.nil();
dbg.location(61,7);
set68=input.LT(1);
if ( input.LA(1)==ID||input.LA(1)==NUMBER||input.LA(1)==TEXT ) {
input.consume();
adaptor.addChild(root_0, (CommonTree)adaptor.create(set68));
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
dbg.recognitionException(mse);
throw mse;
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
dbg.location(61, 28);
}
finally {
dbg.exitRule(getGrammarFileName(), "inval");
decRuleLevel();
if ( getRuleLevel()==0 ) {dbg.terminate();}
}
return retval;
} | 6 |
public void paint(Graphics g) {
if (showingMessage) {
if (showMessageCount <= showMessage) {
g.setColor(Color.WHITE);
g.setFont(font);
g.drawString(message, 25, 350);
showMessageCount++;
} else {
showingMessage = false;
}
}
} | 2 |
@Override
public YamlPermissionOp getOP() throws DataLoadFailedException {
checkCache(PermissionType.OP, "op");
return (YamlPermissionOp) cache.get(PermissionType.OP).get("op");
} | 0 |
public PixImage boxBlur(int numIterations) {
// Replace the following line with your solution.
int i;
PixImage blureven = new PixImage(this);
PixImage blurodd = new PixImage(this);
for (i = 0; i < numIterations; i++) {
if (i % 2 == 0) {
blurodd = blureven.boxBluronce();
} else {
blureven = blurodd.boxBluronce();
}
}
if (i % 2 == 0) {
return blureven;
} else {
return blurodd;
}
} | 3 |
public void itemStateChanged (ItemEvent evt)
{
if (evt.getSource() == cbmi100)
{
appParent.intImageSizePalette = appParent.intImageOriginalSize;
cbmi100.setState(true);
cbmi75.setState(false);
cbmi50.setState(false);
cbmi25.setState(false);
} else if (evt.getSource() == cbmi75)
{
appParent.intImageSizePalette = (appParent.intImageOriginalSize * 3)/4;
cbmi100.setState(false);
cbmi75.setState(true);
cbmi50.setState(false);
cbmi25.setState(false);
} else if (evt.getSource() == cbmi50)
{
appParent.intImageSizePalette = appParent.intImageOriginalSize/2;
cbmi100.setState(false);
cbmi75.setState(false);
cbmi50.setState(true);
cbmi25.setState(false);
} else if (evt.getSource() == cbmi25)
{
appParent.intImageSizePalette = appParent.intImageOriginalSize/4;
cbmi100.setState(false);
cbmi75.setState(false);
cbmi50.setState(false);
cbmi25.setState(true);
}
appParent.imgMapPalette = appParent.imgOriginalMap.getScaledInstance(-1,appParent.intImageSizePalette,Image.SCALE_DEFAULT);
try
{
MediaTracker mdtTracker = new MediaTracker(appParent.frame);
mdtTracker.addImage(appParent.imgMapPalette,0);
mdtTracker.waitForAll();
}catch(Exception e)
{
System.err.println("Error while waiting for images: "+e.toString());
}
int intX = 25 * appParent.intImageSizePalette;
int intY = ((appParent.numMapImages / 25) + 1) * appParent.intImageSizePalette;
setSize(new java.awt.Dimension(intX+(getInsets().left+getInsets().right), intY+(getInsets().top+getInsets().bottom)));
pnlGraphics.setSize(new java.awt.Dimension(intX, intY));
if (appParent.imgPalette != null)
appParent.imgPalette.flush();
appParent.imgPalette = appParent.frmPalette.pnlGraphics.createImage(intX, intY);
appParent.gD_p = appParent.imgPalette.getGraphics();
appParent.g_p = appParent.frmPalette.pnlGraphics.getGraphics();
appParent.update();
appParent.paint(appParent.g);
} | 6 |
public boolean checkComplete() {
int count = 0;
//Check if all answers entered
for(int i=0;i<3;i++) {
for(int n=0;n<3;n++) {
for(int t=0;t<3;t++) {
for(int e=0;e<3;e++) {
if(grid[i][n][t][e].getText().equals("")) {
grid[i][n][t][e].setBackground(Color.RED);
count++;
}
}
}
}
}
repaint();
if(count > 0) {return false;}
else {return true;}
} | 6 |
public ArrayList<Integer> findSubstring(String S, String[] L) {
// Start typing your Java solution below
// DO NOT write main() function
if(L==null || L.length==0) return null;
int n = L.length, m = L[0].length(), l=S.length();
ArrayList<Integer> res = new ArrayList<Integer>();
Map<String,Integer> covered = new HashMap<String,Integer>();
for(int j=0;j<n;j++){
if(covered.containsKey(L[j])){
covered.put(L[j],covered.get(L[j])+1);
}else{
covered.put(L[j], 1);
}
}
int i=0;
while(l-i>=n*m){
Map<String, Integer> temp = new HashMap<String, Integer>(covered);
for(int j=0;j<n;j++){
String testStr = S.substring(i+j*m,i+(j+1)*m);
if(temp.containsKey(testStr)){
if(temp.get(testStr)-1==0)
temp.remove(testStr);
else
temp.put(testStr,temp.get(testStr)-1);
}else
break;
}
if(temp.size()==0) res.add(i);
i++;
}
return res;
} | 9 |
protected Date parseApproximateDate(String[] words, int code)
throws MalformedDateException {
int qualifier = Date.EXACT;
switch (code) {
case ABOUT:
qualifier = Date.ABOUT;
break;
case CALCULATED:
qualifier = Date.CALCULATED;
break;
case ESTIMATED:
qualifier = Date.ESTIMATED;
break;
}
return parsePlainDate(words, 1, 0, qualifier);
} | 3 |
public String[] itemNames(){
if(!this.dataEntered)throw new IllegalArgumentException("no data has been entered");
String[] ret = new String[this.nItems];
for(int i=0; i<this.nItems; i++)ret[i] = this.itemNames[i];
return ret;
} | 2 |
private void altaCuenta (){
DefaultMutableTreeNode node = (DefaultMutableTreeNode) JTreeConta.getLastSelectedPathComponent();
Cuenta loadcuenta = null;
if (node == null){
mensajeError("Primero debe seleccionar una Cuenta.");
}
else{
Object nodeInfo = node.getUserObject();
loadcuenta = (Cuenta) nodeInfo;
}
boolean eligio = eligioCuenta();
if ((eligio)&&((loadcuenta!=null)&&(!loadcuenta.isImputable_C()))){
habilitarOperaciones(false);
limpiarPanelOperacion ();
verPanelOperacion(true);
mensajeError(" ");
jLabel9.setText("Alta de nueva Cuenta:");
this.operacion = "ALTA";
node = (DefaultMutableTreeNode) JTreeConta.getLastSelectedPathComponent();
if (node != null) //Nothing is selected.
{
jTextField4.requestFocus();
int id_padre = Integer.parseInt(jTextField5.getText());
String plan_padre = jTextField2.getText();
if (this.hayLugarEnPlan(id_padre, plan_padre)){
JTreeConta.setEnabled(false);
jTextField3.setText(this.codigoPlanDisponible(id_padre,plan_padre));
}
else{
habilitarOperaciones(true);
limpiarPanelOperacion ();
verPanelOperacion(false);
mensajeError("Se llegó al límite de la Cuenta (9 ó 99), rediseñe su Plan de Cta.");
}
}
}
else{
if (!eligio){
mensajeError("Primero debe seleccionar una Cuenta.");
}
else{
mensajeError("Para AGREGAR una CUENTA debe SELECCIONAR un TÍTULO");
}
}
} | 7 |
@Override
public void map(String key, String value, Context context) {
if(value != null && value.length() > 0 && value.charAt(0) != '#'){
String[] fields = value.split("\t");
if(fields.length == 2){
String inNode = fields[1];
context.write(inNode,"1");
}
}
} | 4 |
public int highScore()
{
return high(0);
} | 0 |
public static boolean divide() {
if ( !popTwo() ) return false;
if ( x == 0 ) {
System.out.println("Cannot divide by 0.");
calcStack.push(y);
calcStack.push(x);
return false;
}
else {
double result = y / x;
pushResult(result);
}
return true;
} | 2 |
public void generateAmbit(String source, String word) {
for (Place p : places) {
int start = p.getLocation() - 60;
int end = p.getLocation() + 60;
while (start > 0 && source.charAt(start) != ' ') { // jump to space or string start
start--;
}
start = start < 0 ? 0 : start;
end = source.indexOf(' ', end);
end = end == -1 ? source.length() : end; // jump to space or string end
String ambit = source.substring(start, end).replace(" " + word + " ", "<b> " + word + " </b>");
if (ambit.startsWith(word)) {
ambit = "<b>" + word + "</b>" + ambit.substring(word.length());
} else if (ambit.endsWith(word)) {
ambit = ambit.substring(0, ambit.length() - word.length() ) + "<b>" + word + "</b>";
}
p.setAmbit(ambit);
}
hasAmbit = true;
} | 7 |
public synchronized void closeEntityManagerFactory() {
if (emf != null) {
emf.close();
emf = null;
if (DEBUG)
System.out.println("n*** Persistence finished at " + new java.util.Date());
}
} | 2 |
@Override
public String getDbConnString() {
return dbconnstring;
} | 0 |
public static void loadFromPreferences() {
clearRecents();
Preferences prefs = Preferences.getInstance();
prefs.resetIfVersionMisMatch(PREFS_MODULE, PREFS_VERSION);
for (int i = 0; i < MAX_RECENTS; i++) {
String path = prefs.getStringValue(PREFS_MODULE, Integer.toString(i));
if (path == null) {
break;
}
addRecent(PathUtils.getFile(PathUtils.normalizeFullPath(path)));
}
} | 2 |
public static ItemInfo itemByString(String string) {
// int
Pattern pattern = Pattern.compile("(?i)^(\\d+)$");
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
int id = Integer.parseInt(matcher.group(1));
return itemById(id);
}
// int:int
matcher.reset();
pattern = Pattern.compile("(?i)^(\\d+):(\\d+)$");
matcher = pattern.matcher(string);
if (matcher.find()) {
int id = Integer.parseInt(matcher.group(1));
short type = Short.parseShort(matcher.group(2));
return itemById(id, type);
}
// name
matcher.reset();
pattern = Pattern.compile("(?i)^(.*)$");
matcher = pattern.matcher(string);
if (matcher.find()) {
String name = matcher.group(1);
return itemByName(name);
}
return null;
} | 3 |
public SynthesisFilter(int channelnumber, float factor, float[] eq0)
{
if (d==null)
{
d = load_d();
d16 = splitArray(d, 16);
}
v1 = new float[512];
v2 = new float[512];
samples = new float[32];
channel = channelnumber;
scalefactor = factor;
setEQ(eq);
//setQuality(HIGH_QUALITY);
reset();
} | 1 |
public void getPorts(String value, String type) {
ArrayList<String[]> data = new ArrayList<String[]>();
Vector<String[]> target = model.getCachedData();
int index = 0;
//no port case b/c default of index is 0.
switch (type) {
case "protocol":
index = 1;
break;
case "name":
index = 2;
break;
case "description":
index = 3;
break;
}
for (int i = 0; i < target.size(); i++)
if (index < 3 ? target.get(i)[index].equals(value) : target.get(i)[index].toLowerCase().contains(value))
data.add(target.get(i));
model.loadData(data);
} | 6 |
public void run(){
if (mode==1){
ready=false;
kill=false;
this.open(filename,auIndex);
}
else {
while(true){
ready=false;
kill=false;
if(mode==2){
this.open(filename,auIndex);
}
if(kill) break;
}
}
} | 4 |
private void postPlugin(boolean isPing) throws IOException {
// Server software specific section
PluginDescriptionFile description = plugin.getDescription();
String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled
String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion();
int playersOnline = Bukkit.getServer().getOnlinePlayers().length;
// END server software specific section -- all code below does not use any code outside of this class / Java
// Construct the post data
final StringBuilder data = new StringBuilder();
// The plugin's description file containg all of the plugin data such as name, version, author, etc
data.append(encode("guid")).append('=').append(encode(guid));
encodeDataPair(data, "version", pluginVersion);
encodeDataPair(data, "server", serverVersion);
encodeDataPair(data, "players", Integer.toString(playersOnline));
encodeDataPair(data, "revision", String.valueOf(REVISION));
// New data as of R6
String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
encodeDataPair(data, "osname", osname);
encodeDataPair(data, "osarch", osarch);
encodeDataPair(data, "osversion", osversion);
encodeDataPair(data, "cores", Integer.toString(coreCount));
encodeDataPair(data, "online-mode", Boolean.toString(onlineMode));
encodeDataPair(data, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
encodeDataPair(data, "ping", "true");
}
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
connection.setDoOutput(true);
// Write the data
final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data.toString());
writer.flush();
// Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final String response = reader.readLine();
// close resources
writer.close();
reader.close();
if (response == null || response.startsWith("ERR")) {
throw new IOException(response); //Throw the exception
}
} | 5 |
public void start() {
VoteFrame stemFrame = new VoteFrame(this);
ResultJFrame localUitslagJFrame = new ResultJFrame(this);
localUitslagJFrame.setVisible(true);
stemFrame.setVisible(true);
this.uitslagJFrame = localUitslagJFrame;
this.voteFrame = stemFrame;
boolean running = true;
while (running) {
String line = readString("Wat wil je doen?");
String[] words = line.split(" ");
if (words.length == 3 && words[0].equals("ADD") && words[1].equals("PARTY")) {
this.voteMachine.addParty(words[2]);
} else if (words.length == 1 && words[0].equals("PARTIES")) {
this.voteMachine.getParties();
} else if (words.length == 1 && words[0].equals("EXIT")) {
running = false;
} else {
print("Unknown command");
}
}
} | 8 |
public void startupMapHook() {
super.startupMapHook();
ModeController mc = getController();
MindMap model = getController().getMap();
if (Tools.safeEquals(getResourceString("file_type"), "user")) {
if (model == null)
return; // there may be no map open
if ((model.getFile() == null) || model.isReadOnly()) {
if (mc.save()) {
export(model.getFile());
return;
} else
return;
} else
export(model.getFile());
} else {
File saveFile = chooseFile();
if (saveFile == null) {
// no file.
return;
}
try {
mTransformResultWithoutError = true;
String transformErrors = transform(saveFile);
if (transformErrors != null) {
JOptionPane.showMessageDialog(null,
getResourceString(transformErrors), "Freemind",
JOptionPane.ERROR_MESSAGE);
mTransformResultWithoutError = false;
} else {
if (Tools
.safeEquals(getResourceString("load_file"), "true")) {
getController().getFrame().openDocument(
Tools.fileToUrl(saveFile));
}
}
} catch (Exception e) {
Resources.getInstance().logException(e);
mTransformResultWithoutError = false;
}
}
} | 9 |
@Override
public boolean okMessage(Environmental host, CMMsg msg)
{
if((((msg.target()==affected)&&(affected instanceof Item))
||(msg.target() instanceof Item)&&(affected instanceof MOB)&&(((MOB)affected).isMine(msg.target())))
&&(msg.targetMinor()==CMMsg.TYP_WATER))
{
if(!dontbother.contains(msg.target())) // this just makes it less spammy
{
final Room R=CMLib.map().roomLocation(affected);
dontbother.add(msg.target());
if(R!=null)
R.show(msg.source(),affected,CMMsg.MSG_OK_VISUAL,L("<T-NAME> resist(s) the oxidizing affects."));
}
return false;
}
return super.okMessage(host,msg);
} | 8 |
private void isLegal() {
if ((null == binaryLogicalOperator)) {
throw new IllegalStateException("Operator cannot be null.");
} else if (((null == validatorLHS) || (null == validatorRHS))) {
throw new IllegalStateException("Atleast one validator must be set for a compound validator.");
}
} | 3 |
public static boolean checkRunButton() {
File file = new File(outputDirField.getText());
if (!file.isAbsolute()) {
file = file.getAbsoluteFile();
}
if (checkFile(file) && (!file.exists() || file.isDirectory())) {
updateRunButton(true);
return true;
} else {
updateRunButton(false);
return false;
}
} | 4 |
public Command scanInput() {
Scanner scanner = new Scanner(System.in);
input = scanner.nextLine();
input = input.toLowerCase();
scanner.close();
Command command = new Command();
if (input.contains("zug")) {
if(this.zugConverter(input)==null){
command.setCommand(CommandConst.ERR);
}else{
String[] values = this.zugConverter(input);
command.setCommand(CommandConst.ZUG);
command.setValues(values);
}
return command;
} else if(input.contains("exit")){
command.setCommand(CommandConst.EXIT);
return command;
} else if(input.contains("ablage")){
command.setCommand(CommandConst.ABL);
return command;
} else if(input.contains("neues spiel")){
command.setCommand(CommandConst.NEW);
return command;
} else if(input.contains("kurze rochade")){
command.setCommand(CommandConst.RS);
return command;
}else if(input.contains("lange rochade")){
command.setCommand(CommandConst.RL);
return command;
} else{
System.out.println("Input nicht erkannt!");
return null;
}
} | 7 |
@SuppressWarnings("unchecked")
@Override
public double getScore(Object userAnswer) {
if (userAnswer == null)
return 0;
ArrayList<String> ans = (ArrayList<String>) userAnswer;
ArrayList<String> trueAns = (ArrayList<String>) answer;
ArrayList<String> ques = (ArrayList<String>) question;
int matches = 0;
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < trueAns.size(); j++) {
if (ans.get(i).equals(trueAns.get(j))) {
matches++;
break;
}
}
}
return score * ((ques.size()-1) - ans.size() - trueAns.size() + 2*matches) / (ques.size()-1);
} | 4 |
private void checkExpressionIsCorrect(String input) {
String regex = "(\\s*\\d+\\s*[\\+\\-\\*\\/]\\s*){1,}\\d+\\s*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (!matcher.matches()) {
int failPosition = getFailPosition(pattern, input);
throw new IllegalArgumentException(failPosition + "");
}
} | 1 |
public static void incorporateFirstInputParameter(MethodSlot method) {
{ List parametertypespecs = method.methodParameterTypeSpecifiers();
StandardObject firstargtype = ((StandardObject)(parametertypespecs.first()));
if (!method.methodFunctionP) {
if (parametertypespecs.emptyP()) {
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Stella.signalTranslationError();
if (!(Stella.suppressWarningsP())) {
Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR);
{
Stella.STANDARD_ERROR.nativeStream.println();
Stella.STANDARD_ERROR.nativeStream.println(" Method has no input parameters, converting it into a function.");
}
;
}
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
method.methodFunctionP = true;
return;
}
else if ((firstargtype != null) &&
(!Stella_Object.typeP(firstargtype))) {
{ Object old$PrintreadablyP$001 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Stella.signalTranslationError();
if (!(Stella.suppressWarningsP())) {
Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR);
{
Stella.STANDARD_ERROR.nativeStream.println();
Stella.STANDARD_ERROR.nativeStream.println(" Illegal complex argument type for the first method parameter: ");
Stella.STANDARD_ERROR.nativeStream.println(" `" + Stella_Object.deUglifyParseTree(firstargtype) + "'.");
}
;
}
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$001);
}
}
if (Stella_Object.anchoredTypeSpecifierP(firstargtype)) {
method.methodParameterTypeSpecifiers().firstSetter(Stella.SGT_STELLA_UNKNOWN);
firstargtype = Stella.SGT_STELLA_UNKNOWN;
}
}
}
method.slotOwner = ((firstargtype != null) ? StandardObject.typeSpecToBaseType(firstargtype) : null);
}
} | 8 |
public static void main(String [] args) {
int bestK = 0;
int bestJ = 0;
boolean solutionFound = false;
boolean noSmallerSolutionExists = false;
long smallestDifference = Long.MAX_VALUE;
for (int k=1; !solutionFound && !noSmallerSolutionExists; k++) {
long pk = penta(k);
for (int j=1; j<k; j++) {
long pj = penta(j);
if (isPenta(pk-pj) && isPenta(pk+pj)) {
if (!solutionFound) {
// first solution found!
solutionFound = true;
bestK = k;
bestJ = j;
smallestDifference = pk-pj;
} else {
if (pk-pj < smallestDifference) {
bestK = k;
bestJ = j;
smallestDifference = pk-pj;
}
}
}
// last time through k-loop, see if we have found the smallest possible solution
if (j==k-1) {
if (smallestDifference < 3*k-1) noSmallerSolutionExists = true;
}
}
}
System.out.println("k: " + bestK + ", j: " + bestJ + ", P(k): " + penta(bestK) + ", P(j): " + penta(bestJ));
System.out.println(smallestDifference);
} | 9 |
private void drawOval(int rx1, int ry1, int w, int h, int c, boolean fill)
{
if (fill)
{
Ellipse2D e = new Ellipse2D.Double(rx1, ry1, w, h);
for (int x = rx1; x <= rx1 + w; x++)
for (int y = ry1; y <= ry1 + h; y++)
if (e.contains(x, y))
drawPoint(x, y, c);
}
else
{
float yr = ((float) h) / 2, xr = ((float) w) / 2;
double tp = 0.01; // t percison
for (double t = 0; t < Math.PI * 2; t += tp)
{
drawPoint((int) Math.round(rx1 + xr + (xr * Math.cos(t))),
(int) Math.round(ry1 + yr + (yr * Math.sin(t))), c);
}
}
} | 5 |
@Override
public final void visit(final int version, final int access,
final String name, final String signature, final String superName,
final String[] interfaces) {
this.version = version;
this.access = access;
this.name = newClass(name);
thisName = name;
if (ClassReader.SIGNATURES && signature != null) {
this.signature = newUTF8(signature);
}
this.superName = superName == null ? 0 : newClass(superName);
if (interfaces != null && interfaces.length > 0) {
interfaceCount = interfaces.length;
this.interfaces = new int[interfaceCount];
for (int i = 0; i < interfaceCount; ++i) {
this.interfaces[i] = newClass(interfaces[i]);
}
}
} | 6 |
@Override
public int attack(final Glacor glacor, final Entity target) {
target.setAttackedBy(glacor);
glacor.setNextAnimation(new Animation(9955));
int SPEED = 50;
glacor.setNextGraphics(new Graphics(905));
World.sendProjectile(glacor, new WorldTile(target), 963, 60, 40, SPEED,
30, 12, 0);
if (!tile.contains(new WorldTile(target)))
tile.add(new WorldTile(target));
addPossibleTargets(glacor, target);
WorldTasksManager.schedule(new WorldTask() {
@Override
public void run() {
if (tile.get(0) == null) {
tile.clear();
targets.clear();
this.stop();
}
World.sendGraphics(target, new Graphics(899), tile.get(0));
for (Player players : targets) {
if (players == null)
continue;
if (tile.get(0) == null)
continue;
if (players.matches(tile.get(0)) && !glacor.isDead())
players.applyHit(new Hit(glacor,
players.getHitpoints() / 2,
HitLook.REGULAR_DAMAGE));
}
tile.clear();
targets.clear();
this.stop();
}
}, 3);
return 3;
} | 7 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// pour le jour meme
Calendar calendar = Calendar.getInstance();
String monthS = "", dayS = "";
int year = calendar.get(Calendar.YEAR);
int monthI = calendar.get(Calendar.MONTH);
monthI++; // commence à zero
if (monthI<10) monthS+="0";
monthS+=monthI;
int dayI = calendar.get(Calendar.DAY_OF_MONTH);
if (dayI<10) dayS+="0";
dayS+=dayI;
// pour la veille
calendar.add(Calendar.DAY_OF_YEAR, -1);
String monthS2 = "", dayS2 = "";
int year2 = calendar.get(Calendar.YEAR);
int monthI2 = calendar.get(Calendar.MONTH);
monthI2++; // commence à zero
if (monthI2<10) monthS2+="0";
monthS2+=monthI2;
int dayI2 = calendar.get(Calendar.DAY_OF_MONTH);
if (dayI2<10) dayS2+="0";
dayS2+=dayI2;
String scheduleID1 = null, scheduleID2 = null;
boolean day = false, previousDay = false;
int n = 0;
do {
if (!day) {
scheduleID1 = APIRequest.getInstance().updateDailyScheduleRequest(Sport.NBA, year, monthS, dayS);
day = callUpdateScore(scheduleID1);
}
if (!previousDay) {
scheduleID2 = APIRequest.getInstance().updateDailyScheduleRequest(Sport.NBA, year2, monthS2, dayS2);
previousDay = callUpdateScore(scheduleID2);
}
System.out.println("n:"+n+",scheduleID1:"+scheduleID1+",scheduleID2:"+scheduleID2+",day:"+day+",previousDay:"+previousDay);
} while ( (scheduleID1==null || scheduleID2==null) && ++n < tries);
} | 9 |
@Override
protected Value evaluate(ExecutionContext context) throws InterpretationException {
Value val = ((AbsValueNode) this.getChildAt(0)).evaluate(context);
if (val.getType() == VariableType.ARRAYLIST) {
ArrayList<Value> list = (ArrayList<Value>) val.getValue();
list.remove(list.size() - 1);
return new Value(list);
} else if (val.getType() == VariableType.STRING) {
String string = val.toString();
return new Value(string.substring(0, string.length() - 1));
} else if (val.getType() == VariableType.NUMBER) {
String string = val.toString();
return new Value(Double.parseDouble(string.substring(0, string.length() - 1)));
} else
throw new InterpretationException(InterpretationErrorType.INVALID_ARGUMENT, line, null);
} | 3 |
public static void doPrint(List ocFile, List compsub, String PDBID, double x[]){
/* Filename: putative_true
%
% Abstract:
% Print out predicted calcium location and associated ligand group
% version 0.3
% Kun Zhao
% Version: 0.2
% Author: Xue Wang
% Date: 1/25/2008
% Replace version 0.1
% Author: Xue Wang
% Date: Jun., 2007
*/
String fileName = "";
String fileNamePdb="";
String currDirectory = System.getProperty("user.dir");
++predictionCount;
int jj = 0;
int lengthCompsub = compsub.size();
//System.out.println(compsub);
//System.out.println("=========================="+compsub.size());
List resultList = new ArrayList();
List resultListPdb = new ArrayList();
List caList = new ArrayList();
caList = FileOperation.getEntriesAsList(currDirectory+"/outputdata/" + PDBID +"_ca.dat");
String resultLine= "";
DecimalFormat doubleFormat = new DecimalFormat(" ###0.000; -###0.000");
DecimalFormat intFormat = new DecimalFormat(" ######");
String serialString = "", resiNumString = "";
int serialNum=0, resiNum=0;
String ocLine = "", atomName="", resiName="", caLine = "";
String calciumX, calciumY, calciumZ;
fileName = currDirectory+"/predictionResults/" + PDBID +"_site.txt";
fileNamePdb = currDirectory+"/predictionResults/" + PDBID +"_site.pdb";
double caX = 0.0, caY = 0.0, caZ = 0.0;
double minDist = 10000.0, caODist = 0.0;
String closeCa = "";
for (jj = 0; jj < caList.size(); jj++) {
caLine = (String)caList.get(jj);
caX = Double.parseDouble(caLine.split(" +")[5]);
caY = Double.parseDouble(caLine.split(" +")[6]);
caZ = Double.parseDouble(caLine.split(" +")[7]);
if(Dist.distThreeD(caX, caY, caZ, x[0], x[1], x[2]) < minDist){
minDist = Dist.distThreeD(caX, caY, caZ, x[0], x[1], x[2]);
//count for selectivity curve
if (minDist<3.5){
correctPredictionCount++;
}
closeCa = caLine.split(" +")[1];
}
if (caCoordinate1.contains(caLine)==false && Dist.distThreeD(caX, caY, caZ, x[0], x[1], x[2])<3.5){
caCoordinate1.add(caLine);
correctPredictionPocketCount++;
}
if (caCoordinate.contains(caLine)==false){
caCoordinate.add(caLine);
totalPocketCount++;
}
}
for (jj = 0; jj < lengthCompsub; jj++) {
ocLine = (String)ocFile.get(Integer.parseInt((String)compsub.get(jj)));
caODist = caODist + Dist.distThreeD(x[0], x[1], x[2],
Double.parseDouble(ocLine.split(" +")[5]),
Double.parseDouble(ocLine.split(" +")[6]),
Double.parseDouble(ocLine.split(" +")[7]));
} caODist = caODist/lengthCompsub;
for (jj = 0; jj < lengthCompsub; jj++) {
ocLine = (String)ocFile.get(Integer.parseInt((String)compsub.get(jj)));
serialNum = Integer.parseInt(ocLine.split(" +")[1]);
resiNum = Integer.parseInt(ocLine.split(" +")[4]);
atomName = ocLine.split(" +")[2];
resiName = ocLine.split(" +")[3];
serialString = intFormat.format(serialNum);
resiNumString = intFormat.format(resiNum);
calciumX = doubleFormat.format(x[0]);
calciumY = doubleFormat.format(x[1]);
calciumZ = doubleFormat.format(x[2]);
DecimalFormat df = new DecimalFormat("####.## ");
if(jj == 0){
resultLine = (">"+Integer.toString(predictionCount)+" ").substring(0,4)
+ serialString.substring(serialString.length() - 6, serialString.length())
+ " "
+ (atomName + " ").substring(0, 4)
+ " "
+ resiNumString.substring(resiNumString.length() - 4,resiNumString.length())
+ " "
+ (resiName + " ").substring(0, 4)
+ calciumX.substring(calciumX.length() - 8, calciumX.length())
+ calciumY.substring(calciumY.length() - 8, calciumY.length())
+ calciumZ.substring(calciumZ.length() - 8, calciumZ.length())
+ " "
+ (closeCa + " ").substring(0,5)
+ " "
+ df.format(minDist)
+ " "
+ df.format(caODist);
resultList.add(resultLine);
}
else{
resultLine = " "
+ serialString.substring(serialString.length() - 6, serialString.length())
+ " "
+ (atomName + " ").substring(0, 4)
+ " "
+resiNumString.substring(resiNumString.length() - 4,resiNumString.length())
+ " "
+ (resiName + " ").substring(0, 4)
+ calciumX.substring(calciumX.length() - 8, calciumX.length())
+ calciumY.substring(calciumY.length() - 8, calciumY.length())
+ calciumZ.substring(calciumZ.length() - 8, calciumZ.length())
+ " "
+ (closeCa + " ").substring(0,5)
+ " "
+ df.format(minDist)
+ " "
+ df.format(caODist);
resultList.add(resultLine);
}
}
resultList.add("\n");
FileOperation.saveResults(resultList, fileName, "a");
//FileOperation.saveResults(resultList, currDirectory+"/predictionResults/" + "alre_site.txt", "a");
String resultLine1="HETATM CA CA"+" " + resultLine.substring(26, 50);
FileOperation.saveResults(resultLine1, fileNamePdb, "a");
} | 9 |
private ArrayList<String> GetProductiveNonTerminals(ArrayList<String> i_productions)
{
ArrayList<String> res_array = new ArrayList<String>();
for(Rule rule : m_rules)
{
boolean is_productive_rule = true;
for(String str : rule.GetRightPart())
{
if(!i_productions.contains(str))
{
is_productive_rule = false;
break;
}
}
if(is_productive_rule)
res_array.add(rule.GetLeftPart());
}
return res_array;
} | 4 |
@Inject
public UnmarshallerPool(@Named("unmarshalContext") JAXBContext context) {
this.context = context;
} | 0 |
public byte[] readNibbleArray() throws IOException
{
final int size = this.readInt();
final int byteCount = ceilDiv(size, 2);
final byte[] nibbles = new byte[size];
final byte[] data = new byte[byteCount];
this.in.read(data);
for (int nibbleIndex = 0, byteIndex = 0, bitIndex = 1; nibbleIndex < size; nibbleIndex++)
{
int l = bitIndex << 2;
nibbles[nibbleIndex] |= data[byteIndex] >> l & 0xF;
--bitIndex;
if (bitIndex < 0)
{
byteIndex++;
bitIndex = 1;
}
}
return nibbles;
} | 2 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith("")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 7 |
@Override
public void loop() {
switch (step) {
case 0:
if(Motors.movement.isMoving()){
if(Motors.tsf.isPressed()){
Motors.movement.backward();
reset();
step++;
}
}
else{
Motors.movement.forward();
}
break;
case 1:
if (delta()>500){
Motors.movement.stop();
if(!Motors.m1.isMoving()&&!Motors.m2.isMoving())
Motors.movement.rotate(90, false);
Motors.movement.stop();
step++;
}
break;
default:
break;
}
} | 7 |
public int getRap_num() {
return rap_num;
} | 0 |
public void nouveauTour() {
tourEnCours++;
if (tourEnCours >= nbTours) {
Game.gameOver();
}
else {
// RAZ des étapes
etape = 0;
indexJoueurEnCours = 0;
joueurEnCours = this.lstJoueurs.get(indexJoueurEnCours);
// Si le peuple n'a pas de joueur, il doit en choisir un
if (joueurEnCours.getPeuple() == null) {
Game.getInstance().selectionPeuple();
}
Game.getInstance().showTemp(joueurEnCours.getNom() + " attaque !");
miseEnMain();
}
} | 2 |
@Override
public void speak()
{
System.out.println("The poodle says \"arf\"");
} | 0 |
@Override
public boolean accept(CourseRec rec) {
if (!this.active || rec.getCategories().isEmpty())
return true;
for (DescRec r : rec.getCategories())
if (selected.contains(r))
return true;
return false;
} | 4 |
void analyzePacket(Packet packet){
boolean[] isExpanded=new boolean[root.getChildCount()];
for(int i=0;i<root.getChildCount();i++) {
isExpanded[i] = tree.isExpanded(new TreePath(((DefaultMutableTreeNode) root.getChildAt(i)).getPath()));
}
root.removeAllChildren();
DefaultMutableTreeNode node;
for(JSnifferPktDtls analyzer:analyzers){
if(analyzer.isInstance(packet)){
analyzer.getDetails(packet);
node=new DefaultMutableTreeNode(analyzer.getProtocol()+"("+analyzer.getInfo()+")");
root.add(node);
String[] names=analyzer.getPropertyNames();
Object[] values=analyzer.getProperties();
if(names==null) {
continue;
}
for(int j=0;j<names.length;j++){
if(values[j] instanceof Vector){
addNodes(node,names[j],(Vector)values[j]);
}else if(values[j]!=null){
addNode(node,names[j]+": "+values[j]);
}
}
}
}
((DefaultTreeModel)tree.getModel()).nodeStructureChanged(root);
for(int i=0;i<Math.min(root.getChildCount(),isExpanded.length);i++) {
if (isExpanded[i]) {
tree.expandPath(new TreePath(((DefaultMutableTreeNode) root.getChildAt(i)).getPath()));
}
}
} | 9 |
private void updateStatus() {
if (RobotMap.driveTrain_leftRearMotor != null){
Robot.driveTrain.updateStatus();
}
Robot.oi.updateStatus();
if (RobotMap.ratchetClimberRatchet != null){
Robot.ratchetClimber.updateStatus();
}
Robot.climberActuator.updateStatus();
if (Robot.dumper != null) {
Robot.dumper.updateStatus();
}
} | 3 |
public static String getAttributeValue(Node node, String name) {
String results = null;
if(node != null && !isNullOrWhitespace(name) && node instanceof Element) {
NamedNodeMap attrs = node.getAttributes();
if(attrs != null) {
for(int j = 0; j < attrs.getLength(); ++j) {
Attr attr = (Attr)attrs.item(j);
boolean nameNodeMatch = false;
if(attr != null) {
nameNodeMatch = attr.getNodeName().equals(name);
if(!nameNodeMatch) {
nameNodeMatch = attr.getLocalName().equals(name);
}
}
if(nameNodeMatch) {
results = attr.getNodeValue();
break;
}
}
}
}
return results;
} | 8 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.