I have a problem. I cant output my LinkedList side by side. I asked this question but sadly my Teacher told me to not change the method head or use the libary of java like calender. I got many advice of using it or change the method head. I am Depending on the grade and the teacher is very strict.
There must be somehow the possibility to output a 2 Dimensional LinkedList from left to right. I can imagine the way one can say if an element from the Generic of LinkedList is outputed then please go further to the right.
I am struggeling at the implementation of this Idea. I hope you can help me.
Here I just returning a String but for testing I output the string what is get added.
public String getYearplan(int from, int until) {
if (from <= until) {
for (int i = from; i <= until; i++) {
LinkedList<String> buildedMonth = buildMonth(i);
this.planlist.add(buildedMonth);
}
for (LinkedList<String> months: planlist) {
for (String s : months) {
System.out.printf("%24s",s);
}
}
}
`
In this method buildMonth I am building the Month and return a LinkedList what get added by this.planlist .
public LinkedList<String> buildMonth(int month) {
LinkedList<String> monthList = new LinkedList<>();
StringBuilder sb = new StringBuilder();
String header = this.monthname[month] + " " + this.year;
sb.append(header);
int lengthOfMonth = calender.getLengthOfMonth(jahr, monat);
for (int day = 1; day <= lengthOfMonth; day++) {
for (int weekday = 0; weekday < 7; weekday++) {
String weDay = kalender.getDayOfWeek(weekday);
this.weekDayName = weDay;
}
this.daynumber++;
String dayOfMonth = this.kalender.getTwoLetter(day);
/*
modus = -1 is calender without holiday
*/
if (this.modus == -1) {
sb.append("\n"+this.weekDayName+"|"+dayOfMonth.toString()+"|\t\t|"+daynumber);
}
}
monthList.add(sb.toString());
return monthList;
}`
This is my output what I get and everything works without some stuff but it is easy to fix. The major problem is that I cant Output it side by side.`The weird thing is that the header of february is moving to left but not the other elements.
January 2017
Sa|01| |1
Sa|02| |2
Sa|03| |3
Sa|04| |4
Sa|05| |5
Sa|06| |6
Sa|07| |7
Sa|08| |8
Sa|09| |9
Sa|10| |10
Sa|11| |11
Sa|12| |12
Sa|13| |13
Sa|14| |14
Sa|15| |15
Sa|16| |16
Sa|17| |17
Sa|18| |18
Sa|19| |19
Sa|20| |20
Sa|21| |21
Sa|22| |22
Sa|23| |23
Sa|24| |24
Sa|25| |25
Sa|26| |26
Sa|27| |27
Sa|28| |28
Sa|29| |29
Sa|30| |30
Sa|31| |31February 2017
Sa|01| |32
Sa|02| |33
Sa|03| |34
Sa|04| |35
Sa|05| |36
Sa|06| |37
Sa|07| |38
Sa|08| |39
Sa|09| |40
Sa|10| |41
Sa|11| |42
Sa|12| |43
Sa|13| |44
Sa|14| |45
Sa|15| |46
Sa|16| |47
Sa|17| |48
Sa|18| |49
Sa|19| |50
Sa|20| |51
Sa|21| |52
Sa|22| |53
Sa|23| |54
Sa|24| |55
Sa|25| |56
Sa|26| |57
Sa|27| |58
Sa|28| |59`
Thats is the Output what I try to achieve.`
January 2017 February 2017
So|01| |1 Mi|01| |32
Mo|02| |2 Do|02| |33
Di|03| |3 Fr|03| |34
Mi|04| |4 Sa|04| |35
Do|05| |5 So|05| |36
Fr|06| |6 Mo|06| |37
I hope it was not much, but I wanted to make my question this time clear.
Best Regards
Maskulin
Iterating through the days at a higher dimension than the months I think is the way to go. That way, you can iterate through each day and list them all before going onto the next day for each month.
The below has not been tested but I hope the concept has been exemplified.
public String getYearplan(int from, int until) {
if (from <= until) {
for (int i = from; i <= until; i++) {
LinkedList<String> buildedMonth = buildMonth(i);
this.planlist.add(buildedMonth);
}
for (int day = 0; day < 31; day++){
for (LinkedList<String> month: planlist) {
try{
System.out.print(month[day]);
} catch (Exception e) {
System.out.print("\t")
}
}
}
}
Related
i have 2 excel sheets, i am comparing cell values using testNg Assertion.
following are the values in sheet1 and sheet2
Sheet1 Sheet2
sachin sachin
david david
nancy nancy
winter winter
int rowCount = xlib.getRowCount("Sheet1");
int rowCount1 = xlib.getRowCount("Sheet2");
for (int i = 34; i<=rowCount;i++)
{
String compair1= xlib.getExcelData("Sheet1", i, 5);
System.out.println(compair1);
for (int j = 34; j<=rowCount1;j++)
{
String compair2=xlib.getExcelData("Sheet2", j, 5);
System.out.println(compair2);
Assert.assertEquals(compair1, compair2);
System.out.println("compared successfully");
}
}
}
}
Result:-
sachin
sachin
compared successfully
david
FAILED: Totalcompare
java.lang.AssertionError: expected [david] but found [sachin]
Expected result
Result:-
sachin
sachin
compared successfully
david
david
compared successfully
nancy
nancy
compared successfully
winter
winter
compared successfully
passed: Totalcompare
I keep getting the following in the serial monitor over and over:
AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
I am using the following code that I got off http://playground.arduino.cc/Main/MPU-6050#sketch:
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68; // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
}
void loop(){
Wire.beginTransmission(MPU);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true); // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print("AcX = "); Serial.print(AcX);
Serial.print(" | AcY = "); Serial.print(AcY);
Serial.print(" | AcZ = "); Serial.print(AcZ);
Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53); //equation for temperature in degrees C from datasheet
Serial.print(" | GyX = "); Serial.print(GyX);
Serial.print(" | GyY = "); Serial.print(GyY);
Serial.print(" | GyZ = "); Serial.println(GyZ);
delay(333);
}
This is the wiring I am using: http://jamesmpoe.com/roboticswiki/images/4/45/MPU6050-Arduino-Uno-Connections.jpg
I do not know what is wrong.
Thank you for your help.
First of all, I'd set the clock to the X gyroscope oscillator instead of the internal oscillator (as it is suggested on the MPU6050 datasheet), hence
Wire.beginTransmission(MPU);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(1); // set to one to turn on the Xgyro oscillator
Wire.endTransmission(true);
In my project, however, I wrote a lot more initializations... I suggest you to
Write some functions to write/read bit(s), byte(s) and word(s) on the I2C interface, because you'll need them
Write functions to get and set the important parts of the registers in the MPU6050
Write more complex functions.
Examples:
// I2C interface
bool i2c_writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data)
{
Wire.beginTransmission(devAddr);
Wire.write((uint8_t) regAddr); // send address
for (uint8_t i = 0; i < length; i++)
{
Wire.write((uint8_t) data[i]);
}
return (Wire.endTransmission() == 0);
}
// Simple function
int16_t mpu6050_getAccelerationX() {
i2c_readBytes(MPU6050_ADDRESS, MPU6050_RA_ACCEL_XOUT_H, 2, rwBuffer);
return (((int16_t)rwBuffer[0]) << 8) | rwBuffer[1];
}
// Complex function
void mpu6050_initialize()
{
mpu6050_reset();
delay(100);
mpu6050_setClockSource(MPU6050_CLOCK_PLL_XGYRO);
mpu6050_setSleepEnabled(false);
mpu6050_setWakeCycleEnabled(false);
mpu6050_switchSPIEnabled(false);
mpu6050_setI2CMasterModeEnabled(false);
mpu6050_setFIFOEnabled(false);
delay(100);
mpu6050_setRate(7); // 1kHz scan freq
mpu6050_setDLPFMode(MPU6050_DLPF_BW_256);
mpu6050_setFullScaleGyroRange(MPU6050_GYRO_FS_250);
mpu6050_setFullScaleAccelRange(MPU6050_ACCEL_FS_2);
mpu6050_setInterruptMode(MPU6050_INTMODE_ACTIVEHIGH);
mpu6050_setInterruptDrive(MPU6050_INTDRV_PUSHPULL);
mpu6050_setInterruptLatch(MPU6050_INTLATCH_WAITCLEAR);
mpu6050_setInterruptLatchClear(MPU6050_INTCLEAR_ANYREAD);
mpu6050_setFSyncInterruptEnabled(0);
mpu6050_setI2CBypassEnabled(0);
mpu6050_setClockOutputEnabled(0);
mpu6050_setIntEnabled(MPU6050_INTERRUPT_MASK_DATA_RDY_BIT); // Interrupt when data ready
}
A useful resource is the MPU6050 registers map (you can find it here).
It was a soldering error.
It works perfectly with the code above.
I'm looking for a library or helper class in Java that would allow me to perform date interval sum and subtractions.
For example, lets's say I have the following date intervals:
A = ["2015-01-01 00:00", "2015-01-20 00:00"]
B = ["2015-01-05 00:00", "2015-01-10 00:00"]
C = ["2015-01-11 00:00", "2015-01-14 00:00"]
D = ["2015-01-19 00:00", "2015-01-25 00:00"]
1 A 20
|----------------------------------|
|---------| |----------| |------------|
5 B 10 11 C 14 19 D 25
And let's say I'd like to calculate the following:
A - B - C + D = { ["2015-01-01 00:00", "2015-01-05 00:00"[,
]"2015-01-10 00:00", "2015-01-11 00:00"[,
]"2015-01-14 00:00", "2015-01-25 00:00"] }
1 5 10 11 14 25
|---| |---| |----------------|
I know I can build my own logic using pure Java, but I'd rather not reinvent the wheel...
I was looking into Joda-Time, but I couldn't figure out how to perform such operations using it.
Thanks a lot!
I found exactly what I needed: Ranges, from the guava-libraries.
Works like this:
Range<Date> a = Range.closed(
new GregorianCalendar(2015, 0, 1).getTime(),
new GregorianCalendar(2015, 0, 20).getTime());
Range<Date> b = Range.closed(
new GregorianCalendar(2015, 0, 5).getTime(),
new GregorianCalendar(2015, 0, 10).getTime());
Range<Date> c = Range.closed(
new GregorianCalendar(2015, 0, 11).getTime(),
new GregorianCalendar(2015, 0, 14).getTime());
Range<Date> d = Range.closed(
new GregorianCalendar(2015, 0, 19).getTime(),
new GregorianCalendar(2015, 0, 25).getTime());
RangeSet<Date> result = TreeRangeSet.create();
result.add(a);
result.remove(b);
result.remove(c);
result.add(d);
System.out.println(result);
The code above prints:
[
[Thu Jan 01 00:00:00 BRST 2015‥Mon Jan 05 00:00:00 BRST 2015),
(Sat Jan 10 00:00:00 BRST 2015‥Sun Jan 11 00:00:00 BRST 2015),
(Wed Jan 14 00:00:00 BRST 2015‥Sun Jan 25 00:00:00 BRST 2015]
]
I think it can be done basically using Joda-Time with some custom code. It is assumed that A is the Interval which all other intervals should relate to.
While this code should give the expected results (and should work for different values accordingly) I highly suggest testing it with very different data, especially for the three cases a) an interval not intersecting A at all, b) intersecting A at the beginning and c) an interval which itself intersects B or C or D.
So despite this, it might help for further tests.
Interval a = new Interval(Instant.parse("2015-01-01T00:00Z"), Instant.parse("2015-01-20T00:00Z"));
List<Interval> l = Arrays.asList(
/* b */ new Interval(Instant.parse("2015-01-05T00:00Z"), Instant.parse("2015-01-10T00:00Z")),
/* c */ new Interval(Instant.parse("2015-01-11T00:00Z"), Instant.parse("2015-01-14T00:00Z")),
/* d */ new Interval(Instant.parse("2015-01-19T00:00Z"), Instant.parse("2015-01-25T00:00Z"))
);
List<Interval> results = new ArrayList<Interval>();
for (Interval i : l) {
if (a.contains(i)) {
// if i is completely inside a, then calculate the first part and the remaining part
// whereas the first part will be added to the result
Interval firstPart = new Interval(a.getStart(), i.getStart());
results.add(firstPart);
// followed by i itself (skipped)
// part after i, inside a
Interval remainingPart = new Interval(i.getEnd(), a.getEnd());
a = remainingPart;
} else if (i.overlaps(a)) {
// if the intervals only overlap, then we take the earliest beginning and the latest ending as a result part
DateTime overlapMin = (a.getStart().isBefore(i.getStart())) ? a.getStart() : i.getStart();
DateTime overlapMax = (a.getEnd().isAfter(i.getEnd())) ? a.getEnd() : i.getEnd();
Interval overlapAndBothParts = new Interval(overlapMin, overlapMax);
results.add(overlapAndBothParts);
// if the checked interval i is at the beginning, then a will become the part after this "overlap"
if (i.getStartMillis() < a.getStartMillis()) {
Interval whatsLeft = new Interval(i.getEndMillis(), a.getEndMillis());
a = whatsLeft;
}
}
}
// print result
for (Interval i : results) {
System.out.println("result part: " + i);
}
I have a Java class that I'm trying to test with Spock. The Java class contains an inner enum:
import static java.util.Calendar.*;
import java.util.*;
public class FederalHolidays {
public enum Observance {
NEW_YEARS_DAY(JANUARY, 1),
BIRTHDAY_OF_MARTIN_LUTHER_KING_JR(JANUARY, MONDAY, 3),
WASHINGTONS_BIRTHDAY(FEBRUARY, MONDAY, 3),
MEMORIAL_DAY(MAY, MONDAY, -1),
INDEPENDENCE_DAY(JULY, 4),
LABOR_DAY(SEPTEMBER, MONDAY, 1),
COLUMBUS_DAY(OCTOBER, MONDAY, 2),
VETERANS_DAY(NOVEMBER, 11),
THANKSGIVING_DAY(NOVEMBER, THURSDAY, 4),
CHIRSTMAS_DAY(DECEMBER, 25);
private final int month;
private final int dayOfMonth;
private final int dayOfWeek;
private final int weekOfMonth;
private static final int NA = 0;
private Observance(int month, int dayOfMonth) {
this.month = month;
this.dayOfMonth = dayOfMonth;
this.dayOfWeek = NA;
this.weekOfMonth = NA;
}
private Observance(int month, int dayOfWeek, int weekOfMonth) {
this.month = month;
this.dayOfMonth = NA;
this.dayOfWeek = dayOfWeek;
this.weekOfMonth = weekOfMonth;
}
boolean isFixedDate() {
return dayOfMonth != NA;
}
}
public Date dateOf(Observance observance, int year) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.ENGLISH);
cal.set(YEAR, year);
cal.set(MONTH, observance.month);
cal.clear(HOUR);
if (observance.isFixedDate()) {
cal.set(DAY_OF_MONTH, observance.dayOfMonth);
} else {
setNthDayOfWeek(cal, observance.dayOfWeek, observance.weekOfMonth);
}
adjustForWeekendsIfNecessary(cal);
return cal.getTime();
}
private void setNthDayOfWeek(Calendar cal, int dayOfWeek, int n) {
int week = 0;
int lastDay = cal.getActualMaximum(DAY_OF_MONTH);
int startDay = n > 0 ? 1 : lastDay;
int endDay = n > 0 ? lastDay : 1;
int incrementValue = n > 0 ? 1 : -1;
for (int day = startDay; day != endDay; day += incrementValue) {
cal.set(DAY_OF_MONTH, day);
if (cal.get(DAY_OF_WEEK) == dayOfWeek) {
week += incrementValue;
if (week == n) {
return;
}
}
}
}
private void adjustForWeekendsIfNecessary(Calendar cal) {
int dayOfWeek = cal.get(DAY_OF_WEEK);
cal.add(DAY_OF_MONTH, dayOfWeek == SATURDAY ? -1 : dayOfWeek == SUNDAY ? 1 : 0);
}
}
My Spock test spec looks like this:
class FederalHolidaysSpec extends Specification {
#Shared
def federalHolidays = new FederalHolidays()
def "holidays are correctly calculated"() {
expect:
federalHolidays.dateOf(observance, year).format('yyyy/MM/dd') == date
where:
observance | year | date
NEW_YEARS_DAY | 2011 | '2010/12/31'
BIRTHDAY_OF_MARTIN_LUTHER_KING_JR | 2011 | '2011/01/17'
WASHINGTONS_BIRTHDAY | 2011 | '2011/02/21'
MEMORIAL_DAY | 2011 | '2011/05/30'
INDEPENDENCE_DAY | 2011 | '2011/07/04'
LABOR_DAY | 2011 | '2011/09/05'
COLUMBUS_DAY | 2011 | '2011/10/10'
VETERANS_DAY | 2011 | '2011/11/11'
THANKSGIVING_DAY | 2011 | '2011/11/24'
CHIRSTMAS_DAY | 2011 | '2011/12/26'
}
}
When I run Spock, I get 10 test errors, one per each row of the table. Every error is identical:
groovy.lang.MissingPropertyException: No such property: Observance for class: bdkosher.FederalHolidaysSpec
at bdkosher.FederalHolidaysSpec.$spock_initializeFields(FederalHolidaysSpec.groovy)
(I'm using Spock 0.7-groovy-2.0, groovy-all 2.2.2 (non-indy), and Java 1.7.0_45.)
Why is Spock looking for a property named Observance on my FederalHolidaysSpec class?
I initially suspected the issue was related to inner enums/static imports, although changing my Spock test to use fully qualified enum values (e.g. bdkosher.FederalHolidays.Observance.CHRISTMAS_DAY) did not make a difference.
EDIT: Java file implementation corrected so it passes test; typos corrected in test file.
Make sure you have correct packages for both the source code and the test case. Below works for me if both the java class and the test class are in the same package.
package bdkosher
import spock.lang.Shared
import spock.lang.Specification
//import bdkosher.FederalHolidays.Observance //Do not need
import static bdkosher.FederalHolidays.Observance.*
class FederalHolidaysSpec extends Specification { .. }
I tested without a default package name as com.example and in a Grails app although the spock version was same.
After hearing of #elems' and #dmahaptro's successes, I started ripping things out of my project structure and reducing down dependencies in my POM.
After dropping the unused src/test/java and src/main/groovy directories entirely, I noticed the FederalHolidaysSpec.groovy source file in my IDE reverted to an older version (I'm not sure if I should blame gmavenplus-plugin or NetBeans for this--I'm suspecting the later since I was consistently testing using mvn clean test). In any case, this older version contained an additional field:
class FederalHolidaysSpec extends Specification {
def data = [(Observance.NEW_YEARS_DAY) : ['2011/12/31']]
This field was causing the test errors. Even with an import bdkosher.FederalHolidays.Observance, Groovy apparently believes the map key to be a property reference rather than a enum reference?
In any case, now I can fix the typos and legitimate test failures. Thanks for the help.
I have an entity class that has an embedded object within it:
#Entity
public class Flight implements Serializable {
/// .... other attributes
#Embedded
#AttributeOverrides({
#AttributeOverride(name = "value", column =
#Column(name = "FLIGHT_TIME")),
#AttributeOverride(name = "dataState", column =
#Column(name = "FLIGHT_TIME_TYPE", length = 20))
})
private DateDataStateValue flightDate;
}
The DateDataStateValue is as follows:
#Embeddable
public class DateDataStateValue implements DataStateValue<Date>, Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "DATASTATE")
#Enumerated(value = EnumType.STRING)
private final DataState dataState;
#Column(name = "DATAVALUE")
#Temporal(TemporalType.TIMESTAMP)
private final Date value;
}
When performing a fetch of Flights from the database, using a CriteriaQuery, and creating an Order object on the time column:
Path<Flight> propertyPath = queryRoot.get("flightDate");
Order order = isAscending() ? criteriaBuilder.asc(propertyPath) : criteriaBuilder.desc(propertyPath);
The ordering is not what I want. For instance, if the flight table has the following values:
Flight 1 | ESTIMATED | 1 Jan 2012
Flight 2 | ESTIMATED | 1 Jan 2011
Flight 3 | ACTUAL | 1 Jan 2010
Flight 4 | ESTIMATED | 1 Jan 2009
The result of an ascending sort will be:
Flight 3 | ACTUAL | 1 Jan 2010
Flight 4 | ESTIMATED | 1 Jan 2009
Flight 2 | ESTIMATED | 1 Jan 2011
Flight 1 | ESTIMATED | 1 Jan 2012
It appears that the default ordering of an #Embedded column is to use the natural ordering of the elements in the order in which they are named in the class. Ie DATASTATE first, then DATAVALUE second.
What I would like to do is whenever the sort property is flightDate, the ordering is the date first, then the state, ie:
Flight 4 | ESTIMATED | 1 Jan 2009
Flight 3 | ACTUAL | 1 Jan 2010
Flight 2 | ESTIMATED | 1 Jan 2011
Flight 1 | ESTIMATED | 1 Jan 2012
Making the DateDataStateValue comparable doesn't affect it, and #orderColumn/#OrderBy don't seem to be the right thing for the job. Does anyone have any ideas?
Thanks in advance.
I didn't even know you could add an order by query on an embeddable property like this. But I wouldn't rely on it, and simply add two orders to your query:
Path<Flight> statePath = queryRoot.get("flightDate.dateState"); // or queryRoot.get("flightDate").get("dateState"): to be tested
Path<Flight> valuePath = queryRoot.get("flightDate.value");
Order[] orders;
if (isAscending()) {
orders = new Order[] {criteriaBuilder.asc(valuePath), criteriaBuilder.asc(statePath) };
}
else {
orders = new Order[] {criteriaBuilder.desc(valuePath), criteriaBuilder.desc(statePath)
}
query.orderBy(orders);
something like "flightDate.value ASC, flightDate.dataState ASC" perhaps, since all you defined was "flightDate", which implies natural ordering of that object