• 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

BeforeU

Oft hope is born when all is forlorn.
codingbat is a good resource. Also, best way to learn is to pick a project you'd like to try. You'll most likely be dealing with data and you can pick your own structures to hold and manipulate.

I'm having a real good time on Codefights. The arcade section starts off very basic, but there's some juicy problems later on, and it does seem to do well at diving into trickier bits of the languages.

this is exactly what I was looking for.

Thank you guys
 

FreezeSSC

Member
Hey everyone I hope its okay to post this here, I'm having a problem with a graphics stack in C and its driving me crazy, I just want to know if I'm doing something wrong or the graphics stack itself is bugged. (this is for an embedded processor so I'm not in a windows environment).

So basically I have a label that displays text, its defined by the library as

Code:
laLabelWidget* label1;

I've written a function that when a button is pressed it takes the label as a paramater and passes it to my main which is constantly updating the text that on the label.

Code:
void UpdateLabelItem(laString str, laLabelWidget* lbl, uint32_t id)

that my function paramaters, it takes the current string stored on the label, the label itself, and a screen identifier. My problem is that I want to make a generic reference to this lbl, so in my function I set it equal to a global pointer

Code:
laLabelWidget* myLabel;

and I just set the 2 equal to each other, then when i'm ready to update the text I call the set text function which is defined as follows

Code:
laLabelWidget_SetText(laLabelWidget* lbl, laString str)

so i Just pass in my value as

Code:
laLabelWidget_SetText(myLabel, newString);

when I pass in my pointer myLabel it crashes, if i reference the original label, label1 it works just fine. this of course means I would have to create a function for each label which is stupid. I've tried doing a double pointer that I set up as follows

Code:
laLabelWidget** myLabel
and in my function I assign it as follows

Code:
myLabel = &lbl;

and I pass it as

Code:
iaLabelWidget_SetText(*myLabel, newString)

but that also crashes. Im a total noob when it comes to pointers in C so I figure I must be doing something wrong but I dont know whats the right direction to be going in.
 

Erudite

Member
Hey everyone I hope its okay to post this here, I'm having a problem with a graphics stack in C and its driving me crazy, I just want to know if I'm doing something wrong or the graphics stack itself is bugged. (this is for an embedded processor so I'm not in a windows environment).

So basically I have a label that displays text, its defined by the library as

Code:
laLabelWidget* label1;

I've written a function that when a button is pressed it takes the label as a paramater and passes it to my main which is constantly updating the text that on the label.

Code:
void UpdateLabelItem(laString str, laLabelWidget* lbl, uint32_t id)

that my function paramaters, it takes the current string stored on the label, the label itself, and a screen identifier. My problem is that I want to make a generic reference to this lbl, so in my function I set it equal to a global pointer

Code:
laLabelWidget* myLabel;

and I just set the 2 equal to each other, then when i'm ready to update the text I call the set text function which is defined as follows

Code:
laLabelWidget_SetText(laLabelWidget* lbl, laString str)

so i Just pass in my value as

Code:
laLabelWidget_SetText(myLabel, newString);

when I pass in my pointer myLabel it crashes, if i reference the original label, label1 it works just fine. this of course means I would have to create a function for each label which is stupid. I've tried doing a double pointer that I set up as follows

Code:
laLabelWidget** myLabel
and in my function I assign it as follows

Code:
myLabel = &lbl;

and I pass it as

Code:
iaLabelWidget_SetText(*myLabel, newString)

but that also crashes. Im a total noob when it comes to pointers in C so I figure I must be doing something wrong but I dont know whats the right direction to be going in.
I'll admit it's been awhile since I've coded in C, so I could be wrong here, but since you've done this:
Code:
myLabel = &lbl;
That means myLabel is the address space of lbl.

Doesn't that mean you can just pass-by-reference it as myLabel?
Code:
iaLabelWidget_SetText(myLabel, newString)

Instead of

Code:
iaLabelWidget_SetText(*myLabel, newString)

I'm taking this idea from this Stack Overflow question:
https://stackoverflow.com/questions/2229498/passing-by-reference-in-c

Specifically this piece of code:
Code:
#include <stdio.h>

void function2(int *param) {
    printf("I've received value %d\n", *param);
    (*param)++;
}

int main(void) {
    int variable = 111;

    function2(&variable);
    printf("variable %d\n", variable);
    return 0;
}
Note that variable is being passed-by-reference to function2 by using the address space of variable as the argument.
 
Hey everyone I hope its okay to post this here, I'm having a problem with a graphics stack in C and its driving me crazy, I just want to know if I'm doing something wrong or the graphics stack itself is bugged. (this is for an embedded processor so I'm not in a windows environment).

So basically I have a label that displays text, its defined by the library as

Code:
laLabelWidget* label1;

I've written a function that when a button is pressed it takes the label as a paramater and passes it to my main which is constantly updating the text that on the label.

Code:
void UpdateLabelItem(laString str, laLabelWidget* lbl, uint32_t id)

that my function paramaters, it takes the current string stored on the label, the label itself, and a screen identifier. My problem is that I want to make a generic reference to this lbl, so in my function I set it equal to a global pointer

Code:
laLabelWidget* myLabel;

and I just set the 2 equal to each other, then when i'm ready to update the text I call the set text function which is defined as follows

Code:
laLabelWidget_SetText(laLabelWidget* lbl, laString str)

so i Just pass in my value as

Code:
laLabelWidget_SetText(myLabel, newString);

when I pass in my pointer myLabel it crashes, if i reference the original label, label1 it works just fine. this of course means I would have to create a function for each label which is stupid. I've tried doing a double pointer that I set up as follows

Code:
laLabelWidget** myLabel
and in my function I assign it as follows

Code:
myLabel = &lbl;

and I pass it as

Code:
iaLabelWidget_SetText(*myLabel, newString)

but that also crashes. Im a total noob when it comes to pointers in C so I figure I must be doing something wrong but I dont know whats the right direction to be going in.

It's kind of hard to follow the code when each line is in a separate block and you can't really get the big picture.

Without seeing more of the code, it looks like your original idea of just writing

Code:
laLabelWidget_SetText(myLabel, newString);

should work. If it doesn't work, but it does work with label1, then the problem is in the code you aren't showing. For example, assert(myLabel == label1); should not trigger an assertion, and if it doesn't then if one works so will the other. But since you said one works but not the other, this must be false, and the only way that can happen is if myLabel is somehow pointing to something else. And the place that is causing that to happen is in some code that isn't shown.
 

FreezeSSC

Member
I'll admit it's been awhile since I've coded in C, so I could be wrong here, but since you've done this:
Code:
myLabel = &lbl;
That means myLabel is the address space of lbl.

Doesn't that mean you can just pass-by-reference it as myLabel?
Code:
iaLabelWidget_SetText(myLabel, newString)

Instead of

Code:
iaLabelWidget_SetText(*myLabel, newString)

I'm taking this idea from this Stack Overflow question:
https://stackoverflow.com/questions/2229498/passing-by-reference-in-c

Specifically this piece of code:
Code:
#include <stdio.h>

void function2(int *param) {
    printf("I've received value %dn", *param);
    (*param)++;
}

int main(void) {
    int variable = 111;

    function2(&variable);
    printf("variable %dn", variable);
    return 0;
}
Note that variable is being passed-by-reference to function2 by using the address space of variable as the argument.



I get confused when using double pointers but from my understanding I thought i needed to deference the double pointer to get the original pointer? I can do it that way but the compiler gives me a warning and it still crashes.



It's kind of hard to follow the code when each line is in a separate block and you can't really get the big picture.

Without seeing more of the code, it looks like your original idea of just writing

Code:

laLabelWidget_SetText(myLabel, newString);
should work. If it doesn't work, but it does work with label1, then the problem is in the code you aren't showing. For example, assert(myLabel == label1); should not trigger an assertion, and if it doesn't then if one works so will the other. But since you said one works but not the other, this must be false, and the only way that can happen is if myLabel is somehow pointing to something else. And the place that is causing that to happen is in some code that isn't shown.

here is the code that gets the text once a button is pressed:

Code:
void ButtonWidget4_PressedEvent(laButtonWidget* btn)
{
    // SetSetpoint
    laString newString;
    laString_Initialize(&newString);   
    laTextFieldWidget_GetText(TextFieldWidget1, &newString);
    UpdateLabelItem(newString, LabelWidget7, HomeScreen_ID);    
    laContext_SetActiveScreen(HomeScreen_ID);  
    laString_Destroy(&newString);    
}

my function that assigns my globals in my main

Code:
void UpdateLabelItem(laString str, laLabelWidget* lbl, uint32_t id){
    
    laString_Copy(&newString, &str);
    label = lbl;
    ScreenID = id;
    flag = 1;
    
}

and when i finally update the label
Code:
void UpdateLabel(void){
    
    uint32_t currentScreen;
    
    currentScreen = laContext_GetActiveScreenIndex();
    
    if(currentScreen == ScreenID){
        laLabelWidget_SetText([B]label[/B], newString);        
    }
    
    flag = 0;
}

if i replace label with LabelWidget7 it works fine. LabelWidget 7 gets passed through in the first function call so my pointer should point to labelwidget7 right?

Edit*

Oh and my global is set up like this

laLabelWidget *label;
 
if i replace label with LabelWidget7 it works fine. LabelWidget 7 gets passed through in the first function call so my pointer should point to labelwidget7 right?

Edit*

Oh and my global is set up like this

laLabelWidget *label;

Do you have a debugger you can use to step through the code?
 
Yes but unfortunately it doesn't work well, gives me a "broken breakpoint" whenever I try to set one on my functions. Does my code make sense at least?

Yea it looks ok. I would probably use some printf statements at various points to print the value of the pointer. like:

Code:
printf("in main, Label7Widget7 = 0x%p\n", LabelWidget7);

etc. and littering these all over the code printing both LabelWidget7 and the global variable. You should be seeing the same number printed right before the call to laLabelWidget_SetText.
 

FreezeSSC

Member
Yea it looks ok. I would probably use some printf statements at various points to print the value of the pointer. like:

Code:
printf("in main, Label7Widget7 = 0x%p\n", LabelWidget7);

etc. and littering these all over the code printing both LabelWidget7 and the global variable. You should be seeing the same number printed right before the call to laLabelWidget_SetText.


Wow so I googled a bit a figured out how to get the debugger to work and turns out that the value stored in the original pointer is changing and my global still has the old value, shouldn't it change with it????? do I need to use a double pointer?
 
Wow so I googled a bit a figured out how to get the debugger to work and turns out that the value stored in the original pointer is changing and my global still has the old value, shouldn't it change with it????? do I need to use a double pointer?

A pointer is just a number. If LabelWidget7 is initially 12, and you say label = LabelWidget7, then now they both have the value 12. It's no different than saying int M = N; if you then go and change N, M is not going to change. Pointers are no different.

I would first try to understand why the original pointer is changing, because it doesn't sound normal.
 

FreezeSSC

Member
A pointer is just a number. If LabelWidget7 is initially 12, and you say label = LabelWidget7, then now they both have the value 12. It's no different than saying int M = N; if you then go and change N, M is not going to change. Pointers are no different.

I would first try to understand why the original pointer is changing, because it doesn't sound normal.

Well the good news is I was able to get it to work, I had to change my function to take the address of the pointer, then I changed label to be a double pointer and passed that in and now it works! I guess I was so surprised because I really didn't expect LabelWidget7 to change I don't know if its supposed to or not, this is a beta graphics stack for a 32 bit pic processor and the documentation is horrendous right now.

Thanks for the help I really appreciate it!!
 
Well the good news is I was able to get it to work, I had to change my function to take the address of the pointer, then I changed label to be a double pointer and passed that in and now it works! I guess I was so surprised because I really didn't expect LabelWidget7 to change I don't know if its supposed to or not, this is a beta graphics stack for a 32 bit pic processor and the documentation is horrendous right now.

Thanks for the help I really appreciate it!!

If you can figure out how to set a data breakpoint in your debugger, then what you can do is this:

1) Set a regular breakpoint at some point before LabelWidget7 changes.
2) Look at the value of &LabelWidget7 in the debugger. It's going to be some hex value.
3) Add a "data breakpoint" of 4 bytes on the value you printed above.
4) Run the program.

It should stop as soon as the value changes and give you a callstack to see what's doing it. It may be in some code deep in the graphics stack, but you can still probably follow it all the way up to your code to find out what's triggering it. Sometimes this is really useful, sometimes not.
 

FreezeSSC

Member
If you can figure out how to set a data breakpoint in your debugger, then what you can do is this:

1) Set a regular breakpoint at some point before LabelWidget7 changes.
2) Look at the value of &LabelWidget7 in the debugger. It's going to be some hex value.
3) Add a "data breakpoint" of 4 bytes on the value you printed above.
4) Run the program.

It should stop as soon as the value changes and give you a callstack to see what's doing it. It may be in some code deep in the graphics stack, but you can still probably follow it all the way up to your code to find out what's triggering it. Sometimes this is really useful, sometimes not.

Didn't know you could do that, that's actually pretty handy, so by doing this I just realized each screen I create is redrawn from its initialization file and so all variables get destroyed and recreated, so I guess the real solution is to change the initialization file so that all strings point to a variable that I can alter instead of trying to alter the widget itself.... So I've been going about it all wrong and the solution is much more simpler than I suspected. Before I came here I posted on their forums and couldn't get a single answer from anyone, You've really helped me a lot thanks for taking the time to help me troubleshoot this.
 
I feel the same... though it depends where the code sits, and what it's doing.

If you write a function that read data (from file or stdout) and must returns a set of char* (or print those and do nothing more with those), I think it's fine. OTOH, if you write a function that receive a buffer and has to print it in parts, I fully agree with you.

It's probably a matter of where the piece of code is, in fact...


Well, I think it IS sometimes the case. I never really understood the reason. But looking at my string.h, I get:
Code:
__BEGIN_NAMESPACE_STD
/* Find the first occurrence of C in S.  */
#ifdef __CORRECT_ISO_CPP_STRING_H_PROTO
extern "C++"
{
extern char *strchr (char *__s, int __c)
     __THROW __asm ("strchr") __attribute_pure__ __nonnull ((1));
extern const char *strchr (const char *__s, int __c)
     __THROW __asm ("strchr") __attribute_pure__ __nonnull ((1));

# ifdef __OPTIMIZE__
__extern_always_inline char *
strchr (char *__s, int __c) __THROW
{
  return __builtin_strchr (__s, __c);
}

__extern_always_inline const char *
strchr (const char *__s, int __c) __THROW
{
  return __builtin_strchr (__s, __c);
}
# endif
}
#else
extern char *strchr (const char *__s, int __c)
     __THROW __attribute_pure__ __nonnull ((1));
#endif
So... it depends.

It's one of those reasons that makes me lean towards a C++ compiler even when I basically only write "C" code (but well... overloading in C, even in X11...)


Feels like sane behavior to me... ;)

At least, when the language is designed this way (each time I see java-styled accessors in Python code, my eyes burn)

Lol, I just am used to seeing certain practices, I guess. I am currently reading the book 'Clean Code' and I feel like the author of that book would drop dead at poor variable naming.
 

Makai

Member
Lol, I just am used to seeing certain practices, I guess. I am currently reading the book 'Clean Code' and I feel like the author of that book would drop dead at poor variable naming.
I loved Clean Code when I read it three years ago. But really "clean code" is adhering to style guidelines - which are always totally different for each language. He's a Java guy so his advice is for that culture, and a lot of it is just his random preferences - like he hates switch statements.

I now strongly prefer snake_case because it leads to less thought about handling acronyms.
variableURL, urlVariable, variableUrl
TypeURL, TypeUrl, URLType, UrlType

url_variable, variable_url
Type_URL, URL_Type

Also more readable, but that's controversial of course. C#'s especially bad with camelCase because it has many unique rules for whether you should use camelCase or PascalCase - I noticed you violated this with a camelCase method. I like your way better than Microsoft's way, but I stick to the rules. :p

Sr. developers here naming variable stringOne, stringTwo... and not using encapsulation. I felt like a douche but I rewrote the existing code with accessors and proper variable names.
Accessors are insanity. I used to think C# was really cool because you could just write

Code:
public Type Property { get; set; }

Instead of

Code:
Type field;

public Type GetField()
{
    return field;
}

public Type SetField(Type field)
{
    this.field = field;
}

But now I prefer

Code:
public Type Field;

It's much simpler - method accessors add a lot of noise to your code and if you use the property shortcut, you suddenly can't tell if code will execute when you change a variable. Use them to expose to an interface but otherwise you're just making a more complicated public field. It will not save you from many bugs and makes the code much more inflexible, especially when you have a bunch of them like in a data model.
 
It's much simpler - method accessors add a lot of noise to your code and if you use the property shortcut, you suddenly can't tell if code will execute when you change a variable. Use them to expose to an interface but otherwise you're just making a more complicated public field. It will not save you from many bugs and makes the code much more inflexible, especially when you have a bunch of them like in a data model.

I mostly only use accessors when I want special access rules over them. public Foo { get; set; } is just stupid, as is public Foo { get { return foo_; } set { foo_ = value; } };

On the other hand, public Foo { get; } can be pretty useful
 
I agree 100% with Makai's post about accessors. I think it's fairly rare that you'd 1) want to have special rules for updating a variable but 2) you only want one way for that to happen. As soon as you find yourself adding more use cases you abandon the property feature entirely.
 

Koren

Member
and a lot of it is just his random preferences
Like all rules, and I hate Python for trying to put arbitraty rules in a PEP.

like he hates switch statements.
Well, they ARE below a functional match, but I kinda like them myself.

Granted, normal cases are be the same as a if...elif...elif... without the "security" of rewriting the variable name each time, and cases that "carry over" may be dangerous, but I still like it. Enough to enjoy this infamous Python trick to bring those in Python.

I now strongly prefer snake_case because it leads to less thought about handling acronyms.
variableURL, urlVariable, variableUrl
For me, the rule is a caps for first chars of each word, so I can't really imagine anything else than an acronym in full caps.

Accessors are insanity. [...]

But now I prefer

Code:
public Type Field;

It's much simpler - method accessors add a lot of noise to your code
If your implementation is fixed, you'll never need value-checking, sync or anything like this, I agree with you that encapsulation for the sale of encapsulation is stupid. Seeing it used everywhere may be one of the reasons I dislike Java. But let's be honest, I could write a books about reasons for not liking Java (and past page 2, you could probably disagree with those, and I still don't care ;) )

The Python solution is really strange at first, but curiously handy after some times, although if used without care, really bug-prone.
 
Actually I retract what I said. When I do C# (which isn't often, and usually for hobby stuff) I often write public Foo { get; set; } because I prefer the Intellisense icon that shows up next to properties over the one that shows up next to public variables.

So sue me.

Edit: Also, since you brought it up, Java sux

Edit 2: why do you voluntarily program in C? :(
 

Somnid

Member
Stick to convention.

At an interview I had this code review exercise that used really obnoxious generated javascript with lower_snake_case variables and lots of object prototypes and accessors (I'm pretty sure the exercise was written for Java or C++ and ported so interviewees could have some options, wish I could have compared). It was completely distracting because it didn't match any known js style but I don't think that was what the exercise was trying to get at. Like the style could have been valid for a team and I wanted to make it clear that I don't want to disrupt team convention but, no, just no.

Accessors in C# are mostly just style, and you should use them because they are idiomatic C#. All you get from not using them is to save a a couple keystrokes (but not really since autocomplete does it for you), but it's sometimes handy to have written it like that when you change accesses in the future. Unity uses public properties and it's really annoying.
 

Chris R

Member
I'm having a real good time on Codefights. The arcade section starts off very basic, but there's some juicy problems later on, and it does seem to do well at diving into trickier bits of the languages.
It's ok I guess. Haven't had anything that killed me with difficulty outside of the one tournament I joined, just not enough time for me to get good solutions in JavaScript :/
 

Megasoum

Banned
Hey guys... I've been playing around with Powershell and WPF coding tonight and I have two basic problems that I just can't seem to find a solution for on Google for some reason.


First of all I have a checkbox (let's call it $wpf.TestCheckbox). I can do stuff based on the Checked and Unchecked event no problem but I want to uncheck it if it is checked when I press a specific button. I can easily find out if it is checked when I press the button but I just can't seem to find the command to uncheck it?

Second problem is that I would like to exit the program when pressing Escape and I can't get the example I've found on Google to work.


Any ideas?
 
First of all I have a checkbox (let's call it $wpf.TestCheckbox). I can do stuff based on the Checked and Unchecked event no problem but I want to uncheck it if it is checked when I press a specific button. I can easily find out if it is checked when I press the button but I just can't seem to find the command to uncheck it?

Second problem is that I would like to exit the program when pressing Escape and I can't get the example I've found on Google to work.


Any ideas?
1) https://msdn.microsoft.com/en-us/li...mitives.togglebutton.ischecked(v=vs.110).aspx

Set this property. :)

2) What I would do is have your main loop be a while loop that checks a Boolean every iteration. When you get a button event that's the escape key, set it to false and your app will break the loop and exit (make sure to close resources here too).
 
Yeah, you guys are right. It really depends on the language. I DO see people execute certain syntax for making variables/functions. I just mostly work in Java, so I am used to a particular approach.

Side note: I am working on learning the Spring Framework and it's really blowing my mind. Dependency Injection is awesome. Swapping out implementations and disregarding tightly coupled code is really cool.
 

Jokab

Member
Yeah, you guys are right. It really depends on the language. I DO see people execute certain syntax for making variables/functions. I just mostly work in Java, so I am used to a particular approach.

Side note: I am working on learning the Spring Framework and it's really blowing my mind. Dependency Injection is awesome. Swapping out implementations and disregarding tightly coupled code is really cool.

I have a love/hate relationship with Spring. On one hand yeah it does some cool things, on the other hand the process to even make something that runs may take a week of studying (or following a good tutorial).
 
I have a love/hate relationship with Spring. On one hand yeah it does some cool things, on the other hand the process to even make something that runs may take a week of studying (or following a good tutorial).

Spring Boot is pretty nice, it makes setting up a small project really easy. No XML configuration, pretty much everything is set up with auto configuration. The real issue with Spring is that it has a TON of reflection magic happening in the background, which can eat into performance and can be very tough to debug.
 
Side note: I am working on learning the Spring Framework and it's really blowing my mind. Dependency Injection is awesome. Swapping out implementations and disregarding tightly coupled code is really cool.
What's the advantage of using Spring over just passing a dependency in as an argument?
 

leroidys

Member
Does anyone have any sort of regimen for staying sharp on interview questions? Not currently looking for a job, but it was pretty hellish trying to re-learn all of my college courses for the last time I was interviewing. If I could get some kind of daily practice going, I feel like things would go much more smoothly the next time I'm looking for work.
 

Jokab

Member
Does anyone have any sort of regimen for staying sharp on interview questions? Not currently looking for a job, but it was pretty hellish trying to re-learn all of my college courses for the last time I was interviewing. If I could get some kind of daily practice going, I feel like things would go much more smoothly the next time I'm looking for work.

Cracking the coding interview is the one that always comes up. Check it out.
 

phisheep

NeoGAF's Chief Barrister
Does anyone have any sort of regimen for staying sharp on interview questions? Not currently looking for a job, but it was pretty hellish trying to re-learn all of my college courses for the last time I was interviewing. If I could get some kind of daily practice going, I feel like things would go much more smoothly the next time I'm looking for work.

I'm doing daily practice on Codefights, which also has an Interview practice section.
 

Koren

Member
Help!

I try to fill a MySQL database from an HTML form, using a PHP script.

As usual, everything works well till you deal with encodings :/

The page is defined as UTF-8 with a
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

The database is Inno_db encoded in utf8_bin

When I enter a 'ç' in the form, I get a 'ç' in the database (I get the same when I access the database from python, using UTF-8 for decoding the bytestring I get).

Since ç is U+00C3 U+00A7, and 0xC3A7 is the UTF-8 sequence for U+00E7 (ç), there's a translation issue somewhere, but I don't know where to look...


Edit: the insertion seems to work when I add accept-charset="ISO-8859-1" in the <form ...> but I'm pretty sure I'll be burned elsewhere...

Edit: well, that was quick: the string is correct in the database, but when I do a query, and insert the string back into the form, I get wrong characters, of course...

Edit (again) : found a solution... Adding mysql_set_charset('utf8') did the trick, although it's deprecated in PHP5.5. I'll have to find a better solution later :/
 

Mike M

Nick N
I've got an app I've written that runs a particular scientific calculation that no one outside of biochemistry is likely to use, but the output is widely variable. I would like to have it return 2 significant digits, but I don't want something that can return something like 0.0000000066 but also returns 423 as 423.0000000000.

Anyone know a way to dynamically set the number of decimal places for something like that? I'm working in Swift, but I could probably translate a solution in JavaScript or Objective-C without too much difficulty.
 
I've got an app I've written that runs a particular scientific calculation that no one outside of biochemistry is likely to use, but the output is widely variable. I would like to have it return 2 significant digits, but I don't want something that can return something like 0.0000000066 but also returns 423 as 423.0000000000.

Anyone know a way to dynamically set the number of decimal places for something like that? I'm working in Swift, but I could probably translate a solution in JavaScript or Objective-C without too much difficulty.

I'm not clear on your requirements. Given these numbers:

423.00000000000001
0.1230000000000001
0.0000000000000001

when you convert these to a string, what would you like the output to be in each case?
 

Koren

Member
Isn't 423.0 4 digits, and should rather be written 423 if you want 3 digits?

Also, should 12.3456 be rendered as 12.3?

Edit: I'd argue it should be
4.23e2
1.23e-1
1.00e-16
if you really care for precise significant digits... Because from a scientific point of view, 1230000000 has usually 10 signigicant digits...
 

Lister

Banned
I'm looking for a litle advice: I'm trying to find a way to structure my objects (structs really as they are pure data objects) in order to work with a generic (static) repository for Azure DocumentDB.

Essentially a generic repository for doing CRUD with DocumentDB might look something like this:

Code:
public static class DocumentDbRepository<T> where T : class
    {
        private static string Endpoint;
        private static string Key;
        ...

        public static void Initialize(IDocumentDbConfig dbConfig, string collectionId)
        {
            Endpoint = dbConfig.Endpoint;
           ...
        }

        public static async Task<T> GetItemAsync(string id)
        {
            try
            {
                Document document = await client.
                    ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
                return (T)(dynamic)document;
            }
            catch (DocumentClientException e)
            {
               ...
            }
        }

        public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate)
        {
            IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                new FeedOptions { MaxItemCount = -1 })
                .Where(predicate)
                .AsDocumentQuery();

            List<T> results = new List<T>();
            while (query.HasMoreResults)
            {
                results.AddRange(await query.ExecuteNextAsync<T>());
            }

            return results;
        }
      .... (other CRUD methods below).
   }

And I can initialize one like so:

Code:
 DocumentDbRepository<WidgetDocument>.Initialize(DocumentDbConfig, "WidgetCollection");

Now I can interact with it like this:

Code:
var widgets = await DocumentDbRepository<WidgetDocument>.GetItemsAsync(p => !p.Deleted);

And it will work with WidgetDocument and return WidgetDocument (or a List<WidgetDocument>) depending on the operation.

All fine and dandy. The issue is that My widgets vary. There are different types of widgets potentially MANY different types. One simple solution would be to initialize multiple repositories, one for each type of WidgetDocument:

Code:
 DocumentDbRepository<WidgetDocument>.Initialize(DocumentDbConfig, "WidgetCollection");
 DocumentDbRepository<FunnyWidgetDocument>.Initialize(DocumentDbConfig, "WidgetCollection");
 DocumentDbRepository<SadWidgetDocument>.Initialize(DocumentDbConfig, "WidgetCollection");
 DocumentDbRepository<GothWidgetDocument>.Initialize(DocumentDbConfig, "WidgetCollection");
 DocumentDbRepository<CrazyWidgetDocument>.Initialize(DocumentDbConfig, "WidgetCollection");

But this seems... clumsy? I'm not sure if this is the best approach. So my current widget model structure is something like this:

Code:
public interface IWidget {
   string name;
   string location;
   TimeSpan expiration;
}

public interface ISad {
  List<string> sadPoems;
  bool IsCrying;
}

public interface IFunny {
  List<string> jokes;
  bool IsLaughing;
}

....

public class SadWidget : IWidget, ISad {
   string name;
   string location;
   TimeSpan expiration;
   List<string> sadPoems;
   bool IsCrying;
}

....

public class CrazyWidget : IWidget, ISad, IFunny {
   string name;
   string location;
   TimeSpan expiration;
   List<string> sadPoems;
   bool IsCrying;
   List<string> jokes;
   bool IsLaughing;
}

Is there a better approach I could take?
 

ColdPizza

Banned
Well, you might be able to just have a collection of widgets since they all share the same base type, and as you iterate through your list you can check the derived types and then initialize as you see fit so you don't have to individually initialize each documentdb repository.
 

Slo

Member
Any good resources for learning data science on Python?

Siraj Raval's YouTube channel. Start at the beginning and watch them all. They're kinda wacky and #dudebro at first, and not always related to machine learning, but he finds his way eventually and starts doing live shows where he teaches you to code. Hell, even his 5 minute videos are worth watching.

https://www.youtube.com/channel/UCWN3xxRkmTPmbKwht9FuE5A

After you get through his free content, register for his new Udacity course.

https://www.udacity.com/course/deep-learning-nanodegree-foundation--nd101
 
I'm looking for a litle advice: I'm trying to find a way to structure my objects (structs really as they are pure data objects) in order to work with a generic (static) repository for Azure DocumentDB.

Essentially a generic repository for doing CRUD with DocumentDB might look something like this:


Is there a better approach I could take?

Any time you go beyond 1 level of inheritance you should reconsider your design choices. I would do something like this:

Code:
public class IWidgetVisitor {
  virtual void visit(SadWidget Sad) = 0;
  virtual void visit(FunnyWidget Funny) = 0;
};

public class IWidgetProperties {
  virtual void visit(WidgetVisitor Visitor) = 0;
};

public class SadWidget : public IWidgetProperties {
   List<string> sadPoems;
   bool IsCrying;

   virtual void visit(WidgetVisitor Visitor) override {
     Visitor.visit(this);
   }
};

public class FunnyWidget : public IWidgetProperties {
  List<string> jokes;
  bool IsLaughing;

   virtual void visit(WidgetVisitor Visitor) override {
     Visitor.visit(this);
   }
};

public class Widget : public IWidget {
   string name;
   string location;
   TimeSpan expiration;

   void HandleProperties(IWidgetVisitor Visitor) {
     for (IWidgetProperties Props in Properties) {
       Props.visit(Visitor);
     }
   }

   List<IWidgetProperties> Properties;
};

public class DumpProperties : public IWidgetVisitor {
  virtual void visit(SadWidget Sad) override {
    System.Console.WriteLine("Poems: " + Sad.SadPoems);
    System.Console.WriteLine("Crying: " + Sad.IsCrying);
  }

  virtual void visit(FunnyWidget Funny) override {
    System.Console.WriteLine("Jokes: " + Funny.Jokes);
    System.Console.WriteLine("Laughing: " + Funny.IsLaughing);
  }
}

Widget CrazyWidget = new Widget();
CrazyWidget.Properties.Append(new FunnyWidget());
CrazyWidget.Properties.Append(new SadWidget());

CrazyWidget.HandleProperties(new DumpProperties());
 
I have an interview for jr. QA coming up. Any advice on possible questions, or scenarios?

I imagine you'll be asked about how you would test a new feature, in which case, talk about edge cases. You'll also be expected to know testing terms like smoke testing, instrumentation testing, etc.
 

Lister

Banned
Any time you go beyond 1 level of inheritance you should reconsider your design choices. I would do something like this:

Code:
public class IWidgetVisitor {
  virtual void visit(SadWidget Sad) = 0;
  virtual void visit(FunnyWidget Funny) = 0;
};

public class IWidgetProperties {
  virtual void visit(WidgetVisitor Visitor) = 0;
};

public class SadWidget : public IWidgetProperties {
   List<string> sadPoems;
   bool IsCrying;

   virtual void visit(WidgetVisitor Visitor) override {
     Visitor.visit(this);
   }
};

public class FunnyWidget : public IWidgetProperties {
  List<string> jokes;
  bool IsLaughing;

   virtual void visit(WidgetVisitor Visitor) override {
     Visitor.visit(this);
   }
};

public class Widget : public IWidget {
   string name;
   string location;
   TimeSpan expiration;

   void HandleProperties(IWidgetVisitor Visitor) {
     for (IWidgetProperties Props in Properties) {
       Props.visit(Visitor);
     }
   }

   List<IWidgetProperties> Properties;
};

public class DumpProperties : public IWidgetVisitor {
  virtual void visit(SadWidget Sad) override {
    System.Console.WriteLine("Poems: " + Sad.SadPoems);
    System.Console.WriteLine("Crying: " + Sad.IsCrying);
  }

  virtual void visit(FunnyWidget Funny) override {
    System.Console.WriteLine("Jokes: " + Funny.Jokes);
    System.Console.WriteLine("Laughing: " + Funny.IsLaughing);
  }
}

Widget CrazyWidget = new Widget();
CrazyWidget.Properties.Append(new FunnyWidget());
CrazyWidget.Properties.Append(new SadWidget());

CrazyWidget.HandleProperties(new DumpProperties());

Oh man, I wouldn't have thought of applying this pattern in this way. Thank you so much!
 
I do not get the YouTube API at all. I have it loading the iframe into a div but I can't click on the thing to play it. In fact hovering over produces no response. I mean I see that there are functions I can use to force it to play but why don't the video controls work?
iqVUSkI.png

This seems like a basic question but google isn't returning anything useful.
 

Kieli

Member
I don't quite understand what intptr_t and size_t are for. The former, to my best understanding, is a type of integer (meaning you can add it to stuff, subtract from it, multiply it), but what it holds is a pointer (and pointers are just addresses to some physical memory).

So that means you can perform mathematical operations on addresses?

Furthermore, what happens if intptr_t x is set to contain the pointer to an array of say 4 chars.

If I want to compare it to another 4 char array stored by intptr_t y, then x == y is not sufficient because it only checks if the two pointers contain the same address. That's not what I want; rather, I want to check if the VALUES pointed to by the two intptrs are the same, so I would have to for-loop traverse through them?
 
I don't quite understand what intptr_t and size_t are for. The former, to my best understanding, is a type of integer (meaning you can add it to stuff, subtract from it, multiply it), but what it holds is a pointer (and pointers are just addresses to some physical memory).

So that means you can perform mathematical operations on addresses?
Yes, the purpose of intptr_t is to have an integer that is guaranteed to be big enough to hold a pointer (pointers are different sizes on different systems). So the point is you can use it to perform pointer arithmetics. This is useful if you're writing your own memory allocator. Other than that you probably shouldn't do it.

Furthermore, what happens if intptr_t x is set to contain the pointer to an array of say 4 chars.
Nothing in particular. You get the adress just like usual.

If I want to compare it to another 4 char array stored by intptr_t y, then x == y is not sufficient because it only checks if the two pointers contain the same address. That's not what I want; rather, I want to check if the VALUES pointed to by the two intptrs are the same, so I would have to for-loop traverse through them?
Well, when you're comparing an array, you're not comparing a value with another. You're comparing multiple values. The only way to do that is with a loop*. Or just use strcmp to do it for you.

* If it's just 4 bytes you could technically do some clever casting but I would advice against it. It would make the code far less maintainable (less readable and now the array has to be 4 bytes or it won't work).
 
Top Bottom