Convert a list of selected days to its hyponym - ios

I have list of days (from monday till sunday).
When a user selects monday till friday or saturday and sunday I want my app to show it's hyponym (weekdays/weekends).
Does iOS provide some default functionality for this (If i'm not mistaken the iOS Alarm app does the same) or do I have to write this functionality myself?

Provided that you have a NSArray with the selected days as numbers, named selectedDays, and that 0 and 6 are weekend days:
NSString *name = nil; // Fill this with the default values (concatenate all names of selected days)
bool days[] = {0,0,0,0,0,0,0};
for (NSNumber *day in selectedDays)
{
int d = [day intValue];
if (d >= 0 && d <= 6) days[d] = true;
}
if ( days[0] == true
&& days[1] == false
&& days[2] == false
&& days[3] == false
&& days[4] == false
&& days[5] == false
&& days[6] == true)
{
name = #"Weekend";
}
if ( days[0] == false
&& days[1] == true
&& days[2] == true
&& days[3] == true
&& days[4] == true
&& days[5] == true
&& days[6] == false)
{
name = #"Weekdays";
}

Related

CoreMotionActivityManager returning either Automotive or Automotive + Stationary true

I'm trying to detect Automotive ActivtyType, however the problem is if "I go on a drive and then stop the car and stay in the car" and simply check the coreMotion logs: I would continue to get numerous mixed callbacks of either
high Confidence: Automotive: True, Stationary: True
or
high confidence: Automotive: True, Stationary: False
or
low confidence: Automotive: True, Stationary: True
I do not get an only Stationary: True, it always comes with automotive
being True as well
There's not much of a pattern to how they come, or at least I haven't been able to find a pattern.
Q: Has anyone found a reliable way of detecting when the car is truly automotive?
I've tried counting the number of callbacks I get and then doing some calculation but that doesn't seem reliable.
FWIW the moment the user gets out of the car then I get either a walking or stationary (with no automotive...which is good) callback and use those callbacks to set a flag to true...so after that if I get any automotive callback...then I know it’s a real automotive...
My code:
func beginMotionTracking(){
let motionLog = OSLog(subsystem: "Spike", category: "Motion")
shouldUseTimer = false
motionActivityManager = CMMotionActivityManager()
var totalWalking = 0
var totalAutomotive = 0
var totalStationary = 0
var totalFalseAutomotive = 0
motionActivityManager?.startActivityUpdates(to: OperationQueue.main){
[weak self] activity in
os_log("Motion is Tracking | desiredAccuracy is %{public}f | RemainingTime : %{public}f ",log: motionLog, type: .default, (self?.locationManager.desiredAccuracy)! , UIApplication.shared.remainingTime())
if activity?.walking == true && (activity?.confidence == .medium || activity?.confidence == .high) && activity?.automotive == false && activity?.stationary == false && activity?.unknown == false {
totalWalking += 1
os_log("medium and high conf: walking %{public}d time", log: motionLog, type: .error, totalWalking)
}else if activity?.stationary == true && (activity?.confidence == .medium || activity?.confidence == .high) && activity?.automotive == false && activity?.walking == false && activity?.unknown == false {
totalStationary += 1
os_log("medium and high conf: stationary %{public}d time", log: motionLog, type: .error, totalStationary)
// false automotive
}else if activity?.automotive == true && activity?.stationary == true && (activity?.confidence == .high) && activity?.walking == false && activity?.unknown == false {
totalFalseAutomotive += 1
os_log("high conf: FALSE Automotive %{public}d time", log: motionLog, type: .error, totalFalseAutomotive)
if totalFalseAutomotive > 2{
totalFalseAutomotive = 0
totalAutomotive = 0
totalStationary = 0
totalWalking = 0
os_log("Too many FALSE automotives, REST all counts back to 0", log: motionLog, type: .fault)
}
}
else if activity?.automotive == true && (activity?.confidence == .high) && activity?.walking == false && activity?.stationary == false && activity?.unknown == false {
totalAutomotive += 1
os_log("high conf: Automotive %{public}d time", log: motionLog, type: .error, totalAutomotive)
if ((totalWalking > 3 && totalAutomotive > 2) || (totalStationary > 3 && totalAutomotive > 2) || (totalAutomotive > 7)){
self?.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
os_log("Motion is Automotive and is about to be stopped: desired AccuracyChanged to HundredMeters | RemainingTime : %{public}f ", log: motionLog, type: .fault, UIApplication.shared.remainingTime())
self?.shouldUseTimer = true
self?.motionActivityManager?.stopActivityUpdates()
}
}
}
}
I'm going through all this hassle, because I'm trying to degrade my core-location Accuracy whenever the user isn't driving for more than 3 minutes and then later using core-motion to detect automotive Motion and use that to put back location Accuracy to hundredMeter.
This is what works for my similar use case, where I want to aggressively restrict interaction when .automotive has become set, but where I'm ok allowing an easy restoration of interaction if it becomes stationary. In logging the messages, it seems to hold onto the .automotive until another mode is detected (e.g. walking)
Since I commute on a bus with WiFi in heavy traffic, I saw repeated messages of:
confidence low, stationary true, automotive true
confidence high, stationary false, automotive true
....
They toggle as such over and over (and I never saw any medium confidence activities) and only when stationary for a sufficient time (10-12s) does the confidence to go high with stationary true, automotive true so I key off that.
Here's the code that I got to work:
func handleMotionActivityUpdates(activity: CMMotionActivity?) {
if let a = activity {
if a.automotive && !a.stationary && (a.confidence == .medium || a.confidence == .high) {
//restrict interaction
} else
if (!a.automotive || a.stationary) && (a.confidence == .medium || a.confidence == .high) {
//re-enable interaction
}
}
}

rails custom date validation

In the form the user has to choose a month and a year. I'd like to make sure that the date is not in the future based on the month. So let's say the current date is 07/01/2016 in which case the user should be able to choose 07/2016 but shouldn't be able to choose 08/2016.
The validation seems to be working, but doesn't look well. Is there an easier way
achieve this?
validate :founded_in_the_past
def founded_in_the_past
if founded && ((founded.month > Date.current.month && founded.year == Date.current.year)
&& founded.year > Date.current.year)
errors.add :base, "Founding date must be in the past."
end
end
Instead of checking with month and year why you are not comparing date directly by creating date object using month and year.
validate :founded_in_the_past
def founded_in_the_past
if founded && (Date.new(founded.year, founded.month, 1) > Date.current)
errors.add :base, "Founding date must be in the past."
end
end
In your code if you select year as 2017 and month as 5 - it will allow to select this date
founded && ((founded.month > Date.current.month &&
founded.year == Date.current.year) &&
founded.year > Date.current.year)
founded = true
founded.month > Date.current.month = false
founded.year == Date.current.year = false
founded.year > Date.current.year = true
If we map this in your condition you condition will look like
true && ((false && false) && true)
This will return false and it will allow user select future date
You can cut out one conditional by using >= eg
if founded && (founded.month > Date.current.month && founded.year >= Date.current.year)

If statement not running - iOS [duplicate]

This question already has answers here:
Quicker if-statement: if `variable` is "value" or "value"
(7 answers)
Closed 7 years ago.
I have a iOS app with a few simple and logical if-statements. However they wont run and I can't understnad why. Here is my simple code:
-(void)viewDidLoad {
[super viewDidLoad];
// Run setup code.
int day = [self currentDay];
if ((day == (1 || 3 || 7) && (day != (2 || 4 || 5 || 6))) {
// Run the calendar setup code for
// Sunday/Tuesday OR saturday.
[self runSetupVX_4];
}
else if ((day == (2 || 4 || 5 || 6)) && (day != (1 || 3 || 7))) {
// Run setup code for Monday
// wednesday, thursday and friday.
[self runSetupVX_2];
}
}
-(int)currentDay {
NSDateComponents *component = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]];
return [component weekday];
}
What am I doing wrong here?
This compiles, but it does something completely different from what you are trying to achieve:
day == (1 || 3 || 7) && (day != (2 || 4 || 5 || 6)
The statement ORs 1, 3, and 7, and then ORs 2, 4, 5, and 6, before performing comparisons.
A proper way to do it is to compare day to 1, 3, and 7 separately. If any of the comparisons is successful, it's also guaranteed that the day is not 2, 4, 5, or 6:
if (day == 1 || day == 3 || day == 7)
...
if (day == 2 || day == 4 || day == 5 || day == 6)
...
You could also rewrite this with a switch:
switch(day) {
case 1:
case 3:
case 7:
// Run the calendar setup code for
// Sunday/Tuesday OR saturday.
[self runSetupVX_4];
break;
case 2:
case 4:
case 5:
case 6:
// Run setup code for Monday
// wednesday, thursday and friday.
[self runSetupVX_2];
break;
}
You're overcomplicating it a bit.
if(day==1 || day==2 || day==3){
[self runSetupVX_4];
}else{
[self runSetupVX_2];
}
Should do the trick
If the first part of each if statement is true, then the second part will be false every time. So you don't have to check the second part.
You can modify your code like this:
-(void)viewDidLoad {
[super viewDidLoad];
// Run setup code.
int day = [self currentDay];
if (day ==1 || day==3 || day==7) {
// Run the calendar setup code for
// Sunday/Tuesday OR saturday.
[self runSetupVX_4];
}
else{
// Run setup code for Monday
// wednesday, thursday and friday.
[self runSetupVX_2];
}}
-(int)currentDay {
NSDateComponents *component = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]];
return [component weekday];
}
Hope this works for you:
if (day == 1 || day == 2 || day == 3) {
// Run the calendar setup code for
// Sunday/Tuesday OR Saturday.
[self runSetupVX_4];
}
else if (day == 2 || day == 4 || day == 5 || day == 6) {
// Run setup code for Monday
// Wednesday, Thursday and Friday.
[self runSetupVX_2];
}
You can put break point at if statement and then check that if statement is get called or not.
-(void)viewDidLoad {
[super viewDidLoad];
// Run setup code.
int day = [self currentDay];
//if ((day == (1 || 3 || 7) && (day != (2 || 4 || 5 || 6))) {
//here u will get 0 or 1 from this (1 || 3 || 7) && (day != (2 || 4 || 5 || 6)))
//And u r comparing with 0 or 1 with day so please check below code how to compare
if (((day == 1 || 3 || 7) && (day != 2 || 4 || 5 || 6)) {
// Run the calendar setup code for
// Sunday/Tuesday OR saturday.
[self runSetupVX_4];
}
else if ((day == 2 || 4 || 5 || 6)&& (day != 1 || 3 || 7)) {
// Run setup code for Monday
// wednesday, thursday and friday.
[self runSetupVX_2];
}
}
-(int)currentDay {
NSDateComponents *component = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]];
return [component weekday];
} //you have problems with comparing variable please check it

How to get distinct value from the list

I have a List generated from Linq to Entities query. In which, I need to get a unique records based on BibId. I have tried changing the query but no help to get the unique records based on BibId.
Query
aa.NewBibContentsModel = (from x in db.BibContents
where (x.TagNo == "245" && x.NormValue == aa.CurrentTitle) || (x.TagNo == "020" && x.NormValue == aa.CurrentISBN) || (x.TagNo == "022" && x.NormValue == aa.CurrentISBN)
select new
{
BibId = x.BibId,
Title = (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == "245" orderby a.Id ascending select a.NormValue),
//Tit = (from a in db.BibContents where a.BibId == line.BibId && a.TagNo == "245" && a.Sfld == "a" select a.NormValue).FirstOrDefault(),
Author = (from a in db.BibContents where a.BibId == x.BibId && splitted.Contains(a.TagNo) && a.NormValue != null select a.TagNo).FirstOrDefault(),
ISBN = (from a in db.BibContents where a.BibId == x.BibId && a.NormValue != null && (a.TagNo == "020" || a.TagNo == "022") orderby a.Id ascending select a.NormValue)
}).AsEnumerable().Select(x => new BibContentsModel
{
BibId = x.BibId,
Title = string.Join(" ", x.Title),
Author = string.Join(" ", (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == x.Author orderby a.Id select a.NormValue)),
ISBN = string.Join(" ", x.ISBN)
}).ToList();
Any help to this problem will be appreciated.
Thanks
What you're trying to achieve is know as Distinct By. MoreLinq has a function for it. The syntax would look like:
(from x in db.BibContentsNo == "022")
... // your query
}).AsEnumerable()
.DistinctBy(x => x.BibId) // <= MoreLinq
What is does is group the records by BibId and take the first element of each group.
You can download MoreLinq as a NuGet package.

asp.net mvc datettime linq check for empty

var postsidebar = from post in postrepository.GetAllPosts()
join pstmt in postrepository.GetAllPostMetas()
on post.int_PostId equals pstmt.int_PostId
where (post.int_PostTypeId == 4
&& post.int_PostStatusId == 2
&& post.int_OrganizationId == layoutrep.GetSidebarDetailById(SidebarDetailsId).int_OrganizationId)
&& (pstmt.vcr_MetaKey.Contains(filter) && pstmt.vcr_MetaValue.Contains("true")
&& (System.DateTime.Now >=
Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m =>
m.vcr_MetaKey == "Publish Date").vcr_MetaValue)))
select post;
how can i check for empty in this part in Date(it is giving error)
&& (System.DateTime.Now >= Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m =>
m.vcr_MetaKey == "Publish Date").vcr_MetaValue)))
You could try eliminated the possibility of an empty value first and then try your cast afterward.
&& pstmt.Post.PostMetas.FirstOrDefault(m =>
m.vcr_MetaKey == "Publish Date"
&& !string.IsNullOrEmpty(m.vcr_MetaValue))
&& (System.DateTime.Now >=
Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m =>
m.vcr_MetaKey == "Publish Date").vcr_MetaValue)))
Try this:
// declare the action for re-use
Func<PostMeta,bool> action = m => m.vcr_MetaKey == "Publish Date";
// then test for Any() before comparing anything
&& (pstmt.Post.PostMetas.Any(action) && System.DateTime.Now >= Convert.ToDateTime(pstmt.Post.PostMetas.First(action).vcr_MetaValue)))

Resources