text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void move(int xa, int ya){
if(xa != 0 && ya != 0){
move(xa, 0);
move(0, ya);
numSteps--;
return;
}
numSteps++;
if(!hasCollided(xa, ya)){
if(ya < 0) {
movingDir = 0;
}
if(ya > 0){
movingDir = 1;
}
if(xa < 0){
movingDir = 2;
}
if(xa > 0){
movingDir = 3;
}
x += xa * speed;
y += ya * speed;
}
} | 7 |
@Override
public void setValue(Object o) {
this.nativeValue=this.convertObject(o);
} | 0 |
@Override
public String execute() {
String actionResult = "";
Map<String, Object> session = ActionContext.getContext().getSession();
User user = (User) session.get("USER");
if (user != null) {
setCurrentUserName(user.getFname() + " " + user.getLname() + " [G]");
String str1=vehicleBusinesService.validateDeviceInVehicle(deviceid,vehicleId);
if(str1.equals("deviceidExist")){
addFieldError("deviceid","Device ID already EXIST.");
actionResult="input";
}else{
}if(str1.equals("ok")){
Vehicle vehicle = new Vehicle();
vehicle.setVehicleId(getVehicleId());
vehicle.setDeviceid(getDeviceid());
vehicle.setVn(vn);
vehicle.setVmake(getVmake());
vehicle.setVmodel(getVmodel());
vehicle.setVfuel_type(getVfuel_type());
String str = getVehicleBusinesService().updateVehicle(vehicle);
if (str.equals("notUpdated")) {
actionResult = "input";
System.err.println(actionResult+"notupdated");
} else {
if (str.equals("updated")) {
actionResult = "success";
}
}
}
if (user.getUprofile() == 2) {
setCurrentUserName(getCurrentUserName() + " [G]");
} else {
if (user.getUprofile() == 3) {
setCurrentUserName(getCurrentUserName() + " [A]");
}
}
}
return actionResult;
} | 7 |
public static String save(Component parent, String filestring) {
if (FileDialogs.hasFileAccess()) {
URL url = ClassLoader.getSystemResource("circuits");
String urlName = url.getFile().substring(1);
if (FileDialogs.fc == null) {
FileDialogs.fc = new JFileChooser(urlName);
}
FileDialogs.fc.setFileFilter(new TextFilter("cir"));
int returnVal = FileDialogs.fc.showSaveDialog(parent);
if (returnVal == 0) {
try {
File file = FileDialogs.fc.getSelectedFile();
FileOutputStream fw = new FileOutputStream(file);
OutputStreamWriter ow = new OutputStreamWriter(fw, "ISO-8859-1");
BufferedWriter bw = new BufferedWriter(ow);
StringReader sr = new StringReader(filestring);
BufferedReader br = new BufferedReader(sr);
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
bw.close();
fw.close();
ow.close();
sr.close();
br.close();
return file.getCanonicalPath();
} catch (IOException e) {
JOptionPane.showMessageDialog(parent, "Error Saving File.\n" + e.getMessage(), "Error FileDialogs.001", 0);
}
}
} else if (FileDialogs.hasClipboardAccess()) {
final JDialog dialog = new JDialog(JOptionPane.getFrameForComponent(parent), "Save", true);
dialog.getContentPane().setLayout(new BorderLayout());
JPanel pane = new JPanel(new BorderLayout());
JLabel label = new JLabel("To Save copy text into a file");
label.setForeground(Color.black);
final JTextArea savearea = new JTextArea(filestring);
savearea.setEditable(false);
savearea.selectAll();
savearea.setPreferredSize(new Dimension(200, 300));
JScrollPane scroller = new JScrollPane(savearea);
pane.add(scroller, "Center");
dialog.getContentPane().add(label, "North");
dialog.getContentPane().add(pane, "Center");
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(1));
dialog.getContentPane().add(buttonPane, "South");
JButton copyButton = new JButton("Copy");
buttonPane.add(copyButton);
copyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
savearea.selectAll();
savearea.copy();
}
});
JButton okButton = new JButton("Close");
dialog.getRootPane().setDefaultButton(okButton);
buttonPane.add(okButton);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
dialog.setLocationRelativeTo(parent);
dialog.pack();
dialog.setVisible(false);
} else {
JOptionPane.showMessageDialog(parent, "Insufficient privilages to save.\nSee Help-Loading and Saving or the Webpage for details of how to enable loading and saving.", "Loading and Saving Disabled", 2);
}
return "";
} | 6 |
Deck() {
// Used to assign values to each card rank.
Integer cardValue = new Integer(1);
String suitRank;
/**
* Assign a unique <"rank-suit", cardValue> mapping for each card and store it into the 'cardValueMap', which
* will be the main data structure to represent our deck of cards.
*/
for (String rank: ranks) {
for (String suit: suits) {
// Create the unique "rank-suit" key by concatenating the rank and suit strings.
suitRank = rank.concat("-" + suit);
// Add the unique "rank-suit" key into a list to keep track of them.
suitRanks.add(suitRank);
// Finally, assign an integer value to each "rank-suit" key, a.k.a card.
cardValueMap.put(suitRank, cardValue);
}
if(cardValue != 10) { cardValue++; }
}
} | 3 |
public static int mySearch(int[] arr, int number)
{
int i=0;
for (i=0; i<arr.length; i++)
{
if (arr[i]==number){return i;}
}
return i;
} | 2 |
private static String[] split(String data, String splits, boolean trim) {
// System.out.println("Split called: '" + data + "' <?> " + splits);
Vector strings = new Vector();
int lastPos = 0;
int mode = 0;
for (int i = 0, n = data.length(); i < n; i++) {
char c = data.charAt(i);
if (splits.indexOf(c) != -1) {
if (mode == 0) {
if (lastPos != 0 && ((lastPos + 1) < n))
lastPos++;
strings.addElement(data.substring(lastPos, i));
}
lastPos = i;
mode = 1;
} else {
mode = 0;
}
}
if (lastPos != 0 && lastPos + 1 < data.length())
lastPos++;
strings.addElement(data.substring(lastPos, data.length()));
String[] retval = new String[strings.size()];
for (int i = 0, n = retval.length; i < n; i++) {
retval[i] = (String) strings.elementAt(i);
}
return retval;
} | 8 |
private Area recursiveGetAreaByName(Area root, String name)
{
if (root.toString().indexOf(name) != -1) //TODO ???
return root;
else
{
for (int i = 0; i < root.getChildCount(); i++)
{
Area ret = recursiveGetAreaByName(root.getChildArea(i), name);
if (ret != null)
return ret;
}
return null;
}
} | 3 |
public static String rightTrim(String str) {
if (str == null) {
return "";
}
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) != 0x20) {
break;
}
length--;
}
return str.substring(0, length);
} | 3 |
public void paint(Graphics g) {
Font helvetica = new Font("Helvetica", Font.BOLD, 18);
g.setFont(helvetica);
g.setColor(Color.WHITE);
//draws the number of sitted people on the center of a table...
//moves the text 10 units up to avoid being covered by the sitted fellas
if (tipo == 1 || tipo == 2 || tipo == 4 || tipo == 5 || tipo == 6 || tipo == 7) {
g.drawString(getValor() + "", getPosX() + getAncho(), getPosY() - 10);
} else {
g.setColor(Color.YELLOW);
g.drawString(getValor() + "", getPosX() + getAncho(), getPosY() - 25);
}
g.setColor(Color.BLACK);
g.drawImage(getImageIcon().getImage(), getPosX(), getPosY(), null);
if (upgrade.getFuncion() != 0) {
upgrade.paint(g, getPosX(), getPosY(), Mesa.this);
}
} | 7 |
public static long calProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return 0;
}
int len = prices.length;
Stack<Integer> highes = new Stack<Integer>();
int localHigh = prices[len-1];
for (int i=len-2; i>=0; i--) {
if (prices[i] < prices[i+1] && prices[i+1] >= localHigh) {
highes.push(i+1);
localHigh = prices[i+1];
}
}
if (highes.isEmpty()) {
return 0;
}
int index = 0, high = highes.pop();
long profit = 0;
while (index < len) {
while (index < high) {
profit += prices[high] - prices[index];
index++;
}
index = high+1;
if (highes.isEmpty()) {
break;
} else {
high = highes.pop();
}
}
return profit;
} | 9 |
private void save(CompoundTag tag)
{
File file = new File(path + player.getName() + ".dat");
File temp;
FileOutputStream output_stream;
NBTOutputStream nbt_output;
if (!file.exists())
{
if (file.getParent() != null)
file.getParentFile().mkdirs();
try
{
file.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
return;
}
}
try
{
temp = File.createTempFile(player.getName(), ".dat.temp");
}
catch (IOException e)
{
e.printStackTrace();
return;
}
try
{
output_stream = new FileOutputStream(temp);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return;
}
try
{
nbt_output = new NBTOutputStream(output_stream);
}
catch (IOException e)
{
e.printStackTrace();
return;
}
try
{
nbt_output.writeTag("", tag);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
nbt_output.close();
}
catch (IOException e)
{
e.printStackTrace();
return;
}
FileUtil.copy(temp, file);
temp.delete();
changed = false;
} | 8 |
protected void initialize() {
Robot.driveTrain.clearEncoder();
} | 0 |
public static void run()
{
System.out.println("\n\n--|Advanced Dice|--------------------------------------------------------------");
System.out.println("Roll 3d6 with only ONE call to the RNG");
// load a hat with our chance weights
Hat<Integer> dice = new Hat<Integer>();
int chances[]={1, 3, 6, 10, 15, 21, 25, 27, 27, 25, 21, 15, 10, 6, 3, 1};
for(int sum = 3; sum <= 18; sum++)
{
dice.put( sum, chances[sum-3] );
}
// roll 3d6 six times
for( int i=0; i<10; i++ ){
System.out.print(dice.get() + " ");
}
} | 2 |
public void put(String atrName, Object val) {
if (atrName.equals(LABEL)) {
v.setLabel((String) val);
} else if (atrName.equals(SHAPE)) {
v.setShape((GShape) val);
} else if (atrName.equals(BORDER)) {
v.setShapeStroke((GStroke) val);
} else if (atrName.equals(LOCATION)) {
v.setLocation((GraphPoint) val);
} else if (atrName.equals(SIZE)) {
v.setSize((GraphPoint) val);
} else if (atrName.equals(MARK)) {
v.setMark((Boolean) val);
} else if (atrName.equals(SELECTED)) {
v.setSelected((Boolean) val);
} else if (atrName.equals(COLOR)) {
v.setColor((Integer) val);
} else if (atrName.equals(LABEL_LOCATION)) {
v.setLabelLocation((GraphPoint) val);
} else {
v.setUserDefinedAttribute(atrName, val);
}
} | 9 |
@SuppressWarnings("unchecked")
public <T> T createDao(Class<T> clazz) throws Exception {
T instance = (T) proxyCache.get(clazz);
if (instance == null) {
DataAccessInterceptor interceptor = newDataAccessInterceptor();
detectDataAccessMethod(clazz, interceptor);
instance = (T) Enhancer.create(clazz, interceptor);
proxyCache.put(clazz, instance);
}
return instance;
} | 1 |
public static SyslogLevel mapStringToSyslog(String level) {
level = level.toLowerCase().trim();
if (level.equals("debug")) {
return SyslogLevel.DEBUG;
} else if (level.equals("info")) {
return SyslogLevel.INFO;
} else if (level.equals("notice")) {
return SyslogLevel.NOTICE;
} else if (level.equals("warning") || level.equals("warn")) {
return SyslogLevel.WARNING;
} else if (level.equals("error")) {
return SyslogLevel.ERROR;
} else if (level.equals("critical")) {
return SyslogLevel.CRITICAL;
} else if (level.equals("alert")) {
return SyslogLevel.ALERT;
} else if (level.equals("emergency")) {
return SyslogLevel.EMERGENCY;
}
return SyslogLevel.DEBUG;
} | 9 |
public int GetCLWoodcutting(int ItemID) {
if (ItemID == 10764) {
return 100;
}
if (ItemID == 10766) {
return 100;
}
if (ItemID == -1) {
return 1;
}
String ItemName = GetItemName(ItemID);
if (ItemName.startsWith("Woodcut. cape")) {
return 100;
}
if (ItemName.startsWith("Woodcutting hood")) {
return 100;
}
return 1;
} | 5 |
public PerformanceTester() {
} | 0 |
private static void print(ResultSet s, int actIndex) {
String resString = "";
try {
while (s.next()) {
resString += "\nName: "
+ s.getString("c_vorname")
+ " "
+ s.getString("c_nachname")
+ "\nGebdat: "
+ (s.getDate("c_gebdat",
GregorianCalendar.getInstance())).toString()
+ "\nOrt: " + s.getString("c_ort") + "\nPLZ: "
+ s.getString("c_plz")
+ "\n-----------------------------------------------";
}
// Just for JOptionPane Message!
int erg = -2;
while (erg == -2) {
if (actIndex == 1) {
erg = JOptionPane.showConfirmDialog(null, resString,
"Alle Customer - SELECT", JOptionPane.OK_OPTION);
} else if (actIndex == 2) {
erg = JOptionPane.showConfirmDialog(null, resString,
"Alle Customer - AFTER INSERT",
JOptionPane.OK_OPTION);
} else if (actIndex == 3) {
erg = JOptionPane.showConfirmDialog(null, resString,
"Alle Customer - AFTER DELETE",
JOptionPane.OK_OPTION);
} else if (actIndex == 4) {
erg = JOptionPane
.showConfirmDialog(
null,
resString,
"Alle Customer - AFTER INSERT with PreparedStatement",
JOptionPane.OK_OPTION);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
} | 7 |
public ProjCoordinate projectInverse(double xyx, double xyy, ProjCoordinate out) {
double th;
th = xyy * ( xyy < 0. ? RYCS : RYCN);
if (Math.abs(th) > 1.)
if (Math.abs(th) > ONETOL) throw new ProjectionException("I");
else th = th > 0. ? ProjectionMath.HALFPI : - ProjectionMath.HALFPI;
else
th = Math.asin(th);
out.x = RXC * xyx / Math.cos(th);
th += th;
out.y = (th + Math.sin(th)) * (xyy < 0. ? RCS : RCN);
if (Math.abs(out.y) > 1.)
if (Math.abs(out.y) > ONETOL) throw new ProjectionException("I");
else out.y = out.y > 0. ? ProjectionMath.HALFPI : - ProjectionMath.HALFPI;
else
out.y = Math.asin(out.y);
return out;
} | 8 |
private String spaceSet(Set set) {
Iterator it = set.iterator();
boolean first = true;
StringBuffer sb = new StringBuffer();
while (it.hasNext()) {
if (!first)
sb.append(" ");
String s = (String) it.next();
sb.append(s.equals("") ? "!" : s);
first = false;
}
return sb.toString();
} | 3 |
public void close() throws IOException {
if(r != null) {
r = null;
ogg.close();
ogg = null;
}
if(w != null) {
w.bufferPacket(info.write(), true);
w.bufferPacket(comment.write(), false);
w.bufferPacket(setup.write(), true);
long lastGranule = 0;
for(VorbisAudioData vd : writtenPackets) {
// Update the granule position as we go
if(vd.getGranulePosition() >= 0 &&
lastGranule != vd.getGranulePosition()) {
w.flush();
lastGranule = vd.getGranulePosition();
w.setGranulePosition(lastGranule);
}
// Write the data, flushing if needed
w.bufferPacket(vd.write());
if(w.getSizePendingFlush() > 16384) {
w.flush();
}
}
w.close();
w = null;
ogg.close();
ogg = null;
}
} | 6 |
private Interceptor[] createInterceptors(Before beforeAnnotation) {
if (beforeAnnotation == null)
return null;
Interceptor[] result = null;
@SuppressWarnings("unchecked")
Class<Interceptor>[] interceptorClasses = (Class<Interceptor>[]) beforeAnnotation.value();
if (interceptorClasses != null && interceptorClasses.length > 0) {
result = new Interceptor[interceptorClasses.length];
for (int i=0; i<interceptorClasses.length; i++) {
result[i] = interMap.get(interceptorClasses[i]);
if (result[i] != null) {
continue;
}
try {
result[i] = interceptorClasses[i].newInstance();
interMap.put(interceptorClasses[i], result[i]);
} catch (Exception e) {
new RuntimeException();
}
}
}
return result;
} | 6 |
private void writeParameters(ObjectOutputStream dout, Object[] params)
throws IOException
{
int n = params.length;
dout.writeInt(n);
for (int i = 0; i < n; ++i)
if (params[i] instanceof Proxy) {
Proxy p = (Proxy)params[i];
dout.writeObject(new RemoteRef(p._getObjectId()));
}
else
dout.writeObject(params[i]);
} | 2 |
public void execute() {
m_random = new Random(m_rowNumber * 11);
m_dataGenerator.setSeed(m_rowNumber * 11);
m_result = new RemoteResult(m_rowNumber, m_panelWidth);
m_status.setTaskResult(m_result);
m_status.setExecutionStatus(TaskStatusInfo.PROCESSING);
try {
m_numOfSamplesPerGenerator =
(int)Math.pow(m_samplesBase, m_trainingData.numAttributes()-3);
if (m_trainingData == null) {
throw new Exception("No training data set (BoundaryPanel)");
}
if (m_classifier == null) {
throw new Exception("No classifier set (BoundaryPanel)");
}
if (m_dataGenerator == null) {
throw new Exception("No data generator set (BoundaryPanel)");
}
if (m_trainingData.attribute(m_xAttribute).isNominal() ||
m_trainingData.attribute(m_yAttribute).isNominal()) {
throw new Exception("Visualization dimensions must be numeric "
+"(RemoteBoundaryVisualizerSubTask)");
}
m_attsToWeightOn = new boolean[m_trainingData.numAttributes()];
m_attsToWeightOn[m_xAttribute] = true;
m_attsToWeightOn[m_yAttribute] = true;
// generate samples
m_weightingAttsValues = new double [m_attsToWeightOn.length];
m_vals = new double[m_trainingData.numAttributes()];
m_predInst = new DenseInstance(1.0, m_vals);
m_predInst.setDataset(m_trainingData);
System.err.println("Executing row number "+m_rowNumber);
for (int j = 0; j < m_panelWidth; j++) {
double [] preds = calculateRegionProbs(j, m_rowNumber);
m_result.setLocationProbs(j, preds);
m_result.
setPercentCompleted((int)(100 * ((double)j / (double)m_panelWidth)));
}
} catch (Exception ex) {
m_status.setExecutionStatus(TaskStatusInfo.FAILED);
m_status.setStatusMessage("Row "+m_rowNumber+" failed.");
System.err.print(ex);
return;
}
// finished
m_status.setExecutionStatus(TaskStatusInfo.FINISHED);
m_status.setStatusMessage("Row "+m_rowNumber+" completed successfully.");
} | 7 |
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name, email, userName, password, bMonth, bDate, bYear, gender, mobile, securityKey;
name = request.getParameter("name");
email = request.getParameter("email");
userName = request.getParameter("userName");
password = request.getParameter("password");
bMonth = request.getParameter("bMonth");
bDate = request.getParameter("bDate");
bYear = request.getParameter("bYear");
gender = request.getParameter("gender");
mobile = request.getParameter("mobile");
securityKey = request.getParameter("securityKey");
String birthDate = bDate + "-" + bMonth + "-" + bYear;
signupDAO signupObject = new signupDAO(name, email, userName, password, birthDate, gender, mobile, securityKey);
try {
signupObject.execute();
System.out.println("Registration Completed Successfully: signup.java Servlet");
response.sendRedirect("/websocchatroom/signIn");
} catch (Exception ex) {
System.out.println(ex + "\n Error in Signup Servlet");
response.sendRedirect("/websocchatroom/error?errorCode=SIGNUPERR");
}
} | 1 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StartPage().setVisible(true);
}
});
} | 6 |
@Test
public void testInfixToPostfix5() throws DAIllegalArgumentException,
DAIndexOutOfBoundsException, ShouldNotBeHereException,
BadNextValueException, UnmatchingParenthesisException {
try {
infix.addLast("/");
infix.addLast("5");
QueueInterface<String> postFix = calc.infixToPostfix(infix);
String result = "245/+";
assertEquals(result, calc.stringTrans(postFix));
} catch (DAIllegalArgumentException e) {
throw new DAIllegalArgumentException();
} catch (DAIndexOutOfBoundsException e) {
throw new DAIndexOutOfBoundsException();
} catch (ShouldNotBeHereException e) {
throw new ShouldNotBeHereException();
} catch (BadNextValueException e) {
throw new BadNextValueException();
} catch (UnmatchingParenthesisException e) {
throw new UnmatchingParenthesisException();
}
} | 5 |
void load() {
observer = ObserverType.getNewInstance(this, model.settings.getObserverType());
Vertex.randomInit.autoInitial();
savedRandomInitiation = Vertex.randomInit.getInitial() != 0;
if (savedRandomInitiation) {
if (model.settings.getInit() == InitType.one) {
int i = GUI.random.nextInt(graph.vertices.size());
graph.vertices.get(i).setInitial(1);
}
if (model.settings.getInit() == InitType.multi) {
for (Vertex v : graph.vertices) {
if (GUI.random.nextBoolean())
v.setInitial(1);
}
}
}
for (Vertex v : graph.vertices) {
v.program = new Program(v, this);
v.program.load(Model.binaryPath, 1);
}
} | 6 |
public static int treeSize(IntBTNode root)
{
if (root == null)
return 0;
else
return 1 + treeSize(root.left) + treeSize(root.right);
} | 1 |
public E peek(){
return (E)element[top];
} | 0 |
public void easterEgg16(){
RoketUtils.submitAchievement(RoketGamerData.ACHIEVEMENT_DAVE);
NewWindowManager wm = nm.getWorld().getGame().getWindows();
new TutorialWindow(wm,"You have","summoned the","fire nation","to do battle!","Prepare to die!");
ai.reset();
int startRow = PavoHelper.getGameHeight(nm.getWorld().getWorldSize())+1;
int startCol = PavoHelper.getGameWidth(nm.getWorld().getWorldSize()) * 2-1;
for(int row = 3; row>0; row--){
for(int col = 10; col>0; col--){
Entity e = nm.findEntity(startRow-row,startCol-col);
if(e!=null){
nm.getGame().getTurnManager().removeEntity(e);
e.dispose();
}
nm.setTileOverlay(startRow-row, startCol-col, (byte)124145);
}
}
startRow = (PavoHelper.getGameHeight(nm.getWorld().getWorldSize())+1)/2;
for(int row = 3; row>0; row--){
for(int col = 10; col>0; col--){
Entity e = nm.findEntity(startRow-row,startCol-col);
if(e!=null){
nm.getGame().getTurnManager().removeEntity(e);
e.dispose();
}
nm.setTileOverlay(startRow-row, startCol-col, (byte)124145);
}
}
startRow = (PavoHelper.getGameHeight(nm.getWorld().getWorldSize())+1)/2*3;
for(int row = 3; row>0; row--){
for(int col = 10; col>0; col--){
Entity e = nm.findEntity(startRow-row,startCol-col);
if(e!=null){
nm.getGame().getTurnManager().removeEntity(e);
e.dispose();
}
nm.setTileOverlay(startRow-row, startCol-col, (byte)124145);
}
}
} | 9 |
public void render(){
if(x == DownGame.GAME_WIDTH/2){
StickManImage_Left.draw(x,y,WIDTH,HEIGHT);
}
else if(x > DownGame.GAME_WIDTH/2 && x <= 3*DownGame.GAME_WIDTH/4){
StickManImage_JumpfromLeft.draw(x,y,WIDTH,HEIGHT);
}
else if(x > 3*DownGame.GAME_WIDTH/4 && x < DownGame.GAME_WIDTH){
StickManImage_JumpfromRight.draw(x-WIDTH,y,WIDTH,HEIGHT);
}
else if(x == DownGame.GAME_WIDTH){
StickManImage_Right.draw(x-WIDTH,y,WIDTH,HEIGHT);
}
} | 6 |
public void menu() {
Integer option;
String s;
boolean exit = false;
while (!exit) {
UI.printHeader();
System.out.println("Selecciona una acción a continuación:");
System.out.println("1) Ver servicios activos");
System.out.println("2) Añadir un servicio");
System.out.println("3) Probar un servicio existente");
System.out.println("4) Eliminar un servicio existente");
System.out.println("");
System.out.println("0) Atrás");
System.out.println("");
System.out.print("Introduce una opción: ");
BufferedReader bufferRead = new BufferedReader(
new InputStreamReader(System.in));
try {
s = bufferRead.readLine();
option = Integer.parseInt(s);
switch (option) {
case 0:
exit = true;
break;
case 1:
list();
break;
case 2:
add();
break;
case 3:
test();
break;
case 4:
remove();
break;
default:
UI.setError("Opción no válida");
break;
}
} catch (NumberFormatException e) {
UI.setError("Opción no válida");
} catch (IOException e) {
e.printStackTrace();
}
}
UI.clearError();
} | 8 |
public Writer write(Writer writer) throws JSONException {
try {
boolean commanate = false;
Iterator keys = keys();
writer.write('{');
while (keys.hasNext()) {
if (commanate) {
writer.write(',');
}
Object key = keys.next();
writer.write(quote(key.toString()));
writer.write(':');
Object value = this.map.get(key);
if (value instanceof JSONObject) {
((JSONObject) value).write(writer);
} else if (value instanceof JSONArray) {
((JSONArray) value).write(writer);
} else {
writer.write(valueToString(value));
}
commanate = true;
}
writer.write('}');
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
}
} | 5 |
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String suffixe = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
suffixe = s.substring(i + 1).toLowerCase();
}
return suffixe != null && isGood(suffixe);
} | 4 |
private void backClicked()
{
WindowStack ws = WindowStack.getLastInstance();
if (ws != null) {
ws.pop();
}
} | 1 |
public boolean addEdge(int srcval,int destval){
Node src=new Node(srcval);
Node dest=new Node(destval);
if(!nodes.contains(src) || !nodes.contains(dest)){
return false;
}else{
Edge temp=new Edge(dest);
ArrayList<Edge> tmp=adjacenyList.get(src);
if(tmp==null){
tmp=new ArrayList<Edge>();
adjacenyList.put(src,tmp);
}
tmp.add(temp);
temp=new Edge(src);
ArrayList<Edge> tmp1=adjacenyList.get(dest);
if(tmp1==null){
tmp1=new ArrayList<Edge>();
adjacenyList.put(dest,tmp1);
}
tmp1.add(temp);
return true;
}
} | 4 |
public int numTrees(int n) {
if (n < result.size())
return result.get(n);
int temp = 0;
for (int i = 0; i < n; i++) {
temp += numTrees(i) * numTrees(n - 1 - i);
}
result.add(temp);
return temp;
} | 2 |
public boolean accept(File file)
{
if (file.isDirectory())
{
return true;
}
else if (extension(file).equalsIgnoreCase(ImageFormat))
{
return true;
}
else
{
return false;
}
} | 2 |
public String getComplementString(String stringToComplement) {
String complement = "";
for (int i = 0; i < stringToComplement.length(); i++) {
Character complementChar = stringToComplement.charAt(i);
if (complementChar.equals('A')) {
complement = complement + "T";
} else if (complementChar.equals('T')) {
complement = complement + "A";
} else if (complementChar.equals('C')) {
complement = complement + "G";
} else if (complementChar.equals('G')) {
complement = complement + "C";
}
}
return complement;
} | 5 |
@Override
public void actionPerformed(ActionEvent e) {
collapseToParent((OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched());
} | 0 |
public void printDirections() {
if(canGoNorth()) {
System.out.println("You can go north.");
}
if(canGoEast()) {
System.out.println("You can go east.");
}
if(canGoSouth()) {
System.out.println("You can go south.");
}
if(canGoWest()) {
System.out.println("You can go west.");
}
} | 4 |
public Piece askMove(Player J,Piece[] Board,int[] mW,ChessGame G){
String L = null;
boolean moveisok = false;
boolean pieceisok = false;
while (!moveisok)
{
//Partie 1 : Origin
do
{
System.out.println("Write a position fo a piece to move.");
while(((L=sc.nextLine()).length())!=2)
{
System.out.println("Error.\nTry again.");
}
L=L.toLowerCase();
int x = (int)L.charAt(0) - (int) 'a';
int y = (int)L.charAt(1) - (int) '1';
if (!isValid(x,y)) {
pieceisok = false;
} else {
mW[0] = Piece.BOARD_SIZE*y+x;
mW[1] = 0;
pieceisok=Utils.comparePieceC(Board,mW[0],J.isWhite());
}
if (!pieceisok) System.out.println("Invalid piece.");
}
while(!pieceisok);
//Partie 2 : Destination
System.out.println("Where to move it ?");
if ((L=sc.nextLine()).length()==2)
{
setDest(L.toLowerCase());
mW[1] = Utils.getPos(destx, desty);
moveisok = Utils.getPiece(Board,mW[0]).checkMove(destx,desty,J,Board);
if (!moveisok) System.out.println("Coup non valide.");
}
else System.out.println("Erreur.");
}
return Utils.getPiece(Board,mW[0]);
} | 7 |
public static void main(String[] args) throws Throwable{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0, N = parseInt(in.readLine().trim()); i < N; i++) {
int C = parseInt(in.readLine().trim()), sum = 0;
ArrayList<Integer> monedas = new ArrayList<Integer>();
for (int j = 0, M = parseInt(in.readLine().trim()); j < M; j++) {
monedas.add(parseInt(in.readLine()));
sum += monedas.get(monedas.size() - 1);
}
int[] arr = new int[sum + 1];
Arrays.fill(arr, MAX_VALUE);
int max = 1;
arr[0]=1;
for (int j = 0; j < monedas.size(); j++)
for (int j2 = max - 1; j2 >= 0; j2--)
if(arr[j2]<MAX_VALUE){
arr[monedas.get(j) + j2] = Math.min(arr[j2] + 1, arr[monedas.get(j) + j2]);
if(max <= C)
max = Math.max(max, monedas.get(j) + j2 + 1);
}
for (int j = C; j < arr.length; j++)
if(arr[j] < MAX_VALUE){
System.out.println(j + " " + (arr[j] - 1));;
break;
}
}
} | 8 |
public void searchTicket(String date) {
HttpResponse response = null;
String info = null;
OrderParameter orderParameter = null;
try {
URIBuilder builder = new URIBuilder();
builder.setScheme("https")
.setHost("dynamic.12306.cn")
.setPath("/otsweb/order/querySingleAction.do")
.setParameter("method", "queryLeftTicket")
.setParameter("orderRequest.train_date", date)
.setParameter("orderRequest.from_station_telecode",
configInfo.getFromStation())
.setParameter("orderRequest.to_station_telecode",
configInfo.getToStation());
if (StringUtils.isNotEmpty(configInfo.getTrainNo())) {
builder.setParameter("orderRequest.train_no",
configInfo.getTrainNo());
} else {
builder.setParameter("orderRequest.train_no", "");
}
builder.setParameter("trainPassType", "QB")
.setParameter("trainClass", configInfo.getTrainClass())
.setParameter("includeStudent", "00")
.setParameter("seatTypeAndNum", "")
.setParameter("orderRequest.start_time_str",configInfo.getOrderTime());
URI uri = builder.build();
HttpGet httpGet = HttpClientUtil.getHttpGet(uri,
UrlEnum.SEARCH_TICKET);
response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
info = EntityUtils.toString(response.getEntity());
while(StringUtils.isBlank(info) || (orderParameter=checkTickeAndOrder(info, date)) == null){
HttpClientUtils.closeQuietly(response);
logger.info("没有余票,休息"+configInfo.getSearchSleepTime()+"秒,继续刷票");
Thread.sleep(configInfo.getSearchSleepTime()*1000);
response = httpClient.execute(httpGet);
code = response.getStatusLine().getStatusCode();
info = EntityUtils.toString(response.getEntity());
if(StringUtils.contains(info, "系统维护中")){
return;
}
if("-10".equals(info)|| StringUtils.isBlank(info)){
logger.info("刷新太过频繁,休息"+configInfo.getSearchWatiTime()+"秒");
Thread.sleep(configInfo.getSearchWatiTime()*1000);
}
}
logger.info("有票了,开始订票~~~~~~~~~");
String[] params = JsoupUtil.getTicketInfo(orderParameter.getDocument());
logger.info("ticketType:" + orderParameter.getTicketType());
orderTicket(date, params, orderParameter.getTicketType());
} catch (Exception e) {
logger.error("searchTicket error!", e);
} finally {
logger.info("close searchTicket");
HttpClientUtils.closeQuietly(response);
}
if (StringUtils.isNotEmpty(info)) {
checkTickeAndOrder(info, date);
} else {
try {
Thread.sleep(10000);
} catch (Exception e) {
logger.error("searchTicket Thread error!", e);
}
searchTicket(date);
}
} | 9 |
private boolean isFileNeedToSync(String path, String md5) {
File f = new File(ConfigManager.getInstance().pathToJar + path);
try {
if (!f.exists() || !md5.equals(Md5Checksum.getMD5Checksum(f.getPath()))) {
return true;
}
} catch (Exception ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
return true;
}
return false;
} | 3 |
public void writeFromArrayList(String path, ArrayList<String> lines, String format, String style, boolean override) {
try {
FileOutputStream fos;
BufferedWriter bw;
if (override) {
fos = new FileOutputStream(path);
if (Check.NULLCheck(format))
bw = new BufferedWriter(new OutputStreamWriter(fos, format));
else
bw = new BufferedWriter(new OutputStreamWriter(fos));
} else {
File fn = new File(path);
if (!fn.exists()) {
fn.createNewFile();
fos = new FileOutputStream(fn);
if (Check.NULLCheck(format))
bw = new BufferedWriter(new OutputStreamWriter(fos, format));
else
bw = new BufferedWriter(new OutputStreamWriter(fos));
} else{
Log.Print(path.substring(path.lastIndexOf(File.separator) + 1) + " 文件已存在");
return;
}
}
for (int i = 0; i < lines.size(); ++i) {
if (style.equalsIgnoreCase("unix"))
bw.write(lines.get(i) + "\n");
else
bw.write(lines.get(i) + "\r\n");
}
bw.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 9 |
public static IntNode listPosition(IntNode head, int position)
{
IntNode cursor;
int i;
if (position <= 0)
throw new IllegalArgumentException("position is not positive");
cursor = head;
for (i = 1; (i < position) && (cursor != null); i++)
cursor = cursor.link;
return cursor;
} | 3 |
public void mouseWheelMoved(MouseWheelEvent e)
{
if(e.getWheelRotation() < 0) //scrolled up
{
}
else if(e.getWheelRotation() > 0) //scrolled down
{
}
} | 2 |
public Dijkstra(Graph graph) {
this.graph = graph;
this.adjacency = graph.getAdjacencyList();
this.vertices = graph.getVertices();
this.edges = graph.getEdges();
this.heap = new BinaryHeap();
} | 0 |
public String toString() {
String affiche = "message deplacement 2";
return affiche;
} | 0 |
protected List<T> executeQuery(String sql) throws SQLException{
List<T> returnList = new ArrayList<T>();
Connection connection= null;
Statement statement= null;
ResultSet rs= null;
try{
connection = getConnection();
statement = connection.createStatement();
rs = statement.executeQuery(sql);
while(rs.next()){
T entity = this.retrieveEntity(rs);
returnList.add(entity);
}
}finally{
if(rs != null) rs.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
}
return returnList;
} | 4 |
private String threeDigitString(int timeValue)
{
String result = Integer.toString(timeValue);
if (result.length() == 1)
{
result = "00" + result;
}
else if (result.length() == 2)
{
result = "0" + result;
}
return result;
} | 2 |
private String getDescription() {
String desc = "@MongoInsert(" + this.getParsedShell().getOriginalExpression() + ")";
if (!StringUtils.isEmpty(globalCollectionName)) {
desc = ",@MongoCollection(" + globalCollectionName + ")";
}
return desc;
} | 1 |
public void cal_price_items()
{
int paid_count = Paid_MaSP.size();
double temp_price;
giaS_mode = select_price.isSelected();
if(giaS_mode)
{
select_price.setText("Bán giá Sỹ");
select_price.setToolTipText("GIÁ SỸ");
}
else
{
select_price.setText("Bán giá Lẻ");
select_price.setToolTipText("GIÁ LẺ");
}
if(paid_count > 0 )
{
for(int i =0; i< paid_count; i++)
{
if((boolean)bang_HoaDon.getValueAt(i, 7))
{
if(giaS_mode) //gia sy
{
temp_price = Paid_GiaSSP.get(i)*(Paid_SoLuongSP.get(i));
}
else
{
temp_price = Paid_GiaLSP.get(i)*(Paid_SoLuongSP.get(i));
}
Paid_TongGiaSP.set(i,temp_price);
}
bang_HoaDon.setValueAt(Paid_TongGiaSP.get(i), i, 6);
}
update_total_Paid_row();
}
} | 5 |
public void addGetMethod(Field field, Method method) {
if(field == null) {
throw new IllegalArgumentException("Field cannot be null");
}
FieldStoreItem item = store.get(FieldStoreItem.createKey(field));
if(item != null) {
item.setGetMethod(method);
} else {
item = new FieldStoreItem(field);
item.setGetMethod(method);
store.put(item.getKey(),item);
}
} | 2 |
public void analyze() {
if (GlobalOptions.verboseLevel > 0)
GlobalOptions.err.println("Reachable: " + this);
ClassInfo[] ifaces = info.getInterfaces();
for (int i = 0; i < ifaces.length; i++)
analyzeSuperClasses(ifaces[i]);
analyzeSuperClasses(info.getSuperclass());
} | 2 |
public ArrayList<PalavraChave> listar(long pesquisaId) throws Exception
{
String sql = "SELECT * FROM Pesquisapalavras_chave WHERE id1 = ?";
ArrayList<PalavraChave> listaPalavraChave = new ArrayList<PalavraChave>();
if (pesquisaId > 0)
{
try
{
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql);
stmt.setLong(1, pesquisaId);
ResultSet rs = stmt.executeQuery();
PalavraChaveDAO pcdao = new PalavraChaveDAO();
while (rs.next())
{
PalavraChave palavraChave = pcdao.listar("WHERE id = " + rs.getLong("id2")).get(0);
listaPalavraChave.add(palavraChave);
}
rs.close();
}
catch (SQLException e)
{
throw e;
}
}
return listaPalavraChave;
} | 3 |
protected void sendRequests() throws Exception{
Session _session=getSession();
Request request;
if(agent_forwarding){
request=new RequestAgentForwarding();
request.request(_session, this);
}
if(xforwading){
request=new RequestX11();
request.request(_session, this);
}
if(pty){
request=new RequestPtyReq();
((RequestPtyReq)request).setTType(ttype);
((RequestPtyReq)request).setTSize(tcol, trow, twp, thp);
if(terminal_mode!=null){
((RequestPtyReq)request).setTerminalMode(terminal_mode);
}
request.request(_session, this);
}
if(env!=null){
for(Enumeration _env=env.keys(); _env.hasMoreElements();){
Object name=_env.nextElement();
Object value=env.get(name);
request=new RequestEnv();
((RequestEnv)request).setEnv(toByteArray(name),
toByteArray(value));
request.request(_session, this);
}
}
} | 6 |
public Player getPlayer() {
if(player == null) {
player = Plugin.plug.getServer().getPlayer(pName);
}
return player;
} | 1 |
public void useGravity(BlackHole bh) {
calculateGravity(bh);
if (x + FONT_SIZE/2 < bh.getX() + bh.getWidth() / 2) {
vx += gravity;
}
if (x + FONT_SIZE/2 > bh.getX() + bh.getWidth() / 2) {
vx -= gravity;
}
if (y + FONT_SIZE/2 < bh.getY() + bh.getHeight() / 2) {
vy += gravity;
}
if (y + FONT_SIZE/2 > bh.getY() + bh.getHeight() / 2) {
vy -= gravity;
}
} | 4 |
public int getPixel(int nx, int ny) {
if (hflip) nx = 7 - nx;
if (vflip) ny = 7 - ny;
int val = 0;
int rowAddr = addr + (2 * ny);
int xMask = 0x80 >> nx;
val |= ((PPU.vram[rowAddr] & xMask) != 0) ? 0x01 : 0;
val |= ((PPU.vram[rowAddr + 1] & xMask) != 0) ? 0x02 : 0;
val |= ((PPU.vram[rowAddr + 16] & xMask) != 0) ? 0x04 : 0;
val |= ((PPU.vram[rowAddr + 17] & xMask) != 0) ? 0x08 : 0;
return val;
} | 6 |
public static Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t))
return m;
}
return null;
} | 7 |
public static ArrayList getPesquisa2(String prod, String data_in, Integer gmp) throws SQLException, ClassNotFoundException {
ArrayList<bConsulta> sts = new ArrayList<bConsulta>();
Connection conPol = conMgr.getConnection("PD");
ResultSet rs;
if (conPol == null) {
throw new SQLException("Numero Maximo de Conexoes Atingida!");
}
//String[] dataspl = data_in.split("/");
//data_in = dataspl[1] + "/" + dataspl[2];
try {
call = conPol.prepareCall("{call sp_consulta2_Totais(?,?,?)}");
call.setString(1, prod);
call.setString(2, data_in);
call.setInt(3, gmp);
rs = call.executeQuery();
while (rs.next()) {
bConsulta reg = new bConsulta();
//reg.setCod_prod(rs.getString("f1"));
reg.setDia(rs.getString("f2"));
reg.setNok(rs.getInt("f3"));
reg.setOk(rs.getInt("f4"));
// reg.setProduzidos(rs.getInt("produzidos"));
reg.setYield(rs.getFloat("f5"));
sts.add(reg);
}
} finally {
if (conPol != null) {
conMgr.freeConnection("PD", conPol);
}
}
return sts;
} | 3 |
public static boolean isColumnValid(Board board, int column) {
boolean valid = true;
if ((column > board.getWidth()) ||
(column < Board.MINWIDTH)) {
valid = false;
}
return valid;
} | 2 |
public void setModel(MDModel mod) {
if (mod == null) {
model = null;
return;
}
if (!(mod instanceof MolecularModel))
throw new IllegalArgumentException("Can't accept non-molecular model");
model = (MolecularModel) mod;
super.setModel(mod);
model.addBondChangeListener(this);
atom = model.getAtoms();
obstacles = model.getObstacles();
bonds = model.getBonds();
bends = model.getBends();
molecules = model.getMolecules();
initEditFieldActions();
if (elementEditor == null)
elementEditor = new ElementEditor(model);
editElementAction = new ModelAction(model, new Executable() {
public void execute() {
elementEditor.setModel(model);
elementEditor.createDialog(AtomisticView.this, true).setVisible(true);
resetAddObjectIndicator();
}
}) {
public String toString() {
return (String) getValue(Action.SHORT_DESCRIPTION);
}
};
editElementAction.putValue(Action.NAME, "Change");
editElementAction.putValue(Action.SHORT_DESCRIPTION, "Change the van der Waals parameters");
model.getActions().put(editElementAction.toString(), editElementAction);
EngineAction ea = new EngineAction(model);
getActionMap().put(ea.toString(), ea);
Action a = new ModelAction(model, new Executable() {
public void execute() {
final LightSource light = model.getLightSource();
if (light == null)
return;
if (lightSourceEditor == null)
lightSourceEditor = new LightSourceEditor();
lightSourceEditor.createDialog(JOptionPane.getFrameForComponent(AtomisticView.this), model).setVisible(true);
}
}) {
public String toString() {
return (String) getValue(Action.SHORT_DESCRIPTION);
}
};
a.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_L);
a.putValue(Action.NAME, "Light Source");
a.putValue(Action.SHORT_DESCRIPTION, "Edit the light source");
model.getActions().put(a.toString(), a);
a = new ModelAction(model, new Executable() {
public void execute() {
if (quantumDynamicsRuleEditor == null)
quantumDynamicsRuleEditor = new QuantumDynamicsRuleEditor();
quantumDynamicsRuleEditor.createDialog(JOptionPane.getFrameForComponent(AtomisticView.this), model).setVisible(true);
}
}) {
public String toString() {
return (String) getValue(Action.SHORT_DESCRIPTION);
}
};
a.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_D);
a.putValue(Action.NAME, "Quantum Dynamics Rules");
a.putValue(Action.SHORT_DESCRIPTION, "Edit quantum dynamics rules");
model.getActions().put(a.toString(), a);
if (!layerBasket.isEmpty()) {
synchronized (layerBasket) {
for (Iterator i = layerBasket.iterator(); i.hasNext();) {
((ModelComponent) i.next()).setModel(model);
}
}
}
defaultPopupMenu = new DefaultPopupMenu(this);
} | 8 |
@Override
public PermissionType getType() {
return PermissionType.CONSOLE;
} | 0 |
private int nextRowDiagonalColumn(Piece[][] pieces, int from_x, int from_y, int to_x, int to_y) {
if(color.equals("black")) {
if(to_x - from_x == 1 && Math.abs(to_y - from_y) == 1 && isOccupiedByAnOpponent(pieces[to_x][to_y])) {
if(to_x == 7) {
return PROMOTION;
}
pieces[to_x][to_y] = pieces[from_x][from_y];
pieces[from_x][from_y] = null;
last_move_info = (char)(((int)'a') + from_y) + "x" + (char)(((int)'a') + to_y) + "" + (8 - to_x) + " ";
return MOVED;
}
}
else {
if(to_x - from_x == -1 && Math.abs(to_y - from_y) == 1 && isOccupiedByAnOpponent(pieces[to_x][to_y])) {
if(to_x == 0) {
return PROMOTION;
}
pieces[to_x][to_y] = pieces[from_x][from_y];
pieces[from_x][from_y] = null;
last_move_info = (char)(((int)'a') + from_y) + "x" + (char)(((int)'a') + to_y) + "" + (8 - to_x) + " ";
return MOVED;
}
}
return NOT_MOVED;
} | 9 |
ControlPanel() {
setBounds(0, 0, 150, 250);
setLayout(null);
CreateButtons = new CreatePokemonButton[CreateButtonSize];
for (int i = 0; i < CreateButtonSize; ++i) {
CreateButtons[i] = new CreatePokemonButton("res/Creation/"
+ ((Integer) (11 + i)).toString() + ".png", "res/Creation/"
+ ((Integer) (11 + i)).toString() + ".png");
CreateButtons[i].setBounds(13, 8 + MainFrame.ButtonSize * i,
MainFrame.ButtonSize, MainFrame.ButtonSize);
CreateButtons[i].addActionListener(new CreationListener(i));
add(CreateButtons[i]);
}
addMeoMeo = new TowerDefense_Button("res/meomeo.png", "res/meomeo.png");
upgradeMeoMeo = new TowerDefense_Button("res/upgrade.png",
"res/upgrade.png");
addMeoMeo.setBounds(57, 5, MainFrame.ButtonSize, MainFrame.ButtonSize);
upgradeMeoMeo.setBounds(57, 50, MainFrame.ButtonSize, MainFrame.ButtonSize);
addMeoMeo.addActionListener(new addMeoMeoListener());
upgradeMeoMeo.addActionListener(new upgradeMeoMeoListener());
add(addMeoMeo);
add(upgradeMeoMeo);
TowerDefense_Button SwitchButton = new TowerDefense_Button(
"res/switch.png", "res/switch.png");
SwitchButton.setBounds(60, 207, MainFrame.ButtonSize, MainFrame.ButtonSize);
SwitchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cb.setChangeViewRequest(true);
}
});
add(SwitchButton);
SendButtons = new TowerDefense_Button[SendButtonSize];
for (int i = 0; i < CreateButtonSize; ++i) {
SendButtons[i] = new TowerDefense_Button("res/Send/"
+ ((Integer) (51 + i)).toString() + ".png", "res/Send/"
+ ((Integer) (51 + i)).toString() + ".png");
SendButtons[i].setBounds(105, 8 + MainFrame.ButtonSize * i,
MainFrame.ButtonSize, MainFrame.ButtonSize);
SendButtons[i].addActionListener(new SendListener(i));
add(SendButtons[i]);
}
} | 2 |
public static void main(String[] args) {
PlayerData.load();
Level level = new Level();
byte[][] byteArr = new byte[][] {
new byte[] { 2, 9, 9, 9, 9, 9, 9, 9, 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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4 },
new byte[] { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }};
byte[][] byteArrNew = new byte[byteArr[0].length][byteArr.length];
for (int i = 0; i < byteArr.length; i++) {
for (int j = 0; j < byteArr[0].length; j++) {
byteArrNew[j][i] = byteArr[i][j];
}
}
level.setTileSet(byteArrNew);
level.setStartPositionX(32.0);
level.setStartPositionY(32.0);
level.save("res/data/levels/Level6");
} | 2 |
private void setDefaultDestination(int destination) {
defaultDestination = destination;
if (otherPunctuationDestination == Integer.MAX_VALUE) otherPunctuationDestination = destination;
if (spaceDestination == Integer.MAX_VALUE) spaceDestination = destination;
if (numDestination == Integer.MAX_VALUE) numDestination = destination;
} | 3 |
private static String convertNewLines(String text, String newLine) {
if (text == null) return ""; // NOI18N
if (newLine == null) return text;
StringBuilder newText = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') newText.append(newLine);
else if (c == '\r') {
if ((i + 1) < text.length() && text.charAt(i + 1) == '\n') {
i++;
newText.append(newLine);
}
} else newText.append(c);
}
return newText.toString();
} | 7 |
public synchronized void endThreadAccess() {
Object requestingUser = Thread.currentThread();
if (m_oCurrentUser == null) {
this.notifyAll();
} else if (m_oCurrentUser == requestingUser) {
m_oCurrentUser = null;
this.notifyAll();
} else { // Some other Thread is currently using us
if (logger.isLoggable(Level.SEVERE)) {
logger.severe(
"ERROR: Thread finished using SeekableInput, but it wasn't locked by that Thread\n" +
" Thread: " + Thread.currentThread() + "\n" +
" Locking Thread: " + m_oCurrentUser + "\n" +
" SeekableInput: " + this);
}
}
} | 3 |
public Resolution newOrder() {
HttpSession session = context.getRequest().getSession();
if (shippingAddressRequired) {
shippingAddressRequired = false;
return new ForwardResolution(SHIPPING);
} else if (!isConfirmed()) {
return new ForwardResolution(CONFIRM_ORDER);
} else if (getOrder() != null) {
orderService.insertOrder(order);
CartActionBean cartBean = (CartActionBean) session.getAttribute("/actions/Cart.action");
cartBean.clear();
setMessage("Thank you, your order has been submitted.");
return new ForwardResolution(VIEW_ORDER);
} else {
setMessage("An error occurred processing your order (order was null).");
return new ForwardResolution(ERROR);
}
} | 3 |
public static Digraph rootedInDAG(int V, int E) {
if (E > (long) V*(V-1) / 2) throw new IllegalArgumentException("Too many edges");
if (E < V-1) throw new IllegalArgumentException("Too few edges");
Digraph G = new Digraph(V);
SET<Edge> set = new SET<Edge>();
// fix a topological order
int[] vertices = new int[V];
for (int i = 0; i < V; i++) vertices[i] = i;
StdRandom.shuffle(vertices);
// one edge pointing from each vertex, other than the root = vertices[V-1]
for (int v = 0; v < V-1; v++) {
int w = StdRandom.uniform(v+1, V);
Edge e = new Edge(v, w);
set.add(e);
G.addEdge(vertices[v], vertices[w]);
}
while (G.E() < E) {
int v = StdRandom.uniform(V);
int w = StdRandom.uniform(V);
Edge e = new Edge(v, w);
if ((v < w) && !set.contains(e)) {
set.add(e);
G.addEdge(vertices[v], vertices[w]);
}
}
return G;
} | 7 |
public String toSource(String className, Instances data) throws Exception {
StringBuffer result;
boolean[] numeric;
boolean[] nominal;
String[] modes;
double[] means;
int i;
result = new StringBuffer();
// determine what attributes were processed
numeric = new boolean[data.numAttributes()];
nominal = new boolean[data.numAttributes()];
modes = new String[data.numAttributes()];
means = new double[data.numAttributes()];
for (i = 0; i < data.numAttributes(); i++) {
numeric[i] = (data.attribute(i).isNumeric() && (i != data.classIndex()));
nominal[i] = (data.attribute(i).isNominal() && (i != data.classIndex()));
if (numeric[i])
means[i] = m_ModesAndMeans[i];
else
means[i] = Double.NaN;
if (nominal[i])
modes[i] = data.attribute(i).value((int) m_ModesAndMeans[i]);
else
modes[i] = null;
}
result.append("class " + className + " {\n");
result.append("\n");
result.append(" /** lists which numeric attributes will be processed */\n");
result.append(" protected final static boolean[] NUMERIC = new boolean[]{" + Utils.arrayToString(numeric) + "};\n");
result.append("\n");
result.append(" /** lists which nominal attributes will be processed */\n");
result.append(" protected final static boolean[] NOMINAL = new boolean[]{" + Utils.arrayToString(nominal) + "};\n");
result.append("\n");
result.append(" /** the means */\n");
result.append(" protected final static double[] MEANS = new double[]{" + Utils.arrayToString(means).replaceAll("NaN", "Double.NaN") + "};\n");
result.append("\n");
result.append(" /** the modes */\n");
result.append(" protected final static String[] MODES = new String[]{");
for (i = 0; i < modes.length; i++) {
if (i > 0)
result.append(",");
if (nominal[i])
result.append("\"" + Utils.quote(modes[i]) + "\"");
else
result.append(modes[i]);
}
result.append("};\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters a single row\n");
result.append(" * \n");
result.append(" * @param i the row to process\n");
result.append(" * @return the processed row\n");
result.append(" */\n");
result.append(" public static Object[] filter(Object[] i) {\n");
result.append(" Object[] result;\n");
result.append("\n");
result.append(" result = new Object[i.length];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" if (i[n] == null) {\n");
result.append(" if (NUMERIC[n])\n");
result.append(" result[n] = MEANS[n];\n");
result.append(" else if (NOMINAL[n])\n");
result.append(" result[n] = MODES[n];\n");
result.append(" else\n");
result.append(" result[n] = i[n];\n");
result.append(" }\n");
result.append(" else {\n");
result.append(" result[n] = i[n];\n");
result.append(" }\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters multiple rows\n");
result.append(" * \n");
result.append(" * @param i the rows to process\n");
result.append(" * @return the processed rows\n");
result.append(" */\n");
result.append(" public static Object[][] filter(Object[][] i) {\n");
result.append(" Object[][] result;\n");
result.append("\n");
result.append(" result = new Object[i.length][];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" result[n] = filter(i[n]);\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("}\n");
return result.toString();
} | 8 |
private int jjMoveStringLiteralDfa25_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjMoveNfa_0(0, 24);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return jjMoveNfa_0(0, 24);
}
switch(curChar)
{
case 48:
return jjMoveStringLiteralDfa26_0(active0, 0x800000000000000L);
case 51:
return jjMoveStringLiteralDfa26_0(active0, 0x7ffe00000000000L);
default :
break;
}
return jjMoveNfa_0(0, 25);
} | 4 |
public void buildIndices() {
if ((allIndices == null) || allIndices.isEmpty()) {
return;
}
for (String indexName : allIndices.keySet()) {
indexMap = allIndices.get(indexName);
indexGlobal.setSubscriptCount(0);
indexGlobal.appendSubscript(indexName);
for (Object value : indexMap.keySet()) {
Object key = indexMap.get(value);
if (key instanceof ArrayList) {
scratchList.clear();
for (Object data : (ArrayList)key) {
scratchList.append(data);
}
indexGlobal.set(scratchList,value);
} else {
indexGlobal.set((String)key,value);
}
}
}
} | 6 |
public Component getTableCellRendererComponent(
JTable table, Object color,
boolean isSelected, boolean hasFocus,
int row, int column) {
Color newColor = (Color)color;
setBackground(newColor);
if (isBordered) {
if (isSelected) {
if (selectedBorder == null) {
selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
table.getSelectionBackground());
}
setBorder(selectedBorder);
} else {
if (unselectedBorder == null) {
unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
table.getBackground());
}
setBorder(unselectedBorder);
}
}
setToolTipText("RGB value: " + newColor.getRed() + ", "
+ newColor.getGreen() + ", "
+ newColor.getBlue());
return this;
} | 4 |
@Override
public boolean removeSpecialTile(Tile tile) {
if(tile == null) return true;
Iterator<Tile> it = specials.iterator();
while(it.hasNext()){
Tile next = it.next();
if(next.getName().equals(tile.getName())){
it.remove();
return true;
}
}
return false;
} | 3 |
public void Save() throws IOException {
if (!new File("levels").exists())
new File("levels").mkdir();
FileOutputStream fos = new FileOutputStream("levels/" + name + ".ggs");
GZIPOutputStream gos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gos);
out.writeLong(serialVersionUID);
out.writeObject(this);
out.close();
gos.close();
fos.close();
} | 1 |
private static void copy(File f1, File f2) {
try {
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 2 |
public int bufferRight(int ori) {
int buff = 0;
int width = getTiles()[0].length == 9 ? 3 : 4; // get width (3 or 4) of piece
width = getTiles()[0].length == 4 ? 2 : width;
for(int j = width-1; j >= 0; --j){
boolean tmp = true;
for(int i = 0; i < width; ++i){
if(tiles[ori][i*width+j]) {
tmp = false;
}
}
if(tmp){
++buff;
} else break;
}
return buff;
} | 6 |
protected void changeSelection() {
ListSelectionModel model = table.getSelectionModel();
int min = model.getMinSelectionIndex(), max = model
.getMaxSelectionIndex();
drawer.clearSelected();
if (min == -1) {
convertPane.getAutomatonPane().repaint();
return;
}
for (; min <= max; min++) {
if (!model.isSelectedIndex(min))
continue;
Production p = table.getGrammarModel().getProduction(min);
Object o = productionToObject.get(p);
if (o == null)
continue;
if (o instanceof State)
drawer.addSelected((State) o);
else
drawer.addSelected((Transition) o);
}
convertPane.getAutomatonPane().repaint();
} | 5 |
private void updateGroups() {
if (user != null) {
groups = new HashMap<>();
groupIdNameMap = new HashMap<>();
//get their groups
ArrayList<Integer> temp = user.getGroups();
if (temp != null) {
groupNames = new String[temp.size()];
Group f;
for (int i = 0; i < groupNames.length; ++i) {
//get the group
f = (Group) MongoHelper.fetch(new Group(temp.get(i)),
MongoHelper.GROUP_COLLECTION);
//record the name
//System.out.println(f);
if (f != null) {
groupNames[i] = f.getName();
//store it in the map
groups.put(f.getName(), f);
groupIdNameMap.put(f.getId(), f.getName());
}
}
//sort
if (groupNames.length > 1) {
Arrays.sort(groupNames);
}
}
}
} | 5 |
public Object getFieldValue(_Fields field) {
switch (field) {
case LEFT_RHINO_ID:
return Long.valueOf(getLeftRhinoId());
case LEFT_TITAN_ID:
return Long.valueOf(getLeftTitanId());
case RIGHT_RHINO_ID:
return Long.valueOf(getRightRhinoId());
case RIGHT_TITAN_ID:
return Long.valueOf(getRightTitanId());
case LABEL:
return getLabel();
case PROPERTIES:
return getProperties();
}
throw new IllegalStateException();
} | 6 |
public void setbossoldclass(HeroClass hc) {
this.oldclass = hc;
} | 0 |
public void run() {
while (true) {
try {
String[] nextCommand;
try {
nextCommand = dialogue.getUserInput("Enter command:").split(" ");
} catch (IOException e) {
throw new SystemCommandException(
"Error while reading most recent command.", e);
}
String commandName = nextCommand[0];
String[] arguments = Arrays.copyOfRange(nextCommand, 1,
nextCommand.length);
SystemCommand<Facade> command = commands.get(commandName);
if (command == null) {
command =
new UnknownSystemCommand<Facade>(facade, dialogue, commandName);
}
int minimumArguments = getCommandMinimumArguments(command);
if (arguments == null || arguments.length < minimumArguments)
throw new SystemCommandException(
"Invalid number of arguments for command ["
+ commandName + "].");
command.processCommand(arguments);
} catch (SystemCommandException e) {
dialogue.reportSystemError(e);
}
}
} | 6 |
public void treeNodesRemoved(TreeModelEvent e) {
invalidate();
} | 0 |
public void remove(Armor a){
switch(a.getType()){
case HEAD: armorList[0] = null;
break;
case SHOULDERS: armorList[1] = null;
break;
case BREAST: armorList[2] = null;
break;
case GLOVES:armorList[3] = null;
break;
case BELT: armorList[4] = null;
break;
case PANTS: armorList[5] = null;
break;
case SHOES: armorList[6] = null;
break;
}
Game.PLAYER.recalculateStats();
} | 7 |
public boolean equals(Object configuration)
{
if(configuration == this)
return true;
try
{
MealyConfiguration config = (MealyConfiguration) configuration;
return super.equals(config) &&
myUnprocessedInput.equals(config.myUnprocessedInput) &&
myOutput.equals(config.myOutput);
}
catch(ClassCastException e)
{
return false;
}
} | 4 |
public HUDQuickBar(HUDManager hm, Registry rg, int x, int y, int w, int h) {
super(hm, rg, x, y, w, h);
setImage("HUD/QuickBar/BG");
HUDArea hudArea = null;
//slots
int slotX = 0;
for (int i = 0; i < SLOTS; i++) {
slotX = SLOT_START_X + (i * SLOT_WIDTH) + (i * SLOT_SPACING);
hudArea = addArea(slotX, SLOT_START_Y, SLOT_WIDTH, SLOT_HEIGHT, "slot");
hudArea.setFont("SansSerif", Font.BOLD, 12);
hudArea.setImage("HUD/QuickBar/Slot");
}
//buttons
hudArea = addArea(BUTTON_INVENTORY_X, BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT, "button_inventory");
hudArea.setImage("HUD/QuickBar/ButtonInventory");
/*hudArea = addArea(BUTTON_REPORT_BUGS_X, BUTTON_Y, BUTTON_REPORT_BUGS_WIDTH, BUTTON_HEIGHT, "button_report_bugs");
hudArea.setImage("HUD/QuickBar/ButtonReportBugs");*/
hudArea = addArea(BUTTON_PAUSE_X, BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT, "button_pause");
hudArea.setImage("HUD/QuickBar/ButtonPause");
hudArea = addArea(BUTTON_HELP_X, BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT, "button_help");
hudArea.setImage("HUD/QuickBar/ButtonHelp");
hudArea = addArea(BUTTON_EXIT_X, BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT, "button_exit");
hudArea.setImage("HUD/QuickBar/ButtonExit");
//hp
hudArea = addArea(HP_BG_X, HP_BG_Y, HP_BG_WIDTH, HP_BG_HEIGHT, "hp_bg");
hudArea.setImage("HUD/QuickBar/HPBG");
hudArea = addArea(HP_BAR_X, HP_BAR_Y, 1, HP_BAR_HEIGHT, "hp_bar");
hudArea.setImage("HUD/QuickBar/HPBar");
hudArea = addArea(HP_TEXT_X, HP_TEXT_Y, 1, 1, "hp");
hudArea.setFont("SansSerif", Font.PLAIN, 11);
//xp
hudArea = addArea(XP_BG_X, XP_BG_Y, XP_BG_WIDTH, XP_BG_HEIGHT, "xp_bg");
hudArea.setImage("HUD/QuickBar/XPBG");
hudArea = addArea(XP_BAR_X, XP_BAR_Y, 1, XP_BAR_HEIGHT, "xp_bar");
hudArea.setImage("HUD/QuickBar/XPBar");
hudArea = addArea(XP_BG_X, XP_BG_Y, XP_BG_WIDTH, XP_BG_HEIGHT, "xp_overlay");
hudArea.setImage("HUD/QuickBar/XPOverlay");
hudArea = addArea(XP_TEXT_X, XP_TEXT_Y, 1, 1, "xp");
hudArea.setFont("SansSerif", Font.PLAIN, 11);
//lock
hudArea = addArea(LOCK_BG_X, LOCK_BG_Y, LOCK_BG_WIDTH, LOCK_BG_HEIGHT, "lock_bg");
hudArea.setImage("HUD/QuickBar/LockBG");
hudArea = addArea(LOCK_X, LOCK_Y, LOCK_WIDTH, LOCK_HEIGHT, "lock");
hudArea.setImage("HUD/QuickBar/Lock");
//status
hudArea = addArea(STATUS_X, STATUS_Y, STATUS_WIDTH, STATUS_HEIGHT, "status");
hudArea.setFont("SansSerif", Font.PLAIN, 11);
hudArea.setTextXY(STATUS_TEXT_X, STATUS_TEXT_Y);
hudArea.setImage("HUD/QuickBar/StatusBG");
//version
hudArea = addArea(VERSION_X, VERSION_Y, VERSION_WIDTH, VERSION_HEIGHT, "version");
hudArea.setFont("SansSerif", Font.BOLD, 12);
hudArea.setTextXY(STATUS_TEXT_X, STATUS_TEXT_Y);
hudArea.setText("Version: " + Game.VERSION);
//power
hudArea = addArea(POWER_TEXT_X, POWER_TEXT_Y, 1, 1, "power");
hudArea.setFont("SansSerif", Font.BOLD, 13);
hudArea.setTextColor(new Color(112, 223, 255));
//level
hudArea = addArea(LEVEL_TEXT_X, LEVEL_TEXT_Y, 1, 1, "level");
hudArea.setFont("SansSerif", Font.BOLD, 13);
hudArea.setTextColor(new Color(243, 238, 102));
//robot stuff
hudArea = addArea(ROBOT_POWER_X, ROBOT_POWER_Y, ROBOT_POWER_WIDTH, ROBOT_POWER_HEIGHT, "robot_power");
hudArea.setImage("HUD/QuickBar/RobotPower");
hudArea = addArea(DIVIDER_X1, DIVIDER_Y, DIVIDER_WIDTH, DIVIDER_HEIGHT, "divider1");
hudArea.setImage("HUD/QuickBar/Divider");
hudArea = addArea(DIVIDER_X2, DIVIDER_Y, DIVIDER_WIDTH, DIVIDER_HEIGHT, "divider2");
hudArea.setImage("HUD/QuickBar/Divider");
hudArea.setIsActive(false);
//robot buttons
hudArea = addArea(ROBOT_BUTTON_PASSIVE_X, ROBOT_BUTTON_Y, ROBOT_BUTTON_WIDTH, ROBOT_BUTTON_HEIGHT, "robot_button_passive");
hudArea.setImage("HUD/QuickBar/RobotPassive");
hudArea.setIsActive(false);
hudArea = addArea(ROBOT_BUTTON_DEFENSIVE_X, ROBOT_BUTTON_Y, ROBOT_BUTTON_WIDTH, ROBOT_BUTTON_HEIGHT, "robot_button_defensive");
hudArea.setImage("HUD/QuickBar/RobotDefensive");
hudArea.setIsActive(false);
hudArea = addArea(ROBOT_BUTTON_AGGRESSIVE_X, ROBOT_BUTTON_Y, ROBOT_BUTTON_WIDTH, ROBOT_BUTTON_HEIGHT, "robot_button_aggressive");
hudArea.setImage("HUD/QuickBar/RobotAggressive");
hudArea.setIsActive(false);
hudArea = addArea(ROBOT_BUTTON_FOLLOW_X, ROBOT_BUTTON_Y, ROBOT_BUTTON_WIDTH, ROBOT_BUTTON_HEIGHT, "robot_button_follow");
hudArea.setImage("HUD/QuickBar/RobotFollow");
hudArea.setIsActive(false);
//robot slots
slotX = 0;
for (int i = 0; i < ROBOT_SLOTS; i++) {
slotX = ROBOT_SLOT_START_X + (i * ROBOT_SLOT_WIDTH) + (i * ROBOT_SLOT_SPACING);
hudArea = addArea(slotX, ROBOT_SLOT_START_Y, ROBOT_SLOT_WIDTH, ROBOT_SLOT_HEIGHT, "robot_slot" + (i + 1));
hudArea.setImage("HUD/QuickBar/RobotSlot");
hudArea.setIsActive(false);
}
//robot battery
hudArea = addArea(ROBOT_BATTERY_X, ROBOT_BATTERY_Y, ROBOT_BATTERY_WIDTH, ROBOT_BATTERY_HEIGHT, "robot_battery_bg");
hudArea.setImage("HUD/QuickBar/RobotBattery");
hudArea = addArea(ROBOT_BATTERY_BAR_X, ROBOT_BATTERY_BAR_Y, 1, ROBOT_BATTERY_BAR_HEIGHT, "robot_battery_bar");
hudArea.setImage("HUD/QuickBar/RobotBatteryMeter");
hudArea = addArea(ROBOT_BATTERY_BAR_TEXT_X, ROBOT_BATTERY_BAR_TEXT_Y, 1, 1, "robot_battery_level");
hudArea.setFont("SansSerif", Font.PLAIN, 11);
hudArea.setText("100%");
} | 2 |
public static ctrlTaller getInstance() {
if (INSTANCE == null) {
creaInstancia();
}
return INSTANCE;
} | 1 |
public JTextField getjTextFieldVilleCP() {
return jTextFieldVilleCP;
} | 0 |
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Lap)) {
return false;
}
final Lap lap = (Lap) o;
if (id != null ? !id.equals(lap.id) : lap.id != null) {
return false;
}
if (rawDataSet != null ? !rawDataSet.equals(lap.rawDataSet) : lap.rawDataSet != null) {
return false;
}
return true;
} | 6 |
public static <E extends Comparable<E>> void sortWithQueue(IMyQueue<E> queue) {
if(queue.isEmpty()) {
return;
}
IMyQueue<E> auxQue = new MyLinkedQueue<E>();
while(!queue.isEmpty()) {
// First get current element from queue
E element = queue.poll();
// Then, get current smallest item (CSI)
// if auxQueue is empty, CSI is current item from queue;
// if auxQueue is not empty and auxQueue's peek is smaller than current item from queue, CSI is this item;
// if auxQueue is not empty and auxQueue's peek is bigger than current item from queue, CSI is current item from queue;
E currMin = (auxQue.peek()!=null && auxQue.peek().compareTo(element)<=0)?auxQue.peek():element;
// put items smaller than item from queue to the end of auxQueue
int size = auxQue.size();
while(!auxQue.isEmpty() && auxQue.peek().compareTo(element)<=0 && size>0) {
auxQue.offer(auxQue.poll());
size--;
}
// put current item from queue to the end of auxQueue
auxQue.offer(element);
// continue to put frontend items which is bigger than current item from queue after current item in auxQueue
while(auxQue.peek().compareTo(currMin)!=0) {
auxQue.offer(auxQue.poll());
}
}
// Put items back to queue
while(!auxQue.isEmpty()) {
queue.offer(auxQue.poll());
}
} | 9 |
public void addRequierField(String requierField) {
if (this.requireFields == null) {
this.requireFields = new ArrayList<String>();
this.requireFields.add(requierField);
} else
this.requireFields.add(requierField);
} | 1 |
@Override
public int compareTo(Apple o) {
if (id > o.getId()) {
return 1;
} else if (id == o.getId()) {
return 0;
} else {
return -1;
}
} | 2 |
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.