• 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

Help?

This is Objective C

I have a date string that is: May 23, 2015 09:00 AM

I'm trying to format the string as:

Code:
[dateFormat setDateFormat:@"MMM dd, yyyy HH:mm a"];

But when I do that, I get: May 23, 2015 00:00 AM
as the result. What am I doing wrong?
 
Help?

This is Objective C

I have a date string that is: May 23, 2015 09:00 AM

I'm trying to format the string as:

Code:
[dateFormat setDateFormat:@"MMM dd, yyyy HH:mm a"];

But when I do that, I get: May 23, 2015 00:00 AM
as the result. What am I doing wrong?

You're combining HH (0-24 hour representation of time) with a (the 12-hour AM/PM representation of time). These cannot go together. Take out the 'a' if you're doing 24 hour time, or use lower case 'hh' if you're doing 12 hour.

See Unicode Technical Standard #35's Appendix F: Date Format Patterns and the "Date Field Symbol Table" contained within for an explanation of what those string matching patterns mean. JavaScript has this, too (EDIT: Whoops, no.)*, as do many other modern programming languages that come with libraries to interpret dates.

Now, specific to iOS/OS X, the date formatter will be initialized with your user's time zone and your user's locale. The Data Formatting Guide's section on parsing date strings suggests you standardize that so that it interprets any string you throw at it as GMT/UTC with something akin to;

Code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = (whatevs)
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

If that's what you want. You might want something that can pick up the user's locale instead and formats the time appropriately, but that's an exercise best left for the reader, and Apple's documentation.


* - I've been staying up many late nights doing Angular. This is available as an Angular filter, but the ECMAScript standard doesn't yet offer a service to convert dates given pattern matching strings. There's only a parse method on the date object that recognizes a fixed number of syntaxes, between ES1 and ES5.1. That's a shame.
 
Thanks for the help. I made a few adjustments but I'm still getting errors. Let me see if I can explain it in more detail. I'm parsing some xml that has date strings that read as: May 25, 2015 09:00 AM

And I'm going to need to do some date manipulation on that date string (offsetting for various timezones, calculating time between now and that future date, etc) so I converted the date string into an NSDate with the following code

Code:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMM dd, yyyy hh:mm a"];
NSDate *date = [dateFormat dateFromString:dateStr];

The problem is with that code, the variable date is null. If I change the dateFormatter to the previous "HH:mm a", I don't get a null, but I do get the erroneous: May 23, 2015 00:00 AM.

I know that format is correct though because it is the same one I use with the current local machine time, and putting it to NSLog displays it correctly, so I'm confused on why it is not reading the date string properly. And I know that's the exact string because I've printed it to console with an "X" at the end and there are no spaces or oddities.

Edit: Actually, I've now noticed that if I have the date formatter be "MMM dd, yyyy hh:mm a" it no longer prints AM/PM when I do the current local time. And, even with the lowercase "hh", it still gives me 24 hour time. So I switched back to the "MMM dd, yyyy HH:mm a" and that gives me 24 hour with the AM/PM. So now it looks like the date format is ignoring the "hh" and just using "HH" or something.

Edit 2: So I had to do the [[NSLocale alloc] initWithLocaleIdentifier:mad:"en_US_POSIX"]; even if I used "hh" explicitly.
 
Yeah, two things that have an annoying affect on NSDateFormatter are the user's locale, and the user's system preferences.

You can lock down the range of dates you have to interpret by assigning a locale to the NSDateFormatter. The idea is that there are NSDateFormatter style constants that allow you to read in the current date and display it depending on how the user set it, and for that you shouldn't specify the locale. The whole Date Formatters section of the Data Formatting guide covers this, it should be read back to front.

I don't know how either of those happen to be set up for the device you're testing on, and I was trying to repro the same issue in the US of A with my computer set to 12 hour time. Combining HH with a failed, but lower case hh or eliminating the a worked fine.

From the sounds of things, I think your device's locale is set to something friendly to 24 hour time and that's caused the formatter to aggressively try and interpret the hour as such. If that's true, the AM/PM with 24 hour time sounds like a glitch, unless there's some region out there that combines the two. And there just might be, but in this case I personally doubt it. :)
 

Ambitious

Member
Check if the data in the row to be found is actually valid in every column -- maybe you've edited by hand and entered invalid data. Also check if the PK field is padded with whitespace or something for weird reasons.

Nothing of that sort, unfortunately. Hibernate's hbm2ddl option is set to create-drop, so the tables are dropped when the session is closed. And the data definitely is correct and valid.

I was finally able to find a workaround, namely making my MDB use bean-managed transactions instead of container-managed transactions. So I just wrapped all persistence-related code between begin() and commit(). Now it works.
But still, it really should work with CMT too. There's still over three weeks until the deadline, so surely I will have figured it out by then.
 

Zeus7

Member
Can anyone help me please. I have to write a Java menu based program for a stack application.

I have gotten this off the internet to get an idea but it doesnt work. This is the first time I have used Java so can anyone tell me what to fix please, thanks.

Code:
import java.io.*;
//to create stack using array and implement StkInterface
public class Stack
{
    int arr[];//array to behave as a stack
    int top;//to point to the top of stack
    final int MAX=10;//to fix the maximum size of array
    //constructor to create array and initialize top
    public void StackNoInterface()
    {
        arr = new int[MAX];
        top = 0;
    }
    //to check stack is empty or not
    public boolean isEmpty()
    {
        if (top == -1)
            return true;
        else
            return false;
    }
    //to check stack is full or not
    public boolean isFull()
    {
        if(top == MAX)
            return true;
        else
            return
            false;
    }
    //to add element in a stack
    public void push(int n)
    {
        if(isFull())
        {
            System.out.println("Stack overflow");
        }
        else
        {
            arr[++top] = n;
        }
    }
    //to take out element from stack
    public int pop()
    {if(isEmpty())
            return -1;
        else
            return arr[top];
    }
    //to show elements in stack
    public void show()
    {if(isEmpty())
            System.out.println("Stack underflow");
        else
        {
            System.out.println("Stack status: ");
            for(int x = top; x >= 0; x--)
            {
                System.out.print(arr[x] + "    ");
            }
        }
    }
//main() to call other methods
public static void main(String args[])
    {
        Stack obj=new Stack();
        BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
        int ch=0,n=0;
        //Displaying Menu
        do
        {
            System.out.print("1. Push");
            System.out.print("\n2. Pop");
            System.out.print("\n3. Show Stack");
            System.out.print("\n4. Exit");
            System.out.print("\nPlease select an option");
            ch=Integer.parseInt(bf.readLine());
            switch(ch)
            {
                case 1:
                System.out.println("Enter a number: ");
                n = Integer.parseInt(bf.readLine());
                obj.push(n);//call to push method
                System.out.println("Pushed. ");
                break;
                
                case 2: //call to  pop method
                int res=obj.pop();
                if(res == -1)
                {
                    System.out.println("No elements to pop. ");
                }
                else
                {
                    System.out.println("Element popped: " + res);
                    break;
                }
                
                case 3: //call to show method
                obj.show();
                break;
                
                case 4:
                System.out.println("Exiting... ");
                System.exit(0);
                
                default:
                System.out.println("Enter 1-4 only! ");
            }//switch ends
        } while(ch!=4);
    }//main() ends
}//class ends
 

Jokab

Member
Can anyone help me please. I have to write a Java menu based program for a stack application.

I have gotten this off the internet to get an idea but it doesnt work. This is the first time I have used Java so can anyone tell me what to fix please, thanks.

Code:
code

Saying "it doesn't work" is very unhelpful. What doesn't work? Does it crash? Does it not give you the output you expect? Do you get errors? What happens?

EDIT: Briefly looked it over and it seems like the "constructor" StackNoInterface (which it actually isn't, just an initializer method) is never called, which means that the array arr is never initialized. After the
Code:
Stack obj = new Stack();
do
Code:
obj.StackNoInterface();
 

Zeus7

Member
Saying "it doesn't work" is very unhelpful. What doesn't work? Does it crash? Does it not give you the output you expect? Do you get errors? What happens?

EDIT: Briefly looked it over and it seems like the "constructor" StackNoInterface (which it actually isn't, just an initializer method) is never called, which means that the array arr is never initialized. After the
Code:
Stack obj = new Stack();
do
Code:
obj.StackNoInterface();

Thanks for the quick reply.

I just realised I never said anything specific about it not working, I apologise for that.
Thanks, it is working now :)
 

Haly

One day I realized that sadness is just another word for not enough coffee.
1) Your major's department will likely have resources for career guidance, like a counselor or some sort of job search connection thing

2) Find companies you like and take a look through their Jobs/Careers pages

3) Use a job search engine like Monster. You can even browse Craiglist

4) You'll need a resume and, depending on where you apply, a cover letter

5) It's actually a bit late in the academic year to look for internships. Most of the lucrative ones have been gobbled up by April so that's something to keep in mind in the future
 
1) Your major's department will likely have resources for career guidance, like a counselor or some sort of job search connection thing

2) Find companies you like and take a look through their Jobs/Careers pages

3) Use a job search engine like Monster. You can even browse Craiglist

4) You'll need a resume and, depending on where you apply, a cover letter

5) It's actually a bit late in the academic year to look for internships. Most of the lucrative ones have been gobbled up by April so that's something to keep in mind in the future

Thanks. My brother said the same thing about finding something I like, but I'm not sure what I like to do. Once I come back to school, I'll go to CS department to ask about internships. Hopefully they help me out. I need a job since I just finished finals and I'm not sure if I'm going to take summer classes. I need something to do before coming back to school.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
It's a joke, what with California being the nation's software development hub.
 
Easiest way (only reliable way...) to get an internship is via personal connections, of course.

Past that, it's:
Code:
while (1)
{
    auto companies = getPlausibleCompanies();
    for (string& c : companies)
        if (sendResumeAndPray(c))
            return c;
    std::this_thread::sleep_for(24h);
}
 

Haly

One day I realized that sadness is just another word for not enough coffee.
- References to strings "c" in ranged-based for loop not const.

REJECTED.
 

doodle

Member
Hey GAF. I, at one point in time, found a subreddit dedicated to the posting/finding of groups that wanted to work on group development projects. I'm looking to start a project to take up my spare time, but do not seem to be able to find many websites that are dedicated to finding groups and the few subreddits that I have found don't receive many replies. Does anyone have any suggestions?
 

Tater Tot

"My God... it's full of Starch!"
Could use a little help on this homework problem:

Print "Censored" if userInput contains the word "darn", else print userInput. End with newline.

Code:
import java.util.Scanner;

public class CensoredWords {
   public static void main (String [] args) {
      String userInput = "";

      userInput = "That darn cat.";

      if(userInput.equals("darn")) {     \\ I typed these two lines
         System.out.println("Censored");
      }

      return;

not really sure what to do.
 
Slightly off-topic, but would anyone here be willing to look at my resume? I'm trying to get a software developer internship, but I'm having no such luck. :\
 

NotBacon

Member
Could use a little help on this homework problem:

Print "Censored" if userInput contains the word "darn", else print userInput. End with newline.

not really sure what to do.

Hint: .equals() will return true only if the two strings it's comparing both contain the exact same characters in the exact same order.

You'll need a function that checks to see if a string *cough* contains *cough* another string.
 

pants

Member
Could use a little help on this homework problem:

Print "Censored" if userInput contains the word "darn", else print userInput. End with newline.

Code:
import java.util.Scanner;

public class CensoredWords {
   public static void main (String [] args) {
      String userInput = "";

      userInput = "That darn cat.";

      if(userInput.equals("darn")) {     \\ I typed these two lines
         System.out.println("Censored");
      }

      return;

not really sure what to do.
You want something like userInput.toLowerCase().contains(placeholderfordarnhere.toLowerCase());
 

mvtn

Member
"Losing data is a feature." – Why Snapchat loves MongoDB

If I had Twitter I'd follow lol.

It doesn't seem to be that active so you won't miss a lot.

I actually love the JavaScript ones, especially this one:
"JavaScript library with no code but cool logo hits 5,000 stars"
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I'm a bit out of touch with C++, but want to check - this is just poor style, not a bug in itself, right?

It's a very small nitpick, not really a bug. Currently, sendResumeAndPray(c) can potentially modify the contents of companies, although I don't think that would matter because it's a temporary list.
There's a more subtle bug too. Each sendResumeAndPray() call appears to block until a response is received. We all know how well that will turn out.
Hah. My own sendResumeAndPray() implementation exhibits that exact same bug, I should probably fix it...
 

empyrean

Member
Bit of advice if anyone may be so kind.

I have an object that is as follows:

Object A
-- some properties --
-- List<Object B> --

Object B
-- some properties --
--List<Object C> --

Object C
-- some properties --
-- List<Object D>

Object D
-- some properties --

Now say I'm trying to follow DDD (to the best of my limited knowledge).

So say i have a repository pattern for each object above, i also have domain services for each object when required.

Im using a TSQL backend.

Where should the code go if i want to construct a fully populated Object A with all sub objects correctly populated? Since my limited understanding is that Repository A shouldn't know or use Repository B so it can't go there. Domain A and Domain B shouldn't really depend on each other? So do i put it in the Application Services?

What about performance? As it currently stands i can bring back an entire objects worth of data (so object a,b,c,d etc) in multiple result sets but in one query to the database. I currently have all a,b,c,d in one repository/service file, if i split this up i can no longer use this single database call to create the full object? and instead would need to make multiple database calls as i can't pass around a data reader in the application/domain layer as thats infrastructure so should be in the repository (C#)?

is this a big issue i should be worried about or is the clearer separation and manageability of code worth this small trade off (the application will be hosted and run locally).

Hope this makes sense and i haven't been too dumb :).

The application is reasonably small and shouldn't particularly grow in scope, so should i just leave them all in the one repository, one domain service and one application service files? Or should i think about splitting these up whilst i can.

Thanks.
 

Water

Member
It's a very small nitpick, not really a bug. Currently, sendResumeAndPray(c) can potentially modify the contents of companies, although I don't think that would matter because it's a temporary list.

It's as I thought then. I read cpp_is_king talking about "another bug" and got paranoid I've forgotten something really fundamental.
 

msv

Member
What's the best way to handle network authentication on repeated requests?

How safe is it to create a unique key on authentication and have the client use that on further requests? I guess that's the most used method online, with cookies and all. It's just that I have to make my own implementation of it, wondering how safe that could be. What if someone different starts making requests with fake keys, see if any work?
 

Daria

Member
heading in to talk to an advisor tomorrow about changing my major to CS (for the third time). originally dropping out freshmen year due to not liking the requirement of a communications class. five years later and three major changes later, I'm back to the original plan.

though they changed some of the required courses and have now added 'mobile app development - iOS' with obj-c still, or android development, I hope it's still a solid program in the next 1.5 years. and same goes for after the university, worrying about a job market bubble that'll pop or languages would change. either way though I'll be happy with my decision.
 

NotBacon

Member
I hope it's still a solid program in the next 1.5 years. and same goes for after the university, worrying about a job market bubble that'll pop or languages would change. either way though I'll be happy with my decision.

I don't think the desire for competent computer scientists is going anywhere...

Computers are continuing to become a bigger part of our lives, and companies are finding out it really does pay off (from what I've heard) to hire qualified CS majors instead of outsourcing overseas.

You picked the right major ;)
 

TronLight

Everybody is Mikkelsexual
Question about structs as functions arguments in C.

Do you HAVE to declare the struct outside the main AND before any function that uses that struct to make it work?

Because I tried declaring a struct inside my main(), and then declaring a struct variable and passing it to a function, and it wasn't compiling. I moved the declaration of the struct outside the main() and it worked. And only if it's declared ABOVE the function.

I swear my book did not mention it.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
A lot of stuff needs to be declared "in order" in raw C AFAIK.

Structs before functions, functions before they're called, local variables at the top of a function block, etc.
 

TronLight

Everybody is Mikkelsexual
A lot of stuff needs to be declared "in order" in raw C AFAIK.

Structs before functions, functions before they're called, local variables at the top of a function block, etc.

I mean yeah, but this struct thing flew completely over my head.
 

wolfmat

Confirmed Asshole
What's the best way to handle network authentication on repeated requests?

How safe is it to create a unique key on authentication and have the client use that on further requests? I guess that's the most used method online, with cookies and all. It's just that I have to make my own implementation of it, wondering how safe that could be. What if someone different starts making requests with fake keys, see if any work?
Ok, so here's the state-of-the-art layout for this.
(1) The token should be impossible to reverse-compute to get to username / password in reasonable time
(2) The token should differ each time it is computed from username / password
(3) The token should not be computed trivially (like, "md5-hash of usernamepassword plus salt" is weak)
(4) The token should be registered as being in use, and should time out eventually (this is why it's called a session)
(5) When transferring requests from user to server, the tokens are part of them; the transfer should be encrypted to make man-in-the-middle attacks extremely hard
(6) When transferring the token (actually, data in general) from server to user, the transfer should also be encrypted
(7) The transfer encryption should be strong
(8) The server should be safe regarding login as admin, services running, firewall configuration, internal communication encryption
(9) You have to assume the client is in a safe environment (legally, you have to actually demand this, or invalidate the session extremely early)

So 1-3 tell you that you should look for readymade solutions to compute tokens. Consider OAuth.
4 is just housekeeping; persist sessions in a database.
5-7 are supposed to be solved with something like OpenSSL or OpenSSH at the least, depending on what your network service is.
8 means you need to administrate the server well.
9 is Terms Of Use territory.

If you've done all that, tokens can STILL be guessed, but they CANNOT be trivially stolen or derived or anything if your client is running in a safe environment.

Let me give an example:
To operate the Facebook Graph API, all you need is a token (a user token for instance). The token is a string. If you make the request to alter a Facebook page, and you provide a valid token associated with a user, and that user is allowed to alter the page, then the alteration will take place regardless of whether the token was guessed or stolen or rightfully obtained.
But guessing the token is superhard.
That's all there is to say about that.

It's a lot of work getting all of this right. So you need to gradually introduce 1-9 (not in that order though).
 

msv

Member
It's a lot of work getting all of this right. So you need to gradually introduce 1-9 (not in that order though).
Okay first - awesome, that was exactly what I wanted to know.

Question though, does it improve security to have the token be based upon the username/password? Is it also possible to use a random GUID/UUID coupled with verifying the source IP/machine id? Or is this so that the server doesn't have to send the client the token, instead the client can compute one themselves?
 

wolfmat

Confirmed Asshole
Okay first - awesome, that was exactly what I wanted to know.

Question though, does it improve security to have the token be based upon the username/password? Is it also possible to use a random GUID/UUID coupled with verifying the source IP/machine id? Or is this so that the server doesn't have to send the client the token, instead the client can compute one themselves?

Source IP / Machine ID can be forged, and is not guaranteed to be unique. The random number doesn't change this. Random numbers are also not the right way to go about this because for example, the sequence 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.....,3222312 could be the perfectly reasonable result of an RNG. So if two users happen to have the same machine, and have the same ISP with a limited IP range, and user 2 logs in one day after user 1 and happens to get the same IP as user 1 yesterday, and by chance, your random number generator spits out the same number, and you haven't involved at least the User ID in this, then you're in trouble.

Also, IP and machine ID are not proper secrets.

Make sure to involve the User ID or Username, and be wary of hashes (hashes clash by definition). Make sure to involve an ascending number (like Unix time) along with the RNG result. When wraparound of the ascending number happens, flush all sessions.

And then, you still have the issue that the User ID or Username are not proper secrets, but the password is (or at least it's supposed to be one ;) ). So if you trivially produce such a token without involving the user's unique password, that's dicey.

As an aside: Don't involve the password directly, also. Generally, don't ever store passwords. With passwords, it's sort of OK to use hashes. Store a password's hash; if a user enters the password on login, compute the hash; if it matches the stored hash, you're good.

Edit: The above goes for your own token generation algorithm. Seriously consider using OAuth2 instead. It'll save you a lot of work and it'll be safer than anything you'll ever come up with unless you're a genius.
 

Kansoku

Member
Guys, I need some help. I can't for the life of me remember some stuff about P, NP and NP- complete and I can't find it on my notes, nor the teachers material nor the internet.

Basically, if I have a problem A which is in NP and a problem B which is in NP-Complete, what can we say about P and NP when:

1. We find a polynomial solution to both A and B
2. We find there's no polynomial solution to A
3. We find there's no polynomial solution to B
4. We find there's no polynomial solution to both A and B

IIRC, from 1 we can deduce P = NP, from 4, P != NP and we can't deduce anything form the other two, but I'm not understanding why.

Thanks.
 

Ambitious

Member
Guys, I need some help. I can't for the life of me remember some stuff about P, NP and NP- complete and I can't find it on my notes, nor the teachers material nor the internet.

Basically, if I have a problem A which is in NP and a problem B which is in NP-Complete, what can we say about P and NP when:

1. We find a polynomial solution to both A and B
2. We find there's no polynomial solution to A
3. We find there's no polynomial solution to B
4. We find there's no polynomial solution to both A and B

IIRC, from 1 we can deduce P = NP, from 4, P != NP and we can't deduce anything form the other two, but I'm not understanding why.

Thanks.

1
If B is NP-complete, then B is also NP-hard, which means we can polynomially reduce any problem in NP to B. A polynomial solution for B would thus provide as with a polynomial procedure for any arbitrary NP problem, which implies P = NP.

2
If there's no polynomial solution for A, then A is in NP but not in P. Therefore P != NP.

3 and 4
If B is NP-complete, then B is also in NP. As per the statement above, then P != NP.


This pic is really helpful in understanding this matter:

1000px-p_np_np-complepdylu.png
 

msv

Member
Thanks again wolfmat.

Uuuurgh, I've had it up to here with project references in Visual Studio.

Layout is like this:

C references B references A.

I cannot use classes from A without referencing A directly (even when B exposes a class from A in a public method). That seems like such a lame restriction to me, should not happen when all the referenced assemblies are managed, in the same solution even!

Besides that, there's no option to just embed the damn classes! VS builds DLLs for each class library. I'm only separating the classes into different projects so that the workflow and clarity is improved, I have no need to distribute DLLs separately! With IntelliJ I could just choose to embed the classes, why not here? IntelliJ has tons of options for deployment, but in VS it seems like there is only one standard deployment type/option? Seems ridiculous that you would have to write something yourself or use an external application just to do something as simple as embedding instead of referencing.

Am I missing something here?
 
Top Bottom