text stringlengths 14 410k | label int32 0 9 |
|---|---|
public JPanel CreatGui(){
int NumberOfServer = serverlist.size();
tabbedPane = new JTabbedPane();
ImageIcon icon = createImageIcon("glorous28.png");
for(int i =0; i < NumberOfServer; i++){
TABID[CurrentTab] = i;
CurrentTab += 1;
ArrayList<JTextArea> serverTextObject = new ArrayList<JTextArea>();
ArrayList<JTextPane> serverObjects = new ArrayList<JTextPane>();
JPanel tempPanel2 = new JPanel();
tempPanel2.setLayout(new GridLayout(2, 0));
tempPanel2.setVisible(true);
tempPanel2.setPreferredSize(new Dimension(480, 300));
JComponent panel;
if(!catalogue.getmanualServer()) {
panel = makeTextPanel("Server: " + Server.getServer((String) serverlist.get(i)).getName() + " IP:" +
Server.getServer((String) serverlist.get(i)).getIp() + " Port: " + Server.getServer((String)
serverlist.get(i)).getPort());
}
else{
panel = makeTextPanel("Server: ");
}
panel.setPreferredSize(new Dimension(300, 50));
panel.setBackground(new Color(Loop254(i, 0), Loop254(i, 1), Loop254(i, 2)));
JPanel tempPanel3 = new JPanel();
tempPanel3.setLayout(new GridLayout(3, 0));
tempPanel3.add(panel);
tempPanel2.add(tempPanel3);
final JTextArea inputArea = defineInputarea();
JScrollPane jScrollPane2 = new JScrollPane();
serverTextObject.add(inputArea);
jScrollPane2.getViewport().add(inputArea);
inputArea.setPreferredSize(new Dimension(330, 120));
inputArea.setLineWrap(true);
inputArea.setFont(new Font("Courier New", Font.BOLD, 12));
inputArea.setWrapStyleWord(true);
JButton sendMessage = new JButton("Send");
JButton connectButton = new JButton("Connect");
JButton disConnectButton = new JButton("Disconnect");
JButton setkey = new JButton("Set key");
JCheckBox Compress = new JCheckBox("Compress");
JCheckBox Encrypted = new JCheckBox("Encrypted");
connectButton.setPreferredSize(new Dimension(150, 30));
disConnectButton.setPreferredSize(new Dimension(150, 30));
setkey.setPreferredSize(new Dimension(90, 20));
disConnectButton.setEnabled(false);
setkey.setEnabled(false);
JTextPane Key = new JTextPane();
Key.setPreferredSize(new Dimension(120, 20));
JPanel tempPanel6 = new JPanel();
JPanel tempBlankPanel = new JPanel();
JPanel tempencryptplane = new JPanel();
tempencryptplane.setLayout(new FlowLayout());
tempPanel6.setLayout(new FlowLayout());
tempPanel6.add(tempBlankPanel);
tempPanel6.add(connectButton);
tempPanel6.add(disConnectButton);
tempPanel3.add(tempPanel6);
tempencryptplane.add(Compress);
tempencryptplane.add(Encrypted);
tempencryptplane.add(Key);
tempencryptplane.add(setkey);
tempPanel3.add(tempencryptplane);
sendMessage.addActionListener(this);
connectButton.addActionListener(this);
disConnectButton.addActionListener(this);
setkey.addActionListener(this);
Buttons.add(sendMessage);
ActionPlanes.add(inputArea);
JPanel tempPanel5 = new JPanel();
tempPanel5.setLayout(new FlowLayout());
JPanel tempPanel4 = new JPanel();
tempPanel4.setPreferredSize(new Dimension(480, 300));
tempPanel5.add(jScrollPane2);
tempPanel5.add(sendMessage);
tempPanel5.add(tempPanel4);
tempPanel2.add(tempPanel5);
JPanel tempPanel = new JPanel();
tempPanel.setLayout(new GridLayout(2, 0));
JTextPane outputArea = defineOutputarea();
serverObjects.add(outputArea);
outputAreaList.add(outputArea);
outputArea.setPreferredSize(new Dimension(18, 10));
JScrollPane jScrollPane1 = new JScrollPane();
jScrollPane1.getViewport().add(outputArea);
jScrollPane1.setPreferredSize(new Dimension(18, 10));
//outputArea.setPreferredSize(new Dimension(400, 500));
tempPanel.add(jScrollPane1);
tempPanel.add(tempPanel2);
//build layout
String serverName = Server.getServer((String)serverlist.get(i)).getName();
if(serverName.length()> 5){
serverName = serverName.substring(0,5) + "..";
}
tabbedPane.addTab(serverName, icon, tempPanel, "Name: " + Server.getServer((String)serverlist.get(i)).getName());
tabs.add(tempPanel);
tabbedPane.setMnemonicAt(i,KeyEvent.VK_ADD);
serverPlanes.add(serverObjects);
serverJTextField.add(serverTextObject);
//##############################################################################
//Creat all arraylists needed (to be able to get the objects later on)
// inputArea,disConnectButton,sendMessage,Compress,Encrypted,Key
// connectButton
//##############################################################################
inputArea.setEnabled(false);
disConnectButton.setEnabled(false);
sendMessage.setEnabled(false);
Compress.setEnabled(false);
Encrypted.setEnabled(false);
Key.setEnabled(false);
JButton[] buttonList = new JButton[]{connectButton, disConnectButton, sendMessage, setkey};
JCheckBox[] boxesList = new JCheckBox[]{Compress,Encrypted};
JTextPane[] textAreas = new JTextPane[]{Key};
JTextArea[] textAreasfields = new JTextArea[]{inputArea};
ArrayList<Object> ClientContent = new ArrayList<Object>();
ClientContent.add(buttonList);
ClientContent.add(boxesList);
ClientContent.add(textAreas);
ClientContent.add(textAreasfields);
Runnable r = new Runnable() {
@Override
public void run() {
new keycheker().enterKeyAction(inputArea);
}
};
EventQueue.invokeLater(r);
Client_Content.add(ClientContent);
if(catalogue.getmanualServer()){
i = NumberOfServer;
}
}
panelOne.add(tabbedPane);
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
return panelOne;
} | 4 |
public static void printTruthTable(String [][] results, int propagationTime){
for(int i = 0; i < results.length; i++){
for(int j = 0; j < results[0].length; j++){
if(i == 0 || results[0][j].length() == 1)
System.out.print("|" + results[i][j]);
else
System.out.print("|" + results[i][j] + String.format("%1$" + (results[0][j].length()-1) + "s", "" ));
}
System.out.println("|");
}
System.out.println("Propagation Time: " + propagationTime + "ns");
} | 4 |
final public void Function_declaration() throws ParseException {
/*@bgen(jjtree) Function_declaration */
SimpleNode jjtn000 = new SimpleNode(JJTFUNCTION_DECLARATION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtn000.jjtSetFirstToken(getToken(1));
try {
Function_head();
Function_body();
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtn000.jjtSetLastToken(getToken(0));
}
}
} | 8 |
public void matchTexture() {
if (getAssociatedPlayer() instanceof ComputerPlayer && !Game.madHax) {
this.setTextureID(TextureManager.getTextureID("card_back"));
}
else {
this.setTextureID(TextureManager.getCardTextureID(card.value, card.suite));
}
} | 2 |
protected int partition(int attIndex, int l, int r) {
double pivot = instance((l + r) / 2).value(attIndex);
while (l < r) {
while ((instance(l).value(attIndex) < pivot) && (l < r)) {
l++;
}
while ((instance(r).value(attIndex) > pivot) && (l < r)) {
r--;
}
if (l < r) {
swap(l, r);
l++;
r--;
}
}
if ((l == r) && (instance(r).value(attIndex) > pivot)) {
r--;
}
return r;
} | 8 |
public static void main(String[] args) throws IOException {
while (true) {
System.out.println("Choose option for HomeWork to be done with...\n 1 - BufferedReader\n 2 - Scanner\n 3 - JOptionPane\n 4 - Exit");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int number = 0;
while (number < 1 || number > 4) {
System.out.println("You can enter ONLY '1', '2', '3' or '4'.");
try {
number = Integer.parseInt(bufferedReader.readLine());
} catch (NumberFormatException ignore) {
}
}
switch (number) {
case 1:
System.out.println("Please, enter your name for BufferedReader...");
String name = bufferedReader.readLine();
System.out.println("Hello, " + name + "! It's BufferedReader!\n");
break;
case 2:
System.out.println("Please, enter your name for Scanner...");
Scanner scanner = new Scanner(System.in);
String scannerName = scanner.nextLine();
System.out.println("Hello, " + scannerName + "! It's Scanner!\n");
break;
case 3:
String ask = JOptionPane.showInputDialog("Please, enter your name for JOptionPane...");
JOptionPane.showMessageDialog(null, "Hello, " + ask + "! It's JOptionPane!\n");
break;
case 4:
bufferedReader.close();
System.exit(0);
break;
}
}
} | 8 |
public Instances defineDataFormat() throws Exception {
// initialize
setOptions(getOptions());
checkCoverage();
Random random = new Random (getSeed());
setRandom(random);
Instances dataset;
FastVector attributes = new FastVector(3);
Attribute attribute;
boolean classFlag = getClassFlag();
FastVector classValues = null;
if (classFlag)
classValues = new FastVector(getClusters().length);
FastVector boolValues = new FastVector(2);
boolValues.addElement("false");
boolValues.addElement("true");
FastVector nomValues = null;
// define dataset
for (int i = 0; i < getNumAttributes(); i++) {
// define boolean attribute
if (m_booleanCols.isInRange(i)) {
attribute = new Attribute("B" + i, boolValues);
}
else if (m_nominalCols.isInRange(i)) {
// define nominal attribute
nomValues = new FastVector(m_numValues[i]);
for (int j = 0; j < m_numValues[i]; j++)
nomValues.addElement("value-" + j);
attribute = new Attribute("N" + i, nomValues);
}
else {
// numerical attribute
attribute = new Attribute("X" + i);
}
attributes.addElement(attribute);
}
if (classFlag) {
for (int i = 0; i < getClusters().length; i++)
classValues.addElement("c" + i);
attribute = new Attribute ("class", classValues);
attributes.addElement(attribute);
}
dataset = new Instances(getRelationNameToUse(), attributes, 0);
if (classFlag)
dataset.setClassIndex(m_NumAttributes);
// set dataset format of this class
Instances format = new Instances(dataset, 0);
setDatasetFormat(format);
for (int i = 0; i < getClusters().length; i++) {
SubspaceClusterDefinition cl = (SubspaceClusterDefinition) getClusters()[i];
cl.setNumInstances(random);
cl.setParent(this);
}
return dataset;
} | 9 |
public static <T> boolean swapArray(T[] array, int i, int j) {
int size = array.length;
if (size < 2 || i == j || i < 0 || i >= size || j < 0 || j >= size) {
return false;
}
T temp = array[i];
array[i] = array[j];
array[j] = temp;
return true;
} | 6 |
private Vector<TrieNode> fetch(TrieNode parent) {
int prev = 0;
Vector<TrieNode> siblings = new Vector<TrieNode>();
for (int i = parent.left; i < parent.right; i++) {
if (this.keys[i].length() < parent.depth) {
continue;
}
String tmp = this.keys[i];
int cur = 0;
if (this.keys[i].length() != parent.depth) {
cur = tmp.charAt(parent.depth) + 1;
}
if (prev > cur) {
throw new RuntimeException("Fatal: Keys are not sorted");
}
if (cur != prev || siblings.size() == 0) {
TrieNode tempNode = new TrieNode(cur, parent.depth + 1, i, 0);
if (siblings.size() != 0) {
TrieNode lastSibling = siblings.lastElement();
lastSibling.right = i;
}
siblings.add(tempNode);
}
prev = cur;
}
if (siblings.size() != 0) {
TrieNode lastSibling = siblings.lastElement();
lastSibling.right = parent.right;
}
return siblings;
} | 8 |
public void mouseReleased(MouseEvent e) {
} | 0 |
public void drawBoard(Graphics g) {
g.drawImage(boardSizer.getBoardImage(), 0, 0, null);
int radius = boardSizer.getPieceRadius();
for (int x = 0; x < board.boardSize; ++x) {
for (int y = 0; y < board.boardSize; ++y) {
int move = board.intersections[x][y];
if (move == Board.PLAYER_1 || move == Board.PLAYER_2) {
g.setColor(BoardSizer.getPlayerColor(move));
g.fillOval(boardSizer.getCenterX(x) - radius / 2, boardSizer.getCenterY(y) - radius / 2, radius, radius);
}
}
}
Intersection lastMove = board.lastMove;
if (lastMove != null) {
g.setColor(Color.RED);
g.drawOval(boardSizer.getCenterX(lastMove.x) - radius / 4, boardSizer.getCenterY(lastMove.y) - radius / 4, radius / 2, radius / 2);
}
} | 5 |
public Offset readOffset(XMLStreamReader2 streamReader) throws XMLStreamException {
Integer periodMultiplier = null;
PeriodEnum period = null;
DayTypeEnum dayType = null;
int startingDepth = streamReader.getDepth();
while(streamReader.hasNext()) {
switch(streamReader.next()) {
case XMLEvent.START_ELEMENT:
if(streamReader.getDepth() == startingDepth + 1) {
String localName = streamReader.getLocalName();
if("periodMultiplier".equals(localName)) {
periodMultiplier = Integer.parseInt(FpmlParser.readText(streamReader));
} else if("period".equals(localName)) {
period = PeriodEnum.valueOf(FpmlParser.readText(streamReader));
} else if("dayType".equals(localName)) {
dayType = DayTypeEnum.fromValue(FpmlParser.readText(streamReader));
}
}
break;
case XMLEvent.END_ELEMENT:
if(streamReader.getDepth() == startingDepth) {
return new Offset(periodMultiplier, period, dayType);
}
}
}
throw new PricerException("No more events before element finished");
} | 8 |
protected void debugOutput(int topK, String filePrefix) {
File parentTopicFolder = new File(filePrefix + "parentTopicAssignment");
File childTopicFolder = new File(filePrefix + "childTopicAssignment");
if (!parentTopicFolder.exists()) {
System.out.println("creating directory" + parentTopicFolder);
parentTopicFolder.mkdir();
}
if (!childTopicFolder.exists()) {
System.out.println("creating directory" + childTopicFolder);
childTopicFolder.mkdir();
}
File parentWordTopicDistributionFolder = new File(filePrefix
+ "wordTopicDistribution");
if (!parentWordTopicDistributionFolder.exists()) {
System.out.println("creating word topic distribution folder\t"
+ parentWordTopicDistributionFolder);
parentWordTopicDistributionFolder.mkdir();
}
for (_Doc d : m_trainSet) {
if (d instanceof _ParentDoc) {
// printParentTopicAssignment(d, parentTopicFolder);
printWordTopicDistribution(d,
parentWordTopicDistributionFolder, topK);
} else {
printChildTopicAssignment(d, childTopicFolder);
}
}
String parentParameterFile = filePrefix + "parentParameter.txt";
String childParameterFile = filePrefix + "childParameter.txt";
printParameter(parentParameterFile, childParameterFile, m_trainSet);
printTopKChild4Stn(filePrefix, topK);
} | 5 |
@EventHandler
public void PigZombieHarm(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getPigZombieConfig().getDouble("PigZombie.Harm.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getPigZombieConfig().getBoolean("PigZombie.Harm.Enabled", true) && damager instanceof PigZombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getPigZombieConfig().getInt("PigZombie.Harm.Time"), plugin.getPigZombieConfig().getInt("PigZombie.Harm.Power")));
}
} | 6 |
public Line2D.Double getClippedLine(Line2D.Double line) {
if (isInside(line.x1, line.y1) && isInside(line.x2, line.y2)) {
return line;
}
if (isInside(line.x1, line.y1) == false && isInside(line.x2, line.y2) == false) {
return null;
}
if (line.x1 != line.x2 && line.y1 != line.y2) {
return null;
}
assert line.x1 == line.x2 || line.y1 == line.y2;
if (line.y1 == line.y2) {
final double newx1 = getClippedX(line.x1);
final double newx2 = getClippedX(line.x2);
return new Line2D.Double(newx1, line.y1, newx2, line.y2);
}
if (line.x1 == line.x2) {
final double newy1 = getClippedY(line.y1);
final double newy2 = getClippedY(line.y2);
return new Line2D.Double(line.x1, newy1, line.x2, newy2);
}
throw new IllegalStateException();
} | 9 |
* @return a set of actual versions in bitset form
*/
BitSet getSelectedVersions( String spec )
{
BitSet bs;
if ( spec != null && spec.length()>0 )
bs = convertVersions( spec );
else
{
bs = new BitSet();
for ( int i=1;i<=versions.size();i++ )
bs.set( i );
}
return bs;
} | 3 |
public static void main(String[] args) {
// read names from file
List<String> names = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/home/nagasaki45/code/cattle_drive/names.txt"));
String line;
while((line = reader.readLine()) != null) {
names.add(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// sort and print the names
Collections.sort(names);
Iterator<String> iter = names.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
} | 5 |
public static ObjectDefinitions getObjectDefinitions(int id) {
ObjectDefinitions def = objectDefinitions.get(id);
if (def == null) {
def = new ObjectDefinitions();
def.id = id;
byte[] data = Cache.STORE.getIndexes()[16].getFile(
getArchiveId(id), id & 0xff);
if (data == null)
System.out.println("Failed loading Object " + id + ".");
else
def.readValueLoop(new InputStream(data));
def.method3287();
if ((def.name != null && (def.name.equalsIgnoreCase("bank booth") || def.name
.equalsIgnoreCase("counter")))) {
def.notCliped = false;
def.projectileCliped = true;
if (def.clipType == 0)
def.clipType = 1;
} else if (DungeonUtils.isDoor(id)) {
def.notCliped = false;
def.projectileCliped = true;
if (def.clipType == 0)
def.clipType = 1;
}
if (def.notCliped) {
def.projectileCliped = false;
def.clipType = 0;
}
objectDefinitions.put(id, def);
}
return def;
} | 9 |
public Person retrieve() {
if (personArray.length == 0) {
return null;
}
Person result = personArray[0];
for (int position = 0; position < personArray.length-1; position++) {
if (personArray[position+1] != null) {
personArray[position] = personArray[position+1];
personArray[position].setPosition(personArray[position].getPosition()-1);
}
}
queueSize--;
if (isHalfSize()) {
halveArraySize();
}
return result;
} | 4 |
public GameData(int numInitialContestants) {
// check if within parameters
if (numInitialContestants > 15 || numInitialContestants < 6)
return; // if not, do not create GameData item
weeksRem = numInitialContestants - 2;
weeksPassed = 0;
setBetAmount(0);
this.numInitialContestants = numInitialContestants;
// containers for contestants and users
allContestants = new ArrayList<Contestant>(numInitialContestants);
allUsers = new ArrayList<User>(5);
castOffs = new Contestant[numInitialContestants];
currentGame = this;
} | 2 |
public void togglefs() {
if (prefs == null)
setfs();
else
setwnd();
} | 1 |
public String readLine() {
if (input != null) {
if (input.hasNext()) {
return input.next();
} else {
return null;
}
} else {
return null;
}
} | 2 |
@Override
public PropertyFilter removeFilterByName(String name) {
for (int i = 0; i < filters.size(); i++) {
PropertyFilter filter = (PropertyFilter) filters.get(i);
String filter_name = filter.getName();
if (filter_name == null && name == null) {
filters.remove(i);
return filter;
} else if (filter_name.equals(name)) {
filters.remove(i);
return filter;
}
}
return null;
} | 4 |
public void recieveCmd(){
int cmd;
try {
cmd = input.read();
} catch (IOException ioe) {
System.out.println("failed to read from serial");
ioe.printStackTrace();
return;
}
System.out.printf("cmd = %x: ", cmd);
if((cmd & 0x80) == 0) return;
switch(cmd){
case 0xC0: // start left click
System.out.println("left click");
r.mousePress(InputEvent.BUTTON1_MASK);
break;
case 0xC1: // end left click
System.out.println("left release");
r.mouseRelease(InputEvent.BUTTON1_MASK);
break;
case 0xC2: // start right click
System.out.println("right click");
r.mousePress(InputEvent.BUTTON3_MASK);
break;
case 0xC3: // end right click
System.out.println("right release");
r.mouseRelease(InputEvent.BUTTON3_MASK);
break;
case 0x80: // move mouse
int[] xy = readXY(false);
xy = mapXY(xy);
r.mouseMove(xy[0], xy[1]);
System.out.printf("move to (%d, %d)\n", xy[0], xy[1]);
break;
case 0xF0: // set keyboard modifiers
setModifiersWithRobot();
break;
default:
System.out.printf("undefined: %x\n");
}
} | 8 |
public boolean poistaRuutu(int a, int b) {
for (int i = 0; i < reuna; i++) {
for (int j = 0; j < reuna; j++) {
if (i == a && j == b) {
ruudukko[i][j] = "";
return true;
}
}
}
return false;
} | 4 |
public static void main(String[] unused) {
Machine M;
BufferedReader input =
new BufferedReader(new InputStreamReader(System.in));
M = null;
boolean firstline = true;
try {
while (true) {
String line = input.readLine();
if (line == null) {
break;
}
if (firstline) {
String[] firstinput = line.split(" ");
if (!firstinput[0].equals("*")) {
System.exit(1);
}
firstline = false;
}
if (isConfigurationLine(line)) {
M = new Machine();
configure(M, line);
} else {
printMessageLine(M.convert(standardize(line)));
}
}
} catch (IOException excp) {
System.err.printf("Input error: %s%n", excp.getMessage());
System.exit(1);
}
} | 6 |
public String reportByMark(){
preReportByMark();
boolean check = true;
if(stdo.getStrMark().isEmpty()){
check = false;
addFieldError("stdo.strMark", "You must a value to mark");
} else {
try {
stdo.setMark(Float.parseFloat(stdo.getStrMark()));
if(stdo.getMark()<0 || stdo.getMark() > 100){
check = false;
addFieldError("stdo.strMark", "You must a value to mark which in [0, 100]");
}
} catch (Exception e) {
check = false;
addFieldError("stdo.strMark", "You must a float value to mark");
}
}
if(check){
students = mdReport.getStudentByMark(clo.getClassname(), ojto.getObjId(), tpo.getTopicId(), stdo.getMark());
if(students.size() > 0){
mMarkStatistics = new LinkedHashMap<Float, PairValue>();
for (StudentObj studentObj : students) {
PairValue pair = mMarkStatistics.get(studentObj.getMark());
if(pair != null){
Integer countMark = Integer.valueOf(pair.getValue1()) + 1;
pair = new PairValue(countMark + "", (int)((countMark * 1.0/students.size()) * 100) + "");
mMarkStatistics.put(studentObj.getMark(), pair);
} else {
mMarkStatistics.put(studentObj.getMark(), new PairValue(1 + "", (int)((1.0/students.size()) * 100) + ""));
}
}
}
}
return SUCCESS;
} | 8 |
public void setUserKey(String key) {
if (key.isEmpty()) {
return;
}
userKeyTextField.setText(key);
BmLog.debug("Setting user key " + key);
} | 1 |
public Reminder()
{
super(Reminder.class.getSimpleName());
} | 0 |
public void displayandSearchContents() {
// Output Scriptures that match
System.out.println("Topic References");
for (int i = 0; i < topicsList.size(); i++) {
String tempTopic = topicsList.get(i).getTopic();
System.out.println(tempTopic);
for (int h = 0; h < entries.size(); h++) {
Entry tempEntry = entries.get(h);
Date tempDate = tempEntry.getDate();
ArrayList<String> topics = tempEntry.getTopics();
for (int j = 0; j < topics.size(); j++) {
if (tempTopic.equals(topics.get(j))) {
System.out.print("\t" + tempDate.getYear() + "-");
System.out.print(tempDate.getMonth() + "-");
System.out.println(tempDate.getDay());
}
}
}
}
System.out.println("Scripture References");
for (int i = 0; i < bookList.size(); i++) {
String tempBookName = bookList.get(i).getBookName();
System.out.println(tempBookName);
for (Entry tempEntry : entries) {
Date tempDate = new Date();
tempDate = tempEntry.getDate();
ArrayList<Scripture> scriptures = new ArrayList<>();
scriptures = tempEntry.getScriptures();
for (int j = 0; j < scriptures.size(); j++) {
if (scriptures.get(j).getBookName().getBookName().equals(tempBookName)) {
System.out.print("\t" + tempDate.getYear() + "-");
System.out.print(tempDate.getMonth() + "-");
System.out.println(tempDate.getDay());
}
}
}
}
} | 8 |
private void validate(byte[] bytes)
{
for (byte b : bytes)
{
if (b == Utils.RECORD_SEPARATOR)
{
throw new RuntimeException("Key contains a Record Separator 0x1E");
}
}
} | 2 |
public void handlePark(Park park) {
park.setManaged(true);
this.park = park;
} | 0 |
@Override
public boolean disInvokeEffects(Environmental E)
{
if(E==null)
return false;
if(E instanceof Affectable)
{
final Affectable aE=(Affectable)E;
final LinkedList<Ability> affects=new LinkedList<Ability>();
for(int a=aE.numEffects()-1;a>=0;a--) // personal affects
{
final Ability A=aE.fetchEffect(a);
if(A!=null)
affects.add(A);
}
for(final Ability A : affects)
{
if(A.canBeUninvoked() && (!A.isAutoInvoked()))
A.unInvoke();
}
}
return !E.amDestroyed();
} | 7 |
public static void startupDateTimeParser() {
{ 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)) {
_StartupDateTimeParser.helpStartupDateTimeParser1();
}
if (Stella.currentStartupTimePhaseP(4)) {
_StartupDateTimeParser.helpStartupDateTimeParser2();
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
Stella.defineFunctionObject("HASHLIST", "(DEFUN HASHLIST ((LIST OBJECT) (TABLE OBJECT)) :TYPE OBJECT :MACRO? TRUE)", Native.find_java_method("edu.isi.stella.Stella_Object", "hashlist", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("YESTERDAY", "(DEFUN YESTERDAY ((PARSED-VALUES DECODED-DATE-TIME) (DEFAULT-VALUES DECODED-DATE-TIME)))", Native.find_java_method("edu.isi.stella.DecodedDateTime", "yesterday", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.DecodedDateTime"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("TODAY", "(DEFUN TODAY ((PARSED-VALUES DECODED-DATE-TIME) (DEFAULT-VALUES DECODED-DATE-TIME)))", Native.find_java_method("edu.isi.stella.DecodedDateTime", "today", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.DecodedDateTime"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("TOMORROW", "(DEFUN TOMORROW ((PARSED-VALUES DECODED-DATE-TIME) (DEFAULT-VALUES DECODED-DATE-TIME)))", Native.find_java_method("edu.isi.stella.DecodedDateTime", "tomorrow", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.DecodedDateTime"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("NOW", "(DEFUN NOW ((PARSED-VALUES DECODED-DATE-TIME) (DEFAULT-VALUES DECODED-DATE-TIME)))", Native.find_java_method("edu.isi.stella.DecodedDateTime", "now", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.DecodedDateTime"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("AM-PM", "(DEFUN (AM-PM SYMBOL) ((STRING OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "amPm", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("ERA", "(DEFUN (ERA SYMBOL) ((STRING OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "era", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("NOON-MIDN", "(DEFUN (NOON-MIDN SYMBOL) ((STRING OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "noonMidn", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("WEEKDAY", "(DEFUN (WEEKDAY KEYWORD) ((THING OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "weekday", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("MONTH", "(DEFUN (MONTH INTEGER-WRAPPER) ((THING OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "month", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("ZONE", "(DEFUN (ZONE FLOAT-WRAPPER) ((THING OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "zone", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("SPECIALP", "(DEFUN (SPECIALP SYMBOL) ((STRING OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "specialp", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("SECONDP", "(DEFUN (SECONDP BOOLEAN-WRAPPER) ((NUMBER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "secondp", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("MINUTE", "(DEFUN (MINUTE BOOLEAN-WRAPPER) ((NUMBER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "minute", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("ZONE-MINUTE", "(DEFUN (ZONE-MINUTE BOOLEAN-WRAPPER) ((NUMBER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "zoneMinute", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("HOUR", "(DEFUN (HOUR BOOLEAN-WRAPPER) ((NUMBER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "hour", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("DAY", "(DEFUN (DAY BOOLEAN-WRAPPER) ((NUMBER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "day", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("YEAR", "(DEFUN (YEAR BOOLEAN-WRAPPER) ((NUMBER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "year", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("TIME-DIVIDER", "(DEFUN (TIME-DIVIDER BOOLEAN-WRAPPER) ((THECHARACTER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "timeDivider", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("DATE-DIVIDER", "(DEFUN (DATE-DIVIDER BOOLEAN-WRAPPER) ((THECHARACTER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "dateDivider", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("DATE-TIME-DIVIDER", "(DEFUN (DATE-TIME-DIVIDER BOOLEAN-WRAPPER) ((THECHARACTER OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "dateTimeDivider", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("MATCH-SUBSTRING", "(DEFUN (MATCH-SUBSTRING CONS) ((SUBSTRING STRING) (PARSING-TIME? BOOLEAN)))", Native.find_java_method("edu.isi.stella.Stella", "matchSubstring", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("DIGIT-VALUE", "(DEFUN (DIGIT-VALUE INTEGER) ((CHAR CHARACTER)))", Native.find_java_method("edu.isi.stella.Stella", "digitValue", new java.lang.Class [] {java.lang.Character.TYPE}), null);
Stella.defineFunctionObject("DECOMPOSE-DATE-TIME-STRING", "(DEFUN (DECOMPOSE-DATE-TIME-STRING CONS) ((STRING STRING) (START INTEGER) (END INTEGER)))", Native.find_java_method("edu.isi.stella.Stella", "decomposeDateTimeString", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("MATCH-PATTERN-ELEMENT", "(DEFUN (MATCH-PATTERN-ELEMENT CONS) ((PATTERN-ELEMENT SYMBOL) (DATUM-ELEMENT OBJECT)))", Native.find_java_method("edu.isi.stella.Symbol", "matchPatternElement", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("MATCH-PATTERN", "(DEFUN (MATCH-PATTERN CONS) ((PATTERN CONS) (DATUM CONS) (DATUM-LENGTH INTEGER)))", Native.find_java_method("edu.isi.stella.Cons", "matchPattern", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.Cons"), java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("DEAL-WITH-NOON-MIDN", "(DEFUN DEAL-WITH-NOON-MIDN ((FORM-VALUE OBJECT) (PARSED-VALUES DECODED-DATE-TIME)))", Native.find_java_method("edu.isi.stella.Stella_Object", "dealWithNoonMidn", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("DEAL-WITH-AM-PM", "(DEFUN DEAL-WITH-AM-PM ((FORM-VALUE OBJECT) (PARSED-VALUES DECODED-DATE-TIME)))", Native.find_java_method("edu.isi.stella.Stella_Object", "dealWithAmPm", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("DEAL-WITH-ERA", "(DEFUN DEAL-WITH-ERA ((FORM-VALUE OBJECT) (PARSED-VALUES DECODED-DATE-TIME)))", Native.find_java_method("edu.isi.stella.Stella_Object", "dealWithEra", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("SET-TIME-VALUES", "(DEFUN SET-TIME-VALUES ((STRING-FORM (CONS OF CONS)) (PARSED-VALUES DECODED-DATE-TIME) (DEFAULT-VALUES DECODED-DATE-TIME)))", Native.find_java_method("edu.isi.stella.Cons", "setTimeValues", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.DecodedDateTime"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("MATCH-DATE-TIME-PATTERNS", "(DEFUN (MATCH-DATE-TIME-PATTERNS CONS) ((DATE-TIME-STRING STRING) (START INTEGER) (END INTEGER) (ERROR-ON-MISMATCH? BOOLEAN)))", Native.find_java_method("edu.isi.stella.Stella", "matchDateTimePatterns", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, java.lang.Integer.TYPE, java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("HELP-PARSE-DATE-TIME-RELATIVE-TO-BASE", "(DEFUN (HELP-PARSE-DATE-TIME-RELATIVE-TO-BASE DECODED-DATE-TIME) ((DATE-TIME-STRING STRING) (BASE-DATE-TIME DECODED-DATE-TIME) (START INTEGER) (END INTEGER) (ERROR-ON-MISMATCH? BOOLEAN) (MERGE-NULL-FIELDS? BOOLEAN)) :PUBLIC? FALSE :CONSTRUCTOR? TRUE)", Native.find_java_method("edu.isi.stella.DecodedDateTime", "helpParseDateTimeRelativeToBase", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.DecodedDateTime"), java.lang.Integer.TYPE, java.lang.Integer.TYPE, java.lang.Boolean.TYPE, java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("PARSE-DATE-TIME-RELATIVE-TO-BASE", "(DEFUN (PARSE-DATE-TIME-RELATIVE-TO-BASE DECODED-DATE-TIME) ((DATE-TIME-STRING STRING) (BASE-DATE-TIME DECODED-DATE-TIME) (START INTEGER) (END INTEGER) (ERROR-ON-MISMATCH? BOOLEAN) (MERGE-NULL-FIELDS? BOOLEAN)) :PUBLIC? TRUE :CONSTRUCTOR? TRUE :DOCUMENTATION \"Tries very hard to make sense out of the argument `date-time-string' and\nreturns a time structure if successful. If not, it returns `null'.\nIf `error-on-mismatch?' is true, parse-date-time will signal an error instead of\nreturning `null'.\nDefault values are passed in via `base-date-time'. If the timezone field that\nis passed in is NULL, then the local time zone for the parsed date/time will\nbe used.\nIf `merge-null-fields?' is `true', then default values from `base-time-date'\nwill be merged into missing components. If `false', then they won't be merged\nin for null components but can still be used as a basis for interpreatation of\nrelative time strings like \\\"now\\\" or \\\"yesterday\\\"\")", Native.find_java_method("edu.isi.stella.DecodedDateTime", "parseDateTimeRelativeToBase", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.DecodedDateTime"), java.lang.Integer.TYPE, java.lang.Integer.TYPE, java.lang.Boolean.TYPE, java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("PARSE-DATE-TIME-IN-TIME-ZONE", "(DEFUN (PARSE-DATE-TIME-IN-TIME-ZONE DECODED-DATE-TIME) ((DATE-TIME-STRING STRING) (TIME-ZONE FLOAT) (START INTEGER) (END INTEGER) (ERROR-ON-MISMATCH? BOOLEAN)) :PUBLIC? TRUE :CONSTRUCTOR? TRUE :DOCUMENTATION \"Tries very hard to make sense out of the argument `date-time-string' and\nreturns a time structure if successful. If not, it returns `null'.\nIf `error-on-mismatch?' is true, parse-date-time will signal an error instead of\nreturning `null'. \nDefault values are 00:00:00 in the given timezone on the current date. If the\ngiven `time-zone' value is `null', then the local time zone for the given date\nand time will be used as determined by the operating system.\")", Native.find_java_method("edu.isi.stella.DecodedDateTime", "parseDateTimeInTimeZone", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Double.TYPE, java.lang.Integer.TYPE, java.lang.Integer.TYPE, java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("PARSE-DATE-TIME", "(DEFUN (PARSE-DATE-TIME DECODED-DATE-TIME) ((DATE-TIME-STRING STRING) (START INTEGER) (END INTEGER) (ERROR-ON-MISMATCH? BOOLEAN)) :PUBLIC? TRUE :GLOBALLY-INLINE? TRUE :CONSTRUCTOR? TRUE :DOCUMENTATION \"Tries very hard to make sense out of the argument `date-time-string' and\nreturns a time structure if successful. If not, it returns `null'.\nIf `error-on-mismatch?' is true, parse-date-time will signal an error instead of\nreturning `null'. \nDefault values are 00:00:00 local time on the current date\" (RETURN (PARSE-DATE-TIME-IN-TIME-ZONE DATE-TIME-STRING NULL START END ERROR-ON-MISMATCH?)))", Native.find_java_method("edu.isi.stella.DecodedDateTime", "parseDateTime", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, java.lang.Integer.TYPE, java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("STRING-TO-DECODED-DATE-TIME", "(DEFUN (STRING-TO-DECODED-DATE-TIME DECODED-DATE-TIME) ((INPUT STRING)) :PUBLIC? TRUE :CONSTRUCTOR? TRUE :DOCUMENTATION \"Returns a decoded date-time object representing the date\nand time parsed from the `input' string. If no valid parse is found,\n`null' is returned.\")", Native.find_java_method("edu.isi.stella.DecodedDateTime", "stringToDecodedDateTime", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null);
Stella.defineFunctionObject("STRING-TO-CALENDAR-DATE", "(DEFUN (STRING-TO-CALENDAR-DATE CALENDAR-DATE) ((INPUT STRING)) :PUBLIC? TRUE :CONSTRUCTOR? TRUE :DOCUMENTATION \"Returns a calendar date object representing the date and time\nparsed from the `input' string. If no valid parse is found,\n`null' is returned.\")", Native.find_java_method("edu.isi.stella.CalendarDate", "stringToCalendarDate", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null);
Stella.defineFunctionObject("STRING-TO-CALENDAR-DATE-WITH-DEFAULT", "(DEFUN (STRING-TO-CALENDAR-DATE-WITH-DEFAULT CALENDAR-DATE) ((INPUT-DATE STRING) (DEFAULT-DATE DECODED-DATE-TIME)) :PUBLIC? TRUE :CONSTRUCTOR? TRUE :DOCUMENTATION \"Returns a calendar date object representing the date and time\nparsed from the `input-date' string. Default values for missing fields and\nthe interpretation of relative references come from `default-date'. If the\n`default-date' is `null', the current date will be used. If a null set of\ndefaults is desired, use `*NULL-DECODED-DATE-TIME*'.\nIf no valid parse is found, `null' is returned.\")", Native.find_java_method("edu.isi.stella.CalendarDate", "stringToCalendarDateWithDefault", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.DecodedDateTime")}), null);
Stella.defineFunctionObject("STARTUP-DATE-TIME-PARSER", "(DEFUN STARTUP-DATE-TIME-PARSER () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella._StartupDateTimeParser", "startupDateTimeParser", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Stella.SYM_STELLA_STARTUP_DATE_TIME_PARSER);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupDateTimeParser"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/STELLA")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT WHITESPACE-CHARS CONS (BQUOTE (#\\ #\\Tab #\\Linefeed #\\Return #\\Page #\\, #\\' #\\`)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT TIME-DIVIDERS CONS (BQUOTE (#\\: #\\.)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT DATE-DIVIDERS CONS (BQUOTE (#\\\\ #\\/ #\\- #\\+)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT DATE-TIME-DIVIDERS CONS (BQUOTE (#\\T)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *ERROR-ON-MISMATCH* BOOLEAN FALSE :PUBLIC? TRUE :DOCUMENTATION \"If TRUE, an error will be signalled if parse-date-time is unable\n to determine the time/date format of the string.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *WEEKDAY-STRINGS* (STRING-HASH-TABLE OF STRING KEYWORD) (NEW (STRING-HASH-TABLE OF STRING KEYWORD)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *MONTH-STRINGS* STRING-TO-INTEGER-HASH-TABLE (NEW STRING-TO-INTEGER-HASH-TABLE))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *ZONE-STRINGS* (STRING-HASH-TABLE OF STRING FLOAT-WRAPPER) (NEW (STRING-HASH-TABLE OF STRING FLOAT-WRAPPER)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *ERA-STRINGS* (STRING-HASH-TABLE OF STRING SYMBOL) (NEW (STRING-HASH-TABLE OF STRING SYMBOL)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *SPECIAL-STRINGS* STRING-HASH-TABLE (NEW STRING-HASH-TABLE))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *SPECIAL-SYMBOLS* (CONS OF SYMBOL) (BQUOTE (YESTERDAY TODAY TOMORROW NOW)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *DATE-TIME-PATTERNS* CONS (BQUOTE ((YEAR (DATE-DIVIDER) MONTH (DATE-DIVIDER) DAY (NOON-MIDN)) ((NOON-MIDN) (WEEKDAY) MONTH (DATE-DIVIDER) DAY (DATE-DIVIDER) YEAR) ((NOON-MIDN) (WEEKDAY) DAY (DATE-DIVIDER) MONTH (DATE-DIVIDER) YEAR) ((NOON-MIDN) (WEEKDAY) MONTH (DATE-DIVIDER) DAY) ((NOON-MIDN) YEAR (DATE-DIVIDER) MONTH (DATE-DIVIDER) DAY) ((NOON-MIDN) MONTH (DATE-DIVIDER) YEAR) ((NOON-MIDN) YEAR (DATE-DIVIDER) MONTH) ((DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (NOON-MIDN (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) ((DATE-TIME-DIVIDER) HOUR (NOON-MIDN)) (YEAR (DATE-DIVIDER) MONTH (DATE-DIVIDER) DAY (DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (YEAR (DATE-DIVIDER) MONTH (DATE-DIVIDER) DAY NOON-MIDN (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (YEAR (DATE-DIVIDER) MONTH (DATE-DIVIDER) DAY NOW) ((WEEKDAY) MONTH (DATE-DIVIDER) DAY (DATE-DIVIDER) YEAR (DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) ((WEEKDAY) DAY (DATE-DIVIDER) MONTH (DATE-DIVIDER) YEAR (DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) ((WEEKDAY) MONTH (DATE-DIVIDER) DAY (DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (MONTH (DATE-DIVIDER) YEAR (DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (YEAR (DATE-DIVIDER) MONTH (DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) ((WEEKDAY) MONTH (DATE-DIVIDER) DAY (DATE-DIVIDER) YEAR (NOON-MIDN) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) ((WEEKDAY) DAY (DATE-DIVIDER) MONTH (DATE-DIVIDER) YEAR (NOON-MIDN) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) ((WEEKDAY) MONTH (DATE-DIVIDER) DAY (NOON-MIDN) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (MONTH (DATE-DIVIDER) YEAR (NOON-MIDN) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (YEAR (DATE-DIVIDER) MONTH (NOON-MIDN) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) ((DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE) (WEEKDAY) MONTH (DATE-DIVIDER) DAY (DATE-DIVIDER) YEAR) ((DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE) (WEEKDAY) DAY (DATE-DIVIDER) MONTH (DATE-DIVIDER) YEAR) ((DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE) (WEEKDAY) MONTH (DATE-DIVIDER) DAY) ((DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE) YEAR (DATE-DIVIDER) MONTH (DATE-DIVIDER) DAY) ((DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE) MONTH (DATE-DIVIDER) YEAR) ((DATE-TIME-DIVIDER) HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE) YEAR (DATE-DIVIDER) MONTH) (WEEKDAY MONTH DAY HOUR (TIME-DIVIDER) MINUTE (TIME-DIVIDER) SECONDP (AM-PM) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE) YEAR) ((WEEKDAY) DAY (DATE-DIVIDER) MONTH (DATE-DIVIDER) YEAR HOUR (TIME-DIVIDER) MINUTE (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) ((WEEKDAY) MONTH (DATE-DIVIDER) DAY (DATE-DIVIDER) YEAR HOUR (TIME-DIVIDER) MINUTE (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (YEAR (DATE-DIVIDER) (MONTH)) (MONTH (DATE-DIVIDER) (YEAR)) ((WEEKDAY) MONTH DAY HOUR TIME-DIVIDER MINUTE (TIME-DIVIDER) (SECONDP) YEAR) (NOW (YESTERDAY)) ((YESTERDAY) NOW) (NOW (TODAY)) ((TODAY) NOW) (NOW (TOMORROW)) ((TOMORROW) NOW) (YESTERDAY (NOON-MIDN)) ((NOON-MIDN) YESTERDAY) (TODAY (NOON-MIDN)) ((NOON-MIDN) TODAY) (TOMORROW (NOON-MIDN)) ((NOON-MIDN) TOMORROW) (YESTERDAY HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (TOMORROW HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)) (TODAY HOUR (TIME-DIVIDER) (MINUTE) (TIME-DIVIDER) (SECONDP) (AM-PM) (DATE-DIVIDER) (ZONE) (TIME-DIVIDER) (ZONE-MINUTE)))))");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} | 6 |
public static void main(String[] args) {
BufferedOutputStream stream = null;
try {
stream = new BufferedOutputStream(new FileOutputStream("out.txt"));
stream.write("Hello, World!".getBytes());
stream.write(System.getProperty("line.separator").getBytes());
stream.write("I am writting into a file using BufferedOutputStream"
.getBytes());
stream.write(System.getProperty("line.separator").getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | 3 |
private void getNextPosition() {
// movement
if(left) {
dx -= moveSpeed;
if(dx < -maxSpeed) {
dx = -maxSpeed;
}
}
else if(right) {
dx += moveSpeed;
if(dx > maxSpeed) {
dx = maxSpeed;
}
}
// falling
if(falling) {
dy += fallSpeed;
}
} | 5 |
public static void main(String[] args) {
User u = null;
try {
u = new User("bob", "builder", "bbuilde");
} catch (InvalidFieldException e) {
}
Contestant c = new Contestant();
Contestant ul = new Contestant();
try {
c.setID("aa");
ul.setID("ab");
u.setWeeklyPick(c);
u.setUltimatePick(ul);
} catch (InvalidFieldException e1) {
e1.printStackTrace();
}
try {
System.out.println(u.toJSONObject().toString());
} catch (ParseException e) {
e.printStackTrace();
}
} | 3 |
public void testPropertyCompareToDay() {
LocalDateTime test1 = new LocalDateTime(TEST_TIME1);
LocalDateTime test2 = new LocalDateTime(TEST_TIME2);
assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0);
assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0);
assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0);
try {
test1.dayOfMonth().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0);
assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0);
assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0);
try {
test1.dayOfMonth().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
} | 2 |
public static void addOL(Gob obj) {
if(obj != null) {
Integer newId = Integer.valueOf(obj.id);
if(!iObj.contains(newId))
iObj.add(newId);
}
} | 2 |
@Override
public void run() throws Exception {
// TODO Auto-generated method stub
try {
// Eclipse doesn't support System.console()
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
ConfigManager config = NetBase.theNetBase().config();
try {
String targetIP = config.getProperty("net.server.ip");
if ( targetIP == null ) {
System.out.println("No net.server.ip entry in config file.");
System.out.print("Enter the server's ip, or empty line to exit: ");
targetIP = console.readLine();
if ( targetIP == null || targetIP.trim().isEmpty() ) return;
}
int targetTCPPort;
System.out.print("Enter the server's TCP port, or empty line to skip: ");
String targetTCPPortStr = console.readLine();
if ( targetTCPPortStr == null || targetTCPPortStr.trim().isEmpty() ) targetTCPPort = 0;
else targetTCPPort = Integer.parseInt(targetTCPPortStr);
System.out.print("Enter number of trials: ");
String trialStr = console.readLine();
int nTrials = Integer.parseInt(trialStr);
int socketTimeout = config.getAsInt("net.timeout.socket", 5000);
System.out.println("Host: " + targetIP);
System.out.println("tcp port: " + targetTCPPort);
System.out.println("trials: " + nTrials);
ElapsedTimeInterval tcpResult = null;
if ( targetTCPPort != 0 ) {
ElapsedTime.clear();
tcpResult = ping(EchoServiceBase.HEADER_STR, targetIP, targetTCPPort, socketTimeout, nTrials);
}
if ( tcpResult != null ) System.out.println("TCP: " + String.format("%.2f msec (%d failures)", tcpResult.mean(), tcpResult.nAborted()));
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("PingRaw.run() caught exception: " +e.getMessage());
}
} | 9 |
public void redrawAllOpenDocuments() {
for (int i = 0, limit = openDocuments.size(); i < limit; i++) {
OutlinerDocument doc = (OutlinerDocument) getDocument(i);
// Only request focus for the current document.
if (doc == getMostRecentDocumentTouched()) {
doc.panel.layout.redraw();
} else {
doc.panel.layout.draw();
}
}
} | 2 |
@Override
public String getHTTPStatusCode(HTTPStatusCodes httpStatusCodes) {
return getPatchMap().containsKey(etag) ? httpStatusCodes.getStatus(204) : httpStatusCodes.getStatus(200);
} | 1 |
public static void main(String[] args) {
w = new Worker();
} | 0 |
private void initNeedParseLangList() {
if (null == needParseLangList) {
needParseLangList = new ArrayList<>();
if (langEnUsjCheckBox.isSelected()) {
needParseLangList.add("en_us");
}
if (langDeDejCheckBox.isSelected()) {
needParseLangList.add("de_de");
}
if (langFrFrjCheckBox.isSelected()) {
needParseLangList.add("fr_fr");
}
if (langEsEsjCheckBox.isSelected()) {
needParseLangList.add("es_es");
}
if (langZhTwjCheckBox.isSelected()) {
needParseLangList.add("zh_tw");
}
if (langItItjCheckBox.isSelected()) {
needParseLangList.add("it_it");
}
}
} | 7 |
private static void expandAllSubheads(OutlinerDocument doc) {
try {
if (doc.tree.getComponentFocus() == OutlineLayoutManager.TEXT) {
TextKeyListener.expandAllSubheads(doc.tree.getEditingNode());
} else if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) {
IconKeyListener.expandAllSubheads(doc.tree);
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
} | 3 |
*/
public void iniciar() {
/* 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(SjfInterfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SjfInterfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SjfInterfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SjfInterfaz.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 SjfInterfaz().setVisible(true);
}
});
} | 6 |
public void addLeft() {
int rows[] = types.getSelectedIndices();
if (rows.length != 0) {
for(int i : rows) {
AccountType type = allTypes.get(i);
if (!debitTypes.contains(type)) {
debitTypes.add(type);
debitModel.addElement(type);
}
}
}
} | 3 |
@Override
public void stateChanged(ChangeEvent ce)
{
System.out.println("you changed the state of the program...:P");
if(((JTabbedPane)(ce.getSource())).getSelectedIndex()==0)
{
if((Student.studentListAudio.size()-Integer.parseInt(studentNumberComboBox.getSelectedItem().toString()))>=0)
waitingButton.setText("Waiting : "+(Student.studentListAudio.size()-Integer.parseInt(studentNumberComboBox.getSelectedItem().toString())));
else
waitingButton.setText("Waiting : 0");
}
else if(((JTabbedPane)(ce.getSource())).getSelectedIndex()==1)
{
if((Student.studentListText.size()-Integer.parseInt(studentNumberComboBox.getSelectedItem().toString()))>=0)
waitingButton.setText("Waiting : "+(Student.studentListText.size()-Integer.parseInt(studentNumberComboBox.getSelectedItem().toString())));
else
waitingButton.setText("Waiting : 0");
}
} | 4 |
private static Animacion crearAnimacionCanasta() {
Animacion anim = new Animacion();
for (int i = 0; i <= 8; i++) {
anim.sumaCuadro (Toolkit.getDefaultToolkit ().getImage (Canasta.class.getResource ("Images/basket/net" + i + ".png")), 200);
}
return anim;
} | 1 |
private void createContenedoresGraphic() {
horizontalContenedoresBarModel = new HorizontalBarChartModel();
horizontalContenedoresBarModel.setStacked(true);
horizontalContenedoresBarModel.setBarMargin(40);
Axis xAxis = horizontalContenedoresBarModel.getAxis(AxisType.X);
xAxis.setLabel("Espacio del Contenedor");
xAxis.setMin(0);
xAxis.setMax(data.getTamMax());
int max=-5;
for(Integer iteracion: data.getCortes().keySet() ){
if(iteracion>max)
max=iteracion;
}
List<ChartSeries> espacios = new ArrayList<ChartSeries>();
Map<Integer,Boolean> chartCreados = new HashMap<Integer,Boolean>();
for(Integer iteracion: data.getCortes().keySet() ){
List<Integer> registros = data.getCortes().get(iteracion);
int i=0;
for(Integer basija:registros){
if(chartCreados.containsKey(i)){
ChartSeries cs= espacios.get(i);
cs.set("Contenedor"+iteracion, basija);
}else{
ChartSeries cs = new ChartSeries();
cs.setLabel("Espacio"+(espacios.size()+1));
for(int k=1;k<=max;k++){
cs.set("Contenedor"+k, 0);
}
cs.set("Contenedor"+iteracion, basija);
espacios.add(cs);
chartCreados.put(i, true);
}
i++;
}
}
for(ChartSeries chart:espacios){
horizontalContenedoresBarModel.addSeries(chart);
}
} | 7 |
public void setAnimState(AnimState state) {
if (state != null) resetAnimState();
getPrivates();
stateColor = g.getColor();
stateNew = new AnimState(state);
g.setColor(state.color); state.color.bind();
if (state.pos.x != 0 || state.pos.y != 0) g.translate(-state.pos.x,-state.pos.y);
if (state.angle != 0) gl.glRotatef(-state.angle,0f,0f,1f);
if (state.scaleH != 1 || state.scaleV != 1) g.scale(1f/state.scaleH,1f/state.scaleV);
} | 6 |
@Override
public boolean setChartOption( String op, String val )
{
boolean bHandled = false;
if( op.equalsIgnoreCase( "Stacked" ) )
{
fStacked = val.equals( "true" );
bHandled = true;
}
else if( op.equalsIgnoreCase( "PercentageDisplay" ) )
{
f100 = val.equals( "true" );
bHandled = true;
}
else if( op.equalsIgnoreCase( "Shadow" ) )
{
fHasShadow = val.equals( "true" );
bHandled = true;
}
else if( op.equalsIgnoreCase( "Smooth" ) )
{ // smooth lines
/* if (b instanceof Serfmt) {
Serfmt s= (Serfmt) b;
if (s.getSmoothLine()) {*/
}
if( bHandled )
{
updateRecord();
}
return bHandled;
} | 5 |
Point computeSize(Control control, int wHint, int hHint, boolean flushCache) {
if (flushCache)
flushCache();
if (wHint == SWT.DEFAULT && hHint == SWT.DEFAULT) {
if (defaultWidth == -1 || defaultHeight == -1) {
Point size = control.computeSize(wHint, hHint, flushCache);
defaultWidth = size.x;
defaultHeight = size.y;
}
return new Point(defaultWidth, defaultHeight);
}
if (currentWidth == -1 || currentHeight == -1 || wHint != currentWhint
|| hHint != currentHhint) {
Point size = control.computeSize(wHint, hHint, flushCache);
currentWhint = wHint;
currentHhint = hHint;
currentWidth = size.x;
currentHeight = size.y;
}
return new Point(currentWidth, currentHeight);
} | 9 |
public ModelState(final boolean score, final int level, final int theme) {
this.ifScore = score;
this.difficulty = level;
this.theme = theme;
endOfTheGame = false;
//назначаем стартовые очки
if (level == 8) {
bricks = new boolean[4][2];
this.score = 1000;
} else if (level == 15) {
bricks = new boolean[5][3];
this.score = 1700;
} else {
bricks = new boolean[8][6];
this.score = 5000;
}
//закрываем всю картинку
for (int i = 0; i < bricks.length; i++) {
for (int j = 0; j < bricks[i].length; j++) {
bricks[i][j] = true;
}
}
//задаем картинку и текущие правильные ответы
setPicture();
rightAnswers = currentRightAnswers;
} | 4 |
public void guardarArchivo(String path){
try {
Configuracion c = principal.configuraciones.buscar(principal.getCurrentServer());
if(c==null){
c = principal.configuraciones.getConfigLocal();
}
FileOutputStream fileOut = new FileOutputStream(c.getStrategiesDir()+"\\"+path);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(contenedorEstrategia);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in strategies.txt");
} catch (IOException i) {
i.printStackTrace();
}
} | 2 |
private static void calculateUsersTopTenMatches(HashMap<Integer, User> userMap) {
/*
* Note: Currently this function is hovering at a runtime of O(N^2). All possible combinations of users are computed, with no cashing, i.e.
* user 1's potential relationship with user 2 is calculated, and later user 2's potential relationship with user 1 is calculated.
* This is one potential avenue of optimization that instantly pops into mind; however there are others methodologies as well, I am sure.
* This code should be viewed as an initial system functionality prototype. If this were a production product, the next step would be
* much more through testing and optimization code reviews.
*/
//Iterate through all users, and calculate their top 10 matches
Iterator<Integer> i = userMap.keySet().iterator();
while(i.hasNext()){
User focusUser = userMap.get(i.next());
LinkedList<Double[]> topTenList = new LinkedList<Double[]>();
//Init topTenList to allow future operations
Double[] init = {-1.0,-1.0};
for(int x = 0; x <10; x ++){
topTenList.add(init);
}
Iterator<Integer> i2 = userMap.keySet().iterator();
while(i2.hasNext()){
//Dont try to match yourself to yourself -- no vain people allowed!
if(i.equals(i2)) continue;
User targetUser = userMap.get(i2.next());
//Note: This duple "Double[]" has userId at index [0] and % match with target at index [1]
//Find the correct location for this result, and add it into the list of top ten
double result = calculateTotalMatchPotential(focusUser, targetUser);
for(int x=0; x<10; x++){
Double[] idMatchPercentInQuestion = {(double)targetUser.getId(), result};
Double[] idMatchPercentInList = topTenList.get(x);
if(result > idMatchPercentInList[1])
{
topTenList.add(x, idMatchPercentInQuestion);
break;
}
}
//We only care about the top ten, so maintain the list length at 10.
if(topTenList.size() > 10){
topTenList.subList(10, topTenList.size()).clear();
}
}
System.out.println("------------Top ten list for " + focusUser.getId() + "----------");
int tempCount = 1;
for(Double[] a : topTenList)
{
System.out.println("Match #" + tempCount++ + ": " + "User #" + a[0].intValue() + " at %" + a[1] *100);
}
packUpResultsIntoJson(topTenList, focusUser.getId());
}
} | 8 |
private static void parseCriteria(Element attrElem, ChartData chartData, AttributeData parentAttr, HashMap<String, Color> colorMap)
throws IOException {
try {
if (attrElem.getAttribute("type").equals("abstract")) {
AttributeAbstractData attr = new AttributeAbstractData();
attr.setName(attrElem.getAttribute("name"));
NodeList nList = attrElem.getChildNodes();
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
parseCriteria((Element)node, chartData, attr, colorMap);
}
}
chartData.addAttributeData(parentAttr, attr);
}
else {
AttributePrimitiveData attr = new AttributePrimitiveData();
attr.setName(attrElem.getAttribute("name"));
attr.setWeight(Double.parseDouble(attrElem.getAttribute("weight")));
attr.setColor(colorMap.get(attr.getName()));
// if (attrElem.getElementsByTagName(XML_DESCRIPTION).getLength() > 0) {
// String htmlText = StringEscapeUtils.unescapeJava(
// attrElem.getElementsByTagName(XML_DESCRIPTION).item(0).getTextContent());
//
// Pattern pat = Pattern.compile("<html>");
// Matcher mat = pat.matcher(htmlText);
// int start = -1;
// if(mat.find())
// start = mat.start();
//
// pat = Pattern.compile("</html>");
// mat = pat.matcher(htmlText);
// int end = -1;
// if(mat.find())
// end = mat.start();
//
// htmlText = htmlText.substring(start, end + 7);
//
// attr.setDescription(htmlText);
// }
Element domainElem = (Element) attrElem.getElementsByTagName(XML_DOMAIN).item(0);
if (domainElem.getAttribute("type").equals("continuous"))
attr.setUnitsName(domainElem.getAttribute("unit"));
attr.setDomain(parseDomain(domainElem));
chartData.addAttributeData(parentAttr, attr);
}
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
throw new IOException(attrElem.getUserData(PositionalXMLReader.LINE_NUMBER).toString());
}
} | 6 |
public void init(){
initialized = true;
int i = 0;
while(i < content.size()){
content.get(i).PreInit(this,new Config(new File("")));
i++;
}
while(i < content.size()){
content.get(i).Init(this);
i++;
}
while(i < content.size()){
content.get(i).PostInit(this);
i++;
}
} | 3 |
public boolean move(int direction) {
if (this.movingState >= 0) {
return false;
}
this.direction = direction;
Point nextPosition = this.getNextTile(direction);
if (nextPosition.x < 0 || nextPosition.y < 0 || nextPosition.x >= Constants.ENVIRONMENT_WIDTH || nextPosition.y >= Constants.ENVIRONMENT_HEIGHT) {
return false;
}
this.movingState = 1;
this.position = new Point(nextPosition);
return true;
} | 5 |
@Override
public void caseAConstanteDeclaracao(AConstanteDeclaracao node)
{
inAConstanteDeclaracao(node);
if(node.getValor() != null)
{
node.getValor().apply(this);
}
if(node.getIdentificador() != null)
{
node.getIdentificador().apply(this);
}
if(node.getConst() != null)
{
node.getConst().apply(this);
}
outAConstanteDeclaracao(node);
} | 3 |
private void paintJogo(Graphics g)
{
// Desenhar
for(int x=0; x<Engine.NUM_COLUMNS; x++)
{
for(int y=0; y<Engine.NUM_LINES; y++)
{
int drawY = Engine.NUM_LINES-1-y;
if( getEngine().getCobra().isPosTrue(x,y) ) // Cobra
{
rectanguloJogo(g, Color.BLUE, x, drawY);
}
else if( getEngine().getObstaculos().isPosTrue(x,y) ) // Obstaculos
{
rectanguloJogo(g, Color.BLACK, x, drawY);
}
else if( getEngine().getTocaPermanente().isPosTrue(x,y) ) // Toca Permanente
{
rectanguloJogo(g, Color.RED, x, drawY);
}
else if( getEngine().getTocaTemporaria().isPosTrue(x,y) ) // Toca Temporária
{
drawTocaTemporaria(g, x, drawY);
}
}
}
} | 6 |
public void inicio(Curso curso) throws Exception
{
salvar = new JButton("Salvar");
id = new JTextInt(curso.getId());
id.setEditable(false);
id.setEnabled(false);
nome = new JTextField(curso.getNome() == null ? "" : curso.getNome());
JPanel pp = new JPanel();
DesignGridLayout layout = new DesignGridLayout(pp);
layout.row().grid(new JLabel("ID:")).add(id);
layout.row().grid(new JLabel("Nome:")).add(nome);
layout.row().grid().add(salvar, 1);
getContentPane().add(new JScrollPane(pp));
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
} | 1 |
private boolean isTitleGood()
{
boolean titleGood = false;
int start = -1;
for (int i = 0; i < this.currentTitle.length(); i++)
{
if (!Trie.isASCIIAlpha(this.currentTitle.charAt(i)))
{
if (-1 != start)
{
String word = this.currentTitle.substring(start, i);
titleGood = this.t.searchWord(word);
if (titleGood)
{
return true;
}
start = -1;
}
}
else
{
start = (-1 == start) ? i : start;
}
}
if (-1 != start)
{
return this.t.searchWord(this.currentTitle.substring(start, this.currentTitle.length()));
}
return false;
} | 6 |
public NewRDPNode(String taxaName, String scoreString) throws Exception
{
this.taxaName = stripQuotes( taxaName);
scoreString = scoreString.trim();
if( scoreString.equals("1") || scoreString.equals("1.0"))
{
this.score = 100;
}
else if ( scoreString.equals("0"))
{
this.score = 0;
}
else
{
if( ! scoreString.startsWith("0.") )
throw new Exception("Unexpected score string "+ scoreString);
if(scoreString.length() == 3)
scoreString = scoreString + "0";
this.score = Integer.parseInt(scoreString.substring(2));
}
if( this.score < 0 || this.score > 100 )
throw new Exception("Unexpected score " + this.score);
} | 7 |
public static Color convertToEnum(String color_name)
{
switch(color_name.toUpperCase())
{
case "YELLOW" : return Color.YELLOW;
case "WHITE" : return Color.WHITE;
case "BROWN" : return Color.BROWN;
case "BLUE" : return Color.BLUE;
case "RED" : return Color.RED;
case "GREEN" : return Color.GREEN;
}
return null;
} | 6 |
public String getAllFarmAnimals(){
Player[] p = Bukkit.getOnlinePlayers();
for(Player player : p){
if(plugin.getAnimalData().contains("Farmer." + player.getUniqueId().toString())){
String farmer = player.getUniqueId().toString();
Set<String> animals = plugin.getAnimalData().getConfigurationSection("Farmer." + farmer + ".Animals").getKeys(false);
for(String animal : animals){
return animal;
}
}else{
return null;
}
}
return null;
} | 3 |
public String[] getOptions() {
int i;
Vector result;
String[] options;
File file;
result = new Vector();
options = super.getOptions();
for (i = 0; i < options.length; i++)
result.add(options[i]);
if (getOutputClassification())
result.add("-classification");
if (getRemoveOldClass())
result.add("-remove-old-class");
if (getOutputDistribution())
result.add("-distribution");
if (getOutputErrorFlag())
result.add("-error");
file = getSerializedClassifierFile();
if ((file != null) && (!file.isDirectory())) {
result.add("-serialized");
result.add(file.getAbsolutePath());
}
else {
result.add("-W");
result.add(getClassifierSpec());
}
return (String[]) result.toArray(new String[result.size()]);
} | 7 |
public int getNorth(){
return this.north;
} | 0 |
public void merge(int[] arrayA, int sizeA, int[] arrayB, int sizeB) {
if (sizeB == 0)
return;
if (sizeA == 0)
System.arraycopy(arrayB, 0, arrayA, 0, sizeB);
int tailA = sizeA - 1;
int tailB = sizeB - 1;
int lastA = tailA + tailB + 1;
while (tailA > -1 && tailB > -1) {
if (arrayA[tailA] > arrayB[tailB]) {
arrayA[lastA] = arrayA[tailA];
lastA--;
tailA--;
} else {
arrayA[lastA] = arrayB[tailB];
lastA--;
tailB--;
}
}
if (tailA == -1) {
System.arraycopy(arrayB, 0, arrayA, 0, tailB + 1);
}
} | 6 |
public void close() {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
if (byteArrayInputStream != null) {
byteArrayInputStream.close();
}
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
logger.log(Level.FINE, "Error closing file streams.", e);
}
} | 5 |
public int linearRegInterceptLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 14;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
return optInTimePeriod-1;
} | 3 |
public int overlapStart(Interval interval) {
int i = 0;
while (i < size() - 1 && !get(i).overlaps(interval)) {
i++;
}
if (i >= size()) {
return -1;
}
return i;
} | 3 |
private void getInfo() {
infoTextArea.setText("");
infoTextArea.append(" Тип FAT: " + extractor.getTypeOfFileSystem());
infoTextArea.append("\n BS_OEMNAME: " + extractor.getBS_OEMNAme());
infoTextArea.append("\n FAT таблиц: " + extractor.getBPB_NumFATs().toString());
infoTextArea.append("\n Байтов в секторе: " + extractor.getBPB_BytsPerSec().toString());
infoTextArea.append("\n Секторов в кластере: " + extractor.getBPB_SecPerClus().toString());
infoTextArea.append("\n Количество кластеров: " + extractor.getCountOfClusters().toString());
int size = extractor.getCountOfClusters() * extractor.getBPB_BytsPerSec();
String dim = "";
if (size >= 1024) {
size /= 1024;
dim = "Кб";
} else if (size >= 1048576) {
size /= 1048576;
dim = "Мб";
} else {
dim = "байт";
}
infoTextArea.append("\n Размер тома FAT32: " + size + " " + dim);
} | 2 |
private static final boolean isDelimiter(char c) {
return ((c == '[') || (c == ']') ||
(c == '(') || (c == ')') ||
(c == '<') || (c == '>') ||
(c == '{') || (c == '}') ||
(c == '/') || (c == '%'));
} | 9 |
public static ProtocolException throwInaccessibleTileException(String direction, Tile theTile){
if(theTile == null){
return new ProtocolException("Invalid move: tile " + direction
+ " is not accessible (outside of map)");
}
else {
return new ProtocolException("Invalid move: " + theTile.tileType + " tile is not accessible");
}
} | 1 |
public static void fail(){
if (round < 6) {
currentPlayer.setScore(MrVago.getPrizes()[0]);
}
if (round >= 6 && round < 11) {
currentPlayer.setScore(MrVago.getPrizes()[5]);
}
if (round >= 11) {
currentPlayer.setScore(MrVago.getPrizes()[10]);
}
saveCurrentPlayer(prevPlayerFile);
LOGG.logInfo("The player gave a false answer." + " " + "The question was: " + actQuestion.getQuestion());
} | 4 |
public static File createRandomFile(File dir, String ext) {
if (!dir.isDirectory()) return null;
File[] files = dir.listFiles();
while (true) {
String fileName = String.valueOf((int) (Math.random() * 1e10)) + '.' + ext;
boolean found = false;
if (files != null) {
for (File file : files) {
if (file.getName().equals(fileName)) {
found = true;
break;
}
}
}
if (!found) return new File(dir, fileName);
}
} | 6 |
public void testSubsetUnion() throws Exception {
for (int i = 0; i < 100; i++) {
int len = (int)(Math.random() * (10 - 1) + 1);
RBtree a = randomRB( len );
RBtree b = randomRB( len );
RBtree ab = a.union( b );
if (!(a.subset( ab )) && !(b.subset( ab )) ) {
throw new Exception("FAILURE A SET WAS NOT IN ITS UNION'S SUBSET");
}
subsetUnionTest++;
}
} | 3 |
public StringSelection getStringSelection() {
StringSelection result;
int[] indices;
int i;
int n;
StringBuffer tmp;
result = null;
// nothing selected? -> all
if (getSelectedRow() == -1) {
// really?
if (ComponentHelper.showMessageBox(
getParent(),
"Question...",
"Do you really want to copy the whole table?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE ) != JOptionPane.YES_OPTION)
return result;
indices = new int[getRowCount()];
for (i = 0; i < indices.length; i++)
indices[i] = i;
}
else {
indices = getSelectedRows();
}
// get header
tmp = new StringBuffer();
for (i = 0; i < getColumnCount(); i++) {
if (i > 0)
tmp.append("\t");
tmp.append(getPlainColumnName(i));
}
tmp.append("\n");
// get content
for (i = 0; i < indices.length; i++) {
for (n = 0; n < getColumnCount(); n++) {
if (n > 0)
tmp.append("\t");
tmp.append(getValueAt(indices[i], n).toString());
}
tmp.append("\n");
}
result = new StringSelection(tmp.toString());
return result;
} | 8 |
public void sortColumns() {
//remove all columns first
for( int i=browseTable.getColumnCount(); i > 0 ;i-- ) {
browseTable.removeColumn(browseTable.getColumnModel().getColumn(i-1));
}
//and now set up only the columns witch should be visible
for(int j=0 ; j < isColumnShow.length; j++) {
if(isColumnShow[j]) {
browseTable.addColumn(new TableColumn(j));
}
}
//setTheWidth
setAllColumnWidths();
} | 3 |
public static void sendPrivateMessageToSpies( BSPlayer sender, BSPlayer receiver, String message ) {
for ( BSPlayer p : getChatSpies() ) {
if ( !( p.equals( sender ) || p.equals( receiver ) ) ) {
p.sendMessage( Messages.PRIVATE_MESSAGE_SPY.replace( "{sender}", sender.getName() ).replace( "{player}", receiver.getName() ).replace( "{message}", message ) );
}
}
} | 3 |
public Document getDoc() {
return doc;
} | 0 |
@Override
public void documentAdded(DocumentRepositoryEvent e) {} | 0 |
private int findSingleBranchMaxPathSum(TreeNode root) {
int leftMaxPathSum=0;
int rightMaxPathSum=0;
if(root.left != null){
leftMaxPathSum = findSingleBranchMaxPathSum(root.left);
}
if(root.right != null){
rightMaxPathSum = findSingleBranchMaxPathSum(root.right);
}
int left = leftMaxPathSum<0?0:leftMaxPathSum;
int right = rightMaxPathSum<0?0:rightMaxPathSum;
if(maxPathSum == null){
maxPathSum = root.val+left+right;
}else if(root.val+left+right>maxPathSum){
maxPathSum = root.val+left+right;
}
int single = left>right?left:right;
return root.val+single;
} | 7 |
public static void init() {
if (weightList == null) {
try {
weightList = new ArrayList<Algorithm>();
HashMap<Integer, ArrayList<String>> listJp = CSVReaderUtils
.csvToListJp();
if (listJp != null && listJp.size() > 0) {
for (Entry<Integer, ArrayList<String>> entry : listJp
.entrySet()) {
Algorithm algorithm = new Algorithm();
algorithm.setAlgorithmId(weightList.size()
+ entry.getKey());
algorithm.setWord(entry.getValue().get(0));
algorithm.setPoint(Double.parseDouble(entry.getValue()
.get(1)));
weightList.add(algorithm);
}
}
HashMap<Integer, ArrayList<String>> listWago = CSVReaderUtils
.csvToListWago();
if (listWago != null && listWago.size() > 0) {
for (Entry<Integer, ArrayList<String>> entry : listWago
.entrySet()) {
Algorithm algorithm = new Algorithm();
algorithm.setAlgorithmId(weightList.size()
+ entry.getKey());
algorithm.setWord(entry.getValue().get(1));
algorithm.setPoint(Double.parseDouble(entry.getValue()
.get(0)));
weightList.add(algorithm);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} | 8 |
public static final boolean isHTML(String fileName) {
for (String file : HTML) {
if (file.equals(fileName)) {
return true;
}
}
return false;
} | 2 |
public void analyzeInnerClasses(ProgressListener pl, double done,
double scale) {
double subScale = scale / innerComplexity;
// If output should be immediate, we delay analyzation to output.
// Note that this may break anonymous classes, but the user
// has been warned.
if ((Options.options & Options.OPTION_IMMEDIATE) != 0)
return;
// Now analyze the inner classes.
for (int j = 0; j < inners.length; j++) {
if (pl != null) {
double innerCompl = inners[j].getComplexity() * subScale;
if (innerCompl > STEP_COMPLEXITY) {
double innerscale = subScale * inners[j].methodComplexity;
inners[j].analyze(pl, done, innerscale);
inners[j].analyzeInnerClasses(null, done + innerscale,
innerCompl - innerscale);
} else {
pl.updateProgress(done, inners[j].name);
inners[j].analyze(null, 0.0, 0.0);
inners[j].analyzeInnerClasses(null, 0.0, 0.0);
}
done += innerCompl;
} else {
inners[j].analyze(null, 0.0, 0.0);
inners[j].analyzeInnerClasses(null, 0.0, 0.0);
}
}
// Now analyze the method scoped classes.
for (int j = 0; j < methods.length; j++)
methods[j].analyzeInnerClasses();
} | 5 |
private static void copyfile(String srFile, String dtFile) {
try {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
EIError.debugMsg("File copied " + srFile + " " + dtFile, EIError.ErrorLevel.Notice);
} catch (Exception e) {
EIError.debugMsg("Couldn't copy file" + srFile + " " + dtFile + " " + e.getMessage(), EIError.ErrorLevel.Error);
}
} | 2 |
final void method3956(byte i, Class310 class310) {
((DirectxToolkit) this).anIDirect3DDevice9810.SetTexture
(((DirectxToolkit) this).anInt8175, class310.method2314(17723));
if (i <= -53) {
if (aClass209Array9795[((DirectxToolkit) this).anInt8175]
== ((Class310) class310).aClass209_3894) {
if (aBooleanArray9804[((DirectxToolkit) this).anInt8175]
== !((Class310) class310).aBoolean3892) {
((DirectxToolkit) this).anIDirect3DDevice9810.SetSamplerState
(((DirectxToolkit) this).anInt8175, 7,
(((Class310) class310).aBoolean3892
? method3952(((Class310) class310).aClass209_3894,
(byte) 86)
: 0));
aBooleanArray9804[((DirectxToolkit) this).anInt8175]
= ((Class310) class310).aBoolean3892;
}
} else {
int i_22_ = method3952(((Class310) class310).aClass209_3894,
(byte) 82);
((DirectxToolkit) this).anIDirect3DDevice9810
.SetSamplerState(((DirectxToolkit) this).anInt8175, 6, i_22_);
((DirectxToolkit) this).anIDirect3DDevice9810
.SetSamplerState(((DirectxToolkit) this).anInt8175, 5, i_22_);
aClass209Array9795[((DirectxToolkit) this).anInt8175]
= ((Class310) class310).aClass209_3894;
if (aBooleanArray9804[((DirectxToolkit) this).anInt8175]
!= ((Class310) class310).aBoolean3892) {
((DirectxToolkit) this).anIDirect3DDevice9810.SetSamplerState
(((DirectxToolkit) this).anInt8175, 7,
(!((Class310) class310).aBoolean3892 ? 0
: method3952(((Class310) class310).aClass209_3894,
(byte) 68)));
aBooleanArray9804[((DirectxToolkit) this).anInt8175]
= ((Class310) class310).aBoolean3892;
}
}
if (!aBooleanArray9784[((DirectxToolkit) this).anInt8175]) {
aBooleanArray9784[((DirectxToolkit) this).anInt8175] = true;
method3935(-123);
method3920(10);
}
}
} | 7 |
public void copyAlphaFrom(CPColorBmp bmp, CPRect r) {
r.clip(getSize());
for (int j = r.top; j < r.bottom; j++) {
for (int i = r.left; i < r.right; i++) {
data[j * width + i] = (data[j * width + i] & 0xffffff) | (bmp.data[j * width + i] & 0xff000000);
}
}
} | 2 |
public TGetResponse postRequest(String URL, String request) throws IOException {
HttpPost hp = new HttpPost(URL);
//StringEntity ent = new StringEntity(request, "UTF-8");
StringEntity ent = new StringEntity(request, HTTP.UTF_8);
hp.setEntity(ent);
hp.addHeader("Authorization", "Basic " + authdata);
if (sessionId != null) {
hp.addHeader("X-Transmission-Session-Id", sessionId);
}
//HttpResponse response = httpclient.execute(targetHost, hp, localcontext);
HttpResponse response = httpclient.execute(targetHost, hp);
if (response.getStatusLine().getStatusCode() == 409) {
EntityUtils.consume(response.getEntity()); //le kell záratni a korábbi kapcsolatot különben:
//HIBA: Invalid use of BasicClientConnManager: connection still allocated.
sessionId = response.getFirstHeader("X-Transmission-Session-Id").getValue();
hp.addHeader("X-Transmission-Session-Id", sessionId);
//response = httpclient.execute(targetHost, hp, localcontext);
response = httpclient.execute(targetHost, hp);
}
TGetResponse r = null;
HttpEntity respEnt = response.getEntity();
if (respEnt != null) {
String line;
//Scanner sc = new Scanner(respent.getContent()).useDelimiter("\\A");
//BufferedReader reader = new BufferedReader(new InputStreamReader(respEnt.getContent()));
BufferedReader reader = new BufferedReader(new InputStreamReader(respEnt.getContent(), "UTF-8"));
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
JsonObject jso = new JsonParser().parse(sb.toString()).getAsJsonObject();
System.out.println(jso);
r = new Gson().fromJson(sb.toString(), TGetResponse.class);
}
return r;
} | 4 |
public static void main(String[] args) {
long number = 600851475143L;
for(int i = 2; i < Math.sqrt(number); i++)
{
if((number / i) * i == number)
number = number / i;
}
System.out.println(number);
} | 2 |
@Id
@Column(name = "PRP_MOA_TIPO")
public String getPrpMoaTipo() {
return prpMoaTipo;
} | 0 |
private void fileChoose() {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
fc.setFileFilter(new FileNameExtensionFilter("20 Questions Files",
"q20", "txt"));
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showOpenDialog(null);
if(returnVal == JFileChooser.CANCEL_OPTION) { //tries to fetch a file from the internet, exits if it is unable to
try {
url = new URL(
"https://docs.google.com/uc?authuser=0&id=0ByEZo2nCK6IySVdFb3FWODUxRW8&export=download");
new questionTree(url.openStream());
}
catch(MalformedURLException e1) {
JOptionPane.showMessageDialog(null,
"URL didn't work. ¯\\_(ツ)_/¯", "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
catch(IOException e1) {
JOptionPane.showMessageDialog(null,
"I/O Exception. Check your internet connection.",
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
if(returnVal == JFileChooser.APPROVE_OPTION)
new questionTree(fc.getSelectedFile()); //creates a new questionTree with selected file
} | 4 |
public MovingSquares(ArrayList<Point> ms) {
movingSquares = new Vector<MovingSquare>();
for (Point point : ms) {
movingSquares.add(new MovingSquare(point));
}
} | 1 |
@Override
public void keyPressed(int key, char c) {
if(!inputEnabled)
return;
ArrayList<GameKeyListener> keyListenersCopy = new ArrayList<GameKeyListener>(keyListeners); //Create a copy because scripts can register keypress components.
System.out.println("Pressed key: " + key);
Iterator<GameKeyListener> it = keyListenersCopy.iterator();
while(it.hasNext()) {
GameKeyListener next = it.next();
next.KeyDown(key, c);
}
} | 2 |
public Data parse(byte[] bytes)
{
String input = getString(bytes).trim();
String s;
if (input.length() < 1) {
s = null;
}else if (getSignPosition() == LEADING) {
char c = input.charAt(0);
s = (isPositive(c) ? "" : "-") + getNumber(c)
+ (input.length() > 1 ? input.substring(1) : "");
} else {
int last = input.length() - 1;
char c = input.charAt(last);
s = (isPositive(c) ? "" : "-")
+ (input.length() > 1 ? input.substring(0, last-1) : "") + getNumber(c);
}
BigInteger big = s == null ? null : new BigInteger(s);
Data data = create();
if (data instanceof DecimalData) {
DecimalData dData = (DecimalData) data;
BigDecimal bigD = big == null ? null : new BigDecimal(big, decimalPlaces());
dData.setValue(bigD);
return data;
} else {
IntegerData iData = (IntegerData) data;
iData.setValue(big);
return data;
}
} | 9 |
private void addNode(CharNode node) {
int charData = 0xFFFF & node.data;
if (charData > 254) {
dict[dictSize++] = (byte) 255;
dict[dictSize++] = (byte) ((node.data >> 8) & 0xFF);
dict[dictSize++] = (byte) (node.data & 0xFF);
} else {
dict[dictSize++] = (byte) (0xFF & node.data);
}
if (node.children != null) {
dictSize += 3; // Space for children address
} else {
dictSize += 1; // Space for just the terminal/address flags
}
if ((0xFFFFFF & node.freq) > 255) {
node.freq = 255;
}
if (node.terminal) {
byte freq = (byte) (0xFF & node.freq);
dict[dictSize++] = freq;
}
} | 4 |
public void initTableHandlers(String decisionSettings, SymbolTableHandler symbolTableHandler) throws MaltChainedException {
transitionTableHandler = new TransitionTableHandler();
tableHandlers = new HashMap<String, TableHandler>();
final String[] decisionElements = decisionSettings.split(",|#|;|\\+");
int nTrans = 0;
for (int i = 0; i < decisionElements.length; i++) {
int index = decisionElements[i].indexOf('.');
if (index == -1) {
throw new ParsingException("Decision settings '"+decisionSettings+"' contain an item '"+decisionElements[i]+"' that does not follow the format {TableHandler}.{Table}. ");
}
if (decisionElements[i].substring(0,index).equals("T")) {
if (!getTableHandlers().containsKey("T")) {
getTableHandlers().put("T", getTransitionTableHandler());
}
if (decisionElements[i].substring(index+1).equals("TRANS")) {
if (nTrans == 0) {
TransitionTable ttable = (TransitionTable)getTransitionTableHandler().addSymbolTable("TRANS");
addAvailableTransitionToTable(ttable);
} else {
throw new ParsingException("Illegal decision settings '"+decisionSettings+"'");
}
nTrans++;
}
} else if (decisionElements[i].substring(0,index).equals("A")) {
if (!getTableHandlers().containsKey("A")) {
getTableHandlers().put("A", symbolTableHandler);
}
} else {
throw new ParsingException("The decision settings '"+decisionSettings+"' contains an unknown table handler '"+decisionElements[i].substring(0,index)+"'. " +
"Only T (Transition table handler) and A (ArcLabel table handler) is allowed. ");
}
}
} | 8 |
public void update()
{
if (followList.size() == 0) return;
// FINDING THE BOUNDING RECTANGLE {
Rectangle bound = new Rectangle(Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 0);
// Finding the minimum position
for (GameObject toFollow : followList) {
if (toFollow.pos.x < bound.x) {
bound.x = (int) (toFollow.pos.x - 5);
}
if (toFollow.pos.y < bound.y) {
bound.y = (int) (toFollow.pos.y - 5);
}
}
// Finding the maximum size
for (GameObject toFollow : followList) {
int relativeX = (int) ((toFollow.pos.x + 5) - bound.x); // relative to bound's x
int relativeY = (int) ((toFollow.pos.y + 5) - bound.y); // ...
if (relativeX > bound.width) {
bound.width = relativeX;
}
if (relativeY > bound.height) {
bound.height = relativeY;
}
}
// }
// Target position:
Vector2d targetPosition = new Vector2d(bound.getCenterX(), bound.getCenterY());
position.x += (targetPosition.x - position.x) / quotient;
position.x += followList.get(0).vel.x;
if (followList.get(0).vel.x > 1) {
position.x += 30;
} else if (followList.get(0).vel.x < - 1) {
position.x -= 30;
} else {
}
//
position.y += (targetPosition.y - position.y) / quotient;
//Target zoom!!! To find this: what zoom do we need to make the bound rectangle fit screen? ( + a little margin yay!!! :D)
double targetZoom;
/*// Apply margins
bound.width += cameraMargin * 2;
bound.height += cameraMargin * 2;
if ((double) bound.width / (double) Game.WIDTH > (double) bound.height / (double) Game.HEIGHT) {
targetZoom = 1/ ((double) bound.width / (double) Game.WIDTH);
} else {
targetZoom = 1/ ((double) bound.height / (double) Game.HEIGHT);
}*/
/*if (followList.size() > 0) {
targetZoom = (200 / 5);
zoom += (targetZoom - zoom) / (quotient * 2);
}*/
} | 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.