Search Results

Search found 351 results on 15 pages for 'pseudocode'.

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

  • Do I need a helper column, or can I do this with a formula?

    - by dwwilson66
    I am using this formula =IF((LEFT($B26,2)="<p"),0,IF($B26="",0,IF($F26<>"",0,(FIND("""../",$B26))))) To parse data similar to the following. <nobr>&nbsp;&nbsp;&nbsp;&nbsp;contractor information</nobr><br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="../City_Electrical_Inspectors.htm"><b> City Electrical Inspectors</b></a><br> <nobr>&nbsp;&nbsp;&nbsp;&nbsp;<a href="../City_Electrical_Inspectors.htm"><b>inspection</b></a></nobr><br> My problem comes in cases such as the first line, in which the line is not a new paragraph nor a link, and my FIND returns an error of #VALUE! Id like to create an IF test to scan the line for the existence of the pattern in my FIND statement before processing that statement. I figured that looking for an error condition may be the way to go. However, the only way I can envision this is as a self-referential formula, similart to the following pseudocode. IF(ISERROR($L26)=TRUE,$L26=0,L$26=the-result-of-the-formula-above) Can this be done with a formula or do I need to use a new helper column? Thanks.

    Read the article

  • Wikipedia A* pathfinding algorithm takes a lot of time

    - by Vee
    I've successfully implemented A* pathfinding in C# but it is very slow, and I don't understand why. I even tried not sorting the openNodes list but it's still the same. The map is 80x80, and there are 10-11 nodes. I took the pseudocode from here Wikipedia And this is my implementation: public static List<PGNode> Pathfind(PGMap mMap, PGNode mStart, PGNode mEnd) { mMap.ClearNodes(); mMap.GetTile(mStart.X, mStart.Y).Value = 0; mMap.GetTile(mEnd.X, mEnd.Y).Value = 0; List<PGNode> openNodes = new List<PGNode>(); List<PGNode> closedNodes = new List<PGNode>(); List<PGNode> solutionNodes = new List<PGNode>(); mStart.G = 0; mStart.H = GetManhattanHeuristic(mStart, mEnd); solutionNodes.Add(mStart); solutionNodes.Add(mEnd); openNodes.Add(mStart); // 1) Add the starting square (or node) to the open list. while (openNodes.Count > 0) // 2) Repeat the following: { openNodes.Sort((p1, p2) => p1.F.CompareTo(p2.F)); PGNode current = openNodes[0]; // a) We refer to this as the current square.) if (current == mEnd) { while (current != null) { solutionNodes.Add(current); current = current.Parent; } return solutionNodes; } openNodes.Remove(current); closedNodes.Add(current); // b) Switch it to the closed list. List<PGNode> neighborNodes = current.GetNeighborNodes(); double cost = 0; bool isCostBetter = false; for (int i = 0; i < neighborNodes.Count; i++) { PGNode neighbor = neighborNodes[i]; cost = current.G + 10; isCostBetter = false; if (neighbor.Passable == false || closedNodes.Contains(neighbor)) continue; // If it is not walkable or if it is on the closed list, ignore it. if (openNodes.Contains(neighbor) == false) { openNodes.Add(neighbor); // If it isn’t on the open list, add it to the open list. isCostBetter = true; } else if (cost < neighbor.G) { isCostBetter = true; } if (isCostBetter) { neighbor.Parent = current; // Make the current square the parent of this square. neighbor.G = cost; neighbor.H = GetManhattanHeuristic(current, neighbor); } } } return null; } Here's the heuristic I'm using: private static double GetManhattanHeuristic(PGNode mStart, PGNode mEnd) { return Math.Abs(mStart.X - mEnd.X) + Math.Abs(mStart.Y - mEnd.Y); } What am I doing wrong? It's an entire day I keep looking at the same code.

    Read the article

  • Is this Hybrid of Interface / Composition kosher?

    - by paul
    I'm working on a project in which I'm considering using a hybrid of interfaces and composition as a single thing. What I mean by this is having a contain*ee* class be used as a front for functionality implemented in a contain*er* class, where the container exposes the containee as a public property. Example (pseudocode): class Visibility(lambda doShow, lambda doHide, lambda isVisible) public method Show() {...} public method Hide() {...} public property IsVisible public event Shown public event Hidden class SomeClassWithVisibility private member visibility = new Visibility(doShow, doHide, isVisible) public property Visibility with get() = visibility private method doShow() {...} private method doHide() {...} private method isVisible() {...} There are three reasons I'm considering this: The language in which I'm working (F#) has some annoyances w.r.t. implementing interfaces the way I need to (unless I'm missing something) and this will help avoid a lot of boilerplate code. The containee classes could really be considered properties of the container class(es); i.e. there seems to be a fairly strong has-a relationship. The containee classes will likely implement code which would have been pretty much the same when implemented in all the container classes, so why not do it once in one place? In the above example, this would include managing and emitting the Shown/Hidden events. Does anyone see any isseus with this Composiface/Intersition method, or know of a better way? EDIT 2012.07.26 - It seems a little background information is warranted: Where I work, we have a bunch of application front-ends that have limited access to system resources -- they need access to these resources to fully function. To remedy this we have a back-end application that can access the needed resources, with which the front-ends can communicate. (There is an API written for the front-ends for accessing back-end functionality as though it were part of the front-end.) The back-end program is out of date and its functionality is incomplete. It has made the transition from company to company a couple of times and we can't even compile it anymore. So I'm trying to rewrite it in my spare time. I'm trying to update things to make a nice(r) interface/API for the front-ends (while allowing for backwards compatibility with older front-ends), hopefully something full of OOPy goodness. The thing is, I don't want to write the front-end API after I've written pretty much the same code in F# for implementing the back-end; so, what I'm planning on doing is applying attributes to classes/methods/properties that I would like to have code for in the API then generate this code from the F# assembly using reflection. The method outlined in this question is a possible alternative I'm considering instead of implementing straight interfaces on the classes in F# because they're kind of a bear: In order to access something of an interface that has been implemented in a class, you have to explicitly cast an instance of that class to the interface type. This would make things painful when getting calls from the front-ends. If you don't want to have to do this, you have to call out all of the interface's methods/properties again in the class, outside of the interface implementation (which is separate from regular class members), and call the implementation's members. This is basically repeating the same code, which is what I'm trying to avoid!

    Read the article

  • Editing files without race conditions?

    - by user2569445
    I have a CSV file that needs to be edited by multiple processes at the same time. My question is, how can I do this without introducing race conditions? It's easy to write to the end of the file without race conditions by open(2)ing it in "a" (O_APPEND) mode and simply write to it. Things get more difficult when removing lines from the file. The easiest solution is to read the file into memory, make changes to it, and overwrite it back to the file. If another process writes to it after it is in memory, however, that new data will be lost upon overwriting. To further complicate matters, my platform does not support POSIX record locks, checking for file existence is a race condition waiting to happen, rename(2) replaces the destination file if it exists instead of failing, and editing files in-place leaves empty bytes in it unless the remaining bytes are shifted towards the beginning of the file. My idea for removing a line is this (in pseudocode): filename = "/home/user/somefile"; file = open(filename, "r"); tmp = open(filename+".tmp", "ax") || die("could not create tmp file"); //"a" is O_APPEND, "x" is O_EXCL|O_CREAT while(write(tmp, read(file)); //copy the $file to $file+".new" close(file); //edit tmp file unlink(filename) || die("could not unlink file"); file = open(filename, "wx") || die("another process must have written to the file after we copied it."); //"w" is overwrite, "x" is force file creation while(write(file, read(tmp))); //copy ".tmp" back to the original file unlink(filename+".tmp") || die("could not unlink tmp file"); Or would I be better off with a simple lock file? Appender process: lock = open(filename+".lock", "wx") || die("could not lock file"); file = open(filename, "a"); write(file, "stuff"); close(file); close(lock); unlink(filename+".lock"); Editor process: lock = open(filename+".lock", "wx") || die("could not lock file"); file = open(filename, "rw"); while(contents += read(file)); //edit "contents" write(file, contents); close(file); close(lock); unlink(filename+".lock"); Both of these rely on an additional file that will be left over if a process terminates before unlinking it, causing other processes to refuse to write to the original file. In my opinion, these problems are brought on by the fact that the OS allows multiple writable file descriptors to be opened on the same file at the same time, instead of failing if a writable file descriptor is already open. It seems that O_CREAT|O_EXCL is the closest thing to a real solution for preventing filesystem race conditions, aside from POSIX record locks. Another possible solution is to separate the file into multiple files and directories, so that more granular control can be gained over components (lines, fields) of the file using O_CREAT|O_EXCL. For example, "file/$id/$field" would contain the value of column $field of the line $id. It wouldn't be a CSV file anymore, but it might just work. Yes, I know I should be using a database for this as databases are built to handle these types of problems, but the program is relatively simple and I was hoping to avoid the overhead. So, would any of these patterns work? Is there a better way? Any insight into these kinds of problems would be appreciated.

    Read the article

  • How to correctly refactor this?

    - by kane77
    I have trouble finding way to correctly refactor this code so that there would be as little duplicate code as possible, I have a couple of methods like this (pseudocode): public List<Something> parseSomething(Node n){ List<Something> somethings = new ArrayList<Something>(); initialize(); sameCodeInBothClasses(); List<Node> nodes = getChildrenByName(n, "somename"); for(Node n:nodes){ method(); actionA(); somethings.add(new Something(actionB()); } return somethings; } methods sameCodeInBothClasses() are same in all classes but where it differs is what hapens in for loop actionA() and it also adds an element to the List of different type. Should I use Strategy pattern for the different parts inside loop? What about the return value (The type of list differs), should the method return just List<Object> that I would then cast to appropriate type? Should I pass the class I want to return as parameter?

    Read the article

  • Perl Curses::UI

    - by user353211
    I am trying to use the library Curses:UI from http://search.cpan.org/dist/Curses-UI/ to build a UI on linux karmic. I can create a simple user interface e.g.: #!usr/usr/bin/perl use strict; use Curses; use Curses::UI; $ui = new Curses::UI(-color_support=1,-clear_on_exit=1,-intellidraw=1); my $window = $ui-add('window', 'Window',intellidraw=1); my $message = $window-add(-text="Hello!",-intellidraw=1); $window-focus(); $ui-mainloop(); Question: I need some way to communicate informatio to the UI i.e. I have a loop which will wait for message to come and change the text in window. Once this message comes a popup will be displayed. Attempt: my $ui = new Curses::UI(-color_support=1,-clear_on_exit=1,-intellidraw=1); my $window = $ui-add('window', 'Window',intellidraw=1); my $message = $window-add(-text="Hello!",-intellidraw=1); pseudocode while(true) #implemented a function to wait { popup($window-text("Hello how are you?")); } $window-focus(); $ui-mainloop(); Problem: The above does not work. I am given a dark screen where my message is displayed. I have read the documentation and when I relocate : $ui-mainloop() above the while loop I am given the user interface but now nothing communicates to the window. Coincise Question: I need some way of displaying the user interface wait for inputs and display messages. Could anyone please help me on this? Thank you!

    Read the article

  • WPF UI Automation - AutomationElement.FindFirst fails when there are lots of elements

    - by Orion Edwards
    We've got some automated UI tests for our WPF app (.NET 4); these test use the UI Automation API's. We call AutomationElement.FindFirst to find a target element, and then interact with it. Example (pseudocode): var nameEquals = new PropertyCondition(AutomationElement.NameProperty, "OurAppWindow"); var appWindow = DesktopWindow.FindFirst(TreeScope.Children, nameEquals); // this succeeds var idEquals = new PropertyCondition(AutomationElement.AutomationIdProperty, "ControlId"); var someItem = appWindow.FindFirst(TreeScope.Descendants, idEquals); // this suceeds sometimes, and fails sometimes! The problem is, the appWindow.FindFirst will sometimes fail and return null, even when the element is present. I've written a helper function which walks the UI automation tree manually and prints it out, and the element with the correct ID is present in all cases. It seems to be related to how many other items are also being displayed in the window. If there are no other items then it always succeeds, but when there are many other complex UI elements being displayed alongside it, then the find fails. I can't find any documented element limit mentioned for any of the automation API's - is there some way around this? I'm thinking I might have to write my own implemententation of FindFirst which does the tree walk manually itself... As far as I can tell this should work, because my tree-printer utility function does exactly that, and it's ok, but it seems like this would be unnecessary and slow :-( Any help would be greatly appreciated

    Read the article

  • ASP MVC Ajax Controller pattern?

    - by Kevin Won
    My MVC app tends to have a lot of ajax calls (via JQuery.get()). It's sort of bugging me that my controller is littered with many tiny methods that get called via ajax. It seems to me to be sort of breaking the MVC pattern a bit--the controller is now being more of a data access component then a URI router. I refactored so that I have my 'true' controller for a page just performing standard routing responses (returing ActionResponse objects). So a call to /home/ will obviously kick up the HomeController class that will respond in the canonical controller fashion by returning a plain-jane View. I then moved my ajax stuff into a new controller class whose name I'm prefacing with 'Ajax'. So, for example, my page might have three different sections of functionality (say shopping cart or user account). I have an ajax controller for each of these (AjaxCartController, AjaxAccountController). There is really nothing different about moving the ajax call stuff into its own class--it's just to keep things cleaner. on client side obviously the JQuery would then use this new controller thusly: //jquery pseudocode call to specific controller that just handles ajax calls $.get('AjaxAccount/Details'.... (1) is there a better pattern in MVC for responding to ajax calls? (2) It seems to me that the MVC model is a bit leaky when it comes to ajax--it's not really 'controlling' stuff. It just happens to be the best and least painful way of handling ajax calls (or am I ignorant)? In other words, the 'Controller' abstraction doesn't seem to play nice with Ajax (at least from a patterns perspective). Is there something I'm missing?

    Read the article

  • JAVA image transfer problem

    - by user579098
    Hi, I have a school assignment, to send a jpg image,split it into groups of 100 bytes, corrupt it, use a CRC check to locate the errors and re-transmit until it eventually is built back into its original form. It's practically ready, however when I check out the new images, they appear with errors.. I would really appreciate if someone could look at my code below and maybe locate this logical mistake as I can't understand what the problem is because everything looks ok :S For the file with all the data needed including photos and error patterns one could download it from this link:http://rapidshare.com/#!download|932tl2|443122762|Data.zip|739 Thanks in advance, Stefan p.s dont forget to change the paths in the code for the image and error files package networks; import java.io.*; // for file reader import java.util.zip.CRC32; // CRC32 IEEE (Ethernet) public class Main { /** * Reads a whole file into an array of bytes. * @param file The file in question. * @return Array of bytes containing file data. * @throws IOException Message contains why it failed. */ public static byte[] readFileArray(File file) throws IOException { InputStream is = new FileInputStream(file); byte[] data=new byte[(int)file.length()]; is.read(data); is.close(); return data; } /** * Writes (or overwrites if exists) a file with data from an array of bytes. * @param file The file in question. * @param data Array of bytes containing the new file data. * @throws IOException Message contains why it failed. */ public static void writeFileArray(File file, byte[] data) throws IOException { OutputStream os = new FileOutputStream(file,false); os.write(data); os.close(); } /** * Converts a long value to an array of bytes. * @param data The target variable. * @return Byte array conversion of data. * @see http://www.daniweb.com/code/snippet216874.html */ public static byte[] toByta(long data) { return new byte[] { (byte)((data >> 56) & 0xff), (byte)((data >> 48) & 0xff), (byte)((data >> 40) & 0xff), (byte)((data >> 32) & 0xff), (byte)((data >> 24) & 0xff), (byte)((data >> 16) & 0xff), (byte)((data >> 8) & 0xff), (byte)((data >> 0) & 0xff), }; } /** * Converts a an array of bytes to long value. * @param data The target variable. * @return Long value conversion of data. * @see http://www.daniweb.com/code/snippet216874.html */ public static long toLong(byte[] data) { if (data == null || data.length != 8) return 0x0; return (long)( // (Below) convert to longs before shift because digits // are lost with ints beyond the 32-bit limit (long)(0xff & data[0]) << 56 | (long)(0xff & data[1]) << 48 | (long)(0xff & data[2]) << 40 | (long)(0xff & data[3]) << 32 | (long)(0xff & data[4]) << 24 | (long)(0xff & data[5]) << 16 | (long)(0xff & data[6]) << 8 | (long)(0xff & data[7]) << 0 ); } public static byte[] nextNoise(){ byte[] result=new byte[100]; // copy a frame's worth of data (or remaining data if it is less than frame length) int read=Math.min(err_data.length-err_pstn, 100); System.arraycopy(err_data, err_pstn, result, 0, read); // if read data is less than frame length, reset position and add remaining data if(read<100){ err_pstn=100-read; System.arraycopy(err_data, 0, result, read, err_pstn); }else // otherwise, increase position err_pstn+=100; // return noise segment return result; } /** * Given some original data, it is purposefully corrupted according to a * second data array (which is read from a file). In pseudocode: * corrupt = original xor corruptor * @param data The original data. * @return The new (corrupted) data. */ public static byte[] corruptData(byte[] data){ // get the next noise sequence byte[] noise = nextNoise(); // finally, xor data with noise and return result for(int i=0; i<100; i++)data[i]^=noise[i]; return data; } /** * Given an array of data, a packet is created. In pseudocode: * frame = corrupt(data) + crc(data) * @param data The original frame data. * @return The resulting frame data. */ public static byte[] buildFrame(byte[] data){ // pack = [data]+crc32([data]) byte[] hash = new byte[8]; // calculate crc32 of data and copy it to byte array CRC32 crc = new CRC32(); crc.update(data); hash=toByta(crc.getValue()); // create a byte array holding the final packet byte[] pack = new byte[data.length+hash.length]; // create the corrupted data byte[] crpt = new byte[data.length]; crpt = corruptData(data); // copy corrupted data into pack System.arraycopy(crpt, 0, pack, 0, crpt.length); // copy hash into pack System.arraycopy(hash, 0, pack, data.length, hash.length); // return pack return pack; } /** * Verifies frame contents. * @param frame The frame data (data+crc32). * @return True if frame is valid, false otherwise. */ public static boolean verifyFrame(byte[] frame){ // allocate hash and data variables byte[] hash=new byte[8]; byte[] data=new byte[frame.length-hash.length]; // read frame into hash and data variables System.arraycopy(frame, frame.length-hash.length, hash, 0, hash.length); System.arraycopy(frame, 0, data, 0, frame.length-hash.length); // get crc32 of data CRC32 crc = new CRC32(); crc.update(data); // compare crc32 of data with crc32 of frame return crc.getValue()==toLong(hash); } /** * Transfers a file through a channel in frames and reconstructs it into a new file. * @param jpg_file File name of target file to transfer. * @param err_file The channel noise file used to simulate corruption. * @param out_file The name of the newly-created file. * @throws IOException */ public static void transferFile(String jpg_file, String err_file, String out_file) throws IOException { // read file data into global variables jpg_data = readFileArray(new File(jpg_file)); err_data = readFileArray(new File(err_file)); err_pstn = 0; // variable that will hold the final (transfered) data byte[] out_data = new byte[jpg_data.length]; // holds the current frame data byte[] frame_orig = new byte[100]; byte[] frame_sent = new byte[100]; // send file in chunks (frames) of 100 bytes for(int i=0; i<Math.ceil(jpg_data.length/100); i++){ // copy jpg data into frame and init first-time switch System.arraycopy(jpg_data, i*100, frame_orig, 0, 100); boolean not_first=false; System.out.print("Packet #"+i+": "); // repeat getting same frame until frame crc matches with frame content do { if(not_first)System.out.print("F"); frame_sent=buildFrame(frame_orig); not_first=true; }while(!verifyFrame(frame_sent)); // usually, you'd constrain this by time to prevent infinite loops (in // case the channel is so wacked up it doesn't get a single packet right) // copy frame to image file System.out.println("S"); System.arraycopy(frame_sent, 0, out_data, i*100, 100); } System.out.println("\nDone."); writeFileArray(new File(out_file),out_data); } // global variables for file data and pointer public static byte[] jpg_data; public static byte[] err_data; public static int err_pstn=0; public static void main(String[] args) throws IOException { // list of jpg files String[] jpg_file={ "C:\\Users\\Stefan\\Desktop\\Data\\Images\\photo1.jpg", "C:\\Users\\Stefan\\Desktop\\Data\\Images\\photo2.jpg", "C:\\Users\\Stefan\\Desktop\\Data\\Images\\photo3.jpg", "C:\\Users\\Stefan\\Desktop\\Data\\Images\\photo4.jpg" }; // list of error patterns String[] err_file={ "C:\\Users\\Stefan\\Desktop\\Data\\Error Pattern\\Error Pattern 1.DAT", "C:\\Users\\Stefan\\Desktop\\Data\\Error Pattern\\Error Pattern 2.DAT", "C:\\Users\\Stefan\\Desktop\\Data\\Error Pattern\\Error Pattern 3.DAT", "C:\\Users\\Stefan\\Desktop\\Data\\Error Pattern\\Error Pattern 4.DAT" }; // loop through all jpg/channel combinations and run tests for(int x=0; x<jpg_file.length; x++){ for(int y=0; y<err_file.length; y++){ System.out.println("Transfering photo"+(x+1)+".jpg using Pattern "+(y+1)+"..."); transferFile(jpg_file[x],err_file[y],jpg_file[x].replace("photo","CH#"+y+"_photo")); } } } }

    Read the article

  • C#: How to parse a hexadecimal digit

    - by Biosci3c
    Okay, I am working on a card playing program, and I am storing card values as hexadecimal digits. Here is the array: public int[] originalCards = new int[54] { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x50, 0x51 }; The first digit refers to the suit (1 = spades; 2 = clubs; .... 5 = Jokers) The second digit is the number of the card (1 = ace, 5 = 5; 13 = K, etc). I would like to do something like the following: Pseudocode: public int ReturnCard(int num) { int card = currentDeck[num]; int suit = card.firsthexdigit; int value = card.secondhexdigit; return 0; } I don't need a new method to work on ints, I just included it for clarity's sake. Anybody know how to do this in C#?

    Read the article

  • Accessing XUL anonymous content using C++

    - by Vaibhav Gade
    Hi All, I am writing Firefox extension using C++. I am trying to access XUL:tabox element in "TabOpen" event handler, but I am unable access any XUL element. I am putting here pseudocode of my extension for reference: HandleEvent() { if (event type is TabOpen) { nsCOMPtr<nsIDOMNode> OriginalNode = do_QueryInterface(event->GetTarget); nsCOMPtr<nsIDOMNodeList> childlist; // // Note here that I got OriginalNode's local name as "tabbrowser" // OriginalNode->GetChildNodes(getter_AddRefs(childlist)); PRUint32 len; childlist->GetLength(&len); // Return 1; consider only "popup" child element. nsString localName; nsCOMPtr<nsIDOMNode> node1; childlist->Item(0, getter_AddRefs(node1)); node1->GetLocalName(localName); // Returns "popup" as the local name. } } By traversing the DOM tree through DOM Inspector, I came to know that XUL elements are anonymous content. How do I access these XUL elements? Very Thanks in advance, Vaibhav.

    Read the article

  • Better ways to implement a modulo operation (algorithm question)

    - by ryxxui
    I've been trying to implement a modular exponentiator recently. I'm writing the code in VHDL, but I'm looking for advice of a more algorithmic nature. The main component of the modular exponentiator is a modular multiplier which I also have to implement myself. I haven't had any problems with the multiplication algorithm- it's just adding and shifting and I've done a good job of figuring out what all of my variables mean so that I can multiply in a pretty reasonable amount of time. The problem that I'm having is with implementing the modulus operation in the multiplier. I know that performing repeated subtractions will work, but it will also be slow. I found out that I could shift the modulus to effectively subtract large multiples of the modulus but I think there might still be better ways to do this. The algorithm that I'm using works something like this (weird pseudocode follows): result,modulus : integer (n bits) (previously defined) shiftcount : integer (initialized to zero) while( (modulus<result) and (modulus(n-1) != 1) ){ modulus = modulus << 1 shiftcount++ } for(i=shiftcount;i>=0;i++){ if(modulus<result){result = result-modulus} if(i!=0){modulus = modulus << 1} } So...is this a good algorithm, or at least a good place to start? Wikipedia doesn't really discuss algorithms for implementing the modulo operation, and whenever I try to search elsewhere I find really interesting but incredibly complicated (and often unrelated) research papers and publications. If there's an obvious way to implement this that I'm not seeing, I'd really appreciate some feedback.

    Read the article

  • shell scripting: search/replace & check file exist

    - by johndashen
    I have a perl script (or any executable) E which will take a file foo.xml and write a file foo.txt. I use a Beowulf cluster to run E for a large number of XML files, but I'd like to write a simple job server script in shell (bash) which doesn't overwrite existing txt files. I'm currently doing something like #!/bin/sh PATTERN="[A-Z]*0[1-2][a-j]"; # this matches foo in all cases todo=`ls *.xml | grep $PATTERN -o`; isdone=`ls *.txt | grep $PATTERN -o`; whatsleft=todo - isdone; # what's the unix magic? #tack on the .xml prefix with sed or something #and then call the job server; jobserve E "$whatsleft"; and then I don't know how to get the difference between $todo and $isdone. I'd prefer using sort/uniq to something like a for loop with grep inside, but I'm not sure how to do it (pipes? temporary files?) As a bonus question, is there a way to do lookahead search in bash grep? To clarify: so the simplest way to do what i'm asking is (in pseudocode) for i in `/bin/ls *.xml` do replace xml suffix with txt if [that file exists] add to whatsleft list end done

    Read the article

  • How to analyze the efficiency of this algorithm Part 2

    - by Leonardo Lopez
    I found an error in the way I explained this question before, so here it goes again: FUNCTION SEEK(A,X) 1. FOUND = FALSE 2. K = 1 3. WHILE (NOT FOUND) AND (K < N) a. IF (A[K] = X THEN 1. FOUND = TRUE b. ELSE 1. K = K + 1 4. RETURN Analyzing this algorithm (pseudocode), I can count the number of steps it takes to finish, and analyze its efficiency in theta notation, T(n), a linear algorithm. OK. This following code depends on the inner formulas inside the loop in order to finish, the deal is that there is no variable N in the code, therefore the efficiency of this algorithm will always be the same since we're assigning the value of 1 to both A & B variables: 1. A = 1 2. B = 1 3. UNTIL (B > 100) a. B = 2A - 2 b. A = A + 3 Now I believe this algorithm performs in constant time, always. But how can I use Algebra in order to find out how many steps it takes to finish?

    Read the article

  • Bubble sort algorithm implementations (Haskell vs. C)

    - by kingping
    Hello. I have written 2 implementation of bubble sort algorithm in C and Haskell. Haskell implementation: module Main where main = do contents <- readFile "./data" print "Data loaded. Sorting.." let newcontents = bubblesort contents writeFile "./data_new_ghc" newcontents print "Sorting done" bubblesort list = sort list [] False rev = reverse -- separated. To see rev2 = reverse -- who calls the routine sort (x1:x2:xs) acc _ | x1 > x2 = sort (x1:xs) (x2:acc) True sort (x1:xs) acc flag = sort xs (x1:acc) flag sort [] acc True = sort (rev acc) [] False sort _ acc _ = rev2 acc I've compared these two implementations having run both on file with size of 20 KiB. C implementation took about a second, Haskell — about 1 min 10 sec. I have also profiled the Haskell application: Compile for profiling: C:\Temp ghc -prof -auto-all -O --make Main Profile: C:\Temp Main.exe +RTS -p and got these results. This is a pseudocode of the algorithm: procedure bubbleSort( A : list of sortable items ) defined as: do swapped := false for each i in 0 to length(A) - 2 inclusive do: if A[i] > A[i+1] then swap( A[i], A[i+1] ) swapped := true end if end for while swapped end procedure I wonder if it's possible to make Haskell implementation work faster without changing the algorithm (there's are actually a few tricks to make it work faster, but neither implementations have these optimizations)

    Read the article

  • how to queue function behind ajax request

    - by user1052335
    What I'm asking is conceptual rather than why my code doesn't work. I'm trying to make a web app that displays content fetched from a database in a sequence, one at a time, and then waits for a response from the user before continuing to the next one. I'm working with javascript on the client side with the JQuery library and php on the server side. In theory, there's time while waiting for the user's input to fetch information from the server using an AJAX request and have it ready for the use by the time he clicks the button, but there's also a chance that such an AJAX request hasn't completed when he clicks the button. So I need something like pseudocode: display current information fetch next data point from the server in the background onUserInput { if ( ajax request complete) { present the information fetched in this request } else if (ajax request not complete) { wait for ajax request complete present information to user } My question is this: how does one implement this " else if (ajax request not complete) { wait for ajax request complete " part. I'm currently using JQuery for my AJAX needs. I'm somewhat new to working with AJAX, and I did search around, but I didn't find anything that seemed on point. I don't know what tools I should use for this. Some kind of queue maybe? I don't need to be spoon fed. I just need to know how this is done, using what tools or if my desired outcome would be accomplished in some other way entirely. Thanks.

    Read the article

  • Synchronizing ASP.NET MVC action methods with ReaderWriterLockSlim

    - by James D
    Any obvious issues/problems/gotchas with synchronizing access (in an ASP.NET MVC blogging engine) to a shared object model (NHibernate, but it could be anything) at the Controller/Action level via ReaderWriterLockSlim? (Assume the object model is very large and expensive to build per-request, so we need to share it among requests.) Here's how a typical "Read Post" action would look. Enter the read lock, do some work, exit the read lock. public ActionResult ReadPost(int id) { // ReaderWriterLockSlim allows multiple concurrent writes; this method // only blocks in the unlikely event that some other client is currently // writing to the model, which would only happen if a comment were being // submitted or a new post were being saved. _lock.EnterReadLock(); try { // Access the model, fetch the post with specificied id // Pseudocode, etc. Post p = TheObjectModel.GetPostByID(id); ActionResult ar = View(p); return ar; } finally { // Under all code paths, we must release the read lock _lock.ExitReadLock(); } } Meanwhile, if a user submits a comment or an author authors a new post, they're going to need write access to the model, which is done roughly like so: [AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveComment(/* some posted data */) { // try/finally omitted for brevity _lock.EnterWriteLock(); // Save the comment to the DB, update the model to include the comment, etc. _lock.ExitWriteLock(); } Of course, this could also be done by tagging those action methods with some sort of "synchronized" attribute... but however you do it, my question is is this a bad idea? ps. ReaderWriterLockSlim is optimized for multiple concurrent reads, and only blocks if the write lock is held. Since writes are so infrequent (1000s or 10,000s or 100,000s of reads for every 1 write), and since they're of such a short duration, the effect is that the model is synchronized , and almost nobody ever locks, and if they do, it's not for very long.

    Read the article

  • Template in monorail ViewComponent

    - by George Polevoy
    Is it possible to have a template with html content in vm for a block component? I'm doing a lot of stuff in html, and want the html reside in a .vm, not in codebehind. Here is what i've got: public class TwoColumn : ViewComponent { public override void Render() { RenderText(@" <div class='twoColumnLayout'> <div class='columnOne'>"); // Context.RenderBody(); Context.RenderSection("columnOne"); RenderText(@" </div> <div class='columnTwo'>"); Context.RenderSection("columnTwo"); RenderText(@" </div> </div> "); } } Here is what i want to get: pageWithTwoColumns.vm: #blockcomponent(TwoColumn) #columnOne One #end #columnTwo Two #end #end twocolumn/default.vm (pseudocode): <div class="twoColumnLayout"> <div class="columnOne"> #reference-to-columnOne </div> <div class="columnTwo"> #reference-to-columnTwo </div> </div>

    Read the article

  • Looking for advice on importing large dataset in sqlite and Cocoa/Objective-C

    - by jluckyiv
    I have a fairly large hierarchical dataset I'm importing. The total size of the database after import is about 270MB in sqlite. My current method works, but I know I'm hogging memory as I do it. For instance, if I run with Zombies, my system freezes up (although it will execute just fine if I don't use that Instrument). I was hoping for some algorithm advice. I have three hierarchical tables comprising about 400,000 records. The highest level has about 30 records, the next has about 20,000, the last has the balance. Right now, I'm using nested for loops to import. I know I'm creating an unreasonably large object graph, but I'm also looking to serialize to JSON or XML because I want to break up the records into downloadable chunks for the end user to import a la carte. I have the code written to do the serialization, but I'm wondering if I can serialize the object graph if I only have pieces in memory. Here's pseudocode showing the basic process for sqlite import. I left out the unnecessary detail. [database open]; [database beginTransaction]; NSArray *firstLevels = [[FirstLevel fetchFromURL:url retain]; for (FirstLevel *firstLevel in firstLevels) { [firstLevel save]; int id1 = [firstLevel primaryKey]; NSArray *secondLevels = [[SecondLevel fetchFromURL:url] retain]; for (SecondLevel *secondLevel in secondLevels) { [secondLevel saveWithForeignKey:id1]; int id2 = [secondLevel primaryKey]; NSArray *thirdLevels = [[ThirdLevel fetchFromURL:url] retain]; for (ThirdLevel *thirdLevel in thirdLevels) { [thirdLevel saveWithForeignKey:id2]; } [database commit]; [database beginTransaction]; [thirdLevels release]; } [secondLevels release]; } [database commit]; [database release]; [firstLevels release];

    Read the article

  • Find all cycles in graph, redux

    - by Shadow
    Hi, I know there are a quite some answers existing on this question. However, I found none of them really bringing it to the point. Some argue that a cycle is (almost) the same as a strongly connected components (s. http://stackoverflow.com/questions/546655/finding-all-cycles-in-graph/549402#549402) , so one could use algorithms designed for that goal. Some argue that finding a cycle can be done via DFS and checking for back-edges (s. boost graph documentation on file dependencies). I now would like to have some suggestions on whether all cycles in a graph can be detected via DFS and checking for back-edges? My opinion is that it indeed could work that way as DFS-VISIT (s. pseudocode of DFS) freshly enters each node that was not yet visited. In that sense, each vertex exhibits a potential start of a cycle. Additionally, as DFS visits each edge once, each edge leading to the starting point of a cycle is also covered. Thus, by using DFS and back-edge checking it should indeed be possible to detect all cycles in a graph. Note that, if cycles with different numbers of participant nodes exist (e.g. triangles, rectangles etc.), additional work has to be done to discriminate the acutal "shape" of each cycle.

    Read the article

  • Pattern for limiting number of simultaneous asynchronous calls

    - by hitch
    I need to retrieve multiple objects from an external system. The external system supports multiple simultaneous requests (i.e. threads), but it is possible to flood the external system - therefore I want to be able to retrieve multiple objects asynchronously, but I want to be able to throttle the number of simultaneous async requests. i.e. I need to retrieve 100 items, but don't want to be retrieving more than 25 of them at once. When each request of the 25 completes, I want to trigger another retrieval, and once they are all complete I want to return all of the results in the order they were requested (i.e. there is no point returning the results until the entire call is returned). Are there any recommended patterns for this sort of thing? Would something like this be appropriate (pseudocode, obviously)? private List<externalSystemObjects> returnedObjects = new List<externalSystemObjects>; public List<externalSystemObjects> GetObjects(List<string> ids) { int callCount = 0; int maxCallCount = 25; WaitHandle[] handles; foreach(id in itemIds to get) { if(callCount < maxCallCount) { WaitHandle handle = executeCall(id, callback); addWaitHandleToWaitArray(handle) } else { int returnedCallId = WaitHandle.WaitAny(handles); removeReturnedCallFromWaitHandles(handles); } } WaitHandle.WaitAll(handles); return returnedObjects; } public void callback(object result) { returnedObjects.Add(result); }

    Read the article

  • Implementing a State Machine in Angular.js to control routing

    - by ldn_tech_exec
    Can anyone help me with integrating a state machine to control routing? What's the best method to do this? Create a service? I need to basically intercept every $location request, run the state machine and let it figure out what the next $location.path should be. Think of the problem like a bank of questions that get added and removed over time. The user visits once in a while, passes in the user's answers object to the statemachine, and the statemachine figures out which question to load. This is my pseudocode, but i need to figure out where to put this or what event I can hook into to make sure all route requests are passed through the machine. Do I need a specific stateMachine controller? Do I create a service? Where do I use the service? Do I need to override $locationProvider? $scope.user.answers = [{ id: 32, answer: "whatever" }, { id:33, answer: "another answer" }] $scope.questions = [{ id:32, question:"what is your name?", path:"/question/1" },{ id:34, question:"how old are you?", path:"/question/2" }] var questions = $scope.questions; angular.forEach(questions, function(question) { if(question.id !exist in $scope.user.answers.id) { $location.path = question.path break; }); Thanks

    Read the article

  • How does the destructor know when to activate itself? Can it be relied upon?

    - by Robert Mason
    Say for example i have the following code (pure example): class a { int * p; public: a() { p = new int; ~a() { delete p; } }; a * returnnew() { a retval; return(&retval); } int main() { a * foo = returnnew(); return 0; } In returnnew(), would retval be destructed after the return of the function (when retval goes out of scope)? Or would it disable automatic destruction after i returned the address and i would be able to say delete foo; at the end of main()? Or, in a similar vein (pseudocode): void foo(void* arg) { bar = (a*)arg; //do stuff exit_thread(); } int main() { while(true) { a asdf; create_thread(foo, (void*)&asdf); } return 0; } where would the destructor go? where would i have to say delete? or is this undefined behavior? Would the only possible solution be to use the STL referenced-counted pointers? how would this be implemented? Thank you- i've used C++ for a while but never quite been in this type of situation, and don't want to create memory leaks.

    Read the article

  • PHP autoloader: ignoring non-existing include

    - by Bart van Heukelom
    I have a problem with my autoloader: public function loadClass($className) { $file = str_replace(array('_', '\\'), '/', $className) . '.php'; include_once $file; } As you can see, it's quite simple. I just deduce the filename of the class and try to include it. I have a problem though; I get an exception when trying to load a non-existing class (because I have an error handler which throws exceptions). This is inconvenient, because it's also fired when you use class_exists() on a non-existing class. You don't want an exception there, just a "false" returned. I fixed this earlier by putting an @ before the include (supressing all errors). The big drawback with this, though, is that any parser/compiler errors (that are fatal) in this include won't show up (not even in the logs), resulting in a hard to find bug. What would be the best way to solve both problems at once? The easiest way would be to include something like this in the autoloader (pseudocode): foreach (path in the include_path) { if (is_readable(the path + the class name)) readable = true; } if (!readable) return; But I worry about the performance there. Would it hurt a lot? (Solved) Made it like this: public function loadClass($className) { $file = str_replace(array('_', '\\'), '/', $className) . '.php'; $paths = explode(PATH_SEPARATOR, get_include_path()); foreach ($paths as $path) { if (is_readable($path . '/' . $file)) { include_once $file; return; } } }

    Read the article

  • Python Post Upload JPEG to Server?

    - by iJames
    It seems like this answer has been provided a bunch of times but in all of it, I'm still getting errors from the server and I'm sure it has to do with my code. I've tried HTTP, and HTTPConnection from httplib and both create quite different terminal outputs in terms of formatting/encoding so I'm not sure where the problem lies. Does anything stand out here? Or is there just a better way? Pieced together from an ancient article because I really needed to understand the basis of creating the post: http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/ Note, the jpeg is supposed to be "unformatted". The pseudocode: boundary = "somerandomsetofchars" BOUNDARY = '--' + boundary CRLF = '\r\n' fields = [('aspecialkey','thevalueofthekey')] files = [('Image.Data','mypicture.jpg','/users/home/me/mypicture.jpg')] bodylines = [] for (key, value) in fields: bodylines.append(BOUNDARY) bodylines.append('Content-Disposition: form-data; name="%s"' % key) bodylines.append('') bodylines.append(value) for (key, filename, fileloc) in files: bodylines.append(BOUNDARY) bodylines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) bodylines.append('Content-Type: %s' % self.get_content_type(fileloc)) bodylines.append('') bodylines.append(open(fileloc,'r').read()) bodylines.append(BOUNDARY + '--') bodylines.append('') #print bodylines content_type = 'multipart/form-data; boundary=%s' % BOUNDARY body = CRLF.join(bodylines) #conn = httplib.HTTP("www.ahost.com") # In both this and below, the file part was garbling the rest of the body?!? conn = httplib.HTTPConnection("www.ahost.com") conn.putrequest('POST', "/myuploadlocation/uploadimage") headers = { 'content-length': str(len(body)), 'Content-Type' : content_type, 'User-Agent' : 'myagent' } for headerkey in headers: conn.putheader(headerkey, headers[headerkey]) conn.endheaders() conn.send(body) response = conn.getresponse() result = response.read() responseheaders = response.getheaders() It's interesting in that the real code I've implemented seems to work and is getting back valid responses, but the problem it it's telling me that it can't find the image data. Maybe this is particular to the server, but I'm just trying to rule out that I'm not doing some thing exceptionally stupid here. Or perhaps there's other methodologies for doing this more efficiently. I've not tried poster yet because I want to make sure I'm formatting the POST correctly first. I figure I can upgrade to poster after it's working yes?

    Read the article

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