Daily Archives

Articles indexed Friday November 8 2013

Page 12/17 | < Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Getting a mirrored mesh from my data structure

    - by Steve
    Here's the background: I'm in the beginning stages of an RTS game in Unity. I have a procedurally generated terrain with a perlin-noise height map, as well as a function to generate a river. The problem is that the graphical creation of the map is taking the data structure of the map and rotating it by 180 degrees. I noticed this problem when I was creating my rivers. I would set the River's height to flat, and noticed that the actual tiles that were flat in the graphical representation were flipped and mirrored. Here's 3 screenshots of the map from different angles: http://imgur.com/a/VLHHq As you can see, if you flipped (graphically) the river by 180 degrees on the z axis, it would fit where the terrain is flattened. I have a suspicion it is being caused by a misunderstanding on my part of how vertices work. Alas, here is a snippet of the code that is used: This code here creates a new array of Tile objects, which hold the information for each tile, including its type, coordinate, height, and it's 4 vertices public DTileMap (int size_x, int size_y) { this.size_x = size_x; this.size_y = size_y; //Initialize Map_Data Array of Tile Objects map_data = new Tile[size_x, size_y]; for (int j = 0; j < size_y; j++) { for (int i = 0; i < size_x; i++) { map_data [i, j] = new Tile (); map_data[i,j].coordinate.x = (int)i; map_data[i,j].coordinate.y = (int)j; map_data[i,j].vertices[0] = new Vector3 (i * GTileMap.TileMap.tileSize, map_data[i,j].Height, -j * GTileMap.TileMap.tileSize); map_data[i,j].vertices[1] = new Vector3 ((i+1) * GTileMap.TileMap.tileSize, map_data[i,j].Height, -(j) * GTileMap.TileMap.tileSize); map_data[i,j].vertices[2] = new Vector3 (i * GTileMap.TileMap.tileSize, map_data[i,j].Height, -(j-1) * GTileMap.TileMap.tileSize); map_data[i,j].vertices[3] = new Vector3 ((i+1) * GTileMap.TileMap.tileSize, map_data[i,j].Height, -(j-1) * GTileMap.TileMap.tileSize); } } This code sets the river tiles to height 0 foreach (Tile t in map_data) { if (t.realType == "Water") { t.vertices[0].y = 0f; t.vertices[1].y = 0f; t.vertices[2].y = 0f; t.vertices[3].y = 0f; } } And below is the code to generate the actual graphics from the data: public void BuildMesh () { DTileMap.DTileMap map = new DTileMap.DTileMap (size_x, size_z); int numTiles = size_x * size_z; int numTris = numTiles * 2; int vsize_x = size_x + 1; int vsize_z = size_z + 1; int numVerts = vsize_x * vsize_z; // Generate the mesh data Vector3[] vertices = new Vector3[ numVerts ]; Vector3[] normals = new Vector3[numVerts]; Vector2[] uv = new Vector2[numVerts]; int[] triangles = new int[ numTris * 3 ]; int x, z; for (z=0; z < vsize_z; z++) { for (x=0; x < vsize_x; x++) { normals [z * vsize_x + x] = Vector3.up; uv [z * vsize_x + x] = new Vector2 ((float)x / size_x, 1f - (float)z / size_z); } } for (z=0; z < vsize_z; z+=1) { for (x=0; x < vsize_x; x+=1) { if (x == vsize_x - 1 && z == vsize_z - 1) { vertices [z * vsize_x + x] = DTileMap.DTileMap.map_data [x - 1, z - 1].vertices [3]; } else if (z == vsize_z - 1) { vertices [z * vsize_x + x] = DTileMap.DTileMap.map_data [x, z - 1].vertices [2]; } else if (x == vsize_x - 1) { vertices [z * vsize_x + x] = DTileMap.DTileMap.map_data [x - 1, z].vertices [1]; } else { vertices [z * vsize_x + x] = DTileMap.DTileMap.map_data [x, z].vertices [0]; vertices [z * vsize_x + x+1] = DTileMap.DTileMap.map_data [x, z].vertices [1]; vertices [(z+1) * vsize_x + x] = DTileMap.DTileMap.map_data [x, z].vertices [2]; vertices [(z+1) * vsize_x + x+1] = DTileMap.DTileMap.map_data [x, z].vertices [3]; } } } } for (z=0; z < size_z; z++) { for (x=0; x < size_x; x++) { int squareIndex = z * size_x + x; int triOffset = squareIndex * 6; triangles [triOffset + 0] = z * vsize_x + x + 0; triangles [triOffset + 2] = z * vsize_x + x + vsize_x + 0; triangles [triOffset + 1] = z * vsize_x + x + vsize_x + 1; triangles [triOffset + 3] = z * vsize_x + x + 0; triangles [triOffset + 5] = z * vsize_x + x + vsize_x + 1; triangles [triOffset + 4] = z * vsize_x + x + 1; } } // Create a new Mesh and populate with the data Mesh mesh = new Mesh (); mesh.vertices = vertices; mesh.triangles = triangles; mesh.normals = normals; mesh.uv = uv; // Assign our mesh to our filter/renderer/collider MeshFilter mesh_filter = GetComponent<MeshFilter> (); MeshCollider mesh_collider = GetComponent<MeshCollider> (); mesh_filter.mesh = mesh; mesh_collider.sharedMesh = mesh; calculateMeshTangents (mesh); BuildTexture (map); } If this looks familiar to you, its because i got most of it from Quill18. I've been slowly adapting it for my uses. And please include any suggestions you have for my code. I'm still in the very early prototyping stage.

    Read the article

  • Better way to load level content in XNA?

    - by user2002495
    Currently I loaded all my assets in XNA in the main Game class. What I want to achieve later is that I only load specific assets for specific levels (the game will consist of many levels). Here is how I load my main assets into the main class: protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); plane = new Player(Content.Load<Texture2D>(@"Player/playerSprite"), 6, 8); plane.animation = "down"; plane.pos = new Vector2(400, 500); plane.fps = 15; Global.currentPos = plane.pos; lvl1 = new Level1(Content.Load<Texture2D>(@"Levels/bgLvl1"), Content.Load<Texture2D>(@"Levels/bgLvl1-other"), new Vector2(0, 0), new Vector2(0, -600)); CommonBullet.LoadContent(Content); CommonEnemyBullet.LoadContent(Content); } protected override void UnloadContent() { } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); plane.Update(gameTime); lvl1.Update(gameTime); foreach (CommonEnemy ce in cel) { if (ce.CollidesWith(plane)) { ce.hasSpawn = false; } foreach (CommonBullet b in plane.commonBulletList) { if (b.CollidesWith(ce)) { ce.hasSpawn = false; } } ce.Update(gameTime); } LoadCommonEnemy(); base.Update(gameTime); } private void LoadCommonEnemy() { int randY = rand.Next(-600, -10); int randX = rand.Next(0, 750); if (cel.Count < 3) { cel.Add(new CommonEnemy(Content.Load<Texture2D>(@"Enemy/Common/commonEnemySprite"), 7, 2, "left", randX, randY)); } for (int i = 0; i < cel.Count; i++) { if (!cel[i].hasSpawn) { cel.RemoveAt(i); i--; } } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(); lvl1.Draw(spriteBatch); plane.Draw(spriteBatch); foreach (CommonEnemy ce in cel) { ce.Draw(spriteBatch); } spriteBatch.End(); base.Draw(gameTime); } I wish to load my players, enemies, all in Level1 class. However, when I move my player & enemy code into the Level1 class, the gameTime returns null. Here is my Level1 class: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input; using SpaceShooter_Beta.Animation.PlayerCollection; using SpaceShooter_Beta.Animation.EnemyCollection.Common; namespace SpaceShooter_Beta.Levels { public class Level1 { public Texture2D bgTexture1, bgTexture2; public Vector2 bgPos1, bgPos2; public float speed = 5f; Player plane; public Level1(Texture2D texture1, Texture2D texture2, Vector2 pos1, Vector2 pos2) { this.bgTexture1 = texture1; this.bgTexture2 = texture2; this.bgPos1 = pos1; this.bgPos2 = pos2; } public void LoadContent(ContentManager cm) { plane = new Player(cm.Load<Texture2D>(@"Player/playerSprite"), 6, 8); plane.animation = "down"; plane.pos = new Vector2(400, 500); plane.fps = 15; Global.currentPos = plane.pos; } public void Draw(SpriteBatch sb) { sb.Draw(bgTexture1, bgPos1, Color.White); sb.Draw(bgTexture2, bgPos2, Color.White); plane.Draw(sb); } public void Update(GameTime gt) { bgPos1.Y += speed; bgPos2.Y += speed; if (bgPos1.Y >= 600) { bgPos1.Y = -600; } if (bgPos2.Y >= 600) { bgPos2.Y = -600; } plane.Update(gt); } } } Of course when I did this, I delete all my player's code in the main Game class. All of that works fine (no errors) except that the game cannot start. The debugger says that plane.Update(gt); in Level 1 class has null GameTime, same thing with the Draw method in the Level class. Please help, I appreciate for the time. [EDIT] I know that using switch in the main class can be a solution. But I prefer a cleaner solution than that, since using switch still means I need to load all the assets through the main class, the code will be A LOT later on for each levels

    Read the article

  • What needs to be done to port a Windows Flash game to Android?

    - by Russell Yan
    My team has developed a game using Flash (with Lua embeded) that targets Windows. And we want to port that game to Android (also iOS in the future). It's acceptable to rewrite the Flash part of client. And some other team in our company recommended Unity3D to replace the Flash part. Since we have no experience in Android/iOS development, we would need to learn some new tool/language anyway. So we would like that learning still be useful after the porting and when we starting a new game. Any thoughts? Edits: I think it is worth noticing the background of the game : the project is started by a tester and developer, both without knowing much about flex and actionscript. They built the game while learning, so most of the code is hard to maintain. I and other two developers joined the project after a year or so when one has leave (and the other be our manager). The other two developers are just graduates with little experience and little knowledge of flex. I am good at the server part and the c# language. Based on the fact that the code is hard to maintain (and we do need to change a lot of code to make the game easier to playe in a mobile device), and I am good at c# (and learning). I still tend to do the porting with Unity, which could get better performance and possibly save time.

    Read the article

  • Producing a smooth mesh from density cloud and marching cubes

    - by Wardy
    Based on my results from this question I decided to build myself a 3D noise map containing float values in place of my existing boolean point values. The effect I'm trying to produce is something like this, rather than typical rolling hills; which should explain the "missing cubes" in the image below. If I render my density map in normal "minecraft mode" (1 block per point in the density map) varying the size of the cube based on the value in my density map (floats in the range 0 to 1) I get something like this: I'm now happy that I can produce a density map for the marching cubes algorithm (which will need a little tweaking) but for some reason when I run it through my implementation it's not producing what I expect. My problem is that I'm getting something like the first image in this answer to my previous question, when I want to achieve the effect in the second image. Upon further investigation I can't see how marching cubes does the "move vertex along the edge" type logic (i.e. the difference between the two images on my previous link). I see that it does do some interpolation, but I'm not convinced I have the correct understanding of what I think it should do, because the code in question appears to give the same result regardless of whether I use boolean or float values. I took the code from here which is a C# implementation of marching cubes, but instead of using the MarchingCubesPrimitive I modified it to accept an object of type IDrawable, containing lists for the various collections (vertices, normals, UVs, indices), the logic was otherwise untouched. My understanding is that given a very low isovalue the accuracy level of the surface being rendered should increase, so in short "less 45 degree slows more rolling hills" type mesh output. However this isn't what I'm seeing. Have I missed something or is the implementation flawed and need to be fixed? EDIT: A little more detail on what I am seeing when I "marching cube" the data. Ok so firstly, ignore the fact that the meshes created by the chunks don't "connect" (i'll probably raise another question about this later). Then look at the shaping of the island, it's too ... square, from the voxels rendered as boxes you get the impression there's a clean soft gradual hill and yet from the image there are sharp falling edges even in the most central areas where the gradient in the first image looks the most smooth. The data is "regenerated" each time I run this so no 2 islands come out the same, and it's purely random so not based on noise, but still, how can it look so smooth in 1 image and so not smooth in the other?

    Read the article

  • using ajax url to call function

    - by Steven Vanerp
    Hopefully I can ask this correctly cuz I know what I want it to do but can't seem to find any answers from searching. I have a func.php page where I have all my functions and I want ajax to use one function from that page. func.php function toptable() { echo"something happens in here"; } index.php <?php include 'func.php'; ?> <script type="text/javascript"> function check_username() { uname=document.getElementById("username").value; var params = "user_id="+uname; var url = "topoftable()"; $.ajax({ type: 'POST', url: url, dataType: 'html', data: params, beforeSend: function() { document.getElementById("right").innerHTML= 'checking' ; }, complete: function() { }, success: function(html) { document.getElementById("right").innerHTML= html ; } }); } </script> Make sense?

    Read the article

  • Counting in R data.table

    - by Simon Z.
    I have the following data.table set.seed(1) DT <- data.table(VAL = sample(c(1, 2, 3), 10, replace = TRUE)) VAL 1: 1 2: 2 3: 2 4: 3 5: 1 6: 3 7: 3 8: 2 9: 2 10: 1 Now I want to to perform two tasks: Count the occurrences of numbers in VAL. Count within all rows with the same value VAL (first, second, third occurrence) At the end I want the result VAL COUNT IDX 1: 1 3 1 2: 2 4 1 3: 2 4 2 4: 3 3 1 5: 1 3 2 6: 3 3 2 7: 3 3 3 8: 2 4 3 9: 2 4 4 10: 1 3 3 where COUNT defines task 1. and IDX task 2. I tried to work with which and length using .I: dt[, list(COUNT = length(VAL == VAL[.I]), IDX = which(which(VAL == VAL[.I]) == .I))] but this does not work as .I refers to a vector with the index, so I guess one must use .I[]. Though inside .I[] I again face the problem, that I do not have the row index and I do know (from reading data.table FAQ and following the posts here) that looping through rows should be avoided if possible. So, what's the data.table way?

    Read the article

  • Cannot implicity convert type void to System.Threading.Tasks.Task<bool>

    - by sagesky36
    I have a WCF Service that contains the following method. All the methods in the service are asynchrounous and compile just fine. public async Task<Boolean> ValidateRegistrationAsync(String strUserName) { try { using (YeagerTechEntities DbContext = new YeagerTechEntities()) { DbContext.Configuration.ProxyCreationEnabled = false; DbContext.Database.Connection.Open(); var reg = await DbContext.aspnet_Users.FirstOrDefaultAsync(f => f.UserName == strUserName); if (reg != null) return true; else return false; } } catch (Exception) { throw; } } My client application was set to access the WCF service with the check box for the "Allow generation of asynchronous operations" and it generated the proxy just fine. I am receiving the above subject error when trying to call this WCF service method from my client with the following code. Mind you, I know what the error message means, but this is my first time trying to call an asynchronous task in a WCF service from a client. Task<Boolean> blnMbrShip = db.ValidateRegistrationAsync(FormsAuthentication.Decrypt(cn.Value).Name); What do I need to do to properly call the method so the design time compile error disappears? Thanks so much in advance...

    Read the article

  • Upgrading From EF 4x to 6 breaks everything

    - by dan h
    Attempted to upgrade my project from EF4 to EF6, I get build errors It appears that if i swap out the namespaces manually to include the entity.core it works, but if i change the .edmx file at all, the code reverts back to the old references and i have to manually edit the code generation files to include the update namespace references. I have attempted to "add code generation item" that does not resolve the issue at all. When i open the .edmx file in the IDE it shows me everything correctly.

    Read the article

  • Haskell: Left-biased/short-circuiting function

    - by user2967411
    Two classes ago, our professor presented to us a Parser module. Here is the code: module Parser (Parser,parser,runParser,satisfy,char,string,many,many1,(+++)) where import Data.Char import Control.Monad import Control.Monad.State type Parser = StateT String [] runParser :: Parser a -> String -> [(a,String)] runParser = runStateT parser :: (String -> [(a,String)]) -> Parser a parser = StateT satisfy :: (Char -> Bool) -> Parser Char satisfy f = parser $ \s -> case s of [] -> [] a:as -> [(a,as) | f a] char :: Char -> Parser Char char = satisfy . (==) alpha,digit :: Parser Char alpha = satisfy isAlpha digit = satisfy isDigit string :: String -> Parser String string = mapM char infixr 5 +++ (+++) :: Parser a -> Parser a -> Parser a (+++) = mplus many, many1 :: Parser a -> Parser [a] many p = return [] +++ many1 p many1 p = liftM2 (:) p (many p) Today he gave us an assignment to introduce "a left-biased, or short-circuiting version of (+++)", called (<++). His hint was for us to consider the original implementation of (+++). When he first introduced +++ to us, this was the code he wrote, which I am going to call the original implementation: infixr 5 +++ (+++) :: Parser a -> Parser a -> Parser a p +++ q = Parser $ \s -> runParser p s ++ runParser q s I have been having tons of trouble since we were introduced to parsing and so it continues. I have tried/am considering two approaches. 1) Use the "original" implementation, as in p +++ q = Parser $ \s - runParser p s ++ runParser q s 2) Use the final implementation, as in (+++) = mplus Here are my questions: 1) The module will not compile if I use the original implementation. The error: Not in scope: data constructor 'Parser'. It compiles fine using (+++) = mplus. What is wrong with using the original implementation that is avoided by using the final implementation? 2) How do I check if the first Parser returns anything? Is something like (not (isNothing (Parser $ \s - runParser p s) on the right track? It seems like it should be easy but I have no idea. 3) Once I figure out how to check if the first Parser returns anything, if I am to base my code on the final implementation, would it be as easy as this?: -- if p returns something then p <++ q = mplus (Parser $ \s -> runParser p s) mzero -- else (<++) = mplus Best, Jeff

    Read the article

  • The builds tools for WindowsKernelModeDriver8.1 (Platform Toolset = 'WindowsKernelModeDriver8.1') cannot be found

    - by Rajeshwar
    I am attempting to build this example. However I am getting the error error MSB8020: The builds tools for WindowsApplicationForDrivers8.1 (Platform Toolset = 'WindowsApplicationForDrivers8.1') cannot be found. To build using the WindowsApplicationForDrivers8.1 build tools, either click the Project menu or right-click the solution, and then select "Update VC++ Projects...". Install WindowsApplicationForDrivers8.1 to build using the WindowsApplicationForDrivers8.1 build tools. I have already installed WDK 8.1 .exe andwhen I right click on the solution I cant find any thing that states "Update VC++ Projects" Any suggestions on how I may resolve this issue and build it. ? I am running Windows 7 and VS2012 Pro.

    Read the article

  • can I add properties to a typo3 extbase domain model object?

    - by The Newbie Qs
    I want to store a username in a coupon object, each coupon object already has the uid of the user who created it. I can loop over the coupon objects and read the associated usernames from fe_users but how then will I save those usernames into the coupons so when they are passed to the template the usernames can be read like so coupon.username, or in some other easy way so each username will appear on the page with the right coupon as they are all printed out in a table? If I was doing basic php instead of typo3 i would just define a query but what is the typo3 v4.5 way? My code so far - which dies on the line where I try to assign the new property --creatorname -- to the $coup object. public function listAction() { $coupons = $this->couponRepository->findAll(); // @var Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository */ $userRepository = $this->objectManager->get("Tx_Extbase_Domain_Repository_FrontendUserRepository"); foreach ($coupons as $coup) { echo '<br />test '.$coup->getCreator(); echo '<br />count = '.$userRepository->countAll().'<br />'; $newObject = $userRepository->findByUid( intval($coup->getCreator())); //var_dump($newObject); var_dump($coup); echo '<br />getUsername '.$newObject->getUsername() ; $coup['creatorname'] = $newObject->getUsername(); echo '<br />creatorname '.$coup['creatorname'] ; } $this->view->assign('coupons', $coupons); }

    Read the article

  • Python sort 2-D list by time string

    - by Mark Kennedy
    How do I sort a multi dimensional list like this based on a time string? The sublists can be of different sizes (i.e. 4 and 5, here) I want to sort by comparing the first time string in each sublist (sublist[-4]) x = (['1513', '08:19PM', '10:21PM', 1, 4], ['1290', '09:45PM', '11:43PM', 1, 4], ['0690', '07:25AM', '09:19AM', 1, 4], ['0201', '08:50AM', '10:50AM', 1, 4], ['1166', '04:35PM', '06:36PM', 1, 4], ['0845', '05:40PM', '07:44PM', 1, 4], ['1267', '07:05PM', '09:07PM', 1, 4], ['1513', '08:19PM', '10:21PM', 1, 4], ['1290', '09:45PM', '11:43PM', 1, 4], ['8772', '0159', '12:33PM', '02:43PM', 1, 5], ['0888', '0570', '09:42PM', '12:20AM', 1, 5], ['2086', '2231', '04:10PM', '06:20PM', 1, 5]) The sorted result would be sortedX = (['0690', '07:25AM', '09:19AM', 1, 4], ['0201', '08:50AM', '10:50AM', 1, 4], ['1166', '04:35PM', '06:36PM', 1, 4], ['0845', '05:40PM', '07:44PM', 1, 4], ['1267', '07:05PM', '09:07PM', 1, 4], ['1513', '08:19PM', '10:21PM', 1, 4], ['1513', '08:19PM', '10:21PM', 1, 4], ['1290', '09:45PM', '11:43PM', 1, 4], ['1290', '09:45PM', '11:43PM', 1, 4], ['8772', '0159', '12:33PM', '02:43PM', 1, 5], ['2086', '2231', '04:10PM', '06:20PM', 1, 5], ['0888', '0570', '09:42PM', '12:20AM', 1, 5]) I tried the following: sortedX = sorted(x, key=lambda k : k[-4]) #k[-4] is the first time string and it works but it doesn't respect the sublist size ordering

    Read the article

  • Asks for Account Type twice

    - by André Fecteau
    Been working on this program for a while now. (had some problems and asked a few times here.) Ran into another one though! The program asks for my account type twice. Can not figure out why or how to fix it. Any help is appreciated, thanks! /* project3.cpp Andre Fecteau CSC135-101 October 29, 2013 This program prints a bank's service fees per month depending on account type */ #include <iostream> using namespace std; /* Basic Function for Copy Paste <function type> <function name> (){ // Declarations // Initalizations // Input // Process // Output // Prolouge } */ void displayInstructions (){ // Declarations // Initalizations // Input // Process // Output cout <<"| -------------------------------------------------------------- |" << endl; cout <<"| ---------- Welcome to the bank fee calculator ---------------- |" << endl; cout <<"| -------------------------------------------------------------- |" << endl; cout <<"| This Program wil ask you to eneter your account number. |" << endl; cout <<"| Then it will ask for your account type Personal or Commercial. |" << endl; cout <<"| Then ask for the amount of checks you have written. |" << endl; cout <<"| Lastly it will output how much your fees are for this month. |" << endl; cout <<"| -------------------------------------------------------------- |" << endl; cout << endl; // Prolouge } int readAccNumb(){ // delarations int accNumber; // intitalizations accNumber = 0.0; // input cout << "Please Enter Account Number:"; cin >> accNumber; // Procesas // output // prolouge return accNumber; } int checksWritten (){ // Declarations int written; // Initalizations written = 0.0; // Input cout <<"Please input the amount of checks you have written this month:"; cin >> written; // Output // Prolouge return written; } char accType (){ // Declarations char answer; int numberBySwitch; // Initalizations numberBySwitch = 1; // Input while (numberBySwitch == 1){ cout << "Please Enter the acount type (C for Comerical and P for Personal):"; cin >> answer; // Process switch (answer){ case 'p': answer = 'P'; numberBySwitch += 2;break; case 'P': numberBySwitch += 2;break; case 'c': answer = 'C'; numberBySwitch += 3;break; case 'C': numberBySwitch += 3;break; default: if(numberBySwitch == 1) { cout << "Error! Please enter a correct type!" <<endl; } } } // Output // Prolouge return answer; } int commericalCalc(int checksWritten){ // Declarations int written; int checkPrice; // Initalizations checkPrice = 0.0; // Input // Process if(written < 20){ checkPrice = 0.10; } // Output // Prolouge return checkPrice; } int personalCalc(int checksWritten){ } double pricePerCheck(char accType, int checksWritten){ // Declarations double price; char answer; // Initalizations price = 0.0; // Input // Process if(accType == 'P'){ } if(accType == 'C'){ if(checksWritten < 20){ price = 0.10; } } // Output // Prolouge return price; } int main(){ // Declarations int accountNumb; char theirAccType; int writtenChecks; double split; // Initalizations accountNumb = 0.0; writtenChecks = 0.0; split = 0.0; theirAccType = ' '; // Input displayInstructions(); theirAccType = accType(); accountNumb = readAccNumb(); split = pricePerCheck(accType(), checksWritten()); // Output cout << endl; cout << "Account Type: " << theirAccType << endl; cout << "Check Price: " << split << endl; // Prolouge return 0; }

    Read the article

  • Why is my variable uninitialized in a separate if test?

    - by user2932733
    For the first run, I need to use dates that are six months prior to the last MySQL date $row_recent[0]. For all of the runs after 1, I am using a previous variable to store the previous date and then decrease the date by 6 months. I have confirmed that the first if test produces the expected result. (MySQL date - 6 Months). However, the second if test outputs $startdate6m as the PHP default due to $previous_6m being uninitialized. Any idea why it won't recognize $previous_6m = $initial6m? <?php while ($run_number < 15) { $run_number++; if($run_number == 1){ if ($month <= 06){ $year6m = date("Y", strtotime($row_recent[0]))-1; $month6m = str_pad((12-(6-date("m", strtotime($row_recent[0])))), 2, "0", STR_PAD_LEFT); $startdate6m = "'".$year6m."-".$month6m."-01'"; $end_date = $startdate6m; $initial6m = $startdate6m; } else{ $year6m = date("Y", strtotime($row_recent[0])); $month6m = str_pad(date("m", strtotime($row_recent[0]))-6, 2, "0", STR_PAD_LEFT); $startdate6m = "'".$year6m."-".$month6m."-01'"; $end_date = $startdate6m; $initial6m = $startdate6m; } } $previous_6m = $initial6m; if($run_number > 1){ # 6 Month # Decrement date by 6 months $month6m = date("m", strtotime($previous_6m)); if ($month6m <= 06){ $year6m = date("Y", strtotime($previous_6m))-1; $month6m = str_pad((12-(6-date("m", strtotime($previous_6m)))), 2, "0", STR_PAD_LEFT); $startdate6m = "'".$year6m."-".$month6m."-01'"; $end_date = $startdate6m; } else{ $year6m = date("Y", strtotime($previous_6m)); $month6m = str_pad(date("m", strtotime($previous_6m))-6, 2, "0", STR_PAD_LEFT); $startdate6m = "'".$year6m."-".$month6m."-01'"; $end_date = $startdate6m; } } $previous_6m = $startdate6m; } ?>

    Read the article

  • Java combine parents of two large inheritance chains

    - by Soylent Green
    I have two parent classes in a huge project, let's say ClassA and ClassB. Each class has many subclasses, which in turn have many subclasses, which in turn have many subclasses, etc. My task is to "marry" these two "families" so that both inherit from a SINGLE parent. I need to essentially make ClassA and ClassB one class (parent) to both of their combined subclasses (children). ClassA and ClassB both currently implement Serializable. I am currently trying to make both inheritance chains inherit from ClassA, and then copy all functions and data members from ClassB into ClassA. This is tedious, and I think a terrible solution. What would be the CORRECT way to solve this problem?

    Read the article

  • How do I get public feed from facebook without user authentication on a native/Desktop app?

    - by KronoS
    I'm looking to get publicly available facebook feeds (i.e. Google's facebook page/posts). However instead of forcing the user to sign into their own facebook app, I want to be able to access these posts. I've looked into using "App Access Tokens" however since my application is a native/Desktop app (iOS, Android, WP8/Win 8) I'm not able to do this. Is there a way to get publicly accessible feeds from facebook without user authentication? I'm using the Facebook C# SDK to access facebook. Currently I'm doing the following: dynamic tokenInfo = fb.Get( String.Format( "/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", FbController.AppId, FbController.AppSecret)); var appAccessToken = (string) tokenInfo.access_token; fb = new FacebookClient(); dynamic response = fb.Get( String.Format( "/google/posts?access_token={0}", appAccessToken)); Problem is that this only works if my application is set to "web" instead of "native/Desktop". I get the following error when running this code and classified app as native/Desktop. (OAuthException - #15) (#15) Requires session when calling from a desktop app

    Read the article

  • transition of x-axis results in overflow

    - by peter
    First of all, no: this question is not about the (yet) ugly transition of the lines (I might open another one for that, though..). I'm displaying data in line charts and the user can select the time horizon. The x-axis then correspondingly transitions so as to fit to the changed time horizon. In attached image, e.g., the time horizon was 1 week and then I switched to 4 weeks. The number of ticks on the x-axis increases from 7 to 28, correspondingly. Question: How can I prevent the x-axis animation to display outside the svg container? As you can see, the additional dates fly in from the left and they are being animated far far outside the container. Any ideas? Right now, the transition works probably in the most simple way it could: // format for x-axis var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .tickFormat(d3.time.format("%d.%m")) .ticks(d3.time.days, 1) .tickSubdivide(0); // Update x-axis svg.select(".x") .transition() .duration(500) .call(xAxis);

    Read the article

  • Qt Serial Port Errors - Data not getting read

    - by user2970546
    I'm trying to read a serial port with the Qt SerialPort library. I can read the data using HyperTerminal. In Qt I used the following code to try and do the same thing. Qt says the the port has been opened correctly, but for some reason, the bytesAvailable from the serial port is always 0. serial.setPortName("COM20"); if (serial.open(QIODevice::ReadOnly)) qDebug() << "Opened port " << endl; else qDebug() << "Unable to open port" << endl; serial.setDataBits(QSerialPort::Data8); serial.setParity(QSerialPort::EvenParity); serial.setBaudRate(QSerialPort::Baud115200); qDebug() << "Is open?? " << serial.isOpen(); // Wait unit serial port data is ready while (!serial.bytesAvailable()) { //qDebug() << serial.bytesAvailable()<<endl; continue; } QByteArray data = serial.read(100); qDebug() << "This is the data -" << data << endl; serial.close(); In comparison, MATLAB code with the same structure as the above code, successfully manages to read the serial port data %Serial Port Grapher - Shurjo Banerjee s = serial('COM20'); s.BaudRate = 460800; s.Parity = 'even'; try input('Ready to begin?'); catch end fopen(s); fh = figure(); hold on; t = 1; while (s.BytesAvailable <= 0) continue end a = fread(s, 1) old_t = 1; old_a = a; while true if (s.BytesAvailable > 0) a = fread(s, 1) figure(fh) t = t + 1; plot([old_t t], [old_a a]); old_t = t; old_a = a; end end fclose(s);

    Read the article

  • Python - creating a list with 2 characteristics bug

    - by user2733911
    The goal is to create a list of 99 elements. All elements must be 1s or 0s. The first element must be a 1. There must be 7 1s in total. import random import math import time # constants determined through testing generation_constant = 0.96 def generate_candidate(): coin_vector = [] coin_vector.append(1) for i in range(0, 99): random_value = random.random() if (random_value > generation_constant): coin_vector.append(1) else: coin_vector.append(0) return coin_vector def validate_candidate(vector): vector_sum = sum(vector) sum_test = False if (vector_sum == 7): sum_test = True first_slot = vector[0] first_test = False if (first_slot == 1): first_test = True return (sum_test and first_test) vector1 = generate_candidate() while (validate_candidate(vector1) == False): vector1 = generate_candidate() print vector1, sum(vector1), validate_candidate(vector1) Most of the time, the output is correct, saying something like [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] 7 True but sometimes, the output is: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 False What exactly am I doing wrong?

    Read the article

  • How to compute power spectrum from 2D FFT

    - by user1452954
    I've encounter a problem when doing my lab assignment, not sure how to implement this: Use fft2 on a gray image and to do Fourier transform and then compute the power spectrum. This is my code so far: >> Pc = imread('pckint.jpg'); >> whos Pc; Name Size Bytes Class Attributes Pc 256x256 65536 uint8 >> imshow(Pc); >> result = fft2(Pc); My question is from the result. How to computer power spectrum?

    Read the article

  • $.post is not working

    - by BEBO
    i am trying to post data to Mysql using jquery $.post and php page. my code is not running and nothing is added to the mysql table. I am not sure if the path i am creating is wrong but any help would be appreciated. Jquery location: f_js/tasks/TaskTest.js <script type="text/javascript"> $(document).ready(function(){ $("#AddTask").click(function(){ var acct = $('#acct').val(); var quicktask = $('#quicktask').val(); var user = $('#user').val(); $.post('addTask.php',{acct:acct,quicktask:quicktask,user:user}, function(data){ $('#result').fadeIn('slow').html(data); }); }); }); </script> addTask.php (runs the jqeury code) <?php include 'dbconnect.php'; include 'sessions.php'; $acct = $_POST['acct']; $task = $_POST['quicktask']; $taskstatus = 'Active'; //get task Creator $user = $_POST['user']; //query task creator from users table $allusers = mysql_query("SELECT * FROM users WHERE username = '$user'"); while ($rows = mysql_fetch_array($allusers)) { //get first and last name for task creator $taskOwner = $rows['user_firstname']; $taskOwnerLast = $rows['user_lastname']; $taskOwnerFull = $taskOwner." ".$taskOwnerLast; mysql_query("INSERT INTO tasks (taskresource, tasktitle, taskdetail, taskstatus, taskowner, taskOwnerFullName) VALUES ('$acct', '$task', '$task', '$taskstatus', '$user', '$taskOwnerFull' )"); echo "inserted"; } ?> Accountview.php finally the front page <html> <div class="input-cont "> <input type="text" class="form-control col-lg-12" placeholder="Add a quick Task..." name ="quicktask" id="quicktask"> </div> <div class="form-group"> <div class="pull-right chat-features"> <a href="javascript:;"> <i class="icon-camera"></i> </a> <a href="javascript:;"> <i class="icon-link"></i> </a> <input type="button" class="btn btn-danger" name="AddTask" id="AddTask" value="Add" /> <input type="hidden" name="acct" id="acct" value="<?php echo $_REQUEST['acctname']?>"/> <input type="hidden" name="user" id="user" value="<?php $username = $_SESSION['username']; echo $username?>"/> <div id="result">result</div> </div> </div> <!-- js placed at the end of the document so the pages load faster --> <script src="js/jquery.js"></script> <script src="f_js/tasks/TaskTest.js"></script> <!--common script for all pages--> <script src="js/common-scripts.js"></script> <script type="text/javascript" src="assets/gritter/js/jquery.gritter.js"></script> <script src="js/gritter.js" type="text/javascript"></script> <script> </html> Firebug reponse: Response Headers Connection Keep-Alive Content-Length 0 Content-Type text/html Date Fri, 08 Nov 2013 21:48:50 GMT Keep-Alive timeout=5, max=100 Server Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16 X-Powered-By PHP/5.4.16 refresh 5; URL=index.php Request Headers Accept */* Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Content-Length 13 Content-Type application/x-www-form-urlencoded; charset=UTF-8 Cookie PHPSESSID=6gufl3guiiddreg8cdlc0htnc6 Host localhost Referer http://localhost/betahtml/AccountView.php?acctname=client%201 User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0 X-Requested-With XMLHttpRequest

    Read the article

  • Powershell - remote folder availability while counting files

    - by ziklop
    I´m trying to make a Powershell script that reports if there´s a file older than x minutes on remote folder. I make this: $strfolder = 'folder1 ..................' $pocet = (Get-ChildItem \\server1\edi1\folder1\*.* ) | where-object {($_.LastWriteTime -lt (Get-Date).AddDays(-0).AddHours(-0).AddMinutes(-20))} | Measure-Object if($pocet.count -eq 0){Write-Host $strfolder "OK" -foreground Green} else {Write-Host $strfolder "ERROR" -foreground Red} But there´s one huge problem. The folder is often unavailable for me bacause of the high load and I found out when there is no connection it doesn´t report an error but continues with zero in $pocet.count. It means it reports everything is ok when the folder is unavailable. I was thinking about using if(Test-Path..) but what about it became unavailable just after passing Test-Path? Does anyone has a solution please? Thank you in advance

    Read the article

  • Ghost activity in android

    - by Ari
    My application works as follow: On start I have some AppStartActivity which does something, finishes itself and starts MainActivity if user is logged in or LoginActivity otherwise. LoginActivity finishes itself and starts MainActivity when user log in successfully. On MainActivity I have SomeActivity from which user can logout. Activity stack for this situation is MainActivity > SomeActivity. It is correct, back button works well. When user click LogOut button there is a problem. I need to show LoginActivity but I don't want to have MainActivity and SomeActivity on activity stack anymore. I could resolve this problem if I wouldn't finish AppStartActivity. I could go back then with flag FLAG_ACTIVITY_CLEAR_TOP and it would work well. But here is a problem with back button. I don't want user to come back to this activity with back button. I want it to exit app instead. UPDATED: Flags FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK would be best, but I need it working in API level 9.

    Read the article

  • Velocity engine fails to load template from a remote shared folder

    - by performanceuser
    I have following code File temlateFile = new File( "D:/config/emails/MailBody.vm" ); temlateFile.exists(); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); velocityEngine.setProperty("file.resource.loader.class", FileResourceLoader.class.getName()); velocityEngine.setProperty("file.resource.loader.path", temlateFile.getParentFile().getAbsolutePath()); velocityEngine.init(); template = velocityEngine.getTemplate( temlateFile.getName() ); This works because it is loading a file from local file system. Once I change the first like to: File temlateFile = new File( "//remote/config/emails/MailBody.vm" ); It doesn't work. org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'MailBody.vm' at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474) at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352) at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533) at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514) at org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:373) at com.actuate.iserver.mail.VelocityContent.<init>(VelocityContent.java:33) at com.actuate.iserver.mail.VolumeCreationMail.<init>(VolumeCreationMail.java:40) at com.actuate.iserver.mail.VolumeCreationMail.main(VolumeCreationMail.java:67) In both cases temlateFile.exists() always return true. Any ideas?

    Read the article

  • Messages not forwarded to error queue when exception is thrown in handler (it works on my machine)

    - by darthjit
    e are using NServicebus 4.0.5 with sql server(sql server 2012) as transport. When the handler throws an exception, NSB does not retry or move the message to the error queue. Successful messages make it to the audit queue but the failed/errored ones don't! . Interestingly, all this works on our local machines(windows 7 ,sql server localdb) but not on windows server 2012 (sql server 2012). Here is the config info on the subscriber: <add name="NServiceBus/Transport" connectionString="Data Source=xxx;Initial Catalog=NServiceBus;Integrated Security=SSPI;Enlist=false;" /> <add name="NServiceBus/Persistence" connectionString="Data Source=xxx;Initial Catalog=NServiceBus;Integrated Security=SSPI;Enlist=false;" /> <MessageForwardingInCaseOfFaultConfig ErrorQueue="error" /> <UnicastBusConfig ForwardReceivedMessagesTo="audit"> <MessageEndpointMappings> <add Assembly="Services.Section.Messages" Endpoint= "Services.ACL.Worker" /> </MessageEndpointMappings> </UnicastBusConfig> And in code it is configured as follows: public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization { public void Init() { IContainer container = ContainerInstanceProvider. GetContainerInstance(); Configure .Transactions.Enable(); Configure.With() .AutofacBuilder(container) .UseTransport<SqlServer>() .Log4Net() //.Serialization.Json() .UseNHibernateSubscriptionPersister() .UseNHibernateTimeoutPersister() .MessageForwardingInCaseOfFault() .RijndaelEncryptionService() .DefiningCommandsAs(type => type.Namespace != null &&type .Namespace.EndsWith("Commands")) .DefiningEventsAs(type => type.Namespace != null &&type .Namespace.EndsWith("Events")) .UnicastBus(); } } Any ideas on how to fix this? here is the log info (there is a lot there, search for error to see the relevant parts) https://gist.github.com/ranji/7378249

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >