text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void visit_aastore(final Instruction inst) {
stackHeight -= 3;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
} | 1 |
void print(Node t, int n, boolean p)
{
if (n > 0)
{
for (int i = 0; i < n; i++)
System.out.print(" ");
}
if (p)
{
if (t.getCar() != null)
{ t.getCar().print(n, true); }
}
else
System.out.print("'(");
} | 4 |
private static boolean comparerTabProduitsIdFourn
(Produit[] tab, int[] tabTest, int n) {
boolean pareil = true;
int i = 0;
try {
if (tab == null && tabTest == null) {
pareil = true;
} else if (tab != null && tabTest != null && tabTest.length == n){
while (i < n && pareil) {
if (tab[i].getIdFournisseur() != tabTest[i]) {
pareil = false;
}
i++;
}
} else {
pareil = false;
}
} catch (Exception e) {
pareil = false;
}
return pareil;
} | 9 |
@Override
public SingleObject create() {
where+=xvel;
xvel+=rand.nextBoolean()?3:-3;
xvel*=Math.abs(xvel)>10?0.8:2;
xvel*=0<where && where<stage.getWidth()?1:-1;
return new TornadoPart(where,stage.getHeight()-90,rand.nextInt(8));
} | 4 |
public AgentIO(SmallWorld smallWorld, MenuItem importMenuItem, MenuItem saveMenuItem) {
this.smallWorld = smallWorld;
this.importMenuItem = importMenuItem;
this.saveMenuItem = saveMenuItem;
} | 0 |
public boolean equals(Animation animation)
{
if(!name.equals(animation.getName()))
return false;
if(duration != animation.getDuration())
return false;
if(hasSubAnimations())
if(subAnimations.size() != animation.getSubAnimations().size())
return false;
else
{
for(int i=0; i<subAnimations.size(); i++)
if(!subAnimations.get(i).equals(animation.getSubAnimations().get(i)))
return false;
}
if(poses.size() != animation.getPoses().size())
return false;
for(int i=0; i<poses.size(); i++)
if(!poses.get(i).equals(animation.getPoses().get(i)))
return false;
return true;
} | 9 |
@Override
public Cluster[] getClusters() {
if (result == null || result.isEmpty()) {
return null;
}
return result.toArray(new Cluster[0]);
} | 2 |
@EventHandler(ignoreCancelled = true)
public void explode(EntityExplodeEvent eee) {
Iterator<Block> iterator = eee.blockList().iterator();
while (iterator.hasNext()) {
Block block = iterator.next();
try {
if (explodeReinforcement(block)) {
block.getDrops().clear();
iterator.remove();
}
} catch (NoClassDefFoundError e){
Citadel.warning("NoClassDefFoundError");
}
}
} | 3 |
public static void main(String[] args){
int count=0;
for(int i=1;i<1e4;i++){
if(isLychrel(i)){
count++;
}
}
System.out.println(count);
} | 2 |
public int getY() {
return y;
} | 0 |
@Override
public void setExecutionControl(ITesterExecutionControl executionControl) {
this.executionControl = executionControl;
} | 0 |
public static OpponentCache getInstance(String scope) {
if (cache.containsKey(scope)) {
return cache.get(scope);
}
OpponentCache instance = new OpponentCache();
cache.put(scope, instance);
return instance;
} | 1 |
public void actionPerformed(ActionEvent ae) {
// your code here
String string = ae.getActionCommand();
try
{
if(string.equals("Add")) processAdding();
if(string.equals("Delete")) processDeletion();
//if(string.equals("View Attendances")
if(string.equals("Save and Exit")) processSaveAndClose();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
} | 4 |
public StringBuffer printStatement(int indent, StringBuffer output) {
printIndent(indent, output);
if (qualification != null) qualification.printExpression(0, output).append('.');
if (typeArguments != null) {
output.append('<');
int max = typeArguments.length - 1;
for (int j = 0; j < max; j++) {
typeArguments[j].print(0, output);
output.append(", ");//$NON-NLS-1$
}
typeArguments[max].print(0, output);
output.append('>');
}
if (accessMode == This) {
output.append("this("); //$NON-NLS-1$
} else {
output.append("super("); //$NON-NLS-1$
}
if (arguments != null) {
for (int i = 0; i < arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
arguments[i].printExpression(0, output);
}
}
return output.append(");"); //$NON-NLS-1$
} | 7 |
public void close(){
try{
if(in!=null)in.close();
if(out!=null)out.close();
if(socket!=null)socket.close();
}
catch(Exception e){
}
in=null;
out=null;
socket=null;
} | 4 |
public static void scaleImageTo256kb(Path img) throws IOException {
File imgFile = img.toFile();
if (imgFile.length() <= BYTE) {
return;
}
File newFile = Constants.PROGRAM_TMP_PATH.resolve(img.getFileName()).toFile();
BufferedImage i = ImageIO.read(imgFile);
if (i.getWidth() > MAXWIDTH) {
BufferedImage j = new BufferedImage(MAXWIDTH, (int) (i.getHeight() * ((float) MAXWIDTH / i.getWidth())), i.getType());
Graphics2D g2 = (Graphics2D) j.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(i, 0, 0, j.getWidth(), j.getHeight(), null);
ImageIO.write(j, "jpg", imgFile);
}
float quality = 1f;
float eps = 0.2f;
int c = 0;
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
FileImageOutputStream output;
IIOImage image;
do {
c++;
FileUtil.deleteFile(newFile.toPath());
iwp.setCompressionQuality(quality);
output = new FileImageOutputStream(newFile);
writer.setOutput(output);
image = new IIOImage(ImageIO.read(imgFile), null, null);
writer.write(null, image, iwp);
writer.reset();
output.flush();
output.close();
quality -= eps / c;
} while ((newFile.length() > BYTE) && (quality > 0.1));
FileUtil.deleteFile(img);
FileUtil.moveFile(newFile.toPath(), img);
} | 4 |
public void paintComponent(Graphics g,
DragAndDropClassObject classOne,
DragAndDropClassObject classTwo){
Vector<Point> pointsOne = new Vector<Point>();
Vector<Point> pointsTwo = new Vector<Point>();
Vector<DragAndDropClassObject> ddClasses =
new Vector<DragAndDropClassObject>();
ddClasses.add(classOne);
ddClasses.add(classTwo);
Vector<Point> currentPoints;
DragAndDropClassObject currentClass;
//Loops through both of the classes on the diagram
//and finds all the points available from both as Points (x,y)
//on the diagram pannel, it sticks these variables into
//pointsOne and pointsTwo as necessarry.
for (int i=0; i<ddClasses.size();i++){
currentPoints = new Vector<Point>();
currentClass = ddClasses.get(i);
currentPoints.add(new Point(currentClass.rect.x, currentClass.rect.y));
currentPoints.add(new Point(currentClass.rect.x +
(currentClass.rect.width/2), currentClass.rect.y));
currentPoints.add(new Point(currentClass.rect.x +
(currentClass.rect.width), currentClass.rect.y));
currentPoints.add(new Point(currentClass.rect.x +
(currentClass.rect.width), currentClass.rect.y +
(currentClass.rect.height/2)));
currentPoints.add(new Point(currentClass.rect.x +
(currentClass.rect.width), currentClass.rect.y +
(currentClass.rect.height)));
currentPoints.add(new Point(currentClass.rect.x +
(currentClass.rect.width/2), currentClass.rect.y +
(currentClass.rect.height)));
currentPoints.add(new Point(currentClass.rect.x, currentClass.rect.y+
(currentClass.rect.height)));
currentPoints.add(new Point(currentClass.rect.x, currentClass.rect.y+
(currentClass.rect.height/2)));
if(i==0){
pointsOne = currentPoints;
} else if (i==1){
pointsTwo = currentPoints;
}
}
/*
* next we loop through all of the possible points combinations
* and note the shortest one available and where both ends are.
*/
int x;
int y;
Point bestPointOne = new Point(0,0);
Point bestPointTwo = new Point(0,0);
int distance = 9999;
for (Point pointOne:pointsOne){
for (Point pointTwo:pointsTwo){
x = Math.abs(pointOne.x-pointTwo.x);
y = Math.abs(pointOne.y-pointTwo.y);
if (x+y<distance){
distance=x+y;
bestPointOne = pointOne;
bestPointTwo = pointTwo;
}
}
}
/*
* finally we draw the graphics to the diagram pannel
* TODO: make the lines squared and more like blueJ.
*/
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.BLACK);
g2.draw(new Line2D.Double(new Point(bestPointOne.x, bestPointOne.y),
new Point(bestPointTwo.x, bestPointTwo.y)));
drawArrowHead(g2, bestPointTwo, bestPointOne, Color.black);
drawQuantifier(g2, bestPointTwo, bestPointOne, this.quantifier);
} | 6 |
private void winner(Player player, Hand hand, int playerScore, int dealerScore) {
if (dealerScore > 21 && playerScore <= 21) {
this.output.println("Player Wins! Collect " + hand.getBet());
player.deposit(hand.getBet());
} else if (playerScore > 21 && dealerScore <= 21) {
this.output.println("Player Loses. Lose " + hand.getBet());
player.withdraw(hand.getBet());
} else if ((playerScore > 21 && dealerScore > 21)
|| playerScore == dealerScore) {
this.output.println("Push. No money gained or lost.");
} else if (playerScore > dealerScore) {
this.output.println("Player Wins! Collect " + hand.getBet());
player.deposit(hand.getBet());
} else if (dealerScore > playerScore) {
this.output.println("Player Loses. Lose " + hand.getBet());
player.withdraw(hand.getBet());
}
} | 9 |
final Class133 method343(int ai[][], boolean flag, int i, int j, Class27_Sub1 class27Sub1, int k, int l, int i1, int j1, int k1, int ai1[][], int l1, Animation animation, int i2) {
long l2;
if (anIntArray574 != null) {
l2 = ((k << 3) + (id << 10)) - -l1;
} else {
l2 = l1 + (id << 10);
}
Model model = (Model) CacheFileWorker.aMRUNodes_3737.getObjectForID(l2);
if (model == null) {
Class39_Sub2 class39Sub2 = method342(l1, k, (byte) -55);
if (class39Sub2 == null) {
return null;
}
model = new Model(class39Sub2, 64 + anInt557, 768 - -(5 * anInt617), -50, -10, -50);
CacheFileWorker.aMRUNodes_3737.addObject(l2, model);
}
boolean flag1 = false;
if (animation != null) {
flag1 = true;
model = (Model) animation.method968(model, l, j, l1, -100, k1);
}
if (k == 10 && l1 > 3) {
if (!flag1) {
model = (Model) model.method502(true, true, true);
flag1 = true;
}
model.method504(256);
}
if (aByte606 != 0) {
if (!flag1) {
model = (Model) model.method502(true, true, true);
boolean flag2 = true;
}
model = model.method519(aByte606, aShort585, ai, ai1, j1, i2, i, false);
}
Class142_Sub8_Sub5.aClass133_3997.aGameObject_2206 = model;
return Class142_Sub8_Sub5.aClass133_3997;
} | 9 |
public void display(){
System.out.println("rectID : "+rectID);
System.out.println("rectName : "+rectName);
System.out.println("linkedvideoname : "+linkedVideoName);
System.out.println("linkedVideoStartFrame : "+linkedVideoStartFrame);
System.out.println("numofkeyframes : "+numOfKeyFrames);
int i=0;
while(i<kf.size())
{
kf.get(i++).display();
}
} | 1 |
public static double readCorpus(Trie dictTrie,String filepath,
HashSet<String> wrongWords
) throws IOException {
BufferedReader reader;
reader = new BufferedReader((new FileReader(filepath)));
StringTokenizer lineTokenizer;
String line;
String word;
double numWords = 0;
TrieNode node;
Pattern pattern = Pattern.compile("^[A-Za-z]*$");
Matcher matcher;
while((line = reader.readLine()) != null)
{
lineTokenizer = new StringTokenizer(line," ");
if(lineTokenizer.countTokens() != 0) {
word = lineTokenizer.nextToken().toLowerCase();
matcher = pattern.matcher(word);
if(matcher.matches()){
// records how many words are found
numWords++;
node = dictTrie.search(word);
if (node == null) {
// if the query can not be found in
// dictionary, then add it into the
// HashSet
wrongWords.add(word);
} else {
// if the word is found in dictionary,
// add its frequency
node.addFrequency();
}
}
}
}
reader.close();
return numWords;
} | 4 |
private int expandMinNode(int depth, int prevAlpha) {
// if cutoff test is satisfied
if (board.isGameOver() || depth == 0)
return board.getBoardStats().getStrength(maxPlayer);
Move[] moves = board.getPossibleMoves(minPlayer);
int beta = MAX_POSSIBLE_STRENGTH;
int current;
// explore each move in turn
for(int i = 0; i < moves.length; i++) {
if(board.move(moves[i])) { // move was legal (column was not full)
moveCount++; // global variable
// *************************************
// CODE NEEDED
// (mostly here)
// *************************************
current = expandMaxNode(depth - 1, beta);
// early return for alpha/beta pruning
if (current < prevAlpha) {
if (board.getPruning()) {
board.undoLastMove();
return current;
} else {
// System.out.println("An early return would have happened here, if pruning were turned on.");
}
}
if (current < beta)
beta = current;
board.undoLastMove(); // undo exploratory move
} // end if move made
} // end for all moves
return beta;
} | 7 |
private void refresh(Font f){
image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
if(f == null){
f = image.getGraphics().getFont();
}
fontMetrics = image.getGraphics().getFontMetrics(f);
int height = fontMetrics.getHeight();
int width = fontMetrics.stringWidth(text);
if(width == 0){
width = 1;
}
if(height == 0){
height = 1;
}
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig = ((Graphics2D) image.getGraphics());
if(f != null){
ig.setFont(f);
}
ig.setColor(color);
ig.drawString(text, 0, fontMetrics.getAscent());
needsRefresh = false;
} | 4 |
@Override
public void deserialize(Buffer buf) {
fightId = buf.readInt();
if (fightId < 0)
throw new RuntimeException("Forbidden value on fightId = " + fightId + ", it doesn't respect the following condition : fightId < 0");
sourceId = buf.readInt();
if (sourceId < 0)
throw new RuntimeException("Forbidden value on sourceId = " + sourceId + ", it doesn't respect the following condition : sourceId < 0");
targetId = buf.readInt();
if (targetId < 0)
throw new RuntimeException("Forbidden value on targetId = " + targetId + ", it doesn't respect the following condition : targetId < 0");
} | 3 |
@Override
public Component getComponentByID(int id) {
Connection conn = null;
PreparedStatement st = null;
Component component = null;
ResultSet row = null;
try {
conn = OracleDAOFactory.createConnection();
st = conn.prepareStatement(GET_COMPONENT_BY_ID);
st.setInt(1,id);
row = st.executeQuery();
if (row.next()) {
component = new Component(id, row.getString(TITLE),
row.getString(DESCRIPTION),
row.getString(PRODUCER), row.getDouble(WEIGHT),
row.getString(IMG), row.getDouble(PRICE));
}else{
throw new NoSuchComponentException("Can't get component from database.");
}
return component;
} catch (SQLException e) {
throw new ShopException("Can't get component from database", e);
} finally {
try {
if (row != null) {
row.close();
}
} catch (SQLException e) {
throw new ShopException(CANT_CLOSE_RESULT_SET, e);
}
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
throw new ShopException(CANT_CLOSE_STATEMENT, e);
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
throw new ShopException(CANT_CLOSE_CONNECTION, e);
}
}
} | 8 |
public void cargarArbol() {
//inicializo el arbol
inicializarArbol();
//cargo las cuentas hijo
r_con.Connection();
int count = 0;
int aux = 0;
Enumeration e = root1.breadthFirstEnumeration();
while (e.hasMoreElements()) {
parent1 = (DefaultMutableTreeNode) e.nextElement();
if (count > aux) {
try {
Cuenta objChildren = (Cuenta) parent1.getUserObject();
ResultSet res = r_con.Consultar("select pc_codigo_plan_cuenta,pc_nro_cuenta,pc_nombre_cuenta,pc_imputable,pc_id_padre from plan_cuentas where pc_id_padre="+objChildren.getNumero_C()+" order by pc_codigo_plan_cuenta");
while (res.next()) {
Cuenta hijo = new Cuenta (res.getString(1), res.getInt(2), res.getString(3),res.getBoolean(4),res.getInt(5));
childnode = new DefaultMutableTreeNode(hijo);
modelo1.insertNodeInto(childnode, parent1, parent1.getChildCount());
}
res.close();
} catch (SQLException ex) {
r_con.cierraConexion();
Logger.getLogger(GUI_Plan_Cuentas.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Pregunto si llego al fin.
if (e.hasMoreElements() == false) {
int toEle = totalElementos(root1.breadthFirstEnumeration());
if (cant_count < toEle) {
aux = count;
count = -1;
e = root1.breadthFirstEnumeration();
cant_count = toEle;
} else {
break;
}
}
count++;
}
//System.out.println(cant_count);
this.JTreeConta.setModel(modelo1);
r_con.cierraConexion();
} | 6 |
public String getMovieName() {
try {
return em.createNamedQuery("Movie.findById", Movie.class)
.setParameter("id", movieId)
.getSingleResult()
.getName();
} catch (NoResultException e) {
return "";
}
} | 1 |
public void plotZCoordinatesele (Graphics2D g2) {
g2.setFont(new Font("Arial", 20, 12));
DecimalFormat f = new DecimalFormat("0.#");
int yInterval=50;
float points = maxY / 4;
for (int x = yInterval, j = 1; x < 250; x+=yInterval){
if(j>3)
break;
g2.drawString("-", 146-diff, 100 + x + 24);
g2.drawString("" + f.format(points * j), 115-diff, 100 + x + 20);
j++;
}
float maxEle = (float) MODTOHAFSD_Utility.findMaximumNumber1(MODTOHAFSD_CalculateValues.input_ele_km);
maxEle = Math.abs(maxEle);
float xpoint = 0;
float prevx = 150;
float elepoint[] = new float[MODTOHAFSD_CalculateValues.input_n_obs+1];
float preelepoint[] = new float[MODTOHAFSD_CalculateValues.input_n_obs+1];
float dis[] = new float[MODTOHAFSD_CalculateValues.input_n_obs+1];
float predis[] = new float[MODTOHAFSD_CalculateValues.input_n_obs+1];
float preele = 320 - (float)( ( 25 * Math.abs(MODTOHAFSD_CalculateValues.input_ele_km[1]) / maxEle ) );
float xpoint1 = 0;
float zpoint = 0;
g2.setColor(Color.RED);
g2.fill(new Rectangle2D.Float(150-diff, 295, 450+diff+diff , 275 ));
Color col = Color.YELLOW;
Color col1 = Color.MAGENTA;
for (int k = 1; k <= MODTOHAFSD_CalculateValues.input_n_obs; k++) {
diff = (float) ( MODTOHAFSD_CalculateValues.input_ddx_km / 2);
diff = (float) (450 * diff / maxX);
xpoint = (float) (450 * MODTOHAFSD_CalculateValues.x[k] / maxX);
if (k == 1){
GradientPaint gradient = new GradientPaint(10, 10, col, 30, 190, col1, true);
g2.setPaint(gradient);
zpoint =(float) (275 * MODTOHAFSD_CalculateValues.o_dep[k] / maxZ);
g2.fill(new Rectangle2D.Float(150-diff, 295,diff+diff, zpoint ));
//g2.fill(new Rectangle2D.Float(150+xpoint, 295, diff, zpoint ));
}
else{
if(k<MODTOHAFSD_CalculateValues.input_n_obs) {
xpoint1 = (float) (450 * MODTOHAFSD_CalculateValues.x[k+1] / maxX);
}
zpoint =(float) (275 * MODTOHAFSD_CalculateValues.o_dep[k] / maxZ);
GradientPaint gradient = new GradientPaint(10, 10, col, 30, 190, col1, true);
g2.setPaint(gradient);
g2.fill(new Rectangle2D.Float(150+xpoint-diff ,295,xpoint1-xpoint, zpoint ));
}
if(k==MODTOHAFSD_CalculateValues.input_n_obs){
zpoint =(float) (275 * MODTOHAFSD_CalculateValues.o_dep[k]/ maxZ);
g2.fill(new Rectangle2D.Float(150+xpoint-diff, 295,diff+diff, zpoint ));
//g2.fill(new Rectangle2D.Float(150+xpoint-diff ,295,diff, zpoint ));
}
}
for (int k = 1; k <= MODTOHAFSD_CalculateValues.input_n_obs; k++) {
g2.setColor(Color.BLACK);
xpoint = (float) (450 * MODTOHAFSD_CalculateValues.x[k] / maxX);
dis[k] = xpoint;
elepoint[k] = 320 - (float) (25 * Math.abs(MODTOHAFSD_CalculateValues.input_ele_km[k]) / maxEle);
preelepoint[k]= preele;
predis[k]= prevx;
g2.draw(new Line2D.Float(prevx, preele, (float)150 + xpoint, elepoint[k]));
prevx = 150+xpoint;
preele = elepoint[k];
}
for(float i = (float)1.0; i<=25;){
for (int k = 1; k <= MODTOHAFSD_CalculateValues.input_n_obs; k++) {
g2.setColor(Color.WHITE);
g2.draw(new Line2D.Float(predis[k], preelepoint[k]-i, (float)150+dis[k], elepoint[k]-i));
}
i=(float) (i+0.5);
}
g2.setColor(Color.BLACK);
g2.drawLine(150, 50 + 20, 150, 550 + 20);
g2.drawString("DISTANCE(km)", 333, 315);
} | 9 |
public String getToolTip() {
return "Attribute Editor";
} | 0 |
public void shutdownOutput (final SocketChannel sc, final Callback.TCPClient cb) {
if ( !sc.isConnected()
|| !sc.isOpen()
|| sc.socket().isClosed()
|| sc.socket().isOutputShutdown()) {return;}
if (this.isLoopThread()) {
try { sc.socket().shutdownOutput(); }
catch (IOException ioe) { cb.onError(this, sc, ioe); }
return;
}
//
// else
//
this.addTimeout(new Callback.Timeout() {
public void go (TimeoutLoop loop) {
// TODO cancel all write operations, or check.
shutdownOutput(sc, cb);
}
});
} | 6 |
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p !=null && q !=null){
if(p.val == q.val){
return isSameTree(p.left , q.left) && isSameTree(p.right , q.right);
}else{
return false;
}
}else if(p ==null && q == null){
return true;
}else{
return false;
}
} | 6 |
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int aLen = getLen(headA);
int bLen = getLen(headB);
int diff = aLen - bLen;
if (diff >= 0) {
while (diff > 0) {
headA = headA.next;
diff--;
}
} else {
diff = -diff;
while (diff > 0) {
headB = headB.next;
diff--;
}
}
while (headA != null && headB != null) {
if (headA == headB) {
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
} | 8 |
public void tickAll() {
for(int var1 = 0; var1 < this.all.size(); ++var1) {
Entity var2;
(var2 = (Entity)this.all.get(var1)).tick();
if(var2.removed) {
this.all.remove(var1--);
this.slot.init(var2.xOld, var2.yOld, var2.zOld).remove(var2);
} else {
int var3 = (int)(var2.xOld / 16.0F);
int var4 = (int)(var2.yOld / 16.0F);
int var5 = (int)(var2.zOld / 16.0F);
int var6 = (int)(var2.x / 16.0F);
int var7 = (int)(var2.y / 16.0F);
int var8 = (int)(var2.z / 16.0F);
if(var3 != var6 || var4 != var7 || var5 != var8) {
this.moved(var2);
}
}
}
} | 5 |
public void loadMap(String file) {
InputStream in = getClass().getResourceAsStream("/maps/" + file + ".map");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
try {
this.cols = Integer.parseInt(br.readLine());
this.rows = Integer.parseInt(br.readLine());
this.map = new int[rows][cols];
this.width = cols * tileSize;
this.height = rows * tileSize;
this.xMin = Game.WIDTH - width;
this.xMax = 0;
this.yMin = Game.HEIGHT - height;
this.yMax = 0;
String delim = "\\s+";
for (int row = 0; row < rows; row++) {
String line = br.readLine();
String[] tokens = line.split(delim);
for (int col = 0; col < cols; col++)
map[row][col] = Integer.parseInt(tokens[col]);
}
} catch (Exception e) {
e.printStackTrace();
}
} | 3 |
public void createAndSaveUrl(String Path, String DistrictID) throws Exception{
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("/com/opendap/poc/ServerContentDownloader.properties"));
String parent = new File(this.getClass().getResource("/boo.txt").getFile()).getParent();
String folderProperty = properties.getProperty("folder");
//String folderPath = folderProperty +"/" + DistrictID + "/" + Path;
String folderPath = "Data/188/2012-03-21";
/* build connection to the database */
try{
File dir = new File(parent, folderPath);
dir.mkdirs();
new File(dir, "newboo3.txt").createNewFile();
//System.out.println(dir.getAbsolutePath());
}catch(Exception e){
e.printStackTrace();
}
try {
int id = 1;
//String DistrictID ="188";
/*Get the district coordinates */
File aFile = new File(this.getClass().getResource("/DistrictCoordinates.txt").getFile());
String LatLong = "";
double maxLat = 0.0;
double minLat = 0.0;
double maxLon = 0.0;
double minLon =0.0;
Double GCMLat = 0.0;
Double GCMLon = 0.0;
double GCMLatMin = 0.0;
double GCMLatMax = 0.0;
double GCMLonmin = 0.0;
double GCMLonMax = 0.0;
Vector LatVec = new Vector();
Vector LonVec = new Vector();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
StringTokenizer sta = new StringTokenizer(line.toString(),"@");
//sta.nextToken();
if(sta.nextToken().toString().equals(DistrictID)){
sta.nextToken();
LatLong = sta.nextToken();
LatLong = LatLong.replace("MULTIPOLYGON(((", "");
LatLong = LatLong.replace(")))", "");
LatLong = LatLong.replace("))", ",");
LatLong = LatLong.replace("((", "");
//defining the area of the resterization
StringTokenizer st = new StringTokenizer(LatLong,",");
StringTokenizer stRaster = new StringTokenizer(LatLong,",");
while(stRaster.hasMoreElements() ){
String next = stRaster.nextElement().toString();
StringTokenizer st3 = new StringTokenizer(next);
Double Lat = Double.parseDouble(st3.nextElement().toString());
Double Lon = Double.parseDouble(st3.nextElement().toString());
LatVec.add(Lat);
LonVec.add(Lon);
}
maxLat = Double.parseDouble(Collections.max(LatVec).toString());
minLat = Double.parseDouble(Collections.min(LatVec).toString());
maxLon = Double.parseDouble(Collections.max(LonVec).toString());
minLon = Double.parseDouble(Collections.min(LonVec).toString());
GCMLat = (maxLat+minLat)/2;
GCMLon = (maxLon + minLon)/2;
GCMLatMin = GCMLat - 5;
GCMLatMax = GCMLat + 5;
GCMLonmin = GCMLon - 5;
GCMLonMax = GCMLon + 5;
}
}
}catch(Exception e){}
int dist = Integer.parseInt(DistrictID);
id = dist;
//the id in database is 1 more than the normal id
id++;
String filename = "";
String urlString = "";
double Lon = 0.0;
double Lat = 0.0;
/*Get the grid co-ordinates of the region */
filename = "GridCoordinates.tsv";
urlString = servletURLPattern_Coordinates.replace("{{minLat}}", String.valueOf(minLat))
.replace("{{maxLat}}",String.valueOf(maxLat)).replace("{{minLon}}", String.valueOf(minLon)).
replace("{{maxLon}}", String.valueOf(maxLon)).replace("{{id}}",String.valueOf(id));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/* Get the soil parameters from the Datalibrary */
filename = "soil.cdf";
urlString = servletURLPattern_soil.replace("{{minLat}}", String.valueOf(minLat))
.replace("{{maxLat}}",String.valueOf(maxLat)).replace("{{minLon}}", String.valueOf(minLon)).
replace("{{maxLon}}", String.valueOf(maxLon)).replace("{{id}}",String.valueOf(id));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/*Call the soil function to convert the soil into ID*/
//Soil sol = new Soil();
/*Get the rainfall co-ordinates for the dataset */
GridCoordinates grid = new GridCoordinates();
Vector vec = grid.Coordinates(folderPath);
Vector rainParameters = new Vector();
Vector NHMMrain = new Vector();
RainNHMM rnhmm = new RainNHMM();
System.out.println ("Vector Size =" + vec.size());
for(int i = 0; i <vec.size();i++){
System.out.println(i);
String pathname = "";
Lon = Double.parseDouble(vec.get(i).toString());
Lat = Double.parseDouble(vec.get(i+1).toString());
i++;
/*this call saves the rainfall values*/
pathname = "rainfall"+"-"+Lat+"-"+Lon;
filename = pathname+".cdf";
urlString = servletURLPattern_rainfall.replace("{{Lat}}", String.valueOf(Lat))
.replace("{{Lon}}",String.valueOf(Lon)).replace("{{id}}",String.valueOf(id));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/* this methods builds up the rainfall files for HMM use*/
pathname = "rainfall"+"-"+Lat+"-"+Lon;
rainParameters = rnhmm.WriteRain(folderPath,pathname);
NHMMrain.add(rainParameters);
/*this call saves the Tmax values when it rained*/
pathname = "TmaxR"+Lat+"-"+Lon;
filename = pathname+".tsv";
urlString = servletURLPattern_TmaxAvgR.replace("{{Lat}}", String.valueOf(Lat))
.replace("{{Lon}}",String.valueOf(Lon));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/*this call saves the Tmax values when it did not rain*/
pathname = "TmaxNR"+Lat+"-"+Lon;
filename = pathname+".tsv";
urlString = servletURLPattern_TmaxAvgNR.replace("{{Lat}}", String.valueOf(Lat))
.replace("{{Lon}}",String.valueOf(Lon));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/*this call saves the Tmin values when it rained*/
pathname = "TminR"+Lat+"-"+Lon;
filename = pathname+".tsv";
urlString = servletURLPattern_TminAvgR.replace("{{Lat}}", String.valueOf(Lat))
.replace("{{Lon}}",String.valueOf(Lon));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/*this call saves the Tmin values when it not rained*/
pathname = "TminNR"+Lat+"-"+Lon;
filename = pathname+".tsv";
urlString = servletURLPattern_TminAvgNR.replace("{{Lat}}", String.valueOf(Lat))
.replace("{{Lon}}",String.valueOf(Lon));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/*this call saves the SRad values when it not rained*/
pathname = "SRadNR"+Lat+"-"+Lon;
filename = pathname+".tsv";
urlString = servletURLPattern_SRadNR.replace("{{Lat}}", String.valueOf(Lat))
.replace("{{Lon}}",String.valueOf(Lon));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/* this call saves the SRad values when it rained */
pathname = "SRadR"+Lat+"-"+Lon;
filename = pathname+".tsv";
urlString = servletURLPattern_SRadR.replace("{{Lat}}", String.valueOf(Lat))
.replace("{{Lon}}",String.valueOf(Lon));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/**/
}
/* this call defines the input parameters to HMM */
rnhmm.WriteInputFiles(folderPath, "sim_nhmm_ind_delexp_params.txt");
rnhmm.WriteInputFiles(folderPath, "lrn_nhmm_ind_delexp_params.txt");
/**************Builds up the rainfall file to be read by NHMM *************************/
/*File dir = new File(parent, folderPath);
File writeFile = new File(dir,"HMM_Input.txt");
FileOutputStream fout = new FileOutputStream(writeFile);
Writer output = new BufferedWriter(new FileWriter(writeFile));
System.out.println(((Vector) NHMMrain.get(0)).size());
for(int k = 0; k <((Vector) NHMMrain.get(0)).size();k++)
{
output.write(((Vector) NHMMrain.get(0)).get(k) + "\t" +((Vector) NHMMrain.get(1)).get(k) + "\t" + ((Vector) NHMMrain.get(2)).get(k));
output.write("\n");
}
/******************************************************************/
/* this call downloads the GCM data */
/*for(int iYear=1982;iYear<2010;iYear++)
{
filename = "GCM_"+iYear+".txt";
urlString = servletURLPattern_GCM.replace("{{year}}", String.valueOf(iYear)).replace("{{minLat}}", String.valueOf(GCMLatMin))
.replace("{{maxLat}}",String.valueOf(GCMLatMax)).replace("{{minLon}}", String.valueOf(GCMLonmin)).
replace("{{maxLon}}", String.valueOf(GCMLonMax));
System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
}
/*this builds up a single input to GCM and keeps it in a single file*/
/* Vector vGCM = new Vector();
for(int iYear=1982;iYear<2010;iYear++)
{
System.out.println(folderPath+ "/GCM_"+iYear+".txt");
File aGCM = new File(this.getClass().getResource("/" +folderPath+ "/GCM_"+iYear+".txt").getFile());
BufferedReader input = new BufferedReader(new FileReader(aGCM));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
System.out.println(line);
vGCM.add(line);
}
}
File dir = new File(parent, folderPath);
File writeFile = new File(dir,"GCM.txt");
FileOutputStream fout = new FileOutputStream(writeFile);
Writer outputGCM = new BufferedWriter(new FileWriter(writeFile));
for (int k = 0; k < vGCM.size(); k++){
outputGCM.write(vGCM.get(k).toString());
outputGCM.write("\n");
outputGCM.flush();
}
outputGCM.close();
/*Call the HMM simulations at this point */
/*Once the dataset for HMM is run...call the NHMM to run at this point*/
ReadNHMMOutput rd = new ReadNHMMOutput();
for(int i = 0; i <vec.size();i++)
{
Lon = Double.parseDouble(vec.get(i).toString());
Lat = Double.parseDouble(vec.get(i+1).toString());
i++;
}
/*Once the NHMM is ready call the ReadNHMMOutput to build the input rainfall file*/
/* At this point Call the
/* Write the input files for the crop models */
/* rnhmm.WriteInputFiles(folderPath, "/DATA.CDE");
rnhmm.WriteInputFiles(folderPath, "/DETAIL.CDE");
rnhmm.WriteInputFiles(folderPath, "/DSMODEL.ERR");
rnhmm.WriteInputFiles(folderPath, "/GCOEFF.CDE");
rnhmm.WriteInputFiles(folderPath, "/GRSTAGE.CDE");
rnhmm.WriteInputFiles(folderPath, "/JDATE.CDE");
rnhmm.WriteInputFiles(folderPath, "/PEST.CDE");
rnhmm.WriteInputFiles(folderPath, "/SGCER040.CUL");
rnhmm.WriteInputFiles(folderPath, "/SGCER040.ECO");
rnhmm.WriteInputFiles(folderPath, "/SGCER040.SPE");
rnhmm.WriteInputFiles(folderPath, "/Simulation.cde");
rnhmm.WriteInputFiles(folderPath, "/SOIL.CDE");
rnhmm.WriteInputFiles(folderPath, "/WEATHER.CDE");
rnhmm.WriteInputFiles(folderPath, "/soil.sol");
rnhmm.WriteInputFiles(folderPath, "/GATI0301.WTH");
//rnhmm.WriteInputFiles(folderPath2, "GCM.txt");
//rnhmm.WriteInputFiles(folderPath2, "DSSATCSM40");
rnhmm.WriteInputFiles(folderPath, "/1-21.WTH");*/
/********Read the crop Model File into the Folder*********/
/*FileChannel ic = new FileInputStream("DSSATCSM40").getChannel();
System.out.println(folderPath);
FileChannel oc = new FileOutputStream(folderPath+"/DSSATCSM40").getChannel();
ic.transferTo(0,ic.size(),oc);
ic.close();
oc.close();*/
//}
//System.out.println(HMMInput);
/* filename = folderPath+ "/Tmax.cdf";
urlString = servletURLPattern_Tmax.replace("{{minLat}}", String.valueOf(minLat))
.replace("{{maxLat}}",String.valueOf(maxLat)).replace("{{minLon}}", String.valueOf(minLon)).
replace("{{maxLon}}", String.valueOf(maxLon)).replace("{{id}}",String.valueOf(id));
//System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);
/*filename = folderPath2+ "/[X+Y]Tmin.tsv";
urlString = servletURLPattern_Tmin.replace("{{minLat}}", String.valueOf(minLat))
.replace("{{maxLat}}",String.valueOf(maxLat)).replace("{{minLon}}", String.valueOf(minLon)).
replace("{{maxLon}}", String.valueOf(maxLon)).replace("{{id}}",String.valueOf(id));
//System.out.println("urlString :" + urlString);
saveUrl(filename , urlString);*/
//}//end of while
//}//end of if
}
/*catch(ClassNotFoundException Exception) {
System.out.println("error occoured during loading the driver");
}*/
catch(Exception e){
System.out.println("error occoured during connecting " + e);
e.printStackTrace();
}
} | 8 |
public List<Map<Integer, Integer>> buildRGBHistogram() {
List<Map<Integer, Integer>> output = new ArrayList<Map<Integer, Integer>>();
Map<Integer, Integer> red = new TreeMap<Integer, Integer>();
Map<Integer, Integer> green = new TreeMap<Integer, Integer>();
Map<Integer, Integer> blue = new TreeMap<Integer, Integer>();
//Loops through the X axis, which will contain the pixel values
for (int x = 0; x < getMaxval(); x++) {
int r = 0, g = 0, b = 0;
//Loops through the Y axis, which will contain the pixel quantity
for (int i = 0; i < data.length; i++) {
if (data[i] == x) {
if (i % 3 == 0) r++;
else if (i % 3 == 1) g++;
else if (i % 3 == 2) b++;
}
}
//Puts the X and Y values on the map
red.put(x, r);
green.put(x, g);
blue.put(x, b);
}
output.add(red);
output.add(green);
output.add(blue);
return output;
} | 6 |
@Override
public final BEXList children() {
final int key = this._key_;
final BEXFileLoader owner = this._owner_;
switch (BEXLoader._typeOf_(key)) {
case BEX_ELEM_NODE: {
final int ref = BEXLoader._refOf_(key);
final int contentRef = owner._chldContentRef_.get(ref);
if (contentRef >= 0) return new BEXListLoader(BEXLoader._keyOf_(BEXLoader.BEX_CHTX_LIST, ref), 0, owner);
return new BEXListLoader(BEXLoader._keyOf_(BEXLoader.BEX_CHLD_LIST, ref), -contentRef, owner);
}
case BEX_VOID_TYPE:
case BEX_ATTR_NODE:
case BEX_TEXT_NODE:
case BEX_ELTX_NODE:
return new BEXListLoader(owner);
}
throw new IAMException(IAMException.INVALID_HEADER);
} | 6 |
@Override
public void execute(DebuggerVirtualMachine dvm) {
dvm.setStepInPending(true);
dvm.setRunning(true);
} | 0 |
public void establishConnection() {
try {
// Load Driver
Class.forName(DRIVER).newInstance();
// Establish connection
connection = DriverManager.getConnection(URL);
System.out.println(URL + " connected...");
} catch ( SQLException ex ) {
System.err.println("SQLException: " + ex.getMessage());
} catch ( ClassNotFoundException ex ) {
Logger.getLogger(HighScores.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(HighScores.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(HighScores.class.getName()).log(Level.SEVERE, null, ex);
}
} | 4 |
private String produceBorders() {
BufferedImage bordersImage = null;
if (ioflags.SAVE)
bordersImage = new BufferedImage(chunksX * MyzoGEN.DIMENSION_X, chunksY * MyzoGEN.DIMENSION_Y, BufferedImage.TYPE_INT_ARGB);
for (Tile tile : MyzoGEN.getOutput().getTilesArray().values()) {
Point[] surrPoints = Utils.getSurroundingPoints(tile.origin);
//if (!tile.wall) {
if (isBorderHeight(tile, surrPoints)) {
/**byte be = Borders.calcBorderTypeByTileTypeEdges(tile, surrPoints, false);
byte bc = Borders.calcBorderTypeByTileTypeCorners(tile, surrPoints, false);
tile.borderHeightEdges = be;
tile.borderHeightCorners = bc;
tile.borderHeightType = Tiles.STONE_WALL;**/
Borders.calculateHeightData(tile, surrPoints);
produceWall(tile, surrPoints, bordersImage);
if (ioflags.SAVE) {
bordersImage.setRGB(tile.origin.x, tile.origin.y, new Color(0, Math.abs(tile.borderFlagTwo), 0, 255).getRGB());
}
}
if (isBorderBiomes(tile, surrPoints)) {
/**byte be = Borders.calcBorderTypeByTileTypeEdges(tile, surrPoints, true);
byte bc = Borders.calcBorderTypeByTileTypeCorners(tile, surrPoints, true);
tile.borderBiomesEdges = be;
tile.borderBiomesCorners = bc;
tile.borderBiomesType = getBorderTypeBiomes(tile, surrPoints);**/
Borders.calculateBiomeData(tile, surrPoints);
if (ioflags.SAVE) {
//System.out.println(tile.borderFlagOne);
bordersImage.setRGB(tile.origin.x, tile.origin.y, new Color(Math.abs(tile.borderFlagOne), 0, 0, 255).getRGB());
}
}
//}
}
if (ioflags.SAVE && bordersImage != null) {
Utils.saveImage(bordersImage, "output/"+name+"/overviews/borders_overview.png");
if (details) System.out.println("Borders overview produced. It can be found in: output/"+name+"/overviews/");
}
return "No errors.";
} | 9 |
@XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "KeyReference", scope = ReferenceList.class)
public JAXBElement<ReferenceType> createReferenceListKeyReference(ReferenceType value) {
return new JAXBElement<ReferenceType>(_ReferenceListKeyReference_QNAME, ReferenceType.class, ReferenceList.class, value);
} | 0 |
private void addServerNotifierAsListener() {
EventsControlSystem ecs = rcs.getECS();
for (Integer decoder : model.getDecodersId()) {
ecs.addListener(Protocol.EVENT_DECODER_STATE0, decoder, serverNotifier);
ecs.addListener(Protocol.EVENT_DECODER_STATE1, decoder, serverNotifier);
ecs.addListener(Protocol.EVENT_DECODER_STATE2, decoder, serverNotifier);
ecs.addListener(Protocol.EVENT_DECODER_STATE3, decoder, serverNotifier);
}
for (Integer lissy : model.getLissiesId()) {
ecs.addListener(Protocol.EVENT_LISSY_SIGNAL, lissy, serverNotifier);
}
for (Integer semaphore : model.getSemaphoresId()) {
ecs.addListener(Protocol.EVENT_TURNOUT_STATE, semaphore, serverNotifier);
}
for (Integer turning : model.getTurningsId()) {
ecs.addListener(Protocol.EVENT_TURNOUT_STATE, turning, serverNotifier);
}
for (Integer locomotive : model.getLocomotivesId()) {
ecs.addListener(Protocol.EVENT_LOK_DIRECTION, locomotive, serverNotifier);
ecs.addListener(Protocol.EVENT_LOK_F_STATE, locomotive, serverNotifier);
ecs.addListener(Protocol.EVENT_LOK_GLOBAL_STATE, locomotive, serverNotifier);
ecs.addListener(Protocol.EVENT_LOK_SPEED, locomotive, serverNotifier);
}
for (Integer sensor : model.getSensorsId()) {
ecs.addListener(Protocol.EVENT_SENSOR_STATE, sensor, serverNotifier);
ecs.addListener(Protocol.EVENT_SENSOR_STATE2, sensor, serverNotifier);
}
for (Integer slot : model.getSlotsId()) {
ecs.addListener(Protocol.EVENT_SLOT_CONSIST, slot, serverNotifier);
ecs.addListener(Protocol.EVENT_SLOT_STATE, slot, serverNotifier);
}
for (Integer track : model.getTracksId()) {
ecs.addListener(Protocol.EVENT_SENSOR_STATE, track, serverNotifier);
}
} | 8 |
protected void writeRow() throws IOException {
final Iterator<String> titlesIter = columnTitles.iterator();
while (titlesIter.hasNext()) {
final String columnTitle = titlesIter.next();
if (getRowMap() != null) {
if (titlesIter.hasNext()) {
writeWithDelimiter(getRowMap().get(columnTitle));
} else {
write(getRowMap().get(columnTitle));
}
}
}
} | 3 |
private boolean colchete() {
//<colchete> ::= “[“ <inteiro> “]” <colchete> | λ*/
boolean erro = false;
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" [")) {
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[0].equals("Numero Inteiro")) {
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" ]")) {
if(!this.colchete()) erro = true;
}else{
erro = true;
errosSintaticos.erroSemColcheteFechadoParametro(tipoDoToken[3], tipoDoToken[1]);
}
} else {
erro = true;
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
}else {
erro = true;
errosSintaticos.erroSemIndiceMatrizParametro(tipoDoToken[3], tipoDoToken[1]);
}
}else{
erro = true;
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
}else{
erro = true;
errosSintaticos.erroSemColcheteAbertoParametro(tipoDoToken[3], tipoDoToken[1]);
}
}else{
erro = true;
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "colchete");
zerarTipoToken();
}
return erro;
} | 7 |
public static String capitalizeEveryWord(String string){
boolean lastWasSpace = false;
char[] stringArray = string.toCharArray();
if(stringArray.length == 0){
return "-1";
}
stringArray[0] = Character.toUpperCase(stringArray[0]);
for (int x = 1;x <= stringArray.length - 1; x++){
if(stringArray[x] == ' '){
lastWasSpace = true;
}
else if(lastWasSpace){
stringArray[x] = Character.toUpperCase(stringArray[x]);
lastWasSpace = false;
}
else{
stringArray[x] = Character.toLowerCase(stringArray[x]);
}
}
string = new String(stringArray);
return string;
} | 4 |
public Maze(int nRows, int nCols)
{
act_rows = nRows/2;
act_cols = nCols/2;
rows = act_rows*2+1;
cols = act_cols*2+1;
feild = new RoomType[rows][cols];
current = new int[act_cols*2-1];
next = new int[act_cols*2-1];
/* Sets the maze to filled */
for(int i =0; i<feild[0].length; i++){
for(int j=0; j<feild.length; j++){
feild[i][j] = MAZE_WALL;
}
}
for(int i=0; i<next.length; i++){
next[i] = UNDETERMINED;
}
/* initialize the first row to unique sets */
for(int i=0; i<current.length; i+=2){
current[i] = i/2+1;
if(i != current.length-1)
current[i+1] = SET_WALL;
}
numSet = current[current.length-1];
} | 5 |
private ArrayList<String> splitMsg(String str) {
ArrayList<String> array = new ArrayList<String>();
int curPos;
int len = str.length();
int countLeft = 0, countRight = 0;
int startIndex = 0;
char ch;
for (curPos = 0; curPos < len; ++curPos) {
ch = str.charAt(curPos);
if (ch == '(') {
++countLeft;
}
else if (ch == ')') {
++countRight;
}
if (countLeft > 0 && countRight > 0
&& countLeft == countRight) {
if (curPos != len - 1) {
array.add(str.substring(startIndex, curPos + 1));
startIndex = curPos + 1;
countLeft = 0;
countRight = 0;
}
else {
array.add(str);
}
}
}
return array;
} | 7 |
void mapOutField(Object from, String from_out, Object to, String to_field) {
if (from == ca.getComponent()) {
throw new ComponentException("wrong connect:" + to_field);
}
ComponentAccess ca_from = lookup(from);
Access from_access = ca_from.output(from_out);
checkFA(from_access, from, from_out);
try {
FieldContent.FA f = new FieldContent.FA(to, to_field);
ca_from.setOutput(from_out, new FieldObjectAccess(from_access, f,
ens));
if (log.isLoggable(Level.CONFIG)) {
log.config(String.format("@Out(%s) -> field(%s)", from_access,
f.toString()));
}
} catch (Exception E) {
throw new ComponentException("No such field '"
+ to.getClass().getCanonicalName() + "." + to_field + "'");
}
} | 3 |
public static Vector arrayListToVector (ArrayList someArrayList) {
// if we've got a null param, leave
if (someArrayList == null) {
return null ;
} // end if
// try to create a vector
Vector someVector = new Vector () ;
// if we failed, leave
if (someVector == null) {
return null ;
} // end if
// okay, we've got a right-sized Vector, it's .... Copy Time !
// for each element of the ArrayList ...
for (int counter = 0, aLsize = someArrayList.size(); counter < aLsize; counter++) {
// copy it to the Vector
someVector.add(someArrayList.get(counter)) ;
} // end for
// done
return someVector ;
} // end arrayListToVector | 3 |
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(columnIndex < 0 || columnIndex >= getColumnCount())
return null;
if(rowIndex < 0 || rowIndex >= getRowCount())
return null;
switch (columnIndex) {
case 0:
return gs.playerStates.get(rowIndex).getNickname();
case 1:
if(gs.playerStates.get(rowIndex).getNickname().equals(gs.activePlayer)) {
return "turn";
}
if(gs.playerStates.get(rowIndex).isActive()) {
return "wait";
} else {
return "finished";
}
case 2:
return gs.playerStates.get(rowIndex).getScore();
}
return null;
} | 9 |
public boolean isSameTree2(TreeNode p, TreeNode q){
Stack<TreeNode> pstack = new Stack<TreeNode>();
Stack<TreeNode> qstack = new Stack<TreeNode>();
pstack.push(p);
qstack.push(q);
while(!pstack.isEmpty() && !qstack.isEmpty()){
p = pstack.pop();
q = qstack.pop();
if (p != null && q != null && p.val == q.val){
pstack.push(p.right);
pstack.push(p.left);
qstack.push(q.right);
qstack.push(q.left);
} else if (p == null && q == null)
continue;
else
return false;
}
if (!pstack.isEmpty() || !qstack.isEmpty())
return false;
return true;
} | 9 |
public String testStart(String appKey, String userKey, String testId) {
try {
appKey = URLEncoder.encode(appKey, "UTF-8");
userKey = URLEncoder.encode(userKey, "UTF-8");
testId = URLEncoder.encode(testId, "UTF-8");
} catch (UnsupportedEncodingException e) {
BmLog.error(e);
}
return String.format("%s/api/rest/blazemeter/testStart/?app_key=%s&user_key=%s&test_id=%s", SERVER_URL, appKey, userKey, testId);
} | 1 |
public int maximalRectangle(char[][] matrix)
{
int numRows = matrix.length;
if (numRows == 0) {
return 0;
}
int numCols = matrix[0].length;
if (numCols == 0) {
return 0;
}
int maxArea = 0;
int[] heights = new int[numCols];
int[] leftBoundaries = new int[numCols];
int[] rightBoundaries = new int[numCols];
Arrays.fill(leftBoundaries, Integer.MIN_VALUE);
Arrays.fill(rightBoundaries, Integer.MAX_VALUE);
for (int row = 0; row < numRows; ++row) {
int currentLeftBound = Integer.MIN_VALUE;
// For each column we calculate the area of the rectangle
// starting at the current row, whose height is maximized.
// Perform pass sweep accross columns:
// 1. From left to right to figure out rectangle height and
// boundary of the rectangle on the left side.
for (int col = 0; col < numCols; ++col) {
if (matrix[row][col] == '1') {
heights[col] = heights[col] + 1;
if (currentLeftBound == Integer.MIN_VALUE) {
currentLeftBound = col;
}
// Pick the left bound that is right-most
leftBoundaries[col] = Math.max(currentLeftBound, leftBoundaries[col]);
} else {
heights[col] = 0;
currentLeftBound = Integer.MIN_VALUE;
leftBoundaries[col] = Integer.MIN_VALUE;
}
}
// 2. From right to left to figure out the boundary
// of the rectangle on the right side and then
// calculate the area of the rectangle.
int currentRightBound = Integer.MAX_VALUE;
for (int col = numCols - 1; col >= 0; --col) {
if (matrix[row][col] == '1') {
if (currentRightBound == Integer.MAX_VALUE) {
currentRightBound = col;
}
// Pick the right bound that is left-most
rightBoundaries[col] = Math.min(currentRightBound, rightBoundaries[col]);
// Calculate rectangle area
int rectangleArea = (rightBoundaries[col] - leftBoundaries[col] + 1) * heights[col];
maxArea = Math.max(maxArea, rectangleArea);
} else {
currentRightBound = Integer.MAX_VALUE;
rightBoundaries[col] = Integer.MAX_VALUE;
}
}
}
return maxArea;
} | 9 |
private PaymentsAPI getPaymentApi() {
if (paymentsApi == null) {
paymentsApi = new PaymentsAPI(config);
}
return paymentsApi;
} | 1 |
public void RenderAll(Shader shader, RenderingEngine renderingEngine)
{
Render(shader, renderingEngine);
for(GameObject child : m_children)
child.RenderAll(shader, renderingEngine);
} | 1 |
public static TreeMap<String, Double> processString(String line) {
TreeMap<String, Double> output = new TreeMap<String, Double>();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken()
.replaceAll("[^\\p{Alpha}]+", "").toLowerCase();
for (int i = 0; i < token.length(); i += 2) { //split the string for char combinations
String substr = token;
if (token.length() > 1) { // filter words with only one character
if (i < token.length() - 1)
substr = substr.substring(i, i + 2);
else if ((i == token.length() - 1))
substr = substr.substring(i - 1);
//increment object counter if exists, else add
if(output.containsKey(substr))
output.put(substr, output.get(substr)+1);
else
output.put(substr, new Double(1));
}
}
}
//System.out.println(output.toString()); //DELME
//System.out.println(entriesSortedByValues(output)); //DELME
Double sum = 0.0; //needed for normalization
Iterator it = output.entrySet().iterator();
while(it.hasNext()) {
Entry<String,Double> entry = (Entry<String, Double>) it.next();
Double value = entry.getValue();
sum+=value;
}
it = output.entrySet().iterator();
Double leastOccurences=(sum/output.size());
while(it.hasNext()) {
Entry<String,Double> entry = (Entry<String, Double>) it.next();
String key = entry.getKey();
Double value = entry.getValue();
if(value>leastOccurences) //must appear more than average times
output.put(key, value/sum); //calculate percentage
else
it.remove(); //..or remove from map
}
return output;
} | 9 |
public synchronized void addAnimation(String string, BufferedImage[] images) {
if(this.getCurrentAnimationType().equals("")){
this.setCurrentAnimationType(string);
}
if(this.animations == null){
this.animations = new Hashtable<>();
}
if(images == null){
images = new BufferedImage[0];
}
this.animations.put(string, images);
} | 3 |
boolean matchOrEmpty(int pips, int x, int y) {
return ((x < 0 || x >= w || y < 0 || y >= h) || (field[x][y] == -1) || (field[x][y] == pips));
} | 5 |
boolean isSim() {
return file != null && (file.getName().endsWith("sim")
|| file.getName().endsWith("luca")
|| file.getName().endsWith("fast")
|| file.getName().endsWith("esp")
|| file.getName().endsWith("dds"));
} | 5 |
@Test
public void testMatrix3fFloatArray() {
float[] entries = new float[9];
for(int i = 0; i < 9; ++i)
entries[i] = i;
Matrix3f m = new Matrix3f(entries);
for(int i = 0; i < 9; i++)
assertEquals(m.entries[i],entries[i],EPSILON);
} | 2 |
public DogTrack(int tracksize) {
this.tracksize = tracksize;
posFido = 0;
posSpot = 0;
posRover = 0;
} | 0 |
private void checkRoute(int[] route, int offset){
if(offset == salesman.n){
count++;
if(count%100000 == 0){
System.out.println("check route "+count);
}
double cost = salesman.calculateCosts(route);
if(minCosts < 0 || cost < minCosts){
minCosts = cost;
System.arraycopy(route,0,minRoute,0,route.length);
}
return;
}
loop: for(int i = 1;i<salesman.n;i++){
for(int j = 0;j<offset;j++){
if(route[j] == i){
continue loop;
}
}
route[offset] = i;
checkRoute(route,offset+1);
}
} | 7 |
@Override
public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) {
if (e.getDocument() == null) {
setEnabled(false);
} else {
setEnabled(true);
}
} | 1 |
private void splitCompounds(String equation, boolean reactantSide) throws SChemPException
{
StringTokenizer token = new StringTokenizer(equation, "+");
if(reactantSide)
{
reactantStrings = new String[token.countTokens()];
reactants = new Compound[reactantStrings.length];
rCoefficients = new int[reactantStrings.length];
}
else
{
productStrings = new String[token.countTokens()];
products = new Compound[productStrings.length];
pCoefficients = new int[productStrings.length];
}
int c = 0;
while(token.hasMoreTokens())
{
String temp = token.nextToken();
String coef = "";
String compound = "";
boolean doneWithCoef = false;
for(int k = 0; k < temp.length(); k++)
{
if(Character.isDigit(temp.charAt(k)) && !doneWithCoef)
{
coef += temp.charAt(k);
}
else
{
doneWithCoef = true;
compound += temp.charAt(k);
}
}
if(reactantSide)
{
if(!coef.equals(""))
rCoefficients[c] = Integer.parseInt(coef);
reactantStrings[c] = compound;
reactants[c] = Compound.parseCompound(compound);
}
else
{
if(!coef.equals(""))
pCoefficients[c] = Integer.parseInt(coef);
productStrings[c] = compound;
products[c] = Compound.parseCompound(compound);
}
c++;
}
} | 8 |
int[] isoFromFixed(long date) {
int weekyear = gjYearFromFixed(date - 3);
int nextWeekyear;
if (weekyear == -1) {
nextWeekyear = 1;
} else {
nextWeekyear = weekyear + 1;
}
if (date >= fixedFromISO(nextWeekyear, 1, 1)) {
weekyear = nextWeekyear;
}
int weekOfWeekyear = (int)(div(date - fixedFromISO(weekyear, 1, 1), 7) + 1);
int dayOfWeek = (int)amod(date, 7);
return new int[]{weekyear, weekOfWeekyear, dayOfWeek};
} | 2 |
public void setClockForGroup(VectorClock clockForGroup) {
this.clockForGroup = clockForGroup;
} | 0 |
private int calculaYparaPuntoCiclista(Ciclista cic,
TreeMap<Integer, Integer> ar) {
int yresu = 0;
int dify = 0;
int yacum = Constantes.ALTO_VENTANA / 4;
boolean encontrado = false;
Iterator<Entry<Integer, Integer>> it = ar.entrySet().iterator();
Iterator<Entry<Integer, Integer>> itaux = ar.entrySet().iterator();
if (it.hasNext()) {
itaux.next();
}
while (itaux.hasNext() && !encontrado) {
Entry<Integer, Integer> tramoini = it.next();
if (it.hasNext()) {
Entry<Integer, Integer> tramofin = itaux.next();
if (cic.getBici().getEspacioRecorrido() >= tramoini.getKey()
&& cic.getBici().getEspacioRecorrido() < tramofin
.getKey()) {
encontrado = true;
int metro_en_el_tramo_del_ciclista = (int) (cic.getBici()
.getEspacioRecorrido() - tramoini.getKey());
int diftramos = tramofin.getKey() - tramoini.getKey();
dify = tramoini.getValue();
int yfintramo = yacum + dify;
yresu = metro_en_el_tramo_del_ciclista * dify / diftramos;
yresu = yacum
- (metro_en_el_tramo_del_ciclista * dify / diftramos)
- Constantes.ANCHO_PUNTO_CICLISTA / 2;
}
}
yacum = yacum - tramoini.getValue();
}
return yresu;
} | 6 |
public static synchronized void playSound() {
new Thread(new Runnable() {
public void run() {
try {
InputStream in = new FileInputStream("sounds/goal.wav");
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} | 1 |
@EventHandler
public void onSignChange(SignChangeEvent event)
{
if(!HotelCount.isAdmin(event.getPlayer()) && !HotelCount.canCreate(event.getPlayer()))
return;
if(event.getLine(0).equalsIgnoreCase("[Counter]"))
{
String region = event.getLine(1);
int low = 0;
int high = 0;
try
{
low = Integer.parseInt(event.getLine(2));
}
catch(Exception exception) { }
try
{
high = Integer.parseInt(event.getLine(3));
}
catch(Exception exception1) { }
int count[] = HotelCount.getSM().getRooms(event.getLine(1), low, high, event.getBlock().getWorld().getName());
event.setLine(0, (new StringBuilder("Gesamt: ")).append(count[SignManager.ALL]).toString());
event.setLine(1, (new StringBuilder("Frei : ")).append(count[SignManager.FREE]).toString());
event.setLine(2, (new StringBuilder("Belegt: ")).append(count[SignManager.TAKEN]).toString());
if(!HotelCount.getSM().freeRoom.isEmpty())
event.setLine(3, HotelCount.getSM().freeRoom);
else
event.setLine(3, "No free room"); // auf deutsch passt es nicht aufs schild!
HotelCount.getSM().addAgent(event.getBlock().getLocation(), region, low, high);
}
} | 6 |
public ComboBoxModel<String> GetListClasse(){
//String columnNames[] = { "Lib Classe"};
DefaultComboBoxModel<String> defModel = new DefaultComboBoxModel<String>();
//defModel.setColumnIdentifiers(columnNames);
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
if (con == null)
System.out.println("con classe ko ");
else
System.out.println("con classe ok ");
Statement statement = con.createStatement();
if (statement == null)
System.out.println("statement classe ko ");
else
System.out.println("statement classe ok ");
//System.out.println("test1 : " + SaisieNom.getText());
ResultSet rs = statement.executeQuery("select * from \"CLASSE\" order by LIBCLASSE" );
//ResultSet rs = statement.executeQuery("select * from \"classe\" where nom='"+SaisieNom.getText()+"'" );
//ResultSet rs = statement.executeQuery("SELECT table_name FROM user_tables" );
defModel.addElement( "All");
String LibClasse = "";
while (rs.next()) {
LibClasse=rs.getString("LIBCLASSE");
defModel.addElement( LibClasse);
}
rs.close();
statement.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
return defModel;
} | 4 |
public WumpusPerception addHunter(final AID senderAID) {
if(log.isLoggable(Logger.INFO))
log.log(Logger.INFO, "addHunter()");
WumpusPerception perception = null;
if (senderAID != null) {
Hunter hunter = new Hunter(senderAID);
if (!hunters.contains(hunter)) {
this.hunters.add(hunter);
worldMap[hunter.getxCoord()][hunter.getyCoord()].hunters.add(hunter);
}
notifyHunterListListeners();
notifyWorldModelListeners();
perception = getPerception(worldMap[hunter.getxCoord()][hunter.getyCoord()]);
return perception;
} else {
//TODO: sinnvoll ändern
throw new RuntimeException();
}
} | 3 |
public static void createTables() throws SQLException, ClassNotFoundException {
// database.plugin.debug("Creating SQLite tables...");
Class.forName("org.sqlite.JDBC");
Connection con = getConnection();
Statement stat = con.createStatement();
if (tableExists("Lifestones") == false) {
System.out.println("Creating Lifestones.Lifestones table.");
stat.executeUpdate("CREATE TABLE `Lifestones` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `world` VARCHAR(32) NOT NULL, `x` INT NOT NULL, `y` INT NOT NULL, `z` INT NOT NULL)");
}
if (tableExists(attunementsTbl) == false) {
System.out.println("Creating Lifestones.Attunements table.");
stat.executeUpdate("CREATE TABLE `"
+ attunementsTbl
+ "` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player` VARCHAR(32) NOT NULL, `world` VARCHAR(32) NOT NULL, `x` DOUBLE NOT NULL, `y` DOUBLE NOT NULL, `z` DOUBLE NOT NULL, `yaw` FLOAT NOT NULL, `pitch` FLOAT NOT NULL)");
}
if (tableExists("Attunements") == true) {// old table;
System.out.println("Removing unique attribute from player in Attunements.");
stat.executeUpdate("INSERT INTO `" + attunementsTbl + "` SELECT * FROM `Attunements`;");
stat.executeUpdate("DROP TABLE `Attunements`;");
}
stat.close();
con.close();
} | 3 |
static public void main(String[] arguments) {
String msg = null;
// create the configuration
Config config = new Config();
// see:
// http://www.javaworld.com/javaworld/jw-08-2004/jw-0816-command.html?page=5
Options opt = new Options(arguments, 2);
// convert fasta: arg1 = fasta files, arg2 = bases files
// c = comma separated list of chromosomes e.g. "1,3,18,X"
opt.addSet("cfset", 2).addOption("cf").addOption("c", Separator.BLANK, Multiplicity.ZERO_OR_ONE);
// extract exons: arg1 = reference bases, arg2 = input bases, arg3 = output exon.bases, arg4 = output exon.locations
// c = comma separated list of chromosomes e.g. "1,3,18,X"
opt.addSet("eeset", 4).addOption("ee").addOption("c", Separator.BLANK, Multiplicity.ZERO_OR_ONE);
// extracts exons from the file provided by RB
// arg2 = input .fa, arg2 = output exon.bases, arg3 = output exon.locations
opt.addSet("rbset", 3).addOption("rb").addOption("c", Separator.BLANK, Multiplicity.ZERO_OR_ONE);
// add -d to all of them
opt.addOptionAllSets("d", Separator.BLANK, Multiplicity.ZERO_OR_ONE);
OptionSet set = opt.getMatchingSet();
if (set == null) {
GLT.showHelp();
// Print usage hints
System.exit(1);
}
// set the directory
if (set.isSet("d")) {
String directory = set.getOption("d").getResultValue(0);
config.setDirectory(directory);
}
msg = "Working directory:" + config.getDirectory();
GLT.logger.info(msg);
// set the chromosomeIds
if (set.isSet("c")) {
String chromosomeIds = set.getOption("c").getResultValue(0);
List<String> ids = new ArrayList<String>(Arrays.asList(chromosomeIds.split(",")));
config.setChromosomeIds(ids);
}
msg = "Working with chromosomes " + config.getChromosomeIds().toString();
GLT.logger.info(msg);
int i = 0;
// Evaluate the different option sets
if (set.getSetName().equals("cfset")) {
// set the different file name masks
config.setInputChromosomeFastaFileName(set.getData().get(i++));
config.setOutputChromosomeBasesFileName(set.getData().get(i++));
for (String id : config.getChromosomeIds()) {
GLT.convertFasta(config, id);
}
}
if (set.getSetName().equals("eeset")) {
// set the different file name masks
config.setReferenceChromosomeBasesFileName(set.getData().get(i++));
config.setInputChromosomeBasesFileName(set.getData().get(i++));
config.setOutputExonBasesFileName(set.getData().get(i++));
config.setOutputExonLocationsFileName(set.getData().get(i++));
for (String id : config.getChromosomeIds()) {
GLT.compileExons(config, id);
Chromosome chromosome = Chromosome.get(id);
// we may have picked up duplicate ones, so throw those away first,
// because it is unnecessary to process them twice
GLT.removeDuplicateExons(config, chromosome);
// find them in the input file
GLT.locateExons(config, chromosome);
// and throw the duplicated ones away again for good measure
GLT.removeDuplicateExons(config, chromosome);
GLT.exportExons(config, chromosome);
}
}
if (set.getSetName().equals("rbset")) {
// set the different file name masks
config.setInputChromosomeFastaFileName(set.getData().get(i++));
config.setOutputExonBasesFileName(set.getData().get(i++));
config.setOutputExonLocationsFileName(set.getData().get(i++));
for (String id : config.getChromosomeIds()) {
GLT.exportRBExons(config, id);
}
}
} | 9 |
@Basic
@Column(name = "FUN_HABILITADO")
public String getFunHabilitado() {
return funHabilitado;
} | 0 |
public void printResult(DefaultTableModel table) {
count = 100;
try {
while ((count > 0) && result.next()) {
count--;
Vector<String> data = new Vector<String>();
for (int i = 1; i <= resultMetaData.getColumnCount(); i++) {
Object res = result.getObject(i);
data.add( res == null ? "NULL" : res.toString());
}
dataList.add(data);
}
table.setDataVector(dataList, header);
if (count > 0) {
close();
}
} catch (SQLException e) {
System.err.println("Error when trying to print the result of " + query);
}
} | 6 |
@Override
public void execute() throws BuildException {
super.execute();
if (jdeHome == null) {
throw new BuildException("jdehome not set");
}
File lib = new File(jdeHome, "lib");
if (lib.isDirectory()) {
Path apiPath = new Path(getProject());
apiPath.setLocation(new File(lib, "net_rim_api.jar"));
imports.add(apiPath);
} else {
throw new BuildException("jde home missing \"lib\" directory");
}
if (output == null) {
throw new BuildException("output is a required attribute");
}
if (destDir == null) {
destDir = getProject().getBaseDir();
} else {
if (!destDir.isDirectory()) {
throw new BuildException("destdir must be a directory");
}
}
if (srcs.size() == 0) {
throw new BuildException("srcdir attribute or <src> element required!");
}
String[] files = srcs.list();
srcs = new Path(getProject());
File f;
// iterate through all source files
for (String file : files) {
f = new File(file);
// when source file is actually a directory, create fileset
if (f.isDirectory()) {
FileSet fs = new FileSet();
fs.setDir(f);
srcs.addFileset(fs);
} else { // otherwise add the source file back into the path object
srcs.setLocation(f);
}
}
// blackberry jde will create this file and pass it to the rapc command
jdp.writeManifest(new File(destDir, output+".rapc"), output);
if (!Utils.isUpToDate(srcs, new File(destDir, output+".cod"))) {
log(String.format("Compiling %d source files to %s", srcs.size(), output+".cod"));
executeRapc();
} else {
log("Compilation skipped, cod is up to date", Project.MSG_VERBOSE);
}
} | 9 |
private void validate() throws RrdException {
if(dsName == null || dsName.length() == 0) {
throw new RrdException("Invalid datasource name specified");
}
if(!isValidDsType(dsType)) {
throw new RrdException("Invalid datasource type specified: " + dsType);
}
if(heartbeat <= 0) {
throw new RrdException("Invalid heartbeat, must be positive: " + heartbeat);
}
if(!Double.isNaN(minValue) && !Double.isNaN(maxValue) && minValue >= maxValue) {
throw new RrdException("Invalid min/max values specified: " +
minValue + "/" + maxValue);
}
} | 7 |
public int surround(int y, int x, int[][] image){
int counter = 0;
for(int i = y - 1; i <= y+1; i++)
for(int j = x -1; j <= x+1; j++){
try{
if(image[i][j] == -16777216)
counter++;
}catch(Exception e){;}
}
if(image[y][x] == -16777216)
counter--;
return counter;
} | 5 |
public void compileFilenamesList(CMFile F, String regex, Vector<String> V)
{
if((!F.canRead())||(!F.isDirectory()))
return;
final String[] list=F.list();
String path=F.getAbsolutePath();
if(!path.endsWith("/"))
path+="/";
for(int l=0;l<list.length;l++)
{
final CMFile F2=new CMFile(path+list[l],null,CMFile.FLAG_LOGERRORS);
if(F2.isDirectory() && !(path+list[l]).equalsIgnoreCase("/resources/map"))
compileFilenamesList(F2,regex,V);
else
if(matches(regex,F2.getName()))
V.addElement(F.getAbsolutePath()+"/"+list[l]);
}
} | 7 |
@Id
@Column(name = "module_id")
public String getModuleId() {
return moduleId;
} | 0 |
public static void checkfile()
{
File file = new File(Homework_datetimecheck.memberurl);
boolean fexists = file.exists();
if (!fexists) {
new add_new_user().setVisible(true);
}
} | 1 |
public static String replaceChatColors(String s) {
for (ChatColor c : ChatColor.values()) {
s = s.replaceAll("&" + c.getChar(), ChatColor.getByChar(c.getChar()) + "");
}
return s;
} | 1 |
public static String escape(String string) {
char c;
String s = string.trim();
StringBuffer sb = new StringBuffer();
int length = s.length();
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
} | 6 |
public String toXmlString() {
StringBuilder sb = new StringBuilder("<apon:address>");
if (this.line1 != null) {
// optional
sb.append("<apon:line1>" + this.line1 + "</apon:line1>");
}
if (this.line2 != null) {
// optional
sb.append("<apon:line2>" + this.line2 + "</apon:line2>");
}
if (this.line3 != null) {
// optional
sb.append("<apon:line3>" + this.line3 + "</apon:line3>");
}
if (this.line4 != null) {
// optional
sb.append("<apon:line4>" + this.line4 + "</apon:line4>");
}
if (this.city != null) {
// optional
sb.append("<apon:city>" + this.city + "</apon:city>");
}
if (this.stateCode != null) {
// optional
sb.append("<apon:stateCode>" + this.stateCode + "</apon:stateCode>");
}
if (this.zip5 != null) {
// optional
sb.append("<apon:zip5>" + this.zip5 + "</apon:zip5>");
}
if (this.zip4 != null) {
// optional
sb.append("<apon:zip4>" + this.zip5 + "</apon:zip4>");
}
sb.append("</apon:address>");
return sb.toString();
} | 8 |
public static void main(String[] args) {
String[] stateList = CSVStrings.MALE_CSV.split("-");
String[] yearList = stateList[0].split(",");
for (int i = 1; i < yearList.length; i++)
{
_populationByYearList.add(new PopulationYear(Integer.parseInt(yearList[i])));
}
parse(stateList, PopulationYear.MALE);
stateList = CSVStrings.FEMALE_CSV.split("-");
parse(stateList, PopulationYear.FEMALE);
stateList = CSVStrings.PERSON_CSV.split("-");
parse(stateList, PopulationYear.PERSON);
try {
// Output File - clear it down first.
File outputFile = new File(OUTPUT_FILE);
outputFile.delete();
FileWriter fw = new FileWriter(OUTPUT_FILE, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("db." + COLLECTION_NAME + ".remove();\n\n");
for (PopulationYear py : _populationByYearList)
{
write(py.toString(), bw);
}
bw.write("\ndb." + COLLECTION_NAME + ".ensureIndex({year: 1});");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 3 |
private static void displayPatients(ResultSet rs)throws SQLException{
StringBuilder bf = new StringBuilder();
while (rs.next()){
bf.append(rs.getInt("pid")).append(": ");
bf.append(rs.getString("firstname")).append(" ");
bf.append(rs.getString("lastname"));
System.out.println(bf.toString());
bf.delete(0, bf.length());
}
} | 1 |
public BoardNode[] startingNodes(int color){
int count = 0;
if(color == 1){
int y;
for(y = 1; y<7; y++){
if(this.getNode(0, y).getColor() == color){
count++;
}
}
y = 1;
BoardNode[] start = new BoardNode[count];
count = 0;
for(; y < 7; y++){
if(this.getNode(0, y).getColor() == color){
start[count] = this.getNode(0, y);
count++;
}
}
return start;
}
else{
int x;
for(x = 1; x < 7; x++){
if(this.getNode(x, 0).getColor() == color){
count++;
}
}
x = 1;
BoardNode[] start = new BoardNode[count];
count = 0;
for(; x<7; x++){
if(this.getNode(x, 0).getColor() == color){
start[count] = this.getNode(x, 0);
count++;
}
}
return start;
}
} | 9 |
public int divide(int dividend, int divisor) {
int result = 0;
if (Math.abs(dividend) < Math.abs(divisor) || dividend == 0 || divisor == 0) {
return result;
}
boolean isPositive = true;
if (dividend < 0 && divisor > 0 || dividend > 0 && divisor < 0) {
isPositive = false;
}
if (divisor == 1 && dividend == Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return result;
} | 9 |
@Override
public void processOneGameTick(long lastFrameTime) {
entityManager = LLP.entityManager;
buffer = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
long offsetX = 0;
long offsetY = 0;
if (LLP.player != null) {
offsetX = entityManager.getComponent(LLP.player, Position.class).x - 200 * LLP.DETAIL_FACTOR;
offsetY = entityManager.getComponent(LLP.player, Position.class).y - 200 * LLP.DETAIL_FACTOR;
}
Set<UUID> set = new HashSet<>(entityManager.getAllEntitiesPossessingComponent(Renderable.class));
for (UUID u : set) {
Graphics g = buffer.getGraphics();
if (entityManager.hasComponent(u, Position.class)) {
Position p = entityManager.getComponent(u, Position.class);
if (entityManager.hasComponent(u, Sprite.class)) {
Sprite s = entityManager.getComponent(u, Sprite.class);
BufferedImage i = ((BufferedImage) LLP.spritesheets.get(s.spritesheet)).getSubimage(s.x, s.y, s.width, s.height);
if (entityManager.hasComponent(u, Fill.class)) {
if (entityManager.hasComponent(u, Collidable.class)) {
Collidable c = entityManager.getComponent(u, Collidable.class);
Rectangle r = new Rectangle((int) ((p.x - s.xOffset - offsetX) / LLP.DETAIL_FACTOR), (int) ((p.y - s.yOffset - offsetY) / LLP.DETAIL_FACTOR), s.width, s.height);
TexturePaint t = new TexturePaint(i, r);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(t);
g2.fillRect((int) ((p.x - s.xOffset - offsetX) / LLP.DETAIL_FACTOR), (int) ((p.y - s.yOffset - offsetY) / LLP.DETAIL_FACTOR), (int) (c.width / LLP.DETAIL_FACTOR), (int) (c.height / LLP.DETAIL_FACTOR));
}
} else {
g.drawImage(i, (int) ((p.x - s.xOffset - offsetX) / LLP.DETAIL_FACTOR), (int) ((p.y - s.yOffset - offsetY) / LLP.DETAIL_FACTOR), null);
}
} else {
if (entityManager.hasComponent(u, Collidable.class)) {
Collidable c = entityManager.getComponent(u, Collidable.class);
g.setColor(Color.red);
g.fillRect((int) (p.x / LLP.DETAIL_FACTOR), (int) (p.y / LLP.DETAIL_FACTOR), (int) (c.width / LLP.DETAIL_FACTOR), (int) (c.height / LLP.DETAIL_FACTOR));
}
}
}
}
} | 7 |
public String convertToString(HashMap map) {
StringBuffer buf = new StringBuffer();
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
String value = (String) map.get(key);
try {
buf.append(URLEncoder.encode(key, "UTF-8"));
buf.append(DELIMITER_MINOR);
buf.append(URLEncoder.encode(value, "UTF-8"));
if (it.hasNext()) {
buf.append(DELIMITER_MAJOR);
}
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
}
}
return buf.toString();
} | 3 |
public static String assertRationalMatrix(double[][] matrix) {
if (matrix == null) {
return "The matrix is null";
}
int rows = matrix.length;
if (rows <= 1) {
return "The matrix does not have more than one row:" + NEWLINE
+ representMatrix(matrix, 3);
}
double[] firstRow = matrix[0];
if (firstRow == null) {
return "The first row of the matrix is null:" + NEWLINE
+ representMatrix(matrix, 3);
}
int columns = firstRow.length;
if (columns <= 1) {
return "The first row of the matrix does not have more than one column:"
+ NEWLINE + representMatrix(matrix, 3);
}
if (rows != columns) {
return "The matrix does not have an equal number of rows and columns:"
+ NEWLINE + representMatrix(matrix, 3);
}
for (int row = 1; row < rows; row++) {
double[] currentRow = matrix[row];
if (currentRow == null) {
return "Row " + (row + 1) + " of the matrix is null:" + NEWLINE
+ representMatrix(matrix, 3);
}
int rowColumns = currentRow.length;
if (rowColumns != columns) {
return "Row "
+ (row + 1)
+ " of the matrix does not have the same number of columns as the first row:"
+ NEWLINE + representMatrix(matrix, 3);
}
}
return null;
} | 8 |
public void setMaxTries(int maxTries) {
this.maxTries = maxTries;
} | 0 |
private ConnectionToClient findOpponent( ConnectionToClient client) throws NullPointerException
{
Long opponentId = -1L; // Default value for a long
ClientNode clientNode = new ClientNode(-999L);;
for( ClientNode node : clientList )
{// Iterate through all clients connected in the list
// If listClient different from clientConnected and that client has himself as opponent
if( node.getPlayerID() == client.getId())
{
clientNode = node; // find client node
break;
}
}
if (clientNode.getOpponentID() == clientNode.getPlayerID())
{
for( ClientNode possibleOpponentNode : clientList )
{// Iterate through all clients connected in the list
// If listClient different from clientConnected and that client has himself as opponent
if( possibleOpponentNode.getPlayerID() != clientNode.getPlayerID() && possibleOpponentNode.getPlayerID() == possibleOpponentNode.getOpponentID())
{
// Sets the client's opponent's opponent as himself
opponentId = possibleOpponentNode.getPlayerID();
possibleOpponentNode.setOpponentID(client.getId());
clientNode.setOpponentID(opponentId);
break;
}
}
}
else
opponentId = clientNode.getOpponentID();
// Iterate through the connectiontoclients array
if(opponentId != -1L)
{
for(Thread clientThread : getClientConnections())// list of connections
{
if(clientThread.getId() == opponentId)
{
return (ConnectionToClient) clientThread;
}
}
}
else
throw new NullPointerException("Client has no opponent.");
return null;
} | 9 |
@Override
public void actionPerformed(ActionEvent event)
{
try
{
if (event.getSource() == buy)
{
Item item = (Item) merchantsInventory.getSelectedValue();
// select item in merchantsInventory JList
startSel = merchantsInventory.getSelectedIndex();
endSel = startSel;
int nitems = merchantsInventory.getModel().getSize();
if (startSel == nitems - 1)
{
merchantsInventory.setSelectionInterval(startSel - 1, endSel - 1);
}
else
{
merchantsInventory.setSelectionInterval(startSel + 1, endSel + 1);
}
int money = item.getModifiedPrice();
if (money > thePlayer.getMoney())
{
topPlayerLabel.setText("Player can not afford that!");
} else
{
if(thePlayer.canFitAnotherItem())
{
topPlayerLabel.setText("Player");
merchantList.removeElement(item);
playerList.addElement(item);
theMerchant.sale((double) item.getModifiedPrice(), item);
thePlayer.purchase((double) item.getModifiedPrice(), item);
updateBanks();
//item.unModify();
repaint();
}
else
{
topPlayerLabel.setText("Player can not fit any more items!");
}
}
} else if (event.getSource() == sell)
{
Item item = (Item) playersInventory.getSelectedValue();
int money = item.getModifiedPrice();
if(money > theMerchant.getMoney())
{
topMerchantLabel.setText("Merchant can not afford that!");
} else
{
topMerchantLabel.setText("Merchant");
// select top item in playerInventory JList
startSel = playersInventory.getSelectedIndex();
endSel = startSel;
int nitems = playersInventory.getModel().getSize();
if (startSel == nitems - 1)
{
playersInventory.setSelectionInterval(startSel - 1, endSel - 1);
}
else
{
playersInventory.setSelectionInterval(startSel + 1, endSel + 1);
}
playerList.removeElement(item);
merchantList.addElement(item);
thePlayer.sale((double) item.getModifiedPrice(), item);
theMerchant.purchase((double) item.getModifiedPrice(), item);
updateBanks();
repaint();
}
} else if (event.getSource() == leave)
{
dispose();
// You are welcome -Jon -- Thank you -Ryan
Orbital loc = ((TradePort) theMerchant).getLocale();
thePlayer.setLoc(loc.getParent());
}
} catch (Exception e)
{
}
} | 9 |
public Ocean toOcean() {
Ocean newOcean = new Ocean(width, height, starveTime);
int x=0;
int y=0;
for(TypeAndSizeAndStarve runs: runLength)
for(int i = 0; i<runs.getSize(); i++){
if(y==width){
x++;
y=0;
}
if(runs.getType() == 1){
newOcean.addShark(y, x, starveTime);
y++;
}
else if(runs.getType() == 2){
newOcean.addFish(y, x);
y++;
}
else
y++;
}
return newOcean;
} | 5 |
public
void registerInterestIn( Class<? extends Data>... someInterestedData ) {
//iterate over the array of data types
for( int i = 0; i < someInterestedData.length; ++i ) {
//and add them to the interest list
_interestedDataList.add( someInterestedData[i] );
}
//if there are actually things to be interested in,
//tell the DataCenter to update the interest
if( ! _interestedDataList.isEmpty() ) {
//
_dataCenter.updateProcessorInterest( _id );
}
} | 3 |
private void saveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMenuItemActionPerformed
// TODO add your handling code here:
int returnVal = saveFileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = saveFileChooser.getSelectedFile();
String filename = file.getName();
String filePath;
if(!filename.contains("."))
{
filename = filename + ".stat";
filePath = file.getPath() + ".stat";
}
else
{
filename = file.getName();
filePath = file.getPath();
}
// System.out.println(file.toString());
ProjectStore project = ProjectStore.getInstance();
// if the project needs to be encrypted then save accordingly
if (isEncrypted) {
project.saveEncryptedProject(filePath, Stakeholders, filename, null, null, null, true, password);
} else {
project.saveProject(filePath, Stakeholders, filename, null, null, null, false);
}
saveMenuItemIsUsed = true;
}
}//GEN-LAST:event_saveMenuItemActionPerformed | 3 |
void prep(char grid[][]){
int n = grid.length;
int m = grid[0].length;
foldedOrWhite = new int[n][m];
foldedOrBlack = new int[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(black(grid, i, j)) foldedOrWhite[i][j] = 0; else foldedOrWhite[i][j] = j>0?foldedOrWhite[i][j-1]+1:1;
}
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(white(grid, i, j)) foldedOrBlack[i][j] = 0; else foldedOrBlack[i][j] = j>0?foldedOrBlack[i][j-1]+1:1;
}
}
} | 8 |
public static void readFromNetwork(int data) {
System.out.println("Read from network: " + data);
switch (data) {
case 100:
bronzeChest.removeItems();
LOCKS[3] = true;
break;
case 101:
ROOMS[0].removeItem(silverKey);
break;
case 102:
break;
case 103:
ROOMS[0].removeItem(note3);
break;
case 104:
ROOMS[1].removeItem(baseballBat);
break;
case 105:
ROOMS[5].removeItem(gun);
break;
case 200:
ROOMS[2].removeItem(zombie1);
break;
case 300:
ROOMS[3].removeItem(zombie2);
break;
case 400:
ROOMS[5].removeItem(zombie3);
break;
}
} | 9 |
public void setExpired(boolean expired) {
this.expired = expired;
} | 0 |
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.