Search Results

Search found 141 results on 6 pages for 'invert'.

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

  • Drupal, Lightbox: cannot edit the content inside

    - by Patrick
    hi, I'm using Drupal and Lightbox module to display the content of articles in this website: donatellabernardi.ch/drupal if you click on an article the lightbox is displayed. However I have 2 problems with it: 1) I cannot use the libraries such as the tooltip library qTip from it. (If you move the mouse over the balls, you'll see the tooltips) 2) I cannot invert the title with the balls (tags), because it seems that the template of the node in the lightbox is not controlled by my theme. I tried also to change the node template (in the drupal root folder), swapping title and meta data but it didn't work. thanks

    Read the article

  • Circle-Rectangle collision in a tile map game

    - by furiousd
    I am making a 2D tile map based putt-putt game. I have collision detection working between the ball and the walls of the map, although when the ball collides at the meeting point between 2 tiles I offset it by 0.5 so that it doesn't get stuck in the wall. This aint a huge issue though. if(y % 20 == 0) { y+=0.5; } if(x % 20 == 0) { x+=0.5; } Collisions work as follows Find the closest point between each tile and the center of the ball If distance(ball_x, ball_y, close_x, close_y) <= ball_radius and the closest point belongs to a solid object, collision has occured Invert X/Y speed according to side of object collided with The next thing I tried to do was implement floating blocks in the middle of the map for the ball to bounce off of. When a ball collides with a corner of the block, it gets stuck in it. So I changed my determineRebound() function to treat corners as if they were circles. Here's that functon: `i and j are indexes of the solid object in the 2d map array. x & y are centre point of ball.` void determineRebound(int _i, int _j) { if(y > _i*tile_w && y < _i*tile_w + tile_w) { //Not a corner xs*=-1; } else if(x > _j*tile_w && x < _j*tile_w + tile_w) { //Not a corner ys*=-1; } else { //Corner float nx = x - close_x; float ny = y - close_y; float len = sqrt(nx * nx + ny * ny); nx /= len; ny /= len; float projection = xs * nx + ys * ny; xs -= 2 * projection * nx; ys -= 2 * projection * ny; } } This is where things have gotten messy. Collisions with 'floating' corners work fine, but now when the ball collides near the meeting point of 2 tiles, it detects a corner collision and does not rebound as expected. I'm a bit in over my head at this point. I guess I'm wondering if I'm going about making this sort of game in the right way. Is a 2d tile map the way to go? If so, is there a problem with my collision logic and where am I going wrong? Any advice/feedback would be great.

    Read the article

  • Fans running very fast on MacBook Pro 8.1 ubuntu 12.04

    - by Tomasz Kacprzak
    I installed Ubuntu 12.04 on Macbook Pro 8.1 and one of the first things I noticed was that the fans were starting to spin very fast every few minutes for 10-30 sec and then going back to normal. That was happening even without any processor load, when completely idle. The fans were usually spinning at 4000 RPM and made much noise. The computer was not getting hotter than usual. When running OSX Lion there was no noise at all, fans almost all the time at 2000 RPM. I spent some time on it and found out that Precise uses a deamon to control the temperature, called macfanctld. You can use /etc/macfanctld.conf to set the configuration. I found out that the high fan speed is not due to the fact that the temperature is getting hot, but because there are two sensors which indicate wrong numbers (you can check that using 'sensors' command ): TW0P: +129.0°C TCTD: +256.0°C TCFC: +0.0°C TMBS: +0.0°C or setting the macfanctld log level to 2: Speed: 4992, *AVG: 56.9C, TC0P: 50.2C, TG0P: 51.5C, Sensors: TB0T:34 TB1T:34 TB2T:33 TC0C:58 TC0D:56 TC0E:59 TC0F:60 TC0P:50 TC1C:58 TC2C:58 TC3C:58 TC4C:57 TCFC:0 TCGC:57 TCSA:53 TCTD:256 TG0D:52 TG0P:52 THSP:42 TM0S:64 TMBS:0 TP0P:54 TPCD:60 TW0P:129 Th1H:51 Th2H:48 Tm0P:40 Ts0P:32 Ts0S:43 Moreover, TCTD was randomly jumping from temperatures of 0 to 256, so this may be the reason for unjustified random fan speeds. macfanctld is taking an average of the sensors including the values above, so the actual AVG temp used to control the fans is wrong, usually biased up, hence high RPM and noise. The workaround solution is to use an option in the macfanctld.conf which allows to ignore the malfunctioning sensors: exclude: 13 16 21 24 After reboot the reported temperatures are usually normal and the fans are working at reasonable speeds. I tested the response of the fans to heavy processor load by asking MATLAB to invert 10000x10000 matrix and the AVG temperature jumped to 63deg, and the fan to max 6200 RPM and then got it back to normal temperature. So I think it is safe so far. There is a expired bug about the failing sensor readings: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/955538 which may be good to open again. My question would be: does anyone know what the failing sensors do and if there is any danger in excluding them? Maybe some better solution to this problem?

    Read the article

  • Fans running very fast on MacBook Pro 8.1

    - by Tomasz Kacprzak
    I installed Ubuntu 12.04 on Macbook Pro 8.1 and one of the first things I noticed was that the fans were starting to spin very fast every few minutes for 10-30 sec and then going back to normal. That was happening even without any processor load, when completely idle. The fans were usually spinning at 4000 RPM and made much noise. The computer was not getting hotter than usual. When running OSX Lion there was no noise at all, fans almost all the time at 2000 RPM. I spent some time on it and found out that Precise uses a deamon to control the temperature, called macfanctld. You can use /etc/macfanctld.conf to set the configuration. I found out that the high fan speed is not due to the fact that the temperature is getting hot, but because there are two sensors which indicate wrong numbers (you can check that using 'sensors' command ): TW0P: +129.0°C TCTD: +256.0°C TCFC: +0.0°C TMBS: +0.0°C or setting the macfanctld log level to 2: Speed: 4992, *AVG: 56.9C, TC0P: 50.2C, TG0P: 51.5C, Sensors: TB0T:34 TB1T:34 TB2T:33 TC0C:58 TC0D:56 TC0E:59 TC0F:60 TC0P:50 TC1C:58 TC2C:58 TC3C:58 TC4C:57 TCFC:0 TCGC:57 TCSA:53 TCTD:256 TG0D:52 TG0P:52 THSP:42 TM0S:64 TMBS:0 TP0P:54 TPCD:60 TW0P:129 Th1H:51 Th2H:48 Tm0P:40 Ts0P:32 Ts0S:43 Moreover, TCTD was randomly jumping from temperatures of 0 to 256, so this may be the reason for unjustified random fan speeds. macfanctld is taking an average of the sensors including the values above, so the actual AVG temp used to control the fans is wrong, usually biased up, hence high RPM and noise. The workaround solution is to use an option in the macfanctld.conf which allows to ignore the malfunctioning sensors: exclude: 13 16 21 24 After reboot the reported temperatures are usually normal and the fans are working at reasonable speeds. I tested the response of the fans to heavy processor load by asking MATLAB to invert 10000x10000 matrix and the AVG temperature jumped to 63deg, and the fan to max 6200 RPM and then got it back to normal temperature. So I think it is safe so far. There is a expired bug about the failing sensor readings: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/955538 which may be good to open again. My question would be: does anyone know what the failing sensors do and if there is any danger in excluding them? Maybe some better solution to this problem?

    Read the article

  • Checking timeouts made more readable

    - by Markus
    I have several situations where I need to control timeouts in a technical application. Either in a loop or as a simple check. Of course – handling this is really easy, but none of these is looking cute. To clarify, here is some C# (Pseudo) code: private DateTime girlWentIntoBathroom; girlWentIntoBathroom = DateTime.Now; do { // do something } while (girlWentIntoBathroom.AddSeconds(10) > DateTime.Now); or if (girlWentIntoBathroom.AddSeconds(10) > DateTime.Now) MessageBox.Show("Wait a little longer"); else MessageBox.Show("Knock louder"); Now I was inspired by something a saw in Ruby on StackOverflow: Now I’m wondering if this construct can be made more readable using extension methods. My goal is something that can be read like “If girlWentIntoBathroom is more than 10 seconds ago” 1st attempt if (girlWentIntoBathroom > (10).Seconds().Ago()) MessageBox.Show("Wait a little longer"); else MessageBox.Show("Knock louder"); So I wrote an extension for integer that converts the integer into a TimeSpan public static TimeSpan Seconds(this int amount) { return new TimeSpan(0, 0, amount); } After that, I wrote an extension for TimeSpan like this: public static DateTime Ago(this TimeSpan diff) { return DateTime.Now.Add(-diff); } This works fine so far, but has a great disadvantage. The logic is inverted! Since girlWentIntoBathroom is a timestamp in the past, the right side of the equation needs to count backwards: impossible. Just inverting the equation is no solution, because it will invert the read sentence as well. 2nd attempt So I tried something new: if (girlWentIntoBathroom.IsMoreThan(10).SecondsAgo()) MessageBox.Show("Knock louder"); else MessageBox.Show("Wait a little longer"); IsMoreThan() needs to transport the past timestamp as well as the span for the extension SecondsAgo(). It could be: public static DateWithIntegerSpan IsMoreThan(this DateTime baseTime, int span) { return new DateWithIntegerSpan() { Date = baseTime, Span = span }; } Where DateWithIntegerSpan is simply: public class DateWithIntegerSpan { public DateTime Date {get; set;} public int Span { get; set; } } And SecondsAgo() is public static bool SecondsAgo(this DateWithIntegerSpan dateAndSpan) { return dateAndSpan.Date.Add(new TimeSpan(0, 0, dateAndSpan.Span)) < DateTime.Now; } Using this approach, the English sentence matches the expected behavior. But the disadvantage is, that I need a helping class (DateWithIntegerSpan). Has anyone an idea to make checking timeouts look more cute and closer to a readable sentence? Am I a little too insane thinking about something minor like this?

    Read the article

  • SSL on local sub-domain and sub-sub-domain

    - by Eduard Luca
    I have both local.domain.com and lmarket.local.domain.com pointing to my localhost from etc/hosts. The problem is that I am using XAMPP on Windows 7, and have 2 SSL VirtualHosts in my apache config, but no matter which one I access, I am taken to local.domain.com. On non-HTTPS requests all works fine, and the vhosts are basically the same. Here is the relevant part of my vhosts: <VirtualHost local.domain.com:443> DocumentRoot "C:/xampp/htdocs/local" ServerName local.domain.com ServerAdmin webmaster@localhost ErrorLog "logs/error.log" <IfModule log_config_module> CustomLog "logs/access.log" combined </IfModule> SSLEngine on SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL SSLCertificateFile "conf/ssl.crt/server.crt" SSLCertificateKeyFile "conf/ssl.key/server.key" <FilesMatch "\.(cgi|shtml|pl|asp|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory "C:/xampp/cgi-bin"> SSLOptions +StdEnvVars </Directory> BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0 CustomLog "logs/ssl_request.log" "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b" </VirtualHost> <VirtualHost lmarket.local.domain.com:443> DocumentRoot "C:/xampp/htdocs/lmarket.local" ServerName lmarket.local.domain.com ServerAdmin webmaster@localhost ErrorLog "logs/error.log" <IfModule log_config_module> CustomLog "logs/access.log" combined </IfModule> SSLEngine on SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL SSLCertificateFile "conf/ssl.crt/server.crt" SSLCertificateKeyFile "conf/ssl.key/server.key" <FilesMatch "\.(cgi|shtml|pl|asp|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory "C:/xampp/cgi-bin"> SSLOptions +StdEnvVars </Directory> BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0 CustomLog "logs/ssl_request.log" "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b" </VirtualHost> If I invert these blocks, then the opposite happens: local.domain.com goes to lmarket.local.domain.com. Any help would be appreciated.

    Read the article

  • Best way to mount 3-4 monitor like this?

    - by jasondavis
    I just purchased 2 HP 2009m widescreen monitors, they are not the biggest thing on the block, they are like 19-20" and are only around 150-200$ so I think they are perfect. I bought 2 of them just to make sure I like them, with the full intention of purchasing more to make either a tripple or quad display. I now I am stuck trying to decide, if I purchase 1 more to have a tripple display I would then like to just wrap the third monitor to either the rigth or left side, I could do this without a mount most likely pretty easy. If I decide to go with 2 more monitors to make a quad display then I would like to add the 2 new monitor directly above the 2 that I have now. So it would make a grid of 2 wide and 2 high. I have posted a few photos belwo to show them now with the 2 I have, you will notice that I have them tilted inwards to make more of a "V" shape instead of them being side by side and "STRAIGHT". Now if I decide to make thegrid of 4 then I will need to buy or build a stand to hold them all tightly together (no whitespace or gap between the grid of monitors) but I would like to still have both rows invert to make the slight "V". Do you know of any existing stands I could purchase that would hold all 4 monitors without making them be STARIGHT without the "V" shape? Any tips appreciated please, also they do have holes in the back for VESA. a few photos... (they are from iphone and lighting made them note very good but you can see what I am working with here)

    Read the article

  • How to crop Screen Recordings under Snow Leopard?

    - by willc2
    Quicktime Player for Snow Leopard now allows you record the screen. Awesome! Once you have a movie it will let you trim screen recordings for length. Is there a way to crop the movie's dimensions, either in QT or using some built-in or free software? Update: How to crop to an arbitrary size and aspect ratio? iMovie only seems to let you crop to the aspect ratio of the containing project. Result: Both good answers but since I have QuickTime Player 7 and Photoshop, that's the workflow I choose as the answer. NOTE: If you have Photoshop Extended, you can import a movie, use the crop tool, and Export the cropped movie. Not free or built-in, but convenient. To summarize the instructions from the video link ricbax posted: Open movie in QuickTime Player 7 Copy a frame and Paste it into a new document in Photoshop Draw a rectangular selection around the area to keep and fill with black Invert the selection and fill with white Save as .GIF, with 2 colors Back in QuickTime Player 7, open Movie Properties window Select the Video Track Select the Visual Settings Tab Drag and Drop the 2-color .GIF file onto the Mask drop area (or use choose file button) Export the (now cropped) movie DONE

    Read the article

  • How do I get FEATURE_LEVEL_9_3 to work with shaders in Direct3D11?

    - by Dominic
    Currently I'm going through some tutorials and learning DX11 on a DX10 machine (though I just ordered a new DX11 compatible computer) by means of setting the D3D_FEATURE_LEVEL_ setting to 10_0 and switching the vertex and pixel shader versions in D3DX11CompileFromFile to "vs_4_0" and "ps_4_0" respectively. This works fine as I'm not using any DX11-only features yet. I'd like to make it compatible with DX9.0c, which naively I thought I could do by changing the feature level setting to 9_3 or something and taking the vertex/pixel shader versions down to 3 or 2. However, no matter what I change the vertex/pixel shader versions to, it always fails when I try to call D3DX11CompileFromFile to compile the vertex/pixel shader files when I have D3D_FEATURE_LEVEL_9_3 enabled. Maybe this is due to the the vertex/pixel shader files themselves being incompatible for the lower vertex/pixel shader versions, but I'm not expert enough to say. My shader files are listed below: Vertex shader: cbuffer MatrixBuffer { matrix worldMatrix; matrix viewMatrix; matrix projectionMatrix; }; struct VertexInputType { float4 position : POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; }; struct PixelInputType { float4 position : SV_POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; }; PixelInputType LightVertexShader(VertexInputType input) { PixelInputType output; // Change the position vector to be 4 units for proper matrix calculations. input.position.w = 1.0f; // Calculate the position of the vertex against the world, view, and projection matrices. output.position = mul(input.position, worldMatrix); output.position = mul(output.position, viewMatrix); output.position = mul(output.position, projectionMatrix); // Store the texture coordinates for the pixel shader. output.tex = input.tex; // Calculate the normal vector against the world matrix only. output.normal = mul(input.normal, (float3x3)worldMatrix); // Normalize the normal vector. output.normal = normalize(output.normal); return output; } Pixel Shader: Texture2D shaderTexture; SamplerState SampleType; cbuffer LightBuffer { float4 ambientColor; float4 diffuseColor; float3 lightDirection; float padding; }; struct PixelInputType { float4 position : SV_POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; }; float4 LightPixelShader(PixelInputType input) : SV_TARGET { float4 textureColor; float3 lightDir; float lightIntensity; float4 color; // Sample the pixel color from the texture using the sampler at this texture coordinate location. textureColor = shaderTexture.Sample(SampleType, input.tex); // Set the default output color to the ambient light value for all pixels. color = ambientColor; // Invert the light direction for calculations. lightDir = -lightDirection; // Calculate the amount of light on this pixel. lightIntensity = saturate(dot(input.normal, lightDir)); if(lightIntensity > 0.0f) { // Determine the final diffuse color based on the diffuse color and the amount of light intensity. color += (diffuseColor * lightIntensity); } // Saturate the final light color. color = saturate(color); // Multiply the texture pixel and the final diffuse color to get the final pixel color result. color = color * textureColor; return color; }

    Read the article

  • Converting openGl code to DirectX

    - by Fredrik Boston Westman
    First of all, this is kind of a follow up question on @byte56 excellent anwser on this question concerning picking algorithms. I'm trying to convert one of his code examples to directX 11 however I have run in to some problems ( I can pick but the picking is way off), and I wanted to make sure I had done it rigth before moving on and checking the rest of my code. I am not that familiar with openGl but I can imagine openGl has diffrent coordinations systems, and functions that alters how you must implement to code abit. This is his code example: public Ray GetPickRay() { int mouseX = Mouse.getX(); int mouseY = WORLD.Byte56Game.getHeight() - Mouse.getY(); float windowWidth = WORLD.Byte56Game.getWidth(); float windowHeight = WORLD.Byte56Game.getHeight(); //get the mouse position in screenSpace coords double screenSpaceX = ((float) mouseX / (windowWidth / 2) - 1.0f) * aspectRatio; double screenSpaceY = (1.0f - (float) mouseY / (windowHeight / 2)); double viewRatio = Math.tan(((float) Math.PI / (180.f/ViewAngle) / 2.00f))* zoomFactor; screenSpaceX = screenSpaceX * viewRatio; screenSpaceY = screenSpaceY * viewRatio; //Find the far and near camera spaces Vector4f cameraSpaceNear = new Vector4f((float) (screenSpaceX * NearPlane), (float) (screenSpaceY * NearPlane), (float) (-NearPlane), 1); Vector4f cameraSpaceFar = new Vector4f((float) (screenSpaceX * FarPlane), (float) (screenSpaceY * FarPlane), (float) (-FarPlane), 1); //Unproject the 2D window into 3D to see where in 3D we're actually clicking Matrix4f tmpView = Matrix4f(view); Matrix4f invView = (Matrix4f) tmpView.invert(); Vector4f worldSpaceNear = new Vector4f(); Matrix4f.transform(invView, cameraSpaceNear, worldSpaceNear); Vector4f worldSpaceFar = new Vector4f(); Matrix4f.transform(invView, cameraSpaceFar, worldSpaceFar); //calculate the ray position and direction Vector3f rayPosition = new Vector3f(worldSpaceNear.x, worldSpaceNear.y, worldSpaceNear.z); Vector3f rayDirection = new Vector3f(worldSpaceFar.x - worldSpaceNear.x, worldSpaceFar.y - worldSpaceNear.y, worldSpaceFar.z - worldSpaceNear.z); rayDirection.normalise(); return new Ray(rayPosition, rayDirection); } All rigths reserved to him of course This is my DirectX 11 code : void GraphicEngine::pickRayVector(float mouseX, float mouseY,XMVECTOR& pickRayInWorldSpacePos, XMVECTOR& pickRayInWorldSpaceDir) { float PRVecX, PRVecY; float nearPlane = 0.1f; float farPlane = 200.0f; floar viewAngle = 0.4 * 3.14; PRVecX = ((( 2.0f * mouseX) / ClientWidth ) - 1 ) * tan((viewAngle)/2); PRVecY = (1-(( 2.0f * mouseY) / ClientHeight)) * tan((viewAngle)/2); XMVECTOR cameraSpaceNear = XMVectorSet(PRVecX * nearPlane,PRVecY * nearPlane, -nearPlane, 1.0f); XMVECTOR cameraSpaceFar = XMVectorSet(PRVecX * farPlane,PRVecY * farPlane, -farPlane, 1.0f); // Transform 3D Ray from View space to 3D ray in World space XMMATRIX invMat; XMVECTOR matInvDeter; invMat = XMMatrixInverse(&matInvDeter, cam->getCameraView()); //Inverse of View Space matrix is World space matrix XMVECTOR worldSpaceNear = XMVector3TransformCoord(cameraSpaceNear, invMat); XMVECTOR worldSpaceFar = XMVector3TransformCoord(cameraSpaceFar, invMat); pickRayInWorldSpacePos = worldSpaceNear; pickRayInWorldSpaceDir = worldSpaceFar-worldSpaceNear; pickRayInWorldSpaceDir = XMVector3Normalize(pickRayInWorldSpaceDir); } A couple of notes: The mouse coordinates are already converted so that the top left corner of the client window would be (0,0) and the bottom rigth (800,600) ( or whatever resolution you would have) I hadn't used any far or near plane before, so i just made some arbitrary number up for them. To my understanding it shouldnt matter as long as the object you are trying to pick is in between the range of thoese numbers The viewAngle is the same angle that I used when setting the camera view with XMMatrixPerspectiveFovLH , I just hadn't made it a member variable of my Camera class yet. I removed the variable aspectRation and zoomFactor because I assumed that they where related to some specific function of his game. Now I'm not sure, but I think the problems lies either withing the mouse to viewspace conversion, maby that we use diffrent coordinations systems. Either that or how i transform the matrixes in the the end, because i know order is important when it comes to matrixes. Any help is appriciated! Thanks in advance. Edit: One more note, my code is in c++

    Read the article

  • Getting FEATURE_LEVEL_9_3 to work in DX11

    - by Dominic
    Currently I'm going through some tutorials and learning DX11 on a DX10 machine (though I just ordered a new DX11 compatible computer) by means of setting the D3D_FEATURE_LEVEL_ setting to 10_0 and switching the vertex and pixel shader versions in D3DX11CompileFromFile to "vs_4_0" and "ps_4_0" respectively. This works fine as I'm not using any DX11-only features yet. I'd like to make it compatible with DX9.0c, which naively I thought I could do by changing the feature level setting to 9_3 or something and taking the vertex/pixel shader versions down to 3 or 2. However, no matter what I change the vertex/pixel shader versions to, it always fails when I try to call D3DX11CompileFromFile to compile the vertex/pixel shader files when I have D3D_FEATURE_LEVEL_9_3 enabled. Maybe this is due to the the vertex/pixel shader files themselves being incompatible for the lower vertex/pixel shader versions, but I'm not expert enough to say. My shader files are listed below: Vertex shader: cbuffer MatrixBuffer { matrix worldMatrix; matrix viewMatrix; matrix projectionMatrix; }; struct VertexInputType { float4 position : POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; }; struct PixelInputType { float4 position : SV_POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; }; PixelInputType LightVertexShader(VertexInputType input) { PixelInputType output; // Change the position vector to be 4 units for proper matrix calculations. input.position.w = 1.0f; // Calculate the position of the vertex against the world, view, and projection matrices. output.position = mul(input.position, worldMatrix); output.position = mul(output.position, viewMatrix); output.position = mul(output.position, projectionMatrix); // Store the texture coordinates for the pixel shader. output.tex = input.tex; // Calculate the normal vector against the world matrix only. output.normal = mul(input.normal, (float3x3)worldMatrix); // Normalize the normal vector. output.normal = normalize(output.normal); return output; } Pixel Shader: Texture2D shaderTexture; SamplerState SampleType; cbuffer LightBuffer { float4 ambientColor; float4 diffuseColor; float3 lightDirection; float padding; }; struct PixelInputType { float4 position : SV_POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; }; float4 LightPixelShader(PixelInputType input) : SV_TARGET { float4 textureColor; float3 lightDir; float lightIntensity; float4 color; // Sample the pixel color from the texture using the sampler at this texture coordinate location. textureColor = shaderTexture.Sample(SampleType, input.tex); // Set the default output color to the ambient light value for all pixels. color = ambientColor; // Invert the light direction for calculations. lightDir = -lightDirection; // Calculate the amount of light on this pixel. lightIntensity = saturate(dot(input.normal, lightDir)); if(lightIntensity > 0.0f) { // Determine the final diffuse color based on the diffuse color and the amount of light intensity. color += (diffuseColor * lightIntensity); } // Saturate the final light color. color = saturate(color); // Multiply the texture pixel and the final diffuse color to get the final pixel color result. color = color * textureColor; return color; }

    Read the article

  • Numerically stable(ish) method of getting Y-intercept of mouse position?

    - by Fraser
    I'm trying to unproject the mouse position to get the position on the X-Z plane of a ray cast from the mouse. The camera is fully controllable by the user. Right now, the algorithm I'm using is... Unproject the mouse into the camera to get the ray: Vector3 p1 = Vector3.Unproject(new Vector3(x, y, 0), 0, 0, width, height, nearPlane, farPlane, viewProj; Vector3 p2 = Vector3.Unproject(new Vector3(x, y, 1), 0, 0, width, height, nearPlane, farPlane, viewProj); Vector3 dir = p2 - p1; dir.Normalize(); Ray ray = Ray(p1, dir); Then get the Y-intercept by using algebra: float t = -ray.Position.Y / ray.Direction.Y; Vector3 p = ray.Position + t * ray.Direction; The problem is that the projected position is "jumpy". As I make small adjustments to the mouse position, the projected point moves in strange ways. For example, if I move the mouse one pixel up, it will sometimes move the projected position down, but when I move it a second pixel, the project position will jump back to the mouse's location. The projected location is always close to where it should be, but it does not smoothly follow a moving mouse. The problem intensifies as I zoom the camera out. I believe the problem is caused by numeric instability. I can make minor improvements to this by doing some computations at double precision, and possibly abusing the fact that floating point calculations are done at 80-bit precision on x86, however before I start micro-optimizing this and getting deep into how the CLR handles floating point, I was wondering if there's an algorithmic change I can do to improve this? EDIT: A little snooping around in .NET Reflector on SlimDX.dll: public static Vector3 Unproject(Vector3 vector, float x, float y, float width, float height, float minZ, float maxZ, Matrix worldViewProjection) { Vector3 coordinate = new Vector3(); Matrix result = new Matrix(); Matrix.Invert(ref worldViewProjection, out result); coordinate.X = (float) ((((vector.X - x) / ((double) width)) * 2.0) - 1.0); coordinate.Y = (float) -((((vector.Y - y) / ((double) height)) * 2.0) - 1.0); coordinate.Z = (vector.Z - minZ) / (maxZ - minZ); TransformCoordinate(ref coordinate, ref result, out coordinate); return coordinate; } // ... public static void TransformCoordinate(ref Vector3 coordinate, ref Matrix transformation, out Vector3 result) { Vector3 vector; Vector4 vector2 = new Vector4 { X = (((coordinate.Y * transformation.M21) + (coordinate.X * transformation.M11)) + (coordinate.Z * transformation.M31)) + transformation.M41, Y = (((coordinate.Y * transformation.M22) + (coordinate.X * transformation.M12)) + (coordinate.Z * transformation.M32)) + transformation.M42, Z = (((coordinate.Y * transformation.M23) + (coordinate.X * transformation.M13)) + (coordinate.Z * transformation.M33)) + transformation.M43 }; float num = (float) (1.0 / ((((transformation.M24 * coordinate.Y) + (transformation.M14 * coordinate.X)) + (coordinate.Z * transformation.M34)) + transformation.M44)); vector2.W = num; vector.X = vector2.X * num; vector.Y = vector2.Y * num; vector.Z = vector2.Z * num; result = vector; } ...which seems to be a pretty standard method of unprojecting a point from a projection matrix, however this serves to introduce another point of possible instability. Still, I'd like to stick with the SlimDX Unproject routine rather than writing my own unless it's really necessary.

    Read the article

  • Why do I get a DependencyProperty.UnsetValue when converting a value in a MultiBinding?

    - by eskerber
    I have an extremely simple IMultiValueConverter that simply OR's two values. In the example below, I want to invert the first value using an equally simple boolean inverter. <MultiBinding Converter="{StaticResource multiBoolToVis}"> <Binding Path="ConditionA" Converter="{StaticResource boolInverter}"/> <Binding Path="ConditionB"/> </MultiBinding> public class BoolInverterConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is bool) { return !((bool)value); } return null; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } When I include the boolInverter, the first value in the MultiValueConverter becomes a "DependencyProperty.UnsetValue". There are no problems when I do not use the converter (other than not the logic I am aiming for, of course). Am I missing something? Stepping through the debugger shows that the InverseBoolConverter is properly inverting the value I pass it, but that value is then not being 'sent' to the MultiValueConverter.

    Read the article

  • How do I locate the CGRect for a substring of text in a UILabel?

    - by bryanjclark
    For a given NSRange, I'd like to find a CGRect in a UILabel that corresponds to the glyphs of that NSRange. For example, I'd like to find the CGRect that contains the word "dog" in the sentence "The quick brown fox jumps over the lazy dog." The trick is, the UILabel has multiple lines, and the text is really attributedText, so it's a bit tough to find the exact position of the string. The method that I'd like to write on my UILabel subclass would look something like this: - (CGRect)rectForSubstringWithRange:(NSRange)range; Details, for those who are interested: My goal with this is to be able to create a new UILabel with the exact appearance and position of the UILabel, that I can then animate. I've got the rest figured out, but it's this step in particular that's holding me back at the moment. What I've done to try and solve the issue so far: I'd hoped that with iOS 7, there'd be a bit of Text Kit that would solve this problem, but most every example I've seen with Text Kit focuses on UITextView and UITextField, rather than UILabel. I've seen another question on Stack Overflow here that promises to solve the problem, but the accepted answer is over two years old, and the code doesn't perform well with attributed text. I'd bet that the right answer to this involves one of the following: Using a standard Text Kit method to solve this problem in a single line of code. I'd bet it would involve NSLayoutManager and textContainerForGlyphAtIndex:effectiveRange Writing a complex method that breaks the UILabel into lines, and finds the rect of a glyph within a line, likely using Core Text methods. My current best bet is to take apart @mattt's excellent TTTAttributedLabel, which has a method that finds a glyph at a point - if I invert that, and find the point for a glyph, that might work. Update: Here's a github gist with the three things I've tried so far to solve this issue: https://gist.github.com/bryanjclark/7036101

    Read the article

  • Calculating skew of text OpenCV

    - by Nick
    I am trying to calculate the skew of text in an image so I can correct it for the best OCR results. Currently this is the function I am using: double compute_skew(Mat &img) { // Binarize cv::threshold(img, img, 225, 255, cv::THRESH_BINARY); // Invert colors cv::bitwise_not(img, img); cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 3)); cv::erode(img, img, element); std::vector<cv::Point> points; cv::Mat_<uchar>::iterator it = img.begin<uchar>(); cv::Mat_<uchar>::iterator end = img.end<uchar>(); for (; it != end; ++it) if (*it) points.push_back(it.pos()); cv::RotatedRect box = cv::minAreaRect(cv::Mat(points)); double angle = box.angle; if (angle < -45.) angle += 90.; cv::Point2f vertices[4]; box.points(vertices); for(int i = 0; i < 4; ++i) cv::line(img, vertices[i], vertices[(i + 1) % 4], cv::Scalar(255, 0, 0), 1, CV_AA); return angle; } When I look at then angle in debug I get 0.000000 However when I give it this image I get proper results of a skew of about 16 degrees: How can I properly detect the skew in the first image?

    Read the article

  • rails inverting to_xml and getting the original model

    - by djacobs7
    I did this: [User.first, User.last].to_xml and got this: <users type="array"> <user> <created-at type="datetime">2010-03-16T06:40:51Z</created-at> <id type="integer">3</id> <password-hash></password-hash> <salt></salt> <updated-at type="datetime">2010-03-16T06:40:51Z</updated-at> <username nil="true"></username> </user> <user> <created-at type="datetime">2010-03-23T03:58:15Z</created-at> <id type="integer">7</id> <password-hash></password-hash> <salt></salt> <tutorial-state nil="true"></tutorial-state> <updated-at type="datetime">2010-03-23T03:58:15Z</updated-at> <username nil="true"></username> </user> </users> How can I take that string of xml and invert it to get the original activerecord objects back?

    Read the article

  • how to export bind and keyframe bone poses from blender to use in OpenGL

    - by SaldaVonSchwartz
    EDIT: I decided to reformulate the question in much simpler terms to see if someone can give me a hand with this. Basically, I'm exporting meshes, skeletons and actions from blender into an engine of sorts that I'm working on. But I'm getting the animations wrong. I can tell the basic motion paths are being followed but there's always an axis of translation or rotation which is wrong. I think the problem is most likely not in my engine code (OpenGL-based) but rather in either my misunderstanding of some part of the theory behind skeletal animation / skinning or the way I am exporting the appropriate joint matrices from blender in my exporter script. I'll explain the theory, the engine animation system and my blender export script, hoping someone might catch the error in either or all of these. The theory: (I'm using column-major ordering since that's what I use in the engine cause it's OpenGL-based) Assume I have a mesh made up of a single vertex v, along with a transformation matrix M which takes the vertex v from the mesh's local space to world space. That is, if I was to render the mesh without a skeleton, the final position would be gl_Position = ProjectionMatrix * M * v. Now assume I have a skeleton with a single joint j in bind / rest pose. j is actually another matrix. A transform from j's local space to its parent space which I'll denote Bj. if j was part of a joint hierarchy in the skeleton, Bj would take from j space to j-1 space (that is to its parent space). However, in this example j is the only joint, so Bj takes from j space to world space, like M does for v. Now further assume I have a a set of frames, each with a second transform Cj, which works the same as Bj only that for a different, arbitrary spatial configuration of join j. Cj still takes vertices from j space to world space but j is rotated and/or translated and/or scaled. Given the above, in order to skin vertex v at keyframe n. I need to: take v from world space to joint j space modify j (while v stays fixed in j space and is thus taken along in the transformation) take v back from the modified j space to world space So the mathematical implementation of the above would be: v' = Cj * Bj^-1 * v. Actually, I have one doubt here.. I said the mesh to which v belongs has a transform M which takes from model space to world space. And I've also read in a couple textbooks that it needs to be transformed from model space to joint space. But I also said in 1 that v needs to be transformed from world to joint space. So basically I'm not sure if I need to do v' = Cj * Bj^-1 * v or v' = Cj * Bj^-1 * M * v. Right now my implementation multiples v' by M and not v. But I've tried changing this and it just screws things up in a different way cause there's something else wrong. Finally, If we wanted to skin a vertex to a joint j1 which in turn is a child of a joint j0, Bj1 would be Bj0 * Bj1 and Cj1 would be Cj0 * Cj1. But Since skinning is defined as v' = Cj * Bj^-1 * v , Bj1^-1 would be the reverse concatenation of the inverses making up the original product. That is, v' = Cj0 * Cj1 * Bj1^-1 * Bj0^-1 * v Now on to the implementation (Blender side): Assume the following mesh made up of 1 cube, whose vertices are bound to a single joint in a single-joint skeleton: Assume also there's a 60-frame, 3-keyframe animation at 60 fps. The animation essentially is: keyframe 0: the joint is in bind / rest pose (the way you see it in the image). keyframe 30: the joint translates up (+z in blender) some amount and at the same time rotates pi/4 rad clockwise. keyframe 59: the joint goes back to the same configuration it was in keyframe 0. My first source of confusion on the blender side is its coordinate system (as opposed to OpenGL's default) and the different matrices accessible through the python api. Right now, this is what my export script does about translating blender's coordinate system to OpenGL's standard system: # World transform: Blender -> OpenGL worldTransform = Matrix().Identity(4) worldTransform *= Matrix.Scale(-1, 4, (0,0,1)) worldTransform *= Matrix.Rotation(radians(90), 4, "X") # Mesh (local) transform matrix file.write('Mesh Transform:\n') localTransform = mesh.matrix_local.copy() localTransform = worldTransform * localTransform for col in localTransform.col: file.write('{:9f} {:9f} {:9f} {:9f}\n'.format(col[0], col[1], col[2], col[3])) file.write('\n') So if you will, my "world" matrix is basically the act of changing blenders coordinate system to the default GL one with +y up, +x right and -z into the viewing volume. Then I also premultiply (in the sense that it's done by the time we reach the engine, not in the sense of post or pre in terms of matrix multiplication order) the mesh matrix M so that I don't need to multiply it again once per draw call in the engine. About the possible matrices to extract from Blender joints (bones in Blender parlance), I'm doing the following: For joint bind poses: def DFSJointTraversal(file, skeleton, jointList): for joint in jointList: bindPoseJoint = skeleton.data.bones[joint.name] bindPoseTransform = bindPoseJoint.matrix_local.inverted() file.write('Joint ' + joint.name + ' Transform {\n') translationV = bindPoseTransform.to_translation() rotationQ = bindPoseTransform.to_3x3().to_quaternion() scaleV = bindPoseTransform.to_scale() file.write('T {:9f} {:9f} {:9f}\n'.format(translationV[0], translationV[1], translationV[2])) file.write('Q {:9f} {:9f} {:9f} {:9f}\n'.format(rotationQ[1], rotationQ[2], rotationQ[3], rotationQ[0])) file.write('S {:9f} {:9f} {:9f}\n'.format(scaleV[0], scaleV[1], scaleV[2])) DFSJointTraversal(file, skeleton, joint.children) file.write('}\n') Note that I'm actually grabbing the inverse of what I think is the bind pose transform Bj. This is so I don't need to invert it in the engine. Also note I went for matrix_local, assuming this is Bj. The other option is plain "matrix", which as far as I can tell is the same only that not homogeneous. For joint current / keyframe poses: for kfIndex in keyframes: bpy.context.scene.frame_set(kfIndex) file.write('keyframe: {:d}\n'.format(int(kfIndex))) for i in range(0, len(skeleton.data.bones)): file.write('joint: {:d}\n'.format(i)) currentPoseJoint = skeleton.pose.bones[i] currentPoseTransform = currentPoseJoint.matrix translationV = currentPoseTransform.to_translation() rotationQ = currentPoseTransform.to_3x3().to_quaternion() scaleV = currentPoseTransform.to_scale() file.write('T {:9f} {:9f} {:9f}\n'.format(translationV[0], translationV[1], translationV[2])) file.write('Q {:9f} {:9f} {:9f} {:9f}\n'.format(rotationQ[1], rotationQ[2], rotationQ[3], rotationQ[0])) file.write('S {:9f} {:9f} {:9f}\n'.format(scaleV[0], scaleV[1], scaleV[2])) file.write('\n') Note that here I go for skeleton.pose.bones instead of data.bones and that I have a choice of 3 matrices: matrix, matrix_basis and matrix_channel. From the descriptions in the python API docs I'm not super clear which one I should choose, though I think it's the plain matrix. Also note I do not invert the matrix in this case. The implementation (Engine / OpenGL side): My animation subsystem does the following on each update (I'm omitting parts of the update loop where it's figured out which objects need update and time is hardcoded here for simplicity): static double time = 0; time = fmod((time + elapsedTime),1.); uint16_t LERPKeyframeNumber = 60 * time; uint16_t lkeyframeNumber = 0; uint16_t lkeyframeIndex = 0; uint16_t rkeyframeNumber = 0; uint16_t rkeyframeIndex = 0; for (int i = 0; i < aClip.keyframesCount; i++) { uint16_t keyframeNumber = aClip.keyframes[i].number; if (keyframeNumber <= LERPKeyframeNumber) { lkeyframeIndex = i; lkeyframeNumber = keyframeNumber; } else { rkeyframeIndex = i; rkeyframeNumber = keyframeNumber; break; } } double lTime = lkeyframeNumber / 60.; double rTime = rkeyframeNumber / 60.; double blendFactor = (time - lTime) / (rTime - lTime); GLKMatrix4 bindPosePalette[aSkeleton.jointsCount]; GLKMatrix4 currentPosePalette[aSkeleton.jointsCount]; for (int i = 0; i < aSkeleton.jointsCount; i++) { F3DETQSType& lPose = aClip.keyframes[lkeyframeIndex].skeletonPose.joints[i]; F3DETQSType& rPose = aClip.keyframes[rkeyframeIndex].skeletonPose.joints[i]; GLKVector3 LERPTranslation = GLKVector3Lerp(lPose.t, rPose.t, blendFactor); GLKQuaternion SLERPRotation = GLKQuaternionSlerp(lPose.q, rPose.q, blendFactor); GLKVector3 LERPScaling = GLKVector3Lerp(lPose.s, rPose.s, blendFactor); GLKMatrix4 currentTransform = GLKMatrix4MakeWithQuaternion(SLERPRotation); currentTransform = GLKMatrix4TranslateWithVector3(currentTransform, LERPTranslation); currentTransform = GLKMatrix4ScaleWithVector3(currentTransform, LERPScaling); GLKMatrix4 inverseBindTransform = GLKMatrix4MakeWithQuaternion(aSkeleton.joints[i].inverseBindTransform.q); inverseBindTransform = GLKMatrix4TranslateWithVector3(inverseBindTransform, aSkeleton.joints[i].inverseBindTransform.t); inverseBindTransform = GLKMatrix4ScaleWithVector3(inverseBindTransform, aSkeleton.joints[i].inverseBindTransform.s); if (aSkeleton.joints[i].parentIndex == -1) { bindPosePalette[i] = inverseBindTransform; currentPosePalette[i] = currentTransform; } else { bindPosePalette[i] = GLKMatrix4Multiply(inverseBindTransform, bindPosePalette[aSkeleton.joints[i].parentIndex]); currentPosePalette[i] = GLKMatrix4Multiply(currentPosePalette[aSkeleton.joints[i].parentIndex], currentTransform); } aSkeleton.skinningPalette[i] = GLKMatrix4Multiply(currentPosePalette[i], bindPosePalette[i]); } Finally, this is my vertex shader: #version 100 uniform mat4 modelMatrix; uniform mat3 normalMatrix; uniform mat4 projectionMatrix; uniform mat4 skinningPalette[6]; uniform lowp float skinningEnabled; attribute vec4 position; attribute vec3 normal; attribute vec2 tCoordinates; attribute vec4 jointsWeights; attribute vec4 jointsIndices; varying highp vec2 tCoordinatesVarying; varying highp float lIntensity; void main() { tCoordinatesVarying = tCoordinates; vec4 skinnedVertexPosition = vec4(0.); for (int i = 0; i < 4; i++) { skinnedVertexPosition += jointsWeights[i] * skinningPalette[int(jointsIndices[i])] * position; } vec4 skinnedNormal = vec4(0.); for (int i = 0; i < 4; i++) { skinnedNormal += jointsWeights[i] * skinningPalette[int(jointsIndices[i])] * vec4(normal, 0.); } vec4 finalPosition = mix(position, skinnedVertexPosition, skinningEnabled); vec4 finalNormal = mix(vec4(normal, 0.), skinnedNormal, skinningEnabled); vec3 eyeNormal = normalize(normalMatrix * finalNormal.xyz); vec3 lightPosition = vec3(0., 0., 2.); lIntensity = max(0.0, dot(eyeNormal, normalize(lightPosition))); gl_Position = projectionMatrix * modelMatrix * finalPosition; } The result is that the animation displays wrong in terms of orientation. That is, instead of bobbing up and down it bobs in and out (along what I think is the Z axis according to my transform in the export clip). And the rotation angle is counterclockwise instead of clockwise. If I try with a more than one joint, then it's almost as if the second joint rotates in it's own different coordinate space and does not follow 100% its parent's transform. Which I assume it should from my animation subsystem which I assume in turn follows the theory I explained for the case of more than one joint. Any thoughts?

    Read the article

  • Show WPF tooltip on disabled item only

    - by DT
    Just wondering if it is possible to show a WPF on a disabled item ONLY (and not when the item is enabled). I would like to give the user a tooltip explaining why an item is currently disabled. I have an IValueConverter to invert the boolean IsEnabled property binding. But it doesn't seem to work in this situation. The tooltip is show both when the item is enabled and disabled. So is is possible to bind a tooltip.IsEnabled property exclusively to an item's own !IsEnabled? Pretty straightforward question I guess, but code example here anyway: public class BoolToOppositeBoolConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType != typeof(bool)) throw new InvalidOperationException("The target must be a boolean"); return !(bool)value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType != typeof(bool)) throw new InvalidOperationException("The target must be a boolean"); return !(bool)value; } #endregion } And the binding: <TabItem Header="Tab 2" Name="tabItem2" ToolTip="Not enabled in this situation." ToolTipService.ShowOnDisabled="True" ToolTipService.IsEnabled="{Binding Path=IsEnabled, ElementName=tabItem2, Converter={StaticResource oppositeConverter}}"> <Label Content="Item content goes here" /> </TabItem> Thanks folks.

    Read the article

  • Calling PHP functions within HEREDOC strings

    - by Doug Kavendek
    In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces. In PHP 5, it is possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example: $fn = 'testfunction'; function testfunction() { return 'ok'; } $string = <<< heredoc plain text and now a function: {$fn()} heredoc; As you can see, this is a bit more messy than just: $string = <<< heredoc plain text and now a function: {testfunction()} heredoc; There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like: ?> <!-- directly outputting html and only breaking into php for the function --> plain text and now a function: <?PHP print testfunction(); ?> The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want. So, the essence of my question is: is there a more elegant way to approach this? Edit based on responses: It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.

    Read the article

  • Java: attributes order in .jsp getting inversed

    - by NoozNooz42
    Every single time I've read about the meta tags, the attribute where in this order for the description: <meta name="description" content="..." /> First name, then content. It's also like that in the Google Webmaster documentation. Basically, it's like that everywhere. Now in a .jsp (in XML notation) I've got the following: <meta name="description" content="${metadesc}"/> So it's name first, then content. Yet on the generated webpage, I get this: <meta content="...(200 chars or so here making it a very long line)..." name="description"/> Somehow the attributes have been inversed. Because the content follows the official W3C and Google recommendations, the content is a bit less than 200 characters long, which makes it a major pain to "visually verify" that the name attribute is correctly there (I've got to scroll). Anyway... Why are these attribute not appearing in the order defined in the .jsp? Can I force them to appear in the same order as I wrote them in my .jsp? I realize the resulting tag may be valid... But I can also imagine a lot of very creative ways to have valid tags which users would be very upset about. Does this make any sense to inverse these attributes? EDIT wow, just wow... If I invert the attributes in my .jsp (that is, writing them in the "wrong" order), then they appear as I want them to appear in the generated web page. (Tomcat 6.0.26 btw)

    Read the article

  • html - selection range - getting the range + starting node + ending node + distance

    - by sugar
    From my previous question for selecting specific html text, I have gone through this link to understand range in html string. Actually I am confused here very much. My question is as follows. For selecting a specific text on html page. We need to follow this steps. assumed html <h4 id="entry1196"><a href="http://radar.oreilly.com/archives/2007/03/call_for_a_blog_1.html" class="external">Call for a Blogger's Code of Conduct</a></h4> <p>Tim O'Reilly calls for a Blogger Code of Conduct. His proposals are:</p> <ol> <li>Take responsibility not just for your own words, but for the comments you allow on your blog.</li> <li>Label your tolerance level for abusive comments.</li> <li>Consider eliminating anonymous comments.</li> </ol> java script to make selection by range var range = document.createRange(); // create range var startPar = [the p node]; // starting parameter var endLi = [the second li node]; // ending parameter range.setStart(startPar,13); // distance from starting parameter. range.setEnd(endLi,17); // distance from ending parameter range.select(); // this statement will make selection I want to do this in invert way. I mean, assume that selection is done by user on browser (safari). My question is that How can we get starting node ( as we have 'the p node' here ) & ending node ( as we have 'the second li node' here ) and the range as well (as we have 13,17 here) ? Please help me. Thanks in advance for sharing your great knowledge. Sagar

    Read the article

  • PHP Missing Function In Older Version

    - by Umair Ashraf
    My this PHP function converts a datetime string into more readable way to represent passed date and time. This is working perfect in PHP version 5.3.0 but on the server side it is PHP version 5.2.17 which lacks this function. Is there a way I can fix this efficiently? This is not only a function which needs this "diff" function but there are many more. public function ago($dt1) { $interval = date_create('now')->diff(date_create($dt1)); $suffix = ($interval->invert ? ' ago' : '-'); if ($v = $interval->y >= 1) return $this->pluralize($interval->y, 'year') . $suffix; if ($v = $interval->m >= 1) return $this->pluralize($interval->m, 'month') . $suffix; if ($v = $interval->d >= 1) return $this->pluralize($interval->d, 'day') . $suffix; if ($v = $interval->h >= 1) return $this->pluralize($interval->h, 'hour') . $suffix; if ($v = $interval->i >= 1) return $this->pluralize($interval->i, 'minute') . $suffix; return $this->pluralize($interval->s, 'second') . $suffix; }

    Read the article

  • In Python, how can I find the index of the first item in a list that is NOT some value?

    - by Ryan B. Lynch
    Python's list type has an index(x) method. It takes a single parameter x, and returns the (integer) index of the first item in the list that has the value x. Basically, I need to invert the index(x) method. I need to get the index of the first value in a list that does NOT have the value x. I would probably be able to even just use a function that returns the index of the first item with a value != None. I can think of a 'for' loop implementation with an incrementing counter variable, but I feel like I'm missing something. Is there an existing method, or a one-line Python construction that can handle this? In my program, the situation comes up when I'm handling lists returned from complex regex matches. All but one item in each list have a value of None. If I just needed the matched string, I could use a list comprehension like '[x for x in [my_list] if x is not None]', but I need the index in order to figure out which capture group in my regex actually caused the match.

    Read the article

  • Processing velocity-vectors during collision as neatly as possible

    - by DevEight
    Hello. I'm trying to create a good way to handle all possible collisions between two objects. Typically one will be moving and hitting the other, and should then "bounce" away. What I've done so far (I'm creating a typical game where you have a board and bounce a ball at bricks) is to check if the rectangles intersect and if they do, invert the Y-velocity. This is a really ugly and temporary solution that won't work in the long haul and since this is kind of processing is very common in games I'd really like to find a great way of doing this for future projects aswell. Any links or helpful info is appreciated. Below is what my collision-handling function looks like right now. protected void collision() { #region Boundaries if (bal.position.X + bal.velocity.X >= viewportRect.Width || bal.position.X + bal.velocity.X <= 0) { bal.velocity.X *= -1; } if (bal.position.Y + bal.velocity.Y <= 0) { bal.velocity.Y *= -1; } #endregion bal.rect = new Rectangle((int)bal.position.X+(int)bal.velocity.X-bal.sprite.Width/2, (int)bal.position.Y-bal.sprite.Height/2+(int)bal.velocity.Y, bal.sprite.Width, bal.sprite.Height); player.rect = new Rectangle((int)player.position.X-player.sprite.Width/2, (int)player.position.Y-player.sprite.Height/2, player.sprite.Width, player.sprite.Height); if (bal.rect.Intersects(player.rect)) { bal.position.Y = player.position.Y - player.sprite.Height / 2 - bal.sprite.Height / 2; if (player.position.X != player.prevPos.X) { bal.velocity.X -= (player.prevPos.X - player.position.X) / 2; } bal.velocity.Y *= -1; } foreach (Brick b in brickArray.list) { b.rect.X = Convert.ToInt32(b.position.X-b.sprite.Width/2); b.rect.Y = Convert.ToInt32(b.position.Y-b.sprite.Height/2); if (bal.rect.Intersects(b.rect)) { b.recieveHit(); bal.velocity.Y *= -1; } } brickArray.removeDead(); }

    Read the article

  • svg mouseup event not fired in IE9, unless the debugger is open

    - by Roberto Lupi
    I am using d3 to build a simple chart that the user can edit interactively with the mouse. It works on in all modern common browser (Chrome, Firefox, Safari), except for Internet Explorer 9 where I can start to drag an item but I never get the mouseup event. The strangest bit is that, if I open the debugger, the page works percetly on Internet Explorer 9 as well. My code looks like this: item.append("svg:circle") .attr("class", "handle") .attr("opacity",0.5) .attr("stroke","gray") .attr("cx", bx(0.5)-bx(0)) .attr("r", 10) .style("cursor", "crosshair") .style("pointer-events", "all") .call(d3.behavior.drag() .on("dragstart", function() { dragTarget = d3.select(this); }) .on("drag", function() { this.parentNode.appendChild(this); // put us on the front, not really needed var dragTarget = d3.select(this); dragTarget .attr("cy", function() { return d3.event.dy + parseInt(dragTarget.attr("cy"))}); }) .on("dragend", function(d, i) { newY = parseInt(d3.select(this).attr("cy")); newValue = y.invert(newY); var serieNo = this.__data__.serieNo; console.log([serieNo+1,i+1]); data[serieNo+1][i+1] = newValue; updateBarChart(); onchange(); }) );

    Read the article

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