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
Subjunctive
Sep 12, 2006

✨sparkle and shine✨

sizeof

Adbot
ADBOT LOVES YOU

Soricidus
Oct 21, 2010
freedom-hating statist shill

what?

Subjunctive
Sep 12, 2006

✨sparkle and shine✨


sizeof will look up both types and variables (as an expression), effectively putting them in the same namespace for its evaluation. (I don't recall which takes precedence.)

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)
I mean, I can't recall a C program where the author ever did 'struct Foo *myFoo = malloc(sizeof(struct Foo));' anyways. I'm mostly talking about Java/C# devs. And I never bothered to learn C++ but you have to use sizeof(struct Foo) for C so I'm not sure what you mean (unless you typedef it ofc).

E: Oh I see, you're saying that since I can do sizeof(int) and int x = 0; sizeof(x).

dougdrums fucked around with this message at 20:30 on Jul 16, 2015

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

dougdrums posted:

I mean, I can't recall a C program where the author ever did 'struct Foo *myFoo = malloc(sizeof(struct Foo));' anyways. I'm mostly talking about Java/C#. And I never bothered to learn C++ but you have to use sizeof(struct Foo) for C so I'm not sure what you mean (unless you typedef it ofc).

I've definitely seen it in C, in macroized allocators for example. And in C++ you don't need the explicit struct, not that typedef of structs is unusual.

Soricidus
Oct 21, 2010
freedom-hating statist shill

Subjunctive posted:

sizeof will look up both types and variables (as an expression), effectively putting them in the same namespace for its evaluation. (I don't recall which takes precedence.)

oh, sure. I thought you were talking about structs, which still have their own namespace when using sizeof in C.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Subjunctive posted:

sizeof will look up both types and variables (as an expression), effectively putting them in the same namespace for its evaluation. (I don't recall which takes precedence.)

There are no special disambiguation rules for sizeof in C, because you can't write sizeof(A) if A is only declared as a struct. C++ mostly doesn't have any ambiguity, because references to types aren't valid expressions by themselves, but functional-style casts (i.e. constructor calls) get resolved in favor of being types if they're truly ambiguous.

crazypenguin
Mar 9, 2005
nothing witty here, move along
You can write sizeof(A) for a typedef A.

But that's just the usual C typedef ambiguity, usually resolved by doing a lookup during lexing to find the lexically-scoped nearest declaration of A, to decide if it's a type name or a variable name.

So there's not an explicit preference between type or variable for sizeof, it's that if you have a name that could resolve to both, one must be shadowing the other.

e: and just to address the original discussion, structs are different namespace than variables in C, but not typedefs! (Just another tiny little piece of why C and friends are pretty crummily designed.)

crazypenguin fucked around with this message at 22:57 on Jul 16, 2015

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

crazypenguin posted:

You can write sizeof(A) for a typedef A.

Yes, and a name that is declared as a typedef is not declared solely as a struct/union/enum (if it is at all).

The C++ rules are really too complex to talk about as if they were merely an extension of the C namespace concept. Different kinds of lookup consider different but overlapping sets of kinds of declarations (tags, types, templates, values, functions, namespaces...), and there are special rules for hiding certain declarations when other kinds of declarations are found in the same scope (but not if they would be found in an enclosing scope). And that's just the declaration namespacing rules, not the actual order-of-lookup rules, or the rules for how to interpret the declarations you find.

qntm
Jun 17, 2009
Perl code:
use strict;
use warnings;
print q america;

dwazegek
Feb 11, 2005

WE CAN USE THIS :byodood:
This was part of a larger function. It's an algorithm to determine how many items are in a block of items. In this case the number of items can only ever be powers of 10 (1, 10, 100, 1000, etc).

C# code:
int length = blockSize.ToString().Length;
int count = (int)Math.Pow((double)10, (double)length - 1);
In order to determine how many items there are, you only need one input parameter, an integer representing the number of items there are. :psyduck:

motorcyclesarejets
Apr 24, 2007
PHP's mt_rand(1, PHP_INT_MAX) only generates odd numbers

Soricidus
Oct 21, 2010
freedom-hating statist shill

lol

because there definitely aren't standard ways to produce out-of-range values from a prng such as by concatenating multiple outputs or whatever. you've gotta just produce one output and scale it, that's the only option

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

FlapYoJacks
Feb 12, 2009

There are so so many things wrong with that I don't even know where to begin. :psyduck:

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)


No fair posting student code :v:

xzzy
Mar 5, 2009

That wasn't actually found in a project, right?

It's a tutorial example from how to write infinite loops, right?

Well I guess it's not technically infinite. It just takes the long way to get where it's going.

b0lt
Apr 29, 2005

xzzy posted:

That wasn't actually found in a project, right?

It's a tutorial example from how to write infinite loops, right?

Well I guess it's not technically infinite. It just takes the long way to get where it's going.

Assuming it's C or C++, it's undefined behavior, which means the compiler can do whatever it wants.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

xzzy posted:

Well I guess it's not technically infinite. It just takes the long way to get where it's going.

If that's C or C++ (and if it isn't what's printf doing there) it's probably infinite - i is signed, and signed integer overflow is undefined, so the loop conditional probably gets omitted come codegen time.

ChickenWing
Jul 22, 2010

:v:

Blotto Skorzany posted:

If that's C or C++ (and if it isn't what's printf doing there)

Java has a printf method

FlapYoJacks
Feb 12, 2009

ChickenWing posted:

Java has a printf method

so does bash and PHP. Although PHP would have $ before the variables.

mobby_6kl
Aug 9, 2009

by Fluffdaddy

Soricidus posted:

lol

because there definitely aren't standard ways to produce out-of-range values from a prng such as by concatenating multiple outputs or whatever. you've gotta just produce one output and scale it, that's the only option
Even better, this is what it actually generates
code:
1d59036c00000001
3a704f3c00000001
25a0828500000001
03a7a24700000001
4f0113b100000001
196cff6d00000001
34f5734d00000001
5fb1a51000000001
41692d8900000001
7eeffa4600000001
:downsbravo:

Space Kablooey
May 6, 2009



code:
Output for 4.3.0 - 4.3.11, 5.0.0 - 5.0.4

    Notice: Use of undefined constant PHP_INT_MAX - assumed 'PHP_INT_MAX' in /in/XVTgS on line 5

    Warning: mt_rand() expects parameter 2 to be long, string given in /in/XVTgS on line 5
    0000000000000000

    Notice: Use of undefined constant PHP_INT_MAX - assumed 'PHP_INT_MAX' in /in/XVTgS on line 5

    Warning: mt_rand() expects parameter 2 to be long, string given in /in/XVTgS on line 5
    0000000000000000

    *snip*
:allears:

xzzy
Mar 5, 2009

I think just about everything has a printf, even languages that don't use it as the primary method of output.

Or failing that they have sprintf.

Soricidus
Oct 21, 2010
freedom-hating statist shill

xzzy posted:

I think just about everything has a printf, even languages that don't use it as the primary method of output.

Or failing that they have sprintf.

c#, python. does javascript even have a formatting function in its standard library?

Sedro
Dec 31, 2008

Soricidus posted:

c#, python. does javascript even have a formatting function in its standard library?
ES6 has template strings with interpolated expressions, but otherwise no

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer
A homemade horror. For background, you can read from this post in the .net thread: http://forums.somethingawful.com/showthread.php?threadid=3644791&pagenumber=85#post448109154

The basic thing is, some genius developer on some far-flung corner of the company decided that our internal graphics search tool should stop being based a a spreadsheet of filenames and tags that we've maintained forever and exported to csv for indexing, and we should instead use the handy "Tags" field that Windows Explorer gives you for .jpg files instead. It's pretty easy to read this information. It's insanely hard to write it. I think this developer knows this, but didn't GAF and asked a bunch of non-technical people do do the bitch work of tagging up 50000+ .jpg files.

Since I'm the "fix it with programming guy" one of the called me and asked me if there was a way to automate this. Since it's a one-off and we'll never need to do it again, I just ground out the first thing that worked. Since Windows' API for updating this metadata doesn't exist, 12 hours and 3 third-party libraries later I have this garbage (it worked, I am getting cookies). Comments inline on the grodier stuff
C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.WindowsAPICodePack.Shell; //This API used to be hosted on MS's website. It's not anymore
										// and the only way to get them is to use the PMC to grab them straight form NuGet.
using Microsoft.WindowsAPICodePack; //Each of these is
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;//For no reason a seperate package on nuget


//There's a hastily thrown together winform not included here, because it's totally uninteresting.
namespace WindowsFormsApplication1
{
    class parser
    {
        public static void handlefiles(String xlsx, String dir, ProgressBar pb){//spreadsheet o tags, directory with the images 
																//(with subfolders named for the worksheets in the excel file), progress bar I never got working right.
       
            SpreadsheetDocument ss = SpreadsheetDocument.Open(xlsx, false); //*. Lines with a * denote crap that's only necessary because OpenXML is stupid.
            WorkbookPart wb = ss.WorkbookPart;//*
            pb.Step = 100/ wb.Workbook.Descendants<Sheet>().Count();
            foreach (Sheet s in wb.Workbook.Descendants<Sheet>())//*
            {
                pb.PerformStep();
                WorksheetPart wp = wb.GetPartById(s.Id) as WorksheetPart; //Worksheetpart and Worksheets are different. 
															    //One of them has the actual content, the other just has names and IDs. They are separate for *reasons*
                SheetData sd = wp.Worksheet.GetFirstChild<SheetData>()//*;
                String dirname = s.Name;
                String fullpath = dir +"\\"+ dirname;
                if (System.IO.Directory.Exists(@fullpath) || dirname.Equals("<name of spreadsheet that has images from the rootdir>"))
                {
                    if (dirname.Equals("<name of spreadsheet that has images from the rootdir>"))
                    {
                        fullpath = dir;
                    }
                    foreach (Row r in sd.Descendants<Row>())//*
                    {
                        String name;
                        String tags;
                        Cell firstCell = r.Elements<Cell>().First<Cell>();//*
                        Cell lastCell = r.Elements<Cell>().Last<Cell>();//*
                                            //Fun story: If you iterate by row, there's no way to grab cells by their column index. 
					   //In fact, there seems to be no good way to grab two columns row-by-row at all
					   //so I just deleted all the columns from all 50 tabs that weren't the filename or tags 
					  //so I could just grab the first and last cells of each row. So ghetto.
                        var stringTable = wb.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();//*. If a cell contains text, god forbid it be in the cell.
																				    //No, you get an ID of an element in a table of strings in the document. For *reasons*.
                        name = stringTable.SharedStringTable.ElementAt(int.Parse(firstCell.CellValue.Text)).InnerText;//*
                        try
                        {
                            tags = stringTable.SharedStringTable.ElementAt(int.Parse(lastCell.CellValue.Text)).InnerText;//*
                        }
                        catch (NullReferenceException ex)
                        {
                            tags = "";//OK, this one is just me being lazy. Some of the images don't have tags, and it was easy enough 
                                           //to just let the exception deal with that since this is one-off
                        }

         
                        markupFile(name, tags, fullpath);
                    }
                }
            }
            int xx = 1;//So, the progress bar just kinda refused to work, so I have this line here so I could set a breakpoint and 
			     //know when the logic had finished running so I could stop the program. :gonk:
            
        }

        private static void markupFile(String fileName, String tags, String fullPath)
        {
            try
            {
                String[] splittags = tags.Split(';');
                String filepath = fullPath + "\\" + fileName + ".jpg";
                var shellFile = Microsoft.WindowsAPICodePack.Shell.ShellObject.FromParsingName(filepath);
                var pw = shellFile.Properties.GetPropertyWriter();
                pw.WriteProperty(SystemProperties.System.Keywords, splittags);
                pw.Close();
            }
            catch (Exception ex)//This is me being exceptionally lazy again. There are a few files that are listed in the spreadsheet 
						//that don't exist anymore. One-off, not dealing with it :)
            {
            }
        }
    }
}
Notice how the only code in here that doesn't suck poo poo is the stuff that is in a library that MS removed from MSDN over a year ago?

Impotence
Nov 8, 2010
Lipstick Apathy

PHP_INT_MAX wasn't added until 5.0.5. I don't see what the horror is here, because it returns boolean false in the above situation and there is a massive warning since the start that it should not be used for anything close to crypto.

canis minor
May 4, 2011

Speaking of PHP - this: http://stackoverflow.com/questions/31617137/why-chr0x00-is-considered-as-true-in-php made me laugh today

down with slavery
Dec 23, 2013
STOP QUOTING MY POSTS SO PEOPLE THAT AREN'T IDIOTS DON'T HAVE TO READ MY FUCKING TERRIBLE OPINIONS THANKS

I get that PHP is a fractal of horrors but pretty much every "WOW PHP IS BAD" post involves people just refusing to accept the way PHP handles loose comparisons.

idiot on stackoverflow posted:

if ($test['bit1column'])

no no no no no no

The mt_rand thing is an actual interesting horror

Volguus
Mar 3, 2009
In a java web application (spring based), one developer thought that when an administrator updates a user information (including password), that administrator should enter the original password of the user. That is a WTF in and of itself, but it gets better. So, how do we check if the password entered is the same as the one in the database? You wouldn't believe it (comments are mine):
Java code:
public boolean verifyPassword(UserInfo userInfo, String password) {
	try {
		//original encoded password
		String passwd = userInfo.getPassword(); 
		//a class that creates a new user instance for no reason whatsoever
		CustomAuthenticationServiceImpl cas = new CustomAuthenticationServiceImpl(); 
		// and stores the password
		cas.setPassword(passwd); 
		// the password encoder we are using. It is injected already by spring, and we have it, but why not make a new instance, and tie ourselves to it
		BCryptPasswordEncoder bce = new BCryptPasswordEncoder(); 
		//make a token
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userInfo.getUsername(), password); 
		//make a new provider (there is one made by spring already, but hey ... let's make one ourselves)
		DaoAuthenticationProvider au = new DaoAuthenticationProvider(); 
		au.setUserDetailsService(cas);
		au.setPasswordEncoder(bce);
		//and now we actually authenticate the user
		au.authenticate(token); 
		//yepee, we're good to go
		return true; 
	} catch (Exception e) {
		// obviously this means that the passwords do not match
		LOG.error("Failed to verify the password: "  + password); 
	}
	return false;
 }
of course, that entire block of poo poo can be replaced by
Java code:
public boolean verifyPassword(UserInfo userInfo, String password) {
	//use the passwordEncoder instance that we have to check if the passwords match
	return this.passwordEncoder.matches(password, userInfo.getPassword());
}
Still, why does the administrator have to enter the user's original password (why does he even know it???) ... it's a mystery.

Space Kablooey
May 6, 2009


Biowarfare posted:

PHP_INT_MAX wasn't added until 5.0.5. I don't see what the horror is here, because it returns boolean false in the above situation and there is a massive warning since the start that it should not be used for anything close to crypto.

Shouldn't PHP 4.4.0 through 4.4.9 throw the same error, then?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

HardDisk posted:

Shouldn't PHP 4.4.0 through 4.4.9 throw the same error, then?

PHP4 went security-only not long after 5.0 was released, and received updates for three years afterward, almost up until 5.3.0 was released. 4.4.0 was released almost exactly a year after 5.0.0, and just a bit before 5.1.0. It seems that they backported the constant for some reason.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Volguus posted:

So, how do we check if the password entered is the same as the one in the database? You wouldn't believe it (comments are mine):
of course, that entire block of poo poo can be replaced by
Java code:
public boolean verifyPassword(UserInfo userInfo, String password) {
	//use the passwordEncoder instance that we have to check if the passwords match
	return this.passwordEncoder.matches(password, userInfo.getPassword());
}

I believe it. The dude doesn't know about this.passwordEncoder and instead writes fairly clear and understandable code to check the password instead. You should have just laughed and said "oh, you don't have to write this, Spring injects a service for us that does this" and CR failed it. Then he would have said "oh cool, that makes things easier" and fixed it. And then you wouldn't have tried to make fun of him on an internet forum for him not knowing literally everything about the massive 500,000 LOC Java Enterprise framework he's using.

Ellie Crabcakes
Feb 1, 2008

Stop emailing my boyfriend Gay Crungus

Suspicious Dish posted:

I believe it. The dude doesn't know about this.passwordEncoder and instead writes fairly clear and understandable code to check the password instead. You should have just laughed and said "oh, you don't have to write this, Spring injects a service for us that does this" and CR failed it. Then he would have said "oh cool, that makes things easier" and fixed it. And then you wouldn't have tried to make fun of him on an internet forum for him not knowing literally everything about the massive 500,000 LOC Java Enterprise framework he's using.
Yeah, if this was a case of literally everything and not a core concept.

[edit] Show me on the doll where the code review touched you.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
this.passwordEncoder is a core concept of Spring?

M31
Jun 12, 2012
Inversion of control is such a core concept in Spring, that even if passwordEncoder was not yet injected into the class, it still would not be reasonable to write that code.

Space Kablooey
May 6, 2009


McGlockenshire posted:

PHP4 went security-only not long after 5.0 was released, and received updates for three years afterward, almost up until 5.3.0 was released. 4.4.0 was released almost exactly a year after 5.0.0, and just a bit before 5.1.0. It seems that they backported the constant for some reason.

Oh, didn't know that.

Volguus
Mar 3, 2009

Suspicious Dish posted:

I believe it. The dude doesn't know about this.passwordEncoder and instead writes fairly clear and understandable code to check the password instead. You should have just laughed and said "oh, you don't have to write this, Spring injects a service for us that does this" and CR failed it. Then he would have said "oh cool, that makes things easier" and fixed it. And then you wouldn't have tried to make fun of him on an internet forum for him not knowing literally everything about the massive 500,000 LOC Java Enterprise framework he's using.

code:
@Autowired
private PasswordEncoder passwordEncoder;
was defined 5 lines above his method. The controller only had one other service injected. It was used in another method (not written by him, true) . There was absolutely no reason whatsoever to not use it.

Adbot
ADBOT LOVES YOU

Soricidus
Oct 21, 2010
freedom-hating statist shill
can't we just be impressed that this codebase is actually using a non-terrible method for storing passwords in the first place?

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