calculation to show image on website every 3rd week - javascript

I have a grails project where need to show on call team icon on home page. there are three images for three team. teams rotate every 3 week so for example team 1 logo will show first (1)and last week(4) of month and so one..
I have tried putting in db table for all 52 weeks and team no and putting it in session-
code in service-
sql.query("SELECT * FROM tbl_ImageForTeamUser where weekno=?",[wkno])
{ rs ->
while (rs.next()) {
def userinf = new UserInfo()
userinf.weekno= rs.getInt("weekno")
userinf.teamname= rs.getString("teamname")
userinf.teamno= rs.getInt("teamno")
items.add(userinf)
}
}
Saved in session-
session.weekno= items[0].teamno()
UI looks like-
<tr>
<g:if test="${session.weekno == "1" }">
<td class="team1" align="right" nowrap></br></br></td>
</g:if>
<g:if test="${session.weekno == "2"}">
<td class="team2" align="right" nowrap></br></br></td>
</g:if>
<g:if test="${session.weekno == "3" }">
<td class="team3" align="right" nowrap></br></br></td>
</g:if>
but somehow this is not looking a good solution. please suggest a better ,coding suggestion .dont want to use DB and handle it on UI side.

The cal.get(Calendar.WEEK_OF_MONTH) will give you 1 2 3 4 5 or the the week of the month it is.
You can use this to print the correct order without having to store it in a database table. because you only have 3 unique ordering of the pictures if I understand your question correctly.
Calendar cal = Calendar.getInstance()
def weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH)
def teamImageCountShown = weekOfMonth % 3
if(teamImageCountShown==1){
//Display 1 2 3
}
if(teamImageCountShown==2){
//Display 2 3 1
}
if(teamImageCountShown==0){
//Display 3 1 2
}

Related

how to display different colors on each column of a row using ngClass in agular?

I have 4 rows, each row contains 3 cards.
I am fetching information for these cards from db then rendering them using ngfor in html.
The problem is I want each of card of a row to show different color.
Example:->
ROW 1:
BLUECARD | WHITECARD | REDCARD
ROW 2:
BLUECARD | WHITECARD | REDCARD
as of now I able to do for two colors but how can I make it for 3 colors as I stated in example.
<div *ngFor="let r of rates; let i=index;">
<div class="box" [ngClass]="i % 2 == 0 ? 'BLUECARD' : 'REDCARD'">
<!-- card contents -->
</div>
</div>
As you can see I am able to show 2 colors alternatively but how can I show 3 colors instead?
I would create an string array with your colors and then [ngClass]=colorArray[i] or something similar.
you can try these (meanwhile i am using silly logic for example only) :-
[ngClass]="{1 : 'BLUECARD', 2 : 'REDCARD', 3 : 'WHITECARD'}[i % 2]"
or
[ngClass]="{'BLUECARD': i % 2 === 0, 'REDCARD' : i % 2 !== 0, 'WHITECARD': i % 2 === undefined }"
I had to do something like this
I created a function that returns a color based on what you give it as a parameter;
In your case, you can create a function that takes i as parameter and returns a color
<div class="box" [ngStyle]="{'background-color':giveCouleur(i)}">
<!-- card contents -->
</div>
In your ts file
giveCouleur(i:any){
var color="default_color";//or null if you want
if(i%2==0){
color="Your_colr";
//ex:color="#ffffff"
}else if(i%3==0){
color="your_color";
}else{
color="your_color"
}
//In this case, you can create as many conditions as you want.
return color;
}
you can try with ngClass
<div class="box" [ngClass]="{giveCouleur(i)}">
<!-- card contents -->
</div>
giveCouleur(i:any){
var color="default_color";//or null if you want
if(i%2==0){
color="BLUECARD";
}else if(i%3==0){
color="REDCARD";
}else{
color="WHITECARD"
}
//In this case, you can create as many conditions as you want.
return color;
}

Comparing the value of a key in an array of objects to a variable in AngularJS

I have a table called follower_tb. The columns in the table are like this: follow_id (this is the primary key), follower_id(the id the person that followed another person), followed_id (the id of the person that is being followed).
In order to fetch the table, I wrote this sql statement.
SELECT p.participant_id,
p.username,
p.fullname,
p.profile_pics,
f.follow_id,
f.follower_id,
f.followed_id
FROM participant_tb p
JOIN follower_tb f ON ( p.participant_id = f.followed_id )
WHERE followed_id = 1 || follower_id = 1
I will be neglecting the participant_tb in my result and go straight to the main point. My result look like this
[{
follow_id: 1,
follower_id: 1,
followed_id: 2
}, {
follow_id: 2,
follower_id: 2,
followed_id: 1
}, {
follow_id: 3,
follower_id: 1,
followed_id: 3
}, {
follow_id: 3,
follower_id: 4,
followed_id: 1
}]
from this, it means the persons with the id of 1 and the id of 2 are following each other. The person with with the id of 1 is following the person with the id of 3 but the person with the id of 3 is not following back. Lastly, the person with the id of 4 is following the person with the id of 1 but he/she is not following back.
I got the result into a scope ($scope.allfollowing) and I used ng-repeat (x in allfollowing) to loop through at the view.
The owner of the account(the person with an id of 1) already has his/her id saved in a scope( $scope.signedin_id).
My main issue is that, I want to display only one of these two buttons using ng-if of angularjs. The first button is the unfollow (this should be displayed in the first case because the two are following each other. It should also be displayed in the second case, because the person with the id of 1 is already following the person with the id of 3), the second button is the followback( this should be displayed in the third case because the person with the id of 1 is yet to follow the person with the id of 4).
I could have used something like this:
ng-if="x.follower_id == signedin_id"
ng-if="x.followed_id == signedin_id"
But the problem is that: for the person with the is of 2(who is following Id of 1 and he is also following back), both buttons will be displayed, how can I solve this problem?
I will be glad if someone show me an effective way to go about this.
Not sure if this is how you want to display the buttons, but maybe you could do something like this:
<div ng-repeat="x in allfollowing">
<button ng-if="x.follower_id == signedin_id" click="unfollow(x.followed_id)">
Unfollow {{x.followed_id}}
</button>
<button ng-if="x.followed_id == signedin_id && notfollowed(x.follower_id)" click="followback(x.follower_id)">
Follow {{x.follower_id}} back
</button>
</div>
notfollowed(string id){
for x in allfollowing{
if (x.followed_id == id){
return false
}
}
return true;
}

Javascript data needs to display HTML output as columns once the following year is evaluated

I have data from last 3 years that I need to display as YEARS for each column.
In C# /asp.net I am looping through and getting all the data and then in javascript I end up looping through the data and then just appending rows to a table.
The problem with this is that since the data goes from 2015 records to then onto 2014 and then 2013 that I will end up with 1 column and many rows
However I want to break it about and show it as
2015 2014 2013
a a a
b b b
Thus how can I do that with the data? I though about Pivoting the data, and I though about div tags , but nothing seems that clear to me
Mockup
Update
I see in another project that this was done in angular (not relevant to my issue) but the way in which it was done was to assume that there was ALWAYS data in each month folder for each year, however, this is not the case to which I have only 4 months to display for 2015
Example of the existing code:
<table class="table-light">
<tr>
<th ng-repeat="year in years"><h2>{{ year }}</h2></th>
</tr>
<tr ng-repeat="month in months">
<td ng-repeat="year in years" class="text-center">
<!-- directory path predicted based on history -->
<a target="_blank" class="link"
href="http://Logs\{{ year }} LOGS\{{ month.number }} - {{ year }}\&file=pdf">{{ month.title }}</a>
</td>
</tr>
</table>
Update 2
My data from chrome console looks like this
Then what I have showing on the web page ends up showing the 2015 months with data, but then It shows that I have files in the month January thus it is getting displayed
3 months from 2015 then 1 month of 2016 , so thus my c# code is correctly knowing to only return the month folders which have files, but I want to arrange them into 3 columns ( I want to display 3 years 2016, 2015, 2014)
I only want to show 1 distinct month if a month contains 1 to many files thus the logic in the javascript below
var strResult = "";
var month = "";
var final = "";
strResult = "<table class='table-light' id='myTableId'><thead><tr><th style='text-align:left;'><h2>2015</h2></th></tr></thead><tbody>";
var unique = {};
var distinct = [];
for (var i in files) {
if (typeof (unique[files[i].shortMonth]) === "undefined") {
distinct.push(files[i].shortMonth);
// do the work here
month = files[i].month;
if (month === "" || month === null) {
month = "";
}
strResult += "<tr><td><a target='blank' class='link ng-binding' href='files.html?id=sub&year=" + files[i].year + "&month=" + files[i].shortMonth + "' onclick=\"getFiles('" + files[i].year + "','" + files[i].shortMonth + "');\">" + month + "</a></td></tr>";
final += month + ",";
}
unique[files[i].shortMonth] = 0;
}
So hopefully that makes more sense as I know how to loop through javascript, but I want to end up displaying the html with the "look" of the screenshot under the word Mockup
However, with the caveat that that the reality is the data as it stands will really only show
2016 2015 2014
January August July
September August
October December

conditionally format php output with javascript

I would like to conditionally apply (based on date and time) with Javascript different CSS styles on a <div> element that contains data output with Php from a Mysql database. The php generates a list of events into various <div>s, where a <div> would receive different coloring depending on the date/time it holds relative to the actual day. (So if the event date/time is in the future, the color would be blue, if in the past, grey.)
I understand a PHP solution would use the server's date/time, while javascript would use the browser's date/time, so I selected javascript for the conditional formatting based on date/time.
I also understand that javascript needs to wait until the whole page loads, including the result of the php query.
(I also understand that I know very little about javascript and php.)
Below is the html and php code I have. This php queries the first 10 events and presents them in a list ordered by date in a bootstrap table. The div #timecode is which I would like to conditionally format (this sample php code does not contain the pagination php code, and returns the first 10 records from the database):
<div class="row">
<div class="venuelista">
<div class="col-sm-9 col-md-9 col-lg-9">
<table class="table">
<tbody>
<?php
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<tr>
<td class="col-md-7">
<div id="timecode" padding="right:5px"><?php echo $row['esemeny_disp_mm_dd']; ?></div>
<div class="eventListTitle"><?php echo $row['esemeny_cim']; ?><br><?php echo $row['esemeny_jelleg']; ?></div>
</td>
<td class="col-md-5">
<div class="eventListTitle"><?php echo $row['esemeny_helyszin']; ?>
</div>
</td>
</tr>
<?php
};
?>
</tbody>
</table>
</div>
</div>
In the Mysql database I have and 'event date' field and a separate 'event time' field.
And this is the javascript I found on the net, maybe on this site, to format the div #timecode on the basis of its date/time (this is just testing if it works against a fix date - it does):
<script>
$(document).ready(function() {
var curtime = new Date(),
curday = curtime.getDate(),
curmonth = curtime.getMonth()+1;
if(curmonth == 7 && curday == 20)
$('#timecode').addClass('circle-disappear-blue');
else
$('#timecode').addClass('circle-disappear-grey');
});
</script>
Problem: javascript only formats the very first php result of the list. I thought the $(document).ready(function() would allow it to format all 10 list items.
Again I am sorry for malformatting my question - I am not on mutual understanding with the code sample function.
Any insight into this is appreciated.
EDIT:
The javascript now looks like this
<script>
$(document).ready(function() {
$('#mytableid tr td:first-child').addClass('circle-disappear-blue');
var curtime = new Date(),
curday = curtime.getDate(),
curmonth = curtime.getMonth()+1;
if(curmonth == 7 && curday == 19)
$('#blue-condtional').addClass('circle-disappear-blue');
else
$('#blue-condtional').addClass('circle-disappear-grey');
});
</script>
add id to your table for example
<table class="table" id="mytableid">
then use proper selector
$('#mytableid tr td:first-child').addClass('circle-disappear-blue');
the other option is to add class to types that you want change color let's say "blue-condtional"
if(curmonth == 7 && curday == 20) {
$('.blue-condtional').addClass('circle-disappear-blue');
} else {
$('.blue-condtional').addClass('circle-disappear-grey');
}
and change
<div id="timecode" padding="right:5px">
to
<div class="blue-condtional">
btw using inline styles is not good habbit.

Angular performance issues, ng-repeat, unwanted callbacks

I'm facing some serious performance issues in my angular app, surely due to my bad ng-repeat implementation but I don't know how to do better. I've tried some other combinations but none give me the result I want, nor better performance. There have been some infinite loops, undefined variables due to asynch and $digest aborting.
This is how it should be looking (so that's the working result, but not optimized for now) : http://scr.hu/0ei9/8bpw9
Days with blue cells = user is present, red cell = absent. Beneath are the "shifts" per day (each shift can be done on various days).
When I console.log some of the functions, they are called way too many times than needed, for example isPresent (for checking if the user submited the day as available) is called 5x180 (180 being probably 5 users x 30 days of month) and getDayOfWeek (used in template for the shifts row) 28+840+812...there are 10 shifts. Whereas I would normally need to call isPresent only 1x180 for all cells and getDayOfWeek 1x30 days of month for one shifts row. That said, I don't really get why its called sooo many times and how to optimize it.
In addition, when I click on a blue cell, the setShift() function is called. I copied the function here but don't analyze it, I only wanted to show that it nowhere calls any of the previous functions, however I console.log an impressive 28x "days of the week" + 180 "is present" and + 812 "day of the week". No Idea where it comes from... to be frank, everything i click calls this same amout - if I change the month, year, click on an independent button...
I omitted some classes and css for better code reading.
Thanks for your help.
Edit
after commenting and decommenting some of the code I see that the most of those unwanted logs when I call the setShift() function come from the last sub-call : showPopover() where I open a $modal. When commented, there is like 1/3 of what I'm used to see. Before the modal appears there is the rest of this stuff. Furthermore I think that the temlpateUrl might be the cause because when commented it does not log all those houndreds of 'is present' and 'day of week'. And when I click anywhere on the modal, it recalls all those functions. Any ideas?
JS angular functions
$scope.isPresent = function(day, month, year, userId) {
console.log('is present')
var date = new Date(year, month - 1, day + 1)
var day = moment(date).format("D-M-YYYY");
for (var i = 0; i < $scope.presences.length; i++) {
var presentDay = moment($scope.presences[i].start).format("D-M-YYYY")
if (presentDay == day && userId == $scope.presences[i].coursierId) {
return true
}
}
}
$scope.getDayOfWeek = function(day, month, year) {
console.log('day of the week')
var date = new Date(parseInt(year), month - 1, day + 1)
var dayId = date.getDay();
return dayId;
}
/*
used for a limited ng-repeat
*/
$scope.getTimes = function(n) {
return new Array(n);
};
/*
Shows a list of sorted out shifts with corresponding
hours, cities and capabilities of coursier.
*/
$scope.setShift = function(day, month, year, userId, event) {
var date = new Date(year, month - 1, day)
var day = moment(date).format("D-M-YYYY");
var dayOfWeek = moment(date).day()
//SORT SHIFTs BY DAY OF WEEK clicked
var day_shifts = $scope.sortShiftByDayOfWeek(dayOfWeek)
//console.log(day_shifts)
//check if the day clicked is an dispo present day
for (var i = 0; i < $scope.presences.length; i++) {
var dispoDay = moment($scope.presences[i].start).format("D-M-YYYY")
//if yes, check the presence user id and the cell of user clicked
if (dispoDay == day) {
//then get all the shifts that fit into this coursier's time range
if ($scope.presences[i].coursierId == userId) {
var dispo = $scope.presences[i];
var dispoHours = $scope.getDispoHoursAndDay(dispo);
var time_shifts = $scope.compareDiposHoursAndShift(dispoHours, day_shifts);
//then sort the shifts by the dispo's and shift's cities
var time_city_shifts = $scope.compareDispoCityAndShift(time_shifts, dispo);
var time_city_able_shifts = $scope.compareUserAndShift(time_city_shifts, userId);
$scope.showPopover(time_city_able_shifts, event);
}
};
};
}
###Calendar table
<table class="table table-bordered">
<!--days of month-->
<tr class="mainHeader">
<th>coursier/jour</th>
##calendar.days = 30 days of month, for example
<th class="monthDay" ng-repeat=" numDay in [] | range: calendar.days">{{$index+1}} {{calendar.daysNames[$index]}}
</th>
</tr>
<!-- user name and days -->
<tr ng-repeat="user in coursiers">
<!-- <td class="coursierName">nom coursier</td> -->
<td>
{{user.name}}
</td>
<td ng-click="setShift($index+1, monthNum,year, user._id, $event)" ng-repeat="numDay in getTimes(calendar.days) track by $index" ng-class=" isPresent($index, monthNum,year, user._id) == true ?
'present' : isAbsent($index, monthNum,year, user._id) == true ?
'absent' : '' ">
</td>
</tr>
<tr>
<td>Shifts par jour</td>
<td class="shiftsParJourCell" ng-repeat="day in getTimes(calendar.days) track by $index">
<span ng-repeat="shift in shifts">
<span ng-repeat="jour in shift.jours">
{{jour.id ==
getDayOfWeek($parent.$parent.$index, monthNum, year) ? shift.nom : ''}}
</span>
</span>
</td>
</tr>
</table>
After a while, in my case the problem was that I wasn't using directives.
The scopes were having unwanted interactions (still don't know why) but after separing my html in angular directives there are no issues so far.

Categories