Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Grr, I meant to give a more detailed explanation of why the namespace for ostream& has to be explicitly scoped, but for the life of me I can't recall the explanation other than that it has to do with the declaration defaulting to the top-level anonymous namespace rather than the std namespace. Perhaps someone like mike_2000_17, Ancient Dragon or ddanbe could give a better explanation?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As Moschops said, te stream insertion and extraction operators are usually implemented as free functions that is are friends of the class, rather than as members, but it would be useful to understand why this is the case. The reason you can't have it as a member operator is because in a class member function, the this pointer is an implicit argument to the function; in an operator, this means that the left side argument is assumed to be the object being operated on. However, for the stream out operator, you want the operator to act on the ostream reference as the left-hand argument, not the object being sent, so in order to get the desired result, the operator cannot be a member of the class it operates on.

In addition, you must explicitly scope the ostream& declarations, rather than relying on using namespace std;. You should never have a using namespace std directive in a header, in fact, for this a several other reasons having to do with namespace pollution, and using namespace std in general is a poor practice even in source files. The whole purpose of separating the standard library members into a separate namespace is to avoid collisions with user-defined functions, and wholesale application of using namespace std; undermines this. All references to the standard library functions should be explicitly scoped, strictly speaking, including such C-style functions as pow() or printf(), though most compilers let you cheat with the C library functions as a …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Can you explain, in detail, the problem you are having, or the part you aren't able to implement? I you are getting any error messages from the compiler, please post them as well.

As an aside, in C++ the main() function always is of type int, and has to have a return value of either zero or some error code. Always, without exception. While void main() was permissible in earlier versions of the C standard (in order to accomodate some non-standard operating systems), it has never been acceptable in C++, even pre-standard. Your compiler should at least be warning you about this, and the fact that it isn't is a sign that it isn't a standards-compliant compiler.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's start by getting this code into some semblance of consistent indentation:

#include<iostream>

using namespace std;

class product 
{
private:
    int code;
    char name[20];
    double price;
    int instock;
    double soldperyear[12];
public:
    product(int,char[],double,int);

    void setproduct(int c , char n[],double p,int i)
    {
        setcode(c);
        setname(n);
        setprice(p);
        setinstock(i);
    }

    void peryear(int i)
    {
        for ( i=1;i<=12;i++)
            soldperyear[i]=0;
    }

    void setcode(int c)
    {
        if(c>=2500&&c<=2750)
            code=c;
        else 
            code=2500;
    }

    void setname(char n[])
    {
        strncpy(name, n,19);
        name[19]='\0';
    }

    void setprice(double p)
    {
        price = p> 0.0?p:0.0;
    }

    void setinstock(int i)
    {
        i=0;
        instock=i;
    }

    int getcode()
    {  
        return code;
    }

    char * getname()
    {
        return name;
    }

    double getprice()
    {
        return price;
    }

    int getstock()
    {
        return instock;
    }

    void increment(int inc)
    {
        instock=instock +inc ;
    }

    void decrement(int ins,int month)
    {
        if(instock>=ins)
        {
            instock-=ins;
            soldperyear[month]+=ins;
        }
        else 
            cout<<" not enough products in stock "<<endl;
    }

    double t (){
        double total =0;
        for (int i=1;i<=12;i++)
            total +=soldperyear[i];
        return total ;

    }

    void print() {
        cout<<" Product: "<<endl;
        cout<<"code :"<<getcode()<<endl;
        cout<<"Name : "<<getname()<<endl;
        cout<<"price: "<<getprice()<<endl;
        cout<<"sold per year : " <<t()<<endl;
        cout<<" In stock : " <<getstock()<<endl;
    }

};

product::product(int c, char n[], double p, int i)
{
    setproduct( c ,  n, p, i);
}

void main()
{
    int code;
    char name[20];
    double price;
    int instock;
    int x;
    int z;

    product car,&ref=car,*ptr=&car,p,&refp=p,*ptrp=&p;

    cout<<"Car: "<<endl
        <<"Enter car code: "<<endl;
    cin>>code;
    car.setcode(code);

    cout<<"Enter Name: "<<endl;
    cin>>name;
    ref.setname(name);

    cout<<"Enter price :"<<endl;
    cin>>price;
    ptr->setprice(price);

    cout<<"Available in stock:"<<endl;
    cin>>instock;
    car.setinstock(instock);
    for(int i=0;i<12;i++)
    {
        int month;
        cout<<"quantity sold per month"<<i+1<<endl;
        cin>>month;
        car.decrement(month,i); …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Trust me, while your compiler may accept void main(), and your instructor may have claimed it is acceptable, the standard does not. I would direct you to this C and C++ FAQ and this essay for clarification on the subject. The point is that in C++, the main() function must explicitly return a status code to the operating system, no exceptions, and if a compiler allows you to declare main() as void, it is a fault in the compiler, not a feature of the language.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, as I have said elsewhere, in C++ main() should always have a return type of int. Some older compilers allowed void main(), but it is actually not permissible under the standard. It should return zero for a successful program run or an error code on failure.

Second, the conio library is non-standard, and since the only place you use it is to pause the screen when the you reach the end of the program - something that is only necessary under some older IDEs such as Bloodshed Dev-C++ - you can safely eliminate it if you upgrade to an IDE that isn't over ten years old, such as the Orwell fork of Dev-C++ or Code::Blocks. Both are in current development, and both have fixed the particular bug that work-around was needed for.

Third, the instructions say to break the problem down into at least two functions, presumably in addition to main(). I would go further than that myself, but that's the specific requirement of the assignment, and even if you are doing this for your own personal study, it is a good practice in any case.

Getting (finally) to your code, well, to start with, you are IMAO hard-coding too many aspects of the program, and not letting the data drive the flow of control. There are several things I can recommend, starting with making a struct type or even a class to hold the department information. Something like this is what I have …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Given that zrd0808 hasn't been on Dnaiweb in four years, I doubt you'll get an answer :-)

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It's quite simple: replace the trailing space, ' ', with endl (the end of line marker for ostreams). BTW, you can always use endl instead of '\n' in C++ stream output, the only difference is that endl (IIRC) also flushes the stream (that is, it forces it to go to print out immediately, rather than build up in the output buffer).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Wouldn't make sense to have the class implement Serializable rather than hard-coding the file output? I haven't used Java serialization before, so I don't know the limitations and weaknesses of it, but I would expect that using that would save a good deal of effort and make the code less brittle.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

lol guys i told u i need help in the main at

Using the two objects, pointer and reference test all the member functions of your class

Actually, you didn't; you simply copied the assignment statement with no information of where you needed help. In any case, you'll need to be more specific than this if we're going to be able to help you with it. What aspect of writing the test code has you troubled?

Are you uncertain how to test the class functions? We can give some advice on the matter, but we cannot write the tests for you. Realistically, it seems straightforward enough, the only real problem is that you'd need to test it in the two cases of a reference and of a pointer, which means using the local member notation for the former and the member indirection notation for the latter. Were you explained these notations clearly, and do you see why they differ?

BTW, in C++ the main() function always is of type int, and has to have a return value of either zero or some error code. Always, without exception. While it was permissible in earlier versions of the C standard (in order to accomodate some non-standard operating systems), it has never been acceptable in C++, even pre-standard. Your compiler should be warning you about this, and the fact that it isn't is a sign that it isn't a standards-compliant compiler.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Adding to what I wrote earlier, here's a simple trick to simplify the printout of the individual hands:

char* get_hand_name(hand h)
{
    char names[][] = {"Rock", "Paper", "Scissors"};

    return names[h];
}

char* get_result_description(outcome result)
{
    char descriptions[][] = {"Draw.", "win for the Player.", "win for the Computer."}
    return descriptions[result];
}

You can then make your printout much simpler:

void print_outcome(hand player, hand computer)
{
    printf("The player chose %s", get_hand_name(player));
    printf("The computer chose %s", get_hand_name(computer);
    printf("This match is a %s", get_result_description(get_result(player, computer)));
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Sadly, my earlier recommendation is as kind a response as I can make; it really is terrible for any professor to be forcing their students to use something as long outdated as Turbo C++, and students shouldn't put up with it. However, seeing how you are stuck in this position, I can give you some practical advice about getting your program to work.

The first thing I recommend is to break the input() function into several smaller functions; right now, there is a tremendous amount of redundancy in the code that could be simplified by modularizing the program better. For example, you could have a function that takes the outcome of the turn and prints whether it is win, lose or draw.

Second, you can structure the program better if, when testing a single variable's value for multiple outcomes, you used a switch statement instead of a series of if statements. This makes the intention clearer, and makes certain kinds of errors less likely.

You can also clarify things by naming the different types of casts, rather than using the magic numbers directly as you are doing now. You can use #define for this purpose, but since there are a sequence of values, you would be better off using enum types for this:

enum outcome {DRAW, PLAYER_WIN, COMPUTER_WIN};
enum hand {ROCK, PAPER, SCISSORS};

These can then be used like so:

outcome get_result(hand player, hand computer) 
{
    switch(player)
    {
        case ROCK:
            switch(computer)
            {
                case ROCK:
                     return …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, there already exists a steganographic plugin for GIMP, which you can probbly use off the shelf for your purposes. The source should be viewable if you want to go over it or make changes to it.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

JasonHippy: This is actually a subtle point, and one that need to be understood: arrays are not pointers, but when used in certain ways will automatically be 'devolved' to pointers (cast, basically) by the compiler so that they can be treated interchangeably with pointers. The array variable name is still a name for the block of memory; there is no separate pointer value pointing to the memory block. The interchangability of arrays and pointers is syntactic sugar, not a reflection of the actual layout in memory.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The issue is not between arrays and other variables in general, but arrays and pointers to said arrays. An array is not a pointer; it is a regular variable, just one which names a block of values rather than a single value. The usual syntax for accessing the elements of an array is

int ary[16];

ary[0] = 17;  /* the 0th element of ary is now 17 */

OK, a quick explanation. A pointer, if you are unfamiliar, is a variable that holds an address in memory, and can be used to refer to this address. Pointers have types, like any other variable, which is a 'pointer to the declared type'. In the following code,

int a, *ptr1, *ptr2;

the type of a is int, while the type of ptr1 and ptr2 is 'pointer to int'. See? The pointer has to know the size of the variable it is pointing to, hence the need for typed pointers.

To use a pointer, you need to get a reference to the variable in question, using the dereference operator, &, like so:

ptr1 = &a;

You now can access the value of a through ptr using the indirection operator:

*ptr1 = 42;   /* the value of a is now 42 */

To pass an address from one pointer to another, you would just assign it like normal:

ptr2 = ptr1;  /* both now point to a */

However, when an array is passed …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What program? I see no code posted here. As we've already said, you need to demonstrate that you have made an attempt in earnest to solve to assignment, and post useful information about the problems you are experiencing and pose meaningful questions about the issues you are experiencing.

We will not do your homework for you. Is that clear enough? We'll assist you in fixing it, but you won't get a whole project written for you by anyone here.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

All well and good, and of some definite interest in general, but... why post this here, except as a way of advertising your blog and thesis? This forum is mostly for assisting others in finding solutions to problems; your neither ask a question nor (within the post) provide an answer. While a few of us will appreciate the contents of your thesis, simply posting the abstract and expecting us to go to your blog for the details is simply inappropriate.

Also, intentionally posting the same material repeatedly is a clear violation the forum rules against spamming. In a persistent message board like this, there is little need to keep sending the same message over and over again, and it is extremely rude to do so.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, the first thing to look at is the headers, both the names and the format of them. A C program will have headers in the form of foo.h, whereas in (modern) C++, the standard library headers will be foo without the extension. Now, this isn't a foolproof method, as there's a lot of pre-standard C++ code floating around, but if you see a header without an extension, it is presumably C++.

Also, in C++, the C library headers should be prepended with a c, making (for example) <stdio.h> into <cstdio>. Again, a lot of older code doesn't match this standard, and even some current code isn't correct in this regard, but if it is like that, it is definitely C++ rather than C.

Next, the headers used may be different; C++ adds a large number of new libraries which use the C++ facilities that don't exist in C. The main ones to look for are <iostream>, <fstream>, <string>, <vector> and <algorithm>.

Fourth, C++ has namespaces, but C does not; so, if you see a reference to using namespace foo;, it will be C++. The same goes for the scoping operator, ::, which is used to indicate membership in either a class or a namespace.

Finally, if it uses cin and cout for input and output, it is going to be C++.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Two pieces of advice:

  1. Check the switches being passed to g++ by your Makefile or IDE, and make sure that it includes Wall (all warnings) as one of the defaults. The compiler will highlight a lot more problems with the code than it would without it. If you are just compiling from the command line, be sure to add that switch to the invocation.

    $ g++ -Wall myprogram.cpp -o myprogram.exe

  2. If your editor or IDE has a regex replace function (such as the M-% of Emacs fame), try a search for lines begining with the word string and find any that need to be changed to std::string. For most regex search functions, the expression would be simply $string or possibly $\w*string depending on how it interprets whitespace.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While you aren't showing it, I assume you are closing the #ifndef at the end of the file.

As for why it isn't finding the std::string class, I'm not sure. While I do see something that ought to be a showstopper - the C library headers <time.h> and stdlib.h> should be <ctime>and <cstdlib> in C++, and <dir.h> is specific to the Borland MS-DOS compilers and wouldn't be in MinGW at all AFAIK - I can only guess what the cause of the problem you are describing. Could you please post the error messages so we can take a look at them?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

miazara: I see that you tried to reply to DaveAmour and rubberman, but you entered the code into the comments, which is too short for such purposes. You need to use the Reply box at the bottom of the page to send a full length reply.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, to begin with, this is a C++ program, not a C program, and a poorly written one at that. The header formats indicate that it probably dates back to the late 1990s, when the then-new C++ standard was still being formalized - either that, or the programmer didn't understand the standard correctly. Several critical values are hard-coded in rather than parameterized, making the implementation brittle. The choice of bubblesort for the sorting algorithm is questionable at best, though with the small range it probably isn't very performance-critical. Finally, the code is pretty badly mangled, with the return types running into the function names and so forth, which means that without many fixes it wouldn't compile cleanly.

While it could fairly easily be re-written in C, you would be a lot better off writing a new implementation of the algorithm yourself. You would waste more time trying to fix this than you would starting over from scratch.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I am going to give you the same advice I give all the students who come here whose professors' are requring them to use Turbo C++ for current-day coursework:

  • Stand up in class, explain to your fellow students that the professor is teaching out-of-date and useless information that will hinder your ability to work in programming in the future,
  • Walk out of the course and encourage as many other classmates as you can to do so as well,
  • Go to the Dean's office and petition for the professor to be removed on the grounds of incompetence.

There is absolutely no justification for using Turbo C++ in an era when it won't even run on most new systems. Modern, powerful and effective compilers and IDEs which support modern versions of the language and present-day programming techniques are freely available from multiple sources, including Microsoft. To still be using and teaching a compiler that is older than most of the students using it is nothing short of criminal.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Consider a forum meant to assist programmers in learning to program, but whose members are constantly bombarded with requests from students who want their homework done for them with no effort on their own part. Explain why it is counterproductive to both the members and the students for the members to acquiesce to such requests, or conversely, provide some proof (e.g., partial code for the project) that the student has made their own effort on the assignment and is legitimately seeking help rather than a hand-out. Extra credit: Demonstrate the likelihood of being caught at cheating by the professor's TA, just from doing a script-driven Google search on fragments of the submitted code from each student.

ddanbe commented: Original :) +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, just to be pedantic about it, Dev-C++ and Eclipse are not themselves compilers; they are development environments which call (presumably) the GCC compiler (which to be even more pedantic, is not actually a compiler either, just a driver for the compiler and linker). I know it sounds picayune to make such distinctions, but there's a reason I bring it up.

You see, development of the original Bloodshed Dev-C++ stopped about ten years ago, and as a result, the IDE (and the default compiler) is sort of frozen in time from around 2005. As a result, the many refinements and changes that have been made to GCC have not been added to it, and compiler that it defaults to is now quite out of date.

However, if you are using Eclipse (or the Orwell Dev-C++ fork, or Code::Blocks, or any other up-to-date IDE), you'll have the latest version of GCC bundled with (as of when you installed it, at least), with the latest and greatest default settings, many of which have to do with code validation. Furthermore, each IDE will have different default switches set when they call GCC, including in most cases -Wall (show all warnings), which Bloodshed Dev-C++ didn't set by default. So, if you are using a newer version of GCC, with a different set of switches set, you could end up with some surprises when compiling code that had seemed fine in the past.

Specifically, the checking for function prototypes has …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Certainly. As I said, I use git for most of my SCM these days, so I'd recommend that, though I am aware that (like all software systems) it has its flaws. Others might recommend something different, like Mercurial or Bazaar, but I'll go with what I know for now. I'll also recommend GitHub for your offsite repo, for much the same reason. The GitHub user docs cover all of this quite well, but I'll go over it briefly for you now; I recommend you read through it, and the linked docs, at least once in toto before you go ahead with anything.

The first step is to make sure you have a suitable SSH public and private key pair. Chances are you already have done this for other things, but if you need to do it now, then what you need to do is run ssh-keygen and enter a suitable passphrase, one which you will remember yourself but which others are unlikely to guess at. Unlike most passwords, the pass phrase can have spaces in it. It can and should be fairly long, at least five or six actual words. You would then run ssh-add /path/to/your/key to register the key. The GitHub documentation on SSH keys gives more detail about how this should be done.

Nex you need to get the git software, whivch fortunately isn't a major dificulty on most Linux distros. From what you said earlier, I assume you are using a Debian based …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

mulusew: Please do not hijack other people's threads, especially if all you are going to do is beg for someone to do you homework for you. Please start a new hread of your own, and demonstrate that you have put some effort into it yourself before you expect us to be able to help you.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, OK, thank you for sharing the files.

I would, however, recommend that you get your code under source control and into a public repository ASAP, both to ensure that the code is secure and to facilitate cooperative work on the project. I personally have moved most of my projects to GithHub, which is free for open-source projects, but a site such as SourceForge or Heroku should be equally suitable (though Heroku is more focused on SaaS enterprise projects). Use whichever SCM you feel most comfortable with; if you haven't used one before, I can give you advice on how to do so.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

That should be correct for the recursive version, yes, though you'll want some patience when it runs: you are producing the whole series of fib(0) to fib(43), one at a time, which means that you'll be recomputing the series, uhm... pardon me if I'm not quite awake enough right now to work it all out but it will be a lot of recomputing. If all you need is fib(43), this particular code is overkill, but if you mean to print the whole series in that range, you are good to go.

Oops, I just noticed something: you need to test in the loop to be i <= 43 in order to get 43 inclusive.

You may want to fiddle about with memoizing the results, though, just to see about how much of a speedup you'll get from it. A std::vector<int> variable should be useful for this purpose.

BTW, are you using Bloodshed Dev-C++ as your IDE by any chance? I noticed the system("pause"); line which is why I ask, that particular problem is specific to the old version of Dev-C++ and some early versions of Visual Studio. If you are, you should be aware that this version of Dev-C++ hasn't been updated in ten years, and has been superceded by the Orwell Dev-C++ fork, which is in current development, has an up-to-date version of GCC bundled with it, and AFAICT doesn't have that specific problem. Alternately, you can try Code::Blocks which is a similar IDE to …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, it's a start I guess, but in this case, the 43 should be what you are passing to the function as n, not hard-coded into the function; it should look like this in your call:

value = fib(43);

The initial value of i should probably be 0, since you are counting up to the value of n.

long Fib(int n)
{
    long f1=1, f2=1, fn;

    for (i=0; i<=n; ++i)
    {
        fn=f1+f2;
        f2=fn;
        f1=f2;
    }

    return fn;
}

(I won't offer advice on whether the algorithm is correct overall, just this one piece of the puzzle.)

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think you will find that much of what you are looking for can be more readily found at the OSDev.org wiki and forums than here. There is a great deal of specialized information on hobbyist operating system development, and they can offer more detailed advice.

However, I am curious: how are you booting this operating system - did you roll your own bootloader, or use an off-the-shelf multiboot loader such as GRUB? Is it a 16-bit, 32-bit, or 64-bit OS (I am assuming 16-bit from the code given)? What toolchain (assembler, linker, C compiler, raw data loader, etc) are you using? What source code control are you using (e.g., Subversion, git, Mercurial)? How did you design the kernel, and what type of kernel is it? What filesystem and executable format are you using? Are you running on a hardware testbed, or using an emulator (e.g., Bochs or virtualizer (e.g., VirtualBox) to test run the system while you develop it? What is your host system (e.g., Windows, Linux. MacOS)? Did you really write a full suite of C system libraries (including, Eris help us, a version of <conio.h>), or did you use an hooked library such as PDCLib to connect to your system calls? What form do your system calls take - software interrupts, call gates, SYSENTER/SYSEXIT? What method of memory management are you using, and have you established virtual memory and paging?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, and what problem are you having? Can you explain in detail what is going on, and where you need further help?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, I didn't realize that was an actual requirement of the assignment. Sorry.

One thing I will strongly recommend is reorganizing the program into functions, so that it is easier to read, and less redundant. Here is what I came up with (though it doesn't take into account the spaces issue):

from random import randint
from statistics import mean

def generate_key():
    """ generate a key for the enciphered message"""
    numbers = list()
    # while n is less than 8
    for n in range(8):
        # generate eight random numbers between 33 and 126
        partial_seed = randint(33, 126)
        numbers.append(partial_seed)
        # this averages and rounds the values in numbers
        # and then subtracts 32
        avg = round(mean(numbers))
        return avg - 32

def apply_cipher(plaintext, cipher_key):
    return [(ord(chars) ^ cipher_key) for chars in plaintext]

def apply_deciphering(ciphertext, cipher_key):
    plaindata =  [chr(values ^ cipher_key) for values in ciphertext]
    return ''.join(plaindata)

def encrypt(source, dest):
    """ encrypt the given file """
    cipher_key = generate_key()
    with open(source) as plaintext_file:
        with open(dest, "wb") as ciphertext_file:
            ciphertext_file.write(bytes(chr(cipher_key), 'utf-8'))
            ciphertext = apply_cipher(plaintext_file.read(), cipher_key)
            ciphertext_file.write(bytes(ciphertext))

def decrypt(source, dest):
    with open(source, "rb") as ciphertext_file:
        ciphertext = ciphertext_file.read()
        cipher_key = ciphertext[0]
        plaintext = apply_deciphering(ciphertext[1:], cipher_key)
        with open(dest, "w") as plaintext_file:
            plaintext_file.write(plaintext)


def print_menu():
    menu = ['Display main menu', 'Encrypt Message', 'Decrypt Message', 'Exit program']
    for opt_number, option in enumerate(menu):
        print('{0}) {1}'.format(opt_number, option))

if __name__ == "__main__":
    print("Hi, Welcome to Text Encryption")
    print("This program will encrypt or decrypt a text file chosen by you.")
    print_menu()

    #the user only has 4 choices
    menu_choice = 0

    #menu_choice == …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I don't think you actually would want to treat the spaces (or whitespace in general) any differently from the other plaintext, actually; you want to write the ciphertext out in a form that gives as little information as possible to a cryptanalyst, so enciphering the whitespace would make more sense. You don't want to store or write the ciphertext out as a string at all, but as a binary in your cipher.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Before proceeding, could you tell us which assembler you are using? Different assemblers, even ones for the same CPU, can have very different syntaces, and the one you are using seems unfamiliar to me. I am guessing it is HLA, but I don't know enough about it to say for certain.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

rubberman: I thought so too, but then I checked using Python (which has bigints), and it turns out that's not the case. Fibonacci numbers do grow quite rapidly, but not quite that rapidly; fib(43) is around 400 million, which will fit a 32-bit signed value.

memo = dict()
memo[0] = 0
memo[1] = 1

def fib(n):
    global memo

    if n in memo.keys():
        return memo[n]
    else:
        memo[n] = fib(n - 1) + fib(n - 2)
        return memo[n]


fib(43)
print(memo)

I think we were both thinking of factorials, which do grow that quickly - fact(43) is around 6 x 10^52.

def fact(n):
    if n <= 1:
        return 1
    else:
        return n * fact(n - 1)

print(fact(43))

(And yes, I know I've given the game away, but the OP would need to be able to re-write the Python code into C++, and if they could do that they wouldn't be posting such a basic question in the first place.)

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I will also warn you that while the conventional tree-recursive algorithm is much simpler than the iterative algorithm, it is extremely inefficient, being of order O(Fib(n)) in time and O(n) in space. This is because (for example) for fib(5), you have to compute fib(4) and fib(3), which in turn have to compute fib(3) + fib(2), which in turn have to compute fib(2) + fib(1) and fib(1) + fib(0), and then compute fib(2) and fib(1), and so on. The total number of calls to fib() is equal to the fibonacci number of n.

It would take quite a while to compute fib(43) that way, even in C++ - unless you use a trick.

The trick is called memoization, and basically means keeping a record of the computed values so that when you come to a value you have already calculated before, you can just look it up in a table rather than re-computed again. I won't go into the details of it, just that it is easiest to use a vector<int> to do it so that you don't have to worry about the size of the table. You don't need to worry about it, but it is something to at least be aware of.

There is an even faster way to compute fibonacci numbers using matrices, but I'll just tantalize you with that fact for now and leave it to you to learn it on your own (hint: Wikipedia covers it quite nicely).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The short answer is, it is using pointer arithmetic to compute the location of an index B in an array of USHORT (where USHORT is a typedef equal to unsigned short) pointed to by C (I assume that somewhere in the elided code, C is being set to either am array or a block allocated on the heap using malloc() or something similar), then dereferences the computed pointer so it can store the value of A at the pointed-to location. It is basically the same as

C[B] = A;

Except that it is (marginally) more efficient.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's back up a bit, however, as I suspect that there is a matter of terminology to be resolved. Is the question the running time of the code (which will vary depending on the machine it is run on, the memory usage, the system loading, and a host of other side issues), or do you need to determine the algorithmic time complexity of the algorithm (how the mean/maximum/minimum running time is proportional to the number of items being processed; e.g., O(n log n), or O(n^2))? These are two very different questions.

For the time complexity of this specific algorithm, you need to consider how many times the algorithm passes over the string in question. In particular, you have one pass over the whole string (line 10), followed by a pass that covers at least one item of the list, at most one-half the length of the string, and on average 1/4 of the list (lines 13-17). Does that give you enough information to work the rest out yourself?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It may be possible in some cases, but not in the general case. I think one can categorically state that if it is, then either the cipher or the key in question is too weak and shouldn't have been used in the first place - unless this is a test or puzzle meant to be solved, rather than an actual practical cryptanalysis problem, of course.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

A few questions that may help us help you:

  • Has the professor presented flowcharts (as opposed to more modern diagramming practices) as a regular part of designing programs?
  • Does the professor mandate the use of Turbo C++ as the compiler?
  • Is this course for the C++ language? The code given is more typical of C than of C++, so it may be that you have misunderstood which of the message boards you wanted.
  • If this is in fact meant to be C++ code, has your professor not taught about the C++ iostream methods at all, or are you forbidden to use them? Some hidebound professors teach C and call it C++, but it is important to understand the difference.
  • Did your professor actually teach and encourage the use of goto in regular code?

If the answer to any of these questions is 'yes', you should immediately quit the class and encourage everyone else you can to do so as well, then petition the university to dismiss the professor in question on the grounds of incompetence. The issue of using goto is particularly damning, as the dangers of regular use of that construct were well understood more than forty years ago - using goto in modern software is so inappropriate that it is a once-in-a-career situation for most developers to find themselves needing to use it explicitly, and then only if all other practical alternatives have been exhausted.

ddanbe commented: Nice! +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Before making any suggestions, I would like to ask if your course of study (whether personal or formal) has gotten to functions and how to write them yet. This would be a big factor in how you approach thsis matter.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It could help if, rather than posting the JavaScript/JQuery code that generates the form being sent, we could see the Python code that is reading it in from the server. There are several ways that can be done, depending on the libraries and/or frameworks you are using.

Let's step back a bit and look at your goals rather than what you currently have it doing. What is this actually supposed to accomplish? What information are you actually trying to extract from the POSTed form? Why does it have to be in the form of a list of dicts?

Oh, BTW, what version of Python are you working in? That could be relevant.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

@rubberman: While your answer is strictly correct, I suspect that the professor who gave this question was being idiomatic (or perhaps merely idiotic) and not expecting the students to be quite so literal about it, in which case C) would be the expected (if subtly wrong) answer. Of course, it hardly matters now, since the quiz that the OP was trying to cheat on had been over before you answered the question, anyway.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Is this 'home-made mini OS' running as an application on an existing system, or are you actually booting it from the bare hardware (or the virtualized equivalent thereof)? I am assuming the latte, which means it is more of an OS simulation than a full OS, not that that is a bad thing; writing an actual operating system is an enormous task, and chances are you aren't up to it yet.

Depending on how serious you are about this, you might want to look at the OSDev wiki, especially the sections on memory management.

Mind you, the memory management you are currently working on is at the application level, not the OS level. Those are two quite different things. Generally speaking, the OS level memory management has to deal with the memory for the entire system, not just some arbitrary size section, and had to deal with issues of the mapping of virtual memory to physical memory, setting up separate process memory spaces, and handling paging, among other things. Application level memory management is a significantly simpler matter, but still not easy.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let me make some corrections to that:

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While I do indeed see some serious issues with how allocate() is implemented, I would say the real problem is happening even earlier. As I said before, what is really going on is that you haven't initialized first to any value at all, whic means that there is no value to check. You need a function that expressly initializes first and runs before either any of your other functions are called:

struct block_meta* init_memory_area(uint8_t mem[], uint16_t size)
{
    struct block_meta* first = malloc(sizeof(struct block_meta));
    first->size = size;
    first->next = NULL;
    first->block_ptr = mem;

    return first;
}

Actually, before we do that, let's rearrange things a little bit:

alloc.h

#ifndef ALLOC_H
#define ALLOC_H 1

#include <stdbool.h>
#include <stdint.h>

struct block_meta
{
    uint8_t size;
    struct block_meta *next;
    void* block_ptr;
};

void* allocate(int size);
bool free_allocated(void* ptr);

#endif

alloc.c

#include <stdlib.h>
#include <stdint.h>
#include "alloc.h"

const unit16_t DATA_SEG_SIZE = UINT16_MAX;
char data_seg[DATA_SEG_SIZE];

struct block_meta* first;

struct block_meta* init_memory_area(uint8_t mem[], uint16_t size);
void* search_for_free(int size);

struct block_meta* init_memory_area(uint8_t mem[], uint16_t size)
{
    struct block_meta* first = malloc(sizeof(struct block_meta));
    first->size = size;
    first->next = NULL;
    first->block_ptr = mem;

    return first;
}

void* search_for_free(int size)
{
    struct block_meta* head;

    if (first == NULL)
    {
        init_memory_area(

    head = first;

    while ( head != NULL )
    {
        if ( head->size == size )
            return head->block_ptr;
        else
            head = head->next;
    }
    return NULL;
}

void free_allocated(void* ptr, int size)
{
    struct block_meta* head = first;

    if(head == NULL)
    {
        first = (struct block_meta *) …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

A few pieces of advice:

  • The heart of the problem you are having is that you haven't initialized the free memory handle (first) before using it. I would start by writing a function to do that and calling it at the start of the program (the reason you don't need to do this explicitly in C applications is because it is done for you as part of the setup for the program before main() is run).
  • If you are using a modern compiler (one that defaults to C99 or later), rather than using char as the memory type, use uint8_t. This is more precise and specific about the size of the elements. You'll need to #include <stdint.h> to get the size-specific integer types, but that's a minor consideration. I mention this now mainly because it is relevant to the next issue.
  • You are using an 8-bit unsigned char for the block sizes. This means that the blocks are a maximum of 255 bytes long. Since you actually have a memory space of 65536, you would need a 16-bit block size to span the whole memory space, or else force the memory to be segmented into 256 pages. I recommend using a uint16_t instead, or if that isn't an option, an unsigned short (though the exact size of that isn't guaranteed to be 16 bits IIRC).
  • In search_for_free(), you have the comparison look for an exact match to the size of the block size being allocated. Exact Fit algorithms rarely work …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you tell us what CPU this is for, and what simulator you are using? It looks like some form of M68K assembly to me offhand, but I without knowing which simulator you are using, I couldn't exactly replicate the circumstances of the program.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To follow up on the last comment:

image.h

#ifndef IMAGE_H
#define IMAGE_H 1

class image
{
private:
    ULONG_PTR m_gdiplusToken;
    Gdiplus::GdiplusStartupInput gdiplusStartupInput;
    HDC hdcimage=CreateCompatibleDC(NULL);
    HGDIOBJ obj=NULL;
    HBITMAP btBitmap=NULL;
    Image *img;
    bool isimgused=false;
    bool isGDIPLUSIniciated=false;
    int imageheight=0;
    int imageweight=0;
    int framecount=0;
    int intSelectFrame=0;
    int framedelay=0;
    string strfilename="";
    Gdiplus::Color clrBackColor=Gdiplus::Color::Transparent;
    HDC hdcwindow;
    bool blnTransparent=true;

    void readimagefile(string filename);

    HICON HICONFromHBITMAP(HBITMAP bitmap);

public:

    image();

    image(HDC hdcWindow);

    image(const int width, const int height);

    image( const string & filename);

    image (const image &cSource);

    image& operator= (const image &cSource);

    property <int> SelectFrame
    {
        Get(int)
        {
            return intSelectFrame;
        },
        Set(int selectframe)
        {
            if(intSelectFrame<0)
                intSelectFrame=0;
            else if (intSelectFrame>=framecount)
                intSelectFrame=framecount-1;
            else
                intSelectFrame=selectframe;

            UINT count = 0;
            count = img->GetFrameDimensionsCount();
            GUID* pDimensionIDs = (GUID*)malloc(sizeof(GUID)*count);
            img->GetFrameDimensionsList(pDimensionIDs, count);
            img->SelectActiveFrame(&pDimensionIDs[0],intSelectFrame);
            Gdiplus::Graphics graphics(hdcimage);
            graphics.Clear(clrBackColor);
            graphics.DrawImage(img, 0, 0, imageweight, imageheight);
            //RePaint();
            free(pDimensionIDs);
        }
    };

    void getImageFromResource(string strResourceName);

    void RePaint(bool blackandwhite=true);

    property<int> FramesCount
    {
        Get(int)
        {
            return framecount;
        }
    };

    property<int> FrameDelay
    {
        Get(int)
        {
            return framedelay;
        }
    };

    property<string> FileName
    {
        Get(string)
        {
            return strfilename;
        },
        Set(string filename)
        {
            readimagefile(filename);
        }
    };

    property<Gdiplus::Color> Backcolor
    {
        Get(Gdiplus::Color)
        {
            return clrBackColor;
        },
        Set(Gdiplus::Color bkcolor)
        {
            clrBackColor = bkcolor;
            SetDCBrushColor(hdcimage,clrBackColor.ToCOLORREF());
        }
    };

    void draw(HDC control);

    operator string()
    {
        return strfilename;
    }

    operator HICON()
    {
        return HICONFromHBITMAP(btBitmap);
    }

    operator HBITMAP()
    {
        return btBitmap;
    }

    int height()
    {
        return imageheight;
    }

    int width()
    {
        return imageweight;
    }

    operator HDC()
    {
        return hdcimage;
    }

    bool operator != ( nullptr_t ) const;

    bool operator==(const image &other) const;

    bool operator!=(const image &other) const;

    bool haveimage();

    ~image();
};

#endif

image.cpp

void image::readimagefile(string filename) …