Search Results

Search found 2200 results on 88 pages for 'human factors'.

Page 80/88 | < Previous Page | 76 77 78 79 80 81 82 83 84 85 86 87  | Next Page >

  • Stack and queue operations on the same array.

    - by Passonate Learner
    Hi. I've been thinking about a program logic, but I cannot draw a conclusion to my problem. Here, I've implemented stack and queue operations to a fixed array. int A[1000]; int size=1000; int top; int front; int rear; bool StackIsEmpty() { return (top==0); } bool StackPush( int x ) { if ( top >= size ) return false; A[top++] = x; return true; } int StackTop( ) { return A[top-1]; } bool StackPop() { if ( top <= 0 ) return false; A[--top] = 0; return true; } bool QueueIsEmpty() { return (front==rear); } bool QueuePush( int x ) { if ( rear >= size ) return false; A[rear++] = x; return true; } int QueueFront( ) { return A[front]; } bool QueuePop() { if ( front >= rear ) return false; A[front++] = 0; return true; } It is presumed(or obvious) that the bottom of the stack and the front of the queue is pointing at the same location, and vice versa(top of the stack points the same location as rear of the queue). For example, integer 1 and 2 is inside an array in order of writing. And if I call StackPop(), the integer 2 will be popped out, and if I call QueuePop(), the integer 1 will be popped out. My problem is that I don't know what happens if I do both stack and queue operations on the same array. The example above is easy to work out, because there are only two values involved. But what if there are more than 2 values involved? For example, if I call StackPush(1); QueuePush(2); QueuePush(4); StackPop(); StackPush(5); QueuePop(); what values will be returned in the order of bottom(front) from the final array? I know that if I code a program, I would receive a quick answer. But the reason I'm asking this is because I want to hear a logical explanations from a human being, not a computer.

    Read the article

  • Qt vs .NET - a few comparisons [closed]

    - by Pirate for Profit
    Event Handling In Qt the event handling system you just emit signals when something cool happens and then catch them in slots, for instance emit valueChanged(int percent, bool something); and void MyCatcherObj::valueChanged(int p, bool ok){} blocking them and disconnecting them when needed, doing it across threads... once you get the hang of it, it just seems a lot more natural and intuitive than the way the .NET event handling is set up (you know, object sender, CustomEventArgs e). And I'm not just talking about syntax, because in the end the .NET delegate crap is the bomb. I'm also talking about in more than just reflection (because, yes, .NET obviously has much stronger reflection capabilities). I'm talking about in the way the system feels to a human being. Qt wins hands down i m o. Basically, the footprints make more sense and you can visualize the project easier without the clunky event handling system. I wish I could it explain it better. The only thing is, I do love some of the ease of C# compared to C++ and .NET's assembly architecture. That is a big bonus for modular projects, which are a PITA to do in C++. Database Ease of Doing Crap Also what about datasets and database manipulations. I think .net wins here but I'm not sure. Threading/Conccurency How do you guys think of the threading? In .NET, all I've ever done is make like a list of master worker threads with locks. I like QConcurrentFramework, you don't worry about locks or anything, and with the ease of the signal slot system across threads it's nice to get notified about the progress of things. Memory Usage Also what do you think of the overall memory usage comparison. Is the .NET garbage collector pretty on the ball and quick compared to the instantaneous nature of native memory management? Or does it just let programs leak up a storm and lag the computer then clean it up when it's about to really lag? However, I am a n00b who doesn't know what I'm talking about, please school me on the subject.

    Read the article

  • Classifying captured data in unknown format?

    - by monch1962
    I've got a large set of captured data (potentially hundreds of thousands of records), and I need to be able to break it down so I can both classify it and also produce "typical" data myself. Let me explain further... If I have the following strings of data: 132T339G1P112S 164T897F5A498S 144T989B9B223T 155T928X9Z554T ... you might start to infer the following: possibly all strings are 14 characters long the 4th, 8th, 10th and 14th characters may always be alphas, while the rest are numeric the first character may always be a '1' the 4th character may always be the letter 'T' the 14th character may be limited to only being 'S' or 'T' and so on... As you get more and more samples of real data, some of these "rules" might disappear; if you see a 15 character long string, then you have evidence that the 1st "rule" is incorrect. However, given a sufficiently large sample of strings that are exactly 14 characters long, you can start to assume that "all strings are 14 characters long" and assign a numeric figure to your degree of confidence (with an appropriate set of assumptions around the fact that you're seeing a suitably random set of all possible captured data). As you can probably tell, a human can do a lot of this classification by eye, but I'm not aware of libraries or algorithms that would allow a computer to do it. Given a set of captured data (significantly more complex than the above...), are there libraries that I can apply in my code to do this sort of classification for me, that will identify "rules" with a given degree of confidence? As a next step, I need to be able to take those rules, and use them to create my own data that conforms to these rules. I assume this is a significantly easier step than the classification, but I've never had to perform a task like this before so I'm really not sure how complex it is. At a guess, Python or Java (or possibly Perl or R) are possibly the "common" languages most likely to have these sorts of libraries, and maybe some of the bioinformatic libraries do this sort of thing. I really don't care which language I have to use; I need to solve the problem in whatever way I can. Any sort of pointer to information would be very useful. As you can probably tell, I'm struggling to describe this problem clearly, and there may be a set of appropriate keywords I can plug into Google that will point me towards the solution. Thanks in advance

    Read the article

  • How to show percentage of 'memory used' in a win32 process?

    - by pj4533
    I know that memory usage is a very complex issue on Windows. I am trying to write a UI control for a large application that shows a 'percentage of memory used' number, in order to give the user an indication that it may be time to clear up some memory, or more likely restart the application. One implementation used ullAvailVirtual from MEMORYSTATUSEX as a base, then used HeapWalk() to walk the process heap looking for additional free memory. The HeapWalk() step was needed because we noticed that after a while of running the memory allocated and freed by the heap was never returned and reported by the ullAvailVirtual number. After hours of intensive working, the ullAvailVirtual number no longer would accurately report the amount of memory available. However, this method proved not ideal, due to occasional odd errors that HeapWalk() would return, even when the process heap was not corrupted. Further, since this is a UI control, the heap walking code was executing every 5-10 seconds. I tried contacting Microsoft about why HeapWalk() was failing, escalated a case via MSDN, but never got an answer other than "you probably shouldn't do that". So, as a second implementation, I used PagefileUsage from PROCESS_MEMORY_COUNTERS as a base. Then I used VirtualQueryEx to walk the virtual address space adding up all regions that weren't MEM_FREE and returned a value for GetMappedFileNameA(). My thinking was that the PageFileUsage was essentially 'private bytes' so if I added to that value the total size of the DLLs my process was using, it would be a good approximation of the amount of memory my process was using. This second method seems to (sorta) work, at least it doesn't cause crashes like the heap walker method. However, when both methods are enabled, the values are not the same. So one of the methods is wrong. So, StackOverflow world...how would you implement this? which method is more promising, or do you have a third, better method? should I go back to the original method, and further debug the odd errors? should I stay away from walking the heap every 5-10 seconds? Keep in mind the whole point is to indicate to the user that it is getting 'dangerous', and they should either free up memory or restart the application. Perhaps a 'percentage used' isn't the best solution to this problem? What is? Another idea I had was a color based system (red, yellow, green, which I could base on more factors than just a single number)

    Read the article

  • Algorithm to retrieve every possible combination of sublists of a two lists

    - by sgmoore
    Suppose I have two lists, how do I iterate through every possible combination of every sublist, such that each item appears once and only once. I guess an example could be if you have employees and jobs and you want split them into teams, where each employee can only be in one team and each job can only be in one team. Eg List<string> employees = new List<string>() { "Adam", "Bob"} ; List<string> jobs = new List<string>() { "1", "2", "3"}; I want Adam : 1 Bob : 2 , 3 Adam : 1 , 2 Bob : 3 Adam : 1 , 3 Bob : 2 Adam : 2 Bob : 1 , 3 Adam : 2 , 3 Bob : 1 Adam : 3 Bob : 1 , 2 Adam, Bob : 1, 2, 3 I tried using the answer to this stackoverflow question to generate a list of every possible combination of employees and every possible combination of jobs and then select one item from each from each list, but that's about as far as I got. I don't know the maximum size of the lists, but it would be certainly be less than 100 and there may be other limiting factors (such as each team can have no more than 5 employees) Update Not sure whether this can be tidied up more and/or simplified, but this is what I have ended up with so far. It uses the Group algorithm supplied by Yorye (see his answer below), but I removed the orderby which I don't need and caused problems if the keys are not comparable. var employees = new List<string>() { "Adam", "Bob" } ; var jobs = new List<string>() { "1", "2", "3" }; int c= 0; foreach (int noOfTeams in Enumerable.Range(1, employees.Count)) { var hs = new HashSet<string>(); foreach( var grouping in Group(Enumerable.Range(1, noOfTeams).ToList(), employees)) { // Generate a unique key for each group to detect duplicates. var key = string.Join(":" , grouping.Select(sub => string.Join(",", sub))); if (!hs.Add(key)) continue; List<List<string>> teams = (from r in grouping select r.ToList()).ToList(); foreach (var group in Group(teams, jobs)) { foreach (var sub in group) { Console.WriteLine(String.Join(", " , sub.Key ) + " : " + string.Join(", ", sub)); } Console.WriteLine(); c++; } } } Console.WriteLine(String.Format("{0:n0} combinations for {1} employees and {2} jobs" , c , employees.Count, jobs.Count)); Since I'm not worried about the order of the results, this seems to give me what I need.

    Read the article

  • TicTacToe AI Making Incorrect Decisions

    - by Chris Douglass
    A little background: as a way to learn multinode trees in C++, I decided to generate all possible TicTacToe boards and store them in a tree such that the branch beginning at a node are all boards that can follow from that node, and the children of a node are boards that follow in one move. After that, I thought it would be fun to write an AI to play TicTacToe using that tree as a decision tree. TTT is a solvable problem where a perfect player will never lose, so it seemed an easy AI to code for my first time trying an AI. Now when I first implemented the AI, I went back and added two fields to each node upon generation: the # of times X will win & the # of times O will win in all children below that node. I figured the best solution was to simply have my AI on each move choose and go down the subtree where it wins the most times. Then I discovered that while it plays perfect most of the time, I found ways where I could beat it. It wasn't a problem with my code, simply a problem with the way I had the AI choose it's path. Then I decided to have it choose the tree with either the maximum wins for the computer or the maximum losses for the human, whichever was more. This made it perform BETTER, but still not perfect. I could still beat it. So I have two ideas and I'm hoping for input on which is better: 1) Instead of maximizing the wins or losses, instead I could assign values of 1 for a win, 0 for a draw, and -1 for a loss. Then choosing the tree with the highest value will be the best move because that next node can't be a move that results in a loss. It's an easy change in the board generation, but it retains the same search space and memory usage. Or... 2) During board generation, if there is a board such that either X or O will win in their next move, only the child that prevents that win will be generated. No other child nodes will be considered, and then generation will proceed as normal after that. It shrinks the size of the tree, but then I have to implement an algorithm to determine if there is a one move win and I think that can only be done in linear time (making board generation a lot slower I think?) Which is better, or is there an even better solution?

    Read the article

  • How to find relation between change in latitudes at centre of map and top/bottom

    - by Imran
    Hi, Im having little trouble finding a relation between the movement at centre and edge of a circle, Im doing for panning world map,my map extent is 180,89:-180,-89, my map pans by adding change(dx,dY) to its extents and not its centre. Now a situation has arrrised where I have to move the map to a specific centre, to calculate the change in longitudes is very easy and simple, but its the change in lattitudes that has caused problem. It seems the change in centreY of map is more than the change at edge of the mapY, or simply if I have to move the map centre from 0long,0lat to 73long,33lat, for dX I simply get 73, but for dY apparently it looks 33 but if i add 33 to top of map that is 89 , it will be 122 which is incorrect since Latitudes are between 90 and -90 . It seems a case a projection of a circle on 2D plane where the edge of circle since is moving backward due to angle expereinces less change and the centre expereinces more change, now is there a relation between these two factors? I tried converting the difference between OriginY and destinationY into radians and then add to Top and Bottom of Map, but it did'nt really work for me. Please note that the map is project on a virtual canvas whose width starts from 256 and increases by 256*2^z , z=0 is default and whole world is visible at that extent of canvas code: public void moveMapTo(double destinationLongitude,double destinationLattitude) // moves map to the new centre { double dXLong=destinationLongitude-centreLongitude; double atanhsinO = atanh(Math.sin(destinationLattitude * Math.PI / 180.00)); double atanhsinD = atanh(Math.sin(centreLatitude * Math.PI / 180.00)); double atanhCentre = (atanhsinD + atanhsinO) / 2; double latitudeSpan =destinationLattitude - centreLatitude; double radianOfCentreLatitude = Math.atan(Math.sinh(atanhCentre)); double dXLat=latitudeSpan / Math.cos(radianOfCentreLatitude); dXLat*=getLattitudeSpan()*(Math.PI/180); <--- HERE IS THE PORBLEM System.out.println("dxLong:"+dXLong+"_dxLat:"+dXLat); mapLeft+=dXLong; mapRight+=dXLong; mapTop+=dXLat; mapBottom+=dXLat; } ////latitude span function private double getLattitudeSpan() { double latitudeSpan = mapTop - mapBottom; latitudeSpan = latitudeSpan / Math.cos(radianOfCentreLatitude); return Math.abs(latitudeSpan); } //ht

    Read the article

  • random, Graphics point ,searching- algorithm, via dual for loop set

    - by LoneXcoder
    hello and thanks for joining me in my journey to the custom made algorithm for "guess where the pixel is" this for Loop set (over Point.X, Point.Y), is formed in consecutive/linear form: //Original\initial Location Point initPoint = new Point(150, 100); // No' of pixels to search left off X , and above Y int preXsrchDepth, preYsrchDepth; // No' of pixels to search to the right of X, And Above Y int postXsrchDepth, postYsrchDepth; preXsrchDepth = 10; // will start search at 10 pixels to the left from original X preYsrchDepth = 10; // will start search at 10 pixels above the original Y postXsrchDepth = 10; // will stop search at 10 pixels to the right from X postYsrchDepth = 10; // will stop search at 10 pixels below Y int StopXsearch = initPoint.X + postXsrchDepth; //stops X Loop itarations at initial pointX + depth requested to serch right of it int StopYsearch = initPoint.Y + postYsrchDepth; //stops Y Loop itarations at initial pointY + depth requested below original location int CountDownX, CountDownY; // Optional not requierd for loop but will reports the count down how many iterations left (unless break; triggerd ..uppon success) Point SearchFromPoint = Point.Empty; //the point will be used for (int StartX = initPoint.X - preXsrchDepth; StartX < StopXsearch; StartX++) { SearchFromPoint.X = StartX; for (int StartY = initPoint.Y - preYsrchDepth; StartY < StpY; StartY++) { CountDownX = (initPoint.X - StartX); CountDownY=(initPoint.Y - StartY); SearchFromPoint.Y = StartY; if (SearchSuccess) { same = true; AAdToAppLog("Search Report For: " + imgName + "Search Completed Successfully On Try " + CountDownX + ":" + CountDownY); break; } } } <-10 ---- -5--- -1 X +1--- +5---- +10 what i would like to do is try a way of instead is have a little more clever approach <+8---+5-- -8 -5 -- +2 +10 X -2 - -10 -8-- -6 ---1- -3 | +8 | -10 Y +1 -6 | | +9 .... I do know there's a wheel already invented in this field (even a full-trailer truck amount of wheels (: ) but as a new programmer, I really wanted to start of with a simple way and also related to my field of interest in my project. can anybody show an idea of his, he learnt along the way to Professionalism in algorithm /programming having tests to do on few approaches (kind'a random cleverness...) will absolutely make the day and perhaps help some others viewing this page in the future to come it will be much easier for me to understand if you could use as much as possible similar naming to variables i used or implenet your code example ...it will be Greatly appreciated if used with my code sample, unless my metod is a realy flavorless. p.s i think that(atleast as human being) the tricky part is when throwing inconsecutive numbers you loose track of what you didn't yet use, how do u take care of this too . thanks allot in advance looking forward to your participation !

    Read the article

  • how can we use AsynCallback method of web service in asp.net

    - by sameer
    Hi All, I was going through the proxy class which is generated using wsdl.exe found the asyncmethod like BeginAsynXXX() and EndAsyncXXX(). i understood how to utilize them on Windows application but i was wondering how can we use them in Web Application built using asp.net here is the code for web service client build as windows application.can any tell me how we can do this with web application. using System; using System.Runtime.Remoting.Messaging; using MyFactorize; class TestCallback { public static void Main(){ long factorizableNum = 12345; PrimeFactorizer pf = new PrimeFactorizer(); //Instantiate an AsyncCallback delegate to use as a parameter //in the BeginFactorize method. AsyncCallback cb = new AsyncCallback(TestCallback.FactorizeCallback); // Begin the Async call to Factorize, passing in our // AsyncCalback delegate and a reference // to our instance of PrimeFactorizer. IAsyncResult ar = pf.BeginFactorize(factorizableNum, cb, pf); // Keep track of the time it takes to complete the async call // as the call proceeds. int start = DateTime.Now.Second; int currentSecond = start; while (ar.IsCompleted == false){ if (currentSecond < DateTime.Now.Second) { currentSecond = DateTime.Now.Second; Console.WriteLine("Seconds Elapsed..." + (currentSecond - start).ToString() ); } } // Once the call has completed, you need a method to ensure the // thread executing this Main function // doesn't complete prior to the call-back function completing. Console.Write("Press Enter to quit"); int quitchar = Console.Read(); } // Set up a call-back function that is invoked by the proxy class // when the asynchronous operation completes. public static void FactorizeCallback(IAsyncResult ar) { // You passed in our instance of PrimeFactorizer in the third // parameter to BeginFactorize, which is accessible in the // AsyncState property. PrimeFactorizer pf = (PrimeFactorizer) ar.AsyncState; long[] results; // Get the completed results. results = pf.EndFactorize(ar); //Output the results. Console.Write("12345 factors into: "); int j; for (j = 0; j<results.Length;j++){ if (j == results.Length - 1) Console.WriteLine(results[j]); else Console.Write(results[j] + ", "); } } }

    Read the article

  • Can GPU capabilities impact virtual machine performance?

    - by Dave White
    While this many not seem like a programming question directly, it impacts my development activities and so it seems like it belongs here. It seems that more and more developers are turning to virtual environments for development activities on their computers, SharePoint development being a prime example. Also, as a trainer, I have virtual training environments for all of the classes that I teach. I recently purchased a new Dell E6510 to travel around with. It has the i7 620M (Dual core, HyperThreaded cpu running at 2.66GHz) and 8 GB of memory. Reading the spec sheet, it sounded like it would be a great laptop to carry around and run virtual machines on. Getting the laptop though, I've been pretty disappointed with the user experience of developing in a virtual machine. Giving the Virtual Machine 4 GB of memory, it was slow and I could type complete sentences and watch the VM "catchup". My company has training laptops that we provide for our classes. They are Dell Precision M6400 Intel Core 2 Duo P8700 running at 2.54Ghz with 8 GB of memory and the experience on this laptops is night and day compared to the E6510. They are crisp and you barely aware that you are running in a virtual environment. Since the E6510 should be faster in all categories than the M6400, I couldn't understand why the new laptop was slower, so I did a component by component comparison and the only place where the E6510 is less performant than the M6400 is the graphics department. The M6400 is running a nVidia FX 2700m GPU and the E6510 is running a nVidia 3100M GPU. Looking at benchmarks of the two GPUs suggest that the FX 2700M is twice as fast as the 3100M. http://www.notebookcheck.net/Mobile-Graphics-Cards-Benchmark-List.844.0.html 3100M = 111th (E6510) FX 2700m = 47th (Precision M6400) Radeon HD 5870 = 8th (Alienware) The host OS is Windows 7 64bit as is the guest OS, running in Virtual Box 3.1.8 with Guest Additions installed on the guest. The IDE being used in the virtual environment is VS 2010 Premium. So after that long setup, my question is: Is the GPU significantly impacting the virtual machine's performance or are there other factors that I'm not looking at that I can use to boost the vm's performance? Do we now have to consider GPU performance when purchasing laptops where we expect to use virtualized development environments? Thanks in advance. Cheers, Dave

    Read the article

  • Algorithm for finding symmetries of a tree

    - by Paxinum
    I have n sectors, enumerated 0 to n-1 counterclockwise. The boundaries between these sectors are infinite branches (n of them). The sectors live in the complex plane, and for n even, sector 0 and n/2 are bisected by the real axis, and the sectors are evenly spaced. These branches meet at certain points, called junctions. Each junction is adjacent to a subset of the sectors (at least 3 of them). Specifying the junctions, (in pre-fix order, lets say, starting from junction adjacent to sector 0 and 1), and the distance between the junctions, uniquely describes the tree. Now, given such a representation, how can I see if it is symmetric wrt the real axis? For example, n=6, the tree (0,1,5)(1,2,4,5)(2,3,4) have three junctions on the real line, so it is symmetric wrt the real axis. If the distances between (015) and (1245) is equal to distance from (1245) to (234), this is also symmetric wrt the imaginary axis. The tree (0,1,5)(1,2,5)(2,4,5)(2,3,4) have 4 junctions, and this is never symmetric wrt either imaginary or real axis, but it has 180 degrees rotation symmetry if the distance between the first two and the last two junctions in the representation are equal. Edit: This is actually for my research. I have posted the question at mathoverflow as well, but my days in competition programming tells me that this is more like an IOI task. Code in mathematica would be excellent, but java, python, or any other language readable by a human suffices. Here are some examples (pretend the double edges are single and we have a tree) http://www2.math.su.se/~per/files.php?file=contr_ex_1.pdf http://www2.math.su.se/~per/files.php?file=contr_ex_2.pdf http://www2.math.su.se/~per/files.php?file=contr_ex_5.pdf Example 1 is described as (0,1,4)(1,2,4)(2,3,4)(0,4,5) with distances (2,1,3). Example 2 is described as (0,1,4)(1,2,4)(2,3,4)(0,4,5) with distances (2,1,1). Example 5 is described as (0,1,4,5)(1,2,3,4) with distances (2). So, given the description/representation, I want to find some algorithm to decide if it is symmetric wrt real, imaginary, and rotation 180 degrees. The last example have 180 degree symmetry. (These symmetries corresponds to special kinds of potential in the Schroedinger equation, which has nice properties in quantum mechanics.)

    Read the article

  • Is it possible to access variable of subclass using object of superclass in polymorphism

    - by fari
    how can i access state varibale of class keyboard with object of class kalaplayer /** * An abstract class representing a player in Kala. Extend this class * to make your own players (e.g. human players entering moves at the keyboard * or computer players with programmed strategies for making moves). */ public abstract class KalaPlayer { /** * Method by which a player selects a move. * @param gs The current game state * @return A side pit number in the range 1-6 * @throws NoMoveAvailableException if all side pits for the player are empty * (i.e. the game is over) */ public abstract int chooseMove(KalaGameState gs) throws NoMoveAvailableException; } public class KeyBoardPlayer extends KalaPlayer { /** * Method by which a player selects a move. * @param gs The current game state * @return A side pit number in the range 1-6 * @throws NoMoveAvailableException if all side pits for the player are empty * (i.e. the game is over) */ public KalaGameState state; public KeyBoardPlayer() { System.out.println("Enter the number of stones to play with: "); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int key = Integer.parseInt(br.readLine()); state=new KalaGameState(key); //key=player1.state.turn; } catch(IOException e) { System.out.println(e); } } public int chooseMove(KalaGameState gs) throws NoMoveAvailableException{ return 0; } } import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; public class KalaGame { KalaPlayer player1,player2; public KalaGame(KeyBoardPlayer Player1,KeyBoardPlayer Player2) { //super(0); player1=new KeyBoardPlayer(); player2 = new KeyBoardPlayer(); //player1=Player1; //player2=Player2; //player1.state ****how can i access the stae variable from Keyboard CLass using object from KalaPlayer key=player1.state.turn; } public void play() { System.out.println("Enter the number of stones to play with: "); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int key = Integer.parseInt(br.readLine()); System.out.println(key); KalaGameState state=new KalaGameState(key); printGame(); } catch(IOException e) { System.out.println(e); } }

    Read the article

  • Executing a .NET Managed Assembly from SQL Server 2008 - Pro's, Con's & Recommendations

    - by RPM1984
    Hi guys, looking for opinions/recommendations/links for the following scenario im currently facing. The Platform: .NET 4.0 Web Application SQL Server 2008 The Task: Overhaul a component of the system that performs (fairly) complex mathematical operations based on a specific user activity, and updates numerous tables in the database. A common user activity might be "Bob" decides to post a forum topic. This results in (the end-solution) needing to look at various factors (about the post he did), then after doing some math based on lookup values/ratios as well as other data in the database, inserting some other data as a result of these operations. The Options: Ok - so here's what im thinking. Although it would be much easier to do this in C# (LINQ-SQL) it doesnt make much sense as the majority of the computations are based on values in the db, and it will get difficult to control/optimize/debug the LINQ over time. Hence, im leaning towards created a managed assembly (C# Class Library) that contains the lookup values (constants) as well as leveraging the math classes in the existing .NET BCL. Basically i'd expose a few methods that can be called by the T-SQL Stored Procedures. This to me has the following advantages: Simplicity of math. Do complex math in .NET vs complex math in T-SQL. No brainer. =) Abstraction of computatations, configurable "lookup" values and business logic from raw T-SQL. T-SQL only needs to care about the data, simplifying the stored procedures and making it easier to maintain. When it needs to do math it delegates off to the managed assembly. So, having said that - ive never done this before (call .NET assmembly from T-SQL), and after some googling the best site i could come up with is here, which is useful but outdated. So - what am i asking? Well, firstly - i need some better references on how to actually do this. "This" being how to call a C# .NET 4 Assembly from within T-SQL Stored Procedures in SQL Server 2008. Secondly, who out there has done this, what problems (if any) did you face? Realize this may be difficult to provide a "correct answer", so ill try to give it to whoever gives me the answer with a combination of good links and a list of pro's/con's/problems with this implementation. Cheers!

    Read the article

  • When is ¦ not equal to ¦?

    - by Trey Jackson
    Background. I'm working with netlists, and in general, people specify different hierarchies by using /. However, it's not illegal to actually use a / as a part of an instance name. For example, X1/X2/X3/X4 might refer to instance X4 inside another instance named X1/X2/X3. Or it might refer an instance named X3/X4 inside an instance named X2 inside an instance named X1. Got it? There's really no "regular" character that cannot be used as a part of an instance name, so you resort to a non-printable one, or ... perhaps one outside of the standard 0..127 ASCII chars. I thought I'd try (decimal) 166, because for me it shows up as the pipe: ¦. So... I've got some C++ code which constructs the path name using ¦ as the hierarchical separator, so the path above looks like X1¦X2/X3¦X4. Now the GUI is written in Tcl/Tk, and to properly translate this into human readable terms I need to do something like the following: set path [getPathFromC++] ;# returns X1¦X2/X3¦X4 set humanreadable [join [split $path ¦] /] Basically, replace the ¦ with / (I could also accomplish this with [string map]). Now, the problem is, the ¦ in the string I get from C++ doesn't match the ¦ I can create in Tcl. i.e. This fails: set path [getPathFromC++] ;# returns X1¦X2/X3¦X4 string match $path [format X1%cX2/X3%cX4 166 166] Visually, the two strings look identical, but string match fails. I even tried using scan to see if I'd mixed up the bit values. But set path [getPathFromC++] ;# returns X1¦X2/X3¦X4 set path2 [format X1%cX2/X3%cX4 166 166] for {set i 0} {$i < [string length $path]} {incr i} { set p [string range $path $i $i] set p2 [string range $path2 $i $i] scan %c $p c scan %c $p2 c2 puts [list $p $c :::: $p2 $c2 equal? [string equal $c $c2]] } Produces output which looks like everything should match, except the [string equal] fails for the ¦ characters with a print line: ¦ 166 :::: ¦ 166 equal? 0 For what it's worth, the character in C++ is defined as: const char SEPARATOR = 166; Any ideas why a character outside the regular ASCII range would fail like this? When I changed the separator to (decimal) 28 (^\), things worked fine. I just don't want to get bit by a similar problem on a different platform. (I'm currently using Redhat Linux).

    Read the article

  • File sizing issue in DOS/FAT

    - by Heather
    I've been tasked with writing a data collection program for a Unitech HT630, which runs a proprietary DOS operating system that can run executables compiled for 16-bit MS DOS with some restrictions. I'm using the Digital Mars C/C++ compiler, which is working well thus far. One of the application requirements is that the data file must be human-readable plain text, meaning the file can be imported into Excel or opened by Notepad. I'm using a variable length record format much like CSV that I've successfully implemented using the C standard library file I/O functions. When saving a record, I have to calculate whether the updated record is larger or smaller than the version of the record currently in the data file. If larger, I first shift all records immediately after the current record forward by the size difference calculated before saving the updated record. EOF is extended automatically by the OS to accommodate the extra data. If smaller, I shift all records backwards by my calculated offset. This is working well, however I have found no way to modify the EOF marker or file size to ignore the data after the end of the last record. Most of the time records will grow in size because the data collection program will be filling some of the empty fields with data when saving a record. Records will only shrink in size when a correction is made on an existing entry, or on a normal record save if the descriptive data in the record is longer than what the program reads in memory. In the situation of a shrinking record, after the last record in the file I'm left with whatever data was sitting there before the shift. I have been writing an EOF delimiter into the file after a "shrinking record save" to signal where the end of my records are and space-filling the remaining data, but then I no longer have a clean file until a "growing record save" extends the size of the file over the space-filled area. The truncate() function in unistd.h does not work (I'm now thinking this is for *nix flavors only?). One proposed solution I've seen involves creating a second file and writing all the data you wish to save into that file, and then deleting the original. Since I only have 4MB worth of disk space to use, this works if the file size is less than 2MB minus the size of my program executable and configuration files, but would fail otherwise. It is very likely that when this goes into production, users would end up with a file exceeding 2MB in size. I've looked at Ralph Brown's Interrupt List and the interrupt reference in IBM PC Assembly Language and Programming and I can't seem to find anything to update the file size or similar. Is reducing a file's size without creating a second file even possible in DOS?

    Read the article

  • SQLAlchemy unsupported type error - and table design issues?

    - by Az
    Hi there, back again with some more SQLAlchemy shenanigans. Let me step through this. My table is now set up as so: engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() students_table = Table('studs', metadata, Column('sid', Integer, primary_key=True), Column('name', String), Column('preferences', Integer), Column('allocated_rank', Integer), Column('allocated_project', Integer) ) metadata.create_all(engine) mapper(Student, students_table) Fairly simple, and for the most part I've been enjoying the ability to query almost any bit of information I want provided I avoid the error cases below. The class it is mapped from is: class Student(object): def __init__(self, sid, name): self.sid = sid self.name = name self.preferences = collections.defaultdict(set) self.allocated_project = None self.allocated_rank = 0 def __repr__(self): return str(self) def __str__(self): return "%s %s" %(self.sid, self.name) Explanation: preferences is basically a set of all the projects the student would prefer to be assigned. When the allocation algorithm kicks in, a student's allocated_project emerges from this preference set. Now if I try to do this: for student in students.itervalues(): session.add(student) session.commit() It throws two errors, one for the allocated_project column (seen below) and a similar error for the preferences column: sqlalchemy.exc.InterfaceError: (InterfaceError) Error binding parameter 4 - probably unsupported type. u'INSERT INTO studs (sid, name, allocated_rank, allocated_project) VALUES (?, ?, ?, ?, ?, ?, ?)' [1101, 'Muffett,M.', 1, 888 Human-spider relationships (Supervisor id: 123)] If I go back into my code I find that, when I'm copying the preferences from the given text files, it actually refers to the Project class which is mapped to a dictionary, using the unique project id's (pid) as keys. Thus, as I iterate through each student via their rank and to the preferences set, it adds not a project id, but the reference to the project id from the projects dictionary. students[sid].preferences[int(rank)].add(projects[int(pid)]) Now this is very useful to me since I can find out all I want to about a student's preferred projects without having to run another check to pull up information about the project id. The form you see in the error has the object print information passed as: return "%s %s (Supervisor id: %s)" %(self.proj_id, self.proj_name, self.proj_sup) My questions are: I'm trying to store an object in a database field aren't I? Would the correct way then, be copying the project information (project id, name, etc) into its own table, referenced by the unique project id? That way I can just have the project id field for one of the student tables just be an integer id and when I need more information, just join the tables? So and so forth for other tables? If the above makes sense, then how does one maintain the relationship with a column of information in one table which is a key index on another table? Does this boil down into a database design problem? Are there any other elegant ways of accomplishing this? Apologies if this is a very long-winded question. It's rather crucial for me to solve this, so I've tried to explain as much as I can, whilst attempting to show that I'm trying (key word here sadly) to understand what could be going wrong.

    Read the article

  • How to Sync CI (Hudson) Activity into an existing automated Build Process (phing, svn)?

    - by maraspin
    OUR CURRENT BUILD PROCESS We're a small team of developers (2 to 4 people depending on project) who currently use Phing to deploy code to a staging environment, before going live. We keep our code in a SVN repo, where the trunk holds current active development and, at certain times, we do make branches that we test and then (if successful), tag and export to the staging env. If everything goes well there too, we finally deploy'em in production servers. Actions are highly automated, but always triggered by human intervention. THE DOUBT We'd now like to introduce Continuous Integration (with Hudson) in the process; unfortunately we have a few doubts about activity syncing, since we're afraid that CI could somewhat interfere with our build process and cause certain problems. Considering that an automated CI cycle has a certain frequency of automatically executed actions, we see 2 possible cases for "integration", each with its own problems: Case A: each CI cycle produces a new branch with its own name; we do use such a name to manually (through phing as it happens now) export the code from the SVN to the staging env. The problem I see here is that (unless specific countermeasures are taken - IE deletion) the number of branches we have can easily grow out of control (let's suppose we commit often, so that we have a fresh new build/branch every N minutes). Case B: each CI cycle creates a new branch named 'current', which is then tagged with a unique name only when we manually decide to export it to staging; the current branch, at any case is then deleted, as soon as the next CI cycle starts up. The problem we see here is that a new cycle could kick in while someone is tagging/exporting the 'current' branch to staging thus creating an inconsistent build (but maybe here I'm just too pessimist, since I confess I don't know whether SVN offers some built-in protection against this). With all this being said, I was wondering if anyone with similar experiences could be so kind to give us some hints on the subject, since none of the approaches depicted above looks completely satisfing to us. Is there something important we just completely left off in the overall picture? Thanks for your attention & (in advance) for your help!

    Read the article

  • Codeigniter validation help

    - by Drew McGhie
    I'm writing a system where users can generate/run queries on demand based on the values of 4 dropdown lists. The lists are dynamically generated based on a number of factors, but at this point, I'm having problems validating the input using codeigniter's built in validation classes. I think I have things out of order, and I've tried looking at the codeigniter site, but I think I'm tripping myself up. in my view(/dashboard/dashboard_index.php), I have the following code block: <?=form_open('dashboard/dashboard_add');?> <select ... name='selMetric'> <select ... name='selPeriod'> <select ... name='selSpan'> <select ... name='selTactic'> <input type="submit" name="submit_new_query" value="Add New Graph" class="minbutton" ></input> <?=form_close();?> Then in my controller, I have the following 2 methods: function index() { $this->load->helper(array('form', 'url')); $this->load->library('validation'); //population of $data $this->load->tile('dashboard/dashboard_index', $data); } function dashboard_add() { $rules['selMetric'] = "callback_sel_check"; $rules['selPeriod'] = "callback_sel_check"; $rules['selSpan'] = "callback_sel_check"; $rules['selTactic'] = "callback_sel_check"; $this->validation->set_rules($rules); $fields['selMetric'] = "Metric"; $fields['selPeriod'] = "Time Period"; $fields['selSpan'] = "Time Span"; $fields['selTactic'] = "Tactic"; $this->validation->set_fields($fields); if ($this->validation->run() == false) { $this->index(); } else { //do stuff with validation information } } Here's my issue. I can get the stuff to validate correctly, but for the number of errors I have, I get Unable to access an error message corresponding to your field name. as the error message for everything. I think my issue that I have the $rules and $fields stuff in the wrong place, but I've tried a few permutations and I just keep getting it wrong. I was hoping I could get some advice on the correct place to put things.

    Read the article

  • Symfony2 Entity to array

    - by Adriano Pedro
    I'm trying to migrate my flat php project to Symfony2, but its coming to be very hard. For instance, I have a table of Products specification that have several specifications and are distinguishables by its "cat" attribute in that Extraspecs DB table. Therefore I've created a Entity for that table and want to make an array of just the specifications with "cat" = 0... I supose the code is this one.. right? $typeavailable = $this->getDoctrine() ->getRepository('LabsCatalogBundle:ProductExtraspecsSpecs') ->findBy(array('cat' => '0')); Now how can i put this in an array to work with a form like this?: form = $this ->createFormBuilder($product) ->add('specs', 'choice', array('choices' => $typeavailableArray), 'multiple' => true) Thank you in advance :) # Thank you all.. But now I've came across with another problem.. In fact i'm building a form from an existing object: $form = $this ->createFormBuilder($product) ->add('name', 'text') ->add('genspec', 'choice', array('choices' => array('0' => 'None', '1' => 'General', '2' => 'Specific'))) ->add('isReg', 'choice', array('choices' => array('0' => 'Material', '1' => 'Reagent', '2' => 'Antibody', '3' => 'Growth Factors', '4' => 'Rodents', '5' => 'Lagomorphs'))) So.. in that case my current value is named "extraspecs", so i've added this like: ->add('extraspecs', 'entity', array( 'label' => 'desc', 'empty_value' => ' --- ', 'class' => 'LabsCatalogBundle:ProductExtraspecsSpecs', 'property' => 'specsid', 'query_builder' => function(EntityRepository $er) { return $er ->createQueryBuilder('e'); But "extraspecs" come from a relationship of oneToMany where every product has several extraspecs... Here is the ORM: Labs\CatalogBundle\Entity\Product: type: entity table: orders__regmat id: id: type: integer generator: { strategy: AUTO } fields: name: type: string length: 100 catnumber: type: string scale: 100 brand: type: integer scale: 10 company: type: integer scale: 10 size: type: decimal scale: 10 units: type: integer scale: 10 price: type: decimal scale: 10 reqcert: type: integer scale: 1 isReg: type: integer scale: 1 genspec: type: integer scale: 1 oneToMany: extraspecs: targetEntity: ProductExtraspecs mappedBy: product Labs\CatalogBundle\Entity\ProductExtraspecs: type: entity table: orders__regmat__extraspecs fields: extraspecid: id: true type: integer unsigned: false nullable: false generator: strategy: IDENTITY regmatid: type: integer scale: 11 spec: type: integer scale: 11 attrib: type: string length: 20 value: type: string length: 200 lifecycleCallbacks: { } manyToOne: product: targetEntity: Product inversedBy: extraspecs joinColumn: name: regmatid referencedColumnName: id HOw should I do this? Thank you!!!

    Read the article

  • Overwhelmed by design patterns... where to begin?

    - by Pete
    I am writing a simple prototype code to demonstrate & profile I/O schemes (HDF4, HDF5, HDF5 using parallel IO, NetCDF, etc.) for a physics code. Since focus is on IO, the rest of the program is very simple: class Grid { public: floatArray x,y,z; }; class MyModel { public: MyModel(const int &nip1, const int &njp1, const int &nkp1, const int &numProcs); Grid grid; map<string, floatArray> plasmaVariables; }; Where floatArray is a simple class that lets me define arbitrary dimensioned arrays and do mathematical operations on them (i.e. x+y is point-wise addition). Of course, I could use better encapsulation (write accessors/setters, etc.), but that's not the concept I'm struggling with. For the I/O routines, I am envisioning applying simple inheritance: Abstract I/O class defines read & write functions to fill in the "myModel" object HDF4 derived class HDF5 HDF5 using parallel IO NetCDF etc... The code should read data in any of these formats, then write out to any of these formats. In the past, I would add an AbstractIO member to myModel and create/destroy this object depending on which I/O scheme I want. In this way, I could do something like: myModelObj.ioObj->read('input.hdf') myModelObj.ioObj->write('output.hdf') I have a bit of OOP experience but very little on the Design Patterns front, so I recently acquired the Gang of Four book "Design Patterns: Elements of Reusable Object-Oriented Software". OOP designers: Which pattern(s) would you recommend I use to integrate I/O with the myModel object? I am interested in answering this for two reasons: To learn more about design patterns in general Apply what I learn to help refactor an large old crufty/legacy physics code to be more human-readable & extensible. I am leaning towards applying the Decerator pattern to myModel, so I can attach the I/O responsibilities dynamically to myModel (i.e. whether to use HDF4, HDF5, etc.). However, I don't feel very confident that this is the best pattern to apply. Reading the Gang of Four book cover-to-cover before I start coding feels like a good way to develop an unhealthy caffeine addiction. What patterns do you recommend?

    Read the article

  • why java application not working after applying "web look and feel" theme?

    - by Vasu
    I have developed "Employee Management System" java project .For improving the ui appearance i have integrated "web look and feel" into my application.Theme is applied correctly. But here the problem arises: At first i have runned the java application without connecting to oracle data base,application have runned and worked perfectly. But when i connected the application to oracle database and runned again the application is taking more time to open and getting strucked. Code: For applying theme try { WebLookAndFeel.install(); }catch(Exception ex){ ex.printStackTrace(); } Code for Connecting DataBase: if (con == null) { File sd = new File(""); File in = new File(sd.getAbsolutePath() + File.separator + "conf.properties"); File dir = new File(sd.getAbsolutePath() + File.separator + "conf.properties"); if (!dir.exists()) { // dir.mkdir(); dir.createNewFile(); Properties pro = new Properties(); pro.load(new FileInputStream(in)); pro.setProperty("driverclass", "oracle.jdbc.driver.OracleDriver"); pro.setProperty("url", "jdbc:oracle:thin:@192.168.1.1:1521:main"); pro.setProperty("username", "gb16"); pro.setProperty("passwd", "gb16"); try { FileOutputStream out = new FileOutputStream(in); pro.store(out, "Human Management System initialization properties"); out.flush(); out.close();} catch(Exception e) { e.printStackTrace(); } } else { // System.out.println("Already exists "); } Properties pro = new Properties(); pro.load(new FileInputStream(in)); Class.forName(pro.getProperty("driverclass")); con = DriverManager.getConnection(pro.getProperty("url"), pro.getProperty("username"), pro.getProperty("passwd")); st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); } else { return con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); } without the theme the application with connected to database working correctly. Please help me in solving this issue. Thanks in advance..

    Read the article

  • writing XML with Xerces 3.0.1 and C++ on windows

    - by Jon
    Hi, i have the following function i wrote to create an XML file using Xerces 3.0.1, if i call this function with a filePath of "foo.xml" or "../foo.xml" it works great, but if i pass in "c:/foo.xml" then i get an exception on this line XMLFormatTarget *formatTarget = new LocalFileFormatTarget(targetPath); can someone explain why my code works for relative paths, but not absolute paths please? many thanks. const int ABSOLUTE_PATH_FILENAME_PREFIX_SIZE = 9; void OutputXML(xercesc::DOMDocument* pmyDOMDocument, std::string filePath) { //Return the first registered implementation that has the desired features. In this case, we are after a DOM implementation that has the LS feature... or Load/Save. DOMImplementation *implementation = DOMImplementationRegistry::getDOMImplementation(L"LS"); // Create a DOMLSSerializer which is used to serialize a DOM tree into an XML document. DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer(); // Make the output more human readable by inserting line feeds. if (serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)) serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); // The end-of-line sequence of characters to be used in the XML being written out. serializer->setNewLine(XMLString::transcode("\r\n")); // Convert the path into Xerces compatible XMLCh*. XMLCh *tempFilePath = XMLString::transcode(filePath.c_str()); // Calculate the length of the string. const int pathLen = XMLString::stringLen(tempFilePath); // Allocate memory for a Xerces string sufficent to hold the path. XMLCh *targetPath = (XMLCh*)XMLPlatformUtils::fgMemoryManager->allocate((pathLen + ABSOLUTE_PATH_FILENAME_PREFIX_SIZE) * sizeof(XMLCh)); // Fixes a platform dependent absolute path filename to standard URI form. XMLString::fixURI(tempFilePath, targetPath); // Specify the target for the XML output. XMLFormatTarget *formatTarget = new LocalFileFormatTarget(targetPath); //XMLFormatTarget *myFormTarget = new StdOutFormatTarget(); // Create a new empty output destination object. DOMLSOutput *output = ((DOMImplementationLS*)implementation)->createLSOutput(); // Set the stream to our target. output->setByteStream(formatTarget); // Write the serialized output to the destination. serializer->write(pmyDOMDocument, output); // Cleanup. serializer->release(); XMLString::release(&tempFilePath); delete formatTarget; output->release(); }

    Read the article

  • How to design service that can provide interface as JAX-WS web service, or via JMS, or as local meth

    - by kevinegham
    Using a typical JEE framework, how do I develop and deploy a service that can be called as a web service (with a WSDL interface), be invoked via JMS messages, or called directly from another service in the same container? Here's some more context: Currently I am responsible for a service (let's call it Service X) with the following properties: Interface definition is a human readable document kept up-to-date manually. Accepts HTTP form-encoded requests to a single URL. Sends plain old XML responses (no schema). Uses Apache to accept requests + a proprietary application server (not servlet or EJB based) containing all logic which runs in a seperate tier. Makes heavy use of a relational database. Called both by internal applications written in a variety of languages and also by a small number of third-parties. I want to (or at least, have been told to!): Switch to a well-known (pref. open source) JEE stack such as JBoss, Glassfish, etc. Split Service X into Service A and Service B so that we can take Service B down for maintenance without affecting Service A. Note that Service B will depend on (i.e. need to make requests to) Service A. Make both services easier for third parties to integrate with by providing at least a WS-I style interface (WSDL + SOAP + XML + HTTP) and probably a JMS interface too. In future we might consider a more lightweight API too (REST + JSON? Google Protocol Buffers?) but that's a nice to have. Additional consideration are: On a smaller deployment, Service A and Service B will likely to running on the same machine and it would seem rather silly for them to use HTTP or a message bus to communicate; better if they could run in the same container and make method calls to each other. Backwards compatibility with the existing ad-hoc Service X interface is not required, and we're not planning on re-using too much of the existing code for the new services. I'm happy with either contract-first (WSDL I guess) or (annotated) code-first development. Apologies if my terminology is a bit hazy - I'm pretty experienced with Java and web programming in general, but am finding it quite hard to get up to speed with all this enterprise / SOA stuff - it seems I have a lot to learn! I'm also not very used to using a framework rather than simply writing code that calls some packages to do things. I've got as far as downloading Glassfish, knocking up a simple WSDL file and using wsimport + a little dummy code to turn that into a WAR file which I've deployed.

    Read the article

  • Show/hide jQuery

    - by Banderdash
    Not much experience with JavaScript, hopefully one of you gurus can help. <div id="themes"> <h2>Research Themes</h2> <ul> <li><a href="">Learn about our approach to the <strong>environment</strong></a><span><a href="#">Expand</a></span></li> <ul class="tier_2 hide"> <li><a href="">Project name numero uno goes here</a></li> <li><a href="">Project name numero dos goes here</a></li> <li><a href="">Project name numero tres goes here</a></li> </ul> <li><a href="">Learn about our approach to <strong>human health</strong></a><span><a href="#">Expand</a></span></li> <ul class="tier_2 hide"> <li><a href="">Project name numero uno goes here</a></li> <li><a href="">Project name numero dos goes here</a></li> <li><a href="">Project name numero tres goes here</a></li> </ul> <li class="last"><a href="">Learn about our approach to <strong>national defense</strong></a><span><a href="#">Expand</a></span></li> <ul class="tier_2 hide"> <li><a href="">Project name numero uno goes here</a></li> <li><a href="">Project name numero dos goes here</a></li> <li><a href="">Project name numero tres goes here</a></li> </ul> </ul> </div><!-- // end themes --> This is my markup. As you can see under each of the first tier of li's there are ul's with classes of tier_2 and hide. I've been trying to create some simple jQuery that on click will remove the hide class from it's child ul, but at the same time check that no other ul's with class of tier_2 are shown (aka the other's have the hide class). This should keep a visitor from expanding so many items at once that it will make the layout look funky. Just not sure how to accomplish this, any ideas?

    Read the article

  • ASP.Net / MySQL : Translating content into several languages

    - by philwilks
    I have an ASP.Net website which uses a MySQL database for the back end. The website is an English e-commerce system, and we are looking at the possibility of translating it into about five other languages (French, Spanish etc). We will be getting human translators to perform the translation - we've looked at automated services but these aren't good enough. The static text on the site (e.g. headings, buttons etc) can easily be served up in multiple languages via .Net's built in localization features (resx files etc). The thing that I'm not so sure about it how best to store and retrieve the multi-language content in the database. For example, there is a products table that includes these fields... productId (int) categoryId (int) title (varchar) summary (varchar) description (text) features (text) The title, summary, description and features text would need to be available in all the different languages. Here are the two options that I've come up with... Create additional field for each language For example we could have titleEn, titleFr, titleEs etc for all the languages, and repeat this for all text columns. We would then adapt our code to use the appropriate field depending on the language selected. This feels a bit hacky, and also would lead to some very large tables. Also, if we wanted to add additional languages in the future it would be time consuming to add even more columns. Use a lookup table We could create a new table with the following format... textId | languageId | content ------------------------------- 10 | EN | Car 10 | FR | Voiture 10 | ES | Coche 11 | EN | Bike 11 | FR | Vélo We'd then adapt our products table to reference the appropriate textId for the title, summary, description and features instead of having the text stored in the product table. This seems much more elegant, but I can't think of a simple way of getting this data out of the database and onto the page without using complex SQL statements. Of course adding new languages in the future would be very simple compared to the previous option. I'd be very grateful for any suggestions about the best way to achieve this! Is there any "best practice" guidance out there? Has anyone done this before?

    Read the article

< Previous Page | 76 77 78 79 80 81 82 83 84 85 86 87  | Next Page >