问:
Should I extract specific functionality into a function and why?
I have a large method which does 3 tasks, each of them can be extracted into a separate function. If I'll make an additional functions for each of that tasks, will it make my code better or worse and why?

Obviously, it'll make less lines of code in the main function, but there'll be additional function declarations, so my class will have additional methods, which I believe isn't good, because it'll make the class more complex.

Should I do that before I wrote all the code or should I leave it until everything is done and then extract functions?

答:
For me there are four reasons to extract code blocks into functions:

You are reusing it: you just copied a block of code into the clipboard. Instead of just pasting it, put it into a function and replace the block with with a function call on both sides. So whenever you need to change that block of code, you only need to change that single function instead of changing the code multiple places. So whenever you copy a code block, you must make a function.

It's a callback: It's an event handler or some kind of user code a library or a framework calls. (I can hardly imagine this without making functions.)

You believe it will be reused, in the current project or maybe somewhere else: you just wrote a block that computes a longest common subsequence of two arrays. Even if your program calls this function only once, I would believe I will need this function eventually in other projects too.

You want self-documenting code: So instead of writing a line of comment over a block of code summarizing what it does, you extract the whole thing into a function, and name it what you would write into a comment. Though I'm not a fan of this, because I like to write out the name of the algorithm used, the reason why I have chosen that algorithm, etc. Function names would be too long then...


问:
Quoting for a project with closed source
I sit with a project that I need to quote, and until the job is awarded, I can only use "View source" to check, and ask a few questions about the system. That makes quoting outright impossible for me to do.

My question is: how do one go about quoting for such a project? What kind of questions should I ask? Do I decline to quote? Due to uncertainty, do I pad my quote?

答:
You can always ask to sign an NDA (Non-Disclosure Agreement) and ask to view the code or at least a sample of it.

You should also be focusing on the business problem rather than the technical aspect. If this is legacy PHP code, you're taking a risk and so is the business and you should be charging as much as possible: double your current rate because the risk is high.

ContentLicense: CC BY-SA 3.0


问:
Analogy for Android fragments
I'm trying to understand the flow of Android apps. I come from a RoR background, so I try and use that background to understand new concepts in Android.

Here's my question:

How can I think about fragments? Are they like partials in Rails? If so, how? If not, why?

答:
Not Sure how android fragments could be compared to RoR but I can tell you about what I know.

You should think of Fragments as SubActivities, just like an Activity a fragment has also a life cycle:

The whole point in fragments is to be able to run multiple section of an activity independently.

It's like breaking down an activity and being able to update each one on its own.

You have to keep in mind fragments run on activities.

To understand more you should look into sample projects like the navigation Drawer one from google where a sliding menu is implemented in an activity, the activity (menu) then is responsible for swaping the different Fragments (Menu items).

Sample code

Title: Analogy for Android fragments


问:
How to ideally calculate profit margin with zero sales
How do you handle the following scenario without null?

You have this problem (In Java):

```<code>BigDecimal sales = ...;
BigDecimal cost = ...;
BigDecimal profit = sales.subtract(cost);
// Profit Margin = profit / sales
BigDecimal profitMargin = profit.divide(sales, 20, RoundingMode.HALF_UP);
</code>```

Because sales is sometimes zero, we turn the last line into:

```<code>BigDecimal profitMargin = sales.compareTo(BigDecimal.ZERO) == 0 ? null : profit.divide(sales, 20, RoundingMode.HALF_UP);
</code>```

In which case if profitMargin == null, then we know what that means. If you make profitMargin = 0, that isn't really correct, nor is infinity a good value either. It seems best that it would remain undefined. Yet, it is an "unexploded bomb." So, what's the best way to handle this?

This questions as originally asked on Stack Overflow, and also referred me to the question Are null references really a bad thing?

答:
Don't ask Us! We're not the ones making business decisions based on the output of your calculations!

Having said that, developers need to know how to approach these situations. In my experience, dilemmas like this fall into two broad scenarios:

This happens relatively often and business users will see output based on $0.00 sales on a regular basis.

This is a corner case that happens extremely rarely. It is so infrequent that business users have difficulty remembering the "last time" it happened. When it does happen, its not a business crisis.

For scenario #1, I would go to the business users and ask them what profit margin % they want to see for $0.00 sales.

For scenario #2, this probably isn't worth wasting the time of business users to find out what they want to see. I would set it to something that is least likely to give a false impression, probably 0%. In my opinion using a number like 20% would give the false impression that money is being made. Don't make a decision on your own unless you are familiar with the users and business. When in doubt, consult the business users.


问:
How to avoid Memory Error
I am working with quite large files (pytables) and I am having problems with the Memory Error when I try to load the data for processing.

I would like some tips about how to avoid this in my python 32bits, since I am new working with pandas and pytables, and I do not know how to work splitting the data in small pieces.

My concern also comes when, if I get to split the data, how to calculate statistics like mean, std, etc without having the entire list or array, etc.

This is a sample of the code that I am using now, this works fine with small tables:

```<code>def getPageStats(pathToH5, pages, versions, sheets):

    with openFile(pathToH5, 'r') as f:
        tab = f.getNode("/pageTable")

        dversions = dict((i, None) for i in versions)
        dsheets = dict((i, None) for i in sheets)
        dpages = dict((i, None) for i in pages)

        df = pd.DataFrame([[row['page'],row['index0'], row['value0'] ] for row in tab.where('(firstVersion == 0) & (ok == 1)') if  row['version'] in dversions and row['sheetNum'] in dsheets and row['pages'] in dpages ], columns=['page','index0', 'value0'])
        df2 = pd.DataFrame([[row['page'],row['index1'], row['value1'] ] for row in tab.where('(firstVersion == 1) & (ok == 1)') if  row['version'] in dversions and row['sheetNum'] in dsheets and row['pages'] in dpages], columns=['page','index1', 'value1'])

        for i in dpages:

            m10 = df.loc[df['page']==i]['index0'].mean()
            s10 = df.loc[df['page']==i]['index0'].std()

            m20 = df.loc[df['page']==i]['value0'].mean()
            s20 = df.loc[df['page']==i]['value0'].std()

            m11 = df2.loc[df2['page']==i]['index1'].mean()
            s11 = df2.loc[df2['page']==i]['index1'].std()

            m21 = df2.loc[df2['page']==i]['value1'].mean()
            s21 = df2.loc[df2['page']==i]['value1'].std()

            yield (i,m10, s10), (i,m11, s11), (i,m20,s20), (i,m21,s21))
</code>```

As you can see, I am loading all the necessary data into a Pandas DataFrame to procoess it, just the mean and the std by now.

This is quite fast, but for a pytable with 22Millions of rows I get Memory Error

答:
As far as I know Pandas is not the best tool if you can not store everything in the memory.

Additionally you are creating some extra data that you might try to avoid.
I'm talking about the list comprehensions.

For once they are a bit too big/complex to be a list comprehension as for me.

Secondly due to the its nature for short period of time your are holding too much data: the complete list + its copy representation within the DataFrame.
With the second assignment (df2) you are holding a new DF, the list and df.
Not to mention all other object you have already created.

Try to use a generator instead of a list comprehension. Either in line by replacing [...] with (...) or a proper generator that will be more readable too.

(When solution 1 is not enough) Drop Pandas and do calculations manually. That might require you to iterate over the data twice, but will get you the result.

Title: How to avoid Memory Error

ContentLicense: CC BY-SA 4.0


问:
Understanding how variable assignment works
When I started learning C programming a few years ago, my tutor taught me similar to most of the tutors around the world. She said me the very basic things like any int datatype is of 2 bytes memory. If the following is my code,

```<code>#include"stdio.h"
#include"conio.h"
void main()
{
    clrscr();
    int i,n;
    n = 0;
    for(i=0;i<3;i++)
        n = n + i;
    printf("%d",n); //obviously it prints 3
    getch();
}
</code>```

she will explain like what I have written below. Here my teacher starts off her class yet again. . .

Listen students. Here we have two integer values. So let us draw two boxes each of 2 bytes memory.The first box be the memory space of i and the second box be that of n. At n = 0; 0 gets stored into the box n. As the control gets into the loop, 0 gets stored into the box i intially.

0 0

Now the condition is checked. i < 3. Condition gets true. So now the value of n changes from 0 to n+i i.e., 0+0=0. The first iteration then ends after the increment statement. Now i gets incremented to 1. So our picture becomes like this.

1 0

And now i < 3 again. Condtion gets true. n changes from 0 to n + i i.e., 0+1=1. Don't forget the increment my dears. Only then our iteration gets completed. i++ makes our i to 2 now. And the picture will now look like

2 1

She will go on similarly step by step and will complete when both the boxes get 3, 3 values.

So thats it kids. After we get our boxes like this

3 3

the value of n gets printed on the screen.

3

By that time, I was merely like a kid nodding its head when a teacher claims earth as a  circular mass. I never asked her any questions. I felt logically she was perfect. But now I am plentiful of queries. If there is a statement like n = n + i;, won't there be a conflict as both the destination space and the operation space is the same n box? Will the operations be done with the help of any default temporary space for calculations? What will happen if I use a recursive code like the following snippet.

```<code>int factorial(int n)
{
    if(n < 2)
    {
        return n;
    }
    else
    {
        n = n * factorial(n - 1);
        return n;
    }
}
</code>```

How could it be possible to use a single n box as my tutor taught? Won't a new n box be created whenever factorial(n - 1) is called? If I am right, how could the computer know which n box value to be returned? Somebody help me please. I am pulling of hairs from ma head!

答:
This is a very good question -- to ask your instructor.  She no doubt has a plan (or syllabus) of what she's going to teach and the order she's going to teach it in.

The first example you show with the for loop might come of of chapter 1 in a text book, while recursion and the factorial example might come from chapter 5.  We don't know what's in chapters 2 - 4, and might accidentally cause more confusion than we'd fix.

To try to answer your initial question:

If there is a statement like n = n + i;, won't there be a conflict as both the destination space and the operation space is the same n box?

Think of any variable (such as n) as a bucket that can hold exactly one number at a time.  Let's assume that number is 0 for now.

The teaching language BASIC used to have a slightly more verbose way of expressing your statement:

LET n = n + i

The idea is to find the bucket n, get the number from it, do some math (i.e., add the number from the other bucket i), then store that number back into the original bucket n.

The trick is to remember that n = n + 1 is not algebra, but a command to a computer to do something.  Using LET was a way to help beginners get past the idea that "=" sometimes means "mathematical equality" and sometimes means "assignment" or "put a copy of the right bucket's stuff into the bucket on the left".


问:
Advice on designing web application with a 40+ year lifetime
Scenario

Currently, I am apart of a health care project whose main requirement is to capture data with unknown attributes using user generated forms by health care providers. The second requirement is that data integrity is key and that the application will be used for 40+ years. We are currently migrating the client's data from the past 40 years from various sources (Paper, Excel, Access, etc...) to the database. Future requirements are:

Workflow management of forms

Schedule management of forms

Security/Role based management

Reporting engine

Mobile/Tablet support

Situation

Only 6 months in, the current (contracted) architect/senior programmer has taken the "fast" approach and has designed a poor system. The database is not normalized, the code is coupled, the tiers have no dedicated purpose and data is starting to go missing since he has designed some beans to perform  "deletes" on the database. The code base is extremely bloated and there are jobs just to synchronize data since the database is not normalized. His approach has been to rely on backup jobs to restore missing data and doesn't seem to believe in re-factoring.

Having presented my findings to the PM, the architect will be removed when his contract ends. I have been given the task to re-architect this application. My team consists of me and one junior programmer. We have no other resources. We have been granted a 6-month requirement freeze in which we can focus on re-building this system.

I suggested using a CMS system like Drupal, but for policy reasons at the client's organization, the system must be built from scratch.

This is the first time that I will be designing a system with a 40+ lifespan. I have only worked on projects with 3-5 year lifespans, so this situation is very new, yet exciting.

Questions

What design considerations will make the system more "future proof"?

What questions should be asked to the client/PM to make the system more "future proof"?

答:
OK, so I'm going to say some things here which are probably going to be pretty unpopular, but stick with me here.

As this is your first project where the data and/or the application is supposed to last for 20+ years, and you are the one leading the project, you need to take a step back and think about what the odds of this project succeeding are.  Because they are basically next to zero.

You need to spend a huge amount of time focusing on the database design and getting that right.  For this project to succeed you need to bring a data architect into the project, and sooner rather that later.  Without someone who is experienced in database design, and who is well practiced in looking forward to how the data can be used in the future the odds of the data still being useful after 5 years much less 40 years is slim to none.

Expecting two people (one of whom has the title of jr. dev) to build something from scratch which is expected to last 40 years, is probably not going to succeed.  There should be a team of people many of who are experienced in working with large projects like this who are working on the data design, the API design and the application design.  Something like this isn't a 2 person project.

Wanting to tie the project to something like Drupal shows why the project needs people who are used to working on these sorts of projects.  You don't want to tie the application to anything that may go out of style within just a few years.  If you did, finding someone to work on the system in 5-10 years could get very difficult very quickly.

I would take this advice to management and explain to them that you need to get more senior people on the project.  Otherwise the project is doomed to fail, and you'll probably end up being the one that takes the blame for it.


答:
Answer from a front-end perspective:

Don't listen to everyone saying it can't be done, because an experimental San Francisco State University web service I co-wrote in 1996 finally went to Internet heaven a couple years ago, and never needed a single browser compatibility fix in that time; that's almost half of your 40-year goal. And this JavaScript-based front-end I made in 1998 for a Stanford Research Institute project was replaced with something flashier a few years later, but there's no reason the original UI couldn't still be running today with minor compatibility fixes.

The trick is to ensure your app uses only widely-supported W3C/ECMA standards and has a clean design under your control. While a lot of web apps written to the trendy 90s-era technology won't work well or at all today, 90s-era web apps written to major standards still do. They may look passé, but they work.

The goal here isn't to write a web app that will go up on their server and remain there for 40 years without anyone touching it again. It's to build a foundation that can still be in use decades down the line, which can grow to support new features without having to be rebuilt from scratch.

First of all, you have to code to official standards and only to official standards. No JavaScript features not part of a ratified ECMAScript standard; ES5.1 is the current version and is generally supported so that's safe to target. Likewise, current versions of HTML5, CSS, and Unicode are good. No experimental JavaScript, CSS3 or HTML features (the ones with vendor-prefixes or without 100% agreement between browsers). And no browser-specific compatibility hacks. You can start using a new feature once it's in the standard and everyone supports it without prefixes.

ES5 support would mean dropping IE8 or earlier, which I suggest anyway since it requires browser-specific hacks which will be useless in a couple of years. I'd suggest ES5's Strict Mode for the best chance at longevity, which actually sets your baseline browser compatibility at IE10 and recent versions of everyone else. Those browsers also have native support for many of HTML5's form validation and placeholder features, which will be useful for a very long time.

New editions of ECMAScript maintain compatibility with older versions, so it'll be much easier to adopt upcoming features if your code is written according to current standards. For instance, classes defined using the upcoming class syntax will be fully interchangeable with classes defined with the current constructor.prototype syntax. So in five years a developer can rewrite classes into the ES6 format on a file-by-file basis without breaking anything -- assuming, of course, that you also have good unit tests.

Second, avoid trendy JavaScript app frameworks, especially if they change the way you code your app. Backbone was all the rage, then SproutCore and Ember were, and now Angular's the framework everyone loves to promote. They may be useful, but they also have something in common: they often break apps and require code changes when new versions come out and their longevity is questionable. I recently updated an Angular 1.1 app to 1.2, and quite a bit had to be rewritten. Likewise, going from Backbone 2 to 3 requires a lot of HTML changes. Standards are slow-moving for a reason, but these frameworks move fast and things breaking periodically are the cost.

Plus, new official standards often leave old frameworks obsolete, and when that happens those frameworks either mutate (with breaking changes) or are left behind. You know what's going to happen to all the world's competing promise libraries once ECMAScript 6 is ratified and all browsers support its standardized Promise class? They'll become obsolete and their developers will stop updating them. If you picked the right framework your code might adapt well enough, and if you guessed poorly you'll be looking at a major refactoring.

So if you're thinking of adopting a third-party library or framework, ask yourself how hard it'll be to remove in the future. If it's a framework like Angular that can't ever be removed without rebuilding your app from scratch, that's a good sign it can't be used in a 40-year architecture. If it's a third-party calendar widget that you abstracted with some custom middleware, replacing it would take a few hours.

Third, give it a good, clean app structure. Even if you aren't using an app framework you can still take advantage of developer tools, build scripts, and a good clean design. I'm personally a fan of Closure Toolkit's dependency management because it's lightweight and its overhead is completely removed upon building your app. LessCSS and SCSS are also great tools for organizing your stylesheets and building out standards-based CSS stylesheets for release.

You can also organize your own code into single-use classes with an MVC structure. That will make it much easier to come back several years into the future and know what you were thinking when you wrote something, and to replace only those parts that need it.

You should also follow the W3C's advice and keep presentational information completely out of your HTML. (That includes cheats like giving elements presentational class names, like "big-green-text" and "two-columns-wide".) If your HTML is semantic and CSS is presentational, it'll be much easier to maintain and adapt it to new platforms in the future. It'll also easier to add support for specialized browsers for blind or disabled people.

Fourth, automate your tests and make sure you have near-full coverage. Write unit tests for every class, whether server-side or in JavaScript. On the front end, make sure each class performs according to its spec in every supported browser. Automate these tests from your build bot for every commit. This is important for both longevity and reliability, since you can catch bugs early even when current browsers obscure them. Both Jasmine and Google Closure's JSUnit based testing frameworks are good.

You'll also want to run full UI functional tests, which Selenium/WebDriver are good at. Basically, you write a program that steps through your UI and uses it as if a person were testing it. Wire those up to the build bot as well.

Lastly, as others have mentioned your data is king. Do think through your data storage model and make sure it's built to last. Make sure that your data schema is solid, and make sure that's tested thoroughly as well on every commit. And make sure your server architecture is scalable. This is even more important than anything you do on the front end.

Title: Advice on designing web application with a 40+ year lifetime

Body:
Scenario

Currently, I am apart of a health care project whose main requirement is to capture data with unknown attributes using user generated forms by health care providers. The second requirement is that data integrity is key and that the application will be used for 40+ years. We are currently migrating the client's data from the past 40 years from various sources (Paper, Excel, Access, etc...) to the database. Future requirements are:

Workflow management of forms

Schedule management of forms

Security/Role based management

Reporting engine

Mobile/Tablet support

Situation

Only 6 months in, the current (contracted) architect/senior programmer has taken the "fast" approach and has designed a poor system. The database is not normalized, the code is coupled, the tiers have no dedicated purpose and data is starting to go missing since he has designed some beans to perform  "deletes" on the database. The code base is extremely bloated and there are jobs just to synchronize data since the database is not normalized. His approach has been to rely on backup jobs to restore missing data and doesn't seem to believe in re-factoring.

Having presented my findings to the PM, the architect will be removed when his contract ends. I have been given the task to re-architect this application. My team consists of me and one junior programmer. We have no other resources. We have been granted a 6-month requirement freeze in which we can focus on re-building this system.

I suggested using a CMS system like Drupal, but for policy reasons at the client's organization, the system must be built from scratch.

This is the first time that I will be designing a system with a 40+ lifespan. I have only worked on projects with 3-5 year lifespans, so this situation is very new, yet exciting.

Questions

What design considerations will make the system more "future proof"?

What questions should be asked to the client/PM to make the system more "future proof"?


答:
The application need not survive 40 years without any evolution. But, because it would or should be built from scratch, it could still be 'functioning'.

What is the most key thing is the 'data architecture' that allows for some stability and governance as well as extensible.

We've designed data architecture and taxonomy that could almost survive the end of humanity but still be extensible. You've got find a true DATA TAXONOMY / DATA ARCHITECTURE person to do this for you.


问:
All programming functions always return to the If or If/Else statement?
After learning, coding, and coding even more than ever now, I have noticed a trend in a lot of programming which I do. The trend is that the majority of my functions are if{} or if{} else{} statements when it comes to performing the functions in my code.

I narrowed out the option of it just being the project which I am working on. The project is building a PHP Framework or Application (whichever you want to call it). The vast majority of my code for the autoloader.php, application.php, and all of the heavy-lifting files are performing their functions of making sure everything loads correctly and builds the environment.

After working with very complex functions within my code to do this and that, they are all wrapped within an if{} or if{} else{} statement.

Is this a common trend for the majority of programming? Or am I over reacting to something which I am seeing a lot of? Does the most complex functions in coding always go back to the basics of the legendary if{} or if{} else{} statement?

答:
There are multiple ways to look at this question.

How the conditionals are used

This is probably more the question you asked. And the answer is, it depends on a number of factors. For folks that heavily use SQL, the end up having queries often built in a way (e.g. using WHERE or HAVING clauses) that the code does not need if conditions. However, those conditions have just moved into somewhere else and look different. Therefore, it becomes an organges to apples comparison.

Some developers will tend to write more conditional code while others may use declarative expressions (such as LINQ in C#), in which the Select, for example, already embodies conditionals.

And lastly, sometimes it's just a personal style. For code clarity, I prefer not to write nested conditionals, and thus end up distributing them elsewhere. In many cases, I reduce the conditionals by using patterns, such as Adapter or DataMapper which pushes conditional in one place and the rest of the logic flows depending on which class was instantiated.

Code complexity

There are some metrics, such as cyclomatic complexity (also known as conditional complexity) that will attempt to estimate whether the code is too complex to be maintainable (and thus considered bad). For the reasons I mentioned in the previous section, and by spending a fair amount of my career in test discipline testing others' code, I can tell you that it's hard to generalize this one too, and thus opinions vary on these metrics, even within the test community.

Howeve, you can read more on these and some tools, such as Visual Studio, will give cyclomatic complexity and sometimes you can try to improve it and see if it helps with code organization. Sometimes, such 'prototyping' does help.

Principle of conditions

In principle, if/else conditions (and all of its sisters) are really making one or more decision. That decision could be because the program actually needs to make a decision on user's behalf (such as deciding whether to include a transaction for a balance sheet, etc.), or a decision for internal program logic (e.g. based on screen resolution, deciding whether the flow is multi-column or single column).

Thus, in general, quite a bit of code can look conditional, and no one can state whether there is anything wrong with it (or not).

Conclusion

In my opinion, code organization is some art and some science. I learnt the art part just by coding for a living for a major part of my career, and the science part by learning through books, code reviews, etc. I do not think anyone can achieve one without the other. Your best bet, if you are concerned about your code, is to convince someone to do a peer review of your architecture, design, data model and code. An outsider, especially someone who hasn't worked with you, can sometimes even bring a perspective that you cannot easily payback. But you can return the favor to them (or someone else).


答:
The key here is to focus on the database (as several above have said). This needs to be coherent and completely describe the operation. It needs to grow with the operation as it changes. If it is not easy to change then it will get out of date and that is the kiss of death. The rest is relatively less important.

I disagree with those above who suggest normalisation is not important, though there are always cases where the current systems are not up to the job. In these cases denormalise but ensure the database handles the extra writes/ changes as part of an atomic transaction. That way you can effectively ignore the problem till you can fix it.

The company I worked for before retirement is running a system that was written from scratch and has grown almost continuously for 25 years, and covers virtually all aspects of a medium retailer. Aspects of this system that I feel were important are:

Integration is vital.

The database needs to be as correct and understandable to both IT and other staff, so an almost paranoid emphasis on naming is required. We have tables of defined mnemonics which are then combined to make up table and field names and all “codes” were likewise named as constants and stored in a EAV table structure.

We encapsulated business logic into database triggers. This is painful at first and requires additional work to transmit error messages to clients and to allow triggers to be changed flexibly without locking the whole table on some systems, but this quickly becomes a massive time saver, and forces the database to be much more correct than otherwise.

Assume you will keep at least reference tables (ideally all but the fastest and least important transactions) for the life of the system, even when “deleted” so your references are correct.

Because of the above ensure any unique identifiers and transaction numbers are sized for the long term. (I originally jokingly suggested that they needed to last until I retired).


问:
Examples of designing a database that handles point tracking?
I'm attempting to expand my knowledge of how database designs and concepts work. I'm working on a hobby web/mobile app for practice that will challenge me. However, I am running into an issue.

What my novel concept is that there are two buttons 'yes' and 'no'.

The buttons can only be clicked once a day.

If 'yes' is clicked then a counter keeps tracks of how many clicks (days) it has been pushed. Example "You've tied your shoes 95 days in a row!"

If 'no' is clicked then the counter "resets" for example "It has been 0 days since you've tied your shoe."

I've done some reading but I haven't been able to find too many examples that are like this.
I've read several posts here (a sample of them below)
(
implementing dynamic query handler on historical data

Storing stop/start points in a database

In an online questionnaire, what is a best way to design a database for keeping track of users all attempts?
)

but I'm still pretty confused on how to move forward. My initial idea was to have a

user table (id | user | password)

points table (id | point | date)

If a person clicks on yes then it adds an entry into the points table. If they don't click anything then no entry occurs. If they click no it's a -1.

However, I'm not certain this is a solid way to build out the database especially if I want to track it.

My questions are:

Given the few tasks above, how to setup the database?

How would I be able to display a counter that once someone hits no it 'resets'? For example the database tracks that the individual has tied their shoes for the last 9 days in a row but once they say no they didn't tie their shoes the counter resets to 0.

How to proceed with analytics side, to show how many times they've clicked no, yes, so on but that's down the road.

答:
Firstly, whenever a user is involved, there is at least one additional state involved: what if the user does not interact or use your app on any given day?

This is important, because it leads to a variety of cases, e.g.

If a user clicks yes on a Saturday, logons on Sunday but doesn't click a yes or a no, what do you want to show to the user?

If a user clicks yes on a Saturday, doesn't logon on Sunday, and then clicks a yes on Monday, what do you want to show to the user? Is that 3 days, 2 days or just 1 day in a row?

If a user clicks no on Saturday, doesn't logon on Sunday, and then clicks a yes on Monday, is that 2 days or just 1 day in a row?

Given that answers to these are not known, there could be additional cases to consider. The DB model usuall depends on what the complete behavior is going to be (i.e. the requirements).

For most flexible design, I would create the points table with the following columns:

```<code>UserId: acts as a foreign key for the id field in the user table
DateOfLastEntry: The date on which the user last clicked anything (regardless of yes or no)
NumberOfConsecutiveYes: number
</code>```

Then code the following cases:

The entry for the user is created on the day the user first clicks a yes or a no.

For every click, compare the DateOfLastEntry with today's date. If the date matches, ignore user's click.

If the DateOfLastEntry is yesterday: I) If the user clicked Yes, add 1 to NumberOfConsecutiveYes, update the DateOfLastEntry  to today. II) If user clicked No, set NumberOfConsecutiveYes to 0, and update the DateOfLastEntry to today.

For the day before yesterday, either use case 3 or add logic for whatever case you want to add.

Body:
Firstly, whenever a user is involved, there is at least one additional state involved: what if the user does not interact or use your app on any given day?

This is important, because it leads to a variety of cases, e.g.

If a user clicks yes on a Saturday, logons on Sunday but doesn't click a yes or a no, what do you want to show to the user?

If a user clicks yes on a Saturday, doesn't logon on Sunday, and then clicks a yes on Monday, what do you want to show to the user? Is that 3 days, 2 days or just 1 day in a row?

If a user clicks no on Saturday, doesn't logon on Sunday, and then clicks a yes on Monday, is that 2 days or just 1 day in a row?

Given that answers to these are not known, there could be additional cases to consider. The DB model usuall depends on what the complete behavior is going to be (i.e. the requirements).

For most flexible design, I would create the points table with the following columns:

UserId: acts as a foreign key for the id field in the user table
DateOfLastEntry: The date on which the user last clicked anything (regardless of yes or no)
NumberOfConsecutiveYes: number

Then code the following cases:

The entry for the user is created on the day the user first clicks a yes or a no.

For every click, compare the DateOfLastEntry with today's date. If the date matches, ignore user's click.

If the DateOfLastEntry is yesterday: I) If the user clicked Yes, add 1 to NumberOfConsecutiveYes, update the DateOfLastEntry  to today. II) If user clicked No, set NumberOfConsecutiveYes to 0, and update the DateOfLastEntry to today.

For the day before yesterday, either use case 3 or add logic for whatever case you want to add.


问:
Understanding Arithmetic In C
I have an embarrassingly simple question, but I need to make sure I understand this correctly. I have a *.c file with the following line:

```<code>    CSRConstant = 2*macroParticleCharge*particleCharge/pow(3*rho0*rho0, 1./3.)/(4*PI*epsilon_o*particleMass*sqr(c_mks));
</code>```

Is this interpreted as:

答:
Yes, I as far as I can tell the expression in the form you have written it will produce a very good approximation to the correct result of evaluating that formula over a very large range of input values.

You have performed a specific simplification of one constant calculation, for reasons I do not understand. If you're going to simplify one calculation, why not simplify all of them?

If this calculation appears inside a loop, you might want to check how good your compiler is at optimising those floating point calculations, especially the constants. If it doesn't, you might want to.

There are some rather specific issues that can arise in using floating point calculations on computers, either when you deal with numbers at extreme values (small and large) or when you perform operations that lose significant digits (like subtraction, in particular). I see none of those here.

Worry not. The computer says yes. This time.

Title: Understanding Arithmetic In C


问:
Best way to indicate more results available
We have a service to return messages. We want to limit the number returned, either allowing the caller to specify the max number to return, or else to use an internal hard limit. We also have thought it would be nice to include in the response whether more messages are available. The "best" way to go about this is not clear.

Here are some ideas so far:

Only set the "more messages" indicator if the user did not specify a max limit, and the internal max limit was hit.

Same as #1 except that "more messages" indicator set regardless of whether the internal hard limit is hit, or the user-specified limit is hit.

Same as #1 (or #2) except that we internally read limit + 1 records, but only return limit records, so we know "for sure" there is at least one additional message rather than "maybe" there are additional messages.

Do away with the "more messages" flag, as it is confusing and unnecessary. Instead force the user to keep calling the API until it returns no messages.

Change "more messages" indicator to something more akin to an EOF indicator, only set when the last message is known to have been retrieved and returned.

What do you think is the best solution? (Doesn't have to be one of the above choices.) I searched and couldn't find a similar question already asked. Hopefully this is not "too subjective".

答:
Usually, it helps to look at how others might have done something similar already, and see if that can be used. This is typically how patterns emerge in software (and some are then even formalized as 'design patterns').

I am most familiar with oData, and in ASP.NET, oData supports both client and server side limit. However, it is up to the servers to decide if they want to set an upper limit even if client specified a response size. For example, if the client asked for a million messages, the server may still choose to limit it to 100 to save the bandwidth costs, and not run into performance issues, etc. So oData implements it the following way:

Client can specify how many records to return via the $top parameter.

Client also specifies how many records to skip via the $skip parameter.

Thus if a client wanted results from 1 to 20, it would set $top=20 and issue the query. For the next page, it would skip the first 20 and thus set $skip=20&$top=20.

The server can also limit the results.

In that case, in the response, it puts a link for the next page, using the odata.nextLink element.

Thus if a client issued a query and did not specify any limit, the server could decide to send 50 rows and then along with the result, send the query for the next page:

```<code>"odata.nextLink":"http://localhost:23645/api/Movies?$skip=50"
</code>```

By setting $skip=50, the next query will start at item 51. The link I provided earlier to MSDN blog has more details.

You could consider utilizing one or both of these approaches, especially if you are returning JSON responses. If you have developers coming to use your service, they might be able to more easily understand (esp. if they have worked with oData). Or you could pick whichever framework is most likely to be known to your developers, and model based on that.

FYI, you don't have to necessarily model both either. However, in this case, it seems quite likely that if you're able to model $top and $skip, then creating the next page link is quite trivial if you choose to limit on the server.

Body:
Usually, it helps to look at how others might have done something similar already, and see if that can be used. This is typically how patterns emerge in software (and some are then even formalized as 'design patterns').

I am most familiar with oData, and in ASP.NET, oData supports both client and server side limit. However, it is up to the servers to decide if they want to set an upper limit even if client specified a response size. For example, if the client asked for a million messages, the server may still choose to limit it to 100 to save the bandwidth costs, and not run into performance issues, etc. So oData implements it the following way:

Client can specify how many records to return via the $top parameter.

Client also specifies how many records to skip via the $skip parameter.

Thus if a client wanted results from 1 to 20, it would set $top=20 and issue the query. For the next page, it would skip the first 20 and thus set $skip=20&$top=20.

The server can also limit the results.

In that case, in the response, it puts a link for the next page, using the odata.nextLink element.

Thus if a client issued a query and did not specify any limit, the server could decide to send 50 rows and then along with the result, send the query for the next page:

"odata.nextLink":"http://localhost:23645/api/Movies?$skip=50"

By setting $skip=50, the next query will start at item 51. The link I provided earlier to MSDN blog has more details.

You could consider utilizing one or both of these approaches, especially if you are returning JSON responses. If you have developers coming to use your service, they might be able to more easily understand (esp. if they have worked with oData). Or you could pick whichever framework is most likely to be known to your developers, and model based on that.

FYI, you don't have to necessarily model both either. However, in this case, it seems quite likely that if you're able to model $top and $skip, then creating the next page link is quite trivial if you choose to limit on the server.


问:
Defining a random "safe" path for a game character
I am writing a game in Java and it can be likened to the recently popular game "Flappy Bird" in the sense that the character moves up and down and the users touch and must avoid the obstacles.

The obstacles are going to be asteroids of varying sizes. I want to spawn these in at a random y co-odinate and with a random size, and then have them move across the screen. The character must then avoid these.

It cant be completely random however as that may result in an non-traversable path. Thus I thought it would be best to define a random safe path first and then fill in the surrounding area with these obstacles. Is this the best approach to solving this problem, and if so is there correct and efficient way of doing this?

答:
This is a common problem in games programming. I know of two approaches, which I think of as Forwards and Backwards.

Forwards means that you generate a game by adding random things (asteroids) using some heuristics, and then you check that it has any solution (within the order of difficulty required). You keep randomly adding and checking until it gets too hard to find another thing to add and still have a solution.

Backwards means that you generate a solution with specific features (difficulty, score, special features, etc). Then you add obsctacle until there is no other solution, but your desired solution is still possible.

I prefer Backwards. Note that most solutions will require hand tuning to get good gameplay, so you need a mixture of random and crafted features.


问:
Infinite loop with a singleton - does this type of issue have a name?
I ran into an unusual error while working on my project. To better learn from and remember it, I'd like to know if this type of error has a name or some definition. (The error itself OutOfMemoryError isn't unusual, I'm talking about what lead to this error).

My (simplified) situation was this:

I had a class Singleton:

```<code>class Singleton extends ClassA{
    private static Singleton instance;

    private Singleton(){ // implicitly calls super() }

    public static Singleton getInstance(){
        if (instance==null) instance = new Singleton();
        return instance;
    }
}
</code>```

And it's superclass ClassA:

```<code>abstract class ClassA{
    public ClassA(){
        ClassB objectB = new ClassB();
        // .. some logic ..
    }
}
</code>```

And a class ClassB that uses Singleton in it's constructor:

```<code>class ClassB{
    public ClassB(){
        Singleton singleton = Singleton.getInstance();
        // .. some logic ..
    }
}
</code>```

What happens is the following:

1- ClassB is instantiated somewhere. It's constructor is invoked and calls Singleton.getInstance().

2- Singleton.getInstance() sees that instance == null and executes instance = new Singleton().

3- The constructor of Singleton is run. It's empty, but it implicitly calls the superclass' (ClassA) constructor.

4- The superclass of Singleton instantiates a ClassB object new ClassB().

5- ClassB's constructor is invoked and calls Singleton.getInstance()...

Since the instantiation of instance in Singleton never reached it's finish, instance == null still returns true, and the cycle never ends.

Resulting in an infinite loop, that finally resulted in an OutOfMemoryError.

So my question is: is this kind of infinite-loop-with-singletons error a common issue? Any ideas how I can avoid it in the future?

答:
It is a simple circular dependency during initialization, independent of the Singleton. There are three classes that instantiate each other in a cycle: A instantiates B, which instantiates C, which in turn instantiates A again, and you have an endless instantiation cycle.

Another thing that needs to be evaluated is why do the objects have a circular dependency on each other regardless of instantiation. That is, even if somehow they were all instantiated, they should not still have a circular dependency since that is often indicative of high coupling and possibly other design issues.

Having said that, it seems that the Singleton is not yet completely implemented, because it does not guarantee singleton across multiple threads. When the locking necessary for a singleton implementation is coded, it will very quickly run into a deadlock.

Usually, these types of errors are found:

At design time by looking at class interactions,

At implementation time by working through the code in the head,

At compile time as some compilers might detect and issue warnings/errors,

At runtime, by getting the kind of exception this code raised.


问:
Where does `this` go in a x64 thiscall?
So I understand that thiscall doesn't really exist in x64 programming. However, I can't really find any definitive explanation as to where the this pointer is put to be passed to the callee.

Is a x64 thiscall like a true cdecl call, where this is put on to the 'stack' last (on both GCC and MSVC compilers)?

EDIT: Running through GDB, it appears so. rdi held the this pointer and rsi held the one parameter that particular method had. Is this how it always works?

答:
As far as I am aware there is no explicit convention for passing a this pointer. Since it is passed into the function as a hidden additional argument, it will be passed using the convention for arguments. Which argument is presumably left to the compiler designer.

There are only two calling conventions in use, effectively Windows and Unix. In each case functions with a small number of arguments (4 or 6) pass all arguments in registers. That still doesn't tell you which has the this pointer.

I'm drawing the distinction between the officially sanctioned calling convention (which says that the first 4 or 6 arguments go in specified registers), and whatever unofficial convention is used for choosing which argument should represent the this pointer. In most cases it will probably be the first argument (which matches your experience), but it may not always be so.

Title: Where does `this` go in a x64 thiscall?


问:
Do you have your own 'misc utils' library? What part are you most proud of?
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
Yes, but only for domain-specific idioms structures (like game-objects-specific containers).

As it's simple utility tools than anything complex, I'm not proud of anything there. I'm the unique user at the moment anyway so there is nothing to be proud of.

ContentLicense: CC BY-SA 2.5


答:
To make things as "future-proof" as possible, plan for change.  That is, try your hardest not to optimize for anything other than the ability to easily change.  So no normalization, no strict validation, and loose coupling galore.

Use major open-source technologies.  For data, closed-source systems are a major source of risk as one can't plan on which companies will go under or change strategies, taking with it all access to the data.  Also, minor open-source projects without a vibrant community are also more likely to lose support.

Use a schema-less NoSQL database.  The sorts of unstructured data being used is almost straight out of the textbook for a document store like MongoDB.  Traditional relational databases and their normalization is good when you know how your data is going to be structured, but that's really a fiction, especially here.  The costs of changing schema in a RDBS just get larger and larger as the system expands.  Know that whatever structure is chosen now is going to end up changing.

Decouple the system heavily using widely accepted standards.  Breaking up all data access and mutation into web services is one step towards this.  Combining that with message queues for submitting changes and such will help individual parts of the system change languages or technologies over time.


问:
Transitioning from Java & C to C++
I learned Java and I'm pretty competent programming in it. I also learned C recently.

I looked at a comparison between Java and C++ and I like C++'s features like operator overloading and its speed.

So, C++ is an OOP language, but it also has all the things java doesn't have and C does, like pointers and memory allocation. Do I need to change something in my OOP design to consider pointers and memory allocation? If so, what do I need to change? If not, why not?

答: No, you don't need to change anything in your design if your design was well thought out from the start. OOD should be language agnostic, that means you should be able to pick any OO language and implement it. </p>

Title: Transitioning from Java & C to C++


答:
In terms of OO design, you don't have to change all that much when going from Java to C++. The majority of the design principles is actually language independent and applicable to both Java and C++.

How you express your design in code can differ quite a bit between languages. The most important thing to remember is C++ does not have automatic garbage collection. That and the fact that any C++ object can be created without using new are the two driving factors behind the differences in expressing your design in C++ or Java code.

In particular, it is very common in C++ to express composition by directly having a member of type X in class Y without involving a pointer.

More in general, if you can avoid dynamic memory allocation in C++, do so. If you can't, see if there is a smart pointer available that can ensure the memory is released again at the right moment.

Title: Transitioning from Java & C to C++

Body:
I learned Java and I'm pretty competent programming in it. I also learned C recently.

I looked at a comparison between Java and C++ and I like C++'s features like operator overloading and its speed.

So, C++ is an OOP language, but it also has all the things java doesn't have and C does, like pointers and memory allocation. Do I need to change something in my OOP design to consider pointers and memory allocation? If so, what do I need to change? If not, why not?


问:
Licensing code from my personal project to my company via an open-source license
I'm currently working on a certain problem for my company (i.e. where I work for hire and don't own the code I produce in any way). It appears, that in one of my past (or, who knows, maybe still present) personal projects there are a few useful source code files that should help with the problem I'm working on. Neither that personal project nor the company project are open source, and they are not going to become so in foreseeable future.

I would like to import that (small) part of my personal project into the company's source tree. But since I'm not yet calling my project RIP, I'd like to give them the code in the way that I retain my copyright over the code. And, of course, they would need to have the copyright over the code as well - luring them into a trap is definitely not my intention. In that regard I would like to give them any right I can - to modify, run, distribute, use in other projects etc., but not to deprive me of the same rights. And I don't care if that (again, small) part of my project becomes publicly available eventually.

The solution I currently have for this is:

Put the copyright information along with the license into every source code file I'm about to import.

Commit this to my Git repository (hosted privately).

Import the specific files and commit them their repository (hosted as GitHub private repository).

The licensing text I'm using is based on MIT license, but slightly modified (I added the third paragraph), here it is:

```<code># Copyright (c) 2013 Real Developer Name
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# The above exclusively applies to files containing this copyright notice, and
# does not apply for the rest of the software package containing these files.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
</code>```

So, the questions are:

Most importantly, will this measure protect both parties from the possible legal issues?

Is the fragment I added (the third paragraph) necessary and/or useful? Can it be improved?

Is it a generally good idea to give your own code to your company to speed up development (assuming that my and their projects will never ever compete)?

答:
As a copyright holder, you have the right to distribute copies of (part of) your personal project to different people using different licenses. So, there is no need to open source part of your personal project just to be able to include it in the work you currently make for your employer.

The alternative option is to tell your boss that you have some code from a personal project that would fit well here and then sit together with your company's lawyer/legal department to draft a non-exclusive license for them to use the code.

If you don't make any silly demands, this should be a straightforward process and you won't have to deal with any fears that might exist regarding the use of open source software.

Regarding your concrete questions:

This copyright license is as good as it gets to protect both of you from copyright infringement claims. It doesn't protect either of you from other legal issues such as patent claims.

The fragment you added is stating the obvious and is not necessary. By default, a copyright license only applies to those files that claim to be governed by that license.

Whether it is a good idea to share your code with your company is a matter of opinion. It can be argued either way and the final decision should be based on what you feel comfortable with yourself.


问:
MVC Best practices (view acquiring data directly from model) and Yii Framework
I'm using Yii for a few years and only right now I realized, that their demo application (empowered by CRUD auto-generation tool -- Gii) seems to be breaking key MVC architecture pattern. I'd like to discuss this here.

As long as I've been using MVC (about four years), I was always told, that view should not acquire data directly from model. Every piece of text about MVC, I've read so far, was always underlining, that both view and models should be completely separate and the controller is the only element, that spins them together. If I need any model data in view (most often used mechanism) I should let my controller to retrieve it and feed view with it.

Correct me, if I'm wrong, but finding this question and an answer to it makes me sure, that I'm right: while it is technically possible, it should be avoided.

So, in terms of Yii, that would be:

```<code>$probes = Probes::model()->getAllProbesForCurrentUser;

$this->render('index', array
(
    'probes'=>$probes
))
</code>```

(quite obvious, I think -- controller retrieves data from model and renders view, feeding it with that model)

If all above is right, then how should I explain this:

```<code><?php $this->widget('CGridView', array
(
    'id'=>'users-grid',
    'dataProvider'=>$model->search(),
    'columns'=>array
    (
        'name',
        'email',
        'level'
    )
)); ?>
</code>```

(a widget placed in view acquires data directly from model)

What am I missing?

答: The array can also called a ViewModel, it is different from the Model because it carries the data the view needs while the Model represent the application business entities. For simple CRUD form they are likely to be identical. But for complex form, a ViewModel can be combined from many models.</p>


答: As Bart van Ingen Schenau points out, C++ doesn't have garbage collection. That means for the most part you must restrict your designs to ones where every object has a single unambiguous owner that disposes of it when the owner goes out of scope. Anything more complicated runs the risk of a memory leak.</p>

Title: Transitioning from Java & C to C++


答: This question is based on a completely wrong assumption. Of course, $model variable, used in widget, is retrieved by a controller and fed to view in as natural way as it can be in MVC world.

Title: MVC Best practices (view acquiring data directly from model) and Yii Framework

Body:
I'm using Yii for a few years and only right now I realized, that their demo application (empowered by CRUD auto-generation tool -- Gii) seems to be breaking key MVC architecture pattern. I'd like to discuss this here.

As long as I've been using MVC (about four years), I was always told, that view should not acquire data directly from model. Every piece of text about MVC, I've read so far, was always underlining, that both view and models should be completely separate and the controller is the only element, that spins them together. If I need any model data in view (most often used mechanism) I should let my controller to retrieve it and feed view with it.

Correct me, if I'm wrong, but finding this question and an answer to it makes me sure, that I'm right: while it is technically possible, it should be avoided.

So, in terms of Yii, that would be:

```<code>$probes = Probes::model()->getAllProbesForCurrentUser;

$this->render('index', array
(
    'probes'=>$probes
))
</code>```

(quite obvious, I think -- controller retrieves data from model and renders view, feeding it with that model)

If all above is right, then how should I explain this:

```<code><?php $this->widget('CGridView', array
(
    'id'=>'users-grid',
    'dataProvider'=>$model->search(),
    'columns'=>array
    (
        'name',
        'email',
        'level'
    )
)); ?>
</code>```

(a widget placed in view acquires data directly from model)

What am I missing?


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
If hundred-million dollar projects can fail even with experienced people, you shouldn't worry about you failing as you are still a student.
I've had a problem to work on and I found that if it is something you get stuck on - you must record every attempt you made to solve it.

That helps:

Proof of attempts done to solve a problem.

Recording this type of failure is important so you learn from it and don't do it again a few days later thinking it will work.

OwnerDisplayName: dimitarie


问:
How can I use guice to replace code dependent on service locator implementation?
Consider I have a service called FileSystem, and that this FileSystem is used by various classes throughout the application. Typically, the service is acquired via some static class method ServiceLocator.getService(FileSystem.class)

Now consider I have a class Game, that depends on the FileSystem object to open up some UI resources. The game will also construct a world, using a WorldFactory. The WorldFactory also requires the FileSystem service.

Here is where I encounter the problem, I construct a new instance of WorldFactory - which requires an instance of FileSystem to be injected into it. However, Guice will not inject into objects it has not constructed. So WorldFactory is left without a FileSystem injected into it.

So I could pass a FileSystem object to the WorldFactory but then in essence Guice hasn't solved any of my problems and I have come to realize I haven't been using Guice correctly because I can do all of this without it?

So then you get an odd instance where the constructor of a game entity requires that you pass an instance to the AudioSystem to it which it can play audio through. It just gets very messy with all these objects/services being explicitly passed around.

Thanks. I'm still new to guice and trying to figure out how to use it.

答:
Both Game and WorldFactory class would have FileSystem as their dependencies. Below is an example of dependency injected through a constructor (it is also possible to inject them directly into fields):

```<code>@Inject
public Game(FileSystem fs) { }

@Inject
public WorldFactory(FileSystem fs) { }
</code>```

You could then write a provider inside one of your modules that would construct and return a new FileSystem instance:

```<code>@Provides
FileSystem provideFileSystem() {
    return ServiceLocator.getService(FileSystem.class);
}
</code>```

Once you treated other services similarly, you will be able to completely remove your reliance on ServiceLocator, moving the service-creating code directly into providers.

So then you get an odd instance where the constructor of a game entity requires that you pass an instance to the AudioSystem to it which it can play audio through. It just gets very messy with all these objects/services being explicitly passed around.

Not only this is not messy, this is the whole point of dependency injection. The thing is, however, that you should never explicitly pass all those instances manually. Instead, you can have Guice reconstruct the dependency graph from them and construct all necessary, intermediate objects (or obtain them in any other way you specify in your providers). On your side, creating the final object is just a matter of calling Injector.getInstance(Foo.class) -- it's up to Guice to figure out how to satisify the dependencies.

Body:
Both Game and WorldFactory class would have FileSystem as their dependencies. Below is an example of dependency injected through a constructor (it is also possible to inject them directly into fields):

@Inject
public Game(FileSystem fs) { }

@Inject
public WorldFactory(FileSystem fs) { }

You could then write a provider inside one of your modules that would construct and return a new FileSystem instance:

@Provides
FileSystem provideFileSystem() {
    return ServiceLocator.getService(FileSystem.class);
}

Once you treated other services similarly, you will be able to completely remove your reliance on ServiceLocator, moving the service-creating code directly into providers.

So then you get an odd instance where the constructor of a game entity requires that you pass an instance to the AudioSystem to it which it can play audio through. It just gets very messy with all these objects/services being explicitly passed around.

Not only this is not messy, this is the whole point of dependency injection. The thing is, however, that you should never explicitly pass all those instances manually. Instead, you can have Guice reconstruct the dependency graph from them and construct all necessary, intermediate objects (or obtain them in any other way you specify in your providers). On your side, creating the final object is just a matter of calling Injector.getInstance(Foo.class) -- it's up to Guice to figure out how to satisify the dependencies.


问:
When deciding a Primary Key, can I use Date part of a DateTime field
I'm designing a payroll system I have designed a database with several tables and this question is related to following tables

EMPLOYEE (Employee_ID [pk], Name,... etc)
LOCATION (Location_ID [pk], Name, Address, ...etc)

These two tables have many to many relationship as one employee can work in several locations and in a location, several employees are working.

These two tables are related through ATTENDANCE table.

ATTENDANCE (Employee_ID, Location_ID, Shift_Type, In, Out)

Shift type would be either "Day" or "Night" and "In" / "Out" fields are DateTime fields. The shift type is decided based on the date in the field "In" . For example if an employee's In field is lets say -06/22/2014 07:30:00 PM then the shift type is Night and shift is belongs to 22/06/2014. (his Out time would be 23/06/2014 07:30AM; that is on next day)

THE CONDITION is that, an Employee can't work same shift on same date twice even in two locations. But an employee can work Day in a location and Night in another location.

My initial primary key selection ATTENDANCE table was (Employee_ID + In) but that is wrong as an employee can work same shift in same day if the In time is slightly different in two occasions.

So now I know the primary key should be some thing like (Employee_ID + Shift_Type + Shift_Date). But the problem is I don't have a Date field in the ATTENDANCE table. But I have In field which is a DateTime field.

Hopping that my understanding about the issue is correct...,

My question is, with out adding another field to ATTENDANCE table as Shift_Date, is there a possibility to get the Date part of the field In, when creating a PRIMARY KEY for this table ?

答:
You can use a date field as a primary key, but you can't key on PART of a field. You'd have to make a separate field with just the date.

This particular condition isn't something that would normally be enforced by building it into the primary key of a table anyway. Your "Employee can't work same shift on same date twice even in two locations" is a business rule, something that isn't necessarily going to be the same forever. (Goodness knows, there are entirely too many places out there that make their employees do split shifts...) A more typical way to handle this would be to just generate an auto-increment field for the primary key, and then enforce your business rules somewhere closer to the user interface.


问:
Full Text Indexing Strategy for MS Excel Documents

Background

As part of a broader application that allows users to search thousands of MS Office documents on a private network, I need to index and make searchable Microsoft Excel files.

My basic approach for all document types is this:

Loop through the raw directories I have been given,

Upload the document to a network share

Extract some searchable text from content of the document.

Create a new MS SQL record with the name of the document, URL of it's location, and searchable content.

Use MS SQL's Full Text indexing on the "content" column so that end-users can search key words or phrases via a user interface.

Problem/Question

I am not sure of the most optimum approach for extracting searchable text from Excel docs.  My initial thought is to loop through the doc: cell-by-cell and pull out all text and then concatenate that text together into the SQL record, but that seems to be a bad strategy as there could be several cells that are exact duplicates, cells that are only numeric, and generally other types of noise.

Is there an established design pattern or strategy for case?  Absent that, I welcome and appreciate any suggestions (as will future Stack Exchange users facing the same problem).

答: Excel files use a string table which "folds together" duplicate entries; if you're willing to do the work, learning the file format and getting to that string table would run much more quickly than launching Excel and etc etc etc. This strategy would have one flaw: it would NOT index strings that were the result of formulas, because those aren't in the table.</p>


问:
Real-time stock market application
I'm an amateur programmer. I'd like to develop a software application (like Tradestation), to analyse real-time market data. Please teach me if the following approach is correct, ie the procedures, knowledge or software needed etc:

Use a DB to read the real-time feed from data provider: what should be the right DB to use? I know it should be a time serious one. Can I use SQL, Mysql, or others? What database can receive real-time data feed? Do I need to configure the DB to do this?

If the real-time data is in ASCII form, how can it be converted to those that can be read by the DB and my application? Should I have to write codes or just use some add-ins? What kind of add-in are needed?

How should I code the program to retrieve the changing data from the DB so that the analysis software screen data can also change asynchronously? (like the RTD in excel)

Which aspects of programming do I need to learn to develop the above?

Are there web resources/ books I can refer to for more information?

答:
I am also working on a similar project to learn the basics of programming.  To answer your question.

You can use mySQL to store certain trading patterns or interesting observation.  There is no point to store data that you don't need.  Again, real live data are super expensive.  Your best bet is to data scrap off yahoo and there are posts stackoverflow that shows you how to do it.  You can look up one of my question and someone showed me how to do it in PYTHON.

My data are in Unicode and parsing it to float is possible.  Ask a more detailed question for that.

Regarding how to deal with the dynamically changing data, it all depends on your trading method.  For example, when I was a professional day trader, I wrote a simple program that just gives me an alert when I see a current bid price is higher than the current ask price.  Another simple strategy can involve a trending stock crossing the high or the low.  You can set variables that save as: open, high, low, moving average, %retracement...

Title: Real-time stock market application


问:
How can Swift be so much faster than Objective-C in these comparisons?
Apple launched its new programming language Swift at WWDC14. In the presentation, they made some performance comparisons between Objective-C and Python. The following is a picture of one of their slides, of a comparison of those three languages performing some complex object sort:

There was an even more incredible graph about a performance comparison using the RC4 encryption algorithm.

Obviously this is a marketing talk, and they didn't go into detail on how this was implemented in each. I leaves me wondering though:

How can a new programming language be so much faster?

Are the Objective-C results caused by a bad compiler or is there something less efficient in Objective-C than Swift?

How would you explain a 40% performance increase? I understand that garbage collection/automated reference control might produce some additional overhead, but this much?

答:
Objective-C dynamically dispatches every method call.

Hypothesis: The benchmark uses static typing to let the Swift compiler hoist the compare method lookup out of the sort loop. This requires a narrow type restriction that only allows Complex objects in the array, not subclasses of Complex.

(In Objective-C you could hoist the method lookup manually if you really want to, by calling on the language runtime support to look up the method pointer. You'd better be sure that all instances in the array are of the very same class.)

Hypothesis: Swift optimizes reference-counting calls out of the loop.

Hypothesis: The Swift benchmark uses a Complex struct in place of an Objective-C object, so sort comparisons don't need dynamic method dispatches (since it can't be subclassed) or reference-counting work (since it's a value type).

(In Objective-C you can fall back to C/C++ for performance as long as it doesn't involve Objective-C objects, e.g. sort a C array of structs.)


问:
Is the Java Integer cache a realization of the object pool pattern?
One of the best-known examples of a full-fledged object pool is the JDBC connection pool. Main reasons:

objects in the pool are expensive to create and relate with external resources

each object in the pool is served to at most one client a time

objects in the pool need to be brought back to a clean state before being served again to a new client

With the above in mind, can the Java Integer cache be regarded as a object pool realization? Here is why I doubt it:

objects in the pool can be used by more than one client a time due to their immutability

immutability also prevents pool objects from reaching a stale state

there's no notion of a "free" object, ready to be allocated to a client

答: It is really the flyweight pattern which is a specialized sort of object pool, where objects get shared to save memory.


问:
Retrying a statement or call in a catch block - code smell or anti-pattern?
I'm wondering how better to perform this operation for a large amount of files. The bit I'd like some thoughts on whether this copy/paste is acceptable enough of a tradeoff.

try to write a file

if the target dir doesn't exist, create it

try again to write the file. If something else throws and exception, let it raise.

```<code>try{
   File.Copy("@D:\foo.txt", @"C:\mydir\foo.txt");
}
catch (DirectoryNotFoundException){
   CreateDirectoryForFile(@"C:\mydir");
   File.Copy("@D:\foo.txt", @"C:\mydir\foo.txt"); //copy pasted from the try block
}
</code>```

There's a simpler block that's easier to read, but leads to a higher number of disk IO calls that is necessary:

```<code>CreateDirectoryForFile(@"C:\mydir\foo.txt");
File.Copy("@D:\foo.txt", @"C:\mydir\foo.txt");
</code>```

Can pattern 1 be improved?

答:
This is a violation of DRY. I really would avoid it. Sooner or later something will change and it will bite you.

You could

Refactor the relevant code as a function

Break out the strings as constants

Write a loop that can only allows one retry.

Anything to avoid cut and paste.


答:
The simple principle is that this is not an Exception per se, it is an expected condition and thus should be checked using if (Directory.Exists(...)) to see if destination directory does not exist (and likewise if (File.Exists(...)) to check if the file already exists in that directory if that is important for your scenario).

You are paying a high performance price for this because exceptions are more costly. As an example, see that when you try to get an item from a Dictionary using an indexer, it throws a KeyNotFoundException if the item did not exist. To avoid having getting and catching this exception, usually people would first check the existence of the item using the Contains method and fetch it only if it existed. So, the Dictionary class thus provided a TryGetValue which will try to fetch the item, but if the item does not exist in the Dictionary, it just returns a false indicating so.

As DeadMG pointed out in the comments, there might be cases where concurrency works out better when you do not check and just perform the operation. An example could be that if your code was only creating the directory, it might be better to just use Directory.Create instead of first checking for existence because the file system state might change between the check and the actual operation.

A coding guideline that I use is that if a method allows one to check for a condition for which an exception may be thrown, consider using that method first, and only rely on exception if there is a strong reason not to check first. There are valid cases, especially over the network where if you checked for the existence of a file and then deleted it, it might incur high latency or bandwidth costs, in which case it might be preferable to just attempt an action and catch an exception. Azure Storage APIs, for example, use such an approach.

Avoid exceptions when a condition is one of the valid possibilities and there is no good reason to prefer exceptions. In your case, it is normal for the directory to not exist, and not an error condition, and you are dealing on the local disk.

EDIT: Updated after DeadMG's comment, my initial response was only focused on the code in the question.

Title: Retrying a statement or call in a catch block - code smell or anti-pattern?

Body:
I'm wondering how better to perform this operation for a large amount of files. The bit I'd like some thoughts on whether this copy/paste is acceptable enough of a tradeoff.

try to write a file

if the target dir doesn't exist, create it

try again to write the file. If something else throws and exception, let it raise.

```<code>try{
   File.Copy("@D:\foo.txt", @"C:\mydir\foo.txt");
}
catch (DirectoryNotFoundException){
   CreateDirectoryForFile(@"C:\mydir");
   File.Copy("@D:\foo.txt", @"C:\mydir\foo.txt"); //copy pasted from the try block
}
</code>```

There's a simpler block that's easier to read, but leads to a higher number of disk IO calls that is necessary:

```<code>CreateDirectoryForFile(@"C:\mydir\foo.txt");
File.Copy("@D:\foo.txt", @"C:\mydir\foo.txt");
</code>```

Can pattern 1 be improved?


答:
The problem with a Java Integer cache is that the VM is optimized for boxing/unboxing.  The lookup mechanism for a "cached" Java Integer is going to be more expensive than just creating the object.

```<code>building cache
test length 500,000,000
cached duration: 12001.345937
boxed duration: 12108.983383
</code>```

In many scenarios the lookup using many threads is going to cause lots of cache misses across different cores and have more of a performance hit.

```<code>System.out.println("building cache");

Integer[] cache = new Integer[50000];

for( int i = 0; i < cache.length; i ++)
{
    cache[i] = new Integer(i);
}

int c = 500 * 1000000;
int t = 0;

System.out.println("test length " + c );

NanoStopWatch watch = new NanoStopWatch();

watch.start();

while( t < c)
{
    Integer p = cache[ (int)  (Math.random() * 5000) ];

    t++;
}

watch.stop();

System.out.println("cached duration: " + watch.duration() );

t = 0;

watch.start();

while( t < c)
{
    Integer p =  (Integer) (int) (Math.random() * 5000);

    t++;
}

watch.stop();

System.out.println("boxed duration: " + watch.duration() );
</code>```

Title: Is the Java Integer cache a realization of the object pool pattern?

Body:
One of the best-known examples of a full-fledged object pool is the JDBC connection pool. Main reasons:

objects in the pool are expensive to create and relate with external resources

each object in the pool is served to at most one client a time

objects in the pool need to be brought back to a clean state before being served again to a new client

With the above in mind, can the Java Integer cache be regarded as a object pool realization? Here is why I doubt it:

objects in the pool can be used by more than one client a time due to their immutability

immutability also prevents pool objects from reaching a stale state

there's no notion of a "free" object, ready to be allocated to a client

Body:
The problem with a Java Integer cache is that the VM is optimized for boxing/unboxing.  The lookup mechanism for a "cached" Java Integer is going to be more expensive than just creating the object.

building cache
test length 500,000,000
cached duration: 12001.345937
boxed duration: 12108.983383

In many scenarios the lookup using many threads is going to cause lots of cache misses across different cores and have more of a performance hit.

System.out.println("building cache");

Integer[] cache = new Integer[50000];

for( int i = 0; i < cache.length; i ++)
{
    cache[i] = new Integer(i);
}

int c = 500 * 1000000;
int t = 0;

System.out.println("test length " + c );

NanoStopWatch watch = new NanoStopWatch();

watch.start();

while( t < c)
{
    Integer p = cache[ (int)  (Math.random() * 5000) ];

    t++;
}

watch.stop();

System.out.println("cached duration: " + watch.duration() );

t = 0;

watch.start();

while( t < c)
{
    Integer p =  (Integer) (int) (Math.random() * 5000);

    t++;
}

watch.stop();

System.out.println("boxed duration: " + watch.duration() );


问:
Difference between DevOps and Software Configuration Management
What is the difference between Development Operations and Software Configuration Management?

For me it seems to be the same as long as both DevOps and Software Configuration Management are focused on:

Establishing development infrastructure - being in charge of version control, build management, deployment management, dependencies management, continuous integration and delivery, etc.

Using best practices for organizing developers environment.

Quality Assurance of development processes - gathering metrics of development effectiveness, working on eliminating bottlenecks of development process (running unit-tests, evaluating unit-tests coverage, running inspections, etc)

Infrastructure management - target platforms and its specifics.

Release management - making sure release has been delivered to customer/client in time.

Maybe I'm missing something? This link shows that usage of term 'Software Configuration Management' prevails. But still, what word combination would you rather use to describe listed range of activities: Development Operations or Software Configuration Management?

答: I see DEVOPs is at the operational execution end - deployment automation scripts,  environment buildouts,  that sort of thing.  SCM on the other hand,  is about the products integrity and the effective management and traceability of changes to the products.  I have always viewed ALM as being a part of SCM - after all,  how on earth can you manage changes to a a product if you have no idea of the drivers for the change or who made them?  Deployment frameworks could fall either side - and which side will invariably depend on the regulatory needs of the organization you work for - after all - do you want a developer to be able to do a quick hack that means your dialysis machine only works properly 99.99% of the time,  or do you need that situation to allow you to hack your website code because your developers have hardcoded IP addresses?</p>


问:
In an enterprise setting, does one apply BDD principles alongside of, or instead of, "traditional" unit testing?
I have a problem visualising how the gap is closed between coarse-grained, n-tier boundary, high level, automated acceptance testing and lower level, task/sub-task scope Unit Testing.

My motivation is to be able to take any unit test in my system and be able to follow backwards, through coverage, which scenario(s) make use of that unit test.

I am familiar with the ideas of BDD: An extension of TDD and writing scenarios at the high level solution design level in the Gerkin format, and driving these scenarios using tools such as JBehave and Cucumber.

Equally, I am familiar with the humble unit test at the utility or task level, and using xUnit to test through the various paths of the function.

Where I begin to come unstuck, then, is when I try to imagine these two disciplines applied together in an enterprise setting.

Perhaps I am going wrong because you tend to use one approach or the other?

In an attempt to articulate my thoughts so far, let's assert that I am right to believe that both are used.

In an agile world, user stories are broken down into tasks and sub-tasks, and in an enterprise setting, where the problems are large and the number of developers per story are many, those tasks and sub-tasks are distributed amongst a team of people with specialist problem solving skills.

Some developers, for example, may specialise in mid-tier Development, develop a controller layer and continue to work downwards. Others may specialise in UI development and work from a controller layer upwards.

Developers may therefore share implementation of a single string of tasks which, when glued back together again, will implement the story.

In this case, it seems to me that cycles of TDD at the task and sub-task level is still necessary, to ensure that the efforts of these developers collaborate correctly within one layer and from one layer to the next (mocking collaborators).

Working in this way implies a certain amount of high level solution design up-front, so contracts between layers are agreed and respected. Perhaps this is articulated as a sequence diagram and perhaps this emerges during the task breakdown session for the story.

Yet, on the other hand, we have the value of defining the BDD acceptance tests at a higher level to configure that all of the blocks work together as expected - a form of super Integration Test, I suppose.

I suppose the answer I am looking for here, aside of the simpler yes/no to the question of "both", is an explanation/worked example of how I and a team of developers start out with a single n-tier scenario and end up with an implementation in an enterprise setting, where we've been able to break the tasks up into layers and share them amongst ourselves and work in parallel to turn the BDD scenario test from red to green, all the while ensuring that the the code we write is only written because the scenario calls for it, and at a fine grained level the code we have written is appropriately unit tested following cycles of TDD at the task and sub-task level as we go.

If, of course that is correct?

答:
I think that there is a common misconception as to what BDD means, that BDD means that we are now writing our tests using tools like Cucumber, SpecFlow, etc instead of traditional unit tests.

That is not the case. BDD is more a way of thinking that moves our focus in the tests from the technical aspects to the more business oriented aspects. Also see this P.SE answer: https://softwareengineering.stackexchange.com/a/135246

A few tools were born out of the BDD world, e.g. Cucumber and RSpec.

Cucumber is not intended as a testing tool - it is intended as a collaboration tool. It allows programmers to collaborate with the business in order to write business specifications.

But you shouldn't use Cucumber because you are in an enterprise setting. You should use Cucumber because you can get customer involved in the software development process. If you do not have the customer strongly involved, you should think twice before using a tool like Cucumber.

Also read this blog post from Aslak Hellesøy (creator of Cucumber): https://cucumber.pro/blog/2014/03/03/the-worlds-most-misunderstood-collaboration-tool.html

RSpec on the other hand is a unit test tool. But with a strong focus on describing the requirements for your code, e.g. by using strings as your test case names, instead of function names. For example

```<code>describe "Login application service" do
  context "user has given 3 incorrect passwords already" do
    it "rejects the user when a correct password attempt is made" do
            ...
    end
  end
end
</code>```

This is a test for a specific component in the system, but the focus of the tests are the business requirements that that particular component helps fulfill.

If you use these two types of tool together, you get a process like this:

Just picked from a random image search for "BDD Cycle". You can exchange SpecFlow with Cucumber, JBehave, TickSpec, or whatever. And you can replace MSpec with RSpec, or even traditional xUnit type frameworks.

If you are under operating in a regulated industry, e.g. medical, or finance, you get the benefit that your software is both validated and verified if you use both.

Collaboration tools helps to make sure that your software fulfill business requirements, because the business collaborated in writing them*. Therefore your software has been validated.

Unit test make sure that each component works correctly, Therefore your software has been verified.

So in your case I would suggest: Continue to write unit tests. Strive to focus on business requirements rather that implementation details. If, and only if, you can get the customer involved, write acceptance tests in a cucumber style.

* This requires that the specification actually describes business process, and not user interfaces, a mistake that many people new to cucumber makes. Also see this site for more: http://www.elabs.se/blog/15-you-re-cuking-it-wrong

Body:
I think that there is a common misconception as to what BDD means, that BDD means that we are now writing our tests using tools like Cucumber, SpecFlow, etc instead of traditional unit tests.

That is not the case. BDD is more a way of thinking that moves our focus in the tests from the technical aspects to the more business oriented aspects. Also see this P.SE answer: https://softwareengineering.stackexchange.com/a/135246

A few tools were born out of the BDD world, e.g. Cucumber and RSpec.

Cucumber is not intended as a testing tool - it is intended as a collaboration tool. It allows programmers to collaborate with the business in order to write business specifications.

But you shouldn't use Cucumber because you are in an enterprise setting. You should use Cucumber because you can get customer involved in the software development process. If you do not have the customer strongly involved, you should think twice before using a tool like Cucumber.

Also read this blog post from Aslak Hellesøy (creator of Cucumber): https://cucumber.pro/blog/2014/03/03/the-worlds-most-misunderstood-collaboration-tool.html

RSpec on the other hand is a unit test tool. But with a strong focus on describing the requirements for your code, e.g. by using strings as your test case names, instead of function names. For example

describe "Login application service" do
  context "user has given 3 incorrect passwords already" do
    it "rejects the user when a correct password attempt is made" do
            ...
    end
  end
end

This is a test for a specific component in the system, but the focus of the tests are the business requirements that that particular component helps fulfill.

If you use these two types of tool together, you get a process like this:

Just picked from a random image search for "BDD Cycle". You can exchange SpecFlow with Cucumber, JBehave, TickSpec, or whatever. And you can replace MSpec with RSpec, or even traditional xUnit type frameworks.

If you are under operating in a regulated industry, e.g. medical, or finance, you get the benefit that your software is both validated and verified if you use both.

Collaboration tools helps to make sure that your software fulfill business requirements, because the business collaborated in writing them*. Therefore your software has been validated.

Unit test make sure that each component works correctly, Therefore your software has been verified.

So in your case I would suggest: Continue to write unit tests. Strive to focus on business requirements rather that implementation details. If, and only if, you can get the customer involved, write acceptance tests in a cucumber style.

* This requires that the specification actually describes business process, and not user interfaces, a mistake that many people new to cucumber makes. Also see this site for more: http://www.elabs.se/blog/15-you-re-cuking-it-wrong


答:
It depends on the reason why you are unable...

logically impossible: Discuss it with the one who wrote the requirements, maybe there is a misunderstanding. Example: at one point, the spec says that the application must look and feel native on all platforms (Windows/Linux/Mac), and in another place, it says that the program must look exactly identical on all platforms

technically impossible: Reevaluate the tools you are working with, maybe they are not appropriate. Discuss the problem with your peers and the project manager. Example: hard realtime requirements in an environment where garbage collection can stop the execution for an indeterminate time

insufficient performance: Maybe you are using the wrong algorithm, or maybe the problem is too hard (e.g. NP-hard) and the requirements doesn't take that into account. Reevaluate the algorithm you are using, maybe there is a faster way. Discuss the problem with your peers and the project manager. Consider switching to a good-enough heuristic instead of a perfect result. Example: path optimization with dozens or even hundreds of nodes

you just don't know how to do it: Ask your peers, ask stackoverflow, search the internet. Contact the support of the tool/lib you are using. Discuss it with the project manager.

it should work, but doesn't, and you have no clue why: Refactor the program to make it more testable. Consider race conditions, they are often the reason for hard-to-find bugs. Ask peers for help, four eyes see more than two. Check the internet for known bugs in the tools/libs you are using.

Title: What happens if you're unable to solve a problem?

Body:
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?