Is there an issue with trying to pass a constant or variable to a rem() method in kotlin? - kotlin

Is there an issue with trying to pass a constant or variable to a rem() method in kotlin?
object TimeCalc {
private const val SECONDS: Int = 1000
private const val MINUTES: Int = SECONDS * 60
private const val HOURS: Int = MINUTES * 60
private const val DAYS: Int = HOURS * 24
fun timeDiff(sTime: Long, eTime: Long){
Log.i("Test", "sec $SECONDS: min $MINUTES : hrs $HOURS : days $DAYS")
var startTime = sTime
var endTime = eTime
var mDiff: Int
var mHours: Int
var mMinutes: Int
var mSeconds:Int
var mMilliS: Int
Log.i("Test", "$startTime - $endTime")
mDiff = (endTime - startTime).toInt()
Log.i("Test", "Diff = $mDiff")
**mHours = mDiff.rem(DAYS)**
Log.i("Test", "Hours = $mHours")
Log.i("Test", "${mHours}")
}
}
Result
I/Test: sec 1000: min 60000 : hrs 3600000 : days 86400000
I/Test: 1545062123189 - 1545062217296
I/Test: Diff = 94107
I/Test: Hours = 94107
I/Test: 94107

Related

Extract Hours and Minute from the of TotalHoursWorked in ASP.net Core

I'm trying to extract the hours and minute separately from the result of TotalHoursWorked.
Here's the code for the computation:
public void ComputeProductivity(long timesheetId)
{
var timesheet = _artDBContext.Timesheets.FirstOrDefault(x => x.Id == timesheetId);
if (timesheet != null)
{
var percentage = 100;
var conversionValue = 60;
var weekValue = 5;
var totalWorkingHoursPerWeek = 7m / 365m;
timesheet.TotalHoursWorked = (decimal)((timesheet.TimesheetDateOut - timesheet.TimesheetDateIn).Value.TotalSeconds) / 3600;
timesheet.ProductivityPerc = (timesheet.TotalHoursWorked / 9) * percentage;
timesheet.ProductivityHr = timesheet.ProductivityMin / conversionValue;//need here
timesheet.ProductivityMin = timesheet.TotalHoursWorked * conversionValue;//also here
timesheet.FTERatio = (timesheet.TotalHoursWorked * weekValue) / (timesheet.TotalHoursWorked * totalWorkingHoursPerWeek );
_artDBContext.Entry(timesheet).State = EntityState.Modified;
_artDBContext.SaveChanges();
}
}
The data type of TotalHoursWorked is decimal for
ex I have 5.5 totalHoursWorked where 5 is the productivityHr and .5 / 60 is the productivityMn. How can I get that answer?

Alarm manager show notification every time when i open the app

I am using the requestj api to send and receive the data from server and setting up the alarm on time that i received from server and alarm calls two hours ago from received time but issue is that when alarm fire on exact time it also fire every time when api calls till that 2 hours didn't completed. Any one know how to prevent it?
1.API code is here
fun getAllFriendsReminders(context: Context) {
val getReminderHttpRequest = HttpRequest()
// val myList = ArrayList<FriendsRemindersListModel>()
getReminderHttpRequest.setOnResponseListener { getReminderListResponse ->
Log.e("getReminders List", getReminderListResponse.code.toString())
Log.e("getReminders List", getReminderListResponse.text)
if (getReminderListResponse.code == HttpResponse.HTTP_OK) {
Log.e("getReminders List", getReminderListResponse.code.toString())
val jsonArray = getReminderListResponse.toJSONArray()
getReminderListModel.clear()
Log.e("list", jsonArray.length().toString())
Log.e("list", jsonArray.toString())
val loggedInUser = appGlobals.getValueString("loginUsername")
for (i in 0 until jsonArray!!.length()) {
if (!onForeGround) {
progressBar!!.progress = i
}
Log.e("listi", i.toString())
val jsonObject = jsonArray.getJSONObject(i)
friendReminderText = jsonObject.getString("reminder")
friendReminderFromName = jsonObject.getString("reminder_from")
friendReminderToName = jsonObject.getString("reminder_to")
friendReminderDate = jsonObject.getString("date")
friendReminderStatus = jsonObject.getString("status")
friendReminderId = jsonObject.getString("id")
if (friendReminderFromName != loggedInUser) {
getReminderListModel.add(FriendsRemindersListModel(0, friendReminderId.toInt(),friendReminderText,
friendReminderDate, friendReminderFromName, friendReminderToName, friendReminderStatus))
//Received date time from server
val dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm:ss a")
// val dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
// val timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a")
val instant = Instant.ofEpochMilli(friendReminderDate.toLong())
val instant1 = Instant.ofEpochMilli(friendReminderDate.toLong() - (120 * 60 * 1000))
val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
val date1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault())
// val exactDate = dateFormatter.format(date)
// val exactTime = timeFormatter.format(date)
val exactDateTime = dateTimeFormatter.format(date)
val alarmDate = Date(friendReminderDate.toLong())
//Current date time
val dates = Date()
val stringFormat = SimpleDateFormat("dd-MM-yyyy hh:mm:ss a")
val dateTimeTo = stringFormat.format(dates.time)
//Set Alarm
if (alarmDate.after(dates)) {
Log.d("D", dates.toString())
Log.d("AlarmDate", alarmDate.toString())
Log.e("2 hour ago", dateTimeFormatter.format(date1))
println(friendReminderDate.toLong() - (120 * 60 * 1000))
Log.e("Set", exactDateTime)
val alarmManager: AlarmManager = context.getSystemService(
AppCompatActivity.ALARM_SERVICE) as AlarmManager
val alarmIntent = Intent(requireContext(), AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Log.e("Alarm", "Alarm")
alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(friendReminderDate.toLong() - 120*60*1000,
pendingIntent), pendingIntent)
} else {
Log.e("Alarm1", "${friendReminderDate.toLong() - (120 * 60 * 1000)}")
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
(friendReminderDate.toLong()) - 120 * 60 * 1000,
pendingIntent)
Log.e("Alarm2", "Alarm")
}
}
// if (exactDateTime > dateTimeTo) {
//
// }
}
}
if (friendReminderFromName != loggedInUser) {
if (friendReminderId != "") {
reminder = FriendsRemindersListModel(0, friendReminderId.toInt(), friendReminderText, friendReminderDate,
friendReminderFromName, friendReminderToName, friendReminderStatus)
}
}
if (getReminderListModel.size.toString() > remindersListModel.size.toString()) {
Log.e("serverListSize", getReminderListModel.size.toString())
Log.e("dbListSize", remindersListModel.size.toString())
Log.e("JsonListSize", jsonArray.length().toString())
for (i in 0 until getReminderListModel.size - 1) {
Log.e("present", getReminderListModel[i].reminderId.toString())
var isPresent = false
for (j in 0 until remindersListModel.size - 1) {
Log.e("present", remindersListModel.toString())
if (remindersListModel.isNotEmpty()) {
if (getReminderListModel[i].reminderId == remindersListModel[i].reminderId) {
isPresent = true
}
}
}
Log.e("presenting", "${!isPresent}")
if (isPresent) {
remindersViewModel.addingReminder(reminder)
}
}
}
else if (getReminderListModel.size.toString() < remindersListModel.size.toString()) {
for (i in 0 until remindersListModel.size - 1) {
for (j in 0 until getReminderListModel.size - 1) {
// var isRemoved = false
// Log.e("i's", i.toString())
Log.e("i's", getReminderListModel.size.toString())
Log.e("i'ss", remindersListModel.size.toString())
if (remindersListModel.isNotEmpty()) {
Log.e("delete3", remindersListModel[i].reminderId.toString())
Log.e("delete3", remindersListModel[i].reminderText)
Log.e("delete4", getReminderListModel[j].reminderId.toString())
Log.e("delete4", getReminderListModel[j].reminderText)
if (remindersListModel[i].reminderId != getReminderListModel[i].reminderId ) {
Log.e("delete2", remindersListModel[i].reminderId.toString())
remindersViewModel.deleteReminder(remindersListModel[i].reminderId)
// getReminderListAdapter.notifyItemRemoved(i)
}
}
}
}
}
// if (getReminderListModel.size.toString() != getRemindersDBList.size.toString()) {
// remindersViewModel.deleteReceivedReminders()
// remindersViewModel.addReminder(getReminderListModel)
// }
if (progressBar!= null) {
progressBar!!.visibility = View.GONE
}
}
}
getReminderHttpRequest.setOnErrorListener {
if (progressBar != null) {
progressBar!!.visibility = View.GONE
}
Log.e("getReminders error", "$it")
Log.e("Alarm1", "${friendReminderDate.toLong() - (120 * 60 * 1000)}")
}
val token = appGlobals.getValueString("userToken")
val headers = HttpHeaders("Authorization", "Token $token")
getReminderHttpRequest.get(AppGlobals.GET_REMINDERS_LIST_API, headers)
}
2. Alarm receiver class:
class AlarmReceiver: BroadcastReceiver() {
#RequiresApi(Build.VERSION_CODES.O)
#SuppressLint("UnsafeProtectedBroadcastReceiver")
override fun onReceive(context: Context?, intent: Intent?) {
showNotification(context!!, MessagingServiceFirebase.title, MessagingServiceFirebase.body)
Log.e("Checking notify", "Notification")
// Toast.makeText(context, "Alarm", Toast.LENGTH_SHORT).show()
Log.e("Checking ", "Notification")
// ringTone(context)
}
// private fun ringTone(context: Context) {
// val alert: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
// val ringtone: Ringtone = RingtoneManager.getRingtone(context, alert)
//
// ringtone.play()
// Toast.makeText(context, "Alarm Called", Toast.LENGTH_SHORT).show()
// }
fun showNotification(ctx: Context, title: String, message: String) {
val notificationManager =
ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "channel"
val name: CharSequence = "channel"
val description = "The channel"
val importance = NotificationManager.IMPORTANCE_HIGH
val mChannel = NotificationChannel(channelId, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.RED
mChannel.enableVibration(true)
mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
mChannel.setShowBadge(false)
notificationManager.createNotificationChannel(mChannel)
}
val builder: NotificationCompat.Builder = NotificationCompat.Builder(ctx, "channel")
.setSmallIcon(R.drawable.ic_baseline_access_alarm_24)
.setContentTitle(title)
.setContentText(message)
val resultIntent = Intent(ctx, HomeActivity::class.java)
val stackBuilder: TaskStackBuilder = TaskStackBuilder.create(ctx)
stackBuilder.addParentStack(HomeActivity::class.java)
resultIntent.putExtra("NotifyTitle", title)
resultIntent.putExtra("NotifyMessage", message)
stackBuilder.addNextIntent(resultIntent)
val resultPendingIntent: PendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(resultPendingIntent)
builder.setAutoCancel(true)
notificationManager.notify(12, builder.build())
}
}
3. Manifest code
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver
android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
</intent-filter>
</receiver>
You pull date from the JSON, and set an alarm for 2 hours before that? So if date is 6pm, you set an alarm for 4pm?
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
friendReminderDate.toLong()) - 120 * 60 * 1000, // date - 2hrs
pendingIntent)
If it's 5pm right now, and you set an alarm for 4pm, it will still set, and fire immediately:
If the stated trigger time is in the past, the alarm will be triggered immediately. If there is already an alarm for this Intent scheduled (with the equality of two intents being defined by Intent#filterEquals), then it will be removed and replaced by this one.
So if you only want to set the alarm if now <= alarmTime, and just skip it if now > alarmTime, you need to do that check before you set the alarm.
It looks like you're trying to do that:
if (alarmDate.after(dates)) {
but alarmDate is "date", not "date - 2hrs" (you're using 6pm instead of 4pm):
val alarmDate = Date(friendReminderDate.toLong())
So during that 2-hour period, you're always setting alarms that fire immediately. You need to use your actual alarm time instead:
// seriously, just do this calculation once and refer to the variable
val alarmTime = friendReminderDate.toLong() - (120 * 60 * 1000)
val alarmDate = Date(alarmTime)
You have a lot of date variables piling up in there, it's confusing and hard to tell what's going on - that's probably how this alarmDate bug crept in.
Also just in case, you know your "alarm receiver" also fires and shows a notification when the device boots and when it first unlocks, right?
The (-2hrs) above is only correct, when you are in:
(UTC +1) zone AND there is SUMMER (+1) or
(UTC +2) zone AND there is WINTER (+0)
The correct datetime is in millis (kotlin datetime to millisecond convert using local zone and daylight offset):
val myalarmdatetime: String = "2022-05-31 23:59:59"
val myalarmdatetimemillis: Long =
ZonedDateTime.of(
LocalDateTime.parse(
myalarmdatetime,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
), ZoneId.systemDefault()
).toInstant().toEpochMilli()

how to write unit test cases in jasmine for this code?

private getTotalMinutesBetweenStartAndEnd(startTime: string, endTime: string): number {
// get each time's hour and min values
let [startHrs, startMins] = this.getHoursAndMinsFromTime(startTime);
let [endHrs, endMins] = this.getHoursAndMinsFromTime(endTime);
// time arithmetic (subtraction)
if (endMins < startMins) {
endHrs -= 1;
endMins += 60;
}
let mins = endMins - startMins;
let hrs = endHrs - startHrs;
// this handles scenarios where the startTime > endTime
if (hrs < 0) {
hrs += 24;
}
return hrs * 60 + mins;
}

Optaplanner ScoreDirector continuous planning DayOff Request

I am trying to enable continuous planning and requests. I have tried to follow the computer example provided within the doco. Code below. I can see the values updated during debug. Code below. What am I doing wrong
public void addEmployeeDayOff(final Employee employee,final DayOffRequest dayOffRequest) {
logger.info("Scheduling employee dayoff ({}).", dayOffRequest);
doProblemFactChange(scoreDirector -> {
NurseRoster nurseRoster = scoreDirector.getWorkingSolution();
Employee workingEmployee = scoreDirector.lookUpWorkingObject(employee);
DayOffRequest dayoffRequest = scoreDirector.lookUpWorkingObject(dayOffRequest);
scoreDirector.beforeProblemPropertyChanged(workingEmployee);
if (workingEmployee == null) {
return;
}
ArrayList<DayOffRequest> requestoffList = new ArrayList<>(nurseRoster.getDayOffRequestList());
nurseRoster.setDayOffRequestList(requestoffList);
scoreDirector.beforeProblemFactAdded(dayoffRequest);
workingEmployee.getDayOffRequestMap().put(dayoffRequest.getShiftDate(), dayoffRequest);
scoreDirector.afterProblemPropertyChanged(workingEmployee);
nurseRoster.getDayOffRequestList().add(dayoffRequest);
scoreDirector.afterProblemPropertyChanged(dayoffRequest);
scoreDirector.triggerVariableListeners();
});
The above is called from here:
List<DayOffRequest> dayOffRequestList;
//updating from database .. not sure if this is the issue
List<DayOffData> dayOffElementList = (List<DayOffData>) rosterService.listDayOffData();
dayOffRequestList = new ArrayList<>(dayOffElementList.size());
long nextdayoffId =0L;
for (DayOffData element : dayOffElementList) {
if (nextdayoffId <= element.getId()) {
nextdayoffId = element.getId() + 1L;
}
DayOffRequest dayOffRequest = new DayOffRequest();
String empID = element.getEmployee().getName();
int weight = element.getWeight();
LocalDate shiftDate = element.getShiftDate();
ShiftDate date1 = shiftDateMap.get(shiftDate);
Employee employee = employeeMap.get(empID);
dayOffRequest.setId(nextdayoffId);
dayOffRequest.setWeight(weight);
dayOffRequest.setEmployee(employee);
dayOffRequest.setShiftDate(date1);
dayOffRequestList.add(dayOffRequest);
//If this is not enabled the values don't pass to the addEmployeeDayOff method is this correct??
scoreDirector.afterProblemFactAdded(dayOffRequest);
scoreDirector.afterProblemFactAdded(employee);
addEmployeeDayOff(employee,dayOffRequest);
}
I found this worked but not sure if this is the correct way to approach the problem.
public void addEmployeeDayOff(final Employee employee, final DayOffRequest dayOffRequest) {
logger.info("Scheduling employee dayoff ({}).", dayOffRequest);
doProblemFactChange(scoreDirector -> {
NurseRoster nurseRoster = (NurseRoster) scoreDirector.getWorkingSolution();
Employee workingEmployee = scoreDirector.lookUpWorkingObject(employee);
DayOffRequest dayoffRequest = (DayOffRequest) scoreDirector.lookUpWorkingObject(dayOffRequest);
scoreDirector.beforeProblemPropertyChanged(workingEmployee);
if (workingEmployee == null) {
return;
}
ArrayList<DayOffRequest> requestoffList = new ArrayList<>(nurseRoster.getDayOffRequestList());
nurseRoster.setDayOffRequestList(requestoffList);
scoreDirector.afterProblemFactAdded(requestoffList);
scoreDirector.afterProblemPropertyChanged(requestoffList);
ArrayList<Employee> beforeempList = new ArrayList<>(nurseRoster.getEmployeeList());
nurseRoster.setEmployeeList(beforeempList);
nurseRoster.getEmployeeList().remove(workingEmployee);
scoreDirector.beforeProblemFactRemoved(workingEmployee);
scoreDirector.afterProblemFactRemoved(workingEmployee);
ArrayList<Employee> empList = new ArrayList<>(nurseRoster.getEmployeeList());
nurseRoster.setEmployeeList(empList);
workingEmployee.getDayOffRequestMap().put(dayOffRequest.getShiftDate(), dayOffRequest);
nurseRoster.getEmployeeList().add(workingEmployee);
scoreDirector.beforeProblemFactAdded(workingEmployee);
scoreDirector.afterProblemFactAdded(workingEmployee);
scoreDirector.triggerVariableListeners();
});
I have uploaded the xml and Java file here https://github.com/rod182211/Optaplanner in to hope someone can advise why when I advance 14 days not all rule continue to apply. I assumed scoredirector only needed to be made aware of changes.
14 Day advance taking into account Requests via the below.
doProblemFactChange(scoreDirector -> {
NurseRoster nurseRoster = scoreDirector.getWorkingSolution();
NurseRosterParametrization nurseRosterParametrization = nurseRoster
.getNurseRosterParametrization();
List<ShiftDate> shiftDateList = nurseRoster.getShiftDateList();
Shift oldLastShift = nurseRoster.getShiftList()
.get(nurseRoster.getShiftList().size() - 1);
long shiftId = oldLastShift.getId() + 1L;
int shiftIndex = oldLastShift.getIndex() + 1;
ShiftDate oldLastShiftDate = shiftDateList
.get(shiftDateList.size() - 1);
long shiftDateId = (oldLastShiftDate.getId() + 1L);
int shiftDayIndex = (oldLastShiftDate.getDayIndex() + 1);
// long parmId = nurseRoster.getNurseRosterParametrization().getId()
// + 1L;
scoreDirector
.beforeProblemPropertyChanged(nurseRosterParametrization);
// Update to get the first day along with adding 14 days to the run
LocalDate startDate = (oldLastShiftDate.getDate().plusDays(1));
LocalDate endDate = (oldLastShiftDate.getDate().plusDays(14));
int maxDayIndex = Math.toIntExact(DAYS.between(startDate, endDate));
int shiftDateSize = maxDayIndex + 1;
List<ShiftDate> shiftDateList1 = new ArrayList<>(shiftDateSize);
shiftDateMap = new HashMap<>(shiftDateSize);
LocalDate date = startDate;
for (int i = 0; i < shiftDateSize; i++) {
ShiftDate shiftDate = new ShiftDate();
shiftDate.setId(shiftDateId);
shiftDate.setDayIndex(shiftDayIndex);
shiftDate.setDate(date);
shiftDate.setShiftList(new ArrayList<>());
shiftDateMap.put(date, shiftDate);
shiftDateId++;
shiftDayIndex++;
date = date.plusDays(1);
nurseRoster.getShiftDateList().add(shiftDate);
shiftDateList1.add(shiftDate);
scoreDirector.afterProblemFactAdded(shiftDate);
}
List<Skill> skillList;
List<Skill> skillElementList = (List<Skill>) nurseRoster
.getSkillList();
skillList = new ArrayList<>(skillElementList.size());
skillMap = new HashMap<>(skillElementList.size());
long id = 0L;
for (Skill element : skillElementList) {
Skill skill = new Skill();
skill.setId(id);
skill.setCode(element.getCode());
skillList.add(skill);
if (skillMap.containsKey(skill.getCode())) {
throw new IllegalArgumentException(
"There are 2 skills with the same code ("
+ skill.getCode() + ").");
}
skillMap.put(skill.getCode(), skill);
id++;
}
List<Contract> contractElementList = (List<Contract>) nurseRoster
.getContractList();
List<Contract> contractList = new ArrayList<>(
contractElementList.size());
contractMap = new HashMap<>(contractElementList.size());
for (Contract element : contractElementList) {
Contract contract = new Contract();
long Id = element.getId();
contract.setId(Id);
contract.setCode(element.getCode());
contract.setDescription(element.getDescription());
WeekendDefinition weekend = element.getWeekendDefinition();
contract.setWeekendDefinition(weekend);
contract.setContractLineList(new ArrayList<ContractLine>());
contractMap.put(contract.getCode(), contract);
contractList.add(contract);
}
List<ShiftTypeSkillRequirement> coverRequirementElementList = (List<ShiftTypeSkillRequirement>) nurseRoster
.getShiftTypeSkillRequirementList();
List<ShiftType> shiftTypeElementList = (List<ShiftType>) rosterService
.listShiftType();
List<ShiftType> shiftTypeList = new ArrayList<>(
shiftTypeElementList.size());
shiftTypeMap = new HashMap<>(shiftTypeElementList.size());
long Id = 0L;
int index = 0;
long shiftTypeSkillRequirementId = 0L;
List<ShiftTypeSkillRequirement> shiftTypeSkillRequirementList = new ArrayList<>(
shiftTypeElementList.size() * 2);
for (ShiftType element : shiftTypeElementList) {
ShiftType shiftType = new ShiftType();
shiftType.setId(Id);
shiftType.setCode(element.getCode());
shiftType.setIndex(index);
String startTimeString = element.getStartTimeString();
shiftType.setStartTimeString(startTimeString);
String endTimeString = element.getEndTimeString();
shiftType.setEndTimeString(endTimeString);
shiftType
.setNight(startTimeString.compareTo(endTimeString) > 0);
shiftType.setDescription(element.getDescription());
for (ShiftTypeSkillRequirement skillElement : coverRequirementElementList) {
ShiftTypeSkillRequirement shiftTypeSkillRequirement = new ShiftTypeSkillRequirement();
shiftTypeSkillRequirement
.setId(shiftTypeSkillRequirementId);
shiftTypeSkillRequirement.setShiftType(shiftType);
Skill skill = skillMap
.get(skillElement.getSkill().getCode());
if (skill == null) {
throw new IllegalArgumentException("The skill ("
+ skillElement.getSkill().getCode()
+ ") of shiftType (" + shiftType.getCode()
+ ") does not exist.");
}
shiftTypeSkillRequirement.setSkill(skill);
shiftTypeSkillRequirementList
.add(shiftTypeSkillRequirement);
shiftTypeSkillRequirementId++;
}
shiftTypeList.add(shiftType);
if (shiftTypeMap.containsKey(shiftType.getCode())) {
throw new IllegalArgumentException(
"There are 2 shiftTypes with the same code ("
+ shiftType.getCode() + ").");
}
shiftTypeMap.put(shiftType.getCode(), shiftType);
Id++;
index++;
}
nurseRoster.setShiftTypeList(shiftTypeList);
nurseRoster.setShiftTypeSkillRequirementList(
shiftTypeSkillRequirementList);
int shiftListSize = shiftDateMap.size() * shiftTypeList.size();
List<Shift> shiftList1 = new ArrayList<>(shiftListSize);
dateAndShiftTypeToShiftMap = new HashMap<>(shiftListSize);
dayOfWeekAndShiftTypeToShiftListMap = new HashMap<>(
7 * shiftTypeList.size());
for (ShiftDate shiftDate : shiftDateList1) {
for (ShiftType shiftType : shiftTypeList) {
Shift shift = new Shift();
shift.setId(shiftId);
shift.setShiftDate(shiftDate);
shiftDate.getShiftList().add(shift);
shift.setShiftType(shiftType);
shift.setIndex(shiftIndex);
shift.setRequiredEmployeeSize(0); // Filled in later
shiftList1.add(shift);
dateAndShiftTypeToShiftMap.put(
Pair.of(shiftDate.getDate(), shiftType.getCode()),
shift);
addShiftToDayOfWeekAndShiftTypeToShiftListMap(shiftDate,
shiftType, shift);
shiftId++;
shiftIndex++;
nurseRoster.getShiftList().add(shift);
scoreDirector.afterProblemFactAdded(shift);
}
}
List<DayOffRequest> dayOffRequestList;
List<DayOffRequest> requestList = (List<DayOffRequest>) nurseRoster.getDayOffRequestList();
DayOffRequest oldLastDayOff = requestList.get(requestList.size() - 1);
long DayOffId = (oldLastDayOff.getId() + 1l);
List<DayOffDate> dayOffElementList = rosterService.listDayOffDate();
dayOffRequestList = new ArrayList<>(dayOffElementList.size());
for (DayOffDate element : dayOffElementList) {
DayOffRequest dayOffRequest = new DayOffRequest();
int weight = element.getWeight();
LocalDate shiftDate = element.getDate();
ShiftDate date1 = shiftDateMap.get(shiftDate);
Employee employee = element.getEmployee();
Employee workingEmployee = scoreDirector.lookUpWorkingObject(employee);
dayOffRequest.setId(DayOffId);
DayOffId++;
dayOffRequest.setWeight(weight);
dayOffRequest.setEmployee(workingEmployee);
dayOffRequest.setShiftDate(date1);
workingEmployee.getDayOffRequestMap().put(date1, dayOffRequest);
nurseRoster.getDayOffRequestList().add(dayOffRequest);
}
List<DayOnRequest> dayOnRequestList;
List<DayOnDate> dayOnElementList1 = rosterService.listDayOnDate();
dayOnRequestList = new ArrayList<>(dayOnElementList1.size());
for (DayOnDate element : dayOnElementList1) {
DayOnRequest dayOnRequest = new DayOnRequest();
long DayOnId = element.getId();
int weight = element.getWeight();
LocalDate localshiftDate = element.getDate();
ShiftDate dateon = shiftDateMap.get(localshiftDate);
Employee employee = element.getEmployee();
Employee workingEmployee = scoreDirector.lookUpWorkingObject(employee);
dayOnRequest.setId(DayOnId);
dayOnRequest.setWeight(weight);
dayOnRequest.setEmployee(workingEmployee);
dayOnRequest.setShiftDate(dateon);
dayOnRequestList.add(dayOnRequest);
workingEmployee.getDayOnRequestMap().put(dateon, dayOnRequest);
nurseRoster.getDayOnRequestList().add(dayOnRequest);
}
List<ShiftOffRequest> shiftOffRequestList;
List<ShiftOffDate> shiftOffElementList = (List<ShiftOffDate>) rosterService.listShiftOffDate();
shiftOffRequestList = new ArrayList<>(shiftOffElementList.size());
for (ShiftOffDate element : shiftOffElementList) {
ShiftOffRequest shiftOffRequest = new ShiftOffRequest();
long ShiftonId = element.getId();
int weight = element.getWeight();
Employee employee = element.getEmployee();
Employee workingEmployee = scoreDirector.lookUpWorkingObject(employee);
LocalDate date1 = element.getDate();
String shiftcode = element.getShiftType().getCode();
Shift shift = dateAndShiftTypeToShiftMap.get(Pair.of(date1, shiftcode));
shiftOffRequest.setId(ShiftonId);
shiftOffRequest.setEmployee(workingEmployee);
shiftOffRequest.setShift(shift);
shiftOffRequest.setWeight(weight);
shiftOffRequestList.add(shiftOffRequest);
workingEmployee.getShiftOffRequestMap().put(shift, shiftOffRequest);
nurseRoster.setShiftOffRequestList(shiftOffRequestList);
}
List<ShiftOnRequest> shiftOnRequestList;
List<ShiftOnDate> shiftOnElementList = (List<ShiftOnDate>) rosterService.listShiftOnDate();
shiftOnRequestList = new ArrayList<>(shiftOnElementList.size());
for (ShiftOnDate element : shiftOnElementList) {
ShiftOnRequest shiftOnRequest = new ShiftOnRequest();
long ShiftonId = element.getId();
int weight = element.getWeight();
Employee employee = element.getEmployee();
Employee workingEmployee = scoreDirector.lookUpWorkingObject(employee);
LocalDate date1 = element.getDate();
String shiftcode = element.getShiftType().getCode();
Shift shift = dateAndShiftTypeToShiftMap.get(Pair.of(date1, shiftcode));
shiftOnRequest.setId(ShiftonId);
shiftOnRequest.setEmployee(workingEmployee);
shiftOnRequest.setShift(shift);
shiftOnRequest.setWeight(weight);
shiftOnRequestList.add(shiftOnRequest);
workingEmployee.getShiftOnRequestMap().put(shift, shiftOnRequest);
nurseRoster.setShiftOnRequestList(shiftOnRequestList);
}
List<CoverRequirements> coverRequirementElementList1 = (List<CoverRequirements>) rosterService
.listCoverRequirements();
for (CoverRequirements element : coverRequirementElementList1) {
String type = element.getShiftType().getCode();
DayOfWeek day = element.getDayOfWeek();
int req = element.getRequiredEmployeesize();
ShiftType shiftType = shiftTypeMap.get(type);
Pair<DayOfWeek, ShiftType> key = Pair.of(day, shiftType);
List<Shift> shiftList = dayOfWeekAndShiftTypeToShiftListMap
.get(key);
for (Shift shift : shiftList) {
shift.setRequiredEmployeeSize(
shift.getRequiredEmployeeSize() + req);
}
}
List<ShiftAssignment> shiftAssignmentList = new ArrayList<>(
shiftList1.size());
long shiftAssignmentId = nurseRoster.getShiftAssignmentList()
.get(nurseRoster.getShiftAssignmentList().size() - 1)
.getId() + 1L;
for (Shift shift : shiftList1) {
for (int i = 0; i < shift.getRequiredEmployeeSize(); i++) {
ShiftAssignment newShiftAssignment = new ShiftAssignment();
newShiftAssignment.setId(shiftAssignmentId);
shiftAssignmentId++;
newShiftAssignment.setShift(shift);
newShiftAssignment.setIndexInShift(i);
shiftAssignmentList.add(newShiftAssignment);
nurseRoster.getShiftAssignmentList()
.add(newShiftAssignment);
scoreDirector.afterEntityAdded(newShiftAssignment);
}
}
//This should move the planning window
nurseRosterParametrization.setFirstShiftDate(shiftDateList1.get(0));
nurseRosterParametrization.setLastShiftDate(shiftDateList1.get(shiftDateList1.size() - 1));
nurseRosterParametrization.setPlanningWindowStart(shiftDateList1.get(0));
nurseRoster.setNurseRosterParametrization(nurseRosterParametrization);
scoreDirector.afterProblemPropertyChanged(nurseRosterParametrization);
scoreDirector.triggerVariableListeners();
}, true);
}

How do I convert timespan to OAdate?

I am using Zedgraph and for x-axis, they require us to convert to OADate. I am plotting live stock chart and I want to show the last 60sec.
So I use zedGraphControl1.GraphPane.XAxis.Scale.Max and zedGraphControl1.GraphPane.XAxis.Scale.Min. For the Max value, I will set it to the latest time while for the Min value I plan to set to the latest time minus 60 secs (variable). I will store the 60sec in the type timespan. But the problem is that timespan does not have the function toOADate.
Implement your own method!
all you need to know is
1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds
1 second = 1000 milliseconds
Example: let's say i have time t= 456722622 msec
struct TimeDetailed
{
public int millisec;
public int seconds;
public int minutes;
public int hours;
public int days;
};
static TimeDetailed tConverted;
int t = 456722622;
public void function(int a)
{
int d,h,m,s;
d=h=m=s=0;
while(a >= 86400000) // milliseconds per day
{
a -= 86400000;
d++;
}
while(a >= 3600000) // milliseconds per hour
{
a -= 3600000;
h++;
}
while(a >= 60000) // milliseconds per minute
{
a -= 60000;
m++;
}
while(a >= 1000) // milliseconds per second
{
a -= 1000;
s++;
}
tConverted.days = d;
tConverted.hours = h;
tConverted.minutes = m;
tConverted.seconds = s;
tConverted.millisec = a;
}
function(t);
the output is:
tConverted.days = 5
tConverted.hours = 6
tConverted.minutes = 52
tConverted.seconds = 2
tConverted.millisec = 622
Though I didn't test this code but you can similarly make one