Search Results

Search found 1725 results on 69 pages for 'equation solving'.

Page 53/69 | < Previous Page | 49 50 51 52 53 54 55 56 57 58 59 60  | Next Page >

  • Dependency Injection Introduction

    - by MarkPearl
    I recently was going over a great book called “Dependency Injection in .Net” by Mark Seeman. So far I have really enjoyed the book and would recommend anyone looking to get into DI to give it a read. Today I thought I would blog about the first example Mark gives in his book to illustrate some of the benefits that DI provides. The ones he lists are Late binding Extensibility Parallel Development Maintainability Testability To illustrate some of these benefits he gives a HelloWorld example using DI that illustrates some of the basic principles. It goes something like this… class Program { static void Main(string[] args) { var writer = new ConsoleMessageWriter(); var salutation = new Salutation(writer); salutation.Exclaim(); Console.ReadLine(); } } public interface IMessageWriter { void Write(string message); } public class ConsoleMessageWriter : IMessageWriter { public void Write(string message) { Console.WriteLine(message); } } public class Salutation { private readonly IMessageWriter _writer; public Salutation(IMessageWriter writer) { _writer = writer; } public void Exclaim() { _writer.Write("Hello World"); } }   If you had asked me a few years ago if I had thought this was a good approach to solving the HelloWorld problem I would have resounded “No”. How could the above be better than the following…. class Program { static void Main(string[] args) { Console.WriteLine("Hello World"); Console.ReadLine(); } }  Today, my mind-set has changed because of the pain of past programs. So often we can look at a small snippet of code and make judgements when we need to keep in mind that we will most probably be implementing these patterns in projects with hundreds of thousands of lines of code and in projects that we have tests that we don’t want to break and that’s where the first solution outshines the latter. Let’s see if the first example achieves some of the outcomes that were listed as benefits of DI. Could I test the first solution easily? Yes… We could write something like the following using NUnit and RhinoMocks… [TestFixture] public class SalutationTests { [Test] public void ExclaimWillWriteCorrectMessageToMessageWriter() { var writerMock = MockRepository.GenerateMock<IMessageWriter>(); var sut = new Salutation(writerMock); sut.Exclaim(); writerMock.AssertWasCalled(x => x.Write("Hello World")); } }   This would test the existing code fine. Let’s say we then wanted to extend the original solution so that we had a secure message writer. We could write a class like the following… public class SecureMessageWriter : IMessageWriter { private readonly IMessageWriter _writer; private readonly string _secretPassword; public SecureMessageWriter(IMessageWriter writer, string secretPassword) { _writer = writer; _secretPassword = secretPassword; } public void Write(string message) { if (_secretPassword == "Mark") { _writer.Write(message); } else { _writer.Write("Unauthenticated"); } } }   And then extend our implementation of the program as follows… class Program { static void Main(string[] args) { var writer = new SecureMessageWriter(new ConsoleMessageWriter(), "Mark"); var salutation = new Salutation(writer); salutation.Exclaim(); Console.ReadLine(); } }   Our application has now been successfully extended and yet we did very little code change. In addition, our existing tests did not break and we would just need add tests for the extended functionality. Would this approach allow parallel development? Well, I am in two camps on parallel development but with some planning ahead of time it would allow for it as you would simply need to decide on the interface signature and could then have teams develop different sections programming to that interface. So,this was really just a quick intro to some of the basic concepts of DI that Mark introduces very successfully in his book. I am hoping to blog about this further as I continue through the book to list some of the more complex implementations of containers.

    Read the article

  • Determining the angle to fire a shot when target and shooter moves, and bullet moves with shooter velocity added in

    - by Azaral
    I saw this question: Predicting enemy position in order to have an object lead its target and followed the link in the answer to stack overflow. In the stack overflow page I used the 2nd answer, the one that is a large mathematical derivation. My situation is a little different though. My first question though is will the answer provided in the stack overflow page even work to begin with, assuming the original circumstances of moving target and stationary shooter. My situation is a little different than that situation. My target moves, the shooter moves, and the bullets from the shooter start off with the velocities in x and y added to the bullets' x and y velocities. If you are sliding to the right, the bullets will remain in front of you as you move so as long as your velocity remains constant. What I'm trying to do is to get the enemy to be able to determine where they need to shoot in order to hit the player. Unless the player and enemy is stationary, the velocity from the ship adding to the velocity of the bullets will cause a miss. I'd rather like to prevent that. I used the formula in the stack overflow answer and did what I thought were the appropriate adjustments. I've been banging at this for the last four hours and I just can't make it click. It is probably something really simple and boneheaded that I am missing (that seems to be a lot of my problems lately). Here is the solution presented from the stack overflow answer: It boils down to solving a quadratic equation of the form: a * sqr(x) + b * x + c == 0 Note that by sqr I mean square, as opposed to square root. Use the following values: a := sqr(target.velocityX) + sqr(target.velocityY) - sqr(projectile_speed) b := 2 * (target.velocityX * (target.startX - cannon.X) + target.velocityY * (target.startY - cannon.Y)) c := sqr(target.startX - cannon.X) + sqr(target.startY - cannon.Y) Now we can look at the discriminant to determine if we have a possible solution. disc := sqr(b) - 4 * a * c If the discriminant is less than 0, forget about hitting your target -- your projectile can never get there in time. Otherwise, look at two candidate solutions: t1 := (-b + sqrt(disc)) / (2 * a) t2 := (-b - sqrt(disc)) / (2 * a) Note that if disc == 0 then t1 and t2 are equal. If there are no other considerations such as intervening obstacles, simply choose the smaller positive value. (Negative t values would require firing backward in time to use!) Substitute the chosen t value back into the target's position equations to get the coordinates of the leading point you should be aiming at: aim.X := t * target.velocityX + target.startX aim.Y := t * target.velocityY + target.startY Here is my code, after being corrected by Sam Hocevar (thank you again for your help!). It still doesn't work. For some reason it never enters the section of code inside the if(disc = 0) (obviously because it is always less than zero but...). However, if I plug the numbers from my game log on the enemy and player positions and velocities it outputs a valid firing solution. I have looked at the code side by side a couple of times now and I can't find any differences. There has got to be something simple I'm missing here. If someone else could look at this code and determine what is going on here I'd appreciate it. I know it's not going through that section because if it were, shouldShoot would become true and the enemy would be blasting away at the player. This section calls the function in question, CalculateShootHeading() if(shouldMove) { UseEngines(); } x += xVelocity; y += yVelocity; CalculateShootHeading(); if(shouldShoot) { ShootWeapons(); } UpdateWeapons(); This is CalculateShootHeading(). This is inside the enemy class so x and y are the enemy's x and y and the same with velocity. One output from my game log gives Player X = 2108, Player Y = -180.956, Player X velocity = 10.9949, Player Y Velocity = -6.26017, Enemy X = 1988.31, Enemy Y = -339.051, Enemy X velocity = 1.81666, Enemy Y velocity = -9.67762, 0 enemy projectiles. The output from the console tester is Bullet position = 2210.49, -239.313 and Player Position = 2210.49, -239.313. This doesn't make any sense. The only thing that could be different is the code or the input into my function in the game and I've checked that and I don't think that it is wrong as it's updated before this and never changed. float const bulletSpeed = 30.f; float const dx = playerX - x; float const dy = playerY - y; float const vx = playerXVelocity - xVelocity; float const vy = playerYVelocity - yVelocity; float const a = vx * vx + vy * vy - bulletSpeed * bulletSpeed; float const b = 2.f * (vx * dx + vy * dy); float const c = dx * dx + dy * dy; float const disc = b * b - 4.f * a * c; shouldShoot = false; if (disc >= 0.f) { float t0 = (-b - std::sqrt(disc)) / (2.f * a); float t1 = (-b + std::sqrt(disc)) / (2.f * a); if (t0 < 0.f || (t1 < t0 && t1 >= 0.f)) { t0 = t1; } if (t0 >= 0.f) { float shootx = vx + dx / t0; float shooty = vy + dy / t0; heading = std::atan2(shooty, shootx) * RAD2DEGREE; } shouldShoot = true; }

    Read the article

  • Multidimensional multiple-choice knapsack problem: find a feasible solution

    - by Onheiron
    My assignment is to use local search heuristics to solve the Multidimensional multiple-choice knapsack problem, but to do so I first need to find a feasible solution to start with. Here is an example problem with what I tried so far. Problem R1 R2 R3 RESOUCES : 8 8 8 GROUPS: G1: 11.0 3 2 2 12.0 1 1 3 G2: 20.0 1 1 3 5.0 2 3 2 G3: 10.0 2 2 3 30.0 1 1 3 Sorting strategies To find a starting feasible solution for my local search I decided to ignore maximization of gains and just try to fit the resources requirements. I decided to sort the choices (strategies) in each group by comparing their "distance" from the multidimensional space origin, thus calculating SQRT(R1^2 + R2^2 + ... + RN^2). I felt like this was a keen solution as it somehow privileged those choices with resouce usages closer to each other (e.g. R1:2 R2:2 R3:2 < R1:1 R2:2 R3:3) even if the total sum is the same. Doing so and selecting the best choice from each group proved sufficent to find a feasible solution for many[30] different benchmark problems, but of course I knew it was just luck. So I came up with the problem presented above which sorts like this: R1 R2 R3 RESOUCES : 8 8 8 GROUPS: G1: 12.0 1 1 3 < select this 11.0 3 2 2 G2: 20.0 1 1 3 < select this 5.0 2 3 2 G3: 30.0 1 1 3 < select this 10.0 2 2 3 And it is not feasible because the resources consmption is R1:3, R2:3, R3:9. The easy solution is to pick one of the second best choices in group 1 or 2, so I'll need some kind of iteration (local search[?]) to find the starting feasible solution for my local search solution. Here are the options I came up with Option 1: iterate choices I tried to find a way to iterate all the choices with a specific order, something like G1 G2 G3 1 1 1 2 1 1 1 2 1 1 1 2 2 2 1 ... believeng that feasible solutions won't be that far away from the unfeasible one I start with and thus the number of iterations will keep quite low. Does this make any sense? If yes, how can I iterate the choices (grouped combinations) of each group keeping "as near as possibile" to the previous iteration? Option 2: Change the comparation term I tried to think how to find a better variable to sort the choices on. I thought at a measure of how "precious" a resource is based on supply and demand, so that an higer demand of a more precious resource will push you down the list, but this didn't help at all. Also I thought there probably isn't gonna be such a comparsion variable which assures me a feasible solution at first strike. I there such a variable? If not, is there a better sorting criteria anyways? Option 3: implement any known sub-optimal fast solving algorithm Unfortunately I could not find any of such algorithms online. Any suggestion?

    Read the article

  • Too complex/too many objects?

    - by Mike Fairhurst
    I know that this will be a difficult question to answer without context, but hopefully there are at least some good guidelines to share on this. The questions are at the bottom if you want to skip the details. Most are about OOP in general. Begin context. I am a jr dev on a PHP application, and in general the devs I work with consider themselves to use many more OO concepts than most PHP devs. Still, in my research on clean code I have read about so many ways of using OO features to make code flexible, powerful, expressive, testable, etc. that is just plain not in use here. The current strongly OO API that I've proposed is being called too complex, even though it is trivial to implement. The problem I'm solving is that our permission checks are done via a message object (my API, they wanted to use arrays of constants) and the message object does not hold the validation object accountable for checking all provided data. Metaphorically, if your perm containing 'allowable' and 'rare but disallowed' is sent into a validator, the validator may not know to look for 'rare but disallowed', but approve 'allowable', which will actually approve the whole perm check. We have like 11 validators, too many to easily track at such minute detail. So I proposed an AtomicPermission class. To fix the previous example, the perm would instead contain two atomic permissions, one wrapping 'allowable' and the other wrapping 'rare but disallowed'. Where previously the validator would say 'the check is OK because it contains allowable,' now it would instead say '"allowable" is ok', at which point the check ends...and the check fails, because 'rare but disallowed' was not specifically okay-ed. The implementation is just 4 trivial objects, and rewriting a 10 line function into a 15 line function. abstract class PermissionAtom { public function allow(); // maybe deny() as well public function wasAllowed(); } class PermissionField extends PermissionAtom { public function getName(); public function getValue(); } class PermissionIdentifier extends PermissionAtom { public function getIdentifier(); } class PermissionAction extends PermissionAtom { public function getType(); } They say that this is 'not going to get us anything important' and it is 'too complex' and 'will be difficult for new developers to pick up.' I respectfully disagree, and there I end my context to begin the broader questions. So the question is about my OOP, are there any guidelines I should know: is this too complicated/too much OOP? Not that I expect to get more than 'it depends, I'd have to see if...' when is OO abstraction too much? when is OO abstraction too little? how can I determine when I am overthinking a problem vs fixing one? how can I determine when I am adding bad code to a bad project? how can I pitch these APIs? I feel the other devs would just rather say 'its too complicated' than ask 'can you explain it?' whenever I suggest a new class.

    Read the article

  • I am not satisfied with my career and accomplished nothing in my life. what should I do now [on hold]

    - by user2906155
    After my complete my College education I got chance to work on software programming. I work on few software and now nothing make me feel good. I don't like web-programming. Can't have too much mind to play with other people in team a designer or a senior. it's totally time wasting for me. We do integration without any source code control. copy through pen drive. I write in too many language for web-programming but know nothing about any language specially. I don't like to have a BOSS. I would like to do something on my own. From last 3 year I thing I will got a better job but I am unable to get it. I am not good at Programming nor my English is native. I have a big list for pay then my salary. I have problem with nothing. my atmosphere is about illiterate people. they abuse 24 hours a day. this thing make me sick. people watch CRIME patrol my home (watching rape in TV because it's happen to someone). I do my work from home. I don't like to live in my state. All state is one of the biggest illiterate state of my country. Once I apply for a Job in China and it's look like I can get thing Job but I don't get it. My family doesn't want me to settle anywhere else. I told my family 4 time a day that I can't live in this worst situation. Everyone (including the person who I work for) tell me that you can do it only you have money. Now I really don't know how to make money. My job not allow me to work for anyone. My productivity going down since I don't learn anything new. I thing if this happen to me for next 2 year I don't have any knowledge more then a peon. I hate it. When I was in other city then I see that if I spent 7 days their all my 7 days going better. even I go for travelling in green places then I like it. but all I hate it where I work for. When I work on other city then I see my productivity are improved and I don't hate my work. I listen a song "If you don't your love what are you doing it for". I seriously don' t know what I still live here because this place gave me nothing but depression and trouble. for people I clear that I don't belong to RICH or middle class family. All I got is doing something on my own or help of someone. affording a rental place make my run on footpath. All I save in one month is just 10$ (approximately) (actually I afford some guys's education now). Can a programmer live worst life like this. I really not happy. Today is a festival in India and I don't celebrate it because I really hate myself. I want to do suicide. someone guide me how to start solving this headache

    Read the article

  • James - mail server configuration help needed

    - by Chaitanya
    Hi, I am trying to setup James mail server on a linux machine. The linux machine has public static ip address assigned. I installed James and added in the config.xml added the servername as mydomain.com. In the DNS for mydomain.com, I have created a A-record, say mx.mydomain.com, which corresponds to the ipaddress of the above mail server machine. Then added mx.mydomain.com as MX record for mydomain.com. In James, I have created a new user test. Then from gmail, I sent a mail to [email protected]. The mail is not received back and it didn't even bounce back. The linux machine is behind a firewall with only 22, 80, 8080 ports open for external network. My question here is, Do I require do open any other ports on the firewall so that the mail I send from gmail arrives to James? If it's not the port problem, any views on solving this issue? I don't want to send mails from this server. It's only for receiving the mails.

    Read the article

  • Advice on database design / SQL for retrieving data with chronological order

    - by Remnant
    I am creating a database that will help keep track of which employees have been on a certain training course. I would like to get some guidance on the best way to design the database. Specifically, each employee must attend the training course each year and my database needs to keep a history of all the dates on which they have attend the course in the past. The end user will use the software as a planning tool to help them book future course dates for employees. When they select a given employee they will see: (a) Last attendance date (b) Projected future attendance date(i.e. last attendance date + 1 calendar year) In terms of my database, any given employee may have multiple past course attendance dates: EmpName AttandanceDate Joe Bloggs 1st Jan 2007 Joe Bloggs 4th Jan 2008 Joe Bloggs 3rd Jan 2009 Joe Bloggs 8th Jan 2010 My question is what is the best way to set up the database to make it easy to retrieve the most recent course attendance date? In the example above, the most recent would be 8th Jan 2010. Is there a good way to use SQL to sort by date and pick the MAX date? My other idea was to add a column called ‘MostRecent’ and just set this to TRUE. EmpName AttandanceDate MostRecent Joe Bloggs 1st Jan 2007 False Joe Bloggs 4th Jan 2008 False Joe Bloggs 3rd Jan 2009 False Joe Bloggs 8th Jan 2010 True I wondered if this would simplify the SQL i.e. SELECT Joe Bloggs WHERE MostRecent = ‘TRUE’ Also, when the user updates a given employee’s attendance record (i.e. with latest attendance date) I could use SQL to: Search for the employee and set the MostRecent value to FALSE Add a new record with MostRecent set to TRUE? Would anybody recommended either method over the other? Or do you have a completely different way of solving this problem?

    Read the article

  • Writing a Javascript library that is code-completion and code-inspection friendly

    - by Vivin Paliath
    I recently made my own Javascript library and I initially used the following pattern: var myLibrary = (function () { var someProp = "..."; function someFunc() { ... } function someFunc2() { ... } return { func: someFunc, fun2: someFunc2, prop: someProp; } }()); The problem with this is that I can't really use code completion because the IDE doesn't know about the properties that the function literal is returning (I'm using IntelliJ IDEA 9 by the way). I've looked at jQuery code and tried to do this: (function(window, undefined) { var myLibrary = (function () { var someProp = "..."; function someFunc() { ... } function someFunc2() { ... } return { func: someFunc, fun2: someFunc2, prop: someProp; } }()); window.myLibrary = myLibrary; }(window)); I tried this, but now I have a different problem. The IDE doesn't really pick up on myLibrary either. The way I'm solving the problem now is this way: var myLibrary = { func: function() { }, func2: function() { }, prop: "" }; myLibrary = (function () { var someProp = "..."; function someFunc() { ... } function someFunc2() { ... } return { func: someFunc, fun2: someFunc2, prop: someProp; } }()); But that seems kinda clunky, and I can't exactly figure out how jQuery is doing it. Another question I have is how to handle functions with arbitrary numbers of parameters. For example, jQuery.bind can take 2 or 3 parameters, and the IDE doesn't seem to complain. I tried to do the same thing with my library, where a function could take 0 arguments or 1 argument. However, the IDE complains and warns that the correct number of parameters aren't being sent in. How do I handle this?

    Read the article

  • Installable ISAM not found

    - by lucky
    I have a requirement in which i upload excel sheets to sql server database. The business logic is executed and display as reports in php. It is working fine till yesterday. Today i tried to upload excel files. It is throwing an error message stating:- Translated version of it by me:- The OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)" has not found "installable ISAM." . Return This is the original message in german:-- [Microsoft][ODBC SQL Server Driver][SQL Server] OLE DB-Anbieter "Microsoft.Jet.OLEDB.4.0" für den Verbindungsserver "(null)" hat die Meldung "Installierbares ISAM nicht gefunden." zurückgeben. Query that i used in the stored procedure:- EXEC('SELECT * INTO temp FROM OPENROWSET(''Microsoft.Jet.OLEDB.4.0'', ''Excel 8.0;Database=' + @ba_bm_status + ''',' + '''SELECT * FROM [qry_BA_Controlling (Report)$]'')'); @ba_bm_status - i/p parameter of srored procedure qry_BA_Controlling (Report) - worksheet name webserver used:- IIS, connection is through odbc. I have no information about this error. Can you please help me in solving the same.

    Read the article

  • Boosting my GA with Neural Networks and/or Reinforcement Learning

    - by AlexT
    As I have mentioned in previous questions I am writing a maze solving application to help me learn about more theoretical CS subjects, after some trouble I've got a Genetic Algorithm working that can evolve a set of rules (handled by boolean values) in order to find a good solution through a maze. That being said, the GA alone is okay, but I'd like to beef it up with a Neural Network, even though I have no real working knowledge of Neural Networks (no formal theoretical CS education). After doing a bit of reading on the subject I found that a Neural Network could be used to train a genome in order to improve results. Let's say I have a genome (group of genes), such as 1 0 0 1 0 1 0 1 0 1 1 1 0 0... How could I use a Neural Network (I'm assuming MLP?) to train and improve my genome? In addition to this as I know nothing about Neural Networks I've been looking into implementing some form of Reinforcement Learning, using my maze matrix (2 dimensional array), although I'm a bit stuck on what the following algorithm wants from me: (from http://people.revoledu.com/kardi/tutorial/ReinforcementLearning/Q-Learning-Algorithm.htm) 1. Set parameter , and environment reward matrix R 2. Initialize matrix Q as zero matrix 3. For each episode: * Select random initial state * Do while not reach goal state o Select one among all possible actions for the current state o Using this possible action, consider to go to the next state o Get maximum Q value of this next state based on all possible actions o Compute o Set the next state as the current state End Do End For The big problem for me is implementing a reward matrix R and what a Q matrix exactly is, and getting the Q value. I use a multi-dimensional array for my maze and enum states for every move. How would this be used in a Q-Learning algorithm? If someone could help out by explaining what I would need to do to implement the following, preferably in Java although C# would be nice too, possibly with some source code examples it'd be appreciated.

    Read the article

  • How to do proper Unicode and ANSI output redirection on cmd.exe?

    - by Sorin Sbarnea
    If you are doing automation on windows and you are redirecting the output of different commands (internal cmd.exe or external, you'll discover that your log files contains combined Unicode and ANSI output (meaning that they are invalid and will not load well in viewers/editors). Is it is possible to make cmd.exe work with UTF-8? This question is not about display, s about stdin/stdout/stderr redirection and Unicode. I am looking for a solution that would allow you to: redirect the output of the internal commands to a file using UTF-8 redirect output of external commands supporting Unicode to the files but encoded as UTF-8. If it is impossible to obtain this kind of consistence using batch files, is there another way of solving this problem, like using python scripting for this? In this case, I would like to know if it is possible to do the Unicode detection alone (user using the scripting should not remember if the called tools will output Unicode or not, it will just expect to convert the output to UTF-8. For simplicity we'll assume that if the tool output is not-Unicode it will be considered as UTF-8 (no codepage conversion).

    Read the article

  • What do you mean by the expressiveness in a programming language?

    - by prosseek
    I see a lot of the word 'expressiveness' when people want to stress one language is better than the other. But I don't see exactly what they mean by it. Is it the verboseness/succinctness? I mean, if one language can write down something shorter than the other, does that mean expressiveness? Please refer to my other question - http://stackoverflow.com/questions/2411772/article-about-code-density-as-a-measure-of-programming-language-power Is it the power of the language? Paul Graham says that one language is more powerful than the other language in a sense that one language can do that the other language can't do (for example, LISP can do something with macro that the other language can't do). Is it just something that makes life easier? Regular expression can be one of the examples. Is it a different way of solving the same problem: something like SQL to solve the search problem? What do you think about the expressiveness of a programming language? Can you show the expressiveness using some code? What's the relationship with the expressiveness and DSL? Do people come up with DSL to get the expressiveness?

    Read the article

  • Pause code execution until UIAlertView button is pressed?

    - by JuBu1324
    One of my methods sends a message to an object (what do you know about that), and expects a BOOL for an answer. However, BOOL answer it is expecting is based on the answer to a UIAlertView created in the receiving object's method. However, the code doesn't pause while waiting for the user to answer the UIAlertView. My problem is: how do I use -alertView:clickedButtonAtIndex in the method's return value? Here's the code the message runs (in this construction, I was expecting navigateAwayFromTab to change based on the user input in the UIAlertView, but it never gets a chance): - (BOOL)readyToNavigateAwayFromTab { NSLog( @"message received by Medical View"); navigateAwayFromTab = NO; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Navigate Away From Tab?" message:@"Navigating away from this tab will save your work." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil ]; [alert show]; [alert release]; return navigateAwayFromTab; } #define CANCEL 0 #define OK 1 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if( buttonIndex == OK ) navigateAwayFromTab = YES; } I've been reading up on the modal UIAlertView debate, and I agree with apple's implementation - at lest as the rule. However, in this case I don't see any way of solving the problem by putting code in -alertView:clickedButtonAtIndex because I don't need to run code based on the UIAlertView, I just need to read the response. Any suggestions on how I can reach my gaol? I've tried a while loop after [alert show] already, but then the alert doesn't even show then, and for a number of reasons I can't use -viewWillDisapear.

    Read the article

  • Is there a perfect algorithm for chess?

    - by Overflown
    Dear Stack Overflow community, I was recently in a discussion with a non-coder person on the possibilities of chess computers. I'm not well versed in theory, but think I know enough. I argued that there could not exist a deterministic Turing machine that always won or stalemated at chess. I think that, even if you search the entire space of all combinations of player1/2 moves, the single move that the computer decides upon at each step is based on a heuristic. Being based on a heuristic, it does not necessarily beat ALL of the moves that the opponent could do. My friend thought, to the contrary, that a computer would always win or tie if it never made a "mistake" move (however do you define that?). However, being a programmer who has taken CS, I know that even your good choices - given a wise opponent - can force you to make "mistake" moves in the end. Even if you know everything, your next move is greedy in matching a heuristic. Most chess computers try to match a possible end game to the game in progress, which is essentially a dynamic programming traceback. Again, the endgame in question is avoidable though. -- thanks, Allan Edit: Hmm... looks like I ruffled some feathers here. That's good. Thinking about it again, it seems like there is no theoretical problem with solving a finite game like chess. I would argue that chess is a bit more complicated than checkers in that a win is not necessarily by numerical exhaustion of pieces, but by a mate. My original assertion is probably wrong, but then again I think I've pointed out something that is not yet satisfactorily proven (formally). I guess my thought experiment was that whenever a branch in the tree is taken, then the algorithm (or memorized paths) must find a path to a mate (without getting mated) for any possible branch on the opponent moves. After the discussion, I will buy that given more memory than we can possibly dream of, all these paths could be found.

    Read the article

  • empty response body in ajax (or 206 Partial Content)

    - by Nikita Rybak
    Hi guys, I'm feeling completely stupid because I've spent two hours solving task which should be very simple and which I solved many times before. But now I'm not even sure in which direction to dig. I fail to fetch static content using ajax from local servers (Apache and Mongrel). I get responses 200 and 206 (depending on the server), empty response text (although Content-Length header is always correct), firebug shows request in red. Javascript is very generic, I'm getting same results even here: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first (just change document location to 'http://localhost:3000/whatever') So, it's probably not the cause. Well, now I'm out of ideas. I can also post http headers, if it'll help. Thanks! Response Headers Connection close Date Sat, 01 May 2010 21:05:23 GMT Last-Modified Sun, 18 Apr 2010 19:33:26 GMT Content-Type text/html Content-Length 7466 Request Headers Host localhost:3000 User-Agent Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language en-us,en;q=0.5 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 115 Connection keep-alive Referer http://www.w3schools.com/ajax/tryit_view.asp Origin http://www.w3schools.com Response Headers Date Sat, 01 May 2010 21:54:59 GMT Server Apache/2.2.14 (Unix) mod_ssl/2.2.14 OpenSSL/0.9.8l DAV/2 mod_jk/1.2.28 Etag "3d5cbdb-fb4-4819c460d4a40" Accept-Ranges bytes Content-Length 4020 Cache-Control max-age=7200, public, proxy-revalidate Expires Sat, 01 May 2010 23:54:59 GMT Content-Range bytes 0-4019/4020 Keep-Alive timeout=5, max=100 Connection Keep-Alive Content-Type application/javascript Request Headers Host localhost User-Agent Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language en-us,en;q=0.5 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 115 Connection keep-alive Origin null

    Read the article

  • codeigniter & cjax framework, fatal error class 'CI_Controller' not found

    - by Martin
    I'm having this weird error with Codeigniter 2.1.3 and latest cjax for codeigniter. Weird thing is, when I download the latest codeigniter, and latest cjax framework for codeitniger and copy to my friends server, and call: domain.com/ajax.php?test/test2 to show the test ajax examples ... it works like a breeze, but when I do this on my server, I get server error (even tho, we both have same php version and such). Server then throws in error log file this error: PHP Fatal error: Class 'CI_Controller' not found in /hosting/www/domain.com/www/application/response/test.php on line 3 Now, I've read thru stackoverflow with people having this problem and solving by changing the construct and calling CI_Controller instead of Controller. But I already do that ... - I mean it's in the basic example that is suppose to work without touching the code, and it does, just not on my domain for some crappy reason. Ajax.php from cjax framework for codeingter should load controller from folder response, named test and call function test2, which looks like this (the actual file named test.php): class Test extends CI_Controller { function __construct() { parent::__construct(); } /** * * ajax.php?test/test/a/b/c * * @param unknown_type $a * @param unknown_type $b * @param unknown_type $c */ function test($a = null,$b = null, $c = null) { $this->load->view('test', array('data' => $a .' '.$b.' '.$c)); } /** * ajax.php?test/test2 * * Here we are testing out the javascript library. * * Note: the library it is not meant to be included in ajax controllers - but in front-controllers, * it is being used here for the sake of simplicity in testing. */ function test2() { $ajax = ajax(); $ajax->update('response','Cjax Works'); $ajax->append('#response','<br /><br />version: '.$ajax->version); $ajax->success('Cjax was successfully installed.', 5); //see application/views/test2.php $this->load->view('test2'); } I was hoping someone could bring some light into this problem - or maybe someone has already experienced it? Thanks for your time! Mart

    Read the article

  • Using Taylor Series to Avoid Loss of Precision

    - by Zachary
    I'm trying to use Taylor series to develop a numerically sound algorithm for solving a function. I've been at it for quite a while, but haven't had any luck yet. I'm not sure what I'm doing wrong. The function is f(x)=1 + x - sin(x)/ln(1+x) x~0 Also: why does loss of precision even occur in this function? when x is close to zero, sin(x)/ln(1+x) isn't even close to being the same number as x. I don't see where significance is even being lost. In order to solve this, I believe that I will need to use the Taylor expansions for sin(x) and ln(1+x), which are x - x^3/3! + x^5/5! - x^7/7! + ... and x - x^2/2 + x^3/3 - x^4/4 + ... respectfully. I have attempted to use like denominators to combine the x and sin(x)/ln(1+x) components, and even to combine all three, but nothing seems to work out correctly in the end. Any help is appreciated.

    Read the article

  • Cross domains sessions - shared shopping cart cross domains

    - by Jaroslav Moravec
    Hi, we are solving the problem with eshop (php, mysql). The client want to have the same eshop on two domains with shared shopping cart. In the shop customer can do the shopping without users account (can't be logged in). And there is the problem, how to make the shared shopping cart cross domain. The data from cart is stored in sessions, which we stored in database too. But we can't solve the problem in carrying data over domains. Identifying unlogged user is not holeproof (research). The example, how it should work Customer goes to domainOne and add some things to the cart. Than he goes to domainTwo (by link, typing domain address, however) and add some other things to the cart. In the cart he has things from both domains (after refreshing page). Do you have any idea, how to solve this problem? What didn't work: redirecting is not possible due to customer requirments cookies are related to domain set_cookie with the other domain didn't work the simpliest way is to carry over only the sessionid (stored in cookies) but we don't know, how to wholeproof identify unlogged users. is there any other place, where data can be stored on client side except cookies? (probably not) we can't use sending sessionid by params in url (if user click to link to the other domain) or resolving the header referer, bcs we don't know, how user can achieve the other domain. If you can't understand me, take me a question. If you think, that having eshop on two domains with shared (common) cart is bad idea, don't tell me, we know it. Thanks for each answer.

    Read the article

  • How do I get google protocol buffer messages over a socket connection without disconnecting the clie

    - by Dan
    Hi there, I'm attempting to send a .proto message from an iPhone application to a Java server via a socket connection. However so far I'm running into an issue when it comes to the server receiving the data; it only seems to process it after the client connection has been terminated. This points to me that the data is getting sent, but the server is keeping its inputstream open and waiting for more data. Would anyone know how I might go about solving this? The current code (or at least the relevant parts) is as follows: iPhone: Person *person = [[[[Person builder] setId:1] setName:@"Bob"] build]; RequestWrapper *request = [[[RequestWrapper builder] setPerson:person] build]; NSData *data = [request data]; AsyncSocket *socket = [[AsyncSocket alloc] initWithDelegate:self]; if (![socket connectToHost:@"192.168.0.6" onPort:6666 error:nil]){ [self updateLabel:@"Problem connecting to socket!"]; } else { [self updateLabel:@"Sending data to server..."]; [socket writeData:data withTimeout:-1 tag:0]; [self updateLabel:@"Data sent, disconnecting"]; //[socket disconnect]; } Java: try { RequestWrapper wrapper = RequestWrapper.parseFrom(socket.getInputStream()); Person person = wrapper.getPerson(); if (person != null) { System.out.println("Persons name is " + person.getName()); socket.close(); } On running this, it seems to hang on the line where the RequestWrapper is processing the inputStream. I did try replacing the socket writedata method with [request writeToOutputStream:[socket getCFWriteStream]]; Which I thought might work, however I get an error claiming that the "Protocol message contained an invalid tag (zero)". I'm fairly certain that it doesn't contain an invalid tag as the message works when sending it via the writedata method. Any help on the matter would be greatly appreciated! Cheers! Dan (EDIT: I should mention, I am using the metasyntactic gpb code; and the cocoaasyncsocket implementation)

    Read the article

  • Unable to install Management Studio Express 2008 due to Visual Studio 2008 installation

    - by Jamie
    I am attempting to install Managment Studio Express 2008 on a Win7 system that already has Visual Studio 2008 installed. I have installed VS 2008 SP1, which results in the About box for Visual Studio giving a version of 9.0.30792.1 SP. When I attempt the Management Studio installation I see a message that tells me that I must install SP1. However, this is already installed. After a fair bit of searching I came across the link below, where someone had commented with a command line option for the installation executable that forced it to skip the check. However, this simply pushed the error to later in the installation process. http://www.thushanfernando.com/index.php/2008/08/10/fix-rule-previous-releases-of-microsoft-visual-studio-2008-failed/. This seems to be a perennial problem for Microsoft. I can't remember a time when I've painlessly installed both Management Studio and Visual Studio. I can't imagine that this is an unusual combination, after all! Anyone had any success in solving this problem before I take on the day-long task of uninstalling and reinstalling Visual Studio and all its associated bits?

    Read the article

  • SQL Server 2005 and 'General network error'

    - by Mariusz
    I know there is a lot of information in the Internet about solving this problem, but it didn't help me. My Delphi application uses dbExpress controls to access the database and execute SQL queries. Once every couple of days, however, it stops working because the database connection fails. This happens on several different computers with different versions of Windows. MSSQL Server 2005 (version 9.0.4035) is installed on each of them. The above mentioned application executes queries every couple of seconds, and they are mainly insert commands. Every couple of days I get a series of exceptions like the following one: [DBNETLIB][ConnectionOpen (PreLoginHandshake()).]General network error. Check your network documentation. And then the SQL server becomes inaccessible until I restart it manually. The information I found in the Internet say that I should install some service packs, change some registry entries etc., but believe me, none of these helps and I don't know what else to do now. Could you please help me solve this problem? Any clues or ideas? I can give you some more information about the server or the application if necessary. Thank you very much in advance.

    Read the article

  • Creating A Single Generic Handler For Agatha?

    - by David
    I'm using the Agatha request/response library (and StructureMap, as utilized by Agatha 1.0.5.0) for a service layer that I'm prototyping, and one thing I've noticed is the large number of handlers that need to be created. It generally makes sense that any request/response type pair would need their own handler. However, as this scales to a large enterprise environment that's going to be A LOT of handlers. What I've started doing is dividing up the enterprise domain into logical processor classes (dozens of processors instead of many hundreds or possibly eventually thousands handlers). The convention is that each request/response type (all of which inherit from a domain base request/response pair, which inherit from Agatha's) gets exactly one function in a processor somewhere. The generic handler (which inherits from Agatha's RequestHandler) then uses reflection in the Handle method to find the method for the given TREQUEST/TRESPONSE and invoke it. If it can't find one or if it finds more than one, it returns a TRESPONSE containing an error message (messages are standardized in the domain's base response class). The goal here is to allow developers across the enterprise to just concern themselves with writing their request/response types and processor functions in the domain and not have to spend additional overhead creating handler classes which would all do exactly the same thing (pass control to a processor function). However, it seems that I still need to have defined a handler class (albeit empty, since the base handler takes care of everything) for each request/response type pair. Otherwise, the following exception is thrown when dispatching a request to the service: StructureMap Exception Code: 202 No Default Instance defined for PluginFamily Agatha.ServiceLayer.IRequestHandler`1[[TSFG.Domain.DTO.Actions.HelloWorldRequest, TSFG.Domain.DTO, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Agatha.ServiceLayer, Version=1.0.5.0, Culture=neutral, PublicKeyToken=6f21cf452a4ffa13 Is there a way that I'm not seeing to tell StructureMap and/or Agatha to always use the base handler class for all request/response type pairs? Or maybe to use Reflection.Emit to generate empty handlers in memory at application start just to satisfy the requirement? I'm not 100% familiar with these libraries and am learning as I go along, but so far my attempts at both those possible approaches have been unsuccessful. Can anybody offer some advice on solving this, or perhaps offer another approach entirely?

    Read the article

  • matplotlib.pyplot/pylab not updating figure while isinteractive(), using ipython -pylab

    - by NumberOverZero
    There are a lot of questions about matplotlib, pylab, pyplot, ipython, so I'm sorry if you're sick of seeing this asked. I'll try to be as specific as I can, because I've been looking through people's questions and looking at documentation for pyplot and pylab, and I still am not sure what I'm doing wrong. On with the code: Goal: plot a figure every .5 seconds, and update the figure as soon as the plot command is called. My attempt at coding this follows (running on ipython -pylab): import time ion() x=linspace(-1,1,51) plot(sin(x)) for i in range(10): plot([sin(i+j) for j in x]) #see ** print i time.sleep(1) print 'Done' It correctly plots each line, but not until it has exited the for loop. I have tried forcing a redraw by putting draw() where ** is, but that doesn't seem to work either. Ideally, I'd like to have it simply add each line, instead of doing a full redraw. If redrawing is required however, that's fine. Additional attempts at solving: just after ion(), tried adding hold(True) to no avail. for kicks tried show() for ** The closest answer I've found to what I'm trying to do was at http://stackoverflow.com/questions/2310851/plotting-lines-without-blocking-execution, but show() isn't doing anything. I apologize if this is a straightforward request, and I'm looking past something so obvious. For what it's worth, this came up while I was trying to convert matlab code from class to some python for my own use. The original matlab (initializations removed) which I have been trying to convert follows: for i=1:time plot(u) hold on pause(.01) for j=2:n-1 v(j)=u(j)-2*u(j-1) end v(1)= pi u=v end Any help, even if it's just "look up this_method" would be excellent, so I can at least narrow my efforts to figuring out how to use that method. If there's any more information that would be useful, let me know.

    Read the article

  • Subview of custom NSView is resizing itself to fit within its superview

    - by Jonathan Patt
    I have a custom NSView which contains a subview—for the purposes of solving this issue, the top level view is simply acting as a container and automatically resizes to fit within the window. Its subview draws a rectangle 10 pixels inset from the edge of the window, except for the bottom, which should get clipped by the window until it's resized to show the entire rectangle. It does not, however, behave as I intend, and instead shrinks the height of the rectangle when its superview has a smaller height than it does. How do I avoid this and have it stay at its proper height and instead get clipped when the superview is smaller? The parent view's implementation code is: - (id)initWithFrame:(NSRect)frameRect { self = [super initWithFrame:frameRect]; if (self) { subView = [[SubView alloc] initWithFrame:frameRect]; } return self; } - (void)drawRect:(NSRect)dirtyRect { [[NSColor grayColor] set]; [subView setFrame:NSMakeRect(10, 10, dirtyRect.size.width - 20, 500)]; [self addSubview:subView]; } - (BOOL)isFlipped { return YES; } And the subview is just: - (void)drawRect:(NSRect)dirtyRect { [[NSColor blackColor] set]; [NSBezierPath strokeRect:dirtyRect]; } - (BOOL)isFlipped { return YES; }

    Read the article

  • Google App Engine application instance recycling and response times...

    - by Konrad
    Hi, I posted this on GAE for Java group, but I hope to get some answers here quicker :) I decided to do some long-run performance tests on my application. I created some small client hitting app every 5-30 minutes and I run 3-5 of threads with such client. I noticed huge differenced in response times and started to investigate issue. I found reason very quick. I am experiencing same issues as described in following topics: Uneven response time between connection to server to first byte sent Application instances seem to be too aggressively recycled Getting 'Request was aborted after waiting too long to attempt to service your request.' after application idle I am using Springframework, it tkes around 18-20s to start app instance, which is causing response times to take from 1s (when requests hits running app - very rare) to 22s when fresh application is created. Is there any solution for this? I was thinking about creating most basic servlet performing critical tasks (serving API call) and leave UI as is. But then I would loose all benefits of Springframework. Is there any solution for this? After solving (hacking) numerous constrains of App Engine which I hit while developing my app that is the one I think will make me move out of App Engine... that's simply to much to all the time think how to win with GAE problems than how to solve my application problems... Any help? Regards Konrad

    Read the article

< Previous Page | 49 50 51 52 53 54 55 56 57 58 59 60  | Next Page >