text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public static String stripNonCharCodepoints(String input) {
StringBuilder retval = new StringBuilder();
char ch;
for (int i = 0; i < input.length(); i++) {
ch = input.charAt(i);
// Strip all non-characters http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Noncharacter_Code_Point=True:]
// and non-printable control characters except tabulator, new line and carriage return
if (ch % 0x10000 != 0xffff && // 0xffff - 0x10ffff range step 0x10000
ch % 0x10000 != 0xfffe && // 0xfffe - 0x10fffe range
(ch <= 0xfdd0 || ch >= 0xfdef) && // 0xfdd0 - 0xfdef
(ch > 0x1F || ch == 0x9 || ch == 0xa || ch == 0xd)) {
retval.append(ch);
}
}
return retval.toString();
} | 9 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Connective other = (Connective) obj;
if (left == null) {
if (other.left != null)
return false;
}
if (right == null) {
if (other.right != null)
return false;
}
if (left.equals(other.left))
return (right.equals(other.right));
if (left.equals(other.right))
return (right.equals(other.left));
return false;
}; | 9 |
@Test
public void testName() {
Iterator<Pair<?>> i = info.namedValues.iterator();
String s = null;
Label label = null;
while(i.hasNext() && s == null){
pair = i.next();
label = pair.getLabel();
switch (label){
case cNme:
s = (String) pair.second();
break;
default:
s = null;
}
}
assertEquals(componentName, s);
} | 4 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(((msg.targetMajor()&CMMsg.MASK_MALICIOUS)>0)
&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS))
&&((msg.amITarget(affected))))
{
final MOB target=(MOB)msg.target();
if((!target.isInCombat())
&&(msg.source().getVictim()!=target)
&&(msg.source().location()==target.location())
&&(CMLib.dice().rollPercentage()>((msg.source().phyStats().level()-(target.phyStats().level()+(2*getXLEVELLevel(invoker()))))*10)))
{
msg.source().tell(L("You are too much in awe of @x1",target.name(msg.source())));
if(target.getVictim()==msg.source())
{
target.makePeace(true);
target.setVictim(null);
}
return false;
}
}
return super.okMessage(myHost,msg);
} | 8 |
public Float getGainTrack_dB() {
return gainTrack_dB;
} | 0 |
public boolean hasItem(int itemSlot)
{
if(inv[itemSlot] != null)
if(itemSlot <= 5 && itemSlot >= 0)
return true;
return false;
} | 3 |
public void putAll(Map<? extends K,? extends V> m) {
for (Map.Entry<? extends K,? extends V> entry : m.entrySet()) {
put (entry.getKey(), entry.getValue());
}
} | 5 |
public static List<String> parseList(String listStr) {
if (isStringNullOrWhiteSpace(listStr) || listStr.length() < 2) return null;
listStr = listStr.substring(1, listStr.length() - 1);
if (isStringNullOrWhiteSpace(listStr)) return new ArrayList<String>();
return Arrays.asList(listStr.split(", "));
} | 3 |
public PapaBicho Factory (String pBicho){
if(pBicho == "tank"){
list = units.tanqueXMLUnit();
setVar();
PapaBicho tank = new PapaBicho(pLevel,pPrice,pIntelligence,pStrenght
,pWeight,pResistance,pMovespeed,
pHitpoints,pWeightLimit,pMana,
pMaxHitPoints);
return tank;
}else if(pBicho == "panzer" ){
list = units.panzerXMLUnit();
setVar();
PapaBicho scout = new PapaBicho(pLevel,pPrice,pIntelligence,
pStrenght,pWeight,pResistance,
pMovespeed,pHitpoints,pWeightLimit,
pMana,pMaxHitPoints);
return scout;
}else if(pBicho == "warrior" ){
list = units.soldadoXMLUnit();
setVar();
PapaBicho warrior = new PapaBicho(pLevel,pPrice,pIntelligence,
pStrenght,pWeight,pResistance,
pMovespeed,pHitpoints,pWeightLimit
,pMana,pMaxHitPoints);
return warrior;
}else if (pBicho == "specialforce"){
list = units.dobleAgenteXMLUnit();
setVar();
PapaBicho specialforce = new PapaBicho(pLevel,pPrice,pIntelligence,
pStrenght,pWeight,pResistance
,pMovespeed,pHitpoints,
pWeightLimit,pMana,
pMaxHitPoints);
return specialforce;
}else if(pBicho == "harvester"){
list = units.peonXMLUnit();
setVar();
Harvester harvester = new Harvester(pLevel,pPrice,pIntelligence,
pStrenght,pWeight,pResistance,
pMovespeed,pHitpoints,
pWeightLimit,pMana,
pMaxHitPoints);
return harvester;
}else if (pBicho == "proharvester"){
list = units.peonEliteXMLUnit();
setVar();
ProHarvester proharvester = new ProHarvester(pLevel,pPrice,
pIntelligence,pStrenght
,pWeight,pResistance,
pMovespeed,pHitpoints,
pWeightLimit,pMana,
pMaxHitPoints);
return proharvester;
}else if (pBicho == "monk"){
list = units.shamanXMLUnit();
setVar();
Monk monk = new Monk(pLevel,pPrice,pIntelligence,pStrenght,pWeight,
pResistance,pMovespeed,pHitpoints,pWeightLimit,
pMana,pMaxHitPoints);
return monk;
}else if (pBicho=="healer"){
units.enfermeroXMLUnit();
setVar();
Healer healer = new Healer(pLevel,pPrice,pIntelligence,pStrenght,
pWeight,pResistance,pMovespeed,pHitpoints
,pWeightLimit,pMana,pMaxHitPoints);
return healer;
}else if (pBicho == "kamikaze"){
units.kamikazeXMLUnit();
setVar();
Kamikaze kamikaze = new Kamikaze(pLevel,pPrice,pIntelligence,
pStrenght,pWeight,pResistance,
pMovespeed,pHitpoints,pWeightLimit,
pMana,pMaxHitPoints);
return kamikaze;
}else{
units.escoltaXMLUnit();
setVar();
PapaBicho scout = new PapaBicho(pLevel,pPrice,pIntelligence,
pStrenght,pWeight,pResistance,
pMovespeed,pHitpoints,pWeightLimit,
pMana,pMaxHitPoints);
return scout;
}
} | 9 |
public boolean LoadWallet() throws LoadingOpenTransactionsFailure {
if (!isPasswordCallbackSet) {
throw new LoadingOpenTransactionsFailure(LoadErrorType.PASSWORD_CALLBACK_NOT_SET, "Must Set Password Callback First!");
}
if (isWalletLoaded) {
throw new LoadingOpenTransactionsFailure(LoadErrorType.WALLET_ALREADY_LOADED, "Already Loaded!");
}
if (!OTAPI_Basic.LoadWallet()) {
throw new LoadingOpenTransactionsFailure(LoadErrorType.WALLET_UNABLE_TO_LOAD, "Unable to Load Wallet");
}
isWalletLoaded = true;
return true;
} | 3 |
protected void initGUI() throws SlickException {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
try {
Renderer renderer = new LWJGLRenderer();
ThemeManager theme = loadTheme(renderer);
gui = new GUI(emptyRootWidget, renderer, null);
gui.applyTheme(theme);
Input input = getContainer().getInput();
TWLInputForwarder inputForwarder = new TWLInputForwarder(gui, input);
input.addPrimaryListener(inputForwarder);
} catch (Throwable e) {
throw new SlickException("Could not initialize TWL GUI", e);
} finally {
GL11.glPopAttrib();
}
} | 1 |
public AbstractOutlinerJDialog(boolean resizeOnShow, boolean alwaysCenter, boolean modal, int initialWidth, int initialHeight, int minimumWidth, int minimumHeight) {
super(Outliner.outliner, "", modal);
this.alwaysCenter = alwaysCenter;
setSize(initialWidth, initialHeight);
addComponentListener(new WindowSizeManager(resizeOnShow, initialWidth, initialHeight, minimumWidth, minimumHeight));
} | 0 |
private static Node arrayToTree(Integer[] arr) {
if(arr == null || arr.length<=0)
return null;
Node[] narr = new Node[arr.length];
if(arr[0]!=null){
narr[0] = new Node(arr[0]);
}
for(int i=0;i<arr.length;i++){
if(2*i+1 < arr.length && arr[2*i+1]!=null){
narr[2*i+1] = new Node(arr[2*i+1]);
narr[i].left = narr[2*i+1];
}
if(2*i+2 < arr.length && arr[2*i+2]!=null){
narr[2*i+2] = new Node(arr[2*i+2]);
narr[i].right = narr[2*i+2];
}
}
return narr[0];
} | 8 |
@Override
public String getSheetName()
{
if( sheetname == null )
{
if( parent_rec != null )
{
WorkBook wb = parent_rec.getWorkBook();
if( (wb != null) && (wb.getExternSheet() != null) )
{ // 20080306 KSC: new way is to get sheet names rather than sheets as can be external refs
String[] sheets = wb.getExternSheet().getBoundSheetNames( ixti );
if( (sheets != null) && (sheets[0] != null) )
{
sheetname = sheets[0];
}
}
}
}
return sheetname;
} | 6 |
public List<Station> findStations( String prefix ) throws ApiException {
if ( prefix.length() < 2 )
return Collections.emptyList();
prefix = prefix.toUpperCase();
try {
Set<Station> fromServer = findStationsOnServer( prefix.substring( 0, 2 ) );
List<Station> results = new ArrayList<Station>();
for ( Station st : fromServer )
if ( st.name.startsWith( prefix ) )
results.add( st );
return results;
} catch ( ClientProtocolException e ) {
throw new ApiException( "Error fetching stations due to protocol error", e );
} catch ( IOException e ) {
throw new ApiException( "Error fetching stations due to IO error", e );
} catch ( JSONException e ) {
throw new ApiException( "Error fetching stations due to parse error", e );
}
} | 6 |
public Integer pop() {
if(len == 0) return null;
int max = heap[0];
heap[0] = heap[len - 1];
len--;
bubbleDown(0);
return max;
} | 1 |
public Tagesspiel(JSONObject setup) {
super("Tagesspiel");
try {
zwerg = setup.getBoolean("Zwergeneinsatz");
} catch (JSONException e) {
}
} | 1 |
private synchronized void processEvent(Sim_event ev) {
double currentTime = GridSim.clock();
boolean success = false;
if(ev.get_src() == myId_) {
// time to update the schedule, remove finished jobs,
// removed finished reservations, start reservations, etc.
if (ev.get_tag() == UPT_SCHEDULE) {
if(currentTime > lastSchedUpt) {
updateSchedule();
lastSchedUpt = currentTime;
}
success = true;
}
}
if(!success) {
processOtherEvent(ev);
}
} | 4 |
public FastaItem getNextFastaItem() throws IOException {
String line;
String headerRow;
String acNum;
int counter = 0;
FastaItem fastaItem = null;
while ((line = reader.readLine()) != null) {
if (line.charAt(0) == '>' && counter == 0) {
headerRow = line;
acNum = line.split("\\|")[1];
fastaItem = new FastaItem(headerRow, acNum);
++counter;
}
else if(line.charAt(0) != '>' && counter == 0){
headerRow = nextHeaderRow;
acNum = nextHeaderRow.split("\\|")[1];
fastaItem = new FastaItem(headerRow, acNum);
fastaItem.addSeqRow(line);
++counter;
}
else if (line.charAt(0) == '>' && counter == 1){
nextHeaderRow = line;
return fastaItem;
}
else {
fastaItem.addSeqRow(line);
}
}
return fastaItem;
} | 7 |
public boolean processMsg(CConnection cc) {
InStream is = cc.getInStream();
OutStream os = cc.getOutStream();
// Read the challenge & obtain the user's password
byte[] challenge = new byte[VNC_AUTH_CHALLENGE_SIZE];
is.readBytes(challenge, 0, VNC_AUTH_CHALLENGE_SIZE);
// JW: Launcher passes in password as property of Options object,
// so there's no need to pop up a dialog asking for a username
// and password, if they are already recorded within the Options object.
StringBuffer passwd = new StringBuffer();
// Cast cc object as CConn, so we access to opts
CConn cconn = (CConn) cc;
if (cconn.opts.password==null || cconn.opts.password.equals(""))
CConn.upg.getUserPasswd(null, passwd);
else
passwd.append(cconn.opts.password);
// Calculate the correct response
byte[] key = new byte[8];
int pwdLen = passwd.length();
byte[] utf8str = new byte[pwdLen];
try {
utf8str = passwd.toString().getBytes("UTF8");
} catch(java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}
for (int i = 0; i < 8; i++)
key[i] = i < pwdLen ? utf8str[i] : 0;
DesCipher des = new DesCipher(key);
for (int j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
des.encrypt(challenge, j, challenge, j);
// Return the response to the server
os.writeBytes(challenge, 0, VNC_AUTH_CHALLENGE_SIZE);
os.flush();
return true;
} | 6 |
public static String[] forgetPassword(String UserName) {
String strQuestion[] = new String[2];
String strList = FileHandle.readDataFile(strFile_User);
strList = strList.replace("<DairyRecord>", "");
strList = strList.replace("</DairyRecord>", "");
//String[] strLine = strList.split(System.getProperty(strLineSeparator));
while(!strList.isEmpty()) {
int start = strList.indexOf("<Register>") + 10;
int end = strList.indexOf("</Register>");
//intercept one record
String singleRecord = strList.substring(start, end);
//erase the current record from the base string
strList = strList.substring(end + 11);
//intercept username
String strUser = singleRecord.substring(singleRecord.indexOf("<UserName>") + 10, singleRecord.indexOf("</UserName>"));
//Check Username
if(UserName.equals(strUser)){
//erase xml element from single record
singleRecord = singleRecord.substring(singleRecord.indexOf("infos") + 5, singleRecord.indexOf("><", singleRecord.indexOf("infos") + 5));
String[] strProperties = singleRecord.split(",");
for (int i = 0; i < strProperties.length; i ++) {
int iOP = strProperties[i].indexOf("=");
//if(strProperties[i].substring(0, iOP).equals("SecurityQ")) {
if(strProperties[i].substring(0, iOP + 1).equals(strSecurityQ)) {
strQuestion[0] = strProperties[i].replace("\"", "").substring(iOP + 1);
//} else if(strProperties[i].substring(0, iOP).equals("SecurityA")) {
} else if(strProperties[i].substring(0, iOP + 1).equals(strSecurityA)) {
strQuestion[1] = strProperties[i].replace("\"", "").substring(iOP + 1);
break;
}
}
//Stop searching
break;
}
}
return strQuestion;
} | 5 |
public void run() {
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
output = new DataOutputStream(socket.getOutputStream());
String line, path = root;
int method = 0;
while ((line = in.readLine()) != null) {
String temp = line.toUpperCase();
if (temp.startsWith("GET")) {
method = 1;
String p = line.split(" ")[1];
path = root + (root.endsWith("/") ? p.substring(1) : p);
} else if (temp.startsWith("HEAD"))
method = 2;
if (method == 0) {
onError(this, 501);
return;
}
File file = new File(clean(path));
String[] f = file.getName().split("\\.");
if (!file.exists()) {
onError(this, 404);
return;
}
if (method == 1) {
setHeader(200, "." + f[f.length - 1]);
writeFile(file);
}
return;
}
} catch (Exception ex) {
ex.printStackTrace();
}
} | 8 |
private void update(int delta) {
rotation += 0.15f * delta;
if (Keyboard.isKeyDown(Keyboard.KEY_LEFT))
xpos -= 0.35f * delta;
if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT))
xpos += 0.35f * delta;
if (Keyboard.isKeyDown(Keyboard.KEY_UP))
ypos -= 0.35f * delta;
if (Keyboard.isKeyDown(Keyboard.KEY_DOWN))
ypos += 0.35f * delta;
// Keep quad on screen
if (xpos < 0)
xpos = 0;
if (xpos > x_res)
xpos = x_res;
if (ypos > y_res)
ypos = y_res;
if (ypos < 0)
ypos = 0;
updateFPS();
} | 8 |
public final assignStatement assignStatement() throws RecognitionException {
assignStatement assignStatement = null;
Token ID20=null;
expression op1 =null;
expression op2 =null;
try {
// /Users/yefang/Documents/research/frontEndGen/test1/src/grammar1/Pi.g:90:58: ( ID ( '[' op1= expr ']' )* '=' op2= expr ';' )
// /Users/yefang/Documents/research/frontEndGen/test1/src/grammar1/Pi.g:91:9: ID ( '[' op1= expr ']' )* '=' op2= expr ';'
{
assignStatement = new assignStatement(); String name = ""; boolean isArrayElement = false; ArrayList<expression> index = null;
ID20=(Token)match(input,ID,FOLLOW_ID_in_assignStatement586);
name = (ID20!=null?ID20.getText():null);
// /Users/yefang/Documents/research/frontEndGen/test1/src/grammar1/Pi.g:93:9: ( '[' op1= expr ']' )*
loop8:
while (true) {
int alt8=2;
int LA8_0 = input.LA(1);
if ( (LA8_0==54) ) {
alt8=1;
}
switch (alt8) {
case 1 :
// /Users/yefang/Documents/research/frontEndGen/test1/src/grammar1/Pi.g:93:10: '[' op1= expr ']'
{
match(input,54,FOLLOW_54_in_assignStatement601);
pushFollow(FOLLOW_expr_in_assignStatement607);
op1=expr();
state._fsp--;
match(input,55,FOLLOW_55_in_assignStatement609);
if(!isArrayElement){
isArrayElement = true;
index = new ArrayList<expression>();
}
index.add(op1);
}
break;
default :
break loop8;
}
}
if(isArrayElement){
arrayElement lhs = new arrayElement(name, index);
assignStatement.lhs = lhs;
}
else
assignStatement.name = name;
match(input,49,FOLLOW_49_in_assignStatement653);
pushFollow(FOLLOW_expr_in_assignStatement668);
op2=expr();
state._fsp--;
assignStatement.assignment = op2;
match(input,46,FOLLOW_46_in_assignStatement680);
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
}
return assignStatement;
}
// $ANTLR end "assignStatement"
// $ANTLR start "whileStatement"
// /Users/yefang/Documents/research/frontEndGen/test1/src/grammar1/Pi.g:113:1: whileStatement returns [whileStatement whileStatement] : WHILE ( loopInvariant )? '(' expr ')' '{' ( statement )+ '} | 7 |
public Display(final double s, final Chunk c) {
chunk = c;
scale = s;
setPreferredSize(getAssumedSize());
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(final MouseEvent e) {
final double scale = getScale();
final int x = (int) (e.getX() / scale);
final int z = (int) (e.getY() / scale);
if(x >= 0 && x < 16 && z >= 0 && z < 16) {
final String tt = "x:" + x + " z:" + z + " b:"
+ getChunk().getBiome(new InChunkPosition(x, z)).name;
setTitle(TITLE + " - " + tt);
setToolTipText(tt);
} else {
setTitle(TITLE);
setToolTipText(null);
}
}
@Override
public void mouseExited(final MouseEvent e) {
setTitle(TITLE);
setToolTipText(null);
}
});
} | 4 |
public static void main(String[] args) throws InterruptedException, ExecutionException {
final SynchronousQueue<Integer> queue = new SynchronousQueue<Integer>();
new Thread() {
@Override
public void run() {
try {
while (running) {
System.out.println("size1:" + queue.size());
sleep(1000);
//System.out.println("element:" + queue.take());
//System.out.println("size2:" + queue.size());
}
} catch (/*Interrupted*/Exception e) {
e.printStackTrace();
}
}
}.start();
queue.put(1);
queue.put(2);
queue.put(3);
//*4
ScheduledExecutorService service= Executors.newScheduledThreadPool(1);
ScheduledFuture future2=service.schedule(new Callable()
{
public String call() throws InterruptedException {
running = false;
return "taskcancelled!";
}
},5, TimeUnit.SECONDS);
System.out.println(future2.get());
} | 2 |
@Override
public BufferedImage draw()
{
BufferedImage image = new BufferedImage(Chunk.getPixelLength(), Chunk.getPixelLength(), BufferedImage.TYPE_INT_ARGB);
Graphics2D gI = image.createGraphics();
return image;
} | 0 |
public void solveSudoku(char[][] board) {
boolean [][] rows = new boolean[9][9];
boolean [][] cols = new boolean[9][9];
boolean [][] cells = new boolean[9][9];
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j){
if(board[i][j] == '.') continue;
int num = board[i][j] - '0' - 1;
rows[i][num] = true;
cols[j][num] = true;
cells[3*(i/3)+(j/3)][num] = true;
}
}
solveSudokuRec(board, rows, cols, cells, 0);
} | 3 |
public static void executeInstance(NanoHTTPD server) {
try {
server.start();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
System.exit(-1);
}
System.out.println("Server started, Hit Enter to stop.\n");
try {
System.in.read();
} catch (Throwable ignored) {
}
server.stop();
System.out.println("Server stopped.\n");
} | 2 |
public boolean clearPathInDiagonalBetween(Field from, Field to) { // Is diagonal path between fields clear?
int fileAdjustment = from.file < to.file ? 1 : -1; // Move left or right
int rankAdjustment = from.rank < to.rank ? 1 : -1; // Move up or down
char file = (char) (from.file + fileAdjustment);
char rank = (char) (from.rank + rankAdjustment);
while (rank != to.rank) {
if (this.getField(file, rank).hasPiece()) {
return false;
}
rank = (char) (rank + rankAdjustment);
file = (char) (file + fileAdjustment);
}
return true;
} | 4 |
public TalkingFrame() {
frame = this;
this.setVisible(true);
this.setIconImage(new ImageIcon("images/logo.ico").getImage());
this.setLayout(new BorderLayout());
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
talkPanel = new JPanel();
talkPanel.setLayout(new FlowLayout());
JButton talkButton[] = new JButton[6];
for (int i = 1; i <= 6; i++) {
talkButton[i - 1] = new JButton(new ImageIcon("images/1" + i
+ ".jpg"));
talkButton[i - 1].setBounds(new Rectangle(new Dimension(25, 26)));
talkPanel.add(talkButton[i - 1]);
}
tabbedPane.addTab("聊天", null, talkPanel, "聊天选项");
this.add(tabbedPane, BorderLayout.NORTH);
playPanel = new JPanel();
playPanel.setLayout(new FlowLayout());
JButton playButton[] = new JButton[6];
for (int i = 1; i <= 6; i++) {
playButton[i - 1] = new JButton(new ImageIcon("images/2" + i
+ ".jpg"));
playPanel.add(playButton[i - 1]);
}
tabbedPane.addTab("娱乐", null, playPanel, "娱乐选项");
usePanel = new JPanel();
usePanel.setLayout(new FlowLayout());
JButton useButton[] = new JButton[4];
for (int i = 1; i <= 4; i++) {
useButton[i - 1] = new JButton(new ImageIcon("images/3" + i
+ ".jpg"));
usePanel.add(useButton[i - 1]);
}
tabbedPane.addTab("应用", null, usePanel, "应用选项");
toolPanel = new JPanel();
toolPanel.setLayout(new FlowLayout());
JButton toolButton[] = new JButton[3];
for (int i = 1; i <= 3; i++) {
toolButton[i - 1] = new JButton(new ImageIcon("images/4" + i
+ ".jpg"));
toolPanel.add(toolButton[i - 1]);
}
tabbedPane.addTab("工具", null, toolPanel, "工具选项");
this.add(tabbedPane, BorderLayout.NORTH);
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
acceptArea = new JTextArea(13, 15);
acceptArea.setLineWrap(true);
acceptArea.setEditable(false);
JScrollPane scrollAccept = new JScrollPane(acceptArea);
scrollAccept
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollAccept
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
centerPanel.add(scrollAccept);
toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setLayout(new BoxLayout(toolBar, BoxLayout.X_AXIS));
JButton barButton[] = new JButton[10];
for (int i = 1; i <= 10; i++) {
barButton[i - 1] = new JButton(new ImageIcon("images/6" + i
+ ".jpg"));
toolBar.add(barButton[i - 1]);
}
styleCombo = new StyleCombo(this);
toolBar.add(styleCombo.styleCombo);
barButton[0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFontChooser fontChooser = new JFontChooser();
Font font = fontChooser.getFont();
acceptArea.setFont(font);
sendArea.setFont(font);
}
});
centerPanel.add(toolBar);
sendTip = "请在这里输入文字,然后点击“发送”,发送信息!";
sendArea = new JTextArea(sendTip, 4, 15);
sendArea.setLineWrap(true);
// 捕捉点击首次在输入框的点击事件,清除输入提示信息!
sendArea.addMouseListener(new MouseAdapter() {
boolean cleared = false;
public void mouseClicked(MouseEvent e) {
if (!cleared) {
if (sendArea.getText() != sendTip) {
sendArea.setText(null);
cleared = !cleared;
}
}
}
});
JScrollPane scrollSend = new JScrollPane(sendArea); // 将输入框加入到滚动面板,并设置滚动条出现条件
scrollSend
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollSend
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
centerPanel.add(scrollSend);
JPanel footPanel = new JPanel();
footPanel.add(Box.createHorizontalGlue());
footPanel.add(Box.createRigidArea(new Dimension(160, 0)));
clearButton = new JButton("清空"); // 点击“清空”,清空输入框
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
sendArea.setText(null);
/*
* setVisible(false); setSize(0,0);
*/
}
});
footPanel.add(clearButton);
footPanel.add(Box.createRigidArea(new Dimension(1, 0)));
concelButton = new JButton("退出"); // 点击“退出”,显示确认对话框,点击“确定”,退出!
concelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// dispose(); //使用这个方法似乎不是真正退出,为什么??
int i = JOptionPane.showConfirmDialog(null, "你确定退出吗?", "退出",
JOptionPane.OK_CANCEL_OPTION);
if (i == JOptionPane.YES_NO_OPTION)
System.exit(0);
}
});
footPanel.add(concelButton);
// stringBuffer = new StringBuffer(10);
footPanel.add(Box.createRigidArea(new Dimension(1, 0)));
sendButton = new JButton("发送"); // 点击发送,将输入框的信息发送过去!
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!(sendArea.getText() == null)) // 如何设置条件,使其在信息为空时不能发送??
{
// stringBuffer.append(sendArea.getText()
// + "\n\n");
// if(sendArea.getText()!=null)
// //如何让它为空是,不能发送??
acceptArea.append("撒旦 " + new Date() + "\n"
+ sendArea.getText() + "\n\n");
// acceptArea.setText(stringBuffer.toString());
}
sendArea.setText(null);
}
});
sendButton.setDefaultCapable(true);
footPanel.add(sendButton);
centerPanel.add(footPanel);
this.add(centerPanel, BorderLayout.CENTER);
eastPanel = new JPanel();
this.add(eastPanel, BorderLayout.EAST);
// eastPanel.setLayout(new
// BoxLayout(eastPanel,BoxLayout.Y_AXIS));
eastPanel.setLayout(new BorderLayout());
clock = new ClockPanel(80, 50, 35);
// eastPanel.add(clock);
eastPanel.add(clock, BorderLayout.CENTER);
MusicPlayer musicPlayer = new MusicPlayer(this);
// eastPanel.add(musicPlayer);
eastPanel.add(musicPlayer, BorderLayout.SOUTH);
this.setSize(560, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null); // 设为null,
// 将窗口置于屏幕的中央
} | 9 |
public IndoorFaceControl(IndoorFace srcIndoorFace)
{
super();
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setBorder(new BevelBorder(BevelBorder.LOWERED));
this.indoorFace = srcIndoorFace;
CollapsablePanel.IndirectDataSource data1IndirectDataSource = new CollapsablePanel.IndirectDataSource()
{
public Component getComponent()
{
return makeNonStretchedPanelFor(new ByteDataTableControl(indoorFace.getFacetData(), indoorFace.getFacetData().length, 0));
}
};
this.add(makeNonStretchedPanelFor(new CollapsablePanel("Facets", data1IndirectDataSource, true)));
final int vertexNumberList[] = indoorFace.getVertexIndexArray();
JPanel vertexListPanel = (JPanel)makeNonStretchedPanelFor(new JLabel("Vertex List: "));
for (int vertexNumberIndex = 0; vertexNumberIndex < vertexNumberList.length; ++vertexNumberIndex)
{
final int finalVertexNumberIndex = vertexNumberIndex;
vertexListPanel.add(new IntTextField(3, new IntValueHolder() {
public int getValue() { return vertexNumberList[finalVertexNumberIndex]; }
public void setValue(int value) { vertexNumberList[finalVertexNumberIndex] = value; }
}));
}
this.add(vertexListPanel);
final short xDisplacementArray[] = indoorFace.getXDisplacementArray();
JPanel xDisplacementPanel = (JPanel)makeNonStretchedPanelFor(new JLabel("X Displacement List: "));
for (int vertexNumberIndex = 0; vertexNumberIndex < xDisplacementArray.length; ++vertexNumberIndex)
{
final int finalVertexNumberIndex = vertexNumberIndex;
xDisplacementPanel.add(new ShortTextField(new ShortValueHolder() {
public short getValue() { return xDisplacementArray[finalVertexNumberIndex]; }
public void setValue(short value) { xDisplacementArray[finalVertexNumberIndex] = value; }
}));
}
this.add(xDisplacementPanel);
final short yDisplacementArray[] = indoorFace.getYDisplacementArray();
JPanel yDisplacementPanel = (JPanel)makeNonStretchedPanelFor(new JLabel("Y Displacement List: "));
for (int vertexNumberIndex = 0; vertexNumberIndex < yDisplacementArray.length; ++vertexNumberIndex)
{
final int finalVertexNumberIndex = vertexNumberIndex;
yDisplacementPanel.add(new ShortTextField(new ShortValueHolder() {
public short getValue() { return yDisplacementArray[finalVertexNumberIndex]; }
public void setValue(short value) { yDisplacementArray[finalVertexNumberIndex] = value; }
}));
}
this.add(yDisplacementPanel);
final short zDisplacementArray[] = indoorFace.getZDisplacementArray();
JPanel zDisplacementPanel = (JPanel)makeNonStretchedPanelFor(new JLabel("Z Displacement List: "));
for (int vertexNumberIndex = 0; vertexNumberIndex < zDisplacementArray.length; ++vertexNumberIndex)
{
final int finalVertexNumberIndex = vertexNumberIndex;
zDisplacementPanel.add(new ShortTextField(new ShortValueHolder() {
public short getValue() { return zDisplacementArray[finalVertexNumberIndex]; }
public void setValue(short value) { zDisplacementArray[finalVertexNumberIndex] = value; }
}));
}
this.add(zDisplacementPanel);
final short uTextureArray[] = indoorFace.getUTextureArray();
JPanel uTexturePanel = (JPanel)makeNonStretchedPanelFor(new JLabel("U Texture List: "));
for (int vertexNumberIndex = 0; vertexNumberIndex < uTextureArray.length; ++vertexNumberIndex)
{
final int finalVertexNumberIndex = vertexNumberIndex;
uTexturePanel.add(new ShortTextField(new ShortValueHolder() {
public short getValue() { return uTextureArray[finalVertexNumberIndex]; }
public void setValue(short value) { uTextureArray[finalVertexNumberIndex] = value; }
}));
}
this.add(uTexturePanel);
final short vTextureArray[] = indoorFace.getVTextureArray();
JPanel vTexturePanel = (JPanel)makeNonStretchedPanelFor(new JLabel("V Texture List: "));
for (int vertexNumberIndex = 0; vertexNumberIndex < vTextureArray.length; ++vertexNumberIndex)
{
final int finalVertexNumberIndex = vertexNumberIndex;
vTexturePanel.add(new ShortTextField(new ShortValueHolder() {
public short getValue() { return vTextureArray[finalVertexNumberIndex]; }
public void setValue(short value) { vTextureArray[finalVertexNumberIndex] = value; }
}));
}
this.add(vTexturePanel);
JPanel bitmapPanel = (JPanel)makeNonStretchedPanelFor(new JLabel("Bitmap: "));
bitmapPanel.add(new StringTextField(new StringValueHolder() {
public String getValue() { return indoorFace.getBitmapName(); }
public void setValue(String value) { indoorFace.setBitmapName(value); }
public int getMaxLength() { return 0; }
}));
this.add(bitmapPanel);
} | 6 |
private void updateDisplay() {
StringBuilder txt = new StringBuilder();
for (Player p : game.getPlayers()) {
txt.append("Player ").append(p.getNum());
if (game.getCurrentPlayer().equals(p)) {
txt.append(" *");
}
txt.append("<br>");
txt.append("Money: ").append(p.getMoney()).append("<br>");
txt.append("Has: ");
for (Token token : p.getTokens()) {
txt.append(token).append(" ");
}
txt.append("<br>");
}
txt.insert(0, "<html>").append("</html>");
label.setText(txt.toString());
panel.setSize(label.getPreferredSize());
System.out.println(txt);
repaint();
} | 3 |
@Override
public double getResult(Object[] object) {
double temp = ((Complex)object[1]).getRe();
double temp2 = ((Complex)object[1]).getIm();
return (Boolean)object[2] ? (temp > -bailout && temp < bailout || temp2 > -bailout && temp2 < bailout ? (Integer)object[0] + 100906 : -((Integer)object[0] + 100850)) : (temp > -bailout && temp < bailout || temp2 > -bailout && temp2 < bailout ? (Integer)object[0] + 100800 : -((Integer)object[0] + 100850));
} | 9 |
private void placeIdentityDiscs() {
while (getElementCoverage(IdentityDisc.class) < COVERAGE) {
final Position randomPos = getRandomPosition();
final IdentityDisc idDisc = new IdentityDisc(grid);
if (grid.validPosition(randomPos) && canHaveAsElement(randomPos, idDisc))
grid.addElementToPosition(idDisc, randomPos);
}
} | 3 |
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return "Player";
case 1:
return "Status";
case 2:
return "Score";
}
return null;
} | 3 |
private void parsePrimitiveDef(){
PrimitiveDef def = new PrimitiveDef();
def.setType(Utils.createPrimitiveType(parts[2]));
int pinCount = Integer.parseInt(parts[3]);
int elementCount = Integer.parseInt(parts[4]);
ArrayList<PrimitiveDefPin> pins = new ArrayList<PrimitiveDefPin>(pinCount);
ArrayList<Element> elements = new ArrayList<Element>(elementCount);
for(int i = 0; i < pinCount; i++){
readLine();
PrimitiveDefPin p = new PrimitiveDefPin();
p.setExternalName(parts[2]);
p.setInternalName(parts[3]);
p.setOutput(parts[4].equals("output)"));
pins.add(p);
}
for(int i = 0; i < elementCount; i++){
readLine();
Element e = new Element();
e.setName(parts[2]);
int elementPinCount = Integer.parseInt(parts[3].replace(")", ""));
e.setBel(parts.length > 5 && parts[4].equals("#") && parts[5].equals("BEL"));
for(int j = 0; j < elementPinCount; j++){
readLine();
PrimitiveDefPin elementPin = new PrimitiveDefPin();
elementPin.setInternalName(parts[2]);
elementPin.setOutput(parts[3].equals("output)"));
e.addPin(elementPin);
}
while(!readLine().startsWith("\t\t)")){
if(line.startsWith("\t\t\t(cfg ")){
for(int k = 2; k < parts.length; k++){
e.addCfgOption(parts[k].replace(")", ""));
}
}
else if(line.startsWith("\t\t\t(conn ")){
Connection c = new Connection();
c.setElement0(parts[2]);
c.setPin0(parts[3]);
c.setForwardConnection(parts[4].equals("==>"));
c.setElement1(parts[5]);
c.setPin1(parts[6].substring(0, parts[6].length()-1));
e.addConnection(c);
}
}
elements.add(e);
}
def.setPins(pins);
def.setElements(elements);
defs.add(def);
} | 9 |
private static String exec(String ...cmd)
{
try {
ProcessBuilder pb = new ProcessBuilder(cmd);
Process process = pb.start();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream stdout = process.getInputStream();
int readByte = stdout.read();
while(readByte >= 0) {
baos.write(readByte);
readByte = stdout.read();
}
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
BufferedReader reader = new BufferedReader(new InputStreamReader(bais));
StringBuilder builder = new StringBuilder();
while(reader.ready()) {
builder.append(reader.readLine());
}
reader.close();
return builder.toString();
}
catch(IOException e) {
throw new LanternaException(e);
}
} | 3 |
public static void extract(File file, String outDir)
{
String result="";
String outFileName = null;
POITextExtractor extractor = null;
boolean filefound=false;
try {
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
if (file.getName().toLowerCase().endsWith(".docx"))
{
XWPFDocument doc = new XWPFDocument(fis);
extractor = new XWPFWordExtractor(doc);
filefound=true;
}
if (file.getName().toLowerCase().endsWith(".doc"))
{
HWPFDocument doc = new HWPFDocument(fis);
extractor=new WordExtractor(doc);
filefound=true;
}
if(filefound)
{
System.out.println("Processing :"+file.getAbsolutePath());
outFileName = file.getName() + ".txt";
result = extractor.getText();
File outFile = new File(outDir+"/"+outFileName);
Writer output = new BufferedWriter(new FileWriter(outFile));
output.write(result);
output.close();
}
else
{
System.out.println("Skipping :"+file.getAbsolutePath()+" Not A Word Document");
}
} catch (Exception exep)
{
exep.printStackTrace();
System.out.println("Exception :");
}
} | 4 |
private void ArribaM() {
//Arriba
Punto temp = vibora.get(0);// La antigua Cabeza
Punto p = new Punto();
p.x = temp.x;
p.y = temp.y - 1;
if (validacion(p)) {
List<Punto> nueva = new ArrayList<Punto>();
nueva.add(p);
nueva.addAll(vibora);
if (!esComida(p))
nueva.remove(nueva.size() - 1);
else {
// Creamos una nueva Presa
Ventana.setP(new Presa(Tablero.filas, Tablero.columnas));
}
vibora = nueva;
} else {
FinDelJuego();
}
} | 2 |
public void shoot(){
if(player.ammo > 0){
for(int i = 0; i < lasers.length; i++){
if(lasers[i] == null){
lasers[i] = new Laser(this,settings.shieldLaserColor, settings.laserSpeed,
player.getCenterPointX(), player.getCenterPointY() - 20,
Math.PI * 3, false, false,
settings.laserWidth, settings.laserHeight, player);
break;
}
}
player.ammo--;
}
} | 3 |
public void SetWaitTime(int waitTime)
{
//set the wait time
this.waitTime = waitTime;
} | 0 |
private void printSubclasses(final Type classType, final PrintWriter out,
final boolean recurse, final int indent) {
final Iterator iter = this.subclasses(classType).iterator();
while (iter.hasNext()) {
final Type subclass = (Type) iter.next();
indent(out, indent);
out.println(subclass);
if (recurse) {
printSubclasses(subclass, out, recurse, indent + 2);
}
}
} | 2 |
private Object[] readOpenList() throws IOException {
ArrayList objects = new ArrayList();
int code;
while (true) {
try {
code = readNextCode();
} catch (EOFException e) {
code = Codes.END_COLLECTION;
}
if (code == Codes.END_COLLECTION) {
return objects.toArray();
}
objects.add(read(code));
}
} | 3 |
@Override
public void render(Graphics2D graphics) {
int startPointGridXCoordinate = 150;
int startPointGridYCoordinate = 20;
for (PlayerInfo p : objectTron.getPlayers()) {
Image cellToRender = cellFinishRed;
if (p.getPlayerNumber() == 2)
cellToRender = cellFinishBlue;
else if (p.getPlayerNumber() == 3)
cellToRender = cellFinishYellow;
else if (p.getPlayerNumber() == 4)
cellToRender = cellFinishGreen;
graphics.drawImage(cellToRender, (p.getBeginPosition().xCoordinate * 41) + startPointGridXCoordinate, (p.getBeginPosition().yCoordinate * 41) + startPointGridYCoordinate, 40, 40, null);
}
} | 4 |
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (args.length != 0) {
return false;
}
sender.sendMessage(plugin.getBroadcaster().styleMessage("Commands: "));
if (sender.hasPermission(HGPermission.ADMIN.toString())) {
sender.sendMessage("/hgadmin <session> <player> - Promotes a player to admin");
}
if (sender.hasPermission(HGPermission.CREATE.toString())) {
sender.sendMessage("/hgcreate <name> - Creates a session");
sender.sendMessage("/hgfinish - Finishes a created session");
}
if (sender.hasPermission(HGPermission.DELETE.toString())) {
sender.sendMessage("/hgdelete <name> - Deletes a session");
}
sender.sendMessage("/hghelp - Shows this information");
sender.sendMessage("/hg - Shows general information about the plugin");
sender.sendMessage("/hginfo <session> - Shows information about a session");
sender.sendMessage("/hgjoin <session> - Joins a session");
sender.sendMessage("/hgleave- Leaves a session");
sender.sendMessage("/hglist - Lists all the currently created sessions");
if (sender.hasPermission(HGPermission.RELOAD.toString())) {
sender.sendMessage("/hgreload - Reloads the configuration");
}
if (sender.hasPermission(HGPermission.START.toString())) {
sender.sendMessage("/hgstart <session> - Starts a session");
}
if (sender.hasPermission(HGPermission.STOP.toString())) {
sender.sendMessage("/hgstop <session> - Stops a session");
}
if (sender.hasPermission(HGPermission.FORCE_JOIN.toString())) {
sender.sendMessage("/hgforcejoin <session> <player> - Forces a player to join a session");
}
if (sender.hasPermission(HGPermission.FORCE_LEAVE.toString())) {
sender.sendMessage("/hgforcequit <player> - Forces a player to leave the session they are currently in");
}
return true;
} | 9 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(UpdaterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UpdaterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UpdaterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UpdaterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UpdaterGUI().setVisible(true);
}
});
} | 6 |
@WebMethod(operationName = "ReadInvoiceIn")
public ArrayList<InvoiceIn> ReadInvoiceIn(@WebParam(name = "inv_in_id") String inv_in_id) {
InvoiceIn inv_in = new InvoiceIn();
ArrayList<InvoiceIn> inv_ins = new ArrayList<InvoiceIn>();
ArrayList<QueryCriteria> qc = new ArrayList<QueryCriteria>();
if(!inv_in_id.equals("-1")){
qc.add(new QueryCriteria("inv_in_id", inv_in_id, Operand.EQUALS));
}
ArrayList<String> fields = new ArrayList<String>();
ArrayList<QueryOrder> order = new ArrayList<QueryOrder>();
try {
inv_ins = inv_in.Read(qc, fields, order);
} catch (SQLException ex) {
Logger.getLogger(JAX_WS.class.getName()).log(Level.SEVERE, null, ex);
}
if(inv_ins.isEmpty()){
return null;
}
return inv_ins;
} | 3 |
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("\n -------------------- MENU --------------------");
System.out.print("\n| |");
System.out.print("\n| 1 - Habitantes |");
System.out.print("\n| 2 - Inmuebles |");
System.out.print("\n| 3 - Espacios Públicos |");
System.out.print("\n| 4 - Ayuntamientos |");
System.out.print("\n| 5 - Partidos políticos |");
System.out.print("\n| 6 - Salir |");
System.out.print("\n| |");
System.out.print("\n ----------------------------------------------");
System.out.print("\nElija un número de las opciones de arriba: ");
String respuesta = sc.nextLine();
switch (respuesta) {
/*------------------------------------------------------ HABITANTES ---------------------------------------------------------*/
case "1": {
Habitante habitante = new Habitante();
habitante.habitanteMain();
break;
}
/*------------------------------------------------------ INMUEBLES ---------------------------------------------------------*/
case "2": {
Inmueble inmueble = new Inmueble();
inmueble.inmuebleMain();
break;
}
/*------------------------------------------------------ ESPACIOS PUBLICOS ---------------------------------------------------------*/
case "3": {
EspacioPublico espacioPublico = new EspacioPublico();
espacioPublico.espacioPublicoMain();
break;
}
/*------------------------------------------------------ AYUNTAMIENTOS ---------------------------------------------------------*/
case "4": {
Ayuntamiento ayuntamiento = new Ayuntamiento();
ayuntamiento.ayuntamientoMain();
break;
}
/*------------------------------------------------------ PARTIDOS ---------------------------------------------------------*/
case "5": {
Partido partido = new Partido();
partido.partidoMain();
break;
}
/*------------------------------------------------------ SALIR ---------------------------------------------------------*/
case "6": {
System.out.println("\n\nSaliendo del programa\n");
break;
}
/*------------------------------------------------------ DEFECTO ---------------------------------------------------------*/
default: {
System.out.println("\n\nCaracter invalido\n");
System.out.println("Saliendo del programa\n");
break;
}
}
} | 6 |
@Override
public void mouseReleased(final MouseEvent e) {
if (this.draggedComponent != null) {
final Point p = e.getPoint();
final Set<Element> ignoreSelection = new HashSet<>();
ignoreSelection.add(this.draggedEdge);
final Element element = getGraphicPanel().getElementAt(p, ignoreSelection);
if (element instanceof Vertex) {
System.out.println("edge move: element hit");
final Vertex vertex = (Vertex) element;
if (this.handlerPos == HandlerPosition.SOURCE) {
if (vertex.canHaveOutput()) {
this.draggedEdge.updateSource(vertex, null);
final BPComponent vertexComponent = (BPComponent) vertex.getComponent();
this.draggedComponent.setSourceX(p.x);
this.draggedComponent.setSourceY(p.y);
this.draggedComponent.updateComponent(vertexComponent, null);
}
} else if (this.handlerPos == HandlerPosition.TARGET) {
if (vertex.canHaveInput()) {
this.draggedEdge.updateTarget(vertex, null);
final BPComponent vertexComponent = (BPComponent) vertex.getComponent();
this.draggedComponent.setTargetX(p.x);
this.draggedComponent.setTargetY(p.y);
this.draggedComponent.updateComponent(null, vertexComponent);
}
}
} else {
if (this.handlerPos == HandlerPosition.SOURCE) {
this.draggedComponent.setSourceX(this.startX);
this.draggedComponent.setSourceY(this.startY);
} else if (this.handlerPos == HandlerPosition.TARGET) {
this.draggedComponent.setTargetX(this.startX);
this.draggedComponent.setTargetY(this.startY);
}
}
getGraphicPanel().repaint();
}
this.draggedEdge = null;
this.draggedComponent = null;
getPanel().getStateManager().moveToState(StateType.SELECT);
} | 8 |
public int getSpeed() {
return speed;
} | 0 |
public void placeableDoneDestroying(Placeable p) {
Player player = p.getDestroyingPlayer();
gameController.stopGather(player);
if (player != null) {
if (gameController.playerAddItem(player, p.getItemName(), 1) == 0) {
p.destroy();
SoundClip cl = new SoundClip("Player/Good");
}
}
if (gameController.multiplayerMode != gameController.multiplayerMode.NONE && registry.getNetworkThread() != null) {
if (registry.getNetworkThread().readyForUpdates()) {
UpdatePlaceable up = new UpdatePlaceable(p.getId());
up.action = "DoneDestroying";
registry.getNetworkThread().sendData(up);
}
}
} | 5 |
private static Kind findKind(String lexeme) {
for (Kind kind : Kind.values()) {
if (kind.lexeme.equals(lexeme)) {
return kind;
}
}
return null;
} | 2 |
private Emision buscarEmision(List idEmisionTemporada){
Emision emi = null;
for (Emision emision : emisiones) {
if (emision.obtenerTVEmite().equals(idEmisionTemporada.get(0)) &&
emision.obtenerFechaPrevista() == idEmisionTemporada.get(1)) // Comprobar como se comparan fechas.
emi = emision;
}
return emi;
} | 3 |
public static LedShape asciiToShape(int ascii) {
if(ascii >= 65 && ascii <= 90 || ascii >= 97 && ascii <= 122)
return charset[-65 + (ascii & ~(1 << 5))].clone();
if(ascii >= 48 && ascii <= 57)
return charset[-22 + ascii].clone();
return new LedShape(0,0, new LedRow(0));
} | 6 |
private void addItem(int numToAdd, ArrayList<Location> locations, boolean checkTargets)
{
Random rand = new Random(); //Random number generate to determine locations of spaces randomly
for(int i = 0; i < numToAdd; i++)
{
//Generate random location
Location newItem = new Location(rand.nextInt(MAX_X),rand.nextInt(MAX_Y));
// Start by assuming no conflicts with a block or target
boolean conflict = false;
//Check to see if this location is already blocked
for(int j = 0; j < blockedLocs.size(); j++){
if(newItem.equals(blockedLocs.get(j))){
conflict = true;
}
}
// blocks are added first, don't need to check targets
if (checkTargets)
{
//Check to see if this location is already a target
for(int j = 0; j < targetLocs.size(); j++){
if(newItem.equals(targetLocs.get(j))){
conflict = true;
}
}
}
// Add the location only if it is not already blocked and is not the starting location
// for one of the players
for (Player player : players)
{
if (newItem.equals(player.getLocation()))
conflict = true;
}
// If any conflict, we did not add an item, so redo this attempt
if(conflict){
i--;
}
else{
locations.add(newItem);
}
}
} | 9 |
public static Mask buildAnOtherMask(Direction d) {
switch (d) {
case HORIZONTAL:
double[][] dValues = { { 1, 1, -1 }, { 1, -2, -1 }, { 1, 1, -1 } };
return new Mask(dValues);
case VERTICAL:
double[][] aValues = { { 1, 1, 1 }, { 1, -2, 1 }, { -1, -1, -1 } };
return new Mask(aValues);
case DIAGONAL:
double[][] bValues = { { 1, 1, 1 }, { 1, -2, -1 }, { 1, -1, -1 } };
return new Mask(bValues);
case INVERSE_DIAGONAL:
double[][] cValues = { { 1, -1, -1 }, { 1, -2, -1 }, { 1, 1, 1 } };
return new Mask(cValues);
}
return null;
} | 4 |
private int esitaytaRivi(int rivinumero, int eiSaaJaadaTyhjaksi)
{
int tyhjaksiJatettava = -1;
do
tyhjaksiJatettava = satunnaisgeneraattori.nextInt((int)pelialue.alue().leveys() + 1) + (int)pelialue.alue().alkupiste().x();
while(tyhjaksiJatettava == eiSaaJaadaTyhjaksi);
for(float x = pelialue.alue().alkupiste().x(); x <= pelialue.alue().paatepiste().x(); x++)
{
Sijainti nykyinen = new Sijainti(x, pelialue.alue().paatepiste().y() - rivinumero );
if((int)x != tyhjaksiJatettava)
pelialue.tungePalikka(new TetrisPalikka(nykyinen));
else
pelialue.poistaPalikka(nykyinen);
}
return tyhjaksiJatettava;
} | 3 |
public static WaveData getWave(String pathToFile) {
File file;
if(Game.isRunningInIdea()) {
file = new File("src/main/resources/" + pathToFile);
}
else{
Console.log("outside IDE FOR WAVE");
file = new File(pathToFile);
}
byte[] bfile = new byte[(int)file.length()];
try(FileInputStream stream = new FileInputStream(file)) {
stream.read(bfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return WaveData.create(new ByteArrayInputStream (bfile));
} | 3 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 7 |
public void setType(int n) {
InputStreamReader isReader= new InputStreamReader(MyMenu.class.getClassLoader().getResourceAsStream(pathAttr));
try (BufferedReader reader = new BufferedReader(isReader)) {
String line = reader.readLine(); // read the first line containning the description of the column
while ((line = reader.readLine()) != null) { // Reading the file line by line
String[] split = line.split(";");
int ID = Integer.parseInt(split[0]);
if (n==ID){ // If we are on the line where the Menu is defined
int size = Integer.parseInt(split[1]);
int i = 0;
for (; i<size;++i){
String[] split2 = split[i+numConfColumn].split(",");
if (split2.length>1) {
MyMenu submenu = new MyMenu(split2[1]);
submenu.setType(Integer.parseInt(split2[0]));
menu.add(submenu); // submenu
} else {
menu.add(new MyMenuItem(Integer.parseInt(split[i+numConfColumn]))); // items
}
}
}
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
} | 5 |
public void setEnvironmentFrame(EnvironmentFrame frame) {
myEnvFrame = frame;
} | 0 |
public void addFriend(User user) {
if (isFriend(user) == IS_FRIEND)
return;
try {
String statement = new String("INSERT INTO " + FriendDBTable
+ " (uid1, uid2)"
+ " VALUES (?, ?)");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
stmt.setInt(1, userID);
stmt.setInt(2, user.userID);
stmt.executeUpdate();
String statement2 = new String("INSERT INTO " + FriendDBTable
+ " (uid1, uid2)"
+ " VALUES (?, ?)");
PreparedStatement stmt2 = DBConnection.con.prepareStatement(statement2);
stmt2.setInt(1, user.userID);
stmt2.setInt(2, userID);
stmt2.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} | 2 |
@EventHandler
public void onPlayerInteractEvent(PlayerInteractEvent event) {
Block clickedBlock = event.getClickedBlock();
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)
&& clickedBlock.getType() == Material.WALL_SIGN
&& clickedBlock.getState() instanceof Sign) {
Inventory inventory = getInventoryForSign(clickedBlock);
if (inventory != null) {
event.getPlayer().openInventory(inventory);
event.setCancelled(true);
}
}
} | 4 |
private static String prepare(LocalizationInfo info, Locale lang, boolean isDefaultLang) {
StringBuilder result = new StringBuilder();
result.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n");
result.append("<!-- " + GENERATOR_COMMENT + " -->\n\n");
result.append("<resources>\n");
String key, value, description;
for (LocalizationStructure.Record record : info.structure.getRecords()) {
switch (record.type) {
case SECTION:
result.append("\n\t<!-- ").append(record.value).append(" -->");
break;
case KEY:
key = record.value;
value = escapeValue(info.localization.getValue(key, lang));
description = record.description;
if (value == null || value.length() == 0) {
if (isDefaultLang) throw new LocalizationException("Missing value for default language (" +
lang + ") for key: " + key);
continue;
}
result.append("\t<string name=\"").append(key).append("\">").append(value).append("</string>");
if (description != null && description.length() > 0) {
result.append(" <!-- ").append(description).append(" -->");
}
break;
}
result.append('\n');
}
result.append("\n</resources>\n");
return result.toString();
} | 8 |
protected JSONValue serialize( Object value )
{
if( value instanceof String )
{
return serializeJSONString((String)value);
} else if( value instanceof Number ) {
return serializeJSONNumber((Number)value);
} else if( value instanceof Boolean) {
return serializeJSONBoolean((Boolean)value);
} else if( value instanceof Object[]) {
return serializeJSONArray((Object[])value);
} else if( value instanceof JSONValue) {
return (JSONValue) value;
}
return null;
} | 5 |
public void registerImportable(IImportable importable) throws StructureException {
if (this.parts.containsKey(importable.nameOf()))
throw new StructureException(String.format(
"Cannot register IImportable with the name %s: already exists!", importable.nameOf()));
parts.put(importable.nameOf(), importable);
} | 1 |
@SuppressWarnings("deprecation")
public Homework_current() {
initComponents();
try {
jEditorPane1.setPage("http://www.patana.ac.th/Gateway/eHomework.asp");
jEditorPane1.setMinimumSize(new Dimension(100, 16));
} catch (IOException ex) {
Logger.getLogger(Homework_current.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
private void selectChart() {
Object[] possibilities = {"Circolar", "Rectangular", "Linear"};
String s = (String)JOptionPane.showInputDialog(
getMainFrame(),
"Choose the chart type:\n",
"Chart Shape",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities,
"Rectangular");
String X = JOptionPane.showInputDialog(getMainFrame(), "Select Chart Width");
String Y = JOptionPane.showInputDialog(getMainFrame(), "Select Chart Height");
if ((s != null) && (s.length() > 0)) {
if(s.equals("Circolar"))
try {
Game.getInstance().setChart(new CircolarChart(Integer.parseInt(X),Integer.parseInt(Y)));
}
catch (Exception e) {
Game.getInstance().setChart(new CircolarChart(10, 10));
}
else if(s.equals("Rectangular"))
try {
Game.getInstance().setChart(new RectangularChart(Integer.parseInt(X),Integer.parseInt(Y)));
}
catch (Exception e) {
Game.getInstance().setChart(new RectangularChart(10,10));
}
else {
try {
Game.getInstance().setChart(new LinearChart(Integer.parseInt(X)));
}
catch (Exception e) {
Game.getInstance().setChart(new LinearChart(20));
}
}
}
} | 7 |
public boolean hasNext() {
return (this.size() != 0);
} | 0 |
public int getIdPos(){
PhpposAppConfigEntity appConfig = getAppConfig("id_pos");
return Integer.parseInt(appConfig.getValue());
} | 0 |
public void setHireDay(int year, int month, int day)
{
Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();
// Example of instance field mutation
hireDay.setTime(newHireDay.getTime());
} | 0 |
private void process() {
boolean borderGeometryWas;
boolean lineGeometryWas;
boolean voronoiGeometryWas;
boolean flatGeometryWas;
boolean gcodeGeometryWas;
boolean wasTranslucent;
double toolDiameterWas;
long startTime = System.currentTimeMillis();
String processName = getClass().toString();
processName = processName.substring(processName.lastIndexOf(".") + 1,
processName.length());
System.out.println((new Date(startTime)).toString() +
": " + processName + " started");
visolate.enableControls(false);
model.enableControls(false);
display.processStarted();
borderGeometryWas = model.isBorderGeometryEnabled();
lineGeometryWas = model.isLineGeometryEnabled();
voronoiGeometryWas = model.isVoronoiGeometryEnabled();
flatGeometryWas = model.isFlatGeometryEnabled();
wasTranslucent = model.isTranslucent2D();
gcodeGeometryWas = model.isGCodeGeometryEnabled();
toolDiameterWas = model.getToolDiameter();
// System.out.println("border: " + borderGeometryWas);
// System.out.println("line: " + lineGeometryWas);
// System.out.println("voronoi: " + voronoiGeometryWas);
// System.out.println("flat: " + flatGeometryWas);
// System.out.println("translucent: " + wasTranslucent);
// System.out.println("gcode: " + gcodeGeometryWas);
// System.out.println("tool diameter: " + toolDiameterWas);
dpi = display.getDPI();
System.out.println("DPI: " + dpi);
Rect b = model.getModelBounds();
mosaicBounds = new Rect(b.x - MOSAIC_BORDER_PELS/((double) dpi),
b.y - MOSAIC_BORDER_PELS/((double) dpi),
b.width + 2.0*MOSAIC_BORDER_PELS/((double) dpi),
b.height + 2.0*MOSAIC_BORDER_PELS/((double) dpi));
canvasWidth = display.getVirtualCanvasWidth();
canvasHeight = display.getVirtualCanvasHeight();
canvasWidthPels = display.getCanvasWidth();
canvasHeightPels = display.getCanvasHeight();
modelWidth = mosaicBounds.width;
modelHeight = mosaicBounds.height;
modelWidthPels = (int) Math.ceil(dpi*modelWidth);
modelHeightPels = (int) Math.ceil(dpi*modelHeight);
rows = modelHeight/canvasHeight;
cols = modelWidth/canvasWidth;
numRows = (int) Math.ceil(rows);
numCols = (int) Math.ceil(cols);
visolate.resetProgressBar(numRows*numCols);
processStarted();
for (int r = 0; r < numRows; r++) {
for (int c = 0; c < numCols; c++) {
double left = c*canvasWidth;
double top = modelHeight - r*canvasHeight;
double right = left + canvasWidth;
if (right > mosaicBounds.width)
right = mosaicBounds.width;
double bottom = top - canvasHeight;
if (bottom < 0.0)
bottom = 0.0;
// int ulx = (int) Math.ceil(left*((double) dpi));
// int uly = (int) Math.ceil((modelHeight-top)*((double) dpi));
int ulx = c*canvasWidthPels;
int uly = r*canvasHeightPels;
int lrx = ulx+canvasWidthPels;
if (lrx > modelWidthPels)
lrx = modelWidthPels;
int lry = uly+canvasHeightPels;
if (lry > modelHeightPels)
lry = modelHeightPels;
int width = lrx-ulx;
int height = lry-uly;
left += mosaicBounds.x;
bottom += mosaicBounds.y;
right += mosaicBounds.x;
top += mosaicBounds.y;
double cx = left + canvasWidth/2;
double cy = top - canvasHeight/2;
display.setCenter(cx, cy);
try {
display.waitForViewUpdate();
} catch (InterruptedException e) {
thread.interrupt(); //re-set interrupt status
}
processTile(r, c,
ulx, uly,
width, height,
left, bottom, right, top);
if (thread.isInterrupted()) {
processInterrupted();
visolate.enableControls(true);
model.enableControls(true);
display.processFinished();
visolate.processFinished();
long endTime = System.currentTimeMillis();
System.out.println((new Date(endTime)).toString() +
": " + processName + " interrupted " +
"(" + (endTime-startTime) + "ms)");
return;
}
visolate.tickProgressBar();
}
}
processCompleted();
model.setToolDiameter(toolDiameterWas);
model.setTranslucent2D(wasTranslucent);
model.enableGCodeGeometry(gcodeGeometryWas);
model.enableFlatGeometry(flatGeometryWas);
model.enableVoronoiGeometry(voronoiGeometryWas);
model.enableLineGeometry(lineGeometryWas);
model.enableBorderGeometry(borderGeometryWas);
visolate.enableControls(true);
model.enableControls(true);
display.processFinished();
visolate.processFinished();
long endTime = System.currentTimeMillis();
System.out.println((new Date(endTime)).toString() +
": " + processName + " finished (" +
(endTime-startTime) + "ms)");
} | 8 |
public EditorRightMenu(Editor editor, SkinPropertiesVO skinProps, Color background) {
this.editor = editor;
this.bg = background;
this.generalChangesMenu = new GeneralChangesMenu(this.bg, skinProps);
this.buttonChangesMenu = new ButtonChangesMenu(this.bg, skinProps);
this.userlistChangesMenu = new UserlistChangesMenu(this.bg, skinProps);
this.usertileChangesMenu = new UsertileChangesMenu(this.bg, skinProps);
this.fontChangesMenu = new FontChangesMenu(this.bg, skinProps);
while (!this.generalChangesMenu.isInitialized() && !this.buttonChangesMenu.isInitialized()
&& !this.userlistChangesMenu.isInitialized()
&& !this.usertileChangesMenu.isInitialized() && !this.fontChangesMenu.isInitialized()) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
setBackground(background);
setLayout(new BorderLayout());
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.GRAY),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
create();
} | 6 |
public void measure(long time) {
// sila ktora sa snazi odoslat spravu
if (player.state == RunState.running)
force = 1;
else
force = 0;
// spravy si udrzuju rozostupy
if ((prevM != null) && (prevM.position - position < defDist)) {
force -= Math.pow(2 * (defDist - prevM.position + position) / defDist, 2);
}
if ((nextM != null) && (position - nextM.position < defDist)) {
force += Math.pow(1.0 * (defDist - position + nextM.position) / defDist, 2);
}
// factor ma kazda sprava vlastny, urci sa nahodne pri vzniku
force *= getEdgeSpeed() * factor;
// oznamime modelu svoju chcenu rychlost
player.listenSpeed(force);
// tahanie uzivatelom
if (selected > 0 && selected != 5) {
double x = edge.from.getX() * (1.0 - position) + edge.to.getX() * position;
double y = edge.from.getY() * (1.0 - position) + edge.to.getY() * position;
double x1 = player.graph.listener.xlast - x;
double y1 = player.graph.listener.ylast - y;
double x2 = (edge.to.getX() - edge.from.getX());
double y2 = (edge.to.getY() - edge.from.getY());
double prod = (x1 * x2 + y1 * y2) / Math.sqrt(x2 * x2 + y2 * y2);
double modelspeed = player.getSpeedBalance() * player.getSendSpeed();
force += Math.min(10.0, Math.max(prod / 100.0, -10.0)) / factor / Math.sqrt(modelspeed);
}
} | 7 |
public void tarjanSCC(int u) {
dfs_num[u] = dfs_low[u] = dfsNumberCounter++;
s.push(u);
visited[u] = true;
for (int i = 0; i < ady[u].size(); i++) {
int v = ady[u].get(i);
if (dfs_num[v] == -1)
tarjanSCC(v);
if (visited[v])
dfs_low[u] = Math.min(dfs_low[u], dfs_low[v]);
}
if (dfs_low[u] == dfs_num[u]) {
res.add(new ArrayList<Integer>());
int v;
do {
v = s.pop();
res.get(numSCC).add(v);
visited[v] = false;
} while (u != v);
numSCC++;
}
} | 5 |
@EventHandler
public void receivePluginMessage( PluginMessageEvent event ) throws IOException, SQLException {
if ( event.isCancelled() ) {
return;
}
if ( !event.getTag().equalsIgnoreCase( "BSWarps" ) ) {
return;
}
if ( !( event.getSender() instanceof Server ) )
return;
event.setCancelled( true );
DataInputStream in = new DataInputStream( new ByteArrayInputStream( event.getData() ) );
String task = in.readUTF();
if ( task.equals( "WarpPlayer" ) ) {
WarpsManager.sendPlayerToWarp( in.readUTF(), in.readUTF(), in.readUTF(), in.readBoolean(), in.readBoolean() );
return;
}
if ( task.equals( "GetWarpsList" ) ) {
WarpsManager.getWarpsList( in.readUTF(), in.readBoolean(), in.readBoolean(), in.readBoolean(), in.readBoolean() );
return;
}
if ( task.equals( "SetWarp" ) ) {
WarpsManager.setWarp( PlayerManager.getPlayer( in.readUTF() ), in.readUTF(), new Location( ( ( Server ) event.getSender() ).getInfo().getName(), in.readUTF(), in.readDouble(), in.readDouble(), in.readDouble(), in.readFloat(), in.readFloat() ), in.readBoolean(), in.readBoolean() );
return;
}
if ( task.equals( "DeleteWarp" ) ) {
WarpsManager.deleteWarp( PlayerManager.getPlayer( in.readUTF() ), in.readUTF() );
return;
}
if ( task.equals( "SendVersion" ) ) {
LoggingManager.log( in.readUTF() );
}
} | 8 |
public DiceImage() {
setPreferredSize(new Dimension(32, 32));
try {
for(int i = 0; i < activeDiceImage.length; i++) {
activeDiceImage[i] = ImageIO.read(
new File(getClass().getResource("/storage/images/dice/" + (i + 1) + ".png").toURI()));
inactiveDiceImage[i] = ImageIO.read(
new File(getClass().getResource("/storage/images/dice/" + (i + 1) + "g.png").toURI()));
}
} catch(IOException e) {
e.printStackTrace();
} catch(URISyntaxException e) {
e.printStackTrace();
}
current = inactiveDiceImage[0];
active = false;
} | 3 |
public void onDisable() {
UVSave.save(vampires, (getDataFolder() + File.separator + "vampires.bin"));
saveConfig();
getLogger().info("UVampires v0.2 disabled!");
} | 0 |
@Override
public Rectangle getBounds() {
float x = position.x, y = position.y;
float width = getKeyFrame().getRegionWidth(), height = getKeyFrame().getRegionHeight();
bounds.x = x;
bounds.y = y;
bounds.width = width * scale.x;
bounds.height = height * scale.y;
switch (registration) {
case BOTTOM_CENTER:
bounds.x = x - width / 2;
break;
case BOTTOM_RIGHT:
bounds.x = x - width;
break;
case CENTER_CENTER:
bounds.x = x - width / 2;
bounds.y = y - height / 2;
break;
case CENTER_LEFT:
bounds.x = x - width;
bounds.y = y - height / 2;
break;
case TOP_CENTER:
bounds.x = x - width / 2;
bounds.y = y - height;
break;
case TOP_LEFT:
bounds.x = x - width;
bounds.y = y - height;
break;
case TOP_RIGHT:
bounds.y = y - height;
break;
}
return bounds;
} | 7 |
public void testPlus_Minutes() {
Minutes test2 = Minutes.minutes(2);
Minutes test3 = Minutes.minutes(3);
Minutes result = test2.plus(test3);
assertEquals(2, test2.getMinutes());
assertEquals(3, test3.getMinutes());
assertEquals(5, result.getMinutes());
assertEquals(1, Minutes.ONE.plus(Minutes.ZERO).getMinutes());
assertEquals(1, Minutes.ONE.plus((Minutes) null).getMinutes());
try {
Minutes.MAX_VALUE.plus(Minutes.ONE);
fail();
} catch (ArithmeticException ex) {
// expected
}
} | 1 |
private RandomAccessFile getTmpBucket() {
try {
TempFile tempFile = tempFileManager.createTempFile();
return new RandomAccessFile(tempFile.getName(), "rw");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
return null;
} | 1 |
public void testIsBefore_YM() {
YearMonth test1 = new YearMonth(2005, 6);
YearMonth test1a = new YearMonth(2005, 6);
assertEquals(false, test1.isBefore(test1a));
assertEquals(false, test1a.isBefore(test1));
assertEquals(false, test1.isBefore(test1));
assertEquals(false, test1a.isBefore(test1a));
YearMonth test2 = new YearMonth(2005, 7);
assertEquals(true, test1.isBefore(test2));
assertEquals(false, test2.isBefore(test1));
YearMonth test3 = new YearMonth(2005, 7, GregorianChronology.getInstanceUTC());
assertEquals(true, test1.isBefore(test3));
assertEquals(false, test3.isBefore(test1));
assertEquals(false, test3.isBefore(test2));
try {
new YearMonth(2005, 7).isBefore(null);
fail();
} catch (IllegalArgumentException ex) {}
} | 1 |
@Override
public int compareTo(Edge e) {
return this.weight - e.getWeight();
} | 0 |
public void process() {
ArrayList<GroundItem> toRemove = new ArrayList<GroundItem>();
for (int j = 0; j < items.size(); j++) {
if (items.get(j) != null) {
GroundItem i = items.get(j);
if(i.hideTicks > 0) {
i.hideTicks--;
}
if(i.hideTicks == 1) { // item can now be seen by others
i.hideTicks = 0;
createGlobalItem(i);
i.removeTicks = HIDE_TICKS;
}
if(i.removeTicks > 0) {
i.removeTicks--;
}
if(i.removeTicks == 1) {
i.removeTicks = 0;
toRemove.add(i);
//removeGlobalItem(i, i.getItemId(), i.getItemX(), i.getItemY(), i.getItemAmount());
}
}
}
for (int j = 0; j < toRemove.size(); j++) {
GroundItem i = toRemove.get(j);
removeGlobalItem(i, i.getItemId(), i.getItemX(), i.getItemY(), i.getItemAmount());
}
/*for(GroundItem i : items) {
if(i.hideTicks > 0) {
i.hideTicks--;
}
if(i.hideTicks == 1) { // item can now be seen by others
i.hideTicks = 0;
createGlobalItem(i);
i.removeTicks = HIDE_TICKS;
}
if(i.removeTicks > 0) {
i.removeTicks--;
}
if(i.removeTicks == 1) {
i.removeTicks = 0;
removeGlobalItem(i, i.getItemId(), i.getItemX(), i.getItemY(), i.getItemAmount());
}
}*/
} | 7 |
private List<URI> getUrisInContext(RepositoryConnection connection, Resource context) throws RepositoryException {
List<URI> uris = new ArrayList<URI>();
// Get all triples in the context
RepositoryResult<Statement> statements = connection.getStatements(null, null, null, false, context);
while (statements.hasNext()) {
Statement statement = statements.next();
// If subject is a URI, add it in if not already present
Resource subject = statement.getSubject();
System.out.println("sample==" + subject.stringValue());
if (subject instanceof URI) {
URI uri = (URI) subject;
if (!uris.contains(uri)) {
System.out.println("sample2==" + uri.stringValue());
uris.add(uri);
}
}
// If object is a URI, add it in if not already present
Value object = statement.getObject();
if (object instanceof URI) {
URI uri = (URI) object;
if (!uris.contains(uri)) {
System.out.println("sample3==" + uri.stringValue());
uris.add(uri);
}
}
}
statements.close();
System.out.println("STATEMENTS===" + uris.toString());
return uris;
} | 5 |
static void Algoritmo(MatingPool Pool, int Repeticiones)
{
while(Repeticiones > 0 && TieneSolucion)
{
ArrayList<Mochila> NuevaPoblacion = new ArrayList<>();
NuevosCandidatos.clear();
System.out.println("\nNUEVOS CANDIDATOS BASADOS EN EL PORCENTAJE DE FITNESS Y UN RANDOM:\n");
for(int i = 0; i < Pool.getListaDeMochilas().size(); i++)
{
NuevosCandidatos.add(Pool.getCandidato(Random(0, 1)));
System.out.print("Nuevo candidato: ");
//Si es nulo significa que no se encontro un intervalo para el resultado del random en la ruleta y esto es solo
//posible si todos los porcentajes son 0%, es decir ningun candidato es valido para tomarse en cuenta.
if(NuevosCandidatos.get(i) != null)
{
NuevosCandidatos.get(i).ShowAsBit();
System.out.println();
System.out.println();
}
else
{
System.out.println();
System.out.println("ERROR: TODOS LOS PORCENTAJES SON 0%");
TieneSolucion = false;
break;
}
}
if(!TieneSolucion)
{
break;
}
System.out.println("\nCRUCES DE LOS CANDIDATOS\n");
for(int i = 0; i <= NuevosCandidatos.size()/2; i++)
{
Mochila Candidato1 = NuevosCandidatos.get(i);
Mochila Candidato2 = NuevosCandidatos.get(i+1);
Mochila Cruce1 = Pool.Cruce(Candidato1, Candidato2);
System.out.println("Candidato 1:");
Candidato1.ShowAsBit();
System.out.println();
System.out.println("Candidato 2:");
Candidato2.ShowAsBit();
System.out.println();
NuevaPoblacion.add(Cruce1);
System.out.println("Cruce 1:");
Cruce1.ShowAsBit();
System.out.println();
if(NuevaPoblacion.size() < NuevosCandidatos.size())
{
Mochila Cruce2 = Pool.Cruce(Candidato2, Candidato1);
NuevaPoblacion.add(Cruce2);
System.out.println("Cruce 2:");
Cruce2.ShowAsBit();
System.out.println();
}
System.out.println();
}
System.out.println("\nNUEVA POBLACION GENERADA DE LOS CRUCES\n");
for(int i = 0; i < NuevaPoblacion.size(); i++)
{
NuevaPoblacion.get(i).ShowAsBit();
System.out.println();
}
System.out.println("\nNUEVA MATING POOL\n");
Pool.setListaDeMochilas(NuevaPoblacion);
Pool.Calcular();
Pool.Show();
Repeticiones--;
}
} | 8 |
public void placeGnome() {
try {
Graph country = graph;
if (graph2 != null) {
Object [] countryOptions = {graph.getName(), graph2.getName()};
String ans = (String) JOptionPane.showInputDialog(mapFrame, "To which country would you like to add a gnome?",
"Adding a gnome", JOptionPane.PLAIN_MESSAGE, null, countryOptions, countryOptions[0]);
if (ans == null) {return;}
else if (ans.equals(countryOptions[0])) {country = graph;}
else {country = graph2;}
}
if (country.isEmpty()) {throw new GraphEmptyException();}
Object [] options = villageList(country);
String strVillage = (String) JOptionPane.showInputDialog(mapFrame,
"Which village would you like to place the new gnome in?",
"Placing a new gnome", JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (strVillage == null) {return;}
Village village = country.find(Integer.parseInt(strVillage));
village.printGnomes();
village.insertGnome(new Gnome());
village.printGnomes();
JOptionPane.showMessageDialog(mapFrame,
"A new gnome has been placed in village " + village.getName(),
"Placing a gnome", JOptionPane.PLAIN_MESSAGE);
mapPanel.removeAll();
drawGraph();
mapFrame.pack();
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(mapFrame, "You did not enter an integer. Try again.", "NumberFormatException", JOptionPane.ERROR_MESSAGE);
} catch (GraphEmptyException e) {
JOptionPane.showMessageDialog(mapFrame, e.getMessage(), "GraphEmptyException", JOptionPane.ERROR_MESSAGE);
} catch (NotFoundException e) { // theoretically not possible
JOptionPane.showMessageDialog(mapFrame, e.getMessage(), "NotFoundException", JOptionPane.ERROR_MESSAGE);
} catch (VillageFullException e) {
JOptionPane.showMessageDialog(mapFrame, e.getMessage(), "VillageFullException", JOptionPane.ERROR_MESSAGE);
}
} // end of placeGnome() | 9 |
public void buttonClicked(int ID)
{
switch (ID)
{
case 50:
updateCharClass();
break;
case 52:
updateThirdSkill();
break;
case 100:
game.beginGame(charClass, skill2, characterStr.count, characterDex.count, characterCon.count, characterInt.count, skill1control.count, skill2control.count, skill3control.count);
break;
case 101:
game.changeMenu(new MainMenu(game));
break;
case 102:
onceTicked = false;
break;
}
} | 5 |
private String useAtomVariables(String s, int frame) {
if (frame >= model.getTapePointer()) {
out(ScriptEvent.FAILED, "There is no such frame: " + frame + ". (Total frames: " + model.getTapePointer()
+ ".)");
return null;
}
int n = model.getAtomCount();
int lb = s.indexOf("%atom[");
int rb = s.indexOf("].", lb);
int lb0 = -1;
String v;
int i;
while (lb != -1 && rb != -1) {
v = s.substring(lb + 6, rb);
double x = parseMathExpression(v);
if (Double.isNaN(x))
break;
i = (int) Math.round(x);
if (i < 0 || i >= n) {
out(ScriptEvent.FAILED, i + " is an invalid index: must be between 0 and " + (n - 1) + " (inclusive).");
break;
}
v = escapeMetaCharacters(v);
Atom a = model.atom[i];
s = replaceAll(s, "%atom\\[" + v + "\\]\\.id", a.getElementNumber());
s = replaceAll(s, "%atom\\[" + v + "\\]\\.mass", a.mass);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.charge", a.charge);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.sigma", a.sigma * 0.1);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.epsilon", a.epsilon);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.friction", a.damp);
// s = replaceAll(s, "%atom\\[" + v + "\\]\\.hx", a.hx);
// s = replaceAll(s, "%atom\\[" + v + "\\]\\.hy", a.hy);
if (frame < 0) {
s = replaceAll(s, "%atom\\[" + v + "\\]\\.rx", a.rx);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.ry", a.ry);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.rz", a.rz);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.vx", a.vx * V_CONVERTER);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.vy", a.vy * V_CONVERTER);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.vz", a.vz * V_CONVERTER);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.ax", a.ax);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.ay", a.ay);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.az", a.az);
}
else {
s = replaceAll(s, "%atom\\[" + v + "\\]\\.rx", a.rQ.getQueue1().getData(frame));
s = replaceAll(s, "%atom\\[" + v + "\\]\\.ry", a.rQ.getQueue2().getData(frame));
s = replaceAll(s, "%atom\\[" + v + "\\]\\.rz", a.rQ.getQueue3().getData(frame));
s = replaceAll(s, "%atom\\[" + v + "\\]\\.vx", a.vQ.getQueue1().getData(frame) * V_CONVERTER);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.vy", a.vQ.getQueue2().getData(frame) * V_CONVERTER);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.vz", a.vQ.getQueue3().getData(frame) * V_CONVERTER);
s = replaceAll(s, "%atom\\[" + v + "\\]\\.ax", a.aQ.getQueue1().getData(frame));
s = replaceAll(s, "%atom\\[" + v + "\\]\\.ay", a.aQ.getQueue2().getData(frame));
s = replaceAll(s, "%atom\\[" + v + "\\]\\.az", a.aQ.getQueue3().getData(frame));
}
lb0 = lb;
lb = s.indexOf("%atom[");
if (lb0 == lb) // infinite loop
break;
rb = s.indexOf("].", lb);
}
return s;
} | 8 |
public static Suit valueOf(char c) {
switch (c) {
case 'S':
case 's':
return Spades;
case 'H':
case 'h':
return Hearts;
case 'D':
case 'd':
return Diamonds;
case 'C':
case 'c':
return Clubs;
default:
return null;
}
} | 8 |
@Override
public void happens() {
// TODO: Change to ensure only explorers
ArrayList<Character> chars = Game.getInstance().getCharacters();
for(Character character: chars){
if(character.getCurrentRoom().getFloor() == Floor_Name.BASEMENT){
int rollResult = character.getTraitRoll(Trait.SANITY);
if((rollResult > 0) && (rollResult < 4)){
Trait chosenTrait = Game.getInstance().chooseAMentalTrait();
int damage = Game.getInstance().rollDice(1);
character.decrementTrait(chosenTrait, damage);
} else if (rollResult == 0){
Trait chosenTrait = Game.getInstance().chooseAMentalTrait();
int damage = Game.getInstance().rollDice(2);
character.decrementTrait(chosenTrait, damage);
}
}
}
} | 5 |
public boolean[] arePasswordsInitialised() {
boolean[] arePasswordsInitialised = new boolean[4];
byte[] response = null;
try {
response = worker.getResponse(worker.select(DatabaseOfEF.MF.getFID()));
for (int i = 0; i < 4; i++) {
String binaryForm;
int j = response[18 + i]; //position of PIN1/PUK1/PIN2/PUK2
binaryForm = Integer.toBinaryString(j).substring(24);
if (binaryForm.charAt(0) == '0') {
arePasswordsInitialised[i] = false;
} else {
arePasswordsInitialised[i] = true;
}
}
} catch (Exception ex) {
Logger.getLogger(CardManager.class.getName()).log(Level.SEVERE, null, ex);
}
return arePasswordsInitialised;
} | 3 |
public Block[][] createNewBoard() {
board = new Block[size][size];
Random r = new Random();
int start = 1;
int end = 18;
int numberOfTreasure = 3;
while (numberOfMines != 0 && numberOfTreasure != 0) {
for (int a = 0; a < size; a++) {
for (int b = 0; b < size; b++) {
int num = r.nextInt((end - start) + 1) + start;
if (num >= 1 && num <= 3 && numberOfMines > 0) {
board[a][b] = new Mines();
--numberOfMines;
continue;
}
if (num == 6 && numberOfTreasure > 0) {
board[a][b] = new Treasure();
--numberOfTreasure;
continue;
} else {
board[a][b] = new Blank();
continue;
}
}
}
}
// add numbers around mines
addNumbers(board);
return board;
} | 9 |
public void spawn() {
Bubble bubble = (Bubble) getEntity();
if (bubble.type == BubbleType.Small) {
level.addEntityBack(bubble);
} else
if (bubble.type == BubbleType.Middle) {
if (new Random().nextBoolean()) {
level.addEntityPop(bubble);
} else {
level.addEntityBack(bubble);
}
} else
if (bubble.type == BubbleType.Big) {
level.addEntityPop(bubble);
}
afterSpawn();
} | 4 |
@Override
public String processCommand(String[] arguments)
throws SystemCommandException {
Election election = facade.getCurrentElection();
if (election == null)
throw new SystemCommandException("No current election set.");
String guid = facade.getCurrentUserGUID();
if (guid == null)
throw new SystemCommandException("No current user set.");
try {
facade.acceptNomination();
} catch(RuntimeException e) {
throw new SystemCommandException(e.getMessage());
}
Set<Candidate> candidates = facade.getCurrentElection().getCandidates();
for (Candidate candidate: candidates){
if (candidate.getGUID().equals(guid))
return "Nomination for the current election ["+
election.getEID()+"] accepted for the current user ["+guid+"].";
}
return "The nomination was not made, perhaps the current user ["+guid+"]" +
" is not eligible for election ["+election.getEID()+"]?";
} | 5 |
public boolean currentlyPlacing() {
if (currentlyPlacing == null) {
return false;
}
return true;
} | 1 |
public static String fromUTF8ByteArray(byte[] bytes)
{
int i = 0;
int length = 0;
while (i < bytes.length)
{
length++;
if ((bytes[i] & 0xf0) == 0xf0)
{
// surrogate pair
length++;
i += 4;
}
else if ((bytes[i] & 0xe0) == 0xe0)
{
i += 3;
}
else if ((bytes[i] & 0xc0) == 0xc0)
{
i += 2;
}
else
{
i += 1;
}
}
char[] cs = new char[length];
i = 0;
length = 0;
while (i < bytes.length)
{
char ch;
if ((bytes[i] & 0xf0) == 0xf0)
{
int codePoint = ((bytes[i] & 0x03) << 18) | ((bytes[i+1] & 0x3F) << 12) | ((bytes[i+2] & 0x3F) << 6) | (bytes[i+3] & 0x3F);
int U = codePoint - 0x10000;
char W1 = (char)(0xD800 | (U >> 10));
char W2 = (char)(0xDC00 | (U & 0x3FF));
cs[length++] = W1;
ch = W2;
i += 4;
}
else if ((bytes[i] & 0xe0) == 0xe0)
{
ch = (char)(((bytes[i] & 0x0f) << 12)
| ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f));
i += 3;
}
else if ((bytes[i] & 0xd0) == 0xd0)
{
ch = (char)(((bytes[i] & 0x1f) << 6) | (bytes[i + 1] & 0x3f));
i += 2;
}
else if ((bytes[i] & 0xc0) == 0xc0)
{
ch = (char)(((bytes[i] & 0x1f) << 6) | (bytes[i + 1] & 0x3f));
i += 2;
}
else
{
ch = (char)(bytes[i] & 0xff);
i += 1;
}
cs[length++] = ch;
}
return new String(cs);
} | 9 |
public TrayInteract( Controller ctrl, MainWindow main )
{
if (!SystemTray.isSupported())
{
// Tray not supported !
Logger.error("FATAL : Tray system not supported !");
System.exit(0);
}
this.ti_image = new ImageIcon("ressources/network.png");
if( this.ti_image == null)
{
// Cannot find tray image !
Logger.error("FATAL : Cannot retrieve Tray Icon !");
System.exit(0);
}
this.ti_controller = ctrl;
this.ti_main = main;
this.ti_trayIcon = new TrayIcon( this.ti_image.getImage() );
this.ti_tray = SystemTray.getSystemTray();
this.ti_popup = new PopupMenu();
this.ti_aboutItem = new MenuItem("About");
this.ti_displayItem = new MenuItem("Display");
this.ti_restartItem = new MenuItem("Restart");
this.ti_exitItem = new MenuItem("Exit");
this.ti_popup.add( this.ti_aboutItem );
this.ti_popup.add( this.ti_displayItem );
this.ti_popup.add( this.ti_restartItem );
this.ti_popup.addSeparator();
this.ti_popup.add( this.ti_exitItem );
this.ti_trayIcon.setPopupMenu( this.ti_popup );
try
{
this.ti_tray.add( this.ti_trayIcon );
}
catch (AWTException e)
{
// TODO Auto-generated catch block
Logger.exception(e.toString());
System.exit(0);
}
this.ti_trayIcon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
ti_main.showWindow();
}
});
}
});
this.ti_aboutItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UserInteract.about();
}
});
this.ti_displayItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ti_main.showWindow();
}
});
this.ti_restartItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
// RESTART METHODS
ti_tray.remove( ti_trayIcon );
ti_controller.restartAll();
}
});
}
});
this.ti_exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
//EXIT METHODS
try
{
ti_tray.remove( ti_trayIcon );
ti_controller.turnOff();
System.exit(0);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
Logger.exception(e.toString());
}
}
});
}
});
} | 4 |
@Override
public void render() {
super.render();
int indx = 0;
int offset = 0;
if(overflow() > 0) {
offset = overflow();
}
Iterator<String> it = inputHistory.iterator();
while(offset > 0) {
it.next();
offset--;
}
while(it.hasNext()) {
String s = it.next();
Renderer.get().drawText(s, x+8, y+8+indx*17, 0.5f);
indx++;
}
} | 3 |
Subsets and Splits