text stringlengths 14 410k | label int32 0 9 |
|---|---|
static final void method1267(GraphicsToolkit graphicstoolkit, int i, int i_78_, int i_79_, int i_80_, int i_81_, int i_82_, boolean bool, boolean bool_83_) {
CacheNode_Sub18.aGraphicsToolkit9607 = graphicstoolkit;
Class22.anInt427 = i;
Class188_Sub2.aBoolean6868 = Class22.anInt427 > 1 && CacheNode_Sub18.aGraphicsToolkit9607.s();
Class36.anInt549 = i_78_;
Class179.anInt2129 = 1 << Class36.anInt549;
Class135.anInt1692 = Class179.anInt2129 >> 1;
Math.sqrt((double) (Class135.anInt1692 * Class135.anInt1692 + Class135.anInt1692 * Class135.anInt1692));
Class159.anInt1995 = i_79_;
Class328.anInt4115 = i_80_;
Node_Sub50.anInt7623 = i_81_;
Node_Sub9_Sub1.anInt9656 = i_82_;
Class146.aClass10_1815 = Class290_Sub3.method3429(true);
Class194_Sub2.method1970(27);
Class256.aClass261ArrayArrayArray3240 = new Class261[i_79_][Class328.anInt4115][Node_Sub50.anInt7623];
Node_Sub38_Sub37.aPlaneArray10466 = new Plane[i_79_];
if (bool) {
Player.anIntArrayArray11128 = new int[Class328.anInt4115][Node_Sub50.anInt7623];
Class320_Sub18.aByteArrayArray8379 = new byte[Class328.anInt4115][Node_Sub50.anInt7623];
Class146.aShortArrayArray1802 = new short[Class328.anInt4115][Node_Sub50.anInt7623];
Class225.aClass261ArrayArrayArray2680 = new Class261[1][Class328.anInt4115][Node_Sub50.anInt7623];
Class368.aPlaneArray4548 = new Plane[1];
} else {
Player.anIntArrayArray11128 = null;
Class320_Sub18.aByteArrayArray8379 = null;
Class146.aShortArrayArray1802 = null;
Class225.aClass261ArrayArrayArray2680 = null;
Class368.aPlaneArray4548 = null;
}
if (bool_83_) {
Class91.aLongArrayArrayArray1228 = new long[i_79_][i_80_][i_81_];
Class143.aClass326Array1771 = new Class326[65535];
Class147.aBooleanArray1820 = new boolean[65535];
Class188_Sub1_Sub1.anInt9337 = 0;
} else {
Class91.aLongArrayArrayArray1228 = null;
Class143.aClass326Array1771 = null;
Class147.aBooleanArray1820 = null;
Class188_Sub1_Sub1.anInt9337 = 0;
}
Node_Sub38_Sub17.method2842(false);
Class303.anAnimableArray3827 = new Animable[2];
SeekableFile.anAnimableArray3884 = new Animable[2];
Node_Sub36.anAnimableArray7429 = new Animable[2];
Class32.anAnimableArray516 = new Animable[10000];
Node_Sub42.anInt7527 = 0;
Class262_Sub15.anAnimableArray7817 = new Animable[5000];
Class348.anInt4290 = 0;
Node_Sub52.aMobileArray7648 = new Mobile[5000];
Class63.anInt923 = 0;
Class139.aBooleanArrayArray1730 = new boolean[Node_Sub9_Sub1.anInt9656 + Node_Sub9_Sub1.anInt9656 + 1][Node_Sub9_Sub1.anInt9656 + Node_Sub9_Sub1.anInt9656 + 1];
Class75.aBooleanArrayArray1002 = new boolean[Node_Sub9_Sub1.anInt9656 + Node_Sub9_Sub1.anInt9656 + 2][Node_Sub9_Sub1.anInt9656 + Node_Sub9_Sub1.anInt9656 + 2];
Node_Sub38_Sub7.anIntArray10150 = new int[Node_Sub9_Sub1.anInt9656 + Node_Sub9_Sub1.anInt9656 + 2];
Node_Sub36_Sub3.aClass179_10058 = Node_Sub36_Sub3.aClass179_10062;
if (Class188_Sub2.aBoolean6868) {
Class234.aBooleanArrayArrayArray2790 = new boolean[i_79_][Node_Sub9_Sub1.anInt9656 + Node_Sub9_Sub1.anInt9656 + 1][Node_Sub9_Sub1.anInt9656 + Node_Sub9_Sub1.anInt9656 + 1];
Class150_Sub2.aBooleanArrayArrayArray8960 = new boolean[i_79_][][];
if (GraphicsToolkit.aClass33Array1549 != null) {
Class262_Sub8.method3169();
}
GraphicsToolkit.aClass33Array1549 = new Class33[Class22.anInt427];
CacheNode_Sub18.aGraphicsToolkit9607.j(GraphicsToolkit.aClass33Array1549.length + 1);
CacheNode_Sub18.aGraphicsToolkit9607.k(0);
for (int i_84_ = 0; i_84_ < GraphicsToolkit.aClass33Array1549.length; i_84_++) {
GraphicsToolkit.aClass33Array1549[i_84_] = new Class33(i_84_ + 1, CacheNode_Sub18.aGraphicsToolkit9607);
new Thread(GraphicsToolkit.aClass33Array1549[i_84_], "wr" + i_84_).start();
}
int i_85_;
if (Class22.anInt427 == 2) {
i_85_ = 4;
Class290.anInt3655 = 2;
} else if (Class22.anInt427 == 3) {
i_85_ = 6;
Class290.anInt3655 = 3;
} else {
i_85_ = 8;
Class290.anInt3655 = 4;
}
Class364.aClass273Array4513 = new Class273[i_85_];
for (int i_86_ = 0; i_86_ < i_85_; i_86_++)
Class364.aClass273Array4513[i_86_] = new Class273(Node_Sub40.aStringArrayArray7505[Class22.anInt427 - 2][i_86_]);
} else {
Class290.anInt3655 = 1;
}
Node_Sub38_Sub25.anIntArray10358 = new int[Class290.anInt3655 - 1];
Class270_Sub2.anIntArray8039 = new int[Class290.anInt3655 - 1];
} | 9 |
public void setTileImages(Image[] paramArrayOfImage)
{
this.TileImages = paramArrayOfImage;
MediaTracker localMediaTracker = new MediaTracker(this);
for (int i = 0; i < paramArrayOfImage.length; i++)
localMediaTracker.addImage(paramArrayOfImage[i], 0); try {
localMediaTracker.waitForAll(); } catch (InterruptedException localInterruptedException) { localInterruptedException.printStackTrace();
}
if ((localMediaTracker.statusAll(false) & 0x4) != 0)
System.out.println("Problems loading the Shroud images!");
} | 3 |
@Override
public byte[] receiveBytes() {
try {
p.writeBytes(new byte[] { '*','r' } );
if (!readUntil((byte)'*',600) || !readUntil((byte)'r',600))
return null;
byte[] oneByte = p.readBytes(1, scaleTimeout(50));
if (oneByte.length != 1)
return null;
int length = (0xFF&(int)(oneByte[0]));
length = (length-1)&0xFF;
if (length == 0)
return null;
//System.out.println("data "+length);
byte[] out = p.readBytes(length, scaleTimeout(5*length));
if (out != null && out.length == length)
return out;
} catch (SerialPortException e) {
} catch (SerialPortTimeoutException e) {
}
return null;
} | 8 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAndWeight other = (UserAndWeight) obj;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
if (Double.doubleToLongBits(weight) != Double
.doubleToLongBits(other.weight))
return false;
return true;
} | 7 |
protected boolean closed(Area A)
{
if(A==null)
return false;
for(final Room.VariationCode code : Room.VariationCode.values())
{
if(closedV.contains(code.toString()))
switch(code.c)
{
case 'W':
if(A.getClimateObj().weatherType(null)==code.num)
return true;
break;
case 'C':
if(A.getTimeObj().getTODCode().ordinal()==code.num)
return true;
break;
case 'S':
if(A.getTimeObj().getSeasonCode().ordinal()==code.num)
return true;
break;
}
}
return false;
} | 9 |
protected static void startReceiveMessage(InputStream in){
while(true){
try{
byte[] temBuffer = new byte[1024];
int count = in.read(temBuffer);
while(count > 0){
String msg = new String(temBuffer,"utf-8");
log.info("the count is:\r\n" + count + "\r\nthe message receive: \r\n" + msg);
temBuffer = new byte[1024];
count = in.read(temBuffer);
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | 3 |
private static void addImgPath(List<ResourceVO> list, Path img) {
if (img != null) {
int num = Integer.parseInt(img.getFileName().toString().split("\\.")[0]);
list.add(new ResourceVO(img, ResourceType.BITMAP, num));
}
} | 1 |
public void setFirstName(String firstName) {
this.firstName = firstName;
} | 0 |
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (qName.equals(mNodeName)) {
verifyNodeBasics(attributes);
verifyNode(attributes);
}
} | 1 |
public void setJournalId(Integer journalId) {
this.journalId = journalId;
} | 0 |
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");
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("\n");
out.write("\n");
out.write("\n");
out.write("\n");
String userid = request.getParameter("uname");
String pwd = request.getParameter("pass");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/p2","root", "");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select * from members where uname='" + userid + "' and pass='" + pwd + "'");
if (rs.next()) {
session.setAttribute("userid", userid);
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("success.jsp");
} else {
out.println("Invalid password <a href='index.jsp'>try again</a>");
}
out.write('\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 |
public void playGame() {
System.out.println("Please enter the boardSize you will be needing. It should be atleast 3 ");
int boardSize;
while (true) {
try{
boardSize = Integer.parseInt(scanner.nextLine());
if(boardSize<3){
System.out.println(" The boardSize should be atleast 3. Please enter the appropriate size ");
continue;
}
}
catch(NumberFormatException exception){
System.out.println("Please enter a valid number greater than or equal to 3");
continue;
}
break;
}
System.out.println("The boardSize you have entered is : "+boardSize);
TicTacToeGame ticTacToeGame = new TicTacToeGame(boardSize);
System.out.println("Please enter the Mode you want to Opt for :");
System.out.println("Enter 1. Between Human-Human *********************");
System.out.println("Enter 2. Between Human-Computer ******************");
System.out.println("Enter 3. Between Computer-Computer ***************");
ticTacToeGame.setMode(Integer.parseInt(scanner.nextLine()));
while (!ticTacToeGame.isGameOver()) {
getNextTurn(ticTacToeGame);
ticTacToeGame.displayGameState();
}
if (ticTacToeGame.getMatchDrawnStatus())
System.out.println("Match is drawn");
else
System.out.println("Winner is :" + ticTacToeGame.getWinner());
} | 5 |
@Override
public void startOutline () {
// initialize the current node to the root node of the outline
this.currentNode = tree.getRootNode();
// clear out any existing children.
while (currentNode.numOfChildren() > 0) {
currentNode.removeChild(currentNode.getLastChild());
} // end while
// set the initial level to the root node's level
currentLevel = -1 ;
} // end startOutline | 1 |
public static boolean writePropertiesFile(String ipAddress, String user, String password, String filepath, String filename, String includeDate){
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("Auto-DDWRT-Backup.properties");
// set the properties value
prop.setProperty("ipAddress", ipAddress);
prop.setProperty("user", user);
prop.setProperty("password", password);
prop.setProperty("filepath", filepath);
prop.setProperty("filename", filename);
prop.setProperty("includeDate", includeDate);
// save properties to project root folder
prop.store(output, null);
}
catch (IOException io) {
io.printStackTrace();
return false;
}
finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
return true;
}//end writePropertiesFile() | 3 |
void stopTest()
{
log("Shutting down....");
if (m_responseQ != null)
{
if (m_responseQ != null)
{
log("Deactivating responseQ...");
m_responseQ.deactivate();
m_responseQ = null;
}
if (m_responseMessageDispatcher != null)
{
log("Response Dispatcher terminating...");
m_responseMessageDispatcher.terminate();
m_responseMessageDispatcher = null;
log("Response Dispatcher terminated...");
}
}
if (m_pool != null)
{
log("Destroying pool...");
m_pool.destroy();
m_pool = null;
}
if (m_consumer != null)
{
log("UnregisterClient...");
m_consumer.unregisterClient(null);
}
if (m_loginHandle != null)
{
log("Dending logoff request");
m_consumer.unregisterClient(m_loginHandle);
m_loginHandle = null;
}
if (m_consumer != null)
{
log("OMMConsumer destroy...");
m_consumer.destroy();
m_consumer = null;
}
if (m_session != null)
{
log("Session release...");
m_session.release();
log("Shutdown completed!!!");
m_session = null;
}
} | 8 |
public String getAddress() {
return address;
} | 0 |
public void run () {
m_running = true;
while (m_running) {
synchronized(this) {
executeQuieries();
}
try {
Thread.sleep(m_updateTime * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized(this) {
executeQuieries();
}
} | 2 |
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
} | 0 |
@Override
public String toString() {
StringBuilder hex = new StringBuilder();
for(byte b : value) {
String hexDigits = Integer.toHexString(b).toUpperCase();
if(hexDigits.length() == 1) {
hex.append("0");
}
hex.append(hexDigits).append(" ");
}
return "TAG_Byte_Array: " + hex.toString();
} | 2 |
public void update() {
// update position
getNextPosition();
checkTileMapCollision();
setPosition(xtemp, ytemp);
// if it hits a wall, go other direction
if(right && dx == 0) {
right = false;
left = true;
facingRight = false;
}
else if(left && dx == 0) {
right = true;
left = false;
facingRight = true;
}
// update animation
animation.update();
if((System.nanoTime()-(int)(elapsed/1000000))%3000 == 0){
}
} | 5 |
private Selector parseSelector() {
Pair<List<SimpleSelector>, PseudoElementSelector> simpleSelectors = parseSimpleSelectors();
CompoundSelector compoundSelector = CompoundSelector.of(simpleSelectors.first);
PseudoElementSelector pseudoElement = simpleSelectors.second;
while (pseudoElement == null) {
Pair<Token, Boolean> p = skipWhitespace();
if (p.first.type == TokenType.EOF) {
break;
} else if (p.first.type == TokenType.COMMA) {
savedToken = p.first;
break;
}
Combinator combinator = null;
if (p.first.type == TokenType.DELIM) {
switch (p.first.value) {
case ">":
combinator = Combinator.CHILD;
break;
case "+":
combinator = Combinator.NEXT_SIBLING;
break;
case "~":
combinator = Combinator.LATER_SIBLING;
break;
}
}
if (combinator == null) {
if (p.second) {
combinator = Combinator.DESCENDANT;
} else {
throw expected("one of ' ', '>', '+', '~'", p.first);
}
savedToken = p.first;
}
simpleSelectors = parseSimpleSelectors();
compoundSelector = new CompoundSelector(simpleSelectors.first, new Pair<>(combinator, compoundSelector));
}
return new Selector(compoundSelector, pseudoElement);
} | 9 |
public ListNode swapPairs(ListNode head) {
if(head == null)
return null;
if(head.next == null)
return head;
ListNode result = head.next;
ListNode p1 = head;
ListNode p2 = head.next;
while(p1 !=null && p2!=null){
ListNode nextP1 = p2.next;
ListNode nextP2 = nextP1 == null ? null : nextP1.next;
p1.next = p2.next == null ? p2.next : p2.next.next == null ? p2.next : p2.next.next;
p2.next = p1;
p1 = nextP1;
p2 = nextP2;
}
return result;
} | 7 |
private void drawMaze(Graphics g) {
for (int y = 0; y < maze.getMazeRawData().length; y++) {
MazeField[] mazeRow = maze.getMazeRawData()[y];
for (int x = 0; x < mazeRow.length; x++) {
MazeField mazeField = mazeRow[x];
g.setColor((mazeField.toString().equals("E") ? Color.WHITE
: Color.BLACK));
g.fillRect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
for (Point targetPoint : maze.targetPoints) {
g.setColor(Color.GREEN);
g.fillRect(targetPoint.x * TILE_SIZE, targetPoint.y * TILE_SIZE,
TILE_SIZE, TILE_SIZE);
}
g.setColor(Color.RED);
g.fillRect(maze.startPoint.x * TILE_SIZE,
maze.startPoint.y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
} | 4 |
@Override
protected void setReaction(Message message) {
try {
String result;
String messageText = message.text.trim();
switch(reactionId) {
case 1: {
String movieSearch = messageText.substring(messageText.indexOf(" ") +1);
result = SearchMovieData(movieSearch);
break;
}
case 2: {
String csfdLink = GenerateCsfdMovieLink(messageText);
result = GetMovieData(csfdLink);
break;
}
default:
return;
}
reaction.add( result );
} catch (Exception e) {
if (e instanceof MovieException) {
reaction.add( e.getMessage() );
}
else {
System.out.println(e);
if (message.text.startsWith(REACT_MESSAGE))
setError("Cannot load given URL.", e);
}
}
} | 5 |
public void getRules(){
try {
String messageFromServer = null;
out.println(PLAYER_NAME_PREFIX+";"+me.getName());
while(me.getSymbol() == null || boardSize == 0 || winningSymNr == 0){
messageFromServer = getMessageFromServer();
if(messageFromServer != null)
proccesMessage(messageFromServer);
}
board = new Board(boardSize);
window.drawBoard(board.drawBoard());
messageFromServer = null;
while(!YOUR_TURN.equals(messageFromServer)|| !WAITING_FOR.regionMatches(true, 0, messageFromServer, 0, 3)){
messageFromServer = getMessageFromServer();
if(messageFromServer!=null)
playTheGame(messageFromServer);
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
} | 8 |
public File getFile() {
Object gotValue=getValue();
if(gotValue==null)
return null;
if(!gotValue.getClass().isAssignableFrom(File.class)) {
throw new ClassCastException("don't know how to convert "
+gotValue.getClass().getName()+" to File");
}
return (File)gotValue;
} | 2 |
public void draw(Graphics graphics, FontDAO fontDAO, ImageDAO imageDAO, TextDAO textDAO, ApplicationState applicationState, Metronome metronome) throws Exception {
graphics.setColor(0x00000000);
graphics.fillRect(0, 0,width(), height());
switch (applicationState.getState()) {
case ApplicationState.SPLASH:
drawSplash(graphics, fontDAO, imageDAO, textDAO);
break;
case ApplicationState.MAIN_MENU:
drawMainMenu(graphics, fontDAO, imageDAO, textDAO);
break;
case ApplicationState.OPTIONS:
drawOptions(graphics, fontDAO, imageDAO, textDAO, metronome);
break;
case ApplicationState.HELP:
drawHelp(graphics, fontDAO, imageDAO, textDAO);
break;
case ApplicationState.ABOUT:
drawAbout(graphics, fontDAO, imageDAO, textDAO);
break;
case ApplicationState.EXIT:
drawExit(graphics, fontDAO, imageDAO, textDAO);
break;
case ApplicationState.METRONOME_STARTED:
drawMetronomeStarted(graphics, fontDAO, imageDAO, textDAO, metronome);
break;
case ApplicationState.METRONOME_STOPPED:
drawMetronomeCore(graphics, fontDAO, imageDAO, textDAO, metronome);
break;
}
} | 8 |
public void run() {
double sign = _negated ? -1 : 1;
double newSpeed = _controller.get() + sign*_rate * _period;
if(Math.abs(newSpeed) < 0.15 && ((sign*_rate < 0) != (newSpeed < 0))) {
_controller.set(0);
} else if (newSpeed < _minSpeed) {
_controller.set(_minSpeed);
} else if(newSpeed > _maxSpeed) {
_controller.set(_maxSpeed);
} else {
_controller.set(newSpeed);
}
} | 5 |
@Override
public synchronized void mark(int readlimit) {
this.mark = readlimit;
} | 0 |
public void setStudentId(int studentId) {
this.studentId = studentId;
} | 0 |
private void insertComplete () {
String completeString = "<Transform translation='0.0 0.0 0.0' rotation='0.0 0.0 0.0 0.0'>\n\t\t<Shape>\n\t\t\t<Box";
if (headerBlock.nameSelect.isSelected()) {
if ((!headerBlock.objectName.getText().equals("")) && (!xSize.getText().equals("")) && (!ySize.getText().equals("")) && (!zSize.getText().equals(""))) {
completeString += " DEF='"+headerBlock.objectName.getText()+"' size='"+
xSize.getText()+" "+
ySize.getText()+" "+
zSize.getText()+"' solid='"+
solidBox.isSelected()+"'/>\n\t\t\t<Appearance>\n\t\t\t\t<Material ";
if (footerBlock.colorKind.getSelectedIndex() == 0) completeString += "diffuseColor=";
else if (footerBlock.colorKind.getSelectedIndex() == 1) completeString += "emissiveColor=";
else completeString += "specularColor=";
completeString += "'"+((float)footerBlock.red/255)+" "+((float)footerBlock.green/255)+" "+((float)footerBlock.blue/255)+"'/>\n";
if ((subfooterBlock.textureBox.isSelected()) && (subfooterBlock.texturePath != null)) {
completeString += "\t\t\t\t<ImageTexture repeatS='"+
subfooterBlock.hBox.isSelected()+"' repeatT='"+
subfooterBlock.vBox.isSelected()+"' url='"+
subfooterBlock.texturePath+"'/>\n";
}
completeString += "\t\t\t</Appearance>\n\t\t</Shape>\n\t</Transform>";
backTrack.appendString(completeString);
formWindowClosing();
} else {
Cerrorinterface bck = new Cerrorinterface("EMPTIEERR", false);
}
} else {
completeString += " USE='"+
headerBlock.useName.getSelectedItem()+"'/>\n\t\t</Shape>\n\t</Transform>";
backTrack.appendString(completeString);
formWindowClosing();
}
backTrack.tagsUpdater.switchUpdate();
} | 9 |
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
if (rootFilter != null) {
rootFilter.doFilter(request, response);
}
RequestHelper helper = new RequestHelper(new CommandParameter(request, response));
ICommand command = helper.getCommand();
String page = command.execute();
dispatch(request, response, page);
} | 1 |
@Override
public NodeVisitor child(String ns, String name) {
if (name == null || name.isEmpty()) {
System.err.println("Encountered a null or empty node name "
+ "in file " + layoutFile + ", skipping node...");
return null;
}
// Check for inclusions
String tname = name.trim();
if (tname.equals("include"))
return new IncludeParser(layoutFile);
// The "merge" tag merges the next hierarchy level into the current
// one for flattening hierarchies.
if (tname.equals("merge"))
return new LayoutParser(layoutFile, theClass);
final SootClass childClass = getLayoutClass(tname);
if (childClass != null && (isLayoutClass(childClass) || isViewClass(childClass)))
return new LayoutParser(layoutFile, childClass);
else
return super.child(ns, name);
} | 7 |
public String getRNC() {
return RNC;
} | 0 |
public void addRule(String source, String dest, String kind,
Integer seqNum, Boolean duplicate, String action) {
this.rules.add(new Rule(source, dest, kind, seqNum, duplicate, action));
} | 0 |
public void setDateLength(long len) {
if (len < HAS_EXTEND_DATA) {
this.payloadLen = (byte) len;
this.payloadLenExtended = 0;
this.payloadLenExtendedContinued = 0;
} else if (len < 1 * Short.MAX_VALUE * 2) {// UNSIGNED
this.payloadLen = HAS_EXTEND_DATA;
this.payloadLenExtended = (short) len;
this.payloadLenExtendedContinued = 0;
} else {
this.payloadLen = HAS_EXTEND_DATA_CONTINUE;
this.payloadLenExtended = 0;
this.payloadLenExtendedContinued = len;
}
} | 2 |
public static List<DomElement> findAllDirectChildrenAndSelect(String html, String selector){
Matcher matcher = allTagFindPattern.matcher(html);
int sequenceIndex = 0;
Vector<Tag> tags = new Vector<Tag>();
while(matcher.find(sequenceIndex)){
Tag tag = new Tag();
tag.setTag(matcher.group(0));
tag.setTagName(matcher.group(2));
tag.setEnd((matcher.group(1)!=null&&!matcher.group(1).equals("")));
tag.setTagEndIndex(matcher.end(0));
tags.add(tag);
sequenceIndex = matcher.end(0);
}
List<Tag> children = new ArrayList<Tag>();
Stack<Tag> stack = new Stack<Tag>();
for(int i = tags.size()-1; i >= 0; i--){
Tag tag = tags.get(i);
//System.out.println(tag.getTagName()+"\t"+i);
if(tag.isEnd()){
stack.push(tag);
}else{
if(stack.isEmpty()){
children.add(0, tag);
}else{
if(stack.peek().getTagName().equals(tag.getTagName())&&stack.peek().isEnd()){
stack.pop();
if(stack.size()==0){
children.add(0, tag);
}
}
}
}
}
return singleTagSelector(selector, children, html);
} | 8 |
public void buildToolbar(){
final JMenuBar menubar = new JMenuBar();
JMenu display_menu = new JMenu("Display Options");
final JCheckBoxMenuItem view = new JCheckBoxMenuItem("Show Critter views");
view.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(view.isSelected()){
planet.display_views = true;
view.setText("Hide Critter views");
}
else{
planet.display_views = false;
view.setText("Show Critter views");
}
}
});
display_menu.add(view);
final JCheckBoxMenuItem sprites = new JCheckBoxMenuItem("Show detailed Critters");
sprites.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(sprites.isSelected()){
sprites.setText("Show simple Critters");
planet.paint_detailed = true;
}
else{
sprites.setText("Show detailed Critters");
planet.paint_detailed = false;
CritterUtil.massApplySimpleSprite(planet);
}
}
});
display_menu.add(sprites);
menubar.add(display_menu);
setJMenuBar(menubar);
} | 2 |
@Override
public boolean isDefault() {
return defaultGroup;
} | 0 |
@Override
public float getCusto() {
// TODO Auto-generated method stub
float cus;
switch (marca) {
case AMD: cus = 300; break;
case INTEL: if(gab.getDescricao().contains("Intel")) cus = 288; else cus = 360; break;
default: cus = 0; break;
}
return cus + gab.getCusto();
} | 3 |
public void forceByteCaching() {
if (isCachingEnabled && !isCached) {
try {
// Create a writable file channel
if (tempFile == null) {
createTempFile();
}
// create output stream in needed
if (fileOutputStream == null) {
fileOutputStream = new FileOutputStream(tempFile);
}
// write the bytes to the cache.
if (byteArrayOutputStream != null)
fileOutputStream.write(byteArrayOutputStream.toByteArray());
isCached = true;
// clear byte arrays to free up some memory.
byteArrayOutputStream = null;
byteArrayInputStream = null;
} catch (IOException e) {
logger.log(Level.FINE, "Error creating the temp file.", e);
}
}
} | 6 |
public void draw() {
background(0);
this.frame.setTitle("Beijing Bus");
this.frame.setIconImage(icon);
map.draw();
if (loadCnt > 0) {
fill(255);
rect(0, 0, width, height);
shape(busLogo, width / 2 - width / 16f, height / 2 - 1.225f * width
/ 16, width / 8f, 1.225f * width / 8);
loadCnt--;
} else {
for (Control control : controls) {
control.display();
}
for (Bus bus : buses) {
bus.display();
}
if (mousePressed) {
for (Bus bus : buses) {
bus.clearPreviosPos();
}
for (Control control : controls) {
control.setIsDisplay(true);
}
button.setIsDisplay(true);
displayFrameCnt = 100;
}
if (displayFrameCnt > 0) {
displayFrameCnt--;
} else {
for (Control control : controls) {
control.setIsDisplay(false);
}
}
}
} | 8 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Physical target=mob.location();
if(target==null)
return false;
if(target.fetchEffect(ID())!=null)
{
mob.tell(L("This place is already a blessed hearth."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 to fill this place with blessedness.^?",prayForWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
setMiscText(mob.Name());
if((target instanceof Room)
&&(CMLib.law().doesOwnThisProperty(mob,((Room)target))))
{
final String landOwnerName=CMLib.law().getPropertyOwnerName((Room)target);
if(CMLib.clans().getClan(landOwnerName)!=null)
setMiscText(landOwnerName);
target.addNonUninvokableEffect((Ability)this.copyOf());
CMLib.database().DBUpdateRoom((Room)target);
}
else
beneficialAffect(mob,target,asLevel,0);
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 to fill this place with blessedness, but <S-IS-ARE> not answered.",prayForWord(mob)));
return success;
} | 9 |
public void setRequestMethod(Method requestMethod) {
this.requestMethod = requestMethod;
} | 0 |
public void addEmails(String emails) {
if (this.emails == null) {
this.emails = new ArrayList<String>();
this.emails.add(emails);
} else {
this.emails.add(emails);
}
} | 1 |
public void LinkInCognitiveGraph(){
//0.找到激活强度最高和次高的节点的激活级别,分别记为high和low
//1.找到激活状态最高的节点,构建一个和它相同的GraphNode
//2.找到激活状态次高的节点,将刚刚完成的GraphNote连接到它的队尾
//3.构建一个和激活状态次高的节点相同的节点,连接它到激活状态最高的节点的后面
//0
int low=GetCurrentSecondHighActivatedNodeAL();
int high=GetCurrentMostHighActivatedNodeAL();
int GraphSize=CognitiveGraph.size();
GraphNode first=new GraphNode();
GraphNode second=new GraphNode();
//1
for(int i=0;i<GraphSize;i++){
if(CognitiveGraph.get(i).ObjOrAttri.get(0).ActivatedLevel==high){
first.ActivatedLevel=high;
first.Symbol=CognitiveGraph.get(i).ObjOrAttri.get(0).Symbol;
first.OriginalType=CognitiveGraph.get(i).ObjOrAttri.get(0).OriginalType;
first.RelationType=CognitiveGraph.get(i).ObjOrAttri.get(0).RelationType;
break;
}
}
//2(3)
for(int i=0;i<GraphSize;i++){
if(CognitiveGraph.get(i).ObjOrAttri.get(0).ActivatedLevel==low){
CognitiveGraph.get(i).ObjOrAttri.add(first);//把first连接上去
second.ActivatedLevel=CognitiveGraph.get(i).ObjOrAttri.get(0).ActivatedLevel;
second.Symbol=CognitiveGraph.get(i).ObjOrAttri.get(0).Symbol;
second.OriginalType=CognitiveGraph.get(i).ObjOrAttri.get(0).OriginalType;
second.RelationType=CognitiveGraph.get(i).ObjOrAttri.get(0).RelationType;
break;
}
}
//3
for(int i=0;i<GraphSize;i++){
if(CognitiveGraph.get(i).ObjOrAttri.get(0).ActivatedLevel==high){
CognitiveGraph.get(i).ObjOrAttri.add(second);//把second连接上去
break;
}
}
} | 6 |
private void setBaseEncoding(String baseencoding) {
if (baseencoding == null) {
encodingName = "none";
return;
} else if (baseencoding.equals("StandardEncoding")) {
encodingName = "StandardEncoding";
encoding = Encoding.getStandard();
} else if (baseencoding.equals("MacRomanEncoding")) {
encodingName = "MacRomanEncoding";
encoding = Encoding.getMacRoman();
} else if (baseencoding.equals("WinAnsiEncoding")) {
encodingName = "WinAnsiEncoding";
encoding = Encoding.getWinAnsi();
} else if (baseencoding.equals("PDFDocEncoding")) {
encodingName = "PDFDocEncoding";
encoding = Encoding.getPDFDoc();
}
// initiate encoding cMap.
if (encoding != null) {
for (char i = 0; i < 256; i++) {
cMap[i] = encoding.get(i);
}
}
} | 7 |
@SuppressWarnings("unused")
private void create() { //créé un villageois
/** if(this.compteur > (this.env.getLongueur() * this.env.getLargeur()) && this.compteur > 100) //la limite du compteur dépend de la taille du terrain, min 100
this.perdu = true; Tu veux faire perdre le forum s'il ne trouve pas de ressource?
**/
if(!this.perdu){
this.compteur++;
if (this.stock-100 >=0){
if(!(this.limitpop <=0)){
launchAgent(new Villageois(this.curent,this.al));
this.stock = this.stock-40;
this.limitpop --;}
else if (this.stock -150>= 0 && this.limitcont >0){
launchAgent(new Constructeur(this.curent,this.al));
this.stock = this.stock -150;
this.limitcont--;
}}
if (this.perdu()) {
for (int i =0 ; i<this.al.caserne.size() ; i++){
killAgent(this.al.caserne.get(i).objet);
}
for(int j = 0 ; j<this.al.demande_ressource.size() ; j++){
killAgent(this.al.demande_ressource.get(j).objet);
}
this.perdu = true;;
}
}
} | 8 |
public boolean executeDBScripts(File file, Statement stmt) throws IOException,SQLException {
boolean isScriptExecuted = false;
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
StringBuffer sb = new StringBuffer();
while ((str = in.readLine()) != null) {
sb.append(str + "\n ");
}
in.close();
stmt.executeUpdate(sb.toString());
isScriptExecuted = true;
} catch (Exception e) {
System.err.println("Failed to execute " + file.getName() +". The error is "+ e.getMessage());
}
return isScriptExecuted;
} | 2 |
public static GsAlbum[] parseAlbums(String data,Gs parent) {
Pattern re=Pattern.compile("\\{result:\\[(.*)\\}");
Matcher m=re.matcher(data);
GsAlbum[] res=new GsAlbum[1];
if(!m.find()) {
res[0]=null;
return res;
}
String realData=m.group(1);
int size=0;
int pos=0;
for(;;) {
int start=realData.indexOf('{',pos);
if(start==-1)
break;
int stop=realData.indexOf('}',start);
if(stop==-1)
break;
pos=stop;
GsAlbum album=new GsAlbum(realData.substring(start+1,stop),parent,stdReg,stdOrder);
if(!album.Ok)
continue;
if(size!=0) {
GsAlbum[] newArr=new GsAlbum[size+1];
System.arraycopy(res, 0, newArr, 0, size);
res=newArr;
}
res[size]=album;
size++;
}
return res;
} | 6 |
public static void checkAccuracyRealFFT_1D() {
System.out.println("Checking accuracy of 1D real FFT...");
for (int i = 0; i < sizes1D.length; i++) {
DoubleFFT_1D fft = new DoubleFFT_1D(sizes1D[i]);
double err = 0.0;
double[] a = new double[sizes1D[i]];
IOUtils.fillMatrix_1D(sizes1D[i], a);
double[] b = new double[sizes1D[i]];
IOUtils.fillMatrix_1D(sizes1D[i], b);
fft.realForward(a);
fft.realInverse(a, true);
err = computeRMSE(a, b);
if (err > eps) {
System.err.println("\tsize = " + sizes1D[i] + ";\terror = " + err);
} else {
System.out.println("\tsize = " + sizes1D[i] + ";\terror = " + err);
}
a = null;
b = null;
fft = null;
System.gc();
}
System.out.println("Checking accuracy of on 1D real forward full FFT...");
for (int i = 0; i < sizes1D.length; i++) {
DoubleFFT_1D fft = new DoubleFFT_1D(sizes1D[i]);
double err = 0.0;
double[] a = new double[2 * sizes1D[i]];
IOUtils.fillMatrix_1D(sizes1D[i], a);
double[] b = new double[2 * sizes1D[i]];
for (int j = 0; j < sizes1D[i]; j++) {
b[2 * j] = a[j];
}
fft.realForwardFull(a);
fft.complexInverse(a, true);
err = computeRMSE(a, b);
if (err > eps) {
System.err.println("\tsize = " + sizes1D[i] + ";\terror = " + err);
} else {
System.out.println("\tsize = " + sizes1D[i] + ";\terror = " + err);
}
a = null;
b = null;
fft = null;
System.gc();
}
System.out.println("Checking accuracy of 1D real inverse full FFT...");
for (int i = 0; i < sizes1D.length; i++) {
DoubleFFT_1D fft = new DoubleFFT_1D(sizes1D[i]);
double err = 0.0;
double[] a = new double[2 * sizes1D[i]];
IOUtils.fillMatrix_1D(sizes1D[i], a);
double[] b = new double[2 * sizes1D[i]];
for (int j = 0; j < sizes1D[i]; j++) {
b[2 * j] = a[j];
}
fft.realInverseFull(a, true);
fft.complexForward(a);
err = computeRMSE(a, b);
if (err > eps) {
System.err.println("\tsize = " + sizes1D[i] + ";\terror = " + err);
} else {
System.out.println("\tsize = " + sizes1D[i] + ";\terror = " + err);
}
a = null;
b = null;
fft = null;
System.gc();
}
} | 8 |
@Override
public boolean importData(TransferHandler.TransferSupport info)
{
GlobalLogger.getLogger().logp(Level.INFO, this.getClass().getName(),
"importData", "importData called.");
if (!info.isDrop())
{
return false;
}
// We need to get the drop location
DropLocation dl = info.getDropLocation();
// Get the task that is being dropped.
Transferable t = info.getTransferable();
Task taskRef;
try
{
taskRef = (Task) t.getTransferData(new DataFlavor(Task.class,
"Task"));
}
catch (Exception e)
{
return false;
}
if (taskRef == null)
{
GlobalLogger.getLogger().logp(Level.INFO,
this.getClass().getName(), "importData(TransferSupport)",
"Failed to get task from import data");
return false;
}
ArrayList<Task> tasks = Timeflecks.getSharedApplication().getTaskList()
.getTasks();
for (Task t1 : tasks)
{
if (t1.getId() == taskRef.getId())
{
taskRef = t1;
break;
}
}
// Now we just set the currently selected time from the dropLocation in
// the Task
Point selectedPoint = dl.getDropPoint();
// We know that it is a valid time, so we just got that time and now we
// are going to set it into the start time for the task.
if (!(info.getComponent() instanceof CalendarPanel))
{
return false;
}
CalendarPanel p = (CalendarPanel) (info.getComponent());
Date date = p.getDateForPoint(selectedPoint);
if (date == null)
{
// If this was invalid in any way, return false
return false;
}
// We actually got the date, so we are good to go
taskRef.setStartTime(date);
// Otherwise, let it keep its original duration
if (!taskRef.isScheduled())
{
taskRef.setDuration(1000 * 60 * 60); // Set the duration to 1 hr,
// which is 1000ms = 1s * 60
// = 1 min * 60 = 1hr
}
try
{
taskRef.saveToDatabase();
}
catch (Exception ex)
{
ExceptionHandler.handleDatabaseSaveException(ex, this.getClass()
.getName(), "importData", "2102");
}
// System.out.println("Time: " + taskRef.getStartTime());
Timeflecks.getSharedApplication().postNotification(
TimeflecksEvent.INVALIDATED_FILTERED_TASK_LIST);
// Timeflecks.getSharedApplication().postNotification(TimeflecksEvent.EVERYTHING_NEEDS_REFRESH);
return true;
} | 9 |
void up(int velocity) {
} | 0 |
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
} | 4 |
private boolean checkGuestForDoubleBooking(ArrayList<Booking> oldBookingList, Booking newBooking) {
boolean doubleBooking = false;
Date newCheckInDate = newBooking.getCheckInDate();
Date newCheckOutDate = newBooking.getCheckOutDate();
int i = 0;
while (doubleBooking == false && oldBookingList.size() > i) {
Date oldCheckInDate = oldBookingList.get(i).getCheckInDate();
Date oldCheckOutDate = oldBookingList.get(i).getCheckOutDate();
if ((newCheckInDate.before(oldCheckInDate) && newCheckOutDate.before(oldCheckInDate))
|| (newCheckInDate.after(oldCheckOutDate) && newCheckOutDate.after(oldCheckOutDate))
|| newCheckInDate.equals(oldCheckOutDate) || newCheckOutDate.equals(oldCheckInDate)) {
doubleBooking = false;
}
else {
doubleBooking = true;
}
i++;
}
return doubleBooking;
} | 8 |
private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed
boolean t = false;
try {
service.startClient();
t = true;
}catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "connexion impossible,verifiez votre connectivite au reseau");
//Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);
}
if (t) {
if (service.connectServer(login.getText(), password.getText())) {
state = true;
MessageUI message = new MessageUI(service);
service.getClient().setMsgUI(message);
message.setVisible(true);
this.dispose();
} else {
JOptionPane.showMessageDialog(this, "informations de connexion incorrectes");
}
}
// try {
// // TODO add your handling code here:
//
// String message= "Abalo";
// //String password= "nini";
//
// Client client= new Client();
// InterServeur serveur = client.getServeurObject();
// boolean con= serveur.getConnexion(login.getText(),password.getText(), client) ;
// if(con==true){
// MessageUI mess= new MessageUI();
// mess.setVisible(true);
// }else{
// JOptionPane.showMessageDialog(this, "L'un de vos données est erronées","Erreur", JOptionPane.ERROR_MESSAGE);
// }
//
// //client.receiveMessage(message, serveur);
//
// /*public boolean getConnexion(String login, String password, Object user) throws RemoteException {
//
// boolean b=ldapTemplate.authenticate("", "(uid="+login+")", password);
// if(b){
// userOnLine.put(user, dao.findByPrimaryKey(login));
// }
//
// return b;*/
// } catch (RemoteException ex) {
// Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);
// }
}//GEN-LAST:event_okActionPerformed | 3 |
private void sort() {
// skip sorting nonunique attributes
if(this.sorted || !this.getProperty().getIsUniqueAttribute())
return;
Collections.sort(this.results);
this.sorted=true;
} | 2 |
public double rank(Deck deck) {
// long startTime = System.currentTimeMillis();
// int count = 0;
int wins = 0;
int ties = 0;
int losses = 0;
for (int i = 0; i < deck.size(); ++i) {
for (int j = i + 1; j < deck.size(); ++j) {
for (int k = j + 1; k < deck.size(); ++k) {
for (int l = k + 1; l < deck.size(); ++l) {
Hand compHand = new Hand(deck.cardsAt(i, j, k, l));
int result = compareTo(compHand);
if (result > 0) {
wins++;
} else if (result < 0) {
losses++;
} else {
ties++;
}
}
}
}
}
/*
System.out.println(toString());
System.out.println("wins: " + wins);
System.out.println("ties: " + ties);
System.out.println("losses: " + losses);
System.out.println("total: " + (wins + ties + losses));
*/
// System.out.println("time: " + (System.currentTimeMillis() - startTime));
// return wins - losses;
return (double) wins / (wins + ties + losses);
} | 6 |
@Override
public void deleteMedType(MedTypeDTO medType) throws SQLException {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.delete(medType);
session.getTransaction().commit();
} catch (Exception e) {
System.err.println("Error while deleting medType!");
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
} | 3 |
public EncryptableObject decrypt(Key key) throws Exception{
String Algrithem;
if(key instanceof PrivateKey){Algrithem = "RSA";}
else{Algrithem = "AES";}
if(encrypted == null) {System.out.println("NULL");return null;}
Cipher decrypt = Cipher.getInstance(Algrithem);
decrypt.init(Cipher.DECRYPT_MODE, key);
ByteArrayInputStream bais = new ByteArrayInputStream(encrypted);
CipherInputStream cin=new CipherInputStream(bais, decrypt);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[2048];
int read=0;
while((read=cin.read(buf))!=-1) {//reading encrypted data
out.write(buf,0,read); //writing decrypted data
out.flush();
}
out.close();
cin.close();
bais.close();
return EncryptableObject.fromByteArray(out.toByteArray());
} | 3 |
private static final String escape(final String rawText) {
// defer initialization of a StringBuffer until we know we need one
StringBuffer buffer = null;
for (int i = 0; i < rawText.length(); i++) {
char c = rawText.charAt(i);
switch (c) {
case CommandManager.PARAMETER_START_CHAR:
case CommandManager.PARAMETER_END_CHAR:
case CommandManager.ID_VALUE_CHAR:
case CommandManager.PARAMETER_SEPARATOR_CHAR:
case CommandManager.ESCAPE_CHAR:
if (buffer == null) {
buffer = new StringBuffer(rawText.substring(0, i));
}
buffer.append(CommandManager.ESCAPE_CHAR);
buffer.append(c);
break;
default:
if (buffer != null) {
buffer.append(c);
}
break;
}
}
if (buffer == null) {
return rawText;
}
return buffer.toString();
} | 9 |
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"context/aopContext.xml");
Service1 service = ctx.getBean(Service1.class);
service.doIt("hoge");
} | 0 |
private void renderInfos(){
if(!renderInfos)return;
Font.render("FPS: " + Game.FPS, x + Game.SCREEN_WIDTH - 80, y + Game.SCREEN_HEIGHT - 15);
Font.render("BGM: " + Options.BGVolume, x + Game.SCREEN_WIDTH - 80, y + Game.SCREEN_HEIGHT - 45);
Font.render("FXM: " + Options.FXVolume, x + Game.SCREEN_WIDTH - 80, y + Game.SCREEN_HEIGHT - 60);
} | 1 |
@MCCommand(cmds = { "list" }, usage = PORT_LIST)
public boolean portList(Player p)
{
Collection<PlayerPort> ports = pc.getPlayerPortals(p);
if (ports == null || ports.isEmpty())
{
return sendMessage(p, "&eNo portals were found");
}
HashMap<World, List<PlayerPort>> wmap = new HashMap<World, List<PlayerPort>>();
for (PlayerPort port : ports)
{
List<PlayerPort> theports = wmap.get(port.getWorld());
if (theports == null)
{
theports = new ArrayList<PlayerPort>();
wmap.put(port.getWorld(), theports);
}
theports.add(port);
}
int maxPorts = PermissionController.getAvailablePorts(p);
for (World w : wmap.keySet())
{
sendMessage(p, "&e--- Portals in &6" + w.getName() + "&e ---");
List<PlayerPort> theports = wmap.get(w);
for (PlayerPort port : theports)
{
sendMessage(
p,
"&2" + port.getPortName() + " &e[&6"
+ port.getSourceStr() + "&e] -> ["
+ port.getDestStr() + "&e]"
+ port.getOptionString());
}
}
sendMessage(p, "&eYou are using &6" + ports.size() + "/" + maxPorts
+ "&e ports");
return true;
} | 6 |
public void adjustmentValueChanged (AdjustmentEvent e)
{
if (e.getSource() == Vertical)
{
switch (e.getAdjustmentType())
{
case AdjustmentEvent.UNIT_INCREMENT:
TD.verticalUp();
break;
case AdjustmentEvent.UNIT_DECREMENT:
TD.verticalDown();
break;
case AdjustmentEvent.BLOCK_INCREMENT:
TD.verticalPageUp();
break;
case AdjustmentEvent.BLOCK_DECREMENT:
TD.verticalPageDown();
break;
default:
int v = Vertical.getValue();
Vertical.setValue(v);
TD.setVertical(v);
return;
}
setVerticalScrollbar();
}
else if (e.getSource() == Horizontal)
{
Horizontal.setValue(TD.setHorizontal(Horizontal.getValue()));
}
} | 6 |
public MimeConverter(CWConfig config)
{
converters = new Hashtable<MIMEType,Class<? extends HTTPOutputConverter>>();
requestStats = new Hashtable<Class<? extends HTTPOutputConverter>, RequestStats>();
for(final String mimeTypeName : config.getFileConverts().keySet())
{
final MIMEType mimeType=MIMEType.All.getValueOf(mimeTypeName);
String className=config.getFileConverts().get(mimeTypeName);
if(className.indexOf('.')<0)
className="com.planet_ink.coffee_web.converters."+className;
try
{
@SuppressWarnings("unchecked")
final
Class<? extends HTTPOutputConverter> converterClass=(Class<? extends HTTPOutputConverter>) Class.forName(className);
registerConverter(mimeType, converterClass);
}
catch (final ClassNotFoundException e)
{
config.getLogger().severe("Converter Manager can't load "+className);
}
catch (final Exception e)
{
config.getLogger().severe("Converter Manager can't converter "+mimeTypeName);
}
}
} | 8 |
private ArrayList<Integer> generateActions(LongBoard state) {
ArrayList<Integer> result = new ArrayList<Integer>();
int middle = x/2;
//TODO choose random when x is even
if (state.isPlayable(middle)) {
result.add(middle);
}
for (int i=1; i <= x/2; i++) {
if(middle + i < x) {
if (state.isPlayable(middle + i)) {
result.add(middle + i);
}
}
if(middle - i > -1) {
if (state.isPlayable(middle - i)) {
result.add(middle - i);
}
}
}
return result;
} | 6 |
private int parseAnswer(String line) {
int questionAnswer = Integer.parseInt(line);
if ((questionAnswer < 1) || (questionAnswer > 16)) {
throw new IllegalArgumentException();
}
return questionAnswer;
} | 2 |
public void activePlayerDoAction(Action actionToDo)
throws InvalidActionException {
if (actionToDo == null)
throw new IllegalArgumentException("Action can't be null!");
actionToDo.doAction(getActivePlayer());
if (actionToDo instanceof EndTurnAction)
activePlayerEndTurn();
else if (getActivePlayer().getRemainingActions() <= 0)
activePlayerEndTurn();
} | 3 |
public static void print(TreeNode root) {
if (null != root) {
System.out.println(root.val + "[" + (null == root.left ? "null" : root.left.val) + "," + (null == root.right ? "null" : root.right.val) + "]");
print(root.left);
print(root.right);
}
} | 3 |
@Override
public void actionPerformed(ActionEvent a) {
if (a.getActionCommand().equals("close")) {
System.exit(0);
}
else if (automaton == null) {
setError("Es ist noch keine Simulation ausgewählt.");
return;
}
else if (a.getActionCommand().equals("step")) {
simulator.step();
}
else if (a.getActionCommand().equals("start")) {
start();
}
else if (a.getActionCommand().equals("stop")) {
stop();
}
else if (a.getActionCommand().equals("reset")) {
reset();
}
else if (a.getActionCommand().equals("resize")) {
Dimension c = panel.getGridSize();
if (c != null) {
resize(c);
}
}
else if (a.getActionCommand().equals("boundaries")) {
updateBounds();
}
} | 9 |
private boolean isClear(int direction) {
Coordinate c = getWallCoordinate(direction);
switch (direction) {
case Display.NORTH:
case Display.SOUTH:
return !WorldBackend.getCurrent()
.checkWall(c.x, c.y, Display.HORIZONTAL);
case Display.EAST:
case Display.WEST:
default:
return !WorldBackend.getCurrent()
.checkWall(c.x, c.y, Display.VERTICAL);
}
} | 4 |
private static long memusagerss() {
long rss = -1;
try {
Reader fr = new FileReader("/proc/self/status");
LineNumberReader lnr = new LineNumberReader(fr);
String line;
while ((line = lnr.readLine()) != null) {
int idx = line.indexOf(':');
if (idx < 0) continue;
String name = line.substring(0, idx);
idx++;
while (idx < line.length() && Character.isWhitespace(line.charAt(idx))) idx++;
String value = line.substring(idx, line.length());
if (name.equals("VmRSS")) {
rss = Utility.atoix(value);
break;
}
}
fr.close();
} catch (Exception e) {
}
return rss;
} | 6 |
public T openForRead() {
Transaction me = Transaction.getLocal();
switch (me.getStatus()) {
case ACTIVE:
Locator locator = this.locator.get();
if (me == locator.owner) {
return locator.current;
}
Locator newLocator = new Locator(me);
while (!Thread.currentThread().isInterrupted()) {
Locator oldLocator = this.locator.get();
Transaction currentOwner = oldLocator.owner;
switch (currentOwner.getStatus()) {
case COMMITTED:
newLocator.current = oldLocator.current;
break;
case ABORTED:
newLocator.current = oldLocator.backup;
break;
case ACTIVE:
ContentionResolver.getLocal().resolve(me, currentOwner);
continue;
}
if (this.locator.compareAndSet(oldLocator, newLocator)) {
return newLocator.current;
}
}
throw new AbortedException();
case COMMITTED:
return openOutsideTransaction();
case ABORTED:
throw new AbortedException();
default:
throw new TransactionFailedException();
}
} | 9 |
public ImportanceTest() {
Data d;
try {
d = Reader.getDataFromFile(new File("files/restaurant.arff"));
System.out.println("Importance function:");
System.out.println("B(0.99) = " + Importance.B(0.99));
System.out.println("Gain(Patrons) = "
+ Importance.importance("Pat", d.getExamples(),
d.getattributeValues()));
System.out.println("Gain(Type) = "
+ Importance.importance("Type", d.getExamples(),
d.getattributeValues()));
System.out.println("Information Gain Ratio:");
System.out.println("Gain(Patrons) = "
+ Importance2.informationGainRatio("Pat", d.getExamples(),
d.getattributeValues(), d.getGoalAttribute()));
System.out.println("Gain(Type) = "
+ Importance2.informationGainRatio("Type", d.getExamples(),
d.getattributeValues(), d.getGoalAttribute()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 1 |
protected void sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header, int size) {
if (!headerAlreadySent(header, "content-length")) {
pw.print("Content-Length: "+ size +"\r\n");
}
} | 1 |
public static boolean performLogin(String uname, String pword) {
//Set username and password
if (uname != null) AccountName = uname;
if (pword != null) Password = pword;
//Initialize request and result objects
YggdrasilRequest request = new YggdrasilRequest(AccountName, Password);
YggdrasilResult result = null;
//Submit the login request
try {
result = request.send();
} catch (Exception ex) {
isLoggedIn = false;
GlobalDialogs.showNotification("Login failed: (" + ex.getClass().getSimpleName() + ") " + ex.getMessage());
return false;
}
if (result.wasSuccessful) {
isLoggedIn = true;
Username = result.Username;
UUID = result.UUID;
AccessToken = result.AccessToken;
return true;
} else {
isLoggedIn = false;
Username = null;
UUID = null;
AccessToken = null;
GlobalDialogs.showNotification("Login failed: " + result.ErrorDescription);
return false;
}
} | 4 |
@Override
public Vector2D calculateGravity(double elapsedTime) {
LinkedList<Sprite>sprites = parent.getParent().parent.getMap().getSprites();
Vector2D force = new Vector2D(0,0);
for(int i = 0; i < sprites.size(); i++){ // Add all sprites that are planets
if(sprites.get(i) instanceof Planet){
Planet p = (Planet)sprites.get(i);
double g = .08;
double pMass = p.dMass;
double sMass = parent.getMass();
Vector2D pCenter = p.getPosition().plus(new Vector2D(p.getWidth()/2, p.getHeight()/2));
Vector2D sCenter = parent.getPosition().plus(new Vector2D(parent.getWidth()/2, parent.getHeight()/2));
double distanceSQ = sCenter.distanceSq(pCenter); //the new vector offsets the position so we orbit around the center of the planet
double distance = sCenter.distance(pCenter);
double pRadius = p.circle.getBounds().height/2;
//this part allow the ship to settle into the planet and stop
if(distance > 35 && distance < pRadius-150){ // don't calculate if too close, or too far
Vector2D preForce = new Vector2D(0,0);
preForce = (pCenter.minus(sCenter));
preForce = preForce.scalarMult(g * pMass * sMass);
preForce = preForce.scalarDiv(distanceSQ);
force = force.plus(preForce);
}else if(distance <= 9){
parent.setVelocity(parent.getVelocity().scalarMult(-.5));
}
}
}
force = force.scalarMult(elapsedTime/1000);
return force;
} | 5 |
public static String lihtneSundmus() {
String tekst = "";
if (Math.random() < lihtsaSundmuseVoimalus) {
int sundmus = random(0, lihtsadSundmused.length - 1);
tekst = lihtsadSundmused[sundmus][0];
String tyyp = lihtsadSundmused[sundmus][1];
int arv = Integer.parseInt(lihtsadSundmused[sundmus][2]);
arv = (arv < 0) ? random(arv, 0) : random(0, arv);
if (tyyp == "pudel")
pudeleid += arv;
if (pudeleid < 0)
pudeleid = 0;
if (tyyp == "raha")
raha += arv;
if (raha < 0)
raha = 0;
}
return tekst;
} | 6 |
private static String getStringFromDocument(Document doc) {
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
} catch (TransformerException ex) {
ex.printStackTrace();
return null;
}
} | 1 |
private void updatePurchasableCards() {
for(Component component : purchasable.getComponents()) {
if(component instanceof PurchasableCardPanel) {
if(((PurchasableCardPanel) component).getData().isInMortgage()) {
((PurchasableCardPanel) component)
.setBorder(BorderFactory.createLineBorder(new Color(218, 0, 0), 3));
} else {
((PurchasableCardPanel) component)
.setBorder(BorderFactory.createLineBorder(new Color(0, 156, 0), 3));
}
}
}
} | 3 |
void telecharger(String ip, int port, String key, boolean [] masque) throws UnknownServiceException, CharConversionException {
int i = 0 , max;
String reponse = "", question = "";
List<String[]> reponse_partielle;
boolean bool;
Fichier file = (Fichier)_hash.get(key);
while (i < masque.length) {
reponse = "";
question = new String("getpieces " + key + " [");
max = 25; // Combien par combien je télécharge
bool = false;
for (int j = i; j<masque.length & 0<max ; j++ ){
i++;
max--;
if (masque[j]) {
question += j + " ";
bool = true;
}
}
question = question.trim() + "]";
if (bool){
if (file == null)
System.out.println("Gros problème !");
reponse_partielle = demanderPiece(ip, port, question, 5, 1000, (int) file.getTaille() );
enregistre(file, reponse_partielle);
System.out.println(file.getPourcentage() + "%");
// *TODO* à virer ?
try{Thread.sleep(100);}
catch(InterruptedException ite){
ite.printStackTrace();
}
}
}
} | 6 |
public static void getBids(PlayerModel playerModel[], PlayerDecider player[], int dealerIndex, int redScore, int blueScore, MellowServerMiddleMan middleMan) {
int prevBids[] = new int[4];
int currentPreviousBid[];
int currentBid;
int indexPlayerAction;
int numChances = 0;
for(int i=0; i<4; i++) {
currentPreviousBid = new int[i];
for(int j=0; j<i; j++) {
currentPreviousBid[j] = prevBids[i];
}
indexPlayerAction = (dealerIndex + 1+ i)%4;
currentBid = -1;
numChances = 0;
middleMan.sendMessageToGroup(playerModel[indexPlayerAction].getPlayerName() +"'s turn to bid:");
while ( true ) {
middleMan.sendMessageToPlayer(playerModel[indexPlayerAction].getPlayerName(), "What's your bid?");
currentBid = player[indexPlayerAction].getBid(playerModel[indexPlayerAction].getHand(), currentPreviousBid, dealerIndex);
if(currentBid < 0 || currentBid > 13) {
numChances++;
if(middleMan.isReadingReplay()) {
throw new RuntimeException("Game stopped suddenly in bidding phase" );
} else {
middleMan.sendMessageToPlayer(player[indexPlayerAction].getName(), "Bid something between 0 and 13 inclusively!");
}
} else if(numChances >= 3) {
middleMan.sendMessageToPlayer(player[indexPlayerAction].getName(), "to player: You default bid to 1. (idiot)");
currentBid = 1;
} else {
break;
}
}
middleMan.sendMessageToPlayer(playerModel[indexPlayerAction].getPlayerName(), "Thank you.");
//current Bid should be between 0 and 13 inclusively.
if(currentBid == 0) {
playerModel[indexPlayerAction].setMellow();
} else {
playerModel[indexPlayerAction].setNumBid(currentBid);
}
middleMan.sendMessageToGroup(playerModel[indexPlayerAction].getPlayerName() +": " + currentBid);
middleMan.recordCommand(playerModel[indexPlayerAction].getPlayerName() +": " + currentBid + "\n");
}
} | 8 |
public static void cadastrarEvento() {
Evento evento = new Evento();
Secao secao = new Secao();
EventoService eventoservice = new EventoServiceImpl();
SecaoService secaoservice = new SecaoServiceImpl();
IngressoService ingressoservice = new IngressoServiceImpl();
Scanner input = new Scanner(System.in);
System.out.println("--------------------------------------------------------------------");
System.out.println("------------------------ CADASTRAR EVENTOS -------------------------");
System.out.println("--------------------------------------------------------------------");
System.out.print("Nome do evento: ");
String nome = input.nextLine();
evento.setNome(nome);
System.out.print("Dia: ");
String dia = input.nextLine();
System.out.print("Mês: ");
String mes = input.nextLine();
System.out.print("Ano: ");
String ano = input.nextLine();
String data = ano + "/" + mes + "/" + dia;
evento.setDataEvento(data);
eventoservice.cadastrarEvento(evento);
System.out.print("Informe o número de seções do evento: ");
String countsecao = input.nextLine();
int count = Integer.parseInt(countsecao);
int i = 0;
while(i<count){
System.out.print("Nome da seção: ");
String nomesecao = input.nextLine();
secao.setNome(nomesecao);
System.out.print("Valor: ");
String v = input.nextLine();
Double valor = Double.parseDouble(v);
secao.setValor(valor);
secaoservice.cadastrarSecao(secao, evento);
System.out.print("Número de ingressos da sessão: ");
String c = input.nextLine();
int countingressos = Integer.parseInt(c);
int j = 0;
while(j<countingressos){
ingressoservice.cadastrarIngresso(secao, evento);
j++;
}
i++;
}
menuEventos();
} | 2 |
public static double points_for_enemy(int fieldID, int ID) {
if (BrickGame.bricks.size() == 1) {
return 0;
}
double points = 0;
for (int i = 0; i < BrickGame.bricks.size(); i++) {
if (i != ID) {
points = points
+ BrickGame.bricks.get(ID).distance_from_enemy
* getManhattanDistance(listFields.get(fieldID)[0],
listFields.get(fieldID)[1],
BrickGame.bricks.get(i).pos_x,
BrickGame.bricks.get(i).pos_y);
}
}
return points / (BrickGame.bricks.size() - 1);
} | 3 |
private void btnNewFolderActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnNewFolderActionPerformed
{//GEN-HEADEREND:event_btnNewFolderActionPerformed
String thename = JOptionPane.showInputDialog(this, "Enter the name of the new folder:", "WiiExplorer", JOptionPane.QUESTION_MESSAGE);
if (thename == null || thename.trim().isEmpty()) return;
if (thename.contains("/") || thename.contains("\\"))
{
JOptionPane.showMessageDialog(this, "Invalid name entered. It must not contain slashes.", "WiiExplorer", JOptionPane.ERROR_MESSAGE);
return;
}
String pathtoaddin = selectedPath;
if (pathtoaddin.isEmpty())
pathtoaddin = archive.getRoot();
else if (archive.fileExists(pathtoaddin))
pathtoaddin = pathtoaddin.substring(pathtoaddin.lastIndexOf("/") + 1);
String fullpath = pathtoaddin + "/" + thename;
FileTreeNode pnode = treeNodes.get(pathtoaddin);
FileTreeNode newnode = new FileTreeNode(archive, fullpath);
int c;
for (c = 0; c < pnode.getChildCount(); c++)
{
String thispath = (String)((FileTreeNode)pnode.getChildAt(c)).toString();
if (thispath.compareTo(thename) >= 0) break;
}
pnode.insert(newnode, c);
treeNodes.put(fullpath, newnode);
DefaultTreeModel listmodel = (DefaultTreeModel)tvFileView.getModel();
listmodel.nodesWereInserted(pnode, new int[] {c});
archive.createDirectory(pathtoaddin, thename);
trySave();
}//GEN-LAST:event_btnNewFolderActionPerformed | 8 |
@Override
public void run() {
InetAddress ia = null;
try {
ia = InetAddress.getByName("localhost");
} catch (UnknownHostException e2) {
e2.printStackTrace();
}
try (DatagramSocket dSocket = new DatagramSocket();) {
try {
String command = "Date:";
byte buffer[] = null;
buffer = command.getBytes();
byte answer[] = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length, ia,6667);
dSocket.send(packet);
packet = new DatagramPacket(answer, answer.length);
dSocket.receive(packet);
controllerCoustomerShop.updateTitle(new String(packet.getData(), 0, packet.getLength()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (SocketException e1) {
e1.printStackTrace();
}
} | 5 |
private void results()
{
if (p1.getHP() < 0)
{
p1.setHP(0);
}
if (p2.getHP() < 0)
{
p2.setHP(0);
}
game.updateP1(getPlayerStats(p1) + getPlayerSkills(p1));
game.updateP2(getPlayerStats(p2) + getPlayerSkills(p2));
game.removeSkills();
if (p1.isAlive())
{
states.setPlayerOneWin();
game.addText(p2.getName() + " has been slain!\n" + p1.getName() + " wins!");
}
else if (p2.isAlive())
{
states.setPlayerTwoWin();
game.addText(p1.getName() + " has been slain!\n" + p2.getName() + " wins!");
}
} | 4 |
private void addListeners() {
reciever.addListener("/input", new OSCListener() {
@Override
public void acceptMessage(Date time, OSCMessage message) {
System.out.println((String)message.getArguments()[0]);
}
});
reciever.addListener("/gridinput", new OSCListener() {
@Override
public void acceptMessage(Date time, OSCMessage message) {
String mes = ((String)message.getArguments()[0]);
//mes.concat("\n");
mes = mes + "Z";
sendStatus("Solving User Puzzle... " + mes);
Parser parser = new Parser(mes);
if(parser.fileCanCreateGrid()){
currentPuzzle = parser.createGrid();
sendToGrid(currentPuzzle.gridToString());
Solver s = new Solver();
//Grid solved = s.bruteForce(currentPuzzle);
long timeOne = System.currentTimeMillis();
Grid solved = s.BFS(currentPuzzle);
long timeTwo = System.currentTimeMillis();
long timeInMilli = timeTwo - timeOne;
if(solved != null){
solved.previousGrids.add(solved);
sendStatus("Solved User Puzzle");
sendToGrid(solved.gridToString());
sendToCurrentStep(solved.previousGrids.size());
sendToMaxSteps(solved.previousGrids.size());
sendToTimeToSolve(timeInMilli);
currentPuzzle = solved;
}else{
sendStatus("This puzzle can't be solved.");
}
} else {
sendStatus("Input not valid. ");
}
}
});
reciever.addListener("/presetnumber", new OSCListener() {
@Override
public void acceptMessage(Date time, OSCMessage message) {
int mes = ((Integer)message.getArguments()[0]);
//mes.concat("\n");
//mes = mes + "Z";
sendStatus("Solving Preset Number " + mes +"...");
Parser parser = new Parser(GridStrings.getGrid(mes-1));
if(parser.fileCanCreateGrid()){
currentPuzzle = parser.createGrid();
sendToGrid(currentPuzzle.gridToString());
Solver s = new Solver();
//Grid solved = s.bruteForce(currentPuzzle);
long timeOne = System.currentTimeMillis();
Grid solved = s.BFS(currentPuzzle);
long timeTwo = System.currentTimeMillis();
long timeInMilli = timeTwo - timeOne;
if(solved != null){
solved.previousGrids.add(solved);
sendStatus("Solved Preset Number " + mes);
sendToGrid(solved.gridToString());
sendToCurrentStep(solved.previousGrids.size());
sendToMaxSteps(solved.previousGrids.size());
sendToTimeToSolve(timeInMilli);
currentPuzzle = solved;
}else{
sendStatus("This puzzle can't be solved. ");
}
} else {
sendStatus("Input not valid ");
}
}
});
reciever.addListener("/stepnumber", new OSCListener() {
@Override
public void acceptMessage(Date time, OSCMessage message) {
int mes = ((Integer)message.getArguments()[0]);
//mes.concat("\n");
//mes = mes + "Z";
if(currentPuzzle.previousGrids.size()<mes){
sendStatus("Index Out Of Bounds!");
return;
}
System.out.println("Showing Step Number " + mes);
sendToCurrentStep(mes);
sendToGrid(currentPuzzle.previousGrids.get(mes-1).gridToString());
}
});
} | 5 |
public static void main(String[] args) {
new GUI();
} | 0 |
public void remove(int n) {
this.filled-=elements.get(n).getValue();
this.elements.remove(n);
} | 0 |
public AnnotationVisitor visitParameterAnnotation(
int parameter,
String desc,
boolean visible)
{
AnnotationVisitor av = mv.visitParameterAnnotation(parameter,
remapper.mapDesc(desc),
visible);
return av == null ? av : new RemappingAnnotationAdapter(av, remapper);
} | 1 |
static public String toHanyuPinyinString(String str,
HanyuPinyinOutputFormat outputFormat, String seperater)
throws BadHanyuPinyinOutputFormatCombination
{
StringBuffer resultPinyinStrBuf = new StringBuffer();
for (int i = 0; i < str.length(); i++)
{
String mainPinyinStrOfChar = getFirstHanyuPinyinString(str.charAt(i), outputFormat);
if (null != mainPinyinStrOfChar)
{
resultPinyinStrBuf.append(mainPinyinStrOfChar);
if (i != str.length() - 1)
{ // avoid appending at the end
resultPinyinStrBuf.append(seperater);
}
} else
{
resultPinyinStrBuf.append(str.charAt(i));
}
}
return resultPinyinStrBuf.toString();
} | 3 |
public void generateHelper(List<String> result, String s, int left, int right) {
if (left > right) {
return;
}
if (left == 0 && right == 0) {
result.add(s);
return;
}
if (left > 0) {
generateHelper(result, s + "(", left - 1, right);
}
if (right > 0) {
generateHelper(result, s + ")", left, right - 1);
}
} | 5 |
public void increasePrice(int percentage) {
List<Product> products = productDao.getProductList();
if (products != null) {
for (Product product : products) {
double newPrice = product.getPrice().doubleValue()
* (100 + percentage) / 100;
product.setPrice(newPrice);
productDao.saveProduct(product);
}
}
} | 2 |
public void write(char[] b, int off, int len) throws IOException {
if (!initialized) {
area.setText("");
initialized = true;
}
// /#ifdef AWT10
// / area.appendText(new String(b, off, len));
// /#else
area.append(new String(b, off, len));
// /#endif
} | 1 |
@Override
public void run() {
while(countDown-- > 0) {
System.out.print(status());
Thread.yield();
}
} | 1 |
public static ArrayList <IngredientData> loadData() {
File load = new File("resources/files/IngredientData/");
Gson loader = new Gson();
ArrayList <IngredientData> res = new ArrayList <IngredientData>();
for (File f : load.listFiles()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
IngredientData read = null;
try {
read = loader.fromJson(br.readLine(), IngredientData.class);
res.add(read);
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return res;
} | 6 |
@EventHandler
public void closeTable(PlayerMoveEvent e) {
Player p = e.getPlayer();
String name = p.getName();
if (Casino.plugin.getDataHandler().getUserList().contains(name))
for (BlackjackTable t : Casino.plugin.getDataHandler().getTableList()) {
if ((!t.getInUse()) ||
(!t.getUser().equals(name)))
continue;
double x1 = t.getBlock().getX();
double y1 = t.getBlock().getZ();
double x2 = p.getLocation().getX();
double y2 = p.getLocation().getZ();
x2 -= x1;
x2 *= x2;
y2 -= y1;
y2 *= y2;
x2 += y2;
double d = Math.sqrt(x2);
if (d >= 2.2D)
t.closeTable(p);
}
} | 5 |
public static void main(String[] args){
System.out.println(0xFFFF);
System.out.println(0_345_345);
System.out.println(0B1111_1111_1101);
int[][] arr = new int[4][4];
for(int i = 0; i<arr.length; i++)
for(int j = 0; j<arr[i].length; j++)
arr[i][j]= (i!=0 ? arr[i-1][arr[i].length-1] +j : j) + (i>1 ? 1:i);
for(int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j]+(j%arr[i].length==arr[i].length-1 ? "\n" : " "));
String hello = "Hello", lo = "lo";
System.out.println(hello == ("Hel" + lo).intern()+ " ");
// System.out.println((Other.hello == hello) + " ");
// System.out.println((other.Other.hello == hello) + " ");
} | 7 |
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.