Search Results

Search found 1523 results on 61 pages for 'assignment'.

Page 19/61 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • ANTLR AST rules fail with RewriteEmptyStreamException

    - by Barry Brown
    I have a simple grammar: grammar sample; options { output = AST; } assignment : IDENT ':=' expr ';' ; expr : factor ('*' factor)* ; factor : primary ('+' primary)* ; primary : NUM | '(' expr ')' ; IDENT : ('a'..'z')+ ; NUM : ('0'..'9')+ ; WS : (' '|'\n'|'\t'|'\r')+ {$channel=HIDDEN;} ; Now I want to add some rewrite rules to generate an AST. From what I've read online and in the Language Patterns book, I should be able to modify the grammar like this: assignment : IDENT ':=' expr ';' -> ^(':=' IDENT expr) ; expr : factor ('*' factor)* -> ^('*' factor+) ; factor : primary ('+' primary)* -> ^('+' primary+) ; primary : NUM | '(' expr ')' -> ^(expr) ; But it does not work. Although it compiles fine, when I run the parser I get a RewriteEmptyStreamException error. Here's where things get weird. If I define the pseudo tokens ADD and MULT and use them instead of the tree node literals, it works without error. tokens { ADD; MULT; } expr : factor ('*' factor)* -> ^(MULT factor+) ; factor : primary ('+' primary)* -> ^(ADD primary+) ; Alternatively, if I use the node suffix notation, it also appears to work fine: expr : factor ('*'^ factor)* ; factor : primary ('+'^ primary)* ; Is this discrepancy in behavior a bug?

    Read the article

  • How you would you describe the Observer pattern in beginner language?

    - by Sheldon
    Currently, my level of understanding is below all the coding examples on the web about the Observer Pattern. I understand it simply as being almost a subscription that updates all other events when a change is made that the delegate registers. However, I'm very unstable in my true comprehension of the benefits and uses. I've done some googling, but most are above my level of understanding. I'm trying to implement this pattern with my current homework assignment, and to truly make sense on my project need a better understanding of the pattern itself and perhaps an example to see what its use. I don't want to force this pattern into something just to submit, I need to understand the purpose and develop my methods accordingly so that it actually serves a good purpose. My text doesn't really go into it, just mentions it in one sentence. MSDN was hard for me to understand, as I'm a beginner on this, and it seems more of an advanced topic. How would you describe this Observer pattern and its uses in C# to a beginner? For an example, please keep code very simple so I can understand the purpose more than complex code snippets. I'm trying to use it effectively with some simple textbox string manipulations and using delegates for my assignment, so a pointer would help!

    Read the article

  • Single Form with Multiple Dynamic Buttons

    - by John Reilly
    I've spent hours/days trying to figure this out and now I'm completely perplexed so I thought I'd give stackoverflow a try. I'm (a newb) working in Java/JSP using Eclipse hosting on Google App Engine trying to develop an app for a volunteer organization I'm a member of. Rather than embarrass myself by showing my current code I'd love just a nudge in the right direction. I have a form (which doubles as a report basically) showing "people" grouped under the "task" they are currently working on. I would like to select multiple people from multiple tasks and reassign them to another task e.g. Bill and Jane are Gardening, Jeff is Painting. I want to select Jane and Jeff (all people have an associated checkbox in the form) and re-assign them to Sweeping (which is a task on the form but has no people assigned to it yet). Ideally, the re-assignment to Sweeping would be via a Sweeping button (each task would have a dynamically-created task button) that would pass the "Sweeping" value to a servlet along with an array or list of people whose checkbox has been checked. The servlet would handle the request (creating an Assignment "object/entity" with timeStamp, personId, taskId) and then re-direct back to the form/report which would then repaint with the current tasks/people generated from the Assignments class in the datastore. All the tasks are user-defined and retrieved from the database when building the form. Ditto the people. I've been trying to keep the jsp for presentation and the servlets for the processing but I'm no purist and would just like to get unstuck. Many thanks in advance for your assistance.

    Read the article

  • Atomic Instructions and Variable Update visibility

    - by dsimcha
    On most common platforms (the most important being x86; I understand that some platforms have extremely difficult memory models that provide almost no guarantees useful for multithreading, but I don't care about rare counter-examples), is the following code safe? Thread 1: someVariable = doStuff(); atomicSet(stuffDoneFlag, 1); Thread 2: while(!atomicRead(stuffDoneFlag)) {} // Wait for stuffDoneFlag to be set. doMoreStuff(someVariable); Assuming standard, reasonable implementations of atomic ops: Is Thread 1's assignment to someVariable guaranteed to complete before atomicSet() is called? Is Thread 2 guaranteed to see the assignment to someVariable before calling doMoreStuff() provided it reads stuffDoneFlag atomically? Edits: The implementation of atomic ops I'm using contains the x86 LOCK instruction in each operation, if that helps. Assume stuffDoneFlag is properly cleared somehow. How isn't important. This is a very simplified example. I created it this way so that you wouldn't have to understand the whole context of the problem to answer it. I know it's not efficient.

    Read the article

  • Constructor is being invoked twice

    - by Knowing me knowing you
    In code: LINT a = "12"; LINT b = 3; a = "3";//WHY THIS LINE INVOKES CTOR? std::string t = "1"; //LINT a = t;//Err NO SUITABLE CONV FROM STRING TO LINT. Shouldn't ctor do it? #pragma once #include "LINT_rep.h" class LINT { private: typedef LINT_rep value_type; const value_type* my_data_; template<class T> void init_(const T&); public: LINT(const char* = 0); LINT(const std::string&); LINT(const LINT&); LINT(const long_long&); LINT& operator=(const LINT&); virtual ~LINT(void); LINT operator+()const; //DONE LINT operator+(const LINT&)const;//DONE LINT operator-()const; //DONE LINT operator-(const LINT&)const;//DONE LINT operator*(const LINT&)const;//DONE LINT operator/(const LINT&)const;///WAITS FOR APPROVAL LINT& operator+=(const LINT&);//DONE LINT& operator-=(const LINT&);//DONE LINT& operator*=(const LINT&);//DONE LINT operator/=(const LINT&);///WAITS FOR APPROVAL }; in line number 3 instead of assignment optor ctor is invoked. Why? I'm willing to uppload entire solution on some server otherwise it's hard to put everything in here. I can also upload video file. Another thing is that when I implement this assignment optor I'm getting an error that this optor is already in obj file? What's going on?

    Read the article

  • Malloc inside another function (ANSI C)

    - by Casper
    Hi I'll go straight to it. I'm working on an assignment, where I suddenly ran into trouble. I have to allocate a struct from within another function, obviously using pointers. I've been staring at this problem for hours and tried in a million different ways to solve it. This is some sample code (very simplified): ... some_struct s; printf("Before: %d\n", &s"); allocate(&s); printf("After: %d\n", &s"); ... /* The allocation function */ int allocate(some_struct *arg) { arg = malloc(sizeof(some_struct)); printf("In function: %d\n", &arg"); return 0; } This does give me the same address before and after the allocate-call: Before: -1079752900 In function: -1079752928 After: -1079752900 I know it's probably because it makes a copy in the function, but I don't know how to actually work on the pointer I gave as argument. I tried defining some_struct *s instead of some_struct s, but no luck. I tried with: int allocate(some_struct **arg) which works just fine (the allocate-function needs to be changed as well), BUT according to the assignment I may NOT change the declaration, and it HAS to be *arg.. And it would be most correct if I just have to declare some_struct s.. Not some_struct *s. I hope I make sense and some of you out there can help me :P Thanks in advice

    Read the article

  • Implementing Drag and Drop using MouseListener for custom Components

    - by Chris Lieb
    I am working on a school assignment that requires me to be able to pick up a tile, drag it to a location, then drop it there. I was able to get this working using TransferHandler and a bunch of stuff from the dnd package, but this is not an acceptable way to perform this action for this assignment according to the professor. So, I am trying to achieve the same effect using the MouseListener interface. The basic setup is this: I have a JPanel-derived class called LocationView that contains JLabel-dervived instances of TileView. I need to get events that give me the LocationView that has the mouse pressed on and the LocationView that has the mouse released on. I am proxying mouse events through the TileView to its containing LocationView so that I can properly handle the mousePressed event. I added System.out.println()'s to the mouse listeners for mousePressed and mouseReleased to both LocationView and TileView so that I could observe the events that were being generated. To my surprise, pressing the mouse on Tile A in Location A, then dragging to Location B and releasing would generate a mouse released event for both Tile A and Location A, but not for Location B. I need the mouse released event triggered for only Location B. To try to work around this, I tried implementing a glass pane based off of the FinalGlassPane found at http://weblogs.java.net/blog/2006/09/20/well-behaved-glasspane. After adding the glass pane and adding an event listener for it, I can see that the mouse events are indeed filtering through the glass pane, but the mouse released event is still only being called on the item the mouse was clicked on. Is there a way to have mousePressed and mouseReleased events associated with the same drag action be called on separate components?

    Read the article

  • Simplest way to automatically alter "const" value in Java during compile time

    - by Michael Mao
    Hi all: This is a question corresponds to my uni assignment so I am very sorry to say I cannot adopt any one of the following best practices in a short time -- you know -- assignment is due tomorrow :( link to Best way to alter const in Java on StackOverflow Basically the only task (I hope so) left for me is the performance tuning. I've got a bunch of predefined "const" values in my single-class agent source code like this: //static final values private static final long FT_THRESHOLD = 400; private static final long FT_THRESHOLD_MARGIN = 50; private static final long FT_SMOOTH_PRICE_IDICATOR = 20; private static final long FT_BUY_PRICE_MODIFIER = 0; private static final long FT_LAST_ROUNDS_STARTTIME = 90; private static final long FT_AMOUNT_ADJUST_MODIFIER = 5; private static final long FT_HISTORY_PIRCES_LENGTH = 10; private static final long FT_TRACK_DURATION = 5; private static final int MAX_BED_BID_NUM_PER_AUC = 12; I can definitely alter the values manually and then compile the code to give it another go around. But the execution time for a thorough "statistic analysis" usually requires over 2000 times of execution, which will typically lasts more than half an hour on my own laptop... So I hope there is a way to alter values using other ways than dig into the source code to change the "const" values there, so I can automatically distributed compiled code to other people's PC and let them run the statistic analysis instead. One other reason for a automatically value adjustment is that I can try using my own agent to defeat itself by choosing different "const" values. Although my values are derived from previous history and statistical results, they are far from the most optimized values. I hope there is a easy way so I can quickly adopt that so to have a good sleep tonight while the computer does everything for me... :) Any hints on this sort of stuff? Any suggestion is welcomed and much appreciated.

    Read the article

  • Using a "take-home" coding component in interview process

    - by Jeff Sargent
    In recent interviews I have been asking candidates to code through some questions on the whiteboard. I don't feel I'm getting a clear enough picture of the candidates technical ability with this approach. Granted, the questions might not be good enough, maybe the interview needs to be longer, etc, but I'm wondering if a different approach would be better. What I'd like to try is to create a simple, working project in Visual Studio and have it checked into source control. The candidate can check that code out from home/wherever and then check back in work representing their response to the assignment that I'll provide. I'm thinking that if the window of time is short enough and the assignment clear enough then the solution will be safe enough from all-out Googling (i.e. they couldn't search for and find the entire solution online). I would then be able to review the candidates work. Has enough worked with something like this before, either to vet a candidate or as a candidate yourself? Any thoughts in general? P.S. my first StackOverflow question - hi guys and gals. EDIT: I've seen comments about asking someone to work for free - I wouldn't mind paying the person for their time.

    Read the article

  • Indenting Paragraph With cout

    - by Eric
    Given a string of unknown length, how can you output it using cout so that the entire string displays as an indented block of text on the console? (so that even if the string wraps to a new line, the second line would have the same level of indentation) Example: cout << "This is a short string that isn't indented." << endl; cout << /* Indenting Magic */ << "This is a very long string that will wrap to the next line because it is a very long string that will wrap to the next line..." << endl; And the desired output: This is a short string that isn't indented. This is a very long string that will wrap to the next line because it is a very long string that will wrap to the next line... Edit: The homework assignment I'm working on is complete. The assignment has nothing to do with getting the output to format as in the above example, so I probably shouldn't have included the homework tag. This is just for my own enlightment. I know I could count through the characters in the string, see when I get to the end of a line, then spit out a newline and output -x- number of spaces each time. I'm interested to know if there is a simpler, idiomatic C++ way to accomplish the above.

    Read the article

  • How can I help fellow students struggling in programming classes?

    - by David Barry
    I'm a computer science student finishing up my second semester of programming classes. I've enjoyed them quite a bit, and learned a lot, but it seems other students are struggling with the concepts and assignments more than I am. When an assignment is due, the inevitable group email comes out the day or two before with people needing some help either with a specific part of the problem, or sometimes people just seem to have a hard time knowing where to start. I'd really like to be able to help out, but I have a hard time thinking of the right way to give them help without giving them the answer. When I'm having trouble understanding a concept, a code snippet can go along way to helping me, but at the same time if it makes a lot of sense, it can be difficult to think of another way to go about it. Plus the Academic Integrity section of each assignment is always looming overhead warning against sharing code with others. I've tried using pseudo code to help give others an idea on program flow, leaving them to figure out how to implement certain aspects of it, but I didn't get too much feedback and don't know how much it actually helped them out, or if it just confused them further. So I'm basically looking to see if anyone has experience with this, or good ways that I can help out other students to nudge them in the right direction or help them think about the problem in the right way.

    Read the article

  • Memory management of objects returned by methods (iOS / Objective-C)

    - by iOSNewb
    I am learning Objective-C and iOS programming through the terrific iTunesU course posted by Stanford (http://www.stanford.edu/class/cs193p/cgi-bin/drupal/) Assignment 2 is to create a calculator with variable buttons. The chain of commands (e.g. 3+x-y) is stored in a NSMutableArray as "anExpression", and then we sub in random values for x and y based on an NSDictionary to get a solution. This part of the assignment is tripping me up: The final two [methods] “convert” anExpression to/from a property list: + (id)propertyListForExpression:(id)anExpression; + (id)expressionForPropertyList:(id)propertyList; You’ll remember from lecture that a property list is just any combination of NSArray, NSDictionary, NSString, NSNumber, etc., so why do we even need this method since anExpression is already a property list? (Since the expressions we build are NSMutableArrays that contain only NSString and NSNumber objects, they are, indeed, already property lists.) Well, because the caller of our API has no idea that anExpression is a property list. That’s an internal implementation detail we have chosen not to expose to callers. Even so, you may think, the implementation of these two methods is easy because anExpression is already a property list so we can just return the argument right back, right? Well, yes and no. The memory management on this one is a bit tricky. We’ll leave it up to you to figure out. Give it your best shot. Obviously, I am missing something with respect to memory management because I don't see why I can't just return the passed arguments right back. Thanks in advance for any answers!

    Read the article

  • o write a C++ program to encrypt and decrypt certain codes.

    - by Amber
    Step 1: Write a function int GetText(char[],int); which fills a character array from a requested file. That is, the function should prompt the user to input the filename, and then read up to the number of characters given as the second argument, terminating when the number has been reached or when the end of file is encountered. The file should then be closed. The number of characters placed in the array is then returned as the value of the function. Every character in the file should be transferred to the array. Whitespace should not be removed. When testing, assume that no more than 5000 characters will be read. The function should be placed in a file called coding.cpp while the main will be in ass5.cpp. To enable the prototypes to be accessible, the file coding.h contains the prototypes for all the functions that are to be written in coding.cpp for this assignment. (You may write other functions. If they are called from any of the functions in coding.h, they must appear in coding.cpp where their prototypes should also appear. Do not alter coding.h. Any other functions written for this assignment should be placed, along with their prototypes, with the main function.) Step 2: Write a function int SimplifyText(char[],int); which simplifies the text in the first argument, an array containing the number of characters as given in the second argument, by converting all alphabetic characters to lower case, removing all non-alpha characters, and replacing multiple whitespace by one blank. Any leading whitespace at the beginning of the array should be removed completely. The resulting number of characters should be returned as the value of the function. Note that another array cannot appear in the function (as the file does not contain one). For example, if the array contained the 29 characters "The 39 Steps" by John Buchan (with the " appearing in the array), the simplified text would be the steps by john buchan of length 24. The array should not contain a null character at the end. Step 3: Using the file test.txt, test your program so far. You will need to write a function void PrintText(const char[],int,int); that prints out the contents of the array, whose length is the second argument, breaking the lines to exactly the number of characters in the third argument. Be warned that, if the array contains newlines (as it would when read from a file), lines will be broken earlier than the specified length. Step 4: Write a function void Caesar(const char[],int,char[],int); which takes the first argument array, with length given by the second argument and codes it into the third argument array, using the shift given in the fourth argument. The shift must be performed cyclicly and must also be able to handle negative shifts. Shifts exceeding 26 can be reduced by modulo arithmetic. (Is C++'s modulo operations on negative numbers a problem here?) Demonstrate that the test file, as simplified, can be coded and decoded using a given shift by listing the original input text, the simplified text (indicating the new length), the coded text and finally the decoded text. Step 5: The permutation cypher does not limit the character substitution to just a shift. In fact, each of the 26 characters is coded to one of the others in an arbitrary way. So, for example, a might become f, b become q, c become d, but a letter never remains the same. How the letters are rearranged can be specified using a seed to the random number generator. The code can then be decoded, if the decoder has the same random number generator and knows the seed. Write the function void Permute(const char[],int,char[],unsigned long); with the same first three arguments as Caesar above, with the fourth argument being the seed. The function will have to make up a permutation table as follows: To find what a is coded as, generate a random number from 1 to 25. Add that to a to get the coded letter. Mark that letter as used. For b, generate 1 to 24, then step that many letters after b, ignoring the used letter if encountered. For c, generate 1 to 23, ignoring a or b's codes if encountered. Wrap around at z. Here's an example, for only the 6 letters a, b, c, d, e, f. For the letter a, generate, from 1-5, a 2. Then a - c. c is marked as used. For the letter b, generate, from 1-4, a 3. So count 3 from b, skipping c (since it is marked as used) yielding the coding of b - f. Mark f as used. For c, generate, from 1-3, a 3. So count 3 from c, skipping f, giving a. Note the wrap at the last letter back to the first. And so on, yielding a - c b - f c - a d - b (it got a 2) e - d f - e Thus, for a given seed, a translation table is required. To decode a piece of text, we need the table generated to be re-arranged so that the right hand column is in order. In fact you can just store the table in the reverse way (e.g., if a gets encoded to c, put a opposite c is the table). Write a function called void DePermute(const char[],int,char[], unsigned long); to reverse the permutation cypher. Again, test your functions using the test file. At this point, any main program used to test these functions will not be required as part of the assignment. The remainder of the assignment uses some of these functions, and needs its own main function. When submitted, all the above functions will be tested by the marker's own main function. Step 6: If the seed number is unknown, decoding is difficult. Write a main program which: (i) reads in a piece of text using GetText; (ii) simplifies the text using SimplifyText; (iii) prints the text using PrintText; (iv) requests two letters to swap. If we think 'a' in the text should be 'q' we would type aq as input. The text would be modified by swapping the a's and q's, and the text reprinted. Repeat this last step until the user considers the text is decoded, when the input of the same letter twice (requesting a letter to be swapped with itself) terminates the program. Step 7: If we have a large enough sample of coded text, we can use knowledge of English to aid in finding the permutation. The first clue is in the frequency of occurrence of each letter. Write a function void LetterFreq(const char[],int,freq[]); which takes the piece of text given as the first two arguments (same as above) and returns in the 26 long array of structs (the third argument), the table of the frequency of the 26 letters. This frequency table should be in decreasing order of popularity. A simple Selection Sort will suffice. (This will be described in lectures.) When printed, this summary would look something like v x r s z j p t n c l h u o i b w d g e a q y k f m 168106 68 66 59 54 48 45 44 35 26 24 22 20 20 20 17 13 12 12 4 4 1 0 0 0 The formatting will require the use of input/output manipulators. See the header file for the definition of the struct called freq. Modify the program so that, before each swap is requested, the current frequency of the letters is printed. This does not require further calls to LetterFreq, however. You may use the traditional order of regular letter frequencies (E T A I O N S H R D L U) as a guide when deciding what characters to exchange. Step 8: The decoding process can be made more difficult if blank is also coded. That is, consider the alphabet to be 27 letters. Rewrite LetterFreq and your main program to handle blank as another character to code. In the above frequency order, space usually comes first.

    Read the article

  • Write a C++ program to encrypt and decrypt certain codes.

    - by Amber
    Step 1: Write a function int GetText(char[],int); which fills a character array from a requested file. That is, the function should prompt the user to input the filename, and then read up to the number of characters given as the second argument, terminating when the number has been reached or when the end of file is encountered. The file should then be closed. The number of characters placed in the array is then returned as the value of the function. Every character in the file should be transferred to the array. Whitespace should not be removed. When testing, assume that no more than 5000 characters will be read. The function should be placed in a file called coding.cpp while the main will be in ass5.cpp. To enable the prototypes to be accessible, the file coding.h contains the prototypes for all the functions that are to be written in coding.cpp for this assignment. (You may write other functions. If they are called from any of the functions in coding.h, they must appear in coding.cpp where their prototypes should also appear. Do not alter coding.h. Any other functions written for this assignment should be placed, along with their prototypes, with the main function.) Step 2: Write a function int SimplifyText(char[],int); which simplifies the text in the first argument, an array containing the number of characters as given in the second argument, by converting all alphabetic characters to lower case, removing all non-alpha characters, and replacing multiple whitespace by one blank. Any leading whitespace at the beginning of the array should be removed completely. The resulting number of characters should be returned as the value of the function. Note that another array cannot appear in the function (as the file does not contain one). For example, if the array contained the 29 characters "The 39 Steps" by John Buchan (with the " appearing in the array), the simplified text would be the steps by john buchan of length 24. The array should not contain a null character at the end. Step 3: Using the file test.txt, test your program so far. You will need to write a function void PrintText(const char[],int,int); that prints out the contents of the array, whose length is the second argument, breaking the lines to exactly the number of characters in the third argument. Be warned that, if the array contains newlines (as it would when read from a file), lines will be broken earlier than the specified length. Step 4: Write a function void Caesar(const char[],int,char[],int); which takes the first argument array, with length given by the second argument and codes it into the third argument array, using the shift given in the fourth argument. The shift must be performed cyclicly and must also be able to handle negative shifts. Shifts exceeding 26 can be reduced by modulo arithmetic. (Is C++'s modulo operations on negative numbers a problem here?) Demonstrate that the test file, as simplified, can be coded and decoded using a given shift by listing the original input text, the simplified text (indicating the new length), the coded text and finally the decoded text. Step 5: The permutation cypher does not limit the character substitution to just a shift. In fact, each of the 26 characters is coded to one of the others in an arbitrary way. So, for example, a might become f, b become q, c become d, but a letter never remains the same. How the letters are rearranged can be specified using a seed to the random number generator. The code can then be decoded, if the decoder has the same random number generator and knows the seed. Write the function void Permute(const char[],int,char[],unsigned long); with the same first three arguments as Caesar above, with the fourth argument being the seed. The function will have to make up a permutation table as follows: To find what a is coded as, generate a random number from 1 to 25. Add that to a to get the coded letter. Mark that letter as used. For b, generate 1 to 24, then step that many letters after b, ignoring the used letter if encountered. For c, generate 1 to 23, ignoring a or b's codes if encountered. Wrap around at z. Here's an example, for only the 6 letters a, b, c, d, e, f. For the letter a, generate, from 1-5, a 2. Then a - c. c is marked as used. For the letter b, generate, from 1-4, a 3. So count 3 from b, skipping c (since it is marked as used) yielding the coding of b - f. Mark f as used. For c, generate, from 1-3, a 3. So count 3 from c, skipping f, giving a. Note the wrap at the last letter back to the first. And so on, yielding a - c b - f c - a d - b (it got a 2) e - d f - e Thus, for a given seed, a translation table is required. To decode a piece of text, we need the table generated to be re-arranged so that the right hand column is in order. In fact you can just store the table in the reverse way (e.g., if a gets encoded to c, put a opposite c is the table). Write a function called void DePermute(const char[],int,char[], unsigned long); to reverse the permutation cypher. Again, test your functions using the test file. At this point, any main program used to test these functions will not be required as part of the assignment. The remainder of the assignment uses some of these functions, and needs its own main function. When submitted, all the above functions will be tested by the marker's own main function. Step 6: If the seed number is unknown, decoding is difficult. Write a main program which: (i) reads in a piece of text using GetText; (ii) simplifies the text using SimplifyText; (iii) prints the text using PrintText; (iv) requests two letters to swap. If we think 'a' in the text should be 'q' we would type aq as input. The text would be modified by swapping the a's and q's, and the text reprinted. Repeat this last step until the user considers the text is decoded, when the input of the same letter twice (requesting a letter to be swapped with itself) terminates the program. Step 7: If we have a large enough sample of coded text, we can use knowledge of English to aid in finding the permutation. The first clue is in the frequency of occurrence of each letter. Write a function void LetterFreq(const char[],int,freq[]); which takes the piece of text given as the first two arguments (same as above) and returns in the 26 long array of structs (the third argument), the table of the frequency of the 26 letters. This frequency table should be in decreasing order of popularity. A simple Selection Sort will suffice. (This will be described in lectures.) When printed, this summary would look something like v x r s z j p t n c l h u o i b w d g e a q y k f m 168106 68 66 59 54 48 45 44 35 26 24 22 20 20 20 17 13 12 12 4 4 1 0 0 0 The formatting will require the use of input/output manipulators. See the header file for the definition of the struct called freq. Modify the program so that, before each swap is requested, the current frequency of the letters is printed. This does not require further calls to LetterFreq, however. You may use the traditional order of regular letter frequencies (E T A I O N S H R D L U) as a guide when deciding what characters to exchange. Step 8: The decoding process can be made more difficult if blank is also coded. That is, consider the alphabet to be 27 letters. Rewrite LetterFreq and your main program to handle blank as another character to code. In the above frequency order, space usually comes first.

    Read the article

  • Java ArrayList remove dupes without sets

    - by Kieran
    I'm having problems removing duplicates from an ArrayList. It's for an assignment for college. Here's the code I have already: public int numberOfDiffWords() { ArrayList<String> list = new ArrayList<>(); for(int i=0; i<words.size()-1; i++) { for(int j=i+1; j<words.size(); j++) { if(words.get(i).equals(words.get(j))) { // do nothing } else { list.add(words.get(i)); } } } return list.size(); } The problem is in the numberOfDiffWords() method. The populate list method is working correctly, as my instructor has given me a sample string (containing 4465 words) to analyse - printing words.size() gives the correct result. I want to return the size of the new ArrayList with all duplicates removed. words is an ArrayList class attribute. UPDATE: I should have mentioned I'm only allowed to use dynamic indexed-based storage for this part of the assignment, which means no hash-based storage.

    Read the article

  • Reading from an write-only(OUT) parameter in pl/sql

    - by sqlgrasshopper5
    When I tried writing to an read-only parameter(IN) of a function, Oracle complains with an error. But that is not the case when reading from an write-only(OUT) parameter of a function. Oracle silently allows this without any error. What is the reason for this behaviour?. The following code executes without any assignment happening to "so" variable: create or replace function foo(a OUT number) return number is so number; begin so := a; --no assignment happens here a := 42; dbms_output.put_line('HiYA there'); dbms_output.put_line('VAlue:' || so); return 5; end; / declare somevar number; a number := 6; begin dbms_output.put_line('Before a:'|| a); somevar := foo(a); dbms_output.put_line('After a:' || a); end; / Here's the output I got: Before a:6 HiYA there VAlue: After a:42

    Read the article

  • Replace without the replace function

    - by Molly Potter
    Assignment: Let X and Y be two words. Find/Replace is a common word processing operation that finds each occurrence of word X and replaces it with word Y in a given document. Your task is to write a program that performs the Find/Replace operation. Your program will prompt the user for the word to be replaced (X), then the substitute word (Y ). Assume that the input document is named input.txt. You must write the result of this Find/Replace operation to a file named output.txt. Lastly, you cannot use the replace() string function built into Python (it would make the assignment much too easy). To test your code, you should modify input.txt using a text editor such as Notepad or IDLE to contain different lines of text. Again, the output of your code must look exactly like the sample output. This is my code: input_data = open('input.txt','r') #this opens the file to read it. output_data = open('output.txt','w') #this opens a file to write to. userStr= (raw_input('Enter the word to be replaced:')) #this prompts the user for a word userReplace =(raw_input('What should I replace all occurences of ' + userStr + ' with?')) #this prompts the user for the replacement word for line in input_data: words = line.split() if userStr in words: output_data.write(line + userReplace) else: output_data.write(line) print 'All occurences of '+userStr+' in input.txt have been replaced by '+userReplace+' in output.txt' #this tells the user that we have replaced the words they gave us input_data.close() #this closes the documents we opened before output_data.close() It won't replace anything in the output file. Help!

    Read the article

  • ndarray field names for both row and column?

    - by Graham Mitchell
    I'm a computer science teacher trying to create a little gradebook for myself using NumPy. But I think it would make my code easier to write if I could create an ndarray that uses field names for both the rows and columns. Here's what I've got so far: import numpy as np num_stud = 23 num_assign = 2 grades = np.zeros(num_stud, dtype=[('assign 1','i2'), ('assign 2','i2')]) #etc gv = grades.view(dtype='i2').reshape(num_stud,num_assign) So, if my first student gets a 97 on 'assign 1', I can write either of: grades[0]['assign 1'] = 97 gv[0][0] = 97 Also, I can do the following: np.mean( grades['assign 1'] ) # class average for assignment 1 np.sum( gv[0] ) # total points for student 1 This all works. But what I can't figure out how to do is use a student id number to refer to a particular student (assume that two of my students have student ids as shown): grades['123456']['assign 2'] = 95 grades['314159']['assign 2'] = 83 ...or maybe create a second view with the different field names? np.sum( gview2['314159'] ) # total points for the student with the given id I know that I could create a dict mapping student ids to indices, but that seems fragile and crufty, and I'm hoping there's a better way than: id2i = { '123456': 0, '314159': 1 } np.sum( gv[ id2i['314159'] ] ) I'm also willing to re-architect things if there's a cleaner design. I'm new to NumPy, and I haven't written much code yet, so starting over isn't out of the question if I'm Doing It Wrong. I am going to be needing to sum all the assignment points for over a hundred students once a day, as well as run standard deviations and other stats. Plus, I'll be waiting on the results, so I'd like it to run in only a couple of seconds. Thanks in advance for any suggestions.

    Read the article

  • RoR ActiveRecord f.select nil method error

    - by sellis6688
    Whenever I use an f.select statement to determine assignment_id(or student_id), and I should get a validation error, I get this error instead of the validation message: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.collect Extracted source (around line #11): 8: </p> 9: <p> 10: <%= f.label 'Assignment:' %><br /> 11: <%= f.select(:assignment_id, @assignments.collect {|p| [p.ass_num, p.id]})%> 12: </p> 13: <p> 14: <%= f.label 'First Student:' %><br /> My grades model: class Grade < ActiveRecord::Base has_and_belongs_to_many :students belongs_to :assignment validates_presence_of :score, :assignment_id, :student_id validates_numericality_of :score, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 100, :allow_nil => true validates_uniqueness_of :student_id, :scope => :assignment_id end If I use a text_field, I don't get the error... but there's far too many students for that. Neither @assignments nor @students are nil. Any suggestions?

    Read the article

  • PHP hashing function not working properly

    - by Jordan Foreman
    So I read a quick PHP login system securing article, and was trying to sort of duplicate their hashing method, and during testing, am not getting the proper output. Here is my code: function decryptPassword($pw, $salt){ $hash = hash('sha256', $salt . hash('sha256', $pw)); return $hash; } function encryptPassword($pw){ $hash = hash('sha256', $pw); $salt = substr(md5(uniqid(rand(), true)), 0, 3); $hash = hash('sha265', $salt . $hash); return array( 'salt' => $salt, 'hash' => $hash ); } And here is my testing code: $pw = $_GET['pw']; $enc = encryptPassword($pw); $hash = $enc['hash']; $salt = $enc['salt']; echo 'Pass: ' . $pw . '<br />'; echo 'Hash: ' . $hash . '<br />'; echo 'Salt: ' . $salt . '<br />'; echo 'Decrypt: ' . decryptPassword($hash, $salt); Now, the output of this should be pretty obvious, but unfortunately, the $hash variable always comes out empty! I'm trying to figure out what the problem could be, and my only guess would be the second $hash assignment line in the encryptPassword(..) function. After a little testing, I've determined that the first assignment works smoothly, but the second does not. Any suggestions? Thanks SO!

    Read the article

  • Fastest way to read/store lots of multidimensional data? (Java)

    - by RemiX
    I have three questions about three nested loops: for (int x=0; x<400; x++) { for (int y=0; y<300; y++) { for (int z=0; z<400; z++) { // compute and store value } } } And I need to store all computed values. My standard approach would be to use a 3D-array: values[x][y][z] = 1; // test value but this turns out to be slow: it takes 192 ms to complete this loop, where a single int-assignment int value = 1; // test value takes only 66 ms. 1) Why is an array so relatively slow? 2) And why does it get even slower when I put this in the inner loop: values[z][y][x] = 1; // (notice x and z switched) This takes more than 4 seconds! 3) Most importantly: Can I use a data structure that is as quick as the assignment of a single integer, but can store as much data as the 3D-array?

    Read the article

  • Why does Java think my object is a variable?

    - by user2896898
    Ok so I'm trying to make a simple pong game. I have a paddle that follows the mouse and a ball that bounces around. I wrote a method collidesWith(Sprite s) inside of my Sprite class that checks if the ball collides with the paddle (this works and isn't the problem). I have two objects extending my sprite class, a ball and a paddle object. So inside of my ball class I'm trying to check if it collides with the paddle. So I've tried if(this.collidesWith(paddle) == true){ System.out.println("They touched"); } I've also tried ball.collidesWith(paddle) and other combinations but it always says the same thing about the paddle (and the ball when I use ball.collidesWith) "Cannot find symbol. Symbol: variable paddle(or ball). Location: class Ball" So if I'm reading this right, it thinks that the paddle (and ball) are variables and it's complaining because it can't find them. How can I make it understand I am passing in objects, not variables? For extra information, an earlier assignment had me make two boxes and for them to change colors when they were colliding. In that assignment I used very similar code to above with if(boxOne.collidesWith(boxTwo) == true){ System.out.println("yes"); } And in this code it worked just fine. The program knew that boxOne and boxTwo were child classes of my Sprite class. Anyone know why they wouldn't work the same?

    Read the article

  • Error 619 when connecting to ForeFront TMG VPN

    - by yang
    I have a fresh new Windows Server 2008 R2 Domain Setup and a ForeFront TMG installation. Both of them are newly installed. I enabled VPN client access and configured address assignment method. Now when I try to connect to VPN over internet (with Windows 7 client) I receive Error 619 stating that the credentials are wrong. Of course credentials are not wrong, something else is wrong here. Any help?

    Read the article

  • Graph paper like drawing software

    - by Algorist
    Hi, I have a college assignment, where I have to draw diagrams of voronoi, delaunay, minimum spanning tree etc for the college. I want to do that in computer. I searched in google with no luck. Is there any good graph drawing software you are aware of? Thank you Bala

    Read the article

  • Tasks carried out for a Software Project

    - by Sara
    Hi, We were asked to propose a web based system for a shop, for an assignment. As i'm a newbee for project management stuff find it quite difficult to come with Tasks for our Gantt chart. Can someone pls suggest a sample gantt or main tasks followed in developing such system Thanks

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >