问:
Error: Can't set headers after they are sent. in nodejs
I am running into the error show below on my app,line 413 points to “res.json(stat); // return in JSON format.” in below code, I looked at other posts with similar error but none helped me, why am I hitting this error ?appreciate any guidance on how to fix it?

```<code>app.post('/api/botjobs.json', function(req, res) {
    // console.log(req.body)
    data = req.body;
    var temp = {};
    temp.radar = data.radar;
    temp.request = data.request;
    if(temp.request == 'cloneradar'){
        temp['params.clonetype'] = data.params.clonetype;
    }
    now = new Date();
    data["updated"] = now;
    // console.log('DATA:')
    // console.log(data)
    // console.log('TEMP:')
    // console.log(temp)
    botjobs.findOne(temp, {}, { sort:{'_id': -1}}, function(err, findstat){
        // console.log(findstat)
        // console.log(err)
        // console.log("inside botjobs findOne");
        if(findstat != null){
            // console.log('updating entry')
            //console.log(findstat);
            data['numupdated'] = findstat['numupdated']+1;
            // console.log(data);
            botjobs.update({'_id':findstat['_id']},data,{ upsert : true, multi: true },function(err,stat){
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format
            });

        }
        else{
            // console.log('creating new entry')
            data["created"] = now;
            data['numupdated'] = 0;
            botjobs.create(data,function(err, stat) {
                // console.log(stat);
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format. —> line 413 in route.js
            });
        }

    });

});
</code>```

Error:-

```<code>Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
    at ServerResponse.res.setHeader (/app/node_modules/express/node_modules/connect/lib/patch.js:134:22)
    at ServerResponse.res.set.res.header (/app/node_modules/express/lib/response.js:595:10)
    at ServerResponse.res.send (/app/node_modules/express/lib/response.js:151:12)
    at ServerResponse.res.json (/app/node_modules/express/lib/response.js:237:15)
    at /app/app/routes.js:413:10
</code>```

答:
"Can't set headers after they are sent", this error occurs when u are trying to send something when the response is already sent. The res.send() ends the response so you cant send anything after res.send(). Why you are receiving this error is because the update call might be returning error and hence the res.send() is getting called which is inside if block.
To avoid the can't set headers error in your case, you need to wrap inside if-else block, like this:

```<code>if (err){
 res.send(err);
}else{
 res.json(stat);
}

</code>```

This will resolve the cant set headers issue, but your code still might fail because i think your update method is failing.

Body:
I am running into the error show below on my app,line 413 points to “res.json(stat); // return in JSON format.” in below code, I looked at other posts with similar error but none helped me, why am I hitting this error ?appreciate any guidance on how to fix it?

app.post('/api/botjobs.json', function(req, res) {
    // console.log(req.body)
    data = req.body;
    var temp = {};
    temp.radar = data.radar;
    temp.request = data.request;
    if(temp.request == 'cloneradar'){
        temp['params.clonetype'] = data.params.clonetype;
    }
    now = new Date();
    data["updated"] = now;
    // console.log('DATA:')
    // console.log(data)
    // console.log('TEMP:')
    // console.log(temp)
    botjobs.findOne(temp, {}, { sort:{'_id': -1}}, function(err, findstat){
        // console.log(findstat)
        // console.log(err)
        // console.log("inside botjobs findOne");
        if(findstat != null){
            // console.log('updating entry')
            //console.log(findstat);
            data['numupdated'] = findstat['numupdated']+1;
            // console.log(data);
            botjobs.update({'_id':findstat['_id']},data,{ upsert : true, multi: true },function(err,stat){
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format
            });

        }
        else{
            // console.log('creating new entry')
            data["created"] = now;
            data['numupdated'] = 0;
            botjobs.create(data,function(err, stat) {
                // console.log(stat);
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format. —> line 413 in route.js
            });
        }

    });

});

Error:-

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
    at ServerResponse.res.setHeader (/app/node_modules/express/node_modules/connect/lib/patch.js:134:22)
    at ServerResponse.res.set.res.header (/app/node_modules/express/lib/response.js:595:10)
    at ServerResponse.res.send (/app/node_modules/express/lib/response.js:151:12)
    at ServerResponse.res.json (/app/node_modules/express/lib/response.js:237:15)
    at /app/app/routes.js:413:10

Body:
"Can't set headers after they are sent", this error occurs when u are trying to send something when the response is already sent. The res.send() ends the response so you cant send anything after res.send(). Why you are receiving this error is because the update call might be returning error and hence the res.send() is getting called which is inside if block.
To avoid the can't set headers error in your case, you need to wrap inside if-else block, like this:

if (err){
 res.send(err);
}else{
 res.json(stat);
}

This will resolve the cant set headers issue, but your code still might fail because i think your update method is failing.


来源: stackexchange

问:
Using JScript.NET today?
Is it a good idea to use JScript.NET these days? Is there any IDE or text editor for JScript.NET? Is there any modern programming language on the CLR that has eval on language level (without the need of external libraries)?</p>

答:
I actually use JScript.NET all the time, I'm probably the only one that still does. It's very useful for making console apps without needing any extras to be installed on the machine.

It's not needed to download anything to start coding in JScript.NET, the jsc.exe compiler comes builtin to Windows 10, and you can compile a simple JScript.NET app to about 20k filesize, which is a lot less than is required just to run a Node script -> download Node (40mb) -> install Node -> run script.

The version of JavaScript is a bit weird, but not so different from modern ES5-ES6, like it has ...rest args in functions, and it has Class, Extends etc, and it has all the .NET goodies if you want to use them, and also optional strong-typing.

ContentLicense: CC BY-SA 3.0

Title: Using JScript.NET today?

ContentLicense: CC BY-SA 4.0


问:
Why does CountA produce an extra row
My code produces an extra row, whenever I fill any data at row 4 column T.

If I leave row 4 column T empty, it will display data at row 5.

```<code>Sub All_N()
    Dim ws As Worksheet

    Sheets("sum").Activate
    Sheets("sum").Range("A5:T1048576").Select
    Selection.ClearContents
    Sheets("sum").Range("A5").Select

    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name <> "sum" Then
            cont1 = Application.WorksheetFunction.CountA(ws.Range("T3:T1048576")) + 2

            For a = 2 To cont1
                If ws.Cells(a, 20) = "N" Then
                    b = Application.WorksheetFunction.CountA(Sheets("sum").Range("T3:T1048576")) + 5
                    Sheets("sum").Cells(b, 1) = ws.Cells(a, 1)
                    Sheets("sum").Cells(b, 2) = ws.Cells(a, 2)
                    Sheets("sum").Cells(b, 18) = ws.Cells(a, 18)
                    Sheets("sum").Cells(b, 19) = ws.Cells(a, 19)
                    Sheets("sum").Cells(b, 20) = ws.Cells(a, 20)
                End If
            Next a
        End If
    Next
End Sub
</code>```

答:
I guess you want to loop over all used rows in all your sheets

and then fill in the next empty row in your "sum" sheet.

To find the last used row in column "T",

you may use .Cells(.Rows.Count, "T").End(xlUp).Row

```<code>Option Explicit

Sub All_N()
    Dim wsSum As Worksheet
    Dim ws As Worksheet
    Dim a As Long, b As Long

    Set wsSum = ActiveWorkbook.Sheets("sum")
    With wsSum
        .Range("A5:T" & .Rows.Count).ClearContents
        b = 5
        For Each ws In ActiveWorkbook.Worksheets
            If ws.Name <> "sum" Then
                For a = 2 To ws.Cells(ws.Rows.Count, "T").End(xlUp).Row
                    If ws.Cells(a, "T") = "N" Then
                        .Cells(b, 1) = ws.Cells(a, 1)
                        .Cells(b, 2) = ws.Cells(a, 2)
                        .Cells(b, 18) = ws.Cells(a, 18)
                        .Cells(b, 19) = ws.Cells(a, 19)
                        .Cells(b, 20) = ws.Cells(a, 20)
                        b = b + 1
                    End If
                Next a
            End If
        Next
    End With
End Sub
</code>```

It is not necessary to Select or Activate anything, see here.

Title: Why does CountA produce an extra row

Body:
My code produces an extra row, whenever I fill any data at row 4 column T.

If I leave row 4 column T empty, it will display data at row 5.

Sub All_N()
    Dim ws As Worksheet

    Sheets("sum").Activate
    Sheets("sum").Range("A5:T1048576").Select
    Selection.ClearContents
    Sheets("sum").Range("A5").Select

    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name <> "sum" Then
            cont1 = Application.WorksheetFunction.CountA(ws.Range("T3:T1048576")) + 2

            For a = 2 To cont1
                If ws.Cells(a, 20) = "N" Then
                    b = Application.WorksheetFunction.CountA(Sheets("sum").Range("T3:T1048576")) + 5
                    Sheets("sum").Cells(b, 1) = ws.Cells(a, 1)
                    Sheets("sum").Cells(b, 2) = ws.Cells(a, 2)
                    Sheets("sum").Cells(b, 18) = ws.Cells(a, 18)
                    Sheets("sum").Cells(b, 19) = ws.Cells(a, 19)
                    Sheets("sum").Cells(b, 20) = ws.Cells(a, 20)
                End If
            Next a
        End If
    Next
End Sub

Body:
I guess you want to loop over all used rows in all your sheets

and then fill in the next empty row in your "sum" sheet.

To find the last used row in column "T",

you may use .Cells(.Rows.Count, "T").End(xlUp).Row

Option Explicit

Sub All_N()
    Dim wsSum As Worksheet
    Dim ws As Worksheet
    Dim a As Long, b As Long

    Set wsSum = ActiveWorkbook.Sheets("sum")
    With wsSum
        .Range("A5:T" & .Rows.Count).ClearContents
        b = 5
        For Each ws In ActiveWorkbook.Worksheets
            If ws.Name <> "sum" Then
                For a = 2 To ws.Cells(ws.Rows.Count, "T").End(xlUp).Row
                    If ws.Cells(a, "T") = "N" Then
                        .Cells(b, 1) = ws.Cells(a, 1)
                        .Cells(b, 2) = ws.Cells(a, 2)
                        .Cells(b, 18) = ws.Cells(a, 18)
                        .Cells(b, 19) = ws.Cells(a, 19)
                        .Cells(b, 20) = ws.Cells(a, 20)
                        b = b + 1
                    End If
                Next a
            End If
        Next
    End With
End Sub

It is not necessary to Select or Activate anything, see here.


问:
Error: "declares multiple JSON fields named..." when parsing classes with getter/setter values defined in interfaces
Consider the following classes/interfaces:

```<code>interface ExampleKotlinInterface {
    val name: String
}
</code>```

```<code>interface ExampleKotlinInterfaceSubclass : ExampleKotlinInterface {
    override var name: String
}
</code>```

```<code>abstract class ExampleKotlinImpl(@SerializedName("name") override val name: String = "zach") : ExampleKotlinInterface
</code>```

```<code>class ExampleKotlinImplSubclass(override var name: String) : ExampleKotlinImpl(name), ExampleKotlinInterfaceSubclass
</code>```

where the first interface defines a value name and the second interface extends this, but exposes the name value as a var.  I am unable to parse the ExampleKotlinImplSubclass with Gson because of the following error:

```<code>java.lang.IllegalArgumentException: class com.example.kotlingetterinterfaceexample.ExampleKotlinImplSubclass declares multiple JSON fields named name

    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:172)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
    at com.google.gson.Gson.getAdapter(Gson.java:458)
    at com.google.gson.Gson.fromJson(Gson.java:926)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at com.google.gson.Gson.fromJson(Gson.java:841)
    at com.google.gson.Gson.fromJson(Gson.java:813)
    at com.example.kotlingetterinterfaceexample.ExampleGsonParseTests.testParseObject(ExampleGsonParseTests.kt:13)
</code>```

using this test code:

```<code>        val json = "{ \"name\" : \"test\" }"

        val result = Gson().fromJson(json, ExampleKotlinImplSubclass::class.java)

        assertNotNull(result)

        assertEquals("test", result.name)
</code>```

The theory is that my superclass should not be allowed to change the value of name, but the subclass should be able to.

Any ideas on how to work around this?

Link to sample project showing this issue: https://github.com/ZOlbrys/kotlingetterinterfaceexample

答:
See my Java based answer. GSON does not handle this kind of situation well. The only option I see is that you do not override fields. What you could do - if it is any help - create one more level in your interfaces, something like:

```<code>interface ExampleKotlinInterfaceTop {
    fun getName(): String
    ...
}

interface ExampleKotlinInterface : ExampleKotlinInterfaceTop {
    val name: String
    ...
}

interface ExampleKotlinInterfaceSubclass : ExampleKotlinInterfaceTop {
    var name: String
    ...
}
</code>```

I am not a Kotlin programmer so guess there is a lot to fix in my example code but as a principle of the possible solution.

Body:
Consider the following classes/interfaces:

interface ExampleKotlinInterface {
    val name: String
}

interface ExampleKotlinInterfaceSubclass : ExampleKotlinInterface {
    override var name: String
}

abstract class ExampleKotlinImpl(@SerializedName("name") override val name: String = "zach") : ExampleKotlinInterface

class ExampleKotlinImplSubclass(override var name: String) : ExampleKotlinImpl(name), ExampleKotlinInterfaceSubclass

where the first interface defines a value name and the second interface extends this, but exposes the name value as a var.  I am unable to parse the ExampleKotlinImplSubclass with Gson because of the following error:

java.lang.IllegalArgumentException: class com.example.kotlingetterinterfaceexample.ExampleKotlinImplSubclass declares multiple JSON fields named name

    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:172)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
    at com.google.gson.Gson.getAdapter(Gson.java:458)
    at com.google.gson.Gson.fromJson(Gson.java:926)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at com.google.gson.Gson.fromJson(Gson.java:841)
    at com.google.gson.Gson.fromJson(Gson.java:813)
    at com.example.kotlingetterinterfaceexample.ExampleGsonParseTests.testParseObject(ExampleGsonParseTests.kt:13)

using this test code:

        val json = "{ \"name\" : \"test\" }"

        val result = Gson().fromJson(json, ExampleKotlinImplSubclass::class.java)

        assertNotNull(result)

        assertEquals("test", result.name)

The theory is that my superclass should not be allowed to change the value of name, but the subclass should be able to.

Any ideas on how to work around this?

Link to sample project showing this issue: https://github.com/ZOlbrys/kotlingetterinterfaceexample

Body:
See my Java based answer. GSON does not handle this kind of situation well. The only option I see is that you do not override fields. What you could do - if it is any help - create one more level in your interfaces, something like:

interface ExampleKotlinInterfaceTop {
    fun getName(): String
    ...
}

interface ExampleKotlinInterface : ExampleKotlinInterfaceTop {
    val name: String
    ...
}

interface ExampleKotlinInterfaceSubclass : ExampleKotlinInterfaceTop {
    var name: String
    ...
}

I am not a Kotlin programmer so guess there is a lot to fix in my example code but as a principle of the possible solution.


问:
stanfordNLP Pipeline - Python
I was wondering how to actually use the StanfordNLP Pipeline through python using the stanfordnlp library. There doesn't seem to be any clear documentation as to how to actually enter the annotators, their attributes, etc.?

For example, nlp = stanfordnlp.Pipeline() sets up a new pipeline. Is there a way to specify which annotators it uses?

For example, I want to specify the following commands:

```<code>-annotators tokenize,ssplit,pos,lemma,ner,depparse,coref,quote -coref.algorithm statistical
</code>```

How would I do that using the stanfordnlp.Pipeline() command?

答:
There are two pipelines:

the native Python pipeline runs tokenize,mwt,pos,lemma,depparse

the traditional Java pipeline

If you want to use the Java pipeline, you need to use the server.

There is detailed discussion of this here: https://stanfordnlp.github.io/stanfordnlp/corenlp_client.html

Title: stanfordNLP Pipeline - Python

Body:
I was wondering how to actually use the StanfordNLP Pipeline through python using the stanfordnlp library. There doesn't seem to be any clear documentation as to how to actually enter the annotators, their attributes, etc.?

For example, nlp = stanfordnlp.Pipeline() sets up a new pipeline. Is there a way to specify which annotators it uses?

For example, I want to specify the following commands:

-annotators tokenize,ssplit,pos,lemma,ner,depparse,coref,quote -coref.algorithm statistical

How would I do that using the stanfordnlp.Pipeline() command?


问:
Ignore Python Exception and directly continue after it in Sub-Module Code
I use a python library that throws an exception that is known to be wrong. In fact, a recent pull requests suggests to just remove the line that throws the exception.

Is there a way to force the python code to continue ignoring the exception without breaking out of the sub-module code? Embedding the library call into an except block does not help, because subsequent code won't be executed.

I could merge the pull request myself and install a custom version of the library, but this breaks the whole deployment/dependency/update process.

The code I want to ignore consists out of these two lines:

```<code>if '<img class="icon meh" src="/yts/img' not in self.watch_html:
    raise VideoUnavailable('This video is unavailable.')
</code>```

from this file that has been patched by this commit in this pr.

答:
I don't think this is possible, and even if it was, I believe it would only be less maintainable.

I think the best solution in this case would be to subclass and override the function in question. The drawbacks are that if you update the library, you have to update the function as well, until the problem is solved completely.
It could look like this, having removed the exception-lines, using the code you linked from pytube:

```<code>from pytube import Caption
from pytube import CaptionQuery
from pytube import extract
from pytube import mixins
from pytube import request
from pytube import Stream
from pytube import StreamQuery
from pytube.compat import install_proxy
from pytube.compat import parse_qsl
from pytube.exceptions import VideoUnavailable
from pytube.helpers import apply_mixin

from pytube import YouTube

class MyYouTube(YouTube):
    # https://github.com/nficano/pytube/blob/master/pytube/__main__.py#L150
    def prefetch(self):
        """Eagerly download all necessary data.

        Eagerly executes all necessary network requests so all other
        operations don't does need to make calls outside of the interpreter
        which blocks for long periods of time.

        :rtype: None

        """
        self.watch_html = request.get(url=self.watch_url)
        self.embed_html = request.get(url=self.embed_url)
        self.age_restricted = extract.is_age_restricted(self.watch_html)
        self.vid_info_url = extract.video_info_url(
            video_id=self.video_id,
            watch_url=self.watch_url,
            watch_html=self.watch_html,
            embed_html=self.embed_html,
            age_restricted=self.age_restricted,
        )
        self.vid_info = request.get(self.vid_info_url)
        if not self.age_restricted:
            self.js_url = extract.js_url(self.watch_html, self.age_restricted)
            self.js = request.get(self.js_url)

#YouTube('https://www.youtube.com/watch?v=irauhITDrsE').streams.first().download()  # Doesnt work
MyYouTube('https://www.youtube.com/watch?v=irauhITDrsE').streams.first().download() # Works
</code>```

Depending on the programming language, this may not always be possible due to visibility. Luckily Python doesn't care much.

Body:
I use a python library that throws an exception that is known to be wrong. In fact, a recent pull requests suggests to just remove the line that throws the exception.

Is there a way to force the python code to continue ignoring the exception without breaking out of the sub-module code? Embedding the library call into an except block does not help, because subsequent code won't be executed.

I could merge the pull request myself and install a custom version of the library, but this breaks the whole deployment/dependency/update process.

The code I want to ignore consists out of these two lines:

if '<img class="icon meh" src="/yts/img' not in self.watch_html:
    raise VideoUnavailable('This video is unavailable.')

from this file that has been patched by this commit in this pr.

Body:
I don't think this is possible, and even if it was, I believe it would only be less maintainable.

I think the best solution in this case would be to subclass and override the function in question. The drawbacks are that if you update the library, you have to update the function as well, until the problem is solved completely.
It could look like this, having removed the exception-lines, using the code you linked from pytube:

from pytube import Caption
from pytube import CaptionQuery
from pytube import extract
from pytube import mixins
from pytube import request
from pytube import Stream
from pytube import StreamQuery
from pytube.compat import install_proxy
from pytube.compat import parse_qsl
from pytube.exceptions import VideoUnavailable
from pytube.helpers import apply_mixin

from pytube import YouTube

class MyYouTube(YouTube):
    # https://github.com/nficano/pytube/blob/master/pytube/__main__.py#L150
    def prefetch(self):
        """Eagerly download all necessary data.

        Eagerly executes all necessary network requests so all other
        operations don't does need to make calls outside of the interpreter
        which blocks for long periods of time.

        :rtype: None

        """
        self.watch_html = request.get(url=self.watch_url)
        self.embed_html = request.get(url=self.embed_url)
        self.age_restricted = extract.is_age_restricted(self.watch_html)
        self.vid_info_url = extract.video_info_url(
            video_id=self.video_id,
            watch_url=self.watch_url,
            watch_html=self.watch_html,
            embed_html=self.embed_html,
            age_restricted=self.age_restricted,
        )
        self.vid_info = request.get(self.vid_info_url)
        if not self.age_restricted:
            self.js_url = extract.js_url(self.watch_html, self.age_restricted)
            self.js = request.get(self.js_url)

#YouTube('https://www.youtube.com/watch?v=irauhITDrsE').streams.first().download()  # Doesnt work
MyYouTube('https://www.youtube.com/watch?v=irauhITDrsE').streams.first().download() # Works

Depending on the programming language, this may not always be possible due to visibility. Luckily Python doesn't care much.


问:
AppleScript iterating through Outlook messages - time received is missing value
I'm using AppleScript to iterate (using a repeater) through messages in an Outlook folder, and I can access TIME RECEIVED on the first iteration, but on subsequent iterations TIME RECEIVED is "Missing Value"

Pared code down to problem area, still repros error.
Using MacOS Mohave 10.14.4, Office 365 for Mac/Home version, Outlook v16.25

```<code>tell application "Microsoft Outlook"
    set msgs to messages of folder "Sent" of default account
    repeat with msg in msgs
        set messageTime to time received of msg
        set y to year of messageTime -- 1st time through is OK, each add'l time says missing value
        display notification "" & y
        delay 1
    end repeat
end tell
</code>```

Actual error message in Script Editor is "Can't get year of missing value".

Tried switching inbox vs. sent, same problem.

答:
My mistake - should've used TIME SENT, not TIME RECEIVED.  And I'm not checking for null (rookie mistake!) :)

set messageTime to time received of msg

should be:

set messageTime to time sent of msg

Body:
I'm using AppleScript to iterate (using a repeater) through messages in an Outlook folder, and I can access TIME RECEIVED on the first iteration, but on subsequent iterations TIME RECEIVED is "Missing Value"

Pared code down to problem area, still repros error.
Using MacOS Mohave 10.14.4, Office 365 for Mac/Home version, Outlook v16.25

tell application "Microsoft Outlook"
    set msgs to messages of folder "Sent" of default account
    repeat with msg in msgs
        set messageTime to time received of msg
        set y to year of messageTime -- 1st time through is OK, each add'l time says missing value
        display notification "" & y
        delay 1
    end repeat
end tell

Actual error message in Script Editor is "Can't get year of missing value".

Tried switching inbox vs. sent, same problem.


问:
Can I get values from the local storage using Async Storage from React Native?
I am new at React Native. There is a native application written in Objective-C for iOS and Java for Android. My task is to add two more screens using React Native. The general solution is here.

The native code already uses a local storage to store permanent data (for example, data about an authorized user). At the same time, React Native uses Async Storage to handle permanent data.

Can I get values from the local storage using Async Storage from React Native?

答: As far as i know AsyncStorage is using Dictionary on iOS side and SQLite on android side. Both of which are not accessible in React Native side. You should write a bridge between native side and React Native to in order to allow passing of data between two sides, this https://github.com/sriraman/react-native-shared-preferences library is a good example, it allows React Native access local native shared prefrences and vice versa. </p>


问:
Why null is being display on the screen in an Angular 5 app?
I have simple template which display a value of a string:

```<code><span class="fax_number">{{company.fax}}</span>
</code>```

When the value empty, the screen display the string "null" instead of
empty string, this happen in many places in the application, is there
a good way to avoid this ?

答:
you can avoid this by setting undefined for the variable.

```<code>this.company.fax = this.company.fax != null ? this.company.fax: undefined;
</code>```

I think adding a condition throughout the project to just check for the null, is not a good idea.

Body:
I have simple template which display a value of a string:

{{company.fax}}

When the value empty, the screen display the string "null" instead of
empty string, this happen in many places in the application, is there
a good way to avoid this ?

Body:
you can avoid this by setting undefined for the variable.

this.company.fax = this.company.fax != null ? this.company.fax: undefined;

I think adding a condition throughout the project to just check for the null, is not a good idea.


问:
Selecting data from sql database doesn't work. how do I fix it?
I am trying to select data from a database. I do have a successful connection, but it seems like the query doesn't work even though I know for sure that the query is right. What am I doing wrong?

If I execute the code below, the result I get is: "Connected successfullyBad query". The 'Bad query' should mean that the query is wrong, but I checked it and it isn't wrong...

```<code><?php
$servername = "localhost";
$username = "root";
$password = "usbw";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>
</code>```

I expect to only see "connected successfully"

答:
Please give database name also, check below code.</p>

```<code><?php
$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = "";      //Enter database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>
</code>```

Body:
I am trying to select data from a database. I do have a successful connection, but it seems like the query doesn't work even though I know for sure that the query is right. What am I doing wrong?

If I execute the code below, the result I get is: "Connected successfullyBad query". The 'Bad query' should mean that the query is wrong, but I checked it and it isn't wrong...

<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>

I expect to only see "connected successfully"

Body:
Please give database name also, check below code.

<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = "";      //Enter database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>


问:
Visual Studio solutions: Do these solutions have too many projects?
In the company I currently work for, we support 4 windows applications that are somewhat related. For each application we have a solution, each ranging from 50 to 100 projects. There are probably 40 or 50 projects that are shared between one or more solutions.

Just to give you an idea, the larger solution has almost 90 projects, 20 of which are UI projects (main application, custom controls projects, UI helper projects), another 20 are Business Layer projects, there's probably 30 or 40 Data Access layer projects and the rest are Windows Service projects and specialized projects

I've always felt that there are too many projects in each solution. Sure, we're talking about large applications, but I don't see why many of the projects couldn't be consolidated. In my previous company, we actually had one single project for the business layer, one single project for the DAL and obviously one project for each windows or web app.

Here are some of the problems I've come across due to the large amount of projects:

Large compile times.

Classes that normally should be Private need to be Public in order to be accessible by other projects in the same layer.

I've recently started using the profiler Eqateq. The trial version allows profiling up to 10 dlls. My situation obviously complicates using this application.

Keeping track of the references between projects is quite complicated. I'm sure there are a lot of unused references between projects.

In contrast, I haven't found an advantage of this situation.

So, my questions are:

When do you decide to create a new project instead of maybe just creating a folder in the current project?

Are there any advantages that I'm overlooking?

UPDATE:

Keep in mind that I'm not proposing having one single project for everything. At a bare minimum, there should be one project for the DAL, one for the BL and one for every UI app. And I realize even that is unrealistic for most applications.
What I'm trying to get at is, what are the best practices for defining the level of "single responsibility" for an assembly? I mean, this is a very subjective matter that, if taken to the extreme, would lead to having one assembly per class.

UPDATE 2:

All three answers provided valuable information, but as I can only select one I'm choosing Doc's for his comment on how to determine the number of DAL projects.
I'm also linking to other questions I just found that have related information: Here and here.
I also recommend reading this article.

答:
I think the real issue here is one of single responsibility. I don't mean in terms of class design I mean the purpose of a .Net project.

Generally a project is used for:

1. Building some code to output a DLL, EXE, Website, API etc.

2. To control access to and structure code in a solution

From my experience, most projects are used for 2.
What this leads to in large solutions is a very breadth-first structure that quickly becomes unintuitive, slows builds, slows visual studio (hello resharper!) means that huge amounts of dependencies get moved from bin to bin which makes all these DLLs that you don't actually need.

For example, if c# access modifiers could be expressed at namespace boundaries (instead of Project) then we wouldn't need to do this and could have meaningful intuitive namespace hierarchies where you would only need a project if you actually need to produce a DLL. Of course I haven't completely thought this through but I feel like something isn't quite right with having so many projects in a solution.

How does Java deal with this? Do large Java projects have lots of circular dependencies?

My answer to the question is to have as few Projects as you can get away with.


问:
Celery worker which directory to start from
I need some help regarding Celery workers. I'm especially not able to understand where (which directory) does the celery worker command needs to be fired from and what is the concept behind it and some things around imports.

So say I have the following directory structure :

```<code>.
├── __init__.py
├── entry.py
├── state1
│   ├── __init__.py
│   ├── family1
│   │   ├── __init__.py
│   │   ├── task1.py
│   │   ├── task2.py
│   │   └── task3.py
│   └── family2
│       ├── __init__.py
│       └── task1.py
└── state2
    ├── __init__.py
    ├── family1
    │   ├── __init__.py
    │   ├── task1.py
    │   └── task2.py
    └── family2
        ├── __init__.py
        ├── task1.py
        └── task2.py
</code>```

. at the root is the current working directory, named project

each of the taskn.py (task1.py, task2.py etc) are the individual tasks. Each task file looks something like this:

```<code>from celery import Celery
from celery.result import AsyncResult
from kombu import Queue

_name_ = "project_x"
celapp=Celery(backend='redis://localhost:6379/0', broker='amqp://a:b@localhost/a_vhost')
CELERY_CONFIG = {
    'CELERY_DEFAULT_QUEUE': 'default',
    'CELERY_QUEUES': (Queue('q1'), Queue('q2'),),
    'CELERY_TASK_SERIALIZER': 'pickle',
    'CELERY_ACCEPT_CONTENT': ['json','pickle']
}

celapp.conf.update(**CELERY_CONFIG)

@celapp.task()
def t1():
    print("starting task")
    time.sleep(5)
    print("Finished task")
</code>```

The below is the content of entry.py:

```<code>import json
from flask_cors import CORS
from flask import Flask, Response, render_template
from flask import request, jsonify, redirect
from functools import wraps
<what would be the import statement to import all the tasks>

_name_ = "project_x"
app     = Flask(_name_)

@app.route("/api1", methods=['POST'])
def api1():
    req = request.jsonify
    if not req:
        return jsonify(success=False, msg="Missing request parameters", code="1")
    else:
        param1 = req.get('p1')
        param2 = req.get('p2')
        tId = startTask()
        return jsonify(success="True", msg="All Good", taskId=tId)

def startTask():
    tId = "abcd123"
    created_task = state1.family1.task1.subtask(queue='q1')
    created_task.delay()
    return tId

if __name__ == '__main__':
    app.run(debug=True, host="192.168.1.7", port="4444")
</code>```

the entry.py is the flask app from where api1 would be triggered and then depending on the parameters I would want to start a specific task.

Now here are my questions:

what would be the import statement to import all the tasks in the entry.py file

where from do I start the worker. I mean from which directory should I start the Celery -A <directory name> worker -l info command and why ?

In many examples I saw that there is a clear segregation between tasks and CeleryApp file. Could someone please suggest what would be a better way to arrange my tasks, and celery configs etc. and how would the above 2 questions align with this new proposed structure ?

答:
So taking the advice from @Patricio, it seemed that it was indeed an import error. My new directory structure looks like the below:

```<code>.
├── __init__.py
├── celeryConfig
│   ├── __init__.py
│   └── celeryApp.py
├── entry.py
├── state1
│   ├── __init__.py
│   ├── family1
│   │   ├── __init__.py
│   │   ├── task1.py
│   │   ├── task2.py
│   │   └── task3.py
│   └── family2
│       ├── __init__.py
│       └── task1.py
└── state2
    ├── __init__.py
    ├── family1
    │   ├── __init__.py
    │   ├── task1.py
    │   └── task2.py
    └── family2
        ├── __init__.py
        ├── task1.py
        └── task2.py
</code>```

while contents of the celeryConfig/celeryApp.py are the below:

```<code>from celery import Celery
from celery.result import AsyncResult
from kombu import Queue

_name_ = "project_x"
celapp=Celery(backend='redis://localhost:6379/0', broker='amqp://a:b@localhost/a_vhost', include=['state1.family1.task1'])
CELERY_CONFIG = {
    'CELERY_DEFAULT_QUEUE': 'default',
    'CELERY_QUEUES': (Queue('q1'), Queue('q2'),),
    'CELERY_TASK_SERIALIZER': 'pickle',
    'CELERY_ACCEPT_CONTENT': ['json','pickle']
}

celapp.conf.update(**CELERY_CONFIG)
</code>```

and the contents of taskn.py is something like:

```<code>from celeryConfig.celeryApp import celapp
import time

@celapp.task()
def t1():
    print("starting task")
    time.sleep(5)
    print("Finished task")
</code>```

while entry.py remains as it is, with just one change as below:

from state1.family1.task1 import t1

And now when celery is started as :
celery -A celeryConfig.celeryApp worker -l info from the root directory, project, it all runs fine. As output of the above command I get the message as

```<code>.
.
.
[tasks]
  . state1.family1.task1.t1

.
.
.
</code>```

indicating that the celery has started correctly and that the task has indeed been registered. So now, in order to get all the tasks registered I can read through the directory/directories and create the include list in celeryApp.py dynamically. (Will post more about it once done)

Thanks @Patricio

Body:
I need some help regarding Celery workers. I'm especially not able to understand where (which directory) does the celery worker command needs to be fired from and what is the concept behind it and some things around imports.

So say I have the following directory structure :

.
├── __init__.py
├── entry.py
├── state1
│   ├── __init__.py
│   ├── family1
│   │   ├── __init__.py
│   │   ├── task1.py
│   │   ├── task2.py
│   │   └── task3.py
│   └── family2
│       ├── __init__.py
│       └── task1.py
└── state2
    ├── __init__.py
    ├── family1
    │   ├── __init__.py
    │   ├── task1.py
    │   └── task2.py
    └── family2
        ├── __init__.py
        ├── task1.py
        └── task2.py

. at the root is the current working directory, named project

each of the taskn.py (task1.py, task2.py etc) are the individual tasks. Each task file looks something like this:

from celery import Celery
from celery.result import AsyncResult
from kombu import Queue

_name_ = "project_x"
celapp=Celery(backend='redis://localhost:6379/0', broker='amqp://a:b@localhost/a_vhost')
CELERY_CONFIG = {
    'CELERY_DEFAULT_QUEUE': 'default',
    'CELERY_QUEUES': (Queue('q1'), Queue('q2'),),
    'CELERY_TASK_SERIALIZER': 'pickle',
    'CELERY_ACCEPT_CONTENT': ['json','pickle']
}

celapp.conf.update(**CELERY_CONFIG)

@celapp.task()
def t1():
    print("starting task")
    time.sleep(5)
    print("Finished task")

The below is the content of entry.py:

import json
from flask_cors import CORS
from flask import Flask, Response, render_template
from flask import request, jsonify, redirect
from functools import wraps
<what would be the import statement to import all the tasks>

_name_ = "project_x"
app     = Flask(_name_)

@app.route("/api1", methods=['POST'])
def api1():
    req = request.jsonify
    if not req:
        return jsonify(success=False, msg="Missing request parameters", code="1")
    else:
        param1 = req.get('p1')
        param2 = req.get('p2')
        tId = startTask()
        return jsonify(success="True", msg="All Good", taskId=tId)

def startTask():
    tId = "abcd123"
    created_task = state1.family1.task1.subtask(queue='q1')
    created_task.delay()
    return tId

if __name__ == '__main__':
    app.run(debug=True, host="192.168.1.7", port="4444")

the entry.py is the flask app from where api1 would be triggered and then depending on the parameters I would want to start a specific task.

Now here are my questions:

what would be the import statement to import all the tasks in the entry.py file

where from do I start the worker. I mean from which directory should I start the Celery -A <directory name> worker -l info command and why ?

In many examples I saw that there is a clear segregation between tasks and CeleryApp file. Could someone please suggest what would be a better way to arrange my tasks, and celery configs etc. and how would the above 2 questions align with this new proposed structure ?

Body:
So taking the advice from @Patricio, it seemed that it was indeed an import error. My new directory structure looks like the below:

.
├── __init__.py
├── celeryConfig
│   ├── __init__.py
│   └── celeryApp.py
├── entry.py
├── state1
│   ├── __init__.py
│   ├── family1
│   │   ├── __init__.py
│   │   ├── task1.py
│   │   ├── task2.py
│   │   └── task3.py
│   └── family2
│       ├── __init__.py
│       └── task1.py
└── state2
    ├── __init__.py
    ├── family1
    │   ├── __init__.py
    │   ├── task1.py
    │   └── task2.py
    └── family2
        ├── __init__.py
        ├── task1.py
        └── task2.py

while contents of the celeryConfig/celeryApp.py are the below:

from celery import Celery
from celery.result import AsyncResult
from kombu import Queue

_name_ = "project_x"
celapp=Celery(backend='redis://localhost:6379/0', broker='amqp://a:b@localhost/a_vhost', include=['state1.family1.task1'])
CELERY_CONFIG = {
    'CELERY_DEFAULT_QUEUE': 'default',
    'CELERY_QUEUES': (Queue('q1'), Queue('q2'),),
    'CELERY_TASK_SERIALIZER': 'pickle',
    'CELERY_ACCEPT_CONTENT': ['json','pickle']
}

celapp.conf.update(**CELERY_CONFIG)

and the contents of taskn.py is something like:

from celeryConfig.celeryApp import celapp
import time

@celapp.task()
def t1():
    print("starting task")
    time.sleep(5)
    print("Finished task")

while entry.py remains as it is, with just one change as below:

from state1.family1.task1 import t1

And now when celery is started as :
celery -A celeryConfig.celeryApp worker -l info from the root directory, project, it all runs fine. As output of the above command I get the message as

.
.
.
[tasks]
  . state1.family1.task1.t1

.
.
.

indicating that the celery has started correctly and that the task has indeed been registered. So now, in order to get all the tasks registered I can read through the directory/directories and create the include list in celeryApp.py dynamically. (Will post more about it once done)

Thanks @Patricio


答:
Try ,</p>

```<code>{{company.fax!=null ? company.fax : "" }}
</code>```

Title: Why null is being display on the screen in an Angular 5 app?

Body:
Try ,

{{company.fax!=null ? company.fax : "" }}


问:
How to fix the problem of opening an .exe file which flashes(closes instantly after the program's end)?
I've been coding for a while with codeblocks and I've coded some C programs. In my project folder of my programs there is the .exe file that I used to click on and get its console output. But today when I click on them and when the program ends it closes instantly without asking me to press a key to quit the program.

The solutions for this problem I've found are to add "system("pause")" and other stuff like that or to compile it directly on the cmd or on codeblocks(and they don't fix the problem as well). But I would like to know how I could be able to open the .exe files like back then.

答:
You can write

```<code>printf("Press ENTER key to Continue\n");
getchar();
</code>```

at the end of your code. The same question can be found here:
how to prevent c program from closing immediately after running

Body:
You can write

printf("Press ENTER key to Continue\n");
getchar();

at the end of your code. The same question can be found here:
how to prevent c program from closing immediately after running


问:
How to set menu time pop up time on exoplayer?
With the Android Exoplayer, when you tap on the screen it brings up the seekbar and some custom buttons I've coded overlayed on top of the video. Is there an attribute to set for how long that menu stays on the screen?</p>

答:
Please check the below declared tag in xml.

```<code><com.google.android.exoplayer2.ui.PlayerView
                android:id="@+id/mPlayerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:controller_layout_id="@layout/exo_playback_control_view"
                app:player_layout_id="@layout/exo_simple_player_view"
                app:repeat_toggle_modes="none"
                app:resize_mode="fixed_height"

                app:show_timeout="5000"

                app:surface_type="texture_view" />
</code>```

The attribute show_timeout when given in milliseconds as mentioned in above player will make the control disappear after 5 seconds. Check this.

Hope it helps. Happy coding!

Body:
Please check the below declared tag in xml.

<com.google.android.exoplayer2.ui.PlayerView
                android:id="@+id/mPlayerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:controller_layout_id="@layout/exo_playback_control_view"
                app:player_layout_id="@layout/exo_simple_player_view"
                app:repeat_toggle_modes="none"
                app:resize_mode="fixed_height"

                app:show_timeout="5000"

                app:surface_type="texture_view" />

The attribute show_timeout when given in milliseconds as mentioned in above player will make the control disappear after 5 seconds. Check this.

Hope it helps. Happy coding!


问:
How can I effectively troubleshoot off-by-one bug in C?
I've written a program to reverse a char array and also reverse words within that array. The program almost works as intended but I believe this is an off-by-one error. I've tried messing with the math involving the loop counters but have not been able to figure this one out. What tool or techniques can I use to solve this type of problem? I've tried printf statements and also using gdb and placing a watch on the counter variables.

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

void reverse_arr(char *arr, size_t len);
void print_chars(char *arr, size_t len);
void reverse_words(char *arr, size_t len);
int main(int argc, char **argv)
{
    char phrase[] = {'p','e','r','f','e','c','t',' ',
                    'm','a','k','e','s',' ','p','r',
                    'a','c','t','i','c','e'};

        size_t i;

    reverse_arr(phrase, sizeof(phrase));
    reverse_words(phrase,sizeof(phrase));
    print_chars(phrase, sizeof(phrase));

    return EXIT_SUCCESS;
}

void reverse_arr(char *arr, size_t len)
{
    size_t front, tail;
    tail = len-1;
    char tmp;
    for(front = 0; front < len/2; front++, tail--)
    {
        tmp = arr[front];
        arr[front] = arr[tail];
        arr[tail] = tmp;
    }

    return;
}

// 1. Search for a space
// 2. When space is found, that space is the place to stop and indicates all between the start and it are a word
// 3. Now call reverse_arr on the word and calculate the length of the word by subtracting tail - start
//
void reverse_words(char *arr, size_t len)
{
    size_t tail, start;
    for(tail = start = 0; tail < len; tail++)
    {
        if(arr[tail] == ' ' || tail == len-1)
        {
            reverse_arr(&arr[start], tail - start);
            start = tail+1;
        }
    }
}

void print_chars(char *arr, size_t len)
{
    size_t i;
    for(i = 0; i < len; i++)
    {
        putchar(arr[i]);
    }
    putchar('\n');

    return;
}
</code>```

This code returns practice makes erfectp. Clearly, this is an off-by-one bug but I've spent some time on this and suffered similar bugs in C in other programs.

答:
The bug is in reverse_words.  Sometimes tail indexes the character after the last character of the word, and sometimes tail indexes the last character of the word itself.

The call to reverse_array from reverse_words is:

```<code>reverse_arr(&arr[start], tail - start);
</code>```

This works if start indexes the first character of the word, and if there are tail - start characters in the word.  So tail must index the character after the last character of the word.

The condition arr[tail] == ' ' is consistent with this, but end condition is not:  (1) the loop exits too soon, and (2) the test tail == len-1 is also off by one.

This can be fixed by iterating one more time, and checking the end condition before trying to access arr[tail] (to avoid indexing past the end):

```<code>void reverse_words(char *arr, size_t len)
{
    size_t tail, start;
    for (tail = start = 0; tail <= len; tail++)
    {
        if (tail == len || arr[tail] == ' ')
        {
            reverse_arr(&arr[start], tail - start);
            start = tail+1;
        }
    }
}
</code>```

Note that the loop exit condition is now <= rather then <, the in-loop end test has shifted by one, and the order of the checks within the loop is reversed.

Body:
I've written a program to reverse a char array and also reverse words within that array. The program almost works as intended but I believe this is an off-by-one error. I've tried messing with the math involving the loop counters but have not been able to figure this one out. What tool or techniques can I use to solve this type of problem? I've tried printf statements and also using gdb and placing a watch on the counter variables.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse_arr(char *arr, size_t len);
void print_chars(char *arr, size_t len);
void reverse_words(char *arr, size_t len);
int main(int argc, char **argv)
{
    char phrase[] = {'p','e','r','f','e','c','t',' ',
                    'm','a','k','e','s',' ','p','r',
                    'a','c','t','i','c','e'};

        size_t i;

    reverse_arr(phrase, sizeof(phrase));
    reverse_words(phrase,sizeof(phrase));
    print_chars(phrase, sizeof(phrase));

    return EXIT_SUCCESS;
}

void reverse_arr(char *arr, size_t len)
{
    size_t front, tail;
    tail = len-1;
    char tmp;
    for(front = 0; front < len/2; front++, tail--)
    {
        tmp = arr[front];
        arr[front] = arr[tail];
        arr[tail] = tmp;
    }

    return;
}

// 1. Search for a space
// 2. When space is found, that space is the place to stop and indicates all between the start and it are a word
// 3. Now call reverse_arr on the word and calculate the length of the word by subtracting tail - start
//
void reverse_words(char *arr, size_t len)
{
    size_t tail, start;
    for(tail = start = 0; tail < len; tail++)
    {
        if(arr[tail] == ' ' || tail == len-1)
        {
            reverse_arr(&arr[start], tail - start);
            start = tail+1;
        }
    }
}

void print_chars(char *arr, size_t len)
{
    size_t i;
    for(i = 0; i < len; i++)
    {
        putchar(arr[i]);
    }
    putchar('\n');

    return;
}

This code returns practice makes erfectp. Clearly, this is an off-by-one bug but I've spent some time on this and suffered similar bugs in C in other programs.

Body:
The bug is in reverse_words.  Sometimes tail indexes the character after the last character of the word, and sometimes tail indexes the last character of the word itself.

The call to reverse_array from reverse_words is:

reverse_arr(&arr[start], tail - start);

This works if start indexes the first character of the word, and if there are tail - start characters in the word.  So tail must index the character after the last character of the word.

The condition arr[tail] == ' ' is consistent with this, but end condition is not:  (1) the loop exits too soon, and (2) the test tail == len-1 is also off by one.

This can be fixed by iterating one more time, and checking the end condition before trying to access arr[tail] (to avoid indexing past the end):

void reverse_words(char *arr, size_t len)
{
    size_t tail, start;
    for (tail = start = 0; tail <= len; tail++)
    {
        if (tail == len || arr[tail] == ' ')
        {
            reverse_arr(&arr[start], tail - start);
            start = tail+1;
        }
    }
}

Note that the loop exit condition is now <= rather then <, the in-loop end test has shifted by one, and the order of the checks within the loop is reversed.


问:
what kind of replication should I use?
I can't understand the difference between transactional replication and merge replication.
This is my scenario:
In an organization I have a SQL server which need to collect information from different sql servers which are located in different parts of organization or around the city and some report will create according to gathered information.
Data in different SQL servers update every 5 or 6 minutes.
I don't know should I use transactional or merge replication?</p>

答:
Merge. Each site is a master of it's own data.

Transactional is one way usually.

You need to share information so merge it is...

Edit, after comment

In which case, yes. Your question implies reporting at each location

However, for performance, I'd consider pushing all updates into a queue using a trigger and Service broker. This way, the write to the remote server is decoupled from the local transaction.

Title: what kind of replication should I use?


问:
How to dynamically set an image or use default
I am mapping through objects and would like to dynamically add the image source, but if there is not an image, id like to load the default image. Ideally this take as little computational power as can be because there are lots of images that will change often..

I already have the dynamic image src setup, but i dont have the loop to check if it exists. Just wondering what the fastest way to do this is.

```<code>...
render() {
    const images = require.context("../../../../../public/images", true);
...

return {
{this.props.items.map...

<img src={images(`./${item.item}`)} />

....)}
</code>```

答:
Thanks to Ray Hatfield, the following solves the problem.

```<code>
function getImage(item) {
    try {
        return images(`./${item}.svg`);
    }
    catch (e) {
        return images('./default.png');
    }
}
</code>```

and then:

```<code><img src={getImage(item.item)} />
</code>```

Body:
I am mapping through objects and would like to dynamically add the image source, but if there is not an image, id like to load the default image. Ideally this take as little computational power as can be because there are lots of images that will change often..

I already have the dynamic image src setup, but i dont have the loop to check if it exists. Just wondering what the fastest way to do this is.

...
render() {
    const images = require.context("../../../../../public/images", true);
...

return {
{this.props.items.map...

<img src={images(`./${item.item}`)} />

....)}

Body:
Thanks to Ray Hatfield, the following solves the problem.

function getImage(item) {
    try {
        return images(`./${item}.svg`);
    }
    catch (e) {
        return images('./default.png');
    }
}

and then:

<img src={getImage(item.item)} />


问:
How do you get a switch statement in android to recognize a checkbox?
I would like to clean up my code and have my checkbox do some actions from the switch statement inside onOptionsItemSelected(). Instead, I have an onClick listener in onCreateOptionsMenu for my custom checkbox. This works, but I would like to understand how to have code inside case R.id.star_favorite: called.</p>

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    checkBox = (CheckBox) menu.findItem(R.id.star_favorite).getActionView();
    checkBox.setButtonDrawable(R.drawable.favorite_checkbox);
    if(currentQuote != null) {
        currentQuoteIsFavorite = currentQuote.getFavorite();
        checkBox.setChecked(currentQuoteIsFavorite);
    }
    checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(currentQuote != null) {
                currentQuoteIsFavorite = !currentQuoteIsFavorite;
                updateFavorite(currentQuoteIsFavorite);
            } else {
                checkBox.setChecked(false);
                Toast.makeText(getApplicationContext(), "No Quote To Save", Toast.LENGTH_SHORT).show();
            }
        }
    });
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.star_favorite:
            //already tried putting code like updateFavorite() inside here but it's not called
            Toast.makeText(this, "Checkbox clicked", Toast.LENGTH_SHORT).show();
            if(currentQuote != null) {
                currentQuoteIsFavorite = !currentQuoteIsFavorite;
                updateFavorite(currentQuoteIsFavorite);
            } else {
                checkBox.setChecked(false);
                Toast.makeText(getApplicationContext(), "No Quote To Save", Toast.LENGTH_SHORT).show();
            }
        case R.id.share_quote:
            Log.d("onOptionsItemSelected", "case R.id.share_quote selected");
            shareQuote();
            break;
        case R.id.menu:
            Log.d("onOptionsItemSelected", "case R.id.menu selected");

            break;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

答:
In this case, you don't need a Checkbox at all. You can use the android:checkable attribute to make a menu item checkable. You then update the icon in onOptionsItemSelected().

QuoteActivity.java

```<code>public class QuoteActivity extends AppCompatActivity {

    // saved state, randomized for testing
    private Random rand = new Random();
    private boolean savedAsFavorite = rand.nextBoolean();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quote_activity);
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.quote_menu, menu);
        toggleItem(menu.findItem(R.id.favorite), savedAsFavorite);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.favorite:
                toggleItem(item, !item.isChecked());
                return true;
            case R.id.share:
                // do something
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void toggleItem(MenuItem item, boolean isChecked) {
        item.setChecked(isChecked);
        item.setIcon(iconDrawable(isChecked));
    }

    private Drawable iconDrawable(boolean isChecked) {
        return getDrawable(isChecked ? R.drawable.favorite_enabled : R.drawable.favorite_disabled);
    }
}
</code>```

quote_menu.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/favorite"
        android:icon="@drawable/favorite_disabled"
        android:title="Favorite"
        app:showAsAction="ifRoom"
        android:checkable="true"
        android:checked="false"/>

    <!-- additional menu items -->

</menu>
</code>```

And of course, you need two drawables for the enabled and disabled state of the favorite icon. Hope that helps!

Body:
I would like to clean up my code and have my checkbox do some actions from the switch statement inside onOptionsItemSelected(). Instead, I have an onClick listener in onCreateOptionsMenu for my custom checkbox. This works, but I would like to understand how to have code inside case R.id.star_favorite: called.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    checkBox = (CheckBox) menu.findItem(R.id.star_favorite).getActionView();
    checkBox.setButtonDrawable(R.drawable.favorite_checkbox);
    if(currentQuote != null) {
        currentQuoteIsFavorite = currentQuote.getFavorite();
        checkBox.setChecked(currentQuoteIsFavorite);
    }
    checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(currentQuote != null) {
                currentQuoteIsFavorite = !currentQuoteIsFavorite;
                updateFavorite(currentQuoteIsFavorite);
            } else {
                checkBox.setChecked(false);
                Toast.makeText(getApplicationContext(), "No Quote To Save", Toast.LENGTH_SHORT).show();
            }
        }
    });
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.star_favorite:
            //already tried putting code like updateFavorite() inside here but it's not called
            Toast.makeText(this, "Checkbox clicked", Toast.LENGTH_SHORT).show();
            if(currentQuote != null) {
                currentQuoteIsFavorite = !currentQuoteIsFavorite;
                updateFavorite(currentQuoteIsFavorite);
            } else {
                checkBox.setChecked(false);
                Toast.makeText(getApplicationContext(), "No Quote To Save", Toast.LENGTH_SHORT).show();
            }
        case R.id.share_quote:
            Log.d("onOptionsItemSelected", "case R.id.share_quote selected");
            shareQuote();
            break;
        case R.id.menu:
            Log.d("onOptionsItemSelected", "case R.id.menu selected");

            break;
    }
    return super.onOptionsItemSelected(item);
}

Body:
In this case, you don't need a Checkbox at all. You can use the android:checkable attribute to make a menu item checkable. You then update the icon in onOptionsItemSelected().

QuoteActivity.java

public class QuoteActivity extends AppCompatActivity {

    // saved state, randomized for testing
    private Random rand = new Random();
    private boolean savedAsFavorite = rand.nextBoolean();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quote_activity);
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.quote_menu, menu);
        toggleItem(menu.findItem(R.id.favorite), savedAsFavorite);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.favorite:
                toggleItem(item, !item.isChecked());
                return true;
            case R.id.share:
                // do something
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void toggleItem(MenuItem item, boolean isChecked) {
        item.setChecked(isChecked);
        item.setIcon(iconDrawable(isChecked));
    }

    private Drawable iconDrawable(boolean isChecked) {
        return getDrawable(isChecked ? R.drawable.favorite_enabled : R.drawable.favorite_disabled);
    }
}

quote_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/favorite"
        android:icon="@drawable/favorite_disabled"
        android:title="Favorite"
        app:showAsAction="ifRoom"
        android:checkable="true"
        android:checked="false"/>

    <!-- additional menu items -->

</menu>

And of course, you need two drawables for the enabled and disabled state of the favorite icon. Hope that helps!


答:
you need to use setItem() for set data and getItem() for get data.
Set data:

```<code>await AsyncStorage.setItem('key', 'data');
</code>```

Fetch data:

```<code>await AsyncStorage.getItem('key');
</code>```

Asyncstorage in react native : https://facebook.github.io/react-native/docs/asyncstorage#docsNav

Body:
I am new at React Native. There is a native application written in Objective-C for iOS and Java for Android. My task is to add two more screens using React Native. The general solution is here.

The native code already uses a local storage to store permanent data (for example, data about an authorized user). At the same time, React Native uses Async Storage to handle permanent data.

Can I get values from the local storage using Async Storage from React Native?

Body:
you need to use setItem() for set data and getItem() for get data.
Set data:

await AsyncStorage.setItem('key', 'data');

Fetch data:

await AsyncStorage.getItem('key');

Asyncstorage in react native : https://facebook.github.io/react-native/docs/asyncstorage#docsNav


问:
Writing a django view that does not return an object
I am writing a django view that just post some data and update a variable in the database. The view will not return anything as I am submitting the data using jquery-ajax.

I am getting the following error:

```<code>The view mysite.views.home didn't return an HttpResponse object
</code>```

Again I do not wish to return an html page or anything of that sort. How can I achieve that?

答: A view in Django must return a HttpResponse, even if it's empty.

Body:
I am writing a django view that just post some data and update a variable in the database. The view will not return anything as I am submitting the data using jquery-ajax.

I am getting the following error:

The view mysite.views.home didn't return an HttpResponse object

Again I do not wish to return an html page or anything of that sort. How can I achieve that?


问:
How can I fix 'android.os.NetworkOnMainThreadException'?
I got an error while running my Android project for RssReader.

Code:

```<code>URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
</code>```

And it shows the below error:

```<code>android.os.NetworkOnMainThreadException
</code>```

How can I fix this issue?

答:
Kotlin version

```<code>internal class RetrieveFeedTask : AsyncTask<String, Void, RSSFeed>() {

    override fun doInBackground(vararg urls: String): RSSFeed? {

        try {
             // download
             // prepare RSSFeeds
             return RSSFeeds

         } catch (e: Exception) {

            //handle exception
            return null
        }
    }

    override fun onPostExecute(feed: RSSFeed) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}
</code>```

Call example,

```<code>RetrieveFeedTask().execute(url)
</code>```

Body:
I got an error while running my Android project for RssReader.

Code:

URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();

And it shows the below error:

android.os.NetworkOnMainThreadException

How can I fix this issue?

Body:
Kotlin version

internal class RetrieveFeedTask : AsyncTask<String, Void, RSSFeed>() {

    override fun doInBackground(vararg urls: String): RSSFeed? {

        try {
             // download
             // prepare RSSFeeds
             return RSSFeeds

         } catch (e: Exception) {

            //handle exception
            return null
        }
    }

    override fun onPostExecute(feed: RSSFeed) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

Call example,

RetrieveFeedTask().execute(url)


问:
Why does pdf of arange function have normal distribution?
arange works on stepwise incrementing values and is not random function then why does it give a random distribution?

```<code>from scipy.stats import norm
import matplotlib.pyplot as plt

x = np.arange(-3, 3, 0.001)
plt.plot(x, norm.pdf(x))
</code>```

I expect a uniform distribution

答:
The library scipy.stats.norm provides functionality of Normal Distribution, not Uniform distribution. Meaning when you apply the probability density function (pdf), you are not applying a constant function, but something else entirely (also knowns as the Bell curve):

https://en.wikipedia.org/wiki/Normal_distribution

So in the end what you are seeing are points between (-3, 3) visualised on the probability density function of Normal distribution. If you want to see Uniform distribution:

```<code>from scipy.stats import uniform
import matplotlib.pyplot as plt

x = np.arange(-3, 3, 0.001)
plt.plot(x, uniform.pdf(x))
</code>```

But that is just a very fancy way to draw a constant line.

Body:
arange works on stepwise incrementing values and is not random function then why does it give a random distribution?

from scipy.stats import norm
import matplotlib.pyplot as plt

x = np.arange(-3, 3, 0.001)
plt.plot(x, norm.pdf(x))

I expect a uniform distribution

Body:
The library scipy.stats.norm provides functionality of Normal Distribution, not Uniform distribution. Meaning when you apply the probability density function (pdf), you are not applying a constant function, but something else entirely (also knowns as the Bell curve):

https://en.wikipedia.org/wiki/Normal_distribution

So in the end what you are seeing are points between (-3, 3) visualised on the probability density function of Normal distribution. If you want to see Uniform distribution:

from scipy.stats import uniform
import matplotlib.pyplot as plt

x = np.arange(-3, 3, 0.001)
plt.plot(x, uniform.pdf(x))

But that is just a very fancy way to draw a constant line.


问:
What's the best way to add a full screen background image in React Native
I wanted to add a full-screen image to the View so I write this code

```<code>return (
    <View style={styles.container}>
        <Image source={require('image!egg')}  style={styles.backgroundImage}/>
    </View>
)
</code>```

and defined the style as

```<code>var styles = StyleSheet.create({
container: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center',
     backgroundColor: '#F5FCFF',
     flexDirection: 'column',
},
     backgroundImage:{
     width:320,
     height:480,
   }
...
</code>```

but in this way how am I supposed to find the actual iPhone screen size?

I've seen an API to access the Pixel Density but nothing about the screen size...

Any idea?

答:
```<code>import { ImageBackground } from "react-native";
<ImageBackground
     style={{width: '100%', height: '100%'}}
     source={require('../assets/backgroundLogin.jpg ')}> //path here inside
    <Text>React</Text>
</ImageBackground>
</code>```

Body:
I wanted to add a full-screen image to the View so I write this code

return (
    <View style={styles.container}>
        <Image source={require('image!egg')}  style={styles.backgroundImage}/>
    </View>
)

and defined the style as

var styles = StyleSheet.create({
container: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center',
     backgroundColor: '#F5FCFF',
     flexDirection: 'column',
},
     backgroundImage:{
     width:320,
     height:480,
   }
...

but in this way how am I supposed to find the actual iPhone screen size?

I've seen an API to access the Pixel Density but nothing about the screen size...

Any idea?


问:
How to get information from database to React site
I'm build a website using ReactJs and Node. In administrator's panel I want to build table with users' names and mails. But... I don't know how to get users' information from database.

I use local database localhost:8080/user/.

In table I have information - name and email of currently logged in administrator.

//my table

```<code><table border = "4" cellpadding = "10">
   <tr><td>UserName</td><td>E-mail</td></tr>
   <tr><td>{isAuthenticated().user.name}</td><td>{isAuthenticated().user.email}</td></tr>
</table>
</code>```

I want to build table on site with users' information, who registered on my  website, no only information with currently logged on administrator.

答:
You can use fetch API to get those data from the server, and call the method fetchData() via life cycle hook componentWillMount() to send request to the server before the page is mounted, you can then iterate each of the elements in the data using map() method in the table element.

```<code>export default class myApp extends React.Component  {

   constructor(props) {
     super(props);

      this.state = {
         data: []
      };
    }

    componentWillMount() {
       this.fetchData();
    }

    fetchData(){
      fetch('https://localhost:8080/user/')
       .then((response) => response.json())
         .then((responseToJson) => {
            this.setState({ data: responseToJson })
          })
          .catch((error) => {
            console.error(error);
          });
     }

     render(){
       const { data } = this.state.data
       return(
         <div>
          {data.map((item, index) => {
           return(
            <div key={index}>
              <table border="4" cellpadding="10">
                 <tr><td>UserName</td><td>E-mail</td></tr>
                 <tr><td>{data.name}</td><td>{data.email}</td></tr>
              </table>
            </div>
            )
           })}
          </div>
        );
      }
   }
</code>```

Body:
I'm build a website using ReactJs and Node. In administrator's panel I want to build table with users' names and mails. But... I don't know how to get users' information from database.

I use local database localhost:8080/user/.

In table I have information - name and email of currently logged in administrator.

//my table

UserName	E-mail

{isAuthenticated().user.name}	{isAuthenticated().user.email}

I want to build table on site with users' information, who registered on my  website, no only information with currently logged on administrator.

Body:
You can use fetch API to get those data from the server, and call the method fetchData() via life cycle hook componentWillMount() to send request to the server before the page is mounted, you can then iterate each of the elements in the data using map() method in the table element.

export default class myApp extends React.Component  {

   constructor(props) {
     super(props);

      this.state = {
         data: []
      };
    }

    componentWillMount() {
       this.fetchData();
    }

    fetchData(){
      fetch('https://localhost:8080/user/')
       .then((response) => response.json())
         .then((responseToJson) => {
            this.setState({ data: responseToJson })
          })
          .catch((error) => {
            console.error(error);
          });
     }

     render(){
       const { data } = this.state.data
       return(
         <div>
          {data.map((item, index) => {
           return(
            <div key={index}>
              <table border="4" cellpadding="10">
                 <tr><td>UserName</td><td>E-mail</td></tr>
                 <tr><td>{data.name}</td><td>{data.email}</td></tr>
              </table>
            </div>
            )
           })}
          </div>
        );
      }
   }


问:
ASP.NET Login Control is redirecting to default.aspx even when the destinationpageurl is not set
We have a login control on a page named login.aspx which is set as the start page of the website. Once the user logs in, it is redirecting to default.aspx although our destinationpageurl is not set to any value.

If we set the destinationpageurl to somepage.aspx, it is working redirecting properly, but why is it redirecting to default.aspx by default, if the destinationpageurl is not set.

Thanks for any help,
Animesh

答: Is it just redirecting to / and it's actually IIS which is serving default.aspx, based on the default document settings?</p>

OwnerDisplayName: Animesh

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bryan Parker


问:
Best practice to avoid N+1 when listing objects retrieved by a method in an associated object
I'm trying to figure the best way to fix a N+1 problem in my rails app.

Let's say I have a model Student, which has a many association of terms.

```<code>student = Student.find_by_name('John')
student.terms
# [{term: 1}, {term: 2}, {term: 3}]
</code>```

So, I need to be able to show the list of student terms but also need to show the previous term in the same view. Currently, for this I have a method that gets the previous term by the attribute start_at which is a DateTime value equivalent to the first  day of the term.

```<code># Term.rb
def previous_term
  Term.where("start_at < ?", start_at).order(start_at: :desc).first&.start_at
end
</code>```

But using this method in the terms list makes a query for each term for each Student

```<code>- @terms.each do |term|
  %td= term.start_at # list current term start_at
  %td= term.previous_term # show previous term start_at - N+1 is here
</code>```

I've thought about loading all student terms in the controller and creating a class method in model Term, this method would detect the previous Term from a ordered collection of Terms.

```<code># Term.rb
def self.get_previous(term_collection, term_id)
  term_collection.detect do |term|
    # logic to filter and get the previous term
  end
end
</code>```

This way it would be filtering the objects in memory instead of making database connections, buuuuut I know there is a better and smarter way to do it (maybe best practice?).

答:
Change the definition of previous_term to

```<code>def previous_term
  where("start_at < ?", start_at).order(start_at: :desc).first&.start_at
end
</code>```

So you'd be able to call

```<code>student.terms.previous_term
</code>```

Alternative with in Ruby, since you already have the collection of terms = student.terms, use Enumerable#max_by (or min_by). Something like:

```<code>previous_term = terms.max_by { |term| term.start_at } # or terms.max_by(&:start_at)
</code>```

Body:
I'm trying to figure the best way to fix a N+1 problem in my rails app.

Let's say I have a model Student, which has a many association of terms.

student = Student.find_by_name('John')
student.terms
# [{term: 1}, {term: 2}, {term: 3}]

So, I need to be able to show the list of student terms but also need to show the previous term in the same view. Currently, for this I have a method that gets the previous term by the attribute start_at which is a DateTime value equivalent to the first  day of the term.

# Term.rb
def previous_term
  Term.where("start_at < ?", start_at).order(start_at: :desc).first&.start_at
end

But using this method in the terms list makes a query for each term for each Student

- @terms.each do |term|
  %td= term.start_at # list current term start_at
  %td= term.previous_term # show previous term start_at - N+1 is here

I've thought about loading all student terms in the controller and creating a class method in model Term, this method would detect the previous Term from a ordered collection of Terms.

# Term.rb
def self.get_previous(term_collection, term_id)
  term_collection.detect do |term|
    # logic to filter and get the previous term
  end
end

This way it would be filtering the objects in memory instead of making database connections, buuuuut I know there is a better and smarter way to do it (maybe best practice?).

Body:
Change the definition of previous_term to

def previous_term
  where("start_at < ?", start_at).order(start_at: :desc).first&.start_at
end

So you'd be able to call

student.terms.previous_term

Alternative with in Ruby, since you already have the collection of terms = student.terms, use Enumerable#max_by (or min_by). Something like:

previous_term = terms.max_by { |term| term.start_at } # or terms.max_by(&:start_at)