Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
floWenoL
Oct 23, 2002

Mustach posted:

I assigned the result of realloc to another variable.
This won't work in C89, and even in C99 and C++ it has the added problems of re-calculating the length of a non-portable string literal in every spot the macro is used. If you really just gotta be sure buff is big enough to hold the string representation of page count:
code:
char *buff = malloc(floor(log10(pagecount)) + 2);

A 'clearer' way would be:

code:
#include <stdio.h>

char widest_uint32[] = "4294967295";

int main() {
  char buffer[sizeof(widest_uint32)];
  sprintf(buffer, "%d", (int)sizeof(widest_uint32));
  printf("sizeof(widest_uint32) = %s\n", buffer);
  return 0;
}

quote:

but really you'd be pretty safe with something like
code:
char buff[124];

If it's so safe, why'd you bump it up from 100? :P

Adbot
ADBOT LOVES YOU

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

floWenoL posted:

If it's so safe, why'd you bump it up from 100? :P
Well, my failed joke is that any arbirary large size above 20* will be fine if you know the buffer is only going to hold the string representation of an integer. I admit it's still a gamble, but it's probably going to be a while before hardware supports more digits (and even then, plain old int might not change).

*For the number of digits in a 64-bit unsigned long, I think? I dunno that's why I'd just use something big.

edit: bleh, that was way too much explaination on my part

Mustach fucked around with this message at 14:43 on Sep 7, 2008

csammis
Aug 26, 2003

Mental Institution

The Mechanical Hand posted:

I want to learn .NET basically and I'm not sure where to start. Is there any poo poo I gotta get down pat before jumping in or is it feasible to pick up a book that tells you from scratch "Hey, here's where to get started, beginners!" and learn from that? Any thoughts?

It's plenty feasible, I'm pretty sure there have been book suggestions for this purpose in the .NET Questions megathread

ante
Apr 9, 2005

SUNSHINE AND RAINBOWS
Test.dat is a 64kb binary file so there should be 65536 characters, but at the end of the loop, n is only at 9388. What's going on?
code:
long n = 0;
FILE *f;
unsigned char buf;
  
	
f = fopen("test.dat","r");
	
while(!feof(f)) {
	fread(&buf,1,1,f);
	data[n] = buf;
	n++;
}

fclose(f); 
This is in C using VC++.

POKEMAN SAM
Jul 8, 2004

ante posted:

Test.dat is a 64kb binary file so there should be 65536 characters, but at the end of the loop, n is only at 9388. What's going on?
code:
long n = 0;
FILE *f;
unsigned char buf;
  
	
f = fopen("test.dat","r");
	
while(!feof(f)) {
	fread(&buf,1,1,f);
	data[n] = buf;
	n++;
}

fclose(f); 
This is in C using VC++.

Open the file for binary (using "rb")

ante
Apr 9, 2005

SUNSHINE AND RAINBOWS

Ugg boots posted:

Open the file for binary (using "rb")

That fixes a headache for me, thanks.

I even tried that before, but I just realised that I hosed up my syntax on the attempt.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
For what it's worth, if you're dead-set on reading a single character at a time, you should use fgetc, not fread. Analogously, if you're dead-set on undergoing open-heart surgery unaesthetized, you should at least get good and drunk first.

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?
In C++ why is it that this:

typedef CDLLclass (*CreateDllObject)();

is okay, but this:

typedef CDLLclass* (*CreateDllObject)();

is a big no no? It simply wont compile.
I need this to be possible, so is there some "extra" syntax rule that is needed for this to work?

Jarl fucked around with this message at 22:21 on Sep 8, 2008

Vanadium
Jan 8, 2005

Works fine, you should probably say what you are trying to do.

floWenoL
Oct 23, 2002

Jarl posted:

In C++ why is it that this:

typedef CDLLclass (*CreateDllObject)();

is okay, but this:

typedef CDLLclass* (*CreateDllObject)();

is a big no no? It simply wont compile.
I need this to be possible, so is there some "extra" syntax rule that is needed for this to work?

Works for me. What error message are you getting?

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?
I started from scratch and now I don't have the problem. The compiler kept telling me that I should put a ';' before '*' which made no sense.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Jarl posted:

I started from scratch and now I don't have the problem. The compiler kept telling me that I should put a ';' before '*' which made no sense.

You missed a ; in an earlier line and the * was the first point the compiler knew for sure needed to be a new statement.

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?

JoeNotCharles posted:

You missed a ; in an earlier line and the * was the first point the compiler knew for sure needed to be a new statement.

No I didn't. Instead it was because I hadn't put a ';' at the end of my class declarations in a header file. Also in that header file I forgot "using namespace std" and these gave all sorts of obscure errors all over the place. I counted 86 in four files.

I should ofc have realized that the function pointers wasn't wrong, but I had just started from one end of the error list. 86 errors. I should have thought something else was wrong.

Jarl fucked around with this message at 09:46 on Sep 9, 2008

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

Jarl posted:

No I didn't. Instead it was because I hadn't put a ';' at the end of my class declarations in a header file.
When building, the header file comes before the rest of the code.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Jarl posted:

I should ofc have realized that the function pointers wasn't wrong, but I had just started from one end of the error list. 86 errors. I should have thought something else was wrong.

This is why it's a good idea to start at the beginning of the error list and, when you fix something that looks like it'll have ripple effects, just ignore the rest of the list and recompile. Usually a big chunk of them will go away. If you start at the end you might be looking at errors that were caused by earlier errors.

(Assuming your project compiles quickly so it's faster to recompile and get a new error list than to go through the rest of the errors and manually skip the ones you know aren't valid anymore, that is.)

Daggerpants
Aug 31, 2004

I am Kara Zor-El, the last daughter of Krypton
I had a problem and it seems like this thread would be the best fit. I'm trying to write a vbs or batch file that reads values from a csv and creates Windows shortcuts with said values. I have a bit of experience with Perl and Java, but I can't really seem to make heads or tails of the few code snippets I've googled regarding creation of shortcuts (i.e. lnk files). Whould vbs or a bat file be the best way to go about this?

VVVVVVVVVVVVV - Edit - Unfortunately its going to be used in a closed system, so I can't use third party software without a huge headache an approval process. Here is what I have so far:

code:

s

Set objDialog = CreateObject("UserAccounts.CommonDialog")

objDialog.Filter = "All Files|*.*"
objDialog.InitialDir = "C:\"
intResult = objDialog.ShowOpen
 
If intResult = 0 Then
       Wscript.Quit
Else
    Wscript.Echo objDialog.FileName
End If

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    (objDialog.FileName, ForReading)
Do Until objTextFile.AtEndOfStream
    strNextLine = objTextFile.Readline
    arrServiceList = Split(strNextLine , ",")
    For i = 1 to Ubound(arrServiceList)
     

Set objShell = WScript.CreateObject("WScript.Shell")
Set objShortCut = objShell.CreateShortcut("C:\Documents and Settings\Administrator\Desktop\" & arrServiceList(0) & ".lnk")
objShortCut.TargetPath = "C:\Documents and Settings\Administrator\Desktop\putty.exe"
objShortCut.Arguments = "-ssh " & arrServiceList(i)
objShortCut.Description = arrServiceList(0)
objShortCut.Save

    Next

Loop

All done.

Daggerpants fucked around with this message at 03:14 on Sep 11, 2008

gold brick
Jun 19, 2001

no he isn't

Daggerpants posted:

I had a problem and it seems like this thread would be the best fit. I'm trying to write a vbs or batch file that reads values from a csv and creates Windows shortcuts with said values.
Is PowerShell an option?

EDIT: I know you're asking for bat/vbs, but this project might make your life a little easier.

gold brick fucked around with this message at 21:10 on Sep 10, 2008

ArchDemon
Jan 2, 2004

People with emotional and trust issues
really piss me off.

A recent problem that just occured (I think it was after i added jQuery to my app) was in a certain page, HTML is not parsing when I change the contents of a DIV.

code:
<DIV ID="page">
        <SCRIPT LANGUAGE="JavaScript">
	function showItem(item, desc, type) {
		$("#description").text("<CENTER><b>" + item + "</b></CENTER><br><br><b>Type</b>: " 
+ type + "<br><br><b>Description</b><br>" + desc);
	}
	</SCRIPT>

<a href=#desc onClick="showItem('Lunar armor', 'Awesome.<br>
[<a href=inventory_equip.php?step=equip&option=Lunar%20armor>Equip this item</a>] &nbsp; 
[<a href=inventory_equip.php?step=drop_item&option=Lunar%20armor>Drop the Lunar armor</a>]', 'armor');">
<img src=images/items/armor.gif border=0>
</a>

<DIV ID="description" NAME="description"><br><br>Click on an item to view its description.<br><br><br></DIV>

</DIV>
I took out a bunch of other meaningless stuff, but these are the 3 functional areas that I can't figure out. Clicking on that armor link that used to display everything, now returns this:
code:
<CENTER><b>Lunar armor</b></CENTER><br><br><b>Type</b>: armor<br><br>
<b>Description</b><br>Awesome.<br>[<a href=inventory_equip.php?step=equip&option=Lunar%20armor>Equip this item</a>] 
[<a href=inventory_equip.php?step=drop_item&option=Lunar%20armor>Drop the Lunar armor</a>]
As in, it's not actually parsing the HTML. When the page is first loaded, the inital HTML in the DIV parses correctly, but upon change, it just shows the tags, literally. This is written in PHP, and I did a str_replace to replace &gt; into > and &lt; into < and yet it still doesn't parse the HTML for display. Any idea how? :S

ArchDemon fucked around with this message at 16:08 on Sep 11, 2008

Vanadium
Jan 8, 2005

Well, it literally puts text into the DOM and not whatever nodes that would parse to. Because it is text and not magical html code.

Just manually create the elements and plug them into the tree yourself. :colbert:

There are some people who would suggest you use some sort of abomination like .innerHTML but that is clearly non-standard and thus unportable and also heresy. Also you would run into escaping issues if you did it like that.

the onion wizard
Apr 14, 2004

ArchDemon posted:

code:
$("#description").text("<CENTER><b>" + item + "</b></CENTER><br><br><b>Type</b>: " ...

I haven't tested this, and it's probably not the best way to go about this, but:

$("#description").empty().append("<CENTER><b>" + item ...);

Mola Yam
Jun 18, 2004

Kali Ma Shakti de!
I'm basically a programming retard, and while I've managed to cobble this Excel VBA together from various tutorials, it doesn't work, and I don't even know enough about what I'm doing wrong to know what to google for to try to fix it.

code:
Function PCodeToState()

    Dim postcode As Integer
    Dim State As String

    postcode = Worksheets("Sheet1").Range("A1").Value

    Select Case postcode
        Case 1000 To 1999, 2000 To 2599, 2620 To 2898, 2921 To 2999
            State = "NSW"
        Case 200 To 299, 2600 To 2619, 2900 To 2920
            State = "ACT"
        Case 3000 To 2999, 8000 To 8999
            State = "VIC"
        Case 4000 To 4999, 9000 To 9999
            State = "QLD"
        Case 5000 To 5799, 5800 To 5999
            State = "SA"
        Case 6000 To 6797, 6800 To 6999
            State = "WA"
        Case 7000 To 7799, 7800 To 7999
            State = "TAS"
        Case 800 To 899, 900 To 999
            State = "NT"
        Case Else
            State = "Unknown State"
    End Select

 End Function
If it's not obvious, what I'm trying to do is convert column A, a list of 4-digit postcodes, into their corresponding state codes.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Mola Yam posted:

I'm basically a programming retard, and while I've managed to cobble this Excel VBA together from various tutorials, it doesn't work, and I don't even know enough about what I'm doing wrong to know what to google for to try to fix it.

I don't know the Excel API well enough to know if you're doing something obviously wrong there, but if you're using this function as, well, a function, you'll want
code:
Return State
at the end.

RandomPauI
Nov 24, 2006


Grimey Drawer
I'm really excited about using computers to test models of society. Books like Nexus and Complex Adaptive Systems convinced me that this was something I needed to learn. Maybe the model would help demonstrate an idea. Maybe it would only provide an excuse to say "Dance, puppets. DANCE!" Either way, science, mad or otherwise, would progress.

Unfortunately I'm an end-user with mediocre math skills. One with more experience fiddling with hardware than fiddling with code. Worse than that, I'm a sociologist. Is it possible for the programming-ignorant to learn how to code relatively simple models?

narbsy
Jun 2, 2007

rjmccall posted:

I don't know the Excel API well enough to know if you're doing something obviously wrong there, but if you're using this function as, well, a function, you'll want
code:
Return State
at the end.

I believe in Excel VBA it's the old style, so <FunctionName> = State.

If return doesn't work, try that.

Also, it might be faster if you told it to process a specific range of the column and iterated over each cell, and populated a cell in another column.

bitprophet
Jul 22, 2004
Taco Defender

A student posted:

I'm really excited about using computers to test models of society. Books like Nexus and Complex Adaptive Systems convinced me that this was something I needed to learn. Maybe the model would help demonstrate an idea. Maybe it would only provide an excuse to say "Dance, puppets. DANCE!" Either way, science, mad or otherwise, would progress.

Unfortunately I'm an end-user with mediocre math skills. One with more experience fiddling with hardware than fiddling with code. Worse than that, I'm a sociologist. Is it possible for the programming-ignorant to learn how to code relatively simple models?

Absolutely -- Python is generally recommended in this area -- it's used very heavily in the sciences, all kinds, from NASA to bioinformatics. Python combines simplicity (thus easy to learn) with power (thus able to express lots of stuff, and do a lot of processing without a lot of code) and this makes it really attractive for people who aren't necessarily professional programmers, but still want to use computers to model the stuff they're working on.

It can make use of C modules in the event that your particular modeling requires some highly performance-oriented code, too.

RandomPauI
Nov 24, 2006


Grimey Drawer
Is python generally self-taught?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

A student posted:

Is python generally self-taught?

In that universities don't usually teach it, yes. Most everyone in CoC was probably self-taught at one point or another anyway. A university degree is really helpful to being the best programmer you can be, but it's by no means necessary.

To put things in perspective, a few of my friends are physicists, and when they need to learn a new language, someone just throws a reference manual at them and they figure it out.

RandomPauI
Nov 24, 2006


Grimey Drawer
I should feel excited about this. Instead it feels like I've just created more work I'd need to do for a thesis project that doesn't even exist yet.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
It's more math than computer science, but you might want to check out "Mathematical Models" by Richard Haberman. It's got a huge section on population dynamics, and it does a pretty good job of showing how you'd solve the differential equations using numerical (e.g. computer) methods.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Jarl posted:

No I didn't. Instead it was because I hadn't put a ';' at the end of my class declarations in a header file. Also in that header file I forgot "using namespace std" and these gave all sorts of obscure errors all over the place. I counted 86 in four files.
Putting 'using namespace ...' in a header file should earn you a punch in the throat, so please don't. It's a very bad habit, and not only defeats the whole purpose of having namespaces, it does it at random throughout your codebase depending on the presence and order of #includes.

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?

TSDK posted:

Putting 'using namespace ...' in a header file should earn you a punch in the throat, so please don't. It's a very bad habit, and not only defeats the whole purpose of having namespaces, it does it at random throughout your codebase depending on the presence and order of #includes.

lol, ups - I see what you mean.

Viper2026
Dec 15, 2004
I got iRaped by Steve Jobs and all I got was this custom title.
I've got a basic question with some entry level scheme

I've been given this block of code:
code:
(define (p x) (p x))

(define (my-if x y z)
          (if x
              y
              z))

(define x 0)

(if (= x 0)
    0
    (p x))

(my-if (= x 0)
       0
       (p x))
The normal if statement before the my-if call evaluates normally, returning a 0 as would be expected. But, the my-if call seems to enter the program into an infinite loop, and I can't seem to figure out why. Any help would be appreciated

Viper2026 fucked around with this message at 21:54 on Sep 15, 2008

TSDK
Nov 24, 2003

I got a wooden uploading this one
Look up the difference between eager (or strict) evaluation and lazy evaluation.

Dr. Horrible
Sep 7, 2008
I have a hopefully laughably easy question for VB.

For my VB class, I need to create a small program with an IF statement in it.

Basically, I have 1 text field for a number to be input, and a compute button.

The IF Statement I have for the button is

code:

   Dim amount As Integer
   Dim price As Double

        price = CDbl(txtPrice.Text)
        amount = CInt(txtBagelAmount.Text)

        If amount <= 6 Then
            price = amount * 0.6
        Else
            price = amount * 0.75
        End If


        FormatCurrency(lblprice)

Now the AMOUNT field is the user input, where the PRICE field is where the calcualtion should resolve itself. However, whenever I run the code it always fails when I press the calculate button.

It errors on "price = CDbl(txtPrice.Text)" Conversion from string "" to type 'Double' is not valid.


I really need help understanding this.

Viper2026
Dec 15, 2004
I got iRaped by Steve Jobs and all I got was this custom title.

TSDK posted:

Look up the difference between eager (or strict) evaluation and lazy evaluation.

Would that be something like this...?

Applicative order: evaluate arguments, then apply
procedure to values

Normal order: substitute argument expressions for
corresponding parameters in body of procedure
definition, then evaluate body

csammis
Aug 26, 2003

Mental Institution

Dr. Horrible posted:

It errors on "price = CDbl(txtPrice.Text)" Conversion from string "" to type 'Double' is not valid.


I really need help understanding this.

txtPrice.Text is "". "" isn't a number, so it can't be converted to a number. What you're trying to do is put the calculated amount in txtPrice? Once you've done the calculation, try txtPrice.Text = CStr(price)

Dr. Horrible
Sep 7, 2008

csammis posted:

txtPrice.Text is "". "" isn't a number, so it can't be converted to a number. What you're trying to do is put the calculated amount in txtPrice? Once you've done the calculation, try txtPrice.Text = CStr(price)

I hopped in the chatroom real fast and instead of cdbl, I changed it to val, and then threw in code for price to output formatcurrency(price) and nailed it.

thanks

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Viper2026 posted:

Would that be something like this...?

Applicative order: evaluate arguments, then apply
procedure to values

Normal order: substitute argument expressions for
corresponding parameters in body of procedure
definition, then evaluate body

Proper "lazy" evaluation (as it appears in e.g. Haskell) is a little more subtle than that, but yeah, you get the general idea.
code:
if
is a special form in LISP/Scheme that can't be duplicated by a simple user-defined function, precisely because it only evaluates one of its second and third arguments, and which one depends on the result of the first. I believe it can be duplicated with a macro, though.

defmacro
Sep 27, 2005
cacio e ping pong

rjmccall posted:

code:
if
is a special form in LISP/Scheme that can't be duplicated by a simple user-defined function, precisely because it only evaluates one of its second and third arguments, and which one depends on the result of the first. I believe it can be duplicated with a macro, though.

For example:

code:
CL-USER> (defmacro newif (condition form1 form2)                                                                                             
           `(cond (,condition ,form1)                                                                                                        
                  (t ,form2)))
NEWIF                                                                                                                                        
CL-USER> (newif (= 0 0) 3 4)
3                                                                                                                                            
CL-USER> (newif (= 0 0) 3 (print "rear end"))
3
But we your definition
code:
CL-USER> (defun my-if (x y z)                                                                                                                
           (if x                                                                                                                             
               y                                                                                                                             
               z))
MY-IF                                                                                                                                        
CL-USER> (my-if (= 0 0) 3 4)
3                                                                                                                                            
CL-USER> (my-if (= 0 0) 3 (print "rear end"))
                                                                                                                                             
"rear end"                                                                                                                                        
3
As you can see, it still returns the correct answer, but it evaluates both forms which it shouldn't. Essentially, the Lisp macro returns the form wrapped in (COND) without evaluating each form first. It only evaluates forms it needs to, making it more "correct".

Adbot
ADBOT LOVES YOU

Vanadium
Jan 8, 2005

Can you implement cond with a macro, without using if or whatever? :colbert:

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply