text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
private List<CmdArg> tokenize()
throws Exception
{
char[] str = value.toCharArray();
int p = 0;
List<CmdArg> tokens = new ArrayList<CmdArg>();
String tok = "";
boolean invar = false;
boolean instr = true;
while (p < str.length) {
if (invar) {
if (RuleTreeParser.isAlNumUS(str[p])) {
tok += str[p];
p++;
continue;
} else {
invar = false;
instr = true;
CmdArg arg = new VarArg(tok);
tokens.add(arg);
tok = null;
continue;
}
} else if (instr) {
if (str[p] != '$') {
tok += str[p];
p++;
continue;
} else {
instr = false;
CmdArg arg = new StringArg(tok);
tokens.add(arg);
tok = null;
continue;
}
} else if(str[p] == '$') {
invar = true;
tok = "$";
p++;
}
}
if (tok != null) {
CmdArg arg = null;
if (instr) {
arg = new StringArg(tok);
} else if (invar) {
arg = new VarArg(tok);
} else {
throw new Exception("Unexpected condition/bug");
}
tokens.add(arg);
}
return tokens;
}
| 9 |
public final void push(T val) {
back_chunk.values [back_pos] = val;
back_chunk = end_chunk;
back_pos = end_pos;
end_pos ++;
if (end_pos != size)
return;
Chunk sc = spare_chunk;
if (sc != begin_chunk) {
spare_chunk = spare_chunk.next;
end_chunk.next = sc;
sc.prev = end_chunk;
} else {
end_chunk.next = new Chunk(klass, size, memory_ptr);
memory_ptr += size;
end_chunk.next.prev = end_chunk;
}
end_chunk = end_chunk.next;
end_pos = 0;
}
| 2 |
private int lookup(int left, int right) {
if (found) {
return 0;
}
if (user.theNumberIs(left)) {
found = true;
return left;
}
if (user.theNumberIs(right)) {
found = true;
return right;
}
if (left == right || left + 1 == right) {
return 0;
}
int half = (right - left) / 2;
return lookup(left, left + half) + lookup(left + half + 1, right);
}
| 5 |
void drawLoadingText(int i, String s) {
while (graphics == null) {
graphics = getGameComponent().getGraphics();
try {
getGameComponent().repaint();
} catch (Exception exception) {
}
try {
Thread.sleep(1000L);
} catch (Exception exception) {
}
}
java.awt.Font boldFont = new java.awt.Font("Helvetica", 1, 13);
FontMetrics fontmetrics = getGameComponent().getFontMetrics(boldFont);
java.awt.Font plainFont = new java.awt.Font("Helvetica", 0, 13);
getGameComponent().getFontMetrics(plainFont);
if (shouldClearScreen) {
graphics.setColor(Color.black);
graphics.fillRect(0, 0, width, height);
shouldClearScreen = false;
}
Color color = new Color(140, 17, 17);
int j = height / 2 - 18;
graphics.setColor(color);
graphics.drawRect(width / 2 - 152, j, 304, 34);
graphics.fillRect(width / 2 - 150, j + 2, i * 3, 30);
graphics.setColor(Color.black);
graphics.fillRect(width / 2 - 150 + i * 3, j + 2, 300 - i * 3, 30);
graphics.setFont(boldFont);
graphics.setColor(Color.white);
graphics.drawString(s, (width - fontmetrics.stringWidth(s)) / 2, j + 22);
}
| 4 |
private void loadKompetenser() {
PanelHelper.cleanPanel(kompetensHolder);
ArrayList<String> al = null;
try {
String query = "select kid from kompetensdoman";
al = DB.fetchColumn(query);
} catch (InfException e) {
e.getMessage();
}
for (String st : al) {
if (Validate.containsOnlyDigits(st)) {
PanelHelper.addPanelToPanel(new KompetensdomanShowBox(Integer.parseInt(st)), kompetensHolder, 540, 100);
Dimension d = kompetensHolder.getPreferredSize();
d.setSize(d.getWidth(), (d.getHeight() + 105));
kompetensHolder.setPreferredSize(d);
}
}
}
| 3 |
public static boolean isItalic(JTextPane pane)
{
AttributeSet attributes = pane.getInputAttributes();
if (attributes.containsAttribute(StyleConstants.Italic, Boolean.TRUE))
{
return true;
}
if (attributes.getAttribute(CSS.Attribute.FONT_STYLE) != null)
{
Object fontWeight = attributes
.getAttribute(CSS.Attribute.FONT_STYLE);
return fontWeight.toString().equals("italic");
}
return false;
}
| 2 |
public static final String format(boolean value) {
return value ? "yes" : "no"; //$NON-NLS-1$ //$NON-NLS-2$
}
| 1 |
public static void initParser(String[] args) throws IllegalArgumentException{
_CSPort = CS.DEFAULT_PORT;
_CSName = "localhost";
if(args.length != 0){
if(args.length == 2){
if(args[0].equals("-n")){
_CSName = args[1];
}
else if(args[0].equals("-p")){
_CSPort = Integer.parseInt(args[1]);
}
else{
throw new IllegalArgumentException("Wrong input args");
}
}
else if(args.length == 4){
if(args[0].equals("-n") && args[2].equals("-p")){
_CSName = args[1];
_CSPort = Integer.parseInt(args[3]);
}
else{
throw new IllegalArgumentException("Wrong input args");
}
}
else{
throw new IllegalArgumentException("Wrong input args");
}
}
}
| 7 |
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> row = new ArrayList<Integer>();
if (root == null) {
return result;
}
TreeIterator iterator = new TreeIterator(root);
while (iterator.hasNext()) {
TreeNode current = iterator.next();
if (current == null) {
result.add(row);
row = new ArrayList<Integer>();
}
else {
row.add(current.val);
}
}
Collections.reverse(result);
return result;
}
| 3 |
public char getNextChar() {
try {
//Leemos un caracter y seteamos a nuestra variable currentChar de objeto
setCurrentChar((char) pr.read());
//Sumamos 1 al caracter en la línea
setNumeroDeCaracterEnLinea(getNumeroDeCaracterEnLinea()+1);
//Si es un salto de línea sumamos a la línea y dejamos de nuevo en 0
//al caracter de la linea
if (getCurrentChar() == '\n') {
setNumeroDeLinea(getNumeroDeLinea()+1);
setNumeroDeCaracterEnLinea(0);
}
} catch (IOException e) {
setIsEOF(true);
Logger.getLogger(ArchivoHandler.class.getName()).log(Level.SEVERE, null, e);
} finally {
//Si el último caracter es un EOF entonces seteamos la variable de objeto isEOF
//y cerramos el archivo
if (getCurrentChar() == '\uffff') try {
setIsEOF(true);
pr.close();
} catch (IOException ex) {
Logger.getLogger(ArchivoHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Devolvemos el caracter recien leido
return getCurrentChar();
}
| 4 |
public void gameTick() {
if (player.isLevelAdvance()) {
levelsCompleted++;
totalPoint += temporaryPoint;
temporaryPoint = 0;
if (currentLevel.getNextLevel() == 0)
gameCompleted = true;
else {
currentLevel = new Level(currentLevel.getNextLevel());
player.setxCoord(currentLevel.getTileWidth()
* currentLevel.getStartX());
player.setyCoord(currentLevel.getTileHeight()
* currentLevel.getStartY());
player.setLevelAdvance(false);
}
} else {
if (player.collisionAble()) {
int beforeCollisionLife = player.getLife();
currentLevel.collision(player);
if (player.getLife() != beforeCollisionLife) { //Checks if the player lost any health
currentLevel.reset();
temporaryPoint = 0;
player.setxCoord(currentLevel.getTileWidth()
* currentLevel.getStartX());
player.setyCoord(currentLevel.getTileHeight()
* currentLevel.getStartY());
}
}
if (!levelComplete()) {
currentLevel.updateLevelIndex();
temporaryPoint++;
}
}
}
| 5 |
public int get(long millis) {
int dayOfWeek = (int) TestGJChronology.mod(iChronology.fixedFromMillis(millis), 7);
if (dayOfWeek == 0) {
dayOfWeek = 7;
}
return dayOfWeek;
}
| 1 |
private void showFilter() {
if (isAncestorOf(searchPanel)) {
remove(searchPanel);
} else {
add(searchPanel,java.awt.BorderLayout.NORTH);
searchPanel.set(mp3list.getIndex(),mp3list.NoE(),mp3list.length());
searchPanel.Focus();
}
revalidate();
repaint();
}
| 1 |
public boolean similarColors(Card c2){
boolean result = false;
String cost1 = this.cost + "1";
String cost2 = c2.getCost() + "1";
for(char c : cost1.toCharArray())
if(c != 1 && cost2.indexOf(c) != -1)
result = true;
for(char c : cost2.toCharArray())
if(cost1.indexOf(c) == -1)
result = false;
return result;
}
| 5 |
public static void connectGraph(){
int n = _graph.getVertexCount();
System.out.println("n = " + n );
System.out.println("Calculating Euclidean Distance");
Collection<BCNode> nodes = _graph.getVertices();
Iterator<BCNode> iti = nodes.iterator();
while( iti.hasNext() ) {
BCNode nodei = iti.next();
Iterator<BCNode> itj = nodes.iterator();
while( itj.hasNext() ) {
BCNode nodej = itj.next();
if( _graph.findEdge(nodei,nodej) == null && nodei != nodej ) {
BCEdge e = new BCEdge( nodei.calcEucDistance( nodej ));
_graph.addEdge(e,nodei,nodej);
}
}
}
}
| 4 |
public void printComponent(Graphics g) {
int recursionDepth = spinnerModel.getNumber().intValue();
List expansion = expander.expansionForLevel(recursionDepth);
// Now, set the display.
Map parameters = lsystem.getValues();
Matrix m = new Matrix();
double pitch = pitchModel.getNumber().doubleValue(), roll = rollModel
.getNumber().doubleValue(), yaw = yawModel.getNumber()
.doubleValue();
m.pitch(pitch);
m.roll(roll);
m.yaw(yaw);
renderer.render(expansion, parameters, m, (Graphics2D) g, new Point());
}
| 0 |
public Timestamp asTimestamp()
{
try {
if (isNull()) {
return null;
} else if (isTimestamp()) {
return (Timestamp) value;
}
if (isTime()) {
Calendar cal = Calendar.getInstance();
cal.setTime((Time) value);
return new Timestamp(cal.getTime().getTime());
} else if (isUtilDate()) {
return new Timestamp(((java.util.Date) value).getTime());
} else if (isString()) {
return Timestamp.valueOf((String) value);
} else {
return Timestamp.valueOf(asString());
}
} catch (IllegalArgumentException a) {
throw new SwingObjectRunException( a, ErrorSeverity.SEVERE, FrameFactory.class);
} catch (Exception b) {
throw new SwingObjectRunException( b, ErrorSeverity.SEVERE, FrameFactory.class);
}
}
| 7 |
public Integer Byte4ToInt32(byte[] bytes) throws Exception {
if (bytes.length != 4) throw new Exception("aBytes.length != 4");
/*** forward algorithm [123][0][0][0] ***/
Integer result = new Integer(0);
byte i = 3;
while(true) {
result |= bytes[i] & 0xFF;
if (i == 0) break;
result <<= 8;
i--;
}
return result;
/*** inverse algorithm 0 0 0 123 ***
int l = 0;
int tmpI = 0;
while(true) {
l |= aBytes[tmpI] & 0xFF;
if (tmpI > 2) break;
l <<= 8;
tmpI++;
}
return l;
***************************/
}
| 3 |
private Location findFood(Location location)
{
Field field = getField();
List<Location> adjacent = field.adjacentLocations(getLocation());
Iterator<Location> it = adjacent.iterator();
while(it.hasNext()) {
Location where = it.next();
Object animal = field.getObjectAt(where);
if(animal instanceof Rabbit) {
Rabbit rabbit = (Rabbit) animal;
if(rabbit.isAlive()) {
rabbit.setDead();
foodLevel = RABBIT_FOOD_VALUE;
// Remove the dead rabbit from the field.
return where;
}
} else if (animal instanceof Korenwolf) {
Korenwolf korenwolf = (Korenwolf) animal;
if(korenwolf.isAlive()) {
if(Math.random()*100 < 50) {
// p0.5 kans dat de korenwolf dood gaat! oh nee!
korenwolf.setDead();
foodLevel = KORENWOLF_FOOD_VALUE;
return where;
/* Dit was Jeffrey's suicidale vos-clause: Als een vos geen hamster te pakken kreeg was
er een kans dat de vos zelf dood ging. Dit werkt niet en geeft regelmatig een runtime fout.
} else if (Math.random()*100 < 10) {
// Tja, die vos heeft de hamster niet te pakken gekregen, karma komt om de hoek
// kijken: is de vos na deze poging om een lief klein hamsterbeest op te peuzelen
// zo vermoeid dat hij spontaan het loodje legt?
// this.setDead();
// where;
*
*/
}
}
}
}
return null;
}
| 6 |
@EventHandler(priority = EventPriority.NORMAL)
public final void onVotifierEvent(final VotifierEvent event) {
Vote vote = event.getVote();
String user = vote.getUsername();
log.info(String.format(plugin.getMessages().getString("player.vote.event"), user));
OfflinePlayer thePlayer = Bukkit.getOfflinePlayer(user);
if (!thePlayer.isOnline()) {
if (!thePlayer.hasPlayedBefore()) {
log.info(String.format(plugin.getMessages().getString("player.never.played"), user));
return;
}
}
VoteData voteData = new VoteData();
voteData.setMinecraftUser(user);
voteData.setTime(new Timestamp(System.currentTimeMillis()));
voteData.setService(vote.getServiceName());
voteData.setIp(vote.getAddress());
database.save(voteData);
plugin.getNextVoteManager().doVote(user);
}
| 2 |
public void setTitle(String title) {
this.title = title;
}
| 0 |
public boolean ApagarTodosQuandoExcluiPessoa(int idPessoa){
try{
PreparedStatement comando = banco.getConexao()
.prepareStatement("UPDATE enderecos SET ativo = 0 WHERE id_pessoa= ?");
comando.setInt(1, idPessoa);
comando.executeUpdate();
comando.getConnection().commit();
return true;
}catch(SQLException ex){
ex.printStackTrace();
return false;
}
}
| 1 |
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n");
out.write(" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <form method=\"post\" action=\"/Project4/Controller?command=Open_Login_Menu\">\n");
out.write("\n");
out.write(" ");
if (_jspx_meth_c_choose_0(_jspx_page_context))
return;
out.write("\n");
out.write(" \n");
out.write(" </form>\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
| 6 |
private static Class<? extends AttributeImpl> getClassForInterface(Class<? extends Attribute> attClass) {
synchronized(attClassImplMap) {
final WeakReference<Class<? extends AttributeImpl>> ref = attClassImplMap.get(attClass);
Class<? extends AttributeImpl> clazz = (ref == null) ? null : ref.get();
if (clazz == null) {
try {
attClassImplMap.put(attClass,
new WeakReference<Class<? extends AttributeImpl>>(
clazz = Class.forName(attClass.getName() + "Impl", true, attClass.getClassLoader())
.asSubclass(AttributeImpl.class)
)
);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Could not find implementing class for " + attClass.getName());
}
}
return clazz;
}
}
| 8 |
public void redraw(GameWorld world) {
this.gameWorld = world;
for (Avatar a : gameWorld.getAvatars()) {
if (a.getName().equals(name)) {
this.avatar = a;
}
}
if (avatar != null) {
int health = avatar.getHealth();
healthBar.setValue(health);
if (health > 75) {
healthBar.setForeground(Color.green);
} else if (health > 50) {
healthBar.setForeground(Color.yellow);
} else if (health > 25) {
healthBar.setForeground(Color.orange);
} else {
healthBar.setForeground(Color.red);
}
}
if (gameWorld.isWin()) {
if (isWon) {
frame.repaint();
return;
}
MediaPlayer.stopCurrent();
MediaPlayer.playWinning();
chatArea.append("Player " + (world.getWinner() + 1)
+ " has won the game!\n");
isWon = true;
}
frame.repaint();
}
| 8 |
private void openSession()
{
if(session == null)
session = HibernateUtils.getSessionFactory().openSession();
}
| 1 |
public void down() {
currentlySelected--;
if(currentlySelected == -1)
currentlySelected = countItemsInInventory() - 1;
}
| 1 |
public Grammar(final Reader in) throws GrammarSyntaxException {
productions = new HashMap<String, TreeSet<String[]>>();
leftmost = new HashMap<String, Set<String>>();
final Scanner sc = new Scanner(in).useDelimiter("\\s*[\r\n]+\\s*");
while (sc.hasNext()) {
final String line = sc.next().trim();
if (!line.startsWith("#")) {
final String[] parts = line.split("\\s+");
if(parts.length < 2 || !"->".equals(parts[1])) throw new GrammarSyntaxException(
"Can't understand " +
"production '" + line + "'.");
final String lhs = parts[0];
final String[] rhs = Arrays.copyOfRange(parts, 2, parts.length);
if (rhs.length == 0) throw new GrammarSyntaxException("Right hand side missing"
+ " in '" + line + "'.");
if(!addProduction(lhs, rhs)) throw new GrammarSyntaxException("Production '"
+ line
+ "' is declared more than once.");
}
}
if(productions.isEmpty()) throw new GrammarSyntaxException(
"There must be at least one"
+ " production.");
}
| 7 |
@Override
public boolean equals(Object matrix) {
if (!(matrix instanceof Matrix)) {
return false;
}
if (((Matrix) matrix).getRows() != rows || ((Matrix) matrix).getColumns() != columns) {
return false;
}
for (int x = 0; x < rows; x++) {
for (int y = 0; y < columns; y++) {
if (((Matrix) matrix).getElement(x, y) != elements[x][y]) {
return false;
}
}
}
return true;
}
| 6 |
@Test
public void testNumberOfDoorways()
{
int numDoors = 0;
int totalCells = board.getNumColumns() * board.getNumRows();
Assert.assertEquals(506, totalCells);
for (int i=0; i<totalCells; i++)
{
BoardCell cell = board.getCellAt(i);
if (cell.isDoorway())
numDoors++;
}
Assert.assertEquals(16, numDoors);
}
| 2 |
public void testSetMinuteOfDay_int2() {
MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8);
try {
test.setMinuteOfDay(24 * 60);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals("2002-06-09T05:06:07.008+01:00", test.toString());
}
| 1 |
public void keyPressed(KeyEvent key)
{
int code = key.getKeyCode();
if(code == KeyEvent.VK_LEFT)
{
player.setLeft(true);
}
if(code == KeyEvent.VK_RIGHT)
{
player.setRight(true);
}
if(code == KeyEvent.VK_DOWN)
{
player.setDown(true);
}
if(code == KeyEvent.VK_Z)
{
player.setJumping(true);
}
if(code == KeyEvent.VK_C)
{
player.setWeaponUse(true);
}
if(code == KeyEvent.VK_1)
{
player.setMegaManType("normal");
}
if(code == KeyEvent.VK_2)
{
player.setMegaManType("twilightsparkle");
}
}
| 7 |
public static Object[] sliceFromFinalBoundary(Object[] sequence, Boolean[] boundaries) {
// Find the last boundary. If no boundary is found, -1 is correct since
// when it is incremented it will be zero, the first index in the text
int last = -1;
for (int i = 0; i < boundaries.length; i++) {
if (boundaries[i]) last = i;
}
// Now get the appropriate slice from last to the end. Increase last
// by one since it is aligned one left of the text
return Arrays.copyOfRange(sequence, last + 1, sequence.length, sequence.getClass());
}
| 2 |
public static void main(String[] args)
{
// initialize all data
try
{
// start reading the input txt file
String fname = "Assignment03.txt";
Scanner scnr = new Scanner(new File(fname));
int numpatch = scnr.nextInt();
int numit = scnr.nextInt();
// create array of patches
Patch[] patch = new Patch[numpatch];
System.out.printf("%-5s %7s %7s\n", "Id", "ePwr", "Reflect");
System.out.println("========================");
// loop over patches and gather info
for(int i = 0; i < numpatch; i++)
{
// assign variables
patch[i] = new Patch(scnr.nextInt(), // patch id
scnr.nextFloat(), // emission pwr
scnr.nextFloat(), // reflectance
scnr.nextInt() // num vis patch
);
// loop over num visible patches
for(int j = 0; j < patch[i].numVisPatch; j++)
{
// update patch objects
patch[i].visIds[j] = scnr.nextInt();
patch[i].formfacts[j] = scnr.nextFloat();
}
// print id, reflectance and emission power
System.out.printf("[%3d] %7.2f %7.2f\n", patch[i].patchId,
patch[i].emissionPower,
patch[i].reflectance
);
}
// start main shooting algorithm
// initialize unshot power
float[] pwrVals = new float[numpatch];
for(int i = 0; i < numpatch; i++)
{
patch[i].unshotPower = patch[i].emissionPower;
patch[i].totalPower = patch[i].unshotPower;
pwrVals[i] = patch[i].unshotPower;
}
// initialize indirect heap helper arrays
int[] outof = new int[pwrVals.length];
int[] into = new int[pwrVals.length];
for(int i = 0; i < outof.length; i++)
{
outof[i] = i; // arrays of indices
into[i] = i;
}
// initialize indirect heap
buildIndirectHeap(pwrVals, outof, into, pwrVals.length);
// start iterative solution
int converged = 0;
while(converged != numit)
{
// find patch k with max unshot pwr in O(1)
int k = getMaxPwrInd(outof);
// shoot unshotPower to all adjacent patches
for(int j = 0; j < patch[k].visIds.length; j++)
{
int i = patch[k].visIds[j] - 1;
patch[i].totalPower += patch[i].reflectance*
patch[k].formfacts[j]*
patch[k].unshotPower;
patch[i].unshotPower += patch[i].reflectance*
patch[k].formfacts[j]*
patch[k].unshotPower;
// restore heap property
increasePatchValue(pwrVals, into, outof, i, patch[i].unshotPower);
}
patch[k].unshotPower = 0;
// restore heap property
decreasePatchValue(pwrVals, into, outof, k, patch[k].unshotPower);
converged++;
}
System.out.println("\n");
System.out.printf("RESULTS AFTER %d ITERATIONS:\n", numit);
System.out.printf("===========================\n");
// print status after the iteration
for(int i = 0; i < numpatch; i++)
{
System.out.printf("[%d] %f\n",
patch[i].patchId,
patch[i].totalPower);
printPatchInfo(patch[i]);
System.out.println("\n");
}
}
catch(Exception ioe)
{
System.out.println("Error: " + ioe.getMessage());
}
}
| 8 |
public void readInput(int level, String type, Client c, int amounttomake) {
if (c.getItems().getItemName(Integer.parseInt(type)).contains("Bronze"))
{
CheckBronze(c, level, amounttomake, type);
}
else if (c.getItems().getItemName(Integer.parseInt(type)).contains("Iron"))
{
CheckIron(c, level, amounttomake, type);
}
else if (c.getItems().getItemName(Integer.parseInt(type)).contains("Steel"))
{
CheckSteel(c, level, amounttomake, type);
}
else if (c.getItems().getItemName(Integer.parseInt(type)).contains("Mith"))
{
CheckMith(c, level, amounttomake, type);
}
else if (c.getItems().getItemName(Integer.parseInt(type)).contains("Adam") || c.getItems().getItemName(Integer.parseInt(type)).contains("Addy"))
{
CheckAddy(c, level, amounttomake, type);
}
else if (c.getItems().getItemName(Integer.parseInt(type)).contains("Rune") || c.getItems().getItemName(Integer.parseInt(type)).contains("Runite"))
{
CheckRune(c, level, amounttomake, type);
}
c.sendMessage("Item: " + type);
}
| 8 |
@Override
public void newbie() {
hello.newbie();
}
| 0 |
private boolean isCtrlTabPressed(KeyEvent e) {
return e.character == SWT.TAB && ((e.stateMask & SWT.CTRL) != 0) && ((e.stateMask & SWT.SHIFT) == 0);
}
| 2 |
public ArrayList<Cliente> searchClientes(String nom){
ArrayList<Cliente> cList = new ArrayList();
ArrayList<Cliente> res = new ArrayList();
cList.addAll(cjtClientes.values());
for(int i=0; i<cList.size(); ++i){
if(cList.get(i).getNombre().contains(nom))
res.add(cList.get(i));
}
return res;
}
| 2 |
public void updatePlayerCards(List<Card> cardlist) {
int size = cardlist.size();
if (size >= 2) {
FirstCardPlayer.setImage(new Image(cardlist.get(0).getLink().toString())); //initialize only if the user has only two
FirstCardPlayer.setVisible(true);
SecoundCardPlayer.setImage(new Image(cardlist.get(1).getLink().toString()));
SecoundCardPlayer.setVisible(true);
}
if (size >= 3) {
ThirdCardPlayer.setImage(new Image(cardlist.get(2).getLink().toString())); //initialize only if the user has three
ThirdCardPlayer.setVisible(true);
}
if (size >= 4) {
FourthCardPlayer.setImage(new Image(cardlist.get(3).getLink().toString())); //initialize only if the user has four
FourthCardPlayer.setVisible(true);
}
if (size >= 5) {
FifthCardPlayer.setImage(new Image(cardlist.get(4).getLink().toString())); //initialize only if the user has five
FifthCardPlayer.setVisible(true);
}
if (size >= 6) {
SixthCardPlayer.setImage(new Image(cardlist.get(5).getLink().toString())); //initialize only if the user has six
SixthCardPlayer.setVisible(true);
}
if (size >= 7) {
SeventhCardPlayer.setImage(new Image(cardlist.get(6).getLink().toString())); //initialize only if the user has seven
SeventhCardPlayer.setVisible(true);
}
if (size >= 8) {
EightCardPlayer.setImage(new Image(cardlist.get(7).getLink().toString())); //initialize only if the user has only eight
EightCardPlayer.setVisible(true);
}
if (size >= 9) {
NineghtCardPlayer.setImage(new Image(cardlist.get(8).getLink().toString())); //initialize only if the user has only nine
NineghtCardPlayer.setVisible(true);
}
}
| 8 |
public List<Integer> getIntegerList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Integer>(0);
}
List<Integer> result = new ArrayList<Integer>();
for (Object object : list) {
if (object instanceof Integer) {
result.add((Integer) object);
} else if (object instanceof String) {
try {
result.add(Integer.valueOf((String) object));
} catch (Exception ex) {
}
} else if (object instanceof Character) {
result.add((int) ((Character) object).charValue());
} else if (object instanceof Number) {
result.add(((Number) object).intValue());
}
}
return result;
}
| 8 |
@EventHandler
private void onInventoryClick(InventoryClickEvent event) {
if(event.getWhoClicked() instanceof Player) {
if(ColoredArmor.config.getBoolean("Check.move-item")) {
Player player = (Player) event.getWhoClicked();
if(!(player.hasPermission("ca.check.move.bypass"))) {
if(event.getView().getTopInventory().getType() == InventoryType.FURNACE
|| event.getView().getTopInventory().getType() == InventoryType.CHEST
|| event.getView().getTopInventory().getType() == InventoryType.ENDER_CHEST) {
if(Armor.isArmor(event.getCurrentItem())) {
if(event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY || event.getAction() == InventoryAction.PICKUP_ALL) {
player.sendMessage(pre + "§cYou are not allowed to §4move §ca §4(Colored)Armor§c!");
event.setCancelled(true);
}
}
}
}
}
}
}
| 9 |
@Override
public BinaryNodePS<T> addLeftChild(Node<T> parent, T info) {
if (!(parent instanceof BinaryNodePS)) {
throw new DifferentNodeTypesException();
} else if (isSafe() && !contains(parent)) {
throw new NodeNotFoundException();
}
BinaryNodePS<T> bn = (BinaryNodePS<T>) parent;
if (bn.getLeft() != null) {
throw new ExistingNodeException();
}
BinaryNodePS<T> child = new BinaryNodePS<T>(info);
child.setParent(bn);
bn.setLeft(child);
modified = true;
size++;
return child;
}
| 4 |
protected static int levelCapacity(int lev)
{
if(lev == 1)
return 2;
else if(lev == 2)
return 8;
else if(lev == 3)
return 18;
else if(lev == 4)
return 32;
else if(lev == 5)
return 32;
else if(lev == 6)
return 18;
else if(lev == 7)
return 8;
return 0;
}
| 7 |
@Override
public void newSource( boolean priority, boolean toStream, boolean toLoop,
String sourcename, FilenameURL filenameURL, float x,
float y, float z, int attModel, float distOrRoll )
{
SoundBuffer buffer = null;
if( !toStream )
{
// Grab the audio data for this file:
buffer = bufferMap.get( filenameURL.getFilename() );
// if not found, try loading it:
if( buffer == null )
{
if( !loadSound( filenameURL ) )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because an error occurred while loading "
+ filenameURL.getFilename() );
return;
}
}
// try and grab the sound buffer again:
buffer = bufferMap.get( filenameURL.getFilename() );
// see if it was there this time:
if( buffer == null )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because audio data was not found for "
+ filenameURL.getFilename() );
return;
}
}
if( !toStream && buffer != null )
buffer.trimData( maxClipSize );
sourceMap.put( sourcename,
new SourceJavaSound( listener, priority, toStream,
toLoop, sourcename, filenameURL,
buffer, x, y, z, attModel,
distOrRoll, false ) );
}
| 6 |
public int size() {
return N;
}
| 0 |
public void tick (int verb)
{
if(!gameOn) return;
//sets the new ivars
Move newMove = computeNewPosition(verb, currentMove);
//how to detect when a piece has landed
//if this move hits something on its down vert, and the pervious verb was also down
//then the pervious position must be the correct landed position
if(board.canPlace(newMove))
{
currentMove = newMove;
displayBoard = new DisplayBoard(board);
displayBoard.place(currentMove);
}
else
{
//landed
if(verb == DOWN)
{
board.place(currentMove);
rowsCleared += board.clearRows();
//check to see if board is too tall
if(board.getMaxHeight() > board.getHeight() - TOP_SPACE)
{
gameOn = false;
}
else
{
//add a new piece and keep playing
addNewPiece();
}
}
}
}
| 4 |
public void body()
{
//register oneself
write("register this entity to GridInformationService entity.");
super.sim_schedule(GridSim.getGridInfoServiceEntityId(),
GridSimTags.SCHEDULE_NOW, GridSimTags.REGISTER_ROUTER,
new Integer(super.get_id()) );
// methods to be overriden by children classes
advertiseHosts();
registerOtherEntity();
sendInitialEvent();
// Process incoming events
Sim_event ev = new Sim_event();
while ( Sim_system.running() )
{
//Sim_event ev = new Sim_event();
super.sim_get_next(ev);
// if the simulation finishes then exit the loop
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION)
{
write("receives, END_OF_SIMULATION, signal, from, " +
GridSim.getEntityName(ev.get_src()) );
processEndSimulation();
break;
}
// process the received event
processEvent(ev);
}
// finalize logging before exiting
if (reportWriter_ != null) {
reportWriter_.finalWrite();
}
}
| 3 |
private static double calculateAngle(double x1, double y1,
double x2, double y2) {
double dx = x2 - x1;
double dy = y2 - y1;
double angle = 0.0; // Horisontal to the right
if (dx == 0.0) { // Vertical
if (dy == 0.0) { // No angle
angle = 0.0;
}
else if (dy > 0.0) { // Points vertical up
angle = Math.PI/2.0;
}
else {// dy < 0, Points down
angle = Math.PI/2.0*3.0;
}
}
else if (dy == 0.0) { // Horisontal
if (dx > 0.0) { // Points right
angle = 0.0;
}
else { // dx < 0.0 Points left
angle = Math.PI;
}
}
else {
if (dx < 0.0) { // Points (up and left) or (down and left)
angle = Math.atan(dy/dx) + Math.PI;
}
else if (dy < 0.0) { // Points down and right
angle = Math.atan(dy/dx) + 2 * Math.PI;
}
else {
angle = Math.atan(dy/dx);
}
}
return angle;
}
| 7 |
public static Node sumThat(Node node1, Node node2, int extraCarry, Node result)
{
if(node1==null && node2==null)
return result;
int sum = extraCarry;
if(node1.val != null)
sum += node1.intVal;
if(node2.val != null)
sum += node2.intVal;
if(sum > 10)
{
sum = sum - 10;
extraCarry = 1;
}
else
extraCarry = 0;
if(result == null)
result = new Node(sum);
return sumThat( node1.next != null ? node1.next : null,
node2.next != null ? node2.next : null,
extraCarry,
result.next);
}
| 8 |
public List<CallData> getCallData(final String callName) {
List<CallData> callDataList = callData.get(callName);
if(callDataList == null) {
callDataList = new LinkedList<CallData>();
callData.put(callName, callDataList);
callNames.add(callName);
}
return callDataList;
}
| 1 |
public static float[] fft(final float[] inputReal, float[] inputImag,
boolean DIRECT) {
// - n is the dimension of the problem
// - nu is its logarithm in base e
int n = inputReal.length;
// If n is a power of 2, then ld is an integer (_without_ decimals)
double ld = Math.log(n) / Math.log(2.0);
// Here I check if n is a power of 2. If exist decimals in ld, I quit
// from the function returning null.
if (((int) ld) - ld != 0) {
System.out.println("The number of elements is not a power of 2.");
return null;
}
// Declaration and initialization of the variables
// ld should be an integer, actually, so I don't lose any information in
// the cast
int nu = (int) ld;
int n2 = n / 2;
int nu1 = nu - 1;
float[] xReal = new float[n];
float[] xImag = new float[n];
float tReal, tImag, p, arg, c, s;
// Here I check if I'm going to do the direct transform or the inverse
// transform.
float constant;
if (DIRECT) {
constant = (float) (-2 * Math.PI);
} else {
constant = (float) (2 * Math.PI);
}
// I don't want to overwrite the input arrays, so here I copy them. This
// choice adds \Theta(2n) to the complexity.
for (int i = 0; i < n; i++) {
xReal[i] = inputReal[i];
xImag[i] = inputImag[i];
}
// First phase - calculation
int k = 0;
for (int l = 1; l <= nu; l++) {
while (k < n) {
for (int i = 1; i <= n2; i++) {
p = bitreverseReference(k >> nu1, nu);
// direct FFT or inverse FFT
arg = constant * p / n;
c = (float) Math.cos(arg);
s = (float) Math.sin(arg);
tReal = xReal[k + n2] * c + xImag[k + n2] * s;
tImag = xImag[k + n2] * c - xReal[k + n2] * s;
xReal[k + n2] = xReal[k] - tReal;
xImag[k + n2] = xImag[k] - tImag;
xReal[k] += tReal;
xImag[k] += tImag;
k++;
}
k += n2;
}
k = 0;
nu1--;
n2 /= 2;
}
// Second phase - recombination
k = 0;
int r;
while (k < n) {
r = bitreverseReference(k, nu);
if (r > k) {
tReal = xReal[k];
tImag = xImag[k];
xReal[k] = xReal[r];
xImag[k] = xImag[r];
xReal[r] = tReal;
xImag[r] = tImag;
}
k++;
}
// Here I have to mix xReal and xImag to have an array (yes, it should
// be possible to do this stuff in the earlier parts of the code, but
// it's here to readibility).
float[] newArray = new float[xReal.length * 2];
float radice = (float) (1 / Math.sqrt(n));
for (int i = 0; i < newArray.length; i += 2) {
int i2 = i / 2;
// I used Stephen Wolfram's Mathematica as a reference so I'm going
// to normalize the output while I'm copying the elements.
newArray[i] = xReal[i2] * radice;
newArray[i + 1] = xImag[i2] * radice;
}
return newArray;
}
| 9 |
private void drawTabArea() {
tabImageProducer.initDrawingArea();
Rasterizer.lineOffsets = sidebarOffsets;
inventoryBackgroundImage.drawImage(0, 0);
if (inventoryOverlayInterfaceID != -1)
drawInterface(0, 0, RSInterface.cache[inventoryOverlayInterfaceID],
0);
else if (tabInterfaceIDs[currentTabId] != -1)
drawInterface(0, 0,
RSInterface.cache[tabInterfaceIDs[currentTabId]], 0);
if (menuOpen && menuScreenArea == 1)
drawMenu();
tabImageProducer.drawGraphics(205, super.gameGraphics, 553);
gameScreenImageProducer.initDrawingArea();
Rasterizer.lineOffsets = viewportOffsets;
}
| 4 |
@EventHandler
public void onEntityDamage(EntityDamageEvent event) {
// do not act when disabled TODO, use unregister when available
if ( !this.sheepFeedPlugin.isEnabled() ) {
return;
}
// see whether this is an attack event
if ( event.getCause() != DamageCause.ENTITY_ATTACK ) {
return;
}
EntityDamageByEntityEvent entDmByEntEv = (EntityDamageByEntityEvent)event;
Entity attacker = entDmByEntEv.getDamager();
Entity target = entDmByEntEv.getEntity();
// attacker needs to be a player and target a sheep
if ( attacker instanceof Player && target instanceof Sheep ) {
Player player = (Player) attacker;
Sheep sheep = (Sheep) target;
SheepFeed.debug("Hitting sheep ("+ sheep.getEntityId() +") that had health "+ sheep.getHealth() +" original damage: "+ event.getDamage());
this.attemptFeedSheep(player, sheep);
if (sheep.isSheared()) {
// cancel the damage given
event.setDamage(0);
}
}
}
| 5 |
public int getIndex(){
return index;
}
| 0 |
private String romI(int i) {
switch (i) {
case 1: return "I";
case 2: return "II";
case 3: return "III";
case 4: return "IV";
case 5: return "V";
case 6: return "VI";
case 7: return "VII";
case 8: return "VIII";
case 9: return "IX";
default:return "";
}
}
| 9 |
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st;
String line;
int[] LL = new int[100005];
int[] RR = new int[100005];
while ((line = br.readLine()) != null) {
st = new StringTokenizer(line);
int S = Integer.parseInt(st.nextToken());
int R = Integer.parseInt(st.nextToken());
if (S == 0 && R == 0) {
break;
}
for (int i = 1; i <= S; i++) {
LL[i] = i - 1;
RR[i] = i + 1;
}
for (int i = 0; i < R; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
if (LL[a] == 0 | LL[b] < 1) {
pw.print("* ");
} else {
pw.print(LL[a] + " ");
}
if (RR[b] == 0 || RR[b] > S) {
pw.print("*\n");
} else {
pw.print(RR[b] + "\n");
}
LL[RR[b]] = LL[a];
RR[LL[a]] = RR[b];
}
pw.print("-\n");
}
br.close();
pw.close();
}
| 8 |
public String toString() {
return new StringBuilder(super.toString())
.append(" [")
.append((this.choked ? "C" : "c"))
.append((this.interested ? "I" : "i"))
.append("|")
.append((this.choking ? "C" : "c"))
.append((this.interesting ? "I" : "i"))
.append("]")
.toString();
}
| 4 |
public static void main(String[] args) {
GraphicsMain.init();
main = new Main();
main.start();
}
| 0 |
private void readEncodingData (int base) {
if (base == 0) { // this is the StandardEncoding
System.arraycopy (FontSupport.standardEncoding, 0, encoding, 0,
FontSupport.standardEncoding.length);
} else if (base == 1) { // this is the expert encoding
// TODO: copy ExpertEncoding
} else {
pos = base;
int encodingtype = readByte ();
if ((encodingtype & 127) == 0) {
int ncodes = readByte ();
for (int i = 1; i < ncodes + 1; i++) {
int idx = readByte () & 0xff;
encoding[idx] = i;
}
} else if ((encodingtype & 127) == 1) {
int nranges = readByte ();
int p = 1;
for (int i = 0; i < nranges; i++) {
int start = readByte ();
int more = readByte ();
for (int j = start; j < start + more + 1; j++) {
encoding[j] = p++;
}
}
} else {
System.out.println ("Bad encoding type: " + encodingtype);
}
// TODO: now check for supplemental encoding data
}
}
| 7 |
private static byte[] getSecondHalf(byte[] block) {
byte[] temp = Arrays.copyOfRange(block, block.length / 2, block.length);
// middle of block is in the middle of a byte
if ( (block.length / 2d) % 1 == 0.5) {
temp = ByteHelper.rotateLeft(temp, temp.length * 8, 4);
}
return temp;
}
| 1 |
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 283, 353);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Search");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new MigLayout("", "[421.00,grow,center]", "[][][][][][][][][]"));
JLabel lblTitle = new JLabel("Title");
lblTitle.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.add(lblTitle, "cell 0 0");
titleField = new JTextField();
titleField.setFont(new Font("Tahoma", Font.PLAIN, 24));
titleField.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(titleField, "cell 0 1,growx");
titleField.setColumns(10);
JLabel lblMediaType = new JLabel("Media Type");
lblMediaType.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.add(lblMediaType, "flowx,cell 0 2");
JLabel label = new JLabel("");
panel.add(label, "cell 0 2");
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String title = titleField.getText();
String prod = productionField.getText();
if(productionField.getText().equals(""))
prod = "*";
HashMap<String, String> infoMap = Database.search(title, "movie", prod);
new InformationGUI(infoMap);
}
});
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"movie", "tv series", "tv movie", "video movie", "tv miniseries", "video game"}));
((JLabel)comboBox.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
panel.add(comboBox, "cell 0 3,growx");
JLabel lblProductionYear = new JLabel("Production Year");
lblProductionYear.setFont(new Font("Tahoma", Font.BOLD, 20));
panel.add(lblProductionYear, "cell 0 5");
productionField = new JTextField();
productionField.setFont(new Font("Tahoma", Font.PLAIN, 24));
productionField.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(productionField, "cell 0 6,growx");
productionField.setColumns(10);
panel.add(btnSearch, "cell 0 8");
}
| 5 |
public boolean inAny(List<Polygon> polygons) {
for(Polygon p: polygons)
if(p.contains(this))
return true;
return false;
}
| 2 |
void periodCertification() {
int inner = 0;
for (int i = 0; i < 4; i++)
inner ^= sfmt[i] & parity[i];
for (int i = 16; i > 0; i >>= 1)
inner ^= inner >> i;
if ((inner & 1) != 0) // check OK
return;
for (int i = 0; i < 4; i++) {
int work = 1;
for (int j = 0; j < 32; j++) {
if ((work & parity[i]) != 0) {
sfmt[i] ^= work;
return;
}
work <<= 1;
}
}
}
| 6 |
public static void main(String[] args)
{
if(args.length > 1) {
String filename = args[0];
LinkedList<String> columns = new LinkedList<String>();
for(int i=1; i<args.length; i++) {
columns.add(args[i]);
}
try {
int[] entries = new int[1];
HashMap<Double, Integer> data = calculateDistribution(filename, columns, entries);
writeDistribution(data, columns, entries[0], filename);
}
catch(IOException exc) {
exc.printStackTrace(System.err);
}
catch(ParseException exc) {
System.err.println("Parsing values failed. Current language is " +NUMBER_FORMAT);
exc.printStackTrace(System.err);
}
} else {
System.err.println("Calculated the distribution of one or more columns");
System.err.println("usage: <filename> <[+|-|%]column1> [[+|-|%]column2...]");
}
}
| 4 |
public void update(){
//Sometimes there seems to be a slight lag between audio .start() and .isActive()
//The audioActivation-boolean takes care of that
if(audioActivation && audioClip.isActive()){
audioActivation = false;
}
if(clicked){
clicked();
}else if(!audioActivation&&audioClip!=null&&!audioClip.isActive()){
//Close audioclip if it isn't playing
this.audioClip.close();
}
}
| 6 |
@Override
public GameState[] allActions(GameState state, Card card, int time) {
GameState[] states = new GameState[1];
states[0] = state;
if(time == Time.DAY)
{
//Do nothing
}
else if(time == Time.DUSK)
{
PickTreasure temp = new PickTreasure();
states = temp.allActions(state, card, time);
}
else if(time == Time.NIGHT)
{
states = new GameState[]{freedSlaveNightAction(state, card, false)};
}
return states;
}
| 3 |
@SuppressWarnings("unchecked")
public String getOverviewChart() {
PreparedStatement st = null;
ResultSet rs = null;
JSONArray json = new JSONArray();
try {
conn = dbconn.getConnection();
st = conn.prepareStatement("SELECT team_id, sum(auton_top)*6 + sum(auton_middle)*4 + sum(auton_bottom)*2 as auton, sum(teleop_top)*3 + sum(teleop_middle)*2 + sum(teleop_bottom) + sum(teleop_pyramid)*5 as teleop, sum(pyramid_level)*10 as climb, sum(auton_top)*6 + sum(auton_middle)*4 + sum(auton_bottom)*2 + sum(teleop_top)*3 + sum(teleop_middle)*2 + sum(teleop_bottom) + sum(teleop_pyramid)*5 + sum(pyramid_level)*10 as total FROM match_record_2013 WHERE event_id = ? GROUP BY team_id order by total desc limit 10");
st.setInt(1, getSelectedEvent());
rs = st.executeQuery();
while (rs.next()) {
JSONObject o = new JSONObject();
o.put("id", rs.getInt("team_id"));
o.put("autonomous", rs.getInt("auton"));
o.put("teleop", rs.getInt("teleop"));
o.put("climb", rs.getInt("climb"));
o.put("total_points", rs.getInt("total"));
json.add(o);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
conn.close();
st.close();
rs.close();
}catch (SQLException e) {
System.out.println("Error closing query");
}
}
return json.toString();
}
| 3 |
public static Image scaleImage(Image source, int width, int height, int gap) {
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) img.getGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(source, 0, 0, width, height + gap, null);
g.dispose();
return img;
}
| 0 |
private boolean r_tidy_up() {
int among_var;
// (, line 183
// [, line 184
ket = cursor;
// substring, line 184
among_var = find_among_b(a_7, 4);
if (among_var == 0)
{
return false;
}
// ], line 184
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 188
// delete, line 188
slice_del();
// [, line 189
ket = cursor;
// literal, line 189
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// ], line 189
bra = cursor;
// literal, line 189
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// delete, line 189
slice_del();
break;
case 2:
// (, line 192
// literal, line 192
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// delete, line 192
slice_del();
break;
case 3:
// (, line 194
// delete, line 194
slice_del();
break;
}
return true;
}
| 8 |
@Override
public String toString() {
switch (handRank) {
case StraightFlush: return ranks.get(0) + " high " + handRank + " of " + suit;
case FourOfAKind: return "Four " + ranks.get(0) + "s, " + ranks.get(1) + " kicker";
case FullHouse: return handRank + ", " + ranks.get(0) + "s full of " + ranks.get(1) + "s";
case Flush: return ranks.get(0) + " high " + handRank + " of " + suit;
case Straight: return ranks.get(0) + " high " + handRank;
case ThreeOfAKind: return "Three " + ranks.get(0) + "s, " + ranks.get(1).shortName + ranks.get(2).shortName + " kicker";
case TwoPair: return "Two pair, " + ranks.get(0) + "s and " + ranks.get(1) + "s, " + ranks.get(2) + " kicker";
case OnePair: return "One pair, " + ranks.get(0) + "s, " + ranks.get(1).shortName + ranks.get(2).shortName + ranks.get(3).shortName + " kicker";
case HighCard: return ranks.get(0) + " high (" + ranks.get(0).shortName + ranks.get(1).shortName + ranks.get(2).shortName + ranks.get(3).shortName + ranks.get(4).shortName + ")";
default: throw new RuntimeException("unknown hand rank: " + handRank);
}
}
| 9 |
@Override
public void mousePressed(MouseEvent e) {
Piece[][] board = _modelBoard.getBoard();
chessPiece = null;
//Piece[][] board = _modelBoard.getBoard();
Component c = _view.getChessBoard().findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel) return;
if( c == null) return;
Point startLocation = c.getParent().getLocation();
xAdjustment = startLocation.x - e.getX();
yAdjustment = startLocation.y - e.getY();
startPanel = (Square) c.getParent();
int xViewStart = startPanel.getxPos();
int yViewStart = startPanel.getyPos();
//Pruefe ob Figur an dieser Stelle
if(analyse.testIfEmpty(xViewStart, yViewStart, board)){
System.out.println("Keine Figur an dieser Stelle!");
//Pruefe ob eigene Figur
}else if(analyse.testIfEnemy(_modelBoard.getPlayerOnTurn().isOwner(), xViewStart, yViewStart, board)){
System.out.println("Das ist keine von deinen Figuren!");
//Sonst bewegen
}else{
for(String entry: control.getPositionOfPosDestSquares(_modelBoard.getPieceOnBoard(xViewStart, yViewStart), xViewStart, yViewStart, board, _modelBoard.getPlayerOnTurn().isOwner())){
String[] parts = entry.split(",");
parts[0] = parts[0].trim();
parts[1] = parts[1].trim();
int xOut = Integer.parseInt(parts[0]);
int yOut = Integer.parseInt(parts[1]);
_view.findSquareByPos(xOut, yOut).setBackground(Color.GREEN);
if(!analyse.testIfEmpty(xOut, yOut, board)){
_view.findSquareByPos(xOut, yOut).setBackground(Color.RED);
}
}
chessPiece = (ChessPiece) c;
int x = e.getX() + xAdjustment;
int y = e.getY() + yAdjustment;
_view.movePiece(chessPiece, x, y);
_view.getFenster().add(chessPiece, JLayeredPane.DRAG_LAYER);
}
}
| 6 |
@Override
public void onKeyPressed(char key, int keyCode, boolean coded) {
if(!coded){
if(key == KeyEvent.VK_ENTER){
//Starts playing the midi
this.midiMusic.startMusic(0, null);
//When you start playing a new song, it isn't paused right from the get-go.
this.paused = false;
//And let's reset the tempo
this.midiMusic.resetTempoFactor();
System.out.println("You pressed ENTER, so the music should start!");
}
else if (key == 'p'){
//Pauses and continues playing music.
if(this.paused){
this.midiMusic.unpause();
this.paused = false;
System.out.println("You pressed p, so music should continue.");
}else{
this.midiMusic.pause();
this.paused = true;
System.out.println("You pressed p, so music should pause.");
}
}
else if (key == 's'){
//Stops playing the music
this.midiMusic.stop();
System.out.println("You pressed s, so everything should stop.");
}
else if (key == 't'){
//Doubles the tempo and resets it
if(this.midiMusic.getTempoFactor() > 1){
this.midiMusic.resetTempoFactor();
System.out.println("You pressed t, so music should return to normal.");
}else{
this.midiMusic.setTempoFactor(2);
System.out.println("You pressed t, so tempo should increase.");
}
}
else if (key == 'l'){
//Sets new start and end points for looping
if(this.looping){
this.midiMusic.setLoopCount(0);
this.midiMusic.setDefaultLoopPoints();
this.looping = false;
System.out.println("You pressed l, so looping should end.");
}else{
this.midiMusic.setLoopCount(-1);
this.midiMusic.setLoopEnd(this.midiMusic.getSequenceLength() - 1000);
this.looping = true;
System.out.println("You pressed l, so looping should start.");
}
}
}
}
| 9 |
@Override
public SkillsMain[] getSkillNames() {
return Constants.rogueSkillSkills;
}
| 0 |
private void afficherDetailsPraticien(String Praticien){
if (ctrlPraticiens == null) {
VuePraticiens vueP = new VuePraticiens(ctrlA);
ctrlPraticiens = new CtrlPraticiens(vueP, vueA);
}
//préparation des combos box
String nomPraticien= Praticien.split(" ")[0];
String prenomPraticien= Praticien.split(" ")[1];
lePraticien = DaoPraticienJPA.selectOneByNomPrenom(em, nomPraticien, prenomPraticien);
ctrlPraticiens.afficherPraticien(lePraticien);
ctrlPraticiens.getVue().setVisible(true);
}
| 1 |
public static void main(String[] args)
{
boolean debugger = false;
if(args != null && args.length > 0 && args[0].equals("true"))
{
debugger = true;
}
Main main = new Main(debugger);
main.setVisible(true);
}
| 3 |
public Date getDoneTime() {
return doneTime;
}
| 0 |
public Board(ArrayList<SimulatorRobot> r, String theme) {
setDoubleBuffered(true);
this.bullets = new Vector();
this.deadRobots = new ArrayList();
this.pills = new ArrayList();
this.expAnim = new ArrayList();
this.obstacles = new ArrayList();
this.ovnis = new ArrayList();
this.robots = r;
this.theme = theme;
for (int i = 0; i < robots.size(); i++) {
if (robots.get(i) != null) {
new Thread(robots.get(i)).start();
pills.add(new HealthPill());
}
}
numObstacles = 1;
for(int i=0; i<numObstacles; i++){
boolean in = false;
while(!in){
Obstacle obs = new Obstacle();
Rectangle2D robstacle = new Rectangle((int)obs.getX(), (int)obs.getY(), obs.getWidth(), obs.getHeight());
for(int c=0; c<Board.robots.size(); c++){
Rectangle2D rrobot = new Rectangle((int)Board.robots.get(c).getX(), (int)Board.robots.get(c).getY(), Board.robots.get(c).getWidth(), Board.robots.get(c).getHeight());
if(!rrobot.intersects(robstacle)){
obstacles.add(obs);
in = true;
return;
}
}
}
}
}
| 6 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(affected==null)
return false;
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
if((!mob.amDead())&&((--diseaseTick)<=0))
{
MOB diseaser=invoker;
if(diseaser==null)
diseaser=mob;
diseaseTick=DISEASE_DELAY();
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,DISEASE_AFFECT());
int dmg=mob.phyStats().level()/2;
if(dmg<1)
dmg=1;
CMLib.combat().postDamage(diseaser,mob,this,dmg,CMMsg.MASK_ALWAYS|CMMsg.TYP_DISEASE,-1,null);
catchIt(mob);
return true;
}
return true;
}
| 7 |
private void writeAnimation(Sprite s, XMLWriter w) throws IOException {
w.startElement("animation");
for (int k = 0; k < s.getTotalKeys(); k++) {
Sprite.KeyFrame key = s.getKey(k);
w.startElement("keyframe");
w.writeAttribute("name", key.getName());
for (int it = 0; it < key.getTotalFrames(); it++) {
Tile stile = key.getFrame(it);
w.startElement("tile");
w.writeAttribute("gid", getGid(stile));
w.endElement();
}
w.endElement();
}
w.endElement();
}
| 2 |
protected static Method findSetter(String name, Class<?> type,
Class<?> self) {
if (name == null || name.trim().isEmpty()) {
return null;
}
Method[] methods = self.getDeclaredMethods();
for (Method method : methods) {
if (!method.getName().equals(name)) {
continue;
}
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length != 1) {
continue;
}
if (ClassUtils.isAssignable(parameters[0], type)) {
return method;
}
}
return null;
}
| 9 |
private void setTimeSpinners() {
Date date = getDate();
if (date != null) {
timeSpinner.setValue( date );
}
}
| 1 |
private static Box initialize() {
Box[] nodes = new Box[7];
nodes[1] = new Box(1);
int[] s = {1, 4, 7};
for (int i = 0; i < 3; ++i) {
nodes[2] = new Box(21 + i);
nodes[1].add(nodes[2]);
int lev = 3;
for (int j = 0; j < 4; ++j) {
nodes[lev - 1].add(new Product(lev * 10 + s[i]));
nodes[lev] = new Box(lev * 10 + s[i] + 1);
nodes[lev - 1].add(nodes[lev]);
nodes[lev - 1].add(new Product(lev * 10 + s[i] + 2));
lev++;
}
}
return nodes[1];
}
| 2 |
@Override
public int hashCode() {
int result = id;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (businessPhone != null ? businessPhone.hashCode() : 0);
result = 31 * result + (homePhone != null ? homePhone.hashCode() : 0);
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (primaryContact ? 1 : 0);
result = 31 * result + (account != null ? account.hashCode() : 0);
return result;
}
| 7 |
public boolean stateEquals(Object o) {
if (o == this)
return true;
if (o == null || !(o instanceof MersenneTwister))
return false;
MersenneTwister other = (MersenneTwister) o;
if (mti != other.mti)
return false;
for (int x = 0; x < mag01.length; x++)
if (mag01[x] != other.mag01[x])
return false;
for (int x = 0; x < mt.length; x++)
if (mt[x] != other.mt[x])
return false;
return true;
}
| 8 |
public void equipOutfit(Item outfit) {
if (! (outfit.type instanceof OutfitType)) return ;
final Actor actor = (Actor) owner ;
final JointSprite sprite = (JointSprite) actor.sprite() ;
final Item oldItem = this.outfit ;
this.outfit = outfit ;
if (hasShields()) fuelCells = MAX_FUEL_CELLS ;
//
// Attach/detach the appropriate media-
if (oldItem != null) {
final OutfitType type = (OutfitType) oldItem.type ;
if (type.skin != null) sprite.removeOverlay(type.skin) ;
}
if (outfit != null) {
final OutfitType type = (OutfitType) outfit.type ;
if (type.skin != null) sprite.overlayTexture(type.skin) ;
currentShields = SHIELD_CHARGE + type.shieldBonus ;
}
}
| 6 |
private static void parseUnit(UnitTree tree, SourceInputStream in)
throws IOException, ParseException {
int ch = in.read();
List<Tree> children = tree.getChildren();
while (ch != -1) {
in.backup();
switch (ch) {
case '+':
case '-':
children.add(parseInc(in));
break;
case '<':
case '>':
children.add(parseMove(in));
break;
case ',':
children.add(new GetCharTree(in.position()));
in.read();
break;
case '.':
children.add(new PutCharTree(in.position()));
in.read();
break;
case '[':
children.add(parseLoop(in));
break;
case ']':
throw new ParseException(" ] without matching [", in.position());
default:
in.read();
}
ch = in.read();
}
}
| 9 |
public Collection<String> getFormatableAttributes(Class<?> clazz) {
Collection<String> attributes = new ArrayList<String>();
for(Method m : clazz.getMethods()) {
// lookup getters
String name = m.getName();
if (m.getParameterTypes().length == 0 && name.matches(getterPattern) && !exceptions.contains(name)) {
attributes.add(getAttributeName(name));
}
}
return attributes;
}
| 5 |
static String readChunk(BufferedReader br, int len) throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; ++i) {
int ch = br.read();
if (ch < 0)
throw new Exception("unexpected EOF in body");
if (ch >= U_0080 && ch < U_0800) // 2 bytes
++i;
else if (ch >= U_D800 && ch < U_E000) // 2 + 2 bytes
++i;
else if (ch >= U_0800 && ch < U_10000) // 3 bytes
i += 2;
else if (ch >= U_10000) // 4 bytes
i += 3;
sb.append((char) ch);
}
return sb.toString();
}
| 9 |
public int SubjectVariable(PHPFileOperations PHPFile, String PHPFileTextClean, int CharNumStart) {
int i = 0, l = PHPFileTextClean.length();
char ch = ' ';
i = CharNumStart;
//recursively detect what follows the function name
while (i < l) {
ch = PHPFileTextClean.charAt(i);
if (ch == '(') {
i = PHPFile.SearchEndChar(PHPFileTextClean, i + 1, ')');
} else if (ch == '{') {
i = PHPFile.SearchEndChar(PHPFileTextClean, i + 1, '}');
} else if (ch == '\"') {
i = PHPFileTextClean.indexOf('\"', i);
// i = SearchEndChar(PHPFileTextClean, i + 1, '\"');
} else if (ch == '\'') {
i = PHPFileTextClean.indexOf('\'', i);
// i = SearchEndChar(PHPFileTextClean, i + 1, '\'');
} else if (ch == '/' & PHPFileTextClean.charAt(i + 1) == '/') {
i = PHPFileTextClean.indexOf('\n', i);
} else if (ch == ',' | ch == ';' | ch == '.' | ch == ' ' | ch == ')') {
break;
}
i++;
}
return i;
}
| 7 |
public void vieillir() {
super.vieillir();
loterie = new Random();
if (age > 15)
fertilite = loterie.nextInt(100);
if (age <= 15 && poids < 40)
grossir(loterie.nextInt(3) + 1);
}
| 3 |
StandardPlane(AbstractToolkit abstracttoolkit, int i, int i_123_, int i_124_, int i_125_, int[][] is, int[][] is_126_, int i_127_) {
super(i_124_, i_125_, i_127_, is);
anAbstractToolkit8004 = abstracttoolkit;
anInt7993 = -2 + anInt3410;
anIntArrayArrayArray8013 = new int[i_124_][i_125_][];
anIntArrayArrayArray7986 = new int[i_124_][i_125_][];
anIntArrayArrayArray8006 = new int[i_124_][i_125_][];
aByteArrayArray8026 = new byte[1 + i_124_][1 + i_125_];
anInt7982 = 1 << anInt7993;
aShortArrayArray7985 = new short[i_125_ * i_124_][];
aFloatArrayArray8021 = new float[1 + anInt3408][anInt3404 - -1];
aFloatArrayArray8019 = new float[1 + anInt3408][anInt3404 - -1];
aByteArrayArray7996 = new byte[i_124_][i_125_];
anIntArrayArrayArray7995 = new int[i_124_][i_125_][];
anInt7981 = i_123_;
anIntArrayArrayArray7997 = new int[i_124_][i_125_][];
aNode_Sub54ArrayArrayArray8007 = new Node_Sub54[i_124_][i_125_][];
aFloatArrayArray8025 = new float[1 + anInt3408][anInt3404 + 1];
for (int i_128_ = 0; i_128_ <= anInt3404; i_128_++) {
for (int i_129_ = 0; (i_129_ ^ 0xffffffff) >= (anInt3408 ^ 0xffffffff); i_129_++) {
int i_130_ = anIntArrayArray3407[i_129_][i_128_];
if (aFloat7988 > (float) i_130_) {
aFloat7988 = (float) i_130_;
}
if ((float) i_130_ > aFloat7987) {
aFloat7987 = (float) i_130_;
}
if (i_129_ > 0 && (i_128_ ^ 0xffffffff) < -1 && i_129_ < anInt3408 && (i_128_ ^ 0xffffffff) > (anInt3404 ^ 0xffffffff)) {
int i_131_ = -is_126_[i_129_ + -1][i_128_] + is_126_[i_129_ + 1][i_128_];
int i_132_ = is_126_[i_129_][1 + i_128_] - is_126_[i_129_][-1 + i_128_];
float f = (float) (1.0 / Math.sqrt((double) (i_132_ * i_132_ + i_131_ * i_131_ + 4 * (i_127_ * i_127_))));
aFloatArrayArray8019[i_129_][i_128_] = f * (float) i_131_;
aFloatArrayArray8021[i_129_][i_128_] = f * (float) (2 * -i_127_);
aFloatArrayArray8025[i_129_][i_128_] = f * (float) i_132_;
}
}
}
aFloat7988--;
aFloat7987++;
aHashTable8022 = new HashTable(128);
if ((anInt7981 & 0x10) != 0) {
aClass263_8008 = new Class263(anAbstractToolkit8004, this);
}
}
| 9 |
public void putAll( Map<? extends Float, ? extends Byte> map ) {
Iterator<? extends Entry<? extends Float,? extends Byte>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Float,? extends Byte> e = it.next();
this.put( e.getKey(), e.getValue() );
}
}
| 8 |
private void setUpShader(String vertexPath, String fragmentPath) throws IOException {
shaderProgram = glCreateProgram();
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
StringBuilder vertexShaderSource = new StringBuilder();
StringBuilder fragmentShaderSource = new StringBuilder();
BufferedReader vertexReader = new BufferedReader(new FileReader(vertexPath));
BufferedReader fragmentReader = new BufferedReader(new FileReader(fragmentPath));
String vertexLine = null;
while ((vertexLine = vertexReader.readLine()) != null) {
vertexShaderSource.append(vertexLine).append('\n');
}
vertexReader.close();
String fragmentLine = null;
while ((fragmentLine = fragmentReader.readLine()) != null) {
fragmentShaderSource.append(fragmentLine).append('\n');
}
fragmentReader.close();
glShaderSource(vertexShader, vertexShaderSource);
glCompileShader(vertexShader);
if (glGetShaderi(vertexShader, GL_COMPILE_STATUS) == GL_FALSE) {
System.err.println("Vertex shader was not compiled.");
System.err.println(glGetShaderInfoLog(vertexShader, 1024));
throw new RuntimeException();
}
glShaderSource(fragmentShader, fragmentShaderSource);
glCompileShader(fragmentShader);
if (glGetShaderi(fragmentShader, GL_COMPILE_STATUS) == GL_FALSE) {
System.err.println("Fragment shader was not compiled.");
System.err.println(glGetShaderInfoLog(fragmentShader, 1024));
throw new RuntimeException();
}
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
if (glGetProgrami(shaderProgram, GL_LINK_STATUS) == GL_FALSE) {
System.err.println("Shader program was not linked.");
System.err.println(glGetProgramInfoLog(shaderProgram, 1024));
throw new RuntimeException();
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
| 5 |
public Object newInstance(final Object... override) throws InstantiationException, IllegalAccessException
{
if (clazz != null) {
return clazz.newInstance();
}
else if (isCollection || isArray) {
if (override.length > 0) {
return ((Class<?>) override[0]).newInstance();
}
else if (collectionClass != null) {
return collectionClass.newInstance();
}
else {
return new ArrayList<Object>();
}
}
else if (isMap) {
return new HashMap<Object, Object>();
}
return field.getType().newInstance();
}
| 7 |
@Override
public Titre insert(Titre obj) {
PreparedStatement pst = null;
try {
pst = this.connect().prepareStatement("INSERT INTO Titre (nom,annee,id) VALUES (?,?,?);");
pst.setString(1, obj.getNom());
pst.setString(2, obj.getAnnee());
pst.setInt(3, obj.getId());
pst.executeUpdate();
System.out.println("insertion Titre terminer");
} catch (SQLException ex) {
Logger.getLogger(TitreDao.class.getName()).log(Level.SEVERE, "insertion echouer", ex);
}finally{
try {
if(pst != null)
pst.close();
} catch (SQLException ex) {
Logger.getLogger(TitreDao.class.getName()).log(Level.SEVERE, "liberation du preparedstatement echouée", ex);
}
}
return obj;
}
| 3 |
@After
public void tearDown() {
}
| 0 |
protected void getClaimDetail(String title) {
if (title != null) {
for (int i = 0; i < claimResultList.size(); i++) {
if (claimResultList.get(i).getTitle().equals(title)) {
if (!(claimResultList.get(i).getDescription() == null
|| claimResultList.get(i).getDescription().equals("null"))) {
descriptionJtxa.setText(claimResultList.get(i).getDescription());
}
if (!(claimResultList.get(i).getParentClaim() == null
|| claimResultList.get(i).getParentClaim().equals("null"))) {
parentContentJlbl.setText(claimResultList.get(i).getParentClaim().getTitle());
} else {
parentContentJlbl.setText("None");
}
dialogContentJlbl.setText(claimResultList.get(i).getDialogState());
playerContentJlbl.setText(claimResultList.get(i).getName());
currentClaim = claimResultList.get(i);
break;
}
}
}
}
| 7 |
Color getShadedColorForType(int pType, double pSunValue)
{
double lBrightness;
if(pSunValue < 0)
{
// The sun is below the horizon.
lBrightness = fNightSideBrightness / 100;
} else
{
// The sun is above the horizon. The brightness will range from
// the base to the maximum value.
lBrightness = (fDaySideValueBase + pSunValue * fDaySideValueRange) / 100;
}
if(lBrightness > 1.0)
{
lBrightness = 1.0;
}
switch(pType)
{
case BitGeneratorMap.PixTypeSpace:
return COLOR_SPACE;
case BitGeneratorMap.PixTypeStar:
return COLOR_STAR;
case BitGeneratorMap.PixTypeGridLand:
return shade(COLOR_GRID_LAND, lBrightness);
case BitGeneratorMap.PixTypeGridWater:
return shade(COLOR_GRID_WATER, lBrightness);
case BitGeneratorMap.PixTypeLand:
return shade(COLOR_LAND, lBrightness);
case BitGeneratorMap.PixTypeWater:
return shade(COLOR_WATER, lBrightness);
}
return null;
}
| 8 |
public void redraw() {
// update playing area
// 1) look at cards in playerHand and dealerHand and add/update labes in the "Grid"
for (int i = 1; i < dealerHand.getCardCount() + 1; i++) {
Card dealerCard = dealerHand.getCard(i - 1);
arLblDealer[i].setIcon(new ImageIcon(GetFileName(dealerCard)));
}
for (int i = 1; i < playerHand.getCardCount() + 1; i++) {
Card playerCard = playerHand.getCard(i - 1);
arLblPlayer[i].setIcon(new ImageIcon(GetFileName(playerCard)));
}
if (bInGame) {
arLblDealer[1].setIcon(new ImageIcon("back-blue-75-2.png"));
}
// 2) update any status messages
lblStatus.setText(sMessage);
lblMoney.setText(sMoney);
}
| 3 |
public static BufferedImage crop(BufferedImage image, int x, int y, int width, int height) {
return image.getSubimage(x, y, (width > 0 ? width : 1), (height > 0 ? height : 1));
}
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.