Search Results

Search found 137 results on 6 pages for 'ceil'.

Page 2/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • Asymptotic runtime of list-to-tree function

    - by Deestan
    I have a merge function which takes time O(log n) to combine two trees into one, and a listToTree function which converts an initial list of elements to singleton trees and repeatedly calls merge on each successive pair of trees until only one tree remains. Function signatures and relevant implementations are as follows: merge :: Tree a -> Tree a -> Tree a --// O(log n) where n is size of input trees singleton :: a -> Tree a --// O(1) empty :: Tree a --// O(1) listToTree :: [a] -> Tree a --// Supposedly O(n) listToTree = listToTreeR . (map singleton) listToTreeR :: [Tree a] -> Tree a listToTreeR [] = empty listToTreeR (x:[]) = x listToTreeR xs = listToTreeR (mergePairs xs) mergePairs :: [Tree a] -> [Tree a] mergePairs [] = [] mergePairs (x:[]) = [x] mergePairs (x:y:xs) = merge x y : mergePairs xs This is a slightly simplified version of exercise 3.3 in Purely Functional Data Structures by Chris Okasaki. According to the exercise, I shall now show that listToTree takes O(n) time. Which I can't. :-( There are trivially ceil(log n) recursive calls to listToTreeR, meaning ceil(log n) calls to mergePairs. The running time of mergePairs is dependent on the length of the list, and the sizes of the trees. The length of the list is 2^h-1, and the sizes of the trees are log(n/(2^h)), where h=log n is the first recursive step, and h=1 is the last recursive step. Each call to mergePairs thus takes time (2^h-1) * log(n/(2^h)) I'm having trouble taking this analysis any further. Can anyone give me a hint in the right direction?

    Read the article

  • Translation of a RoR view to Java

    - by mnml
    Hi, for some reasons I am trying to translate the following RoR view code to a GSP view: List<Object> objectscontains the data I want to display in 3 columns <% modulo_objects = @objects.length % 3 base = @objects.length / 3 base = base.ceil case modulo_objects when 0 cols = [base, base, base] when 1 cols = [base, base + 1, base] when 2 cols = [base + 1, base, base + 1] end counter = 0 %> <% 3.times do |i| %> <td width="220" align="center" style="padding-right: 15px;"> <% cols[i].times do %> <h1><a href="/objects/show/<%= @objects[counter].urlname %>" ><%= @objects[counter].name %></a></h1> <% counter = counter + 1 %> <% end %> </td> <% end %> This is what I got so far: #{extends 'main.html' /} %{ modulo_objects = objects.size() % 3 base = objects.size() / 3 base = Math.ceil(base) if(modulo_objects == 0) cols = [base, base, base] else if(modulo_objects == 1) cols = [base, base + 1, base] else if(modulo_objects == 2) cols = [base + 1, base, base + 1] endif counter = 0 }% #{list items:1..3, as:'i'} <td width="220" align="center" style="padding-right: 15px;"> #{list items:cols[i]} <a href="@{Objects.show(objects.get(counter).name.replaceAll(" ", "-"))}" >${objects.get(counter).name}</a> %{ counter = counter + 1 }% #{/list} </td> #{/list} The idea is to keep the items organised in 3 columns like 1|0|1 4|5|4 or 5|4|5 for example, I don't really understand if #{list items:cols[i]} will reproduce ruby's cols[i].times do. So far the Java view is does not display more than two elements.

    Read the article

  • Why would this Lua optimization hack help?

    - by Ian Boyd
    i'm looking over a document that describes various techniques to improve performance of Lua script code, and i'm shocked that such tricks would be required. (Although i'm quoting Lua, i've seen similar hacks in Javascript). Why would this optimization be required: For instance, the code for i = 1, 1000000 do local x = math.sin(i) end runs 30% slower than this one: local sin = math.sin for i = 1, 1000000 do local x = sin(i) end They're re-declaring sin function locally. Why would this be helpful? It's the job of the compiler to do that anyway. Why is the programmer having to do the compiler's job? i've seen similar things in Javascript; and so obviously there must be a very good reason why the interpreting compiler isn't doing its job. What is it? i see it repeatedly in the Lua environment i'm fiddling in; people redeclaring variables as local: local strfind = strfind local strlen = strlen local gsub = gsub local pairs = pairs local ipairs = ipairs local type = type local tinsert = tinsert local tremove = tremove local unpack = unpack local max = max local min = min local floor = floor local ceil = ceil local loadstring = loadstring local tostring = tostring local setmetatable = setmetatable local getmetatable = getmetatable local format = format local sin = math.sin What is going on here that people have to do the work of the compiler? Is the compiler confused by how to find format? Why is this an issue that a programmer has to deal with? Why would this not have been taken care of in 1993? i also seem to have hit a logical paradox: Optimizatin should not be done without profiling Lua has no ability to be profiled Lua should not be optimized

    Read the article

  • Artifacts when trying to draw background grid without anti-aliasing in a QGraphicsScene

    - by estan
    Hi folks, I'm trying to draw a background grid in the drawBackground() function of my QGraphicsScene subclass: void Scene::drawBackground(QPainter *painter, const QRectF &rect) { const int gridSize = 50; const int realLeft = static_cast<int>(std::floor(rect.left())); const int realRight = static_cast<int>(std::ceil(rect.right())); const int realTop = static_cast<int>(std::floor(rect.top())); const int realBottom = static_cast<int>(std::ceil(rect.bottom())); // Draw grid. const int firstLeftGridLine = realLeft - (realLeft % gridSize); const int firstTopGridLine = realTop - (realTop % gridSize); QVarLengthArray<QLine, 100> lines; for (qreal x = firstLeftGridLine; x <= realRight; x += gridSize) lines.append(QLine(x, realTop, x, realBottom)); for (qreal y = firstTopGridLine; y <= realBottom; y += gridSize) lines.append(QLine(realLeft, y, realRight, y)); //painter->setRenderHint(QPainter::Antialiasing); painter->setPen(QPen(QColor(220, 220, 220), 0.0)); painter->drawLines(lines.data(), lines.size()); // Draw axes. painter->setPen(QPen(Qt::lightGray, 0.0)); painter->drawLine(0, realTop, 0, realBottom); painter->drawLine(realLeft, 0, realRight, 0); } However, unless I turn on anti-aliasing, moving items around will sometimes leave artifacts in the grid (areas where it's not drawn). It seems it mostly happens at low zoom levels, when the view is zoomed out a bit. Any ideas what I might be doing wrong here? I'd really don't want to turn anti-aliasing on since the lines are strictly horizontal and vertical, and I'd like them to be as crisp as possible. Any help is much appriciated, Regards, Elvis

    Read the article

  • Cleaner way of using modulus for columns

    - by WmasterJ
    I currently have a list (<ul>) of people that I have divided up into two columns. But after finishing the code for it I keept wondering if there is a more effective or clean way to do the same thing. echo "<table class='area_list'><tr>"; // Loop users within areas, divided up in 2 columns $count = count($areaArray); for($i=0 ; $i<$count ; $i++) { $uid = $areaArray[$i]; // get the modulus value + ceil for uneven numbers $rowCalc = ($i+1) % ceil($count/2); if ($rowCalc == 1) echo "<td><ul>"; // OUTPUT the actual list item echo "<li>{$users[$uid]->profile_lastname}</li>"; if ($rowCalc == 0 && $i!=0) echo "</ul></td>"; } echo "</tr></table>"; Any ideas of how to make this cleaner or do it in another way?

    Read the article

  • PHP resizing PNGs results in corrupted files

    - by Robert
    I have a PHP script that resizes .jpg, .gif, and .png files to a bounding box. $max_width = 500; $max_height = 600; $filetype = $_FILES["file"]["type"]; $source_pic = "img/" . $idnum; if($filetype == "image/jpeg") { $src = imagecreatefromjpeg($source_pic); } else if($filetype == "image/png") { $src = imagecreatefrompng($source_pic); } else if($filetype == "image/gif") { $src = imagecreatefromgif($source_pic); } list($width,$height)=getimagesize($source_pic); $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; if( ($width <= $max_width) && ($height <= $max_height) ) { $tn_width = $width; $tn_height = $height; } else if (($x_ratio * $height) < $max_height) { $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; } else { $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } $tmp = imagecreatetruecolor($tn_width,$tn_height); imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height); $destination_pic = "img/thumbs/" . $idnum . "thumb"; if($filetype == "image/jpeg") { imagejpeg($tmp,$destination_pic,80); } else if($filetype == "image/png") { imagepng($tmp,$destination_pic,80); } else if($filetype == "image/gif") { imagegif($tmp,$destination_pic,80); } imagedestroy($src); imagedestroy($tmp); The script works fine with jpeg and gif but when running on a png the file will be corrupted. Is there anything special I need to use when working with a png? I have never worked with this sort of thing in PHP so I'm not very familiar with it.

    Read the article

  • Fragment shader seems to floor() imprecisely

    - by Peter K.
    I'm trying to interpolate coordinates in my fragment shader. Unfortunately if close to the upper edge the interpolated value of fVertexInteger seems to be rounded up instead of beeing floored. This happens above approximately fVertexInteger >= x.97. Example: floor(64.7) returns 64.0 -- correct floor(64.98) returns 65.0 -- incorrect The same happens on ceiling close above x.0, where ceil(65.02) returns 65.0 instead of 66.0. Q: Any ideas how to solve this? Note: GL ES 2.0 with GLSL 1.0 highp floats are not supported in fragment shaders on my hardware flat varying hasn't been a solution, because I'm drawing TRIANGLE_STRIP and can't redeclare the provoking vertex (only OpenGL 3.2+) Fragment Shader: varying float fVertexInteger; varying float fVertexFraction; void main() { // Fix vertex integer fixedVertexInteger = floor(fVertexInteger); // Fragment color gl_FragColor = vec4( fixedVertexInteger / 65025.0, fract(fixedVertexInteger / 255.0), fVertexFraction, 1.0 ); }

    Read the article

  • How do I consistently re-size my game window and elements?

    - by Milo
    In my 2D game, I have a flow layout. Inside the flow layout are tables. I have a slider that lets the user make the tables larger or smaller. This makes the background larger or smaller too. Everything should scale proportionally which means the background should stay at the same position when I make things larger, and it almost does. When the scrollbar is at 0, it does exactly this. As the scrollbar gets further down problems arise. I'll toggle the slider maybe 3 times and on the fourth time, the background jumps a little lower on the Y axis. In order to be efficient, I only start rendering the background near the parent of the flow layout. Here it is: void LobbyTableManager::renderBG( GraphicsContext* g, agui::Rectangle& absRect, agui::Rectangle& childRect ) { int cx, cy, cw, ch; g->getClippingRect(cx,cy,cw,ch); g->setClippingRect(absRect.getX(),absRect.getY(),absRect.getWidth(),absRect.getHeight()); float scale = 0.35f; int w = m_bgSprite->getWidth() * getTableScale() * scale; int h = m_bgSprite->getHeight() * getTableScale() * scale; int numX = ceil(absRect.getWidth() / (float)w) + 2; int numY = ceil(absRect.getHeight() / (float)h) + 2; float offsetX = m_activeTables[0]->getLocation().getX() - w; float offsetY = m_activeTables[0]->getLocation().getY() - h; int startY = childRect.getY(); if(moo) { std::cout << "S=" << startY << ","; } int numAttempts = 0; while(startY + h < absRect.getY() && numAttempts < 1000) { startY += h; if(moo) { std::cout << startY << ","; } numAttempts++; } if(moo) { std::cout << "\n"; moo = false; } g->holdDrawing(); for(int i = 0; i < numX; ++i) { for(int j = 0; j < numY; ++j) { g->drawScaledSprite(m_bgSprite,0,0,m_bgSprite->getWidth(),m_bgSprite->getHeight(), absRect.getX() + (i * w) + (offsetX),absRect.getY() + (j * h) + startY,w,h,0); } } g->unholdDrawing(); g->setClippingRect(cx,cy,cw,ch); } The numeric problem seems to be in the value of startY. I outputted startY figuring out its value: As you can see here, this is me only zooming in, pay attention to the final number before the next s=. You'll notice that, what should happen is, the numbers should be linear, ex: -40, -38, -36, -34, -32, -30, etc. As you'll notice, the start numbers linearly correlate ex: 62k, 64k, 66k, 68k, 70k etc.. but the end result is wrong every third or 4th time. Here is most of the resize code: void LobbyTableManager::setTableScale( float scale ) { scale += 0.3f; scale *= 2.0f; agui::Gui* gotGui = getGui(); float scrollRel = m_vScroll->getRelativeValue(); setScale(scale); rescaleTables(); resizeFlow(); if(gotGui) { gotGui->toggleWidgetLocationChanged(false); } updateScrollBars(); float newVal = scrollRel * m_vScroll->getMaxValue(); if((int)(newVal + 0.5f) > (int)newVal) { newVal++; } m_vScroll->setValue(newVal); static int x = 0; x++; moo = true; //std::cout << m_vScroll->getValue() << std::endl; if(gotGui) { gotGui->toggleWidgetLocationChanged(true); } if(gotGui) { gotGui->_widgetLocationChanged(); } } void LobbyTableManager::valueChanged( agui::VScrollBar* source,int val ) { if(getGui()) { getGui()->toggleWidgetLocationChanged(false); } m_flow->setLocation(0,-val); if(getGui()) { getGui()->toggleWidgetLocationChanged(true); getGui()->_widgetLocationChanged(); } }

    Read the article

  • MySQL column not found

    - by vian
    The SQL query without where statement runs great and outputs good results, but when I include WHERE condition it shows Unknown column 'date1' in 'where clause'. What's the problem? SELECT IF(e.weekly, DATE_ADD(DATE(e.time), INTERVAL CEIL(DATEDIFF('2010-04-08', e.time)/7) WEEK), DATE(e.time)) AS `e.date1`, `v`.`lat`, `v`.`lng` FROM `events` AS `e` INNER JOIN `venues` AS `v` ON e.venue_id = v.id WHERE e.date1 > '2010-09-01'

    Read the article

  • Translate RoR Code to Java

    - by mnml
    Hi, for some reasons I am trying to translate the following RoR view code to a Java Groovy view: <% modulo_artists = @artists.length % 3 base = @artists.length / 3 base = base.ceil case modulo_artists when 0 cols = [base, base, base] when 1 cols = [base, base + 1, base] when 2 cols = [base + 1, base, base + 1] end counter = 0 %> <% id_hash = {"0" => "url('/images/actorsbg.png');", "1" => "url('/images/musiciansbg.png');", "2" => "url('/images/artistsbg.png') no-repeat; color: #FFF;", "3" => "url('/images/fashionbg.png')"} %> <div id="artists_<%=params[:artist_cat]%>" style="background: <%= id_hash[params[:artist_cat]] %>;" > <table border="0" width="660" height="164" cellpadding="0" cellspacing="0"> <tr valign="middle"> <% 3.times do |i| %> <td width="220" align="center" style="padding-right: 15px;"> <% cols[i].times do %> <h1><a href="/artists/show/<%= @artists[counter].urlname %>" ><%= @artists[counter].name %></a></h1> <% counter = counter + 1 %> <% end %> </td> <% end %> </tr> </table> </div> This is what I got so far: #{extends 'main.html' /} %{ modulo_artists = artists.size() % 3 base = artists.size() / 3 base = Math.ceil(base) if(modulo_artists == 0) cols = [base, base, base] else if(modulo_artists == 1) cols = [base, base + 1, base] else if(modulo_artists == 2) cols = [base + 1, base, base + 1] endif counter = 0 }% <div id="artists_${artist_cat}" style="background:${id_hash};" > <table border="0" width="660" height="164" cellpadding="0" cellspacing="0"> <tr valign="middle"> #{list items:1..3, as:'i'} <td width="220" align="center" style="padding-right: 15px;"> #{list items:cols[i]} <h1><a href="@{Artists.show(artists.get(counter).name.replaceAll(" ", "-"))}" >${artists.get(counter).name}</a></h1> %{ counter = counter + 1 }% #{/list} </td> #{/list} </tr> </table> </div> The idea is to keep the items organised in 3 columns like 1|0|1 4|5|4 or 5|4|5 for example

    Read the article

  • Problem with the POSIX module

    - by planetp
    After moving my mod_perl site from Linux hosting to FreeBSD, I have this error in the logfile: Your vendor has not defined POSIX macro SIGRTMIN, used at ../../lib/POSIX.pm (autosplit into ../../lib/auto/POSIX/SigRt/_init.al) line 993\n The script just imports POSIX and utilizes some functions (ceil, etc) How can I solve this issue ?

    Read the article

  • is it possible to get the duration of a streaming mp3 in Flash

    - by dubbeat
    Hi, I'm wondering if it is at all possible to get the total duration of an mp3 being streamed in flash? At the moment I'm using the following code to estimate the lenght but it is always inaccurate var loadTime:Number=_track.bytesLoaded / _track.bytesTotal; var loadPercent:uint=Math.round(100 * loadTime); estimatedLength=Math.ceil(_track.length / (loadTime));

    Read the article

  • C code to round numbers

    - by webgenius
    Is there any way to round numbers in C? I do not want to use ceil and floor. Is there any other alternative? I came across this code snippet when I Googled for the answer: (int)(num < 0 ? (num - 0.5) : (num + 0.5)) The above line always prints the value as 4 even when float num =4.9. Please suggest a solution.

    Read the article

  • round() for float in C++

    - by Roddy
    I need a simple floating point rounding function, thus: double round(double); round(0.1) = 0 round(-0.1) = 0 round(-0.9) = -1 I can find ceil() and floor() in the math.h - but not round(). Is it present in the standard C++ library under another name, or is it missing??

    Read the article

  • Client Side pagination with jQuery

    - by TheNone
    I have tried to write a script for pagination contents of an element with jQuery: <script type="text/javascript"> $(document).ready(function(){ var per_page = 2; var num_item = $('#en1').children().size(); var num_page = Math.ceil(num_item/per_page); $('#current_page').val(0); $('#per_page').val(per_page); var navigation_html = ''; var current = 0; while(num_page > current){ navigation_html += '<a class="page_link" href="javascript:paginate(' + current +')" longdesc="' + current +'">'+ (current + 1) +'</a>'; current++; } $('#page_navigation').html(navigation_html); $('#page_navigation .page_link:first').addClass('active_page'); $('#en1').children().css('display', 'none'); $('#en1').children().slice(0, per_page).css('display', 'block'); }); function paginate(page_num){ var per_page = parseInt($('#per_page').val()); start = page_num * per_page; finish= start + per_page; $('#en1').children().css('display', 'none').slice(start, finish).css('display', 'block'); $('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page'); $('#current_page').val(page_num); } </script> http://jsfiddle.net/kqfyL/9/ This script paginate the contents of element by id "en1". I want to paginate 4-5 element (en2, en3, ...). When I insert code inside o document ready in a function, pagination doesnt work: function init(myId){ var ID = document.getElementById("myId"); var per_page = 6; var num_item = $(ID).children().size(); var num_page = Math.ceil(num_item/per_page); $('#current_page').val(0); $('#per_page').val(per_page); var navigation_html = ''; var current = 0; while(num_page > current){ navigation_html += '<a class="page_link" href="javascript:paginate(' + current +')" longdesc="' + current +'">'+ (current + 1) +'</a>'; current++; } $('#page_navigation').html(navigation_html); $('#page_navigation .page_link:first').addClass('active_page'); $('#ID').children().css('display', 'none'); $('#ID').children().slice(0, per_page).css('display', 'block'); } init(en1); What is wrong in init function? Thanks in advance

    Read the article

  • NZEC in spoj FACKT

    - by frodo
    I was trying to solve this problem http://www.spoj.pl/problems/FACKT/, and I keep getting a Non-Zero Exit Code (NZEC). How exactly do I figure out what to change in the code to overcome this? Here is the code import math import sys def cal_num(n): i = 1 f = 1 while f<n: f *= i i = i + 1 return i-1 while 1: line = sys.stdin.readline() if line == "": break n = int(line) x = cal_num(n) y = math.factorial(2*x) l = int(math.ceil(math.log(y,10))) print (x,l) Any suggestion would be welcome.

    Read the article

  • traffic shaping for certain (local) users

    - by JMW
    Hello, i'm using ubuntu 10.10 i've a local backup user called "backup". :) i would like to give this user just a bandwidth of 1Mbit. No matter which software wants to connect to the network. this solution doesn't work: iptables -t mangle -A OUTPUT -p tcp -m owner --uid-owner 1001 -j MARK --set-mark 12 iptables -t mangle -A POSTROUTING -p tcp -m owner --uid-owner 1001 -j MARK --set-mark 12 tc qdisc del dev eth0 root tc qdisc add dev eth0 root handle 2 htb default 1 tc filter add dev eth0 parent 2: protocol ip pref 2 handle 50 fw classid 2:6 tc class add dev eth0 parent 2: classid 2:6 htb rate 10Kbit ceil 1Mbit tc qdisc show dev eth0 tc class show dev eth0 tc filter show dev eth0 does anyone know how to do it? thanks a lot in advance

    Read the article

  • how to limit upload bandwidth per user in linux?

    - by Gihan Lasita
    Can anyone provide the tc command to limit upload bandwidth per user in Debian Lenny? I found that to mark packets per user with iptables I can use the following command iptables -t mangle -A OUTPUT -p tcp -m owner --uid-owner testuser -j MARK --set-mark 500 but I have no idea how to use tc update by running following commands, i managed to limit testuser upload bandwidth to 10Mbit iptables -t mangle -N HTB_OUT iptables -t mangle -I POSTROUTING -j HTB_OUT iptables -t mangle -A HTB_OUT -j MARK --set-mark 30 iptables -t mangle -A HTB_OUT -m owner --uid-owner testuser -j MARK --set-mark 10 tc qdisc replace dev eth0 root handle 1: htb default 30 tc class replace dev eth0 parent 1: classid 1:1 htb rate 10Mbit burst 5k tc class replace dev eth0 parent 1:1 classid 1:10 htb rate 10Mbit ceil 10Mbit tc qdisc replace dev eth0 parent 1:10 handle 10: sfq perturb 10 tc filter add dev eth0 parent 1:0 prio 0 protocol ip handle 10 fw flowid 1:10 now the problem is, i do not want to limit testuser's FTP bandwidth but by running above commands FTP speed also limited to 10Mbit. Regards

    Read the article

  • Is it possible to limit output bandwidth between eth0 and lo?

    - by mmcbro
    I'm trying to limit the bandwidth between my eth0 output (nginx proxy) to my loopback inteface (apache) by filtering on destination port. Incoming Packet -> Eth0 -> 0.0.0.0:80 Nginx -> tc qdisc class/iptable mangle 2525port -> 127.0.0.1:2525 Apache I don't know if it's even possible I'm just experimenting. My rules are the followings : tc qdisc add dev eth0 root handle 1:0 htb tc class add dev eth0 parent 1:0 classid 1:10 htb rate 2mbps ceil 2mbps prio 0 tc filter add dev eth0 parent 1:0 prio 0 protocol ip handle 10 fw flowid 1:10 iptables -A OUTPUT -t mangle -p tcp --dport 2525 -j MARK --set-mark 10 I also tried to with FORWARD chain but its still the same.

    Read the article

  • Shaping with shorewall complex shaper not work (or I don't understand principle of operation)

    - by strangeman
    I have router (Debian 6) with 2 network interfaces (and 1 virtual tun interface): eth0 - localnet, 192.168.1.0/24, router ip is 192.168.1.1 eth1 - internet tun0 - openvpn to central office. openvpn network - 10.1.0.0/24, central office network - 192.168.0.0/24 I need shape all traffic, which moves 192.168.1.0/24-192.168.0.1:6666 and 192.168.1.0/24<-192.168.0.1:6666, and restrict its speed to 200kbit. Now, I have this configuration, but its not work: tcdevices (set up interface parameters) #INTERFACE IN-BANDWITH OUT-BANDWIDTH eth0 100mbit 100mbit #LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE tcrules (mark all traffic, which move on 6666 port) #MARK SOURCE DEST PROTO PORT(S) 1 0.0.0.0/0 0.0.0.0/0 tcp 6666 #LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE tcclasses (shape all marked traffic) #INTERFACE MARK RATE CEIL PRIORITY OPTIONS eth0 1 200kbit 200kbit 2 eth0 255 9*full/10 full 1 default #LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE Where is my mistake?

    Read the article

  • Game Over function is not working Starling

    - by aNgeLyN omar
    I've been following a tutorial over the web but it somehow did not show something about creating a game over function. I am new to the Starling framework and Actionscript so I'm kind of still trying to find a way to make it work. Here's the complete snippet of the code. package screens { import flash.geom.Rectangle; import flash.utils.getTimer; import events.NavigationEvent; import objects.GameBackground; import objects.Hero; import objects.Item; import objects.Obstacle; import starling.display.Button; import starling.display.Image; import starling.display.Sprite; import starling.events.Event; import starling.events.Touch; import starling.events.TouchEvent; import starling.text.TextField; import starling.utils.deg2rad; public class InGame extends Sprite { private var screenInGame:InGame; private var screenWelcome:Welcome; private var startButton:Button; private var playAgain:Button; private var bg:GameBackground; private var hero:Hero; private var timePrevious:Number; private var timeCurrent:Number; private var elapsed:Number; private var gameState:String; private var playerSpeed:Number = 0; private var hitObstacle:Number = 0; private const MIN_SPEED:Number = 650; private var scoreDistance:int; private var obstacleGapCount:int; private var gameArea:Rectangle; private var touch:Touch; private var touchX:Number; private var touchY:Number; private var obstaclesToAnimate:Vector.<Obstacle>; private var itemsToAnimate:Vector.<Item>; private var scoreText:TextField; private var remainingLives:TextField; private var gameOverText:TextField; private var iconSmall:Image; static private var lives:Number = 2; public function InGame() { super(); this.addEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage); } private function onAddedToStage(event:Event):void { this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); drawGame(); scoreText = new TextField(300, 100, "Score: 0", "MyFontName", 35, 0xD9D919, true); remainingLives = new TextField(600, 100, "Lives: " + lives +" X ", "MyFontName", 35, 0xD9D919, true); iconSmall = new Image(Assets.getAtlas().getTexture("darnahead1")); iconSmall.x = 360; iconSmall.y = 40; this.addChild(iconSmall); this.addChild(scoreText); this.addChild(remainingLives); } private function drawGame():void { bg = new GameBackground(); this.addChild(bg); hero = new Hero(); hero.x = stage.stageHeight / 2; hero.y = stage.stageWidth / 2; this.addChild(hero); startButton = new Button(Assets.getAtlas().getTexture("startButton")); startButton.x = stage.stageWidth * 0.5 - startButton.width * 0.5; startButton.y = stage.stageHeight * 0.5 - startButton.height * 0.5; this.addChild(startButton); gameArea = new Rectangle(0, 100, stage.stageWidth, stage.stageHeight - 250); } public function disposeTemporarily():void { this.visible = false; } public function initialize():void { this.visible = true; this.addEventListener(Event.ENTER_FRAME, checkElapsed); hero.x = -stage.stageWidth; hero.y = stage.stageHeight * 0.5; gameState ="idle"; playerSpeed = 0; hitObstacle = 0; bg.speed = 0; scoreDistance = 0; obstacleGapCount = 0; obstaclesToAnimate = new Vector.<Obstacle>(); itemsToAnimate = new Vector.<Item>(); startButton.addEventListener(Event.TRIGGERED, onStartButtonClick); //var mainStage:InGame =InGame.current.nativeStage; //mainStage.dispatchEvent(new Event(Event.COMPLETE)); //playAgain.addEventListener(Event.TRIGGERED, onRetry); } private function onStartButtonClick(event:Event):void { startButton.visible = false; startButton.removeEventListener(Event.TRIGGERED, onStartButtonClick); launchHero(); } private function launchHero():void { this.addEventListener(TouchEvent.TOUCH, onTouch); this.addEventListener(Event.ENTER_FRAME, onGameTick); } private function onTouch(event:TouchEvent):void { touch = event.getTouch(stage); touchX = touch.globalX; touchY = touch.globalY; } private function onGameTick(event:Event):void { switch(gameState) { case "idle": if(hero.x < stage.stageWidth * 0.5 * 0.5) { hero.x += ((stage.stageWidth * 0.5 * 0.5 + 10) - hero.x) * 0.05; hero.y = stage.stageHeight * 0.5; playerSpeed += (MIN_SPEED - playerSpeed) * 0.05; bg.speed = playerSpeed * elapsed; } else { gameState = "flying"; } break; case "flying": if(hitObstacle <= 0) { hero.y -= (hero.y - touchY) * 0.1; if(-(hero.y - touchY) < 150 && -(hero.y - touchY) > -150) { hero.rotation = deg2rad(-(hero.y - touchY) * 0.2); } if(hero.y > gameArea.bottom - hero.height * 0.5) { hero.y = gameArea.bottom - hero.height * 0.5; hero.rotation = deg2rad(0); } if(hero.y < gameArea.top + hero.height * 0.5) { hero.y = gameArea.top + hero.height * 0.5; hero.rotation = deg2rad(0); } } else { hitObstacle-- cameraShake(); } playerSpeed -= (playerSpeed - MIN_SPEED) * 0.01; bg.speed = playerSpeed * elapsed; scoreDistance += (playerSpeed * elapsed) * 0.1; scoreText.text = "Score: " + scoreDistance; initObstacle(); animateObstacles(); createEggItems(); animateItems(); remainingLives.text = "Lives: "+lives + " X "; if(lives == 0) { gameState = "over"; } break; case "over": gameOver(); break; } } private function gameOver():void { gameOverText = new TextField(800, 400, "Hero WAS KILLED!!!", "MyFontName", 50, 0xD9D919, true); scoreText = new TextField(800, 600, "Score: "+scoreDistance, "MyFontName", 30, 0xFFFFFF, true); this.addChild(scoreText); this.addChild(gameOverText); playAgain = new Button(Assets.getAtlas().getTexture("button_tryAgain")); playAgain.x = stage.stageWidth * 0.5 - startButton.width * 0.5; playAgain.y = stage.stageHeight * 0.75 - startButton.height * 0.75; this.addChild(playAgain); playAgain.addEventListener(Event.TRIGGERED, onRetry); } private function onRetry(event:Event):void { playAgain.visible = false; gameOverText.visible = false; scoreText.visible = false; var btnClicked:Button = event.target as Button; if((btnClicked as Button) == playAgain) { this.dispatchEvent(new NavigationEvent(NavigationEvent.CHANGE_SCREEN, {id: "playnow"}, true)); } disposeTemporarily(); } private function animateItems():void { var itemToTrack:Item; for(var i:uint = 0; i < itemsToAnimate.length; i++) { itemToTrack = itemsToAnimate[i]; itemToTrack.x -= playerSpeed * elapsed; if(itemToTrack.bounds.intersects(hero.bounds)) { itemsToAnimate.splice(i, 1); this.removeChild(itemToTrack); } if(itemToTrack.x < -50) { itemsToAnimate.splice(i, 1); this.removeChild(itemToTrack); } } } private function createEggItems():void { if(Math.random() > 0.95){ var itemToTrack:Item = new Item(Math.ceil(Math.random() * 10)); itemToTrack.x = stage.stageWidth + 50; itemToTrack.y = int(Math.random() * (gameArea.bottom - gameArea.top)) + gameArea.top; this.addChild(itemToTrack); itemsToAnimate.push(itemToTrack); } } private function cameraShake():void { if(hitObstacle > 0) { this.x = Math.random() * hitObstacle; this.y = Math.random() * hitObstacle; } else if(x != 0) { this.x = 0; this.y = 0; lives--; } } private function initObstacle():void { if(obstacleGapCount < 1200) { obstacleGapCount += playerSpeed * elapsed; } else if(obstacleGapCount !=0) { obstacleGapCount = 0; createObstacle(Math.ceil(Math.random() * 5), Math.random() * 1000 + 1000); } } private function animateObstacles():void { var obstacleToTrack:Obstacle; for(var i:uint = 0; i<obstaclesToAnimate.length; i++) { obstacleToTrack = obstaclesToAnimate[i]; if(obstacleToTrack.alreadyHit == false && obstacleToTrack.bounds.intersects(hero.bounds)) { obstacleToTrack.alreadyHit = true; obstacleToTrack.rotation = deg2rad(70); hitObstacle = 30; playerSpeed *= 0.5; } if(obstacleToTrack.distance > 0) { obstacleToTrack.distance -= playerSpeed * elapsed; } else { if(obstacleToTrack.watchOut) { obstacleToTrack.watchOut = false; } obstacleToTrack.x -= (playerSpeed + obstacleToTrack.speed) * elapsed; } if(obstacleToTrack.x < -obstacleToTrack.width || gameState == "over") { obstaclesToAnimate.splice(i, 1); this.removeChild(obstacleToTrack); } } } private function checkElapsed(event:Event):void { timePrevious = timeCurrent; timeCurrent = getTimer(); elapsed = (timeCurrent - timePrevious) * 0.001; } private function createObstacle(type:Number, distance:Number):void{ var obstacle:Obstacle = new Obstacle(type, distance, true, 300); obstacle.x = stage.stageWidth; this.addChild(obstacle); if(type >= 4) { if(Math.random() > 0.5) { obstacle.y = gameArea.top; obstacle.position = "top" } else { obstacle.y = gameArea.bottom - obstacle.height; obstacle.position = "bottom"; } } else { obstacle.y = int(Math.random() * (gameArea.bottom - obstacle.height - gameArea.top)) + gameArea.top; obstacle.position = "middle"; } obstaclesToAnimate.push(obstacle); } } }

    Read the article

  • Finding which tiles are intersected by a line, without looping through all of them or skipping any

    - by JustSuds
    I've been staring at this problem for a few days now. I rigged up this graphic to help me visualise the issue: http://i.stack.imgur.com/HxyP9.png (from the graph, we know that the line intersects [1, 1], [1, 2], [2, 2], [2, 3], ending in [3,3]) I want to step along the line to each grid space and check to see if the material of the grid space is solid. I feel like I already know the math involved, but I haven't been able to string it together yet. I'm using this to test line of sight and eliminate nodes after a path is found via my pathfinding algorithms - my agents cant see through a solid block, therefore they cant move through one, therefore the node is not eliminated from the path because it is required to navigate a corner. So, I need an algorithm that will step along the line to each grid space that it intersects. Any ideas? I've taken a look at a lot of common algorithms, like Bresenham's, and one that steps at predefined intervals along the line (unfortunately, this method skips tiles if they're intersecting with a smaller wedge than the step size). I'm populating my whiteboard now with a mass of floor() and ceil() functions - but its getting overly complicated and I'm afraid it might cause a slowdown.

    Read the article

  • jQuery, ASP.NET, and Browser History

    - by Stephen Walther
    One objection that people always raise against Ajax applications concerns browser history. Because an Ajax application updates its content by performing sneaky Ajax postbacks, the browser backwards and forwards buttons don’t work as you would normally expect. In a normal, non-Ajax application, when you click the browser back button, you return to a previous state of the application. For example, if you are paging through a set of movie records, you might return to the previous page of records. In an Ajax application, on the other hand, the browser backwards and forwards buttons do not work as you would expect. If you navigate to the second page in a list of records and click the backwards button, you won’t return to the previous page. Most likely, you will end up navigating away from the application entirely (which is very unexpected and irritating). Bookmarking presents a similar problem. You cannot bookmark a particular page of records in an Ajax application because the address bar does not reflect the state of the application. The Ajax Solution There is a solution to both of these problems. To solve both of these problems, you must take matters into your own hands and take responsibility for saving and restoring your application state yourself. Furthermore, you must ensure that the address bar gets updated to reflect the state of your application. In this blog entry, I demonstrate how you can take advantage of a jQuery library named bbq that enables you to control browser history (and make your Ajax application bookmarkable) in a cross-browser compatible way. The JavaScript Libraries In this blog entry, I take advantage of the following four JavaScript files: jQuery-1.4.2.js – The jQuery library. Available from the Microsoft Ajax CDN at http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js jquery.pager.js – Used to generate pager for navigating records. Available from http://plugins.jquery.com/project/Pager microtemplates.js – John Resig’s micro-templating library. Available from http://ejohn.org/blog/javascript-micro-templating/ jquery.ba-bbq.js – The Back Button and Query (BBQ) Library. Available from http://benalman.com/projects/jquery-bbq-plugin/ All of these libraries, with the exception of the Micro-templating library, are available under the MIT open-source license. The Ajax Application Let’s start by building a simple Ajax application that enables you to page through a set of movie database records, 3 records at a time. We’ll use my favorite database named MoviesDB. This database contains a Movies table that looks like this: We’ll create a data model for this database by taking advantage of the ADO.NET Entity Framework. The data model looks like this: Finally, we’ll expose the data to the universe with the help of a WCF Data Service named MovieService.svc. The code for the data service is contained in Listing 1. Listing 1 – MovieService.svc using System.Data.Services; using System.Data.Services.Common; namespace WebApplication1 { public class MovieService : DataService<MoviesDBEntities> { public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("Movies", EntitySetRights.AllRead); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } } } The WCF Data Service in Listing 1 exposes the movies so that you can query the movie database table with URLs that looks like this: http://localhost:2474/MovieService.svc/Movies -- Returns all movies http://localhost:2474/MovieService.svc/Movies?$top=5 – Returns 5 movies The HTML page in Listing 2 enables you to page through the set of movies retrieved from the WCF Data Service. Listing 2 – Original.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Movies with History</title> <link href="Design/Pager.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Page <span id="pageNumber"></span> of <span id="pageCount"></span></h1> <div id="pager"></div> <br style="clear:both" /><br /> <div id="moviesContainer"></div> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script src="App_Scripts/Microtemplates.js" type="text/javascript"></script> <script src="App_Scripts/jquery.pager.js" type="text/javascript"></script> <script type="text/javascript"> var pageSize = 3, pageIndex = 0; // Show initial page of movies showMovies(); function showMovies() { // Build OData query var query = "/MovieService.svc" // base URL + "/Movies" // top-level resource + "?$skip=" + pageIndex * pageSize // skip records + "&$top=" + pageSize // take records + " &$inlinecount=allpages"; // include total count of movies // Make call to WCF Data Service $.ajax({ dataType: "json", url: query, success: showMoviesComplete }); } function showMoviesComplete(result) { // unwrap results var movies = result["d"]["results"]; var movieCount = result["d"]["__count"] // Show movies using template var showMovie = tmpl("<li><%=Id%> - <%=Title %></li>"); var html = ""; for (var i = 0; i < movies.length; i++) { html += showMovie(movies[i]); } $("#moviesContainer").html(html); // show pager $("#pager").pager({ pagenumber: (pageIndex + 1), pagecount: Math.ceil(movieCount / pageSize), buttonClickCallback: selectPage }); // Update page number and page count $("#pageNumber").text(pageIndex + 1); $("#pageCount").text(movieCount); } function selectPage(pageNumber) { pageIndex = pageNumber - 1; showMovies(); } </script> </body> </html> The page in Listing 3 has the following three functions: showMovies() – Performs an Ajax call against the WCF Data Service to retrieve a page of movies. showMoviesComplete() – When the Ajax call completes successfully, this function displays the movies by using a template. This function also renders the pager user interface. selectPage() – When you select a particular page by clicking on a page number in the pager UI, this function updates the current page index and calls the showMovies() function. Figure 1 illustrates what the page looks like when it is opened in a browser. Figure 1 If you click the page numbers then the browser history is not updated. Clicking the browser forward and backwards buttons won’t move you back and forth in browser history. Furthermore, the address displayed in the address bar does not change when you navigate to different pages. You cannot bookmark any page except for the first page. Adding Browser History The Back Button and Query (bbq) library enables you to add support for browser history and bookmarking to a jQuery application. The bbq library supports two important methods: jQuery.bbq.pushState(object) – Adds state to browser history. jQuery.bbq.getState(key) – Gets state from browser history. The bbq library also supports one important event: hashchange – This event is raised when the part of an address after the hash # is changed. The page in Listing 3 demonstrates how to use the bbq library to add support for browser navigation and bookmarking to an Ajax page. Listing 3 – Default.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Movies with History</title> <link href="Design/Pager.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Page <span id="pageNumber"></span> of <span id="pageCount"></span></h1> <div id="pager"></div> <br style="clear:both" /><br /> <div id="moviesContainer"></div> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script src="App_Scripts/jquery.ba-bbq.js" type="text/javascript"></script> <script src="App_Scripts/Microtemplates.js" type="text/javascript"></script> <script src="App_Scripts/jquery.pager.js" type="text/javascript"></script> <script type="text/javascript"> var pageSize = 3, pageIndex = 0; $(window).bind('hashchange', function (e) { pageIndex = e.getState("pageIndex") || 0; pageIndex = parseInt(pageIndex); showMovies(); }); $(window).trigger('hashchange'); function showMovies() { // Build OData query var query = "/MovieService.svc" // base URL + "/Movies" // top-level resource + "?$skip=" + pageIndex * pageSize // skip records + "&$top=" + pageSize // take records +" &$inlinecount=allpages"; // include total count of movies // Make call to WCF Data Service $.ajax({ dataType: "json", url: query, success: showMoviesComplete }); } function showMoviesComplete(result) { // unwrap results var movies = result["d"]["results"]; var movieCount = result["d"]["__count"] // Show movies using template var showMovie = tmpl("<li><%=Id%> - <%=Title %></li>"); var html = ""; for (var i = 0; i < movies.length; i++) { html += showMovie(movies[i]); } $("#moviesContainer").html(html); // show pager $("#pager").pager({ pagenumber: (pageIndex + 1), pagecount: Math.ceil(movieCount / pageSize), buttonClickCallback: selectPage }); // Update page number and page count $("#pageNumber").text(pageIndex + 1); $("#pageCount").text(movieCount); } function selectPage(pageNumber) { pageIndex = pageNumber - 1; $.bbq.pushState({ pageIndex: pageIndex }); } </script> </body> </html> Notice the first chunk of JavaScript code in Listing 3: $(window).bind('hashchange', function (e) { pageIndex = e.getState("pageIndex") || 0; pageIndex = parseInt(pageIndex); showMovies(); }); $(window).trigger('hashchange'); When the hashchange event occurs, the current pageIndex is retrieved by calling the e.getState() method. The value is returned as a string and the value is cast to an integer by calling the JavaScript parseInt() function. Next, the showMovies() method is called to display the page of movies. The $(window).trigger() method is called to raise the hashchange event so that the initial page of records will be displayed. When you click a page number, the selectPage() method is invoked. This method adds the current page index to the address by calling the following method: $.bbq.pushState({ pageIndex: pageIndex }); For example, if you click on page number 2 then page index 1 is saved to the URL. The URL looks like this: Notice that when you click on page 2 then the browser address is updated to look like: /Default.htm#pageIndex=1 If you click on page 3 then the browser address is updated to look like: /Default.htm#pageIndex=2 Because the browser address is updated when you navigate to a new page number, the browser backwards and forwards button will work to navigate you backwards and forwards through the page numbers. When you click page 2, and click the backwards button, you will navigate back to page 1. Furthermore, you can bookmark a particular page of records. For example, if you bookmark the URL /Default.htm#pageIndex=1 then you will get the second page of records whenever you open the bookmark. Summary You should not avoid building Ajax applications because of worries concerning browser history or bookmarks. By taking advantage of a JavaScript library such as the bbq library, you can make your Ajax applications behave in exactly the same way as a normal web application.

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >