I have a pretty detailed while-loop and have been really resisting having to ask for help once again but I am at a loss! I really apologize for this while-loop code, there's a lot going on but I don't want to leave anything out just in case you viewers require to see it all.
func retRhoCurrent() -> Double {
while abs(pTarget - pCalc) > 1 {
//
// SET rhoCurrent
//
if (pTarget > pCalc) {
rhoLow = rhoCurrent
if(rhoCurrent >= rhoHigh) {
rhoCurrent += RHO_C
rhoHigh = rhoCurrent
} else {
rhoCurrent += ((rhoHigh - rhoCurrent)/2)
}
} else {
rhoHigh = rhoCurrent
rhoCurrent += ((rhoLow - rhoCurrent)/2)
}
//
// SET rhoR
//
rhoR = rhoCurrent / RHO_C
//
// SET DIFFERENTIAL
//
diffAggregate = 0
for var kIndex = 0; kIndex < NK_VALUES.count; ++kIndex {
diffSegment = NK_VALUES[kIndex]
diffSegment *= pow(rhoR, IK_VALUES[kIndex])
diffSegment *= pow(tempR, JK_VALUES[kIndex])
iFactor = 0
if LK_VALUES[kIndex] > 0 {
diffSegment *= exp(-1 * pow(rhoR, LK_VALUES[kIndex]))
iFactor = LK_VALUES[kIndex] * pow(rhoR, LK_VALUES[kIndex])
}
if PK_VALUES[kIndex] > 0 {
diffSegment *= exp(-1 * PK_VALUES[kIndex] * pow(rhoR, 2) - BK_VALUES[kIndex] * pow(tempR - UK_VALUES[kIndex], 2))
iFactor = 2 * rhoR * PK_VALUES[kIndex] * (rhoR - 1)
}
diffAggregate += (diffSegment * (IK_VALUES[kIndex] - iFactor))
}
//
// SET pCalc
//
zDiff + 1 + diffAggregate
pCalc = zDiff * R_CONST * 1000 * tempK * rhoCurrent
}
return rhoCurrent
}
I guess another question i have also is the main value I want out of this while loop is rhoCurrent (as I will use this final # to calculate something else). Doing the "return rhoCurrent" will work, correct?
Thanks so much in advance!!
I think you intended this line to assign a value, but it doesn't:
zDiff + 1 + diffAggregate
Because it doesn't assign a value, diffAggregate is not used in the body of your while loop. rhoR is also not used because of this. Your function can be simplified as such:
func retRhoCurrent() -> Double {
while abs(pTarget - pCalc) > 1 {
//
// SET rhoCurrent
//
if (pTarget > pCalc) {
rhoLow = rhoCurrent
if(rhoCurrent >= rhoHigh) {
rhoCurrent += RHO_C
rhoHigh = rhoCurrent
} else {
rhoCurrent += ((rhoHigh - rhoCurrent)/2)
}
} else {
rhoHigh = rhoCurrent
rhoCurrent += ((rhoLow - rhoCurrent)/2)
}
//
// SET pCalc
//
pCalc = zDiff * R_CONST * 1000 * tempK * rhoCurrent
}
return rhoCurrent
}
I'm really suspicious of the variables that you use in the loop but do not initialize within the function. What are the initial values for rhoLow, rhoHigh, rhoCurrent, tempK, zDiff, pTarget, and pCalc?
This method is very messy and depends on a lot of magic. It is modifying values that it does not own, meaning you could experience unexpected things in other areas of your app. It is definitely not thread-safe (though this may not be a concern for you).
Related
I m making a card game where 3 random numbers are generated..I need to check are these numbers Row numbers...
like 4 6 5 and 23,24,22. are row numbers
I have made method but I think there should be easy arithmetic formulas
I have tried this and working well, but I need simple arithmatic formula to avoid use of array and for
bool isAllInRow(int num1, int num2,int num3)
{
//subject : tinpati
List<int> numbers=[num1,num2,num3];
bool is_in_row=true;
numbers.sort();
if(numbers[0]==1 && numbers[1]==12 && numbers[2]==13)
return true;
for(int x=0;x<numbers.length-1;x++)
{
if(numbers[x]-numbers[x+1]!=-1)
{
is_in_row=false;
break;
}
}
return is_in_row;
}
So you want to know if the cards form a straight, with aces both low and high.
Is the "three cards" fixed, or would you want to generalize to more cards?
Sorting should be cheap for such a short list, so that's definitely a good start. Then you just need to check the resulting sequence is increasing adjacent values.
I'd do it as:
bool isStraight(List<int> cards) {
var n = cards.length;
if (n < 2) return true;
cards.sort();
var first = cards.first;
if (first == 1 && cards[1] != 2) {
// Pretend Ace is Jack if n == 3.
// Accepts if remaining cards form a straight up to the King.
first = 14 - n;
}
for (var i = 1; i < n; i++) {
if (cards[i] != first + i) return false;
}
return true;
}
This code rejects card sets that have duplicates, or do not form a straight.
I think you are looking for Arithmetic Progression.
bool checkForAP(List<int> numberArr) {
numberArr.sort();
int diff = numberArr[1] - numberArr[0];
if (numberArr[2] - numberArr[1] != diff) {
return false;
}
return true;
}
And modify your function like
bool isAllInRow(int num1, int num2,int num3) {
//subject : tinpati
List<int> numbers=[num1,num2,num3];
bool is_in_row=true;
numbers.sort();
if(numbers[0]==1 && numbers[1]==12 && numbers[2]==13)
return true;
return checkForAP(numbers);
}
Note: remove sort in AP method as it is of no use. Since your numbers
list length is 3 I directly compared numbers for AP, the same can also
be written for n numbers with for.
bool checkForAp(numberArr) {
numberArr.sort();
int diff = numberArr[1] - numberArr[0];
for(int i = 2; i< numberArr.length ;i++) {
if (numberArr[i] - numberArr[i - 1] != diff) {
return false;
}
}
return true;
}
You could do it like this:
bool isAllInRow(int num1, int num2,int num3) {
if (num1 == num2 || num2 == num3) return false;
var maxNum = max(num1, max(num2, num3));
var minNum = min(num1, min(num2, num3));
return (maxNum - minNum == 2) || (minNum == 1 && maxNum == 13 && num1 + num2 + num3 == 26);
}
I've been messing around with the Camarilla Indicator and I wanted to get the main pivot values for my EA, can I use iCustom() for that? or should I just pass the code to the EA? but where exactly would I place it? I tried to place it on the onTick() but with a condition of only calculating the pivots when there is a new daily candle, but the values most of the times don't match.
void OnTick()
{
static datetime today;
if (today != iTime (Symbol(), PERIOD_D1, 0))
{
today = iTime (Symbol(), PERIOD_D1, 0);
int counted_bars=IndicatorCounted();
//---- TODO: add your code here
int cnt=720;
//---- exit if period is greater than daily charts
if(Period() > 1440)
{
Print("Error - Chart period is greater than 1 day.");
}
//---- Get new daily prices & calculate pivots
day_high=0;
day_low=0;
yesterday_open=0;
today_open=0;
cur_day=0;
prev_day=0;
while (cnt!= 0)
{
if (TimeDayOfWeek(Time[cnt]) == 0)
{
cur_day = prev_day;
}
else
{
cur_day = TimeDay(Time[cnt]- (GMTshift*3600));
}
if (prev_day != cur_day)
{
yesterday_close = Close[cnt+1];
today_open = Open[cnt];
yesterday_high = day_high;
yesterday_low = day_low;
day_high = High[cnt];
day_low = Low[cnt];
prev_day = cur_day;
}
if (High[cnt]>day_high)
{
day_high = High[cnt];
}
if (Low[cnt]<day_low)
{
day_low = Low[cnt];
}
cnt--;
}
H3 = ((yesterday_high - yesterday_low)* D3) + yesterday_close;
H4 = ((yesterday_high - yesterday_low)* D4) + yesterday_close;
L3 = yesterday_close - ((yesterday_high - yesterday_low)*(D3));
L4 = yesterday_close - ((yesterday_high - yesterday_low)*(D4));
L5 = yesterday_close - (H5 - yesterday_close);
H5 = (yesterday_high/yesterday_low)*yesterday_close;
Print ("H3: " + DoubleToStr(H3));
Print ("H4: " + DoubleToStr(H4));
Print ("H5: " + DoubleToStr(H5));
Print ("L3: " + DoubleToStr(L3));
Print ("L4: " + DoubleToStr(L4));
Print ("L5: " + DoubleToStr(L5));
}
I have points(lat,long) coordindates and i have area leftTop(lat,long) rightBottom(lat,long) , i need to check if my points is inside area.
It's not correct just to check if point coordinate is more than leftLat, and less rightLat.
I have corners
leftLat=81.49021937827182
leftLng=38.979793936014175
rightLat=-0.5414380758487521
rightLng=173.9797962829470
function rayCrossesSegment($point, $a, $b)
{
$px = $point['lng'];
$py = $point['lat'];
$ax = $a['lng'];
$ay = $a['lat'];
$bx = $b['lng'];
$by = $b['lat'];
if ($ay > $by) {
$ax = $b['lng'];
$ay = $b['lat'];
$bx = $a['lng'];
$by = $a['lat'];
}
// alter longitude to cater for 180 degree crossings
if ($px < 0) {
$px += 360;
};
if ($ax < 0) {
$ax += 360;
};
if ($bx < 0) {
$bx += 360;
};
if ($py == $ay || $py == $by) {
$py += 0.00000001;
}
if (($py > $by || $py < $ay) || ($px > max($ax, $bx))) {
return false;
}
if ($px < min($ax, $bx)) {
return true;
}
$red = ($ax != $bx) ? (($by - $ay) / ($bx - $ax)) : INF;
$blue = ($ax != $px) ? (($py - $ay) / ($px - $ax)) : INF;
return ($blue >= $red);
}
I'm trying to get a nice easing scroll effect on my site using smoothscroll.js from http://cferdinandi.github.io/smooth-scroll/ (shown as code below) and it works fine. However, scrolling with mousewheel while that's in effect causes the page to jitter all over the place because there are two animations taking place - the one from the the mousewheel and the other from the anchor scroll. So I'd like to either disable mousewheel on the anchor scroll animation or disable the anchor scroll animation on mousewheel. I'm not sure how to alter the code to do that. I'm pretty sure I should just be able to add a line or two to the code below but I've been trying for many hours and I can't get anything to work.
/* =============================================================
Smooth Scroll 3.2
Animate scrolling to anchor links, by Chris Ferdinandi.
http://gomakethings.com
Easing support contributed by Willem Liu.
https://github.com/willemliu
Easing functions forked from Gaëtan Renaudeau.
https://gist.github.com/gre/1650294
URL history support contributed by Robert Pate.
https://github.com/robertpateii
Fixed header support contributed by Arndt von Lucadou.
https://github.com/a-v-l
Infinite loop bugs in iOS and Chrome (when zoomed) by Alex Guzman.
https://github.com/alexguzman
Free to use under the MIT License.
http://gomakethings.com/mit/
* ============================================================= */
window.smoothScroll = (function (window, document, undefined) {
'use strict';
// Feature Test
if ( 'querySelector' in document && 'addEventListener' in window && Array.prototype.forEach ) {
// SELECTORS
var scrollToggles = document.querySelectorAll('[data-scroll]');
// METHODS
// Run the smooth scroll animation
var runSmoothScroll = function (anchor, duration, easing, url) {
// SELECTORS
var startLocation = window.pageYOffset;
// Get the height of a fixed header if one exists
var scrollHeader = document.querySelector('[data-scroll-header]');
var headerHeight = scrollHeader === null ? 0 : scrollHeader.offsetHeight;
// Set the animation variables to 0/undefined.
var timeLapsed = 0;
var percentage, position;
// METHODS
// Calculate the easing pattern
var easingPattern = function (type, time) {
if ( type == 'easeInQuad' ) return time * time; // accelerating from zero velocity
if ( type == 'easeOutQuad' ) return time * (2 - time); // decelerating to zero velocity
if ( type == 'easeInOutQuad' ) return time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
if ( type == 'easeInCubic' ) return time * time * time; // accelerating from zero velocity
if ( type == 'easeOutCubic' ) return (--time) * time * time + 1; // decelerating to zero velocity
if ( type == 'easeInOutCubic' ) return time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration
if ( type == 'easeInQuart' ) return time * time * time * time; // accelerating from zero velocity
if ( type == 'easeOutQuart' ) return 1 - (--time) * time * time * time; // decelerating to zero velocity
if ( type == 'easeInOutQuart' ) return time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
if ( type == 'easeInQuint' ) return time * time * time * time * time; // accelerating from zero velocity
if ( type == 'easeOutQuint' ) return 1 + (--time) * time * time * time * time; // decelerating to zero velocity
if ( type == 'easeInOutQuint' ) return time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration
return time; // no easing, no acceleration
};
// Update the URL
var updateURL = function (url, anchor) {
if ( url === 'true' && history.pushState ) {
history.pushState( {pos:anchor.id}, '', '#' + anchor.id );
}
};
// Calculate how far to scroll
var getEndLocation = function (anchor) {
var location = 0;
if (anchor.offsetParent) {
do {
location += anchor.offsetTop;
anchor = anchor.offsetParent;
} while (anchor);
}
location = location - headerHeight;
if ( location >= 0 ) {
return location;
} else {
return 0;
}
};
var endLocation = getEndLocation(anchor);
var distance = endLocation - startLocation;
// Stop the scrolling animation when the anchor is reached (or at the top/bottom of the page)
var stopAnimation = function () {
var currentLocation = window.pageYOffset;
if ( position == endLocation || currentLocation == endLocation || ( (window.innerHeight + currentLocation) >= document.body.scrollHeight ) ) {
clearInterval(runAnimation);
}
};
// Scroll the page by an increment, and check if it's time to stop
var animateScroll = function () {
timeLapsed += 16;
percentage = ( timeLapsed / duration );
percentage = ( percentage > 1 ) ? 1 : percentage;
position = startLocation + ( distance * easingPattern(easing, percentage) );
window.scrollTo( 0, position );
stopAnimation();
};
// EVENTS, LISTENERS, AND INITS
updateURL(url, anchor);
var runAnimation = setInterval(animateScroll, 16);
};
// Check that anchor exists and run scroll animation
var handleToggleClick = function (event) {
// SELECTORS
// Get anchor link and calculate distance from the top
var dataID = this.getAttribute('href');
var dataTarget = document.querySelector(dataID);
var dataSpeed = this.getAttribute('data-speed');
var dataEasing = this.getAttribute('data-easing');
var dataURL = this.getAttribute('data-url');
// EVENTS, LISTENERS, AND INITS
event.preventDefault();
if (dataTarget) {
runSmoothScroll( dataTarget, dataSpeed || 500, dataEasing || 'easeInOutCubic', dataURL || 'false' );
}
};
// EVENTS, LISTENERS, AND INITS
// When a toggle is clicked, run the click handler
Array.prototype.forEach.call(scrollToggles, function (toggle, index) {
toggle.addEventListener('click', handleToggleClick, false);
});
// Return to the top of the page when back button is clicked and no hash is set
window.onpopstate = function (event) {
if ( event.state === null && window.location.hash === '' ) {
window.scrollTo( 0, 0 );
}
};
}
})(window, document);
I figured it out - I added
$("html").bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(){
clearInterval(runAnimation);
});
directly under
var runSmoothScroll = function (anchor, duration, easing, url) {
as runSmoothScroll is the function called to run the scrolling animation. So whenever that function is called, it adds the function for ending the animation, clearInterval(runAnimation) to the mousewheel. I also figured out a way to get the script to temporarily disable mousewheel.
/* =============================================================
Smooth Scroll 3.2
Animate scrolling to anchor links, by Chris Ferdinandi.
http://gomakethings.com
Easing support contributed by Willem Liu.
https://github.com/willemliu
Easing functions forked from Gaëtan Renaudeau.
https://gist.github.com/gre/1650294
URL history support contributed by Robert Pate.
https://github.com/robertpateii
Fixed header support contributed by Arndt von Lucadou.
https://github.com/a-v-l
Infinite loop bugs in iOS and Chrome (when zoomed) by Alex Guzman.
https://github.com/alexguzman
Free to use under the MIT License.
http://gomakethings.com/mit/
* ============================================================= */
window.smoothScroll = (function (window, document, undefined) {
'use strict';
// Feature Test
if ( 'querySelector' in document && 'addEventListener' in window && Array.prototype.forEach ) {
// SELECTORS
var scrollToggles = document.querySelectorAll('[data-scroll]');
// METHODS
// Run the smooth scroll animation
var runSmoothScroll = function (anchor, duration, easing, url) {
/*
//2/23/2014 Figured out how to disable mousewheel for a set amount of time
//disable mousewheel function
$("html").bind("scroll mousedown DOMMouseScroll mousewheel keyup", false);
//pause until animated scrolling is finished, then enable mousewheel
setTimeout(function(){
$("html").unbind("scroll mousedown DOMMouseScroll mousewheel keyup", false);
}, duration);
*/
//alternatively, can end the animation prematurely if mousewheel is used
$("html, body").bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(){
clearInterval(runAnimation);
});
// SELECTORS
var startLocation = window.pageYOffset;
// Get the height of a fixed header if one exists
var scrollHeader = document.querySelector('[data-scroll-header]');
var headerHeight = scrollHeader === null ? 0 : scrollHeader.offsetHeight;
// Set the animation variables to 0/undefined.
var timeLapsed = 0;
var percentage, position;
// METHODS
// Calculate the easing pattern
var easingPattern = function (type, time) {
if ( type == 'easeInQuad' ) return time * time; // accelerating from zero velocity
if ( type == 'easeOutQuad' ) return time * (2 - time); // decelerating to zero velocity
if ( type == 'easeInOutQuad' ) return time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
if ( type == 'easeInCubic' ) return time * time * time; // accelerating from zero velocity
if ( type == 'easeOutCubic' ) return (--time) * time * time + 1; // decelerating to zero velocity
if ( type == 'easeInOutCubic' ) return time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration
if ( type == 'easeInQuart' ) return time * time * time * time; // accelerating from zero velocity
if ( type == 'easeOutQuart' ) return 1 - (--time) * time * time * time; // decelerating to zero velocity
if ( type == 'easeInOutQuart' ) return time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
if ( type == 'easeInQuint' ) return time * time * time * time * time; // accelerating from zero velocity
if ( type == 'easeOutQuint' ) return 1 + (--time) * time * time * time * time; // decelerating to zero velocity
if ( type == 'easeInOutQuint' ) return time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration
return time; // no easing, no acceleration
};
// Update the URL
var updateURL = function (url, anchor) {
if ( url === 'true' && history.pushState ) {
history.pushState( {pos:anchor.id}, '', '#' + anchor.id );
}
};
// Calculate how far to scroll
var getEndLocation = function (anchor) {
var location = 0;
if (anchor.offsetParent) {
do {
location += anchor.offsetTop;
anchor = anchor.offsetParent;
} while (anchor);
}
location = location - headerHeight;
if ( location >= 0 ) {
return location;
} else {
return 0;
}
};
var endLocation = getEndLocation(anchor);
var distance = endLocation - startLocation;
// Stop the scrolling animation when the anchor is reached (or at the top/bottom of the page)
var stopAnimation = function () {
var currentLocation = window.pageYOffset;
if ( position == endLocation || currentLocation == endLocation || ( (window.innerHeight + currentLocation) >= document.body.scrollHeight ) ) {
clearInterval(runAnimation);
}
};
// Scroll the page by an increment, and check if it's time to stop
var animateScroll = function () {
timeLapsed += 16;
percentage = ( timeLapsed / duration );
percentage = ( percentage > 1 ) ? 1 : percentage;
position = startLocation + ( distance * easingPattern(easing, percentage) );
window.scrollTo( 0, position );
stopAnimation();
};
// EVENTS, LISTENERS, AND INITS
updateURL(url, anchor);
var runAnimation = setInterval(animateScroll, 16);
};
// Check that anchor exists and run scroll animation
var handleToggleClick = function (event) {
// SELECTORS
// Get anchor link and calculate distance from the top
var dataID = this.getAttribute('href');
var dataTarget = document.querySelector(dataID);
var dataSpeed = this.getAttribute('data-speed');
var dataEasing = this.getAttribute('data-easing');
var dataURL = this.getAttribute('data-url');
// EVENTS, LISTENERS, AND INITS
event.preventDefault();
if (dataTarget) {
runSmoothScroll( dataTarget, dataSpeed || 500, dataEasing || 'easeInOutCubic', dataURL || 'false' );
}
};
// EVENTS, LISTENERS, AND INITS
// When a toggle is clicked, run the click handler
Array.prototype.forEach.call(scrollToggles, function (toggle, index) {
toggle.addEventListener('click', handleToggleClick, false);
});
// Return to the top of the page when back button is clicked and no hash is set
window.onpopstate = function (event) {
if ( event.state === null && window.location.hash === '' ) {
window.scrollTo( 0, 0 );
}
};
}
})(window, document);
I have the following:
package {
import flash.display.MovieClip;
public class Ratio extends MovieClip {
private var counter:Number;
private var frequency:Number;
private var ratio:String;
private var max:Number;
public function Ratio() {
ratio ="2/8";
var arr = ratio.split("/");
max = arr[1];
frequency = arr[0];
counter = 0;
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function loop(e:Event):void {
trace(counter + ": " + (counter < frequency));
counter++;
if (counter == max) {
counter = 0;
}
}
public function destroy():void {
removeEventListener(Event.ENTER_FRAME, loop);
}
}
}
This outputs something like:
0: true
1: true
2: false
3: false
0: true
1: true
2: false
3: false
But what I would actually like is:
0: true
1: false
2: true
3: false
0: true
1: false
2: true
3: false
i.e. more even dispersion (alternation)...is there a way to do this?
I think I may have missed the point here, but this should give the desired output:
private function loop(e:Event):void {
trace(counter + ": " + !Boolean(counter % 2));
counter++;
if (counter == max) counter = 0;
}
Update:
Although it's getting a little heavy-handed, the following creates an alternating dispersion where it is exactly possible. Everything else runs in a straight sequence. I'm no mathematician though, and I feel that it could be done better. For example this will treat 3/9 as 1,1,1,0,0,0,0,0,0, whereas a 'nicer' distribution might be 0,1,0,0,1,0,0,1,0
var ratio:String = "3/5";
var counter:int = 0;
var arr = ratio.split("/");
var frequency:int = arr[0];
var max:int = arr[1];
addEventListener(Event.ENTER_FRAME,loop);
function loop(e:Event):void {
if((max+1) / frequency == 2 || max / frequency == 2) {
trace(counter + ": " + !Boolean(counter % 2));
} else if((max-1) / frequency == 2) {
trace(counter + ": " + Boolean(counter % 2));
} else {
trace(counter < frequency);
}
counter++;
if (counter == max) removeEventListener(Event.ENTER_FRAME,loop);
}