method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
2b6d9164-2e75-40e8-a480-a3eeeb2e6a03 | 6 | public String toString()
{
String out = "";
if (quantity > 1)
out += quantity;
if (miniCompounds != null && miniCompounds.length > 0)
{
for (int i = miniCompounds.length - 1; i >= 0; i--)
out += miniCompounds[i];
}
else
{
if (miniCompounds == null)
System.err.println("miniCompounds is null");
else if (miniCompounds.length <= 0)
System.err.println("miniCompounds is empty");
out = "An error occurred";
}
return out;
} |
1e608424-d151-4a4d-bf92-fca8dd9f2ba1 | 1 | @Override
public EndPoint getOtherEndPoint() {
if( connection.getSourceEndPoint() == this ){
return connection.getTargetEndPoint();
}
else{
return connection.getSourceEndPoint();
}
} |
562ce275-2320-420a-b8de-3ae0caff9864 | 4 | @Test
public void test_intersection() {
HLLCounter h0 = new HLLCounter(true, 1024);
HLLCounter h1 = new HLLCounter(true, 1024);
HLLCounter h2 = new HLLCounter(true, 1024);
HLLCounter h3 = new HLLCounter(true, 1024);
for(int i = 0; i < 10000; i++) {
h0.put(String.valueOf(i));
}
for(int i = 5000; i < 15000; i++) {
h1.put(String.valueOf(i));
}
for(int i = 8000; i < 11000; i++) {
h2.put(String.valueOf(i));
}
for(int i = 8000; i < 9000; i++) {
h3.put(String.valueOf(i));
}
assertEquals(4853, HLLCounter.intersect(h0, h1)); //about 5000
assertEquals(1922, HLLCounter.intersect(h0, h2)); //about 2000
assertEquals(937, HLLCounter.intersect(h0, h3)); //about 1000
assertEquals(2963, HLLCounter.intersect(h1, h2)); //about 3000
assertEquals(958, HLLCounter.intersect(h1, h3)); //about 1000
assertEquals(986, HLLCounter.intersect(h2, h3)); //about 1000
assertEquals(1862, HLLCounter.intersect(h0, h1, h2)); //about 2000
assertEquals(762, HLLCounter.intersect(h0, h1, h3)); //about 1000
assertEquals(934, HLLCounter.intersect(h0, h2, h3)); //about 1000
assertEquals(958, HLLCounter.intersect(h1, h2, h3)); //about 1000
assertEquals(762, HLLCounter.intersect(h0, h1, h2, h3)); //about 1000
assertEquals(0, HLLCounter.intersect());
assertEquals(0, HLLCounter.intersect(new HLLCounter(), h0));
} |
a9f3ecee-0f21-4a17-8d4d-8f414f1162b8 | 5 | public boolean containedBy(Box3D box) {
return
(xpos >= box.xpos) &&
(ypos >= box.ypos) &&
(zpos >= box.zpos) &&
(xmax <= box.xmax) &&
(ymax <= box.ymax) &&
(zmax <= box.zmax) ;
} |
816a3902-044c-47fc-9d4a-714cb742df49 | 9 | public SortProgram(String s) {
super(s);
setBounds(500,100,350,450);
setLayout(null);
JLabel laInput = new JLabel("Path to input data file:");
laInput.setBounds(105,10,200,15);
add(laInput);
final JTextField tfInput = new JTextField("");
tfInput.setBounds(55, 35, 220, 25);
tfInput.setFont(new Font("Courier", 0, 12));
add(tfInput);
JRadioButton rbBubble = new JRadioButton("Bubble Sort");
rbBubble.setBounds(65, 80, 150, 15);
add(rbBubble);
rbBubble.setSelected(true);
rbBubble.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
typeOfSort = 1;
}
});
JRadioButton rbInsertion = new JRadioButton("Insertion Sort");
rbInsertion.setBounds(65, 100, 150, 15);
add(rbInsertion);
rbInsertion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
typeOfSort = 2;
}
});
JRadioButton rbBogo = new JRadioButton("Bogo Sort");
rbBogo.setBounds(65, 120, 150, 15);
add(rbBogo);
rbBogo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
typeOfSort = 3;
}
});
ButtonGroup bgFrom = new ButtonGroup();
bgFrom.add(rbBubble);
bgFrom.add(rbInsertion);
bgFrom.add(rbBogo);
JLabel laOutput= new JLabel("Path to output data file:");
laOutput.setBounds(105,150,200,15);
add(laOutput);
final JTextField tfOutput = new JTextField("");
tfOutput.setBounds(55, 175, 220, 25);
tfOutput.setFont(new Font("Courier", 0, 12));
add(tfOutput);
final JTextArea taResult = new JTextArea("");
taResult.setBounds(20, 280, 295, 100);
// Color bg = getBackground();
taResult.setLineWrap(true);
// taResult.setBackground(bg);
taResult.setEditable(false);
add(taResult);
JButton btSort = new JButton ("Sort");
btSort.setBounds(112,230,105,30);
add(btSort);
btSort.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent ae) {
ArrayList aList = new ArrayList<Integer>();
Scanner sc = null;
String inputFile = new String(tfInput.getText().replace("\\", "\\\\"));
String outputFile = new String(tfOutput.getText().replace("\\", "\\\\"));
if (inputFile.isEmpty() || outputFile.isEmpty()) {
taResult.setText("Enter the path to data file");
} else {
try {
sc = new Scanner(new File(inputFile));
while (sc.hasNextInt()) {
aList.add(sc.nextInt());
}
switch (typeOfSort)
{
case 1:
BubbleSort bubble = new BubbleSort();
bubble.sort(aList);
taResult.setText("");
taResult.append("The number of comparisons: "+bubble.getCompareCount()+'\n');
taResult.append("The number of insertions: "+bubble.getInsertCount()+'\n');
taResult.append("The time of sorting: "+bubble.getTimeOfSorting()+" ms"+'\n');
break;
case 2:
InsertionSort insert = new InsertionSort();
insert.sort(aList);
taResult.setText("");
taResult.append("The number of comparisons: "+ insert.getCompareCount()+'\n');
taResult.append("The number of insertions: "+ insert.getInsertCount()+'\n');
taResult.append("The time of sorting: "+ insert.getTimeOfSorting()+" ms"+'\n');
break;
case 3:
BogoSort bogo = new BogoSort();
bogo.sort(aList);
taResult.setText("");
taResult.append("The number of comparisons: "+ bogo.getCompareCount()+'\n');
taResult.append("The number of insertions: "+ bogo.getInsertCount()+'\n');
taResult.append("The time of sorting: "+ bogo.getTimeOfSorting()+" ms"+'\n');
break;
}
try {
PrintWriter pw = new PrintWriter(new File(outputFile));
for (int i = 0; i < aList.size(); i++) {
pw.print(aList.get(i)+" ");
}
pw.flush();
} catch (FileNotFoundException e) {
taResult.setText(e.getMessage());
}
} catch (FileNotFoundException e) {
taResult.setText(e.getMessage());
}
}
}
});
} |
f932b6bc-99c7-4e49-8092-75aa1eda38c8 | 2 | public static int getLastId()
{
String sql = "SELECT idclientes FROM clientes ORDER BY idclientes DESC LIMIT 0,1";
if(!BD.getInstance().sqlSelect(sql)){
return 0;
}
if(!BD.getInstance().sqlFetch()){
return 0;
}
return BD.getInstance().getInt("idclientes");
} |
14d3c4fe-94aa-4672-880b-d1855277658b | 0 | static public int getImageSizeW()
{
return imageSizeW;
} |
23ad89eb-2d67-4e60-aeb9-d5289573b2bc | 0 | public String getWeight() {
return weight;
} |
399fa6c1-6045-44ba-b66e-3c331be5c9ea | 5 | @Override
public void reactToCollision(Entity other, boolean notOnTheEdge)
{
if (Hidable.class.isInstance(other))
hide((Hidable)other);
if (Eatable.class.isInstance(other) && notOnTheEdge)
eat((Eatable)other);
if (Tail.class.isInstance(other) && notOnTheEdge)
examineTail((Tail)other);
} |
83b56312-4baa-4316-8f4b-c1a304d31bfb | 1 | public boolean equals(final Object obj) {
return ((obj instanceof Label) && (((Label) obj).index == index));
} |
21259f58-9c59-4c36-8575-50996c975e58 | 6 | public static Location extractTarget(AIUnit aiUnit, PathNode path) {
if (path == null) return null;
final Unit unit = aiUnit.getUnit();
final Location loc = path.getLastNode().getLocation();
Settlement settlement = (loc == null) ? null : loc.getSettlement();
return (settlement instanceof IndianSettlement
&& invalidIndianSettlementReason(aiUnit,
(IndianSettlement)settlement) == null)
? (IndianSettlement)settlement
: (settlement instanceof Colony
&& invalidColonyReason(aiUnit, (Colony)settlement) != null)
? (Colony)settlement
: null;
} |
f0f43de0-6836-494f-a455-7ed1f9079632 | 6 | public MonthCount(ReadData data) {
storeIDMap = data.getStoreIDMap();
storeCommentMap = data.getStoreCommentMap();
for (String storeID : storeCommentMap.keySet()) {
String type = storeIDMap.get(storeID).getType();
String[] types = type.split(" ");
for (int i = 0; i < types.length; i++) {
type = types[i];
if (!typeMonthCountMap.containsKey(type) ) {
typeMonthCountMap.put(type, new int[13]);
}
ArrayList<Comment> comments = storeCommentMap.get(storeID);
for (Comment tpComment: comments) {
typeMonthCountMap.get(type)[tpComment.getMonth()]++;
totalCounts[tpComment.getMonth()]++;
}
}
}
for (String type:typeMonthCountMap.keySet()) {
int[] monthCounts = typeMonthCountMap.get(type);
System.out.print(type + ":");
for (int i = 1; i <= 12; i++)
System.out.print( Math.round( ((float)monthCounts[i]/(float)totalCounts[i]) *1000) + " ");
System.out.println();
}
} |
01eb02a8-0f38-450a-b0b6-ed8c2f354eb9 | 8 | public static int numpadToY(char num){ //returns the y direction of each keypad input.
switch(num){
case('1'):
return 1;
case('2'):
return 1;
case('3'):
return 1;
case('4'):
return 0;
case('6'):
return 0;
case('7'):
return -1;
case('8'):
return -1;
case('9'):
return -1;
default:
return 0;
}
} |
3b722357-ad09-4e43-84b0-be4d68fed24a | 2 | public static void main(String[] args){
//we make an enhanced for loop.
//we call the class through the object we make
//called sObject. Enumerations make built in arrays
//and we call them as seen down below. values is a key Word
//that can't be changed.
//the sObject loops through the names of the objects or
//constants inside the enumeration class we made, not its data
//inside the parenthesis.
for(SecondaryClass sObject: SecondaryClass.values())
//the format is all strings.
//So we print out the name of the method or constant we're on in the array
//then we run the method to get the description of the constant we're on
//which will go through the constructor we made in the other class.
//then we get the age of the object or constant we're on by also passing through the constructor
//whenever the object is made.
System.out.printf("%s\t%s\t%s\n", sObject, sObject.getDesc(), sObject.getAge());
System.out.println("\nAnd now for the range of constants!!!\n");
//we import the enumSet so we can get a range form enums we want to print out instead of printing out every
//single constant. it takes in two arguments, the from where you want to start, and where
//you want it to end.
for(SecondaryClass sObject : EnumSet.range(SecondaryClass.Vincenzo, SecondaryClass.Lily)){
System.out.printf("%s\t%s\t%s\n", sObject, sObject.getDesc(), sObject.getAge());
}
} |
7e097700-b692-4778-a6cb-f566c92e39df | 3 | public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo mutablePersistenceUnitInfo)
{
try
{
Resource[] resources = resourceLoader.getResources("classpath:"+getPath()); //resourceLoader.getResources("classpath:org/myexample/*.class");
for (Resource resource : resources)
{
CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();
MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
if (metadataReader.getAnnotationMetadata().isAnnotated(javax.persistence.Entity.class.getName()))
{
mutablePersistenceUnitInfo.addManagedClassName(metadataReader.getClassMetadata().getClassName());
}
}
mutablePersistenceUnitInfo.setExcludeUnlistedClasses(true);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
} |
1ec29919-a64a-44fa-8030-486dc1000edd | 4 | public DeckOfCards(int n){
m_size = n;
m_cards = new HashSet<Card>(m_size);
switch(m_size){
case 54: // 54 Cards
m_cards.add(new Card("Joker1",14));
m_cards.add(new Card("Joker2",14));
case 52: // 52 Cards
for(int i=2;i<=6;i++){
m_cards.add(new Card("Carreau",i));
m_cards.add(new Card("Coeur",i));
m_cards.add(new Card("Trèfle",i));
m_cards.add(new Card("Pique",i));
}
default: // 32 Cards
for(int i=7;i<=13;i++){
m_cards.add(new Card("Carreau",i));
m_cards.add(new Card("Coeur",i));
m_cards.add(new Card("Trèfle",i));
m_cards.add(new Card("Pique",i));
}
m_cards.add(new Card("Carreau",1));
m_cards.add(new Card("Coeur",1));
m_cards.add(new Card("Trèfle",1));
m_cards.add(new Card("Pique",1));
break;
}
} |
9d52f0a0-8e45-4ca1-900d-d2c36288d699 | 1 | public static void main(String s[]) throws IOException
{
int denomination[] = { 1, 7, 10 };
//CoinChange cc = new CoinChange(14, denomination);
//System.out.println(cc);
//for (int i = 0; i <= cc.totalAmount; i++)
//System.out.print(cc.n[i] + " ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(br.readLine(), ",");
ArrayList<Integer> arrIntegers = new ArrayList<>();
for(;tokenizer.hasMoreTokens();)
{
arrIntegers.add(Integer.parseInt(tokenizer.nextToken().trim()));
}
int n = Integer.parseInt(br.readLine());
CoinChange cc = new CoinChange(n, Arrays.copyOf(arrIntegers.toArray(), arrIntegers.size(), Integer[].class));
System.out.println(cc.getNCoins());
} |
f5254cfb-6000-4587-b8c2-c5b9d40c42dd | 6 | private void drawToMap(List<RiverSection> sections) {
RiverSection oldSection = null;
for (RiverSection section : sections) {
riverMap.put(section.getPosition(), this);
if (oldSection != null) {
section.setBranch(oldSection.direction.getReverseDirection(),
oldSection.getSize());
}
Tile tile = map.getTile(section.getPosition());
if (tile.isLand()) {
if (section.getSize() >= TileImprovement.FJORD_RIVER) {
TileType greatRiver = map.getSpecification().getTileType("model.tile.greatRiver");
tile.setType(greatRiver);
// changing the type resets the improvements
//container.addRiver(section.getSize(), section.encodeStyle());
logger.fine("Added fjord (magnitude: " + section.getSize() +
") to tile at " + section.getPosition());
} else if (section.getSize() > TileImprovement.NO_RIVER) {
TileItemContainer container = tile.getTileItemContainer();
if (container == null) {
container = new TileItemContainer(tile.getGame(), tile);
tile.setTileItemContainer(container);
}
container.addRiver(section.getSize(), section.encodeStyle());
logger.fine("Added river (magnitude: " + section.getSize() +
") to tile at " + section.getPosition());
}
region.addTile(tile);
oldSection = section;
}
}
} |
c9574855-1d4d-4141-928d-9f9174f3151e | 1 | @Override
public void render() {
glPushMatrix();
{
glTranslatef(getParent().getPosition().getX(),getParent().getPosition().getY(),0);
for(Particle p:particles){
p.render();
}
}
glPopMatrix();
} |
3bd5f21b-e5b2-4c79-8000-93dcbed88404 | 0 | public static void initialiseGUI() {
gui = new GUI(testWorld);
gui.initaliseWorldMap(testWorld, 0, 0);
} |
732ebe0b-6566-4bbe-9c6a-ec49f9ab36f4 | 5 | public Util(String[] args) {
if (args.length > 0) parseArguments(args);
filePath = (filePath != null ? filePath : null);
format = (format != null ? format : Arguments.FORMAT_CSV);
sudokuSize = (sudokuSize != null ? sudokuSize : Arguments.SIZE_9x9);
folderPath = (folderPath != null ? folderPath : new String("SudokuBoards/hard3.sudoku"));
System.out.println("Sudoku Size: " + sudokuSize);
System.out.println("FolderPath: " + folderPath);
System.out.println("FilePath: " + filePath);
System.out.println("Format: " + format);
} |
7c505e98-6ef9-40f7-a5b9-a7fe61d048ac | 1 | private static int createPNG(StdImage image, List<byte[]> imageData, List<Integer> imageType, int type, int dpi) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!StdImage.writePNG(baos, image, dpi)) {
throw new IOException(UNABLE_TO_CREATE_PNG);
}
byte[] bytes = baos.toByteArray();
imageData.add(bytes);
imageType.add(Integer.valueOf(type));
return 8 + bytes.length;
} |
a0160bbf-7330-4f52-ba64-632c8435fdfb | 7 | @Override
public void draw(Graphics2D g) {
g.drawImage(Images.loadImage("/gui/crafting.png").getSubimage(0, 0, 96, 106), centerX - (96/2), centerY - (106/2),96,106,null);
for(Button b : buttonList){
b.draw(g);
}
for(int slot = 0; slot < player.getInventory().getItems().length; slot++){
ItemStack i = player.getStackInSlot(slot);
if(i != null){
int x = slot < 5 ? (centerX - 40) + (slot*getSlotSpacingX()) : (centerX - 40) + ((slot-5)*getSlotSpacingX());
int y = slot < 5 ? centerY + 19 : centerY + 19 + getSlotSpacingY();
i.getItem().draw(g, x, y, i);
}
}
int i = 0;
for(ItemStack stack : Crafting.getRecipe(slot_index)){
if(stack != null){
stack.getItem().draw(g, centerX + 51 + ((i%3)*getSlotSpacingX()), centerY - 45 + ((i/3)*getSlotSpacingY()), stack);
i++;
}
}
super.draw(g);
} |
ccb29680-954b-44a0-b396-8fe9cae446db | 7 | public static void main(String[] args) {
int limit = 28123;
ArrayList<Integer> abundantNums = new ArrayList<Integer>();
for (int i = 1; i < limit; i++)
if (abundant(i))
abundantNums.add(i);
int numSumOfAbundant;
boolean[] sumOfAbundant = new boolean[limit + 1];
for (int i = 0; i < abundantNums.size(); i++)
for (int j = i; j < abundantNums.size(); j++) {
numSumOfAbundant = abundantNums.get(i) + abundantNums.get(j);
if (numSumOfAbundant <= limit)
sumOfAbundant[numSumOfAbundant] = true;
else
break;
}
int sum = 0;
for (int i = 0; i < sumOfAbundant.length; i++)
if (!sumOfAbundant[i])
sum += i;
System.out.println(sum);
// Solution: 4179871
} |
26dc7bce-e1b4-45ab-8694-5d66b8244cc1 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TipoLogradouro other = (TipoLogradouro) obj;
if (this.idTipoLogradouro != other.idTipoLogradouro && (this.idTipoLogradouro == null || !this.idTipoLogradouro.equals(other.idTipoLogradouro))) {
return false;
}
return true;
} |
16379b22-e032-452c-8283-739a07bcc770 | 9 | private int findRelevantElement(StackTraceElement[] trace) {
if (trace.length == 0) {
return -1;
} else if (included.size() == 0) {
return 0;
}
int firstIncluded = -1;
for (String myIncluded : included) {
for (int i = 0; i < trace.length; i++) {
StackTraceElement ste = trace[i];
if (ste.getClassName().startsWith(myIncluded)) {
if (i < firstIncluded || firstIncluded == -1) {
firstIncluded = i;
break;
}
}
}
}
if (firstIncluded >= 0 && trace[firstIncluded].getClassName().equals("net.sf.odinms.tools.performance.CPUSampler$SamplerThread")) { // don't sample us
return -1;
}
return firstIncluded;
} |
064fe0f0-2928-4246-8808-492c80e827d0 | 6 | */
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Sims_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Sims_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Sims_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Sims_1.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 Sims_1().setVisible(true);
}
});
} |
f2ca4521-352a-4d3a-a77d-de1aff1b6752 | 2 | private int getSiblingIndex(final int index) {
if (index == 0) {
return 0;
}
if (index % 2 == 0) {
return getLeftChildIndex(getParentIndex(index));
} else {
return getRightChildIndex(getParentIndex(index));
}
} |
c339ba74-89aa-45a8-aa9e-68630d435a94 | 6 | public void selectRegion(Region regionToSelect)
{
// ONLY LOOK FOR IT IF IT EXISTS
if (worldDataManager.hasRegion(regionToSelect))
{
LinkedList<Region> pathToRegion = worldDataManager.getPathFromRoot(regionToSelect);
DefaultMutableTreeNode walker = (DefaultMutableTreeNode)worldTreeModel.getRoot();
boolean regionFound = false;
int pathIndex = 0;
while (!regionFound)
{
Region testRegion = (Region)walker.getUserObject();
if (testRegion.getId().equals(regionToSelect.getId()))
{
// SELECT THIS NODE
TreePath pathToWalker = new TreePath(walker.getPath());
worldTree.setSelectionPath(pathToWalker);
regionFound = true;
}
// LOOK THROUGH THE CHILD NODES FOR THE NEXT ONE
else
{
DefaultMutableTreeNode testNode;
boolean childFound = false;
for (int i = 0; i < walker.getChildCount() && !childFound; i++ )
{
testNode = (DefaultMutableTreeNode)walker.getChildAt(i);
testRegion = (Region)testNode.getUserObject();
Region testChild = pathToRegion.get(pathIndex + 1);
if (testRegion.getId().equals(testChild.getId()))
{
childFound = true;
walker = testNode;
}
}
pathIndex++;
}
}
TreeNode[] pathToRoot = worldTreeModel.getPathToRoot(walker);
TreePath path = new TreePath(pathToRoot);
worldTree.setSelectionPath(path);
}
} |
ebe1f845-d1c3-4c70-a300-f4810c202d17 | 9 | public List<Location> adjacentLocations(Location location) {
assert location != null : "Null location passed to adjacentLocations";
// The list of locations to be returned.
List<Location> locations = new LinkedList<Location>();
if (location != null) {
int row = location.getRow();
int col = location.getCol();
for (int roffset = -1; roffset <= 1; roffset++) {
int nextRow = row + roffset;
if (nextRow >= 0 && nextRow < depth) {
for (int coffset = -1; coffset <= 1; coffset++) {
int nextCol = col + coffset;
// Exclude invalid locations and the original location.
if (nextCol >= 0
&& nextCol < width
&& (roffset != 0 || coffset != 0)){
locations.add(new Location(nextRow, nextCol));
}
}
}
}
// Shuffle the list. Several other methods rely on the list
// being in a random order.
Collections.shuffle(locations, rand);
}
return locations;
} |
c7910834-4997-415a-8584-cc89142b9a1f | 0 | public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.black);
g.drawLine(x, y + height / 2, x + width, y + height / 2);
g.drawLine(x + width - height / 2, y, x + width, y + height / 2);
g.drawLine(x + width - height / 2, y + height, x + width, y + height
/ 2);
} |
5658df52-0308-40c0-8ef6-dea949dbfda6 | 1 | public boolean IsEmpty(int colonne, int rangee){
if(coordoneeJeu.get(rangee)[colonne]==false){
return true;
}
else{
return false;
}
} |
f5846f40-2f5d-4012-855d-5efc0403276d | 6 | public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (end()) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
} |
6dec677f-dae6-40f0-a3e3-3398272750ac | 0 | @Override
public int hashCode() {
return id;
} |
4e332989-f187-454f-bfa6-6b66aac2c0be | 9 | public void renderLight(Screen screen, int xScroll, int yScroll) {
int xo = xScroll >> 4;
int yo = yScroll >> 4;
int w = (screen.w + 15) >> 4;
int h = (screen.h + 15) >> 4;
screen.setOffset(xScroll, yScroll);
int r = 4;
for (int y = yo - r; y <= h + yo + r; y++) {
for (int x = xo - r; x <= w + xo + r; x++) {
if (x < 0 || y < 0 || x >= this.w || y >= this.h) continue;
List<Entity> entities = entitiesInTiles[x + y * this.w];
for (int i = 0; i < entities.size(); i++) {
Entity e = entities.get(i);
// e.render(screen);
int lr = e.getLightRadius();
if (lr > 0) screen.renderLight(e.x - 1, e.y - 4, lr * 8);
}
int lr = getTile(x, y).getLightRadius(this, x, y);
if (lr > 0) screen.renderLight(x * 16 + 8, y * 16 + 8, lr * 8);
}
}
screen.setOffset(0, 0);
} |
1964ead7-8dc0-41f5-85aa-64c78cb3c240 | 8 | @Override
public boolean tick(Tickable ticking, int tickID)
{
Item I=null;
if(affected instanceof Item)
I=(Item)affected;
if((canBeUninvoked())&&(I!=null)&&(I.owner() instanceof MOB)
&&(I.amWearingAt(Wearable.WORN_NECK)))
{
final MOB mob=(MOB)I.owner();
if((!mob.amDead())
&&(mob.isMonster())
&&(CMLib.flags().isInTheGame(mob,false)))
CMLib.commands().postRemove(mob,I,false);
}
return super.tick(ticking,tickID);
} |
69004c33-9806-4926-97c1-593a0f6223ca | 8 | private boolean processFields() {
//
// Validate the category information
//
int type = categoryType.getSelectedIndex();
if (type < 0) {
JOptionPane.showMessageDialog(this, "You must select a category type",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
type = categoryTypeModel.getTypeAt(type);
String name = categoryName.getText();
if (name.length() == 0) {
JOptionPane.showMessageDialog(this, "You must specify a category name",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
for (CategoryRecord c : CategoryRecord.categories) {
if (name.equals(c.getName()) && c != category) {
JOptionPane.showMessageDialog(this, "Category name '"+name+"' is already in use",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
//
// Create a new category or update an existing category
//
if (category == null) {
category = new CategoryRecord(name, type);
category.setHide(categoryHidden.isSelected());
if (CategoryRecord.categories.contains(category)) {
JOptionPane.showMessageDialog(this, "Category '"+name+"' already exists",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
CategoryRecord.categories.add(category);
listModel.addDBElement(category);
} else {
if (!category.getName().equals(name)) {
CategoryRecord.categories.remove(category);
category.setName(name);
CategoryRecord.categories.add(category);
}
category.setType(type);
category.setHide(categoryHidden.isSelected());
listModel.updateDBElement();
}
Main.dataModified = true;
return true;
} |
8a2af8e4-7a74-48d0-a349-366c9a683dee | 2 | public boolean opEquals(Operator o) {
return o instanceof StoreInstruction
&& o.operatorIndex == operatorIndex && o.isVoid() == isVoid();
} |
6b8df336-d38e-43f3-86fa-14c451b6a2eb | 2 | public Font newFont(float size) {
Font font = null;
InputStream is = null;
is = StageShop.class.getResourceAsStream("/fonts/Perfect DOS VGA 437 Win.ttf");
// is = StageShop.class.getResourceAsStream("/fonts/BMgermar.ttf");
// is = StageShop.class.getResourceAsStream("/fonts/Minecraftia.ttf");
try {
font = Font.createFont(Font.TRUETYPE_FONT, is);
font = font.deriveFont(Font.PLAIN, size);
} catch (FontFormatException e) {
} catch (IOException e) {
}
return font;
} |
3f9629a6-f5a5-400e-96a7-29f02eb2a159 | 5 | void joinChannel(String cname, Client client) {
if (checkForChannel(cname)) {
Channel c = getChannelByName(cname);
try {
clients.remove(client);
} catch (Exception e) {
e.printStackTrace();
}
if (c.checkUser(client) == false) {
c.addUser(client);
c.sendChannelMSG(":" + client.getName() + "!" + client.getName() + "@" + client.getIP() + " JOIN " + "#" + cname);
c.sendChannelMSG(":" + client.getName() + " MODE " + client.getName() + " :" + "+i");
client.setMode("+i");
}
} else {
Channel c = getChannelByName(cname);
try {
clients.remove(client);
} catch (Exception e) {
e.printStackTrace();
}
if (c.checkUser(client) == false) {
c.addUser(client);
c.sendChannelMSG(":" + client.getName() + "!" + client.getName() + "@" + client.getIP() + " JOIN " + "#" + cname);
c.sendChannelMSG(":" + client.getName() + " MODE " + client.getName() + " :" + "+i");
client.setMode("+i");
}
}
} |
842c036b-17ef-403e-925a-cb15af4a4d84 | 1 | public void setLeaseDurationMilliseconds(final long leaseDurationMilliseconds) {
//// Preconditions
if (leaseDurationMilliseconds < 2000) {
throw new InvalidParameterException("leaseDurationMilliseconds must be at least 2000");
}
this.leaseDurationMilliseconds = leaseDurationMilliseconds;
} |
b8157b85-0823-4a96-9114-a12ba6d88372 | 1 | public static Item getItemSomething(String name){
// get item
Item item = ItemStorageInventory.create().getItemfromStorage(name);
if(item != null)
System.out.println("you just get "+ item + " from item list \n");
else
System.out.println("getting "+ item + " failed\n");
return item;
} |
b6d0dd98-c505-470a-9f25-5e343b8ff988 | 3 | private void formPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_formPropertyChange
if (evt.getPropertyName().equals("LataaTyopaivat")) {
if (palkanlaskenta.getProfiili() != null) {
malli.clear();
this.tyopaivat = palkanlaskenta.getProfiili().getTyopaivat();
for (int i = 0; i < tyopaivat.size(); i++) {
malli.addElement(tyopaivat.get(i));
}
}
}
}//GEN-LAST:event_formPropertyChange |
8702ea4e-b201-4440-aa3f-65ec0af2f78b | 7 | private static int partition(int[] array, int start, int end) {
int randomIdx = new Random().nextInt(end-start+1)+start;
// Switch first item with the one of randomIdx
int tmp = array[start];
array[start] = array[randomIdx];
array[randomIdx] = tmp;
int piovtV = array[start];
while(start<end) {
while(start<end && array[end]>=piovtV) {end--;}
if(start<end) {array[start++] = array[end];}
while(start<end && array[start]<piovtV) {start++;}
if(start<end) {array[end--] = array[start];}
}
array[start] = piovtV;
return start;
} |
b001abf2-6d92-4b67-b59a-fc757d572221 | 8 | @Override
public void update(double time_difference) {
// TODO Auto-generated method stub
if(host.ip != null){
clientIP = host.ip;
clientName = host.clientName;
Server server = new Server();
}else{
clientIP = null;
clientName = null;
}
switch (connection.getStatus()){
case STATUS_IDLE:
if(host.ip != null){
connection.connect(host.ip.getHostAddress(), tcpConnection.TCP_PORT);
}
break;
case STATUS_TRAINING: break;
case STATUS_ALIVE:
//advance to multiplayer
main.closeScene();
main.setScene(new scn.Multiplayer(main,difficulty,connection,1));
break;
case STATUS_FAILED:
//reset host variables; enable button
host.ip = null;
host.clientName = null;
if(buttons != null){
for (lib.ButtonText button : buttons) {
button.setAvailability(true);
}
}
connection = new tcpConnection(true);
break;
}
} |
534c4f08-407b-4bb2-a3ea-b9d1b4fdf8f7 | 3 | boolean isDirect(char c) {
return c < 0x80 && (D_SET[c] || (optionalDirect && O_SET[c]));
} |
58299e14-ed8c-482f-be59-7af7b936ee0f | 3 | public GerarBackup(){
File diretorio = new File(pasta);
File bck = new File(arq);
if (!diretorio.isDirectory()) {
System.out.println("Não Existe!");
new File(pasta).mkdir();
} else {
System.out.println("Existe!");
}
// Cria Arquivo de Backup
try {
if (!bck.isFile()) {
System.out.println("Arquivo Não Existe!");
String comando = "C:/Program Files/MySQL/MySQL Server 5.5/bin/mysqldump.exe";
ProcessBuilder pb = new ProcessBuilder(comando, "--user=root", "--password=sistemaacic!@#", "audizio", "--result-file="+arq);
pb.start();
JOptionPane.showMessageDialog(null, "Cópia de segurança realizada com sucesso\nLOCAL: "+arq, "Backup", JOptionPane.CLOSED_OPTION);
} else {
System.out.println("Arquivo Existe!");
JOptionPane.showMessageDialog(null, "Você já realizou o backup hoje!\nLOCAL: "+arq, "Backup", JOptionPane.CLOSED_OPTION);
//dispose();
}
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Copia de segurança não realizada!", "Backup", JOptionPane.CLOSED_OPTION);
}
} |
37e1ae6c-cfc4-456f-acdf-dc116a8bdc6a | 2 | public void tick(long delta) {
switch(gameType) {
case 0:
zoneArray[currentZoneX][currentZoneY].tick(delta);
break;
case 1:
break;
}
} |
d6f6e93a-a202-4036-8b20-e7b4840f4c6d | 9 | public void removeFoundNode(AvlNode q) {
AvlNode r;
// at least one child of q, q will be removed directly
if (q.left == null || q.right == null) {
// the root is deleted
if (q.parent == null) {
if (q.left != null)
this.root = q.left;
else if (q.right != null)
this.root = q.right;
else
this.root = null;
return;
}
r = q;
} else {
// q has two children --> will be replaced by successor
r = successor(q);
q.element = r.element;
}
AvlNode p;
if (r.left != null) {
p = r.left;
} else {
p = r.right;
}
if (p != null) {
p.parent = r.parent;
}
if (r.parent == null) {
this.root = p;
} else {
if (r == r.parent.left) {
r.parent.left = p;
} else {
r.parent.right = p;
}
// balancing must be done until the root is reached.
recursiveheight(r.parent);
}
r = null;
} |
b07dee50-0583-4a01-b6d6-15cddc6ca7d1 | 8 | public static void main(String[] args) {
try{
int i = 0; // счетчик подключений
ServerSocket server = new ServerSocket(SERVER_PORT);// слушаем порт 1234
Socket socket;
while(true) {
socket = server.accept();
if (getNumberOfUsers() < MAX_NUMBER_OF_USERS) {
String name;
System.out.println("Trying to connect");
(new BufferedReader(new InputStreamReader(socket.getInputStream()))).readLine();
while (true) {
name = (new BufferedReader(new InputStreamReader(socket.getInputStream()))).readLine();
if (!checkUserNamePassword(name)){
say(socket,"Wrong password, try again.");
say(socket,"Enter your name:");
continue;
}else {
name = name.substring(0,name.indexOf(":"));
}
if (checkName(name)) {
say(socket, "OK");
break;
} else {
say(socket, "This name is already taken. Try another:");
}
}
i++;
new Server(getNewUser(name, socket), socket, name);
if (messageKeeper.getMessages() != null) {
say(socket, "------------------");
say(socket, "Previous comments:");
for (String s : messageKeeper.getMessages()) {
say(socket, s);
}
say(socket, "------------------");
}
System.out.println("New client: number " + i + ", Name: " + name);
}else {
new CancelServer(socket);
}
}
} catch(Exception e){
e.printStackTrace();
}
} |
3b6e1a79-da60-4853-a765-e31363bc42e1 | 4 | public void addASReplica(XmlNode node, XmlNode replicanode) {
if (node == null || replicanode == null)
return;
List<XmlNode> list = ASreplicsMap.get(node);
if (list != null) {
if (!list.contains(replicanode))
list.add(replicanode);
}
else {
list = new ArrayList<XmlNode>();
list.add(replicanode);
ASreplicsMap.put(node, list);
}
} |
8dbb9201-1ae3-4537-97d2-6df8e3a0fb8f | 0 | public void setEmail(String s)
{
EMAIL = s;
} |
3356d1b7-ea3b-42e2-98b9-d046def8ed84 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MenuWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MenuWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MenuWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MenuWindow.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 MenuWindow().setVisible(true);
}
});
} |
29c43955-e6da-4a97-9864-981d384016ae | 2 | public void swapCards(CardComponent card1, CardComponent card2) {
int index1 = this.getSubComponentIndex(card1);
int index2 = this.getSubComponentIndex(card2);
if (index1 < 0 || index2 < 0) {
return;
}
this.getSlot(index1).unSocket();
this.getSlot(index2).unSocket();
this.swapSubComponents(card1, card2);
card1.trackTarget(this.getSlot(index2));
card2.trackTarget(this.getSlot(index1));
} |
13398bba-ee65-4ab0-aa8c-707c9b314a5e | 7 | private static void setCommonAttributes(EmailDetailsDto emailDto, MultiPartEmail email) throws EmailException, SwingObjectException {
email.setHostName(SwingObjProps.getSwingObjProperty("emailsmtp"));
email.setAuthenticator(new DefaultAuthenticator(emailDto.getEmailID(),emailDto.getPassword()));
email.setFrom(emailDto.getEmailID(), emailDto.getFromName());
email.setDebug(true);
email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
try {
if(emailDto.getTo().indexOf(",")!=-1){
String[] splitTo=emailDto.getTo().split(",");
for(String emailTo : splitTo){
email.addTo(emailTo.trim());
}
}else{
email.addTo(emailDto.getTo().trim());
}
if (emailDto.getCc()!=null) {
if (emailDto.getCc().indexOf(",") != -1) {
String[] splitCC = emailDto.getCc().split(",");
for (String emailCC : splitCC) {
email.addCc(emailCC.trim());
}
} else {
email.addCc(emailDto.getCc().trim());
}
}
}catch(EmailException e) {
throw new SwingObjectException("swingobj.email.checkto",e,ErrorSeverity.ERROR, EmailHelper.class);
}
email.setSubject(emailDto.getSubj()==null?"":emailDto.getSubj());
} |
fd7fb3ee-34b8-4f1f-9327-c06cc3a7171f | 6 | public static void main(String[] args) {
// This counts how many people we had to check
int counter = 0;
// This is the index of the array we update
int index;
// array to contain ALL THE BIRTHDAYS
int[] daysOfYear = new int[365];
// Used to test if its possible for three birthdays to be consecutive up
// to index.
boolean consecutiveBirthdays = false;
do {
index = (int) (Math.random() * 365);
daysOfYear[index]++;
counter++;
} while (daysOfYear[index] < 3);
// Three consecutive birthdays???
// FIX!!!!
do {
index = (int) (Math.random() * 365);
daysOfYear[index]++;
counter++;
if (index >= 2) {
if (daysOfYear[index] >= 1 && daysOfYear[index - 1] >= 1
&& daysOfYear[index - 2] >= 1) {
consecutiveBirthdays = true;
}
}
} while (!consecutiveBirthdays);
// The final Output.
System.out.println("It took " + counter
+ " times to find 3 people with the same birthday");
} |
1dde6f07-c58a-4a49-b52a-8b236151d611 | 7 | private TypeMirror getTypeMirror() {
String methodName = getMethodName();
if (methodName.startsWith("get") || methodName.startsWith("is")) {
List<? extends VariableElement> params = element.getParameters();
if (params.isEmpty()) {
return element.getReturnType();
}
} else if (methodName.startsWith("set")) {
List<? extends VariableElement> params = element.getParameters();
if (params.size() == 1) {
VariableElement param = params.iterator().next();
return param.asType();
}
}
throw new IllegalStateException();
} |
8fd012b9-0c97-4401-a7a5-13d9a9d29ec5 | 9 | public static long S5(){
long numS5 = 0;
// S5: No student should write exams with no break between them
for(Student s : Environment.get().students.objects()){
for(Lecture l1 : s.lectures){
if(l1.session == null) continue;
for(Lecture l2 : s.lectures){
if(l2.session == null) continue;
// lecture session days should not be null!
assert l1.session.day != null;
assert l2.session.day != null;
// student attends two different lectures with exams on the same day
if(l1 != l2 && l1.session.day.equals(l2.session.day)){
// lecture session times should never be null!
assert l1.session.time != null;
assert l2.session.time != null;
if(l1.session.time <= l2.session.time){
// examlength cannot be null
assert l1.examLength != null;
// next exam starts without break!
if(l1.examLength + l1.session.time == l2.session.time){
//System.out.println("Found S5: " + l1.getName() + " " + l2.getName());
numS5++;
}
}
}
}
}
}
return numS5;
} |
8d8410b4-d0c4-4eef-9a08-006edbbdfe4d | 9 | public static Equation GenRndEquation(int numOperators){
//Create arrayList of expressions
ArrayList<Expression> eList = new ArrayList<Expression>();
//Create a random
Random rnd = new Random();
//Add a first numerical expression to equationList (First thing in an equation must be a number)
eList.add(new NumericalExpression(rnd.nextInt(10) + 1));
//For each proceeding operator
for(int i = 0; i < numOperators; i++){
//Choose an operator
int opChoice = rnd.nextInt(4);
//Declare a variable for the operator expression
OperatorExpression o = null;
//Declare variable for second random numerical expression
NumericalExpression e2 = null;
//Add that operator to the list
switch(opChoice){
case 0:
//SEt operator
o = new AdditionExpression();
break;
case 1:
//Set operator
o = new SubtractionExpression();
break;
case 2:
//SEt operator
o = new MultiplicationExpression();
break;
case 3:
//If division, find every factor of the first numerical expression
ArrayList<Integer> validDivisors = new ArrayList<Integer>();
for(int j = 1; j <= eList.get(eList.size() - 1).evaluate(); j++){
if(eList.get(eList.size() - 1).evaluate() % j == 0){
//If e1 % j == 0, j is a factor of e1 and should be added to the list
validDivisors.add(j);
}
}
//Set o
o = new DivisionExpression();
//CHoose random e2
int randE2Index = rnd.nextInt(validDivisors.size());
//Create e2
e2 = new NumericalExpression(validDivisors.get(randE2Index));
break;
default:
//Shit went down
break;
}
//Create e2 (if not already created)
if(e2 == null){
e2 = new NumericalExpression(rnd.nextInt(10));
}
//Add operator
eList.add(o);
//Add a final numericalexpression
eList.add(e2);
}
//Declare a returnEquation
Equation returnEquation;
try{
returnEquation = new Equation(eList);
}
catch(InvalidEquationException iEE){
//If the equation is invalid, make another?
System.out.println("From generating a random equation: " + iEE.getMessage());
returnEquation = GenRndEquation(numOperators);
}
//Return a put together equation
return returnEquation;
} |
614b6b9b-983e-492a-b397-8f4c28e1dee7 | 1 | public synchronized void take() throws InterruptedException {
while (taken)
wait();
taken = true;
} |
d8654462-7db5-4283-9a15-a475714840b8 | 1 | private void calculateMinMax() {
double[] minFlows = new double[flows.length];
double[] maxFlows = new double[flows.length];
for (int i = 0; i < flows.length; i++) {
minFlows[i] = flows[i].getMin();
maxFlows[i] = flows[i].getMax();
}
this.min = NetPresentValue.npv(minFlows, rate.getMax());
this.max = NetPresentValue.npv(maxFlows, rate.getMin());
} |
5c03cfe1-e60f-441b-afab-868ced8f0634 | 0 | @Column(name = "NOV_AAAAMM")
@Id
public Integer getNovAaaamm() {
return novAaaamm;
} |
bc03d7b2-f1d9-49f5-b13f-28eeb0375f2d | 2 | public void checkDead() {
ArrayList<Fish> fishies2 = new ArrayList<Fish>();
for (Fish a : fishies) {
if (a.getHealth() <= 0) {
fishies2.add(a);
}
}
fishies.removeAll(fishies2);
} |
f70d79d2-96e6-4d2f-8a71-b640f05a8eef | 2 | public static void print(PrintProxy proxy) {
if (proxy != null) {
PrintManager mgr = proxy.getPrintManager();
if (mgr != null) {
mgr.print(proxy);
} else {
WindowUtils.showError(UIUtilities.getComponentForDialog(proxy), NO_PRINTER_SELECTED);
}
}
} |
39a2d4d0-b126-40c6-a47c-0e591174baae | 8 | public ImageStore () {
MinuetoImage tileImage;
MinuetoImage tempImage;
URL imageLocation;
MinuetoFont arial64B = new MinuetoFont("Arial",64,true,false);
MinuetoFont arial40B = new MinuetoFont("Arial",32,true,false);
this.imageDatabase = new MinuetoImage[128];
try {
imageLocation = this.getClass().getResource("1945.png");
if (imageLocation != null) {
tileImage = new MinuetoImageFile(imageLocation);
} else {
tileImage = new MinuetoImageFile("images/1945.png");
}
} catch (MinuetoFileException mfe) {
System.err.println("Could not load image file.");
System.exit(-1);
return;
}
try {
imageLocation = this.getClass().getResource("title.png");
if (imageLocation != null) {
imageDatabase[TITLE_BG] = new MinuetoImageFile(imageLocation);
} else {
imageDatabase[TITLE_BG] = new MinuetoImageFile("images/title.png");
}
} catch (MinuetoFileException mfe) {
System.err.println("Could not load title image file.");
System.exit(-1);
return;
}
this.imageDatabase[MAP_TILE2] = tileImage.crop(103,499,64,64);
this.imageDatabase[MAP_TILE3] = tileImage.crop(168,499,64,64);
this.imageDatabase[MAP_TILE4] = tileImage.crop(233,499,64,64);
this.imageDatabase[MAP_TILE1] = new MinuetoImage(64,64);
tempImage = tileImage.crop(268,235,32,32);
this.imageDatabase[MAP_TILE1].draw(tempImage, 0,0);
this.imageDatabase[MAP_TILE1].draw(tempImage, 0,32);
this.imageDatabase[MAP_TILE1].draw(tempImage, 32,0);
this.imageDatabase[MAP_TILE1].draw(tempImage, 32,32);
this.imageDatabase[PLAYER_PLANE1] = tileImage.crop(301,104,64,64);
this.imageDatabase[PLAYER_LIFE] = tileImage.crop(136,202,32,32);
this.imageDatabase[ENEMY_PLANE_SMALL1] = tileImage.crop(136,70,32,32);
for (int i = 1; i < 16; i++) {
this.imageDatabase[ENEMY_PLANE_SMALL1+i] =
this.imageDatabase[ENEMY_PLANE_SMALL1].rotate((Math.PI * i) / 8.0);
}
this.imageDatabase[ENEMY_PLANE_SMALL2] = tileImage.crop(136,4,32,32);
for (int i = 1; i < 16; i++) {
this.imageDatabase[ENEMY_PLANE_SMALL2+i] =
this.imageDatabase[ENEMY_PLANE_SMALL2].rotate((Math.PI * i) / 8.0);
}
this.imageDatabase[ENEMY_PLANE_SMALL3] = tileImage.crop(136,103,32,32);
for (int i = 1; i < 16; i++) {
this.imageDatabase[ENEMY_PLANE_SMALL3+i] =
this.imageDatabase[ENEMY_PLANE_SMALL3].rotate((Math.PI * i) / 8.0);
}
this.imageDatabase[ENEMY_PLANE_BOSS] = tileImage.crop(598,4,98,98);
for (int i = 1; i < 16; i++) {
this.imageDatabase[ENEMY_PLANE_BOSS+i] =
this.imageDatabase[ENEMY_PLANE_BOSS].rotate((Math.PI * i) / 8.0);
}
this.imageDatabase[SUBMARINE] = new MinuetoImage(64,128);
this.imageDatabase[SUBMARINE].draw(this.imageDatabase[MAP_TILE1], 0,0);
this.imageDatabase[SUBMARINE].draw(this.imageDatabase[MAP_TILE1], 0,64);
this.imageDatabase[SUBMARINE+1] = this.imageDatabase[SUBMARINE].crop(0,0,64,64);
this.imageDatabase[SUBMARINE+2] = this.imageDatabase[SUBMARINE].crop(0,0,64,64);
this.imageDatabase[SUBMARINE+3] = this.imageDatabase[SUBMARINE].crop(0,0,64,64);
this.imageDatabase[SUBMARINE+4] = this.imageDatabase[SUBMARINE].crop(0,0,64,64);
this.imageDatabase[SUBMARINE+5] = this.imageDatabase[SUBMARINE].crop(0,0,64,64);
tempImage = tileImage.crop(367,103,31,97);
this.imageDatabase[SUBMARINE].draw(tempImage, 15,15);
tempImage = tileImage.crop(400,103,31,97);
this.imageDatabase[SUBMARINE+1].draw(tempImage, 15,15);
tempImage = tileImage.crop(433,103,31,97);
this.imageDatabase[SUBMARINE+2].draw(tempImage, 15,15);
tempImage = tileImage.crop(466,103,31,97);
this.imageDatabase[SUBMARINE+3].draw(tempImage, 15,15);
tempImage = tileImage.crop(499,103,31,97);
this.imageDatabase[SUBMARINE+4].draw(tempImage, 15,15);
tempImage = tileImage.crop(532,103,31,97);
this.imageDatabase[SUBMARINE+5].draw(tempImage, 15,15);
this.imageDatabase[DESTROYER] = new MinuetoImage(64,256);
this.imageDatabase[DESTROYER].draw(this.imageDatabase[MAP_TILE1], 0,0);
this.imageDatabase[DESTROYER].draw(this.imageDatabase[MAP_TILE1], 0,64);
this.imageDatabase[DESTROYER].draw(this.imageDatabase[MAP_TILE1], 0,128);
this.imageDatabase[DESTROYER].draw(this.imageDatabase[MAP_TILE1], 0,192);
this.imageDatabase[DESTROYER+1] = this.imageDatabase[DESTROYER].crop(0,0,64,64);
tempImage = tileImage.crop(466,301,40,196);
this.imageDatabase[DESTROYER].draw(tempImage, 12, 30);
tempImage = tileImage.crop(508,301,40,196);
this.imageDatabase[DESTROYER+1].draw(tempImage, 12, 30);
this.imageDatabase[PLAYER_BULLET] = tileImage.crop(37,169,32,32);
this.imageDatabase[PLAYER_LARGE_BULLET] = tileImage.crop(4,169,32,32);
this.imageDatabase[SMALL_BULLET] = tileImage.crop(70,202,32,32);
this.imageDatabase[POWERUP_WEAPON] = tileImage.crop(103,268,32,32);
this.imageDatabase[POWERUP_ARMOR] = tileImage.crop(136,268,32,32);
this.imageDatabase[POWERUP_LIFE] = tileImage.crop(202,268,32,32);
this.imageDatabase[BOMB] = tileImage.crop(268,268,32,32);
this.imageDatabase[EXPLOSION_SMALL1] = tileImage.crop(70,169,32,32);
this.imageDatabase[EXPLOSION_SMALL2] = tileImage.crop(103,169,32,32);
this.imageDatabase[EXPLOSION_SMALL3] = tileImage.crop(136,169,32,32);
this.imageDatabase[EXPLOSION_SMALL4] = tileImage.crop(169,169,32,32);
this.imageDatabase[EXPLOSION_SMALL5] = tileImage.crop(202,169,32,32);
this.imageDatabase[EXPLOSION_SMALL6] = tileImage.crop(235,169,32,32);
this.imageDatabase[EXPLOSION_BIG1] = tileImage.crop(4,301,64,64);
this.imageDatabase[EXPLOSION_BIG2] = tileImage.crop(70,301,64,64);
this.imageDatabase[EXPLOSION_BIG3] = tileImage.crop(136,301,64,64);
this.imageDatabase[EXPLOSION_BIG4] = tileImage.crop(202,301,64,64);
this.imageDatabase[EXPLOSION_BIG5] = tileImage.crop(268,301,64,64);
this.imageDatabase[EXPLOSION_BIG6] = tileImage.crop(334,301,64,64);
this.imageDatabase[GAMEOVER]
= new MinuetoText("Game Over", arial64B, MinuetoColor.WHITE);
this.imageDatabase[TITLE]
= new MinuetoText("Fire In the Sky", arial64B, MinuetoColor.WHITE);
this.imageDatabase[TITLE_SHADOW]
= new MinuetoText("Fire In the Sky", arial64B, new MinuetoColor(10,10,10));
this.imageDatabase[PRESS_START]
= new MinuetoText("Press Space to Play", arial40B, MinuetoColor.WHITE);
this.imageDatabase[PRESS_START_SHADOW]
= new MinuetoText("Press Space to Play", arial40B, new MinuetoColor(10,10,10));
this.imageDatabase[MISSION_SUCCESS]
= new MinuetoText("Mission Success!", arial64B, MinuetoColor.WHITE);
this.mapDatabase = new MinuetoImage[4];
this.mapDatabase[0] = this.imageDatabase[MAP_TILE1];
this.mapDatabase[1] = this.imageDatabase[MAP_TILE2];
this.mapDatabase[2] = this.imageDatabase[MAP_TILE3];
this.mapDatabase[3] = this.imageDatabase[MAP_TILE4];
} |
a096cd23-4b30-4740-927b-b3ce12816bf0 | 4 | private void initializeTree() {
for (String line : lines) {
if (line != null) {
String[] words = line.split("\\s+");
if (words.length > 0) {
String[] elementAndContact = words[0].split("=");
if (elementAndContact.length == 2)
{
String element = elementAndContact[0];
String contact = elementAndContact[1];
addElement(element, contact);
}
}
}
}
} |
6bd672a1-22ff-4d54-ab67-7cf43a6c2931 | 2 | public void setUserlistPadding(int[] padding) {
if ((padding == null) || (padding.length != 4)) {
this.userlist_Padding = UIPaddingInits.USERLIST.getPadding();
} else {
this.userlist_Padding = padding;
}
somethingChanged();
} |
50631681-5e59-4262-a02f-9c71022369cb | 8 | @Override
public void setImages() {
if (waitImage == null) {
File imageFile = new File(Structure.baseDir
+ "MarineSentryGunMkII.png");
try {
waitImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (attackImage == null) {
File imageFile = new File(Structure.baseDir
+ "MarineSentryGunMkIIFire.png");
try {
attackImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (upgradeImage == null) {
File imageFile = new File(Structure.baseDir
+ "MarineSentryGunMkII.png");
try {
upgradeImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (explodeImage == null) {
File imageFile = new File(Structure.baseDir
+ "explosion-sprite40.png");
try {
explodeImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
} |
1bcec5a7-3152-4167-8ac0-ef2999053260 | 8 | private void displayResultSetsInDialog(final JFrame frame, String sql) throws SQLException {
StringBuilder warnings = new StringBuilder();
StringBuilder text = new StringBuilder();
Statement statement = SybaseBuddyApplication.connection.createStatement();
boolean results = statement.execute(sql);
int rowsAffected = 0;
do {
if (results) {
ResultSet resultSet = statement.getResultSet();
ResultSetMetaData metaData = resultSet.getMetaData();
int numColumns = metaData.getColumnCount();
while (resultSet.next()) {
StringBuilder row = new StringBuilder();
for (int i = 1; i <= numColumns; i++) {
if (i > 1) {
row.append("\t");
}
row.append(resultSet.getString(i));
}
text.append(row.toString()).append("\n");
}
} else {
rowsAffected = statement.getUpdateCount();
}
SQLWarning sqw = statement.getWarnings();
while ((sqw != null) && (sqw instanceof SybSQLWarning)) {
warnings.append(sqw.getMessage());
sqw = sqw.getNextWarning();
}
statement.clearWarnings();
results = statement.getMoreResults();
} while (results || (rowsAffected != -1));
System.out.println(warnings);
displayTextAreaDialog(frame, text.toString());
} |
e3482936-280b-4c81-a115-cc27aa6e6f20 | 2 | @RequestMapping(value = "/assignmentForm")
public ModelAndView showCustomerForm(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("assignmentForm");
String method = request.getParameter("action");
if (method.equals("add")) {
modelAndView.addObject("command", new Assignment());
} else if (method.equals("edit")) {
String assignmentId = request.getParameter("id");
Assignment assignment = getAssignmentsDAO().getById(Integer.parseInt(assignmentId));
modelAndView.addObject("command", assignment);
}
modelAndView.addObject("employeesList", getEmployeesDAO().getAll());
modelAndView.addObject("projectsList", getProjectsDAO().getAll());
return modelAndView;
} |
16e29c8a-b280-4cb3-a8d6-95129bdc15ae | 8 | public static int neighbors(int[][] board, final int x, final int y) {
int neighbors = 0;
for (int i = x - 1; i <= x + 1; i++) {
if (i >= 0 && i < board.length) {
for (int j = y - 1; j <= y + 1; j++) {
if (j >= 0 && j < board[0].length) {
if (!(i == x && j == y)) {
neighbors += board[i][j];
}
}
}
}
}
return neighbors;
} |
79abe551-7cb0-469a-b878-21835228ab00 | 4 | @Test(groups = { "Character-Sorting", "Primitive Sort" })
public void testSelectionSortChar() {
Reporter.log("[ ** Selection Sort ** ]\n");
try {
testSortCharacters = new SelectionSort<>(
primitiveShuffledArrayChar.clone());
Reporter.log("1. Unsorted Random Array\n");
timeKeeper = System.currentTimeMillis();
testSortCharacters.sortArray();
if (testSortCharacters.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
Reporter.log("2. Sorted Random Array\n");
timeKeeper = System.currentTimeMillis();
testSortCharacters.sortArray();
if (testSortCharacters.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
Reporter.log("3. Reversed Sorted Array\n");
ShuffleArray.reverseArray(testSortCharacters.getArray());
timeKeeper = System.currentTimeMillis();
testSortCharacters.sortArray();
if (testSortCharacters.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
}
catch (Exception x) {
System.err.println(x);
throw x;
}
} |
de38bb57-651c-4c35-b566-41067decba0e | 2 | public Tree multiplicativeExpressionPro(){
Tree firstConditionalExpression = null, secondConditionalExpression = null;
if((firstConditionalExpression = unaryExpressionPro()) != null){
if((secondConditionalExpression = multiplicativeExpressionDashPro(firstConditionalExpression)) != null){
return secondConditionalExpression;
}
return firstConditionalExpression;
}
return null;
} |
38205efd-4295-4545-810a-39f1150ba4bb | 8 | private static DRDiffReport doDiffOperationToReport(List<String> bdbLogFileContents, List<String> hadoopLogFileContents, IDiffStrategy diffStrategy) {
int bdbLogFileIndex = 0;
int hadoopLogFileIndex = 0;
int bdbLogFileLength = bdbLogFileContents.size();
int hadoopLogFileLength = hadoopLogFileContents.size();
DRDiffReport result = new DRDiffReport();
result.setTotalLine(bdbLogFileLength);
StringBuilder resultOutputString = new StringBuilder();
while (bdbLogFileIndex < bdbLogFileLength && hadoopLogFileIndex < hadoopLogFileLength) {
String bdbLogFileLine = bdbLogFileContents.get(bdbLogFileIndex);
String hadoopLogFileLine = hadoopLogFileContents.get(hadoopLogFileIndex);
String[] bdbSplitContents = bdbLogFileLine.split(AnalyseConstants.KEY_VALUE_SPLITTER);
String[] hadoopSplitContents = hadoopLogFileLine.split(AnalyseConstants.KEY_VALUE_SPLITTER);
int compareResult = bdbSplitContents[0].compareTo(hadoopSplitContents[0]);
if (compareResult == 0) {
if (diffStrategy.needCompare(bdbSplitContents[0])) {
String valueCompareOutput = diffStrategy.doCompareOperation(bdbSplitContents[0], bdbSplitContents[1], hadoopSplitContents[1]);
if (valueCompareOutput == null) {
result.sameLinePlus();
} else {
result.differentLinePlus();
resultOutputString.append(valueCompareOutput);
}
} else {
result.ignoreLinePlus();
}
bdbLogFileIndex++;
hadoopLogFileIndex++;
} else if (compareResult > 0) {
hadoopLogFileIndex++;
} else {
// resultOutputString.append(String.format("bdb file not found: %s%s", bdbSplitContents[0], AnalyseConstants.MULTI_LINE_SPLITTER));
bdbLogFileIndex++;
result.noFoundLinePlus();
}
}
if (bdbLogFileIndex != bdbLogFileLength) {
resultOutputString.append("The following content is not processed...").append(AnalyseConstants.MULTI_LINE_SPLITTER);
for (int i = bdbLogFileIndex; i < bdbLogFileLength; i++) {
resultOutputString.append(bdbLogFileContents.get(i)).append(AnalyseConstants.MULTI_LINE_SPLITTER);
}
result.noFoundLinePlus(bdbLogFileLength - bdbLogFileIndex);
}
result.setResultOutputString(resultOutputString.toString());
return result;
} |
5fee3a7b-c91c-4164-b350-fa288de5b908 | 2 | public void testPropertyPlusNoWrapMinute() {
LocalTime test = new LocalTime(10, 20, 30, 40);
LocalTime copy = test.minuteOfHour().addNoWrapToCopy(9);
check(test, 10, 20, 30, 40);
check(copy, 10, 29, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(39);
check(copy, 10, 59, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(40);
check(copy, 11, 0, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(1 * 60 + 45);
check(copy, 12, 5, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(13 * 60 + 39);
check(copy, 23, 59, 30, 40);
try {
test.minuteOfHour().addNoWrapToCopy(13 * 60 + 40);
fail();
} catch (IllegalArgumentException ex) {}
check(test, 10, 20, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(-9);
check(copy, 10, 11, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(-19);
check(copy, 10, 1, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(-20);
check(copy, 10, 0, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(-21);
check(copy, 9, 59, 30, 40);
copy = test.minuteOfHour().addNoWrapToCopy(-(10 * 60 + 20));
check(copy, 0, 0, 30, 40);
try {
test.minuteOfHour().addNoWrapToCopy(-(10 * 60 + 21));
fail();
} catch (IllegalArgumentException ex) {}
check(test, 10, 20, 30, 40);
} |
2bef2812-d93c-4185-a7ba-0f891f5898d9 | 2 | public static void deleteFile() {
File[] files = FileLister.getFilesArrayFile();
int selection = FileChooser.chooseFile();
if (selection < files.length) {
boolean success = files[selection].delete();
if (success) {
System.out.println(">File successfully deleted");
} else {
System.out.println(">File NOT deleted");
}
} else {
System.out.println(">No such file exists");
}
} |
108b7424-d646-4834-b331-8102097bdb08 | 7 | public void run()
{
List<CyNode> allNodes = new ArrayList<CyNode>();
allNodes = network.getNodeList();
CyRow row;
if(doRestart)
{
for(CyNode currNode : allNodes)
{
row = ColumnsCreator.DefaultNodeTable.getRow(currNode.getSUID());
Double initialOutput = row.get(ColumnsCreator.INITIAL_OUTPUT_VALUE, Double.class);
row.set(ColumnsCreator.CURR_OUTPUT, initialOutput);
}
}
while(running)
{
for(CyNode currNode : allNodes)
{
Double nextOutput = evaluate(currNode, network);
row = ColumnsCreator.HiddenNodeTable.getRow(currNode.getSUID());
row.set(ColumnsCreator.NEXT_OUTPUT, nextOutput);
}
for(CyNode currNode : allNodes)
{
row = ColumnsCreator.HiddenNodeTable.getRow(currNode.getSUID());
Double currOutput = row.get(ColumnsCreator.NEXT_OUTPUT, Double.class);
row = ColumnsCreator.DefaultNodeTable.getRow(currNode.getSUID());
row.set(ColumnsCreator.CURR_OUTPUT, currOutput);
//Set the EDGE_SOURCE_NODE_OUTPUT for all outgoing edges
List<CyEdge> outgoingEdges = new ArrayList<CyEdge>();
outgoingEdges = network.getAdjacentEdgeList(currNode, CyEdge.Type.OUTGOING);
for(CyEdge currEdge : outgoingEdges)
{
row = ColumnsCreator.DefaultEdgeTable.getRow(currEdge.getSUID());
row.set(ColumnsCreator.EDGE_SOURCE_NODE_OUTPUT, currOutput);
}
}
viewHandler.refresh(networkView);
try {
Thread.sleep((long)(10000 - appContext.getSpeed()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |
66ec5221-0d51-4103-9ba6-5e073f9dde29 | 4 | private static void copyMemory(long src, Object dest, long size) {
long sSize = size;
while (size > 0) {
if (size >= 8) {
$.putLong(dest, sSize - size, $.getLong(null, src));
size -= 8;
src += 8;
} else if (size >= 4) {
$.putInt(dest, sSize - size, $.getInt(null, src));
size -= 4;
src += 4;
} else if (size >= 2) {
$.putShort(dest, sSize - size, $.getShort(null, src));
size -= 2;
src += 2;
} else {
$.putByte(dest, sSize - size, $.getByte(null, src));
size--;
src++;
}
}
} |
a640afc9-7dc1-4a42-8cbe-45106db54813 | 4 | public Circle score(ShortImageBuffer edges)
{
if(this.x <= this.radius ||
this.y <= this.radius ||
this.x >= (edges.getWidth() - this.radius) ||
this.y >= (edges.getHeight() - this.radius)) return this.scoreCheck(edges);
return this.scoreNoCheck(edges);
} |
6df3e92b-6cfb-4c33-a836-5aa9d5c0c3b3 | 9 | @Override
public void actionPerformed(ActionEvent e) {
final boolean ok = viewMutantsConfiguration.getLiteralOmission().isSelected()
|| viewMutantsConfiguration.getLiteralNegation().isSelected()
|| viewMutantsConfiguration.getClauseOmission().isSelected()
|| viewMutantsConfiguration.getClauseNegation().isSelected()
|| viewMutantsConfiguration.getOperatorAnd().isSelected()
|| viewMutantsConfiguration.getOperatorOr().isSelected();
if (ok) {
Runnable code = new Runnable() {
@Override
public void run() {
viewMutantsConfiguration.setVisible(false);
}
};
if (SwingUtilities.isEventDispatchThread()) {
code.run();
} else {
SwingUtilities.invokeLater(code);
}
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
model.evaluateMutationScore(viewMutantsConfiguration.getLiteralOmission().isSelected(),
viewMutantsConfiguration.getLiteralNegation().isSelected(),
viewMutantsConfiguration.getClauseOmission().isSelected(),
viewMutantsConfiguration.getClauseNegation().isSelected(),
viewMutantsConfiguration.getOperatorAnd().isSelected(),
viewMutantsConfiguration.getOperatorOr().isSelected(), false);
} catch (Exception ex) {
Logger.getLogger(ControllerRunCoverage.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
t.start();
} else {
Runnable code = new Runnable() {
@Override
public void run() {
view.displayErrorMessageNoMutants();
}
};
if (SwingUtilities.isEventDispatchThread()) {
code.run();
} else {
SwingUtilities.invokeLater(code);
}
}
} |
25d6d744-462e-465a-b1e6-b0b01c31f373 | 5 | @SuppressWarnings("unchecked")
public static <K, V> void mergePropertiesIntoMap(Properties props, Map<K, V> map) {
if (map == null) {
throw new IllegalArgumentException("Map must not be null");
}
if (props != null) {
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
Object value = props.getProperty(key);
if (value == null) {
// Potentially a non-String value...
value = props.get(key);
}
map.put((K) key, (V) value);
}
}
} |
4626c839-8b5a-4b28-9c19-92ff7ce46518 | 7 | public static void startupStrategies() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupStrategies.helpStartupStrategies1();
}
if (Stella.currentStartupTimePhaseP(4)) {
Logic.$PARALLEL_STRATEGIES$ = List.list(Cons.cons(Logic.KWD_DISJUNCTIVE_IMPLICATION_INTRODUCTION, Cons.cons(Logic.KWD_UNIVERSAL_INTRODUCTION, Cons.cons(Logic.KWD_REFUTATION, Stella.NIL))));
Logic.$PL_ANONYMOUS_MODULE$ = Stella.getStellaModule("PL-ANONYMOUS", true);
}
if (Stella.currentStartupTimePhaseP(5)) {
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("CONDITIONAL-ANTECEDENT-PROOF-ADJUNCT", "(DEFCLASS CONDITIONAL-ANTECEDENT-PROOF-ADJUNCT (PROOF-ADJUNCT) :SLOTS ((PROVABLE-RULE :TYPE PROPOSITION) (GOAL :TYPE PROPOSITION) (PHASE :TYPE KEYWORD :INITIALLY :FORWARD-RULE)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.ConditionalAntecedentProofAdjunct", "newConditionalAntecedentProofAdjunct", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.ConditionalAntecedentProofAdjunct", "accessConditionalAntecedentProofAdjunctSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ConditionalAntecedentProofAdjunct"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("CLUSTERED-CONJUNCTION-PROOF-ADJUNCT", "(DEFCLASS CLUSTERED-CONJUNCTION-PROOF-ADJUNCT (PROOF-ADJUNCT) :SLOTS ((CLUSTER-FRAMES :TYPE (VECTOR OF CONTROL-FRAME))))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.ClusteredConjunctionProofAdjunct", "newClusteredConjunctionProofAdjunct", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.ClusteredConjunctionProofAdjunct", "accessClusteredConjunctionProofAdjunctSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ClusteredConjunctionProofAdjunct"), 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)) {
_StartupStrategies.helpStartupStrategies2();
Stella.defineFunctionObject("CONTINUE-FORALL-PROOF", "(DEFUN (CONTINUE-FORALL-PROOF KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "continueForallProof", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("CONTINUE-EXISTS-PROOF", "(DEFUN (CONTINUE-EXISTS-PROOF KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "continueExistsProof", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("CONTINUE-CONSTANT-PROOF", "(DEFUN (CONTINUE-CONSTANT-PROOF KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "continueConstantProof", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineExternalSlotFromStringifiedSource("(DEFSLOT CONTROL-FRAME INFERENCE-CUTOFF-REASON :TYPE KEYWORD :ALLOCATION :DYNAMIC)");
Stella.defineFunctionObject("REGISTER-INFERENCE-CUTOFF", "(DEFUN REGISTER-INFERENCE-CUTOFF ((FRAME CONTROL-FRAME) (REASON KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "registerInferenceCutoff", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("CONTINUE-FAIL-PROOF", "(DEFUN (CONTINUE-FAIL-PROOF KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "continueFailProof", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineMethodObject("(DEFMETHOD (CONTINUE-PARTIAL-FAIL-PROOF KEYWORD) ((SELF CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "continuePartialFailProof", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Keyword")}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("STARTUP-STRATEGIES", "(DEFUN STARTUP-STRATEGIES () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic._StartupStrategies", "startupStrategies", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Logic.SYM_LOGIC_STARTUP_STRATEGIES);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Logic.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupStrategies"), 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("LOGIC")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PARALLEL-STRATEGIES* (LIST OF KEYWORD) (LIST :DISJUNCTIVE-IMPLICATION-INTRODUCTION :UNIVERSAL-INTRODUCTION :REFUTATION) :DOCUMENTATION \"List of strategies (keywords) that fork a parallel\ncontrol stack before executing.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *FAILED-GOAL-CUTOFFS* INTEGER 0)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SUCCEEDED-GOAL-CUTOFFS* INTEGER 0)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PL-ANONYMOUS-MODULE* MODULE (GET-STELLA-MODULE \"PL-ANONYMOUS\" TRUE))");
Logic.defineExplanationPhrase(Logic.KWD_CONSTANT_PROPOSITION, Logic.KWD_TECHNICAL, "trivially", Stella.NIL);
Logic.defineExplanationPhrase(Logic.KWD_CONSTANT_PROPOSITION, Logic.KWD_LAY, "trivially", Stella.NIL);
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} |
87265ae9-4f04-47fa-9229-10a6ab14dfdf | 4 | public void draw(Graphics g){
int x = getX();
int y = getY();
int w = getW();
int h = getH();
if(w < 0){
x +=w;
w *= -1;
}
if(h < 0){
y +=h;
h *= -1;
}
Graphics2D g2 = (Graphics2D) g;
if(getLinePattern())
g2.setStroke(new MyDashStroke(getLineWidth()));
else
g2.setStroke(new BasicStroke(getLineWidth()));
if(getShadow()){
g2.setColor(Color.black);
g2.fillRect(x+4, y+4, w, h);
g2.setColor(Color.black);
g2.drawRect(x+4, y+4, w, h);
}
g2.setColor(getFillColor());
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) getAlfa()));
g2.fillRect(x, y, w, h);
g2.setColor(getLineColor());
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) getAlfa()));
g2.drawRect(x, y, w, h);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) 1));
super.draw(g2);
} |
9fa10e8d-857e-4399-8751-f123166ead5c | 1 | @Test
public void getValofRow_test() {
try{
double [][]mat= {{3.0,2.0}, {1.0,3.0}};
int j=0;
double[]result = Matrix.getVecOfRow(mat, j);
double []exp= {3.0,2.0};
Assert.assertArrayEquals(exp, result, 0.0);
}
catch (Exception e) {
// TODO Auto-generated catch block
fail("Not yet implemented");
}
} |
92b7c859-239a-465f-bedc-d29b6cfa947a | 1 | private void registerManaged(Environment environment) {
final Map<String, Managed> beansOfType = applicationContext.getBeansOfType(Managed.class);
for (String beanName : beansOfType.keySet()) {
Managed managed = beansOfType.get(beanName);
environment.lifecycle().manage(managed);
logger.info("Registering managed: " + managed.getClass().getName());
}
} |
dddb6ca5-882d-432f-b096-ce7ec892c9ac | 4 | public void setupVaultEconomy() {
if (!hasVaultPlugin() || !manager.isPluginEnabled("Vault") || econHook != null) {
return;
}
RegisteredServiceProvider<Economy> economyProvider = plugin.getServer().getServicesManager().getRegistration(Economy.class);
if (economyProvider != null) {
econHook = economyProvider.getProvider();
plugin.getLogger().info("Successfully hooked into Vault for economy transactions");
}
} |
b92c454e-41ab-424d-9348-b20f280868e4 | 9 | public void mate(){
boolean impregnate = false;
Organism partner = null;
for(int o = 0; o < environment.getOrganisms().size(); o ++){
// for(Organism o : environment.getOrganisms()){
if(environment.getOrganisms().get(o).getSpecies () == getSpecies()){
if(environment.getOrganisms().get(o) != this){
if(Math.hypot(environment.getOrganisms().get(o).getX()-getX(), environment.getOrganisms().get(o).getY()-getY())<30){
if(shouldMate(environment.getOrganisms().get(o))){
impregnate = true;
partner=environment.getOrganisms().get(o);
if(environment.getOrganisms().get(o).wombs.size()>0){
environment.getOrganisms().get(o).wombs.get(0).impregnate(this);
}
break;
}
}
}
}
}
if(impregnate && partner != null){
if(wombs.size()>0){
wombs.get(0).impregnate(partner);
}
// birthOffspring();
}
} |
2df492e3-27b8-4dee-8f0b-1ef80dc40431 | 4 | public void escribirPalabras(int lin, String etq, String cod, String ope){
String line;
line = Integer.toString(lin);
try{
BufferedWriter bw = new BufferedWriter(new FileWriter("P2ASM.INST",true));
bw.write(line);
bw.write("\t ");
if(etq.isEmpty())
bw.write("Null");
else
bw.write(etq);
bw.write("\t ");
if(cod.isEmpty())
bw.write("Null");
else
bw.write(cod);
bw.write("\t ");
if(ope.isEmpty())
bw.write("Null");
else
bw.write(ope);
bw.close();
}catch(IOException ioe){}
} |
e198a839-4dda-469e-8887-2e399ead77bb | 2 | public static void main(String[] args) {
Sequence sequence = new Sequence(10);
for (int i = 0; i < 10; i++)
sequence.add(Integer.toString(i));
// Selector selector = sequence.selector();
// while (!selector.end()) {
// System.out.print(selector.current() + " ");
// selector.next();
// }
Selector reverseSelector = sequence.reverseSelecor();
while (!reverseSelector.end()) {
System.out.print(reverseSelector.current() + " ");
reverseSelector.next();
}
} |
a76209cf-d92c-482c-8938-077990363dc8 | 6 | @EventHandler
public void CaveSpiderHarm(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.getCaveSpiderConfig().getDouble("CaveSpider.Harm.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getCaveSpiderConfig().getBoolean("CaveSpider.Harm.Enabled", true) && damager instanceof CaveSpider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getCaveSpiderConfig().getInt("CaveSpider.Harm.Time"), plugin.getCaveSpiderConfig().getInt("CaveSpider.Harm.Power")));
}
} |
50599660-f116-4404-9088-1480d754f283 | 2 | public static final boolean isJSP(String fileName) {
for (String file : JSP) {
if (file.equals(fileName)) {
return true;
}
}
return false;
} |
b6b9659b-e075-4a24-91af-187dee59fac0 | 8 | @Override
public int hashCode() {
int result = item != null ? item.hashCode() : 0;
result = 31 * result + (item2 != null ? item2.hashCode() : 0);
result = 31 * result + (item3 != null ? item3.hashCode() : 0);
result = 31 * result + (item4 != null ? item4.hashCode() : 0);
result = 31 * result + (item5 != null ? item5.hashCode() : 0);
result = 31 * result + (item6 != null ? item6.hashCode() : 0);
result = 31 * result + (item7 != null ? item7.hashCode() : 0);
result = 31 * result + (rest != null ? rest.hashCode() : 0);
return result;
} |
052ce9a5-08c0-43ce-9c07-3bd3831fe8f4 | 8 | public Case getCaseByDirection(int direction, Case position){
switch(direction){
case 0:
{
if(position.getCaseNumber()-16 > 0){
return this.casefield[position.getCaseNumber()-16];
}
return null;
}
case 1:
{
if(position.getCaseNumber()%16 != 0){
return this.casefield[position.getCaseNumber()-1];
}
return null;
}
case 2:
{
if(position.getCaseNumber()%16 != 15){
return this.casefield[position.getCaseNumber()+1];
}
}
case 3:
{
if(position.getCaseNumber()+16 < 256){
return this.casefield[position.getCaseNumber()+16];
}
return null;
}
default:
return null;
}
} |
f0b2adb7-8b53-40a0-b652-279edc96697e | 7 | public static void loadWeightsFromFile(){
File input = null;
Scanner reader = null;
try {
input = new File(".data\\nnsave40_110000newLR");
reader = new Scanner(input);
} catch ( java.io.FileNotFoundException e ) {
try {
input = new File(".data/nnsave40_110000newLR");
reader = new Scanner(input);
} catch ( java.io.FileNotFoundException e1 ) {
e1.printStackTrace();
System.out.println("shit happened");
}
}
try{
String[] line = reader.nextLine().split(",");
numInputs = Integer.parseInt(line[0]);
numHiddenNodes = Integer.parseInt(line[1]);
inHid = new double[numInputs][numHiddenNodes];
for(int i = 0; i < inHid.length; i++){
line = reader.nextLine().split(",");
for(int j = 0; j < inHid[i].length; j++){
inHid[i][j] = Double.parseDouble(line[j]);
}
}
line = reader.nextLine().split(",");
numOutputs = Integer.parseInt(line[1]);
hidOut = new double[numHiddenNodes][numOutputs];
for(int i = 0; i < hidOut.length; i++){
line = reader.nextLine().split(",");
for(int j = 0; j < hidOut[i].length; j++){
hidOut[i][j] = Double.parseDouble(line[j]);
}
}
}
catch(Exception e){
e.printStackTrace();
System.out.println("stuff happened");
}
} |
97af73ac-8db6-41cd-8180-5a9bca837778 | 7 | public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
boolean bleft = false, bright=false;
if(root.left==null && root.right==null)
{
if(sum==root.val)
return true;
else
return false;
}
if(root.left != null) bleft =hasPathSum(root.left, sum-root.val);
if(root.right != null) bright =hasPathSum(root.right, sum-root.val);
return bleft||bright;
} |
47fc887a-00b8-4f41-a976-57019090db76 | 5 | public void update(double dt) {
translatePosition = new Vector4(0, 0, 0);
translateLookAt = new Vector4(0, 0, 0);
// moze sie troche dziwne wydawac ale dziala poprawnie
localXAxis.setX(_lookAt.getZ() * -1);
localXAxis.setZ(_lookAt.getX());
localXAxis.normalize();
Vector4D newXAxis = new Vector4(localXAxis);
newXAxis.multiply(_xAxisMovement * dt);
Vector4D newlook = new Vector4(_lookAt);
if (_xAxisMovement != 0) {
translatePosition.add(newXAxis);
}
if (_zAxisMovement != 0) {
translatePosition.add(newlook.multiply(_zAxisMovement * dt));
}
if (_xAxisRotate != 0) {
_lookAt.arbitraryAxisRotation(_xAxisRotate
* _cameraRotateSpeedKeyboard * dt, localXAxis);
}
if (_yAxisRotate != 0) {
_lookAt.yAxisRotation(-_yAxisRotate * _cameraRotateSpeedKeyboard
* dt);
}
if (!translatePosition.isNull()) {
translatePosition.normalize();
_center.add(translatePosition.multiply(_cameraMoveSpeed * dt));
}
} |
4c91629e-93de-4993-86fb-9e1a85460018 | 7 | @Override
protected BufferedImage doInBackground() throws Exception {
long starttime = System.nanoTime();
BufferedImage image = new BufferedImage(AREAX, AREAY, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
double dpcnt; //Delta percent
dpcnt = 99.99 / AREAY;
percnt = 0;
Dx = (REEL_MAX - REEL_MIN) / AREAX;
Dy = (IMAG_MAX - IMAG_MIN) / AREAY;
//Dx = -0.00357142857142857142857142857143;
//Dy = -0.00357142857142857142857142857143;
double x = REEL_MIN;
double y = IMAG_MIN;
for (int i = 0; i < AREAY; i++) {
percnt = percnt + dpcnt;
for (int j = 0; j < AREAX; j++) {
int count = 0;
double p0 = x;
double q0 = y;
double LIMIT = 20.0;
for (int k = 0; Math.abs(p0) <= LIMIT && Math.abs(q0) <= LIMIT && k < LOOP_LIMIT; k++) {
double p1 = p0 * p0 - q0 * q0 + x;
double q1 = 2 * p0 * q0 + y;
p0 = p1;
q0 = q1;
count++;
}
if (Math.abs(p0) < LIMIT && Math.abs(q0) < LIMIT) {
g.setColor(Color.black);
} else {
//g.setColor(farve);
g.setColor(AdvColorPix(count));
}
g.drawLine(j, i, j, i);
x = x + Dx;
}
x = REEL_MIN;
y = y + Dy;
}
System.out.println("Time to render: " + ((System.nanoTime() - starttime) / 1000) + " μs");
percnt = 100.0;
return image;
} |
85482b69-1aea-45b9-82db-ebac6d9eedcc | 1 | private static JPanel[] createEmptyBuckets() {
JPanel[] output = new JPanel[SIZE];
for(int i = 0; i < SIZE; i++) {
output[i] = new JPanel(new GridLayout(0, 1));
}
return output;
} |
c2cafe46-670a-40f8-b7b7-89c4d39a36d8 | 6 | private void showProperty(final String propertyName) throws UnrecognizedCommandException {
java.util.Set<String> properties = Set.properties;
Properties systemProp = Conf.getSystemProperties();
StringBuilder sb = new StringBuilder();
if (null == propertyName) {
int len1 = 0;
for (String name : properties) {
if (name.length() > len1) len1 = name.length();
}
len1 += 2;
int c = 0;
for (String name : Set.properties) {
sb.append(name).append(TextUtilities.repeatStringPattern(" ", len1 - name.length())).append(systemProp.get(name));
if (++c < Set.properties.size()) sb.append(LINE_SEPARATOR);
}
} else {
if (!properties.contains(propertyName)) throw new UnrecognizedCommandException(COMMAND_NAME + ", property [" + propertyName + "] not found");
sb.append(propertyName).append(" ").append(systemProp.get(propertyName));
}
out.println(sb.toString());
} |
b8d0a79d-532c-4da2-acd8-b8acb77fef75 | 5 | private void heapify(int i) {
int pienin;
int l = left(i);
int r = right(i);
if (r <= keonKoko) {
if (taulukko[i] < taulukko[r]) {
pienin = r;
}
else pienin = l;
if (taulukko[i] > taulukko[pienin]) {
vaihda(i, pienin);
heapify(pienin);
}
}
else if (i == keonKoko && taulukko[i] > taulukko[l]) {
vaihda(i,l);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.