text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public Database(String databasePath) throws SQLException {
try {
Class.forName("org.hsqldb.jdbcDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
connection = DriverManager.getConnection("jdbc:hsqldb:file:" + databasePath, "SA", "");
Statement delayStmt = connection.createStatement();
try {
delayStmt.execute("SET WRITE_DELAY FALSE");
} finally {
delayStmt.close();
}
connection.setAutoCommit(false);
Statement stmt1 = connection.createStatement();
try {
String messagesTable = "CREATE TABLE messages(nick VARCHAR(255) NOT NULL,"
+ "message VARCHAR(4096) NOT NULL,"
+ "timeposted BIGINT NOT NULL)";
stmt1.execute(messagesTable);
} finally {
stmt1.close();
}
Statement stmt2 = connection.createStatement();
try {
String statisticsTable = "CREATE TABLE statistics(key VARCHAR(255), value INT)\n"
+ "INSERT INTO statistics(key, value) VALUES ('Total messages', 0)\n"
+ "INSERT INTO statistics(key, value) VALUES ('Total logins', 0)";
stmt2.execute(statisticsTable);
} finally {
stmt2.close();
}
connection.commit();
} | 1 |
public boolean isInVillage(Point2D p)
{
if (p.getX() > getSideLength() || p.getX() < 0 || p.getY() > getSideLength() || p.getY() < 0)
return false;
return true;
} | 4 |
protected void scanPCData(StringBuffer data)
throws IOException
{
for (;;) {
char ch = this.readChar();
if (ch == '<') {
ch = this.readChar();
if (ch == '!') {
this.checkCDATA(data);
} else {
this.unreadChar(ch);
return;
}
} else if (ch == '&') {
this.resolveEntity(data);
} else {
data.append(ch);
}
}
} | 4 |
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
Point point = snapMouseToBoard(arg0.getX(), arg0.getY());
if (availableMoves != null) {
for (Move m : availableMoves) {
if (m.getEndingTile().getX() == point.x
&& m.getEndingTile().getY() == point.y) {
if (m.getType() == Move.Type.MOVE_PROMOTE) {
ChessPiece.Type type = promptForPieceType();
CompoundMove move = (CompoundMove) m;
MoveTransform transform = (MoveTransform) move
.getMoveB();
transform.setTransformation(type);
}
availableMoves = null;
hasSelectedPiece = false;
game.applyMove(m);
this.recalculateAllAvailableMoves();
return;
}
}
hasSelectedPiece = false;
availableMoves = null;
}
if (game.getChessBoard().isValidLocation(point.x, point.y)
&& game.getChessBoard().hasPieceAtLocation(point.x, point.y)
&& game.getChessBoard().getPiece(point.x, point.y).getPlayer() == game
.getCurrentTurn()) {
lastSelectedX = point.x;
lastSelectedY = point.y;
hasSelectedPiece = true;
availableMoves = game.generateMovesForTile(game.getChessBoard()
.getTile(lastSelectedX, lastSelectedY));
}
} | 8 |
public void reset()
{
for (int i=0; i<BANDS; i++)
{
settings[i] = 0.0f;
}
} | 1 |
public String consumeAttributeKey() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny('-', '_', ':')))
pos++;
return queue.substring(start, pos);
} | 3 |
public void nPairsElimination()
{
ArrayList<ArrayList<Integer>> uniqueNPairs = getUniqueNPairs();
for(int i=0; i<9; i++)
{
for(int j=0; j<uniqueNPairs.size(); j++)
{
if(!cells[i].getPosNumbers().equals(uniqueNPairs.get(j)))
{
cells[i].removePosNumbers(uniqueNPairs.get(j));
}
}
}
} | 3 |
private void fall(Level var1, int var2, int var3, int var4) {
int var11 = var2;
int var5 = var3;
int var6 = var4;
while(true) {
int var8 = var5 - 1;
int var10;
LiquidType var12;
if(!((var10 = var1.getTile(var11, var8, var6)) == 0?true:((var12 = Block.blocks[var10].getLiquidType()) == LiquidType.WATER?true:var12 == LiquidType.LAVA)) || var5 <= 0) {
if(var5 != var3) {
if((var10 = var1.getTile(var11, var5, var6)) > 0 && Block.blocks[var10].getLiquidType() != LiquidType.NOT_LIQUID) {
var1.setTileNoUpdate(var11, var5, var6, 0);
}
var1.swap(var2, var3, var4, var11, var5, var6);
}
return;
}
--var5;
}
} | 8 |
public final EsperParser.assign_return assign() throws RecognitionException {
EsperParser.assign_return retval = new EsperParser.assign_return();
retval.start = input.LT(1);
Object root_0 = null;
Token ASSIGN24=null;
Token IDENTIFIER25=null;
EsperParser.expr_return expr26 =null;
Object ASSIGN24_tree=null;
Object IDENTIFIER25_tree=null;
try {
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:45:8: ( ASSIGN ^ IDENTIFIER expr )
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:45:10: ASSIGN ^ IDENTIFIER expr
{
root_0 = (Object)adaptor.nil();
ASSIGN24=(Token)match(input,ASSIGN,FOLLOW_ASSIGN_in_assign364);
ASSIGN24_tree =
(Object)adaptor.create(ASSIGN24)
;
root_0 = (Object)adaptor.becomeRoot(ASSIGN24_tree, root_0);
IDENTIFIER25=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_assign367);
IDENTIFIER25_tree =
(Object)adaptor.create(IDENTIFIER25)
;
adaptor.addChild(root_0, IDENTIFIER25_tree);
pushFollow(FOLLOW_expr_in_assign369);
expr26=expr();
state._fsp--;
adaptor.addChild(root_0, expr26.getTree());
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} | 1 |
public int characterAt(int at) throws JSONException {
int c = get(at);
if ((c & 0x80) == 0) {
return c;
}
int character;
int c1 = get(at + 1);
if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1;
if (character > 0x7F) {
return character;
}
} else {
int c2 = get(at + 2);
character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF
&& (character < 0xD800 || character > 0xDFFF)) {
return character;
}
}
throw new JSONException("Bad character at " + at);
} | 8 |
@Override
public void keyPressed(KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.VK_LEFT:
setOpen(false, getTreeContainerRows(mSelectedRows, event.isAltDown()));
break;
case KeyEvent.VK_RIGHT:
setOpen(true, getTreeContainerRows(mSelectedRows, event.isAltDown()));
break;
case KeyEvent.VK_UP:
keyScroll(selectUp(event.isShiftDown()));
break;
case KeyEvent.VK_DOWN:
keyScroll(selectDown(event.isShiftDown()));
break;
case KeyEvent.VK_HOME:
keyScroll(selectToHome(event.isShiftDown()));
break;
case KeyEvent.VK_END:
keyScroll(selectToEnd(event.isShiftDown()));
break;
default:
return;
}
event.consume();
} | 6 |
public static void applyDamage(Actor target, double amount, DamageType type) {
switch (type) {
case SLASHING:
target.damage(amount - target.characterSheet.armor);
break;
case BASHING:
break;
case PIERCING:
break;
case ELEMENT_FIRE://Fire resist specific stuff would go here
target.damage(amount);
break;
}
} | 4 |
public String getAttributeDefaultValue(String name, String aname)
{
Object attribute[] = getAttribute(name, aname);
if (attribute == null) {
return null;
} else {
return (String) attribute[1];
}
} | 1 |
public static void MSDsort(String[] a) {
String[] aux = new String[a.length];
msdSort(a, aux, 0, a.length - 1, 0);
} | 0 |
protected void execute() {
//Check if the climber is at the end
checkSwitches();
double speed = 0;
if (m_isRising){
//Use full speed on the upstroke
//if (Timer.getFPGATimestamp()-m_startRise < 0.6*RISE_STROKE_LENGTH){
speed = 1;
//}else{
// speed = .8;
//}
System.out.println("Raising for next pull");
}else{
//Go at 80% speed until the pole is grabbed
if (!m_grabbedPole){
speed = -.8;
if (Robot.ratchetClimber.getCurrent() > 12.5 && Timer.getFPGATimestamp() - m_startDescent > 0.5){
m_grabbedPole = true;
}
System.out.println("Waiting to grab the pole");
}else{
//After the pole is grabbed, start a timer. Use the timer as Y in the function y/5 + .7 to get the speed; creates a ramp effect
if (m_timer == null){
m_timer = new Timer();
m_timer.start();
System.out.println("Grabbed the pole");
}
double timerSpeed = (m_timer.get()/5) + .7;
if ((timerSpeed) < 1.0){
speed = -timerSpeed;
System.out.println("Climbing with speed of " + -timerSpeed);
}else{
speed = -1;
System.out.println("Climbing with full speed");
}
}
speed = speed*Robot.oi.getLeftThrottle();
}
Robot.ratchetClimber.driveMotor(speed);
} | 6 |
public void playRound() {
previousBoard = DeltaBoard.cloneBoard(board);
// Checks if user's king is in check before moving
if (isChecked(userColor, getXOfKing(userColor), getYOfKing(userColor), true)){ // Check whether the user's king is in check prior to user's turn
System.out.println("Your King is in check!");
}
kingPreviouslyChecked = ((King)board.get(getXOfKing(userColor),getYOfKing(userColor))).isChecked(); // Keeps track of whether the user's king was checked before this turn
// getUserChoice() returns boolean signifying if iteration of the loop should be skipped
if (getUserChoice()){
return;
}
// handleCastle() returns boolean signifying if iteration of the loop should be skipped
if (handleCastle()){
return;
}
// handleEnPassant() returns boolean signifying if iteration of the loop should be skipped
if (handleEnPassant()){
return;
}
// handlePawnJump() returns boolean signifying if iteration of the loop should be skipped
if (handlePawnJump()){
return;
}
// Regular Move: Checks if king is in check after move
if (validMove(myXCoor, myYCoor, targXCoor, targYCoor, userColor, true)) {
// Case when the resulting position does NOT result in a check on the user's king
if (chosen.getType().equals("PAWN")){
handlePawnPromotion(targXCoor, targYCoor);
}
if (target == null) { // Print feedback information to user
System.out.println(clearScreen() + "Successful move: " + chosen + " (" + myXCoor + "," + myYCoor + ") to (" + targXCoor + "," + targYCoor + ").\n");
}
else { // Print feedback information to user
System.out.println(clearScreen() + "Successful kill: " + chosen + " (" + myXCoor + "," + myYCoor + ") takes " + target + " (" + targXCoor + "," + targYCoor + ").\n");
}
advanceRound();
}
else{
loopRound();
}
} | 8 |
@Override
public boolean isCellEditable(EventObject anEvent)
{
// Normally: from context menu -> Rename
if (anEvent == null)
return beforeEdition();
// Normally: from F2 press
if (anEvent.getClass() == java.awt.event.ActionEvent.class)
return beforeEdition();
if (anEvent.getClass() == MouseEvent.class)
{
MouseEvent e = (MouseEvent) anEvent;
if (e.getClickCount() == 2)
new FilePlayer(getSelected()).execute();
}
return false;
} | 4 |
public void breakCheck(int state){
if(state == ItemEvent.SELECTED)
linePattern = true;
else
linePattern = false;
if(selectedDrawings.size() != 0){
for(int i=0;i<selectedDrawings.size();i++){
selectedDrawings.elementAt(i).setBreak(linePattern);
}
}
} | 3 |
public void increaseShieldEnergy() {
if(leftOverEnergy>0) {
shieldEnergy++;
leftOverEnergy--;
for(int i=0; i < ship.shields.size(); i++) {
ship.shields.get(i).setStrength(shieldEnergy*100);
}
}
} | 2 |
public void selectAttributesCVSplit(Instances split) throws Exception {
double[][] attributeRanking = null;
// if the train instances are null then set equal to this split.
// If this is the case then this function is more than likely being
// called from outside this class in order to obtain CV statistics
// and all we need m_trainIstances for is to get at attribute names
// and types etc.
if (m_trainInstances == null) {
m_trainInstances = split;
}
// create space to hold statistics
if (m_rankResults == null && m_subsetResults == null) {
m_subsetResults = new double[split.numAttributes()];
m_rankResults = new double[4][split.numAttributes()];
}
m_ASEvaluator.buildEvaluator(split);
// Do the search
int[] attributeSet = m_searchMethod.search(m_ASEvaluator,
split);
// Do any postprocessing that a attribute selection method might
// require
attributeSet = m_ASEvaluator.postProcess(attributeSet);
if ((m_searchMethod instanceof RankedOutputSearch) &&
(m_doRank == true)) {
attributeRanking = ((RankedOutputSearch)m_searchMethod).
rankedAttributes();
// System.out.println(attributeRanking[0][1]);
for (int j = 0; j < attributeRanking.length; j++) {
// merit
m_rankResults[0][(int)attributeRanking[j][0]] +=
attributeRanking[j][1];
// squared merit
m_rankResults[2][(int)attributeRanking[j][0]] +=
(attributeRanking[j][1]*attributeRanking[j][1]);
// rank
m_rankResults[1][(int)attributeRanking[j][0]] += (j + 1);
// squared rank
m_rankResults[3][(int)attributeRanking[j][0]] += (j + 1)*(j + 1);
// += (attributeRanking[j][0] * attributeRanking[j][0]);
}
} else {
for (int j = 0; j < attributeSet.length; j++) {
m_subsetResults[attributeSet[j]]++;
}
}
m_trials++;
} | 7 |
protected void refreshAllCubes() {
if(this.cube != null)
{
for(int face = 0; face < this.cube.getNumFaces(); face++)
{
for(int row = 1; row <= this.cube.getDimension(); row++)
{
for(int column = 1; column <= this.cube.getDimension(); column++)
{
for(Window w:images){
if(face == w.face && row == w.row && column== w.col){
if(!w.isDiscovered){
((MatchingPatternCube)this.cube).showMeshOnFace(face, row, column,"images/match/background.png");
}
w.isOpen = false;
}
}
}
}
}
}
} | 9 |
public void evaluate(int size) {
if (stop)
return;
if (size >= DANGEROUS_SIZE) {
System.out.printf("\nInformation for Collection %s (id: %d)\n", className, id);
System.out.printf(" * Collection is very long (%d)!\n", size);
if (reads == 0) {
System.out.printf(" * Collection was never read!\n");
}
if (deletes == 0) {
System.out.printf(" * Collection was never reduced!\n");
}
System.out.printf("Recorded usage for this Collection:\n");
for (String code : interactingCode) {
System.out.printf(" * %s\n", code);
}
System.out.printf(
"Warned about Collection %s (id: %d). For performance reasons not warning about it anymore.\n",
className, id);
// at least somehow reduce our impact on CPU and memory
stop = true;
interactingCode.clear();
}
} | 5 |
public void actionPerformed(ActionEvent e) {
if(vulaux){vulaux=false;return;}
if(presionado==0){
this.boton1=(JButton)e.getSource();
presionado=1;
}
else if(presionado==1){
this.boton2=(JButton)e.getSource();
this.swap();
}
} | 3 |
public void saveResizeToUndo(ArrayList<DrawableItem> selected) {
ArrayList<UndoableItem> toAdd = new ArrayList<>();
for (DrawableItem selection : selected) {
UndoableItem ud = new UndoableItem(selection, 3);
Panel temp = (Panel) selection;
int x = ((Panel) selection).getInitialResizePoint().x;
int y = ((Panel) selection).getInitialResizePoint().y;
int width = ((Panel) selection).getInitialWidth() - ((Rectangle) temp.getShape()).width;
int height = ((Panel) selection).getInitialHeight() - ((Rectangle) temp.getShape()).height;
ud.setX(width);
ud.setY(height);
ud.setInitialP(new Point(x, y));
((Panel) selection).setInitialWidth(((Rectangle) temp.getShape()).width);
((Panel) selection).setInitialHeight(((Rectangle) temp.getShape()).height);
((Panel) selection).setInitialResizePoint(new Point(((Rectangle) temp.getShape()).x, ((Rectangle) temp.getShape()).y));
toAdd.add(ud);
}
this.addItemtoUndo(toAdd);
} | 1 |
public boolean areImagesSimilar(File image1, File image2) {
if ( image1 == null || image2 == null ||
!image1.exists() || !image2.exists() ||
image1.getAbsolutePath().equals(image2.getAbsolutePath()))
return false;
// Descriptors have to be loaded before every use (can't be reused for another image)
List<ImageDescriptor> image1Descriptors = getAllDescriptors();
List<ImageDescriptor> image2Descriptors = getAllDescriptors();
int similarityHits = 0;
for(int i = 0; i < image1Descriptors.size(); ++i){
List<double[]> image1Features = image1Descriptors.get(i).run(image1);
List<double[]> image2Features = image2Descriptors.get(i).run(image2);
double euklid = euklidSimilarity(image1Features, image2Features);
if (euklid < image1Descriptors.get(i).getTreshold())
{
System.out.println(image1Descriptors.get(i).getDescriptorName());
similarityHits++;
}
}
System.out.print(String.format(
"%s and %s has similarity score: %s: ",
image1.getName(),
image2.getName(),
similarityHits
)
);
System.out.println();
return similarityHits > 4;
} | 7 |
public void eliminate(Position pos){
board[pos.getY()][pos.getX()] = null;
} | 0 |
private Boolean checkTables() throws Exception {
if (!this.db.checkTable("chunky_objects")) {
if (!db.createTable(QueryGen.createObjectTable())) return false;
Logging.info("Created chunky_objects table.");
}
if (!this.db.checkTable("chunky_ownership")) {
if (!db.createTable(QueryGen.createOwnerShipTable())) return false;
Logging.info("Created chunky_ownership table.");
}
if (!this.db.checkTable("chunky_permissions")) {
if (!db.createTable(QueryGen.createPermissionsTable())) return false;
Logging.info("Created chunky_permissions table.");
}
if (!this.db.checkTable("chunky_groups")) {
if (!db.createTable(QueryGen.createGroupsTable())) return false;
Logging.info("Created chunky_groups table.");
}
return true;
} | 8 |
public ComplexMatrix subtract(ComplexMatrix b) {
try {
return this.add(b.reverseSign());
} catch (Exception e) {
e.printStackTrace();
return null;
}
} | 1 |
public boolean func_77648_a(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10)
{
if (par7 == 0)
{
par5--;
}
if (par7 == 1)
{
par5++;
}
if (par7 == 2)
{
par6--;
}
if (par7 == 3)
{
par6++;
}
if (par7 == 4)
{
par4--;
}
if (par7 == 5)
{
par4++;
}
if (!par2EntityPlayer.canPlayerEdit(par4, par5, par6))
{
return false;
}
int i = par3World.getBlockId(par4, par5, par6);
if (i == 0)
{
par3World.playSoundEffect((double)par4 + 0.5D, (double)par5 + 0.5D, (double)par6 + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F);
par3World.setBlockWithNotify(par4, par5, par6, Block.fire.blockID);
}
par1ItemStack.damageItem(1, par2EntityPlayer);
return true;
} | 8 |
@Override
@SuppressWarnings("unchecked")
public void setValue(@Nullable ThreadMirror threadMirror, @Nullable ObjectValueMirror thisObjectValue, @NotNull Value<?> value)
{
if(isStatic() && thisObjectValue != null || !isStatic() && thisObjectValue == null)
{
throw new IllegalArgumentException();
}
try
{
if(thisObjectValue == null)
{
Type_SetValues.process(vm, parent(), new ImmutablePair<FieldOrPropertyMirror, Value<?>>(this, value));
}
else
{
ObjectReference_SetValues.process(vm, thisObjectValue, new ImmutablePair<FieldOrPropertyMirror, Value<?>>(this, value));
}
}
catch(JDWPException e)
{
throw e.asUncheckedException();
}
} | 9 |
* @return Returns the startsize for the given swimlane.
*/
public mxRectangle getStartSize(Object swimlane)
{
mxRectangle result = new mxRectangle();
mxCellState state = view.getState(swimlane);
Map<String, Object> style = (state != null) ? state.getStyle()
: getCellStyle(swimlane);
if (style != null)
{
double size = mxUtils.getDouble(style, mxConstants.STYLE_STARTSIZE,
mxConstants.DEFAULT_STARTSIZE);
if (mxUtils.isTrue(style, mxConstants.STYLE_HORIZONTAL, true))
{
result.setHeight(size);
}
else
{
result.setWidth(size);
}
}
return result;
} | 3 |
public String toCSVString(){
StringBuilder builder = new StringBuilder();
for (int i = 0; i < cells.size(); i++) {
Cell cell = cells.get(i);
builder.append(cell.getCellValue());
if(i != cells.size() - 1) {
builder.append(",");
}
}
return builder.toString();
} | 2 |
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension ds = getSize();
d = Math.min(ds.width, ds.height) - 5;
float strokeWidth = (float) d / 200.0f;
stroke = new BasicStroke(strokeWidth);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(stroke);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (d <= 0)
return;
g.clearRect(0, 0, ds.width, ds.height);
g.translate((ds.width - d) / 2, (ds.height - d) / 2);
g.setColor(Color.black);
g.drawRect(0, 0, d, d);
for (int i = 0; i < agents.length; i++)
agents[i].paintComponent(g, d);
} | 2 |
public void set(UsuarioBean oUsuarioBean) throws Exception {
try {
oMysql.conexion(enumTipoConexion);
oMysql.initTrans();
if (oUsuarioBean.getId() == 0) {
oUsuarioBean.setId(oMysql.insertOne("usuario"));
}
oMysql.updateOne(oUsuarioBean.getId(), "usuario", "login", oUsuarioBean.getLogin());
oMysql.updateOne(oUsuarioBean.getId(), "usuario", "password", oUsuarioBean.getPassword());
oMysql.commitTrans();
} catch (Exception e) {
oMysql.rollbackTrans();
throw new Exception("UsuarioDao.setCliente: Error: " + e.getMessage());
} finally {
oMysql.desconexion();
}
} | 2 |
public void setRef(String ref) {
this.ref = ref;
} | 0 |
@Test
public void testEntrySet()
{
CaseInsensitiveStringMap map = new CaseInsensitiveStringMap();
//add some data
map.put("foo", "bar");
map.put("bar", "42");
Set<Entry<String, String>> entrySet = map.entrySet();
for(Entry<String,String>e:entrySet)
{
assertTrue(e.getKey().equalsIgnoreCase("foo")||e.getKey().equalsIgnoreCase("bar"));
assertTrue(e.getValue().equalsIgnoreCase("42")||e.getValue().equalsIgnoreCase("bar"));
}
} | 3 |
private void scheduleTasks() {
if (AutoSaveEnabled) {
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, saveRunnable,
SaveInterval, SaveInterval);
}
if (AutoBroadcastEnabled) {
Bukkit.getScheduler().scheduleSyncRepeatingTask(this,
broadcastRunnable, broadcastIntverval, broadcastIntverval);
}
Bukkit.getScheduler().scheduleSyncRepeatingTask(this,
tickRunnable, 100, 1);
} | 2 |
@Override
public void preUpdate() {
Event ev;
boolean expDamage = false;
while(eventExist())
{
ev = popEvent();
if(ev.getName().equals("explosion"))
{
if(!expDamage)
{
hp-=5;
expDamage = true;
if(hp <= 0 && alive)
{
destroy();
pushEvent(ev.getSource().source, "monster xp");
for(int i = 0; i < 10; i ++)
{
listElements.addElement(new MonsterBouftouBallHeal(x+Math.random()*30-15, y+Math.random()*30-15, ev.getSource().source));
}
}
}
}
if(ev.getName().equals("robot"))
{
destroy();
}
}
} | 7 |
public void addConnections(PlayerMP player, Packet00Login packet) {
boolean alreadyExist = false;
for (PlayerMP p : connectedPlayers) {
if (player.getUsername().equalsIgnoreCase(p.getUsername())) {
if (p.getIp() == null) {
p.setIp(player.getIp());
}
if (p.getPort() == -1) {
p.setPort(player.getPort());
}
alreadyExist = true;
} else {
sendData(packet.getData(), p.getIp(), p.getPort());
packet = new Packet00Login(p.getUsername(), p.getX(), p.getY(), p.getHP(), p.getUniqueID());
sendData(packet.getData(), player.getIp(), player.getPort());
}
}
if (!alreadyExist) {
connectedPlayers.add(player);
if (player.getIp() != null) {
Packet04Tiles packetTiles = new Packet04Tiles(game.getLevel().getTiles());
sendData(packetTiles.getData(), player.getIp(), player.getPort());
Packet05AddNPC packetNPC = null;
for (Mob m : game.getLevel().getMobs()) {
if (!(m instanceof Player)) {
packetNPC = new Packet05AddNPC((int) m.getX(), (int) m.getY(), m.getHP(), m.getUniqueID(), m.NPCType );
sendData(packetNPC.getData(), player.getIp(), player.getPort());
}
}
}
}
} | 8 |
private int getPreferredHeight() {
int maxHeight = 0;
for (int i=0, count=getComponentCount(); i<count; i++) {
Component component = getComponent(i);
Rectangle r = component.getBounds();
int height = r.y + r.height;
if (height > maxHeight) {
maxHeight = height;
}
}
maxHeight += ((FlowLayout) getLayout()).getVgap();
return maxHeight;
} | 2 |
private static void addNewAnnotations() throws Exception
{
List<Holder> holders= getList();
for(Holder h : holders)
System.out.println(h.conting + " " + h.startPos+ " " + h.endPos+ " " + h.pcas.get(0));
BufferedReader reader =new BufferedReader(new FileReader(new File(
ConfigReader.getCREOrthologsDir() + File.separator +
"chs_11_plus_cards.txt")));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(
ConfigReader.getCREOrthologsDir() + File.separator +
"chs_11_plus_cardsWithChunkPCA.txt"
)));
writer.write(reader.readLine());
for( int x=0; x < 10; x++)
writer.write("\tPCA" + (x+1));
writer.write("\n");
for(String s = reader.readLine(); s != null; s = reader.readLine())
{
String[] splits = s.split("\t");
int startPos =Integer.parseInt(splits[5]);
int endPos = Integer.parseInt(splits[6]);
if( startPos > endPos)
{
int temp = startPos;
startPos = endPos;
endPos = temp;
}
Holder h = findInListOrNull(holders, splits[4], startPos, endPos);
writer.write(s);
for( int x=0;x < 10; x++)
{
writer.write("\t" + ( h == null ? "" : h.pcas.get(x) ) );
}
writer.write("\n");
}
writer.flush(); writer.close();
reader.close();
} | 6 |
@SuppressWarnings("deprecation")
public static void setHealth(Player player, String playerName,
String healPlayerName, String amount) {
ArrayList<Player> healPlayers = AdminEyeUtils
.requestPlayers(healPlayerName);
if (healPlayers == null && healPlayerName != null) {
StefsAPI.MessageHandler.buildMessage().addSender(playerName)
.setMessage("error.playerNotFound", AdminEye.messages)
.changeVariable("playername", healPlayerName).build();
return;
}
if (!AdminEyeUtils.isNumber(amount)) {
StefsAPI.MessageHandler.buildMessage().addSender(playerName)
.setMessage("error.notANumber", AdminEye.messages)
.changeVariable("number", amount).build();
return;
}
int health = AdminEyeUtils.getNumber(amount);
if (health > 20) {
health = 20;
} else if (health < 0) {
health = 0;
}
String healedPlayers = "";
for (Player healPlayer : healPlayers) {
healPlayer.setHealth(health);
healedPlayers += "%A" + healPlayer.getName() + "%N, ";
}
healedPlayers = (healPlayerName.equals("*") ? healedPlayers = AdminEye.config
.getFile().getString("chat.everyone") + "%N, "
: healedPlayers);
AdminEye.broadcastAdminEyeMessage(playerName, "sethealth", "hp",
"playernames", healedPlayers, "amount", health + "");
} | 7 |
public synchronized void write(Tag tag, Object obj){
if(obj == null || obj.toString().isEmpty())
return;
if(this.disableTag.contains( tag ))
return;
String formatted = "";
if(this.showCaller) {
StackTraceElement s = new Exception().getStackTrace()[1];
formatted = String.format( "%s.%s ", s.getClassName(), s.getMethodName() );
}
String date = new SimpleDateFormat( "yy-MM-dd HH:mm:ss.SSS" ).format( new Date() );
String mp = "[%s] %s%-7s: %s\n";
this.printStream.printf(mp, date, formatted, tag.toString(), obj.toString() );
this.printStream.flush();
} | 4 |
ViewPanel(Session session)
{
this.session = session;
final int ROWS = 1;
final int COLUMNS = 1;
String querry = "SELECT * FROM records";
ResultSet results = null;
Statement stmt = null;
this.setLayout(new GridLayout(ROWS, COLUMNS));
this.conn = session.getConnection();
// Attempt to create a statement to interface with the conn.
try
{
stmt = conn.createStatement();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
JTable table = null;
JScrollPane scrollPane = null;
// try to get results and display them in the spread.
try
{
results = stmt.executeQuery(querry);
String[] headings = {"ID", "Start Time", "Duration"};
// Set Model to be an instance of
//the non-editable subclass, DBTableModel.
dbtm = new DBTableModel();
dbtm.setColumnCount(4);
table = new JTable(dbtm);
scrollPane = new JScrollPane(table);
//Render the DB.
while( results.next() )
{
// For each row of the query results, add a row to the JTable.
String[] rowData = new String[3];
// render the date as
rowData[0] = results.getString(4);
rowData[1] = TIME_DISPLAY_FORMAT.format( results.getLong(2) * 1000 );
rowData[2] = TIME_DISPLAY_FORMAT.format( ( results.getLong(2)
+ results.getLong(3) ) * 1000 );
rowData[3] = results.getString(5);
dbtm.addRow(rowData);
}
this.add(scrollPane);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 3 |
private void closeStream(Closeable stream) {
if (stream == null) {
return;
}
try {
stream.close();
} catch (IOException ex) {
System.out.println(ex);
}
} | 2 |
@EventHandler
public void IronGolemInvisibility(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getIronGolemConfig().getDouble("IronGolem.Invisibility.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getIronGolemConfig().getBoolean("IronGolem.Invisibility.Enabled", true) && damager instanceof IronGolem && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getIronGolemConfig().getInt("IronGolem.Invisibility.Time"), plugin.getIronGolemConfig().getInt("IronGolem.Invisibility.Power")));
}
} | 6 |
public String getTrappingInformation() {
Object value = library.getObject(entries, "Trapped");
if (value != null && value instanceof StringObject) {
StringObject text = (StringObject) value;
return cleanString(text.getDecryptedLiteralString(securityManager));
}
else if (value instanceof String) {
return (String) value;
}
return null;
} | 3 |
public void setCheckStart(int checkStart)
{
_checkStart = checkStart;
} | 0 |
@Override
protected void execute(Path file) throws Exception {
BufferedImage img = ImageIO.read(file.toFile());
if (img.getWidth() > img.getHeight()) {
rotate(file, file, PI_BY_2);
}
String targetName = null;
String name = getName(file);
if (name.startsWith("QR")) { // QR Code
String signature = name.split(SEP)[2];
Result result = decode(file);
String code = result == null ? "CND" : result.getText();
switch (code.toUpperCase()) {
case "CND": //Could Not Detect
targetName = String.format("%s%s", signature, MANUAL_DETECT);
break;
case BLANK_CODE: //Blank Page
case "ATTACHMENT": //Reference Sheet
break;
default: //Noteworthy QRCode
targetName = String.format("QR_%s_%s%s", code, signature, DETECTED);
}
} else { // Graded Response ID
targetName = name + DETECTED;
}
if (targetName != null) {
Path targetFile = file.resolveSibling(targetName);
if (!Files.exists(targetFile))
resize(file, targetFile, WIDTH, HEIGHT);
}
Files.delete(file);
} | 8 |
public User getUser(String login, String password) throws Exception {
// On cherche le login
Iterator<User> it = users.iterator();
while (it.hasNext()) {
User user = it.next();
if (user.getLogin().equals(login)) {
// On a trouvé le login
// On compare le mot de passe
if (user.getPassword().equals(password)) {
// On a trouvé le bon user
return user;
} else {
// Le mot de passe est faux
throw new Exception("Wrong password");
}
}
}
// On a pas trouvé de user
throw new Exception("Wrong login");
} | 3 |
public boolean opEquals(Operator o) {
return (o instanceof LocalLoadOperator && ((LocalLoadOperator) o).local
.getSlot() == local.getSlot());
} | 1 |
public static HandshakeBuilder translateHandshakeHttp( ByteBuffer buf, Role role ) throws InvalidHandshakeException , IncompleteHandshakeException {
HandshakeBuilder handshake;
String line = readStringLine( buf );
if( line == null )
throw new IncompleteHandshakeException( buf.capacity() + 128 );
String[] firstLineTokens = line.split( " ", 3 );// eg. HTTP/1.1 101 Switching the Protocols
if( firstLineTokens.length != 3 ) {
throw new InvalidHandshakeException();
}
if( role == Role.CLIENT ) {
// translating/parsing the response from the SERVER
handshake = new HandshakeImpl1Server();
ServerHandshakeBuilder serverhandshake = (ServerHandshakeBuilder) handshake;
serverhandshake.setHttpStatus( Short.parseShort( firstLineTokens[ 1 ] ) );
serverhandshake.setHttpStatusMessage( firstLineTokens[ 2 ] );
} else {
// translating/parsing the request from the CLIENT
ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client();
clienthandshake.setResourceDescriptor( firstLineTokens[ 1 ] );
handshake = clienthandshake;
}
line = readStringLine( buf );
while ( line != null && line.length() > 0 ) {
String[] pair = line.split( ":", 2 );
if( pair.length != 2 )
throw new InvalidHandshakeException( "not an http header" );
handshake.put( pair[ 0 ], pair[ 1 ].replaceFirst( "^ +", "" ) );
line = readStringLine( buf );
}
if( line == null )
throw new IncompleteHandshakeException();
return handshake;
} | 7 |
public Direction getInverse()
{
switch (this)
{
case left: return right;
case up: return down;
case right: return left;
case down: return up;
default: return up;
}
} | 4 |
@Override
public void callChangeOfferStatus(String username, String status,
String servicename) {
Service service = new Service();
Call call;
try {
call = (Call)service.createCall();
Object[] inParams = new Object[]{username, status, servicename};
call.setTargetEndpointAddress(new URL(SERVICES_URL));
call.setTargetEndpointAddress(SERVICES_URL);
call.setOperationName(new QName(CHANGE_OFFER_STATUS));
call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY, "");
call.addParameter("username", string, String.class, ParameterMode.IN);
call.addParameter("status", string, String.class, ParameterMode.IN);
call.addParameter("servicename", string, String.class, ParameterMode.IN);
call.setReturnClass(void.class);
call.invoke(inParams);
} catch (ServiceException e) {
System.out.println("Error calling change offer request");
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
} | 3 |
private void addNodeAndDaughtersToXML( ENode node, BufferedWriter writer, int level, HashMap<String, NewRDPParserFileLine> rdpMap ) throws Exception
{
String tabString = "";
for( int x=0; x <= level; x++ )
tabString += "\t";
String taxaName = "" + node.getLevel();
String rank = null;
String commonName = null;
//String phylaName = null;
if( rdpMap != null )
{
NewRDPParserFileLine line = rdpMap.get( node.getNodeName() );
if( line != null)
{
NewRDPNode rdpNode = line.getLowestNodeAtThreshold(RDP_THRESHOLD);
taxaName = rdpNode.getTaxaName() + " " + taxaName;
rank = line.getLowestRankThreshold(RDP_THRESHOLD);
commonName = tabString + "\t<common_name>" + line.getSummaryStringNoScore(50, 2)+"</common_name>\n";
//NewRDPNode phylaNode = line.getTaxaMap().get(NewRDPParserFileLine.PHYLUM);
//if( phylaNode != null)
// phylaName = tabString + "\t<accession>" + phylaNode.getTaxaName() + "</accession>\n";
}
}
writer.write(tabString + "<clade>\n");
//if( phylaName != null)
// writer.write(phylaName);
writer.write( tabString + "\t<name>" + node.getNodeName()
+ "(" + node.getNumOfSequencesAtTips() + "seqs) level " + node.getLevel() +"</name>\n");
if( level > 1 )
{
double branchLength = LEVELS[level-1] - LEVELS[level];
writer.write(tabString + "\t<branch_length>" + branchLength + "</branch_length>\n");
}
else
{
double branchLength = 0.01;
writer.write(tabString + "\t<branch_length>" + branchLength + "</branch_length>\n");
}
writer.write(tabString + "\t<taxonomy>");
// obviously, just a stub at this point
writer.write(tabString + "\t<scientific_name>" + taxaName + "(" + rank + ")" +"</scientific_name>\n");
if( commonName != null)
writer.write(commonName);
if( rank != null)
writer.write(tabString + "\t<rank>" + rank + "</rank>\n");
writer.write(tabString + "\t</taxonomy>\n");
level++;
for( ENode daughter: node.getDaughters() )
addNodeAndDaughtersToXML(daughter, writer, level, rdpMap);
writer.write(tabString + "</clade>\n");
} | 7 |
public static void main (String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println ("Inserisci Il Numero Di Tipi Di Francobolli: ");
int franc_num = kb.nextInt();
kb.nextLine();
Francobollo [] franc_arr = new Francobollo[franc_num];
for (int i=0; i<franc_num; i++) {
franc_arr[i] = new Francobollo();
System.out.println ("Inserisci La Nazione Del Francobollo " + i + " : ");
franc_arr[i].nazione = kb.nextLine();
System.out.println ("Inserisci Il Numero Di Esemplari Del Francobollo " + i + " : ");
franc_arr[i].num_franc_tipo = kb.nextInt();
kb.nextLine();
System.out.println ("Inserisci Il Costo Dei Francobolli Del Francobollo " + i + " : ");
franc_arr[i].money = kb.nextInt();
kb.nextLine();
}
do {
int choice = menu();
System.out.println ("Scelta : " + choice);
switch (choice) {
case 1: System.out.println ("\n\nNumero Esemplari Totale : " + Conta_Esemplari(franc_arr,franc_num));
break;
case 2: System.out.println ("\n\nValore Totale Esemplari: " + Value(franc_arr,franc_num));
break;
case 3: System.out.println ("\n\nValore Totale Esemplari: " + Most_Value(franc_arr,franc_num));
break;
case 4: int tmp = Most_Numbered(franc_arr,franc_num);
System.out.println ("Nzione Del Most Numbered: " + franc_arr[tmp].nazione);
break;
case 5: System.exit(0); break;
}
} while (true);
} | 7 |
public void displayError(String message){
Object[] buttons = {"Continue", "Quit"};
int userInput = JOptionPane.showOptionDialog(null,
message,
"Quantum Werewolves",
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
buttons,
buttons[0]);
switch(userInput){
case JOptionPane.YES_OPTION : break;
case JOptionPane.NO_OPTION : int check = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?", "Quantum Werewolves"
, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
switch(check){
case JOptionPane.YES_OPTION : System.exit(0);
case JOptionPane.NO_OPTION : break;
}
break;
case JOptionPane.CLOSED_OPTION : System.exit(0);
}
} | 5 |
public int reverse(int x) {
boolean isNeg = false;
if(x < 0) {
isNeg = true;
x = -1 * x;
}
int res = 0;
while (x > 0){
res = 10 * res + x % 10;
x /= 10;
}
if (res < 0){ // probably res > MAX_VALUE
return 0;
}else {
if (isNeg) return -1 * res;
else return res;
}
} | 4 |
public static int countCommElmts(ArrayList<Integer> newScores1,
ArrayList<Integer> newScores2) {
int count = 0;
for (int i = 0; i < newScores1.size(); i++) {
if (newScores1.get(i) == newScores2.get(i))
count++;
}
return count;
} | 2 |
public void deleteSong(BESong aSong) throws Exception {
try {
ds.deleteSong(aSong);
} catch (SQLException ex) {
throw new Exception("Could not create the song " + aSong.getId());
}
} | 1 |
public void setBackLeftThrottle(int backLeftThrottle) {
this.backLeftThrottle = backLeftThrottle;
if ( ccDialog != null ) {
ccDialog.getThrottle3().setText( Integer.toString(backLeftThrottle) );
}
} | 1 |
public static void main(String[] args) {
float x,y,z;
final float PI=3.14f;
boolean a,b,c,d,e,f;
a=((4-2)*(5+1)/2)>2-(4+3);
System.out.print("\nEl resultado es: "+ a);
b=(6+3)>8 && (6-1)*2 < 8 || 23==8;
System.out.print("\nEl resultado es: "+ b);
x=7;
z=2;
c=(1.0 < x) && (x < z+7.0);
System.out.print("\nEl resultado es: "+ c);
x=1;
y=4;
z=10;
d=(PI * x*x > y || 2*PI*x <= z);
System.out.print("\nEl resultado es: "+ d);
x=1;
y=4;
z=10;
e=(x>3 && y==4 || x + y <= z);
System.out.print("\nEl resultado es: "+ e);
x=1;
y=4;
z=10;
f=(x>3 && (y==4 || x + y <= z));
System.out.print("\nEl resultado es: "+ f);
} | 8 |
private boolean detect50Sync(CircularDataBuffer circBuf,WaveData waveData) {
int pos=0,b0,b1;
int f0=getSymbolFreq(circBuf,waveData,pos);
b0=getFreqBin();
// Check this first tone isn't just noise the highest bin must make up 10% of the total
if (getPercentageOfTotal()<10.0) return false;
pos=(int)samplesPerSymbol50*1;
int f1=getSymbolFreq(circBuf,waveData,pos);
b1=getFreqBin();
if (f0==f1) return false;
if (f0>f1) {
highTone=f0;
highBin=b0;
lowTone=f1;
lowBin=b1;
}
else {
highTone=f1;
highBin=b1;
lowTone=f0;
lowBin=b0;
}
// If either the low bin or the high bin are zero there is a problem so return false
if ((lowBin==0)||(highBin==0)) return false;
// Calculate the shift and check if it is OK
int dif=highTone-lowTone;
int ashift;
if (dif>shift) ashift=dif-shift;
else ashift=shift-dif;
// If we have more than a 10 Hz difference then we have a problem
if (ashift>10) return false;
else return true;
} | 7 |
public static Snake crossover(Snake parent1, Snake parent2) {
Snake child = new Snake();
int takenFromOne = 0;
for(int i = 0; i < 6; i++) {
Gene g = parent1.getGenes()[i];
child.setGene(takenFromOne, g);
takenFromOne++;
}
int takenFromTwo = 3;
for(int i = 3; i < 6; i++) {
if(takenFromTwo < 6) {
for(Gene gene : child.getGenes()) {
for(Gene g : parent2.getGenes()) {
if(!child.containsGene(g)) {
child.setGene(child.getIndex(gene), g);
}
}
}
}
}
System.out.println(child);
return child;
} | 6 |
public static void main(String[] args) {
System.out.println("Starting");
CycAccess access = null;
try {
access = new CycAccess("localhost", 3660);
String query = "(#$isa ?X #$Dog)";
InferenceWorkerSynch worker = new DefaultInferenceWorkerSynch(query,
CycAccess.inferencePSC, null, access, 500000);
InferenceResultSet rs = worker.executeQuery();
try {
int indexOfX = rs.findColumn("?X");
while (rs.next()) {
CycObject curDog = rs.getCycObject(indexOfX);
System.out.println("Got dog: " + curDog.cyclify());
}
System.out.flush();
} finally {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (access != null) {
access.close();
}
}
System.out.println("Finished");
System.exit(0);
} | 3 |
public void test_08_alt_del() {
initSnpEffPredictor("testCase");
String file = "./tests/alt_del.vcf";
VcfFileIterator vcf = new VcfFileIterator(file);
vcf.setCreateChromos(true);
// They are so long that they may produce 'Out of memory' errors
for (VcfEntry vcfEntry : vcf) {
System.out.println(vcfEntry);
boolean hasDel = false;
for (Variant sc : vcfEntry.variants()) {
hasDel |= sc.isDel();
System.out.println("\t" + sc + "\t" + sc.isDel());
}
Assert.assertEquals(true, hasDel);
}
} | 2 |
public void makeMoves()
{
if (showStuff == true)
{
System.out.println(toString());
}
isRunning = p1.canMove(theBoard, '$');
theBoard = p1.move(theBoard, '$');
maintenence();
incrementTurn();
// System.out.println(timeSinceJump);
isRunning = p2.canMove(theBoard, '@');
if (runs() == 0)
{
if (showStuff == true)
{
System.out.println(toString());
}
theBoard = p2.move(theBoard, '@');
incrementTurn();
maintenence();
}
} | 3 |
@Override
public void putAll(Map<? extends String, ? extends Object> map) throws ClassCastException {
Set<? extends String> keys = map.keySet();
for (String key : keys) {
if (key == null)
throw new NullPointerException();
this.checkInstance(map.get(key));
}
super.putAll(map);
} | 5 |
public void read(BufferedReader buff)
{
try
{
while(buff.ready())
{
line = buff.readLine();
piecePlace = pattern[0].matcher(line);
pieceMove = pattern[1].matcher(line);
if(piecePlace.find())
{
String chessPiece = piecePlace.group("ChessPiece");
String chessColor = piecePlace.group("ChessColor");
String chessLetter = piecePlace.group("Column");
String chessNum = piecePlace.group("Row");
if(chessColor.equals("d"))
{
chessPiece = chessPiece.toLowerCase();
}
placePiece(numberTranslation(chessNum),letterTranslation(chessLetter), chessPiece);
}
else if(pieceMove.find())
{
b.displayBoard();
String firstSpaceLetter = pieceMove.group("OriginColumn");
String firstSpaceNum = pieceMove.group("OriginRow");
String secondSpaceLetter = pieceMove.group("NewColumn");
String secondSpaceNum = pieceMove.group("NewRow");
chessPieceRedirection(letterTranslation(firstSpaceLetter), numberTranslation(firstSpaceNum), letterTranslation(secondSpaceLetter), numberTranslation(secondSpaceNum));
}
else
{
System.err.println(line + " is not a valid input");
}
}
}
catch (IOException e)
{
System.err.println("IO exception");
}
} | 5 |
private final void initUI()
{
// initialize a layout manager:
this.setLayout(new BorderLayout());
// create a menu bar:
JMenuBar menubar = new JMenuBar();
// ---------------------------------------------------------
// First dropdown menu: "File"
// ---------------------------------------------------------
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
// Set up a save dialog option under the file menu:
JMenuItem menu_file_save;
ImageIcon menu_file_save_icon = null;
try
{
menu_file_save_icon = new ImageIcon(getClass().getResource("/SciTK/resources/document-save-5.png"));
menu_file_save = new JMenuItem("Save", menu_file_save_icon);
}
catch(Exception e)
{
menu_file_save = new JMenuItem("Save");
}
menu_file_save.setMnemonic(KeyEvent.VK_S);
menu_file_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu_file_save.setToolTipText("Save an image");
menu_file_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
saveImage();
}
});
file.add(menu_file_save);
// Set up a save data dialog option under the file menu:
JMenuItem menu_file_save_data;
try
{
menu_file_save_data = new JMenuItem("Save data", menu_file_save_icon);
}
catch(Exception e)
{
menu_file_save_data = new JMenuItem("Save data");
}
menu_file_save_data.setToolTipText("Save raw data to file");
menu_file_save_data.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
saveData();
}
});
file.add(menu_file_save_data);
// add a menu item to close the window
JMenuItem menu_file_exit;
try
{
ImageIcon menu_file_exit_icon = new ImageIcon(getClass().getResource("/SciTK/resources/application-exit.png"));
menu_file_exit = new JMenuItem("Exit", menu_file_exit_icon);
}
catch(Exception e)
{
menu_file_exit = new JMenuItem("Exit");
}
menu_file_exit.setMnemonic(KeyEvent.VK_X);
menu_file_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu_file_exit.setToolTipText("Close window");
menu_file_exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
file.add(menu_file_exit);
// ---------------------------------------------------------
// Second dropdown menu: "Edit"
// ---------------------------------------------------------
JMenu edit = new JMenu("Edit");
edit.setMnemonic(KeyEvent.VK_E);
// copy to clipboard
JMenuItem menu_edit_copy_image;
ImageIcon menu_edit_copy_icon = null;
try
{
menu_edit_copy_icon = new ImageIcon(getClass().getResource("/SciTK/resources/edit-copy-7.png"));
menu_edit_copy_image = new JMenuItem("Copy", menu_edit_copy_icon);
}
catch(Exception e)
{
menu_edit_copy_image = new JMenuItem("Copy");
}
menu_edit_copy_image.setMnemonic(KeyEvent.VK_C);
menu_edit_copy_image.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu_edit_copy_image.setToolTipText("Copy image to clipboard");
menu_edit_copy_image.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
copyImage();
}
});
edit.add(menu_edit_copy_image);
// copy data to clipboard
JMenuItem menu_edit_copy_data;
try
{
menu_edit_copy_data = new JMenuItem("Copy data", menu_edit_copy_icon);
}
catch(Exception e)
{
menu_edit_copy_data = new JMenuItem("Copy data");
}
menu_edit_copy_data.setToolTipText("Copy data to clipboard");
menu_edit_copy_data.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
copyData();
}
});
edit.add(menu_edit_copy_data);
// zoom:
JMenuItem menu_edit_zoom;
try
{
ImageIcon menu_edit_zoom_icon = new ImageIcon(getClass().getResource("/SciTK/resources/zoom-3.png"));
menu_edit_zoom = new JMenuItem("Zoom",menu_edit_zoom_icon);
}
catch(Exception e)
{
menu_edit_zoom = new JMenuItem("Zoom");
}
menu_edit_zoom.setMnemonic(KeyEvent.VK_Z);
menu_edit_zoom.setToolTipText("Set image zoom");
menu_edit_zoom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setZoom();
}
});
edit.add(menu_edit_zoom);
// ---------------------------------------------------------
// Third dropdown menu: "Analysis"
// ---------------------------------------------------------
JMenu analysis = new JMenu("Analysis");
analysis.setMnemonic(KeyEvent.VK_A);
// select a point
JMenuItem menu_analysis_point = new JMenuItem("Select point");
menu_analysis_point.setToolTipText("Select a point in the image");
menu_analysis_point.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
selectPoint();
}
});
analysis.add(menu_analysis_point);
// select a rectangle
JMenuItem menu_analysis_rectangle = new JMenuItem("Select rectangle");
menu_analysis_rectangle.setToolTipText("Select a rectangle in the image");
menu_analysis_rectangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
selectRectangle();
}
});
analysis.add(menu_analysis_rectangle);
// select a circle
JMenuItem menu_analysis_circle = new JMenuItem("Select circle");
menu_analysis_circle.setToolTipText("Select a circle in the image");
menu_analysis_circle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
selectCircle();
}
});
analysis.add(menu_analysis_circle);
// Clear all selections
JMenuItem menu_analysis_clear = new JMenuItem("Clear all");
menu_analysis_clear.setToolTipText("Clear all selections from image");
menu_analysis_clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
clearSelections();
}
});
analysis.add(menu_analysis_clear);
// ---------------------------------------------------------
// General UI
// ---------------------------------------------------------
// Add File to the menu:
menubar.add(file);
// Add Edit to the menu:
menubar.add(edit);
// Add Analysis to the menu:
menubar.add(analysis);
// Set menubar as this JFrame's menu
setJMenuBar(menubar);
// call updateUI(), which handles the image stuff.
if( !(icon_label instanceof JLabel) )
icon_label = new JLabel();
icon_label.setHorizontalAlignment(SwingConstants.CENTER);
add(icon_label,BorderLayout.CENTER);
updateUI();
// set size automatically:
pack();
// if the window is closed, just dispose it:
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
this.setLocationRelativeTo(null);
this.setVisible(true);
} | 7 |
public static void saveLocal(String tt,String text_temp,
String linkUrl){
try {
FileOutputStream out = null ;
OutputStreamWriter out1 = null ;
BufferedWriter bw=null;
if("else".equals(DivideText.divide(text_temp))){
out = new FileOutputStream("else\\"+tt+".txt");
out1=new OutputStreamWriter(out);
bw=new BufferedWriter(out1);
bw.write(text_temp+"\r\n"+"原文引用自: "+linkUrl);
bw.close();
}
if("Society".equals(DivideText.divide(text_temp))){
out = new FileOutputStream("Society\\"+tt+".txt");
out1=new OutputStreamWriter(out);
bw=new BufferedWriter(out1);
bw.write(text_temp+"\r\n"+"原文引用自: "+linkUrl);
bw.close();
}
if("Nation".equals(DivideText.divide(text_temp))){
out = new FileOutputStream("Nation\\"+tt+".txt");
out1=new OutputStreamWriter(out);
bw=new BufferedWriter(out1);
bw.write(text_temp+"\r\n"+"原文引用自: "+linkUrl);
bw.close();
}
if("Inter".equals(DivideText.divide(text_temp))){
out = new FileOutputStream("Inter\\"+tt+".txt");
out1=new OutputStreamWriter(out);
bw=new BufferedWriter(out1);
bw.write(text_temp+"\r\n"+"原文引用自: "+linkUrl);
bw.close();
}
}
catch(Exception e)
{
}
} | 5 |
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Product { ");
sb.append("productCode=").append(productCode);
sb.append(", prices=").append(prices);
sb.append('}');
return sb.toString();
} | 0 |
@Override
public void renderMoving(Engine e, Graphics g, int i, int j) {
for(Particle par:e.getWorld().getParticleArray()){
if(par == null)
continue;
g.drawImage(par.getImage(), par.getLocation().getX()-i+e.getWidth()/2, par.getLocation().getY()-j+e.getHeight()/2, null);
}
for(Entity en:e.getWorld().getEntityArray()){
if(en == null)
continue;
g.drawImage(en.getImage(), en.getLocation().getX()-i+e.getWidth()/2, en.getLocation().getY()-j+e.getHeight()/2, null);
}
for(Entity en:((TestWorld)e.getWorld()).getPlayers()){
if(en == null)
continue;
g.drawImage(en.getImage(), en.getLocation().getX()-i+e.getWidth()/2, en.getLocation().getY()-j+e.getHeight()/2, null);
}
//Drawing the player (not an entity!)
g.drawImage(e.getWorld().getPlayer().getImage(), e.getWorld().getPlayer().getLocation().getX()-i+e.getWidth()/2, e.getWorld().getPlayer().getLocation().getY()-j+e.getHeight()/2, null);
for(Gui gui : e.getGuis().values()){
gui.render(g);
}
} | 7 |
public int getIdxNum() throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int x = 0;
try{
conn=getConnection();
String sql = "select max(idx) from food";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()){
x = rs.getInt(1) +1;
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(rs!=null)try{rs.close();}catch(SQLException ex){}
if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){}
if(conn!=null)try{conn.close();}catch(SQLException ex){}
}
return x;
} | 8 |
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
String pw = plugin.config.getString("Apply.Password");
String defaultgroup = plugin.config.getString("Apply.Defaultgroup");
String group = plugin.config.getString("Apply.Group");
if(sender instanceof Player)
{
Player player = (Player) sender;
if(plugin.config.getBoolean("Apply.Enabled"))
{
if(!player.hasPermission("MasterPromote.member"))
{
if(args.length == 1)
{
if(args[0].equals(pw))
{
plugin.getPermissionsHandler().promote(player, group, PROMOTIONTYPE.APPLY);
String msg = plugin.messages.getString("UsedPW").replace("&", "\u00A7");
player.sendMessage(msg.replace("<group>", group));
System.out.println("[PLAYER_COMMAND] " + player.getName() + ": /apply");
System.out.println("[MasterPromote]User " + player.getName() + " has been promoted to " + group + " group!");
return true;
}
else
{
if(plugin.config.getBoolean("Apply.KickWrongPW"))
{
player.kickPlayer(plugin.messages.getString("WrongPW").replace("&", "\u00A7"));
System.out.println("[MasterPromote]Player " + player.getName() + " has been kicked for typing in the wrong password");
return true;
}
else
{
player.sendMessage(plugin.messages.getString("WrongPW").replace("&", "\u00A7"));
return true;
}
}
}
}
else
{
player.sendMessage(ChatColor.RED + "You have to be in group " + defaultgroup + " to use this command!");
return true;
}
}
else
{
player.sendMessage(plugin.messages.getString("FunctionDisabled").replace("&", "\u00A7"));
return true;
}
}
else
{
System.out.println("You can use this command only as a player");
return true;
}
return false;
} | 6 |
public void saveImage() {
BufferedImage bi = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
this.paint(g);
g.dispose();
try {
ImageIO.write(bi, "png", new File(System.getProperty("resources") + "/TempCol.png"));
} catch(IOException e) {}
} | 1 |
public void excluir(int id){
dlo.excluir(id);
for (int i = 0; i < categorias.size(); i++){
if (categorias.get(i).getId() == id){
categorias.remove(i);
break;
}
}
exibirMensagem("Categoria excluída com sucesso");
} | 2 |
@Override
public void loadRecipes(File dir) {
if (!this.open) {
BackpacksPlugin.getInstance().getLogger().warning("**** No longer accepting new registrations!");
}
if (!dir.isDirectory()) {
throw new IllegalArgumentException("Given file: " + dir.getName() + " is not a directory!");
}
for (File file : dir.listFiles(new RecipeFilter())) {
loadRecipe(file);
}
} | 3 |
private void updateStopHistory() {
ArrayList<StopAdapter> stops = GTFS.getCurrentStopWindow();
LinkedList<StopAdapter> closest = calcClosestStops();
if (closest != null) {
if (mStopHistoryIndex == -1) {
mStopHistory.set(0, closest);
mStopHistoryIndex = 0;
} else {
boolean duplicate = false;
for (int i = 0; i < COORD_BUFFER_SIZE; i++) {
if (closest.hashCode() == mStopHistory.get(
mStopHistoryIndex).hashCode()) {
duplicate = true;
break;
}
}
if (!duplicate) {
mStopHistoryIndex = incIndex(mStopHistoryIndex);
mStopHistory.set(mStopHistoryIndex, closest);
findProbableRoutes();
}
}
}
} | 5 |
public boolean peekMap(String fname){
int max_length = 0;
ArrayList <String> lines = new ArrayList <String> ();
try {
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fname);
if (in == null) {
System.out.println("no hay nivel " + fname);
return false;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("#")) {
lines.add(line);
if (line.length() > max_length) {
max_length = line.length();
}
}
}
reader.close();
}
catch (IOException ex) {
System.out.println("Error al leer el archivo del mapa: " + fname);
}
return true;
} | 5 |
private void savePreferences() {
try {
preferencesFile.createNewFile();
preferences.storeToXML(new FileOutputStream(preferencesFile), null);
print("Preferences saved successfully.");
} catch (IOException e) {
// TODO Auto-generated catch block
print("ERROR: Failed to save preferences.");
}
} | 1 |
public static MethodSlot lookupOptionHandler(StorageSlot slot) {
{ Symbol handlername = ((Symbol)(KeyValueList.dynamicSlotValue(slot.dynamicSlots, Stella.SYM_STELLA_SLOT_OPTION_HANDLER, null)));
MethodSlot handler = null;
if (handlername == null) {
if (Stella.$DEFAULT_OPTION_HANDLER$ != null) {
return (Stella.$DEFAULT_OPTION_HANDLER$);
}
else {
return (Symbol.lookupFunction(Stella.SYM_STELLA_DEFAULT_OPTION_HANDLER));
}
}
handler = Symbol.lookupFunction(handlername);
if ((((Integer)(Stella.$SAFETY$.get())).intValue() >= 2) &&
((handler != null) &&
((!(handlername == Stella.SYM_STELLA_DEFAULT_OPTION_HANDLER)) &&
(!handler.conformingSignaturesP(Stella.$DEFAULT_OPTION_HANDLER$))))) {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("The signature of slot option handler `" + handlername + "' does not conform to that of 'default-option-handler'.");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (handler);
}
} | 6 |
public Percolation(int N) // create N-by-N grid, with all sites blocked
{
if (N<=0)
{
throw new IllegalArgumentException();
}
this.N = N;
uf_inst = new WeightedQuickUnionUF (N*N+2);
uf_real = new WeightedQuickUnionUF (N*N+1);
grid = new boolean [N*N];
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
grid[N*i+j] = false;
}
uf_inst.union(i, N*N);
uf_inst.union(N*(N-1)+i, N*N+1);
uf_real.union(i, N*N);
}
} | 3 |
@Override
public SymptomDTO getSymptomById(Long id) throws SQLException {
Session session = null;
SymptomDTO symptom = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
symptom = (SymptomDTO) session.load(SymptomDTO.class, id);
} catch (Exception e) {
System.err.println("Error while getting symptom!");
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return symptom;
} | 3 |
public static Description extractGoalDescription(Proposition goal, Keyword headortail) {
{ Vector arguments = goal.arguments;
{ Keyword testValue000 = goal.kind;
if ((testValue000 == Logic.KWD_ISA) ||
((testValue000 == Logic.KWD_PREDICATE) ||
((testValue000 == Logic.KWD_FUNCTION) ||
(testValue000 == Logic.KWD_IMPLIES)))) {
if (Stella_Object.isaP(goal.operator, Logic.SGT_STELLA_SURROGATE)) {
{ NamedDescription description = Logic.getDescription(((Surrogate)(goal.operator)));
if (description == null) {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
stream000.nativeStream.println("ERROR: Can't finalize relations because relation `" + ((Surrogate)(goal.operator)).symbolName + "' is undefined..");
Logic.helpSignalPropositionError(stream000, Logic.KWD_ERROR);
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
throw ((PropositionError)(PropositionError.newPropositionError(stream000.theStringReader()).fillInStackTrace()));
}
}
if (NamedDescription.chainableRelationP(description, headortail)) {
return (description);
}
}
}
}
else if (testValue000 == Logic.KWD_NOT) {
{ Description argumentdescription = Proposition.extractGoalDescription(((Proposition)((arguments.theArray)[0])), headortail);
if (argumentdescription != null) {
return (NamedDescription.getComplementOfGoalDescription(((NamedDescription)(argumentdescription))));
}
}
}
else {
}
}
return (null);
}
} | 9 |
@Override // update the cardHandler -> cardHandler.update() pls keep this method as clean as possible
public void update( GameContainer container, StateBasedGame game, int delta ) throws SlickException
{
Score currentScore = new Score();
input = container.getInput();
//Update the CardHandler
CH.update(container, game, delta);
//resets music
if(game.getCurrentStateID() == ID && startMusic)
{
backgroundMusic = SoundTrack.TRACK_TWO;
try {
backgroundMusic.play();
backgroundMusic.setVolume(0.1f);
SoundEffect.setVolume(0.8f);
CH.resetTimer();
} catch (OutOfRangeException e) {e.printStackTrace();}
finally{ startMusic = false;}
}
//check for escape
if(input.isKeyDown(Input.KEY_ESCAPE))
{
// add score to the list and save the list
currentScore = CH.getScoreObject();
if ( currentScore != null && currentScore.getScore() != 0) {
currentScore.setPlayerName(scoresList.getCurrentPlayerName());
scoresList.addEntry(currentScore);
// save the scores list to the file
saveScores(scoresList);
}
container.exit();
}
//gameover
if(CH.getTime().getTime() <= 0)
{
// add score to the list
currentScore = CH.getScoreObject();
currentScore.setPlayerName(scoresList.getCurrentPlayerName());
scoresList.addEntry(currentScore);
// save the scores list to the file
saveScores(scoresList);
game.enterState(2, new FadeOutTransition(Color.red, 1000), new FadeInTransition(Color.red, 300) );
}
//update time for the fuse
time = CH.getTime().getTime();
} | 7 |
public void render(Graphics g)
{
unit.render(g);
} | 0 |
@Basic
@Column(name = "FES_ID_POS")
public Integer getFesIdPos() {
return fesIdPos;
} | 0 |
public void decouvrir(Position pos, int dist){
for (int x=pos.getX() - dist; x <= pos.getX() + dist; x++){
for (int y=pos.getY() - dist; y <= pos.getY() + dist; y++){
if ((x >= 0) && (x < IConfig.LARGEUR_CARTE) && (y >= 0) && (y < IConfig.HAUTEUR_CARTE)){
map[x][y].decouvrir();
}
}
}
} | 6 |
public static void eightdrome(int a, int b) {
if(b <10000000) { return; }
for(int d=1; d<10; d++) {
for(int d2=0; d2<10; d2++) {
for(int d3=0; d3<10; d3++) {
for(int d4=0; d4<10; d4++) {
int test = 10000000*d +1000000*d2 + 100000*d3 + 10000*d4+1000*d4 +100*d3 + 10*d2 + d;
if(isPrime(test) && test>=a && test<=b) { list.add(test); }
}
}
}
}
} | 8 |
public boolean isMarker(Position position) {
return (board[position.getY()][position.getX()] instanceof Marker);
} | 0 |
public void setImage(Image image) {
button.setIcon(image == null ? null : new ImageIcon(image));
} | 1 |
public boolean isValid(Event event)
{
int commandType = event.getCommandType();
int minExpectedArgCount = minExpectedArgByteCount(commandType);
int maxExpectedArgCount = maxExpectedArgByteCount(commandType);
if (minExpectedArgCount == maxExpectedArgCount)
{
if (-1 != minExpectedArgCount)
{
if (minExpectedArgCount != (event.getRawData().length - EVENT_COMMAND_ARGS_OFFSET))
return false;
}
}
else
{
if (-1 != minExpectedArgCount)
{
int actualArgs = event.getRawData().length - EVENT_COMMAND_ARGS_OFFSET;
if ((actualArgs < minExpectedArgCount) || (actualArgs > maxExpectedArgCount))
return false;
}
}
return true;
} | 6 |
public static void disposeImages() {
// dispose loaded images
{
for (Image image : m_imageMap.values()) {
image.dispose();
}
m_imageMap.clear();
}
// dispose decorated images
for (int i = 0; i < m_decoratedImageMap.length; i++) {
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i];
if (cornerDecoratedImageMap != null) {
for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) {
for (Image image : decoratedMap.values()) {
image.dispose();
}
decoratedMap.clear();
}
cornerDecoratedImageMap.clear();
}
}
} | 5 |
final int[] method3042(int i, int i_16_) {
if (i_16_ != 255)
return null;
anInt9409++;
int[] is = ((Class348_Sub40) this).aClass191_7032.method1433(0, i);
if (((Class191) ((Class348_Sub40) this).aClass191_7032).aBoolean2570) {
int i_17_ = Class348_Sub40_Sub6.anInt9139 / anInt9405;
int i_18_ = Class286_Sub2.anInt6212 / anInt9410;
int[] is_19_;
if ((i_18_ ^ 0xffffffff) < -1) {
int i_20_ = i % i_18_;
is_19_
= this.method3048(i_20_ * Class286_Sub2.anInt6212 / i_18_,
633706337, 0);
} else
is_19_ = this.method3048(0, 633706337, 0);
for (int i_21_ = 0; Class348_Sub40_Sub6.anInt9139 > i_21_;
i_21_++) {
if (i_17_ <= 0)
is[i_21_] = is_19_[0];
else {
int i_22_ = i_21_ % i_17_;
is[i_21_] = is_19_[(Class348_Sub40_Sub6.anInt9139 * i_22_
/ i_17_)];
}
}
}
return is;
} | 5 |
private void createClassView( FileOutputStream fos, ModClass modClass ) throws Exception
{
String[] menus =modClass.getMenuPath().split( "/" );
if( ( menus.length == 0 ) || menus[ 0 ].isEmpty() )
{
throw new Exception( "The class '" + modClass.getName() + "'menu Path with errors." );
}
// Create the menu entries
// Search for the root menu. If doesnt exist yet create it.
MenuItem rootMenu = MenuItem.searchMenuItem( menus[ 0 ].toLowerCase() );
if( rootMenu == null )
{
rootMenu = new MenuItem( menus[ 0 ] );
MenuItem.appendMenuItem( rootMenu );
}
MenuItem parentMenu = rootMenu;
MenuItem menuItem = null;
for( int index = 1; index < menus.length; index++ )
{
menuItem = MenuItem.searchMenuItem( menus[ index ].toLowerCase() );
if( menuItem == null )
{
// Check if its the last menu entry that indicate it is the action menu
if( index == ( menus.length - 1 ) ) // It is the action
{
menuItem = new MenuItem( menus[ index ], "", parentMenu.getId(), "action_" + nameToId( modClass.getName() ).toLowerCase() );
MenuItem.appendMenuItem( menuItem );
}
else
{
menuItem = new MenuItem( menus[ index ], parentMenu.getId() );
MenuItem.appendMenuItem( menuItem );
}
}
parentMenu = menuItem;
}
if( menuItem == null )
{
menuItem = rootMenu;
menuItem.setAction( "action_" + nameToId( modClass.getName() ).toLowerCase() );
}
String content = MODULE_VIEW_CLASS;
content = content.replace( "{MODULE_VIEW_CLASS_NAME_ID}", nameToId( modClass.getName() ) );
content = content.replace( "{MODULE_VIEW_CLASS_NAME}", modClass.getName() );
content = content.replace( "{MODULE_VIEW_MENU_NAME}", menuItem.getName() );
content = content.replace( "{MODULE_VIEW_CLASS_FORM}", getClassViewForm( modClass ) );
content = content.replace( "{MODULE_VIEW_CLASS_TREE}", getClassViewTree( modClass ) );
content = content.replace( "{MODULE_VIEW_CLASS_MODE}", getClassViewMode( modClass ) );
fos.write( content.getBytes() );
} | 7 |
public IMessage crypter(IMessage clair, String key) {
/*
* Les caractres sont encods un un via oprations elementaires
* Les caractres ne correspondant pas des lettres sont ajouts tel quels.
*/
long d=new Date().getTime();
this.remplirHashMap(this.adapterCle(key));
IMessage m=this.adapterMessage(clair);
char[] c=new char[m.taille()];
for(int i=0;i<m.taille();i++) {
if(m.getChar(i)>=65 && m.getChar(i)<=90) {
c[i]=Character.toUpperCase(this.crypterChar(m.getChar(i)));
}
else {
if(m.getChar(i)>=97 && m.getChar(i)<=122) {
c[i]=this.crypterChar(m.getChar(i));
}
else{
c[i]=m.getChar(i);
}
}
}
this.time=new Date().getTime()-d;
return Fabrique.fabriquerMessage(c);
} | 5 |
public <T extends GraphItem> void addCapability( CapabilityName<? super T> name, T capability ) {
if( getCapability( name ) != null ) {
throw new IllegalStateException( "there is already a capability for " + name );
}
setCapability( name, capability );
addChild( capability );
} | 2 |
public JPanel getUserlistImageframeMenu() {
if (!this.init_1) {
IllegalStateException e = new IllegalStateException("Call init first!");
throw e;
}
return this.userlistImageframeMenu;
} | 1 |
public boolean verifyWeeks() {
boolean[] w = selectedWeeks();
return w[0] || w[1] || w[2] || w[3] || w[4] || w[5] || w[6] || w[7];
} | 7 |
Subsets and Splits