text stringlengths 14 410k | label int32 0 9 |
|---|---|
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(VtnReporGanancias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VtnReporGanancias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VtnReporGanancias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VtnReporGanancias.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 VtnReporGanancias().setVisible(true);
}
});
} | 6 |
private static void sort(int[] lotto) {
// for (int i = 0; i < lotto.length; i++) {
// for (int j = 0; j < i; j++) {
// if (lotto[i] < lotto[j]) {
// lotto[i] ^= lotto[j];
// lotto[j] ^= lotto[i];
// lotto[i] ^= lotto[j];
// }
// }
// }
for (int i = 0; i < lotto.length - 1; i++) {
for (int j = i + 1; j < lotto.length; j++) {
if (lotto[i] > lotto[j]) {
lotto[i] ^= lotto[j];
lotto[j] ^= lotto[i];
lotto[i] ^= lotto[j];
}
}
}
} | 3 |
@Override
public final void testFailure(Failure failure) throws Exception {
super.testFailure(failure);
selectListener(failure.getDescription()).testFailure(failure);
} | 0 |
public int maxPoints(Point[] points) {
if (points == null)
return 0;
if (points.length < 2)
return points.length;
Map<Double, Integer> table = new HashMap<>();
int dup = 1, max = 0;
for (int i = 0; i < points.length; i++) {
table.clear();
dup = 1;
for (int j = 0; j < points.length; j++) {
if (i == j)
continue;
if (points[i].x == points[j].x && points[i].y == points[j].y) {
dup++;
} else {
double k;
if (points[i].x == points[j].x) {
k = Double.MAX_VALUE;
} else {
k = (points[i].y - points[j].y) * 1.0 / (points[i].x - points[j].x);
}
if (table.containsKey(k)) {
table.put(k, table.get(k) + dup);
} else {
table.put(k, 1 + dup);
}
dup = 1;
max = Math.max(max, table.get(k));
}
max = Math.max(dup, max);
}
}
return max;
} | 9 |
@Override
protected void startGame() {
notifyNewGame();
discardCards();
shuffle();
community.clear();
doAntes();
doBlinds();
doneFlop = false;
doneTurn = false;
doneRiver = false;
dealPlayerCards();
for (int i = 0; i < 5; i++) {
community.add(deck.deal());
}
waitForBets();
if (countPlayers(true, true, false) > 1) {
doneFlop = true;
doDrawRound(players.get((dealer + 1) % numplayers), 1, 1, false);
doBettingRound();
}
if (countPlayers(true, true, false) > 1) {
doneTurn = true;
doBettingRound();
}
if (countPlayers(true, true, false) > 1) {
doneRiver = true;
doBettingRound();
}
if (countPlayers(true, true, false) > 1) {
doShowDown();
} else {
doWinner();
}
for (Player player : players) {
if (player.getCash() <= 0) {
player.setOut();
}
}
notifyEndGame();
doDealerAdvance();
} | 7 |
public AlignedAllocation next() {
// if duration is over, get next start stop
if ((alignment != null && duration <= maxDuration && alignment.startPoint + duration <= intervalsUpperBound) == false) {
this.nextStop();
}
AlignedAllocation ret = new AlignedAllocation();
ret.startPoint = alignment.startPoint;
ret.intervalIndexOfStartPoint = alignment.startValuesIndex;
ret.endPoint = alignment.startPoint + duration;
if (duration == maxDuration || alignment.startPoint + duration == intervalsUpperBound) {
this.nextStop();
nextIsSkipped = true;
return ret;
}
//set next duration to min of duration to upper bound, max duration and next stop end
duration = Math.min(maxDuration, elementaryIntervals.get(currentIntervalOfEnd).getEnd() - alignment.startPoint);
currentIntervalOfEnd++;
return ret;
} | 5 |
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
for (int T=parseInt(in.readLine().trim()),t=0;t<T;t++) {
if(t>0)
sb.append("\n");
in.readLine();
char[] str=in.readLine().trim().toCharArray();
int res=-1;
for(int i=1;i<=str.length&&res==-1;i++)
if(str.length%i==0) {
boolean ws=true;
for(int j=0;j<str.length&&ws;j+=i)
ws=is(str, j, i);
if(ws)
res=i;
}
sb.append(res).append("\n");
}
System.out.print(new String(sb));
} | 8 |
@Override
public void mouseExited(MouseEvent e) {} | 0 |
@Override
public AbstractComponent parse(String string) throws BookParseException {
if (string == null) {
throw new BookParseException("String is null");
}
try {
TextComponent component = (TextComponent) factory
.newComponent(EComponentType.CODE_LINE);
for (String s : string.split("")) {
if (!s.equals("")) {
component.addComponent(new CharacterParser().parse(s));
}
}
return component;
} catch (ComponentException e) {
throw new BookParseException("Code line parsing failed", e);
}
} | 4 |
public static boolean getSortingOrder(String order)
throws StreamParserException {
order = order.toLowerCase();
switch (order) {
case "a":
case "asc":
case "ascending":
return false;
case "":
case "d":
case "desc":
case "descending":
return true;
default:
throw new StreamParserException();
}
} | 7 |
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
if(source.getText().equals("Annuler")){
dispose();
}else{
if(mainPanel.getSelectedComponent().equals(param)){
p.resizeFiguresOnLayer(working_layer, Integer.parseInt(tailleX.getText()), Integer.parseInt(tailleY.getText()));
p.moveFiguresOnLayer(working_layer, Integer.parseInt(originX.getText()), Integer.parseInt(originY.getText()));
}else if(mainPanel.getSelectedComponent().equals(borderColor)){
Color newColor = borderColorCC.getColor();
p.setFigureBorderColor(working_layer, newColor);
}else if(mainPanel.getSelectedComponent().equals(bgColor)){
Color newColor = bgColorCC.getColor();
p.setFigureFillingColor(working_layer, newColor);
}
if(source.getText().equals("OK"))
dispose();
}
} | 5 |
@Override
public <T> List<T> queryPage(String sql, Page page, RowMapper<T> rowMapper, int fetchSize, Object... args) {
int total = queryCount(sql, args);
page.setTotal(total);
if (total <= 0) {
return new ArrayList<T>(0);
}
String pageSql = dialect.getPaginationSql(sql, page);
LOGGER.info("分页查询操作SQL:" + pageSql);
return query(pageSql, rowMapper, fetchSize, args);
} | 1 |
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] a = new int[n];
int[] o = new int[n];
int[] bit = new int[n];
for(int i=0; i<n; i++){
a[i] = Integer.parseInt(st.nextToken());
o[i] = a[i];
update(bit, i+1, 1);
}
int m = Integer.parseInt(br.readLine());
while(m-->0){
st = new StringTokenizer(br.readLine());
if(Integer.parseInt(st.nextToken())==1){
int index = Integer.parseInt(st.nextToken());
int value = Integer.parseInt(st.nextToken());
while(value>0){
if(a[index-1]==0){
int l=1; int r=n;
int realIndex = query(bit, index);
while(l<r){
int mid = (r-l)/2+l;
if(query(bit, mid)>realIndex) r=mid; else l=mid+1;
}
if(query(bit, l)>realIndex){
index = l;
} else{
value = 0;
}
} else{
if(value>=a[index-1]){
value -= a[index-1];
a[index-1] = 0;
update(bit, index, -1);
} else{
a[index-1] -= value;
value = 0;
}
}
}
} else{
int index = Integer.parseInt(st.nextToken());
System.out.println(o[index-1]-a[index-1]);
}
}
} | 9 |
public List<Keyword> getKeywords(Graph graph) {
List<Keyword> keywords = new ArrayList<Keyword>();
Map<String, Double> keys = new TreeMap<String, Double>();
for (Node node : graph.values()) {
keywords.add(new Keyword(node.getKey(), node.getRank()));
}
Collections.sort(keywords);
System.out.println("DBG SIZE1 " + keywords.size());
for (Keyword k : keywords) {
System.out.println("DBG " + k.getValue() + " " + k.getRank());
}
//int lim = (int) (keywords.size() * 0.15);
int lim = keywords.size() / (int) (keywords.size() * 0.05);
for (int i = 0; i < lim; i++) {
keys.put(keywords.get(i).getValue(), keywords.get(i).getRank());
}
System.out.println("DBG SIZE2 " + keys.size());
for (String key : keys.keySet()) {
System.out.println("\tDBG KEYS " + key + " " + keys.get(key));
}
keywords.clear();
for (Sentence sentence : sentences) {
//List<Keyword> kl = sentence.getCollocations(language, keys);
List<Keyword> kl = sentence.getCollocations2(language, keys);
keywords.addAll(kl);
}
// Delete equals elements
List<Keyword> ans = new ArrayList<Keyword>();
for (int i = 0; i < keywords.size(); i++) {
// System.out.println("DBG " + keywordHandleList.get(i).getValue());
boolean eq = false;
for (int j = i + 1; j < keywords.size(); j++) {
if (keywords.get(i).getValue().trim().equals(keywords.get(j).getValue().trim())) {
eq = true;
break;
}
}
if (!eq) {
ans.add(keywords.get(i));
}
}
Collections.sort(ans);
return ans;
} | 9 |
public void removeBet(Block bet) {
Set<Player> betsKeys = bets.keySet();
for(Player key : betsKeys) {
if(bets.get(key).contains(bet))
bets.get(key).remove(bet);
}
} | 2 |
public void setDebt(double debt) {
this.debt = debt;
} | 0 |
public int getNumeroDePrestamos(Usuarios u){
int numero = 0;
PreparedStatement ps;
try {
ps = mycon.prepareStatement(
"SELECT "
+ "COUNT(Usuarios.nombre) as total "
+ "FROM "
+ "Prestamos, Libros, Usuarios "
+ "WHERE "
+ "Prestamos.id_usuario=? "
+ "AND Usuarios.codigo=Prestamos.id_usuario "
+ "AND Prestamos.id_libro = Libros.codigo "
+ "AND Prestamos.estado='pendiente' ");
ps.setString(1, u.getCodigo());
ResultSet rs = ps.executeQuery();
if(rs.next()){
numero = rs.getInt("total");
}
} catch (SQLException ex) {
Logger.getLogger(PrestamosCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
return numero;
} | 2 |
public void tableChanged(TableModelEvent e)
{
/*
* int row = e.getFirstRow(); if (modelToView != null) { int[] mToV
* = getModelToView(); if (row < mToV.length) {
* updateColor(mToV[row], e); } else { updateColor(mToV[row] - 1,
* e); } } else { updateColor(row, e); }
*/
// If we're not sorting by anything, just pass the event along.
if (!isSorting())
{
clearSortingState();
fireTableChanged(e);
return;
}
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
{
cancelSorting();
fireTableChanged(e);
return;
}
// We can map a cell event through to the view without widening
// when the following conditions apply:
//
// a) all the changes are on one row (e.getFirstRow() ==
// e.getLastRow()) and,
// b) all the changes are in one column (column !=
// TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) ==
// NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
//
// Note: INSERT and DELETE events fail this test as they have column
// == ALL_COLUMNS.
//
// The last check, for (modelToView != null) is to see if
// modelToView
// is already allocated. If we don't do this check; sorting can
// become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow() && column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED && modelToView != null)
{
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this, viewIndex, viewIndex,
column, e.getType()));
return;
}
// Something has happened to the data that may have invalidated the
// row order.
clearSortingState();
fireTableDataChanged();
return;
} | 6 |
private FloatQueue computeQueue(String expression, byte averageFlag) {
FloatQueue q = new FloatQueue(model.getTapeLength());
if (expression.startsWith("\""))
expression = expression.substring(1);
if (expression.endsWith("\""))
expression = expression.substring(0, expression.length() - 1);
q.setName(expression);
String str = useSystemVariables(expression);
float result = 0;
float sum = 0;
String s = null;
int n = model.getTapePointer();
for (int k = 0; k < n; k++) {
s = useAtomVariables(str, k);
s = useMoleculeVariables(s, k);
double x = parseMathExpression(s);
if (Double.isNaN(x))
return null;
result = (float) x;
if (averageFlag == 1) {
sum = k == 0 ? result : 0.05f * result + 0.95f * sum;
q.update(sum);
}
else if (averageFlag == 2) {
sum += result;
q.update(sum / (k + 1));
}
else {
q.update(result);
}
}
return q;
} | 7 |
public static void closeStream(Stream self) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(self);
if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_INPUT_FILE_STREAM)) {
{ InputFileStream self000 = ((InputFileStream)(self));
InputFileStream.terminateFileInputStreamP(self000);
}
}
else if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_OUTPUT_FILE_STREAM)) {
{ OutputFileStream self000 = ((OutputFileStream)(self));
OutputFileStream.terminateFileOutputStreamP(self000);
}
}
else if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_INPUT_STRING_STREAM)) {
{ InputStringStream self000 = ((InputStringStream)(self));
InputStringStream.terminateStringInputStreamP(self000);
}
}
else if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_OUTPUT_STRING_STREAM)) {
{ OutputStringStream self000 = ((OutputStringStream)(self));
OutputStringStream.terminateStringOutputStreamP(self000);
}
}
else if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_INPUT_STREAM)) {
{ InputStream self000 = ((InputStream)(self));
InputStream.terminateInputStreamP(self000);
}
}
else if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_OUTPUT_STREAM)) {
{ OutputStream self000 = ((OutputStream)(self));
OutputStream.terminateOutputStreamP(self000);
}
}
else {
}
}
} | 6 |
public String[][] getNColumnDataAraqne(String name, String mgr_ip, String query) {
LogDbClient client = null;
Vector rowSet = new Vector();
Vector row = null;
int colCnt = 0;
try {
client = DBConnectionManager.getInstance().getQueryClient(mgr_ip);
LogCursor cursor = null;
try {
cursor = client.query(query);
logger.debug(cursor.hasNext());
while (cursor.hasNext()) {
Map<String, Object> o = cursor.next();
Set<String> keyset = o.keySet();
colCnt = keyset.size();
row = null;
row = new Vector();
for (String key : keyset) {
row.addElement(o.get(key));
}
rowSet.addElement(row);
}
logger.debug(query);
} catch (IOException e) {
logger.error(e.getMessage() + " : error query => " + query, e);
} finally {
if (cursor != null) {
try {
cursor.close();
} catch (IOException e) {
}
}
DBConnectionManager.getInstance().freeConnection(client);
}
} catch (Exception e) {
// close(con, stmt, rs);
logger.error(e.getMessage() + " : error query => " + query, e);
}
logger.debug(rowSet.size());
String[][] data = new String[rowSet.size()][colCnt];
for (int i = 0; i < data.length; i++) {
row = null;
row = (Vector) rowSet.elementAt(i);
for (int j = 0; j < colCnt; j++) {
if (row.elementAt(j) == null) {
data[i][j] = "-";
} else {
data[i][j] = row.elementAt(j).toString().trim();
}
}
}
return data;
} | 9 |
private static boolean[] primeBoolArray(int limit) {
boolean[] nums = new boolean[limit];
for (int i = 2; i < nums.length; i++)
nums[i] = true;
int nextPrime = 2;
while (nextPrime < nums.length / 2) {
int i = nextPrime;
for (; i < nums.length; i += nextPrime)
nums[i] = false;
nums[nextPrime] = true;
for (int j = nextPrime + 1; j < nums.length; j++) {
if (nums[j] == true) {
nextPrime = j;
break;
}
}
}
return nums;
} | 5 |
@Override
public String toString() {
int spos = 0;
int max = Math.min(start-1, cs.length()-1);
int charCount = 0;
for (int i = 0; i < max + 1 && i < 20; i++) {
char c = cs.charAt(max-i);
if (c == '\r' || (c == '\n' && (max-i-1 < 0 || cs.charAt(max-i-1) != '\r'))) {
if (charCount > 0) break;
} else if (c != '\n') {
spos = max-i;
charCount++;
}
}
return (spos <= max) ? cs.subSequence(spos, max+1).toString() : "";
} | 9 |
@Override
public boolean isBoolean() {
return this == TRUE || this == FALSE;
} | 1 |
public static void rectangle(double x, double y, double halfWidth, double halfHeight) {
if (halfWidth < 0) throw new IllegalArgumentException("half width must be nonnegative");
if (halfHeight < 0) throw new IllegalArgumentException("half height must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
} | 4 |
public void testPieceSetup(){
OthelloPiece[][] test = OthelloBoard.getPieces();
for(int k = 0; k < getP1PiecesX().size(); k++){
if(getM_playerOneColour().equals("Black")){
if(test[getP1PiecesX().get(k)][getP1PiecesY().get(k)].getPieceColour().equals(Piece.OthelloPieceColour.BLACK)){
System.out.println("Right");
System.out.println(getP1PiecesX().get(k) + " " + getP1PiecesY().get(k));
}
}else{
if(test[getP1PiecesX().get(k)][getP1PiecesY().get(k)].getPieceColour().equals(Piece.OthelloPieceColour.WHITE)){
System.out.println("Right");
System.out.println(getP1PiecesX().get(k) + " " + getP1PiecesY().get(k));
}
}
}
System.out.println("PieceCount: " + getP1PiecesX().size());
for(int k2 = 0; k2 < getP2PiecesX().size(); k2++){
if(getM_playerTwoColour().equals("Black")){
if(test[getP2PiecesX().get(k2)][getP2PiecesY().get(k2)].getPieceColour().equals(Piece.OthelloPieceColour.BLACK)){
System.out.println("Right");
System.out.println(getP2PiecesX().get(k2) + " " + getP2PiecesY().get(k2));
}
}else{
if(test[getP2PiecesX().get(k2)][getP2PiecesY().get(k2)].getPieceColour().equals(Piece.OthelloPieceColour.WHITE)){
System.out.println("Right");
System.out.println(getP2PiecesX().get(k2) + " " + getP2PiecesY().get(k2));
}
}
}
System.out.println("PieceCount2: " + getP2PiecesX().size());
} | 8 |
public static void main(String[] args) {
FileReader fr = null;
String Folder=Long.toString(System.nanoTime());
try {
File A=new File("idents.txt");
fr = new FileReader (A);
BufferedReader br = new BufferedReader(fr);
String linea;
ArrayList<String> ListaFiles=new ArrayList<String>();;
while ((linea = br.readLine())!=null)
{
ListaFiles.add(linea);
}
if (args.length==0)
Todo.processLines(ListaFiles, Folder);
else if (args[0].equals("S"))
Sueltos.processLines(ListaFiles,Folder);
else if (args[0].equals("C"))
Unidos.processLines(ListaFiles,Folder);
else if (args[0].equals("T"))
Todo.processLines(ListaFiles,Folder);
br.close();
System.out.println("FIN");
} catch (Exception e) {
e.printStackTrace();
} finally
{
try{
if( null != fr ){
fr.close();
}
}catch (Exception e2){
e2.printStackTrace();
}
}
} | 8 |
public void testMoneyConverter() {
System.out.println("** testMoneyConverter **");
final CycFort currUSD = MoneyConverter.lookupCycCurrencyTerm(Currency.getInstance("USD"));
final BigDecimal amount = BigDecimal.valueOf(50.25);
final CycNaut cycMoney = new CycNaut(currUSD, amount);
final Money javaMoney = new Money(amount, Currency.getInstance("USD"));
try {
assertTrue(MoneyConverter.isCycMoney(cycMoney));
assertEquals(javaMoney, MoneyConverter.parseCycMoney(cycMoney));
assertEquals(cycMoney, MoneyConverter.toCycMoney(javaMoney));
assertEquals(cycMoney, DataType.MONEY.convertJavaToCyc(javaMoney));
assertEquals(javaMoney, DataType.MONEY.convertCycToJava(cycMoney));
} catch (Exception e) {
Assert.fail(e.getMessage());
}
System.out.println("** testMoneyConverter OK **");
} | 1 |
private void btnRecommendMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRecommendMousePressed
if (Manager.getInstance().getCurrentProfile() == null) {
JOptionPane.showMessageDialog(null, "Please load a profile first.");
return;
}
Disc recommendedDisc = FrolfUtil.recommendDiscForBag(Manager.getInstance().getCurrentProfile().getDiscs());
JOptionPane.showMessageDialog(null, "" + recommendedDisc.getName());
} | 1 |
public ArrayList<Move> getPossibleMoves(Loyalty loyalty)
{
ArrayList<Move> possibleMoves = super.getPossibleMoves(loyalty);
ArrayList<Move> realPossibleMoves = new ArrayList<Move>();
for(Move possibleMove : possibleMoves)
{
boolean possible = true;
Game nextGame = new Game(getGame());
Board nextBoard = nextGame.getBoard();
nextBoard.executeMove(possibleMove);
for(Node node : nextBoard.getNodes())
{
Piece checkCandidate = null;
if(node.getPiece() != null && node.getPiece().getLoyalty() != loyalty)
{
checkCandidate = node.getPiece();
}
if(checkCandidate == null)
{
continue;
}
else
{
for(Move move : checkCandidate.getPossibleMoves())
{
for(Node jumped : move.getJumped())
{
if(jumped.getPiece() instanceof King)
{
possible = false;
}
}
}
}
}
if(possible)
{
realPossibleMoves.add(possibleMove);
}
}
return realPossibleMoves;
} | 9 |
boolean findTripod(Board board, int colour) {
// For each hex that has three or more connecting hexes with same colour, add to queue.
PriorityQueue<Hex> queue = new PriorityQueue<Hex>(board.numHexes);
PriorityQueue<Hex> visited = new PriorityQueue<Hex>(board.numHexes);
int i, j, n, numAdj;
Hex currentHex;
Hex[] neighbours;
for (i=0; i<board.rows.length; i++) {
for (j=0; j<board.rows[i].length; j++) {
// Do the following if on colour
if (board.rows[i][j].getColour() == colour) {
numAdj = 0;
currentHex = board.rows[i][j];
neighbours = currentHex.getAdjacent();
// Look at each of its neighbours to see if they are also on colour
for (n=0; n<neighbours.length; n++) {
// null check first
if (neighbours[n] != null) {
if (neighbours[n].getColour() == colour) {
numAdj++;
}
}
}
// If three or more adjacent on colour hexes, add to queue
if (numAdj >= 3) {
queue.add(currentHex);
}
}
}
}
// For each hex in the queue, we trace connecting hexes until we hit an edge or no more connectors.
while (queue.size() != 0) {
currentHex = queue.poll();
neighbours = currentHex.getAdjacent();
if (trace(currentHex, neighbours, colour, board, visited) >= 3) {
return true;
}
}
return false;
} | 9 |
public static CommandLine bindPosix(Options options, String[] args,
Object pojo) throws CLIOptionBindingException {
CommandLineParser parser = new PosixParser();
CommandLine cli = null;
try {
cli = parser.parse(options, args);
Class<? extends Object> clazz = pojo.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(CLIOptionBinding.class)) {
if(field.isAccessible()){
bindByField( pojo, cli, field);
}else{
Method m= getSetter( clazz, field);
if(m!=null){
bindByMethod( pojo, cli, m, field
.getAnnotation(CLIOptionBinding.class));
}
}
}
}
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(CLIOptionBinding.class)
&& method.getParameterTypes().length == 1) {
bindByMethod( pojo, cli, method, null);
}
}
} catch (Throwable e) {
throw new CLIOptionBindingException(
"Failed to bind cli option to POJO:" + pojo.toString(), e);
}
return cli;
} | 9 |
public String getWord() {
do {
boolean currentWordIDisIntList = false;
currentWordID = getRandomWordID();
if (passedWordsIdList.size() > 0 && passedWordsIdList.size() != wordList.size()) {
for (Integer id : passedWordsIdList) {
if (id == currentWordID) {
currentWordIDisIntList = true;
break;
}
}
}
else {
System.out.println("ELSE");
break;
}
if (!currentWordIDisIntList) {
break;
}
}
while (true);
passedWordsIdList.add(currentWordID);
return wordList.get(currentWordID);
} | 6 |
private long updateRewrite(Master master, File f, Location accessLoc, int rewriteCount) {
MasterMeta fm = null;
if (master.map.containsKey(f.getId())) {
fm = master.map.get(f.getId());
} else {
fm = new MasterMeta(f);
master.map.put(f.getId(), fm);
}
int cCount = master.clusters.size();
int writes = 0;
long maxDelay = -1;
for (int i = 0; i < cCount && writes < rewriteCount; i++) {
Cluster cluster = master.clusters.get(i);
if (fm.instances.contains(cluster) || !cluster.isHealthy()) {
continue;
}
FileWrite fw = cluster.write(f, NODE_PER_CLUSTER_WRITE_REDUNDANCY);
double distance = accessLoc.distance(cluster.getLocation());
if (fw.time > 0) { // Cluster had sufficient space.
maxDelay = Math.max(maxDelay, fw.time + Util.networkTime(f.getSize(), distance));
fm.instances.add(cluster);
writes++;
} else if (fw.time != Cluster.NO_SPACE_SENTINEL) {
cluster.calibrateSpaceAvailability(NODE_PER_CLUSTER_WRITE_REDUNDANCY);
}
}
if (writes < rewriteCount) {
return -1;
}
return maxDelay;
} | 8 |
public String getLastName() {
return lastName;
} | 0 |
public void mapCSVData(List<String> parsedCSVData) throws ParseException {
Entry newEntry;
switch (parsedCSVData.size()) {
case 3:
newEntry = Entry.createNewEntry(parsedCSVData.get(0),
parsedCSVData.get(1), parsedCSVData.get(2), null, null, null, null);
break;
case 4:
newEntry = Entry.createNewEntry(parsedCSVData.get(0),
parsedCSVData.get(1), parsedCSVData.get(2), parsedCSVData.get(3), null, null, null);
break;
case 5:
newEntry = Entry.createNewEntry(parsedCSVData.get(0),
parsedCSVData.get(1), parsedCSVData.get(2), null, null, parsedCSVData.get(3), parsedCSVData.get(4));
break;
case 6:
newEntry = Entry.createNewEntry(parsedCSVData.get(0),
parsedCSVData.get(1), parsedCSVData.get(2), parsedCSVData.get(3), parsedCSVData.get(4), parsedCSVData.get(5), null);
break;
case 7:
newEntry = Entry.createNewEntry(parsedCSVData.get(0),
parsedCSVData.get(1), parsedCSVData.get(2), parsedCSVData.get(3), parsedCSVData.get(4), parsedCSVData.get(5), parsedCSVData.get(6));
break;
default:
throw new IllegalArgumentException("Wrong number of arguments: "
+ parsedCSVData.size() + " - The first 3 elements " +
"cannot be null.");
}
UpdateOrCreateEntries(newEntry);
} | 5 |
public List<String> getAllAddresses() {
ArrayList<String> addresses = new ArrayList<String>();
for (Map.Entry<String, String> entry : to.entrySet())
addresses.add(entry.getKey());
for (Map.Entry<String, String> entry : cc.entrySet())
addresses.add(entry.getKey());
for (Map.Entry<String, String> entry : bcc.entrySet())
addresses.add(entry.getKey());
return addresses;
} | 3 |
public boolean isLoop() {
return (getSource() != null && getSource() == getTarget())
|| (sourceParentView != null && sourceParentView == targetParentView)
|| (sourceParentView != null && getTarget() != null && getTarget()
.getParentView() == sourceParentView)
|| (targetParentView != null && getSource() != null && getSource()
.getParentView() == targetParentView);
} | 9 |
public void updateHeight(int l, int r) {
if(l > r) {int t = l; l = r; r = t;}
for(int i = l; i <= r; i ++)
heightOfX[i-left] = 1000;
for(int i = 0; i < num; i ++) {
if(!isExist[i]) continue;
double xl = 1000, xr = 0, y = 1000;
for(int j = 0; j < 4; j ++) {
xl = blocksPts[i][j].getX() < xl ? blocksPts[i][j].getX() : xl;
xr = blocksPts[i][j].getX() > xr ? blocksPts[i][j].getX() : xr;
y = blocksPts[i][j].getY() < y ? blocksPts[i][j].getY() : y;
}
for(int j = Math.max((int)xl, l); j <= Math.min((int)xr, r); j ++)
heightOfX[j-left] = Math.min(heightOfX[j-left], (int)y);
}
} | 9 |
@Transient
@JsonIgnore
public Event getEvent() {
return event;
} | 0 |
public void parallelRender(int[] raster, int width, int height){
//calculate view frustrum
if (!isInitialized) init();
Ray[] rays = cam.generateRays(width, height);
int threadCount = 8;
TracerThread[] tts = new TracerThread[threadCount];
for (int i = 0; i <threadCount; i++ ){
tts[i] = new TracerThread(rays,((i*rays.length)/threadCount),(((i+1)*rays.length)/threadCount),world);
tts[i].start();
}
for(TracerThread thread : tts) try {
thread.join();
// for (Ray r : rays) r.voxel = trace(r);
} catch (InterruptedException ex) {
Logger.getLogger(Tracer.class.getName()).log(Level.SEVERE, null, ex);
}
// for (Ray r : rays) r.voxel = trace(r);
for(int x = 0; x < width; x++){
for(int y = 0; y < height;y++){
Ray r = rays[(x*height) +y];
raster[x+width*y] = r.voxel!=null?voxelColors[0x000000ff&r.voxel.ID].getRGB():Color.black.getRGB();
}
}
} | 7 |
public void zoneEventOccurred(String eventZone, int eventType) {
if((eventType == ZoneEvents.MOVEMENT || eventType == ZoneEvents.ENTER )
&& eventZone.equals("menuBar")){
if(Debug.gui)
System.out.println(eventZone);
if(triggerShimmyIn()){
mouseInMenuArea = true;
}
else if(triggerShimmyOut()){
mouseInMenuArea = false;
}
else{
if(Debug.gui)
System.out.println("MenuBar - do nothing");
}
}
} | 7 |
private ValueWithTimestamp getLocalValue(Column col,long start_ts,long end_ts,boolean hasEnd){
ValueWithTimestamp data=localData.get(col);
if(data==null)
return null;
if(hasEnd){
if(data.timestamp>=start_ts && data.timestamp<=end_ts)
return data;
return null;
}else{
if(data.timestamp>=start_ts)
return data;
return null;
}
} | 5 |
static Line closestPair(ArrayList<Shapes.Point> xPoints, ArrayList<Shapes.Point> yPoints, ArrayList<Shapes.Point> aux,
int left, int right, Line s0) {
if (left >= right) {
return new Line(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE);
}
int middle = ((right + left) >> 1) + ((right + left) % 2);
Shapes.Point mPoint = xPoints.get(middle);
Line lS;
lS = closestPair(xPoints, yPoints, aux, left, middle - 1, s0);
Line rS;
rS = closestPair(xPoints, yPoints, aux, middle + 1, right, s0);
Line s = lS.compare(rS).compare(s0);
int index = 0;
for (int i = left; i <= right; i++) {
if ((Math.abs((new Line(yPoints.get(i), mPoint)).getSize())) < (s.getSize())) {
aux.add(index++, yPoints.get(i));
}
}
for (int i = 0; i < index; i++) {
for (int j = i + 1; (j < index) && (aux.get(i).getY() - aux.get(j).getY()) <
(s.getSize()); j++) {
if (((new Line(aux.get(i), aux.get(j))).getSize()) < (s.getSize())) {
s = new Line(aux.get(i), aux.get(j));
}
}
}
g.setColor(Color.YELLOW);
if (lS.getPoint1().getX() < 400) {
drawB(lS);
}
g.setColor(Color.BLUE);
if (rS.getPoint1().getX() < 400) {
drawB(rS);
}
g.setColor(Color.BLACK);
drawB(s);
jLabel1.update(jLabel1.getGraphics());
g.setColor(Color.RED);
return s;
} | 9 |
public void setHeading(String heading) {
this.heading = heading;
} | 0 |
private void compute_pcm_samples1(Obuffer buffer)
{
final float[] vp = actual_v;
//int inc = v_inc;
final float[] tmpOut = _tmpOut;
int dvp =0;
// fat chance of having this loop unroll
for( int i=0; i<32; i++)
{
final float[] dp = d16[i];
float pcm_sample;
pcm_sample = (float)(((vp[1 + dvp] * dp[0]) +
(vp[0 + dvp] * dp[1]) +
(vp[15 + dvp] * dp[2]) +
(vp[14 + dvp] * dp[3]) +
(vp[13 + dvp] * dp[4]) +
(vp[12 + dvp] * dp[5]) +
(vp[11 + dvp] * dp[6]) +
(vp[10 + dvp] * dp[7]) +
(vp[9 + dvp] * dp[8]) +
(vp[8 + dvp] * dp[9]) +
(vp[7 + dvp] * dp[10]) +
(vp[6 + dvp] * dp[11]) +
(vp[5 + dvp] * dp[12]) +
(vp[4 + dvp] * dp[13]) +
(vp[3 + dvp] * dp[14]) +
(vp[2 + dvp] * dp[15])
) * scalefactor);
tmpOut[i] = pcm_sample;
dvp += 16;
} // for
} | 1 |
public void move() {
// TODO: 根据窗口大小判断
if (x <= 0)
moveToRight = true;
else if (y >= 400)
isAlive = false;
else if (x >= 585)
moveToRight = false;
else if (y <= 25)
moveToDown = true;
if(moveToDown)
y += YSPEED;
else
y -= YSPEED;
if(moveToRight)
x += XSPEED;
else
x -= XSPEED;
} | 6 |
public TemplateModel get(String s) throws TemplateModelException {
switch (s) {
case "name":
return new SimpleScalar(m_name);
case "symbol":
return new SimpleScalar(m_symbol);
case "change":
return new SimpleNumber(m_change);
case "lastPrice":
return new SimpleNumber(m_lastTradePrice);
case "news":
return m_news;
default:
throw new TemplateModelException();
}
} | 5 |
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
MovingObjectPosition movingobjectposition = getMovingObjectPositionFromPlayer(par2World, par3EntityPlayer, true);
if (movingobjectposition == null)
{
return par1ItemStack;
}
if (movingobjectposition.typeOfHit == EnumMovingObjectType.TILE)
{
int i = movingobjectposition.blockX;
int j = movingobjectposition.blockY;
int k = movingobjectposition.blockZ;
if (!par2World.canMineBlock(par3EntityPlayer, i, j, k))
{
return par1ItemStack;
}
if (!par3EntityPlayer.canPlayerEdit(i, j, k))
{
return par1ItemStack;
}
if (par2World.getBlockMaterial(i, j, k) == Material.water && par2World.getBlockMetadata(i, j, k) == 0 && par2World.isAirBlock(i, j + 1, k))
{
par2World.setBlockWithNotify(i, j + 1, k, Block.waterlily.blockID);
if (!par3EntityPlayer.capabilities.isCreativeMode)
{
par1ItemStack.stackSize--;
}
}
}
return par1ItemStack;
} | 8 |
protected void addBlocks(Node node, Automaton automaton, Set locatedStates,
Map i2s, Document document) {
assert(automaton instanceof TuringMachine); //this code should really be in TMTransducer, but I see why it's here
if(node == null) return;
if (!node.hasChildNodes())
return;
NodeList allNodes = node.getChildNodes();
ArrayList blockNodes = new ArrayList();
for (int k = 0; k < allNodes.getLength(); k++) {
if (allNodes.item(k).getNodeName().equals(BLOCK_NAME)) {
blockNodes.add(allNodes.item(k));
}
}
Map i2sn = new java.util.TreeMap(new Comparator() {
public int compare(Object o1, Object o2) {
if (o1 instanceof Integer && !(o2 instanceof Integer))
return -1;
if (o1 instanceof Integer)
return ((Integer) o1).intValue()
- ((Integer) o2).intValue();
if (o2 instanceof Integer)
return 1;
return ((Comparable) o1).compareTo(o2);
}
});
createState(blockNodes, i2sn, automaton, locatedStates, i2s, true,
document);
// return i2s;
} | 8 |
private void inv6ActionPerformed(java.awt.event.ActionEvent evt)
{
if(!game.getInBattle())
{
outputText.setText(game.useItem(5) + "\n" + game.getCurrentRoom().getExitString());
if(game.itemRemoved())
inv6.setText("inv6(empty)");
}
else
outputText.setText(game.guiPressed("inv6"));
} | 2 |
public static <T> T buscarObjeto( ArrayList<T> lista, Object id)
{
Iterator<T> iterator = lista.iterator();
T objeto;
while (iterator.hasNext())
{
objeto = iterator.next();
if (((ObjetoBD) objeto).getId().equals( id))
return objeto;
}
return null;
} | 2 |
public static void messageReceived(Message message) {
cbText.add(message);
ChatboxInterface chatbox = InterfaceHandler.getChatbox();
if (cbText.size() > 100) {
cbText.remove(0);
chatbox.setScrollY(chatbox.getScrollY() + 1);
}
if (chatbox.getScrollY() != 0 && chatbox.getScrollY() > -100) {
chatbox.setScrollY(chatbox.getScrollY() - 1);
}
} | 3 |
public int getLightRadius() {
int r = 2;
if (activeItem != null) {
if (activeItem instanceof FurnitureItem) {
int rr = ((FurnitureItem) activeItem).furniture.getLightRadius();
if (rr > r) r = rr;
}
}
return r;
} | 3 |
public void decreaseRope(int x, int y) {
if (ropelength > -1) {
ropelength --;
}
x += 1;
y -= 2;
switch (ropelength) {
case 124: getWorld().removeObject(rope6); ropeman.setLocation(x, y+15); break;
case 99: getWorld().removeObject(rope5); ropeman.setLocation(x, y+13); break;
case 74: getWorld().removeObject(rope4); ropeman.setLocation(x, y+11); break;
case 49: getWorld().removeObject(rope3); ropeman.setLocation(x, y+9); break;
case 24: getWorld().removeObject(rope2); ropeman.setLocation(x, y+7); break;
case 0: getWorld().removeObject(rope); getWorld().removeObject(ropeman); break;
}
} | 7 |
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (taskId > 0) {
this.plugin.getServer().getScheduler().cancelTask(taskId);
taskId = -1;
}
}
} | 2 |
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char grade = in.next().charAt(0);
switch (grade) {
case 'A':
case 'B':
case 'C':
System.out.println("Passes");
break;
case 'D':
case 'F':
System.out.println("Fail");
break;
default:
System.out.println("Invalid");
break;
}
} | 5 |
public void hideGame() {
image.setVisible(false);
for (Base b : Game.getInstance().getBaseManager().getBases()) {
b.setVisible(false);
}
for(GroupAgent a : Game.getInstance().getAgentManager().getAgents()){
a.setVisible(false);
}
for(Tower t : Game.getInstance().getTowerManager().getTowers()) {
t.setVisible(false);
}
line.setVisible(false);
lineCursor.setVisible(false);
panelInfoRealPlayer.setVisible(false);
panelInfoIAPlayers.setVisible(false);
} | 3 |
@After
public void tearDown() {
} | 0 |
public EuclidsExtended(int input1, int input2) {
variables = new Result(input1,input2);
// Ensure the input is valid
if(input1<=0||input2<=0){
variables.setError(EuclidsExtended.NonPos);
}
} | 2 |
public int load( String filePath ) {
XMLConfigParser pars = new XMLConfigParser();
pars.parseDocument("Format");
String file = filePath.substring(filePath.lastIndexOf("\\"));
String extension = file.substring(file.indexOf(".") + 1);
String fileExtension = null;
for ( XMLConfigParser elems : pars.getMyFormats() ){
for ( int i = 0; i < elems.getExtension().length; i ++){
if ( extension.equalsIgnoreCase(elems.getExtension()[ i ] ) ){
fileExtension = elems.getName();
break;
}
}
if ( fileExtension != null) {
break;
}
}
char c = fileExtension.charAt(0);
switch (c) {
case 'W' :
loadable = new WavLoader( filePath );
break;
case 'M' :
loadable = new Mp3Loader( filePath );
break;
}
// To-Do
// try {
// extension = Files.probeContentType( Paths.get( filePath ) );
// } catch (IOException e) {
// e.printStackTrace();
// }
/* Choosing file decoder */
//if ( WavLoader.getFileIdentifier().compareToIgnoreCase( extension ) == 0 ) {
//loadable = new WavLoader( filePath );
//}
return 0;
} | 6 |
private String formatLinks(String content) {
String buf = "";
int idx = 0;
int aStart = 0;
int aEnd = -4;
while (content.indexOf("<a", idx) != -1) {
aStart = content.indexOf("<a", idx);
buf += content.substring(aEnd+4, aStart);
aEnd = content.indexOf("</a>", aStart);
String link = content.substring(aStart, aEnd);
int linkidx = link.indexOf("href=\"");
String title = this.removeHtml.matcher(link).replaceAll("");
link = link.substring(linkidx, link.indexOf("\"", linkidx + 6)).replace("href=\"", "");
buf += "$u{$col[0,0,192]{$a["+ link + "]{" + title + "}}}";
idx = aEnd;
}
buf += content.substring(aEnd+4);
return buf;
} | 1 |
protected boolean isWriteIgnoredElement(String element, TreePath<String> path, Dependency dependency) {
// if (isDebianBuild() && DEBIAN_BUILD_IGNORED_ELEMENTS.contains(element)) {
// System.out.println("Build ignored " + element + " " + printPath(path) + " for " + dependency);
// }
// if (isBuildWithoutDoc() && DEBIAN_DOC_IGNORED_ELEMENTS.contains(element)) {
// System.out.println("Doc ignored " + element + " " + printPath(path) + " for " + dependency);
// }
// if (WRITE_IGNORED_ELEMENTS.contains(element)) {
// System.out.println("Write ignored " + element + " " + printPath(path) + " for " + dependency);
// }
return path.size() == 1 && (isDebianBuild && DEBIAN_BUILD_IGNORED_ELEMENTS.contains(element))
|| (isBuildWithoutDoc && DEBIAN_DOC_IGNORED_ELEMENTS.contains(element))
|| WRITE_IGNORED_ELEMENTS.contains(element);
} | 5 |
private int compareIP(byte[] ip, byte[] beginIp) {
for (int i = 0; i < 4; i++) {
int r = compareByte(ip[i], beginIp[i]);
if (r != 0)
return r;
}
return 0;
} | 2 |
public SimpleDoubleProperty wrapWidthProperty() {
return wrapWidth;
} | 0 |
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj)
{
if (obj instanceof Tuple<?,?>) {
if(x.equals(((Tuple<X,Y>)obj).x) && y.equals(((Tuple<X,Y>)obj).y))
{
return true;
}
}
return false;
} | 5 |
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Parameter that = (Parameter) obj;
if (key == null) {
if (that.key != null)
return false;
} else if (!key.equals(that.key))
return false;
if (value == null) {
if (that.value != null)
return false;
} else if (!value.equals(that.value))
return false;
return true;
} | 9 |
public long getAddress() {
if (addressSize == 4)
return normalize($.getInt(this, offset));
else
return $.getLong(this, offset);
} | 1 |
@Override
public void run() {
System.out.println("The tread number " + numderTread + " started.");
while (!stopTread) {
int rows = MatrixDouble.getRowsForThreadWithInkrement();
//System.out.println("The tread number " + numderTread + ". Rows = " + rowsA + ".");
if (rows >= rowTotal) {
stopTread();
} else {
try {
multiply(rows);
} catch (MatrixIndexOutOfBoundsException e) {
System.out.println("Error: " + e);
}
}
}
System.out.println("The tread number " + numderTread + " stopped.");
sumTread = 0;
} | 3 |
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
switch (args[0]) {
case "1": {
General.setParser(new LogicParser());
work = new Checker1();
break;
}
case "2": {
General.setParser(new LogicParser());
work = new Deduct2();
break;
}
case "3": {
General.setParser(new LogicParser());
work = new Proof3();
break;
}
case "4": {
General.setParser(new PredicateParser());
work = new Deduct4();
break;
}
case "5": {
General.setParser(new ArithmeticParser());
work = new Checker5();
break;
}
case "6": {
break;
}
default:
break;
}
try {
in = new BufferedReader(new FileReader(args[1]));
String[] arr = args[1].split("\\.");
out = new PrintWriter(new FileWriter(arr[0] + ".out"));
work.doSomething();
in.close();
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
} catch (IOException | LexingException | ParsingException | IncorrectProofException | ProofGeneratingException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
out.println();
// out.println("... Программа завершила свою работу за " + (endTime - startTime) + " мс");
out.close();
} | 8 |
public List<TrackData> getTrackDataList_History(
List<TrackData> list_track_data, String startDate, String endDate, String vregisteration_num) {
try {
m_Connection = getDbConnection().getConnection();
m_Statement = m_Connection.createStatement();
String m_Query = "select Phone_No,cv,Latitude,Longitude,Speed,Acc_Status,location from livemessagedata where Phone_No in "
+ "( "
+ " select deviceid from vehicle where vregisteration_num = '" + vregisteration_num + "' "
+ ") "
+ "and "
+ "cv between "
+ "'" + startDate + "' "
+ "and "
+ "'" + endDate + "'";
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
m_ResultSet = m_Statement.executeQuery(m_Query);
log.info(m_Query);
while (m_ResultSet.next()) {
TrackData trackData = new TrackData();
trackData.setDeviceid(m_ResultSet.getString("Phone_No"));
trackData.setDate(df.format(m_ResultSet.getTimestamp("cv")));
if (trackData.getLatitudeList().equals("")) {
trackData.setLatitudeList(m_ResultSet.getString("Latitude"));
} else {
trackData.setLatitudeList(trackData.getLatitudeList() + "," + m_ResultSet.getString("Latitude"));
}
if (trackData.getLongitudeList().equals("")) {
trackData.setLongitudeList(m_ResultSet.getString("Longitude"));
} else {
trackData.setLongitudeList(trackData.getLongitudeList() + "," + m_ResultSet.getString("Longitude"));
}
trackData.setLocation(m_ResultSet.getString("location"));
trackData.setSpeed(Double.parseDouble(m_ResultSet.getString("Speed")));
int x = Integer.parseInt(m_ResultSet.getString("Acc_Status"));
if (x == 0) {
trackData.setAcc_status("OFF");
} else {
trackData.setAcc_status("ON");
}
list_track_data.add(trackData);
}
} catch (SQLException sqe) {
log.info(sqe);
} finally {
try {
if (m_ResultSet != null) {
m_ResultSet.close();
}
if (m_Statement != null) {
m_Statement.close();
}
if (m_Connection != null) {
m_Connection.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return list_track_data;
} | 9 |
private int isDimensionOk(String dimTxt) {
int dimension;
try
{
dimension = Integer.parseInt(dimTxt);
}
catch (NumberFormatException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(new Frame(), "Erreur de dimension, format incorrect");
return -1;
}
if (dimension<4 ||dimension > 15) {
JOptionPane.showMessageDialog(new Frame(), "Erreur de dimension : les dimensions doivent être comprises entre 4 et 15");
return -1;
}
else {
return dimension;
}
} | 3 |
public Plateau()
{
this.cases = new Case[NOMBRE_DE_LIGNES][NOMBRE_DE_COLONNES];
// Creé les objets de type Case du tableau.
for (int numeroDeLigne = 0; numeroDeLigne < NOMBRE_DE_LIGNES; numeroDeLigne++)
for (int numeroDeColonne = 0; numeroDeColonne < NOMBRE_DE_COLONNES; numeroDeColonne++)
this.cases[numeroDeLigne][numeroDeColonne] = new Case(
new Position(numeroDeLigne, numeroDeColonne));
this.installerPions();
} | 2 |
public static Integer ge(Object o1, Object o2){
if (o1 == null && o2 == null){
return 1;
} else if (o1 != null && o2 == null){
return 1;
} else if (o1 instanceof Number && o2 instanceof Number){
return ((Number)o1).doubleValue() >=((Number)o2).doubleValue() ? 1 : 0;
}
return 0;
} | 7 |
private void setHorLength(int horLength) {
if (horLength < 10)
throw new IllegalArgumentException("The size of the grid has to be at least 10x10!");
this.horLength = horLength;
} | 1 |
public boolean isRemoving() {
return this.isRemoving;
} | 0 |
@Override
public void run()
{
running = true;
while (running)
{
try
{
switch (fizzBuzzStep)
{
case FIZZ:
{
Long value = fizzInputQueue.take();
fizzOutputQueue.put(Boolean.valueOf(0 == (value.longValue() % 3)));
break;
}
case BUZZ:
{
Long value = buzzInputQueue.take();
buzzOutputQueue.put(Boolean.valueOf(0 == (value.longValue() % 5)));
break;
}
case FIZZ_BUZZ:
{
final boolean fizz = fizzOutputQueue.take().booleanValue();
final boolean buzz = buzzOutputQueue.take().booleanValue();
if (fizz && buzz)
{
++fizzBuzzCounter;
}
break;
}
}
sequence++;
}
catch (InterruptedException ex)
{
break;
}
}
} | 7 |
public AbstractPreference createNew(String key) {
String type = getProperty(key + KEY_JOIN + TYPE);
String scopeType = getProperty(key + KEY_JOIN + SCOPE);
if (type == null) {
LOGGER.fatal("Unable to load preference for key:" + key);
throw new UnsupportedOperationException("Unable to load preference for key:" + key);
}
Preferences scope = scopeType.equalsIgnoreCase("user") ? getUserApplicationNode() : getSystemApplicationNode();
if (type.equals("String")) {
String value = getProperty(key + KEY_JOIN + DEFAULT);
return new StringPreference(value, scope,
getProperty(key + KEY_JOIN + CATEGORY),
key,
getProperty(key + KEY_JOIN + NAME),
getProperty(key + KEY_JOIN + DESCRIPTION));
}
else if (type.equals("Incremental")) {
Long value = Long.parseLong(getProperty(key + KEY_JOIN + DEFAULT));
return new IncrementalPreference(value,
scope,
getProperty(key + KEY_JOIN + CATEGORY),
key,
getProperty(key + KEY_JOIN + NAME),
getProperty(key + KEY_JOIN + DESCRIPTION));
}
else if (type.equals("Integer")) {
Integer value = Integer.parseInt(getProperty(key + KEY_JOIN + DEFAULT));
return new IntegerPreference(value,
scope,
getProperty(key + KEY_JOIN + CATEGORY),
key,
getProperty(key + KEY_JOIN + NAME),
getProperty(key + KEY_JOIN + DESCRIPTION));
}
else if (type.equals("Double")) {
Double value = Double.parseDouble(getProperty(key + KEY_JOIN + DEFAULT));
return new DoublePreference(value,
scope,
getProperty(key + KEY_JOIN + CATEGORY),
key,
getProperty(key + KEY_JOIN + NAME),
getProperty(key + KEY_JOIN + DESCRIPTION));
}
else if (type.equals("List")) {
List<String> value = ListPreference.unwrap(getProperty(key + KEY_JOIN + DEFAULT));
return new ListPreference(value,
scope,
getProperty(key + KEY_JOIN + CATEGORY),
key,
getProperty(key + KEY_JOIN + NAME),
getProperty(key + KEY_JOIN + DESCRIPTION));
}
else if (type.equals("File")) {
File value = new File(getProperty(key + KEY_JOIN + DEFAULT));
return new FilePreference(value,
scope,
getProperty(key + KEY_JOIN + CATEGORY),
key,
getProperty(key + KEY_JOIN + NAME),
getProperty(key + KEY_JOIN + DESCRIPTION));
}
else if (type.equals("Boolean")) {
Boolean value = Boolean.parseBoolean(getProperty(key + KEY_JOIN + DEFAULT));
return new BooleanPreference(value,
scope,
getProperty(key + KEY_JOIN + CATEGORY),
key,
getProperty(key + KEY_JOIN + NAME),
getProperty(key + KEY_JOIN + DESCRIPTION));
}
throw new UnsupportedOperationException("Unsupported preference type for key:" + key);
} | 9 |
public DrawingToolbar(WhiteboardClientModel model) {
this.model = model;
this.setFloatable(false);
ButtonGroup toolButtons = new ButtonGroup();
boolean first = true;
for (Class<? extends DrawingTool> toolClass : new Class[] { Pen.class, Eraser.class }) {
ToolSelectionButton button = new ToolSelectionButton(toolClass);
toolButtons.add(button);
this.add(button);
// the first tool in the list is the one selected by default
if (first) {
button.doClick();
first = false;
}
}
this.addSeparator();
this.add(new JLabel("Current color: "));
colorPickerButton = new JButton(" "); // makes it bigger
colorPickerButton.setBackground(this.model.getColor());
colorPickerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(DrawingToolbar.this, "Pick color",
DrawingToolbar.this.model.getColor());
if (color != null) {
colorPickerButton.setBackground(color);
DrawingToolbar.this.model.setColor(color);
}
}
});
this.add(colorPickerButton);
this.addSeparator();
this.add(new JLabel("Pen width: "));
JSlider brushWidthSlider = new JSlider(1, 20, 5);
brushWidthSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
DrawingToolbar.this.model.setBrushWidth(((JSlider) (e.getSource())).getValue());
}
});
this.add(brushWidthSlider);
this.addSeparator(new Dimension(40, 1));
JButton changeUsernameButton = new JButton("Change username...");
changeUsernameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = JOptionPane.showInputDialog(DrawingToolbar.this, "Change username to",
DrawingToolbar.this.model.getUsername());
if (username == null)
return;
username = WhiteboardClientModel.sanitizeString(username);
DrawingToolbar.this.model.setUsername(username);
}
});
this.add(changeUsernameButton);
JButton switchWhiteboardButton = new JButton("Switch whiteboard...");
switchWhiteboardButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String whiteboardID = JOptionPane.showInputDialog(DrawingToolbar.this,
"Switch to whiteboard: (leave blank for a new randomly-named board)",
DrawingToolbar.this.model.whiteboard == null ? ""
: DrawingToolbar.this.model.whiteboard.whiteboardID);
if (whiteboardID == null)
return;
whiteboardID = WhiteboardClientModel.sanitizeString(whiteboardID);
DrawingToolbar.this.model.switchWhiteboard(whiteboardID);
}
});
this.add(switchWhiteboardButton);
} | 7 |
public MapObject getObjectNear(int x, int y, double zoom) {
Rectangle2D mouse = new Rectangle2D.Double(x - zoom - 1, y - zoom - 1, 2 * zoom + 1, 2 * zoom + 1);
Shape shape;
for (MapObject obj : objects) {
if (obj.getWidth() == 0 && obj.getHeight() == 0) {
shape = new Ellipse2D.Double(obj.getX() * zoom, obj.getY() * zoom, 10 * zoom, 10 * zoom);
} else {
shape = new Rectangle2D.Double(obj.getX() + bounds.x * myMap.getTileWidth(),
obj.getY() + bounds.y * myMap.getTileHeight(),
obj.getWidth() > 0 ? obj.getWidth() : zoom,
obj.getHeight() > 0 ? obj.getHeight() : zoom);
}
if (shape.intersects(mouse)) {
return obj;
}
}
return null;
} | 6 |
private static void browseTranslateRules() {
handler.listTranslateRules();
System.out.print("Enter option (new, remove, main, or quit): ");
String userInput = readString();
while ((!(userInput.equalsIgnoreCase("quit")))
&& (state == CONTEXT_TRANSLATERULES)) {
if (userInput == "quit") {
state = CONTEXT_EXIT;
} else if (userInput.equalsIgnoreCase("main")) {
System.out.println(MENU_MAIN);
state = CONTEXT_MAIN;
} else if (userInput.equalsIgnoreCase("list")) {
handler.listTranslateRules();
} else {
String[] tokens = userInput.split(" ", 2);
if (tokens.length == 2) {
if (tokens[0].equalsIgnoreCase("new")) {
System.out.print("Enter the rule string: ");
String ruleString = readString();
handler.rulesNew(tokens[1], ruleString);
} else if (tokens[0].equalsIgnoreCase("remove")) {
handler.rulesDelete(tokens[1]);
} else {
System.out.println("Input not recognised");
}
} else {
System.out.println("Input not recognised");
}
}
System.out.print("Enter option (new, remove, main, or quit): ");
userInput = readString();
}
} | 8 |
private Rule removeDefeater_transformDefeater(Rule origRule) throws TheoryNormalizerException {
if (origRule.getRuleType() != RuleType.DEFEATER) return null;
List<Literal> origHeadLiterals = origRule.getHeadLiterals();
if (origHeadLiterals.size() > 1) throw new TheoryNormalizerException(getClass(),
"rule head contains more than 1 literal");
Literal origHeadLiteral = origHeadLiterals.get(0);
Mode dummyLiteralMode = origHeadLiteral.getMode();
Mode ruleMode = origRule.getMode();
if ("".equals(dummyLiteralMode.getName())) dummyLiteralMode = ruleMode;
String sign = (origHeadLiteral.isNegation()) ? "+" : "-";
Rule newRule = DomUtilities.getRule(origRule.getLabel(), RuleType.DEFEASIBLE);
newRule.setOriginalLabel(origRule.getOriginalLabel());
newRule.setMode(ruleMode);
try {
addBodyLiterals(newRule, origRule.getBodyLiterals(), "");
newRule.addHeadLiteral(DomUtilities.getLiteral(origHeadLiteral.getName() + sign, true, dummyLiteralMode,null,
(String[]) null, true));
} catch (Exception e) {
}
return newRule;
} | 5 |
public void drawTank(Image up,Image down,Image left,Image right,Tank tank){
if( tank.getLastDir()==DirKey.Up ){
gBuffer.drawImage(up, tank.getX(), tank.getY(), null);
}
else if( tank.getLastDir()==DirKey.Left ){
gBuffer.drawImage(left, tank.getX(), tank.getY(), null);
}
else if( tank.getLastDir()==DirKey.Right ){
gBuffer.drawImage(right, tank.getX(), tank.getY(), null);
}
else if( tank.getLastDir()==DirKey.Down ){
gBuffer.drawImage(down, tank.getX(), tank.getY(), null);
}
final int dY=10;
final int dY2=5;
gBuffer.setColor(Color.GRAY);
gBuffer.drawRect(tank.getX(),tank.getY()-dY, Tank.FULL_HP, 6);
gBuffer.setFont(new Font("", Font.BOLD, 10));
gBuffer.drawString(tank.getName(), tank.getX(), tank.getY()-dY-dY2);
if( tank.getId()==id && tank.getType()==Tank.GENERAL ){
gBuffer.setColor(new Color(0,162,232));
}
else if( tank.getType()!=Tank.GENERAL ){
gBuffer.setColor(Color.BLACK);
}
else{
gBuffer.setColor(new Color(237,28,36));
}
gBuffer.fillRect(tank.getX()+1,tank.getY()-dY+1, tank.getHp()-1, 5);
} | 7 |
public void processPdu(CommandResponderEvent event) {
String ip;
String[] address = event.getPeerAddress().toString().split("/");
ip = address[0];
Iterator<Entry<String, SnmpAgent>> it = snmpAgents.entrySet()
.iterator();
while (it.hasNext()) {
Map.Entry<String, SnmpAgent> agent = (Map.Entry<String, SnmpAgent>) it
.next();
if (agent.getKey().contentEquals(ip)) {
agent.getValue().sendTrap(event.getPDU(), ip);
}
}
} | 2 |
@Override
public void initialize(URL location, ResourceBundle resources) {
Optional<String> username = getUserLogin();
if (username.isPresent() && username.get().length() != 0) {
user = username.get();
} else {
// no login = quit
System.exit(0);
}
sound = Sound.getInstance();
codeList = FXCollections.observableArrayList();
output.setItems(codeList);
// Create a MenuItem and place it in a ContextMenu
deleteBarcode = new MenuItem("Usuń kod");
contextMenu = new ContextMenu(deleteBarcode);
// sets a cell factory on the ListView telling it to use the previously-created ContextMenu
output.setCellFactory(ContextMenuListCell.<String> forListView(contextMenu));
deleteBarcode.setOnAction(this);
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
barcode = newValue;
// schedule new task when barcode starts appearing
if (newValue.length() == 1) {
input.setStyle("-fx-background-color: red;");
// create task and schedule it
timer = new Timer("rolex");
task = new BarcodeTimer();
timer.schedule(task, 2000);
}
}
});
Platform.runLater(new Runnable() {
@Override
public void run() {
input.requestFocus();
}
});
storage = new Storage(user + "-" + getTimestamp());
updateStatus();
appendTooltips();
} | 4 |
public TransformsType getTransforms() {
return transforms;
} | 0 |
public static int m_bf(final int n, final int c) {
return c*n;
} | 0 |
static void eraseBoard()
{
for(int i=0;i<place.length;i++)place[i]=place.length-2;
for(int i=0;i<pad.length;i++)
{
for(int l=0;l<pad[i].length;l++)
{
pad[i][l].delete();
}
}
for(int i=0;i<but.length;i++)
{
but[i].delete();
}
red.erase();
blue.erase();
console.erase();
res.delete();
restxt.erase();
menu.delete();
menutxt.erase();
//song.stopPlayFile();
computer=false;
selectionScreenStage=0;
} | 4 |
private void merge(T[] a, T[] aux, int lo, int mid,
int hi)
{
// i and j is used to point to the currently processing element in the
// first and 2nd half respectively
int i = lo, j = mid + 1;
// Copy a[lo..hi] to aux[lo..hi].
for (int k = lo; k <= hi; k++)
aux[k] = a[k];
// Merge back to a[lo..hi].
for (int k = lo; k <= hi; k++)
if (i > mid) // 1st half is exhausted.
a[k] = aux[j++];
else if (j > hi) // 2st half is exhausted.
a[k] = aux[i++];
else if (less(aux[j], aux[i]))
a[k] = aux[j++];
else
a[k] = aux[i++];
} | 5 |
public boolean renderBlockLadder(Block block, int i, int j, int k) {
Tessellator tessellator = Tessellator.instance;
int l = block.getBlockTextureFromSide(0);
if (this.overrideBlockTexture >= 0) {
l = this.overrideBlockTexture;
}
float f = block.getBlockBrightness(this.blockAccess, i, j, k);
tessellator.setColorOpaque_F(f, f, f);
int i1 = (l & 15) << 4;
int j1 = l & 240;
double d = (double) ((float) i1 / 256.0F);
double d1 = (double) (((float) i1 + 15.99F) / 256.0F);
double d2 = (double) ((float) j1 / 256.0F);
double d3 = (double) (((float) j1 + 15.99F) / 256.0F);
int k1 = this.blockAccess.getBlockMetadata(i, j, k);
float f1 = 0.0F;
float f2 = 0.05F;
if (k1 == 5) {
tessellator.addVertexWithUV((double) ((float) i + f2), (double) ((float) (j + 1) + f1), (double) ((float) (k + 1) + f1), d, d2);
tessellator.addVertexWithUV((double) ((float) i + f2), (double) ((float) (j + 0) - f1), (double) ((float) (k + 1) + f1), d, d3);
tessellator.addVertexWithUV((double) ((float) i + f2), (double) ((float) (j + 0) - f1), (double) ((float) (k + 0) - f1), d1, d3);
tessellator.addVertexWithUV((double) ((float) i + f2), (double) ((float) (j + 1) + f1), (double) ((float) (k + 0) - f1), d1, d2);
}
if (k1 == 4) {
tessellator.addVertexWithUV((double) ((float) (i + 1) - f2), (double) ((float) (j + 0) - f1), (double) ((float) (k + 1) + f1), d1, d3);
tessellator.addVertexWithUV((double) ((float) (i + 1) - f2), (double) ((float) (j + 1) + f1), (double) ((float) (k + 1) + f1), d1, d2);
tessellator.addVertexWithUV((double) ((float) (i + 1) - f2), (double) ((float) (j + 1) + f1), (double) ((float) (k + 0) - f1), d, d2);
tessellator.addVertexWithUV((double) ((float) (i + 1) - f2), (double) ((float) (j + 0) - f1), (double) ((float) (k + 0) - f1), d, d3);
}
if (k1 == 3) {
tessellator.addVertexWithUV((double) ((float) (i + 1) + f1), (double) ((float) (j + 0) - f1), (double) ((float) k + f2), d1, d3);
tessellator.addVertexWithUV((double) ((float) (i + 1) + f1), (double) ((float) (j + 1) + f1), (double) ((float) k + f2), d1, d2);
tessellator.addVertexWithUV((double) ((float) (i + 0) - f1), (double) ((float) (j + 1) + f1), (double) ((float) k + f2), d, d2);
tessellator.addVertexWithUV((double) ((float) (i + 0) - f1), (double) ((float) (j + 0) - f1), (double) ((float) k + f2), d, d3);
}
if (k1 == 2) {
tessellator.addVertexWithUV((double) ((float) (i + 1) + f1), (double) ((float) (j + 1) + f1), (double) ((float) (k + 1) - f2), d, d2);
tessellator.addVertexWithUV((double) ((float) (i + 1) + f1), (double) ((float) (j + 0) - f1), (double) ((float) (k + 1) - f2), d, d3);
tessellator.addVertexWithUV((double) ((float) (i + 0) - f1), (double) ((float) (j + 0) - f1), (double) ((float) (k + 1) - f2), d1, d3);
tessellator.addVertexWithUV((double) ((float) (i + 0) - f1), (double) ((float) (j + 1) + f1), (double) ((float) (k + 1) - f2), d1, d2);
}
return true;
} | 5 |
public String setData(String SQL) {
try {
if (connOjbect == null){
if (! connectToDB()){
return "Error";
}
}
String message;
Statement st = connOjbect.createStatement();
if (st.execute(SQL)){
message = "OK";
}
else{
message = "Error";
}
st.close();
return message;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "Error";
}
} | 4 |
@SuppressWarnings("deprecation")
public void testCompareTo() {
LocalDate test1 = new LocalDate(2005, 6, 2);
LocalDate test1a = new LocalDate(2005, 6, 2);
assertEquals(0, test1.compareTo(test1a));
assertEquals(0, test1a.compareTo(test1));
assertEquals(0, test1.compareTo(test1));
assertEquals(0, test1a.compareTo(test1a));
LocalDate test2 = new LocalDate(2005, 7, 2);
assertEquals(-1, test1.compareTo(test2));
assertEquals(+1, test2.compareTo(test1));
LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
assertEquals(-1, test1.compareTo(test3));
assertEquals(+1, test3.compareTo(test1));
assertEquals(0, test3.compareTo(test2));
DateTimeFieldType[] types = new DateTimeFieldType[] {
DateTimeFieldType.year(),
DateTimeFieldType.monthOfYear(),
DateTimeFieldType.dayOfMonth(),
};
int[] values = new int[] {2005, 6, 2};
Partial p = new Partial(types, values);
assertEquals(0, test1.compareTo(p));
assertEquals(0, test1.compareTo(new YearMonthDay(2005, 6, 2)));
try {
test1.compareTo(null);
fail();
} catch (NullPointerException ex) {}
// try {
// test1.compareTo(new Date());
// fail();
// } catch (ClassCastException ex) {}
try {
test1.compareTo(new TimeOfDay());
fail();
} catch (ClassCastException ex) {}
Partial partial = new Partial()
.with(DateTimeFieldType.centuryOfEra(), 1)
.with(DateTimeFieldType.halfdayOfDay(), 0)
.with(DateTimeFieldType.dayOfMonth(), 9);
try {
new LocalDate(1970, 6, 9).compareTo(partial);
fail();
} catch (ClassCastException ex) {}
} | 3 |
@Override
public void mark(int boardPosition, Cell[] cellBoard, int rows, int columns)
throws IllegalMark{
//Find the row.
int boardPositionRow = boardPosition / columns * columns;
//Mark the row.
for(int i= boardPositionRow; i < boardPositionRow + columns; i++ ){
mark(boardPosition,i,cellBoard);
}
} | 1 |
private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes | 8 |
public int countClients() {
int count = getClients().size();
if (count > size) {
count = size;
}
return count;
} | 1 |
public static String SHA1(String text) {
String Sha1 = "";
String value = text.toUpperCase();
try {
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash;
md.update(value.getBytes("iso-8859-1"), 0, value.length());
sha1hash = md.digest();
Sha1 = convertToHex(sha1hash);
} catch (NoSuchAlgorithmException ex) {
writeToLog("Algoritme is onjuist: " + ex.getMessage());
} catch (UnsupportedEncodingException ex) {
writeToLog("Encoding is onjuist: " + ex.getMessage());
}
return Sha1;
} | 2 |
@Test
public void testCreatingContactWithoutPhoneNumberShouldFail() {
try {
new Contact("Bart", "Simpson");
fail("Was expecting an Exception when no phone number is provided.");
} catch (IllegalArgumentException iae) {
Assert.assertEquals("Please provide a value for Phone Number as it is a non-nullable field.", iae.getMessage());
}
} | 1 |
public ClassInfo[] loadClassesFromZipFile(final ZipFile zipFile)
throws ClassNotFoundException {
final ClassInfo[] infos = new ClassInfo[zipFile.size()];
// Examine each entry in the zip file
final Enumeration entries = zipFile.entries();
for (int i = 0; entries.hasMoreElements(); i++) {
final ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
continue;
}
try {
final InputStream stream = zipFile.getInputStream(entry);
final File file = new File(entry.getName());
infos[i] = loadClassFromStream(file, stream);
} catch (final IOException ex) {
System.err.println("IOException: " + ex);
}
}
return (infos);
} | 4 |
@Override
public void execute(double t) {
Matrix u1 = input1.getInput();
Matrix u2 = input2.getInput();
Matrix u3 = input3.getInput();
double[] y = new double[input1.getDim() + input2.getDim()
+ input3.getDim()];
if (u1 != null)
for (int i = 0; i < input1.getDim(); i++)
y[i] = u1.get(i, 0);
if (u2 != null)
for (int i = 0; i < input2.getDim(); i++)
y[input1.getDim() + i] = u2.get(i, 0);
if (u3 != null)
for (int i = 0; i < input3.getDim(); i++)
y[input1.getDim() + input2.getDim() + i] = u3.get(i, 0);
try {
outputY.setOutput(new ColumnMatrix(y));
} catch (OrderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 7 |
private int percolateDown(int index, E item){
while(((4*index)+1) <= lastIndex){
//Note this is brute force and needs to be optimized
int mindex = 4*index+1;
int track = (lastIndex - ((4*index)+4));
if(track <0){
//Know track is either -1 -2 -3
track = track + 3;
}else{
track = 3;
}
//Loop through finding the index of the smallest value
for(int i =1; i<=track; i++){
if(comparator.compare(heap[mindex],heap[index*4+1+i])>0){
mindex = index*4+1+i;
}
}
if(comparator.compare(heap[mindex], item)<0){
heap[index] = heap[mindex];
index = mindex;
}else{
break;
}
}
return index;
} | 5 |
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.