Angular_time filter - angularjs

I want to make time filter which will show + if time is positive and - if time is negative (I have some calculations received from server), and showing only hours and minutes.
I did folowing, please comment on how this could be better
timeClock.filter('signedDuration', function () {
return function (timespan) {
if (timespan) {
var hoursInDay = 24;
var days = moment.duration(timespan).days();
var hours = moment.duration(timespan).hours();
var totalHours = (days * hoursInDay + hours);
totalHours = totalHours > 0 ? "+" + totalHours
: totalHours;
var minutes = moment.duration(timespan).minutes();
minutes = minutes < 0 ? Math.abs(minutes)
: minutes;
var output = '';
output += totalHours + 'h ';
output += minutes + 'm';
return output;
}
};
});

Related

I need to highlight a datepicker method only for a specific input field

There are 7 input fields in my code but I want to use them for only one. Also there are multiple pages where this datepicker is used all done through a common datepicker directive. I don't want the other pages and input fields to get affected with this change. Here is my code :
beforeShowDay: function(date) {
var month = date.getMonth() + 1;
var year = date.getFullYear();
var day = date.getDate();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
var newDate = month + "/" + day + "/" + year;
if (jQuery.inArray(newDate, highlight_date) != -1) {
//console.log(newDate);
return [true, "highlight"];
}
return [true];
}

React Stopwatch timer not working as expected

Need a React Timer Stopwatch that starts from 00:00:00 i.e., (hh:mm:ss) that estimates the time taken to finish a quiz, tried various things storing things in state.
Something similar to this :
But, setState Makes the app crash.
The Logic :
var seconds = 0, minutes = 0, hours = 0, t;
state = { clock : '' };
componentDidMount()
{
timer();
}
add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
time = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
this.setState({ clock : time });
timer();
}
timer() {
t = setTimeout(add, 1000);
}
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
The View :
</div>
{this.state.clock}
<div>
Any way how to create a Stopwatch with start and stop option in react?
Thanks in advance..!

Display all days(dates) between two dates in angularjs

I want to use select "From" and "To" dates from datepicker and display all dates in between, in tabular form using angularjs.
Try this function to calculate no. of days. Hope it helps
function daysCalculator(date1, date2) {
var d1 = new Date(date1);
var d2 = new Date(date2);
var days = d1.getTime() - d2.getTime();
days = parseInt((((days / 1000) / 60) / 60) / 24)
return days;
}
Try using this.
function getDates(fromDate, toDate) {
var dateArray = [];
var nextDate = fromDate;
while (nextDate <= toDate) {
dateArray.push( nextDate );
nextDate.setDate(fromDate.getDate() + 1);
}
return dateArray;
}

How can I set an interval inside the custom filter

I created a custom date filter, but I want to set an interval for every second to make it run like a clock ecvery second. Thank you in advance
This is my code.
app.filter('DateGap', function() {
// In the return function, we must pass in a single parameter which will be the data we will work on.
// We have the ability to support multiple other parameters that can be passed into the filter optionally
return function update(input, optional1, optional2) {
var t1 = new Date(input + 'Z');
var t2 = new Date();
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var sec_num = Math.floor(Seconds_Between_Dates); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (typeof PenddingHours != "undefined")
return hours >= PenddingHours ? true : false;
if (hours < 10) { hours = "0" + hours; }
if (minutes < 10) { minutes = "0" + minutes; }
if (seconds < 10) { seconds = "0" + seconds; }
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
});
The following will run the filter every second. I am unable to get the filter to work as is, but it logs the updated date in the console so that you can at least see that it is being called each second.
This is just one way to do it. You could also apply the filter to the myDate variable within the controller and skip putting the filter in the markup.
angular.module('intervalExample', [])
.controller('ExampleController', ['$scope', '$interval',
function($scope, $interval) {
$scope.myDate = new Date();
var stop;
$scope.startTimer = function() {
stop = $interval(function() {
$scope.myDate = new Date();
}, 1000);
};
$scope.stopTimer = function() {
if (angular.isDefined(stop)) {
$interval.cancel(stop);
stop = undefined;
}
};
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopTimer();
});
$scope.startTimer();
}
])
.filter('DateGap', function() {
// In the return function, we must pass in a single parameter which will be the data we will work on.
// We have the ability to support multiple other parameters that can be passed into the filter optionally
return function update(input, optional1, optional2) {
console.log(input);
var t1 = new Date(input); // + 'Z');
var t2 = new Date();
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var sec_num = Math.floor(Seconds_Between_Dates); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (typeof PenddingHours != "undefined")
return hours >= PenddingHours ? true : false;
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="intervalExample">
<div ng-controller="ExampleController">
Current time is: <span my-current-time="format"></span> {{ myDate | DateGap }}
</div>
</div>
You can't asynchronously change the output of a filter in angular 1.x. Filters are pure functions, the output depends only on the input which is a constant date in your case. Use a controller to handle the timing:
angular.module('intervalExample', [])
.controller('ExampleController', ['$scope', '$interval',
function($scope, $interval) {
$scope.myTime = 0;
var startTime = Date.now();
var timer = $interval(function() {
$scope.myTime = Date.now() - startTime;
}, 1000);
$scope.$on('$destroy', function() {
$interval.cancel(timer);
});
}
])
.filter('TimeSpan', function() {
// In the return function, we must pass in a single parameter which will be the data we will work on.
// We have the ability to support multiple other parameters that can be passed into the filter optionally
return function update(input, optional1, optional2) {
var dif = input;
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var sec_num = Math.floor(Seconds_Between_Dates); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (typeof PenddingHours != "undefined")
return hours >= PenddingHours ? true : false;
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="intervalExample">
<div ng-controller="ExampleController">
Current time is: <span my-current-time="format"></span> {{ myTime | TimeSpan }}
</div>
</div>

Mixpanel Data to Google Sheets

I am trying to push mixpanel data into a single Google Sheet using code from here:
https://github.com/melissaguyre/mixpanel-segmentation-google-spreadsheets
I am having issues with the API_PARAMETERS not looping through as expected. (Formula, Formula1, & Formula2) The first two parameters loop through fine, but when the final is added, I get the error:
TypeError: Cannot read property "2016-07-11" from undefined. (line 143, file "Code")
Here is the code:
* Step 1) Fill in your account's Mixpanel Information here
`enter code here`*/
var API_KEY = '******';
var API_SECRET = '****';
/**
* Step 2) Define the tab # at which to create new sheets in the spreadsheet.
* 0 creates a new sheet as the first sheet.
* 1 creates a new sheet at the second sheet and so forth.
*/
var CREATE_NEW_SHEETS_AT = 0;
/**
* Step 3) Define date range as a string in format of 'yyyy-mm-dd' or '2013-09-13'
*
* Today's Date: set equal to getMixpanelDateToday()
* Yesterday's Date: set equal to getMixpanelDateYesterday()
*/
var FROM_DATE = getMixpanelDate(7);
var TO_DATE = getMixpanelDate(1);
/**
* Step 4) Define Segmentation Queries - Get data for an event, segmented and filtered by properties.
var API_PARAMETERS = {
'Formula' : [ 'QuestionAsked', '(properties["InputMethod"]) == "Voice" or (properties["InputMethod"]) == "Text" ', 'general', 'day', 'B7'],
'Formula1' : [ 'QuestionAsked', '(properties["InputMethod"]) == "Voice" or (properties["InputMethod"]) == "Text" ', 'unique', 'day', 'B2'],
//'Formula2' : [ 'QuestionAnswered', '(properties["InputMethod"]) == "Voice" or (properties["InputMethod"]) == "Text" ', 'unique', 'day', 'B3' ],
};
// Iterates through the hash map of queries, gets the data, writes it to spreadsheet
function getMixpanelData() {
for (var i in API_PARAMETERS)
{
var cell = API_PARAMETERS[i][4];
fetchMixpanelData(i, cell);
}
}
// Creates a menu in spreadsheet for easy user access to above function
function onOpen() {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
activeSpreadsheet.addMenu(
"Mixpanel", [{
name: "Get Mixpanel Data", functionName: "getMixpanelData"
}]);
}
/**
* Gets data from mixpanel api and inserts to spreadsheet
*
*/
function fetchMixpanelData(sheetName, cell) {
var c = cell;
var expires = getApiExpirationTime();
var urlParams = getApiParameters(expires, sheetName).join('&')
+ "&sig=" + getApiSignature(expires, sheetName);
// Add URL Encoding for special characters which might generate 'Invalid argument' errors.
// Modulus should always be encoded first due to the % sign.
urlParams = urlParams.replace(/\%/g, '%25');
urlParams = urlParams.replace(/\s/g, '%20');
urlParams = urlParams.replace(/\[/g, '%5B');
urlParams = urlParams.replace(/\]/g, '%5D');
urlParams = urlParams.replace(/\"/g, '%22');
urlParams = urlParams.replace(/\(/g, '%28');
urlParams = urlParams.replace(/\)/g, '%29');
urlParams = urlParams.replace(/\>/g, '%3E');
urlParams = urlParams.replace(/\</g, '%3C');
urlParams = urlParams.replace(/\-/g, '%2D');
urlParams = urlParams.replace(/\+/g, '%2B');
urlParams = urlParams.replace(/\//g, '%2F');
var url = "http://mixpanel.com/api/2.0/segmentation?" + urlParams;
Logger.log("THE URL " + url);
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var dataAll = JSON.parse(json);
var dates = dataAll.data.series;
Logger.log(API_PARAMETERS);
for (i in API_PARAMETERS){
var parametersEntry = API_PARAMETERS[i];
for (i in dates){
data = dataAll.data.values[parametersEntry[0]][dates[i]];
}
insertSheet(data, c);
};
}
function insertSheet(value, cell) {
var sheetName = 'Formula';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var c = sheet.getRange(cell).setValue(value);
};
/**
* Returns an array of query parameters
*/
function getApiParameters(expires, sheetName) {
var parametersEntry = API_PARAMETERS[sheetName];
return [
'api_key=' + API_KEY,
'expire=' + expires,
'event=' + parametersEntry[0],
'where=' + parametersEntry[1],
'type=' + parametersEntry[2],
'unit=' + parametersEntry[3],
'from_date=' + FROM_DATE,
'to_date=' + TO_DATE
];
}
/**
* Sorts provided array of parameters
*
function sortApiParameters(parameters) {
var sortedParameters = parameters.sort();
// Logger.log("sortApiParameters() " + sortedParameters);
return sortedParameters;
}
/**
function getApiExpirationTime() {
var expiration = Date.now() + 10 * 60 * 1000;
// Logger.log("getApiExpirationTime() " + expiration);
return expiration;
}
/**
* Returns API Signature calculated using api_secret.
*/
function getApiSignature(expires, sheetName) {
var parameters = getApiParameters(expires, sheetName);
var sortedParameters = sortApiParameters(parameters).join('') + API_SECRET;
// Logger.log("Sorted Parameters " + sortedParameters);
var digest = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, sortedParameters);
var signature = '';
for (j = 0; j < digest.length; j++) {
var hashVal = digest[j];
if (hashVal < 0) hashVal += 256;
if (hashVal.toString(16).length == 1) signature += "0";
signature += hashVal.toString(16);
}
return signature;
}
/**
*********************************************************************************
* Date helpers
*********************************************************************************
*/
// Returns today's date string in Mixpanel date format '2013-09-11'
function getMixpanelDateToday() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if ( mm < 10 ) {
mm = '0' + mm;
}
today = yyyy + '-' + mm + '-' + dd;
return today;
}
// Returns yesterday's's date string in Mixpanel date format '2013-09-11'
function getMixpanelDate(days){
var today = new Date();
var d = new Date(today);
d.setDate(today.getDate() - days);
//Logger.log(yesterday);
var dd = d.getDate();
//Logger.log(yesterday);
var mm = d.getMonth() + 1;
var yyyy = d.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
d = yyyy + '-' + mm + '-' + dd;
//Logger.log(yesterday);
return d;
}

Resources