问:
Which of these two shuffle algorithms is more random?
Which of below two shuffle algorithms (shuffle1 and shuffle2) is more random?

```<code>public final class Shuffle {
    private static Random random;

    public static void shuffle1(final Object[] array) {
        if (random == null) {
            random = new Random();
        }

        for (int i = array.length - 1; i > 0; i--) {
            swap(array, i, random.nextInt(i + 1));
        }
    }

    public static void shuffle2(final Object[] array) {
        if (random == null) {
            random = new Random();
        }

        for (int i = 0; i < array.length; i++) {
            swap(array, i, i + random.nextInt(array.length - i));
        }
    }

    protected static void swap(final Object[] array, final int i, final int j) {
        final Object tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
}
</code>```

The shuffle2 algorithm guaranties that all elements are directly touched, but, in shuffle1 algorithm, the element with index = 0 is never directly touched because of the condition i > 0.

答:
If you just want a shuffle then use Collections.shuffle(Arrays.asList(array)); which was written by people smarter than you and me.

As for the guarantee that the first element gets touched consider that in the second algorithm the last step (when i==array.length-1) that you are calling random.nextInt(1) which always return 0 which makes that step meaningless

Beyond that the algorithms are equivalent.


答:
Assuming that your random number generator is sufficiently robust, then the optimal algorithm is the Fisher–Yates shuffle

The algorithm can be summarised as this :-

```<code>Given a list of items numbered from 1 to N
Pick a random item between 1 and N and swap with item N
Pick a random item between 1 and N-1 and swap with item N-1
...
Pick a random item between 1 and 2 and swap with item 2.
</code>```

Of course if the selected item is already in position then there's no need to swap.

The key point is to avoid swapping an item again, once it has been placed in position. See here for a discussion on the bias that can be introduced if you do.

ContentLicense: CC BY-SA 3.0

Title: Which of these two shuffle algorithms is more random?

Body:
Which of below two shuffle algorithms (shuffle1 and shuffle2) is more random?

```<code>public final class Shuffle {
    private static Random random;

    public static void shuffle1(final Object[] array) {
        if (random == null) {
            random = new Random();
        }

        for (int i = array.length - 1; i > 0; i--) {
            swap(array, i, random.nextInt(i + 1));
        }
    }

    public static void shuffle2(final Object[] array) {
        if (random == null) {
            random = new Random();
        }

        for (int i = 0; i < array.length; i++) {
            swap(array, i, i + random.nextInt(array.length - i));
        }
    }

    protected static void swap(final Object[] array, final int i, final int j) {
        final Object tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
}
</code>```

The shuffle2 algorithm guaranties that all elements are directly touched, but, in shuffle1 algorithm, the element with index = 0 is never directly touched because of the condition i > 0.

Body:
Assuming that your random number generator is sufficiently robust, then the optimal algorithm is the Fisher–Yates shuffle

The algorithm can be summarised as this :-

Given a list of items numbered from 1 to N
Pick a random item between 1 and N and swap with item N
Pick a random item between 1 and N-1 and swap with item N-1
...
Pick a random item between 1 and 2 and swap with item 2.

Of course if the selected item is already in position then there's no need to swap.

The key point is to avoid swapping an item again, once it has been placed in position. See here for a discussion on the bias that can be introduced if you do.


问:
What are the different meanings of 'fixture'?
I have some difficulty understanding the concept of "fixture". I know what a test suite is, a test case, a test run,
but what exactly is a "fixture"? A parameterized test case?

It seems to me that the meaning or semantics of the term "fixture" can vary slightly by programming language or by testing framework? I think a phpunit fixture

"the code to set the world up in a known state and then return it to
  its original state when the test is complete. This known state is
  called the fixture of the test."

is slightly different from a "fitnesse fixture", where

"Fixtures are a bridge between the Wiki pages and the System Under
  Test (SUT), which is the actual system to test".

Is there an expert in software testing around here who can answer this question?  References to other programming languages are welcome.

答:
In the context of testing tools you mentioned, such as PHPUnit and Fitnesse, this term definitely refers to the notion of test fixture:

something used to consistently test some item, device, or piece of software...

Software

Test fixture refers to the fixed state used as a baseline for running tests in software testing. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. Some people call this the test context.

Examples of fixtures:

Loading a database with a specific, known set of data

Erasing a hard disk and installing a known clean operating system installation

Copying a specific known set of files

Preparation of input data and set-up/creation of fake or mock objects...

Use of fixtures

Some advantages of fixtures include separation of the test initialization (and destruction) from the testing, reusing a known state for more than one test, and special assumption by the testing framework that the fixture set up works...


问:
Well designed Open Source WPF Applications
I'm just wondering if anyone knows about some well designed .NET Open Source Applications using WPF?

I have already tried to search at the usual sites like GitHub and Sourceforge, but I wasn't very satisfied by the results at all.

Actually I'm interested in the right usage of MVVM, Data Binding etc. in the context of relatively large Software (at least more than the few lines of sample code, you will find at most Tutorials and Books). Also ORM with NHibernate lies in my main concern.

Currently I also do have the overall impression WPF is not used very extensively at all, am I right with that?
Which closed source (commercial) Software Products are out there, using it?

答:
Visual Studio is built using WPF. WPF is typically used for internal Line-of-Business applications in businesses of different size. The thing is that you don't need a large application to showcase proper use of MVVM and Data Bindings. Also it's not an open-source kind of technology. What would you build with it that would be useful to a wide range of people? A CMS? A graphics editor?

Check CodeProject: https://www.google.com/search?q=site%3Acodeproject.com+mvvm

The projects will not be big but could be less trivial than quick tutorial samples, for example:

http://www.codeproject.com/Articles/484616/MVVM-Diagram-Designer


问:
Writing my problem solving approach on paper?
I'm a freshman Computer Science student and we just started doing some actual projects in Python. I have found I'm very efficient when I use the pen and paper method that my professor suggested in class. But when I can't write my problem down and work my algorithms out on paper I am really slow. During labs, I always seem to have to take the assignment back to my dorm. When I get there and write it out I solve the problem that took me the whole class in like 5 minutes.

Maybe it's because I get stressed seeing people solving labs before me. Or maybe it's the pen and paper method.

I was browsing through forums and someone wrote that if you have to write your programs on paper then you shouldn't be a programmer. I'm really worried because I'm so much better when I can see what the program is doing and track my way through it before typing actual code. Am I doing something wrong?

Edit: Sorry for being unclear, but when I said writing on paper I meant my problem solving approach (e.g writing examples, making tables with values, etc.) not my actual code. I just use the paper to get my ideas out.

答: Do what works for you. I wouldn't write code on paper. I do write pseudocode and draw flowcharts on paper, but writing the full code seems like a waste of time. </p>


答: Outside of the testing context, the term fixture is sometimes used to describe the initial data in storage (like the initial data in a database) when deploying an application for the first time.</p>

Title: What are the different meanings of 'fixture'?

Body:
I have some difficulty understanding the concept of "fixture". I know what a test suite is, a test case, a test run,
but what exactly is a "fixture"? A parameterized test case?

It seems to me that the meaning or semantics of the term "fixture" can vary slightly by programming language or by testing framework? I think a phpunit fixture

"the code to set the world up in a known state and then return it to
  its original state when the test is complete. This known state is
  called the fixture of the test."

is slightly different from a "fitnesse fixture", where

"Fixtures are a bridge between the Wiki pages and the System Under
  Test (SUT), which is the actual system to test".

Is there an expert in software testing around here who can answer this question?  References to other programming languages are welcome.


问:
Continuous Integration with Bamboo and Maven, Managing Version Numbers?
I am currently developing a product that is broken up into a few main parts: A Server, an Android client, a Desktop client, and a class library for providing common data structures. Currently my team is using Maven (with a private Nexus repo) and TeamCity to do continuous integration, but we're having a ton of problems with builds failing due to version numbering issues. Our current solution involves using the Auto-Increment Versions Plugin for Maven, but any time we make any changes to our pom files we have to manually update the version of the pom file since the version of the pom in Git is now out of date.

My team and I have decided to look at Atlassian Bamboo, and since we are making changes to our workflow we would like to iron out these issues all at once. Here is what we are looking for:

We want to specify a major and a minor build number (such as 0.3) and have the resulting artifact deployed to our repository as major.minor.auto-incrementing-build-number (such as 0.3.2, 0.3.3, 0.4.0).

We want this to be as automatic as possible, since we have several developers and it only takes one person making a mistake to cause a disruption to everyone's workflow.

We would prefer for this functionality to happen in Bamboo if possible, as Bamboo's "clone project" feature would allow us to replicate this functionality across multiple applications quickly, as well as keeping all of our pom files from having a ton of additional code for managing versions.

Has anyone had any experience doing something like this through Bamboo, or is there another approach that I should consider to make this easier?

答:
A sweetfa suggested, the best approach is to use Maven's SNAPSHOT versions for development. The versions increase only at release with the help of the Maven Release Plugin. All of this can be automated from Jenkins.

I don't see any reason why you should increase the artifact version, at any time other than release; you have git for holding the code in a more granular fashion, and you can do a build at any time.


问:
Open source project question in interview
I've recently applied for a position as C# developer, and during the interview, the interviewers asked me many times if I contribute to develop one or more open source project.

Since they let me write a lot of code (from basics to TDD,MVVM,MVP), I didn't get the meaning of such a question, especially cause they insisted a lot on the topic and the thing started to bother me.

I wish I could have time enough to develop open source software, but I don't get why a company that sells software pretend that their employees work for free in their spare time.

What's the real reason of this question (apart from checking your code)?

答: One of the reasons is that some people believe, that if you participated in open source projects, you will write better code. This idea comes from a common opinion that the quality of the code in open source projects is higher, since it usually undergoes a review by both the peer developers and the community of the project. This opinion is disputable, though.</p>


答:
Don't get too caught up in the whole open source or working for free concept. They want to see code you've written. If all of your work was done for various companies, you're not going to be able to include this work. This is no different than a portfolio for a writer, musician or other type of creative work.

You can write code during the interview process, but there can be drawbacks because of time contstraint and it's difficult to show how you would design larger/more complicated projects, fix bugs, and refactor code.

Title: Open source project question in interview

Body:
I've recently applied for a position as C# developer, and during the interview, the interviewers asked me many times if I contribute to develop one or more open source project.

Since they let me write a lot of code (from basics to TDD,MVVM,MVP), I didn't get the meaning of such a question, especially cause they insisted a lot on the topic and the thing started to bother me.

I wish I could have time enough to develop open source software, but I don't get why a company that sells software pretend that their employees work for free in their spare time.

What's the real reason of this question (apart from checking your code)?


问:
Which ASP.Net programming model is closer to PHP?
I've been using ASP.Net WebForms for the last year or two at work for development, but I've used PHP for personal projects for 10 years. So, I'm far more adept at developing with PHP.

When it comes to ASP.Net MVC, I have no experience with it because I've avoided it because I assumed it would just be a more complicated form of WebForms. Recently, I've been doing more research and it's sounding like MVC might be closer to what what I want. But, something I'm still not clear on is which ASP.Net programming model is closer to developing with PHP.

My biggest complaint about ASP.Net WebForms is the "magic boxes." Namely the View State, and ScriptManager.

I don't like that WebForms messes with my client side HTML/JavaScript/CSS. WebForms does a lot of this including, but not limited to:

Inserting JavaScript that I can't modify and have to rely on Microsoft to ensure cross-browser compatibility.

Forcefully changing the name attributes of tags that make use of  runat="server".

Wrapping the contents of a <form> with a
 tag.

Forcing wrapping everything inside one big <form> tag.

Everything in WebForms feels like it's catered to in-experienced web-developers who only know how to write Windows applications with .Net.

Standard names for tags and attributes are changed when using <asp:xxx> tags. For example, instead of an anchor () tag, it's a "hyperlink" (i.e. <asp:HyperLink>). Instead of href= it's NavigationUrl=.

The event driven model.

I also don't like the complete separation of server side code from the client side code. I miss being able to do things like this...

```<code> <table>
     <tr>
         <td>Name</td>
         <td>Age</td>
     </tr>
     <? foreach( $people as $person ) { ?>
     <tr>
         <td><?= $person->name ?></td>
         <td><?= $person->age ?></td>
     </tr>
     <? } ?>
 </table>
</code>```

So, with these points in mind, which programming model is closer to development with PHP (i.e. do the annoyances of WebForms that I've listed here exist in MVC)?

Note: I have found ways around many, if not all of these annoyances, but did not feel the solutions I use are revelent to the question at hand.

答:
I have recently read pro_asp.net_mvc_4_4th_edition and it adressed a lot of your points - I would say MVC was specifically designed to AVOID the problems you mentioned.
if you want a nice and comprehensive introduction I would give the book a try, it is very well written.</p>


答:
I started developing an Open Source application in WPF as a showcase for WPF and MVVM. I didn't get around to finishing but it does have a lot of the structure in place for anyone to get an understanding of how all the pieces interact:

https://github.com/smclark/DriverManager

Obviously it's not perfect, but it was something I wanted to do just to get it all down somewhere.

Title: Well designed Open Source WPF Applications

Body:
I'm just wondering if anyone knows about some well designed .NET Open Source Applications using WPF?

I have already tried to search at the usual sites like GitHub and Sourceforge, but I wasn't very satisfied by the results at all.

Actually I'm interested in the right usage of MVVM, Data Binding etc. in the context of relatively large Software (at least more than the few lines of sample code, you will find at most Tutorials and Books). Also ORM with NHibernate lies in my main concern.

Currently I also do have the overall impression WPF is not used very extensively at all, am I right with that?
Which closed source (commercial) Software Products are out there, using it?


问:
Are there any valid use-cases for eager boolean evaluation?
Today I learned about eager boolean evaluation. In the following example, Bar() will be evaluated even when Foo() is true.

if (Foo() | Bar())
```

<p>This answer on SO has an example:</p>

<pre class="lang-cs prettyprint-override"><code>if ((first = (i == 7)) & (second = (j == 10))) { //do something }
</code>```

The use-case here would be that you want to reuse the results, but I would rather write it like this then:

first = (i == 7);
second = (j == 10);
if (first && second) { //do something }
```

Another use-case would be that Bar() has a side-effect that should be executed regardless of Foo() being true or false. Question is, can that be good code or would it indicate a code smell?

答:
The biggest one would be thwarting cryptographic timing attacks by eliminating the branches the short-circuit operators generate.

a timing attack is a side channel attack in which the attacker attempts to compromise a cryptosystem by analyzing the time taken to execute cryptographic algorithms. Every logical operation in a computer takes time to execute, and the time can differ based on the input; with precise measurements of the time for each operation, an attacker can work backwards to the input.

Information can leak from a system through measurement of the time it takes to respond to certain queries. How much such information can help an attacker depends on many variables: crypto system design, the CPU running the system, the algorithms used, assorted implementation details, timing attack countermeasures, the accuracy of the timing measurements, etc...


问:
How much time should jquery wait?
I'm programming a jQuery functionality for doing a search on articles while the user is typing in the search field.

I implemented a bind in jQuery that at every keyup, it sets a clearTimeout and a setTimeout to the actual function doing the post to the server. This is because users can be writing something and I want to avoid multiple posts.

I got "stuck" with: from the user interface point of view, what time should I set for the setTimeout? I tried different times (1s, 1.5s, 0.5s) but I have to admit the choice seems kind of random to me.

This raised the broader question: Is there any reference or study that answers the question of what are the "optimal" times for dynamic web interfaces?

I only now noticed that I've used more timers before (e.g. slides), that were also chosen "randomly".

Putting in other terms, does anyone knows how to justify why a given event in web interface has (or should have) a specific delta-time or range of delta-times?

(I'm sorry if this question is not adequate to here, It seemed to me closer than SO.)

答:
Take a look at http://imlocation.wordpress.com/2007/12/05/how-fast-do-people-type/

If you take the median:

Median = 38 WPM = 228 characters/minute

This gives 3.8 characters per second on average.

So if you waited 0.26 seconds before sending the query you are not querying faster than the speed half of people can type. It all depends on your system and whether it can cope with the amount of requests generated at this rate if it so happens the users of your system are slower than this (if everyone is at this speed then there's no problem).

Title: How much time should jquery wait?


答:
A little questionable, but I've seen code that did two nontrivial, related, boolean returning operations and combined them like your Foo | Bar example. The only real issue is that often a comment should be placed, it's too easy to glance over and ignore the single operator when all that's expected is the regular boolean comparison.

If your environment uses both in a regular setting and people are used to seeing it, I'd say its fine, but that seems unlikely. When in doubt, write the code that's easier to read. Surprise foreign syntax when you're chasing a bug just kind of sucks.

Title: Are there any valid use-cases for eager boolean evaluation?

Body:
Today I learned about eager boolean evaluation. In the following example, Bar() will be evaluated even when Foo() is true.

if (Foo() | Bar())
```

<p>This answer on SO has an example:</p>

<pre class="lang-cs prettyprint-override"><code>if ((first = (i == 7)) & (second = (j == 10))) { //do something }
</code>```

The use-case here would be that you want to reuse the results, but I would rather write it like this then:

first = (i == 7);
second = (j == 10);
if (first && second) { //do something }
```

Another use-case would be that Bar() has a side-effect that should be executed regardless of Foo() being true or false. Question is, can that be good code or would it indicate a code smell?


答:
It is generally accepted that short-circuit (as opposed to "eager") evaluation is the correct approach, both from an optimization point of view and from the point of view of understanding typical code.

Consider:

```<code>while ((i < N) && (test(p[i]))) {
  do something
}
</code>```

This kind of code is EXTREMELY common.  Eager evaluation will perform the test on the array element even if the subscript is explicitly out of range.  That's generally a very bad idea.

If it is critically necessary that both parts be performed, one can write something like the following:

```<code>bool part1, part2;
while ((part1 = (i < N)), (part2 = (test(p[i]))), (part1 && part2)) {
  do something
}
</code>```

This uses the C comma operator to evaluate several expressions and return the value of the last one.

Body:
It is generally accepted that short-circuit (as opposed to "eager") evaluation is the correct approach, both from an optimization point of view and from the point of view of understanding typical code.

Consider:

while ((i < N) && (test(p[i]))) {
  do something
}

This kind of code is EXTREMELY common.  Eager evaluation will perform the test on the array element even if the subscript is explicitly out of range.  That's generally a very bad idea.

If it is critically necessary that both parts be performed, one can write something like the following:

bool part1, part2;
while ((part1 = (i < N)), (part2 = (test(p[i]))), (part1 && part2)) {
  do something
}

This uses the C comma operator to evaluate several expressions and return the value of the last one.


答:
In normal circumstances, I'd consider it highly likely to be a typo, and that the logical || or && was intended rather than the bitwise | or & operators.

There are situations where you are dealing with hardware, where the use of bitwise operators is the correct code implementation, but then, doing it inside the if statement is less than ideal for code clarity and debugging.

Likewise, if the purpose was to ensure consistent timing of code (as in thwarting cryptographic timing attacks), the use of an IF statement is likely to be a bad choice of implementation.


答:
It's cute to call this eager boolean evaluation, but what the operators actually do (in C-style languages) is bitwise boolean evaluation.

The examples you've quoted work as desired, but this use does not work as desired in general.  If your second example was

```<code>if ((first = foo()) & (second = bar())) { /*do something*/ }
</code>```

and foo() returned 1 and bar() returned 2 -- both of which are non-zero and hence true as far as if and && are concerned -- then the if will not fire and something will not be done.  This will be surprising to readers of your code.

So this is an obscure usage and a code smell.  If you want to ensure that second =/Bar()'s  side-effects occur, it's better to write that desire out explicitly by using separate statements, as you noted.

Body:
It's cute to call this eager boolean evaluation, but what the operators actually do (in C-style languages) is bitwise boolean evaluation.

The examples you've quoted work as desired, but this use does not work as desired in general.  If your second example was

if ((first = foo()) & (second = bar())) { /*do something*/ }

and foo() returned 1 and bar() returned 2 -- both of which are non-zero and hence true as far as if and && are concerned -- then the if will not fire and something will not be done.  This will be surprising to readers of your code.

So this is an obscure usage and a code smell.  If you want to ensure that second =/Bar()'s  side-effects occur, it's better to write that desire out explicitly by using separate statements, as you noted.


问:
Is copyrights notice of a BSD licensed library considered as endorsement?
As I am reviewing a BSD license for an open source library to use it in my commercial product, I found this paragraph:

Redistribution and use in source and binary forms are permitted
  provided that the above copyright notice and this paragraph are
  duplicated in all such forms and that any documentation, advertising
  materials, and other materials related to such distribution and use
  acknowledge that the software was developed by the organization.

Its clear that I have to mention the copyright notice, but as for the next paragraph:

The name of the organization may not be used to endorse or promote
  products derived from this software without specific prior written
  permission.

If I just put the copyright notice of the used library, is that considered as I am promoting my product by mentioning the library copyrights notice? Shall I seek a written permission? or I just need to add the copyright notice only?

答:
You are, By including the copyright notice, fulfilling the terms of the BSD license for the library, and to draw your users attention to the terms that they have to accept to use the library.

My understanding of the intention of the clause you have highlighted is that its there to prevent you from claiming that as part of this license you have any partnership, sponsorship or that the third party has in any way seen, reviewed, or approved your specific use of their library.


问:
Rest API and caching data
I have developed an application where you should be able to browse products catalog(READ ONLY) even network access is down no wifi or 3g/lte etc. Clients(windows,ios,android etc) consume the rest api.  So far There is a REST api that grabs parts like categories with products and other api call to get preferences etc. This adds logic at client like joining them together something that developers dont like.

Also we need to add multiple pricebooks for each product. Current proposed solution demanded by team  was to require network for this operation and get products with price of the pricebook.

As the ideal solution would be to ask for what is needed everytime this isnt real solution as it would degrade performance and would make offline usage impossible.
So I believe that each client probably should just store at a simple local database the data  and resync based on some versioning?Products/catalogs change about 1 time per month.

答:
Implement something inspired from etags.

Store the version# of the data on local db.

Make a rest request to check for the version stored on local db vs version on server.

If different, fetch the newer data and store it in db.

Title: Rest API and caching data


问:
Layer style applied, but intuition is different
Currently, I'm developing an architecture for a system of the following kind:

There are a couple of existing applications (front end) with which one can define UML profiles capturing some specific domain aspects. Since the tools are proprietary the produced models are not exchangeable by default. On the other hand there are a couple of tools which can analyze the produced frontend models (back end). These also have their own mechanisms (which are different from the frontends) to represent the domain aspects.

Since this would produce m*n model transformations with m frontends and n backends, I chose to introduce an exchange model which captures all relevant information from the frontends and nevertheless allows the backend to have enough information for analysis. This approach results in only m+n transformations.

My bird-eye view on the architecture:

Things go like that:

Transformation is possible between frontend model<->exchange model and exchange model<->backend model. Analysis tasks are triggered in the frontend and are delegated to the backend, where they are executed.

At the first glance, it looked for me like a layered style, but the more I thought about it, the intuition of the problem is not to make different layers exchangeable, where the layers achieve separation of concerns and focus on portability.

It is rather to introduce an intermediate layer, which decouples the two others and targets mainly at extendability. Another point is that the highest abstraction is not found on the highest layer but on the intermediate layer, i.e. the exchange format should be the core of the architecture where frontends and backends can be attached to. It should not need to know anything about its attached frontends or backends. This also means that the backend layer must know how to transform the exchange format into its own model representation, which is a upward usage not allowed in the layered style.

This boils down to the questions:

Do you know some architectural style which is similar to the one I depicted and also follows its intuition?

Why isn't this a good example for layered style (apart from the upward usage)?

Since the application is mainly model-driven, are there some specific architectural patterns/styles for systems of this kind?

Thanks for help in advance!

EDIT:
Actually I am concerned with layers, because the coarse vision of this architecture is embedded in an existing project and is communicated there as "layers". But from an architectural point of view, it doesn't fit the style.
The problem lies between the documentation and the communication of the architecture. If most of the stakeholders talk about a layered architecture and I introduce the layered view into it, although it isn't applied correctly, wouldn't this confuse all stakeholders, who have the right understanding of a layered architecture?

The goal is to document the views of the style which is really applied to have a correct basis for communicating the architecture.

答:
The Frontend-Exchange-Backend presented in the question can be easily identified as very common three-layer approach, usually seen in distributed systems (see, eg middleware, maybe understood in a slightly broader sense).

Common language among stakeholders is more important, than purity of implementation. For example, many web-based MVC systems are far from the ideal and even far from being MVC in the first place. The meaning of layers in your case can be explained in some Overview section of the documentation.

More important is that the software architecture makes the system less complex by adding abstraction layer between heterogeneous frontends and backends.

At the macrolevel, layered architecture you describe seems to be ok. Personally I'd preferred component-based architecture in your case, but I guess those two aren't mutually exclusive, as components can be easily thought of as arranged in layers.

On a microlevel, take a look at structural patterns like Adapter, Proxy and Facade. Not that those should be used directly (it depends on what you are building, data processing patterns, etc). Patterns also depend on much impedance mistmatch there is between frontends and backends. For example, different modes of operation can make it harder to connect parts (eg, if one frontend uses "push" technology, another "pull" technology and, say, third one uses batch mode to run tasks/dump data once a day - I encountered this case in one of applications).

From your question it is not quite clear whether your application build software using UML models or is the end result of transforming UML into code (or is it even run-time interpreter for UML?). In any case, gluing is needed and the resulting architecture may be quite similar in both cases.

Model-driveness is, IMHO, orthogonal to layeredness of the architecture. However, I am not very familiar with Model-driven architecture, if this is what you mean. And in this respect ready parts of the solution constrain your architecture choice. IF I understood the question well, you have several DSLs (each of frontends use different UMLs).

All in all, it is very hard to advice suitable architectural abstraction from already highly abstracted overview. The advice is however to forget purity and care more for practicality.


问:
JavaScript Frameworks for traditionally structured web applications
I am looking for a way to control large amounts of JavaScript code in a ASP.Net MVC web application.

I have been looking at Ember.js and whilst it's pretty compelling it takes control of the routing and as such treats the server as little more than a place from which to receive API calls. This isn't really useful for what I need.

I wondered if there recommendations for similar projects out there that allow faster, more structured, JavaScript but in traditional server-based web applications?

答:
You can disable Ember's URL management. Read the guide http://emberjs.com/guides/configuring-ember/embedding-applications/ before you discard Ember. What's considered a structured web application on client-side is moving forward in a rapid and pleasant manner (i.e. Ember). That fact does also make Niphra's suggested article from Smashing Magazine outdated if you are evaluating Ember.

But Ember might still not be way to go for structuring large amounts of existing JavaScript code. Someone else might fill in on that subject.


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
with the underscore.

Bill Wagner explains why in Effective C#.
But I would never name an integer myInteger,
better something like _age or _length.
Including the TypeName in the instance name is a horrible practice.
Names should be self explanatory and since C# is Type-Safe types can be found out att all times.

ContentLicense: CC BY-SA 2.5


问:
Why isn't SSL/TLS built into modern Operating Systems?
A lot of the basic network protocols that make up the infrastructure of the Internet are built in to most major Operating Systems.  For example, TCP, UDP, and DNS are all built into Linux, UNIX and Windows, and are made available to the programmer through low-level system APIs.

But when it comes to SSL or TLS, one has to turn to a third-party library such as OpenSSL or Mozilla NSS.

SSL is a relatively old protocol, and it's basically an industry standard as ubiquitous as TCP/IP, so why isn't it built into most Operating Systems?

答:
There are a number of reasons, but perhaps the most compelling is that cryptography is very, very hard to actually get right. It is unwise to implement it yourself unless you can devote major resources to verifying that it is correct and strong. Most people who work with cryptographic software don't have the time, expertise, or desire to bog down in this; they trust third-party libraries so that their devs can handle that part of the work, while the application developers can get back to making what they want to make.

OS developers are not so different. Sometimes there is an overriding interest -for example, your business model or lawyers require you to keep the code closed- and so you don't have much of a choice in the matter: if you can't find someone who will let you do what you have to, then you have to roll your own. Others have already mentioned how Microsoft does this. But generally speaking, OS developers that can use third-party libraries prefer to do it that way, for the same reasons that application developers do.


答:
MVC is probably a bit closer to PHP then Web Forms. The "annoyances" you specifically ask about in reference to Web Forms mostly do not exist in MVC. However, its important to note that although MVC is closer to PHP than Web Forms it is still significantly different than building a web page in PHP.

There are specific conventions you follow in ASP.NET MVC. It still forces separate server side and "client side" code as you call it. It does, however, encourage keeping presentation logic out of the controller and in the view while keeping all non-presentation logic out of the view and in other places (controller, model, service layer, etc...).

Pages in ASP.NET MVC are route driven rather than file driven. This is a major difference between base PHP and ASP.NET MVC.

Unless you've programmed an MVC structured website in PHP you're still likely to find many of the concepts in ASP.NET MVC foreign, even if some of the annoyances you reference are not present. Vanilla PHP (without any additional framework) is much more comparable in programming model to classic ASP. ASP.NET MVC is more comparable to Ruby on Rails than anything else. Not sure that ASP.NET Web Forms is really comparable to anything.

Title: Which ASP.Net programming model is closer to PHP?

Body:
I've been using ASP.Net WebForms for the last year or two at work for development, but I've used PHP for personal projects for 10 years. So, I'm far more adept at developing with PHP.

When it comes to ASP.Net MVC, I have no experience with it because I've avoided it because I assumed it would just be a more complicated form of WebForms. Recently, I've been doing more research and it's sounding like MVC might be closer to what what I want. But, something I'm still not clear on is which ASP.Net programming model is closer to developing with PHP.

My biggest complaint about ASP.Net WebForms is the "magic boxes." Namely the View State, and ScriptManager.

I don't like that WebForms messes with my client side HTML/JavaScript/CSS. WebForms does a lot of this including, but not limited to:

Inserting JavaScript that I can't modify and have to rely on Microsoft to ensure cross-browser compatibility.

Forcefully changing the name attributes of tags that make use of  runat="server".

Wrapping the contents of a <form> with a
 tag.

Forcing wrapping everything inside one big <form> tag.

Everything in WebForms feels like it's catered to in-experienced web-developers who only know how to write Windows applications with .Net.

Standard names for tags and attributes are changed when using <asp:xxx> tags. For example, instead of an anchor () tag, it's a "hyperlink" (i.e. <asp:HyperLink>). Instead of href= it's NavigationUrl=.

The event driven model.

I also don't like the complete separation of server side code from the client side code. I miss being able to do things like this...

```<code> <table>
     <tr>
         <td>Name</td>
         <td>Age</td>
     </tr>
     <? foreach( $people as $person ) { ?>
     <tr>
         <td><?= $person->name ?></td>
         <td><?= $person->age ?></td>
     </tr>
     <? } ?>
 </table>
</code>```

So, with these points in mind, which programming model is closer to development with PHP (i.e. do the annoyances of WebForms that I've listed here exist in MVC)?

Note: I have found ways around many, if not all of these annoyances, but did not feel the solutions I use are revelent to the question at hand.


问:
Does Scrum turn active developers into passive developers?
I'm a web developer working in a team of three developers and one designer. It's now about five months that we've implemented the agile scrum software development methodology. But I have a weird feeling I just wanted to share in this site.

One important factor in human life is decision-making process. However, there is a big difference in decisions you make. Some decisions are just the outcome of an internal or external force, while other decisions are completely based on your free will, and some decisions are simply something in between. The more freedom you have in making decisions, the more self-driven your work would become. This seems to be a rule. Because we tend to shape our lives ourselves.

There is a big difference between you deciding what to do, or being told what to do.

Before scrum, I felt like having more freedom in making the decisions which were related to development, analysis, prioritizing implementation, etc. I had more feeling like I'm deciding what I'm doing.

However, due to the scrum methodology, now many decisions simply come from the product owner. He prioritizes PBIs, he analyzes how the software should work, even sometimes how the UI and functionality should be implemented. I know that this is part of the scrum methodology, and I also know that this may result in better sales of product in future. However, I now feel like I'm always getting told to do something, instead of deciding to do something. This syndrome now has made me more passive towards the work.

I tend to search less to find a better solution, approach, or technique

I don't wake up in the morning expecting to get to an enjoyable work. Rather, I feel like being forced to work in order to live

I have more hunger to work on my own hobby projects after work

I won't push the team anymore to get to the higher technological levels

I spend more time now on dinner, or tea-times and have less enthusiasm to get back to work

I'm now willing more for the work to finish sooner, so that I can get home

The big problem is, I see and diagnose this behavior in my colleagues too. Is it the outcome of scrum? Does scrum really makes the development team feel like they have no part in forming the overall software, thus making the passive to the project?
How can I overcome this feeling?

答: As per my experience, Scrum is to deeply watch you what you do. It is just sitting on your shoulder and watching what you do. Even though it has its own advantage, I hate the scrum methodology. It expects the count, not the quality. Quality is getting compromised with scrum methodology.</p>


问:
What are the different aspects to consider when porting code from a single threaded environment to a multi threaded environment or vice versa?
I want to provide some library functionality and a reference application, which will run on a fully-featured, POSIX-compliant platform. The app and library will need bi-directional serial port communication, user input from keyboard, user display to text console, and probably timers.

I also want to provide a porting guide so that users of the library can port it (with or without the reference application) to their own platforms, which may be POSIX-compliant or not, and may or may not support multiple threads.

I am taking care of the main platform portability issue by writing portable code for everything as far as possible and providing a self-contained porting layer for platform-specific code. In my porting guide I will tell the user to replace the porting layer functions with implementations for their own platform.

However as far as the threading model goes, I have two choices:

implement my reference application as a very simple single-threaded program (main loop would poll keyboard, poll serial port, check timer status, and call library functions as needed)

use the pthreads library and have a main app thread with separate threads for user input, serial port receive, and timer expiry, all of which would post messages to my main app thread for processing.

Whichever model I choose I will have to explain to users how to port it to a platform which may be using a different model.

Even if I use a single-threaded implementation for the reference app, I will make sure any library functionality is re-entrant (or put big caveats around it if that isn't possible).

What considerations should I bear in mind, in my implementation and the porting guide? What information would you want if you were porting some multi-threaded code to a single threaded system, or vice versa?

答:
As with all multi-threaded development, the introduction of multiple threads means the following need to be managed:

Managing concurrent access to shared resources to ensure consistency

Design of locking strategy to prevent deadlocks

Managing of resources that are thread locked. (e.g. can you read your serial port from multiple threads at the same time?)

Shutdown / Error handling.  This can introduce many unexpected code paths, do resources always get properly released, can deadlock occur?

I'm not seeing a particular problem with doing all this on a single thread, as keyboard and serial can be made essentially non-blocking. It all comes down to your library, and how long do the function calls in your library take to complete?


答:
Unfortunately, using & as a replacement for && is flat out wrong.  It's not just the evaluation strategies, the actual meanings of the two operators are different. There are a great many integer values where x && y has a different value than x & y.  Try the following code:

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

int main()
{
        int i,j;
        int a,b;
        for (i = 0; i <= 100; i++) {
                for (j = i; j <= 100; j++) {
                        a = i && j;
                        b = i & j;
                        if (a && !b) {
                                printf("%d\t%d\n", i, j);
                        }

                }
        }

    return 0;
}
</code>```

Nearly a third of the combinations have different results when comparing using & and &&.  Since it's not safe to assume that a true value from a C function is anything other than non-zero, you're asking for trouble by expecting them to have the same value.

Body:
Unfortunately, using & as a replacement for && is flat out wrong.  It's not just the evaluation strategies, the actual meanings of the two operators are different. There are a great many integer values where x && y has a different value than x & y.  Try the following code:

#include<stdio.h>

int main()
{
        int i,j;
        int a,b;
        for (i = 0; i <= 100; i++) {
                for (j = i; j <= 100; j++) {
                        a = i && j;
                        b = i & j;
                        if (a && !b) {
                                printf("%d\t%d\n", i, j);
                        }

                }
        }

    return 0;
}

Nearly a third of the combinations have different results when comparing using & and &&.  Since it's not safe to assume that a true value from a C function is anything other than non-zero, you're asking for trouble by expecting them to have the same value.


答:
In general, you do not need to get permission to include a copyright notice when redistributing a piece of BSD-licensed software. Indeed, if it were necessary, then you could not satisfy the license's first mandatory condition without permission, which would cause it to violate both Free Software and Open Source definitions. So, we can be certain that either 1) both the OSI and FSF have gravely misunderstood the BSD license text or 2) you can include copyright notices without running afoul of the no-promotion clause.

However, it may still be possible to display your copyright notice in such a way that it suggests promotion. For example, if your software used a library made by Google, it would be very misleading to include a message where you present the name of the organization in way that suggests endorsement, like

"Based on Foo Library, copyright GOOGLE, INC., 2011" (That's as big as Markdown will let me make it, but imagine the name perhaps ten or fifteen times larger.)

Whether a particular copyright notice display could be reasonably considered to imply endorsement is a decision made by a judge. If you are still worried that your unobtrusive copyright notice might be confused for endorsement, you might include a disclaimer alongside the notice like:

While this software is based upon software developed by <organization>, this software distribution, <your software name>, is in no way endorsed by <organization>.

Any similarly-phrased is certainly a helpful step toward indicating a good-faith attempt to follow the conditions of the license. Whether it's enough to protect you against all judgments in all jurisdictions seems impossible to say (and certainly not possible for a non-lawyer like me to say).

If you're still worried that you might attract legal attention, then consult a lawyer, who can give vastly better advice that strangers on the Internet.

Title: Is copyrights notice of a BSD licensed library considered as endorsement?

Body:
As I am reviewing a BSD license for an open source library to use it in my commercial product, I found this paragraph:

Redistribution and use in source and binary forms are permitted
  provided that the above copyright notice and this paragraph are
  duplicated in all such forms and that any documentation, advertising
  materials, and other materials related to such distribution and use
  acknowledge that the software was developed by the organization.

Its clear that I have to mention the copyright notice, but as for the next paragraph:

The name of the organization may not be used to endorse or promote
  products derived from this software without specific prior written
  permission.

If I just put the copyright notice of the used library, is that considered as I am promoting my product by mentioning the library copyrights notice? Shall I seek a written permission? or I just need to add the copyright notice only?


问:
When does it become overkill?
First off, I apologize cause I don't know how to make a community thread; so someone help me out please.

As a developer, across many platforms, technologies and even on an infrastructure level; I always find myself asking, when am I doing TOO much?!?

It's been a never ending learning process, since I started. One (1) thing I learned is that requirements are barely valid for an extended period of time, and as such a little foresight may go a long way.

But where is the balance, and how do you know when you're losing time, not gaining it?!

答:
When I answer no to "am I going to be mad I didn't do this later and it bites me..

IRL Resource and time constraints usually get me before I have to ask this question much though.  At that point you just focus on the most important/achievable bits and hope for the best.

Title: When does it become overkill?


答: There is no reason to introduce multi-threading just because you need to react to multiple input sources.  You can wait for the keyboard, serial port, and timer via the POSIX select system call.  If you are using C++, then you could use the ACE library Reactor.</p>

Title: What are the different aspects to consider when porting code from a single threaded environment to a multi threaded environment or vice versa?

Body:
I want to provide some library functionality and a reference application, which will run on a fully-featured, POSIX-compliant platform. The app and library will need bi-directional serial port communication, user input from keyboard, user display to text console, and probably timers.

I also want to provide a porting guide so that users of the library can port it (with or without the reference application) to their own platforms, which may be POSIX-compliant or not, and may or may not support multiple threads.

I am taking care of the main platform portability issue by writing portable code for everything as far as possible and providing a self-contained porting layer for platform-specific code. In my porting guide I will tell the user to replace the porting layer functions with implementations for their own platform.

However as far as the threading model goes, I have two choices:

implement my reference application as a very simple single-threaded program (main loop would poll keyboard, poll serial port, check timer status, and call library functions as needed)

use the pthreads library and have a main app thread with separate threads for user input, serial port receive, and timer expiry, all of which would post messages to my main app thread for processing.

Whichever model I choose I will have to explain to users how to port it to a platform which may be using a different model.

Even if I use a single-threaded implementation for the reference app, I will make sure any library functionality is re-entrant (or put big caveats around it if that isn't possible).

What considerations should I bear in mind, in my implementation and the porting guide? What information would you want if you were porting some multi-threaded code to a single threaded system, or vice versa?


问:
Why we use virtual and override keywords in c#
Can anyone explain me what's the point of overriding base class implementations (if its not abstract), because it's not ethical move to modify features of the parent class according to the wishes of derived classes. The best way is to make the base classes abstract and carry on the inheritance chain. Whereas when designing a class hierarchy initially we gather or elicit  all the essential requirements/features that should be belonged to a base class. Therefore, in a middle of a project we do not need to change base class implementations. According to my knowledge, base class implementation should be a constant. Thus, under this aspect, there's no real use of "override" keyword in c#. If it's not so please explain me with an example.</p>

答:
Note: The OP mention that it seems OK to you to override base implementations of abstract classes, so this answer is tailored around that assumption.

It's probably a bad idea to inherit from classes which were not designed for inheritance (see why are concrete types rarely useful as bases for further derivation).  Many of the C# experts believe that C# classes should be sealed by default.

See also Why Are So Many Of The Framework Classes Sealed?.

All that being said, the only difference between an abstract class and a concrete class that was designed for inheritance is that the latter can be instantiated.  Alternatively, a concrete class is like an abstract class that has no methods lacking some form of default implementation.  All of the design considerations that make it OK to inherit from an abstract class also make it OK to inherit from a concrete class that was designed for inheritance.

An interesting example is UserControl.  Being able to derive from UserControl is of high value, since there is a lot of asp.net functionality which leverages polymorphism.

ContentLicense: CC BY-SA 4.0


问:
When opening pdf's in browser, why is "inspect element" available and "view source" not?
When opening pdf's in Chrome and Firefox, the "view source" button is greyed out. "Inspect elemet," however, reveals HTML. Are the browsers simply downloading the file and generating html to display it?</p>

答:
Firefox has used PDF.js as the default PDF viewer since Firefox 19. When you view a PDF in Firefox (provided you haven't changed your browser's PDF settings), you are viewing an HTML rendering of the document. You can't "view source" because there was no HTML source downloaded, but you can "inspect element" because the document you're viewing in-browser is written in HTML, based on the original PDF.

In Chrome (at least v29, in Windows), the browser relies on a native PDF plugin. There is HTML generated, but it looks like:

```<code><html>
    <body><embed ...></body>
</html>
</code>```

where the <embed> element holds the PDF and is rendered by a plugin. This is the same way that images are rendered standalone in Chrome. You wouldn't "view source" on an image, but Chrome allows you to inspect the minimal framing HTML that surrounds the content.

Body:
Firefox has used PDF.js as the default PDF viewer since Firefox 19. When you view a PDF in Firefox (provided you haven't changed your browser's PDF settings), you are viewing an HTML rendering of the document. You can't "view source" because there was no HTML source downloaded, but you can "inspect element" because the document you're viewing in-browser is written in HTML, based on the original PDF.

In Chrome (at least v29, in Windows), the browser relies on a native PDF plugin. There is HTML generated, but it looks like:

<html>
    <body><embed ...></body>
</html>

where the <embed> element holds the PDF and is rendered by a plugin. This is the same way that images are rendered standalone in Chrome. You wouldn't "view source" on an image, but Chrome allows you to inspect the minimal framing HTML that surrounds the content.


答: MVC gets you closer but it is still vastly more formal than PHP really wants to be unless you are using a MVC framework. What is more equivalent to a typical, raw PHP app would be ASP.NET Web Pages. That will support inline code as shown above without the framework and ceremony MVC requires -- down to not needing a separate controller file. Microsoft also packages many of helper libraries so you can integrate things like Facebook or twitter by doing little more than writing @Facebook.Like() in your code.


问:
Is it appropriate for interviewers to ask candidates for their Stack Exchange user name?
Would you consider it appropriate if you were asked for your Stack Exchange username in a software job interview (or as a pre-interview screening question)?

To me, it seems like a very reasonable request, and one that would be extremely informative -- I'm sure I could learn more about a candidate in five minutes by looking at the questions and answers they have posted on Stack Exchange than by a 30 minute interview. But would such a question be bad form? Is it "too personal"?

(Likewise for GitHub, or other public/online code sharing forums.)

答:
There may be cultural differences between Europe and the USA on this, but here's my perspective on this...

When you are applying for a job, as a candidate you are wanting to present yourself, your experience and your ability to do the job in question. You are actively shaping how you are presented to make it a simple choice for the employer to say yes, this is our new employee.

Employers are trying to identify who out of their candidates are capable of doing the work, have the ability to settle into the companies' culture and to hopefully avoid recruiting an employee that's causes more problems than they solve.

So, when I'm recruiting, I do not, and will not ask a candidate for their Stack Exchange identity, or their Facebook username, Twitter account or Google ID. I would consider all these as private personal activities, and would respect the candidates' reasonable expectation that these were not work-related issues, unless by their conduct they made them so.

If on an application, a CV mentioned their Stack Exchange identity, I would ignore it, other than noting that they use Stack Exchange, mildly positive for a graduate, kind of expected for anyone with commercial experience.

My interview process is about giving the opportunity for a candidate to demonstrate that they can do the work we are recruiting for. If they can demonstrate that, and look like a reasonable social mix then they will probably be offered the job.

I could see the Stack Exchange account being used like references, in that job is offered, subject to satisfactory references, but I'm still far from convinced that this is fair, and not undue intrusion into their non-work life.

If as part of an interview process I was asked if I use and contribute on Stack Exchange, the answer would be yes, but if asked for my user name, I would say 'I'll have to get back to you on that'. The reason why is this:  I have never been employed to contribute to Stack Exchange, and until that changes, it's completely part of my private, personal life.

Now, consider what the effect would be on Stack Exchange if your profile became part of the interview process.

People would soon learn that you would have to have a pretty exceptional profile for it to be a significant factor in you being invited for interview, and that it's never going to make up for a bad interview. In short, its only effect will be to prevent you from getting a job.

So, just like you take great care about what goes in your CV, you would do the same on Stack Exchange. No comments, only very carefully thought-out answers, and if you were not 100% sure, you wouldn't post. Would you leave up a down voted answer? Or badly received questions? Of course not.

Stack Exchange will be the worse for it.


问:
How should I handle two crons that update the database?
I'm working on a Bitcoin-clone block explorer (specifically Mincoin) which has a block timer of about 1 minute. For those unfamiliar with Bitcoin, basically a new data structure called a block is propagated to the network about every minute. A block itself holds a lot of information, but three things are the most important:

The previous block before it

The next block in the chain

A data structure containing transactions on the network

So sometimes in Bitcoin there is a "reorganization" which means the network finds that some of the most recent blocks are not valid and it switches over to another miner's branch.

At the moment every 1 minute I get all of the new blocks from the network and I store them into my database. However when a reorganization happens I was previously unable to delete and re-do the block structure of my database.

Now that I've written that functionality in, I'm encountering a new problem. I've got a function that looks in the past 100 blocks and checks if the hash of the block is the same as what my Mincoin client reports. If there was a reorganization, then some blocks will be different. I find the first block that is different and I delete from the database the block before it (so that block can point to the correct new one that will be found), the block itself, and all records of all blocks and transactions that happen after it, then rebuild from there.

The problem is the process of finding and deleting each transaction within the deleted blocks takes more than one minute because of the large amount of data, even though the fields I'm searching on are indexed. So I'm worried that the 1 minute cron I've put on the program will cause a problem where it starts to write again from the database at the same time the process of deleting from the rebuilding function is happening.

I'm using PHP and PDO so I have a PDO transaction for the rebuilding function, but this just adds more confusion. If the PDO transaction starts deleting records, then during that process a new cron finds some new blocks and writes them to the database, then the PDO transaction ends, which data will be stored? Will it cause an error? How is the best way to handle this -- should I write some field into the database that controls the regular cron (simply put a switch 0 or 1 for on and off) and keep the switch disabled while the rebuilding function is doing its thing?

I'm not sure how to structure the flow of this program to ensure I am not causing my database to have inaccurate data in it.

答: Here is one possible solution: instead of putting your jobs directly into the cron list, create a queueing mechanism which starts jobs sequentially and does not start a new job before the previous one has not ended. The advantage is that you don't to change anything in your database and don't need to provide any locking fields. There are several solutions possible to implement such a queue, for example, you could use cron to trigger the queue management, or to add the same job every minute to queue (whilst other jobs are added just once or in different time intervals).</p>


问:
MVC Architecture -- How many Controllers do I need?
I have been coding for a while, but mostly scripts and simple applications. I've moved into a new role where it is all about developing Web Apps and using a proper MVC architecture, so I am desperately trying to learn about all that very quickly.

I hope this question is not too similar to "Best Practices for MVC Architecture" but as I am going through a few different tutorials, I noticed that some have multiple controllers for different things.

How many controllers does a single web app need?

I realize this would be difficult to answer without an example so I'll provide one:

Application:

User logs in.

User can do one of three things:

a)  Upload a file (stored in a mongodb database with meta data).

b)  Search for a file.

c)  Log out.

My question is a general one, but I gave the example to help out anyone trying to answer.

答:
Most of your code would be happening in a business layer right? If that's the case then all you are really doing in your controller is returning data to the view.

Not really sure if I'm a fan of separating the controllers into subtypes. Whilst you should maintain separation of concerns I think subtypes is going a little too far. Also you need to be careful in cases where heavy objects are initialized in the constructor or a controller. For example: in your example you would want a heavy object, used only for search/upload file to be released when the user is on the login page.

It's better to have a controller per logic unit, for example AccountController (login, registration, logout), FileController (search, upload) and so on.


答: Man, that's an ancient variant of the BSD license.  U.C.Berkeley rewrote the canonical BSD license in 1999 to remove the "advertising materials" clause.  It's self-contradictory - you must include the attribution including the organization's name, but you cannot include the organization's name.</p>


答:
If I just put the copyright notice of the used library, is that considered as I am promoting my product by mentioning the library copyrights notice?

That's not relevant.

The restriction of the license is that you can't claim that the author of the BSD code is somehow endorsing or is involved with your product; only that your software includes code they wrote.

Shall I seek a written permission? or I just need to add the copyright notice only?

The only thing you are required to do is to put the Copyright notice and a copy of the full license in your documentation and in all other places you put Copyright claims or notices. It's sufficient to put a copy of the license in among other documentation as a file in the copies of your software that you distribute.


问:
Generics and Type-erasure
Generics in Java are implemented using type erasure. The JLS  says that the inspiration was backward compatibility. Where as on the other hand C# generics are reifiable.

Theoretically what are the advantages and disadvantages by having Generics as "erasure" or "reifiable"?

Is Java missing onto something?

答:
Another advantage of erased generics, is that different languages that compile to the JVM employ different strategies for generics, e.g. Scala's definition-site versus Java's use-site covariance. Also Scala's higher-kinded generics would have been more difficult to support on .Net's reified types, because essentially Scala on .Net ignored C#'s incompatible reification format. If we had reified generics in the JVM, most likely those reified generics wouldn't be suitable for the features we really like about Scala, and we'd be stuck with something suboptimal. Quoting from Ola Bini's blog,

What this all means is that if you want to add reified generics to the
  JVM, you should be very certain that that implementation can encompass
  both all static languages that want to do innovation in their own
  version of generics, and all dynamic languages that want to create a
  good implementation and a nice interfacing facility with Java
  libraries. Because if you add reified generics that doesn’t fulfill
  these criteria, you will stifle innovation and make it that much
  harder to use the JVM as a multi language VM.

Personally I don't consider the necessity of using a TypeTag context bound in Scala for conflicting overloaded methods as a disadvantage, because it moves the overhead and inflexibility of reification from a global (whole program and all possible languages) to a use-site per language issue that is only the case less frequently.

Title: Generics and Type-erasure


问:
Creating a System Sequence Diagram from an [extended] use case
As I have been taught - one controller = one use case.

But I have:

OutsiderController

SupplierController (which extends OutsiderController)

SubContractorController (which also extentds OutsiderController)

And I want to do the SSD for SupplierController and SubContractorController. What do I do? Do I write in both SSDs the methods from OutsiderController?

答: Providing one System Sequence Diagram (SSD)  will be enough if all the Controllers do the same flow with minor differences </p>


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
For databases I go with:

```Table: Things

ID       Name
1        Bodkin Van Horn
2        Hoos-Foos
3        Hoos-Foos
4        Hot-Shot
5        Marvin O'Gravel Balloon Face
6        Snimm
7        Marvin O'Gravel Balloon Face
8        Marvin O'Gravel Balloon Face
9        Dave```

Write me some SQL that will de-duplicate a table like this based on the name (and I don't care which ID I get back but whichever one is returned must be valid for that name).  So the table once the correct SQL has been applied to it will present something like:

```Table: Things

ID       Name
1        Bodkin Van Horn
2        Hoos-Foos
4        Hot-Shot
5        Marvin O'Gravel Balloon Face
6        Snimm
9        Dave```

I like it because:

De-duplication is a real world problem

There are a bunch of ways to do it

I think that pretty much all of those ways need you to either understand (slightly) more complex SQL (essentially GROUP BY and HAVING) or the ability to reason through chaining multiple simpler statements.

Because of this last bit even if they're struggling with syntax or whatever, you can ask them what they're thinking and talk through it that way.

It references Dr. Seuss

(This is where I find that there is some entirely trivial way of doing this and I've been over complicating it all these years).

Body:
For databases I go with:

Table: Things

ID       Name
1        Bodkin Van Horn
2        Hoos-Foos
3        Hoos-Foos
4        Hot-Shot
5        Marvin O'Gravel Balloon Face
6        Snimm
7        Marvin O'Gravel Balloon Face
8        Marvin O'Gravel Balloon Face
9        Dave

Write me some SQL that will de-duplicate a table like this based on the name (and I don't care which ID I get back but whichever one is returned must be valid for that name).  So the table once the correct SQL has been applied to it will present something like:

Table: Things

ID       Name
1        Bodkin Van Horn
2        Hoos-Foos
4        Hot-Shot
5        Marvin O'Gravel Balloon Face
6        Snimm
9        Dave

I like it because:

De-duplication is a real world problem

There are a bunch of ways to do it

I think that pretty much all of those ways need you to either understand (slightly) more complex SQL (essentially GROUP BY and HAVING) or the ability to reason through chaining multiple simpler statements.

Because of this last bit even if they're struggling with syntax or whatever, you can ask them what they're thinking and talk through it that way.

It references Dr. Seuss

(This is where I find that there is some entirely trivial way of doing this and I've been over complicating it all these years).


问:
Is there a better way to organize my module tests that avoids an explosion of new source files?
I've got a neat (so I thought) way of having each of my modules produce a unit-test executable if compiled with the -DTESTMODULE flag. This flag guards a main() function that can access all static data and functions in the module, without #including a C file.

From the README:

  -- Modules --
The various modules were written and tested separately before being
coupled together to achieve the necessary basic functionality.
Each module retains its unit-test, its main() function, guarded
by #ifdef TESTMODULE. `make test` will compile and execute all the
unit tests, producing copious output, but importantly exitting with
an appropriate success or failure code, so the `make test` command will
fail if any of the tests fail.

    Module TOC
    __________

test   obj     src    header structures CONSTANTS
----   ---     ---     ---   --------------------
m      m.o     m.c     m.h   mfile mtab TABSZ
s      s.o     s.c     s.h   stack STACKSEGSZ
v      v.o     v.c     v.h   saverec_
       f.o     f.c     f.h    file
ob    ob.o    ob.c    ob.h   object
ar    ar.o    ar.c    ar.h    array
st    st.o    st.c    st.h    string
di    di.o    di.c    di.h   dichead dictionary
nm    nm.o    nm.c    nm.h    name
gc    gc.o    gc.c    gc.h    garbage collector
itp          itp.c   itp.h   context
  osunix.o osunix.c osunix.h  unix-dependent functions
```

<p>It's compile by a tricky bit of makefile,</p>

<pre class="lang-none prettyprint-override"><code>m:m.c ob.h ob.o err.o $(CORE) itp.o $(OP)
        cc $(CFLAGS) -DTESTMODULE $(LDLIBS) -o $@ $< err.o     ob.o s.o ar.o st.o v.o di.o gc.o nm.o itp.o $(OP) f.o
</code>```

where the module is compiled with its own C file plus every other object file except itself.

But it's creating difficulties for the kindly programmer who offered to write the Autotools files for me. So the obvious way to make it "less weird" would be to bust-out all the main functions into separate source files. But, but ... Do I gotta?

答:
Here is a simple solution:

Write wrapper files that define TESTMODULE and then include the appropriate .c file. For example:

```<code>// m_test.c

#define TESTMODULE
#include "m.c"
</code>```

If you were to adjust your .c files so that the actual code that would go into the .o file was not compiled when you had TESTMODULE defined, you could compile all the .o files normally, and then compile the *_test.c files and link with all of the .o files  (rather than excluding the one that was being compiled that had the test code).

This allows you to keep the tests and the definition in the same files but simplify the build environment.

Body:
Here is a simple solution:

Write wrapper files that define TESTMODULE and then include the appropriate .c file. For example:

// m_test.c

#define TESTMODULE
#include "m.c"

If you were to adjust your .c files so that the actual code that would go into the .o file was not compiled when you had TESTMODULE defined, you could compile all the .o files normally, and then compile the *_test.c files and link with all of the .o files  (rather than excluding the one that was being compiled that had the test code).

This allows you to keep the tests and the definition in the same files but simplify the build environment.


答:
How about a simple case where you MUST use override:

Any class that implements the IDisposable interface.  (And any class that owns a resource that must be cleaned up should implement it.)

Title: Why we use virtual and override keywords in c#

Body: Can anyone explain me what's the point of overriding base class implementations (if its not abstract), because it's not ethical move to modify features of the parent class according to the wishes of derived classes. The best way is to make the base classes abstract and carry on the inheritance chain. Whereas when designing a class hierarchy initially we gather or elicit  all the essential requirements/features that should be belonged to a base class. Therefore, in a middle of a project we do not need to change base class implementations. According to my knowledge, base class implementation should be a constant. Thus, under this aspect, there's no real use of "override" keyword in c#. If it's not so please explain me with an example.</p>


问:
Use ruby's array sort() method, or add items in correct place with a binary lookup?
If I am loading a whole load of items (un-ordered words from a file or something) would it be more efficient to load them all to a Ruby array, and then use the built in sort! method or to do a binary lookup for the place of each item in the list as I load it, and add it in that position.

Basic code:

```<code>array = []
lines.each do |line|
    array.push line
end
array.sort!
</code>```

vs

```<code>array = []
lines.each do |line|
    array.insert(find_index(line), line)
end
</code>```

find_index() would lookup the correct index for the item in the array using a binary search.

答: array.insert is O(n) for insertions in the middle (because it has to copy a part of the array), making the second variant O(n^2), while push is O(1), and sort! is O(n log n), so the first variant is only O(n log n). Also the first variant looks cleaner.


答:
Something called aff_z, which was part of my engineering school's C examinations and was used as a "dummy" test to have students fail when coming back from holidays (our marking system implied that failing a test stopped the marking, so failing that dummy test would invalidate your whole test. Forces you to pay attention to moronic details). I did reuse it once or twice during interviews.

Anyways... I forgotten the exact formulation but it was something like this...

```<code>Write a function taking a single char parameter named c and returning nothing (void).
You function must satisfy the following requirements:

 - if c is bigger or equal to 0, then print 'z' to standard output
 - if c is stricly smaller than 0 , then print 'z' to standard output
 - in any other case, print the letter 'z' to standard output
</code>```

The sad thing is that not only some students would come up with extremely convoluted solutions when the answer is fairly obvious, but that some would even manage to fail.

And believe it or not, it did happen during interviews as well.

Running it in interviews was fairly fun, as some applicants would start writing the possible branches and then realize what is wrong (obviously, if you only ask them orally, that is quite understandable that they do so as you speak... but if you give it in writing, I find it puzzling...)

It's dumb, but I guess it's a minimalistic screening (similarly, when hiring JS programmers, I always ask how to declare a variable, and then depending on their answer whether or not using var makes any difference at all. Quite often a sad moment, honestly.)

Title: What is your favorite whiteboard interview problem?

Body:
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

Body:
Something called aff_z, which was part of my engineering school's C examinations and was used as a "dummy" test to have students fail when coming back from holidays (our marking system implied that failing a test stopped the marking, so failing that dummy test would invalidate your whole test. Forces you to pay attention to moronic details). I did reuse it once or twice during interviews.

Anyways... I forgotten the exact formulation but it was something like this...

Write a function taking a single char parameter named c and returning nothing (void).
You function must satisfy the following requirements:

 - if c is bigger or equal to 0, then print 'z' to standard output
 - if c is stricly smaller than 0 , then print 'z' to standard output
 - in any other case, print the letter 'z' to standard output

The sad thing is that not only some students would come up with extremely convoluted solutions when the answer is fairly obvious, but that some would even manage to fail.

And believe it or not, it did happen during interviews as well.

Running it in interviews was fairly fun, as some applicants would start writing the possible branches and then realize what is wrong (obviously, if you only ask them orally, that is quite understandable that they do so as you speak... but if you give it in writing, I find it puzzling...)

It's dumb, but I guess it's a minimalistic screening (similarly, when hiring JS programmers, I always ask how to declare a variable, and then depending on their answer whether or not using var makes any difference at all. Quite often a sad moment, honestly.)


问:
Is there any way to limit the scope of a knockout.js application?
I have a legacy project which I have been approved to work in a knockout.js module.  This is great, however the application is extremely complex and I need to use some of the pre-built form validation of our application.

My form validators work fine until a dynamic template gets switched out.  I can't for the life of me figure out the error. Nothing in the console and my vast debugging efforts have been fruitless.

I'm thinking that my solution could be something along the lines of limiting the scope of the knockout application similar to how one can declare ng-app in angular.js.

I can't find a working example of how to do this or any documentation relevant to knockout.js

答:
The scope to which elements knockout binds itself with is determined from the way you call ko.applyBindings. It takes two parameters, an object to be used as the root view model and an element to "apply" the bindings on. The latter parameter is optional and usually tutorials and documentation leaves it out like this:

```<code>ko.applyBindings(viewModel);
</code>```

By default, without the second parameter, knockout will apply the bindings on the whole document. If you want to limit the bindings from one specific HTML element you can specify it as the second parameter to be used as a parent instead of the document. Pretty much like this:

```<code>var parent = document.getElementById('someElementId');
// or if you are using jquery, use $('#someElementId')[0]

ko.applyBindings(viewModel, parent);
</code>```

It is briefly described in this section of the knockout docs.

Body:
The scope to which elements knockout binds itself with is determined from the way you call ko.applyBindings. It takes two parameters, an object to be used as the root view model and an element to "apply" the bindings on. The latter parameter is optional and usually tutorials and documentation leaves it out like this:

ko.applyBindings(viewModel);

By default, without the second parameter, knockout will apply the bindings on the whole document. If you want to limit the bindings from one specific HTML element you can specify it as the second parameter to be used as a parent instead of the document. Pretty much like this:

var parent = document.getElementById('someElementId');
// or if you are using jquery, use $('#someElementId')[0]

ko.applyBindings(viewModel, parent);

It is briefly described in this section of the knockout docs.


答:
A suggestion from my kindly programmer friend:

one solution for the link problem would be to use a different define
   for each file (TEST_MODULE_AR, TEST_MODULE_ITP, etc...)

And that seems simpler.

Title: Is there a better way to organize my module tests that avoids an explosion of new source files?

Body:
I've got a neat (so I thought) way of having each of my modules produce a unit-test executable if compiled with the -DTESTMODULE flag. This flag guards a main() function that can access all static data and functions in the module, without #including a C file.

From the README:

  -- Modules --
The various modules were written and tested separately before being
coupled together to achieve the necessary basic functionality.
Each module retains its unit-test, its main() function, guarded
by #ifdef TESTMODULE. `make test` will compile and execute all the
unit tests, producing copious output, but importantly exitting with
an appropriate success or failure code, so the `make test` command will
fail if any of the tests fail.

    Module TOC
    __________

test   obj     src    header structures CONSTANTS
----   ---     ---     ---   --------------------
m      m.o     m.c     m.h   mfile mtab TABSZ
s      s.o     s.c     s.h   stack STACKSEGSZ
v      v.o     v.c     v.h   saverec_
       f.o     f.c     f.h    file
ob    ob.o    ob.c    ob.h   object
ar    ar.o    ar.c    ar.h    array
st    st.o    st.c    st.h    string
di    di.o    di.c    di.h   dichead dictionary
nm    nm.o    nm.c    nm.h    name
gc    gc.o    gc.c    gc.h    garbage collector
itp          itp.c   itp.h   context
  osunix.o osunix.c osunix.h  unix-dependent functions
```

<p>It's compile by a tricky bit of makefile,</p>

<pre class="lang-none prettyprint-override"><code>m:m.c ob.h ob.o err.o $(CORE) itp.o $(OP)
        cc $(CFLAGS) -DTESTMODULE $(LDLIBS) -o $@ $< err.o     ob.o s.o ar.o st.o v.o di.o gc.o nm.o itp.o $(OP) f.o
</code>```

where the module is compiled with its own C file plus every other object file except itself.

But it's creating difficulties for the kindly programmer who offered to write the Autotools files for me. So the obvious way to make it "less weird" would be to bust-out all the main functions into separate source files. But, but ... Do I gotta?


问:
Unit testing methods which access an Internet API
Hi I'm developing a Wordpress plugin which accesses a couple of API's (Amazon Product API, Flickr, Freebase, Ebay).
I've already started writing unit tests for it but I'm still wondering if its really the way to go since it takes a lot of time downloading data from the API primarily because my download speed isn't that fast (around 2 Mb/s max).
Currently it takes 2 hours or more to run the whole test suite and sometimes I even reach the API limit and the test won't pass.

Is there a better way of doing this? Perhaps automating the test or even allow me to upload the tests somewhere which has a faster download speed.

Do I really need to be testing methods which access the API to begin with? Can I just make use of a mock data instead of querying the API directly?

Thanks in advance!

答:
You would provide a facade for each of these APIs, which is essentially a wrapper class. So each of the API functions you are going to use will be wrapped by your own code, which you can then also mock.

This means you would have a AmazonProductAPIWrapper class which directly calls each of the APIs you are going to be consuming.


问:
Learning how to integrate JavaScript with other languages
After learning JavaScript syntax, what are some good resources for learning about integrating JavaScript with other languages (HTML, XML, CSS, PHP) to create real, useful applications?

I'm most interested in reading articles or other people's code - not so interested in books. Basically, I'm looking to move from programming puzzle-solvers to programming complex applications and could use some advice.

答: If you know these languages you mentioned it is very easy to integrate Js with these . Specially with Html and css  cause these are client side application .. With php and c# also its not that tricky</p>


问:
How do I make sense of the javascript frameworks explosion ? Should I learn them all?
For a beginner web developer who is still doing web development the conventional way (PHP/J2EE/Struts on server side, HTML/CSS/Javascript on client side), I was bowled over by the recent blog post on Trello technology stack.

I can't help feeling overwhelmed by the list of new technologies and frameworks mentioned in this post and specifically the ubiquitousness of Javascript frameworks.

My question is, is this the future of web development? Are there any articles, websites or resources that can help me make sense of where each of these new frameworks fit in a modern web application ?

答:
Depends on your requirement . Then you need to review the frame works . Which ever will suited best for you go for that
http://javacourseblog.blogspot.in/2013/08/mvc-in-javascript-angular-vs-backbone_1416.html</p>


问:
Database designs, parallel tables, or extra fields?
I run a database for a sequencing centre. There are other developers getting data out of this and running automated and semi automated processes from the database.

We are discussing a change to the database.

At the moment we have a library that has a one-to-one relationship with a multiplex_index, which can be used to identify the library. We now want to add an optional GBS_index to each library (another optional one-to-one relationship). So each library will have a multiplex_index and optionally a GBS_index.

The columns stored on the new GBS_index will be the same as for the multiplex_index. So we have 2 options for storing the GBS_index data.

1) Store the GBS_index data in the original multiplex_index table, and identifying it by its "type" field.

2) We can add a parallel table for the GBS_index, which mirrors the multiplex_index table.

I favour the second parallel table option, as I see it as less likely to break existing code (scripts query the database for a list of multiplex_indexes, these would need to exclude the GBL_indexes in this case).

Conceptually the two types of indexes are both "multiplex indexes", but used in a slightly different manner.

Are there any strong arguments for or against either option?

Ok, a quick explanation of DNA sequencing may help.

DNA sequencing involves taking DNA from cells and splitting them up into "reads" of approx 200 base pairs (each base pair is like a DNA char A,T,G or C).

We load libraries (DNA from a prepared biological sample) on to a machine and sequence them. The two types indexes I talked about are a another piece of DNA with a known sequence, that is attached to the start of the library DNA before it is sequenced. That way, we can read the first bit of sequence we can identify what library each read (~200 chars) came from. (We are generally interested in the numbers of reads matching a position on a reference genome).

Now we can have one (multiplex) or two (multiplex + GBS) indexes at the start of the library DNA (one comes after the other), which form a unique combination to identify the library.

Initially two libraries with the same multiplex_index should not be loaded together, as you couldn't identify them from the multiplex_index sequence. Now the combination of the two indexes should be unique.

答:
Parrallel Table:

You are correct that using a new "parallel" table for GBS_index will be less likely to break existing processes. Even if you could reuse the old table without an extra type-field you would be changing the relationship from a 1-1 to a 1-many. This would be a breaking change.

The draw back is this design is not data driven. What if a 3rd type of index is introduced? 4th, 5th.... 20th? I'm not familiar with DNA but if the types can scale it would require a query change every time a new type is introduced. Adding a type with a parallel table may not be a "breaking" change but it would require a change nonetheless every time a type is introduced. Writing queries against 20+ tables would be cumbersome.

Add an extra type field:

This design would be a breaking change. You are changing the relationship from 1-1 to 1-many. But if the relationship really is 1-many then it "should" be modeled that way in the database.

This design is also data driven. Every time a new type is introduced you merely add data to the "type" lookup table. No query changes required (except for the initial change you are doing now of course).

Conclusion:

I prefer adding the extra field as it models the 1-many relation with a 1-many relationship in the database. The parallel table emulates a 1-many with multipe 1-1 relations and is not data-driven for new types in the future.

Both designs will work. It comes down to how critical and political a breaking change is. And whether the types are fixed at 2 or scale to N.


问:
Objects of different programming languages
Apparently, there are some resemblance between objects in JavaScript and dictionaries in Python. Each language defines an object a little different (and there is some logic that all definitions to be the same as in physics).

How are objects alike and how do they differ between JavaSscript, Python and PHP?

答:
Objects really represent the same thing in all three languages: a bundling of state and operations. What truly differs is their implementation of this idea.

The largest difference is that Python & PHP are class-based object-oriented systems, meaning that the "templates" for objects are pre-defined. When a new intance of one of these templates or classes is initialized, the class's pattern or definition is used to shape the newly initialized object.

In JavaScript, the object system is prototype based. Rather than having some definition as to how objects of the same type ought to be defined and initialized, JavaScript takes a special object, a prototype, and clones it to create a new instance of that class.

All three languages are dynamic, which sets them apart from the C#/Java ecosystem in that you still have a good deal more flexibility. In JavaScript, Python and PHP you can dynamically add new properties and even functions at runtime whereas this is not truly possible in C#/Java.

See the following links for more information:

http://en.wikipedia.org/wiki/Prototype-based_programming

http://en.wikipedia.org/wiki/Class-based_programming


问:
I have to use Visual Studio 2005. What are good alternatives to using LINQ?
I have recently started a new job and am being forced to use VS 2005 and .NET 2. This has been quite painful for a number of reasons, but the one big change from VS 2005 to its successors was the introduction of LINQ and extension methods.

A common pattern that I used to follow when using enumerations was the following:

```<code>foreach(var myObject in myObjects.Where(x => x.Property == someValue)
{
    //Do some stuff
}
</code>```

What I am having difficulty with is coming up with a succinct way of expressing the same statement in C# 2.  The best I have come up with is the following:

```<code>foreach(MyObject myObject in myObjects)
{
    if(myObject.Property == someValue)
    {
        //Do some stuff
    }
}
</code>```

Is there a more effective or efficient way of writing this code?

How would you write C# 2 code so that it can most easily be transformed into C# 5 code (we will be upgrading to VS2012/.NET 4.5 after the next release)?

答:
Before LINQ has been introduced we used PowerCollections (https://powercollections.codeplex.com/). To give you some examples:

```<code>Algorithms.Convert(enumerable, converter) <=> enumerable.Select(converter)
Algorithms.Exists(enumerable, predicate) <=> enumerable.Any(predicate)
Algorithms.FindFirstWhere(enumerable, predicate) <=> enumerable.FirstOrDefault(predicate)
</code>```

and so on.
Unfortunately, you will have to use this clunky "delegate (...) { ... }" syntax instead of lambda syntax, but technically it's the same thing.

Good luck!

Body:
Before LINQ has been introduced we used PowerCollections (https://powercollections.codeplex.com/). To give you some examples:

Algorithms.Convert(enumerable, converter) <=> enumerable.Select(converter)
Algorithms.Exists(enumerable, predicate) <=> enumerable.Any(predicate)
Algorithms.FindFirstWhere(enumerable, predicate) <=> enumerable.FirstOrDefault(predicate)

and so on.
Unfortunately, you will have to use this clunky "delegate (...) { ... }" syntax instead of lambda syntax, but technically it's the same thing.

Good luck!