• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Thanks for the help!

I did it in a very crude way, I think. I just created a common variable between the nodes called index and when I wanted to get a specific node, I just traversed through the list and stops when it reaches the index I wanted.

I'm sure there's a better way of doing this though but this will do for now.

No problem!

That should work for now, but ideally you would want to be searching based off of one of the element's of the node. (The "lastName" variable, for example.) That way you wouldn't have to be keeping track of indexes anywhere, especially since lists don't have to be sorted or anything. You could run into a bit of trouble later when removing and adding new nodes.
 
I started using it in addition to usings to prove to a third party vendor that it wasn't my code causing their Oracle databases to not let release their connections. Now it's just habit.

Drop that habit. ;) It's probably not a particularly egregious one, all things considered, but adding extra fluff and redundancy to code is usually only a bad thing, it's more cruft to have to wade through when trying to maintain the code in the future.

The "using" construct is just syntactic sugar, the compiler already expands it to a try/finally for you. I haven't peeked at the language specification recently, but from memory, it will take a snippet of code that looks like this:

Code:
using (SomeDisposableResource foo = new SomeDisposableResource())
{
    foo.Frob(); 
}

And expand it to this during compilation:

Code:
SomeDisposableResource foo = null; 
try 
{
	foo = new SomeDisposableResource();
	foo.Frob();
}
finally
{
	if (foo != null) 
	{
		((IDisposable)foo).Dispose();
	}
}

It might throw an extra temp variable in there, I don't remember, and call dispose on that instead (setting it equal first to the variable in code). But that's basically the rough outline of it.
 

GaimeGuy

Volunteer Deputy Campaign Director, Obama for America '16
Interesting conundrum on a personal project I'm doing:
I have class ObjectPool, abstract class AbstractObject, and derived classes ObjectB, ObjectC, and ObjectD

From the ObjectPool, I want to be able to reset member variables of an instance of AbstractObject to a default state, from the bottom up. The idea is that each derived class handles members declared within its scope, and then tells its superclass to deal with any of the inherited members.

So AbstractClass:reset() would need to be public and virtual so that the pool can call it, but I want a protected implementation which can also be called by ObjectB::reset(), ObjectC::reset(), and ObjectD::reset().

I guess I could define AbstractClass::initialize() as a protected method for the protected implemention described above, but it seems like a hackjob.
 

Water

Member
Interesting conundrum on a personal project I'm doing:
I have class ObjectPool, abstract class AbstractObject, and derived classes ObjectB, ObjectC, and ObjectD

From the ObjectPool, I want to be able to reset member variables of an instance of AbstractObject to a default state, from the bottom up. The idea is that each derived class handles members declared within its scope, and then tells its superclass to deal with any of the inherited members.

So AbstractClass:reset() would need to be public and virtual so that the pool can call it, but I want a protected implementation which can also be called by ObjectB::reset(), ObjectC::reset(), and ObjectD::reset().

I guess I could define AbstractClass::initialize() as a protected method for the protected implemention described above, but it seems like a hackjob.
The reason that feels like a hackjob to me is that every derived class' reset() has to manually call the protected implementation in base class, and you might conceivably also forget to do it.

How about this: make reset() a nonvirtual final function in AbstractClass, have it reset AbstractClass' members and then call a protected reset_impl() function which is pure virtual? That way you only have to write the derived class' stuff in reset_impl().
 

Roubjon

Member
Any MIPS Assembly language experts here? I thought I might as well ask you guys this question, because why not.

I'm writing a program in MIPS Assembly Language that requires you to check each individual character in a string. To do this I know I have to iterate through the array character by character, but it isn't working.

Here are pieces of the relevant code:

.text
.globl main

main: li $v0, 4 #Command for print string.
la $a0, prompt #Start addr. of prompt string.
syscall #Prompt user for text.

li $v0, 8 #Command for read string.
la $a0, string #Buffer.
li $a1, 81 #Max. no. of characters (incl. newline).
move $10, $a0 #Move the buffer string into $10.
syscall #Read the string.

lbu $11, 0($10) #This is first character in string.

jal initial #Jump to the intial function.
jal parse #Jump to the parse function.

and then whenever I want to increment the index location, I just do this at a certain point inside the parse function:

nextIndex: addi $10, $10, 1 #Move onto the next index of the array.

I think it should be working, but it isn't. Sorry about the shitty formatting, but I can't get it to look any better. I'm not really expecting anyone to help out, but thanks for reading anyways lol.
 

GaimeGuy

Volunteer Deputy Campaign Director, Obama for America '16
The reason that feels like a hackjob to me is that every derived class' reset() has to manually call the protected implementation in base class, and you might conceivably also forget to do it.

How about this: make reset() a nonvirtual final function in AbstractClass, have it reset AbstractClass' members and then call a protected reset_impl() function which is pure virtual? That way you only have to write the derived class' stuff in reset_impl().

I thought about that, but what if I only want to implement the reset_impl() stuff for objects of class B right now, but may extend it to C and D in the future? Going pure virtual forces me to do it all in one go.

Mixing the two ideas together, if we have reset() be a public nonvirtual final function in abstractClass, and reset_impl() be a protected virtual function (moving the resetting of AbstractClass's members to the implementation defined in the base class)... do we get the behavior I desire?
 
C#.

Anyone here have good experience with timers? Programming in Visual Studio, I've been working on an amateur game for the last few days (just for fun of course; nothing that I'll release). It's a turn-based game, and I'd like there to be a pause between the player attacking the enemy and the enemy attacking the player. This method happens when the player presses the physical attack button:

Code:
        private void btnAttackPh_Click(object sender, EventArgs e)
        {
            DisableAttackButtons();

            int playerDMG = CalculateAttackDamage(PlayerStrength);
            EnemyAttacked(playerDMG);

            //tmrCombat.Tick

            int enemyDMG = CalculateAttackDamage(EnemyStrength);
            PlayerAttacked(enemyDMG);

            if (PlayerCurrentHealth != 0)
                EnableAttackButtons();
        }

I was thinking I could make it so that you have to wait for the timer to tick (one second wait or maybe one and a half seconds), but I'm not sure how to make it work. Googling hasn't been of much help but I'll keep Googling and see if I can find something.
 

pompidu

Member
If any SQL gurus could point me in the right direction on this would be a huge help. I'm learning SQL and want to create a report that would generate the Account #s under the same Person ID that were created <= 30 days of each other and exclude any others. All the information needed is in the same table.

For example this code pulls up a list of Person's who have more than one Account and their Creation date:

Code:
	select accounttid, creationdate, personid from Table1 where personid in ( 
	select (personid) from Table1 group by personid having COUNT (accountid) > 1)
	
	accountid	creationdate	personid
	5501624	2013-05-01	101
	5501544	2013-05-03	101
	5510220	2013-10-24	10337
	5504204	2013-06-27	10337
	5502332	2013-05-21	1047
	5502628	2013-05-28	1047
	5508844	2013-10-01	1047

Not sure where to go from here. I want to then take these Account numbers and somehow compare the Creationdates for less than or equal to a 30 day differential but only compare them when the Person IDs are the same.

try this http://stackoverflow.com/questions/6584666/whats-wrong-with-this-less-than-date-query
 

CronoShot

Member
So I'm trying to write a program in C that reads information from a file and puts it into a structure, but includes spaces, something like:

Code:
Sanders        Nathan         1778 N. Deer Run              Detroit             MI45634B
Wilson         Dylan          12345 N. Malibu Beach Blvd    Irvine              CA97894I
Stewart        Connor         13456 E. Wilshire Blvd        Santa Monica        CA97845I

where I read the last name into part of the structure, first name into part of the structure and so on. Basically, I want to say "characters 1-15 go into the last name portion of the structure, characters 16-30 go into the first name portion", etc. etc. But I also want to include the spaces from stuff like the address and city.

How on earth would I do something like that? My only experience with reading from a file is reading numbers.
 

Jokab

Member
So I'm trying to write a program that reads information from a file and puts it into a structure, but includes spaces, something like:

Code:
Sanders        Nathan         1778 N. Deer Run              Detroit             MI45634B
Wilson         Dylan          12345 N. Malibu Beach Blvd    Irvine              CA97894I
Stewart        Connor         13456 E. Wilshire Blvd        Santa Monica        CA97845I

where I read the last name into part of the structure, first name into part of the structure and so on. Basically, I want to say "characters 1-15 go into the last name portion of the structure, characters 16-30 go into the first name portion", etc. etc. But I also want to include the spaces from stuff like the address and city.

How on earth would I do something like that? My only experience with reading from a file is reading numbers.
Which language?
 

Never mind, I managed to solve it :)

Like so:

Code:
        private void btnAttackPh_Click(object sender, EventArgs e)
        {
            DisableAttackButtons();
            btnTutorial.Enabled = false;

            int playerDMG = CalculateAttackDamage(PlayerStrength);
            EnemyAttacked(playerDMG);

            tmrCombat.Start();
        }






        private void tmrCombat_Tick(object sender, EventArgs e)
        {
            if (CurrentEnemyHealth != 0)
            {
                int enemyDMG = CalculateAttackDamage(EnemyStrength);
                PlayerAttacked(enemyDMG);
            }

            if (PlayerCurrentHealth != 0 && CheckLevel == false)
            {
                EnableAttackButtons();
                btnTutorial.Enabled = true;
            }

            tmrCombat.Stop();
        }
 

CronoShot

Member
I think you've basically got it. What don't you understand?

Read the file line by line. For each line, follow any string copying tutorial to copy characters from the positions you're interested in into the appropriate places in your struct.

I guess the main thing I'm confused about it how to select certain character positions.

I know how to copy the first 15 characters into last name, but how do say I want characters 16-30 to be in first name? How do I start in the middle of a line, and include spaces as well in certain spots, but not in others?
 
How do I start in the middle of a line, and include spaces as well in certain spots, but not in others?

String is just an array of characters in C, isn't it? Do you know how to do something with the middle n elements of an array? As for getting rid of white space in some cases and not in others, either make two functions or make your parsing function do either depending on an input parameter.

If you want to trim off surrounding white space, increment the starting character until it's not a space, and decrement the ending character until it's not a space, then copy the characters betwixt.

If any SQL gurus could point me in the right direction on this would be a huge help.

This may be useful: Sql date select rows within X seconds range of each other.
 
I don't know a thing about C (yet!), but C# is built on C, so maybe I can be of a little use. Like CrudeDiatribe said, a string is an array of characters. For-loops are great when using arrays. You can use them to get just the characters you want. As for removing spaces, in C# you can use ".Trim()" after the string. There are other various Trim commands that delete all spaces. ".Trim()" only deletes those at the start and end of a string, so string x.Trim() = " h j "; would be string x = "h j";. But yeah, this might not work in C so I'm sorry if I'm not helping :)
 

tokkun

Member
You can trim whitespace from the end of a C-string like this:

Code:
int pos = strlen(my_string) - 1;
while (isspace(my_string[pos]) && pos > 0) {
  my_string[pos--] = '\0';
}

There are other ways to do it, but the basic idea is to set the character immediately after the last non-space character to the null byte, '\0'.
 

CronoShot

Member
I suppose I'm still just confused on how to read the line from the file. I know how to copy from an array, but do I copy each line to an array in my program, then copy the pieces from that into my struct? Is there a way to do it directly?
 

usea

Member
I suppose I'm still just confused on how to read the line from the file. I know how to copy from an array, but do I copy each line to an array in my program, then copy the pieces from that into my struct? Is there a way to do it directly?
You should do whatever is simplest. In my opinion, it's much simpler to copy the whole line from the file into a string, and then edit the string afterward.

In fact I'd copy the entire file to memory first, then operate on each line separately. Unless the file you're reading from is huge and performance/space concerns matter, simpler is always better.
 
Just finished taking my Intro to C++ course final. First part was 70 multiple choice question and the second part was writing 3 programs out on paper. The first part I feel I did really good on, that second not so much. I find that if I can't reference internet source when programming or receive feedback from the compiler, I struggle.I have maintained a grade of 90% throughout this semester, yet it's apparent that I need to apply more coding time to my schedule. I'm so disgusted with myself right now.
 
Just finished taking my Intro to C++ course final. First part was 70 multiple choice question and the second part was writing 3 programs out on paper. The first part I feel I did really good on, that second not so much. I find that if I can't reference internet source when programming or receive feedback from the compiler, I struggle.I have maintained a grade of 90% throughout this semester, yet it's apparent that I need to apply more coding time to my schedule. I'm so disgusted with myself right now.

Don't be so hard on yourself, that sounds like a bloody hard test! I don't think I've ever had a 70 question AND 3 program final, or anything near that. Especially for an intro course.

(I'm also not particularly fond of tests that require you to code on paper, since it doesn't really reflect at all on a person's real abilities to code. At least if they mark you off for things like syntax errors. I'm fine with them grading some code on paper if they're much more concerned that you understand the concepts and the logic behind the program, rather then syntax and obscure methods. It's another level of absurdity when you get points knocked off for missing a semicolon on code written on paper.)
 
Doing some Java. How do I repeat that string ten times by doing a loop in a loop?


public class Uppgift2 {
public static void main(String[] args)
{
String emil = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
for (int i = 0; i < 25; i = i + 1)
{
System.out.print(emil.charAt(i));


while (){

}


}
}
}
 

Jokab

Member
Doing some Java. How do I repeat that string ten times by doing a loop in a loop?

//code

First of all, use the
Code:
 tag to post code, it looks much nicer. Like so:
[code]public class Uppgift2 {
	public static void main(String[] args) 
	{
		String emil = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
		for (int i = 0; i < 25; i = i + 1)
		{ 
			System.out.print(emil.charAt(i));
	        }
	}
}

Second, you have the printing of the string down, which involves printing 25 characters from the string. Now you want to print that whole thing 10 times. So you'll want to wrap the printing for-loop in another for-loop which simply executes the printing 10 times.
 
Looks like I have an interview on Monday for a job as the webmaster for the CS department at my school. (Apparently some people still call them webmasters...)

Anyway, hoping I get it. All my previous jobs during school have been off campus. That's fine, I just hate having to truck back and forth between campus and work all day long. Sometimes it ends up being like 4 or 5 round trips a day to get to all my classes and work...having a job on campus would be great.
 
Don't be so hard on yourself, that sounds like a bloody hard test! I don't think I've ever had a 70 question AND 3 program final, or anything near that. Especially for an intro course.

(I'm also not particularly fond of tests that require you to code on paper, since it doesn't really reflect at all on a person's real abilities to code. At least if they mark you off for things like syntax errors. I'm fine with them grading some code on paper if they're much more concerned that you understand the concepts and the logic behind the program, rather then syntax and obscure methods. It's another level of absurdity when you get points knocked off for missing a semicolon on code written on paper.)

Thanks for the encouragement. Good luck on your job interview
 

Korosenai

Member
Need help with a program. I have to find the minimum and maximum from two arrays, using a function template, then output it on the screen. So here is my main function:

Code:
int main()
{
    int int_array[8] = {5, 1, 3, 6, 9, 8, -1, 4};
    min_and_max(int_array,8);
    
    char char_array[8] = {'C', 'T', 'K', 'A', 'V', 'B', 'D', 'E'};
    min_and_max(char_array,8); 
    
    return 0;
}

and here is my function template:

Code:
template <class L>
void min_and_max (L my_array, int size)
{
    int count;
    int max, min;
    
    min = my_array[0];
    for (count = 1; count < size; count++)
    {
        if (my_array[count] < min)
            min = my_array[count];
    }
    
    cout << "Output:" << endl;
    cout << "Min: " << min;
    
    max = my_array[0];
    for (count = 1; count < size; count++)
    {
        if (my_array[count] > max)
            max = my_array[count];
    }
    
    cout << ", Max: " << max << endl;
}

Here is the output i'm getting vs. the one I should be getting:

Code:
What i'm getting
Output:
Min: -1, Max: 9
Output:
Min: 65, Max: 86

What I should be getting
Output:
Min: -1, Max: 9
Output:
Min: A, Max: V

I know the problem is right here with this bit of code:
Code:
int max, min;
Where I initialize min and max as integers, because when I switch them with char then I get the reverse result. I'm just not sure how to fix the code.

edit: I changed my code to this:

Code:
L max, min;

And now these are the errors i'm getting: http://i.imgur.com/m9FkRRG.png

It's saying the arrays are not assignable.

double edit: Nevermind I fixed it.
 
Just finished taking my Intro to C++ course final. First part was 70 multiple choice question and the second part was writing 3 programs out on paper. The first part I feel I did really good on, that second not so much. I find that if I can't reference internet source when programming or receive feedback from the compiler, I struggle.I have maintained a grade of 90% throughout this semester, yet it's apparent that I need to apply more coding time to my schedule. I'm so disgusted with myself right now.

I honestly didn't even know that multiple choice questions were still a thing. It's not a good way to do a test at all. And why are you disgusted with yourself, man? You have no reason to. Ever.

(I'm also not particularly fond of tests that require you to code on paper, since it doesn't really reflect at all on a person's real abilities to code. At least if they mark you off for things like syntax errors. I'm fine with them grading some code on paper if they're much more concerned that you understand the concepts and the logic behind the program, rather then syntax and obscure methods. It's another level of absurdity when you get points knocked off for missing a semicolon on code written on paper.)

Requiring you to write code on paper is great in my opinion, though of course it shouldn't be huge. A program written in code on paper should never be longer than a page, and obviously if you get a point off because you missed a semicolon then something is seriously wrong with the school you're at. Syntax errors don't matter. What matter is that you show that you know how to solve something. That you know how to think and how to use various methods.
 
Simple probability type question:

I'm working on a simple simulation of lets say the propagation of a forest fire or something. Starting with a point in a matrix, each point surrounding it has an [x]% chance of catching fire and each point that surrounds a point on fire has an [x]% chance of catching on fire as well.

Right now I just do

Code:
matrix[ i ][ j ] = (rand( ) % 100 <= percent)

for each 8 blocks surrounding the point i, j. percent is a number from 0 to 100 inclusive.

I think that's what I want and the simulation does appear to do exactly what I want it to do, I just figured I'd see if there was any other ways of doing this.
 

maeh2k

Member
Simple probability type question:

I'm working on a simple simulation of lets say the propagation of a forest fire or something. Starting with a point in a matrix, each point surrounding it has an [x]% chance of catching fire and each point that surrounds a point on fire has an [x]% chance of catching on fire as well.

Right now I just do

Code:
matrix[ i ][ j ] = (rand( ) % 100 <= percent)

for each 8 blocks surrounding the point i, j. percent is a number from 0 to 100 inclusive.

I think that's what I want and the simulation does appear to do exactly what I want it to do, I just figured I'd see if there was any other ways of doing this.

Nothing wrong with that. Just make sure you don't overwrite a burning cell with false. And depending on the rest of the function you maybe don't want to spread the fire too far in one iteration (spreading from cells you just set to true).

You could use a slightly modified breadth first search or you can just go over all cells each iteration.
 

midramble

Pizza, Bourbon, and Thanos
I figured this would be a good place to ask.

Could any of you suggest a good OpenCL book?

I'm pretty familiar with OpenGL but I'm going to be diving into a lot of high performance GPU calculation stuff in the next few months so I figured I should brush up on my OpenCL.
 
Nothing wrong with that. Just make sure you don't overwrite a burning cell with false. And depending on the rest of the function you maybe don't want to spread the fire too far in one iteration (spreading from cells you just set to true).

You could use a slightly modified breadth first search or you can just go over all cells each iteration.

That's what I thought. And yeah I was running into that issue earlier so since each cell is either 1 or 0, a simple
Code:
if(!matrix[ i ][ j ])
fixes that. The board itself is about 10 tiles bigger in each direction and iterates through a space the size of the original dimensions so it doesn't segfault.

It's for a larger cellular automata project so I'm just iterating through all cells.
 
Requiring you to write code on paper is great in my opinion, though of course it shouldn't be huge. A program written in code on paper should never be longer than a page, and obviously if you get a point off because you missed a semicolon then something is seriously wrong with the school you're at. Syntax errors don't matter. What matter is that you show that you know how to solve something. That you know how to think and how to use various methods.

What benefits does doing that on paper have over writing it on a computer with a compiler and linter?

I'm not saying that there aren't any benefits, I'm just curious what your arguments for doing it on paper are.
 
What benefits does doing that on paper have over writing it on a computer with a compiler and linter?

I'm not saying that there aren't any benefits, I'm just curious what your arguments for doing it on paper are.

I know in my case if I just jump to the keyboard and a text editor I'll kind of get stuck on what I'm supposed to do. When I get behind a keyboard to do something I end up jumping around a lot and trying to get everything done at once.

For example right now I'm working on parallelizing a project I've been working on and that requires me to deal with inter-process communication and shared buffers and all the fun stuff, and I'm currently prototyping it out on paper because it requires me to think step by step with the added plus of being able to draw diagrams where needed to make sure my thought process is correct.
 

fallagin

Member
Any MIPS Assembly language experts here? I thought I might as well ask you guys this question, because why not.

I'm writing a program in MIPS Assembly Language that requires you to check each individual character in a string. To do this I know I have to iterate through the array character by character, but it isn't working.

Here are pieces of the relevant code:



and then whenever I want to increment the index location, I just do this at a certain point inside the parse function:



I think it should be working, but it isn't. Sorry about the shitty formatting, but I can't get it to look any better. I'm not really expecting anyone to help out, but thanks for reading anyways lol.

Oh hey, this is probably a little late, I'll try to help as much as I can though.

First off, you probably know this, but make sure that you aren't overwriting important registers in your functions. A good way to do this is to use calling conventions with the registers.

You seem to be naming some of your registers by their numbers, which works, but it is harder to use calling conventions in this manner. Instead of using $10 and $11, you should be using the registers as $t0 - t9 for caller saved registers(meaning you save them before calling a function if needed; they are also called temporary registers because they can be overwritten by called functions without having to save) and $s0 -$s8 for callee saved registers(meaning the called function saves them if it is going to use them).

In order to give more specific advice I will probably need to see the rest of the code and maybe some more detail on what you are trying to do and what is going wrong.
 

hateradio

The Most Dangerous Yes Man
Does anyone know the search engine where you can enter peculiar programing code (like Scala's "<:<", since searching for "<:<" doesn't turn up anything) and get the result on how to use it/where it is in its API?

Ironically, I can't find it.
 

Onemic

Member
Anyone know how to read a text file into a struct array? I've been trying to figure out how to do so to no avail.

Here's the function header

Code:
int getRawData(FILE* fp, struct nameRecord records[], int currSize)

where the first parameter is passed a file already open for reading, the second an array of nameRecord structs, and the third the number of records currently in that array. The function is supposed to read the data from the file into the array placing it at the end of the array. It then returns the total number of records in the array after reading the file.

I'm also at a loss at initializing the number of elements for the nameRecord struct array. We've never been taught memory allocation and the problem doesn't make any mention of how many records are within the files, making initialization an excercise in frustration. So far, I'm taking advice from someone at stackOverflow and using malloc, but I don't even really know what it does.

Some info on the program itself to provide context:

program will ask the user to enter a name (you may assume that the name will be no more than 30 characters long). It will then find the popularity of the name between 1921 and 2010 and print out a chart and graph. The program will then ask the user if they wish to do another analysis and repeat the process.

The program will pull information from the following data sources in determining the popularity of a name.

ontario female baby names
ontario male baby names

Note that some names are considered both male and female so your program will needs the data from both files regardless of the name entered.

here's what I have so far:

Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

struct nameRecord {
    char name[31];
    int year;
    int frequency;
};
void allCaps(char[]);
int getRawData(FILE*, struct nameRecord[], int);
void setYearTotals(struct nameRecord, int, int);
void setNameYearTotals(char, struct nameRecord, int, int);
void getPerHundredThousand(int, int, double);
void printData(double);
void graphPerHundredThousand(double);

int main(void)
{
    int currSizem = 0;
    int currSizef = 0;
    struct nameRecord *records;
    FILE* fp = NULL;
    FILE* fp2 = NULL;
    char name[31];
    printf("Please enter your name: ");
    scanf("%30[^\n]", name);
    printf("your name is %s\n", name);

//opening both male and female name files and reading them in order to get the total number of records in the array
    fp = fopen("malebabynames.csv", "r");
    if (fp != NULL) {
        printf("file opened\n");
        while(3 == fscanf(fp, "%[^,],%d,%d", records[currSizem].name, &records[currSizem].year, &records[currSizem].frequency)) {
            currSizem++;
        }
    } else {
        printf("file failed to open\n");
    }
    if(currSizem > 0) {
        records = malloc(currSizem * sizeof(struct nameRecord));
    }

    fp2 = fopen("femalebabynames.csv", "r");
    if (fp != NULL) {
        printf("file opened\n");
        while(3 == fscanf(fp2, "%[^,],%d,%d", records[currSizef].name, &records[currSizef].year, &records[currSizef].frequency)) {
            currSizef++;
        }
    } else {
        printf("file failed to open\n");
    }
    if(currSizef > 0) {
        records = malloc(currSizef * sizeof(struct nameRecord));
    }

    return 0;
}

//function that automatically capitalizes the users inputted name
void allCaps(char s[]) {
    while(*s != '\0') {
        *s = toupper((unsigned char) *s);
        s++;
    }
}
//function that reads and places the read files into the struct arrays
int getRawData(FILE* fp, struct nameRecord records[], int currSize) {
    int i;
    for(i = 0; i < currSize; i++) {
        fscanf(fp, "%[^,],%d,%d", records[i].name, &records[i].year, &records[i].frequency);
    }
    return 0;
}
 
I found this blog post about writing a simple garbage collector in C on Hacker News:
http://journal.stuffwithstuff.com/2013/12/08/babys-first-garbage-collector/

The GC was always kind of a black box to me, and while this only explains a very simple type of GC, it's still very interesting.


@ Onemic: First thing I noticed, when opening a file and checking whether it succeeded, in the case it fails, you need to exit your program. (failing to open that file seems like an unrecoverable error) I recommend using a function (say, void bail_out(char* reason, int exit_code)) that prints the cause of failure to stderr and shuts down the program. Also, if you're using Linux/Unix, you could use errno and strerror to get a detailed error description.
I've never used fscanf, but I assume it reads formatted input from a file and puts it somewhere. If you ran this code now, I think you'd get a segfault from line 35 because you're writing to memory that is not allocated. (you declare the *records pointer in line 23 but it's not initialized). You need to malloc before reading in the entries from the file. What malloc does is the following: It allocates a block of memory with the given size and returns a pointer to the beginning of this block. That memory is not initialized (that means, if you read from it, you'll get random junk, not zeroes or anything regular) and every malloc needs a corresponding free() at some point in the program or the memory leaks. (this is especially important if you allocate memory in a loop). I would try to allocate some memory for the records array (say 25 entries), then read until you have no more space left in the array (keep count of the number of entries you've written to the array) and once it's full, use realloc() to increase the size of the array.
 
Just got back from an interview. Went fairly well I think, but I couldn't for the life of me remember what normalizing a database means. I also tend to ramble a bit when I'm nervous without actually getting anywhere with what I'm saying. Hate that post-interview anxiety. =\ Gah. Oh well.
 
'sup C++ GAF, I have a nasty little request that might be better suited for stackoverflow, but I post on GAF too much as is so why not:

I have a SchedulerThread class that runs as a thread and maintains a list of std::function<>s that it's supposed to run when asked. The declarations look like this:
Code:
public:
	SchedulerThread();
	~SchedulerThread();

	void shutdown();

	void schedule(const std::function<void()>& fun, unsigned millis);
	void schedulePeriodic(const std::function<void()>& fun, unsigned millis);

protected:
	void run();

	void waitForWork();
	bool doWork();

The idea is that something scheduled to run in 20 ms should run in 20 ms, something scheduled to run in 2000 ms should run in 2 seconds, etc. scheduledPeriodic() provides the ability for the function to be rescheduled again after it runs. The functions are kept (along with the expiry time) in sorted order, so that waitForWork() can sit on the front element and know he didn't skip anything.

Blah blah blah, it works, doesn't crash, passes tests, who cares. Ok, but:

As originally written, it uses a std::multimap and a mutex to synchronize access to the map. The way it works, a priority_queue would do the job as well. (and in fact probably makes more sense than a multimap anyway)

I need schedule() to be lock-free, and "as wait-free as possible" (definition). I need a concurrent/threadsafe priority queue or sorted container or something, and I certainly don't want to write my own. Thread Building Blocks' concurrent_priority_queue comes tantalizingly close, but in their infinite wisdom they only implemented try_pop() -- and not front() or begin() or givemethefirstelementwithoutmutatingthequeueyoudumbfuckers(). I've currently implemented it using that, and it works, but I'm pop()ing and push()ing every time I schedule my delay. It's not the end of the world, but I'm kinda mad about this.

So, long story short: what are the sweet C++ concurrent data structure libraries besides tbb? Anybody have any good experiences? Bad experiences?
 

Korosenai

Member
edit: Nevermind

I always post asking how to do something, then figure it out five minutes later >.<

Your Book class only takes 3 parameters currently. Just like in your C++ code, you need to define all 7 of the parameters in the __init__ method (which is basically the equivalent of a C++ constructor). If there's going to be a variable number of parameters then set some to optional by initializing them to something in the parameter list, or using args or kwargs.

And when you call the Product __init__, you can pass in whatever variables you got when instantiating your Book object.

Something like:

Code:
class Book(Product):
    def __init__(self, pub, aut, isbn, pid, name, price, stock):
        Product.__init__(self, pid, name, price, stock)
        self.pub = pub
        self.aut = aut
        self.isbn = isbn

Damn, should have reloaded the page first. Yeah, this is exactly what I did. Already got it running and everything.

Also on a side note, i'm really loving Python. Basically it's bonus points for my class to translate my c++ code to other languages, and Python is really enjoyable.
 
I need some help converting some c++ code to Python.

Basically I need to convert this:

But it isn't working. I keep getting this error:

Your Book class only takes 3 parameters currently. Just like in your C++ code, you need to define all 7 of the parameters in the __init__ method (which is basically the equivalent of a C++ constructor). If there's going to be a variable number of parameters then set some to optional by initializing them to something in the parameter list, or using args or kwargs.

And when you call the Product __init__, you can pass in whatever variables you got when instantiating your Book object.

Something like:

Code:
class Book(Product):
    def __init__(self, pub, aut, isbn, pid, name, price, stock):
        Product.__init__(self, pid, name, price, stock)
        self.pub = pub
        self.aut = aut
        self.isbn = isbn
 
Never mind, figured how to dynamically allocate a 2D array of structs in C. Just a question, why can I access it doing something like:
array[0][0].num=4;
And not:
array[0][0]->num=4;
 

Magni

Member
script.js
Code:
$(".wtf").hover(function() {
  $("i", this).addClass("hidden");
  $("span", this).removeClass("hidden");
}, function() {
  $("span", this).addClass("hidden");
  $("i", this).removeClass("hidden");
});

index.html
Code:
<ul>
  <li>
    <a class="wtf" href="#">
      <i class="fa fa-chevron-up"></i>
      <span class="hidden">top</span>
    </a>
  </li>
</ul>

Why doesn't this work? It works on JSFiddle. It works if I copy paste the JavaScript code into the console.

So why doesn't it work despite the JavaScript file being loaded correctly (console.logs work fine). What stupid detail am I forgetting?

This is with Bootstrap 3 and jQuery 2 if it matters.
 

Kyuur

Member
Quick (maybe not so) question for you folks! I am coding in AS3, but psuedocode will do the trick.

I have a button class that takes a function as a parameter. The function is trigger upon click.

I have a need to dynamically create some buttons that perform the same function (edit value inside an Array) but for a different value depending on which button it is. For example:

Code:
Button 1 = Change Array[1] to "On"
Button 2 = Change Array[2] to "On"

As far as I can tell, there is no way to pass a parameter with function, ie:

Code:
add ( Button(clickFunction(1)) );

So it feels like I'm kind of boned. I didn't want to have to create a new class derived from Button to address this specific need, but it is looking that way. Anyone have any suggestions?

Edit: Found a solution using function closures:

Code:
add ( Button( function():void { clickFunction(1) } ) );
 

hateradio

The Most Dangerous Yes Man
Why doesn't this work? It works on JSFiddle. It works if I copy paste the JavaScript code into the console.

So why doesn't it work despite the JavaScript file being loaded correctly (console.logs work fine). What stupid detail am I forgetting?

This is with Bootstrap 3 and jQuery 2 if it matters.
Where are you loading the file? Above the ".wtf" element or below it? If the script is loaded before the elements, it won't find the ".wtf" element, so nothing will happen.

I'd suggest you wrap the code in the ready function.

http://api.jquery.com/ready/
 

Magni

Member
Where are you loading the file? Above the ".wtf" element or below it? If the script is loaded before the elements, it won't find the ".wtf" element, so nothing will happen.

I'd suggest you wrap the code in the ready function.

http://api.jquery.com/ready/

Ugh I had a feeling it was something like this, thanks! I'm more of a backend guy, trying to go fullstack but I still have a ways to go haha
 
Top Bottom