问:
Binding software to one PC
I have generated a .exe of a Python script. I wish to give this software as a demo version to few of clients.

For the same I want to bind the software to a particular PC. i.e. If I install the software one a particular PC, the client should not be able to copy the .exe from his PC to some other PC and use the software.

What are the ways in which I can ensure this. I have heard that binding the MAC address of the PC with software is one of the options. Please correct me if I am wrong or suggest other methodologies of achieving the desired task.

答:
This is an ages-old problem. The only working solution is to make your executable crucially depend on a piece of hardware the user does not control. This is usually either a networked server you control, or a hardware dongle. Both should do some non-trivial and vital computations, else the dependency can be short-circuited using a debugger and then a patch.

Usually this approach works reasonably well only if you make substantial money form each installation (to offset the cost of the dongle), or have quite many installations (to offset the cost of creating and maintaining the server).

If you want your demo version stay demo, actually remove some important code from it, and build a separate binary. Often demos allow to do everything but not to save the results.

Also, Python programs are not particularly easy to protect from reverse-engineering and modification.

In short, forget the technical means, rethink your sales model.

Title: Binding software to one PC


答:
Short version: It can't be done, so don't bother.

Long version: What you're trying to do has been tried ever since the invention of the floppy disc.  They call it "copy protection" or more recently "DRM", and it does not work, never has, and never can.  Trying to make bytes that are not copyable is like trying to make water that's not wet.  This doesn't keep people from putting tons of research into it, generally as an anti-piracy scheme.

Microsoft, who spends more money on R&D each quarter than many of us will see in our entire lives, put a huge amount of work into it for Windows 8.  A working crack was available before Windows 8 was even released to the public.  If they can't make it work, with all those resources available, do you really think you even have the slightest chance?

Copying stuff that "shouldn't" be copied is not a technology issue; it's a social issue.  You and the person doing the copying disagree on whether or not it should be copied.  There's a well-established system for dealing with social issues of this sort: contract law.  Get them to sign a contract that places liability on them if they use it in certain ways, and that will do more than all the technical attempts to make bytes un-copyable in all the world.

ContentLicense: CC BY-SA 3.0

Title: Binding software to one PC

Body:
I have generated a .exe of a Python script. I wish to give this software as a demo version to few of clients.

For the same I want to bind the software to a particular PC. i.e. If I install the software one a particular PC, the client should not be able to copy the .exe from his PC to some other PC and use the software.

What are the ways in which I can ensure this. I have heard that binding the MAC address of the PC with software is one of the options. Please correct me if I am wrong or suggest other methodologies of achieving the desired task.


问:
The difference between "concurrent" and "parallel" execution?
What is the difference between the terms concurrent and parallel execution?  I've never quite been able to grasp the distinction.

The tag defines concurrency as a manner of running two processes simultaneously, but I thought parallelism was exactly the same thing, i.e.:  separate threads or processes which can potentially be run on separate processors.

Also, if we consider something like asynchronous I/O, are we dealing with concurrency or parallelism?

答:
Concurrent execution is the generalized form of parallel execution. For example parallel program can also be called concurrent but reverse is not true.

Concurrent execution is possible on single processor (multiple threads, managed by scheduler)

Parallel execution is not possible on single processor but on multiple processors. (One process per processor)

For details read this research paper
Concepts of Concurrent Programming


问:
In Agile, what do you do with a severly underpointed story?
Our team is pretty good at planning/pointing, but once in a blue moon, we will have a severely underpointed story. I'm talking something we thought it would take a couple days and we realize its going to take the whole sprint. What is the recommended approach to fix this when we realize our error so that it doesn't make our velocity unusable for the next sprint planning?</p>

答:
As soon as you identify a story that is too large to absorb in the current iteration your team needs to do the following ASAP:

Communicate your concern to the whole team. Since you tagged this scrum you need to talk to the Scrum Master and Product Owner specifically, but everyone needs to be aware.

Identify what it is that made it take more time. Odds are there was something missed during estimation. Either a missed requirement or something really was tougher than it looked (e.g. some feature cannot be implemented the way you assumed earlier due to a framework limitation).

Come up with a new estimate given the new information.

Schedule it.

If it is too big for a single sprint or it makes sense to split it into multiple stories, break it up into multiple stories and move them to the backlog. If possible, move one of the new (smaller) stories back into the current sprint in the now-empty space.

Else if its new size is small enough for the current iteration, leave it in place (not likely in your case but a good step to leave in for the general case).

Else move it to the backlog.

Letting the story slip can look bad, but you know what is worse? Perpetual crunch-time and everything else that comes with procrastination and lack of planning.


问:
How to write proper documentation for references in a docblock?
I am adding documentation to PHP code using the phpDocs tool:

```<code>/**
* This is a summary
*
* This is a description
*
* @use This function is called here and here
*/
function doSomething(){

}
</code>```

I am just wondering if I want to add within this docblock a 'use' tag that says where this function doSomething() is called how do I go doing it properly?

答:
Don't do it.  There is no proper way of doing it.

Documenting which places a function gets called from is a remnant of the structured programming paradigm of the seventies and the eighties.  I actually do remember back in 1989 a professor asking us to document functions this way; I never heard of anyone doing such a thing ever since. This paradigm has been dead for more than two decades. We have moved on.

A function that does not stand on its own is not worth having. If a function does in fact stand on its own, then who calls it is of no concern to the function, it does not affect what the function does, nor how it does it.  So, you really don't care who calls it. Anyone may call it, and they don't need permission from a doc comment to do it.

To put it in different words, a well written function is by definition a function that need not, and should not, care who calls it.  By including information about who calls it in its documentation you are tempting the reader to suspect that this function may somehow be tightly coupled with these particular callers, forcing the reader to double check to make sure that in fact it is not, because tight coupling would be a terrible thing to do.

Also, the set of places that call a certain function tends to change drastically as you keep working on the code base, so this particular kind of documentation becomes outdated very fast, while at the same time it is something that you can ask your IDE at any moment by simply pressing a key combination, (it is usually called "Find References" or something similar,) and the IDE will tell you in milliseconds, and it will do that far more accurately than any documentation ever would.

So: absolutely pointless.


问:
Mixing reactive programming with non-reactive return requirements

Variable context from an initial non-reactive caller

The whole application cannot be reactive i.e. this method needs to return a result here

```<code>public string GetTextOfInterest()
{
    var searchQuery = "Single Responsibility";
    var titleShouldContain = "SRP";
    var uriShouldContain = "pattern";
    var pageShouldContain = "arguments";
    return this.NonReactive(searchQuery, titleShouldContain, uriShouldContain,pageShouldContain);
}
</code>```

Non-reactive blocking implementation

This non-reactive implementation works fine

```<code>private string NonReactive(string searchQuery, string titleShouldContain, string uriShouldContain, string pageShouldContain)
{
    // Googler returns result directly here and does not move on before
    var gooResult = this.googler.Search(searchQuery);
    if (gooResult.Title.Contains(titleShouldContain) && gooResult.Uri.Contains(uriShouldContain))
    {
        // Blocking here again to wait for this result
        var scrResult = this.scraper.Scrape(gooResult.Uri);
        if (scrResult.Body.Contains(pageShouldContain))
        {
            // Blocking up to this point ensures sequential execution and ability to return this final result
            return scrResult.Body;
        }
    }
    return null;
}
</code>```

How to answer reactively?

This reactive implementation does not work

```<code>private string ReactiveButUseless(string searchQuery, string titleShouldContain, string uriShouldContain, string pageShouldContain)
{
    googler.Stream.Subscribe(
        gooResult =>
            {
                if (gooResult.Title.Contains(titleShouldContain) && gooResult.Uri.Contains(uriShouldContain))
                {
                    scraper.Stream.Subscribe(
                        scrResult =>
                            {
                                if (scrResult.Body.Contains(pageShouldContain))
                                {
                                    // Get final result here, but no good as method has already returned (null)
                                    var finalResult = scrResult.Body;
                                }
                            });
                    scraper.Scrape(gooResult.Uri);
                }
            });
    googler.Search(searchQuery);
    return null;
}
</code>```

Is there any way of implementing a working reactive solution?

without having to change the Googler and Scraper implementation because they need to stay clean and reusable for other purposes (otherwise could pass in delegates)

and without blocking? Could wait for result of stream and block, but then it is no better than the non-reactive blocking implementation? Or is it just not possible to mix reactive and non-reactive styles without blocking?

答:
Short answer is no.

The two things you want are mutually exclusive, you cannot continue a code block while waiting for an answer from an asynchronous server and somehow guarantee to get it back before the code block returns (with the exception of async/await [see below]).

That being said if you want to use Reactive, there are a couple approaches to try:

First some clean up:

```<code>    private IObservable<string> GetScrapeStream(Uri resultUri, string pageShouldContain)
    {
        return Observable.Create<string>(observer =>
        {
            var subscription =
                scraper.Stream
                .Where(result => result.Body.Contains(pageShouldContain))
                .Select(result => result.Body)
                .Subscribe(observer);

            scraper.Scrape(resultUri);
            return subscription;
        });
    }

    private IObservable<string> GetGoogleStream(string searchQuery,
                                                string titleShouldContain,
                                                string uriShouldContain,
                                                string pageShouldContain)
    {
        return Observable.Create<string>(observer =>
        {
            var subscription =
                googler.Stream
                .Where(result => result.Title.Contains(titleShouldContain) &&
                                 result.Uri.Contains(uriShouldContain))
                .SelectMany(result =>
                {
                    return GetScrapeStream(result.Uri, pageShouldContain);
                })
                .Subscribe(observer);

            googler.Search(searchQuery);
            return subscription;
        });
    }
</code>```

Now since I already said you can't have your cake and eat it too, you have two options really:

```<code>//This will block, and Last() is actually deprecated, so it will probably be going away
private string ReactiveButBlocking(string searchQuery,
                                   string titleShouldContain,
                                   string uriShouldContain,
                                   string pageShouldContain)
{
  return GetGoogleStream(searchQuery, titleShouldContain, uriShouldContain, pageShouldContain)
         .Last();
}
</code>```

If you have at least .Net 4.5 you also have async/await available to you, which are supported very nicely in Rx, however, your method signature will change slightly, and in the caller method you will need to do string result = await ReactiveAndAsync(...); Realize though that this is not your standard blocking, because it actually frees up the the thread until the method returns a value.

see reference

```<code>private async Task<string> ReactiveAndAsync(string searchQuery,
                                  string titleShouldContain,
                                  string uriShouldContain,
                                  string pageShouldContain)
{
  return await GetGoogleStream(searchQuery, titleShouldContain, uriShouldContain, pageShouldContain);
}
</code>```

tl;dr

Rx doesn't do anything magical, it won't defeat causality and it isn't perfect for every use case, at least not until 3.0. However, it will let you create logic streams that hopefully improve readability, extensibility and a separation of concerns.

Body:
Short answer is no.

The two things you want are mutually exclusive, you cannot continue a code block while waiting for an answer from an asynchronous server and somehow guarantee to get it back before the code block returns (with the exception of async/await [see below]).

That being said if you want to use Reactive, there are a couple approaches to try:

First some clean up:

    private IObservable<string> GetScrapeStream(Uri resultUri, string pageShouldContain)
    {
        return Observable.Create<string>(observer =>
        {
            var subscription =
                scraper.Stream
                .Where(result => result.Body.Contains(pageShouldContain))
                .Select(result => result.Body)
                .Subscribe(observer);

            scraper.Scrape(resultUri);
            return subscription;
        });
    }

    private IObservable<string> GetGoogleStream(string searchQuery,
                                                string titleShouldContain,
                                                string uriShouldContain,
                                                string pageShouldContain)
    {
        return Observable.Create<string>(observer =>
        {
            var subscription =
                googler.Stream
                .Where(result => result.Title.Contains(titleShouldContain) &&
                                 result.Uri.Contains(uriShouldContain))
                .SelectMany(result =>
                {
                    return GetScrapeStream(result.Uri, pageShouldContain);
                })
                .Subscribe(observer);

            googler.Search(searchQuery);
            return subscription;
        });
    }

Now since I already said you can't have your cake and eat it too, you have two options really:

//This will block, and Last() is actually deprecated, so it will probably be going away
private string ReactiveButBlocking(string searchQuery,
                                   string titleShouldContain,
                                   string uriShouldContain,
                                   string pageShouldContain)
{
  return GetGoogleStream(searchQuery, titleShouldContain, uriShouldContain, pageShouldContain)
         .Last();
}

If you have at least .Net 4.5 you also have async/await available to you, which are supported very nicely in Rx, however, your method signature will change slightly, and in the caller method you will need to do string result = await ReactiveAndAsync(...); Realize though that this is not your standard blocking, because it actually frees up the the thread until the method returns a value.

see reference

private async Task<string> ReactiveAndAsync(string searchQuery,
                                  string titleShouldContain,
                                  string uriShouldContain,
                                  string pageShouldContain)
{
  return await GetGoogleStream(searchQuery, titleShouldContain, uriShouldContain, pageShouldContain);
}

tl;dr

Rx doesn't do anything magical, it won't defeat causality and it isn't perfect for every use case, at least not until 3.0. However, it will let you create logic streams that hopefully improve readability, extensibility and a separation of concerns.


问:
How to find a programming mentor?
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.

答:
i think that forums would be the best way to find some people with expertiece on the matter. I believe you should start there.

Checkout some c++ sites on google or maybe our dear friend stackoverflow, where there are lot of c++ ninjas ready to answer your questions!

Title: How to find a programming mentor?

ContentLicense: CC BY-SA 2.5


问:
Limitations of modern programming languages for low-level network programming
For say a network packet sniffer, are there any of the more modern high level languages such as C# or Java, that would actually be unsuitable or limiting when it would come to constructing a packet sniffer?

From most open source examples which I have encountered, it seems C/C++ are the preferred languages when it comes to network programming.

Would I be limited in using purely C#?

I'm not asking for opinions to what language is best, but I'm asking whether the use of particular languages (especially C# or Java) would be a problem.

答: I've created a few low level networking programs in c#, mainly a protocol stack, and a chat messenger. The only issue I ever had was the overhead that comes along with using a high level language. You can still do all of the low level things like looking at packets, and reading individual bytes. Java & .NET both have built-in support for sockets and byte buffering which is all you really need!</p>


问:
Are there any downsides for the same API to perform two slightly different functions?
Take for example the following two GET requests with slightly different arguments:

```<code>../user/login_at
</code>```

which returns the last login date of the user, and

```<code>../user/login_at?start=2015-05-01&end=2015-05-31
</code>```

which returns an array of all login dates of the user within May.

Are there any downsides for this API to perform these two slightly different functions?

答: No. I think they are clear and should be different because they perform different tasks, even if they perform activities for the same entity.</p>


问:
Creating a queue for web services
I have a program running that collects metadata from the internets.

Every so often a summary of this data is written up (every 30 min or so) and the summary is posted to a database.

The summary is also sent out to many web service APIs.

I'm trying to avoid the problem of this program locking up when webservice APIs timeout. So I'm thinking of creating a queue to process these webservice requests.

How should I create this queue? With a database of some sort? It could be a program storing queued items in memory, I suppose. Is there some standard process for creating a queue for webservice calls?

答:
This sounds like a perfect use-case for Apache Kafka:

Each partition is an ordered, immutable sequence of messages that is continually appended to—a commit log. The messages in the partitions are each assigned a sequential id number called the offset that uniquely identifies each message within the partition.
  The Kafka cluster retains all published messages—whether or not they have been consumed—for a configurable period of time. For example if the log retention is set to two days, then for the two days after a message is published it is available for consumption, after which it will be discarded to free up space. Kafka's performance is effectively constant with respect to data size so retaining lots of data is not a problem.

Link to the docs: http://kafka.apache.org/documentation.html#introduction

Title: Creating a queue for web services


答:
I could think of,
in the first example the user expecting a string or json Object value to return. But in the second example, the user expecting to return an array.
It may lead the user to create messy if else statement.

It would be better if you rename the endpoint to.

/user/last_login_at

and

/user/login_logs

Title: Are there any downsides for the same API to perform two slightly different functions?

Body:
Take for example the following two GET requests with slightly different arguments:

```<code>../user/login_at
</code>```

which returns the last login date of the user, and

```<code>../user/login_at?start=2015-05-01&end=2015-05-31
</code>```

which returns an array of all login dates of the user within May.

Are there any downsides for this API to perform these two slightly different functions?


问:
Need semi-efficient algorithm for 3-dimensional increasing sequence
I have a set of puzzle challenges for a prototype jigsaw puzzle kit, similar to commercial products offered by Thinkfun and Popular Playthings. I have a candidate list of 300 puzzle challenges and would like to select 40 of them. For each challenge, I have a numerical value that represents the challenge's difficulty, another value that represents the challenge's difficulty after one hint is given, and a third value that represents the challenge's difficulty after a second hint is given.

When I present the puzzles ordered by difficulty, ideally the puzzles should also still have the same relative difficulty after a hint is given. For example, a hard puzzle with one hint should not be easier than an easy puzzle with one hint. If I can select 40 puzzles with that property, then I have the advantage that I can say "for younger children, give two hints for each puzzle" and not have to re-order the puzzle numbers.

I don't really need all subsets of 40 that fit my criteria, just one good one. If I had a list of all subsets, though, I would be able to choose one using more desiderata. For example, I would find one that best clusters into four groups of 10, and then label the challenges "easy", "medium", "hard", and "expert".

I would like to find all subsets of 40 of the points so that no matter which dimension I sort the subset on, the ordering is the same.

In other words, find a subset { P0, P1, P2, ... P39 } so that whenever A < B, X[PA] < X[PB], Y[PA] < Y[PB], and Z[PA] < Z[PB].

I tried a stupid recursive greedy algorithm and it is way too slow.

答:
I eventually got the answer I wanted by a smarter dynamic programming approach.

The insight was to realize that although the nature of my problem didn't allow for a total ordering of all the elements, it did allow for a partial ordering of all the elements.  The challenge, then, was to calculate the coverings in that partial order.  To do that, I used the following algorithm.

```<code>for each Point in (all points sorted increasingly by dimension X)
   let Coverings[Point] = empty set
   let Lowerset[Point] = empty set
   let Candidates = {all previous points}
   for each PrevPoint in (all previous points sorted decreasingly by dimension X)
      if (PrevPoint in Candidates and PrevPoint < Point)
         add PrevPoint to Coverings[Point]
       let Lowerset[Point] = union(Lowerset[Point], Lowerset[PrevPoint], PrevPoint)
         let Candidates = intersection(Candidates, inverse(Lowerset[PrevPoint]))
     endif
    end for
end for
</code>```

Having the lines about Candidates isn't strictly necessary, but it makes the code a bit more efficient by not having to look through the same nodes over and over.

Once I had the set of all coverings, I was then able to send it to Graphviz dot to generate a Hasse diagram for my set.

And by looking at my Hasse diagram, I was quickly able to tell that the diameter of my graph was 40, which is just barely enough to do what I want to do.

P.S.  I added a bit more of my code to keep track of the "depth" in which the node appears on the Hasse diagram.  With that I was able to generate a simpler diagram that removed all coverings that jump a generation.

Body:
I eventually got the answer I wanted by a smarter dynamic programming approach.

The insight was to realize that although the nature of my problem didn't allow for a total ordering of all the elements, it did allow for a partial ordering of all the elements.  The challenge, then, was to calculate the coverings in that partial order.  To do that, I used the following algorithm.

for each Point in (all points sorted increasingly by dimension X)
   let Coverings[Point] = empty set
   let Lowerset[Point] = empty set
   let Candidates = {all previous points}
   for each PrevPoint in (all previous points sorted decreasingly by dimension X)
      if (PrevPoint in Candidates and PrevPoint < Point)
         add PrevPoint to Coverings[Point]
       let Lowerset[Point] = union(Lowerset[Point], Lowerset[PrevPoint], PrevPoint)
         let Candidates = intersection(Candidates, inverse(Lowerset[PrevPoint]))
     endif
    end for
end for

Having the lines about Candidates isn't strictly necessary, but it makes the code a bit more efficient by not having to look through the same nodes over and over.

Once I had the set of all coverings, I was then able to send it to Graphviz dot to generate a Hasse diagram for my set.

And by looking at my Hasse diagram, I was quickly able to tell that the diameter of my graph was 40, which is just barely enough to do what I want to do.

P.S.  I added a bit more of my code to keep track of the "depth" in which the node appears on the Hasse diagram.  With that I was able to generate a simpler diagram that removed all coverings that jump a generation.


答:
Perhaps create a Boolean parameter, so that you retrieve the last login by:

/user/login_at?last

You effectively then have one endpoint that filters by query string, and could use a call like:

/user/login_at?start=2015-05-01&end=2015-05-31&last

...to get the last login time in May.


问:
Why do programs use call stacks, if nested function calls can be inlined?
Why not have the compiler take a program like this:

```<code>function a(b) { return b^2 };
function c(b) { return a(b) + 5 };
</code>```

and convert it into a program like this:

```<code>function c(b) { return b^2 + 5 };
</code>```

thereby eliminating the computer's need to remember c(b)'s return address?

I suppose the increased hard disk space and RAM needed to store the program and support its compilation (respectively) is the reason why we use call stacks. Is that correct?

答:
This is called "inlining" and many compilers do this as an optimization strategy in cases where it makes sense.

In your particular example, this optimization would save both space and execution time. But if the function was called in multiple places in the program (not uncommon!), it would increase code size, so the strategy becomes more dubious. (And of course if a function called itself directly or indirectly it would be impossible to inline, since then the code would become infinite in size.)

And obviously it is only possible for "private" functions. Functions which are exposed for external callers cannot be optimized away, at least not in languages with dynamic linking.


答:
There are two parts to your question: Why have multiple functions at all (instead of replacing function calls with their definition) and why implement those functions with call stacks instead of statically allocating their data somewhere else?

The first reason is recursion. Not just the "oh let's make a new function call for every single item in this list" kind, also the modest kind where you have maybe two calls of a function active at the same time, with many other functions in between them. You need to put local variables on a stack to support this, and you can't inline recursive functions in general.

Then there's a problem for libraries: You don't know which functions will be called from where and how often, so a "library" could never really be compiled, only shipped to all clients in some convenient high-level format that is then be inlined into the application. Aside from other problems with this, you completely lose dynamic linking with all its advantages.

Additionally, there are many reasons to not inline functions even when you could:

It's not necessarily faster. Setting up the stack frame and tearing it down are maybe a dozen single-cycle instructions, for many large or looping functions that's not even 0.1% of their execution time.

It may be slower. Duplication of code has costs, e.g., it will put more pressure in the instruction cache.

Some functions are very large and called from many places, inlining them everywhere increases binary far beyond what's reasonable.

Compilers often have a hard time with very large functions. Everything else being equal, a function of size 2*N takes more than 2*T time where a function of size N takes T time.

Title: Why do programs use call stacks, if nested function calls can be inlined?

Body:
Why not have the compiler take a program like this:

```<code>function a(b) { return b^2 };
function c(b) { return a(b) + 5 };
</code>```

and convert it into a program like this:

```<code>function c(b) { return b^2 + 5 };
</code>```

thereby eliminating the computer's need to remember c(b)'s return address?

I suppose the increased hard disk space and RAM needed to store the program and support its compilation (respectively) is the reason why we use call stacks. Is that correct?


答:
You want function inlining, and most (optimizing) compilers are doing that.

Notice that inlining requires the called function to be known (and is effective only if that called function is not too big), since conceptually it is substituting the call by the rewriting of the called functgion. So you generally cannot inline an unknown function (e.g. a function pointer -and that includes functions from dynamically linked shared libraries-, which is perhaps  visible as a virtual method in some vtable; but some compilers might sometimes optimize thru devirtualization techniques). Of course it is not always possible to inline recursive functions (some clever compilers might use partial evaluation and in some cases be able to inline recursive functions).

Notice also the inlining, even when it is easily possible, is not always effective: you (actually your compiler) could increase so much the code size that CPU caches (or branch predictor) would work less efficiently, and that would make your program run slower.

I am a bit focusing on functional programming style, since you tagged your qestion as such.

Notice that you don't need to have any call stack (at least in the machine sense of the "call stack" expression). You could use only the heap.

So, take a look at continuations and read more about continuation passing style (CPS) and CPS transformation (intuitively, you could use continuation closures as reified "call frames" allocated in the heap, and they are sort-of mimicking a call stack; then you need an efficient garbage collector).

Andrew Appel wrote a book Compiling with Continuations and an old paper garbage collection can be faster than stack allocation. See also A.Kennedy's paper (ICFP2007) Compiling with Continuations, Continued

I also recommend reading Queinnec's Lisp In Small Pieces book, which has several chapters related to continuation & compilation.

Notice also that some languages (e.g. Brainfuck) or abstract machines (e.g. OISC, RAM) don't have any calling facilities but are still Turing-complete, so you don't (in theory) even need any function call mechanism, even if it is extremely convenient.  BTW, some old instruction set architectures (e.g. IBM/370) don't even have a hardware call stack, or a pushing call machine instruction (the IBM/370 had only a Branch and Link machine instruction)

At last, if your entire program (including all the needed libraries) does not have any recursion you could store the return address (and the "local" variables, which are actually becoming static) of each function in static locations. Old Fortran77 compilers did that in the early 1980s (so the compiled programs did not use any call stack at that time).


答:
You might check out your local Linux User Group (here you'll find a list), usually most of the participants are programmers - or at least perl hackers. Plus, if you tell them you're there to find a programming mentor, they'll love you.

A post on craigslist might be worth a try, but I wouldn't bet on that.

Also, if you're based in Germany, there is a couple of places I can suggest in particular.

Title: How to find a programming mentor?

Body:
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.


问:
Alternatives to Request For Comments
I personally find RFC's quite difficult to read. They tend to be quite long, not precise enough, really old and for the most part, quite difficult to convert into actual working code. I think the evidence that I'm not the only one is quite large given that most developers I have spoken to have never seen an RFC.

Why are RFC's structured the way they are? Couldn't a set of code examples or unit tests be written in multiple languages instead? That way you could read the RFC in a language that you are familiar with...

Besides writing examples in multiple languages, are there any other specification organizations that use something else besides RFC's? If so, what do they use?

(Unrelated: I would like to add the tags: ietf, rfc, w3c but I do not have enough reputation, an edit would be appreciated)

答:
Why are RFC's hard to read?

The purpose of RFC's is to ensure interoperability on the internet by precisely specifying protocols. For this purpose precision and unambiguity is much more important than easy readability for laymen. The target audience for RFC's are systems developers implementing network stacks, not the common developer who just writes import HttpLibrary;

Furthermore RFC's are supposed to be long lived. The first RFC's are from 1969, and many older are still critical for the internet infrastructure.

These priorities leads to some choices which makes them harder to read:

They use an plaintext paged ASCII format which is not very browser-friendly (monospace font, strange gaps when pages split and so on). In this age were everything is HTML or at worst PDF, this seems like a relic. But in the time since RFC's was invented multiple "rich"-text formats have come and gone, but plain ASCII remains readable on all systems. And it is an unambiguous format, not subject to browser bugs and differences.

They use a jargon where some words have more specific meaning than in plain language, eg. the infamous:

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
   document are to be interpreted as described in RFC 2119 [RFC2119].

This is more akin to legal jargon, where precision is more important than easy readability.

RFCs attempts to be as short and to the point as possible, again to avoid ambiguities. For example, adding a code example introduces redundancy. If the code example subtly contradicts the spec, it will be unclear which is correct. If there are code examples in multiple languages this risk increases. Furthermore, code examples become dated. If RFC's from the 70ies had code examples, they might have been in Fortran or BCPL or assembler for processors long obsolete. It would have been more work making sense of the code examples than to read the RFC-prose, however obtuse.

The W3C are uses a different approach than RFC's. They write Recommendations which are generally easier to read. They are formatted in easy readable HTML, and use illustrative examples much more (the examples are typically marked as not normative to avoid ambiguities if the example contradict the spec). W3C recommendations are therefore quite readable. For example the CSS2 spec is (in my opinion) easier to understand than many CSS tutorials.

The W3C recommendations have a different audience than RFC's. The audience for RFC's are systems developers, while the audience for W3C recommendations are browser and application developers, and web authors and designers. A much broader audience.

That said, RFC's are not that difficult to read. If you get over the archaic presentation format, they are often surprisingly easy to understand.

Title: Alternatives to Request For Comments


问:
Strategies to manage a modular C# framework
Currently I'm building a large framework whose purpose is to run several algorithms in sequence.

Many of these algorithms have interdependencies in data structure - the output of one algo is the input of another algo, for instance MagicVectorXY. The algorithms need to be modular and compact, because some of these algorithms will be reused in many other separate frameworks. And we want to avoid unreachable code as much as possible.

Our current solution is to compile each algorithm into its own .dll, while shared interfaces/3rd party math libraries/shared data structures reside in a CommonInterfaces.dll. However, this leads to proliferation of Projects in the Visual Studio Solution, and there's still significant unreachable code in the CommonInterfaces.dll.

What other strategies are there to manage such a modular framework?

PS: We foresee ~10 algorithms, and things like database layer, WCF, scheduling and Unit Tests for each project are all their own projects as well. So around 25-30 projects estimated in that single solution.

答:
The information here is a bit scarce...

First of all (if you haven't already) you may want to check out SOLID. Follwing these rules will give your sofware a good dependency structure. A nice dependency structure is key to being able to swap modules in and out. (And you will not need to reference the datalayer to compile your algorithms)

What strikes me the most in your description is "shared interfaces". To make each algorithm a true module you want each module to individually define the interfaces it uses. See ISP. Then the implementation of the different interfaces can be in a single class that references the algorithm .dll:s but you can also provide different implementations for different frameworks if needed. Or maybe you have a default implementation that you can package with the module.

Also, don't be afraid to add projects. And I would recommend thinking about structuring the code by functionality (module/algorithm/etc.) instead of just different layers as that will allow you to for example pick the parts of the data layer you need.


问:
How come the NSA could release SELinux as GPL when all US Gov work must be Public Domain?
I'm not sure if this is a good question for this site, but it does deal with the things to do with working as programmer.

SELinux is a security enhanced version of Linux, and was initially developed by the National Security Agency (NSA) of the USA. Since it's linked into the Linux kernel, it's available under the GNU GPL licence (right?).

However I thought that all work made by the US federal government had to be public domain (right?).

So how was the NSA able to legally produce something that's not PD, but instead GPL?

答:
The FSF answer this question themselves:

Can the US Government release improvements to a GPL-covered program?

Yes. If the improvements are written by US government employees in the course of their employment, then the improvements are in the public domain. However, the improved version, as a whole, is still covered by the GNU GPL. There is no problem in this situation.

So the source code which is actually written by federal employees is in the public domain. You are free to do what you want with these components. But the rest is under the GPL, hence distribution of the work as a whole must comply with the GPL.


问:
Are long functions acceptable if they have internal structure?
When dealing with complicated algorithms in languages with support for nested functions (such as Python and D) I often write huge functions (because the algorithm is complicated) but mitigate this by using nested functions to structure the complicated code.  Are huge (100+ line) functions still considered evil even if they're well-structured internally via the use of nested functions?

Edit:  For those of you not familiar with Python or D, nested functions in these languages also allow access to the outer function scope.  In D this access allows mutation of variables in the outer scope.  In Python it only allows reading.  In D you can explicitly disable access to the outer scope in a nested function by declaring it static.

答:
Put them in a separate module.

Assuming your solution is not more bloated than needing you haven't got too many options. You've already split up the functions in different sub functions so the question is where you should put it:

Put them in a module with only one "public" function.

Put them in a class with only one "public" (static) function.

Nest them in a function (as you've described).

Now both the second and third alternatives is in some sense nesting, but the second alternative would by some programmers not seem to bad. If you don't rule out the second alternative I don't see too much reason to rule out the third.


问:
Rendering head :ok vs head :no_content. Any good practices?
Whenever I take in data and do something like delete a post, etc. I generally return head :no_content.

For example:

```<code>def destroy
  @post = Post.find_by(external_id: params[:post_id])
  @post.destroy!

  head :no_content
end
</code>```

Is it good practice to use head :no_content over head :ok? Not too sure when to use either.

答:
This is the expected behavior in case of a DELETE request. So much so that in rails if you generate a resource or scaffold (using rails generate), this is what is generated.

All 2xx statuses are "success" statuses. So if you are actually not sending any content, it is best to mention it with a no_content

So rest assured that what you are doing is in fact correct and expected.


问:
How to maintain modularity in C?
I am writing C code with multiple modules like LCD display, flash memory, and GSM module etc. The project consists of thousands of lines of code, in different files.

The behavior of the system can be changed with run-time parameters (eg LCD brightness) using a buttons. And during compile time by redefining #define directives and const variables.

Currently all of these variables and constants lie with the rest of the modules in their respective files. I am finding is very hard to maintain the settings without losing modularity.

My question is two part:

How do I make the compile time parameters more accessible? Moving all the variables to a separate file would certainly make life easier by making all the settings available in one place. Also some settings go in groups, so it makes more sense to change one #define in one file rather than fishing for many #defines in multiple files. But it does not seem right to destroy the modularity this way.

I need to write code that will save all the runtime parameters  to flash memory, and retrieve them on reboot. Ideally this should be done in getter and setter functions. But the problem is that all the settings and configurations are stored in a sector in flash memory. A parameter can't just be rewritten without erasing the flash memory. So LCD module can't change its brightness without being aware of all the other parameters. It makes more sense to keep all the settings in a struct, but the cost is moving the variables away from the modules.

What is the best way to tackle this problem without compromising on the readability and modularity of code.

答:
(I suggest to cross-compile on a Linux running on your laptop; it has lots of good tools helpful for cross-development)

The compile time parameters are probably best to be put in some header file with #define, but that header file could be generated (at build time) by some configuration script. (look perhaps into GNU autoconf for inspiration, but is is often enough to generate such configuration header by your own shell scripts).

The settings could indeed stay in a flash memory, and concretely you would access them as a single struct (containing all settable parameters). I'll probably suggest to have a setting facility which loads that  struct from flash to RAM, modify the data in RAM, and write out it in flash at end (BTW, most BIOSes on laptop or desktop PCs are doing that).

You might even use some metaprogramming techniques. You could generate (e.g. using some script in Guile or Python ...) at build time some C code for that struct, the accessing function, the help messages, etc...

Notice that recent versions GNU make are very configurable (even extensible with Guile), so your build procedure (i.e. your Makefile) can do some quite fancy things;in particular generate some of your C code (in generated header *.h files or generated *.c files)

Title: How to maintain modularity in C?


问:
How small is the footprint of a small C compiler?
This week I could optimize using a reduced C library that allowed a drastic shrinkage in code size - from about 60 K to about 6 K and then we could load the code in the 8 K on-chip memory  of an FPGA (Altera DE2) which I suppose is SRAM so there is SRAM both on-chip and off-chip(?)

The program was rather small itself and we noticed that most of the size was from libraries and doing embedded system we reduce the libraries to only what is needed so that the footprint is minimized.

It makes me wonder about something I heard in the media which was a story, maybe fictious, that Microsoft had to deliver a C compiler in only 20 K or so in the 70s or early 80s when there was not much memory available for software, is it true? What is a feasible size of the footprint for a small C compiler?

答:
Writing a tiny C compiler is easy, if you don't care about the performance of the generated code. TinyCC (originally by F.Bellard, now here) is such a compiler: it compiles quite quickly C programs (perhaps with a compilation time 5 to 10 times faster than GCC ...) but the produced executable is very slow (often more than 3 times slower than what gcc -O2 gives you). And nwcc is small, but probably generates slow code (w.r.t. what gcc -O2 can produce). The tcc compiler (i.e. TinyCC) is quite small (a few dozens of thousand lines of C code) and the executable (on x86-64) is about 190Kbytes.

But on current processors, you need an optimizing compiler to get most of the performance from the compiled executable code. And good optimizations are hard to achieve and need a big lot of compiler code: both GCC and Clang/LLVM have several millions lines of source code (some of which is generated by specific programs producing C or C++ code). See also this reply to a related question.


答:
Learning to program is an ambitious and (I think everyone on this site will agree) noble cause.  However, it is a difficult one to start from scratch and learn, even with a mentor.  I think that you will find that taking at least some introductory classes to give you a base will be the best way to go.

A mentor is a great idea, and I wouldn't be here 15+ years later as a coder without the guy who put up with my questions at my first "real" job, but in reality, one single person won't be able to give you the time and guidance you will need to become a successful programmer.  He or she will probably have a full time job (or course load) themselves.  That's not to say you shouldn't find a mentor (or mentors), just that you'll need something else as well.

Sites like this, and online tutorials, and books, and everything else are pieces of the puzzle.  Education makes up the border pieces.

This is not meant to discourage you; on the contrary, I think that setting realistic expectations will give you a better chance at success.

Title: How to find a programming mentor?


问:
Is there a name for the anti-pattern of having low-level components controlling higher-level ones?
For example, suppose I had a pageControl UI class and a searcher business logic class with the following :

pageControl.js

```<code>function searchButtonClicked() {
  // call business logic class method when button clicked
  searcher.beginSearch();
}

function showSearchResultsPage(searchResults) {
  // when this is called, display results
  ui.loadContent(searchResults);
}
</code>```

searcher.js

```<code>// This module has a low to moderate chance of someday being used on two or more different pages.
function beginSearch() { ... }

function searchCompleted(results) {
  // This here is what I view as the main problem
  pageControl.showSearchResultsPage(results);
}
</code>```

The problem is that searcher is specifically tied to pageControl, and it's making the decision that the search result page will be the next thing to appear. The example I was going to give to people about why this is bad gives the idea that "You wouldn't directly conditionally call the logic for your entire app inside of Button>onClick", but I'm trying to find a more comprehensive argument about why that is.

At first I thought this was "inversion of control" but looking that up on Wikipedia didn't portray it as negatively, so I don't think that's the right term for this kind of pattern.

Is there a name for this anti-pattern of having low-level components controlling higher-level ones?

答:
Circular Dependency

If we view pageControl.js as your UI layer, a controller perhaps, and searcher.js as you data access and or business layer, a circular dependency has been introduced that effectively makes them inseparable and defeats any benefits of layering.

Arguments could also be made for spaghetti code and accidental complexity.


答:
Placing all of the compile time switches into 1 central file makes finding and changing them easy.  That said, compile time switches can be confusing, particularly if there is a significant quantity of them.

I worked on an embedded project where there were a few different boards to control different hardware, but had the same MCU, communication protocols, flash storage, and other similar properties.  Rather than use #defines to switch between building the different versions of firmware, I put all of the core modules into a "Core" directory and the board-specific modules into their own directories.  I setup the build process to build all versions of the firmware at once.  This helps prevents a breaking change when working on the "Core" component.

Part of the same project involved saving various parameters to flash.  Each module that needed to write to flash had its own flash parameters struct, along with a unique entry in a moduleID enum.  When a module wanted to save its data, it would pass a pointer to the flash parameter struct, the size of the struct (in bytes), and  its moduleID to the flash storage module.

The flash storage module just looks at the passed struct pointer as a chunk of memory.  It would copy the data into flash, and add a small header that contained the moduleID and the size of memory.  When a module wanted its data from flash, it would pass its moduleID to the flash storage module, and then the flash storage module would scan the flash block for the moduleID, load the data into RAM, and then return it to the calling param.  This way, the flash storage didn't need to know about who called it.  All it cared about was the moduleID passed to it and the size of the data it was handing.

Title: How to maintain modularity in C?

Body:
I am writing C code with multiple modules like LCD display, flash memory, and GSM module etc. The project consists of thousands of lines of code, in different files.

The behavior of the system can be changed with run-time parameters (eg LCD brightness) using a buttons. And during compile time by redefining #define directives and const variables.

Currently all of these variables and constants lie with the rest of the modules in their respective files. I am finding is very hard to maintain the settings without losing modularity.

My question is two part:

How do I make the compile time parameters more accessible? Moving all the variables to a separate file would certainly make life easier by making all the settings available in one place. Also some settings go in groups, so it makes more sense to change one #define in one file rather than fishing for many #defines in multiple files. But it does not seem right to destroy the modularity this way.

I need to write code that will save all the runtime parameters  to flash memory, and retrieve them on reboot. Ideally this should be done in getter and setter functions. But the problem is that all the settings and configurations are stored in a sector in flash memory. A parameter can't just be rewritten without erasing the flash memory. So LCD module can't change its brightness without being aware of all the other parameters. It makes more sense to keep all the settings in a struct, but the cost is moving the variables away from the modules.

What is the best way to tackle this problem without compromising on the readability and modularity of code.


答: Join an open source project. You don't necessarily have to program for them either. Most projects would love to have someone help with documentation. You can look at the code and ask questions. When you fell comfortable your can start to write code for them.</p>

Title: How to find a programming mentor?


答:
First, reconsider how you are defining module boundaries.  "Compile-time settings" is a perfectly reasonable module.  If it feels cleaner to split a responsibility off, it should be split off.  As Basile pointed out, GNU autoconf is extremely common for this purpose.  It generates one header file you can include elsewhere as needed.  Just take care to make your #ifdef blocks as large as possible.  Try not to pepper them everywhere, and try to use alternatives if possible.

Second, you need to define your own abstractions.  For some reason, C has a tendency to create a blind spot to that in programmers, especially programmers who are accustomed to high-level programs in languages with massive libraries.

That means if you wish you had functions like write_setting_to_flash(LCD_BRIGHTNESS, brightness) and read_setting_from_flash(LCD_BRIGHTNESS) then write them.  Choose the interface you wish you had and make it happen.  Settings persistence is a separate responsibility from a driver.  They should be handled separately.

Essentially, what you are seeing as one module (LCD) is really 3 or 4 (driver, compile-time settings, flash persistence).  If you start looking at it that way, the design should fall into place much more cleanly.

Title: How to maintain modularity in C?


问:
Identity Design ASP.NET
I am trying to design a system with the below features, and am currently trying to figure out best way to handle Identity :

There will be multiple decoupled parts of the system, with same customers accessing various parts

I would like users organized by organizations/companies, i.e. user1 & user2 belong to ORG1

I would like additional info to be stored within a user profile, info will originate from various systems, as well as global info such as address, etc

For roles I haven't yet decided whether or not they will be handled by individual apps or globally and specialized in certain apps

My conundrum is whether to use the new MVC Identity released in ASP.NET Beta currently out, or use WIF or Active Directory. I am assuming that a centralized application handling users & their associated admin tasks and then federating to other applications is best. If I understand correctly any of the 3 are able to do that.

What I am wondering is which to use to be most flexible. Basically something that can be expanded later and doesn't have a huge learning curve, possibly to mobile & api use. I don't know enough about WIF or AD as I have never really used them, and ASP.NET Identity is still in beta and not really 100% documented. My experience with authentication systems is working with ones out of the box. I've never really had to deal with SSO or federation

One thing I wanted to add is there is no need for outside registration. Registration will be handled purely by admins, not sure if this ties in at all, but thought it may be of importance

答:
This application suite sounds sufficiently complex to warrant a business object layer. You need a separate project that contains your business models. Two of your business models would be User, and Organization. User would have an object reference to its Organization.

Design the User class to have all the properties you need ignoring the underlying provider. Once you have finished the class design, if MVC Identity is sufficient for your needs, I would recommend that you use it. If it is not, don't try to force it, roll your own.

Either way, your calls should looks something like this:

```<code>BusinessModels.MyUser user = MyUserRepo.GetUserByUsername(MVCIdentity.CurrentUser.Username);
</code>```

Title: Identity Design ASP.NET

Body:
This application suite sounds sufficiently complex to warrant a business object layer. You need a separate project that contains your business models. Two of your business models would be User, and Organization. User would have an object reference to its Organization.

Design the User class to have all the properties you need ignoring the underlying provider. Once you have finished the class design, if MVC Identity is sufficient for your needs, I would recommend that you use it. If it is not, don't try to force it, roll your own.

Either way, your calls should looks something like this:

BusinessModels.MyUser user = MyUserRepo.GetUserByUsername(MVCIdentity.CurrentUser.Username);


答: It is called an inversion of authority, named so by Ed Yourdon if memory serves. An example of the usage can be found here.

Title: Is there a name for the anti-pattern of having low-level components controlling higher-level ones?

Body:
For example, suppose I had a pageControl UI class and a searcher business logic class with the following :

pageControl.js

```<code>function searchButtonClicked() {
  // call business logic class method when button clicked
  searcher.beginSearch();
}

function showSearchResultsPage(searchResults) {
  // when this is called, display results
  ui.loadContent(searchResults);
}
</code>```

searcher.js

```<code>// This module has a low to moderate chance of someday being used on two or more different pages.
function beginSearch() { ... }

function searchCompleted(results) {
  // This here is what I view as the main problem
  pageControl.showSearchResultsPage(results);
}
</code>```

The problem is that searcher is specifically tied to pageControl, and it's making the decision that the search result page will be the next thing to appear. The example I was going to give to people about why this is bad gives the idea that "You wouldn't directly conditionally call the logic for your entire app inside of Button>onClick", but I'm trying to find a more comprehensive argument about why that is.

At first I thought this was "inversion of control" but looking that up on Wikipedia didn't portray it as negatively, so I don't think that's the right term for this kind of pattern.

Is there a name for this anti-pattern of having low-level components controlling higher-level ones?


问:
Low coupling when using sealed classes?
Typically, when trying to decouple classes I use Inversion of Control. Lately I've been using a third-party library whose components are sealed. Are there any design patterns to handle this situation? They have multiple component classes that're sealed and I quite often need to use them. I was about to inherit from it and give it an interface to operate through until I noticed it was sealed and impossible to do so.

The library doesn't change a whole lot (only in major versions) so I could pretty easily get away with keeping the classes coupled in this particular scenario, however this has got me wondering about cases where this would not be the case.

How do you keep coupling low in your code when using third-party sealed classes?

答:
As some of the comments mentioned, you may be either consuming the library incorrectly or it may not be a well designed library. But ignoring this, a variation façade pattern seems appropriate.

I don't have enough information about your application, but I can think of two approaches off of the top of my head:

Simple

```<code>class MyObject
{
     private _libraryObject;
     public MyObject(LibraryObject source)
     {
           _libraryObject = source;
     }

     public MyProperty1
     {
         get { return _libraryObject.Property1; }
         set { _libraryObject.Property1 = value; }
     }
 }
</code>```

Complex, but even more decoupled

```<code>//Inside repository class
GetObject()
{
     MyObject myObject = new MyObject();
     Mapper.Map(libraryObject, myObject); //Translate a LibraryObject to MyObject
     return myObject;
}
</code>```

You can now do what ever you want with this class, including inherit from it.

Title: Low coupling when using sealed classes?

Body:
As some of the comments mentioned, you may be either consuming the library incorrectly or it may not be a well designed library. But ignoring this, a variation façade pattern seems appropriate.

I don't have enough information about your application, but I can think of two approaches off of the top of my head:

Simple

class MyObject
{
     private _libraryObject;
     public MyObject(LibraryObject source)
     {
           _libraryObject = source;
     }

     public MyProperty1
     {
         get { return _libraryObject.Property1; }
         set { _libraryObject.Property1 = value; }
     }
 }

Complex, but even more decoupled

//Inside repository class
GetObject()
{
     MyObject myObject = new MyObject();
     Mapper.Map(libraryObject, myObject); //Translate a LibraryObject to MyObject
     return myObject;
}

You can now do what ever you want with this class, including inherit from it.


答:
Cases which that approach cannot handle:

function fib(a) { if(a>2) return fib(a-1)+fib(a-2); else return 1; }

function many(a) { for(i = 1 to a) { b(i); };}

There are languages and platforms with limited or no call stacks. PIC microprocessors have a hardware stack limited to between 2 and 32 entries. This creates design constraints.

COBOL bans recursion: https://stackoverflow.com/questions/27806812/in-cobol-is-it-possible-to-recursively-call-a-paragraph

Imposing a ban on recursion does mean that you can represent the entire callgraph of the program statically as a DAG. Your compiler could then emit one copy of a function for each place from which it's called with a fixed jump instead of a return. No stack required, just more program space, potentially quite a lot for complex systems. But for small embedded systems this means you can guarantee not to have a stack overflow at runtime, which would be bad news for your nuclear reactor / jet turbine / car throttle control etc.


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答:
Because you can see the whole thing at once. By being able to see the whole thing, it can be easier to work with, and that's always nice. It's sort of like the reason that many C++ programmers still use printf-type statements: It's not typesafe (though gcc at least can check types on printf statements), and it's not pretty, but boy is it compact and usable.

If it's a simple enough regex, then they often ARE the best way to do things - their compact form and many capabilities make them perfect for certain tasks. The problem comes when you make the regex so complicated that you can't read it anymore, or when you're using a complex regex to do something that could be more quickly done via simple string operations.

Regex, like any other powerful tool, must be use in proper moderation - not too much, not too little. And unless performance is a big concern, a single regex may at times be quicker to write and easier to debug than a series of string operations.


问:
How Do News Websites E.g. Forbes / Zdnet Seamlessly Merge One Webpage into Another?
If you go to E.g:

http://www.forbes.com/sites/adrianbridgwater/2015/06/12/why-technology-has-to-be-continuous/
OR

http://www.zdnet.com/article/if-you-want-those-cool-ios-9-features-its-time-to-buy-a-new-ipad/

When you get to the bottom of the Page, a New News story loads and the URL in my Internet Browser changes to the URL of this Next News Story.
So I was wondering how a webpage can almost instantly load the next webpage with almost negligible delay between pages. Are they for example Pre-downloading the Webpage of the Next News story, and then loading the webpage really fast?

答:
The short answer is that the page's client-side Javascript code detects when you get "too close" to the bottom of the page, and asks the server for more data when that happens.

Without getting too technical, they are not reloading the entire web page. Instead the Javascript code on that page is requesting more data from the server, then when it receives the new data, it adds that data to the current page. The parts of the page that do not need to change remain completely unchanged.

The most modern way of doing this is to use the HTML5 history-modification features, which appears to be what those sites are using.


答:
One big key to understanding what is happening: It is possible, via Javascript, to set the URL in the addressbar without actually redirecting the user.  To see this in action, paste the below code into a supported browser's console.  Notice that it changes your address bar to http://programmers.stackexchange.com/yay.html.

```<code>history.pushState(null,null,'/yay.html')
</code>```

The benefit of this approach is that if the user bookmarks after scrolling to a story, the bookmark will know where to send the user.  DeviantArt's infinite scrolling of search results is a nice example of this behavior.

Title: How Do News Websites E.g. Forbes / Zdnet Seamlessly Merge One Webpage into Another?

Body:
If you go to E.g:

http://www.forbes.com/sites/adrianbridgwater/2015/06/12/why-technology-has-to-be-continuous/
OR

http://www.zdnet.com/article/if-you-want-those-cool-ios-9-features-its-time-to-buy-a-new-ipad/

When you get to the bottom of the Page, a New News story loads and the URL in my Internet Browser changes to the URL of this Next News Story.
So I was wondering how a webpage can almost instantly load the next webpage with almost negligible delay between pages. Are they for example Pre-downloading the Webpage of the Next News story, and then loading the webpage really fast?

Body:
One big key to understanding what is happening: It is possible, via Javascript, to set the URL in the addressbar without actually redirecting the user.  To see this in action, paste the below code into a supported browser's console.  Notice that it changes your address bar to http://programmers.stackexchange.com/yay.html.

history.pushState(null,null,'/yay.html')

The benefit of this approach is that if the user bookmarks after scrolling to a story, the bookmark will know where to send the user.  DeviantArt's infinite scrolling of search results is a nice example of this behavior.


答:
There might be some inconvenience in parsing the answer, as already noted by bekicot in his answer:

The problem is that your result has a different structure for the two cases.

Why does it have that gratuitious difference?

Simply make the first query answer with a single-element-array, and all is fine.

Aside from that, there's no problem at all. It's analogous to function overloading in languages like C++, where different overloads (different number and type of parameters) can return different result-types.


问:
Storing Multi-select and Single-select data together
I've got a database with some multi-select fields. To keep it simple, let's just say those fields are MatchGender and Interests. I want users to be able to find people who match (hence Gender is a multi-select; they can choose to match against one or both genders) and interests/hobbies. Along with those fields, there are several "single-select" fields such as the user's city, state, their gender, etc...

I'm trying to figure out the best way to store this data so it's easily searchable. Do I store the multi-select data in a single field that is comma delimited? Do I store it in a separate table with a UserID? Pros/Cons of each?

By the way, this is a SQL Server back-end database that will be accessed through an ASP web interface.

答:
Make an Interest table, and then another table (UserInterest) holding the foreign keys of both User and Interest

What you're describing is a many-to-many relationship between User and Interest. If you go through the process of database normalization for your data model you will see that holding a comma-separated list of values fails on two points:

Each column should hold only one data item, but a comma-separated list is multiple items.

Each Interest is a repeated data item in User. If you needed to change something about it (maybe correcting a spelling error, or changing the name to something more descriptive), then if you hold the Interests as strings in the User table, you'd need to run a massive update statement on User.

The combination of holding everything in User and holding comma-separated lists compounds the second issue; if you did need to change the name of an Interest, you wouldn't be able to run a very simple update - you'd have to do some sort of string manipulation to find every instance of an Interest and modify it.

With the structure I have suggested, if you ever need to change the name of an Interest, you will update one row in the Interest table.

Also, this way means you'll never need to do string manipulation to match up interests between two people. If you had the interests of Person A as "fishing, baking, paper craft" and Person B as "tobogganing, paper craft, fishing" you'd have to do some unpleasant data-wrangling to realise they shared two-thirds of their interests. Instead, you can just do a set of joins - and with aggregation functions in SQL you could even do things like figuring out the number of matched interests, percentage of matched interests, etc.

Finally, you'll thank yourself later if you ever need to build any reporting, business intelligence, or other down-stream systems over this data. Or you'll remain in the good books of whoever it is who does need to build those things.


问:
Mapping between 4+1 architectural view model & UML
I'm a bit confused about how the 4+1 architectural view model maps to UML.

Wikipedia gives the following mapping:

Logical view: Class diagram, Communication diagram, Sequence diagram.

Development view: Component diagram, Package diagram

Process view: Activity diagram

Physical view: Deployment diagram

Scenarios: Use-case diagram

The paper Role of UML Sequence Diagram Constructs in Object Lifecycle Concept gives the following mapping:

Logical view (class diagram (CD), object diagram (OD), sequence diagram (SD), collaboration diagram (COD), state chart diagram (SCD), activity diagram (AD))

Development view (package diagram, component diagram),

Process view (use case diagram, CD, OD, SD, COD, SCD, AD),

Physical view (deployment diagram), and

Use case view (use case diagram, OD, SD, COD, SCD, AD) which combines the four mentioned above.

The web page UML 4+1 View Materials presents the following mapping:

Finally, the white paper Applying 4+1 View Architecture with UML 2 gives yet another mapping:

Logical view class diagrams, object diagrams, state charts, and composite structures

Process view sequence diagrams, communication diagrams, activity diagrams, timing diagrams, interaction overview diagrams

Development view component diagrams

Physical view deployment diagram

Use case view use case diagram, activity diagrams

I'm sure further search will reveal other mappings as well.

While various people usually have different perspectives, I don't see why this is the case here. Specially, each UML diagram describes the system from a particular aspect. So, for instance, why the "sequence diagram" is considered as describing the "logical view" of the system by one author, while another author considers it as describing the "process view"?

Could you please help me clarify the confusion?

答:
Do you still use VCR that you bought back in 1995.? 4 + 1 was applicable back then when software was in it's infancy. But even then, nobody ever used more than 2 or 3 "views". In the last 20 years software engineering changed. Nowadays, scope/context and conceptual and logical and physical and ... are all differentiated. A lot of COTS solutions have to be integrated, and so on. Today, we are talking about landscape maps, service realizations and dozens of other views and viewpoints.
The best way to look at it is through a simple taxonomy framework like Zachman: 6 views and 6 viewpoints. Let that be your starting point.
6 views are:
contextual
conceptual or business
logical or system
physical or technology
delivery or artifacts
functioning enterprise

6 viewpoints are:
data or What
function or How
network or Where
people or Who
time or When
motivation or Why

Let's look an example. If we are interested only in data, we will start with the scope view and say, "Our scope is CRM". In the conceptual view for data viewpoint we'll come up with some semantic model for CRM. The model will be conceptual, business information  concepts rather than data objects.
Next, in the logical view we'll produce logical data model from our conceptual model of CRM. We may use ER methodology to produce logical data model.
Then, in the physical view, we'll produce physical data model. Here, we'll define concrete data types for db platform of our choice, indexes etc.
Finally, in delivery view we'll have our DDL script, while in the functioning enterprise view we'll have a binary file deployed on some database server and mapped into internal data structures of the DBMs vendor.
We repeat this for every viewpoint or column. Also, if there is more than one stakeholder we''ll create more than one model for each viewpoint/view combination.
Now that you have this taxonomy in place, you can define your own viewpoints and views and align these into this taxonomy. For example, for enterprise level initiatives the following viewpoints are all important:
actor cooperation
application behavior
application cooperation
application structure
application usage
business function
business process
business process cooperation
implementation and deployment
information structure
infrastructure
infrastructure usage
landscape map
overview
layered
organizational
service realization
etc

Krutchen's 4+1 could not possibly satisfy all of these needs


问:
How to sign a document in LAMP environment?
I'm working on a LAMP environment (Linux-Apache-MySQL-PHP) and I need to sign documents (PDF, but maybe in a future, I'll use other formats so I'm interested in a general answer).

These documents are uploaded by the admin users, signed (internal process, transparent to admin) and the client users could download the files anywhere, anytime using any web browser.

We need to sign these documents so neither the admin users or the clients may claim the files were modified. The idea is to ensure that the document the admin uploaded in a given date is the document that the client downloaded in a later date without any tamper.

How do I enforce non-repudiation given these constraints?

答:
The easiest way to enforce these guarantees is using PKI.

PDFs allow signatures, but to enforce non-repudiation you need to have certificates for each person and some central way to manage them.

You could use a truly public key infrastructure where you purchase certificates from e.g. VeriSign or another root CA (certificate authority) for each user, but that can be expensive.

Depending on the size of your organization and the clients involved, you may be able to run your own CA making the cost of issuing certificates zero. However, this would be cumbersome if you have a lot of external clients.

Running your own CA, at a very high level, means you have one root certificate that is self-signed and installed on client machines (this is similar to the certificates installed in your web browser so you can validate e.g. that your bank's web site is who they say it is). You then sign each individual certificate using that root certificate. Clients can validate signatures by checking the signature matches the client certificate, and validating the client certificate against the root certificate.


问:
Are there any downsides for the same API to perform two slightly different functions?
Take for example the following two GET requests with slightly different arguments:

```<code>../user/login_at
</code>```

which returns the last login date of the user, and

```<code>../user/login_at?start=2015-05-01&end=2015-05-31
</code>```

which returns an array of all login dates of the user within May.

Are there any downsides for this API to perform these two slightly different functions?

答:
It looks fine to me. If you know any prospective users of the API, you could ask them if it would be better to always return an array; with one entry if only the last login of the user is requested; this also means that returning an empty array is a perfectly fine way to tell the client that the user never actually logged in. </p>

<p>The client can then use identical code to process the answer to the point where he/she has an array of objects, typically 1 and sometimes 0 entries in the first case, and any number of entries in the second case. </p>

Body:
It looks fine to me. If you know any prospective users of the API, you could ask them if it would be better to always return an array; with one entry if only the last login of the user is requested; this also means that returning an empty array is a perfectly fine way to tell the client that the user never actually logged in.

The client can then use identical code to process the answer to the point where he/she has an array of objects, typically 1 and sometimes 0 entries in the first case, and any number of entries in the second case.


问:
Difference between data models and schemas
I was just starting with reading a book about databases and encountered schemas and data models. I read that schema is the structural design of a database and data model is a set of conceptual tools to describe the data and the relationships like Er model etc. I don't get the real sense of difference between the two. Is schema actually a file in Dbms and data model is just a concept? </p>

答:
A schema is collection of database objects that are logically grouped together.  These can be anything, tables, views, stored procedure etc.  Schemas are typically used to logically group objects in a database.  For example, an application that has reporting and auditing components may have 2 schemas called reporting and auditing with a collection of tables, stored procedures etc.  With Schemas, one can segregate out the reporting objects and audit objects.  One can also create different security accounts which can only access a specific schema.  A fully qualified name will include the schema.  For example:

```<code>SELECT * FROM [Test].[dbo].[Person]
</code>```

Test is the database.
dbo is the schema.
Person is the table.

A data model in a database should be relational which means it is described by tables.  The data describes how the data is stored and organized.   A data model may belong to one or more schemas, typically usually it just belongs to one schema.

The person table will be a part of a number of tables and relations that make up the data model.

Body:
A schema is collection of database objects that are logically grouped together.  These can be anything, tables, views, stored procedure etc.  Schemas are typically used to logically group objects in a database.  For example, an application that has reporting and auditing components may have 2 schemas called reporting and auditing with a collection of tables, stored procedures etc.  With Schemas, one can segregate out the reporting objects and audit objects.  One can also create different security accounts which can only access a specific schema.  A fully qualified name will include the schema.  For example:

SELECT * FROM [Test].[dbo].[Person]

Test is the database.
dbo is the schema.
Person is the table.

A data model in a database should be relational which means it is described by tables.  The data describes how the data is stored and organized.   A data model may belong to one or more schemas, typically usually it just belongs to one schema.

The person table will be a part of a number of tables and relations that make up the data model.


问:
Const and non-const methods, and possible mutable data member?
I'm working on a design and implementation change due to a bug. The bug fix requires us to modify a class object in a const method. I think the two options are:

Have the non-const method cast this to const (and hence call the const method)?

Have the const method cast away const-ness (and hence call the non-const method)?

In the case of (1), we have to declare the data members as mutable.

In the case of (2), we can do away with mutable data members.

The third option - don't get into this situation in the first place - is no longer available.

What is the best practice for a const method and non-const method that operates on member data? Or, put another way, how should this design and implementation change proceed?

The gyrations are due to a bug fix and our extreme desire that "things just work" with existing code. We don't want to force users to rewrite their code, so we do something lazily in a const method (users call Foo and have never called Bar until the fix):

```<code>void Foo() const
{
    // Added due to bug fix
    if(!m_bar)
        Bar();
}

void Bar() const
{
    // m_1 and m_2 are mutable
    m_1 = ...
    m_2 = ...

    // m_3 and m_4 are untouched...

    m_bar = true;
}
</code>```

The problem actually goes deeper into the design. For example, Bar is declared virtual and non-const in a base class. So we have to do these things while avoiding name hiding.

A similar question that takes some of the mutable approach: Is it a bad idea to use mutable for pre-allocated temporaries?

答:
There are always two sides to constness: Being const in the sense of the programming language, and being logically constant. Say a C++ object has a pointer to a std::string object. If the C++ object is const, I can't change the pointer to point to a different std::string object. However, I can change the contents of the std::string object. Which doesn't change the object in the view of the language, but it logically changes the object.

const methods shouldn't logically change the object. Using "mutable", they can change the object. If you have for example a cache object, it is logically unchanged if it gives the same replies to the same requests. Whether it loads some object from disk to memory or unloads it from memory doesn't change how it reacts to requests.

Things like caching, on demand calculation, changing an internal representation, don't logically change the object, so I'd be Ok with making things mutable and changing them in a const method.


问:
How do I store the OAuth v1 consumer key and secret for an open source desktop Twitter client without revealing it to the user?
I want to make a thick-client, desktop, open source twitter client. I happen to be using .NET as my language and Twitterizer as my OAuth/Twitter wrapper, and my app will likely be released as open source.

To get an OAuth token, four pieces of information are required:

Access Token (twitter user name)

Access Secret (twitter password)

Consumer Key

Consumer Secret

The second two pieces of information are not to be shared, like a PGP private key. However, due to the way the OAuth authorization flow is designed, these need to be on the native app. Even if the application was not open source, and the consumer key/secret were encrypted, a reasonably skilled user could gain access to the consumer key/secret pair.

So my question is, how do I get around this problem? What is the proper strategy for a desktop Twitter client to protect its consumer key and secret?

答:
Section 4.6 of RFC 5849, which defines OAuth 1, states that the consumer secret was never intended for use by desktop consumers, despite Twitter's use thereof in practice. As Nelson Elhage pointed out in "Dear Twitter", Twitter can and does terminate consumer keys of desktop clients, provided that the client isn't too big to fail. But there are two workarounds to allow use of OAuth 1 in a desktop or mobile application.

One way is to proxy the entire Twitter protocol through a server that you operate. This way, the consumer secret stays on your server. This is the workaround recommended by Dick Hardt, editor of the OAuth 1 spec. This workaround does not address the cost of operating this server.

The other way, as suggested in a post by Raffi Krikorian to the Twitter development talk Google group and a post by Chris Steipp to a Wikipedia mailing list, is to "have each user register their copy of your desktop application as its own consumer." Then the user would copy and paste the newly registered consumer key and consumer secret into your application. The manual for your application would then need to include detailed instructions on how to register a new application on Twitter's developer site. This official limitation has a few practical problems:

Your client will face a usability disadvantage compared to well-known proprietary clients.

The form to create a new app doesn't appear to offer a way to pre-populate the required fields. This means you will have to update the registration walkthrough in your manual whenever Twitter changes the procedure for registering an app.

The developer agreement requires users to be of legal age to enter a binding contract. This means a user of your application aged 13 to 17 must have a parent accept the agreement on the user's behalf.

Twitter's Developer Policy prohibits mass-registering applications and "name squatting", which it defines as "submitting multiple applications with the same function under different names." I am unaware of any precedent as to whether Twitter has treated unrelated users who have registered separate copies of one application as "name squatters".


问:
Can I use git to replay changes for projects that use media assets rather than program source code?
So while waiting for a project to build I like to run gource and see a fun video of my team building the project over time. While I was watching me and my team fly around editing and changing the file tree a coworker who is on our media team loved the visual representation and immediately asked how I could do this for his team's media projects ( documentaries, short videos, poster design projects ) which are worked on as a team and everyone edits files individually and then pushes them up to a central server on the LAN.

I know git would freak every file change because to it the entire file is new every time they say export the video to the LAN or anything like that. But would a quick git repo be possible for a media team? How much overhead vs pay off would they expect?

答:
Pro and Cons:

For:

will store different versions over time

will still be able to use compression to reduce file size for older versions.

will enable different developers to share one code (or asset in this case) base.

will make sure any common files stay with 1 version.

will track who touches which files.

can use the git-fat tool https://github.com/jedbrown/git-fat to not store the files in git but use $ git fat pull when you want to get one

will be the same tool that many people will already know form using it for code.

Against:

different versions of media assets will probably need to be stored in their (compressed) entirety.

standard 'git difference' functionality will not work on media which is not code without customization.

people will need training in at least a subset of git commands and/or a git gui

will require all users to get all files, which for media, can mean a huge amount of data

The last point, also mentioned by Esben Skov Pedersen, is possibly a good reason to use SVN for the media.  This would be a judgement call.  With SVN you get the huge advantage of being able to get individual files and directories instead of the complete repository as with git.  The downside is that its an older technology with some different philosophies and and if folks use git at all (either concurrently or at other times) they will find the different philosophies and different syntax (or, worst, same syntax, different meaning!) confusing.


答:
Prunning is only feasible if you can use any heuristics based on the properties of the tree you are parsing, if it is general and no special properties for either the structure or the value, you risk on prunning the correct answer. That leaves you with still having to parse all the tree.

Since what you are doing doesnt involve modifying the tree, one possible option is to multi-threading (since i see you are coding in Java) in order improve speed execution.

Title: Given a tree calculating Max Sum from top to bottom suing DFS? optimization?

Body:
given a tree i want to calculate max sum of each path from top to bottom. I used DFS for the operation. Here is the function which takes root as input and gives max sum of the path from top to bottom :

```<code>   private int DFS_max(TreeNode root) {
    // TODO Auto-generated method stub
    if(root == null){
        //System.out.println(root.value);
        //System.out.println();
        return 0;
    }

    int lvalue = DFS_max(root.getLeftNode());
    int rvalue = DFS_max(root.getRightNode());

    //System.out.print(root.value+" ");

    return (Math.max(lvalue, rvalue)+root.value );
}
</code>```

however it takes to long time to execute following input:

```<code>9235
9096 637
973 3269 7039
3399 3350 4788 7546
1739 8032 9427 976 2476
703 9642 4232 1890 704 6463
9601 1921 5655 1119 3115 5920 1808
645 3674 246 2023 4440 9607 4112 3215
660 6345 323 1664 2331 7452 3794 7679 3102
1383 3058 755 1677 8032 2408 2592 2138 2373 8718
8117 4602 7324 7545 4014 6970 4342 7682 150 3856 8177
1966 1782 3248 1745 4864 9443 4900 8115 4120 9015 7040 9258
4572 6637 9558 5366 7156 1848 2524 4337 5049 7608 8639 8301 1939
7714 6996 2968 4473 541 3388 5992 2092 2973 9367 2573 2658 9965 8168
67 1546 3243 752 8497 5215 7319 9245 574 7634 2223 8296 3044 9445 120
7064 1045 5210 7347 5870 8487 3701 4301 1899 441 9828 3076 7769 8008 4496 6796
5256 2199 464 5164 4039 1014 8099 7932 1909 3051 4805 1698 8578 1771 5889 5711 9967
6830 2603 9256 3629 2793 5219 6534 8838 944 5113 4981 6811 6958 48 9463 7477 5723 1111
7907 9312 4756 8096 3564 7809 9326 2502 5346 6383 5658 3791 423 701 3417 5042 2669 3759 5017
8754 6389 4368 7284 2150 7288 6145 459 4079 1631 7595 620 2350 171 6401 4222 1182 5561 2669 7641
3335 696 6551 360 454 708 5378 7750 8156 3187 4263 8282 9494 9607 1989 435 1558 5920 909 6567 5174
1771 5573 4603 6962 5957 9870 3482 6287 324 6551 5035 7100 5595 6189 3178 6047 354 4873 1168 3815 8771 1222
8982 6194 3575 3673 5892 5035 8234 8414 7744 6956 6341 6824 4562 9416 6808 8836 1692 9636 609 5238 6918 1685 8565
7610 6713 1077 9905 9328 7107 4166 8230 4864 8540 1762 4870 7483 9504 2516 9634 7336 761 1805 5454 2967 530 6166 6541
9277 1113 1596 9327 4106 9159 6484 1666 3774 5001 6357 8586 5151 1306 8160 2201 8124 7684 6362 9309 7702 5800 1827 2679 9402
9080 7085 1053 5077 2129 8422 8489 8852 7628 6024 5841 4504 2658 8298 5860 6226 2157 5477 8728 4520 4513 590 6642 7711 3209 3005
4500 7462 8825 848 8698 3585 7756 3857 7587 9434 7531 7443 5232 4212 3761 2111 4765 2628 432 9750 8871 5534 3519 9777 2692 7383 7686
3624 8816 7672 7245 5646 4888 3871 5462 2170 1897 2787 823 8107 5186 5782 4911 2313 835 816 4192 8726 7262 903 7191 187 5542 4234 9292
5817 2292 5964 9704 836 5776 5457 9027 9782 9306 5636 1268 250 5976 3032 1188 4460 5327 8071 6400 229 5587 5243 3777 1265 4847 1853 1421 9092
704 2262 685 5345 716 1758 7567 3740 5354 480 9161 5544 1022 3196 8803 1074 3236 5157 3026 2407 9018 7720 4543 9281 3233 13 8065 996 5680 4485
9963 1991 4531 4900 8560 7771 6957 5041 9103 823 9644 5190 6393 3295 291 1344 8459 4311 6189 8997 6670 5018 7465 9360 1255 3737 714 891 6314 6900 3369
3160 5093 8864 404 3212 4571 5136 2730 6864 8175 9081 991 8629 6874 1727 9398 4353 1791 7975 1676 79 6005 173 5249 9092 9272 1827 401 6713 7010 26 8267
8974 4103 5046 5274 6983 4807 9583 1897 3563 2384 8047 476 2499 5930 8452 214 3611 7346 5579 7471 8807 8361 4272 5997 5233 6109 6024 4832 1692 5886 327 1273 3633
1377 4645 2518 160 5935 3329 2396 3755 3272 6328 8905 9729 2328 3103 4238 7738 8995 5798 1396 2157 6902 8463 558 1575 515 5827 3949 234 6437 6012 126 5832 2979 6441
7307 8791 3842 1132 657 7840 9032 640 289 5535 5045 2925 5151 5220 6760 4623 2934 7859 5524 7361 7679 3131 1427 3046 4833 4257 2937 5389 8209 128 3724 2300 4461 1466 4779
5267 8533 9 9710 7333 7839 986 2533 875 3863 9532 147 22 7337 1095 6244 267 7172 4391 9425 9587 3942 3000 5959 1211 5846 8321 6766 8081 8815 2253 9001 2992 2718 2738 4910
6435 2443 9071 4492 6216 6061 6768 3976 9095 2236 3682 9092 4889 5596 70 689 7730 1847 5340 394 7524 4099 3329 5672 7042 8078 6141 6914 6522 6675 3795 4000 8177 3662 3259 6130 7610
2258 5763 6708 7737 6758 5762 4507 3566 4424 8365 3451 2915 465 4607 5963 9007 1072 5565 9005 5753 8196 6975 7712 5498 5059 5742 8816 2030 3209 8568 4937 8719 345 728 1278 2792 3133 9997
8226 1983 721 6701 6953 9027 2801 5895 239 2827 701 1815 7406 2497 1211 7901 525 1956 638 7934 8869 8237 936 5126 9949 6296 633 6368 8425 6713 806 8251 8680 397 316 9989 2901 6176 5180
5883 4165 2973 4063 6614 3168 8186 5624 4303 8055 7803 3721 1023 9048 1845 3325 4237 3518 782 3410 5515 2521 4720 3050 785 6882 7356 3478 1374 9420 981 1986 5142 67 7113 3167 6122 2324 9764 9257
9240 2726 4783 4078 3959 9828 9244 4470 6945 5576 9405 8984 9255 9900 4457 6075 7944 8826 5918 3086 5487 7507 9357 2894 2955 2176 5932 7258 4504 9219 6115 4612 1390 5323 6949 5366 3494 9970 7190 9565 5099
408 1771 233 9549 9691 8154 641 4346 372 2372 5306 4199 9991 1790 2614 4628 9646 4980 1610 2803 3596 6476 6735 5484 6132 5633 2054 6181 1731 4350 891 4916 5913 7961 7657 4368 7146 7280 6168 5573 4644 7463
2764 4872 2984 1130 3119 1307 2067 9021 8833 320 175 1340 3573 5251 8588 6919 8844 2877 8567 5325 6300 3049 5378 9129 6921 5313 9471 9705 7350 7360 1923 107 219 1110 9836 2867 8386 2290 7486 8872 2663 8492 730
5867 8841 8856 5413 1612 2596 5748 5338 7189 203 5146 1741 595 8910 7746 4155 9357 3261 7284 2035 3615 2738 6013 7593 7917 1633 9843 2925 754 4269 7264 8673 5793 7381 6835 7263 7709 6751 7766 1013 8521 7056 6920 4360
7443 2273 3418 9801 8378 8974 8954 9246 4411 6370 7927 5950 7904 5051 6515 7396 8136 1045 3969 6132 5834 3021 2540 3863 5369 8259 4713 3878 938 7348 7709 8282 2613 8476 5590 9457 1787 9665 8699 9658 3258 1318 8696 8707 2945
2046 4951 7421 6082 7912 4707 3529 598 8938 5077 7661 4384 6996 9684 9235 3127 6083 6544 6007 7501 9347 6667 6444 4635 7229 4760 1094 8971 7614 4417 7722 1933 1969 208 5048 8094 1119 8218 1666 7993 522 4744 9958 4152 7693 89
9612 7380 3771 710 1762 5054 7126 8320 2685 1662 9388 8978 5499 4646 3294 8688 9370 5317 7359 4567 8370 5459 4536 2262 6300 5134 733 971 9561 6144 4359 7153 7467 8628 9912 6814 8260 5362 7016 4115 9541 9460 1306 981 3825 6374 5069
8361 3493 390 3674 4850 4541 9096 8460 2493 5224 6751 7965 2760 3920 8877 7202 7919 394 5969 8981 4346 5975 3758 2230 4641 1135 1125 9698 4879 3430 4465 1502 1795 4859 9068 1531 2233 5295 3901 906 3839 7849 6098 6405 1623 2772 5385 2056
9751 8824 6710 8920 1747 4906 1411 1538 5134 184 3420 9440 8450 7965 7169 8679 9609 7117 8177 1438 4561 4963 5590 1412 4378 7282 8360 8899 7026 4281 3187 2305 7333 6235 2890 2116 4971 8843 8424 9320 5605 6329 6432 2684 4828 9772 6893 8386 7931
9250 2232 1035 1163 989 51 7337 1713 4906 6565 2308 4321 3688 6762 3303 2175 1854 321 8894 8548 2141 9426 8111 3471 6968 5728 468 6697 4772 8928 8778 4151 4531 8724 4829 164 6951 5181 2656 1852 7463 9987 5372 5192 4444 2515 9302 4612 5865 120
</code>```

I wanted to optimize this code to run faster ? how can i do it? i am not able to figure out what goes wrong here?