问:
How can I transition to a job using the Microsoft stack?
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?

答:
Since you are really only just starting out in your career, it may not be as hard as you think to get a job using the MS technology stack with very little experience.  You just have to be willing to shoot for the junior jobs.

I've hired a lot of people, and I have different expectations of their experience based on the position I'm trying to fill.  If I'm looking at a senior or architect level role, I'd expect to see a fair amount of experience.  But not all of it has to be in the exact technology or skill set I'm looking for.  If I want someone with C# experience but they have 5 of Java and 3 of C++, I know they aren't going to have much difficulty picking up a new language.  By the way, as you get further into your career, you will quickly realize that learning a new language often isn't a big deal.  Learning all the libraries and idioms of the language is what takes time.

When I'm looking at a junior position, I give a lot less weight to their experience.  I really want to figure out of they have the capability to learn.  Getting your CS (or whatever) degree is a good step in that direction, because it shows that you were able to learn something.  If you have work experience in the CS field, great.  Someone thought you were smart enough to hire.  I'm going to throw some programming questions at you (maybe on paper, maybe on a whiteboard) and ask you to solve them in your favorite language.  Yes, in the language of your choice.  What I'm trying to see is if you can work your way through a problem, and I'll be able to follow enough your whatever language you pick to see whether you got the answer right or not.

Obviously if you know something about the technology the job will require, all the better.  Spend your off hours boning up on the subjects so you will at least be able to recognize the important keywords they might throw at you.

To give you some more hope, I hired a guy who had some C experience but not a lot.  It was for a junior C job.  The guy was obviously smart, well spoken, and could reason through the problem.  Unfortunately, he was still a bit weak on the C side.  We said, "tell you what, work on your C, come back in a couple of weeks, and we'll try this again."  He did, we asked him different questions (obviously), and he was definitely better.  Not knock it out of the park better, but a definite improvement.  We decided to hire him, and didn't regret it.  He worked hard, and when he wasn't sure, he asked questions.

So the upshot of this long winded ramble is, if you want to change what you are working on, go for it.  Especially this early in your career.  Shoot for the jobs and see what happens.  If you can, get some feedback on where you did well, and not so well.  In the end, it will be worth it.


问:
My coworker commits and pushes without testing
When my coworker thinks that there is no need for a test on his PC, he makes changes, commits and then pushes. Then he tests on the production server and realizes that he made a mistake. It happens once in a week. Now I see that he made 3 commits and and pushes with deployment to the production server within 5 minutes.

I told him few times that this is not the way how good work is done. I don't want to be rude to him again and he is in the same status with me in the company and he has worked more than me here.

I want this behavior to be punished in some way or make it unpleasant as much as possible.

Before I started, the company was deploying using antique methods, such as FTP, and there was no version control.

I forced them/us to use Git, Bitbucket, Dploy.io, and HipChat. The deployment is not automatic, someone has to login to dply.io and press the deploy button.

Now, how can I force them to not test on the production server? Something like HipChat bot can sense that there is repeated edits on the same line and send a notice to the programmer.

答:
This is not uncommon, particularly in small teams.  Don't make a big deal about it, but make an informal rule:

Break the build, bring in donuts.

Either 1) You'll get donuts twice a week or 2) they will adhere to the standard.

Bring it up in a meeting.  Not accusingly, don't mention anyone by name, but something similar to, "Since we introduced version control and deployment standards, things have become much easier and the server is up more of the time than it used to be.  This is great!  However it's still tempting to take a shortcut and submit without proper testing.  It's a gamble, though, and our server is on the line. I suggest that from now on if any of us submits code that breaks the server, the person responsible brings in donuts for the team the next day."

Substitute something else for donuts if desired, and don't make it expensive - lunch for the entire team would be too much, but a $5 box of donuts or fruit/veggie tray, or chips and dip, etc, etc would probably be annoying enough to make them actually weigh the risk against the convenience of skipping testing without making it a burden that would push them away from the team or company.

ContentLicense: CC BY-SA 3.0


问:
Are there concrete reasons not to use libraries and code snippets heavily?
Overall I'm in programming for about 8 years now and it seems to me that I'm relying more and more on open source libraries and snippets (damn you GitHub!) to "get the job done". I know that in time I could write me own implementation but I like to focus on the overall design.

Is this normal (non corporate environment)? What could go wrong if my "programming" is nothing more than gluing different libraries together?

I know about "don't reinvent the wheel" but what happens when you don't invent a single wheel anymore?

答:
For completion purposes, allow a counter argument:
http://web.archive.org/web/20150326134617/https://michaelochurch.wordpress.com/2015/03/25/never-invent-here-the-even-worse-sibling-of-not-invented-here/

a mentality that I call "Never Invent Here" (NeIH). With that
  mentality, external assets are overvalued and often implicitly
  trusted, leaving engineers to spend more time adapting to the quirks
  of off-the-shelf assets, and less time building assets of their own.

There is always a balance.


问:
Is the question "What is the using statement" a bad question to ask an interviewee?
We're looking to hire a new junior C# developer.
We're not looking for guru's or anything, so my boss asked me to write down a few questions and answers of varying difficulty to assess their skills.

My first question was "What does the using statement do".

So far after 2 interviews (both fresh out of college I think) both answered "used for including a namespace". After telling them not to confuse it with the using directive neither could explain what it does.

To me this seemed a fairly easy question for someone who has worked with C#. Am I wrong and is it a bad/confusing question?

答:
Remember, your job is to identify a talented guy, not someone who remembers the syntax of the language because they were taught to do so.

When you ask this question, chances are, your prospects have seen and used using statement before, however, were confused by the words statement and directive.

I am not a junior in any way, and first thing that popped in my mind when I read your question was the exactly that - the directive just because how much more prevalent the use of it is compared to the statement.

Another very important aspect, is you want a person who can think logically and learn code as they go - one way to gauge that is to show them the code samples - if the person is a good programmer, they will be able to understand what the statement does even without knowing the statement function in the beginning most of the time. Do the same to someone who learned the syntax religiously without understanding it and you might be up to a nasty surprise.

I would rather provide a prospect with code sample, and ask to describe what the statement does because in the end of the day, programmer will be looking at code 70% of the time. This way you eliminate confusion based on "interview fear" and might hire a talented person.


问:
Understanding of fork call
I was just reading an article online about fork().According to what I get,the fork() system call creates a subprocess and the program counter is updated to the next instruction and the control is passed on to the child process and then control comes back to the parent process.On exectuting the following program:

```<code> printf("%d\n",fork());
</code>```

I expected the output to be :

0
positive value

since the successful call to fork() returns 0 to the child process and process ID of child to parent,and child will run first after the call to fork(),but I was amazed to find the output as:

positive value
0

Where am I going wrong?

答: There is no defined order in which processes will execute after a fork, so either answer can occur.

Title: Understanding of fork call


问:
Relationship between objects
I got the models Post and Category. A Post is assigned to a Category. A Category has many Posts. They should be stored in a database. I implemented the following classes for it:

Models/Post.php:

```<code>class Post {
    /**
     * Title of the post.
     *
     * @var string
     */
    public $title;

    /**
     * The category that is assigned to the post.
     *
     * @var Category
     */
    public $category;

    public function __construct($title, Category $category) {
        $this->title = $title;
        $this->category = $category;
    }
}
</code>```

Models/Category.php:

```<code>class Category {
    /**
     * Name of the category.
     *
     * @var string
     */
    public $name;

    /**
     * Posts that are assigned to this category.
     *
     * @var Post[]
     */
    public $posts;

    public function __construct($name, array $posts) {
        $this->name = $name;
        $this->posts = $posts;
    }
}
</code>```

When I want to display a post, I will fetch it via an ID from a database. But what about the category? When I want to get the name of the category (to display it in the meta informations below the post) I have to fetch all posts that belongs to this category.

So my questions is: Is it better to store the IDs of the posts in Category::$posts instead the entire objects?

答:
From what I see, you have designed your models in such a way that you can't have a category without posts.

You have multiple ways of solving this, I will cover a couple.

1. Utilize Inheritance and have 2 category objects.

Have 2 category classes. BaseCategory and CategoryWithPosts inheriting from BaseCategory. Unless you need all posts in your category object, instantiate BaseCategory. In the constructor for CategoryWithPosts load your posts.

2. Have the posts lazy loaded.

Supply an instance of PostService to your category class upon instantiation and expose a method named GetPost(). This way you can operate on your category class as you need and when you need the posts, just call the method.

I am pretty certain you don't need posts in most of the instances of your category class.

Title: Relationship between objects


问:
Is Haskell's type system an obstacle to understanding functional programming?
I'm studying Haskell for the purpose of understanding functional programming, with the expectation that I'll apply the insight that I gain in other languages (Groovy, Python, JavaScript mainly.)

I choose Haskell because I had the impression that it is very purely functional, and wouldn't allow for any reliance on state.

I did not choose to learn Haskell because I was interested in navigating an extremely rigid type system.

My question is this:  Is a strong type system a necessary by-product of an extremely pure functional language, or is this an unrelated design choice particular to Haskell?

答:
The most dynamically typed functional language is arguably Scheme. That said, Haskell's type system is an indicator of its purity. It's a question of "how does one measure purity?". Haskell's type system lets you easily cordon off impure actions in IO. To do that, you need a static type system.

But let's say Haskell's type system has nothing to do with functional programming. It would still be the height of hubris to claim that the type system wouldn't help you in this educational endeavor. Haskell's type system is rich and complex, and all the more interesting when compared to the type systems of C++ and OCaml.

Is it an obstacle? No, I think it is an asset. Try to consider how to deal with Haskell's laziness without IO for example.


问:
Issues deciding on approach to create object
I'm trying to decide what's the best approach to instantiate a particular class. Basically there are two use cases for it: instantiate it in order to save a new entry to the database and fetch an existing entry from the database (and maybe edit the fetched entry and save it back to the database).

The issue I'm having right now is that I can't decide which mechanism for instantiating that class and populating its fields to choose. Say I have this class

```<code>public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}
</code>```

And here are the usecases. If you want to fetch a student for the database, the code looks something like:

```<code>Student student = MyLibrary.GetStudent(id);
</code>```

And if you want to create a new student and add it to the database:

```<code>Student student = new Student();
student.FirstName = "James";
student.LastName = "Jackson";
// etc
MyLibrary.CreateStudent(student);
</code>```

The massive issue with this approach is that all the setters are public and I absolutely do not want this. But at the same time I want the user to be able to populate most of the Student fields freely (maybe with the exception of Id.

I'm thinking the builder pattern could be employed in here. This way I can keep the setters private and force the user to create read-only students via the builders. However it then becomes really awkward if the user wants to update a field and save it to the database:

```<code>var student = MyLibrary.GetStudent(id);
var newStudent = new Student.Builder(id).FirstName("NewFirstName").LastName(student.LastName)...etc...Build();
MyLibrary.CreateStudent(newStudent);
</code>```

Basically my only issue with the builder approach is that the code can get quite awkward and tedious if you want to update an existing entry. Some of the classes I have can have around 10 fields and it's not great having to copy 9 of the fields and update one. But it may be much nicer than having a class with public setters.

What other options do I have?

答:
What you need is CQRS(Command Query Responsibility Segregation)

The idea is that what you save and what you load back and edit later is not the same object. This way you have control over what fields are private and what are public. What can be updated, and what can't.

In CQRS you have Command Model and Query Model. Command model is responsible for CREATE/UPDATE functionality, query model is responsible for fetching the data.


问:
Nested functions; allow or not?
Having programmed a whole lot in python, using nested functions is a good way to not clutter the namespace with small helper functions that are only used once.

Now I'm programming in go, and upon writing some code that I immediately wanted to refactor into an inner function, I found that go does not allow nested function declarations. I immediately changed the function to an anonymous function and saved it in a variable, and called it as a normal function. However, this seems to go against the language design since the normal function declaration syntax cannot be used inside another function.

Is there a good reason to not allow, or to deter use of nested function declarations?

答:
The behavior and semantics of nested functions are much closer to anonymous functions than to non-nested functions.  Most likely, they simply wanted the syntax to reflect that difference.

However, it wouldn't surprise me to see nested functions in a future update, because I believe the reasons are more cultural than technical.  Go was intended as a successor to C-family languages for systems programming.  The previous dominant languages for that purpose didn't support nested functions, and so programmers who work in those areas haven't incorporated nested functions into their design idioms.

To many programmers, that kind of encapsulation at the function level doesn't "feel" right.  To them, encapsulation of helper functions is the job of a class, end of story.  This is a deeply-ingrained, reflexive attitude among many object-oriented programmers.  You'll see this if you ever work somewhere that does mostly C++ programming with some python utilities on the side.

I think this attitude is slowly changing as functional-style features are being added to "enterprise" languages, but it might take a couple generations.

Title: Nested functions; allow or not?


问:
Can I avoid more faults if I use different paradigms for the implementation and the specification/tests?
Since it is convenient for the developer, the same paradigm are often used for implementations and specifications, e.g.

for testing (e.g. Java for the implementation and unit tests, Scala for the implementation and property testing)

for model-based testing (e.g. C# for the implementation and specifications using Spec Explorer, or Java for the implementation and specifications using Conformiq)

for verification (e.g. C for some embedded software and specifications in the C-like language Promela for model checking, or Dafny, which integrates implementation and specification).

There even seems to be a trend in this direction.

I always thought using different paradigms would help think on different abstraction levels and more generally in different structures, and that faults could be detected much better that way, when checking the implementation against the tests/specification (similar to using design diversity for fault tolerant systems).

So is it true that different paradigms for the implementation and specification can avoid more faults? Do you have a citable reference?

答:
This is not completely related, but if you includes formal specification languages, you have benefits with annotating your code with formal invariants and contracts.

See for example the ACSL reference manual, for C. The same goes for Ada which allows forall expressions that are not part of the language, but available for specifications:  http://docs.adacore.com/spark2014-docs/html/ug/appendix.html. Also, you could have a look at ACL2.

When it comes to tests, you may want to look at Model-Based Testing: you define a model that is useful only for tests.

It is often easier to describe the test in a functional way clearly conveys what the implementation should do, instead of how.


问:
Best place to declare functions in this example
Suppose I have code that accepts html GET requests:

```<code>server.get('path/to/some/endpoint', function(req,res) {
    function a() {
        //function goes here
    }
}
</code>```

Is it better to declare functions (like a()) outside the server.get's callback scope?  What are the pro's/con's to each?

答:
You are declaring a local scope function in this case. This means it will only be available withing your scope which is very limited.

If you are not planing to reuse it, I wouldn't declare a function all together. if you are planing to reuse it, I would move it outside the callback scope into  a separate module/class depending on what the responsibility of the function is.

Ideally you want to keep your routing clean of any extra steps other than routing. This is Single Responsibility Principle.


问:
Why i must validate attributes at JSF page?
I want to know the best pratice, to validate the attributes on jsf project. I know two forms of validation:

Option 1: Validate on JSF page

JSF Page validation:

```<code><h:inputText value="#{userBean.textEg}" maxlength="15" />
</code>```

Bean attribute:

```<code>private String textEg; // ++getAndSetter
</code>```

Where i defined by param at input my maxLength.

Option 2: Validate on Bean

JSF Page attribute:

```<code><h:inputText value="#{userBean.textEg}" />
</code>```

Bean Validation:

```<code>@Max(15)
private String textEg; // ++getAndSetter
</code>```

Both options work fine, but, my question is when to use option 1 and when to use option 2, if apply.

答:
If technology allows you you should validate in multiple layers - so someone with a security inclination would argue - "why not both?".

But to keep it simple I would suggest option 2. The reason being option 2 allows you to unit test your application and your unit test will be bound by the restrictions of the actually deployed application. Option 1 is unlikely to be UTed and hence I would suggest restricting yourself to the bare minimum code or logic possible.


答:
I don't find it surprising at all. I'm a relatively fresh into the workforce developer, and I've been using C# at work for about a year. I've been using it for personal projects in the same time. I've written several apps, and several web-apps. I just had to look up the using statement to answer your question.

I've seen it in examples online, and it's obvious what it does when I see it, but I've never had occasion to use it in my code, and I wouldn't have been able to answer your question.

As I said, it's pretty obvious what it does. I looked up this article, and skimmed to this example:

```<code>using (TextWriter w = File.CreateText("log.txt"))
{
    w.WriteLine("This is line one");
}
</code>```

source: Understanding the 'using' statement in C#

I still have never read or formally learned anything about a using statement, but I would guess from the example that the scope of the object is that code section, and it is deleted when the section elapses. If you show them something, and they're competent, they will have no trouble working with it. However, just asking what a using statement is is not a useful question, in my opinion.

Title: Is the question "What is the using statement" a bad question to ask an interviewee?

Body:
We're looking to hire a new junior C# developer.
We're not looking for guru's or anything, so my boss asked me to write down a few questions and answers of varying difficulty to assess their skills.

My first question was "What does the using statement do".

So far after 2 interviews (both fresh out of college I think) both answered "used for including a namespace". After telling them not to confuse it with the using directive neither could explain what it does.

To me this seemed a fairly easy question for someone who has worked with C#. Am I wrong and is it a bad/confusing question?

Body:
I don't find it surprising at all. I'm a relatively fresh into the workforce developer, and I've been using C# at work for about a year. I've been using it for personal projects in the same time. I've written several apps, and several web-apps. I just had to look up the using statement to answer your question.

I've seen it in examples online, and it's obvious what it does when I see it, but I've never had occasion to use it in my code, and I wouldn't have been able to answer your question.

As I said, it's pretty obvious what it does. I looked up this article, and skimmed to this example:

using (TextWriter w = File.CreateText("log.txt"))
{
    w.WriteLine("This is line one");
}

source: Understanding the 'using' statement in C#

I still have never read or formally learned anything about a using statement, but I would guess from the example that the scope of the object is that code section, and it is deleted when the section elapses. If you show them something, and they're competent, they will have no trouble working with it. However, just asking what a using statement is is not a useful question, in my opinion.


问:
How did JavaScript become popular?
In ancient history, Brendan Eich had a language design, and in today's world, JavaScript is a popular language implemented and used in many different places.

What caused the language to become popular? Was it the C-like syntax familiar to previous programmers? Did Netscape have enough control of the market to force it to be used? Or is there some deeper reason that JavaScript is popular and other languages are not?

Particularly, if you had to make a language as popular as JavaScript, what initial conditions would you need to recreate its growth in popularity?

答:
JavaScript became popular because of AJAX and good inspection tools such as Firebug. Of course the fact that it worked on all major browsers and was only way to do DHTML helped.

Basically to make even ugliest language successfull it has to be able to do really usefull thing that no other language can. Also you need to provide tools that allow programmers to really feel that they contol what language does which was not the case for javascript before firebug.

ContentLicense: CC BY-SA 2.5

Title: How did JavaScript become popular?


问:
Do I need a web-service for this case? Data-synchronization over multiple clients
I'm new in this area and a little bit confused about my current thoughts on a web-service implementation for my application. I want to synchronize all connected clients with the current data on a MySQL DB. I came up to use web-services as for coordination purposes, but I got stuck.

The way I tried to implement it is...

The web-service is running a deamon to check/listen on CRUD operations affecting DB data. Once an CRUD operation has been occured it undetakes to notify all the connected clients and each client in turn refreshes the JTable with current DB data and informs the user with the change that took place on the DB.

This is where I'm stuck...

The way I'm thinking it's (maybe?) wrong, since conceptually web-services are awaiting for client requests and then send him the corresponding response. But here, there is no client requests. The web-service just sends a response (noification), which must multicast since it's unaware of a "calling" client -there's no request.

Therefore, in order a client to send a request it must "cron" all the time the web-service if a change on the DB has been occured. Then the web-service responts as true or false with the CRUD details (CRUDEventFired(event_type, event_details)). But, this is not optimal as it will create big and (much of time) useless traffic especially when there is no CRUD operation occured. Also, there will be two different deamons (one in web-service and the other in client-app) that check/listen for the same type of event and that's redundant.

Also, with that implementation it seems that there's no need for a web-service at all and the code to check the DB for changes could be implemented in the client. On the other hand setting the client responsible for the DB changes would require to code the same functions in different platforms (desktop, ios, android, etc), while setting the web-service as the coordinator for data synchronization between clients would require to code only once the appropriate function and each client simply implement its own NotificationListener().

Is it wrong the way I'm thinking using web-services? How it should be changed? Do I even need to use web-services?

I attach my diagram for your convinience.

答:
It sounds like you are looking to implement push notifications from your back-end service to each front-end client.

Two options come to mind:

WebSockets will allow your clients to maintain a persistent two-way communication channel with the server. Updates on the client can be sent along the persistent channel, and when the web-server receives a change to the data store, it can propagate it out to each connected client. Using this, each client will probably (more on this later) have the most updated data whenever it wants to make a change to it

HTTP Long Poll is an older method (that works quite well) that utilizes HTTP with long timeouts to accomplish something similar to push updates. Each client opens a HTTP request for some resource and has a long timeout (say, 2 minutes for example). When something changes, the server will respond with the new data, otherwise, it will wait for the full 2 minutes before sending a 304 NOT MODIFIED response to the server. In this way, the client can get notifications pretty quickly, but without constantly polling.

Both of these ideas can be read up on here: https://en.wikipedia.org/wiki/Push_technology#HTTP_server_push

Both of these options suffer from the possibility that two clients will want to make updates at the same time, and one my overwrite the other. In this way it is easy for your data-store to become out of sync or have logical inconsistencies in it. If you would like to avoid this, as pjc50 mentioned, you may want to consider using a distributed database.

For those who will think it is useful, here is some pseudo-code for long-polling:

long-poll client & server pseudo-code

```<code>/**
 * Handles long-poll request for one client and sends updated
 * content to the client when it changes, or a 304 NOT MODIFIED
 * response if it doesn't change within the timeout period
 */

handleClientRequest(HTTRequest clientRequest) {
    String uri = clientRequest.getURI();
    int timeout = clientRequest.getTimeout();

    /* Wait for the resource to change. You should use
     * a more sophisticated waiting scheme, like semaphores,
     * java monitors, or any number of thread synchronization
     * techniques
     */
    while ((resource hasnt changed) && (total wait time < timeout))
        sleep(timeout / 100)

    if (resource did change)
        send new content
    else
        send HTTP 304 NOT MODIFIED response
}

/**
 * Continually sends long-poll requests to the server,
 * and updates data whenever it changes
 */
clientLongPoll(uri) {
    int timeout = 120 // seconds

    while (true) {
        HttpRequest request = new Request(uri);
        request.setTimeout(timeout);

        /* this will hang until the server responds, up to 2 minutes */
        HttpResponse response = request.send()
        if (resposne.contentChanged() == true)
            update local data store
    }
}
</code>```

Web socket libraries usually rely on an event-based scheme (onConnected(), onNewMessage(), onDisconnected(), etc...), but each library is different. The basic idea is that whenever a client starts up, it should contact the server to initiate a WebSockets connection, and from there, each can send messages back and forth whenever their local data changes.

Body:
It sounds like you are looking to implement push notifications from your back-end service to each front-end client.

Two options come to mind:

WebSockets will allow your clients to maintain a persistent two-way communication channel with the server. Updates on the client can be sent along the persistent channel, and when the web-server receives a change to the data store, it can propagate it out to each connected client. Using this, each client will probably (more on this later) have the most updated data whenever it wants to make a change to it

HTTP Long Poll is an older method (that works quite well) that utilizes HTTP with long timeouts to accomplish something similar to push updates. Each client opens a HTTP request for some resource and has a long timeout (say, 2 minutes for example). When something changes, the server will respond with the new data, otherwise, it will wait for the full 2 minutes before sending a 304 NOT MODIFIED response to the server. In this way, the client can get notifications pretty quickly, but without constantly polling.

Both of these ideas can be read up on here: https://en.wikipedia.org/wiki/Push_technology#HTTP_server_push

Both of these options suffer from the possibility that two clients will want to make updates at the same time, and one my overwrite the other. In this way it is easy for your data-store to become out of sync or have logical inconsistencies in it. If you would like to avoid this, as pjc50 mentioned, you may want to consider using a distributed database.

For those who will think it is useful, here is some pseudo-code for long-polling:

long-poll client & server pseudo-code

/**
 * Handles long-poll request for one client and sends updated
 * content to the client when it changes, or a 304 NOT MODIFIED
 * response if it doesn't change within the timeout period
 */

handleClientRequest(HTTRequest clientRequest) {
    String uri = clientRequest.getURI();
    int timeout = clientRequest.getTimeout();

    /* Wait for the resource to change. You should use
     * a more sophisticated waiting scheme, like semaphores,
     * java monitors, or any number of thread synchronization
     * techniques
     */
    while ((resource hasnt changed) && (total wait time < timeout))
        sleep(timeout / 100)

    if (resource did change)
        send new content
    else
        send HTTP 304 NOT MODIFIED response
}

/**
 * Continually sends long-poll requests to the server,
 * and updates data whenever it changes
 */
clientLongPoll(uri) {
    int timeout = 120 // seconds

    while (true) {
        HttpRequest request = new Request(uri);
        request.setTimeout(timeout);

        /* this will hang until the server responds, up to 2 minutes */
        HttpResponse response = request.send()
        if (resposne.contentChanged() == true)
            update local data store
    }
}

Web socket libraries usually rely on an event-based scheme (onConnected(), onNewMessage(), onDisconnected(), etc...), but each library is different. The basic idea is that whenever a client starts up, it should contact the server to initiate a WebSockets connection, and from there, each can send messages back and forth whenever their local data changes.


问:
Algorithm to cut out and straighten rectangles from image
I am looking to write an algorithm to cut rectangular images and straighten them in a new image. The bigger concept is that I will be scanning a bunch of physical pictures (on a physical scanner). They're all the same size (give or take a couple of pixels) and I can make sure they're all separated, so they're absolutely not overlapping or touching each other.

As a result of this, I want to split them up into separate files, so I can easily digitize a load of pictures, whose physical copies belonged to my grandmother and now have to be divided among different families.

Does any algorithm exist for this scenario, or am I forced to think up my own? I was thinking about simply trying to find the corners of the images first, then cutting the squares out using these corners, then simply rotating them. There might be an easier/faster processing time way though (or an existing product!)

答:
What you are trying to do is typically a series of image processing problems.
Have a look at algorithms in ImageJ such as the canny edge detector for finding edges in an image. This will produce a greyscale image where edges are lighter in color than non edges. These can sometimes do the job of finding the edge well enough with a little contextual help on your part. Then by choosing some intensity threshold, you can get only the edges from the image and use that slice the image up. Also consider filtering the images by their RGB values before running the edge detector on them.</p>


问:
Java 8: Good practice to pass Streams around in APIs for lazy operations?
In pre-Java 8 lambda-heavy libraries like Guava, the outputs use common Java Collection Framework interfaces so is easy to pass them around to external/internal APIs and still harness some lazy computation if the library method does it (e.g. lazy filter() and transform()).

However, in Java 8 Streams, the call to get a Collection/Map is terminal (i.e. eager) and it will also allocate new data structures to hold the results.

For complicated computations with multiple stages and strategy pattern in the middle, this causes a lot of unnecessary allocations due to the intermediate results.

So, do people think it is a good practice for internal APIs (i.e. strategy pattern strategies) to take and return Streams or should I just fallback to the lazy but not streamlined (pun intended I guess) Guava APIs?

Edit:

My main concern with Stream is that it can only be consumed once and passing something like a Supplier<Stream<X>> looks extremely cumbersome. It almost pushes you just to pass a Collection and then re-stream() it (and paying the cost of eager evaluation at that point).

答:
Laziness in Java 8 Streams works the same as it used to for Iterables in Guava: you have to pass on the Iterable to stay lazy and evaluation happens, once you build a Collection from the Iterator. Both Streams and Iterators can only be consumed once.

So for your method interfaces, the more general way (permitting laziness) is to use the Stream interface (whenever you would have used Iterable before). As @Philipp says, this allows them to be used in Stream pipelines.

Hopefully, since Stream now is an official Java standard interface, there will be more and more other libraries and functions which can efficiently work on Streams directly.


问:
What categories of software modeling problems is object orientation highly unsuitable for?
I'm trying to get a better grasp of the applicability of object-oriented programming and design. I'm curious about some examples of situations where object orientation is not simply inefficient or overkill, but highly inappropriate and entirely not recommended.

Nowadays it seems that OOP can be applied to a very wide range of software modeling problems, but I'd like to know when OOP would be one of the worst ideas of all paradigms.

答:
First of all, don't confuse OO modeling with OO programming. Most modern programming languages are more or less OO and can be used to implement most designs whether they have been derived using OO modeling or not. I can write a program following a relatively procedural design (or event-driven, or some other style) and still use Java Collections with their practical OO interfaces.

Now for modeling, I'd say don't use OO in domains where more specific frameworks are already established. For example, if you deal with an event-based problem, then it makes sense to describe your design using events (not classes) as a building block and only for implementation (if you use an OO language) decide on how to map that to classes or objects. For example, you could find that all your events need the same set of methods, so you implement them all using one class.

In my experience it is actually always better to figure out notions of design using concepts from the application domain and only in actual implementation decide what should become a class or a subclass and what are important methods. Classes and methods, in my opinion are much more useful at structuring code than at structuring your customer's problem.


问:
Accessing database from static and non-static methods
I'm currently building a REST API in PHP & MySQL, and now I'm stuck at how I should structure the classes and the database connection.

Let's say I have a table in my database for movies. How should I structure my code for connecting to the database?

Currently I have this:

```<code><?php
//Db.php

class Db
{
    private $db;
    private $table = '';
    private $where = '';

    public function __construct()
    {

        $json = json_decode(file_get_contents(INC_ROOT . '/app/db.json'), true);

        $this->db = new \PDO(
            'mysql:host='.$json['host'].';dbname='.$json['dbname'].';charset=utf8',
            $json['username'],
            $json['password']
        );
        $this->db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
    }

    public function table($tbl)
    {
        $this->table = $tbl;
        $this->where = '';
        return $this;
    }

    ...
}
</code>```

```<code><?php
//Movie.php

class Movie
{
    public $db;
    public $id;
    public $title;

    public static function getById($id)
    {
        $instance = new self();
        $result = $db->table('movies')->where("id = $id")->select();
        $instance->id = $result[0]['id'];
        $instance->title = $result[0]['title'];
        return $instance;
    }

    public static function getAll()
    {
        $instances = array();
        $results = $db->table('movies')->select();
        foreach($results as $movie){
            $instance = new self();
            $instance->id = $movie['id'];
            $instance->title = $movie['title'];
            $instances[] = $instance;
        }
        return $instances;
    }

    public function updateTitle($title)
    {
        $this->title = $title;
        //update in database
    }
}
</code>```

The rest of the api is built using Slim so it's basically

```<code>$app = new Slim();
$app->container->singleton('db', function() {
    return new Db();
});

$app->get('/movies', function() use ($app) {
    $db = $app->container['db'];
    $movies = Movie::getAll();
}

$app->get('/movies/:id', function($id) use ($app) {
    $db = $app->container['db'];
    $movie = Movie::getById($id);
}
</code>```

The problem here is that I don't know how to access the database from both the static and non-static methods in the Movie class. I don't want to send an instance of the database class to each Movie method. But creating a new db instance inside each method doesn't seem optimal either.

So where should I create the db instance and how do I access it?

答:
What you probably want to do here is use a repository... This would have your querying methods directly related to your Object and would use and instance of the DB as part of its constructor:

```<code>$repo = new MovieRepository($db);
$movies = $repo->findAll();
</code>```

And or writing you might have:

```<code>$repo = new MovieRepository($db);
$movie = $repo->findById($id);
$movie->setTitle('A new Title');
$repo->update($movie);
</code>```

So in your Slim controller for example:

```<code>$app->get('/movies/:id', function($id) use ($app) {
    $repo = new MovieRepository($app->container['db']);
    $movie = $repo->findById($id);
}
</code>```

Body:
What you probably want to do here is use a repository... This would have your querying methods directly related to your Object and would use and instance of the DB as part of its constructor:

$repo = new MovieRepository($db);
$movies = $repo->findAll();

And or writing you might have:

$repo = new MovieRepository($db);
$movie = $repo->findById($id);
$movie->setTitle('A new Title');
$repo->update($movie);

So in your Slim controller for example:

$app->get('/movies/:id', function($id) use ($app) {
    $repo = new MovieRepository($app->container['db']);
    $movie = $repo->findById($id);
}


答:
There are several ways to look at this. One way is from the point of view of data abstraction. (I'm going to ignore looking at this from the perspective of programming paradigms, since @Robert's answer already does a good job.) The two most popular forms of data abstraction in use today are Abstract Data Types and Objects. (Actually, there is a rather popular third form: no abstraction at all.)

The main difference between ADTs and Objects is that ADT instances hide their representation from instances of other types but not from instances of the same type, whereas objects also hide their representation from other objects of the same type. (If you are familiar with Java, that's the difference between classes and interfaces, classes define ADTs and interfaces define objects.)

What this means is that because of the higher level of encapsulation, OO has the potential to be more flexible and extensible. However, algorithms which need access to the representation of two objects are simply impossible to implement. For example, you cannot efficiently concatenate two doubly-linked lists in OO, because you need access to both the first list's tail's next pointer as well as the second list's head's prev pointer. If you call the first list's concat method, it has no access to the second list's internals and vice versa, the only way to do this efficiently is by one of the lists exposing its internals to the other one, i.e. breaking OO encapsulation. (You can of course concatenate two lists by iterating the second one, i.e. do it in O(n), but you can't do it in O(1).)

Title: What categories of software modeling problems is object orientation highly unsuitable for?

Body:
I'm trying to get a better grasp of the applicability of object-oriented programming and design. I'm curious about some examples of situations where object orientation is not simply inefficient or overkill, but highly inappropriate and entirely not recommended.

Nowadays it seems that OOP can be applied to a very wide range of software modeling problems, but I'd like to know when OOP would be one of the worst ideas of all paradigms.


问:
Why is implicit parallelism/concurrency not more widespread?
Implicit parallelism^ can take a big burden away from many programmers, placing it on the computer. So... why is it is not more widespread at present?

^ Implicit parallelism is to make a computer be able to figure out itself how to do more than one thing at a time, instead of a programmer needing to do this job using threads and the like

答:
Apart from the points mentioned in the other answers (hard to prove that operations are independent, and programmers think serially), there is a third factor that needs to be considered: the cost of parallelization.

The truth is, that thread parallelism has very significant costs associated with it:

Thread creation is very expensive: To the Kernel, starting a thread is just about the same as starting a process. I'm not sure about the precise costs, but I believe it's in the order of ten microseconds.

Thread communication via mutexes is expensive: Usually, this requires a system call on each side, possibly putting a thread to sleep and waking it up again, which produces latency as well as cold caches and flushed TLBs. On average, taking and releasing a mutex costs around one microsecond.

So far, so good. Why is this a problem for implicit parallelism? Because implicit parallelism is easiest to prove on the small scales. It is one thing to prove that two iterations of a simple loop are independent of each other, it is a whole different thing to prove that printing something to stdout and sending a query to a database are independent of each other and can be executed in parallel (the database process could be on the other side of the pipe!).

That is, the implicit parallelism that a computer program can prove is likely unexploitable because the costs of parallelization are greater than the advantage of parallel processing. On the other hand, the big scale parallelism that can really accelerate an application is not provable for a compiler. Just think about how much work a CPU can do within a microsecond. Now, if the parallelization is supposed to be faster than the serial program, the parallel program must be able to keep all CPUs busy for several microseconds between two mutex calls. That requires really coarse grained parallelism, which is almost impossible to prove automatically.

Finally, no rule without an exception: Exploitation of implicit parallelism works where no threads are involved, which is the case with vectorization of the code (using SIMD instruction sets like AVX, Altivec, etc.). That indeed works best for the small scale parallelism that's relatively easy to prove.


问:
How to sort fractions (small numbers)
We have 100 000 fractions:
Let's consider following fractions.
p/(2^q) such that 0 <= p,q <= 10

As you can see there are <= 10 * 10 different fractions, but we have 100 000 that we have to sort them  (so there are little unique elements).

Task is about thinking fast algorithm to sort fractions.

I ask you for looking at my proposition and show me your ideas.
(I assume that fractions are given by pair, for instance:
p/q <----> (p, q)
)
on input we have array a

My idea:

```<code>for i = 1 to n do t[i] = a[i].first * 2^(10)
countsort (t)
bring results from t to a (remember about / 2^10)
</code>```

答:
First, your definition of your numbers can lead to non-fractions (e.g., p=2, q=0).

Second, to summarize your idea:

Store all your fractions as integers

Perform an integer sort

Convert all your integers back to fractions

Seems like a lot of unnecessary memory and time when a lot of sorting algorithms can be done using a simple comparison sort and you can leave your data in its original form.

With a comparison sort, you only have to implement a custom comparison operator that exploits knowledge of your specialized fractions. For example in C++, you could use the built-in sort function and just implement your own comparator.

The comparator function compare(a,b) just needs to return true if fraction a is less then fraction b otherwise return false. For example, this function can exploit the fact that multiplying by 2 can be done as a bit shift. So your comparison could look something like

```<code>a.first * (1 << b.second) < b.first * (1 << a.second)
</code>```

Title: How to sort fractions (small numbers)

Body:
First, your definition of your numbers can lead to non-fractions (e.g., p=2, q=0).

Second, to summarize your idea:

Store all your fractions as integers

Perform an integer sort

Convert all your integers back to fractions

Seems like a lot of unnecessary memory and time when a lot of sorting algorithms can be done using a simple comparison sort and you can leave your data in its original form.

With a comparison sort, you only have to implement a custom comparison operator that exploits knowledge of your specialized fractions. For example in C++, you could use the built-in sort function and just implement your own comparator.

The comparator function compare(a,b) just needs to return true if fraction a is less then fraction b otherwise return false. For example, this function can exploit the fact that multiplying by 2 can be done as a bit shift. So your comparison could look something like

a.first * (1 << b.second) < b.first * (1 << a.second)


答:
Consider the three pillars of OOP:

Encapsulation: The capability to hide data and instructions inside an object

Inheritance: The ability to create one object from another

Polymorphism: The ability for objects of a derrived class to override/extend/inherit properties and methods from a base class

If these benefits do not offer any real value to solving the problem at hand, you can argue that perhaps OOP is not the ideal choice, or at least not necessary.

In practice, the benefit that comes with well-designed and well-written OOP rarely justifies the "overhead" when working with relatively small applications or applications that are resource-constrained. In the wild I've seen many ETL processes built in languages like C# and Java that don't necessarily follow the object-oriented paradigm.  Yes, there is a "class" because of the constraints of these languages, but all methods are made static and exist within a single class called Program.(cs/java) that acts as the application's entry point.

Truthfully it's difficult to think of situations where OOP is the absolute worst of all available programming paradigms, but there are cases where it is not the most ideal paradigm.  One could say that yes, an object-oriented paradigm is not always ideal for a situation that lends itself to an event-driven or procedural paradigm, but it's difficult to say whether it would be more or less ill-suited to the situation than, say, a functional paradigm.


问:
Why would a program allow an object to be initialized when it doesn't support all methods/properties of the interface type it was defined as?
I'm under the impression that an object MUST support all methods/properties upon being initialized or else the program will create an error.  However, if you see below I am defining 2 variables (doc and el) as htmldocuments.  Thus any object assigned to these variables must in theory support all htmldocument methods/properties, otherwise an error will be raised.  In this scenario doc is the control variable and el is the test variable.  "doc" is set to a document object, which can obviously support all htmldocument interface methods. "el" is set to a single htmlparagraphelement, which CANNOT support all htmldocument interface methods. However, no error occurs.  In the next line, I test the htmldocument interface method called "createRange" on both variables.  It works fine (as expected) with the doc variable.  An error is raised with the el variable saying "Object doesn't support this method".   This is also expected, but what I don't understand how I got this far in the first place.  Shouldn't an error have been raised when the object was initialized?

VBA:

```<code>'Turn on references to Microsoft Internet Controls
'and Microsoft HTML Object Libraries before running

Sub qstn()

Dim IE As New InternetExplorer
'Note that both doc and el are declared within the HTMLdocument interface
Dim doc As HTMLDocument, el As HTMLDocument

IE.navigate "https://www.youtube.com/"

IE.Visible = True

Do Until IE.ReadyState = 4: Loop

'No error expected here.  Document object is returned
'which has all properties and methods of HTMLDocument interface
Set doc = IE.Document

'Why am I not getting a type mismatch here?
'I should not be allowed to go any further on this line
Set el = IE.Document.getElementsByTagName("p")(0)

'Random method to prove that the actual document object can execute this method
doc.createRange

'Same method used on the object that was also declared as HTMLdocument,
'but was set as an htmlparagraphelement.  This will not working
'because the htmlparagraphelement doesn't support it
el.createRange

End Sub
</code>```

答:
For the most part, VBA uses late binding, not the kind of early binding that you are describing.

In strongly-typed languages like C#, you will get the behavior you expect, because the compiler will check your method calls against the class definitions and complain that they don't match.  This is early-binding.

But in a loosely-typed, late-binding language like VBA, you don't get the error until the interpreter actually attempts to execute the offending code.


问:
Is it fine to have broken intermediate commits, as long as the final commit in any push works?
Related: Should every git commit leave the project in a working state?

Suppose I make the following commits locally:

Modify the database schema, breaking the application.

Update the application so it is compatible with the database schema again.

As long as I push both commits, master remains in a working state.  However, a historical version is broken.

I'm aware that I can use git rebase -i to squash the commits together.  However, the resulting commit will be large and less descriptive.  If I need to search the commit history to find out why I changed something, I'd rather find the original commit showing what I did and why.

My questions are:

Has anyone encountered difficulties due to broken historical commits in master?

If so, is there a simple way to avoid such difficulties, without discarding individual commit messages and changes?

答:
Short Answer: Yes

Testing:

Test driven development means you write tests that break (ie show failing).

Then you write the code to make the tests work.

Development:

Commit small, Commit often.

Each commit is a rollback point. If you realize you are on the wrong path you can rollback to a previous point relatively easily. If you are commits are fine grain enough you can rollback to the correct point.

Caveat:

This does not mean

1) You check broken code into master.

2) You need to push all micro commits for everybody to review.

Use branches to do your work. Potentially compress micro commits for the review processes so they are in logically distinct units with appropriate comments. If you are using git you will not loose the original set of commits you can just create a new more logical set of commits for the review proceses that will be merged into master.


问:
What false ideas are there that puts people off using threads?
Implementing threading in a program is hard, yes, however why is it that some people will not implement them even when there is an obvious need for it.

An example: Program has to load a dataset from a database, the thing to do would be to make the connection and get the data from the database in a worker thread and then load it into the GUI, leaving the GUI thread responsive for the user.

But no, I've talked to people whom seem to think that threads are evil and bad and whatnot and one should avoid them at all costs.  I've even heard that some class instructor advised against to use of threads and therefore did not want cover their use. WHAT???

With the hardware going into multi-core, I think that we need to understand threads better and not be afraid to use them. I find it a fascinating subject personally.

So what are things you've heard about threading that are false?

答:
You will eventually loose any gains from threading because fixing crazy bugs that will arise from use of some libraries/functions that are not thread safe (what you were not aware of) will require excessive synchronization.

You have much higher probability of encountering bug that you will not be able to fix if you use threads then when you don't.


问:
Determining game item prices based off of player trades/in-game economy
I've been working on a game the past few months and I'm finally starting to approach issues regarding the in-game economy. The game is sort of like an MMORTS, players create their own nations and they have cities all over the world map. I want players to be able to trade resources between their cities and other players' cities. For the sake of this example, let's say the cities are trading oil. One city might be right next to a few oil deposits, so they're going to sell to other cities that don't have any oil deposits next to them.

Instead of the game having a fixed price for oil, I want the price of one unit of oil in the game to reflect the current supply and demand of it in game. How can I go about doing this within the virtual economy of my game?

My first thought was to take the average price payed for oil between trades among players; however, how do I protect from friends working together to continuously trade oil at higher prices between each other to artificially inflate the prices for their gain?

Note: I have little to no knowledge on how an economy works in-depth, so I hope this question isn't too silly.

答:
One of the biggest challenges is making the trade worth while for players.

Consider monopoly for example. players randomly aquire streets and are supposed to trade them amonst themselves. the streets aquire value because there is a bonus if you can get a whole set. However! In fact the winning strategy is never to trade. As there is a finite number set of streets and only one winner there is no incentive to trade when you are in a winning position.

Another good example is settlers of catan. Here the trading is more advantagous. But still aquiring a monopoly and not selling at any price is a viable strategy.

Trade can also be made worthless in the other direction. Sins of a solar empire lets players sell thier resources to a market. however as you can always buy  or sell and the price fluctuation is limited essentialy resources and money are interchangable.

To hit the sweet spot of trade being important but not so much that it stops taking place is a real balancing act. In my view there are a number of key factors you need though.

1: win/win deals. This is where resource X is worth more to me than it is to you and resource Y is worth more to you than it is to me.

2: indirect competition. My gain shouldnt nessecarly be your loss

3: secrecy. you shouldnt know the exact value of your resources to me. If you know I need 3 sheep to win, tjat trade isnt going to happen


问:
What design pattern best suits managing handles to objects, without passing handles or Manager around?
I'm writing a game in C++ using OpenGL.

For those that don't know, with the OpenGL API you make a lot of calls to things like glGenBuffers and glCreateShader etc. These return types of GLuint which are unique identifiers to what you just created. The thing being created lives on the GPU memory.

Considering that GPU Memory is sometimes limited, you don't want to create two things that are the same when they're to be used by multiple objects.

For example, Shaders. You link a Shader Program and then you have a GLuint. When you're done with the Shader, you should call glDeleteShader (or something to that affect).

Now, let's say I have a shallow class hierarchy like:

```<code>class WorldEntity
{
public:
    /* ... */
protected:
    ShaderProgram* shader;
    /* ... */
};

class CarEntity : public WorldEntity
{
    /* ... */
};

class PersonEntity: public WorldEntity
{
    /* ... */
};
</code>```

Any code I've ever seen would require that all the Constructors have a ShaderProgram* passed to it to be stored in the WorldEntity. ShaderProgram is my class that encapsulates the binding of a GLuint to the current shader state in the OpenGL context as well as a few other helpful things that you need to do with Shaders.

The problem I have with this is:

There's a lot of parameters needed to construct a WorldEntity (consider that there might be a mesh, a shader, a bunch of textures etc, all of which could be shared, so they're passed as pointers)

Whatever is creating the WorldEntity needs to know what ShaderProgram it needs

This probably requires some sort of gulp EntityManager class that knows what instance of what ShaderProgram to pass to different entities.

So now because there's a Manager the classes need to either register themselves with the EntityManager along with the ShaderProgram instance they need, or I need a big-ass switch in the manager that I need to update for every new WorldEntity derived type.

My first thought was to create a ShaderManager class (I know, Managers are bad) that I pass by reference or pointer to the WorldEntity classes so that they can create whatever ShaderProgram they want, via the ShaderManager and the ShaderManager can keep track of already existing ShaderPrograms, so it can return one that already exists or create a new one if needed.

(I could store the ShaderPrograms via the hash of the filenames of the ShaderPrograms actual source code)

So now:

I'm now passing pointers to ShaderManager instead of ShaderProgram, so there's still a lot of parameters

I don't need an EntityManager, the entities themselves will know what instance of ShaderProgram to create, and ShaderManager will handle the actual ShaderPrograms.

But now I don't know when ShaderManager can safely delete a ShaderProgram that it holds.

SO now I've added reference counting to my ShaderProgram class that deletes its internal GLuint via glDeleteProgram and I do away with ShaderManager.

So now:

An object can create whatever ShaderProgram it needs

But now there's duplicate ShaderPrograms because there's no external Manager keeping track

Finally I come to make one of two decisions:

1. Static Class

A static class that's invoked to create ShaderPrograms. It keeps an internal track of ShaderPrograms based on a hash of the filenames
- this means I no longer need to pass pointers or references to ShaderPrograms or ShaderManagers around, so less parameters
- The WorldEntities have all knowledge about the instance of ShaderProgram they want to create

This new static ShaderManager needs to:

keep a count of the number of times a ShaderProgram is used and I make ShaderProgram no copyable OR

ShaderPrograms count their references and only call glDeleteProgram in their destructor when the count is 0 AND ShaderManager periodically checks for ShaderProgram's with a count of 1 and discards them.

The downsides to this approach I see are:

I have global static class which might be a problem. The OpenGL Context needs to be created prior to the invoking any glX functions. So potentially, a WorldEntity might be created and try to create a ShaderProgram prior to OpenGL Context creation, which will result in a crash.

The only way around this is back to passing everything around as pointers/references, or having a global GLContext class that can be queried, or holding everything in a class that creates the Context on construction. Or maybe just a global boolean IsContextCreated that can be checked. But I worry that this gives me ugly code everywhere.

What I can see the devolving to is:

The big Engine class that has every other class hidden inside of it so that it can control the construction/deconstruction order appropriately. This seems like a big mess of interface code between the user of the engine and the engine, like a wrapper over a wrapper

A whole slew of "Manager" classes that keep track of instances and delete things when neccessary. This might be a necessary evil?

AND

When to actually clear ShaderPrograms out of the static ShaderManager? Every few minutes? Every Game Loop? I'm gracefully handling the re-compiling of a shader in the case when a ShaderProgram was deleted but then a new WorldEntity requests it; but I'm sure there's a better way.

2. A better method

That's what I'm asking for here

答:
Opengl has been designed as a C library, and it has the characteristics of procedural software. One of the opengl rules coming from being a C library looks like this:

"When complexity of your scene increases,  you'll have more handles that need to be passed around the code"

This is feature of the opengl api. Basically it assumes that your whole code is inside main() function, and all those handles are passed through the main()'s local variables.

Consiquences of this rule are as follows:

You should not try to put a type or interface to the data-passing path. Reason is that this type would be unstable, requiring constant changes when complexity of your scene increases.

The data-passing path should be in main() function.


答:
I would say:

"Validate in every place you can do so."

The sooner you validate, the sooner you provide feedback to the user of the system. This reduces eventual errors, provides hands-on training and eventually improves the user experience.

You need to validate in your business logic, because there are many business rules that won't make it to your UI. The more important reason is that your back end cannot afford to trust your front end, especially over the web.

You need to validate in your repository because the UI isn't the only place that you can make changes to your data.

Especially with this strategy in place, it is very important that data is treated coherently, even if it is not treated consistently. The classic issue of this dilemma is a simple text area input field. It can be no longer than 43 bytes, say, because that is what the database field size is defined to be.

However, the text area in a web browser can accept non-ASCII characters, such as accents and glyphs. So, the string that arrives in your application may fit the text area maximum size, but, when translated to UTF-8 for insertion in your database, it's size might be somewhat larger.

The feedback to the user entering the data has to make sense, even when they don't (rightly so) understand the details of character encodings or database field limits.

Title: Why i must validate attributes at JSF page?

Body:
I want to know the best pratice, to validate the attributes on jsf project. I know two forms of validation:

Option 1: Validate on JSF page

JSF Page validation:

```<code><h:inputText value="#{userBean.textEg}" maxlength="15" />
</code>```

Bean attribute:

```<code>private String textEg; // ++getAndSetter
</code>```

Where i defined by param at input my maxLength.

Option 2: Validate on Bean

JSF Page attribute:

```<code><h:inputText value="#{userBean.textEg}" />
</code>```

Bean Validation:

```<code>@Max(15)
private String textEg; // ++getAndSetter
</code>```

Both options work fine, but, my question is when to use option 1 and when to use option 2, if apply.


问:
Continue building off an ugly code base or start refactoring?
I'm currently interning at a company where I've been tasked with building an application from scratch. I've been working about 8 weeks, with 4 left to go. I've written a lot of code in that time, but now as I go over it, I'm realizing that it's really quite inefficient, ugly, and going to be hard to maintain for whoever gets this after I leave. I only have a few things left to implement, but I feel like I should place a higher priority on making the code better for future developers before I keep adding to it. Given my timeframe, is it more worth it to finish and then refactor, or refactor now and add afterward?</p>

答:
We're the wrong people to ask.

You're writing this code for the company; essentially it is your customer.  Someone in that company knows who's going to work on it next; someone has an idea of whether more features or more maintainable code have greater value for them.

You are your customer, too, in some ways - what do you want to get out of this?  Pride?  Experience?  Education?  Usually an internship involves learning something - it always should - what do you want to learn?  Four weeks from now, when you leave, how will you feel about the project?  One of the things to learn is the importance of communication - communicate your concerns and your questions to the relevant people at the company, and see how that works out.


答:
DELIVER

This is your priority. This is all they care about. This is what you've got to do.

If you get to deliver something that you feel has a sense of quality to it, you'll fell better and work better, and see a future for yourself in that company.

But you have to be realistic about time constraints. Do you have first hand experience of refactorings? Can you really do what you think you could do? Or are you overestimating your energy and commitment and underestimating the troubles you will run into?

Be pessimistic, consider that a refactoring might take 4 to 8 times longer than you feel it might. If that much more time would still get you to deliver on a reasonable schedule, go for it. Otherwise take the cheap messy shortcut: repurpose the crappy code you're dealt with and die another day.

Choose your battles wisely. Most ain't worth the hassle.

Title: Continue building off an ugly code base or start refactoring?

Body: I'm currently interning at a company where I've been tasked with building an application from scratch. I've been working about 8 weeks, with 4 left to go. I've written a lot of code in that time, but now as I go over it, I'm realizing that it's really quite inefficient, ugly, and going to be hard to maintain for whoever gets this after I leave. I only have a few things left to implement, but I feel like I should place a higher priority on making the code better for future developers before I keep adding to it. Given my timeframe, is it more worth it to finish and then refactor, or refactor now and add afterward?</p>


问:
Pushing data from Server to Client without a client request?
I've noticed while browsing Stack Exchange that there are dynamic notifications like "3 new messages, click to show". I want to have this kind of dynamic updating for what I'm about to explain.

Let's say I want to create a carousel/slideshow of 10 recent news articles. I want this carousel to be updated hourly, in a queue. Newer articles will push older articles out of the queue. The solution off the top of my head would be.

User logs on to client.

Client calculates # of minutes until next hour mark and sets a timer to execute at the hour.

At hour mark, send a request to the server about any new news articles that haven't been in the carousel already.

Handle response.

Reset timer.

Is this an acceptable strategy? Can I achieve this without relying on client requests? In other words how does Stack Exchange achieve its dynamic updating?

答:
I cannot speak for how SE does it although since it is a website there are several ways that they could which could include a cron job set to run a php/asp/what-have-you script on the hour to push data.  But this would be if you were looking for a web only solution.

But since you are mentioning a client you could perhaps create a file with the date/time of the latest news update to that client and have the client check the value stored in said file and compare it to the user's system time to see if an hour has passed since the last update.  If it has been at least an hour then the client requests the latest news stream from your server which then returns the latest news stream to the client.

I would avoid using a timer or at least using a timer solely as that method would work only if the user keeps the client open to keep the timer running.  But if you (also) have the file as I suggested then you can create a subroutine to open the file, store the time into a variable and compare it to the system time and make the request if it has been at least an hour.  Then you simply make calls to the sub in relation to certain events.  I would definitely call it on form load because if the user is just restarting their client then you'd want the latest news.  If it had been a few days since they were on the client then it would be showing news that old.  In the least tie that sub to client load and kick off the timer as you suggested.  Theoretically as long as the user keeps the client open the timer will keep doing its thing and then you have the sub run on load for when there is no active timer to keep track of the timing.

I apologize if I misunderstood what you were going for as I am not totally certain what you are going for.  But hopefully either way there's something of value in here for you!


问:
Integer Map Algorithm
For my project, I need to map integers so that inputting int X will output int Y where both X and Y are defined during runtime.

I've used Dictionary<int,int> in .NET but its memory use is too high and the access speed is too long for my case.

Instead, I want to make a custom class that essentially does what a Dictionary<int,int> does in that it maps an integer key to an integer value.

What is the underlying concept behind the Dictionary and how would I implement something like it?

Note: I don't need to remove elements or check if the collection contains an element. I only need to be able to define input-output pairs and access the outputs with inputs.

答:
This answer is merely provided to reduce the frustration. In general, a person is better advised to learn how to conduct performance benchmarking properly before asking such a question.

If your "keys" exclusively consist of consecutive integers, you can use an integer array. Zero-based consecutive integers can be used as array index as-is. Non-zero-based consecutive integers may require an index value adjustment before using it with an array.

Even if the keys are not strictly consecutive, in that there are a small amount of holes (unused integer values between the minimum and maximum keys), it might still be beneficial performance-wise to use an array.

Remember that using an array makes your code fragile (more easily broken) to changes. Therefore, carefully analyze your project's current and future needs, and document the limitations inside your code comments, or somehow make them obvious to your project's users.

If there is some magic mathematical functions that map your integer keys into your lookup values, test to see whether that will be faster.

If your dictionary is constructed incrementally (adding keys one by one), consider using the Dictionary constructor with the size preallocation option,  with an estimate of the maximum size needed. This reduces the time spent in reallocating and rehashing.

As pointed out in others' comments, you can benchmark with SortedDictionary (docs), which is typically, but not guaranteed to be a binary search tree.

If you know that the distribution of your integer keys may have unusual statistical distribution characteristics (for example, all of your keys are even-numbered, and so on), you may have to implement a workaround:

Depending on the Dictionary implementation, a workaround might not be necessary if it is already implemented from within.

Otherwise, you will need to apply a "key diffusion / avalanche function" to your integer keys, and use the modified key as a hash table index inside a typical "modulo-N" hash table.

A typical good choice (for hash tables) is the MurmurHash3 function.

A sorted int-int dictionary that is initialized up-front and never changed can be re-implemented as an array of integer pairs, and lookup can be performed with binary search.

If the int-int mapping comes from some mathematical functions that has monotonic trends, it might be possible to perform the table lookup faster than binary search.

Title: Integer Map Algorithm


问:
Does knowing Latin or other logical languages contribute to being a better programmer?
I'm currently studying Latin at school, and what I've learned is that it's a very logical language. I feel this has contributed to my programming ability, as it makes it my code easier to understand.

Is there any relation between knowledge of a very logical language such as Latin and the comprehension of code?

答: I think learning languages where tiny details make a huge difference in the meaning of everything, such as Polish or Chinese, can make you better programmer. Logic is easy; adhering to peculiarities is not.</p>


答:
I looked at the source code of the dictionary and noticed the use of "buckets". I'm not exactly sure how a dictionary sorts objects into buckets but it's a simple task with integers.

The main problem, I've logiced, is converting the input into an index that's small as possible yet doesn't collide with other inputs' indexes to make the array the outputs are stored in as small as possible, which is where buckets come in.

If the input is 255, the array can't be that large to store the output in the index of 255. Instead, operations are done on the number to determine where its output is stored.

Here's my implementation. It's optimized for my particular use because the largest key is 255.

```<code>public class FastMap {
    //8 buckets because the maximum key is 255
    public int[][] Buckets = new int[][8];

    public void Add (int input, int output)
    {
        //Finding out which bucket output will be assigned in
        int bucketIndex = input % 32;
        //Finding out the index inside of the bucket the output will be assigned to
        int innerIndex = input / 32;
        //Dropping output into the necessary bucket
        int[] bucket = Buckets[bucketIndex];
        if (bucket == null)
        {
            bucket = new int[8];
            Buckets[bucketIndex] = bucket;
        }
        bucket[innerIndex] = output;
    }
    public int GetValue (int input)
    {
        return (Buckets[input % 32][input / 32]);
    }
}
</code>```

I'm going to be playing with this more but already, my implementation out-performs Dictionary<int,int> in both memory use and performance.

Title: Integer Map Algorithm

Body:
For my project, I need to map integers so that inputting int X will output int Y where both X and Y are defined during runtime.

I've used Dictionary<int,int> in .NET but its memory use is too high and the access speed is too long for my case.

Instead, I want to make a custom class that essentially does what a Dictionary<int,int> does in that it maps an integer key to an integer value.

What is the underlying concept behind the Dictionary and how would I implement something like it?

Note: I don't need to remove elements or check if the collection contains an element. I only need to be able to define input-output pairs and access the outputs with inputs.

Body:
I looked at the source code of the dictionary and noticed the use of "buckets". I'm not exactly sure how a dictionary sorts objects into buckets but it's a simple task with integers.

The main problem, I've logiced, is converting the input into an index that's small as possible yet doesn't collide with other inputs' indexes to make the array the outputs are stored in as small as possible, which is where buckets come in.

If the input is 255, the array can't be that large to store the output in the index of 255. Instead, operations are done on the number to determine where its output is stored.

Here's my implementation. It's optimized for my particular use because the largest key is 255.

public class FastMap {
    //8 buckets because the maximum key is 255
    public int[][] Buckets = new int[][8];

    public void Add (int input, int output)
    {
        //Finding out which bucket output will be assigned in
        int bucketIndex = input % 32;
        //Finding out the index inside of the bucket the output will be assigned to
        int innerIndex = input / 32;
        //Dropping output into the necessary bucket
        int[] bucket = Buckets[bucketIndex];
        if (bucket == null)
        {
            bucket = new int[8];
            Buckets[bucketIndex] = bucket;
        }
        bucket[innerIndex] = output;
    }
    public int GetValue (int input)
    {
        return (Buckets[input % 32][input / 32]);
    }
}

I'm going to be playing with this more but already, my implementation out-performs Dictionary<int,int> in both memory use and performance.


问:
Is the output of a neural net supposed to have had the activation function applied to it?
TL; DR:

Is the output from a feed-forward neural a direct result of the activation function?

I.e: If the activation function is the sigmoid function, will the output always be between 0 and 1?

I'm having difficulty understanding the activation function, and the output of a feed-forward neural net.

From what I understand, the propagation of a signal through the net follows this pattern:

The input values are fed to the nodes of the first hidden layer.

Each node of the layer multiplies each input by the associated weight, and gets a sum of all the weighted inputs.

The activation function (I'm using a sigmoid function) is applied to the sum, and the result becomes the activation for the node.

The first hidden layer becomes the new input, and the above repeats for it and the second hidden layer.

This continues until the output layer has received from the last hidden layer.

Question 1: Is my above understanding of the process correct?

My misunderstanding is about the resulting activations of the output layer. Since the sigmoid activation function was applied to the output, the output will always be within the range of 0 to 1 (assuming a sigmoid function was used).

Question 2: Is this correct? Should the output values be a direct result of the sigmoid function?

I'm asking because this throws a wrench in my simple first test of my net. I was using this to train my net (it should be self explanatory enough to not require more code examples/context). The fitness function is inside:

```<code>    public List<Double> trainNet(List<Double> input, List<Double> expectedOutput, GeneticAlgorithm<Double> ga, int gens) {

            ga.setFitnessFunction( genes -> {
                assert output.sizeWithoutBias() == expectedOutput.size();
                setWeights( genes.getSequence() );

                //"Fire" net
                List<Double> output = update();

                int fitness = Integer.MAX_VALUE;
                for (int i = 0; i < output.size(); i++) {
                    fitness -= 100 * Math.abs( output.get(i) - expectedOutput.get(i) );
                }

                return fitness;
            } );

            resetInput(input);

            ga.simNGens(gens);

            return output.getActivationsWithoutBias();
        }
</code>```

Basically, I'm just subtracting difference between the output and and expected output from the fitness. This "worked" (seemingly) until I realized that I forgot about the sigmoid function. So I added it (trimmed excerpt):

```<code>public class Node {

    private List<Double> weights;
    private double activation = 0;

    public void addWeightedInputs(List<Double> inputs) {
        if (inputs.size() != weights.size()) throw new IllegalArgumentException(
            "Input size (" + inputs.size() +
                ") doesn't match weight's size (" + weights.size() + ").\nThis: " + this );

        double sum = 0;

        for (int i = 0; i < inputs.size(); i++) {
            sum += weights.get(i) * inputs.get(i);
        }

        activation = sigmoidFunction(sum);
        System.out.println("Act: " + activation + ", Sum: " + sum);
    }

    private static double sigmoidFunction(double activation) {
        return 1.0 / (1 + Math.pow(Math.E, -activation));
    }
}
</code>```

The problem is, now, the expected output is in a "raw" form ([1,2,3]), and the output from the net is in "sigmoid form" ([0.9993,0.8764,0.9966]). Obviously now the fitness function is broken, since the output and the expected out are very different.

Question 3: Which is correct: the fitness function's expectation, or the output from the net? If the "sigmoid output" is correct, how do I use it in that form?

答:
Question 1: Is my above understanding of the process correct?

Yes; for the feed-forward process. It should be noted that the process can be computed with a matrix multiply for each layer.

Question 2: Is this correct? Should the output values be a direct result of the sigmoid function?

Yes, you generally apply the activation function to output layer. It should be obvious that the range of your output will match the range of your activation function. In some cases you may need to map the output for it to be useful.

N.b. the activation function doesn't need to the same for every layer, you could configure your network however you want/need. For example NNs for image recognition usually start with alternating layers of convolution and pooling layers, before they get into any fully connected layers. You just need to apply the correct derivative to the correct layer when back propagating.

Question 3: Which is correct: the fitness function's expectation, or the output from the net? If the "sigmoid output" is correct, how do I use it in that form?

This question is difficult to answer, it appears somewhat malformed, i.e. the second sentence doesn't refer to anything in the first. The short answer is sigmoid and map; the long answer is:

A neural network (NN) is a universal function approximator. The goal of training the network is to get its output to match the output of the function (F()) you are approximating. The output is supposed to be getting closer and closer to the expected value as you train, so it gets more and more correct as you train. It won't be correct until your training is complete and the weights have converged.

The loss function (a fitness function is a type of loss function) tells you how far off the output is from the expected value. The loss function also isn't 'correct' since it is the error signal for your network, not the output. When your loss is near zero, it indicates that the output is very close to correct.

A very common network output is a one hot vector where all the values are 0, except for one which is 1. This is useful for classification, where each element (in the output vector) represents the probability the input is of a given class.

The one hot output lines up very will with the range of a sigmoid, all values are between 0 and 1 (ideally exactly zero or one).

If your function has a different range you will have to map it, and use the mapped value to compare with the output. Or use a different activation function, like rectified linear. Obviously if the desired range doesn't correspond to the range of the activation function you will have to map, or swap your activation function.

Also, I don't know where you got your values for sigmoid([1,2,3]) the correct values would be [0.731059, 0.880797, 0.952574] not [0.9993,0.8764,0.9966] as you have.

I noticed that you are using a genetic algorithm for optimization instead of back-propagation. Due to the high dimensionality of NNs a genetic weight optimization is almost certainly going to be under-sampling your error space. This will lead to a slowly converging network. You also lose out on many of the advancements in back-propagation, like momentum. Some enhancements like drop-out should still be able to be applied, however.

Much of the power of NNs comes from the back-propagation scheme, and most NNs are trained with gradient descent via back-propagation. Genetic optimization sort of misses the point of NNs (they are not quite orthogonal, however.)

Genetic algorithms are often used to optimize the architecture of a NN, i.e. how many layers and of what size.

Genetic optimization does get around the vanishing gradient problem, which generally limits sigmoid networks to 2 hidden layers at maximum.

Genetic optimization is, however, preferable when you have a plethora of local minima in your error space that gradient descent is likely to get stuck in and/or have trouble moving past. In this case the genetic optimization will probably preform better, since it doesn't 'care' about the shape of your error space.

N.b. writing your own neural network is generally only recommended as a learning exercise, if you intend to do actual work you should use an existing library, as it will already be debugged for you; debugging NNs is notoriously difficult. Bugs tend to be in two categories, ones that just completely break the network, and ones that just hinder the network, making it slower (to converge); if the bug doesn't break the network, the network still learns, just slower, or not as well as it should. The second class of bugs can be very difficult to find!

Your initial tests of the network should be something that is easy to verify without a network, ex. linear regression:

can be done without a NN

only takes 3 nodes(2 in, 1 out) to do with a NN

can verify the answer without a network.

Also a small network is easy to calculate an update by hand to verify the math is correct as well; if you write a NN from scratch you will probably need verify a single pass (forward and back-prop) by hand at some point during debugging!


答:
In order to push data, you'd have to identify a Client, and that would be done by subscribing the client to the server. Once that's done you'd have a list of subscribed client with a persistent connection.

Depending on what you want to achieve, I'd say it's best for the client to request to the server, so that you don't have to maintain a persistent connection and make use of request/response communication protocols as HTTP.

One example that comes to mind to keep a persistent connection would be a live chat / instant messaging system, as the communication should happen real time.

Keep in mind persistent connection are usually implemented through the use of sockets, which adds an overlay in implementing your own communication protocol, encryption, etc...

Title: Pushing data from Server to Client without a client request?

Body:
I've noticed while browsing Stack Exchange that there are dynamic notifications like "3 new messages, click to show". I want to have this kind of dynamic updating for what I'm about to explain.

Let's say I want to create a carousel/slideshow of 10 recent news articles. I want this carousel to be updated hourly, in a queue. Newer articles will push older articles out of the queue. The solution off the top of my head would be.

User logs on to client.

Client calculates # of minutes until next hour mark and sets a timer to execute at the hour.

At hour mark, send a request to the server about any new news articles that haven't been in the carousel already.

Handle response.

Reset timer.

Is this an acceptable strategy? Can I achieve this without relying on client requests? In other words how does Stack Exchange achieve its dynamic updating?


问:
Parsing XML to two separate (WInForm) controls
I've spent a great deal of time researching a solution to my issue with very little success.  I'm rather new with .NET and vb.net so I apologize if this seems simple to anyone else.  I had a first version of what I am trying to do which worked fine.  I will provide sample XML and the vb.net code I used to render it.  As I decided that I needed to add an additional node to the XML file I am no longer sure how to process it.

Original XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<!--Transaction File.-->
<Transaction>
  <Items>
   <Item>
    <ItemID>1234</ItemID>
    <PriceEach>100.00</PriceEach>
    <Purchased>2</Purchased>
    <ItemTotal>200.00</ItemTotal>
   </Item>
   <Item>
    <ItemID>2345</ItemID>
     <PriceEach>2.50</PriceEach>
     <Purchased>3</Purchased>
     <ItemTotal>7.50</ItemTotal>
   </Item>
  </Items>
 </Transaction>
</code>```

Vb.net code to populate DataGridView with each item being its own row.

```<code> Dim Transaction As New DataSet
     Transaction.ReadXml(TransactionID) 'TransactionID is sent to this code
     DataGridView1.DataSource = Transaction.Tables(0)
</code>```

This works perfectly.  However, I decided that I needed to add a new node to hold the total cost for the specific transaction.  So the new XML file is as such:

```<code><?xml version="1.0" encoding="utf-8"?>
<!--Transaction File.-->
<Transaction>
  <TransactionTotal>207.50</TransactionTotal>
  <Items>
   <Item>
    <ItemID>1234</ItemID>
    <PriceEach>100.00</PriceEach>
    <Purchased>2</Purchased>
    <ItemTotal>200.00</ItemTotal>
   </Item>
   <Item>
    <ItemID>2345</ItemID>
     <PriceEach>2.50</PriceEach>
     <Purchased>3</Purchased>
     <ItemTotal>7.50</ItemTotal>
   </Item>
  </Items>
 </Transaction>
</code>```

So now I have a new tagset of TransactionTotal which should be displayed as the text property of a label titled TransactionTotal.  TransactionTotal.Text = ??  The TransactionTotal tags are on the same level as the Items tags.  And then The DataGridView should show all of each Item within Items as a new row in the DGV.

Obviously this new node makes my original DGV populate code invalid.  I use a Try/Catch statement which throws no errors because the XML file is found and it validates as proper XML but my DGV is blank as the code is thrown off by TransactionTotal being added into the mix.

I greatly appreciate any help leading me the right way!

答:
My apologies but a muse came along and I have an answer to my own question which I wanted to post here in case it helps someone else.  However, if you have any other ideas of how to do this then please share.

Updated Code:

```<code>    Dim TransactionItems As New DataSet
    TransactionItems.ReadXml(TransactionID) ' still passed into this code by user selection
    DataGridView1.DataSource = TransactionItems.Tables(2)
    TransactionTotal.Text = TransactionItems.Tables(0).Rows(0).Item(0).ToString()
</code>```

Honestly in my original code I did not really understand the "Tables" part of the code to put the Items into the DataGridView.  As it turns out each node was being turned into a separate table.  Now the value between the TransactionTotal tags is set as the text property of a label.

Body:
My apologies but a muse came along and I have an answer to my own question which I wanted to post here in case it helps someone else.  However, if you have any other ideas of how to do this then please share.

Updated Code:

    Dim TransactionItems As New DataSet
    TransactionItems.ReadXml(TransactionID) ' still passed into this code by user selection
    DataGridView1.DataSource = TransactionItems.Tables(2)
    TransactionTotal.Text = TransactionItems.Tables(0).Rows(0).Item(0).ToString()

Honestly in my original code I did not really understand the "Tables" part of the code to put the Items into the DataGridView.  As it turns out each node was being turned into a separate table.  Now the value between the TransactionTotal tags is set as the text property of a label.


问:
How did JavaScript become popular?
In ancient history, Brendan Eich had a language design, and in today's world, JavaScript is a popular language implemented and used in many different places.

What caused the language to become popular? Was it the C-like syntax familiar to previous programmers? Did Netscape have enough control of the market to force it to be used? Or is there some deeper reason that JavaScript is popular and other languages are not?

Particularly, if you had to make a language as popular as JavaScript, what initial conditions would you need to recreate its growth in popularity?

答:
In my opinion, Javascript is popular because it is supported well.

First, it's the only language for both Netscape and IE in its time. After a "javascript community" is established and became stable, no one could ever think about "another good" that requires to build from scratches. They just contribute to make it better and better.

If you want to build a new popular language, the first thing I think about is that you must determine who use that language. The first customers are always hard to get, and you must make your language superior to javascript in some way or another. Maybe even in a restricted field/ restricted community of programmers, for example, "better/faster javascript engine for iPhone mobile" may be a good choice.

Moreover, your language should be easy to use and customize by community, because it's the community that determine which language could survive.

Title: How did JavaScript become popular?


答:
Basically you need to push data to the client, and as a bidirectional communication is not in the scope of http protocol, its not easy to implement it on your own.

The Solution of your problem is socket.io

As its website states,

"Socket.IO enables real-time bidirectional event-based communication.
It works on every platform, browser or device, focusing equally on reliability and speed."

Hope this will solve your problem.