text stringlengths 14 410k | label int32 0 9 |
|---|---|
private static Def convert(XmlConfig cfg, com.grey.naf.Config nafcfg, Def def, String peername, boolean client)
throws com.grey.base.ConfigException, java.io.IOException
{
if (def == null) def = new Def();
int pos = peername == null ? -1 : peername.indexOf(':');
if (pos != -1) peername = peername.substring(0, pos);
def.isClient = client;
def.localCertAlias = cfg.getValue("@cert", false, null);
def.peerCertName = cfg.getValue("@peercert", false, peername);
def.clientAuth = cfg.getInt("@clientauth", false, def.clientAuth);
def.trustFormat = cfg.getValue("@tstype", false, def.trustFormat);
def.trustPasswd = cfg.getPassword("@tspass", def.trustPasswd);
def.storeFormat = cfg.getValue("@kstype", false, def.storeFormat);
def.storePasswd = cfg.getPassword("@kspass", def.storePasswd);
def.certPasswd = cfg.getPassword("@certpass", def.certPasswd);
def.protocol = cfg.getValue("@proto", false, def.protocol);
def.sessionCache = cfg.getInt("@cache", false, def.sessionCache);
def.sessionTimeout = cfg.getTime("@expiry", def.sessionTimeout);
def.shakeFreq = cfg.getTime("@shake", def.shakeFreq);
def.shakeTimeout = cfg.getTime("@timeout", def.shakeTimeout);
def.latent = cfg.getBool("@latent", def.latent);
def.mdty = (def.latent ? cfg.getBool("@mandatory", def.mdty) : false);
if (nafcfg == null) {
def.trustPath = makeURL(cfg.getValue("@tspath", false, def.trustPath == null ? null : def.trustPath.toString()));
def.storePath = makeURL(cfg.getValue("@kspath", false, def.storePath == null ? null : def.storePath.toString()));
} else {
def.trustPath = nafcfg.getURL(cfg, "@tspath", null, false, def.trustPath == null ? null : def.trustPath.toString(), null);
def.storePath = nafcfg.getURL(cfg, "@kspath", null, false, def.storePath == null ? null : def.storePath.toString(), null);
}
return def;
} | 9 |
private Integer parseInt() throws StreamCorruptedException {
StringBuffer lenStr = new StringBuffer();
while (input.remaining() > 0) {
char ch = input.get();
if (ch == ';') {
//indexPlus(1);
break;
} else {
lenStr.append(ch);
}
}
Integer value = 0;
try {
value = Integer.valueOf(lenStr.toString());
} catch (Throwable e) {
throw new StreamCorruptedException("Integer value" + lenStr + " failed to go to float at" + String.valueOf(input.position()));
}
objHistory.add(value);
return value;
} | 3 |
public void main() {
Stage stage=new Stage();
ToolBar toolBar=new ToolBar();
Button btn1=new Button("Danes");
btn1.setFocusTraversable(false);
Button btn2=new Button("Jutri");
btn2.setFocusTraversable(false);
Button btn3=new Button("Pojutrišnjem");
btn3.setFocusTraversable(false);
Region spacer1=new Region();
spacer1.setPrefWidth(30);
Region spacer2=new Region();
spacer2.setPrefWidth(60);
Region spacer3=new Region();
spacer3.setPrefWidth(30);
Button settings=new Button("Nastavitve");
settings.setFocusTraversable(false);
HBox h1=new HBox(5);
h1.getStyleClass().addAll("segmented-button-bar");
h1.getChildren().addAll(btn1, btn2, btn3);
toolBar.getItems().addAll(spacer1, h1, spacer2, settings);
try {
BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(Main.path+"filter.txt"), "UTF-8"));
String ln; String out="";
while ((ln=in.readLine())!=null) out+=ln;
filter=out;
} catch (Exception e) {}
final TextArea textArea=new TextArea(Functions.text(0, filter));
textArea.setWrapText(true);
textArea.setEditable(false);
textArea.setStyle("-fx-focus-color: transparent;");
textArea.setFocusTraversable(false);
btn1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
textArea.setText(Functions.text(0, filter));
view=0;
}
});
btn2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
textArea.setText(Functions.text(1, filter));
view=1;
}
});
btn3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
textArea.setText(Functions.text(2, filter));
view=2;
}
});
settings.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
final Stage stage1=new Stage();
TextArea about=new TextArea();
about.setWrapText(true);
about.setEditable(false);
about.setStyle("-fx-focus-color: transparent;");
about.setFocusTraversable(false);
about.setText("Avtor: Vid Drobnič, Gimnazija Vič; vse pravice pridržane.\n\nVerzija: " + Main.currentVersion);
about.setMaxHeight(100);
final TextField filter=new TextField("Filter:");
filter.setEditable(false);
filter.setStyle("-fx-focus-color: transparent;");
filter.setFocusTraversable(false);
filter.setMaxSize(55, 50);
final TextField input=new TextField();
input.setEditable(true);
String filterString="";
try {
BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(Main.path+"filter.txt"), "UTF-8"));
String ln; String out="";
while ((ln=in.readLine())!=null) out+=ln;
filterString=out;
} catch (Exception e) {}
input.setText(filterString);
HBox h1=new HBox(10);
h1.getChildren().addAll(filter, input);
Button submit=new Button("Nastavi");
submit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
try {
PrintWriter out=new PrintWriter(Main.path+"filter.txt");
out.print(input.getText());
out.close();
} catch (Exception e) {}
Gui.filter=input.getText().replaceAll(" ", "");
textArea.setText(Functions.text(view, Gui.filter));
stage1.close();
}
});
HBox h2=new HBox();
h2.setAlignment(Pos.CENTER);
h2.getChildren().addAll(submit);
VBox root=new VBox(15);
root.setPadding(new Insets(25, 25, 25, 25));
root.getChildren().addAll(about, h1, h2);
Scene scene=new Scene(root, 500, 250);
stage1.setScene(scene);
stage1.setTitle("Preproste Suplence");
stage1.getIcons().add(new Image(com.DzinVision.preprosteSuplence.main.Main.class.getResourceAsStream("icon.png")));
stage1.show();
}
});
BorderPane root=new BorderPane();
root.setTop(toolBar);
root.setCenter(textArea);
Scene scene=new Scene(root, 600, 800);
stage.setScene(scene);
stage.setTitle("Preproste Suplence");
stage.getIcons().add(new Image(com.DzinVision.preprosteSuplence.main.Main.class.getResourceAsStream("icon.png")));
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent windowEvent) {
System.exit(0);
}
});
stage.showAndWait();
} | 5 |
private void create(int initialValue, Color bg, String fieldTitle, String fieldlabel, boolean showResetBtn) {
setPreferredSize(new Dimension(GUIConstants.DEFAULT_FIELD_WIDTH, FIELDHEIGHT));
setBackground(bg);
setBorder(BorderFactory.createTitledBorder(fieldTitle));
setLayout(new VerticalLayout(5, VerticalLayout.CENTER));
JPanel panel = new JPanel();
panel.setBackground(bg);
this.add(panel);
JLabel label = new JLabel(fieldlabel + ": ");
panel.add(label);
this.numberfield = new JTextField();
this.numberfield.setColumns(this.numberLength);
this.numberfield.setToolTipText(Field.strHeightTooltip);
this.numberfield.setText(initialValue + "");
panel.add(this.numberfield);
this.numberfield.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (controlSizeInput(Numberfield.this.numberfield)
&& controlSizeInputLength(Numberfield.this.numberfield, Numberfield.this.numberLength)) {
Numberfield.this.numberfield.setForeground(Color.BLACK);
onKeyReleased(Numberfield.this.numberfield.getText());
} else {
Numberfield.this.numberfield.setForeground(Color.RED);
onKeyReleased(null);
}
}
});
JPanel panel2 = new JPanel();
panel2.setBackground(bg);
this.add(panel2);
JButton resetBtn = new JButton(Field.strReset);
resetBtn.setEnabled(showResetBtn);
resetBtn.setBackground(bg);
panel2.add(resetBtn);
resetBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
resetOnClick();
}
});
} | 2 |
public static void main(String[] argv) {
if (argv.length < 2) {
System.out
.println("Incorrect parameters.\nUsage: java -cp bin:libs/snakeyaml-1.13.jar lab0.Logger <config_filename> <local_name>");
} else {
Logger logger = new Logger(argv[0], argv[1]);
logger.listen();
logger.showCommandPrompt();
}
} | 1 |
public static void init() {
try {
DIR.mkdirs();
new File(DIR, "saves").mkdir();
File us = new File(DIR, "username");
if (!us.exists() || us.length() == 0) {
USERNAME = JOptionPane.showInputDialog("Bitte gib deinen Benutzernamen an.");
if (USERNAME == null) System.exit(0);
us.createNewFile();
Helper.setFileContent(us, USERNAME);
} else {
USERNAME = Helper.getFileContent(us);
}
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
@Override
public void createFromXML(NodeList attributes) {
for(int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
if(node.getNodeType() == Node.ELEMENT_NODE) {
Node value = node.getFirstChild();
if(node.getNodeName().equalsIgnoreCase("money")) {
money = Integer.parseInt(value.getNodeValue());
}
if(node.getNodeName().equalsIgnoreCase("crap")) {
crap = Integer.parseInt(value.getNodeValue());
}
if(node.getNodeName().equalsIgnoreCase("cum")) {
cum = Integer.parseInt(value.getNodeValue());
}
}
}
} | 5 |
public int[] getCurrentSituation() {
int[] situation = new int[5];
// observe cell to the north
if (current.isAgainstNorthWall()) {
situation[0] = Site.WALL;
}
else {
if (grid[curY - 1][curX].hasCan()) {
situation[0] = Site.CAN;
}
else {
situation[0] = Site.EMPTY;
}
}
// observe cell to the south
if (current.isAgainstSouthWall()) {
situation[1] = Site.WALL;
}
else {
if (grid[curY + 1][curX].hasCan()) {
situation[1] = Site.CAN;
}
else {
situation[2] = Site.EMPTY;
}
}
// observe cell to the east
if (current.isAgainstEastWall()) {
situation[2] = Site.WALL;
}
else {
if (grid[curY][curX + 1].hasCan()) {
situation[2] = Site.CAN;
}
else {
situation[2] = Site.EMPTY;
}
}
// observe cell to the west
if (current.isAgainstWestWall()) {
situation[3] = Site.WALL;
}
else {
if (grid[curY][curX - 1].hasCan()) {
situation[3] = Site.CAN;
}
else {
situation[3] = Site.EMPTY;
}
}
// observe current cell
if (current.hasCan()) {
situation[4] = Site.CAN;
}
else {
situation[4] = Site.EMPTY;
}
return situation;
} | 9 |
private void draw()
{
//De achtergrond tekenen
g.drawImage(bgimage, 0, 0, 0);
//De pijl die positie aangeeft tekenen
g.drawImage(positie, 105, count * 87, 0);
//Als piano open staat tekenen we de pads voor de piano
if(piano.active)
{
for(int i = 0; i < 5; i++)
{
instruments[i].draw();
}
}
//Als gitaar open staat de pads voor gitaar tekenen
if(gitaar.active)
{
for(int i = 5; i < 10; i++)
{
instruments[i].draw();
}
}
//Als overig open staat tekenen we daar de pads voor
if(drums.active)
{
for(int i = 10; i < 15; i++)
{
instruments[i].draw();
}
}
piano.drawButton();
gitaar.drawButton();
drums.drawButton();
play.draw();
//Send all graphics from Buffer to Screen
flushGraphics();
} | 6 |
public static JnlpBrowser create() {
try {
Class<? extends ServiceManager> cl = Class.forName("javax.jnlp.ServiceManager").asSubclass(ServiceManager.class);
Method m = cl.getMethod("lookup", String.class);
BasicService basic = (BasicService)m.invoke(null, "javax.jnlp.BasicService");
return(new JnlpBrowser(basic));
} catch(Exception e) {
return(null);
}
} | 2 |
boolean userWon() {
for (int i = 0; i < 3; i++)
if (getNumEachPiece(board[i], X)[0] == 3)
return true;
for (int j = 0; j < 3; j++)
if (getNumEachPiece(getColumn(j), X)[0] == 3)
return true;
if (getNumEachPiece(getBottomUpDiag(), X)[0] == 3
|| getNumEachPiece(getTopDownDiag(), X)[0] == 3)
return true;
return false;
} | 6 |
public void award_bonus(BigInteger threshold, BigInteger bonus) {
if (getBalance().compareTo(threshold) >= 0)
deposit(bonus);
} | 1 |
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof ConnectionDetails)) {
return false;
}
final ConnectionDetails otherConnectionDetails = (ConnectionDetails)other;
return
hashCode() == otherConnectionDetails.hashCode() &&
getLocalPort() == otherConnectionDetails.getLocalPort() &&
getRemotePort() == otherConnectionDetails.getRemotePort() &&
isSecure() == otherConnectionDetails.isSecure() &&
getLocalHost().equals(otherConnectionDetails.getLocalHost()) &&
getRemoteHost().equals(otherConnectionDetails.getRemoteHost());
} | 7 |
* @param theta the angle with which to calculate R
* @return the radius
*/
private double calculateR(int type, double theta) {
double r = 0;
switch(type){
case 1 :
r = scaleFactor * (Math.cos(3*theta));
break;
case 2 :
r = scaleFactor * (a * theta);
break;
case 3 :
r = scaleFactor * (a * (1+ Math.cos(theta)));
break;
case 4 :
r = scaleFactor * (a * (1+ 2 * Math.cos(theta)));
break;
case 5 :
r = scaleFactor * (Math.pow(Math.cos(3 * theta), -8)); // 8th root
break;
case 6 :
r = scaleFactor * ( 1+2*Math.cos(4 * theta));
break;
case 7 :
r = scaleFactor * ( 1+2*Math.cos(3 * theta));
break;
case 8 :
r = scaleFactor * (
Math.pow(Math.E, Math.cos(theta))
- (2*Math.cos(4*theta))
+ (Math.pow(Math.sin(theta/12), 5)));
break;
case 9 :
r = scaleFactor * (
Math.pow(Math.E, Math.sin(theta))
-(2*Math.cos(4*theta))
+(Math.pow(Math.cos(theta/4), 3)));
break;
}
return r;
} | 9 |
private boolean backupApps() {
new Thread() {
@Override
public void run() {
ProcessBuilder process = null;
Process pr = null;
List<String> args = null;
String line = null;
BufferedReader reader = null;
try {
adbController.rootServer();
adbController.remountDevice(device);
workingLabel.setText(workingLabel2);
File f = new File(backupDir + "/" + backupTitleLabel1.getText() + backupTitleText.getText() + "/data");
f.mkdirs();
process = new ProcessBuilder();
args = new ArrayList<>();
args.add(adbController.getADB().getAbsolutePath());
args.add("-s");
args.add(device.toString());
args.add("pull");
args.add("/data");
process.command(args);
process.directory(f);
process.redirectErrorStream(true);
pr = process.start();
reader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while ((line = reader.readLine()) != null) {
if (debug)
logger.log(Level.DEBUG, "ADB Output: " + line);
if (line.contains("files pulled.")) {
workingLabel.setText(line);
break;
}
}
pr.destroy();
reader.close();
args.clear();
for (int i = 0; i < 2000; i++) {
} // Display result to user before continuing work.
} catch (IOException ex) {
logger.log(Level.ERROR, "An error occurred while backing up applications: " + ex.toString() + "\nThe error stack trace will be printed to the console...");
ex.printStackTrace(System.err);
}
interrupt();
}
}.start();
return true;
} | 5 |
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
} | 8 |
public void visitForceChildren(final TreeVisitor visitor) {
if (visitor.reverse()) {
for (int i = target.length - 1; i >= 0; i--) {
target[i].visit(visitor);
}
for (int i = source.length - 1; i >= 0; i--) {
source[i].visit(visitor);
}
} else {
for (int i = 0; i < source.length; i++) {
source[i].visit(visitor);
}
for (int i = 0; i < target.length; i++) {
target[i].visit(visitor);
}
}
} | 5 |
@Override
public Map<String, Collection<?>> call() throws Exception {
return null;
} | 1 |
public static Consensus reAlign(Alignment layoutMap, double epsilonPrecision, int numOfIterations) {
Consensus consensus = getConsensus(layoutMap);
double initialScore = consensus.getConsensusScore();
boolean shouldContinue = true;
int iteration = 1;
int length = layoutMap.keySet().size();
ArrayList<Integer> keys = new ArrayList<Integer>();
for (Integer i : layoutMap.keySet()) {
keys.add(i);
}
double minimalScore = initialScore;
Consensus bestConsensus = consensus;
while(shouldContinue) {
System.out.println("Iterating...");
for (int k = 0; k < length; k++) {
Read sequence = layoutMap.detachFromAlignmentOnIndex(keys.get(k));
dashFunction(sequence);
dashFunction(consensus);
consensus = getConsensus(layoutMap);
//double deltaConsensusScore =
getAlignment(sequence, consensus, sequence.getLength()* epsilonPrecision);
//score = consensus.consensusScore + deltaConsensusScore + 0.5*getConsensusScoreWithFunction2(sequence, layoutMap);
layoutMap.insertSequenceIntoAlignment(sequence);
consensus = getConsensus(layoutMap);
if (consensus.getConsensusScore() < minimalScore) {
bestConsensus = consensus;
minimalScore = consensus.getConsensusScore();
}
//System.out.println(k);
//System.out.println(bestConsensus.consensusScore);
}
if (bestConsensus.getConsensusScore() >= initialScore || iteration == numOfIterations) {
shouldContinue = false;
}
System.out.println("After "+iteration+" iterations score is: "+ bestConsensus.getConsensusScore() +" previous score : "+initialScore );
initialScore = bestConsensus.getConsensusScore();
iteration++;
}
return bestConsensus;
} | 6 |
public void InitUI()
{
// Initializing button images
try {
Image img = ImageIO.read(getClass().getResource("/karel/guipics/stop.png"));
Stop.setIcon(new ImageIcon(img));
} catch (IOException ex) {}
try {
Image img = ImageIO.read(getClass().getResource("/karel/guipics/pause.png"));
Pause.setIcon(new ImageIcon(img));
} catch (IOException ex) {}
try {
Image img = ImageIO.read(getClass().getResource("/karel/guipics/slower.png"));
Slowdown.setIcon(new ImageIcon(img));
} catch (IOException ex) {}
try {
Image img = ImageIO.read(getClass().getResource("/karel/guipics/faster.png"));
Speedup.setIcon(new ImageIcon(img));
} catch (IOException ex) {}
try {
Image img = ImageIO.read(getClass().getResource("/karel/guipics/go.png"));
jButton4.setIcon(new ImageIcon(img));
} catch (IOException ex) {}
try {
Image img = ImageIO.read(getClass().getResource("/karel/guipics/right.png"));
jButton6.setIcon(new ImageIcon(img));
} catch (IOException ex) {}
try {
Image img = ImageIO.read(getClass().getResource("/karel/guipics/left.png"));
jButton5.setIcon(new ImageIcon(img));
} catch (IOException ex) {}
Pause.setText("Pause");
Pause.setFont(new Font("Arial", Font.PLAIN, 0));
blankPanel.setVisible(true);
lastPane = buttonPanel;
hidePanels(lastPane);
logText.setEditable(false);
// Creating the popout frame with line numbering
programmerFrame = new JInternalFrame("Programmer Mode");
// Building Menu
JMenuBar textbar;
JButton menuSave, menuSaveAs, menuLoad;
JButton menuRun;
textbar = new JMenuBar();
menuRun = new JButton("Run");
menuRun.setFont(new Font("Arial", Font.PLAIN, 10));
menuRun.setMinimumSize(new Dimension(75, 25));
menuRun.setPreferredSize(new Dimension(75, 25));
menuRun.setMaximumSize(new Dimension(75, 25));
textbar.add(menuRun);
menuSaveAs = new JButton("Auto Save");
menuSaveAs.setFont(new Font("Arial", Font.PLAIN, 10));
menuSaveAs.setMinimumSize(new Dimension(90, 25));
menuSaveAs.setPreferredSize(new Dimension(90, 25));
menuSaveAs.setMaximumSize(new Dimension(90, 25));
textbar.add(menuSaveAs);
menuSave = new JButton("Save As");
menuSave.setFont(new Font("Arial", Font.PLAIN, 10));
menuSave.setMinimumSize(new Dimension(75, 25));
menuSave.setPreferredSize(new Dimension(75, 25));
menuSave.setMaximumSize(new Dimension(75, 25));
textbar.add(menuSave);
menuLoad = new JButton("Load");
menuLoad.setFont(new Font("Arial", Font.PLAIN, 10));
menuLoad.setMinimumSize(new Dimension(75, 25));
menuLoad.setPreferredSize(new Dimension(75, 25));
menuLoad.setMaximumSize(new Dimension(75, 25));
textbar.add(menuLoad);
// Creating the JTextArea's
programmerFrame.setJMenuBar(textbar);
// programmerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane textpane = new JScrollPane();
programmerText = new JTextArea();
lines = new JTextArea("1");
// Listening for input and adding lines
programmerText.getDocument().addDocumentListener(new DocumentListener()
{
public String getText()
{
int caretPosition = programmerText.getDocument().getLength();
Element root = programmerText.getDocument().getDefaultRootElement();
String text = "1" + System.getProperty("line.separator");
for(int i = 2; i < root.getElementIndex( caretPosition ) + 2; i++)
{
text += i + System.getProperty("line.separator");
}
return text;
}
@Override
public void changedUpdate(DocumentEvent de) {
lines.setText(getText());
}
@Override
public void insertUpdate(DocumentEvent de) {
lines.setText(getText());
}
@Override
public void removeUpdate(DocumentEvent de) {
lines.setText(getText());
}
});
textpane.getViewport().add(programmerText);
textpane.setRowHeaderView(lines);
textpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
programmerFrame.add(textpane);
programmerFrame.pack();
programmerFrame.setSize(390,540);
programmerFrame.setVisible(false);
blankPanel.add(programmerFrame);
// Setting it to fill all of the space in the pane
try{programmerFrame.setMaximum(true);}
catch(Exception e){};
// Removing the title bar of the programmerframe
((javax.swing.plaf.basic.BasicInternalFrameUI)programmerFrame.getUI())
.setNorthPane(null);
lines.setBackground(Color.LIGHT_GRAY);
lines.setEditable(false);
menuRun.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(java.awt.event.ActionEvent e)
{
programmerRunButton(e);
}
});
menuSave.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(java.awt.event.ActionEvent e)
{
programmerSaveButton(e);
}
});
menuLoad.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(java.awt.event.ActionEvent e)
{
programmerLoadButton(e);
}
});
menuSaveAs.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(java.awt.event.ActionEvent e)
{
programmerAutosaveButton(e);
}
});
} | 9 |
@Override
public IReceiveQuery getReceiveQuery() {
return receiveQuery;
} | 0 |
public Object getValueAt(int row, int col) {
if (col == 0) {
return data.getBusinessObjects().get(row).getNr();
} else if (col == 1) {
return data.getBusinessObjects().get(row).getMensuality();
} else if (col == 2) {
return data.getBusinessObjects().get(row).getIntrest();
} else if (col == 3) {
return data.getBusinessObjects().get(row).getCapital();
} else if (col == 4) {
return data.getBusinessObjects().get(row).getRestCapital();
} else return null;
} | 5 |
public static List<ExInterval> unionExIntervals(List<ExInterval> I) {
// Empty input.
List<ExInterval> uni = new ArrayList<>();
if (I.isEmpty()) {
return uni;
}
// Sorts ExIntervals according to their left endpoints.
Collections.sort(I);
ExInterval curr = new ExInterval();
curr = I.get(0);
for (int i = 1; i < I.size(); ++i) {
if (I.get(i).left.val < curr.right.val
|| (I.get(i).left.val == curr.right.val
&& (I.get(i).left.isClose || curr.right.isClose))) {
if (I.get(i).right.val > curr.right.val
|| (I.get(i).right.val == curr.right.val
&& I.get(i).right.isClose)) {
curr.right = I.get(i).right;
}
} else {
uni.add(curr);
curr = I.get(i);
}
}
uni.add(curr);
return uni;
} | 9 |
public void solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if (n < 9) {
System.out.println(0);
System.exit(0);
}
if (n == 9) {
System.out.println(8);
System.exit(0);
}
System.out.print("72");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n - 10; i++) {
sb.append("0");
}
System.out.println(sb);
} | 3 |
public String blockTypeToString(){
String s = "unrecognized";
switch( getBlockType() ){
case BLOCK_TYPE_UNKNOWN: s = "unknown"; break;
case BLOCK_TYPE_CATALOG: s = "DB catalog"; break;
case BLOCK_TYPE_BPT_HEADER: s = "B+Tree header"; break;
case BLOCK_TYPE_BPT_INTERNAL: s = "B+Tree internal"; break;
case BLOCK_TYPE_BPT_LEAF: s = "B+Tree leaf"; break;
}
return s;
} | 5 |
private void shuffleParticles(double[][]particles) {
for(int i = 0; i < numberOfParticles; i++){
for(int k = 0; k < particles[i].length; k++){
int index = i + (int)(Math.random() * ((particles.length - i) + 1));
double temp = particles[i][k];
particles[i][k] = particles[i][index];
particles[i][index] = temp;
}
}
} | 2 |
public AST rFactor() throws SyntaxError {
AST t;
if (isNextTok(Tokens.LeftParen)) { // -> (e)
scan();
t = rExpr();
expect(Tokens.RightParen);
return t;
}
if (isNextTok(Tokens.INTeger)) { // -> <int>
t = new IntTree(currentToken);
scan();
return t;
}
if (isNextTok(Tokens.Float)) { // -> <float>
t = new FloatTree(currentToken);
scan();
return t;
}
t = rName();
if (!isNextTok(Tokens.LeftParen)) { // -> name
return t;
}
scan(); // -> name '(' (e list ',')? ) ==> call
t = (new CallTree()).addKid(t);
if (!isNextTok(Tokens.RightParen)) {
do {
t.addKid(rExpr());
if (isNextTok(Tokens.Comma)) {
scan();
} else {
break;
}
} while (true);
}
expect(Tokens.RightParen);
return t;
} | 7 |
public static void frequencyCount(String s) {
char c[] = s.toCharArray();
int count;
for (int i = 0; i < c.length; i++) {
count = 0;
for (int j = 0; j < c.length; j++) {
if ((j < i) && (c[j] == c[i])) {
break;
}
else if ((j >= i) && (c[i] == c[j])) {
count++;
}
}
if (count != 0) {
System.out.println(c[i] + "\t:\t" + count);
}
}
} | 7 |
public static void main(String[] args){
Chap15Q6<String> rs = new Chap15Q6();
for(String s : "go to the hell".split(" ")){
rs.add(s);
}
for(int i = 0; i < 10; i++)
print(rs.select());
Chap15Q6<Integer> intrs = new Chap15Q6();
int[] nums = {1,2,3,4,5,6};
for(Integer i : nums){
intrs.add(i);
}
for(int i = 0; i < 10; i++)
print(intrs.select());
} | 4 |
public synchronized void replaceContactInBucket(Bucket bucket, Contact node)
{
if (node.isAlive())
{
Contact leastRecentlySeen = bucket.getLeastRecentlySeenBucketContact();
//The LRS node can be replaced if it is not the local node, AND it is DEAD
if (!isLocalNode(leastRecentlySeen) && (leastRecentlySeen.isDead()))
{
//replace the node in the bucket
bucket.removeBucketContact(leastRecentlySeen.getNodeId());//remove the LRS node from the bucket
bucket.addBucketContact(node);//add the new node to the bucket
touchBucket(bucket);
return;
}
}
addContactToBucketCache(bucket, node);
try
{
controlNode.ping(bucket.getLeastRecentlySeenBucketContact());
}
catch(IOException ioe)
{
//log
System.err.println("Error in ping");
}
} | 4 |
private void createStructure() {
Random random = new Random((int)Math.random()*100);
data = new DataArrays<Float[]>();
for(int i=0; i<kitSize; i++){
array = new Float[length];
for (int j=0; j<array.length; j++){
array[j] = random.nextFloat()*chars;
}
data.addToKit(array);
}
} | 2 |
public boolean load(String mainClass, String mainMethod, String version, BufferedImage icon)
{
try
{
_loader = new URLClassLoader(new URL[]{_path.toURI().toURL()}, Launcher.class.getClassLoader());
Class<?> cl = _loader.loadClass(mainClass);
cl.getMethod(mainMethod, new Class<?>[]{BufferedImage.class, String.class, String.class}).invoke(null, new Object[] {icon, version, Util.getApplicationPath()});
_loaded = true;
return true;
}
catch(Exception e)
{
_exception = e;
_loaded = false;
return false;
}
} | 3 |
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} | 7 |
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("eweather")) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("update")) {
return updateWeather(sender);
}
else if (args[0].equalsIgnoreCase("info")) {
return info(sender, args);
}
else if (args[0].equalsIgnoreCase("set")) {
return setWeather(sender, args);
}
else if (args[0].equalsIgnoreCase("reset")) {
return resetWeather(sender, args);
}
else if (args[0].equalsIgnoreCase("reload")) {
return reloadConfiguration(sender);
}
}
else {
return printUsage(sender);
}
}
return false;
} | 7 |
public static Locale parseLocale(String localeString) {
StringTokenizer localeParser = new StringTokenizer(localeString, "-_");
String lang = null, country = null, variant = null;
if (localeParser.hasMoreTokens())
lang = localeParser.nextToken();
if (localeParser.hasMoreTokens())
country = localeParser.nextToken();
if (localeParser.hasMoreTokens())
variant = localeParser.nextToken();
if (lang != null && country != null && variant != null)
return new Locale(lang, country, variant);
else if (lang != null && country != null)
return new Locale(lang, country);
else if (lang != null)
return new Locale(lang);
else
return new Locale("");
} | 9 |
public boolean isPrime(long l) {
// extend our list of primes if necessary in order to search for l
while (maxPrimeFound < l) {
this.getNext();
}
// now binary search for l
int lo = 1;
int hi = numPrimesFound;
while (true) {
int mid = (lo+hi) / 2;
long midPrime = primesFound.get(mid);
if (midPrime == l) {
return true;
} else if (Math.abs(hi-lo) <= 1) {
// bottom out case
// actually all base cases at once, so we don't have to be precise about even/odd 1-or-2
if ((primesFound.get(lo) == l) || (primesFound.get(hi) == l)) {
return true;
} else {
return false;
}
} else if (midPrime < l) {
lo = mid;
} else {
hi = mid;
}
}
} | 7 |
public void save() {
if (datacfg != null) {
for (String key : datacfg.getKeys(false)) {
datacfg.set(key, null);
}
}
for (SellSign sign : mh.getSellSigns()) {
Block b = sign.getBlock();
String key = "SellSigns." + b.getWorld().getName() + "." + sign.getRegion().getId();
datacfg.set(key + ".Type", sign.getType());
datacfg.set(key + ".Account", sign.getOwner());
datacfg.set(key + ".Price", sign.getPrice());
datacfg.set(key + ".GP", sign.getGp().getID());
datacfg.set(key + ".X", b.getX());
datacfg.set(key + ".Y", b.getY());
datacfg.set(key + ".Z", b.getZ());
}
for (RentSign sign : mh.getRentSigns()) {
Block b = sign.getBlock();
String key = "RentSigns." + b.getWorld().getName() + "." + sign.getRegion().getId();
datacfg.set(key + ".Type", sign.getType());
datacfg.set(key + ".Account", sign.getOwner());
datacfg.set(key + ".Price", sign.getPrice());
datacfg.set(key + ".Renter", sign.getRenter());
datacfg.set(key + ".GP", sign.getGp().getID());
datacfg.set(key + ".Intervall", sign.getIntervall());
datacfg.set(key + ".Paytime", date.format(sign.getPaytime()));
datacfg.set(key + ".X", b.getX());
datacfg.set(key + ".Y", b.getY());
datacfg.set(key + ".Z", b.getZ());
}
for (Globalprice gp : mh.getGlobalPrices()) {
datacfg.set("GlobalPrices." + gp.getID(), gp.getPrice());
}
try {
datacfg.save(dataFile);
} catch (IOException e) {
};
} | 6 |
public static ItemStack convertToCraftItemStack(ItemStack itemStack) {
if (AS_CRAFT_OPY_ACCESSOR == null) {
ClassTemplate template = new Reflection().reflect(MinecraftReflection.getCraftItemStackClass());
List<SafeMethod<ItemStack>> methods = template.getSafeMethods(withExactName("asCraftCopy"), withArguments(ItemStack.class));
if (methods.size() > 0) {
AS_CRAFT_OPY_ACCESSOR = methods.get(0).getAccessor();
} else {
throw new RuntimeException("Failed to get the asCraftCopy method!");
}
}
return AS_CRAFT_OPY_ACCESSOR.invokeStatic(itemStack);
} | 2 |
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket(host,port);
// 请求连接为低成本连接
socket.setTrafficClass(0x02);
// 请求高性能与最小延时
socket.setTrafficClass(0x04|0x10);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(socket!=null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 4 |
private void treeRefresh(File[] masterFiles) {
TreeItem[] items = tree.getItems();
int masterIndex = 0;
int itemIndex = 0;
for (int i = 0; i < items.length; ++i) {
final TreeItem item = items[i];
final File itemFile = (File) item.getData(TREEITEMDATA_FILE);
if ((itemFile == null) || (masterIndex == masterFiles.length)) {
// remove bad item or placeholder
item.dispose();
continue;
}
final File masterFile = masterFiles[masterIndex];
int compare = compareFiles(masterFile, itemFile);
if (compare == 0) {
// same file, update it
treeRefreshItem(item, false);
++itemIndex;
++masterIndex;
} else if (compare < 0) {
// should appear before file, insert it
TreeItem newItem = new TreeItem(tree, SWT.NONE, itemIndex);
treeInitVolume(newItem, masterFile);
new TreeItem(newItem, SWT.NONE); // placeholder child item to get "expand" button
++itemIndex;
++masterIndex;
--i;
} else {
// should appear after file, delete stale item
item.dispose();
}
}
for (;masterIndex < masterFiles.length; ++masterIndex) {
final File masterFile = masterFiles[masterIndex];
TreeItem newItem = new TreeItem(tree, SWT.NONE);
treeInitVolume(newItem, masterFile);
new TreeItem(newItem, SWT.NONE); // placeholder child item to get "expand" button
}
} | 6 |
@Override
public void enter() {
Group root = GroupBuilder.create().build();
String[] menuButtonLabels = { "Singleplayer", "Multiplayer", "Credits", "Quit" };
final StateType[] menuButtonEvents = { StateType.SINGLE_PLAYER_SELECTED, StateType.TWO_PLAYER_SELECTED, StateType.CREDITS_SELECTED,
StateType.QUIT_SELECTED };
for (int i = 0; i < menuButtonLabels.length; ++i) {
final int crap_i = i;
final Text text = TextBuilder.create()
.text(menuButtonLabels[i])
.font(Font.font("Arial", 40))
.build();
text.snapshot(null, null);
text.setX((stage.getWidth() - text.getLayoutBounds().getWidth()) / 2);
text.setY((stage.getHeight() - text.getLayoutBounds().getHeight()) / 2 + 70 * (i - (menuButtonLabels.length - 1) / 2));
text.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
EventSystem.getInstance().queueEvent(new StateUpdateEvent(menuButtonEvents[crap_i]));
}
});
text.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
FillTransition ft = new FillTransition(Duration.millis(200), text);
ft.setToValue(Color.WHITE);
ft.play();
ScaleTransition st = new ScaleTransition(Duration.millis(200), text);
st.setToX(1.3d);
st.setToY(1.15d);
st.play();
}
});
text.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
FillTransition ft = new FillTransition(Duration.millis(200), text);
ft.setToValue(Color.BLACK);
ft.play();
ScaleTransition st = new ScaleTransition(Duration.millis(200), text);
st.setToX(1f);
st.setToY(1f);
st.play();
}
});
root.getChildren().add(text);
}
FadeTransition ft = new FadeTransition(Duration.millis(1500), root);
ft.setFromValue(0f);
ft.setToValue(1f);
ft.play();
Scene scene = stage.getScene();
scene.setRoot(root);
stage.setScene(scene);
stage.show();
// EventSystem.getInstance().queueEvent(new
// StateUpdateEvent(StateType.TWO_PLAYER_SELECTED));
} | 1 |
public static boolean isTable(String OID) {
switch(OID) {
case "1.3.6.1.2.1.1.9":
return true;
case "1.3.6.1.2.1.2.2":
return true;
case "1.3.6.1.2.1.3.1":
return true;
case "1.3.6.1.2.1.4.20":
return true;
case "1.3.6.1.2.1.4.21":
return true;
case "1.3.6.1.2.1.4.22":
return true;
case "1.3.6.1.2.1.6.13":
return true;
case "1.3.6.1.2.1.7.5":
return true;
default:
return false;
}
} | 8 |
public Bid_DTO getBid(long bidId) throws NoHayDatosDBException {
Bid_DTO bidResultado;
bidResultado = null;
String CONSULTA = "SELECT * FROM actionBazaar.Bid WHERE idBid = ?";
try{
PreparedStatement pstmt = conexion.prepareStatement( CONSULTA );
pstmt.setLong( 1 , bidId );
ResultSet rs = pstmt.executeQuery();
if (rs.next() ){
bidResultado = new Bid_DTO( rs.getDouble("importe"), rs.getInt("idItem") , rs.getInt("idUser") );
} else {
throw new NoHayDatosDBException( "No fueron encontrados datos para el bid: " + bidId );
}
}catch (SQLException e){
e.printStackTrace();
}
return bidResultado;
} | 2 |
private void comboCidadeAssessoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboCidadeAssessoriaActionPerformed
String item = String.valueOf(comboModelCidadeAssesoria.getSelectedItem());
if(item.equals("Selecionar....") || item == "null"){
System.out.println("Olá");
if(listaCheia == true){
comboModelBairroAssesoria.removeAllElements();
comboModelBairroAssesoria.addElement("Selecionar....");
}
comboBairroAssessoria.setSelectedIndex(0);
}else{
System.out.println("Carregando bairros!");
String idc = String.valueOf(comboCidadeAssessoria.getSelectedIndex());
carregaBairrosAssesoria(idc);
listaCheia = true;
}
}//GEN-LAST:event_comboCidadeAssessoriaActionPerformed | 3 |
public static int getLongestShipNotDestroyed()
{
ArrayList<Integer> shipSizesLeft = new ArrayList<Integer>();
for(int size : BattleShipGame.shipSizes)
shipSizesLeft.add(new Integer(size));
for(Ship ship : sunkShips)
shipSizesLeft.remove(new Integer(ship.getSize()));
int largest = 1;
for(Integer in : shipSizesLeft)
if(in.intValue() > largest)
largest = in.intValue();
return largest;
} | 4 |
@Before
public void setUp() throws Exception
{
} | 0 |
public void onAction(String name, boolean isPressed, float tpf) {
if (inputEnabled) {
if (name.equals("up") && isPressed) {
up = true;
}
if (name.equals("down") && isPressed) {
down = true;
}
if (name.equals("right") && isPressed) {
right = true;
}
if (name.equals("left") && isPressed) {
left = true;
}
}
} | 9 |
public KeyStroke getKey() {
return KeyStroke.getKeyStroke('d');
} | 0 |
public TableCellRenderer getCellRenderer(int row, int column) {
if (!finalEdit)
return super.getCellRenderer(row, column);
int mc = convertColumnIndexToModel(column);
return cellEditors[row][mc] == null ? super
.getCellRenderer(row, column) : RENDERER;
} | 2 |
public void remoteSignal(String from,String method,String url) {
if (url.indexOf("/smithers/downcheck")!=-1) {
for(Iterator<SmithersProperties> iter = smithers.values().iterator(); iter.hasNext(); ) {
SmithersProperties sm = (SmithersProperties)iter.next();
if (!sm.isAlive()) {
LOG.info("One or more smithers down, try to recover it");
LazyHomer.send("INFO","/domain/internal/service/getname");
}
}
} else {
// only one trigger is set for now so we know its for nodes :)
if (ins.checkKnown()) {
// we are verified (has a name other than unknown)
MaggieProperties mp = maggies.get(myip);
if (mp!=null && mp.getStatus().equals("on")) {
if (!running) {
LOG.info("This bart will be started");
running = true;
}
setLogLevel(mp.getDefaultLogLevel());
} else {
if (running) {
LOG.info("This bart will be turned off");
running = false;
} else {
LOG.info("This bart is not turned on, use smithers todo this for ip "+myip);
}
}
}
}
} | 8 |
public SHSMsgBean() {
} | 0 |
@Override
public String toString() {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("########################################\n");
sBuilder.append("# BeatTime plugin collection preferences\n");
sBuilder.append("# Only change these settings via this \n");
sBuilder.append("# file when the server is off or the \n");
sBuilder.append("# plugin was disabled! \n");
sBuilder.append("########################################\n\n");
sBuilder.append(".settings {\n");
for (String key : preferences.keySet())
sBuilder.append(String.format("\tpref::[name={0}, value={1}]\n", key, preferences.get(key)));
sBuilder.append("};\n");
return sBuilder.toString();
} | 1 |
private int is(int x, int y) {
if (x < 0 || x > cwidth - 1 || y < 0 || y > cheight - 1) {
return 1;
}
return (cells[y][x] == true ? 1 : 0);
} | 5 |
public void load(Thinlet thinlet, Object table) {
UIDefaults defaults = UIManager.getDefaults();
Hashtable iconcache = new Hashtable();
for (Enumeration keys = defaults.keys(); keys.hasMoreElements();) {
String key = (String) keys.nextElement();
Object value = defaults.get(key);
Object row = Thinlet.create("row");
Object keycell = Thinlet.create("cell");
thinlet.setString(keycell, "text", key);
thinlet.add(row, keycell);
Object valuecell = Thinlet.create("cell");
if (value instanceof Color) {
Color color = (Color) value;
Image icon = (Image) iconcache.get(color);
if (icon == null) {
icon = createIcon(thinlet, color);
iconcache.put(color, icon);
}
thinlet.setIcon(valuecell, "icon", icon);
thinlet.setString(valuecell, "text", "0x" +
Integer.toHexString(0xff000000 | color.getRGB()).substring(2));
}
else if (value instanceof Font) {
Font font = (Font) value;
StringBuffer fonttext = new StringBuffer(font.getName());
if (font.isBold()) { fonttext.append(" bold"); }
if (font.isItalic()) { fonttext.append(" italic"); }
fonttext.append(' '); fonttext.append(font.getSize());
thinlet.setString(valuecell, "text", fonttext.toString());
}
else {
thinlet.setString(valuecell, "text", value.toString());
}
thinlet.add(row, valuecell);
thinlet.add(table, row);
}
} | 6 |
public static boolean isInRange( String rng, int rowFirst, int rowLast, int colFirst, int colLast )
{
int[] sh = getRowColFromString( rng );
// the guantlet
if( sh[1] < colFirst )
{
return false;
}
if( sh[1] > colLast )
{
return false;
}
if( sh[0] < rowFirst )
{
return false;
}
if( sh[0] > rowLast )
{
return false;
}
return true; // passes!
} | 4 |
@Override
public void vieraile(TormaysReunaanViesti viesti) {
// toisin kuin pallo jonka paikka palaa keskelle jos törmää ylä\alareunaan, tämä törmääjä voi törmätä
// esimerkiksi aivan vasemman reunan yläosan tuntumassa vasempaan reunaan ja välittömästi törmätä yläreunaan
// jos suunta ei huomioida, entiteetti lentää ruudulta ulos tai jää jumiin.
if (tormaysLaskuri > 0 && viesti.getReuna() == viimeisinTormattyReuna) {
return;
}
viimeisinTormattyReuna = viesti.getReuna();
switch (viimeisinTormattyReuna) {
case YLA:
case ALA:
viestit.lisaaViesti(new MuutaNopeusViesti(1, -1.0));
break;
case VASEN:
case OIKEA:
viestit.lisaaViesti(new MuutaNopeusViesti(-1.0, 1));
}
tormaysLaskuri = TORMAYS_HUOMIOIMATTA_JATTAMIS_AIKA;
} | 6 |
@Basic
@Column(name = "last_name")
public String getLastName() {
return lastName;
} | 0 |
public void setType(String type)
{
if (type.equals("eau") || type.equals("feu") || type.equals("terre") || type.equals("air"))
{
typeSorcier_ = type;
if (type.equals("air"))
puissanceType = 1;
if (type.equals("eau"))
puissanceType = 2;
if (type.equals("feu"))
puissanceType = 3;
if (type.equals("terre"))
puissanceType = 4;
}
} | 8 |
public String readUrl(String urlString) {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 4 |
private void readHand(GameState state) {
int cardsInHand = countCardsInHand(state.getScreen());
if(cardsInHand > handCostIndiciesByHandSize.size()) {
throw new GameStateViolationException("Too many cards in hand, the parser is probably reading pixels it shouldn't");
}
List<Integer> cardCostOffsets = handCostIndiciesByHandSize.get(cardsInHand);
List<Scroll> newHand = new ArrayList<Scroll>(cardsInHand);
for(int i = 0; i < cardsInHand; i++) {
int xOffset = cardCostOffsets.get(i);
BufferedImage subImage = state.getScreen().getSubimage(xOffset, handRow, 11, 16);
ImageUtil.saveImage(subImage, "C:\\debug\\handCost" + i + ".png"); //debug
PixelMap costPixelMap = new PixelMap(subImage, 1);
ImageUtil.saveImage(costPixelMap.asImage(), "C:\\debug\\handCostPixelMap" + i + ".png"); //debug
double maxSimilarity = 0;
int closestMatch = 0;
int currentNumber = 1;
for(PixelMap numberMap : numberMaps) {
if(numberMap == null) {
continue;
}
ImageUtil.saveImage(costPixelMap.and(numberMap).asImage(), "C:\\debug\\andMap_" + currentNumber + ".png");
double similarity = costPixelMap.and(numberMap).getRelativeDensity(numberMap);
if(similarity > maxSimilarity) {
maxSimilarity = similarity;
closestMatch = currentNumber;
}
currentNumber++;
}
newHand.add(new UnitScroll(closestMatch, closestMatch, 2, closestMatch));
}
state.setHand(newHand);
} | 5 |
public void heapify(ArrayList<Integer> array, int index,int size) {
int left = this.getLeft(index);
int right = this.getRight(index);
int largest = array.get(index);
int temp = index;
if (left != -1 && array.get(left) > largest && left<size) {
largest = array.get(left);
temp = left;
}
if (right != -1 && array.get(right) > largest && right <size) {
largest = array.get(right);
temp = right;
}
if (temp != index) {
int tempo = array.get(index);
array.add(index, array.get(temp));
array.remove(index+1);
array.add(temp, tempo);
array.remove(temp+1);
if(temp < size / 2){
heapify(array,temp,size);
}
}
} | 8 |
public static Filter isInterface()
{
return new IsInterface();
} | 0 |
public int getAttendance(){
if(attendees != null){
int attendance = attendees.size();
return attendance;
} else{
System.out.println("There are not attendees listed for this meeting!");
}
return 0;
} | 1 |
public String toString() {
return getDescription();
} | 0 |
public void itemStateChanged(ItemEvent evt) {
//LookAndFeel laf = UIManager.getLookAndFeel();
JRadioButton source = (JRadioButton) evt.getSource();
if (source == radioLaFGTK)
try {
//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
SwingUtilities.updateComponentTreeUI(panel1);
} catch (Exception e) {
lblMessage.setText("Error setting GTK+ LAF: " + e);
}
else if (source == radioLaFMetal)
try {
// cross-platform Java L&F (also called "Metal")
//UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(panel1);
} catch (Exception e) {
lblMessage.setText("Error setting CrossPlatform LAF: " + e);
}
else if (source == radioLaFCDEMotif)
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
SwingUtilities.updateComponentTreeUI(panel1);
} catch (Exception e) {
lblMessage.setText("Error setting Motif LAF: " + e);
}
else if (source == radioLaFNimbus)
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(panel1);
} catch (Exception e) {
lblMessage.setText("Error setting Nimbus LAF: " + e);
}
lblMessage.setText(String.format("Look and Feel: %s", UIManager.getLookAndFeel().getName()));
} | 8 |
protected double[] missingValueStrategyAggregateNodes(double[] instance,
Attribute classAtt) throws Exception {
if (classAtt.isNumeric()) {
throw new Exception("[TreeNode] missing value strategy aggregate nodes, "
+ "but class is numeric!");
}
double[] preds = null;
TreeNode trueNode = null;
boolean strategyInvoked = false;
int nodeCount = 0;
// look at the evaluation of the child predicates
for (TreeNode c : m_childNodes) {
if (c.getPredicate().evaluate(instance) == Predicate.Eval.TRUE) {
// note the first child to evaluate to true
if (trueNode == null) {
trueNode = c;
}
nodeCount++;
} else if (c.getPredicate().evaluate(instance) == Predicate.Eval.UNKNOWN) {
strategyInvoked = true;
nodeCount++;
}
}
if (strategyInvoked) {
double[] aggregatedCounts =
freqCountsForAggNodesStrategy(instance, classAtt);
// normalize
Utils.normalize(aggregatedCounts);
preds = aggregatedCounts;
} else {
if (trueNode != null) {
preds = trueNode.score(instance, classAtt);
} else {
doNoTrueChild(classAtt, preds);
}
}
return preds;
} | 7 |
public static void copyBlob(String srcContainerName, String policyId,
String destContainerName, String blobName, int server) {
CloudBlobClient cloudBlobClients = null;
CloudBlobClient cloudBlobClientd = null;
try {
storageAccountSource = new CloudStorageAccount(
new StorageCredentialsAccountAndKey(
"portalvhdsh8ghz0s9b7mx9",
"ThVIUXcwpsYqcx08mtIhRf6+XxvEuimK35/M65X+XlkdVCQNl4ViUiB/+tz/nq+eeZAEZCNrmFVQwwN3QiykvA=="),
true);
storageAccountDest = new CloudStorageAccount(
new StorageCredentialsAccountAndKey(
"portalvhds1fyd5w3n1hnd6",
"DPBb+Y6B2kJEG/yN3Sm3PUDdljXY7BYyIkmZD/NUZU0l3LnDu7qXMjnRRJJgQWAeZTFCUi/xJtiCTIPYKnvI+A=="),
true);
cloudBlobClients = storageAccountSource.createCloudBlobClient();
cloudBlobClientd = storageAccountDest.createCloudBlobClient();
} catch (URISyntaxException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
CloudBlobContainer srcContainer = null;
CloudBlobContainer destContainer = null;
try {
destContainer = cloudBlobClientd
.getContainerReference(destContainerName);
srcContainer = cloudBlobClients
.getContainerReference(srcContainerName);
openContainer(destContainer);
openContainer(srcContainer);
} catch (URISyntaxException | StorageException e1) {
e1.printStackTrace();
}
String blobToken = null;
CloudBlob destBlob = null;
CloudBlob sourceBlob = null;
// get the SAS token to use for all blobs
try {
sourceBlob = srcContainer.getBlockBlobReference(blobName);
destBlob = destContainer.getBlockBlobReference(blobName);
System.out.println(destBlob + " " + destBlob.getName());
if (!destBlob.exists()) {
System.out.println("Blob does not exist");
}
//System.out.println(sourceBlob.acquireLease(40, "ok", null, null, null));
destBlob.startCopyFromBlob(sourceBlob);
System.out.println(destBlob.getCopyState().getStatusDescription());
closeContainer(srcContainer);
closeContainer(destContainer);
} catch (StorageException | URISyntaxException e) {
//e.printStackTrace();
System.out.println(e.getLocalizedMessage());
}
} | 4 |
public void delTriangles( ArrayList<Triangle> triangles ) throws Exception
{
glBindBuffer( GL_ARRAY_BUFFER, resource.getVboIndex() );
for ( Triangle triangle : triangles )
delTriangle( triangle, false );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
} | 1 |
public boolean tntcontrolSubCommand(CommandSender sender, String[] args) {
boolean cmdProcessed = false;
String subCommand = args[1].toLowerCase();
if (subCommand.equalsIgnoreCase("limit")) {
limitOption(sender, args);
cmdProcessed = true;
}
if (subCommand.equalsIgnoreCase("yield")) {
yieldOption(sender, args);
cmdProcessed = true;
}
if (subCommand.equalsIgnoreCase("radius")) {
radiusOption(sender, args);
cmdProcessed = true;
}
if (subCommand.equalsIgnoreCase("fire")) {
fireOption(sender, args);
cmdProcessed = true;
}
if (subCommand.equalsIgnoreCase("tool")) {
toolOption(sender, args);
cmdProcessed = true;
}
if (subCommand.equalsIgnoreCase("redstone")) {
redstoneOption(sender, args);
cmdProcessed = true;
}
if (subCommand.equalsIgnoreCase("reclaim")) {
reclaimOption(sender, args);
cmdProcessed = true;
}
if (subCommand.equalsIgnoreCase("reload")) {
reloadOption(sender, args);
cmdProcessed = true;
}
return cmdProcessed;
} | 8 |
public Map<String, Set<String>> identifyInterface(Set<String> interfaceNames, Set<String> classNames) throws ClassNotFoundException {
this.interfaceFilter = (null == interfaceFilter) ? new HashSet<String>() : interfaceFilter;
this.packageFilter = new HashSet<String>();
this.jarFilter = new HashSet<String>();
Map<String, Set<String>> classTable = new HashMap<String, Set<String>>();
for (String className : classNames) {
Set<String> interfaces = verifyClass(convertClassName(className));
for (String interfaceName : interfaceNames) {
if (interfaces.contains(interfaceName)) {
Set<String> classList = classTable.get(interfaceName);
if (null == classList) {
classList = new HashSet<String>();
classTable.put(interfaceName, classList);
}
if (!classList.contains(className)) classList.add(className);
}
}
}
return classTable;
} | 6 |
public void setTransient() {
if(level > 20) {
level = 20;
}
} | 1 |
public double deltaT(double JD) {
double T = (JD - J2000) / JCY;
double[][] data = { { -25.0, 184.4, 111.6, 31.0, 0.0 },
{ -17.0, -31527.7, -4773.29, -212.0889, -3.93731 },
{ -10.0, 6833.0, 1996.25, 186.1189, 3.87068 },
{ -3.5, -116.0, -88.45, -22.3509, -3.07831 },
{ -3.0, -4586.4, -4715.24, -1615.08, -184.71 },
{ -2.0, -427.3, -556.12, -228.71, -30.67 },
{ -1.5, 150.7, 310.8, 204.8, 41.6 },
{ -1.0, -150.5, -291.7, -196.9, -47.7 },
{ -0.7, 486.0, 1896.4, 2606.9, 1204.6 },
{ +0.2, 65.9, 96.0, 35.0, -20.2 },
{ +2.0, 63.4, 111.6, 31.0, 0.0 } };
for (int j = 0; j < data.length; j++) {
if (T < data[j][0])
return (data[j][1] + T
* (data[j][2] + T * (data[j][3] + T * data[j][4]))) / 86400.0;
}
return 0.0;
} | 2 |
public PreparedHTTPResponse create( HTTPHeaders headers,
PostDataWrapper postData,
UUID socketID,
Socket socket,
UUID sessionID,
Map<String,BasicType> additionals
) {
this.getHTTPHandler().getLogger().log( Level.INFO,
getClass().getName(),
"socketID=" + socketID + ", sessionID=" + sessionID + ", additionalSettings=" + additionals
);
BasicType statusCode = additionals.get( "statusCode" );
BasicType reasonPhrase = additionals.get( "reasonPhrase" );
BasicType errorMessage = additionals.get( "errorMessage" );
try {
if( statusCode == null || reasonPhrase == null || errorMessage == null ) {
this.getHTTPHandler().getLogger().log( Level.WARNING,
getClass().getName(),
"Cannot build error reply. The passed additionals miss some essential params (statusCode="+statusCode+", reasonPhrase="+reasonPhrase+", errorMessage="+errorMessage+"). Senging INTERNAL_SERVER_ERROR. additionals=" + additionals.toString()
);
return buildPreparedErrorResponse( headers,
socketID,
socket,
sessionID, // userID,
Constants.HTTP_STATUS_SERVERERROR_INTERNAL_SERVER_ERROR,
"Internal Server Error",
"The system encountered a fatal error. Your request could not be processed.",
additionals
);
} else {
return buildPreparedErrorResponse( headers,
socketID,
socket,
sessionID, // userID,
statusCode.getInt(),
reasonPhrase.getString(),
errorMessage.getString(),
additionals
);
}
} catch( BasicTypeException e ) {
this.getHTTPHandler().getLogger().log( Level.WARNING,
getClass().getName(),
"Cannot build error reply. The passed additionals miss some essential params (statusCode="+statusCode+", reasonPhrase="+reasonPhrase+", errorMessage="+errorMessage+"). Senging INTERNAL_SERVER_ERROR."
);
return buildPreparedErrorResponse( headers,
socketID,
socket,
sessionID, // userID,
Constants.HTTP_STATUS_SERVERERROR_INTERNAL_SERVER_ERROR,
"Internal Server Error",
"The system encountered a fatal error. Your request could not be processed.",
additionals
);
}
} | 4 |
public void createTree(int n, int k){
if(Integer.bitCount(k) != 1)
{
System.err.println("number of parts must be a power of 2");
System.exit(-1);
}
// get the maximum number of links that can be stored
boolean failed = true;
double maxLinks = 0d;
while(failed)
{
maxLinks = 0d;
failed = false;
for(socketHandler h : socketHandlers)
{
if(h.maxSize < 0)
{
failed = true;
}
maxLinks += h.maxSize;
}
}
System.out.println("Maximum number of links I can store: " + maxLinks);
int nodesPerPart = (int) Math.floor((double)n/(double)(k));
int l = 0;
int u = l + (int)Math.floor((((double)socketHandlers[0].maxSize)/maxLinks) * (double)n);
int[][] b = new int[k][2];
for(int i=0;i<k-1;i++)
{
b[i][0] = l;
b[i][1] = u;
l = u + 1;
u = l + (int)Math.floor((((double)socketHandlers[i+1].maxSize)/maxLinks) * (double)n);
}
u = n;
b[k-1][0] = l;
b[k-1][1] = u;
// creates the tree recursively with T being the centre part
T = getPartLinkSet(b,k/2,k/4);
System.exit(2);
} | 5 |
private void loadCounts() {
String anstallda = "";
String kompetenser = "";
String projekts = "";
String plattformar = "";
try {
String query = "select count(*) from anstalld";
anstallda = DB.fetchSingle(query);
} catch (InfException e) {
e.getMessage();
}
try {
String query = "select count(*) from kompetensdoman";
kompetenser = DB.fetchSingle(query);
} catch (InfException e) {
e.getMessage();
}
try {
String query = "select count(*) from spelprojekt";
projekts = DB.fetchSingle(query);
} catch (InfException e) {
e.getMessage();
}
try {
String query = "select count(*) from plattform";
plattformar = DB.fetchSingle(query);
} catch (InfException e) {
e.getMessage();
}
lblAnstCount.setText("Antal anställda: " + anstallda);
lblKompCount.setText("Antal kompetensdomäner: " + kompetenser);
lblPlatCount.setText("Antal plattformar: " + plattformar);
lblSpCount.setText("Antal spelprojekt: " + projekts);
} | 4 |
private void calcShadowDrop() {
if (pane != null) {
maxFall.setLocation(location);
maxFall.translate(0, 1);
point.setLocation(location);
do {
if (!assertLegal(pane, block, point, block, null)) { break; }
else { point.translate(0, -1); maxFall.translate(0, -1); }
} while (true);
}
} | 3 |
static String bitSetToString( ArrayList<Version> sigla,
ArrayList<Group> groups, BitSet bs )
{
try
{
StringBuilder sb = new StringBuilder();
for ( int i = bs.nextSetBit(0); i>= 0; i = bs.nextSetBit(i+1))
{
Version v = sigla.get(i-1);
String siglum = v.shortName;
if ( isLayerName(siglum) )
{
Group g = groups.get(v.group-1);
siglum = g.name+"/"+v.shortName;
}
if ( sb.length()>0 )
sb.append( " " );
sb.append( siglum );
}
return sb.toString();
}
catch ( Exception e )
{
System.out.println("error");
return "";
}
} | 4 |
private void getFloorPlan(String inputFile) {
String line = null;
BufferedReader br = null;
File f = new File(inputFile);
try {
br = new BufferedReader(new FileReader(f));
} catch (Exception e) {
LOGGER.log(Level.WARNING, "File not Found", e);
}
for (;;) {
try {
line = br.readLine();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Cannot Read File", e);
}
if (line == null) {
break;
}
if (line.contains("cell")) {
/*make new cell*/
CellDescription cellDescription = new CellDescription();
cellDescription.sI.atChargingStation = true;
getFloorPlanGetXY(line, cellDescription);
getFloorPlanGetFloor(line, cellDescription);
getFloorPlanGetDirt(line, cellDescription);
getFloorPlanWS(line, cellDescription);
getFloorPlanChargingStation(line, cellDescription);
/*save it*/
floorPlan.add(cellDescription);
}
}
try {
br.close();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Cannot close file", e);
}
} | 6 |
@Override
public String toString() {
return null;
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JsonString other = (JsonString) obj;
if (other.hasComments() ^ hasComments())
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
if (hasComments() && !getComments().equals(other.getComments()))
return false;
return true;
} | 9 |
public Matrix times(Matrix B) {
Matrix A = this;
if (A.N != B.M) throw new RuntimeException("Illegal matrix dimensions.");
Matrix C = new Matrix(A.M, B.N);
for (int i = 0; i < C.M; i++)
for (int j = 0; j < C.N; j++)
for (int k = 0; k < A.N; k++)
C.data[i][j] += (A.data[i][k] * B.data[k][j]);
return C;
} | 4 |
@Override
public String getColumnName(int column) {
String name = "?";
switch (column) {
case 0:
name = "Name";
break;
case 1:
name = "Date";
break;
case 2:
name = "Type";
break;
}
return name;
} | 3 |
@Override
public Serializable load(){
try {
db.start();
DBCollection collection = db.getDB().getCollection("games");
XStream xStream = new XStream();
DBObject obj = collection.findOne();
if (obj == null)
return null;
String xml = (String)obj.get("blob");
Serializable xmlObj = (Serializable) xStream.fromXML(xml);
db.stop(true);
return xmlObj;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
} | 2 |
@Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println("In Maritime Trade handler");
String responseMessage = "";
if(exchange.getRequestMethod().toLowerCase().equals("post")) {
try {
String unvalidatedCookie = exchange.getRequestHeaders().get("Cookie").get(0);
CookieParams cookie = Cookie.verifyCookie(unvalidatedCookie, translator);
BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
String inputLine;
StringBuffer requestJson = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
requestJson.append(inputLine);
}
in.close();
System.out.println(requestJson);
//
MaritimeTradeRequest request = (MaritimeTradeRequest) translator.translateFrom(requestJson.toString(), MaritimeTradeRequest.class);
exchange.getRequestBody().close();
ServerModel serverModel = this.movesFacade.maritimeTrade(request, cookie);
System.out.println("Request Accepted!");
// create cookie for user
List<String> cookies = new ArrayList<String>();
// send success response headers
exchange.getResponseHeaders().put("Set-cookie", cookies);
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
movesLog.store(new MaritimeTradeCommand(movesFacade, request, cookie));
responseMessage = translator.translateTo(serverModel);
} catch (InvalidCookieException | InvalidMovesRequest e) { // else send error message
System.out.println("unrecognized / invalid maritime trade request");
responseMessage = e.getMessage();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
}
}
else {
// unsupported request method
responseMessage = "Error: \"" + exchange.getRequestMethod() + "\" is no supported!";
exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
}
//set "Content-Type: text/plain" header
List<String> contentTypes = new ArrayList<String>();
String type = "text/plain";
contentTypes.add(type);
exchange.getResponseHeaders().put("Content-type", contentTypes);
if (!responseMessage.isEmpty()) {
//send failure response message
OutputStreamWriter writer = new OutputStreamWriter(
exchange.getResponseBody());
writer.write(responseMessage);
writer.flush();
writer.close();
}
exchange.getResponseBody().close();
} | 4 |
public void execute(HyperGraph graph) throws MaintenanceException
{
HGIndexer indexer = graph.get(hindexer);
if (indexer == null)
return;
HGIndex<?,?> idx = graph.getIndexManager().getIndex(indexer);
if (idx == null)
throw new MaintenanceException(false,"Indexer " + indexer + " with handle " + hindexer +
" present in graph, but no actual index has been created.");
for (HGHandle currentType : hg.typePlus(indexer.getType()).getSubTypes(graph))
{
if (typesAdded.contains(currentType)) // are we resuming from a previous interruption?
{
// if the type has been completed processed, skip it
if (!typesAdded.get(typesAdded.size()-1).equals(currentType))
continue;
// otherwise, we are resuming the processing of 'currentType' and
// the lastProcessed variable should contain the handle of the last
// atom of that type that was added to the index
}
else
{
typesAdded.add(currentType);
lastProcessed = null;
}
indexAtomsTypedWith(graph, idx, indexer, currentType);
}
} | 7 |
public void visitEnd() {
if (argumentStack % 2 != 0) {
declaration.append('>');
}
argumentStack /= 2;
endType();
} | 1 |
public void cycle() {
// Do instruction limiting so we don't run at light speed
if(!limiter())
return;
// If we've hit the instruction limit, reset count so that
// the timers can be updated
if(instruction_count == 5)
instruction_count = 0;
System.out.println(String.format("\n\nPC@%x: %x; I: %x", PC, memory[PC], I));
/*
Java has no unsigned support and the conversion from
bytes to shorts can get messed up so we're going to
step around the issue here.
*/
int msb, lsb, total;
msb = (((int)memory[PC]) & 0xFF);
lsb = (((int)memory[PC + 1]) & 0xFF);
// Get opcode
//Opcode = (short)((memory[PC] << 8) | memory[PC + 1]);
total = ((msb << 8) | lsb);
Opcode = (short)total;
System.out.println("\tOp: " + String.format("%x", Opcode));
// Main execution switch
Execute(Opcode);
// Update timers
// These only fire when instruction count is zero as this
// allows us to limit the Hz that the interpreter runs at
if(instruction_count == 0) {
if(delay_timer > 0)
{
delay_timer--;
}
if(sound_timer > 0)
{
sound_timer--;
if(sound_timer > 0)
{
System.out.println("SoundT: " + sound_timer);
sound.setPlaying(true);
}
else
{
if(sound.isPlaying())
sound.setPlaying(false);
}
}
}
// Update instruction count
instruction_count++;
} | 7 |
private boolean r_Step_4() {
int among_var;
int v_1;
// (, line 140
// [, line 141
ket = cursor;
// substring, line 141
among_var = find_among_b(a_7, 18);
if (among_var == 0)
{
return false;
}
// ], line 141
bra = cursor;
// call R2, line 141
if (!r_R2())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 144
// delete, line 144
slice_del();
break;
case 2:
// (, line 145
// or, line 145
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 145
if (!(eq_s_b(1, "s")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 145
if (!(eq_s_b(1, "t")))
{
return false;
}
} while (false);
// delete, line 145
slice_del();
break;
}
return true;
} | 9 |
private static void getAvailableFlights()
{
//for each flight
for(Flight flight:flightList)
{
if(flight.hasOpenSeats())
{
//we already know that the flight is not empty
//print out Flight#, Date, and seats remaining
display.printFlightInfo(flight);
}
}
} | 2 |
public Model(int playerCount) {
listener = new ArrayList<IModelChangeListener>();
field = new Field(FIELD_WIDTH, FIELD_HEIGHT);
player = new Player[playerCount];
activeItems = new ArrayList<Item>();
newActiveItems = new ArrayList<Item>();
for (int i = 0; i < playerCount; i++) {
player[i] = new Player(1, 13, 10, 2);
field.addItem(player[i]);
}
for (int i = 0; i < FIELD_HEIGHT; i++) {
field.addItem(new BlockWall(0, i));
field.addItem(new BlockWall(FIELD_WIDTH - 1, i));
}
for (int i = 0; i < FIELD_WIDTH; i++) {
field.addItem(new BlockWall(i, 0));
field.addItem(new BlockWall(i, FIELD_HEIGHT - 1));
}
int min = FIELD_HEIGHT < FIELD_WIDTH ? FIELD_HEIGHT : FIELD_WIDTH;
for (int i = 1; i < min - 1; i++) {
field.addItem(new BlockDestroyable(i, i));
}
notifyListener();
} | 5 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Physical target=mob.location();
if(target==null)
return false;
if(target.fetchEffect(ID())!=null)
{
mob.tell(L("This place is already a sanctum."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 to make this place a sanctum.^?",prayForWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
setMiscText(mob.Name());
if((target instanceof Room)
&&(CMLib.law().doesOwnThisProperty(mob,((Room)target))))
{
final String landOwnerName=CMLib.law().getPropertyOwnerName((Room)target);
if(CMLib.clans().getClan(landOwnerName)!=null)
{
setMiscText(landOwnerName);
beneficialAffect(mob,target,asLevel,0);
}
else
{
target.addNonUninvokableEffect((Ability)this.copyOf());
CMLib.database().DBUpdateRoom((Room)target);
}
}
else
beneficialAffect(mob,target,asLevel,0);
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 to make this place a sanctum, but <S-IS-ARE> not answered.",prayForWord(mob)));
return success;
} | 9 |
*/
public static long
PointToAngle
( int x,
int y )
{
// MAES: note how we don't use &BITS32 here. That is because we know that the maximum possible
// value of tantoangle is angle
// This way, we are actually working with vectors emanating from our current position.
x-= viewx;
y-= viewy;
if ( (x==0) && (y==0) )
return 0;
if (x>= 0)
{
// x >=0
if (y>= 0)
{
// y>= 0
if (x>y)
{
// octant 0
return tantoangle[ SlopeDiv(y,x)];
}
else
{
// octant 1
return (ANG90-1-tantoangle[ SlopeDiv(x,y)]);
}
}
else
{
// y<0
y = -y;
if (x>y)
{
// octant 8
return -tantoangle[SlopeDiv(y,x)];
}
else
{
// octant 7
return ANG270+tantoangle[ SlopeDiv(x,y)];
}
}
}
else
{
// x<0
x = -x;
if (y>= 0)
{
// y>= 0
if (x>y)
{
// octant 3
return (ANG180-1-tantoangle[ SlopeDiv(y,x)]);
}
else
{
// octant 2
return (ANG90+ tantoangle[ SlopeDiv(x,y)]);
}
}
else
{
// y<0
y = -y;
if (x>y)
{
// octant 4
return (ANG180+tantoangle[ SlopeDiv(y,x)]);
}
else
{
// octant 5
return (ANG270-1-tantoangle[ SlopeDiv(x,y)]);
}
}
}
// This is actually unreachable.
// return 0;
} | 9 |
public static void startupWalk() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$);
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupWalk.helpStartupWalk1();
_StartupWalk.helpStartupWalk2();
_StartupWalk.helpStartupWalk3();
_StartupWalk.helpStartupWalk4();
}
if (Stella.currentStartupTimePhaseP(4)) {
_StartupWalk.helpStartupWalk5();
}
if (Stella.currentStartupTimePhaseP(5)) {
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("TRANSLATION-UNIT", "(DEFCLASS TRANSLATION-UNIT (STANDARD-OBJECT) :PUBLIC? TRUE :PUBLIC-SLOTS ((TU-HOME-MODULE :TYPE MODULE :OPTION-KEYWORD :TU-HOME-MODULE) (THE-OBJECT :TYPE OBJECT) (CATEGORY :TYPE SYMBOL) (ANNOTATION :TYPE STRING) (AUXILIARY? :TYPE BOOLEAN) (CODE-REGISTER :TYPE OBJECT) (TRANSLATION :TYPE OBJECT) (REFERENCED-GLOBALS :TYPE (LIST OF GLOBAL-VARIABLE) :ALLOCATION :EMBEDDED :COMPONENT? TRUE)) :PUBLIC-METHODS ((HOME-MODULE ((SELF TRANSLATION-UNIT)) :TYPE MODULE (RETURN (TU-HOME-MODULE SELF)))) :PRINT-FORM (PRINT-TRANSLATION-UNIT SELF STREAM))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.stella.TranslationUnit", "newTranslationUnit", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.stella.TranslationUnit", "accessTranslationUnitSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.TranslationUnit"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupWalk.helpStartupWalk6();
_StartupWalk.helpStartupWalk7();
_StartupWalk.helpStartupWalk8();
_StartupWalk.helpStartupWalk9();
_StartupWalk.helpStartupWalk10();
_StartupWalk.helpStartupWalk11();
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/STELLA")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *AVAILABLE-STELLA-FEATURES* (LIST OF KEYWORD) (LIST :WARN-ABOUT-UNDEFINED-METHODS :WARN-ABOUT-MISSING-METHODS :SUPPRESS-WARNINGS :USE-HARDCODED-SYMBOLS :USE-COMMON-LISP-STRUCTS :USE-COMMON-LISP-CONSES :USE-CPP-GARBAGE-COLLECTOR :MINIMIZE-JAVA-PREFIXES :TRANSLATE-WITH-COPYRIGHT-HEADER) :DOCUMENTATION \"List of available STELLA features.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CURRENT-STELLA-FEATURES* (LIST OF KEYWORD) (LIST) :DOCUMENTATION \"List of currently enabled STELLA features.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DEFAULT-STELLA-FEATURES* (LIST OF KEYWORD) (LIST :WARN-ABOUT-UNDEFINED-METHODS :WARN-ABOUT-MISSING-METHODS :USE-CPP-GARBAGE-COLLECTOR :USE-COMMON-LISP-CONSES :MINIMIZE-JAVA-PREFIXES) :DOCUMENTATION \"List of STELLA features enabled by default and after resetting them\nwith `reset-stella-features'.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *TRACED-KEYWORDS* (LIST OF KEYWORD) NULL :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *SAFETY* INTEGER 3 :DOCUMENTATION \"Integer between 0 and 3. Higher levels call more\nsafety checks.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *DEBUGLEVEL* INTEGER 3 :DOCUMENTATION \"Integer between 0 and 3. Higher levels generate more\ncode to aid debugging.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *OPTIMIZESPEEDLEVEL* INTEGER 3 :DOCUMENTATION \"Integer between 0 and 3. Higher levels optimize for\ngreater execution speed.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *OPTIMIZESPACELEVEL* INTEGER 3 :DOCUMENTATION \"Integer between 0 and 3. Higher levels optimize for\nless code size and memory consumption.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TRANSLATIONUNITS* (LIST OF TRANSLATION-UNIT) NULL :PUBLIC? TRUE :DOCUMENTATION \"List of objects representing partially walked\ntop-level definitions and auxiliary code.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CURRENTTRANSLATIONUNIT* TRANSLATION-UNIT NULL :PUBLIC? TRUE :DOCUMENTATION \"The translation unit currently operated on.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TRANSLATIONPHASE* KEYWORD NULL :PUBLIC? TRUE :DOCUMENTATION \"Indicates the current translation phase which is one of\n:DEFINE, :FINALIZE, :WALK, or :TRANSLATE.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TRANSLATIONVERBOSITYLEVEL* INTEGER 1 :PUBLIC? TRUE :DOCUMENTATION \"The higher the level, the more progress annotations are\ngenerated during the translation of Stella declarations.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *USEHARDCODEDSYMBOLS?* BOOLEAN FALSE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TRANSLATOROUTPUTLANGUAGE* KEYWORD (RUNNING-IN-LANGUAGE) :DOCUMENTATION \"Specifies the current translator output language; either\n:common-lisp, :idl, :java, :cpp, or :cpp-standalone. The initial value\npoints to the native implementation language of this STELLA instance.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *LOCALVARIABLETYPETABLE* (KEY-VALUE-LIST OF SYMBOL STANDARD-OBJECT) NULL :DOCUMENTATION \"Table mapping local variable names their declared types\n(declared explicitly or implicitly).\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *METHODBEINGWALKED* METHOD-SLOT NULL :DOCUMENTATION \"Contains the method or function being walked, or else `null'.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *FOUNDRETURN?* BOOLEAN FALSE :DOCUMENTATION \"Indicates that one or more return statements have been found\nduring the walk of the current method.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TARGETTYPE* TYPE-SPEC @VOID :DOCUMENTATION \"Bound to the target type for an expression currently walked.\nUsed instead of an extra argument to `walk-a-tree', since only a few types\nof expressions need to know about their expected type (e.g., FUNCALL).\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *LOCALGENSYMTABLE* KEY-VALUE-LIST NULL :DOCUMENTATION \"Table that maps each prefix of a function-local gensym\nto its own gensym counter and/or to related gensyms.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TRANSLATIONERRORS* INTEGER 0 :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TRANSLATIONWARNINGS* INTEGER 0 :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TRANSLATIONNOTES* INTEGER 0 :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *FUNCTION-CALL-LOG-STREAM* OUTPUT-STREAM NULL :DOCUMENTATION \"The current log file to which function calls should be logged.\nA non-NULL value indicates that function call logging is enabled.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LOG-FUNCTION-CALLS?* BOOLEAN FALSE :DOCUMENTATION \"Translation switch which indicates that methods should\nbe instrumented to log their calls to a file.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LOG-BREAK-POINT-COUNTER* INTEGER NULL)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *WRAPPED-TYPE-TABLE* (CONS OF CONS) (BQUOTE ((@INTEGER-WRAPPER @INTEGER) (@LONG-INTEGER-WRAPPER @LONG-INTEGER) (@FLOAT-WRAPPER @FLOAT) (@NUMBER-WRAPPER @NUMBER) (@STRING-WRAPPER @STRING) (@MUTABLE-STRING-WRAPPER @MUTABLE-STRING) (@CHARACTER-WRAPPER @CHARACTER) (@BOOLEAN-WRAPPER @BOOLEAN) (@FUNCTION-CODE-WRAPPER @FUNCTION-CODE) (@METHOD-CODE-WRAPPER @METHOD-CODE))) :DOCUMENTATION \"Table of pairs used by `wrapper-value-type' and\n`type-to-wrapped-type'.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *COERSION-TABLE* (CONS OF CONS) (BQUOTE ((@BOOLEAN @BOOLEAN-WRAPPER INLINE-WRAP-BOOLEAN) (@INTEGER @INTEGER-WRAPPER WRAP-LITERAL) (@LONG-INTEGER @LONG-INTEGER-WRAPPER WRAP-LITERAL) (@INTEGER @BOOLEAN-WRAPPER INTEGER-TO-BOOLEAN-WRAPPER) (@INTEGER @BOOLEAN INTEGER-TO-BOOLEAN) (@FLOAT @FLOAT-WRAPPER WRAP-LITERAL) (@MUTABLE-STRING @STRING MUTABLE-STRING-TO-STRING) (@MUTABLE-STRING @MUTABLE-STRING-WRAPPER WRAP-LITERAL) (@STRING @STRING-WRAPPER WRAP-LITERAL) (@STRING @MUTABLE-STRING STRING-TO-MUTABLE-STRING) (@STRING @SYMBOL INTERN-SYMBOL) (@CHARACTER @CHARACTER-WRAPPER WRAP-LITERAL) (@CHARACTER @STRING CHARACTER-TO-STRING) (@FUNCTION-CODE @FUNCTION-CODE-WRAPPER WRAP-LITERAL) (@METHOD-CODE @METHOD-CODE-WRAPPER WRAP-LITERAL) (@SYMBOL @STRING SYMBOL-NAME) (@BOOLEAN-WRAPPER @BOOLEAN INLINE-UNWRAP-BOOLEAN) (@INTEGER-WRAPPER @INTEGER WRAPPER-VALUE) (@INTEGER-WRAPPER @LONG-INTEGER WRAPPER-VALUE) (@LONG-INTEGER-WRAPPER @LONG-INTEGER WRAPPER-VALUE) (@FLOAT-WRAPPER @FLOAT WRAPPER-VALUE) (@NUMBER-WRAPPER @FLOAT NUMBER-WRAPPER-TO-FLOAT) (@STRING-WRAPPER @STRING WRAPPER-VALUE) (@MUTABLE-STRING-WRAPPER @MUTABLE-STRING WRAPPER-VALUE) (@CHARACTER-WRAPPER @CHARACTER WRAPPER-VALUE) (@FUNCTION-CODE-WRAPPER @FUNCTION-CODE WRAPPER-VALUE) (@METHOD-CODE-WRAPPER @METHOD-CODE WRAPPER-VALUE) (@SURROGATE @CLASS SURROGATE-VALUE) (@SURROGATE @MODULE SURROGATE-VALUE) (@INPUT-STREAM @NATIVE-INPUT-STREAM NATIVE-STREAM) (@OUTPUT-STREAM @NATIVE-OUTPUT-STREAM NATIVE-STREAM) (@NUMBER @INTEGER (CAST <X> @INTEGER)) (@NUMBER @LONG-INTEGER (CAST <X> @LONG-INTEGER)) (@NUMBER @FLOAT (CAST <X> @FLOAT)) (@INTEGER @FLOAT (CAST <X> @FLOAT)) (@INTEGER @SINGLE-FLOAT (CAST <X> @SINGLE-FLOAT)) (@LONG-INTEGER @FLOAT (CAST <X> @FLOAT)) (@LONG-INTEGER @SINGLE-FLOAT (CAST <X> @SINGLE-FLOAT)) (@FLOAT @SINGLE-FLOAT IDENTITY) (@FLOAT @DOUBLE-FLOAT IDENTITY) (@INTEGER @SHORT-INTEGER IDENTITY) (@INTEGER @LONG-INTEGER IDENTITY) (@INTEGER @UNSIGNED-SHORT-INTEGER IDENTITY) (@INTEGER @UNSIGNED-LONG-INTEGER IDENTITY))) :DOCUMENTATION \"Table of triples used by `lookup-coersion-method' to\nlocate a coersion method.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SYMBOL-REGISTRY* (HASH-TABLE OF GENERALIZED-SYMBOL GENERALIZED-SYMBOL) (NEW (HASH-TABLE OF GENERALIZED-SYMBOL GENERALIZED-SYMBOL)) :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SYMBOL-SET* (LIST OF GENERALIZED-SYMBOL) (NEW (LIST OF GENERALIZED-SYMBOL)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CURRENTFILE* STRING NULL :PUBLIC? TRUE :DOCUMENTATION \"Name of file that is currently being translated.\nA NULL value indicates an incremental translation.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *SPECIALVARIABLESTACK* (KEY-VALUE-LIST OF SYMBOL SYMBOL) (NEW (KEY-VALUE-LIST OF SYMBOL SYMBOL)) :DOCUMENTATION \"Stack mirroring the current state of bound specials\nwith their associated old-value variables.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *SPECIALSENABLED?* BOOLEAN TRUE :DOCUMENTATION \"`true' if using specials is enabled and legal.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *NOFSPECIALSATLOOPENTRY* INTEGER 0 :DOCUMENTATION \"Number of specials bound at the most recent entry\nto a LOOP/WHILE/FOREACH construct.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *TYPE-PREDICATE-TABLE* (CONS OF CONS) (BQUOTE ((@BOOLEAN BOOLEAN? SUBTYPE-OF-BOOLEAN?) (@INTEGER INTEGER? SUBTYPE-OF-INTEGER?) (@LONG-INTEGER LONG-INTEGER? SUBTYPE-OF-LONG-INTEGER?) (@FLOAT FLOAT? SUBTYPE-OF-FLOAT?) (@STRING STRING? SUBTYPE-OF-STRING?) (@CHARACTER CHARACTER? SUBTYPE-OF-CHARACTER?) (@WRAPPER WRAPPER? SUBTYPE-OF-WRAPPER?) (@BOOLEAN-WRAPPER BOOLEAN? SUBTYPE-OF-BOOLEAN?) (@INTEGER-WRAPPER INTEGER? SUBTYPE-OF-INTEGER?) (@LONG-INTEGER-WRAPPER LONG-INTEGER? SUBTYPE-OF-LONG-INTEGER?) (@FLOAT-WRAPPER FLOAT? SUBTYPE-OF-FLOAT?) (@STRING-WRAPPER STRING? SUBTYPE-OF-STRING?) (@CHARACTER-WRAPPER CHARACTER? SUBTYPE-OF-CHARACTER?) (@VERBATIM-STRING-WRAPPER VERBATIM-STRING? SUBTYPE-OF-VERBATIM-STRING?) (@SURROGATE SURROGATE? SUBTYPE-OF-SURROGATE?) (@TYPE TYPE? SUBTYPE-OF-TYPE?) (@SYMBOL SYMBOL? SUBTYPE-OF-SYMBOL?) (@TRANSIENT-SYMBOL TRANSIENT-SYMBOL? SUBTYPE-OF-TRANSIENT-SYMBOL?) (@KEYWORD KEYWORD? SUBTYPE-OF-KEYWORD?) (@CONS CONS? SUBTYPE-OF-CONS?) (@CLASS STELLA-CLASS? SUBTYPE-OF-CLASS?) (@STORAGE-SLOT STORAGE-SLOT? SUBTYPE-OF-STORAGE-SLOT?) (@METHOD-SLOT METHOD-SLOT? SUBTYPE-OF-METHOD-SLOT?) (@ANCHORED-TYPE-SPECIFIER ANCHORED-TYPE-SPECIFIER? SUBTYPE-OF-ANCHORED-TYPE-SPECIFIER?) (@PARAMETRIC-TYPE-SPECIFIER PARAMETRIC-TYPE-SPECIFIER? SUBTYPE-OF-PARAMETRIC-TYPE-SPECIFIER?))) :DOCUMENTATION \"Table of specialized type predicates for various types.\nThese predicates have to be used instead of `isa?', since they also work\nduring bootstrap when only some class objects are defined.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *NUMERIC-TYPE-HIERARCHY* (LIST OF TYPE) (LIST @INTEGER @LONG-INTEGER @FLOAT @NUMBER))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *INLININGMETHODCALL?* BOOLEAN FALSE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MIXIN-IMPLEMENTATION-STYLE* KEYWORD :SECOND-CLASS :DOCUMENTATION \"A keyword describing how mixin classes are handled in\nsingle-inheritance target languages. The legal values are\n:FIRST-CLASS-WITH-METHOD, which means that variables of a mixin type\nare legal and that slot access on a mixin type is facilitated by\ninherited-down accessor methods and a catch-all method on OBJECT,\n:FIRST-CLASS-WITH-TYPECASE which is similar but replaces the catch-all\nmethod with a function using a TYPECASE, and :SECOND-CLASS, which\nmeans that variables of a mixin type are illegal and no additional\naccessors and catch-all methods are needed.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MAX-NUMBER-OF-STARTUP-UNITS* INTEGER 60 :DOCUMENTATION \"The maximum number of startup units that can be combined\ninto a single startup function (this avoids the construction of huge startup\nfunctions that would cause too much stress for some wimpy compilers).\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *NATIVE-NAME-TABLE* (HASH-TABLE OF SYMBOL (KEY-VALUE-LIST OF KEYWORD LIST)) (NEW HASH-TABLE))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *EVALUATIONTREE* OBJECT NULL :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *EVALUATIONPARENTTREE* OBJECT NULL :PUBLIC? TRUE)");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} | 7 |
@Test
public void testInfixToPostfix15() throws DAIllegalArgumentException,
DAIndexOutOfBoundsException, ShouldNotBeHereException,
BadNextValueException, UnmatchingParenthesisException {
try {
infix.addLast("+");
infix.addLast("-23");
QueueInterface<String> postFix = calc.infixToPostfix(infix);
String result = "24+-23+";
String inCalc = calc.stringTrans(postFix);
System.out.println(inCalc);
assertEquals(result, inCalc);
} catch (DAIllegalArgumentException e) {
throw new DAIllegalArgumentException();
} catch (DAIndexOutOfBoundsException e) {
throw new DAIndexOutOfBoundsException();
} catch (ShouldNotBeHereException e) {
throw new ShouldNotBeHereException();
} catch (BadNextValueException e) {
throw new BadNextValueException();
} catch (UnmatchingParenthesisException e) {
throw new UnmatchingParenthesisException();
}
} | 5 |
public void updatePosition() {
if (xPos < xDestination)
xPos += 1;
else if (xPos > xDestination)
xPos -= 1;
if (yPos < yDestination)
yPos += 1;
else if (yPos > yDestination)
yPos -= 1;
if (xPos == xDestination && yPos == yDestination && currentlyAnimating) {
currentlyAnimating = false;
role.msgDoneAnimating();
}
} | 7 |
public void update(float dt) {
// handle key presses
int ttx = (Keyboard.isKeyPressed(Keyboard.Key.A) ? -1 : 0) + (Keyboard.isKeyPressed(Keyboard.Key.D) ? 1 : 0);
int tty = (Keyboard.isKeyPressed(Keyboard.Key.W) ? -1 : 0) + (Keyboard.isKeyPressed(Keyboard.Key.S) ? 1 : 0);
Vector2 target = new Vector2(ttx, tty);
// normalize target direction
target = target.normalize();
// set length to target velocity
// increasing accelRate should make movements more sharp and dramatic
target = target.scl(accelRate);
// target is now acceleration
Vector2 acc = new Vector2(target);
// integrate acceleration to get velocity
velocity = velocity.sclAdd(acc, dt);
// limit velocity vector to maxMoveSpeed
velocity = velocity.clamp(0, maxMoveSpeed);
// add velocity to position
position = position.add(velocity);
// apply friction
velocity = velocity.scl(fConst);
sprite.setPosition(position.toVector2f());
// set player angle based on mouse position
Vector2 mousePos = new Vector2(Mouse.getPosition(Window.getRenderWindow()));
Vector2 truePos = new Vector2(Window.getRenderWindow().mapCoordsToPixel(position.toVector2f()));
angle = (float) Math.atan2(mousePos.y - truePos.y, mousePos.x - truePos.x);
angle *= (180 / Math.PI);
if (angle < 0) {
angle += 360;
}
angle += 90;
sprite.setRotation(angle);
// if moving, stream particles from opposite side of movement
if (ttx != 0 || tty != 0) {
moveParticleSystem.addParticle();
}
float sin = (float) Math.sin(angle);
float cos = (float) Math.cos(angle);
// set position and angle of particle based off current player sprite
Vector2 particlePos = position.add(new Vector2(cos, sin));
moveParticleSystem.setOrigin(particlePos);
moveParticleSystem.setParticleDecayRate(4);
moveParticleSystem.setParticleRadius(2);
} | 7 |
@Override
public void mousePressed(MouseEvent e) {
for (Interface i : InterfaceHandler.getActiveInterfaces()) {
if (i.getBounds().contains(e.getX(), e.getY())) {
if (InterfaceHandler.getFocused() != i)
InterfaceHandler.setFocused(i);
break;
}
}
} | 3 |
public static void main(String[] args) {
/************************************************************************/
/*login information:
trial: set dummy account:
user name: user
password: user
real: load file IO here:
load text file storing user account information
*/
/************************************************************************/
final Db db = new Db();
final LogAc logAc = new LogAc();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyWindow frame = new MyWindow(db,logAc);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} | 1 |
void toggleLift() {
//System.out.println("Toggle lift");
if (cloud != null) {
//System.out.println("set cloud to null");
cloud = null;
app.cameraMan.cutSetup(flyingDot, flyingDot.isUser);
return;
}
if (circuit != null) {
//System.out.println("set circuit to null");
circuit = null;
circuitPoint = null;
app.cameraMan.cutSetup(flyingDot, flyingDot.isUser);
return;
}
if (circlePoint != null) {
//System.out.println("set circle point to null");
circlePoint = null;
app.cameraMan.cutSetup(flyingDot, flyingDot.isUser);
return;
}
Cloud c = app.sky.getCloudAt(flyingDot.p);
if (c != null) {
//System.out.println("set cloud !");
setCloud(c);
app.cameraMan.cutSetup(cloud, flyingDot.isUser);
return;
}
Hill h = app.landscape.getHillAt(flyingDot.p);
if (h != null) {
//System.out.println("set hill !");
setCircuit(h.getCircuit());
app.cameraMan.cutSetup(h, flyingDot.isUser);
return;
}
//no cloud or ridge - do a wiggle
//System.out.println("no cloud or ridge, so circle !");
wiggleCount = wiggleSize * 4 + 1;
} | 5 |
public void preview(
boolean canPlace, Rendering rendering, Tile from, Tile to
) {
if (from == null) return ;
final Tile t = from ;
final World world = t.world ;
setPosition(t.x, t.y, t.world) ;
final TerrainMesh overlay = world.terrain().createOverlay(
world, surrounds(), false, Texture.WHITE_TEX
) ;
overlay.colour = canPlace ? Colour.GREEN : Colour.RED ;
rendering.addClient(overlay) ;
if (sprite() == null) return ;
this.viewPosition(sprite().position) ;
sprite().colour = canPlace ? Colour.GREEN : Colour.RED ;
rendering.addClient(sprite()) ;
} | 4 |
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.