问:
Should class with only static data need to be instantiated?
I have two classes. 1. Node 2. MixedStateManager

Node class:

Node class maintains the state of nodes in the system. One such data is state.

```<code>public class Node
   {
      private int state;

     public void setState(int s)
     {
      state = s;
     }

     public int getState()
     {
       return state;
     }
    }
</code>```

MixedStateManager:

MixedStateManager sees if all the nodes in the system are in the same state or not. If the nodes don't have the same value for state value, then the system is said to be in MixedState. I've a variable mixedState for the same. I've made it static because, if the value is changed by one instance of the class, then it should be visible by others. Another thing to note is MixedStateManager is called by different threads which change the value of state of nodes.

```<code>public class MixedStateManager{

public static boolean mixedState;

public boolean isMixedState(){
 return mixedState;
}

public void setMixedState(){
// get all instances of Node class;
   if state of all instances are same
     mixedState = true;
   else
     mixedState = false
}
}
</code>```

Question: As MixedStateManager has only one data which is static, does it make sense to instantiate this class and then set value. Or can I make all methods static too?

Responses will be appreciated.
Thanks

答:
I would argue that no class should ever have static data. That lies the road to testing hell and non-threadsafe code.

Also:

Only make methods static if they have zero side-effects (ie only process the data passed as parameters in a deterministic fashion).

Do not couple classes, such as having setMixedState rely on accessing Node, pass the method what it needs.

Instead have a method like:

```<code>public static bool areNodesMixedState(Node[] nodes) {
    if (state of all instances are same) {
        return true;
    else
        return false
    }
}
</code>```

Body:
I would argue that no class should ever have static data. That lies the road to testing hell and non-threadsafe code.

Also:

Only make methods static if they have zero side-effects (ie only process the data passed as parameters in a deterministic fashion).

Do not couple classes, such as having setMixedState rely on accessing Node, pass the method what it needs.

Instead have a method like:

public static bool areNodesMixedState(Node[] nodes) {
    if (state of all instances are same) {
        return true;
    else
        return false
    }
}


问:
Distributing a modified OpenJDK class with a proprietary app
I want to distribute a Java class I borrowed from the GPLv2'ed OpenJDK and modified for my own needs as a part of my proprietary application.

The header at the top of the source file states (and I've preserved the same in the modified copy):

```<code>/*
 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 */
</code>```

Given that classpath exception is effective, would it be sufficient to distribute the modified *.java file packed alongside the corresponding *.class file in a JAR archive? Am I obliged to explicitly mention that "this product uses software distributed under GPLv2" somewhere in the THIRDPARTYLICENSEREADME.txt file?

Alternatively, would it be sufficient to create a GPLv2'ed (with classpath exception) Maven artifact, deploy a binary artifact together with my product, and give the link to the source artifact in the THIRDPARTYLICENSEREADME.txt file?

In either of the above cases, does it make any sense to additionally include something like

```<code>private static final String LICENSE = "This code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 only, as published by the Free Software Foundation.";
</code>```

in the source code, so that the license clause is additionally available in the binary class file(s)?

答: Either of your options is a valid way of complying with the license, but from a practical standpoint the second is preferable because it allows developers to work more easily with your modified code. As to including the license string in the binary, I'm not convinced I see the point - who's going to be looking for it there?</p>

ContentLicense: CC BY-SA 3.0


问:
What is a latency-bound and a memory-bound application in HPC?
I understand that in HPC hybrid systems, for instance a MIC architecture, main memory access is much slower than access to data in own cache or in the cache of another core.

I read that HPC MIC architecture works best with programs with streamed memory access, or negligeable memory access.

When do we say that w program is latency-bound or memory-bound? What is the difference? Are there some HPC architecture which are optimal for this kind of programs?

答:
An application is called memory-bound if it requires a lot of data from memory, so most of its execution time is spent reading and writing data.

Latency-bound can be thought as a subset of the memory-bound category and it occurs primarily when you don't retrieve too much data from memory at once, but you have to wait a lot to get the data close to the processor, in the upper levels of the memory hierarchy.

What developers usually do is to hide this latency through techniques such as software pipelining and data prefetching and to organize the instructions and operations of the applications in a way that the processor does not sit idle waiting for data.

I don't know if there's a specific architecture to tackle memory-bound applications but I know of techniques like the ones mentioned before and that the computer industry is trying to bridge the gap between memory and processor performance by bringing the data closer to the computation (SoC) or developing co-processors that can perform more autonomously from the host (and its memory).

There's a similar thread in this StackOverflow thread. Also, you can take a look a several papers like this one.


问:
What is ant build file and maven build file?
Can somebody please tell me in simple words what exactly is ant build file and maven build file?</p>

答:
They are XML files that describe how to build and package software (usually Java software).

Ant files are used by the Ant tool, which provides more flexible, free-form builds.  An Ant build file is much like a program in its own right (only encoded as verbose XML).

POM files are used by Maven, which has a different philosophy and imposes more structure.  The Maven approach is more declarative than Ant.  Writing a Maven build is less like writing a procedural program to build the software.

ContentLicense: CC BY-SA 2.5


答:
You can make it all static, but that will result in (arguably) unnecessary stronger coupling & dependency between the clients of the manager and the manager.

Thus, I agree with @DavidArno on avoiding static state as much as possible.

As @RobertHarvey noted, for logging, I use a static variable to hold a reference to a logger object because maintaining that reference everywhere you might want to add logging can be overly burdensome.

You already have the manager as an object, which is good, so if you need state for the manager, you should move it from the class to the object (by removing the static declaration).

Title: Should class with only static data need to be instantiated?

Body:
I have two classes. 1. Node 2. MixedStateManager

Node class:

Node class maintains the state of nodes in the system. One such data is state.

```<code>public class Node
   {
      private int state;

     public void setState(int s)
     {
      state = s;
     }

     public int getState()
     {
       return state;
     }
    }
</code>```

MixedStateManager:

MixedStateManager sees if all the nodes in the system are in the same state or not. If the nodes don't have the same value for state value, then the system is said to be in MixedState. I've a variable mixedState for the same. I've made it static because, if the value is changed by one instance of the class, then it should be visible by others. Another thing to note is MixedStateManager is called by different threads which change the value of state of nodes.

```<code>public class MixedStateManager{

public static boolean mixedState;

public boolean isMixedState(){
 return mixedState;
}

public void setMixedState(){
// get all instances of Node class;
   if state of all instances are same
     mixedState = true;
   else
     mixedState = false
}
}
</code>```

Question: As MixedStateManager has only one data which is static, does it make sense to instantiate this class and then set value. Or can I make all methods static too?

Responses will be appreciated.
Thanks


问:
Best practice for a REST-ful API where objects would naturally have a "/" in their identifier
I am designing a REST api for a document management system. To make the API more natural, I thought about using the natural identifier for a file, which is it's path (usually having forward slashes "/" in it), and not something like an artificial id such as a UUID.

Naturally, a user would identify a file by it's path:

```<code>/path/to/file.txt
</code>```

Unfortunately, this clashes with common, good API design.

This would work:

```<code>Retrieving a file: GET /api/v1/files/<path/to/file.txt>
</code>```

However, other methods you would like to have, will become a bit problematic:

```<code>Retrieving a file list of a folder: GET /api/v1/folders/<path/to/folder>/files
</code>```

My thoughts so far:

avoid unique identifiers with "/" in it entirely, and use an artificial UUID (such as Alfresco is using NodeId / NodeRefs). This would add another layer of abstraction to it, where a unique id is just not very natural from a business domain perspective

don't use the identifier in the url path but in a parameter (against good API design patterns)

(requesting the API users to replace the / with another character is of course also not an option)

Of course, files and folders as we know it from a file system, are naturally identified by it's path. In that particular case, one could argue that if someone wants to use the path as the identifier, than the correct way for doing:

```<code>Retrieving a file: GET /api/v1/files/<path/to/file.txt>
</code>```

would actually be:

```<code>Retrieving a file: GET /api/v1/folders/<path>/folders/<to>/files/<file.txt>
</code>```

if we want to be really correct here.

Update: I want to ask the community about best practices and experiences here - especially when Dropbox and Google Drive both use two different approaches (see first answer and comments below): DropBox is using the path while Google Drive is using IDs.

答:
You may wish to look into Google Drive API's way of handling this. In their case, paths are abstractions and files are selected by id.

A file is a resource.
It can belong to a folder, so it has a 'Parents' property. It can belong to multiple folders (either as a shared item, or to simulate soft-links), so it can have multiple 'Parents'.
It can be moved to a different "folder", in which case the actual resource does not change location -- its parents property is just changed. The filename is not used in the URI, because an id is unique and a string can have odd characters.


问:
If everything is supposed to be an object in Java (barring primative types), isn't this contradicting the point of static?
I often write code which makes an object and then use static methods in static classes to manipulate said object.

Am I missing the point of OOP? How do I know whether I'm thinking in the OOP mind set? I doubt I am...

答:
Yes, you are missing OOP principles in your coding. OOP is not about bearing primitive types, OOP is about having an object that has responsibilities(methods essentially).

GRASP Principles are a good start to learn where which method belongs in OOP.

In OOP you want to treat most instances as objects that have responsibilities and instance fields(instance specific variables). However, sometimes(and I mean sometimes) you would find a need to have a static class, which is perfectly valid as long as you really sure this class has no need for an instance. But before you settle down with creating one, think - "Am I missing an object?".

Your Functional Way:

```<code>var alice = new Person("Alice");

ChangeName(alice, "John");

// Somewhere in your static code
function ChangeName(Person person, string name) {
    person.name = name;
}
</code>```

OOP Way:

```<code>var alice = new Person("Alice");
alice.ChangeName("John");

public class Person {
    private _name;

    public Person(string name) {
        _name = name;
    }

    public void ChangeName(string name) {
        _name = name;
    }
}
</code>```

Body:
Yes, you are missing OOP principles in your coding. OOP is not about bearing primitive types, OOP is about having an object that has responsibilities(methods essentially).

GRASP Principles are a good start to learn where which method belongs in OOP.

In OOP you want to treat most instances as objects that have responsibilities and instance fields(instance specific variables). However, sometimes(and I mean sometimes) you would find a need to have a static class, which is perfectly valid as long as you really sure this class has no need for an instance. But before you settle down with creating one, think - "Am I missing an object?".

Your Functional Way:

var alice = new Person("Alice");

ChangeName(alice, "John");

// Somewhere in your static code
function ChangeName(Person person, string name) {
    person.name = name;
}

OOP Way:

var alice = new Person("Alice");
alice.ChangeName("John");

public class Person {
    private _name;

    public Person(string name) {
        _name = name;
    }

    public void ChangeName(string name) {
        _name = name;
    }
}


问:
Final steps of wrapping up a Python script into a program
I finished building a Python script containing eight functions which download files, extracts them, manipulate and analyze their data and then produce graphs and export them into PNG files.

The input files are located in a remote FTP site, but some intermediate files and the output PNG files as well are saved locally in the computer file system. There are 100 lines of code in total.

Currently, I first execute it so that the Python console gets the function definitions, then I call the eight functions one by one to get the results.

For instance, I call the downloading function to download the archive files, then I call the function that extracts those files and so on.
I am sure this isn't the best way to use a Python script, so I thought of asking here if anyone could provide the steps to get the most out of my script in terms of usage. I suspect a good way would be to turn the script into one or more modules, but I am not sure at all about that.

If possible, please provide details for two possible scenarios:

The script is only used by me and I do have Python installed and know how to use it

The script is used by other users who don't have Python installed

答:
Have the 8 function calls wrapped in

```<code>if __name__ == '__main__':
</code>```

Then you can call the script by running

```<code>python NAME_OF_YOUR_SCRIPT.py
</code>```

If you need to pass any variables in when running it, use the argparse module

Body:
Have the 8 function calls wrapped in

if __name__ == '__main__':

Then you can call the script by running

python NAME_OF_YOUR_SCRIPT.py

If you need to pass any variables in when running it, use the argparse module


答:
I would suggest implementing command line parameters and command line help using argparse.  The different functions could then be selected by command line options.  If others without python installed need to use your program, then I would package it as an executable using pyinstaller.

Pyinstaller can be used to build 3 possilbe executables: onefile, onedir or console. The console type doesn't need a gui and is a stand alone exe. The onefile is a stand alone exe and onedir is a typical installation with required component files like images and dlls and such in a folder.

Title: Final steps of wrapping up a Python script into a program

Body:
I finished building a Python script containing eight functions which download files, extracts them, manipulate and analyze their data and then produce graphs and export them into PNG files.

The input files are located in a remote FTP site, but some intermediate files and the output PNG files as well are saved locally in the computer file system. There are 100 lines of code in total.

Currently, I first execute it so that the Python console gets the function definitions, then I call the eight functions one by one to get the results.

For instance, I call the downloading function to download the archive files, then I call the function that extracts those files and so on.
I am sure this isn't the best way to use a Python script, so I thought of asking here if anyone could provide the steps to get the most out of my script in terms of usage. I suspect a good way would be to turn the script into one or more modules, but I am not sure at all about that.

If possible, please provide details for two possible scenarios:

The script is only used by me and I do have Python installed and know how to use it

The script is used by other users who don't have Python installed


问:
Endianness at bit level
I am learning the union and struct and I wrote the code below. What I do not understand is why the output is different when I change from a little endian to a big endian machine.

My understanding is that endianness is important when you have more than one byte. But I have only 8 bits.

This code is not portable at this time and I want to understand how to make it portable. I would like to avoid detecting the endianness or using bit shifting techniques. I know about htonX functions but I do not think that applies here.

```<code>    #include <stdio.h>

    int main()
    {
      typedef union {
        struct {
          unsigned char b0:1;
          unsigned char b1:1;
          unsigned char b2:1;
          unsigned char b3:1;
          unsigned char b4:1;
          unsigned char b5:1;
          unsigned char b6:1;
          unsigned char b7:1;
        } bits;
        unsigned char byte;
      } HW_Register;

      HW_Register reg;
      reg.byte = 3;

      printf("%d %d %d %d %d %d %d %d\n",
        reg.bits.b0,
        reg.bits.b1,
        reg.bits.b2,
        reg.bits.b3,
        reg.bits.b4,
        reg.bits.b5,
        reg.bits.b6,
        reg.bits.b7);

      printf("%d\n",reg.byte);
      printf("Size of reg.byte: %d\n", sizeof(reg.byte));
    }
</code>```

答:
The order in which bit fields are placed in an integer is independent of the order in which bytes are placed in an integer. Both are implementation details. That is generally not a problem, because memory is only byte addressable, and all hardware preserves the value of a byte during transmissions.

Yet, while bit and byte ordering are theoretically independent of each other, CPU documentations tend to number the bits in the same order as they number the bytes: X86 documentation will refer to the least significant bit as bit 0, while Power documentation will refer to the most significant bit as bit 0. Your compiler writers seem to have chosen the same numbering as the respective documentation.

As such, your only hope of achieving portability, is to do the bit fiddling yourself, defining a flags variable and a bunch of constants to set/mask the respective bits:

```<code>const unsigned char kBit0 = 1 << 0,
                    kBit1 = 1 << 1,
                    kBit2 = 1 << 2,
                    kBit3 = 1 << 3,
                    kBit4 = 1 << 4,
                    kBit5 = 1 << 5,
                    kBit6 = 1 << 6,
                    kBit7 = 1 << 7,

unsigned char reg = 3;
printf("%d %d %d %d %d %d %d %d\n",
    !!(reg & kBit0),
    !!(reg & kBit1),
    !!(reg & kBit2),
    !!(reg & kBit3),
    !!(reg & kBit4),
    !!(reg & kBit5),
    !!(reg & kBit6),
    !!(reg & kBit7));
</code>```

This numbers the bits in little endian fashion, irrespective of the machine. If you want big endian numbering, just define your constants accordingly.

Title: Endianness at bit level

Body:
The order in which bit fields are placed in an integer is independent of the order in which bytes are placed in an integer. Both are implementation details. That is generally not a problem, because memory is only byte addressable, and all hardware preserves the value of a byte during transmissions.

Yet, while bit and byte ordering are theoretically independent of each other, CPU documentations tend to number the bits in the same order as they number the bytes: X86 documentation will refer to the least significant bit as bit 0, while Power documentation will refer to the most significant bit as bit 0. Your compiler writers seem to have chosen the same numbering as the respective documentation.

As such, your only hope of achieving portability, is to do the bit fiddling yourself, defining a flags variable and a bunch of constants to set/mask the respective bits:

const unsigned char kBit0 = 1 << 0,
                    kBit1 = 1 << 1,
                    kBit2 = 1 << 2,
                    kBit3 = 1 << 3,
                    kBit4 = 1 << 4,
                    kBit5 = 1 << 5,
                    kBit6 = 1 << 6,
                    kBit7 = 1 << 7,

unsigned char reg = 3;
printf("%d %d %d %d %d %d %d %d\n",
    !!(reg & kBit0),
    !!(reg & kBit1),
    !!(reg & kBit2),
    !!(reg & kBit3),
    !!(reg & kBit4),
    !!(reg & kBit5),
    !!(reg & kBit6),
    !!(reg & kBit7));

This numbers the bits in little endian fashion, irrespective of the machine. If you want big endian numbering, just define your constants accordingly.


问:
Is it bad practice to use constant variables with global scope in C++?
So I was reading section 3.2 (One definition rule section) in the latest working draft of the C++ standard and came across this:

Every program shall contain exactly one definition of every non-inline
  function or variable that is odr-used in that program; no diagnostic
  required.

This struck me as strange with regard to the variable part, because if a header file has a global constant variable and function like so:

```<code>const int k = 10;

int foo(const int &i) {
    return 0;
}
</code>```

What if you mistakenly call foo(k)? It seems like this would result in UB because k has internal linkage (i.e. every translation unit would have its own definition of k, so there wouldnt be exactly one definition ... in that program). So basically if you have any const variable with global scope you'd have to remember not to call any functions which take its reference or address.

答:
The one definition rule in the standard is not "appear" only once, but that they have only a single definition. E.g. if the const were in a header file, it could appear in multiple translation units, yet they would all have the same single definition. As an aside, the linker could then fold them all into a single location (if a location is even required).

What if you mistakenly call foo(k)? It seems like this would result in UB...

There would be no undefined behavior here. The internal linkage is fine, it is const and there is only a single definition of it.

This (the const int i = 1234;) has a general use case for program wide constant values, e.g. const double pi = 3.1415, const std::size_t answer = 42; etc.

On a side note, you have specifically asked about the global variables, but placing constants and the like into namespaces are always a good way to avoid name clashes etc.

ContentLicense: CC BY-SA 4.0


答:
You're close, but not quite. The bad practice here is declaring global variables outside of a namespace.

```<code>namespace jucestain {
    const int k = 10;

    int foo(const int &i) {
        return 0;
    }
} // end namespace jucestain
</code>```

Once you put it in a namespace, foo(k) will only resolve to foo(10) if you have using namespace jucestain; at the top of your file. Otherwise you'd have to write jucestain::foo(jucestain::k), which is pretty hard to do by accident.

And even without a namespace, there's no undefined behavior because k still only has one definition per translation unit, and it's the translation units that matter (otherwise the header file containing k wouldn't have to be "included in multiple places" to begin with).

Title: Is it bad practice to use constant variables with global scope in C++?

Body:
So I was reading section 3.2 (One definition rule section) in the latest working draft of the C++ standard and came across this:

Every program shall contain exactly one definition of every non-inline
  function or variable that is odr-used in that program; no diagnostic
  required.

This struck me as strange with regard to the variable part, because if a header file has a global constant variable and function like so:

```<code>const int k = 10;

int foo(const int &i) {
    return 0;
}
</code>```

What if you mistakenly call foo(k)? It seems like this would result in UB because k has internal linkage (i.e. every translation unit would have its own definition of k, so there wouldnt be exactly one definition ... in that program). So basically if you have any const variable with global scope you'd have to remember not to call any functions which take its reference or address.

Body:
You're close, but not quite. The bad practice here is declaring global variables outside of a namespace.

namespace jucestain {
    const int k = 10;

    int foo(const int &i) {
        return 0;
    }
} // end namespace jucestain

Once you put it in a namespace, foo(k) will only resolve to foo(10) if you have using namespace jucestain; at the top of your file. Otherwise you'd have to write jucestain::foo(jucestain::k), which is pretty hard to do by accident.

And even without a namespace, there's no undefined behavior because k still only has one definition per translation unit, and it's the translation units that matter (otherwise the header file containing k wouldn't have to be "included in multiple places" to begin with).


问:
Development Workflow (Git/CI) in varied tech level .NET Shop
tl;dr: I need a development workflow for ASP.NET apps that works for the designer on a Mac, the content writers who don't have visual studio, and the C#/.NET developers (mostly me), such that we can have Continuous Integration and normal branching and merging.

Current workflow

A designer and a few content editors make tweaks to the site on our development/staging server (mostly HTML and CSS changes, plus occasional tweaks to some JSON files that define content). Once they like it, they ask my boss or me to commit and push those changes. The staging server actually hosts a cloned copy of our site's Git repository. We (my boss or I) connect to the clone and commit using git (SourceTree, actually), and push the change, which causes it to deploy through continuous integration.

Why This Sucks

It looks like my boss and I are the only ones committing.

If someone's SourceTree app is touching the repository on the dev site at the same time as you, it can prevent you from committing.

The development environment is substantively different in how it's deployed from the production environment. This effectively creates "builds on my machine" scenarios even though we're developing against a server.

We can't use pull requests and code review, which are really helpful when a less-technical person is submitting code.

We're working with one branch, so it's easy for the production source to get polluted with commits that are unstable in the production environment. That makes reverting dodgier.

Where to go next

I would much rather have a workflow where people clone the repository, create their own branch, make changes and commit them, and then do a pull request (or just merge) into the develop branch, and let the CI server do the deployment routine in the development environment first.

There's a couple issues with this:

Most of the people making changes need the instant feedback of editing files on a live webserver. We could have them build/run the apps on their machine, but...

Our designer lives in Mac OSX, and we don't have Visual Studio licences for him or the content writers. And why should we have to? They're not .NET devs!

After hacking with it for an hour or so, it looks like the freely available cross platform .NET dev tools like Visual Studio Code and Xamarin Studio won't work for the apps we most need this for (which run .NET 4.5.1 MVC).

Thoughts on how I might resolve the tension?

One compromise might be to leave the dev site as it is and make a second staging site that is deployed through CI. That doesn't entirely resolve everything (people would still be connecting to a shared git clone, which messes up SourceTree), but it gets us closer to where I'd like to be.

答:
I would much rather have a workflow where people clone the repository, create their own branch, make changes and commit them

Absolutely they should - in my mind this is the reason for a distributed version control. If they lack confidence in the tools, a little practice should take care of that.

We're working with one branch

I'm sure this is a hidden source of issues - don't. Use things like Gitflow (and alternatives) and allow each designer and developer to work on their own branches (or collaborate on feature branches). You can also explore scripted pushes to the origin to assist the designers with the workflow and speed up their turn around time on an issue.

We could have them build/run the apps on their machine, but...

Do you have access to test servers for them to run a build and test it?

I think that there is even more motivation here for their own cloned repositories linked to a CI build (TeamCity and Octopus type tools would help here) and deploy to the test servers.

I'm not sure the resources you have available, but you could also explore Azure based servers etc. Given they have Macs, you could also run VMs on them. I use VirtualBox based test machines much success. This also touches on the compromises you mention, it is all a case of balancing the resources currently available against any new additional expenses.

... we don't have Visual Studio licences for him or the content writers. And why should we have to? They're not .NET devs!

Again, this may be dependent on the size of the team etc. but it may be worth your while to explore the Visual Studio Community Edition (it is free, but there are limitations) that may be enough for the designers to use.


问:
Why is filesystem preferred for logs instead of RDBMS?
Question should be clear from its title. For example Apache saves its access and error logs in files instead of RDBMS no matter on how large or small scale it is being utilized.

For RDMS we just have to write SQL queries and it will do the work while for files we must decide a particular format and then write regex or may be parsers to manipulate them. And those might even fail in particular circumstances if great care was not paid.

Yet everyone seems to prefer filesystem for maintaining the logs. I am not biased against any of these methods but I would like to know why it is practiced like this. Is it speed or maintainability or something else?

答: Complexity. Adding RDBMS will increase complexity of whole system astronomically. And ability to manage complexity is the main thing which distinguishes programmers from source code producers.</p>


问:
Global counter using iOS and Parse?
I'm very new to Parse and trying to set up what is basically a voting app where I can collect data on how many times all users have pressed a button. I found some information on Atomic Increment Operations from Parse but I'm trying to have this feature be implemented as something like a singleton.

So if I wanted to do this for one user:

```<code>gameScore.incrementKey("score" byAmount:NSNumber(numberWithInt:10))
gameScore.saveInBackground()
</code>```

How would I get the same implementation where all users can update the same counter?

答:
I was actually able to solve my problem by using Firebase instead of Parse. I wanted real-time updating and Firebase provided that with ease. Here's my code for the View Controller:</p>

```<code>//
//  ViewController.swift
//  Firebase Test
//
//  Created by Cole Smith on 7/24/15.
//  Copyright (c) 2015 Cole Smith. All rights reserved.
//

import UIKit
import Firebase

class ViewController: UIViewController {

    var firebaseRef = Firebase(url: "[LINK TO FIREBASE]")
    var valueOfCounter: Int = 0

    @IBOutlet weak var counterLabel: UILabel!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func counterPressed(sender: AnyObject) {
        valueOfCounter++
        incrementCounterToFirebase(valueOfCounter)
    }

    func incrementCounterToFirebase(intForSubmission: Int) {
        firebaseRef.setValue(intForSubmission)

        // Read data and react to changes
        firebaseRef.observeEventType(.Value, withBlock: {
            snapshot in
            println("\(snapshot.key) -> \(snapshot.value)")
            self.counterLabel.text = "\(snapshot.value)"
        })
    }
}
</code>```

Title: Global counter using iOS and Parse?

Body:
I was actually able to solve my problem by using Firebase instead of Parse. I wanted real-time updating and Firebase provided that with ease. Here's my code for the View Controller:

//
//  ViewController.swift
//  Firebase Test
//
//  Created by Cole Smith on 7/24/15.
//  Copyright (c) 2015 Cole Smith. All rights reserved.
//

import UIKit
import Firebase

class ViewController: UIViewController {

    var firebaseRef = Firebase(url: "[LINK TO FIREBASE]")
    var valueOfCounter: Int = 0

    @IBOutlet weak var counterLabel: UILabel!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func counterPressed(sender: AnyObject) {
        valueOfCounter++
        incrementCounterToFirebase(valueOfCounter)
    }

    func incrementCounterToFirebase(intForSubmission: Int) {
        firebaseRef.setValue(intForSubmission)

        // Read data and react to changes
        firebaseRef.observeEventType(.Value, withBlock: {
            snapshot in
            println("\(snapshot.key) -> \(snapshot.value)")
            self.counterLabel.text = "\(snapshot.value)"
        })
    }
}


问:
How do I handle long running third party calls from backing up my message queue?
Here is my exact scenario.

I must make requests to a third party service

The service takes ~15 seconds to respond

It also has no webhooks or any call back mechanisms

These requests are not made constantly throughout the day, but in chunks

The requests to the third party service are made from a consumer that is pulling from a queue

using mass transit default impl & rabbitmq

All of the messages the product generates are currently put into one queue. The same queue with the calls to the third party service

There are currently 3 consumers, running 4 worker threads each for a total of 12 worker threads. This is the current maximum number of concurrent messages that can be handled at once

Throughout the day the message queue will receive ~100 of these messages that will back up the queue. All 12 worker threads will process the ~15s calls and the queue will begin to backup. This results in extreme loss in functionality. Delayed emails, etc.  It normally continues to grow the queue for ~30 minutes until it catches up

When this occurs the consumers are running at 0% CPU because they are all in thread waits.

The question I have is how do I setup my message queue and consumers so that they don't backup.  I am trying to prevent loss of functionality of the site for those 30 minute time blocks.  Anything goes.

Recap:

1 queue

~15 seconds tasks running at 0% cpu

12 consumer worker threads

Queue backs up and takes ~30 minutes to catch up

using mass transit default impl & rabbitmq

答:
There are a couple different ways you might deal with long running blocking tasks:

Increase the number of workers. As long as CPU utilization in staying low, additional workers will allow you to more quickly dispatch these long running service calls. More workers only becomes problematic at the point that some resource is under contention (cpu, memory, network, disk, etc). You mention in a comment that "worker threads are limited", but in an application with very long running blocking tasks it is not uncommon to throw 100s if not 1000s of worker threads at the problem.

If the problem is that long running tasks are starving other work sent to the same queue, you can prioritize the messages. This way workers will always pickup the next highest priority task. However, if your queue depth keeps growing because you cannot process messages fast enough you'll need more workers.

Another approach to reducing starvation would be to send the messages to different queues which have their own workers. This will offer the lowest latency for your non-blocking tasks and make it easier to balance resource usage when tuning the number of workers.


问:
Where to put the domain in MVCS
From what I've read and understand MVCS (Model-View-Controller-Store) is a design pattern that lets you do the following:

View - Application view, what the user will see.

Controllers - Manages the views and calls the models.

Model - Business logic.

Stores -  Calls to db for CRUD operations retrieving and putting data.

Now where should I put the domain in this design? By domain, I mean the actual classes that represents the objects from db for example a user. Should they be inside the model or in a different layer?

答: Unless you come up with some specific code that changes my mind, I'm going to say that MVCS is just a slight variation on MVC that makes it clearer that the Business Domain lives in the Model, and is technically separate from the data Store.  MVC just includes S (the data store) as part of the Model, but the business domain always lives there.</p>

Title: Where to put the domain in MVCS


问:
Why don't RDBMSes return joined tables in a nested format?
For example, say I want to fetch a User and all of his phone numbers and email addresses. The phone numbers and emails are stored in separate tables, One user to many phones/emails. I can do this quite easily:

```<code>SELECT * FROM users user
    LEFT JOIN emails email ON email.user_id=user.id
    LEFT JOIN phones phone ON phone.user_id=user.id
</code>```

The problem* with this is that it's returning the user's name, DOB, favorite color, and all the other information stored in the user table over-and-over again for each record (users×emails×phones records), presumably eating up bandwidth and slowing down the results.

Wouldn't it be nicer if it returned a  single row for each user, and within that record there was a list of emails and a list of phones? It would make the data much easier to work with too.

I know you can get results like this using LINQ or perhaps other frameworks, but it seems to be a weakness in the underlying design of relational databases.

We could get around this by using NoSQL, but shouldn't there be some middle ground?

Am I missing something? Why doesn't this exist?

* Yes, it's designed this way. I get it. I'm wondering why there isn't an alternative that is easier to work with. SQL could keep doing what it's doing but then they could add a keyword or two to do a little bit of post-processing that returns the data in a nested format instead of a cartesian product.

I know this can be done in a scripting language of your choice, but it requires that the SQL server either sends redundant data (example below) or that you to issue multiple queries like SELECT email FROM emails WHERE user_id IN (/* result of first query */).

Instead of having MySQL return something akin to this:

```<code>[
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "email": "johnsmith45@gmail.com",
    },
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "email": "john@smithsunite.com",
    },
    {
        "name": "Jane Doe",
        "dob": "1953-02-19",
        "fav_color": "green",
        "email": "originaljane@deerclan.com",
    }
]
</code>```

And then having to group on some unique identifier (which means I need to fetch that too!) client-side to reformat the result set how you want it, just return this:

```<code>[
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "emails": ["johnsmith45@gmail.com", "john@smithsunite.com"]
    },
    {
        "name": "Jane Doe",
        "dob": "1953-02-19",
        "fav_color": "green",
        "emails": ["originaljane@deerclan.com"],
    }
]
</code>```

Alternatively, I can issue 3 queries: 1 for the users, 1 for the emails, and 1 for the phone numbers, but then the email and phone number result sets need to contain the user_id so that I can match them back up with the users I previously fetched. Again, redundant data and needless post-processing.

答:
The concept of relational closure basically means that the result of any query is a relation which can be used in other queries as if it was a base table. This is an powerful concept because it makes queries composable.

If SQL allowed you to write queries which output nested data structures, you would break this principle. A nested data structure is not a relation, so you would need a new query language, or complex extensions to SQL, in order to query it further or to join it which other relations.

Basically you would build a hierarchical DBMS on top of a relational DBMS. It will be much more complex for a dubious benefit, and you lose the advantages of a consistently relational system.

I understand why it would sometimes be convenient to be able output hierarchically structured data from SQL, but the cost in the added complexity throughout the DBMS to support this is definitely not worth it.


问:
What would happen if two different commits in one git repo had the same hash?
I know this has been said to be pretty much statistically impossible but that's a different question. What would be the consequences if against all odds, this did occur? </p>

答:
If two files have the same hash, then git assumes they are the same file. For example if you change a file in such a way that the hash stays the same, git will not realise that the file has changed and "git status" will not report it. Now if you change a file twice, so that the hash changes from A to X and back to A, and you committed both changes, and I pull the repo while having the old file with hash A, then it's most likely that I won't get the change because git thinks I've got it already. </p>

<p>Of course with 160 bit hash, it's much more likely that one meteorite hits the server containing the master and destroys it with all backups, while another one hits you, destroys your computer and kills you just before you try to commit.
</p>

Body:
If two files have the same hash, then git assumes they are the same file. For example if you change a file in such a way that the hash stays the same, git will not realise that the file has changed and "git status" will not report it. Now if you change a file twice, so that the hash changes from A to X and back to A, and you committed both changes, and I pull the repo while having the old file with hash A, then it's most likely that I won't get the change because git thinks I've got it already.

Of course with 160 bit hash, it's much more likely that one meteorite hits the server containing the master and destroys it with all backups, while another one hits you, destroys your computer and kills you just before you try to commit.


答:
As an example, floating-point arithmetic often has high throughput, but also high latency. For example, you might be able to start two multiplications every cycle, but it might take five cycles until the result of a multiplication is available. The first is called throughput (two per cycle), the second is latency.

If you perform calculations so that one operation is dependent on the previous one, you may become latency bound. Say you calculate (x0 + y0) * (x1 + y1) * (x2 + y2) * ... If you do this in a naive way, then each multiplication can only start 5 cycles after the previous one, so you end up with 0.2 multiplications and 0.2 additions per cycle even though the processor could do much more work per cycle. That's code that is latency bound.

Hyperthreading is very useful for latency bound code, because it's very easy for the processor to handle two latency bound threads at the same speed as one. If your code is limited by throughput, hyper threading doesn't help one bit. Basically, the worse the code, the more help do you get from hyper threading.

Title: What is a latency-bound and a memory-bound application in HPC?

Body:
I understand that in HPC hybrid systems, for instance a MIC architecture, main memory access is much slower than access to data in own cache or in the cache of another core.

I read that HPC MIC architecture works best with programs with streamed memory access, or negligeable memory access.

When do we say that w program is latency-bound or memory-bound? What is the difference? Are there some HPC architecture which are optimal for this kind of programs?


问:
How can I show and hide a single field across my web application through a checked value?
Let's say I have a field called "FooName" and I have "FooName" in several places across my web application (ASP.NET MVC4). I have a check box that allows me to turn "FooName" on and off across the application. Currently, I have access to the checked value (I can grab the saved value from the database) but I'm not sure how to show/hide "FooName" text display across the application? </p>

<p>Is there a utility class I can use or make? Should I use a regex to parse all my web pages? What should I do? </p>

答:
I think you are misunderstanding the MVC pattern a bit.

One of the purposes of MVC pattern is to divide your application into "layers".

The Model-layer which contains "data"

The View-layer which represents the "data" (the Model)

The Controller-layer which handles user input and modifies "data" (the Model)

The Model does not tell the View how the data should be presented.

The View interpretes the Model and presents the data.

This means that the Model may contain information about how data the may be presented by using properties or fields. But ultimately it's up to the View.

In your case (for example) you may add the property – Model.DisplayFooName. But this in itself will not change how your View looks because the View has not been altered. Your Model has a shiny new property that your View may use to change the way the data in your Model is presented. In essence the Model is powerless when it comes to the View. Your View decides how your Model-data should be presented, and you cannot make changes only to your Model, to change the way the data is presented in the View.

TL;DR:

Ultimately, changes to your Model cannot change how View decides to present data in it.

To tackle the actual problem:

If you have a global setting to toggle the display of your FooName, you can create a HtmlHelper to speed up the process of toggling it. Instead of having to write something like...:

```<code>if (GlobalSettings.DisplayFooName)
{
    <strong>@Model.FooName</strong>
}
</code>```

... every time you want to toggle it,

you can create helper that allows you to just simply write

```<code>@Html.PrintFooName(Model.FooName)
</code>```

Or even..:

```<code>@Html.PrintFooName()
</code>```

...since the HtmlHelper contains the model-data.

This could be sped up by using Find & Replace.

Body:
I think you are misunderstanding the MVC pattern a bit.

One of the purposes of MVC pattern is to divide your application into "layers".

The Model-layer which contains "data"

The View-layer which represents the "data" (the Model)

The Controller-layer which handles user input and modifies "data" (the Model)

The Model does not tell the View how the data should be presented.

The View interpretes the Model and presents the data.

This means that the Model may contain information about how data the may be presented by using properties or fields. But ultimately it's up to the View.

In your case (for example) you may add the property – Model.DisplayFooName. But this in itself will not change how your View looks because the View has not been altered. Your Model has a shiny new property that your View may use to change the way the data in your Model is presented. In essence the Model is powerless when it comes to the View. Your View decides how your Model-data should be presented, and you cannot make changes only to your Model, to change the way the data is presented in the View.

TL;DR:

Ultimately, changes to your Model cannot change how View decides to present data in it.

To tackle the actual problem:

If you have a global setting to toggle the display of your FooName, you can create a HtmlHelper to speed up the process of toggling it. Instead of having to write something like...:

if (GlobalSettings.DisplayFooName)
{
    <strong>@Model.FooName</strong>
}

... every time you want to toggle it,

you can create helper that allows you to just simply write

@Html.PrintFooName(Model.FooName)

Or even..:

@Html.PrintFooName()

...since the HtmlHelper contains the model-data.

This could be sped up by using Find & Replace.


问:
Difference between '\n' and '\r\n'
Yes yes, I am aware that '\n' writes a newline in UNIX while for Windows there is the two character sequence: '\r\n'. All this is very nice in theory, but my question is why? Why the carriage return character is extra in Windows? If UNIX can do it in \n why does it take Windows two characters to do this?

I am reading David Beazley's Python book and he says:

For example, on Windows, writing the
  character '\n' actually outputs the
  two- character sequence '\r\n' (and
  when reading the file back, '\r\n' is
  translated back into a single '\n'
  character).

Why the extra effort?

I will be honest. I have known the difference for a long time but have never bothered to ask WHY. I hope that is answered today.

Thanks for your time.

答:
Historically, line feed meant that the platen - the roller on which you type - rotated one line, causing text to appear on the next line... but in the next column.

Carriage return meant "return the bit with which you type to the beginning of the line".

Windows uses CR+LF because MS-DOS did, because CP/M did, because it made sense for serial lines.

Unix copied its \n convention because Multics did.

I suspect if you dig far enough back, you'll find a political disagreement between implementors!

(You left out the extra fun bit, where Mac convention is (or used to be) to just use CR to separate lines. And now Unicode also has its own line separator, U+2028!)

Title: Difference between '\n' and '\r\n'


问:
Does auto make C++ code harder to understand?
I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand—every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

```<code>auto x = GetX();
</code>```

Than:

```<code>someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();
</code>```

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder—does auto make C++ code harder to understand?

答:
There are several reasons why I dislike auto for general use:

You can refactor code without modifying it.  Yes, this is one of the things often listed as a benefit of using auto.  Just change the return type of a function, and if all of the code that calls it uses auto, no additional effort is required!  You hit compile, it builds - 0 warnings, 0 errors - and you just go ahead and check your code in without having to deal with the mess of looking through and potentially modifying the 80 places the function is used.

But wait, is that really a good idea?  What if the type mattered in a half dozen of those use-cases, and now that code actually behaves differently?  This also can implicitly break encapsulation, by modifying not just the input values, but the behavior itself of the private implementation of other classes that call the function.

1a.  I'm a believer in the concept of "self-documenting code".  The reasoning behind self-documenting code is that comments tend to become out-of-date, no longer reflecting what the code is doing, whereas the code itself - if written in an explicit manner - is self-explanatory, always stays up to date on its intent, and won't leave you confused with stale comments.  If types can be changed without needing to modify the code itself though, then the code/variables themselves can become stale.  For example:

auto bThreadOK = CheckThreadHealth();

Except the problem is that CheckThreadHealth() at some point was refactored to return an enum value indicating the error status, if any, instead of a bool.  But the person who made that change missed inspecting this particular line of code, and the compiler was of no help because it compiled without warnings or errors.

You may never know what the actual types are.  This is also often listed as a primary "benefit" of auto.  Why learn what a function is giving you, when you can just say, "Who cares?  It compiles!"

It even kind of works, probably.  I say kind of works, because even though you're making a copy of a 500 byte struct for every loop iteration, so you can inspect a single value on it, the code is still completely functional.  So even your unit tests don't help you realize that bad code is hiding behind that simple and innocent-looking auto.  Most other people scanning through the file won't notice it on first glance either.

This also can be made worse if you don't know what the type is, but you choose a variable name that makes a wrong assumption about what it is, in effect achieving the same result as in 1a, but from the very beginning rather than post-refactor.

Typing the code when initially writing it isn't the most time consuming part of programming.  Yes, auto makes writing some code faster initially.  As a disclaimer, I do type > 100 WPM, so maybe it doesn't bother me as much as others.  But if all I had to do was write new code all day, I'd be a happy camper.  The most time consuming part of programming is diagnosing hard-to-reproduce, edge-case bugs in the code, often which result from subtle non-obvious problems - such as the kind overuse of auto is likely to introduce (reference vs. copy, signed vs. unsigned, float vs. int, bool vs. pointer, etc.).

It seems obvious to me that auto was introduced primarily as a workaround for terrible syntax with standard library template types.  Rather than try to fix the template syntax that people are already familiar with - which may also be nearly impossible to do because of all of the existing code it could break - add in a keyword that basically hides the problem.  Essentially what you might call a "hack".

I actually don't have any disagreement with the use of auto with standard library containers.  It's obviously what the keyword was created for, and functions in the standard library are not likely to fundamentally change in purpose (or type for that matter), making auto relatively safe to use.  But I would be very cautious about using it with your own code and interfaces that may be much more volatile, and potentially subject to more fundamental changes.

Another useful application of auto that enhances the capability of the language is creating temporaries in type-agnostic macros.  This is something you couldn't really do before, but you can do it now.

OwnerDisplayName: Felics


问:
Can a model have itself as a foreign key?
I am doing a coding project in rails. I have a user model, and I want to add a "spouse_id" to it (which would reference other users). Can a model reference itself in a foreign key?</p>

答:
Thanks to the comments:

Then the answer is "of course." It's called a self-join.


问:
Protecting a new file format?
I'm wondering when you create a new file format, what are the options to protect said format from being used without consent? I don't think you can patent a file format based off what I have read so far. So not sure if anyone has any idea on this.

I know this might seem like a weird question given that file formats are used by anyone and everyone. But if I was to create a file format that acted as an application in a sense how would I protect this?

答:
You really can't.

If you make the file format sufficiently painful to deal with and avoid providing documentation for the actual file format, you can make the logical choice for the vast majority of people to use your API to interact with the file.  Nothing prevents someone from going to the effort of reverse engineering the file format and interacting with raw files themselves but if it's much easier to use your API, that's the path most people will take.  And if you release new versions constantly that make subtle tweaks that break existing code that isn't using your API, you can ratchet up the pain anyone would have dealing with your raw files directly.

This is basically (intentionally and unintentionally) the path Microsoft walked with the various binary Office file formats.  They were sufficiently complex that if a competing office suite tried to read or write anything more than the simplest file, you'd inevitably find that something was lost in translation.

Of course, if you do something like this, particularly intentionally, you'll incur the wrath of a large fraction of developers.  In the vast, vast majority of cases, if you're creating a file format, you'll have way more problems convincing people to support it than you will in preventing people from manipulating your proprietary files.  Having people write code that can interact with your files easily is generally an important driver of your file format's success.  Alienating the people you need to generate popularity for your file format would almost always be a bad idea.

Title: Protecting a new file format?


答:
You cannot protect a file format legally.  However, if the process to create or use the file format is sufficiently novel, that process can potentially be patented.

For example, the .gif file format was not protected in any way shape or form.  However, the LZW algorithm used to compress or decompress gifs was assigned patents.

It mattered little until they started enforcing their patents.  The act of enforcing them turned .gif from one of the 2 mainstay image formats of the internet, into a non-starter format which is now only used because gif89a allows some rudimentary animation without a plugin.  .png has taken over the rest of the .gif market.  The patents are now all expired, but it's too late for the format.

Title: Protecting a new file format?

Body:
I'm wondering when you create a new file format, what are the options to protect said format from being used without consent? I don't think you can patent a file format based off what I have read so far. So not sure if anyone has any idea on this.

I know this might seem like a weird question given that file formats are used by anyone and everyone. But if I was to create a file format that acted as an application in a sense how would I protect this?


答:
As far as I'm aware this harks back to the days of typewriters.

\r is carriage return, which is what moves where you are typing on the page back to the left (or right if that is your culture)

\n is new line, which moves your paper up a line.

Doing only one of these on a typewriter would put you in the wrong place to start writing a new line of text.

When computers came about I guess some people kept the old model, but others realised that it wasn't necessary and encapsulated a full newline as one character.

Title: Difference between '\n' and '\r\n'

Body:
Yes yes, I am aware that '\n' writes a newline in UNIX while for Windows there is the two character sequence: '\r\n'. All this is very nice in theory, but my question is why? Why the carriage return character is extra in Windows? If UNIX can do it in \n why does it take Windows two characters to do this?

I am reading David Beazley's Python book and he says:

For example, on Windows, writing the
  character '\n' actually outputs the
  two- character sequence '\r\n' (and
  when reading the file back, '\r\n' is
  translated back into a single '\n'
  character).

Why the extra effort?

I will be honest. I have known the difference for a long time but have never bothered to ask WHY. I hope that is answered today.

Thanks for your time.


答:
If you define a file format, you should on the contrary publicly document its specification, since a file format is a mean of communicating data between software and people.

I am not the only one in avoiding closed file formats. If I used some of them, I would be trapped into the product needing them. In some contexts and many organizations, using an undocumented proprietary file format would be frowned upon or forbidden. In France, the Ayrault government issued a decree favoring open standards (and preferably free software). AFAIK the European Commission is doing something similar.

So to be successful, you don't want to "protect" your file format, you want to specify your file format as well as possible in a public specification so that it becomes a de facto standard (used by competitors).

And you cannot legally forbid reverse-engineering your format (at least not in Europe ; AFAIU reverse-engineering is explicitly legal in Europe if done for interoperability reasons, but IANAL).

Hiding your file format would probably make it a world-wide failure; nobody would use it (which of course is the ultimate protection, but are you really wanting that?).

Title: Protecting a new file format?


问:
Best way to consume REST service within Servlet on same server?
I'm builiding a web app and I'm implementing a RESTful API to expose the server to all sort of clients.

On the web client I want to have both server rendering and client rendering. The majority of the layout will be server rendering and changes/updates will be through javascript.

In order to serve the HTML from the server I need to consume the REST API, so I was thinking on putting the logic on servlets which will interact with the REST API and then print the result using JSP.

What I would like to know is:

What is the best way to do consume the REST services in the servlets? I mean they are on the same server so should I still implement a REST client on the servlets?

Won't that create too many http requests? Client -> Servlet -> REST API, isn't there a way to do it in a more direct way?

答:
Calling your RESTful services will result in more HTTP connections (and also threads) open on your server. If you are not careful and manage the HTTP client correctly you could leak connections. If the service interface changes, how will you know? Will you remember to update your servlets? Developers would expect the compiler to give some errors. All of this would mean both a performance and maintenance overhead.

What you want to do is separate the contract (RESTful invocation and representation) from the service logic see SOA Service Pattern. This allows you to create many kinds of client representations (rest, static web/jsp, soap, Ejb/rmi, etc) while reusing the same logic throughout.


答:
You raise Apache specifically, so I will discuss this in detail.

Apache can be configured to log to a database, although it requires an external plugin to do so. Using such a plugin can make log analysis easier, but only if you intend to write your own log analysis software. Standard off-the-shelf log analysers assume your logs are in files, so you won't be able to use these.

When I was doing this, I also experienced reliability issues: if the database server's write buffer filled up (which can happen with mysql if you use up your file system quota for the user it runs under) it starts queuing up queries until they are able to proceed, at which point Apache starts waiting for it to finish, resulting in hung requests to your web site.

(This issue may now be fixed, of course - it was many years ago that I did this)

Title: Why is filesystem preferred for logs instead of RDBMS?

Body:
Question should be clear from its title. For example Apache saves its access and error logs in files instead of RDBMS no matter on how large or small scale it is being utilized.

For RDMS we just have to write SQL queries and it will do the work while for files we must decide a particular format and then write regex or may be parsers to manipulate them. And those might even fail in particular circumstances if great care was not paid.

Yet everyone seems to prefer filesystem for maintaining the logs. I am not biased against any of these methods but I would like to know why it is practiced like this. Is it speed or maintainability or something else?


问:
What is the different between web site and web application?
I have a friend who works in financing. His company wants a website for the company. He is really confused about a web site and a web app, and I don't really understand them enough to explain. Can you all give me some clear explanation about it?</p>

答:
Web site is the most generic term for "something visible to people using a web browser and accessible via a URL". This can be just a collection of static HTML files and images, but nowadays that is pretty rare.

A Web application is a web site with (more or less complex) functionality behind it, i.e. what the user sees is generated by some sort of program, which also reacts to user actions, i.e. the user can do more than just click on links.

Arguably, "web application" implies also that the site's does something more complex than just displaying information with some added convenience features (such as search, comments or user ratings), i.e. some people might say that a web site based on a CMS such as Wordpress isn't really a web application. But the terms are somewhat fluid.


答:
The web console which are used as the addons to perform programmed tasks for some web or internet pages are 'web apps' while the pages we see in our web browser which physically shows in the devices after we hit enter to an URL are webpage.

The web app may be vary from extension file format

But webpage are in .htm, .html, .asp, .aspx, etc format.

Title: What is the different between web site and web application?

Body: I have a friend who works in financing. His company wants a website for the company. He is really confused about a web site and a web app, and I don't really understand them enough to explain. Can you all give me some clear explanation about it?</p>


问:
What should JITed bytecode do exactly?
I'm working on a VM (and a scripting language for it) that I plan to implement JITing for. I'm only working on the "plumbing" of it now, but I don't want the JIT compiler to be an afterthought. However, while I understand the fundamentals of it, I'm a bit confused on what exactly the JIT should do.

There are two ways I could think of it being implemented:

Translate the bytecode into "proper" x86 just like any compiler would, thus eliminating the interpreter/VM part.

Translate the bytecode into x86 that calls VM functions to tell it what to do thus eliminating the interpreter's opcode decoding step and going straight to calling the internal VM functions.

The first method would be difficult to implement simply because it requires knowledge on not only building a full-blown compiler, but being able to compile a high-level language that relies normally on VM functionality to be compiled into native code.

The second method would be much simpler to implement as you're not actually compiling the program, you're just dynamically creating a list of C function calls (to the internal VM) with corresponding operands with x86 instructions to call in the same order that would've otherwise require an interpreter to "decode".

However, while the second clearly seems more sane to implement, I'm not too sure how much more (or less) it would effect the performance of the program. What direction should I aim for? Any notable pros and cons?

答:
You're right that method 2 won't give you a huge performance boost over a simple bytecode interpreter loop. The real gains are to be made by using method 1. That said, method 1 isn't as hard these days as it used to be, as there are libraries that can help.

One interesting approach that should be relatively east and might give good performance is to use LLVM to implement method 2, and use an existing LLVM compiler (eg clang) to compile the functions you're calling to LLVM code rather than native - then run its optimization steps over the result, particularly the function call inliner. This should result in reasonably good native code without much in the way of complexity.

Title: What should JITed bytecode do exactly?


答:
I would recommend using some existing JIT library, like GCCJIT, libjit, LLVM, asmjit, ... You could even consider translating your bytecode to C, dynamically compiling that C code into a shared library at runtime, and dlopen-ing that plugin etc...

You'll need to understand some compilation and optimization techniques to do so (in particular because your bytecode might be semantically far from the internal representations needed by the JIT library that you'll use).

Title: What should JITed bytecode do exactly?

Body:
I'm working on a VM (and a scripting language for it) that I plan to implement JITing for. I'm only working on the "plumbing" of it now, but I don't want the JIT compiler to be an afterthought. However, while I understand the fundamentals of it, I'm a bit confused on what exactly the JIT should do.

There are two ways I could think of it being implemented:

Translate the bytecode into "proper" x86 just like any compiler would, thus eliminating the interpreter/VM part.

Translate the bytecode into x86 that calls VM functions to tell it what to do thus eliminating the interpreter's opcode decoding step and going straight to calling the internal VM functions.

The first method would be difficult to implement simply because it requires knowledge on not only building a full-blown compiler, but being able to compile a high-level language that relies normally on VM functionality to be compiled into native code.

The second method would be much simpler to implement as you're not actually compiling the program, you're just dynamically creating a list of C function calls (to the internal VM) with corresponding operands with x86 instructions to call in the same order that would've otherwise require an interpreter to "decode".

However, while the second clearly seems more sane to implement, I'm not too sure how much more (or less) it would effect the performance of the program. What direction should I aim for? Any notable pros and cons?


问:
What do you do when you feel stuck on a project?
When I am in a code or design rut, I tend to find a non-dev coworker to discuss the problem with. It forces me to explain the problem in great detail and I'll usually find something I missed in the process.

What are your "unsticking" methods?

答:
Good sleep helps.

Sometimes I have been stuck on a problem and worked out the solution in my head while I sleep. I literally wake up with an aha solution. Sometimes you just need to reset your brain.


答:
The reason the conventions hold on their various systems (\n on unix type systems, \r\n on Windows, etc) is that once you've picked a convention you CAN'T change it without breaking a bunch of people's files. And that's generally frowned upon.

Unix-type systems were developed (very early days) using various models of teletype, and at some point someone decided the equipment should carriage return when it did a line feed.

Windows came from DOS, so for Windows the question really is: Why did DOS use this cr/lf sequence? I'm guessing it has something to do with CP/M, where DOS has some of it's roots. Again, specific models of teletype may have played a role.

Title: Difference between '\n' and '\r\n'


问:
Publishing a crate containing both lib.rs and main.rs files
In the Importing External Crates section of the Rust book the author creates main.rs file in an already existing library project. I randomly picked up a bunch of crates from crates.io, examined their structure and did not find any project containing both lib.rs and main.rs files. So i'm wondering if it is common to have both files in a library project hosted at crates.io or it should be considered a poor style?

To be more clear, I'm asking about developing a library designed to share with the community, not about an executable with a few days lifecycle.
I'm aware of Cargo's testing capabilities, so the purpose of main.rs I want to add to the library is not testing. A good example of how my main.rs in the library crate should relate to the library is how curl command line tool is related to libcurl library. To my mind it is convenient to have a project for which cargo build builds an executable by default but all the functionality is available for importing as a library.

答:
The easiest way to create a crate which contains a binary and library (such as your curl and libcurl example) is to create a folder src/bin in your project and place your a file that will serve as the entry point to your binary there (must contain a fn main() {}). In your example this would be src/bin/curl.rs.

All of your "library" code would go in src/lib.rs (and additional modules).

Finally, you'd add a section to your Cargo.toml describing where to find the binary.

```<code>[[bin]]
name = "curl"
</code>```

So the project layout would look like this (assuming we named the project curl-rs with cargo):

```<code>$ tree curl-rs
curl-rs
├── bin
│   └── curl.rs
├── Cargo.toml
└── src
    └── lib.rs

2 directories, 3 files
</code>```

In order to use the functionality defined in our lib.rs it's the same as if using an external dep:

```<code>// in src/bin/curl.rs
extern crate curl;

fn main() {
    // Do stuff
}
</code>```

Compiling this project will place a statically linked binary curl in target/{debug,release} as well as a libcurl.rlib which will be used if someone simply uses this project as a dep from something like crates.io.

Body:
The easiest way to create a crate which contains a binary and library (such as your curl and libcurl example) is to create a folder src/bin in your project and place your a file that will serve as the entry point to your binary there (must contain a fn main() {}). In your example this would be src/bin/curl.rs.

All of your "library" code would go in src/lib.rs (and additional modules).

Finally, you'd add a section to your Cargo.toml describing where to find the binary.

[[bin]]
name = "curl"

So the project layout would look like this (assuming we named the project curl-rs with cargo):

$ tree curl-rs
curl-rs
├── bin
│   └── curl.rs
├── Cargo.toml
└── src
    └── lib.rs

2 directories, 3 files

In order to use the functionality defined in our lib.rs it's the same as if using an external dep:

// in src/bin/curl.rs
extern crate curl;

fn main() {
    // Do stuff
}

Compiling this project will place a statically linked binary curl in target/{debug,release} as well as a libcurl.rlib which will be used if someone simply uses this project as a dep from something like crates.io.


答:
A "web application" is a computer program that accepts web based requests (usually with HTTP/HTTPS) and generates output based on business logic.

A "web site" is a collection of pages that are somehow grouped together (often by domain name).

A "web site" may be composed of one or more "web apps".  A web site may also contain "flat files", which are not part of a web app, but just kind of stand alone.

Generally, when one talks about web apps, you're talking about the program that creates the site, or at least part of the site.  When you're talking about a web site, you're talking about the user's experience when they point their web browser to your domain.

Edit:
It occurs to me that you could also have a Web App that is "just a tool". An application that is used by a business or individual to do a set of tasks.  Its called "web" because the primary interface into it is a web-browser, but I wouldn't call it a "site", because it is specifically an application to do a specific thing.


问:
Strategy for Website Talking to API on Same Server
I have a RESTful API that allows retrieval of data through requests such as GET http://example.com/users/id/1 (Coded following this tutorial).

The code igniter controller looks like this:

```<code>class Example_api extends REST_Controller {

function user_get()
{
    $data = array('returned: '. $this->get('id'));
    $this->response($data);
}
</code>```

This API was written specifically for the reason that I should be able to access the same code logic from the web frontend as well as mobile apps etc. Now, the mobile app is easy to write but I want to find the strategy for using the API from the web site. The website is essentially sitting on the same server that offers this API and it does not seem right to me to make an HTTP request to the API from code and go through the network again.

So, the question is, how do I use the API from the php code in the same site without going through the network.

答: For the moment, as 9000 said, I can't see any real reason to take another approach. However, if design is your main goal, perhaps you should separate your web app from your API server? That way both your web app and your mobile and native apps connect to a uniform REST implementation. Speed at that point is all on your API server, and REST pretty much expects HTTP otherwise it wouldn't be as simple as REST.</p>


问:
Define an object with the interface as a type instead of class name
I try to practice with the design patterns and explore one of the possible implementations of the Observer Design Pattern in Java. I paid attention, that in this example the object is defined with the interface type and not the class one:

```<code>//user-made observer interface
public interface Observer {…}

//observer class to watch after subject objects
public class MyTopicSubscriber implements Observer {…}

//subject class to notify observer of any updates
public class MyTopicPublisher implements Subject {
     private List<Observer> observers;
}
</code>```

As you can see, the list observers is a type of Observer, which is an interface. Why decided a programmer, in this case, to use the interface as a type for the list of objects and not the class name MyTopicSubscriber?

The full code example published above:

http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial

Update to moderators:

In this question, I don't ask what exactly the interface is, but why it worths to use the interface as a type of collection's objects. Thus, my question can't be considered as a possible duplicate of the proposed question, which deals with basic explanation of what interfaces in programming are, my question is more narrow and specific.

Thanks.

答:
That's exactly what interfaces are for. The programmer doesn't care what types of objects might be in the list, as long as they provide the method calls expected of any Observer. This way, your list can contain instances of MyTopicSubscriber, MyFileSystemChangeSubscriber, MyMailboxSubscriber, etc. (these are fictitious titles, of course).

By using interfaces in your design, you allow yourself more flexibility in your model, because you now have multiple types of objects being observed, with a simple Observable interface. In a purely inheritance-based design, everything Observable would have to be derived from a single class, even classes that have nothing in common with each other, except that you want to Observe them.

This kind of interface-driven design lends itself very nicely to unit testing, as you can now mock-up any object and insert it into your list to generate the types of behaviors you want to test. As long as it's Observable, and provides the methods expected of any Observable, your code won't care that it's a specialized test object, rather than a regular object from your application.


问:
Is there a relationship between a data source (JSON) and the Model that consumes it?
I have put together a large quiz data structure. It is in JSON format but I guess it could be XML etc.  It may look something like this simplified:

```<code>{
   "quiz":{

       "title": "Welcome to Quiz"
       "entries": [

            {

                "question": "programmers.so is awesome?"
                "answers": [
                     {
                         "answer": "Yes"
                     },
                     {
                         "answer": "Yes!"
                     }
                ]
            }
       ]
    }
}
</code>```

I now need to make an application which can consume this data. I am going to start by getting it loaded and putting it into Models.

But... The data here does not represent all the data I need. Say for example that when you select an answer, I am going to want to keep track of what answer was selected.

That information does not belong in the data.

Do I want to base my model structure on the JSON structure or do I keep it separate?

Has the data

```<code>class Model {

    protected data: IQuizJSON;

    constructor(data: IQuizJSON){

          this.data = data;

          //use the data to construct unpolluted models

    }

}
</code>```

Is the data

```<code>class Model {

    title: string;
    entries: Entry[];

    constructor(data: IQuizJSON){

          this.title = data.title;
          this.entries = [];
          for (var i: number = 0; i < data.entries.length; i++){
               this.entries.push(new Entry(data.entries[i]));
          }

    }

}
class Entry implements IQuizEntry {

     question: string;

     constructor(data: IQuizEntryJSON){

          this.question = new Question(data.question); //etc

     }

}
</code>```

Until now I have read about how Models and Views interact, but here the data and model seem to merge and I am not sure of the best way to proceed?

答:
You can have as many models as you need to meet the many goals that a successful application has to address.

One concept that might help here is the Single Responsibility Principle. Basically, you ask the question, "what would cause this data structure to change?" In your case, changing the details of the quiz structure would be a prime source for change. Hence, your base data model reflects all and only the external representation.

A second part of your business object, though, is the ability to track what answer was selected, for instance. In general you would want a second data structure to retain the information about selections. Certainly, you would want to store those statistics separately from the sources for your quiz. Among other things, you might want to store correlations of answer selection with other answers selected, or which people selected which answer.

So the answer is that you need to create an aggregate data structure which contains a data structure that matches the quiz representation, as well as a data structure that stores statistics of interest.

Additionally, you really don't want to have the argument to the constructor be the JSON data. It is much better to have a factory, along with a builder. This would allow you to switch to XML, say, as your external representation, and that should not require changing your base model.


答:
It sounds like both the API and the website share a common language (PHP). In such a scenario I often find that the functionality used by the API can often be abstracted out into a less API specific object that other solutions (like the website) can also utilize.

This object would serve as a shared interface for the website and the API. Very little functionality then needs to live in the API code as it is simply operating as a translation layer between HTTP requests and the object.

It also saves the website from having to make network calls to an API and allows it to interact with the object more naturally.

If your API's functionality is relatively simple this runs the risk of being an over-architected approach so you'll need to consider if this is necessary and maintainable in your specific situation.

Title: Strategy for Website Talking to API on Same Server

Body:
I have a RESTful API that allows retrieval of data through requests such as GET http://example.com/users/id/1 (Coded following this tutorial).

The code igniter controller looks like this:

```<code>class Example_api extends REST_Controller {

function user_get()
{
    $data = array('returned: '. $this->get('id'));
    $this->response($data);
}
</code>```

This API was written specifically for the reason that I should be able to access the same code logic from the web frontend as well as mobile apps etc. Now, the mobile app is easy to write but I want to find the strategy for using the API from the web site. The website is essentially sitting on the same server that offers this API and it does not seem right to me to make an HTTP request to the API from code and go through the network again.

So, the question is, how do I use the API from the php code in the same site without going through the network.


问:
"Correct" way to use inheritance
Within a small project, a class Storage is meant to store any type of Item. Now, an Item has a String name, and an interaction. For example, a clock item might implement the interaction increment(int num), whereas a seat might implement sit(bool true).

Should I be simply writing classes for Item, Clock and Seat and letting Seat and Clock inherit from Item? Obviously the interaction they use varies, so short of writing every possible Item's interaction as a virtual method in Item I'm not sure how to deal with all the specific interaction types.

At the moment, I'm finding the Item and then using using conditionals to use the correct behavior on interaction, but that seems sort of roundabout and not so great.

Is there a better way to do this?

答:
If I understand you correctly, it sounds like you're working with something like this pseudocode:

```<code>void foo(Item i) {
   if(i instanceof Clock) {
       (i as Clock).increment();
   } else if(i instanceof Chair) {
       (i as Chair).sit();
   }
}
</code>```

As you suspect, this is a code smell. A pretty strong one, actually.

The immediate problem is that, because this function has to know the concrete type of i, there is absolutely no benefit to using the Item base class. In fact, this function is claiming that it can take any arbitrary Item object, when it can't, so it's lying to everyone that tries to use it. If you're very lucky, the solution is as simple as splitting it into void foo(Clock c) and void foo(Chair c), but it may run deeper than that.

Normally, this happens when you design your object hierarchy around real-world things you want to "exist" in your program, rather than around the actions you actually want your program to perform. The only simple solution is to redesign the relevant part of your program. Unfortunately, without knowing anything about the rest of your program, we can only guess what the optimal change would be. On the one hand, maybe you can come up with a single Interactable interface that serves the needs of all of your objects and their callers. On the other hand, maybe it doesn't make any sense to try unifying all these disparate types and you should move the Chair code far away from the Clock code. And there are many additional options in between. Either way, it's going to be hard working out what the correct design is, but solving that problem now will save you a lot of pain down the road (unless of course this project stays very small and simple).

In the hopes of being slightly more useful than "this is a hard problem, but good luck", I'll try to sketch a simple example solution. Your example reminds me of video games that have an "interact" button, so let's say I'm designing the item interaction code for such a game. I could start by asking myself what keys, ammunition, first-aid kits, talismans and plastic bags have in common, but then I end up in the situation you described.

Instead I would ask what happens when I interact with each of these items. What I find is that, at least for the specific game I'm playing today, some of the possible answers include:

I want to remove the item from the screen, add it to the inventory, show a 3d model of it along with a "I got X" message, then wait for a button press.

I want to pause the game, show some text at the bottom of the screen, wait for the user to scroll through it by pressing buttons, then resume.

Like #2, except the last piece of text includes a choice, and depending on the user's selection, we may show an animation, change the state of some other objects in the room, and spawn a few monsters before resuming.

It would make lots of sense to write a standard interface for each of these item types, since all items of a given type do essentially the same things; you can write a function that takes a ShowTextInteractable which doesn't care whether it's a Book or a CreepyDoll or a Flowerpot (and it may not even use subclassing, perhaps new ShowTextInteractable("It's a flowerpot.") is good enough). Also notice that I haven't even touched on using items from the inventory; those should be completely different types from items "in the world" because they do completely different things. But hopefully that gives you some idea what I'm talking about.

Title: "Correct" way to use inheritance

Body:
If I understand you correctly, it sounds like you're working with something like this pseudocode:

void foo(Item i) {
   if(i instanceof Clock) {
       (i as Clock).increment();
   } else if(i instanceof Chair) {
       (i as Chair).sit();
   }
}

As you suspect, this is a code smell. A pretty strong one, actually.

The immediate problem is that, because this function has to know the concrete type of i, there is absolutely no benefit to using the Item base class. In fact, this function is claiming that it can take any arbitrary Item object, when it can't, so it's lying to everyone that tries to use it. If you're very lucky, the solution is as simple as splitting it into void foo(Clock c) and void foo(Chair c), but it may run deeper than that.

Normally, this happens when you design your object hierarchy around real-world things you want to "exist" in your program, rather than around the actions you actually want your program to perform. The only simple solution is to redesign the relevant part of your program. Unfortunately, without knowing anything about the rest of your program, we can only guess what the optimal change would be. On the one hand, maybe you can come up with a single Interactable interface that serves the needs of all of your objects and their callers. On the other hand, maybe it doesn't make any sense to try unifying all these disparate types and you should move the Chair code far away from the Clock code. And there are many additional options in between. Either way, it's going to be hard working out what the correct design is, but solving that problem now will save you a lot of pain down the road (unless of course this project stays very small and simple).

In the hopes of being slightly more useful than "this is a hard problem, but good luck", I'll try to sketch a simple example solution. Your example reminds me of video games that have an "interact" button, so let's say I'm designing the item interaction code for such a game. I could start by asking myself what keys, ammunition, first-aid kits, talismans and plastic bags have in common, but then I end up in the situation you described.

Instead I would ask what happens when I interact with each of these items. What I find is that, at least for the specific game I'm playing today, some of the possible answers include:

I want to remove the item from the screen, add it to the inventory, show a 3d model of it along with a "I got X" message, then wait for a button press.

I want to pause the game, show some text at the bottom of the screen, wait for the user to scroll through it by pressing buttons, then resume.

Like #2, except the last piece of text includes a choice, and depending on the user's selection, we may show an animation, change the state of some other objects in the room, and spawn a few monsters before resuming.

It would make lots of sense to write a standard interface for each of these item types, since all items of a given type do essentially the same things; you can write a function that takes a ShowTextInteractable which doesn't care whether it's a Book or a CreepyDoll or a Flowerpot (and it may not even use subclassing, perhaps new ShowTextInteractable("It's a flowerpot.") is good enough). Also notice that I haven't even touched on using items from the inventory; those should be completely different types from items "in the world" because they do completely different things. But hopefully that gives you some idea what I'm talking about.


问:
Should class with only static data need to be instantiated?
I have two classes. 1. Node 2. MixedStateManager

Node class:

Node class maintains the state of nodes in the system. One such data is state.

```<code>public class Node
   {
      private int state;

     public void setState(int s)
     {
      state = s;
     }

     public int getState()
     {
       return state;
     }
    }
</code>```

MixedStateManager:

MixedStateManager sees if all the nodes in the system are in the same state or not. If the nodes don't have the same value for state value, then the system is said to be in MixedState. I've a variable mixedState for the same. I've made it static because, if the value is changed by one instance of the class, then it should be visible by others. Another thing to note is MixedStateManager is called by different threads which change the value of state of nodes.

```<code>public class MixedStateManager{

public static boolean mixedState;

public boolean isMixedState(){
 return mixedState;
}

public void setMixedState(){
// get all instances of Node class;
   if state of all instances are same
     mixedState = true;
   else
     mixedState = false
}
}
</code>```

Question: As MixedStateManager has only one data which is static, does it make sense to instantiate this class and then set value. Or can I make all methods static too?

Responses will be appreciated.
Thanks

答:
A static class with only static methods and static data is nothing more or less then a collection of global variables and a library of functions disguised as something resembling OO.

Such a class need never be instantiated because the result will not be an object, just an empty shell.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
I like the php progress and scalability in the recent days.

The new features introduced in java have only make the things complex rather then making it simple.

request 1:
db-connection-pool facility as additional library.

request 2:

I am asking for the reverse ajax or comet programming or RTMP facility as a built in library.These are already developed for .net,java, python and perl by dojo foundation

We have similar things in php but not a complete solution.

Also there is support for observer pattern in  SPL. but not properly documented.

Xajax framework (good but it requires redesign the application)

bye for now.

OwnerDisplayName: Shashank