text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
uidb.occurence();
}
} | 1 |
public void mouseClicked(MouseEvent e) {
int column = jtSaves.columnAtPoint(e.getPoint());
ArrayList <Map> unsortedList = saves;
ArrayList <Map> sortedList;
boolean sens = sortWay[column];
switch (column) {
case 0:
sortedList = Tri.sortByName(unsortedList, sens);
updateTable(sortedList);
break;
case 1:
sortedList = Tri.sortByDate(unsortedList, sens);
updateTable(sortedList);
break;
case 2:
sortedList = Tri.sortByTurnsNumber(unsortedList, sens);
updateTable(sortedList);
break;
case 3:
sortedList = Tri.sortByDuration(unsortedList, sens);
updateTable(sortedList);
break;
default:
throw new IllegalArgumentException();
}
saves = sortedList;
Arrays.fill(sortWay,true);
sortWay[column] = sens^true;
updateTable(saves);
} | 4 |
private void copyEntry(final InputStream is, final OutputStream os)
throws IOException {
if (outRepresentation == SINGLE_XML) {
return;
}
byte[] buff = new byte[2048];
int i;
while ((i = is.read(buff)) != -1) {
os.write(buff, 0, i);
}
} | 2 |
public JFrame getChooseFrame() {
boolean test = false;
if (test || m_test) {
System.out.println("GameSelecter :: getChooseFrame() BEGIN");
}
if (test || m_test) {
System.out.println("GameSelecter :: getChooseFrame() END");
}
return m_choose;
} | 4 |
private static ValueTypePair[][] loadGrazingSubbasinData(ValueTypePair[][] vtp, Statement inA, Statement inB, String subGrz, String grzArea) {
ValueTypePair[][] vTemp = new ValueTypePair[vtp.length * 20][3];
HashSet ids = new HashSet(), subs = new HashSet();
int index = 0;
for (ValueTypePair[] v : vtp) {
ids.add(v[0].getPairValueAsInt());
}
try {
ResultSet sRs = inA.executeQuery("SELECT * FROM " + subGrz + " ORDER BY grazing;");
while(sRs.next()) {
int subId = sRs.getInt(1);
int grzId = sRs.getInt(2);
if(ids.contains(grzId)) {
if(subs.contains(subId)) {
}
else {
subs.add(subId);
sRs = inA.executeQuery("SELECT * FROM " + subGrz + " WHERE subbasin = " + subId + ";");
int k = 0;
IdValuePair[] iTempArea = new IdValuePair[vtp.length];
IdValuePair[] iTempPct = new IdValuePair[vtp.length];
while(sRs.next()) {
grzId = sRs.getInt(2);
//if(ids.contains(grzId)) {
ResultSet aRs = inB.executeQuery("SELECT * FROM " + grzArea + " WHERE id = " + grzId + ";");
iTempArea[k] = new IdValuePair(aRs.getInt(1), aRs.getDouble(2));
iTempPct[k] = new IdValuePair(sRs.getInt(2), sRs.getDouble(3));
k++;
//}
//else {
// ResultSet aRs = inB.executeQuery("SELECT * FROM " + grzArea + " WHERE id = " + grzId + ";");
// iTempArea[k] = new IdValuePair(aRs.getInt(1), aRs.getDouble(2));
// iTempPct[k] = new IdValuePair(sRs.getInt(2), sRs.getDouble(3));
// k++;
//}
}
IdValuePair[] grazeArea = new IdValuePair[k];
IdValuePair[] grazePct = new IdValuePair[k];
System.arraycopy(iTempArea, 0, grazeArea, 0, k);
System.arraycopy(iTempPct, 0, grazePct, 0, k);
double cost = calculateGrazingMeanCost(grazeArea, grazePct, vtp);
int year = 1991;
for(int i = 0; i < 20; i++) {
vTemp[index * 20 + i][0] = new ValueTypePair(subId, 1);
vTemp[index * 20 + i][1] = new ValueTypePair(year, 1);
vTemp[index * 20 + i][2] = new ValueTypePair(cost, 0);
year++;
}
index++;
sRs = inA.executeQuery("SELECT * FROM " + subGrz + " ORDER BY grazing;");
}
}
}
} catch (SQLException e) {
Logger.getLogger(BuildDB.class.getName()).log(Level.SEVERE, null, e);
}
ValueTypePair[][] vals = new ValueTypePair[index * 20][3];
System.arraycopy(vTemp, 0, vals, 0, vals.length);
return vals;
} | 7 |
public PreferencesModel(Preferences preferencesRoot, int numberOfIpsToStore) {
_preferencesRoot = preferencesRoot;
_numberOfIpsToStore = numberOfIpsToStore;
// gibt es Einträge in den Preferences zu IP und Port ? Wenn nein -> Default-Werte localhost:8083
try {
String[] children = _preferencesRoot.childrenNames();
if(children.length > 0) { // es gibt abgespeicherte Werte
Preferences lastUsedNode = _preferencesRoot.node(children[0]); // zuletzt abgespeicherter Wert
_selectedIp = lastUsedNode.get("ip", "localhost");
_selectedPort = lastUsedNode.get("port", "8083");
synchronized(_ipList) {
for(int i = 0; i < children.length; i++) {
String child = children[i];
Preferences childPrefs = _preferencesRoot.node(child);
String ip = childPrefs.get("ip", null);
if(ip != null && !_ipList.contains(ip)) _ipList.add(ip);
}
}
}
}
catch(BackingStoreException ex) {
ex.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
/**
* Falls sich etwas an den Knoten ändert, muss die Liste ggf. auch geändert werden.
*/
_preferencesRoot.addNodeChangeListener(new NodeChangeListener() {
public void childAdded(NodeChangeEvent evt) {
actualizeIpList();
}
public void childRemoved(NodeChangeEvent evt) {
actualizeIpList();
}
public void actualizeIpList() {
try {
synchronized(_ipList) {
_ipList.clear();
String[] children = _preferencesRoot.childrenNames();
for(int i = 0; i < children.length; i++) {
String child = children[i];
Preferences childPrefs = _preferencesRoot.node(child);
String ip = childPrefs.get("ip", null);
if(ip != null && !_ipList.contains(ip)) _ipList.add(ip);
}
}
}
catch(BackingStoreException ex) {
_debug.warning("Die Liste mit den IP-Adressen konnte nicht aktualisiert werden", ex);
}
}
});
} | 9 |
public BufferedImage getSprite() {
if (moveX==0)
return stand;
return walk.sprite;
} | 1 |
public void loadBlockList()
{
RegenPlugin.get().getLogger().info(RegenPlugin.get().getName() + ".LoadBlockList() fileName: " + BLOCK_LIST_FILE);
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = dbfac.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
return;
}
File file = new File(BLOCK_LIST_FILE);
if(!file.exists()){
return;
}
FileInputStream fis;
try {
fis = new FileInputStream(BLOCK_LIST_FILE);
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
Document document;
try {
document = docBuilder.parse(fis);
Element regen_block_list_element = document.getDocumentElement();
NodeList regen_block_list = regen_block_list_element.getChildNodes();
for(int index = 0; index < regen_block_list.getLength(); index++)
{
Node node = regen_block_list.item(index);
if(node instanceof Element)
{
//a child element to process
Element block_element = (Element) node;
Block block = originalWorld.getBlockAt(Integer.parseInt(block_element.getAttribute("x"))
,Integer.parseInt(block_element.getAttribute("y"))
,Integer.parseInt(block_element.getAttribute("z")));
this.addBlockToRegenList(block);
}
}
} catch (SAXException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
file.delete();
} | 7 |
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(GetJavaPath.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GetJavaPath.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GetJavaPath.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GetJavaPath.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 GetJavaPath().setVisible(true);
}
});
} | 6 |
public static void main(String[] args) {
long start = System.nanoTime();
String num = "7316717653...2963450"; // Edited out most of the number. The problem with the full number can be found here:
int max = 1, current = 1; // http://projecteuler.net/problem=8
for(int i = 0; i + 4 < num.length(); i++){
current = 1;
for(int j = 0; j < 5; j++){
current *= Integer.parseInt(num.substring(i+j,i+j+1));
}
if(current > max){
max = current;
}
}
System.out.println(max);
System.out.println("Done in " + (double) (System.nanoTime() - start)
/ 1000000000 + " seconds.");
} | 3 |
public static String getFieldName(String _name, boolean erveryBigWord) throws Exception {
char[] nameChars = _name.toCharArray();
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < nameChars.length; i++) {
if (StringUtil.isBigChr(nameChars[i])) {
if (i > 0 && (StringUtil.isSmallChr(nameChars[i - 1]) || erveryBigWord)) {
sb.append("_");
}
sb.append(nameChars[i]);
} else
sb.append(StringUtil.getRefChar(nameChars[i]));
}
return sb.toString();
} | 5 |
public void run(){
if(! hasStarted()){
Property<String> outputFileProp = getFirstProperty("output-file");
if((outputFileProp == null) || (outputFileProp.getValue() == null)){
die("OutputAdapter requires an output-file property.");
}
File outputFile = new File(outputFileProp.getValue());
String characterSet = "UTF-8";
Property<String> charSetProp = getFirstProperty("character-set");
if((charSetProp != null) && (charSetProp.getValue() != null)){
characterSet = charSetProp.getValue();
}
try {
writer = new OutputStreamWriter(new FileOutputStream(outputFile), characterSet);
}
catch (UnsupportedEncodingException uee) {
die("OutputAdapter given invalid character encoding. Exception caught: '" + uee + "'.");
}
catch (FileNotFoundException fnfe) {
die("OutputAdapter can't find file to write. Exception caught: '" + fnfe + "'.");
}
}
super.run();
} | 7 |
public Pet[] createArray(int size) {
Pet[] result = new Pet[size];
for(int i = 0; i < size; i++)
result[i] = randomPet();
return result;
} | 1 |
public void setPasswordfieldRightshift(int shift) {
if (shift < 0) {
this.passwordfieldRightshift = UIShiftInits.PWAREA_RIGHT.getShift();
} else {
this.passwordfieldRightshift = shift;
}
} | 1 |
private int getPort() {
int port = uri.getPort();
if( port == -1 ) {
String scheme = uri.getScheme();
if( scheme.equals( "wss" ) ) {
return WebSocket.DEFAULT_WSS_PORT;
} else if( scheme.equals( "ws" ) ) {
return WebSocket.DEFAULT_PORT;
} else {
throw new RuntimeException( "unkonow scheme" + scheme );
}
}
return port;
} | 3 |
public String formatMessage(ChatPlayer player, String message) {
String output = "";
String format = getFormat();
ProxiedPlayer p = player.getPlayer();
if (CommandUtil.hasPermission(p, NicknameCommand.PERMISSION_NODES)) {
output = format.replace("%player", player.getDisplayName());
} else {
output = format.replace("%player", player.getName());
}
String server = player.getCurrentServer();
if (plugin.serverNames.containsKey(server)) {
output = output.replace("%server", plugin.serverNames.get(server));
} else {
output = output.replace("%server", server);
}
output = output.replace("%cname", channelName);
if (plugin.useVault) {
output = output.replace("%prefix", player.getPrefix());
output = output.replace("%suffix", player.getSuffix());
}else{
output = output.replace("%prefix", "");
output = output.replace("%suffix", "");
}
output = output.replace("%title", "");
if (CommandUtil.hasPermission(p, PERMISSION_NODES_COLORED_CHAT)) {
output = output.replace("%message", message);
output = colorSub(output);
} else {
if (plugin.formatChat) {
message = format(message);
output = colorSub(output);
output = output.replace("%message", message);
} else {
output = colorSub(output);
output = output.replace("%message", message);
}
}
return output;
} | 5 |
public static void start(final int i) {
new Thread() {
public void run() {
try {
clojure.lang.Compiler.load(new FileReader(
"src/Clojure_Bindings.clj"));
} catch (Exception e1) {
e1.printStackTrace();
}
while (true) {
ServerSocket serv = null;
Socket sock = null;
try {
serv = new ServerSocket(i);
sock = serv.accept();
PrintWriter output = new PrintWriter(
sock.getOutputStream());
BufferedReader commandInput = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
clojureOut = output;
clojure.lang.Compiler
.load(new StringReader(
"(use 'Clojure-Bindings)"
+ "(def *out* "
+ "synthseq.clojureinterop.ClojureServer/clojureOut)"));
while (true) {
Object out = null;
try {
out = clojure.lang.Compiler
.load(new StringReader(commandInput
.readLine()));
} catch (Exception e) {
out = e;
}
output.println(out);
output.flush();
}
} catch (java.net.BindException e) {
System.out.println("Server already open. Exiting.");
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
try {
serv.close();
sock.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}.start();
} | 7 |
private float getReducedDecodingHeight(int row, int col) {
ArrayList<AxisPairMetrics> amList =parameterizedDisplay.getMetricsList();
Collections.sort(amList, new SortMetrics(MetaMetrics.DistanceEntropy));
int firstQuartile = metricsList.size()/4;
int thirdQuartile= (3*metricsList.size())/4;
float newBoxHeight =0;
//penalize low value
for(int index=0; index<metricsList.size(); index++)
{
AxisPairMetrics am = metricsList.get(index);
// System.err.println(" Entropy value " + am.getColorEntropy());
if(am.getDimension1()==row & am.getDimension2()==col)
{
if(index<=firstQuartile)
newBoxHeight = boxHeight*0.75f;
else if(index>firstQuartile && index <= thirdQuartile)
newBoxHeight = boxHeight*0.5f;
else if(index>thirdQuartile)
newBoxHeight = boxHeight*0.25f;
}
}
//System.err.println(" Decoding height +++++++++ " +newBoxHeight);
return newBoxHeight;
} | 6 |
public static void main(String[] args) throws IOException {
Game.AgentsCreation();
int i;
int teams_count =0;
System.out.println("***********************************************************");
System.out.println("Battle is about to start. All agents stats: ");
for (i=0; i<Game.number_of_agents; i++){
Game.all_agents[i].PrintHp();
}
boolean gameFinished = false;
while (!gameFinished){
Arrays.sort(Game.all_agents,speedcomparator);
for (i=0; i < Game.number_of_agents; i++){
if (Game.all_agents[i].IsAlive()){
System.out.println("Now it is agent's "+ Game.all_agents[i].GetName() + " turn");
Game.all_agents[i].Turn();
}
else{
System.out.println("Agent "+ Game.all_agents[i].GetName()+ " is dead, so no turn for him :( ");
}
}
System.out.println("***********************************************************");
System.out.println("Round Finished. Agents stats: ");
for (i=0; i<Game.number_of_agents; i++){
Game.all_agents[i].PrintHp();
}
teams_count =0;
for (i=1; i <= Game.number_of_teams; i++){
if (Game.team_alive[i] != 0){
teams_count++;
winner = i;
}
}
System.out.println("Teams count = " + teams_count);
if (teams_count < 2){
gameFinished = true;
break;
}
}
System.out.println("*****************************************************************");
System.out.println("*****************************************************************");
System.out.println("*****************************************************************");
System.out.println("*****************************************************************");
System.out.println("*****************************************************************");
System.out.println("*****************************************************************");
System.out.println("The winner is Team " + winner);
System.out.println("*****************************************************************");
System.out.println("*****************************************************************");
System.out.println("*****************************************************************");
} | 8 |
public static void downloadOrUpdateInstaller(IMonitor monitor, String host, File dest, boolean update)
{
String fileName = "unknow";
byte[] buffer = new byte[65536];
try
{
URL url = new URL(host);
URLConnection urlconnection = url.openConnection();
if((urlconnection instanceof HttpURLConnection))
{
urlconnection.setRequestProperty("Cache-Control", "no-cache");
urlconnection.connect();
}
int fileLength = urlconnection.getContentLength();
if(fileLength == -1)
{
JOptionPane.showMessageDialog(null, "Invalide download link, cannot install", Language.getLocalizedString("error"), JOptionPane.ERROR_MESSAGE);
return;
}
monitor.setMaximum(fileLength);
fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1);
InputStream inputstream = urlconnection.getInputStream();
if(update)
{
fileName = fileName.replace(".jar", "new.jar");
}
FileOutputStream fos = new FileOutputStream(dest.toString() + File.separator + fileName);
long downloadStartTime = System.currentTimeMillis();
int downloadedAmount = 0;
int bufferSize;
int currentSizeDownload = 0;
while((bufferSize = inputstream.read(buffer, 0, buffer.length)) != -1)
{
fos.write(buffer, 0, bufferSize);
currentSizeDownload += bufferSize;
monitor.setProgress(currentSizeDownload);
downloadedAmount += bufferSize;
long timeLapse = System.currentTimeMillis() - downloadStartTime;
if(timeLapse >= 1000L)
{
float downloadSpeed = downloadedAmount / (float)timeLapse;
downloadSpeed = (int)(downloadSpeed * 100.0F) / 100.0F;
downloadedAmount = 0;
downloadStartTime += 1000L;
if(downloadSpeed > 1000F)
{
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
monitor.setNote("Download " + fileName + " at " + String.valueOf(df.format(downloadSpeed / 1000)) + " mo/s");
}
else
{
monitor.setNote("Download " + fileName + " at " + String.valueOf(downloadSpeed) + " ko/s");
}
}
}
inputstream.close();
fos.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, "Error while trying to download " + fileName, Language.getLocalizedString("error"), JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} | 7 |
@Test
public void testPreAuthorization() {
Gateway beanstream = new Gateway("v1", 300200578,
"4BaD82D9197b4cc4b70a221911eE9f70");
CardPaymentRequest paymentRequest = new CardPaymentRequest();
paymentRequest.setAmount(90.00);
paymentRequest.setOrderNumber(getRandomOrderId("GAS"));
paymentRequest.getCard()
.setName("John Doe")
.setNumber("5100000010001004")
.setExpiryMonth("12")
.setExpiryYear("18")
.setCvd("123");
try {
PaymentResponse response = beanstream.payments().preAuth(paymentRequest);
PaymentResponse authResp = beanstream.payments().preAuthCompletion(response.id, 43.50);
if (!authResp.isApproved()) {
Assert.fail("This auth completion should be approved because a greater amount has been pre authorized");
}
} catch (BeanstreamApiException ex) {
System.out.println(BeanstreamResponse.fromException(ex));
Assert.fail(ex.getMessage());
}
// Pre-auth and complete again but supply PaymentRequest details in the complete
CardPaymentRequest paymentRequest2 = new CardPaymentRequest();
paymentRequest2.setAmount(30.00);
paymentRequest2.setOrderNumber(getRandomOrderId("Pumpkins"));
paymentRequest2.getCard()
.setName("John Doe")
.setNumber("5100000010001004")
.setExpiryMonth("12")
.setExpiryYear("18")
.setCvd("123");
try {
PaymentResponse response = beanstream.payments().preAuth(paymentRequest2);
paymentRequest2.setAmount(4.00);
PaymentResponse authResp = beanstream.payments().preAuthCompletion(response.id, paymentRequest2);
if (!authResp.isApproved()) {
Assert.fail("This auth completion should be approved because a greater amount has been pre authorized");
}
} catch (BeanstreamApiException ex) {
System.out.println(BeanstreamResponse.fromException(ex));
Assert.fail(ex.getMessage());
}
} | 4 |
public double evaluate(double x) {
return Math.pow(x, _power);
} | 0 |
public void decorateChunk(WorldChunk chunk, World w, Random rand)
{
int randInt = 0;
int theTop = 0;
for(int i = 0 ; i < 16 ; i++)
{
randInt = rand.nextInt(10);
theTop = chunk.getMaxHeight(i) + 1;
if(w.getBlockAt(16 * chunk.chunkID + i, theTop).equals("air"))
{
if(randInt == 3)
{
if(rand.nextBoolean())
{
w.setBlock(chunk.chunkID * 16 + i, theTop, "flowerRed");
}
}
else if(randInt == 7)
{
if(rand.nextBoolean())
{
w.setBlock(chunk.chunkID * 16 + i, theTop, "flowerWhite");
}
}
else
{
if(rand.nextBoolean())
{
w.setBlock(chunk.chunkID * 16 + i, theTop, "herb");
}
}
}
}
} | 7 |
protected final void writePacket(final SelectionKey key, final MMOConnection<T> con)
{
if (!prepareWriteBuffer(con))
{
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
return;
}
DIRECT_WRITE_BUFFER.flip();
final int size = DIRECT_WRITE_BUFFER.remaining();
int result = -1;
try
{
result = con.write(DIRECT_WRITE_BUFFER);
}
catch (IOException e)
{
// error handling goes on the if bellow
}
// check if no error happened
if (result >= 0)
{
// check if we written everything
if (result == size)
{
// complete write
synchronized (con.getSendQueue())
{
if (con.getSendQueue().isEmpty() && !con.hasPendingWriteBuffer())
{
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
}
}
}
else
{
// incomplete write
con.createWriteBuffer(DIRECT_WRITE_BUFFER);
}
}
else
{
con.getClient().onForcedDisconnection();
closeConnectionImpl(key, con);
}
} | 6 |
public Systemereignis theoriestundeEintragen(int thema, Date beginn) {
ArrayList<Fahrlehrerindaten> fahrlehrerin = ressourcenverwaltung.get_fahrlehrerin();
Date end = (Date) beginn.clone();
end.setMinutes(beginn.getMinutes()+90);
for (int i=0;i<this.theoriestunde.size();i++) {
Theoriestunde stunde = this.theoriestunde.get(i);
if ((stunde.get_Datum().before(beginn) && stunde.get_end().after(beginn))
|| (stunde.get_Datum().before(end) && stunde.get_end().after(end))
|| stunde.get_Datum().equals(beginn)
|| stunde.get_end().equals(end)) {
return(new Systemereignis(Nachricht.Theoriestunde_nicht_hinzugefuegt_Raum_belegt));
}
}
for (int i=0;i<fahrlehrerin.size();i++) {
if (fahrlehrerin.get(i).verfuegbar(beginn,end)) {
Theoriestunde new_ts = new Theoriestunde(thema,beginn);
new_ts.set_fahrlehrerin(fahrlehrerin.get(i));
fahrlehrerin.get(i).add_Theoriestunde(new_ts);
this.theoriestunde.add(new_ts);
return(new Systemereignis(Nachricht.Theoriestunde_erfolgreich_hinzugefuegt));
}
}
return(new Systemereignis(Nachricht.Theoriestunde_nicht_hinzugefuegt_keine_Lehrerin_verfuegbar));
} | 9 |
public char translateFrom (final Cell other) {
if (other.row - 1 == row && other.col == col) {
return 'D';
} else if (other.row + 1 == row && other.col == col) {
return 'U';
} else if (other.row == row && other.col - 1 == col) {
return 'L';
} else if (other.row == row && other.col + 1 == col) {
return 'R';
} else {
return 'A'; // something wrong here..
}
} | 8 |
@Override
public void render(Graphics g) {
super.render(g);
if (shouldRender) {
hudManager.playerRender(g, positionX + PAPERDOLL_X, positionY + PAPERDOLL_Y, true);
}
} | 1 |
public void showUsage(Command command, CommandSender sender, boolean prefix) {
CommandInfo info = command.getClass().getAnnotation(CommandInfo.class);
if (!plugin.has(sender, info.permission())) return;
sender.sendMessage((prefix ? "Usage: " : "") + info.usage() + " " + ChatColor.YELLOW + info.desc());
} | 2 |
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(RegistroEntradasInvestigacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegistroEntradasInvestigacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegistroEntradasInvestigacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegistroEntradasInvestigacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new RegistroEntradasInvestigacion().setVisible(true);
}
});
} | 6 |
public int compareTo(BitFeld b) {
/*
* liefert 1, falls |this| > |b| 0, falls |this| = |b| -1, falls |this|
* < |b|
*/
/* Arrays Bitweise vergleichen */
for (int i = this.size - 1; i >= 0; i--) {
if (this.bits[i] & !(b.bits[i]))
return 1;
if (!(this.bits[i]) & b.bits[i])
return -1;
}
/*
* Es konnte keine Differenz gefunden werden => Bitfelder sind gleich
*/
return 0;
} | 3 |
public Animal getPredator(int index) {
return predators.get(index);
} | 0 |
public static Object call_method(Object object, String methodName) {
Object retObj = null;
try {
Class<?> cls = object.getClass();
Class<?> partypes[] = new Class[0];
Method meth = cls.getMethod(methodName, partypes);
Object arglist[] = new Object[0];
retObj = meth.invoke(object, arglist);
} catch (Throwable e) {
}
return retObj;
} | 3 |
public boolean remove(Unit unit) {
int tolerance = 20;
int remaining = building.getRemainingTrainTime();
boolean buildIsDone = false;
if (remaining != 0) {
for (UnitType type : ableToBuild) {
if (type.buildTime() - tolerance <= remaining
&& remaining <= type.buildTime()) {
buildIsDone = true;
break;
}
}
} else {
buildIsDone = true;
}
if (!buildIsDone || queue.isEmpty() || unit.getType() != queue.get(0)) {
return false;
}
queue.remove(0);
return true;
} | 7 |
public void update(double[] y) {
if (numPoints < N) {
// Just add this point to the end - not saturated and don't have to scroll yet!
for(int p = 0; p < numPlots; p++) {
y_vals[p][numPoints] = y[p];
}
numPoints++;
} else {
// Scroll all the points over by 1, and then add it
for(int i = 0; i < N - 1; i++) {
for(int p = 0; p < numPlots; p++) {
y_vals[p][i] = y_vals[p][i + 1];
}
}
for(int p = 0; p < numPlots; p++) {
y_vals[p][N - 1] = y[p];
}
}
if (AUTO_Y_SCALE) {
for(int i = 0; i < numPlots; i++) {
if (maxY < y[i]) {
maxY = y[i];
}
}
}
} | 8 |
private void skipToEndOfLine() throws IOException {
while (pos < limit || fillBuffer(1)) {
char c = buffer[pos++];
if (c == '\n') {
lineNumber++;
lineStart = pos;
break;
} else if (c == '\r') {
break;
}
}
} | 4 |
static Method getDeclaredMethod(final Class clazz, final String name,
final Class[] types) throws NoSuchMethodException {
if (System.getSecurityManager() == null)
return clazz.getDeclaredMethod(name, types);
else {
try {
return (Method) AccessController
.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws Exception {
return clazz.getDeclaredMethod(name, types);
}
});
}
catch (PrivilegedActionException e) {
if (e.getCause() instanceof NoSuchMethodException)
throw (NoSuchMethodException) e.getCause();
throw new RuntimeException(e.getCause());
}
}
} | 3 |
@Override
public void spring(MOB target)
{
if((target!=invoker())&&(target.location()!=null)&&(text().length()>0))
{
if((doesSaveVsTraps(target))
||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target)))
target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) opening a monster cage!"));
else
if(target.location().show(target,target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> trip(s) open a caged monster!")))
{
super.spring(target);
final Item I=CMClass.getItem("GenCaged");
((CagedAnimal)I).setCageText(text());
monster=((CagedAnimal)I).unCageMe();
if(monster!=null)
{
monster.basePhyStats().setRejuv(PhyStats.NO_REJUV);
monster.bringToLife(target.location(),true);
monster.setVictim(target);
if(target.getVictim()==null)
target.setVictim(monster);
}
}
}
} | 8 |
public void onStartPage(PdfWriter writer, Document document) {
if (!this.texts.isEmpty()) {
Phrase nullphrase = new Phrase(this.marginTop, "\n是\n");
try {
document.add(nullphrase);
} catch (DocumentException e) {
e.printStackTrace();
}
for (int i = 0; i < texts.size(); ++i) {
float xper = (float) this.coordinate[i][0];
int xPos = (int)(document.getPageSize().getWidth() * xper / 100);
float yper = (float) this.coordinate[i][1];
int yPos = (int)(document.getPageSize().getHeight() * (1 - yper / 100));
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_CENTER, this.texts.get(i), xPos,
yPos, 0);
}
}
} | 3 |
private void readTotalSpend()
{
try
{
CsvReader csvReader = new CsvReader(sourceFileTotalSpend);
if(csvReader.readHeaders() == true)
{
while(csvReader.readRecord()==true)
{
//apar_id,apar_name,address,place,province,Country_code,zip_code,telephone_1,comp_reg_no,acctype
// TODO : constants for each header ?
String id = csvReader.get("text apar_id");
String client = csvReader.get("client");
String amount = csvReader.get("amt");
String period = csvReader.get("text period");
period += "01";
// TODO: only import this client for now
if(clientFilter.length()==0 || client.equalsIgnoreCase(clientFilter))
{
Company c = allCompanies.getCompanyFromId(id);
if(c!=null)
{
try
{
Date date = getDateWithOffset(period);
double val = XmlHelper.getDoubleFromXmlString(amount);
c.getTotalSpendCollection().upsert(new DoubleDatedValue(date, val));
}
catch(ParseException pe)
{
logger.warning("Failed to read row - Parse exception : " + csvReader.getRawRecord());
}
}
}
}
}
csvReader.close();
}
catch(FileNotFoundException fnfe)
{
logger.warning(fnfe.getMessage());
}
catch(IOException ioe)
{
logger.warning(ioe.getMessage());
}
catch(Exception e)
{
logger.warning(e.getMessage());
}
} | 9 |
void add(long n) {
if (arrIndx == len) {
arrIndx = 0;
listIndx++;
list.add(new long[len]);
}
list.get(listIndx)[arrIndx] = n;
arrIndx++;
} | 1 |
@Override
protected void toASCII(StringBuilder ascii, int level) {
indent(ascii, level);
NSObject[] array = allObjects();
ascii.append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN);
int indexOfLastNewLine = ascii.lastIndexOf(NEWLINE);
for (int i = 0; i < array.length; i++) {
Class<?> objClass = array[i].getClass();
if ((objClass.equals(NSDictionary.class) || objClass.equals(NSArray.class) || objClass.equals(NSData.class))
&& indexOfLastNewLine != ascii.length()) {
ascii.append(NEWLINE);
indexOfLastNewLine = ascii.length();
array[i].toASCII(ascii, level + 1);
} else {
if (i != 0)
ascii.append(" ");
array[i].toASCII(ascii, 0);
}
if (i != array.length - 1)
ascii.append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN);
if (ascii.length() - indexOfLastNewLine > ASCII_LINE_LENGTH) {
ascii.append(NEWLINE);
indexOfLastNewLine = ascii.length();
}
}
ascii.append(ASCIIPropertyListParser.ARRAY_END_TOKEN);
} | 9 |
private void beginGame()
{
Empire.SoundsOfEmpire.playIntroMusic();
final JFrame begFrame = new JFrame();
begFrame.setSize(new Dimension (20,20));
begFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(RomanLegion.class.getResource("graphics/legionist_icon.png")));
begFrame.setVisible(false);
final JWindow begWindow = new JWindow(begFrame);
begWindow.setFocusable(true);
begWindow.requestFocus();
final JButton begButton = new JButton("The Die is Cast...");
begWindow.setSize(new Dimension(480, 640));
begWindow.setForeground(Empire.EmpireDrawer.COLOR_BLACK);
begWindow.setBackground(Empire.EmpireDrawer.COLOR_BLACK);
Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize();
begWindow.setLocation((displaySize.width -begWindow.getWidth())/2, (displaySize.height - begWindow.getHeight())/2);
JPanel begPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
begPanel.setForeground(Empire.EmpireDrawer.COLOR_BLACK);
begPanel.setBackground(Empire.EmpireDrawer.COLOR_BLACK);
begPanel.add(new JLabel(Empire.EmpireDrawer.MAIN_TITLE));
begPanel.add(new JLabel(Empire.EmpireDrawer.EMPEROR));
JPanel namePanel = new JPanel ();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.X_AXIS));
namePanel.setBackground(Empire.EmpireDrawer.COLOR_BLACK);
namePanel.setForeground(Empire.EmpireDrawer.COLOR_BLACK);
JLabel nameLabel = new JLabel("Please type your name: ");
nameLabel.setFont(Empire.EmpireDrawer.TIMES_BOLD_17);
nameLabel.setForeground(Empire.EmpireDrawer.COLOR_WHITE);
namePanel.add(nameLabel);
final JTextField inputName = new JTextField(15);
inputName.setFont(Empire.EmpireDrawer.TIMES_BOLD_17);
inputName.setForeground(Empire.EmpireDrawer.COLOR_BLACK);
//inputName.setBackground(Empire.EmpireDrawer.COLOR_BLACK);
inputName.setText("");
inputName.requestFocus();
inputName.setEditable(true);
inputName.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent arg0)
{
}
@Override
public void keyReleased(KeyEvent arg0)
{
}
@Override
public void keyTyped(KeyEvent arg0)
{
//inputName.add
if(inputName.getText().length() >= 3)
{
begButton.setEnabled(true);
}
else
{
begButton.setEnabled(false);
}
}
});
namePanel.add(inputName);
begPanel.add(namePanel);
begButton.setFont(Empire.EmpireDrawer.TIMES_BOLD_24);
begButton.setBackground(Empire.EmpireDrawer.COLOR_GOLD);
begButton.setEnabled(false);
begButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0)
{
Empire.getInstance().setEmperor(inputName.getText());
begWindow.setVisible(false);
Empire.SoundsOfEmpire.stopIntroMusic();
begFrame.setVisible(false);
begWindow.dispose();
begFrame.dispose();
}
});
begPanel.add(begButton);
begWindow.getContentPane().add(BorderLayout.CENTER, begPanel);
//begWindow.pack();
begWindow.setVisible(true);
begFrame.setLocation(begWindow.getLocation());
begFrame.setVisible(true);
while(begWindow.isVisible())
{
try
{
Thread.sleep(100);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
} | 3 |
public Response serve( String uri, String method, Properties header, Properties parms, String data )
{
try{
String response_string=null;
if(data!=null){
System.out.println(DateFormat.getTimeInstance(DateFormat.FULL).format(Calendar.getInstance().getTime()));
System.out.println("Command: " + data);
String command=getCommand(data);
if(command==null){
throw(new IllegalArgumentException("Unknown message format"));
}else if(command.equals("START")){
response_string="READY";
commandStart(data);
}else if(command.equals("PLAY")){
response_string=commandPlay(data);
/* }else if(command.equals("replay")){
response_string=commandReplay(data);*/
}else if(command.equals("STOP")){
response_string="DONE";
commandStop(data);
}else{
throw(new IllegalArgumentException("Unknown command:"+command));
}
}else{
throw(new IllegalArgumentException("Message is empty!"));
}
System.out.println(DateFormat.getTimeInstance(DateFormat.FULL).format(Calendar.getInstance().getTime()));
System.out.println("Response:"+response_string);
if(response_string!=null && response_string.equals("")) response_string=null;
return new Response( HTTP_OK, "text/acl", response_string );
}catch(IllegalArgumentException ex){
System.err.println(ex);
ex.printStackTrace();
return new Response( HTTP_BADREQUEST, "text/acl", "NIL" );
}
} | 8 |
public Dimension getPreferredSize() {
return new Dimension(22 * x, 22 * y);
} | 0 |
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
final Room R=mob.location();
if((R!=null)&&(!R.getArea().getClimateObj().canSeeTheMoon(R,null)))
{
if((R.getArea().getTimeObj().getTODCode()!=TimeClock.TimeOfDay.DUSK)
&&(R.getArea().getTimeObj().getTODCode()!=TimeClock.TimeOfDay.NIGHT))
return Ability.QUALITY_INDIFFERENT;
if((R.domainType()&Room.INDOORS)==0)
return Ability.QUALITY_INDIFFERENT;
if(R.fetchEffect(ID())!=null)
return Ability.QUALITY_INDIFFERENT;
return super.castingQuality(mob, target,Ability.QUALITY_BENEFICIAL_SELF);
}
}
return super.castingQuality(mob,target);
} | 7 |
public static boolean pnpoly(int npol, float[] xp, float[] yp, float x, float y)
{
int i, j;
boolean c = false;
for (i = 0, j = npol-1; i < npol; j = i++) {
if ((((yp[i] <= y) && (y < yp[j])) ||
((yp[j] <= y) && (y < yp[i]))) &&
(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i]))
c = !c;
}
return c;
} | 6 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((declaration == null) ? 0 : declaration.hashCode());
result = prime * result + ((ident == null) ? 0 : ident.hashCode());
result = prime
* result
+ ((statementSequence == null) ? 0 : statementSequence
.hashCode());
return result;
} | 3 |
private void ConsultaBDNaoConformidadeSelect( ){
int idNaoConformidade = 0;
int idContResultado = 0;
int idFuncionario = 0;
String dataNaoConform = "";
String ocorrencia = "";
String medidaCorrecti = "";
String resultado = "NC";
String nomefuncionario = "";
String correctiva = "N";
int idFuncionarioResponsavel = 0;
String nomeFuncionarioResponsavel = "";
contaNaoConformidade_MedidasCorrectivas = 0;
model = (DefaultTableModel) jTableNaoConformidades.getModel();
//Ligação BD
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}catch(ClassNotFoundException e){
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
System.out.println("O driver expecificado nao foi encontrado.");
}
try{
con = DriverManager.getConnection(url);
String nomeTabela = "CONTROLORESULTADOS";
String sql = "select * from "+nomeTabela+" where IDFUNCIONARIO="+idFuncionarioNaoConformidade +"and RESULTADO="+"'"+ resultado +"'";
//String sql = "select * from "+nomeTabela+" where IDFUNCIONARIO="+funcionario;
PreparedStatement st = (PreparedStatement) con.prepareStatement(sql);
ResultSet rs = st.executeQuery();
while(rs.next()){
idControloResultadosID = rs.getInt("IDCONTRESULTADOS");
System.out.println("IDCONTROLORESULTADO Pesquisar -> " + idControloResultadosID);
//VARIVAEL GLOBAL
addNewNaoConformidadeIdFuncionario = idFuncionario;
// addNewNaoConformidadeIdFuncionario = funcionario;
//ESCREVER NA TABELA A PESQUISA
String nomeTabela2 = "NAOCONFORMIDADES";
String sql2 = "select * from "+nomeTabela2+" where IDCONTRESULTADOS="+idControloResultadosID+" and CORRECTIVA='" + correctiva + "'";
PreparedStatement st2 = (PreparedStatement) con.prepareStatement(sql2);
ResultSet rs2 = st2.executeQuery();
while(rs2.next()){
idNaoConformidade = rs2.getInt("IDNAOCONF");
idContResultado = rs2.getInt("IDCONTRESULTADOS");
idFuncionario = rs2.getInt("IDFUNCIONARIO");
nomefuncionario = selectString("FUNCIONARIO","IDFUNCIONARIO",idFuncionario,"NOME");
dataNaoConform = rs2.getString("DATANAOCONFORMIDADE");
ocorrencia = rs2.getString("OCORRENCIA");
medidaCorrecti = rs2.getString("MEDIDACORRECTIVA");
idFuncionarioResponsavel = rs2.getInt("IDFUNCIONARIOMEDIDACORRECTIVA");
nomeFuncionarioResponsavel = selectString("FUNCIONARIO","IDFUNCIONARIO",idFuncionarioResponsavel,"NOME");
model.addRow(new Object[]{idNaoConformidade,nomefuncionario, dataNaoConform, ocorrencia, medidaCorrecti, nomeFuncionarioResponsavel});
contaNaoConformidade_MedidasCorrectivas++;
idContResultadosUltimo = idContResultado;
}
st2.close();
}
st.close();
con.close();
}catch (SQLException ex){
System.err.println("SQLException: " + ex.getMessage());
}
/* VERIFICAR SE É O ULTIMO OU NAO NA LISTA *
* IR A TABELA CONTROLO RESULTADOS ALTERAR O VALOR DO RESULTADO*/
if (contaNaoConformidade_MedidasCorrectivas == 0){
//PERGUNTAMOS SE QUER ADICIONAR UMA NAO CONFORMIDADE OU SE QUE ALTERAR O ESTADO DO CONTROLO DE RESULTADO
int resultNaoConformidade = JOptionPane.showConfirmDialog(jDialogConsultarControlos, "Deseja Adicionar uma Nova Não Conformidade ?", null, JOptionPane.YES_NO_OPTION);
if(resultNaoConformidade == JOptionPane.YES_OPTION){
//ADICIONAR NOVA NAO CONFORMIDADE
System.out.println("\n\nABRIR JANELA NAO CONFORMIDADE");
jDialogNaoConformidades.setVisible(true);
}else if (resultNaoConformidade == JOptionPane.NO_OPTION){
int resultAtualizarEstado = JOptionPane.showConfirmDialog(jDialogConsultarControlos, "Deseja Actualizar o Estado da Medida Correctiva \n e do Controlo de Resultados ?", null, JOptionPane.YES_NO_OPTION);
if (resultAtualizarEstado == JOptionPane.YES_OPTION){
System.out.println("ACTUALIZAR O ESTADO DO CONTROLO E DA MEDIDAD CORRECTIVA");
}
}
//ACTUALIZAR OS DADOS NA TABELA NAO CONFORMIDADES
// ActualizaMedidaCorrectiva();
// //ACTUALIZAR A TABELA DE CONTROLO DE RESULTADOS
// JOptionPane.showMessageDialog(jDialogMedidasCorrectiva, "IRÁ SER ALERADO O RESULTADO DO CONTROLO DE RESULTADO!");
// ActualizaControloResultado();
// jTextAreaObservacaoMedidaCorrectiva.setText("");
// jDialogMedidasCorrectiva.setVisible(false);
// jDialogConsultaNaoConformidades.setVisible(false);
}
System.out.println("\n*** NUMERO DE REGISTO DE NAO CONFORMIDADES");
System.out.println("REGISTOS: " + contaNaoConformidade_MedidasCorrectivas);
System.out.println("ID ULTIMO: " +idContResultadosUltimo);
System.out.println("*** SELECCIONADO NA TABELA ");
System.out.println("ID : " + idFuncionarioNaoConformidade );
} | 8 |
public int getIndex() {
if (mParent != null) {
return mIndex;
}
return -1;
} | 1 |
public static void main(String[] args)
{
int x, y, r, proceso;
x = Integer.parseInt(JOptionPane.showInputDialog("Ingrese un Valor Entero para 'X':"));
y = Integer.parseInt(JOptionPane.showInputDialog("Ingrese un Valor Entero para 'Y':"));
if ((x <= 0) || (x > 255))
{
r = -1;
JOptionPane.showMessageDialog(null, "Resultado: " + r);
}
else
{
int[] arreglo = new int[y];
arreglo[0] = x;
for (int i = 1; i <arreglo.length; i++)
{
proceso = x / (i+1);
arreglo[i] = proceso;
}
for (int i = 0; i < arreglo.length; i++)
{
if(i == (y-1))
{
JOptionPane.showMessageDialog(null, "Resultado: " + arreglo[i]);
}
}
}
} | 5 |
public void inicio(PalavraChave palavrachave) throws Exception
{
salvar = new JButton("Salvar");
id = new JTextInt(palavrachave.getId());
id.setEditable(false);
id.setEnabled(false);
palavra = new JTextField(palavrachave.getPalavra() == null ? ""
: palavrachave.getPalavra());
JPanel pp = new JPanel();
DesignGridLayout layout = new DesignGridLayout(pp);
layout.row().grid(new JLabel("ID:")).add(id);
layout.row().grid(new JLabel("Palavra-chave:")).add(palavra);
layout.row().grid().add(salvar, 1);
getContentPane().add(new JScrollPane(pp));
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400, 150);
setVisible(true);
} | 1 |
public static int getType(Neuron n){
if(n instanceof InputNeuron_Add)
return 1;
if(n instanceof OutputNeuron_Add)
return 2;
if(n instanceof Neuron_Add)
return 3;
if(n instanceof DistanceThresholdChecker)
return 4;
if(n instanceof PitChecker)
return 5;
if(n instanceof HorizontalChecker)
return 6;
if(n instanceof VerticalChecker)
return 7;
return 3; //default
} | 7 |
public static void SortOrbitals()
{
for (int x = 0; x < Ops.getOrbitalClasses().size(); x++)
{
switch (Ops.getOrbitalClasses(x).GetHZRating())
{
case 1:
HotOrbitals.add(x);
break;
case 2:
HZOrbitals.add(x);
break;
case 3:
ColdOrbitals.add(x);
break;
case 4:
HotOrbitals.add(x);
HZOrbitals.add(x);
ColdOrbitals.add(x);
break;
}
}
} | 5 |
public int getPerceptIndex( String percept ){
if( percept.equals(SOLVED) ){
return (getPerceptsNumber() - 1);
}else{
int[] values = new int[2];
int k = 0;
try {
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(
percept));
while (k < 2 && tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
values[k] = (int) (tokenizer.nval);
k++;
}
}
return values[0] * DIGITS + values[1];
} catch (Exception e) {
return -1;
}
}
} | 5 |
public int getType() {
return mType;
} | 0 |
@Override
public void configure(AbstractCommand command, String[] args) {
TimeBanHelpCommand helpCommand = (TimeBanHelpCommand) command;
if (args.length >= 1) {
helpCommand.setManPage(args[0]);
} else {
helpCommand.setManPage("help");
}
} | 1 |
protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
} | 9 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof News)) return false;
News news = (News) o;
if (id != news.id) return false;
if (!annotation.equals(news.annotation)) return false;
if (!author.equals(news.author)) return false;
if (!category.equals(news.category)) return false;
if (!content.equals(news.content)) return false;
if (!startDate.equals(news.startDate)) return false;
if (!title.equals(news.title)) return false;
return true;
} | 9 |
public void paint(Graphics g){
//ここに描画処理を書きます。
Color bgcol = new Color(220,220,220);
setBackground(bgcol);
g.setColor(Color.BLACK);
g.drawLine(0, (int)dmax.get(1,0) - 100, (int)dmax.get(0, 0), (int)dmax.get(1, 0) - 100); //
g.drawLine(100 , 0, 100, (int)dmax.get(1, 0)); //y軸
int zeropointx = 100;
int zeropointy = (int) dmax.get(1, 0) - 100;
for(int i = 0; i < drawpo.length; i++){
for(int j = 0; j < drawpo[i].samplenum(); j++){
double xy[] = new double[drawpo[i].dimension()];
for(int k = 0; k < drawpo[i].dimension(); k++){
xy[k] = drawpo[i].returnPoint(j).get(k,0);
}
if(classmethod == 0){
g.setColor(setclr(drawpo[i].returnkclass(j)));
}
else{
g.setColor(setclr(drawpo[i].returnnnclass(j)));
}
g.fillRect(zeropointx + (int) xy[0], zeropointy - (int) xy[1], 3, 3);
}
}
} | 4 |
public boolean canPlaceBlockAt(World par1World, int par2, int par3, int par4)
{
int var5 = par1World.getBlockId(par2, par3 - 1, par4);
return var5 == this.blockID ? true : (var5 != Block.grass.blockID && var5 != Block.dirt.blockID && var5 != Block.sand.blockID ? false : (par1World.getBlockMaterial(par2 - 1, par3 - 1, par4) == Material.water ? true : (par1World.getBlockMaterial(par2 + 1, par3 - 1, par4) == Material.water ? true : (par1World.getBlockMaterial(par2, par3 - 1, par4 - 1) == Material.water ? true : par1World.getBlockMaterial(par2, par3 - 1, par4 + 1) == Material.water))));
} | 7 |
public void setDataChiusura(Date dataChiusura) {
this.dataChiusura = dataChiusura;
} | 0 |
public synchronized void gridletPause(int gridletId, int userId, boolean ack)
{
boolean status = false;
// Find in EXEC List first
int found = gridletInExecList_.indexOf(gridletId, userId);
if (found >= 0)
{
// updates all the Gridlets first before pausing
updateGridletProcessing();
// Removes the Gridlet from the execution list
ResGridlet rgl = (ResGridlet) gridletInExecList_.remove(found);
if (rgl.getRemainingGridletLength() == 0.0)
{
found = -1; // meaning not found in Queue List
rgl.setGridletStatus(Gridlet.SUCCESS);
rgl.finalizeGridlet();
super.sendFinishGridlet( rgl.getGridlet() );
logger.log(Level.INFO,super.resName_
+ ".PerfectCheckpointing.gridletPause(): Cannot pause"
+ " Gridlet #" + gridletId + " for User #" + userId
+ " since it has FINISHED.");
}
else
{
status = true;
rgl.setGridletStatus(Gridlet.PAUSED); // change the status
gridletPausedList_.add(rgl); // add into the paused list
}
}
else { // Find in QUEUE list
found = gridletQueueList_.indexOf(gridletId, userId);
}
// if found in the Queue List
if (!status && found >= 0)
{
status = true;
// removes the Gridlet from the Queue list
ResGridlet rgl = (ResGridlet) gridletQueueList_.remove(found);
rgl.setGridletStatus(Gridlet.PAUSED); // change the status
gridletPausedList_.add(rgl); // add into the paused list
}
// if not found anywhere in both exec and paused lists
else if (found == -1)
{
logger.log(Level.INFO,super.resName_ +
".PerfectCheckpointing.gridletPause(): Error - cannot " +
"find Gridlet #" + gridletId + " for User #" + userId);
}
// sends back an ack if required
if (ack)
{
super.sendAck(GridSimTags.GRIDLET_PAUSE_ACK, status,
gridletId, userId);
}
} | 6 |
private void initialize(final Spel spel) throws IOException {
this.spel = spel;
// Haal informatie uit de controller
String vraag = spel.getVraagTekst();
onderdelen = spel.getOnderdelen();
// Layout instellingen
setBounds(0, 0, 1024, 768);
setLayout(new MigLayout("ins 0 10px 10px 10px", "[124][grow][]",
"[110.00][350px:24.00,grow][:126.00:250px,grow,fill]"));
// Middenvlak toevoegen
middenvlak.setLayout(new GridLayout(1, 0, 0, 0));
add(middenvlak, "cell 1 1 2 1,grow");
// Vraag toevoegen
add(JLabelFactory.createJLabel(vraag), "cell 1 0 2 1");
// Toon kiesbare onderdelen
JPanel buttonsPanel = JPanelFactory.createTransparentJPanel();
buttonsPanel.setLayout(new MigLayout("ins 10px 10px 0 10px", "[grow]",
"[grow][grow][grow][grow][grow][grow][grow][grow][grow][grow]"));
add(buttonsPanel, "cell 0 1,grow");
toonOnderdelen(buttonsPanel, onderdelen);
gekozenAntwoordenPanel = JPanelFactory.createTransparentJPanel();
gekozenAntwoordenPanel.setBackground(new Color(0, 0, 0, 0));
gekozenAntwoordenPanel.setLayout(new MigLayout("ins 0", "[][][][][][][][][][]", "[grow,fill]"));
JScrollPane scrollPane = JPanelFactory.createJScrollPane(gekozenAntwoordenPanel);
scrollPane.setBorder(BorderFactory.createLineBorder(Color.white));
add(scrollPane, "cell 0 2 2 1,grow");
volgendeOnderdeel();
toonInfoPanel(spel);
spel.getTimer().start();
spel.getTimer().addObserver(new Observer() {
@Override
public void update(Observable arg0, Object arg1) {
if (spel.getTimer().hasLost()) spel.openPanel(new GameOver(spel, GameOver.Reason.TIMEUP));
}
});
} | 1 |
private boolean renderPistonExtension(Block par1Block, int par2, int par3, int par4, boolean par5)
{
int i = blockAccess.getBlockMetadata(par2, par3, par4);
int j = BlockPistonExtension.getDirectionMeta(i);
float f = par1Block.getBlockBrightness(blockAccess, par2, par3, par4);
float f1 = par5 ? 1.0F : 0.5F;
double d = par5 ? 16D : 8D;
switch (j)
{
case 0:
uvRotateEast = 3;
uvRotateWest = 3;
uvRotateSouth = 3;
uvRotateNorth = 3;
par1Block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.25F, 1.0F);
renderStandardBlock(par1Block, par2, par3, par4);
renderPistonRodUD((float)par2 + 0.375F, (float)par2 + 0.625F, (float)par3 + 0.25F, (float)par3 + 0.25F + f1, (float)par4 + 0.625F, (float)par4 + 0.625F, f * 0.8F, d);
renderPistonRodUD((float)par2 + 0.625F, (float)par2 + 0.375F, (float)par3 + 0.25F, (float)par3 + 0.25F + f1, (float)par4 + 0.375F, (float)par4 + 0.375F, f * 0.8F, d);
renderPistonRodUD((float)par2 + 0.375F, (float)par2 + 0.375F, (float)par3 + 0.25F, (float)par3 + 0.25F + f1, (float)par4 + 0.375F, (float)par4 + 0.625F, f * 0.6F, d);
renderPistonRodUD((float)par2 + 0.625F, (float)par2 + 0.625F, (float)par3 + 0.25F, (float)par3 + 0.25F + f1, (float)par4 + 0.625F, (float)par4 + 0.375F, f * 0.6F, d);
break;
case 1:
par1Block.setBlockBounds(0.0F, 0.75F, 0.0F, 1.0F, 1.0F, 1.0F);
renderStandardBlock(par1Block, par2, par3, par4);
renderPistonRodUD((float)par2 + 0.375F, (float)par2 + 0.625F, (((float)par3 - 0.25F) + 1.0F) - f1, ((float)par3 - 0.25F) + 1.0F, (float)par4 + 0.625F, (float)par4 + 0.625F, f * 0.8F, d);
renderPistonRodUD((float)par2 + 0.625F, (float)par2 + 0.375F, (((float)par3 - 0.25F) + 1.0F) - f1, ((float)par3 - 0.25F) + 1.0F, (float)par4 + 0.375F, (float)par4 + 0.375F, f * 0.8F, d);
renderPistonRodUD((float)par2 + 0.375F, (float)par2 + 0.375F, (((float)par3 - 0.25F) + 1.0F) - f1, ((float)par3 - 0.25F) + 1.0F, (float)par4 + 0.375F, (float)par4 + 0.625F, f * 0.6F, d);
renderPistonRodUD((float)par2 + 0.625F, (float)par2 + 0.625F, (((float)par3 - 0.25F) + 1.0F) - f1, ((float)par3 - 0.25F) + 1.0F, (float)par4 + 0.625F, (float)par4 + 0.375F, f * 0.6F, d);
break;
case 2:
uvRotateSouth = 1;
uvRotateNorth = 2;
par1Block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.25F);
renderStandardBlock(par1Block, par2, par3, par4);
renderPistonRodSN((float)par2 + 0.375F, (float)par2 + 0.375F, (float)par3 + 0.625F, (float)par3 + 0.375F, (float)par4 + 0.25F, (float)par4 + 0.25F + f1, f * 0.6F, d);
renderPistonRodSN((float)par2 + 0.625F, (float)par2 + 0.625F, (float)par3 + 0.375F, (float)par3 + 0.625F, (float)par4 + 0.25F, (float)par4 + 0.25F + f1, f * 0.6F, d);
renderPistonRodSN((float)par2 + 0.375F, (float)par2 + 0.625F, (float)par3 + 0.375F, (float)par3 + 0.375F, (float)par4 + 0.25F, (float)par4 + 0.25F + f1, f * 0.5F, d);
renderPistonRodSN((float)par2 + 0.625F, (float)par2 + 0.375F, (float)par3 + 0.625F, (float)par3 + 0.625F, (float)par4 + 0.25F, (float)par4 + 0.25F + f1, f, d);
break;
case 3:
uvRotateSouth = 2;
uvRotateNorth = 1;
uvRotateTop = 3;
uvRotateBottom = 3;
par1Block.setBlockBounds(0.0F, 0.0F, 0.75F, 1.0F, 1.0F, 1.0F);
renderStandardBlock(par1Block, par2, par3, par4);
renderPistonRodSN((float)par2 + 0.375F, (float)par2 + 0.375F, (float)par3 + 0.625F, (float)par3 + 0.375F, (((float)par4 - 0.25F) + 1.0F) - f1, ((float)par4 - 0.25F) + 1.0F, f * 0.6F, d);
renderPistonRodSN((float)par2 + 0.625F, (float)par2 + 0.625F, (float)par3 + 0.375F, (float)par3 + 0.625F, (((float)par4 - 0.25F) + 1.0F) - f1, ((float)par4 - 0.25F) + 1.0F, f * 0.6F, d);
renderPistonRodSN((float)par2 + 0.375F, (float)par2 + 0.625F, (float)par3 + 0.375F, (float)par3 + 0.375F, (((float)par4 - 0.25F) + 1.0F) - f1, ((float)par4 - 0.25F) + 1.0F, f * 0.5F, d);
renderPistonRodSN((float)par2 + 0.625F, (float)par2 + 0.375F, (float)par3 + 0.625F, (float)par3 + 0.625F, (((float)par4 - 0.25F) + 1.0F) - f1, ((float)par4 - 0.25F) + 1.0F, f, d);
break;
case 4:
uvRotateEast = 1;
uvRotateWest = 2;
uvRotateTop = 2;
uvRotateBottom = 1;
par1Block.setBlockBounds(0.0F, 0.0F, 0.0F, 0.25F, 1.0F, 1.0F);
renderStandardBlock(par1Block, par2, par3, par4);
renderPistonRodEW((float)par2 + 0.25F, (float)par2 + 0.25F + f1, (float)par3 + 0.375F, (float)par3 + 0.375F, (float)par4 + 0.625F, (float)par4 + 0.375F, f * 0.5F, d);
renderPistonRodEW((float)par2 + 0.25F, (float)par2 + 0.25F + f1, (float)par3 + 0.625F, (float)par3 + 0.625F, (float)par4 + 0.375F, (float)par4 + 0.625F, f, d);
renderPistonRodEW((float)par2 + 0.25F, (float)par2 + 0.25F + f1, (float)par3 + 0.375F, (float)par3 + 0.625F, (float)par4 + 0.375F, (float)par4 + 0.375F, f * 0.6F, d);
renderPistonRodEW((float)par2 + 0.25F, (float)par2 + 0.25F + f1, (float)par3 + 0.625F, (float)par3 + 0.375F, (float)par4 + 0.625F, (float)par4 + 0.625F, f * 0.6F, d);
break;
case 5:
uvRotateEast = 2;
uvRotateWest = 1;
uvRotateTop = 1;
uvRotateBottom = 2;
par1Block.setBlockBounds(0.75F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
renderStandardBlock(par1Block, par2, par3, par4);
renderPistonRodEW((((float)par2 - 0.25F) + 1.0F) - f1, ((float)par2 - 0.25F) + 1.0F, (float)par3 + 0.375F, (float)par3 + 0.375F, (float)par4 + 0.625F, (float)par4 + 0.375F, f * 0.5F, d);
renderPistonRodEW((((float)par2 - 0.25F) + 1.0F) - f1, ((float)par2 - 0.25F) + 1.0F, (float)par3 + 0.625F, (float)par3 + 0.625F, (float)par4 + 0.375F, (float)par4 + 0.625F, f, d);
renderPistonRodEW((((float)par2 - 0.25F) + 1.0F) - f1, ((float)par2 - 0.25F) + 1.0F, (float)par3 + 0.375F, (float)par3 + 0.625F, (float)par4 + 0.375F, (float)par4 + 0.375F, f * 0.6F, d);
renderPistonRodEW((((float)par2 - 0.25F) + 1.0F) - f1, ((float)par2 - 0.25F) + 1.0F, (float)par3 + 0.625F, (float)par3 + 0.375F, (float)par4 + 0.625F, (float)par4 + 0.625F, f * 0.6F, d);
break;
}
uvRotateEast = 0;
uvRotateWest = 0;
uvRotateSouth = 0;
uvRotateNorth = 0;
uvRotateTop = 0;
uvRotateBottom = 0;
par1Block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
return true;
} | 8 |
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.equals(""))
text = "0";
if (!StringUtils.hasText(text)) {
setValue(null);
} else {
setValue(Integer.parseInt(text));// 这句话是最重要的,他的目的是通过传入参数的类型来匹配相应的databind
}
} | 3 |
public void dstwdg(int id, Widget w) {
if(w == chrlist) {
destroy();
succeed();
}
} | 1 |
public TreeMenu(){
super();
menu = new JPopupMenu();
menu.setLightWeightPopupEnabled(false);
addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
grabFocus();
}
});
MouseAdapter ma = new MouseAdapter() {
private void myPopupEvent(MouseEvent e) {
int x = e.getX();
int y = e.getY();
JTree tree = (JTree)e.getSource();
TreePath path = tree.getPathForLocation(x, y);
if (path != null){
tree.setSelectionPath(path);
}
// return;
//Object obj = path.getLastPathComponent();
//String label = "popup: " + obj.getTreeLabel();
checkEnabledMenuAction();
menu.show(tree, x, y);
}
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) myPopupEvent(e);
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) myPopupEvent(e);
}
};
addMouseListener(ma);
createMenu();
createMenuShortcut();
} | 3 |
public synchronized int select(int interestOps, Integer timeout) {
int n;
Selector selector;
if ((interestOps & SelectionKey.OP_READ) != 0) {
selector = readSelector;
} else {
selector = writeSelector;
}
selector.selectedKeys().clear();
try {
if (timeout == null) {
n = selector.select();
} else {
int tv = timeout.intValue();
switch(tv) {
case 0:
n = selector.selectNow();
break;
default:
n = selector.select((long)tv);
break;
}
}
} catch(IOException e) {
throw new SystemException(e.toString());
}
return n;
} | 4 |
public int hashCode() {
return super.hashCode() ^ myLabel.hashCode();
} | 0 |
private FrontCommand getCommand(HttpServletRequest req)
throws Exception {
try {
return (FrontCommand) getCommandClass(req).newInstance();
} catch (Exception e) {
throw new Exception();
}
} | 1 |
public void addArc(Node elem) {
int nodeIndex = adjacentNodes.indexOf(elem);
if (nodeIndex == -1)
adjacentNodes.add(elem);
} | 1 |
private Collection<T> criaInstancias(ResultSet result) throws SQLException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
ArrayList<T> instancias = new ArrayList<>();
result.first();
do {
Constructor constructor = null;
try {
constructor = classe.getConstructor();
constructor.setAccessible(true);
} catch (NoSuchMethodException e) {
char primeiro = Character.toUpperCase(nomeEntidade.charAt(0));
throw new RuntimeException("Construtor padrão " + primeiro
+ nomeEntidade.substring(1) + "() não está presente");
}
T object = (T) constructor.newInstance();
for (Field campo : campos) {
campo.setAccessible(true);
switch (campo.getType().getSimpleName().toLowerCase()) {
case "long":
campo.set(object, result.getLong(apoio.getNomeCampo(campo)));
break;
case "string":
campo.set(object, result.getString(apoio.getNomeCampo(campo)));
break;
case "int":
campo.set(object, result.getInt(apoio.getNomeCampo(campo)));
break;
case "double":
campo.set(object, result.getDouble(apoio.getNomeCampo(campo)));
break;
case "float":
campo.set(object, result.getFloat(apoio.getNomeCampo(campo)));
break;
case "char":
campo.set(object, result.getString(apoio.getNomeCampo(campo)).charAt(0));
break;
}
}
instancias.add(object);
} while (result.next());
return instancias;
} | 9 |
public void inserir(long idPesquisa, ArrayList<Pesquisador> pesquisadores) throws Exception
{
String sql = "INSERT INTO Pesquisacolaboradores (id1,id2) VALUES(?, ?)";
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql);
for (Pesquisador pesquisador : pesquisadores)
{
stmt.setLong(1, idPesquisa);
stmt.setLong(2, pesquisador.getId());
try
{
stmt.execute();
}
catch (SQLException e)
{
throw e;
}
stmt.clearParameters();
}
} | 2 |
public static void listDBs() throws Exception
{
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
// see if a connection is established
if(conn != null)
{
System.out.println("Connection established");
}
// list all the databases in it:
DatabaseMetaData meta = conn.getMetaData();
ResultSet res = meta.getCatalogs();
System.out.println("List of databases: ");
while (res.next())
{
System.out.println(" "+res.getString("TABLE_CAT"));
}
// close response
res.close();
// close connection
conn.close();
} | 2 |
public static void setZeros( int[][] m ) {
// m is a two dimenstional array which represents a Matrix
int rows = m.length ;
int cols = m[0].length;
List<Integer> rIdx = new ArrayList<>();
List<Integer> cIdx = new ArrayList<>();
// 1.iterate through the matrix to find all 0
for ( int y=0; y != rows; ++y )
for( int x=0; x != cols; ++x ) {
if ( m[y][x] == 0 ) {
rIdx.add( y );
cIdx.add( x );
}
}
// 2. set all rows to zeros.
for ( int i : rIdx ) {
for ( int j=0; j != cols; j++) {
m[i][j] = 0;
}
}
// 3. set all column to zeros.
for ( int i : cIdx ) {
for ( int j=0; j != cols; j++) {
m[j][i] = 0;
}
}
} | 7 |
public Object invoke() throws Exception {
Method m = null;
Method[] tabm = classe.getMethods();
for (int i = 0; i < tabm.length; i++) {
if (!tabm[i].getName().equals(method))
continue;
Class[] paramTypes = tabm[i].getParameterTypes();
int paramLength = (param == null)?0:param.length;
if (paramTypes.length != paramLength)
continue;
// Même nom et même nombre de paramètres => méthode trouvée!!
// On ne va pas jusqu'à tester le type des paramètres pour l'instant.
// pour les varArgs, passer un tableau vide a l'appel
m = tabm[i];
break;
}
if (m == null)
throw new NoSuchMethodException();
return m.invoke(object, param); //si object == null, method statique
} | 5 |
public void initOnGoing() {
ScheduledThreadPoolExecutor pe = (ScheduledThreadPoolExecutor) Executors
.newScheduledThreadPool(1);
InitFetcherManager ccf = this.new InitFetcherManager();
long ongoingCycleDelay = Long.valueOf(ConfigManager.getInstance()
.getConfigItem(IautosConstant.ONGOING_CYCLE_DELAY, 86400));
pe.scheduleAtFixedRate(ccf, 0, ongoingCycleDelay, TimeUnit.SECONDS);
} | 0 |
protected void createSource() throws JavaLayerException
{
Throwable t = null;
try
{
Line line = AudioSystem.getLine(getSourceLineInfo());
if (line instanceof SourceDataLine)
{
source = (SourceDataLine)line;
//source.open(fmt, millisecondsToBytes(fmt, 2000));
source.open(fmt);
/*
if (source.isControlSupported(FloatControl.Type.MASTER_GAIN))
{
FloatControl c = (FloatControl)source.getControl(FloatControl.Type.MASTER_GAIN);
c.setValue(c.getMaximum());
}*/
source.start();
}
} catch (RuntimeException ex)
{
t = ex;
}
catch (LinkageError ex)
{
t = ex;
}
catch (LineUnavailableException ex)
{
t = ex;
}
if (source==null) throw new JavaLayerException("cannot obtain source audio line", t);
} | 5 |
private String readLine(InputStream in) {
// reads a line of text from an InputStream
StringBuffer data = new StringBuffer("");
int c;
try {
// if we have nothing to read, just return null
in.mark(1);
if (in.read() == -1) {
return null;
} else {
in.reset();
}
while ((c = in.read()) >= 0) {
// check for an end-of-line character
if ((c == 0) || (c == 10) || (c == 13)) {
break;
} else {
data.append((char) c);
}
}
// deal with the case where the end-of-line terminator is \r\n
if (c == 13) {
in.mark(1);
if (in.read() != 10) {
in.reset();
}
}
} catch (Exception e) {
if (debugLevel > 0) {
debugOut.println("Error getting header: " + e);
}
}
// and return what we have
return data.toString();
} | 9 |
public void testUnique() throws Exception {
//Return if this is not Windows OS
if (!isWindows) {
return;
}
/*
* Number of timestamps to generate on each client
*/
int iterations = 11000;
/*
* Number of client threads
*/
int threadCount = 4;
// Launch threadCount client threads and set them
// off generating time stamps
long[][] threadTimes = new long[threadCount][iterations];
Thread[] clockClients = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
clockClients[i] = new ClockClient(threadTimes[i], iterations);
clockClients[i].start();
}
// Wait until all the threads are done
boolean working = true;
while (working) {
working = false;
for (int i = 0; i < threadCount; i++) {
if (clockClients[i].isAlive()) {
working = true;
}
}
}
// Check for duplicates within each client
// Ridiculously inefficient, but effective -- sort and walk
for (int j = 0; j < threadTimes.length; j++) {
Arrays.sort(threadTimes[j]);
for (int i = 0; i < threadTimes.length - 1; i++) {
if (threadTimes[j][i] == threadTimes[j][i + 1]) {
fail( "Duplicate time stamps generated: " + threadTimes[j][i] + " " + i);
}
}
}
} | 8 |
private Entry<K,V> getPrecedingEntryInclusive(K key) {
Entry<K,V> p = root;
if (p==null)
return null;
while (true) {
int cmp = compare(key, p.key);
if (cmp > 0) {
if (p.right != null)
p = p.right;
else
return p;
}
else if (cmp == 0) {
return p;
}
else {
if (p.left != null) {
p = p.left;
} else {
Entry<K,V> parent = p.parent;
Entry<K,V> ch = p;
while (parent != null && ch == parent.left) {
ch = parent;
parent = parent.parent;
}
return parent;
}
}
}
} | 8 |
public void run() {
Fluid.log("Target: Accepting connections on port " + port);
while(isConnected()) {
try {
// accept and do as little processing as possible
if(username != null && password != null)
new Client(this, clientConnection.accept(), idleTimeout, max, ruleFile, username, password);
else
new Client(this, clientConnection.accept(), idleTimeout, max, ruleFile);
}
catch(IOException e) {
// accept next client
}
}
} | 4 |
public static void main(String[] args) throws UnsupportedLookAndFeelException {
final Logger l = Logger.getLogger(Load.class.getName());
Thread cleanupThread = new Thread(
new Runnable() {
@Override
public void run() {
System.out.println("Shutdown hook ran.");
otapiJNI.OTAPI_Basic_AppShutdown();
}
});
Runtime.getRuntime().addShutdownHook(cleanupThread);
int retVal = Loader.Load();
if (0 < retVal) // success (run Moneychanger)
{
launch(Moneychanger.class, args);
}
if (0 == retVal) // cancel (just quit, no need to cleanup)
{
l.log(Level.WARNING, "Failed to Load. Will not atempt to run Moneychanger!");
Runtime.getRuntime().removeShutdownHook(cleanupThread);
System.exit(0);
}
if (0 > retVal) // error (quit and cleanup)
{
l.log(Level.SEVERE, "Failed to Load. Will not atempt to run Moneychanger!");
System.exit(0);
}
} | 3 |
public void calculateNumberOfBreakpoints() {
int counter = 0;
for (int i = 0; i < permutArray.length - 1; i++) {
if (permutArray[i] - permutArray[i + 1] != -1) {
counter++;
}
}
if (permutArray[0] != 1) {
counter++;
}
if (permutArray[permutArray.length - 1] != permutArray.length) {
counter++;
}
System.out.print(counter);
} | 4 |
public Object getValueAt( int row, int col )
{
Object dummy = liste.get( row ) ;
if (dummy != null)
{
ISOLanguage data = (ISOLanguage) liste.get( row ) ;
switch (col)
{
case FULL_ENTRY:
return dummy ;
case 0:
return data.getLanguageIso() ;
case 1:
return data.getLanguageName() ;
}
}
return "" ;
} | 4 |
private void loadImages() {
try {
// Load tiles
tileMap = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("Tiles.png")); // Grab the tilemap
for (byte i = 0; i < tiles.length; i++) { // For every tile that there should be
tiles[i] = tileMap.getSubimage(i * 32, 0, 32, 32); // Create a subimage from tile map, and store it as a separate image
}
// Load plants
plantMap = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("Plant.png")); // Grab the tilemap
for (byte i = 0; i < plants.length; i++) { // For every tile that there should be
plants[i] = plantMap.getSubimage(i * 32, 0, 32, 32); // Create a subimage from tile map, and store it as a seperate image
}
playerMap = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("Player.png"));
for (byte i = 0; i < playerFaces.length; i++) { // For every tile that there should be
playerFaces[i] = playerMap.getSubimage(i * 32, 0, 32, 32); // Create a subimage from tile map, and store it as a separate image
}
toolMap = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("Tools.png"));
for (byte i = 0; i < tools.length; i++) { // For every tile that there should be
tools[i] = toolMap.getSubimage(i * 32, 0, 32, 32); // Create a subimage from tile map, and store it as a separate image
}
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
@Override
protected void buildModel() throws Exception {
for (int iter = 1; iter <= numIters; iter++) {
errs = 0;
loss = 0;
DenseMatrix PS = new DenseMatrix(numUsers, numFactors);
DenseMatrix QS = new DenseMatrix(numItems, numFactors);
DenseMatrix ZS = new DenseMatrix(numUsers, numFactors);
// ratings
for (MatrixEntry me : trainMatrix) {
int u = me.row();
int j = me.column();
double ruj = me.get();
if (ruj <= 0)
continue;
double pred = predict(u, j, false);
double euj = g(pred) - normalize(ruj);
errs += euj * euj;
loss += euj * euj;
for (int f = 0; f < numFactors; f++) {
double puf = P.get(u, f);
double qjf = Q.get(j, f);
PS.add(u, f, gd(pred) * euj * qjf + regU * puf);
QS.add(j, f, gd(pred) * euj * puf + regI * qjf);
loss += regU * puf * puf + regI * qjf * qjf;
}
}
// friends
for (MatrixEntry me : socialMatrix) {
int u = me.row();
int v = me.column();
double tuv = me.get(); // tuv ~ cik in the original paper
if (tuv <= 0)
continue;
double pred = DenseMatrix.rowMult(P, u, Z, v);
int vminus = inDegrees.get(v); // ~ d-(k)
int uplus = outDegrees.get(u); // ~ d+(i)
double weight = Math.sqrt(vminus / (uplus + vminus + 0.0));
double euv = g(pred) - weight * tuv; // weight * tuv ~ cik*
loss += regC * euv * euv;
for (int f = 0; f < numFactors; f++) {
double puf = P.get(u, f);
double zvf = Z.get(v, f);
PS.add(u, f, regC * gd(pred) * euv * zvf);
ZS.add(v, f, regC * gd(pred) * euv * puf + regZ * zvf);
loss += regZ * zvf * zvf;
}
}
P = P.add(PS.scale(-lRate));
Q = Q.add(QS.scale(-lRate));
Z = Z.add(ZS.scale(-lRate));
errs *= 0.5;
loss *= 0.5;
if (isConverged(iter))
break;
}
} | 8 |
@Override
public void show()
{
stage=new Stage();
Gdx.input.setInputProcessor(stage);
// retrieve the default table actor
table = new Table( getSkin() );
final TextButton saveSpot1;
final TextButton saveSpot2;
final TextButton saveSpot3;
final TextButton saveSpot4;
final TextButton saveSpot5;
TextButton exitButton=new TextButton("Back",getSkin());
if(!datafh1.exists())
saveSpot1= new TextButton("1", getSkin());
else {
data1=Odczyt("data1.txt");
saveSpot1= new TextButton(data1, getSkin());}
if(!datafh2.exists())
saveSpot2= new TextButton("2", getSkin());
else {
data2=Odczyt("data2.txt");
saveSpot2= new TextButton(data2, getSkin());}
if(!datafh3.exists())
saveSpot3= new TextButton("3", getSkin());
else {
data3=Odczyt("data3.txt");
saveSpot3= new TextButton(data3, getSkin());}
if(!datafh4.exists())
saveSpot4= new TextButton("4", getSkin());
else {
data4=Odczyt("data4.txt");
saveSpot4= new TextButton(data4, getSkin());}
if(!datafh5.exists())
saveSpot5= new TextButton("5", getSkin());
else {
data5=Odczyt("data5.txt");
saveSpot5= new TextButton(data5, getSkin());}
Texture backgroundTexture = new Texture(Gdx.files.internal("kulki1.jpg"));
Image backImage = new Image(backgroundTexture);
saveSpot1.addListener( new DefaultActorListener() {
@Override
public void touchUp(
ActorEvent event,
float x,
float y,
int pointer,
int button )
{
super.touchUp( event, x, y, pointer, button );
FileHandle fh=Gdx.files.local("zapis1.txt");
fh.writeString(String.valueOf(pozx)+" "+String.valueOf(pozz)+" "+String.valueOf(index),false);
data1=getDateTime();
saveSpot1.setText(data1);
datafh1.writeString(data1,false);
}
} );
saveSpot2.addListener( new DefaultActorListener() {
@Override
public void touchUp(
ActorEvent event,
float x,
float y,
int pointer,
int button )
{
super.touchUp( event, x, y, pointer, button );
FileHandle fh=Gdx.files.local("zapis2.txt");
fh.writeString(String.valueOf(pozx)+" "+String.valueOf(pozz)+" "+String.valueOf(index),false);
data2=getDateTime();
saveSpot2.setText(data2);
datafh2.writeString(data2,false);
}
} );
saveSpot3.addListener( new DefaultActorListener() {
@Override
public void touchUp(
ActorEvent event,
float x,
float y,
int pointer,
int button )
{
super.touchUp( event, x, y, pointer, button );
FileHandle fh=Gdx.files.local("zapis3.txt");
fh.writeString(String.valueOf(pozx)+" "+String.valueOf(pozz)+" "+String.valueOf(index),false);
data3=getDateTime();
saveSpot3.setText(data3);
datafh3.writeString(data3,false);
}
} );
saveSpot4.addListener( new DefaultActorListener() {
@Override
public void touchUp(
ActorEvent event,
float x,
float y,
int pointer,
int button )
{
super.touchUp( event, x, y, pointer, button );
FileHandle fh=Gdx.files.local("zapis4.txt");
fh.writeString(String.valueOf(pozx)+" "+String.valueOf(pozz)+" "+String.valueOf(index),false);
data4=getDateTime();
saveSpot4.setText(data4);
datafh4.writeString(data4,false);
}
} );
saveSpot5.addListener( new DefaultActorListener() {
@Override
public void touchUp(
ActorEvent event,
float x,
float y,
int pointer,
int button )
{
super.touchUp( event, x, y, pointer, button );
FileHandle fh=Gdx.files.local("zapis5.txt");
fh.writeString(String.valueOf(pozx)+" "+String.valueOf(pozz)+" "+String.valueOf(index),false);
data5=getDateTime();
saveSpot5.setText(data5);
datafh5.writeString(data5,false);
}
} );
exitButton.addListener( new DefaultActorListener() {
@Override
public void touchUp(
ActorEvent event,
float x,
float y,
int pointer,
int button )
{
super.touchUp( event, x, y, pointer, button );
game.setScreen(new MenuScreen(game));
}
} );
System.out.println(pozx);
System.out.println(pozz);
table.setFillParent(true);
table.add( "Save your game" ).colspan( 3 );
table.row();
table.add(saveSpot1).width(200).height(40).padTop(10);
table.row();
table.add(saveSpot2).width(200).height(40).padTop(10);
table.row();
table.add(saveSpot3).width(200).height(40).padTop(10);
table.row();
table.add(saveSpot4).width(200).height(40).padTop(10);
table.row();
table.add(saveSpot5).width(200).height(40).padTop(10);
table.row();
table.add(exitButton).width(200).height(40).padTop(10);
stage.addActor(backImage);
stage.addActor(table);
} | 5 |
public static Cons javaTranslateDefineGlobalVariableUnit(TranslationUnit unit) {
{ GlobalVariable global = ((GlobalVariable)(unit.theObject));
{ Object old$Context$000 = Stella.$CONTEXT$.get();
Object old$Module$000 = Stella.$MODULE$.get();
try {
Native.setSpecial(Stella.$CONTEXT$, global.homeModule());
Native.setSpecial(Stella.$MODULE$, ((Context)(Stella.$CONTEXT$.get())).baseModule);
{ StringWrapper variabletype = (global.variableSpecialP ? StringWrapper.wrapString(Stella.javaYieldSpecialVariableClassName()) : StandardObject.javaTranslateTypeSpec(GlobalVariable.globalVariableTypeSpec(global)));
Cons typelist = Cons.cons(variabletype, Stella.NIL);
Stella_Object initialvaluetree = Stella_Object.javaTranslateATree(unit.codeRegister);
StringWrapper variablename = Symbol.javaTranslateGlobalName(global.variableName, true);
typelist = Cons.cons(StringWrapper.wrapString("static"), typelist);
if (global.variableConstantP ||
global.variableSpecialP) {
typelist = Cons.cons(StringWrapper.wrapString("final"), typelist);
}
if (global.variablePublicP) {
typelist = Cons.cons(StringWrapper.wrapString("public"), typelist);
}
if ((unit.codeRegister == Stella.KWD_UNBOUND_SPECIAL_VARIABLE) ||
global.variableSpecialP) {
return (Cons.list$(Cons.cons(Stella.SYM_STELLA_JAVA_GLOBAL, Cons.cons(StringWrapper.wrapString(global.documentation), Cons.cons(Cons.list$(Cons.cons(Cons.cons(Stella.SYM_STELLA_JAVA_TYPE, typelist.concatenate(Stella.NIL, Stella.NIL)), Cons.cons(variablename, Cons.cons(Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_JAVA_MAKE, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_JAVA_IDENT, Cons.cons(variabletype, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Cons.cons(Stella.SYM_STELLA_JAVA_ACTUALS, Stella.NIL), Cons.cons(Stella.NIL, Stella.NIL))))), Stella.NIL), Stella.NIL)))), Stella.NIL)))));
}
else {
return (Cons.list$(Cons.cons(Stella.SYM_STELLA_JAVA_GLOBAL, Cons.cons(StringWrapper.wrapString(global.documentation), Cons.cons(Cons.list$(Cons.cons(Cons.cons(Stella.SYM_STELLA_JAVA_TYPE, typelist.concatenate(Stella.NIL, Stella.NIL)), Cons.cons(variablename, Cons.cons(Cons.cons(initialvaluetree, Stella.NIL), Stella.NIL)))), Stella.NIL)))));
}
}
} finally {
Stella.$MODULE$.set(old$Module$000);
Stella.$CONTEXT$.set(old$Context$000);
}
}
}
} | 6 |
public final Rectangle getBoundingRectangle() {
double rotmc1x = Math.cos(rotation);
double rotmc1y = Math.sin(rotation);
double rotmc2x = -rotmc1y;
double rotmc2y = rotmc1x;
double hx = width * 0.5;
double hy = height * 0.5;
double leftBound = 0;
double rightBound = 0;
double topBound = 0;
double bottomBound = 0;
for (int xSign = -1; xSign <= 1; xSign += 2) {
for (int ySign = -1; ySign <= 1; ySign += 2) {
double xPos = rotmc1x * hx * xSign + rotmc2x * hy * ySign;
double yPos = rotmc1y * hx * xSign + rotmc2y * hy * ySign;
if (xPos < leftBound) {
leftBound = xPos;
} else if (xPos > rightBound) {
rightBound = xPos;
}
if (yPos < bottomBound) {
bottomBound = yPos;
} else if (yPos > topBound) {
topBound = yPos;
}
}
}
return new Rectangle((int) (x+leftBound), (int) (y+bottomBound),
(int) (rightBound-leftBound), (int) (topBound-bottomBound));
} | 6 |
private static boolean chechAccess(AccessRight accessRight)
{
if(accessRight == AccessRight.MANAGER)
{
System.out.println("YOU ARE MANAGER !");
return true;
}
else if(accessRight == AccessRight.DEPARTMENT)
{
System.out.println("YOU ARE DEPARTMENT !");
return false;
}
return false;
} | 2 |
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent e) {
// Only looking for anvils
if (!(e.getInventory() instanceof AnvilInventory)) {
return;
}
ItemStack item = e.getCurrentItem();
// Only looking for kits
if (!item.hasItemMeta()) {
return;
}
ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName() && meta.hasLore() && meta.getDisplayName().startsWith("Kit ")) {
if (meta.getLore().contains(ChestKitsPlugin.LORE_KEY)) {
e.setCancelled(true);
}
}
} | 6 |
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if(columnIndex == 2) {
if((Boolean)aValue) {
super.setValueAt((!(Boolean)aValue), rowIndex, columnIndex + 1);
}
super.setValueAt(aValue, rowIndex, columnIndex);
} else if(columnIndex == 3) {
if((Boolean)aValue) {
super.setValueAt((!(Boolean)aValue), rowIndex, columnIndex - 1);
}
super.setValueAt(aValue, rowIndex, columnIndex);
} else {
super.setValueAt(aValue, rowIndex, columnIndex);
}
} | 4 |
public Socket connect() throws IOException {
String[] headers = makeHeaders();
s = _getSocket();
try {
oc = s.getOutputStream();
for (String header : headers) {
oc.write(header.getBytes());
oc.write("\r\n".getBytes());
}
oc.flush();
ic = s.getInputStream();
while (true) {
String line = readline(ic);
Matcher m = END_PATTERN.matcher(line);
if (m.matches()) {
return s;
}
m = HEADER_PATTERN.matcher(line);
if (m.matches()) {
responseHeaders.put(m.group(1), m.group(2));
continue;
}
m = HTTP_PATTERN.matcher(line);
if (m.matches()) {
String status_code = m.group(1);
String reason_phrase = m.group(2);
if (!"200".equals(status_code)) {
throw new IOException("HTTP status " + status_code
+ " " + reason_phrase);
}
} else {
throw new IOException("Unknown HTTP line " + line);
}
}
} catch (IOException exn) {
s.close();
throw exn;
} catch (RuntimeException exn) {
s.close();
throw exn;
}
} | 8 |
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
//System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
} | 0 |
public void setExcludeFromExportColumns(final String[] excludeFromExportColumns) {
if (excludeFromExportColumns != null) {
this.excludeFromExportColumns = excludeFromExportColumns.clone();
} else {
this.excludeFromExportColumns = null;
}
} | 1 |
private void heapify(int i){
int vasenLapsi = vasenLapsi(i);
int oikeaLapsi = oikeaLapsi(i);
if (oikeaLapsi < this.koko){
Siirto suurempi = null;
int suurempiInd = 0;
if (keko[oikeaLapsi].suurempiKuin(keko[vasenLapsi])){
suurempi = keko[oikeaLapsi];
suurempiInd = oikeaLapsi;
} else {
suurempi = keko[vasenLapsi];
suurempiInd = vasenLapsi;
}
if (suurempi.suurempiKuin(keko[i])){
keko[suurempiInd] = keko[i];
keko[i] = suurempi;
heapify(suurempiInd);
}
} else if (vasenLapsi == this.koko && keko[vasenLapsi].suurempiKuin(keko[i])){
Siirto temp = keko[vasenLapsi];
keko[vasenLapsi] = keko[i];
keko[i] = temp;
}
} | 5 |
protected long computeSVUID() throws IOException {
ByteArrayOutputStream bos;
DataOutputStream dos = null;
long svuid = 0;
try {
bos = new ByteArrayOutputStream();
dos = new DataOutputStream(bos);
/*
* 1. The class name written using UTF encoding.
*/
dos.writeUTF(name.replace('/', '.'));
/*
* 2. The class modifiers written as a 32-bit integer.
*/
dos.writeInt(access
& (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL
| Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT));
/*
* 3. The name of each interface sorted by name written using UTF
* encoding.
*/
Arrays.sort(interfaces);
for (int i = 0; i < interfaces.length; i++) {
dos.writeUTF(interfaces[i].replace('/', '.'));
}
/*
* 4. For each field of the class sorted by field name (except
* private static and private transient fields):
*
* 1. The name of the field in UTF encoding. 2. The modifiers of the
* field written as a 32-bit integer. 3. The descriptor of the field
* in UTF encoding
*
* Note that field signatures are not dot separated. Method and
* constructor signatures are dot separated. Go figure...
*/
writeItems(svuidFields, dos, false);
/*
* 5. If a class initializer exists, write out the following: 1. The
* name of the method, <clinit>, in UTF encoding. 2. The modifier of
* the method, java.lang.reflect.Modifier.STATIC, written as a
* 32-bit integer. 3. The descriptor of the method, ()V, in UTF
* encoding.
*/
if (hasStaticInitializer) {
dos.writeUTF("<clinit>");
dos.writeInt(Opcodes.ACC_STATIC);
dos.writeUTF("()V");
} // if..
/*
* 6. For each non-private constructor sorted by method name and
* signature: 1. The name of the method, <init>, in UTF encoding. 2.
* The modifiers of the method written as a 32-bit integer. 3. The
* descriptor of the method in UTF encoding.
*/
writeItems(svuidConstructors, dos, true);
/*
* 7. For each non-private method sorted by method name and
* signature: 1. The name of the method in UTF encoding. 2. The
* modifiers of the method written as a 32-bit integer. 3. The
* descriptor of the method in UTF encoding.
*/
writeItems(svuidMethods, dos, true);
dos.flush();
/*
* 8. The SHA-1 algorithm is executed on the stream of bytes
* produced by DataOutputStream and produces five 32-bit values
* sha[0..4].
*/
byte[] hashBytes = computeSHAdigest(bos.toByteArray());
/*
* 9. The hash value is assembled from the first and second 32-bit
* values of the SHA-1 message digest. If the result of the message
* digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of
* five int values named sha, the hash value would be computed as
* follows:
*
* long hash = ((sha[0] >>> 24) & 0xFF) | ((sha[0] >>> 16) & 0xFF)
* << 8 | ((sha[0] >>> 8) & 0xFF) << 16 | ((sha[0] >>> 0) & 0xFF) <<
* 24 | ((sha[1] >>> 24) & 0xFF) << 32 | ((sha[1] >>> 16) & 0xFF) <<
* 40 | ((sha[1] >>> 8) & 0xFF) << 48 | ((sha[1] >>> 0) & 0xFF) <<
* 56;
*/
for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
svuid = (svuid << 8) | (hashBytes[i] & 0xFF);
}
} finally {
// close the stream (if open)
if (dos != null) {
dos.close();
}
}
return svuid;
} | 4 |
protected String getLabel(Node node) {
String prefix = " ";
String suffix = " ";
if (attribute.equalsIgnoreCase(TAXON_NAMES)) {
return prefix+tree.getTaxon(node).getName()+suffix;
}
if( tree instanceof RootedTree ) {
final RootedTree rtree = (RootedTree) tree;
if (attribute.equalsIgnoreCase(NODE_HEIGHTS) ) {
return prefix+getFormattedValue(rtree.getHeight(node))+suffix;
} else if (attribute.equalsIgnoreCase(BRANCH_LENGTHS) ) {
return prefix+getFormattedValue(rtree.getLength(node))+suffix;
}
}
final Object value = node.getAttribute(attribute);
if (value != null) {
if (value instanceof Double) {
return prefix+formatter.getFormattedValue((Double) value)+suffix;
}
if(value instanceof Date){
DateFormat format = new SimpleDateFormat("dd MMM yyyy h:mm a");
return prefix+format.format((Date)value)+suffix;
}
String s = value.toString();
//limit node labels to 15 chars (plus ...)
//if(s.length() > 15)
// return s.substring(0,15)+"...";
return prefix+s+suffix;
}
return null;
} | 7 |
@Override
public void actionPerformed(ActionEvent acc) {
try {
if (OPEN_ACTION.equals(acc.getActionCommand())) {
stateManager.openScene();
Console.println("Open Scene");
} else if (SAVE_ACTION.equals(acc.getActionCommand())) {
stateManager.saveScene(false);
} else if (SAVEAS_ACTION.equals(acc.getActionCommand())) {
stateManager.saveScene(true);
} else if (NEW_ACTION.equals(acc.getActionCommand())) {
stateManager.newScene();
Console.println("New Scene");
} else if (EXIT_ACTION.equals(acc.getActionCommand())) {
EditorPreferencesManager.savePreferences();
System.exit(0);
} else if (PLAY_ACTION.equals(acc.getActionCommand())) {
stateManager.play();
Console.println("Game Started");
} else if (STOP_PLAY_ACTION.equals(acc.getActionCommand())) {
stateManager.stopPlay();
Console.println("Game Stopped");
} else if (LOAD_EXTENSION.equals(acc.getActionCommand())) {
stateManager.loadNewExtension();
}
} catch (final Exception e) {
Console.println(e);
}
} | 9 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.