How to select random date in a date range AS3 - actionscript-3

I'm trying to get a random date in a date range and this is what i have so far but it doesnt seem to be working ??
Where I'm I Going wrong ??
//Gets the date difference
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference; }
// gets a random number
function randomRange(max:Number, min:Number = 0):Number {
return Math.round(Math.random() * (max - min) + min); }
protected function getRandomDate:void {
// TODO Auto-generated method stub
var dat1:Date= new Date();
var dat2:Date = new Date(1989, 4, 16)
var num:Number = new Number(differenceBetweenDates(dat2,dat1));
var random:Number= new Number(randomRange(num));
currDate.setDate(dat2.date+random);
getComic(formatDate(currDate));
dat2 = new Date(1989, 4, 16)
}

I found a couple errors in your code.
currDate.setDate(dat2.date+random)
setDate sets the date in the month, not an arbitrary date in time. Also, you want to use dat2.time, not dat2.date.
Should be
currDate.setTime(dat2.time+random)
Here's a slightly different version you might want to try out. I removed the MS_PER_DAY computation, so, you may want to add that back in if you need it, but I found this easier to look at:
public function getRandomTimeBetweenDates(date1:Date, date2:Date):Number
{
return Math.round(Math.random() * (Math.abs(date2.time - date1.time)));
}
public function getRandomDate():Date {
var dat1:Date= new Date();
var dat2:Date = new Date(1989, 4, 16)
dat2.setTime(dat2.time + getRandomTimeBetweenDates(dat2,dat1));
return dat2;
}

Related

Event recurrence number as variable in event description Google App Script Calendar

I have the following code that creates an appointment that recurs 6 times. This is working nicely, however, it would be great if I could access the number of the recurrence in a variable and print that in the title as "appointment 1", "appointment 2", etc. Is this possible with the addWeeklyRule method or would it only be possible with a loop?
var eventSeries = cal3.createEventSeries(name, startTime, endTime, CalendarApp.newRecurrence().addWeeklyRule().times(6), {
description: descriptionText
Found a way to do it without a method but just got the events and changed the title. Had to add a wait step though because it couldn't find the events right after creating them.
Utilities.sleep(5000);
var untilPlanned = new Date(startTime.getTime() + (1000 * 60 * 60 * 24 * 7 * 8));
var startPlanned = new Date(startTime.getTime() - (1000 * 60 * 60 * 12));
//search for events
var eventsPlanned = cal3.getEvents(startPlanned, untilPlanned, {
search: descriptionText
});
for (var k = 0; k < eventsPlanned.length; k++) {
var sessionNo = k + 1;
var title = Sessie: " + sessionNo + "
eventsPlanned[k].setTitle(title);
}

Primefaces LineChartModel: put date in Y axis

I'm using JSF2 and PrimeFaces 5.1.
My problem is that I don't know how to put dates in the Y axis of my graph. It only accepts Number types.
/**
* Graph's definition
* #return LineChartModel
* #throws ParseException
*/
public LineChartModel createLineModels() throws ParseException {
LineChartModel lineChartModel = new LineChartModel();
lineChartModel = initCategoryModel();
lineChartModel.setTitle("Graph's title");
lineChartModel.setLegendPosition("nw");
lineChartModel.getAxes().put(AxisType.X, new CategoryAxis("PV"));
Axis yAxis = this.lineChartModel.getAxis(AxisType.Y);
yAxis.setTickInterval("1");
yAxis.setLabel("Provisional dates");
return lineChartModel;
}
/**
* Initialization of the graph
* #return LineChartModel
* #throws ParseException
*/
public LineChartModel initCategoryModel() throws ParseException {
LineChartModel model = new LineChartModel();
ChartSeries provisionalDates= new ChartSeries();
provisionalDates.setLabel("Dates");
//Here, I set my data in the Graph
//In x-axis the date and the y-axis a numerical value
provisionalDates.set("2016-01-01", 5);
provisionalDates.set("2016-01-15", 8);
model.addSeries(provisionalDates);
return model;
}
My issue are those lines:
provisionalDates.set("2016-01-01", 5);
provisionalDates.set("2016-01-15", 8);
The method set only accept a Numerical value. I want to have date instead.
Do you know a way so I can put my dates in the Y axis?
Thanks
I finally found an answer with jqPlot.
The method set only accept a numerical value so what I did is to convert my date in milliseconds.
long dateMS= myDate.getTime();
provisionalDates.set("2016-01-15", dateMS);
Then, you can add an extender to your chart with PF. The extender allows you to configure your chart:
model.setExtender("extender"); //Works with PF 5+
After that, you just need to make the extender function:
function extender() {
this.cfg.axes.yaxis.tickOptions = {
formatter: function (format, value) {
return $.jqplot.sprintf(convertDate(value));
}
};
}
The convertDate function only convert a getTime to dd/mm/yyyy.
function convertDate(ms) {
var dateReadable = new Date(ms);
var year = dateReadable.getFullYear();
var month = dateReadable.getMonth() + 1;
if (month < 10) {
month = "0" + month;
}
var day = dateReadable.getDate();
if (day < 10) {
day = "0" + day;
}
return day + "/" + month + "/" + year;
}

Flash Builder 4.6 | mx:DataGrid | Decimal to Fraction...or Fraction to Decimal Formatting

My datagrid has a depth-dimensions column that shows fractions (one dimension used for example is 24 3/8). I have the ability to choose the text (fraction or decimal), but essentially I would need to be able to convert back and forth from 24 3/8 to 24.375.
Why the Decimal format is needed:
I have checkboxes to filter the depth-dimensions column, so I'll need decimal form for that logic (e.g. checkbox to see filter depth-dimensions between 20 and 26).
Why the fraction format is needed: I'll need the fraction format because that depth-dimension data will be referenced as a string in another part of the application. The filter doesn't work when in this format is used in the dataGrid, because it won't recognize 24 3/8 as a number/int.
So basically I'm looking for a way to convert between the two formats, 24 3/8 to 24.375 and 24.375 to 24 3/8.
Again, my apologies for the confusion - I'm able to re-edit and/or add more details if needed.
Thanks in advance!
--moe
Why the fraction format is needed: I'll need the fraction format
because that depth-dimension data will be referenced as a string in
another part of the application.
Your reason for needing the fraction format seems odd. Do you understand that you can use a Number data type in a String by casting it?
var decimalNum:Number = 3.14;
//concatenating a Number with a String automatically casts it
var autoCastString:String = "I want to eat some " + decimalNum;
trace(autoCastString);
// cast as String type
var decimalString:String = String(decimalNum);
trace("Mmmm! I like", decimalString);
Output:
I want to eat some 3.14
Mmmm! I like 3.14
But perhaps you have other reasons. The code below is from this link: Decimal to Fraction. I haven't tested it.
package com.lookmum.util
{
public class Fraction
{
private static var it :Number = 0;
public static var iterationLimit:Number = 10000;
public static var accuracy :Number = 0.00001;
public function Fraction()
{
}
private static function resetIt():void
{
it = 0;
}
private static function addIt():Boolean
{
it++;
if (it == iterationLimit)
{
trace('error : too many iterations');
return true;
}
else
{
return false;
}
}
public function getFractionString(num:Number):String
{
var fracString:String;
var fracArray:Array = getFraction(num);
switch (fracArray.length)
{
case 1 :
fracString = num.toString();
break;
case 2 :
fracString = fracArray[0].toString() + '/' + fracArray[1].toString();
break;
case 3 :
fracString = fracArray[0].toString() + ' ' + fracArray[1].toString() + '/' + fracArray[2].toString();
break;
}
return fracString;
}
public function getFraction(num:Number):Array
{
var fracArray:Array = new Array();
var hasWhole:Boolean = false;
if (num >= 1)
{
hasWhole = true;
fracArray.push(Math.floor(num));
}
if (num - Math.floor(num) == 0)
{
return fracArray;
}
if (hasWhole)
{
num = num - Math.floor(num);
}
var a:Number = num - int(num);
var p:Number = 0;
var q:Number = a;
resetIt();
while (Math.abs(q - Math.round(q)) > accuracy)
{
addIt();
p++;
q = p / a;
}
fracArray.push(Math.round(q * num));
fracArray.push(Math.round(q));
return fracArray;
}
}
}

How to get an array of numbers without looping

I would like to create an array of numbers and then randomize those numbers.
Here is what I've come up with. It does two things.
It gets an array from 0 to the length specified. What the main question was about.
It then randomizes the items in that array
// returns [1,2,3,4,5,6,7,8,9,10] except shuffled
var array:Array = getSequenceArray(10);
/**
* Get an array of the range of numbers from 1 to the number specified and randomize them.
* */
public function getRandomArray(count:int):Array {
// this part is not looped. yay!
var array:Array = new Array(count).map(function (item, index) { return index + 1; });
return randomizeArray(array);;
}
/**
* Randomize items in an array
* */
public function randomizeArray(original:Array, cloneArray:Boolean = true):Array {
var length:int = original.length;
var shuffledArray:Array = [];
var newArray:Array = original.slice();
var randomNumber:Number;
// this is still using a loop. this loop is less of an issue than the first
while (length) {
randomNumber = Math.floor(Math.random() * length);
shuffledArray.push(newArray.splice(randomNumber, 1)[0]);
length--;
}
if (!cloneArray) {
original.splice(0, shuffledArray.length);
original.push.apply(this, shuffledArray);
return original;
}
return shuffledArray;
}

Box2D - FRIM (Frame Rate Independent Movement)

I've been trying to implement a FRIM system for my game for the last couple of days.I did some research and came upon this article - it seemed simple enough to implement so I got started.
Everything seems to work fine except I get some temporal aliasing (moving bodies seem to jump ahead a bit) - this happens when more Box2D steps are processed....I think.
private const FIXED_TIMESTEP:Number = 1 / 60;
private const velocityIterations:int = 8;
private const positionIterations:int = 3;
private var fixedTimestepAccumulator:Number = 0;
private var fixedTimestepAccumulatorRatio:Number = 0;
public function Step(dt:Number):void
{
//dt - time between frames - I'm passing the e.passedTime - from the enter frame event; using Starling
fixedTimestepAccumulator += dt;
var nSteps:uint = Math.floor(fixedTimestepAccumulator / FIXED_TIMESTEP);
if (nSteps > 0)
{
fixedTimestepAccumulator = fixedTimestepAccumulator - nSteps * FIXED_TIMESTEP;
}
fixedTimestepAccumulatorRatio = fixedTimestepAccumulator / FIXED_TIMESTEP;
var nStepsClamped:int = Math.min(nSteps, MAX_STEPS);
for (var i:int = 0; i < nStepsClamped; ++i)
{
resetSmoothStates();
singleStep(FIXED_TIMESTEP);
}
world.ClearForces();
smoothStates();
}
private function resetSmoothStates():void
{
for (var bb:b2Body = world.GetBodyList(); bb; bb = bb.GetNext())
{
if (bb.GetUserData() is MyUserData && bb.GetType() != b2Body.b2_staticBody )
{
//each of my bodies have a reference to their sprite (actor) in userData
var _userdata:MyUserData=bb.GetUserData();
_userdata.x = _userdata.bodyPreviousX = bb.GetPosition().x * RATIO;
_userdata.y= _userdata.bodyPreviousY = - bb.GetPosition().y* RATIO;
_userdata.rotation = _userdata.bodypreviousRotation= _userdata.bodypreviousRotation = - bb.GetAngle();
}
}
}
private function smoothStates():void
{
var oneMinusRatio:Number = 1.0 - fixedTimestepAccumulatorRatio;
for (var bb:b2Body = world.GetBodyList(); bb; bb = bb.GetNext())
{
if (bb.GetUserData() is MyUserData && bb.GetType() != b2Body.b2_staticBody )
{
var userdata=bb.GetUserData();
userdata.x = (fixedTimestepAccumulatorRatio * bb.GetPosition().x * RATIO + oneMinusRatio * userdata.bodyPreviousX) ;
userdata.y = (- fixedTimestepAccumulatorRatio * bb.GetPosition().y * RATIO + oneMinusRatio * userdata.bodyPreviousY) ;
userdata.rotation = (- fixedTimestepAccumulatorRatio * bb.GetAngle() + oneMinusRatio * userdata.bodypreviousRotation);
}
}
}
private function singleStep(dt:Number):void
{
Input();
world.Step(dt, velocityIterations, positionIterations);
}
What am I doing wrong?
Any help, suggestions would be highly appreciated.
Thanks
I did this once in a game I was working on so that I could lockstep the game to a certain update rate (this was in iOS). This was based on the code in Daley's book (Learning iOS Game Programming), which was based on some other article in the web (I believe, it may be Allen Bishop's). The code looked like this:
void GameManager::UpdateGame()
{
const uint32 MAXIMUM_FRAME_RATE = Constants::DEFAULT_OBJECT_CYCLES_PER_SECOND();
const uint32 MINIMUM_FRAME_RATE = 10;
const uint32 MAXIMUM_CYCLES_PER_FRAME = (MAXIMUM_FRAME_RATE/MINIMUM_FRAME_RATE);
const double UPDATE_INTERVAL = (1.0/MAXIMUM_FRAME_RATE);
static double lastFrameTime = 0.0;
static double cyclesLeftOver = 0.0;
double currentTime;
double updateIterations;
currentTime = CACurrentMediaTime();
updateIterations = ((currentTime - lastFrameTime) + cyclesLeftOver);
if(updateIterations > (MAXIMUM_CYCLES_PER_FRAME*UPDATE_INTERVAL))
{
updateIterations = MAXIMUM_CYCLES_PER_FRAME*UPDATE_INTERVAL;
}
while (updateIterations >= UPDATE_INTERVAL)
{
// DebugLogCPP("Frame Running");
updateIterations -= UPDATE_INTERVAL;
// Set the random seed for this cycle.
RanNumGen::SetSeed(_cycleManager->GetObjectCycle());
// Dispatch messages.
_messageManager->SendMessages();
// Update all entities.
_entityManager->Update();
// Update the physics
_gameWorldManager->Update(Constants::DEFAULT_OBJECT_CYCLE_SECONDS());
// Advance the cycle clock.
_cycleManager->Update();
}
cyclesLeftOver = updateIterations;
lastFrameTime = currentTime;
}
I can't put my finger on the specific item that is wrong in yours. However, this part is suspicious:
var nStepsClamped:int = Math.min(nSteps, MAX_STEPS);
Before this, you updated your accumulator with:
fixedTimestepAccumulator = fixedTimestepAccumulator - nSteps * FIXED_TIMESTEP;
But now the actual number of steps you are going to execute may be different because of the clamping (nStepsClamped). So your time accumulation is different than the number of steps you actually execute.
Was this helpful?
I decided to go with another approach. I'm using filtered delta times for the physics (I know this can cause some problems).
Here's what I'm doing now:
//Play around with this filter value if things don't look right
var filter:Number=0.4;
filtered_dt= time_between_frames * filter + filtered_dt * (1 - filter);
//Poll imputs and apply forces
// I use velocityIterations =6, positionIterations=3
world.Step(filtered_dt, velocityIterations, positionIterations);
//move sprites here
world.ClearForces();
Another thing you have to do is to scale the forces you apply to your bodies using filtered_dt so things don't "explode" when the frame rate changes a lot.
Hope this helps some one else ... it's not the perfect solution but it works for me.
If you have slow moving bodies the interpolation method above should work fine too.