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

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

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

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

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

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

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

Frankly, I haven't had the chance to look the class over in detail, but my impression is that there is too much being 'baked in' to this one class, and that much of it could be separated out into subclasses. Were I designing this, I would make image an abstract class and use subclasses for most of the actual implementation; an icon subclass would in particular make sense, and move a lot of extraneous code out of the parent class.

David_50's suggestion of caching the images is a sensible one as well. I would use a priority queue (heap) and a Least Recently Used algorithm to track the cache; as new images get added, it would check to see if any images have a priority below some minimum level, and remove those from the heap, while each reference to an image already in the heap would brevet it back up to the top of the heap.

And oh yes, you have too many of you methods - as in all of them - in the class declaration. This is C++, not Java; you will want to move the majority of the implementation code into a separate source file.

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

Ah, a good question, and one I am actually glad to see here. It shows some thought beyond the usual questions here.

However, I should caution you that thater are a lot of ways to approach this issue, and which is going to work for you will depemnd on both your own temperment, your experience, the scope and nature of the project, and who well established the conventional solutions to the problem(s) are. You generally will approach a small project different from a larger one - or rather, you generally want to do as much as you can to break larger ones down into smaller ones, then apply the design principles to the individual parts.

One thing I will say is that your approach will evolve over time, as you become more fluent in the programming languages and techniques. Just as when you arew learning a spoken language, and often have to rely on phrasebooks and dictionaries to get your through until you start to actually grasp the language, so too will you need to work a lot with references and tutorials at first. The difference is that this is a wide-open field, and one that changes rapidly, so chances are there will always be things that will send you looking for reference material no matter how skilled you become.

Not knowing what you're skill level is, let's start with the simplest suggestions first:

  1. Try to get familiar with as many of the common data structures, algorithms, and design patterns …

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

I am fairly certain that Vegaseat was poking fun at the 'Is Lisp a Legacy Language?' thread when he posted this. Or maybe at the whole concept of 'legacy languages' in the first place, especially when questions about new languages like Go also end up getting posted here for lack of a better place to ask. Really, I've always felt that 'Legacy Languages' is a poor name for this section in the first place, as it carries a certain judgement about the languages themselves.

<rant>
I mean, yes, no one is going to argue that languages like COBOL 65, FoxPro, Pilot, or MUMPS are not dated, but if people are still using them - and some are, amazingly enough - how is that 'legacy'? I can see the term 'legacy code', especially when applied to software where the source code, the translator, or the original target system no longer exist, but 'legacy language' really can only refer to one that is directly tied to an obsolete architecture in a way that it can't run on other systems (i.e., it isn't portable).
</rant>

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

The standard Datetime and Calendar classes only work with Gregorian calendar dates; however, after some searching I did find a project on Sourceforge for a multi-calendar utility module for Python, and it does specifically include the Persian calendar. Assuming it works, that may be what you need.

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

Ah, I see. Well, I can help you out I think. Fortunatel,y functions in Python are dead easy, and once you get the idea of them, you'll probably use them quite a bit.

Using a function is already familiar to you; you used the standard functions len(), print(), and sqrt() already. While len() and print() are part of the Python language itself, sqrt() is actually a part of the math library, and not a part of the core language at all. While the libraries are part of what comes with the language, they are separate from the language itself, which is why you need to use import in order to use them.

Writing your own function is almost as easy, but I should explain a little about why you would want to first. There are three main reasons for writing functions in Python (and most programming languages in general). First, they let you give a name to a particular piece of code. This allows you to ''abstract'' the idea of that piece of code, so you don't have to think about what's inside of it; you can just use the name. Second, it makes it easy to use the same piece of code in more than one place, making the program smaller and reducing the number of places you need to fix if you have to change something. Finally, a function can be ''parameterized'', that is to say, it can let you describe ''part'' of a piece of code, without …

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

OK, you are mostly on the right track, I would say. However, there are things that can be done to improve it. Has your professor covered defining functions yet? If so, I would certainly recommend writing the average as a a function, that way you don't have to repeat the same code in the SD section twice. In fact, I would write all of these as functions, and simply have the main program call them as needed.

Also, while it is useful to have a defined value for the input when testing, don't forget that the actual project assignment calls for getting the input from the user. You should be able to write that as a function, too.

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

We are certainly willing and able to help, but we'd need to know what sort of help you need. What have you done so far, and where are you stuck? Do you know the basics of how to write a function, how to use Python arithmetic, and so forth? Do you know how to calculate the mean, median. etc. by hand, and how you would apply that to writing the program?

Also, what version of Python are you using (2.x or 3.x), and is there a specific environment or IDE you are using for developing the programs?

I will caution you, though: do not expect anyone here to write the programs for you. We will assist you, but we are not a free homework-solving site. Show us that you've made an effort, and we will do what we can to aid you, but we will not and cannot do your work for you.

Gribouillis commented: indeed +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

That's correct, except that either the size of the declaration should be resd (32-bit - my mistake in my earlier post) or the size of the operand should be word (16-bit). Which you want depends on the how high the score can go - 16-bit unsigned values go only to 65536, while 32-bit unsigned go over 4 billion. If you expect the scoring to exceed 65536, then use a dword or even a qword (64-bit).

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

That depends on what the label userscore is for. Is it a single dword holding the value as an integer, or is it a byte buffer holding a string? In other words, assuming NASM syntax, is it:

userscore:    resw 1  ; or 'userscore dw ?' in MASM 

or

userscore:    resb 8   ; or some other arbitrary size string

If it is a string, then yes, it would need to be converted first, then added to, then converted again. However, in that case, you may find it more useful to have userscore stored as a dword in integer form and only converted to a string when being displayed.

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

In light of the regular if slow traffic in certain specialized questions - especially regarding operating systems development and compiler development - I would like to suggest that a sticky be added to the Software Development forum giving links to specialized sites such as OSDev.org, where those sorts of questions are more likely to find a ready answer. It should be a mod-access only thread, so that it isn't flooded with questions about the subjects or with links to irrelevant sites, but there should be a suggestion to PM the mods if you have a site to add to the list. Does anyone else think this is a good idea?

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

While SenthilAnand's point is correct, and excellent advice, it is not the source of the compilation error; the compiler is perfectly happy to let you perform an assignment in the conditional, it just usually isn't what you intended and will have unexpected results when run.

The real problem is that you are putting semi-colons after each if() statement's conditional, ending the if statement. Now, once again, this is for the most part accpetable syntax, until you get to the last of the else if() clauses:

    if (sales <= 0 && commission == -1)
        ;
    else if (sales <= 10000 && commission == sales * 0.2)
        ;
    else if (sales <= 40000 && commission == sales * .05 + 2000)
        ;
    else if (sales >= 40000 && commission = sales*.1 + 17000)
        ;
    {
        //calculate and display the output
        sales = sales <= 0 ;
        commission = -1 ;
        sales = sales <= 10000 ;
        commission = sales*0.2 ;
        sales = sales <= 40000 ;
        commission = sales*.05 + 2000 ;
        sales = sales >= 40000 ;
        commission = sales*.1 + 17000 ;
        printf("\nsales %d ", totalsales);
        printf("\ntotalcommissions: %.0f%% \n\n", commission);//zero decimal places
    }
    else

(Note how I have indent the code for readability, and in particular, how I made the empty bodies of the if() statements explicit.)

Now, one thing many starting C programmers aren't aware of is that you can put a block (a section of starting with an open brace and ending with a close …

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

No, you don't. You want to stay away from gets() entirely, in fact. The function is extremely dangerous, because it is prone to buffer overruns, and no experienced C/C++ programmer still uses it.

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

If you have Windows Vista or later, you won't be able to install Turbo C++, at least not directly. Turbo C++ is simply too old, being a 16-bit MS-DOS program, and is no longer supported by modern versions of Windows. In order to install it, you would need a DOS emulator such as DOSBox, or set up a virtual machine image with an installation of DOS or an older version of Windows in it.

Personally, I would recommend against using Turbo C++ in any case, if you have any choice in the matter. I realize that there are many Universities and even national collegiate systems which have standardized on it, but it is simply outdated and trying to learn modern programming from it is going to be misleading at best. You would be better off downloading Visual Studio Express, Code::Blocks with MinGW GCC, or Pelles C in order to get a decent, modern compiler and IDE combination. This may not be an option for you, but you shold at least be aware of the limitations of Turbo C++ before installing it.

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

Well, then, that's quite a problem. What have you tried so far? Did the instructor provide all of the necessary information for you to compute the voltages? Have you discussed the matter with the instructor?

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

Well, to answer the question, the usual solution to having a multidimensional ArrayList is to declare an ArrayList of ArrayList of the type being stored:

ArrayList<ArrayList<String> > data = new ArrayList<ArrayList<String> >();

data.add(new ArrayList<String>());
data.add(new ArrayList<String>());
data.get(0).add("Alex");
data.get(0).add("31");
data.get(1).add("Burren");
data.get(1).add("Java");

However, no experienced Java developer would ever do this. The usual solution is to design a class that holds the personal data for the individual - yes, even if it is a one-off - and have the name, age, and ArrayList of pet's names as instance variables of the class:

class Person {
    public String name;
    public int age;
    public ArrayList<String> pets;

    Person(String name, int age, String ... pets) {
        this.name = name;
        this.age = age;
        this.pets = new ArrayList<String>();
        for (String pet: pets) {
            this.pets.add(pet);
        }
    }
}

public class myProgram {
    public static void main(String[] args) {
        Person myPerson = new Person("Alex", 31, "Burren", "Java");
    }
}

I made the fields public for this example to keep it simple, but usually they would be private and give them getters and setters - you wouldn't want uncontrolled access to them, in case someone accidentally changed age to -17, for example.

You'll also note that the c'tor uses a bit of an odd parameter list: the elipsis (the ...) means 'follow this with zero or more arguments of type x before this and put them in an array named y after this'. You don't need to worry too much about it, just know that it will …

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

I think you will find that the problem lies less with your program than it does with the way Notepad renders the codepoints. I don't know all of the details of how Notepad determines how to interpret the characters, but if I read what you are saying correctly, it basically only checks whether the the first few characters are in the ASCII range, and if they are not, it interprets the file as UTF-8; but if the first character is in the ASCII range, it interprets the file as ASCII (or more likely, either LATIN-1 or ISO-8859-1). The stream of bytes you are writing is correct; it is the interpretation of them that Notepad uses that is at fault.

If anyone knows how to force Notepad to interpret a file as UTF-8, please speak up. This video purports to explain how, but it is not a trivial process, and appears to involve registry changes.

In the meawhile, I would instead use an editor that supports multiple encodings such as Notepad++ or TextPad.

However, if the real issue is permitting your user base to edit the file manually, then that is a serious problem with no obvious solution.

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

(most IDE's refer to "intellisense" as "Code Completion", especially for linux)

That's because the term 'Intellisense' is a trademark of Microsoft. Other developers can't use that name. In any case, 'auto-completion' was the term used long before Microsoft introduced their version of it.

As for IDEs, I think both PyCharm and Eric have good auto-completion, but I'm not sure if either one have quite the feature you are looking for.

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

First off, you'll want to use the tab escape sequence, "\t", rather than the tab character itself in your string replace. Second, your are returning the function at the end of the first pass of the loop; you seem confused as to how you want the function to work, whether it should operate on the input directly or take a local argument. I would recommend re-writing it to take a string argument and return the modified string, then call it from a loop that does the actual input and output.

On the subject of input and output, if you are writing a filter, I would recommend a with statement on sys.stdin and a loop on readlines() rather than an explicit input() statement.

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

I would probably need to add a case for it in the switch in LexicalAnalysis.cpp, right? And add it to the state diagram?

If you want them as separate token types, then yes to both, though most languages treat all whitespace as a single token type.

The answer to the last part would depend on whether you are trying to represent the actual newline (which can be either a single byte or two bytes, depending on the operating system), or the escape representation of the newline. I assume you want the newline itself, in which case you would use the latter version.

You would only need to parse the escape form when handling character and string literals, and since this mini-language doesn't have any quoted literal token types, it isn't relevant. Not yet anyway - you'll want to keep it in mind when you start working on more elaborate language forms later.

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

No.

The rule at DaniWeb are simple:

Do provide evidence of having done some work yourself if posting questions from school or work assignments

We can provide assistance, but we cannot do the work for you. You must solve the problem, if you are to learn from it. Otherwise, you are cheating, something we cannot condone, and even if we did, you would be likely to get caught. Do the work yourself; we've given you more than enough information to solve the problem.

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

I assume that the OP is referring to XMBC Media Center, but I don't know enough about it myself to make sense out of the question, either. I would suggest that the OP seek help on the XMBC forums directly, as there presumably would be people familiar with the program in question.

I will recommend one other thing, as a general principle in Python programming. Rather than having the extended if-elif/else statement you have from lines 22-53, it would be better structured and more Pythonic to make a lookup table consisting of a range and a value. A simple representation might be a dictionary where the key is a tuple pairing the startpoint and endpoint of the length range, and the the second value is the width. You would then have a function to extract the values from the dictionary as needed. Something like this should work:

def get_program_width(program_length):
    width_map = {(10, 60): 342.5, (60, 90): 690, (90, 105) : 1050, 
                 (105, 120): 1400, (120, 150): 1750, (150, 180): 2100, 
                 (180, 210): 2450, (210, 240): 2800, (240, 270): 3150, 
                 (270, 300): 3500, (300, 330): 3850, (330, 360): 4200, 
                 (360, 390): 3250, (390, 420): 4550, (420, 450): 4900, 
                 (450, 480): 5250}

    keylist = width_map.keys()

    for key in keylist:
        if program_length in range(key[0] + 1, key[1] + 1):
            return width_map[key]
    return 0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Except that SQLite is a completely different database system.

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

Actually, you've misunderstood what the term 'SQL injection' means, and fortunately for you, your script doesn't involve any. All your code does is open a connection to a MySQL database server and create a cursor, the basic steps interacting with a database.

SQL injection is a (bad) way of building a SQLquery string, in which user input is inserted directly to a text query string and then executed:

name = raw_input("What is your name?")
cur.execute("SELECT * FROM Students WHERE Name = '%s';" % name)

The reason this is a bad idea is the same reason while it was a bad idea to use input() in Python 2.x: because the user could put anything into the input, not just their name, and the 'data' will get executed along with the query. For example, if I entered Robert'; DROP TABLE Students; --, the final query string would read

"SELECT * FROM Students WHERE Name = 'Robert'; DROP TABLE Students; --';"

which would wreak havoc on the database.

The way to avoid SQL injection is to use a prepared statement, which is a feature of the database that vetts the data automatically for you, making the above scenario less likely.

name = raw_input("What is your name?")
cur.execute("SELECT * FROM Students WHERE Name = %s;", (name))     

This may seem like a trivial difference, but when using the prepared statement, the database checks the validity of the interpolated data, making sure that the cannot execute …

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

I realize that we seem to be dragging our feet, but the thing is, we are trying to avoid the many people who are trying to get free homework solutions. We get such things all too often, and as a result, we generally don't geive direct solutions, only advice.

In this case, there are a few things that stand out. First, it is hard to see where synchronized would come up in this, since there aren't any shared values anywhere. I realize you are trying to understand thread synchronization better, but this example doesn't seem to need it.

Second, the way you currently have things, the first thread is completing before the second thread is begun (indeed, given that it is just a single assignment, it probably completes before you .join it), which, as I understand it, has the effect that the instance variable is no longer in scope even if you access it from the thread object. Any corrections on this would be appreciated, BTW.

Third, as JamesCherill pointed out, you want to use e.printStackTrace() rather than e.getStackTrace() on line 29, in order to see the results of the exception, if one is raised. As it is, it fetches the stack trace but does nothing with it.

If this is an assignment, could you please post the exact wording of the project? That will help us get an idea of what you need. Ordinarily, we wouldn't ask for that, but the program requirements aren't very clear as to why, …

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

The difference is that when you were creating ob in Checking, were were creating an object in each thread, which meant that they weren't shared between the different threads - each thread was synchronizing a different object. You need to have a shared object to synchronize on if you are trying to provide mutual exclusion.

By constructing the single object in main(), and more importantly, passing that single object to all three threads, all three threads share the object. That is what the synchronized block is for - for controlling access to a shared resource. If you aren't sharing the resource, then synchronized will have no effect.

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

The first thing I would recommend in starting out with Python is finding a good Integrated Development Environment, oe IDE; while IDLE, the one that comes with Python, is passable, it is not really new-user friendly and takes a bit of getting used to. Unfortunately, 'good' is very subjective when it comes to IDEs, so you might find yourself trying a few before you come across the best fit. This thread and this one discuss the matter at length, without really giving a solid answer, for example. My personal choices are PyCharm (if you are willing to shell out for it) and Eric (which is free), but they might be a bit overwhelming to a novice. If you are planning to stick with Python 2 - not recommended, but many do - then Dr Python is excellent for novices. Still, you need to try a few out to get the one you are comfortbale with.

So why is the IDE so important, when all you really need is Notepad and an open shell window? Convenience, primarily. A good Python IDE will have both an editing window and an interpreter window in plain sight, making it easy to use the Python listener (the interactive interpreter) to test things in, while still having access to the program you are writing. Also, a good IDE makes it easier to work with more than one source module, when you get to that point in …

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

What have you tried so far, and what problems are you having with it? Please include at least enough of your source code to explain any difficulties you are experiencing.

Keep in mind the following DaniWeb community rule:

Do provide evidence of having done some work yourself if posting questions from school or work assignments

And be aware that we will not do your homework for you.

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

That, plus you may want to have a little patience. Fora like this aren't IM or Twitter; they are more like email, where you might have to wait hours or even days before a response. OTOH, it also means that you aren't limited to 140 characters, so posts can be a good deal longer than on more rapid forms of communication. You should learn to take advantage of this, and stop posting one-line messages here.

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

Hmmn, I gather from the downvote that I went a bit too far in helping this particular person. Either that, or the fact that I did a favor for a help vampire like the OP offended someone. In either case, I do apologize, and will be more circumspect in the future.

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

My optimism in others' good intentions is battling with my pessimism about help vampires (which the OP is quickly proving herself to be). Still, in the hope of giving her at least a leg up, I'll try to give what advice I may.

a) Explain how the computer passes control to a subroutine (or procedure) and returns it to the main routine once the task has been completed.

The basic mechanism, inside the compiled code, consists of saving the address of the location in memory just past where the function call is made, and jumping to the function. When the function ends, it retrieves the address and jumps back to the location it was called from. There are a few different ways this can be done, such as linkage registers and function windows, but the usual method is to save the return address on the hardware stack. There! That's enough information to get you started, but not by any means a full explanation.

b) Explain, giving a relevant example, how a subroutine (or procedure) can be used several times in the same program, each time accepting different data values and passing back different results.

Hint: All of the standard C and C++ I/O stream operations are actually library functions. Have you ever used printf() or cout << more than once in a program?

c) ABS and INT are two numeric data handling functions found in many languages. Explain what EACH of the following …

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

Good to meet you, though I should point out that such introductions really ought to be posted to the 'Community Introductions' forum, rather than one of the language fora. Since you are new, I don't think anyone will fault you for it, but it is something to be aware of if you are going to any other message boards in the future.

For now, please read the forum rules and get to know what's going on. If you haven't any specific questions right now, you might want to lurk for a bit, and try the social fora as well. Again, good to have you on board.

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

jwenting: I agree that it certainly looks like that, and for all I know you may be right (the part suggesting it compile more than one language is particularly damning), but I prefer to give the benefit of the doubt for cases like this. I'd rather hear from the OP to see what they have to say for themselves before jumping to that conclusion.

Even if you are right, I'd rather treat it as an opportunity to teach something useful to someone rather than simply smack them down for their ignorance. Seeing how the OP hasn't replied to anything said so far, it is likely a moot point anyway; I am well aware, just as you are, that the majority of first-time posters never return. That doesn't mean we shouldn't make an effort to help those who eventually do.

(I'll also admit a bit of personal interest in this anyway, as language design and translation is one of my main interests in the field. I have a very ambitious ongoing project of my own in this area, though I have deliberately kept the core language minimal precisely to make it feasible to complete in a few years' time. That, plus the choice of Lisp dialects for both the implementation language (R6RS Scheme) and the source language (Thelema) - and even the target language (my Assiah x86 assembler) - mean I have some real shot at finishing it in a reasonable time frame. Even so, a 'reasonable …

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

If you have a question like this, please start a new thread rather than resurrecting a long-dead one like this.

As for why printf() and scanf() aren't used in Java very often, well, to begin with, ther is no scanf() method in the standard Java library. Rather, the Scanner class is used for the same purpose, which not only has fewer issues than the C style scanf(), but gives better control of the input.

As for printf(), it was introduced into the language fairly late on, and is usually only used for fairly complex string formatting; most of the things which you would use printf() for in C are handled better by the overloaded forms of print() and println(). Even with complex formatting, it is more common to use the String.format() mathod to do the string interpolation, then display the generated string with print().

I should add that even in C, scanf() has fallen into disuse for most modern programming, as it has a number of pitfalls to it. Today, most experienced programmers use fgets() to get the input and then parse the string using sscanf(), which is more secure and less prone to buffer overruns and newline issues.

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

The purpose of the d'tor is not to free the object itself; that is done by delete, which should only be applied to dynamically allocated memory (that is, values allocated using new) in any case. Also, freeing the object does not overwrite the object; the memory itself is is still unchanged, at least for the time being, and in order to ensure that a pointer variable no longer points at that now-invalid memory location, you need to assign a new value (such as 0) to it.

The purpose of the destructor is to clean up the elements of the objects that are not automatically released when the object itself is freed: deleteing any dynamically allocated instance values, closing files, releasing semaphores, and the like.

As sepp2k said, the d'tor should almost never be called directly. However, if a class has a d'tor, it is called automatically when an object of the class is freed, whether by means of delete or when a local goes out of scope.

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

It would be impossible to say without more information, as the term Mealy Machine refers to a class of Finite State Automata, not a specific FSA. You would have to know the state transitions for the specific machine in order to determine what the output would be.

iqra aslam commented: can u please draw a mealy machine and pass the input from it +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There was a time when mad skillz was sufficient. In the 1970s, just claiming to be an assembly programmer would get you a high-paying job; in the mid-1980s, a C programmer with any experience might as well own the Philosopher's Stone; in 1995, you could walk into a company with an HTML book under one arm and get hired. But for the past fifteen years, most employers are looking for a good deal more than just the ability to copy code out of a book or off of the web.

C++ is an excellent starting place for a career, but it is not in and of itself enough, unless you are prepared to slog through ten years of small contracts from freelancer.com to earn enough experience to qualify for a entry-level corporate position - and even that is unlikely to work, as almost all companies today require a college degree for any position higher than janitor. At minimum, you'll need some sort of certification, and there are none specifically for C++ that are universally accepted.

Knowing anough about basic data structures and algorithms is just the tip of the iceberg. You need to know about the common tools (version control, various IDEs - you'll often be different environments in different jobs - the command-line toolchains, wikis, build tools such as Make, Ant, or Maven, and so on), common methodologies, common libraries, and common operating system APIs. You'll need to know how to work with programs written in other …

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

Well, I don't think going from a long to a short will help.

BTW, I suggest you look at where the comment is in relation to the modulo expression.

    b=a/2;                /*Formula for Decimal
    c=a%2;                  to Binary*/

As you have it here, the second line is getting commented out entirely.

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

OK, I've finally got Netbeans running and connecting to a local (embedded) database that I created manually with IJ, so I've got a handle on what you are talking about. As it happens, there is a way to add a foreign key to a table in Netbeans, but it isn't quite intuitive.

What you need to do is create the attribute (that is, the field) you are going to use as a foreign key in the table you are relating, making sure it is the same type as the key of the table it relates to. Then, after you have saved the table, you go to the table's etry under the database, and open the tree node so that it shows the indexes and foreign keys. Right click on foreign keys and select Execute Command. You then would code an ALTER TABLE statement in the Command window to add the FK constraint.

For example, in the database I created, I have a table State with a NUMERIC primary key id, and a twoCHAR field state for the abbreviations of the US states. In another table, Address, I have a NUMERIC key state which I will set a foreign key constraint on:

ALTER TABLE APP.Address
ADD CONSTRAINT address_state_fk
FOREIGN KEY (state) 
REFERENCES State (id)

I then hit 'SQL Execute' to add the constraint.

There may be any easier way to do this, but this way does work.

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

It shouldn't be too much for a lambda expression, so long as you recall a) that you can use a boolean expression such as in in a regular statement, and b) the string library includes a handy set of constant strings with the sets of letters, digits, and whitespace. All you should need to do is import string and apply in to your string's first character, and string.digits, and you should be able to use that as the lambda expression.

(OK, I'm sandbagging on this, as I've tested it and it works fine in Python 3.4, but I feel it is better to lead you to the code than simply give it to you. In this case, the explanation should be more than adequate for you to get the appropriate code worked out.)

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

I the absence of other information, I would recommend trying the -I option with the path to the header files in question.

g++ -Ipath\to\include main.cpp program1.cpp -o program1.exe

However, if they are in the path already that shouldn't be necessary, so there may be more to this than that.