问:
BigQuery Storage Write / managedwriter api return error server_shutting_down
As we know, the advantage of BigQuery Storage Write API, one month ago, we replace insertAll with managedwriter API on our server. It seems to work well for one month, however, we met the following errors recently

```<code>rpc error: code = Unavailable desc = closing transport due to: connection error:
desc = "error reading from server: EOF", received prior goaway: code: NO_ERROR,
debug data: "server_shutting_down"
</code>```

The version of managedwriter API are:

```<code>cloud.google.com/go/bigquery v1.25.0
google.golang.org/protobuf v1.27.1
</code>```

There is a piece of retrying logic for storage write API that detects error messages on our server-side. We notice the response time of storage write API becomes longer after retrying, as a result, OOM is happening on our server. We also tried to increase the request timeout to 30 seconds, and most of those requests could not be completed within it.

How to handle the error server_shutting_down correctly?

Update 02/08/2022

The default stream of managedwrite API is used in our server. And server_shutting_down error comes up periodically. And this issue happened on 02/04/2022 12:00 PM UTC and the default stream of managedwrite API works well for over one month.

Here is one wrapper function of appendRow and we log the cost time of this function.

func (cl *GBOutput) appendRows(ctx context.Context,datas [][]byte, schema *gbSchema) error {
    var result *managedwriter.AppendResult
    var err error
    if cl.schema != schema {
        cl.schema = schema
        result, err = cl.managedStream.AppendRows(ctx, datas, managedwriter.UpdateSchemaDescriptor(schema.descriptorProto))
    } else {
        result, err = cl.managedStream.AppendRows(ctx, datas)
    }
    if err != nil {
        return err
    }
    _, err = result.GetResult(ctx)
    return err
}
```

When the error server_shutting_down comes up, the cost time of this function could be several hundred seconds. It is so weird, and it seems to there is no way to handle the timeout of appendRow.

答:
Are you using the "raw" v1 storage API, or the managedwriter?  I ask because managedwriter should handle stream reconnection automatically.  Are you simply observing connection closes periodically, or something about your retry traffic induces the closes?

The interesting question is how to deal with in-flight appends for which you haven't yet received an acknowledgement back (or the ack ended in failure).  If you're using offsets, you should be able to re-send the append without risk of duplication.

Body:
As we know, the advantage of BigQuery Storage Write API, one month ago, we replace insertAll with managedwriter API on our server. It seems to work well for one month, however, we met the following errors recently

rpc error: code = Unavailable desc = closing transport due to: connection error:
desc = "error reading from server: EOF", received prior goaway: code: NO_ERROR,
debug data: "server_shutting_down"

The version of managedwriter API are:

cloud.google.com/go/bigquery v1.25.0
google.golang.org/protobuf v1.27.1

There is a piece of retrying logic for storage write API that detects error messages on our server-side. We notice the response time of storage write API becomes longer after retrying, as a result, OOM is happening on our server. We also tried to increase the request timeout to 30 seconds, and most of those requests could not be completed within it.

How to handle the error server_shutting_down correctly?

Update 02/08/2022

The default stream of managedwrite API is used in our server. And server_shutting_down error comes up periodically. And this issue happened on 02/04/2022 12:00 PM UTC and the default stream of managedwrite API works well for over one month.

Here is one wrapper function of appendRow and we log the cost time of this function.

func (cl *GBOutput) appendRows(ctx context.Context,datas [][]byte, schema *gbSchema) error {
    var result *managedwriter.AppendResult
    var err error
    if cl.schema != schema {
        cl.schema = schema
        result, err = cl.managedStream.AppendRows(ctx, datas, managedwriter.UpdateSchemaDescriptor(schema.descriptorProto))
    } else {
        result, err = cl.managedStream.AppendRows(ctx, datas)
    }
    if err != nil {
        return err
    }
    _, err = result.GetResult(ctx)
    return err
}

When the error server_shutting_down comes up, the cost time of this function could be several hundred seconds. It is so weird, and it seems to there is no way to handle the timeout of appendRow.


来源: stackexchange

问:
Manually calculate the boxplot whiskers in altair
I'm looking for a way to find the values of the boxplot whiskers, manually, within altair itself (so without adding an extra column in the dataframe).

Below is a plot I'm trying to create. The orange area should align with the boxplot whiskers, so the first value of 'x' inside the 1.5*iqr range.

I have been playing around with vega expressions (inrange, clampRange ...) but could not find a way to do so.

Open the Chart in the Vega Editor

```<code>import altair as alt
import pandas as pd

values =  [0, 3, 4.4, 4.5, 4.6, 5, 7]
df = pd.DataFrame({'x': values})

points = alt.Chart(df).mark_circle(color='black', size=120).encode(
    x=alt.X('x:Q', scale=alt.Scale(zero=False)),
)

boxplot = alt.Chart(df).mark_boxplot(ticks=True, extent=1.5, outliers=True).encode(
    x='x:Q',
)

iqr = alt.Chart(df).mark_rect(color='lime').encode(
    x='q1(x):Q',
    x2='q3(x):Q'
)

whiskers = alt.Chart(df).mark_rect(color='orange').transform_aggregate(
    q1='q1(x)',
    q3='q3(x)',
).transform_calculate(
    iqr=alt.datum.q3 - alt.datum.q1,
    q0=alt.datum.q1 - (alt.datum.iqr * 1.5),
    q100=alt.datum.q3 + (alt.datum.iqr * 1.5),
).encode(
    x='q0:Q',
    x2='q100:Q',
)

minmax = alt.Chart(df).mark_rect(color='red').transform_aggregate(
    xmin='min(x)',
    xmax='max(x)'
).encode(
    x='xmin:Q',
    x2='xmax:Q',
).properties(width=1000)

((boxplot + points) & (minmax + whiskers + iqr + points)).resolve_scale(x='shared')
</code>```

答:
The key here is to be able to use the aggregate values of the quartiles to filter the original data. When you use transform_aggregate you are reducing the dataframe to only include the aggregate values you are creating. If you instead use transform_joinaggregate you are joining the aggregate values to the original dataframe, which means that you can then use transform_filter to return the max and min original data points within the bounds of the q1/q3 -/+ 1.5 * IQR:

```<code>whiskers = alt.Chart(df).mark_rect(color='orange').transform_joinaggregate(
    q1='q1(x)',
    q3='q3(x)',
).transform_calculate(
    iqr='datum.q3 - datum.q1'
).transform_filter(
    # VL concatenates these strings so we can split
    # them on two lines to improve readability
    'datum.x < (datum.q3 + datum.iqr * 1.5)'
    '&& datum.x > (datum.q1 - datum.iqr * 1.5)'
).encode(
    x='min(x)',
    x2='max(x)',
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for a way to find the values of the boxplot whiskers, manually, within altair itself (so without adding an extra column in the dataframe).

Below is a plot I'm trying to create. The orange area should align with the boxplot whiskers, so the first value of 'x' inside the 1.5*iqr range.

I have been playing around with vega expressions (inrange, clampRange ...) but could not find a way to do so.

<a href="https://vega.github.io/editor/#/url/vega-lite/N4Igxg9gdgZglgcxALlANzgUwO4tJKAFzigFcJSBnAdTgBNCALFAFgAY2AacaYsiygAlMiRoRQBmDgF9p3NATABDccgDaoADZKAnpgBOKDSAC2S-QGs8IQjoAOmFCABGEAB53NEcd0xvCmEQoAIwAdACs3BSEmlj6lCiE+qSY3MRgFgnISSlyIIGQdCRIqCBu1vCYmnRO5Wn2jsggAI6kSkRwhCpwaI6ycqBmlta2Dk5gcPpgmo7ckF6GTc7aGSDclHAAXo3BAExseQUQRVAloOWlldW1ayCUyjPW2-oQKDBKmpSYeaONLW0dLrEXogfoAXQGIG0ekWxiGVlKvyc+kwYB8PAWyMwNUOUEKxWsF1AVxqTTcJhItyRTVa7WIQJ6fW4bl2FSw1zJZnKsjS+nalBgEH0JiMoCUCAQKIQKkaxggdicFKgtxJN24SiyZSVoM4oHliqUdRAqrJtw1tS5oIhYO42HoTBCHAOutM5gRoGpIBRaNu8yFTiF7QQTPyeOOBNKRON7NJLTYVIaTlpgO6ILyLLZVVjzWCHFBPz5UAFQpF6jFEqlMtFIH1NOCKpjapA5rrOr1CppEgbWabLZaXekEJdDzApG0AScAAo6CpSCZQs0JAACAC0S5nhDnC+CAEozZq4M1DJCR2Oq01p7P5znV0vL5v54f9EuAFRLsLhHd79Wa5rxk8fKO45-PeW6LkuADUd4bluT6vu+ERfvuSa5v+Q6DG6IyJk03ron6ixQnAJghkcJxnGU1jipKmDShOrbcCaFH1GMNIAvSqYhhmpRUZWdH9t2HIUf0LrwlhLHgJM0yzBi-pLCsVjrFsOz7Li+KnISmaCUa9wfI0oDPK8yDvJ83zMX8ybscCfSyNa3Abko1hQEoxFOPZK7OEo7zBAA7LsMCYAAbAF7DecoYAAJwABwsOFdABc44QwCwMUSGAIYopQECaCCpQ6Y8kZOJQjDmNi+bcAAJPcjCYGYThiIQdiUMgAD0zW9NKoQIJ0jCkM4oRwBAzVVTVShtTRSgrrEARtSwoQ+aEbChAAVplyp2SoGqYIQWSgG5Hleb5-lBSFYVRTFcUJUlKVpdWFzOuckiQhcs0sE9rARG9yCzQFn3hJ93mDrIQA" rel="nofollow noreferrer">Open the Chart in the Vega Editor

import altair as alt
import pandas as pd

values =  [0, 3, 4.4, 4.5, 4.6, 5, 7]
df = pd.DataFrame({'x': values})

points = alt.Chart(df).mark_circle(color='black', size=120).encode(
    x=alt.X('x:Q', scale=alt.Scale(zero=False)),
)

boxplot = alt.Chart(df).mark_boxplot(ticks=True, extent=1.5, outliers=True).encode(
    x='x:Q',
)

iqr = alt.Chart(df).mark_rect(color='lime').encode(
    x='q1(x):Q',
    x2='q3(x):Q'
)

whiskers = alt.Chart(df).mark_rect(color='orange').transform_aggregate(
    q1='q1(x)',
    q3='q3(x)',
).transform_calculate(
    iqr=alt.datum.q3 - alt.datum.q1,
    q0=alt.datum.q1 - (alt.datum.iqr * 1.5),
    q100=alt.datum.q3 + (alt.datum.iqr * 1.5),
).encode(
    x='q0:Q',
    x2='q100:Q',
)

minmax = alt.Chart(df).mark_rect(color='red').transform_aggregate(
    xmin='min(x)',
    xmax='max(x)'
).encode(
    x='xmin:Q',
    x2='xmax:Q',
).properties(width=1000)

((boxplot + points) & (minmax + whiskers + iqr + points)).resolve_scale(x='shared')

Body:
The key here is to be able to use the aggregate values of the quartiles to filter the original data. When you use transform_aggregate you are reducing the dataframe to only include the aggregate values you are creating. If you instead use transform_joinaggregate you are joining the aggregate values to the original dataframe, which means that you can then use transform_filter to return the max and min original data points within the bounds of the q1/q3 -/+ 1.5 * IQR:

whiskers = alt.Chart(df).mark_rect(color='orange').transform_joinaggregate(
    q1='q1(x)',
    q3='q3(x)',
).transform_calculate(
    iqr='datum.q3 - datum.q1'
).transform_filter(
    # VL concatenates these strings so we can split
    # them on two lines to improve readability
    'datum.x < (datum.q3 + datum.iqr * 1.5)'
    '&& datum.x > (datum.q1 - datum.iqr * 1.5)'
).encode(
    x='min(x)',
    x2='max(x)',
)


问:
Choosing DB model for an app similar to Notion, Block-based ("paragraphs") or document-based?

1. The problem

Lately, it seems that many note managers with "infinite" tree structure are choosing a block model (where each paragraph is an entry in the DB), instead of a document or file model.

Blocks
Documents

Notion
 Workflowy
 Remnote
 Dynalist
 Roam Research
Evernote
 Obsidian
 Bear app

If you find any errors in the table, please let me know.

We have been developing an app very similar to Notion for 8 months now, also using the block model, but we are considering making a radical change and switching to the document model. The structure of our blocks in MongoDB currently looks like this:

```<code>_id: "61fd3ede7f6d2cc7a53ca669"
children: Array
    0: "61fd3ee87f6d2cc7a53ca66b"
    1: "61fd3ef37f6d2cc7a53ca671"
    2: "61fd3ef77f6d2cc7a53ca673"
backlinks: Array
type: "bullet"
parentPage: Array
    _id: "61fd3ede7f6e2ccra53ca664"
    userParent: "german-jablo"
    permisionParent: "edit, comment, read"
parentParagraph: "61fd3ede7f6d2cc7a53ca668"
content: "<p>This is a paragraph</p>"
isCollapsed: false
createdAt: 2022-02-04T14:57:34.280+00:00
updatedAt: 2022-02-04T14:57:59.585+00:00
</code>```

Many pages talk about the differences of both approaches (example) although in a very vague way, so we decided to open this thread to find a more scientific answer to the question.

Features of our app

app
Blocks that can be opened as documents
Blocks that can collapse or expand their children

Notion
Page type blocks
Toggle type blocks

Workflowy
All
All

Evernote
Documents
None

Our app
Page type blocks
All others

Our app has two types of "blocks". The page type (which, like in Notion, can be inserted into any note and generate a document "inside" the current document), and the rest of the blocks, which are equivalent to the "toggle" block type in Notion (i.e. they can be collapsed or their nested children can be expanded).

2. What we have tried

In trying to answer our question (which DB model would work best for our application), we've realized that the answer is probably "it depends". Perhaps both models have strengths or weaknesses in different types of operations or situations. That is why we formulated this comparison table describing how we believe the performance of both models would be for each of these operations.

Operation
Blocks
Documents
Apparent Winner

Fetch the contents of a page
Find all paragraphs in the DB.
Search the document in the DB.
Document

Render the content of a page**
Build the tree from the paragraphs recursively. You can omit the children of paragraphs whose isCollapsed property is true
Render the document
Document

Update the content of a paragraph in the DB
Only the modified paragraph is rewritten
The whole document is rewritten
Block

Alternatives for rendering very large documents *
Blocks can be fetched or rendered as you scroll (as Workflowy does), or as you expand child paragraphs that were collapsed.
I thought that Grifds could achieve similar behavior, breaking the document into smaller chunks and bringing them in piecemeal, but it doesn't support updating an individual chunk, or even the entire document. It could also corrupt an HTML by splitting it into binary format.
Block

Import or paste content
In addition to converting the clipboard to HTML and/or sanitizing it, you must set up paragraphs with tree structure recursively. Note: Roam Research e.g. supports importing in JSON format, but generally users do not handle this format beforehand.
Only convert the clipboard to HTML and/or sanitize the clipboard
Document

Copy content**
Clipboard must be sanitized and/or transformed
Correct by default**
Document

Real-Time Collaboration
At the document level, could use some tree-based (Json) library like Automerge, or combine with some CRDT library for paragraph level.
Could use tinymce solution.
Tie? Both seem to have their advantages and disadvantages.

*Render very large documents: Most users probably do not use notes larger than 250 kb (considering that multimedia files are referenced in a separate collection). Still, in the document model, the question arises: how can we load, render or edit large documents in manageable chunks? One idea we came up with is to split HTML documents that reach large dimensions into portions of a certain size in kb, instead of splitting them into paragraphs. (It would be like a kind of Gridfs that allows you to modify the file in parts.) Could this be a good idea?

**Should the DOM be nested? In order to be able to collapse or expand nested child paragraphs, note managers with a block model structure the DOM in a nested way (paragraphs are in divs, inside their parent divs, etc.). However, an alternative in the document model could be that when the user presses tab, only that block (HTML tag such as
 or
) is assigned an attribute with a number less than or equal to 1, representing the nesting levels relative to the previous block. This way when you press tab to nest or shift-tab to un-nest, you only have to modify one attribute of an HTML element instead of many elements; and the DOM stays simple, without having nested blocks.

3. Our conclusions

We believe that for each of the rows in the comparison table, benchmarks could be done measuring the performance of both models.
Other people have done something similar here and here, comparing the performance of note managers using both models. The problem with those tests is that it is difficult to draw an accurate conclusion about the goodness of both models. Obsidian uses documents locally, so you don't have to sync notes. Roam Research is a very new and poorly optimized app. Standard Notes encrypts notes locally. In other words, it's not always apples to apples.

And even if tests could be done, we believe that the answer may even depend on how each user uses the application. Suppose user A usually organizes his notes in long documents using paragraph nesting (to collapse or expand them). On the other hand user B usually organizes his notes by creating new documents within documents. It is likely that a block model based manager would work better for user A while a document based one would work better for B.

So, we tried to push our doubt as far as we could, but we are still not sure of the answer Which of the two models do you think would offer better performance for our app and why?

4. Update

I just found some very interesting information. It seems that both TinyMCE and CKEditor (up to version 4), the view and the model converge with the HTML being based on content-editable. However, CKEditor 5 switched to MVC [source 1], [source 2].

I've done a short test pasting a large clipboard of a few MB in TinyMCE 5, CKEditor 4 and CKEditor 5, and the latter has been a bit slower. I hope soon to be able to do more tests with other things like dragging blocks or rendering large documents.

In a GitHub thread about CKEditor 5's performance when working with large documents, one of the contributors said "It works slower than the native content-editable element obviously, but the typing experience is pretty well".

答: Looks like you've done your homework. Database modeling is sometimes a bit of an art rather than a science. I think that with both models, you can achieve good performance if you optimize them well. So I would recommend that you go for the one that requires less work. Since you've been working on the block model for 8 months already, that's probably the best option for you.</p>

Body:
1. The problem

Lately, it seems that many note managers with "infinite" tree structure are choosing a block model (where each paragraph is an entry in the DB), instead of a document or file model.

Blocks
Documents

Notion
 Workflowy
 Remnote
 Dynalist
 Roam Research
Evernote
 Obsidian
 Bear app

If you find any errors in the table, please let me know.

We have been developing an app very similar to Notion for 8 months now, also using the block model, but we are considering making a radical change and switching to the document model. The structure of our blocks in MongoDB currently looks like this:

_id: "61fd3ede7f6d2cc7a53ca669"
children: Array
    0: "61fd3ee87f6d2cc7a53ca66b"
    1: "61fd3ef37f6d2cc7a53ca671"
    2: "61fd3ef77f6d2cc7a53ca673"
backlinks: Array
type: "bullet"
parentPage: Array
    _id: "61fd3ede7f6e2ccra53ca664"
    userParent: "german-jablo"
    permisionParent: "edit, comment, read"
parentParagraph: "61fd3ede7f6d2cc7a53ca668"
content: "
This is a paragraph
"
isCollapsed: false
createdAt: 2022-02-04T14:57:34.280+00:00
updatedAt: 2022-02-04T14:57:59.585+00:00

Many pages talk about the differences of both approaches (example) although in a very vague way, so we decided to open this thread to find a more scientific answer to the question.

Features of our app

app
Blocks that can be opened as documents
Blocks that can collapse or expand their children

Notion
Page type blocks
Toggle type blocks

Workflowy
All
All

Evernote
Documents
None

Our app
Page type blocks
All others

Our app has two types of "blocks". The page type (which, like in Notion, can be inserted into any note and generate a document "inside" the current document), and the rest of the blocks, which are equivalent to the "toggle" block type in Notion (i.e. they can be collapsed or their nested children can be expanded).

2. What we have tried

In trying to answer our question (which DB model would work best for our application), we've realized that the answer is probably "it depends". Perhaps both models have strengths or weaknesses in different types of operations or situations. That is why we formulated this comparison table describing how we believe the performance of both models would be for each of these operations.

Operation
Blocks
Documents
Apparent Winner

Fetch the contents of a page
Find all paragraphs in the DB.
Search the document in the DB.
Document

Render the content of a page**
Build the tree from the paragraphs recursively. You can omit the children of paragraphs whose isCollapsed property is true
Render the document
Document

Update the content of a paragraph in the DB
Only the modified paragraph is rewritten
The whole document is rewritten
Block

Alternatives for rendering very large documents *
Blocks can be fetched or rendered as you scroll (as Workflowy does), or as you expand child paragraphs that were collapsed.
I thought that Grifds could achieve similar behavior, breaking the document into smaller chunks and bringing them in piecemeal, but it doesn't support updating an individual chunk, or even the entire document. It could also corrupt an HTML by splitting it into binary format.
Block

Import or paste content
In addition to converting the clipboard to HTML and/or sanitizing it, you must set up paragraphs with tree structure recursively. Note: Roam Research e.g. supports importing in JSON format, but generally users do not handle this format beforehand.
Only convert the clipboard to HTML and/or sanitize the clipboard
Document

Copy content**
Clipboard must be sanitized and/or transformed
Correct by default**
Document

Real-Time Collaboration
At the document level, could use some tree-based (Json) library like Automerge, or combine with some CRDT library for paragraph level.
Could use tinymce solution.
Tie? Both seem to have their advantages and disadvantages.

*Render very large documents: Most users probably do not use notes larger than 250 kb (considering that multimedia files are referenced in a separate collection). Still, in the document model, the question arises: how can we load, render or edit large documents in manageable chunks? One idea we came up with is to split HTML documents that reach large dimensions into portions of a certain size in kb, instead of splitting them into paragraphs. (It would be like a kind of Gridfs that allows you to modify the file in parts.) Could this be a good idea?

**Should the DOM be nested? In order to be able to collapse or expand nested child paragraphs, note managers with a block model structure the DOM in a nested way (paragraphs are in divs, inside their parent divs, etc.). However, an alternative in the document model could be that when the user presses tab, only that block (HTML tag such as
 or
) is assigned an attribute with a number less than or equal to 1, representing the nesting levels relative to the previous block. This way when you press tab to nest or shift-tab to un-nest, you only have to modify one attribute of an HTML element instead of many elements; and the DOM stays simple, without having nested blocks.

3. Our conclusions

We believe that for each of the rows in the comparison table, benchmarks could be done measuring the performance of both models.
Other people have done something similar here and here, comparing the performance of note managers using both models. The problem with those tests is that it is difficult to draw an accurate conclusion about the goodness of both models. Obsidian uses documents locally, so you don't have to sync notes. Roam Research is a very new and poorly optimized app. Standard Notes encrypts notes locally. In other words, it's not always apples to apples.

And even if tests could be done, we believe that the answer may even depend on how each user uses the application. Suppose user A usually organizes his notes in long documents using paragraph nesting (to collapse or expand them). On the other hand user B usually organizes his notes by creating new documents within documents. It is likely that a block model based manager would work better for user A while a document based one would work better for B.

So, we tried to push our doubt as far as we could, but we are still not sure of the answer Which of the two models do you think would offer better performance for our app and why?

4. Update

I just found some very interesting information. It seems that both TinyMCE and CKEditor (up to version 4), the view and the model converge with the HTML being based on content-editable. However, CKEditor 5 switched to MVC [source 1], [source 2].

I've done a short test pasting a large clipboard of a few MB in TinyMCE 5, CKEditor 4 and CKEditor 5, and the latter has been a bit slower. I hope soon to be able to do more tests with other things like dragging blocks or rendering large documents.

In a GitHub thread about CKEditor 5's performance when working with large documents, one of the contributors said "It works slower than the native content-editable element obviously, but the typing experience is pretty well".


问:
Why does a static constructor not have any parameters?
Per MSDN:

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

Can any one please explain why can't the static constructor have parameters?

答:
A Static Constructor is called implicitly by CLR automatically and it is the first block of code to run under a class.
We cannot pass any parameters to the static constructors because these are called implicitly and for passing parameters, we have to call it explicitly which is not possible

For More Clarification Refer This-enter link description here


问:
onBlur event post field to php script with Ajax
I'm working on lowering shopping cart abandonment rates for a client. I'd like to be able to post form data from individual input fields of a registration form to a php script, every time onblur fires.

The form fields would need to keep the value entered by the visitor and page shouldn't refresh so I think Ajax is the best solution. Any example code that does this would be appreciated.

Thanks

答:
Something like this would probably work for you:

```<code><html>
    <head>
        <script type="text/javascript">
            function sendData(obj) {
                var xmlhttp;

                if (window.XMLHttpRequest) {
                    xmlhttp=new XMLHttpRequest();
                } else {
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }

                xmlhttp.onreadystatechange=function() {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                        // Do stuff when script returns
                        alert(xmlhttp.responseText);
                    }
                }

                xmlhttp.open("GET","script.php?" + obj.name + "=" + obj.value + "&t="+Math.random(),true);
                xmlhttp.send();
            }

        </script>
    </head>

    <body>
        Input 1 <input type="text" onblur="sendData(this)" name="input1" /><br />
        Input 2 <input type="text" onblur="sendData(this)" name="input2" /><br />
        Input 3 <input type="text" onblur="sendData(this)" name="input3" /><br />
    </body>
</html>
</code>```

The random number at the end of the request is to make sure the browser doesn't return a cached response instead of actually sending your data to the server.

ContentLicense: CC BY-SA 3.0

Body:
Something like this would probably work for you:

<html>
    <head>
        <script type="text/javascript">
            function sendData(obj) {
                var xmlhttp;

                if (window.XMLHttpRequest) {
                    xmlhttp=new XMLHttpRequest();
                } else {
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }

                xmlhttp.onreadystatechange=function() {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                        // Do stuff when script returns
                        alert(xmlhttp.responseText);
                    }
                }

                xmlhttp.open("GET","script.php?" + obj.name + "=" + obj.value + "&t="+Math.random(),true);
                xmlhttp.send();
            }

        </script>
    </head>

    <body>
        Input 1 <input type="text" onblur="sendData(this)" name="input1" /><br />
        Input 2 <input type="text" onblur="sendData(this)" name="input2" /><br />
        Input 3 <input type="text" onblur="sendData(this)" name="input3" /><br />
    </body>
</html>

The random number at the end of the request is to make sure the browser doesn't return a cached response instead of actually sending your data to the server.


问:
NodeJS email-templates i18n localization
I have an issue with the localization of the pug templates combined with i18n. The language keeps rolling back to "en" language, but I've set the locale: 'sl' in the send() function, this is from the documentation of the email-templates.

Here is my code in typescript:

```<code>import * as path from 'path';
import Email = require("email-templates");
import { transporter } from '../mailerConnection';
import { I18n } from 'i18n';

export async function sendOutActivationEmail() {

  const i18n = new I18n();
  i18n.configure({
    locales: ['en', 'sl'],
    directory: path.join(__dirname, '../../locales'),
    register: global
  });

  const email = new Email({
    message: {
      from: '"test" <noreplay@test.com>'
    },
    // uncomment below to send emails in development/test env:
    //send: true,
    transport: transporter,
    i18n: i18n
  });

  email
    .send({
      template: path.join(__dirname, '../templates', 'activation'),
      message: {
        to: 'test@gmail.com'
      },
      locals: {
        locale: 'sl',
        name: 'Test'
      }
    })
    .then(console.log)
    .catch(console.error);

}
sendOutActivationEmail().catch(console.error);
</code>```

Here is html.pug template:

```<code>p= __('message')
</code>```

Here is en.json:

```<code>{
    "message": "message1"
}
</code>```

Here is sl.json:

```<code>{
    "message": "messageSLO"
}
</code>```

Here is the link to email-templates localization documentation: https://www.npmjs.com/package/email-templates#localization

What am I doing wrong that the functions doesn't switch to "sl" language? Thanks...

答:
Actually they use extension of the default i18n package is ladjs/i18n so the object that you pass to the email-template needs to be in different shape.

I solved my issue using the code below:

```<code>const email = new Email({
    message: {
        from: '"Test" <noreplay@test.com>'
    },
    // uncomment below to send emails in development/test env:
    //send: true,
    transport: transporter,
    i18n: {
        locales: ['en', 'sl'],
        directory: path.join(__dirname, '../../locales'),
        defaultLocale: 'en'
    }
});
</code>```

Body:
I have an issue with the localization of the pug templates combined with i18n. The language keeps rolling back to "en" language, but I've set the locale: 'sl' in the send() function, this is from the documentation of the email-templates.

Here is my code in typescript:

import * as path from 'path';
import Email = require("email-templates");
import { transporter } from '../mailerConnection';
import { I18n } from 'i18n';

export async function sendOutActivationEmail() {

  const i18n = new I18n();
  i18n.configure({
    locales: ['en', 'sl'],
    directory: path.join(__dirname, '../../locales'),
    register: global
  });

  const email = new Email({
    message: {
      from: '"test" <noreplay@test.com>'
    },
    // uncomment below to send emails in development/test env:
    //send: true,
    transport: transporter,
    i18n: i18n
  });

  email
    .send({
      template: path.join(__dirname, '../templates', 'activation'),
      message: {
        to: 'test@gmail.com'
      },
      locals: {
        locale: 'sl',
        name: 'Test'
      }
    })
    .then(console.log)
    .catch(console.error);

}
sendOutActivationEmail().catch(console.error);

Here is html.pug template:

p= __('message')

Here is en.json:

{
    "message": "message1"
}

Here is sl.json:

{
    "message": "messageSLO"
}

Here is the link to email-templates localization documentation: https://www.npmjs.com/package/email-templates#localization

What am I doing wrong that the functions doesn't switch to "sl" language? Thanks...

Body:
Actually they use extension of the default i18n package is ladjs/i18n so the object that you pass to the email-template needs to be in different shape.

I solved my issue using the code below:

const email = new Email({
    message: {
        from: '"Test" <noreplay@test.com>'
    },
    // uncomment below to send emails in development/test env:
    //send: true,
    transport: transporter,
    i18n: {
        locales: ['en', 'sl'],
        directory: path.join(__dirname, '../../locales'),
        defaultLocale: 'en'
    }
});


问:
Deadlock on All GoRoutines When Using Channels and WaitGroup
I am new to Go and am currently attempting to run a function that creates a file and returns it's filename and have this run concurrently.

I've decided to try and accomplish this with goroutines and a WaitGroup. When I use this approach, I end up with a list size that is a couple hundred files less than the input size. E.g. for 5,000 files I get around 4,700~ files created.

I believe this is due to some race conditions:

```<code>wg := sync.WaitGroup{}

filenames := make([]string, 0)

for i := 0; i < totalFiles; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        filenames = append(filenames, createFile())
    }()
}

wg.Wait()

return filenames, nil
</code>```

Don't communicate by sharing memory; share memory by communicating.

I tried using channels to "share memory by communicating". Whenever I do this, there appears to be a deadlock that I can't seem to wrap my head around why. Would anyone be able to point me in the right direction for using channels and waitgroups together properly in order to save all of the created files to a shared data structure?

This is the code that produces the deadlock for me (fatal error: all goroutines are asleep - deadlock!):

```<code>wg := sync.WaitGroup{}

filenames := make([]string, 0)
ch := make(chan string)

for i := 0; i < totalFiles; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        ch <- createFile()
    }()
}

wg.Wait()

for i := range ch {
    filenames = append(filenames, i)
}

return filenames, nil
</code>```

Thanks!

答:
The first one has a race. You have to protect access to filenames:

```<code>mu:=sync.Mutex{}
for i := 0; i < totalFiles; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        filenames = append(filenames, createFile())
    }()
}
</code>```

For the second case, you are waiting for the goroutines to finish, but goroutines can only finish once you read from the channel, so deadlock. You can fix it by reading from the channel in a separate goroutine.

```<code>go func() {
  for i := range ch {
      filenames = append(filenames, i)
  }
}()

wg.Wait()
close(ch) // Required, so the goroutine can terminate

return filenames, nil
</code>```

There is a lock-free version, if the number of files is fixed:

```<code>filenames := make([]string, totalFiles)
for i := 0; i < totalFiles; i++ {
    wg.Add(1)
    go func(index int) {
        defer wg.Done()
        filenames[index]=createFile()
    }(i)
}
wg.Wait()
</code>```

Body:
I am new to Go and am currently attempting to run a function that creates a file and returns it's filename and have this run concurrently.

I've decided to try and accomplish this with goroutines and a WaitGroup. When I use this approach, I end up with a list size that is a couple hundred files less than the input size. E.g. for 5,000 files I get around 4,700~ files created.

I believe this is due to some race conditions:

wg := sync.WaitGroup{}

filenames := make([]string, 0)

for i := 0; i < totalFiles; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        filenames = append(filenames, createFile())
    }()
}

wg.Wait()

return filenames, nil

Don't communicate by sharing memory; share memory by communicating.

I tried using channels to "share memory by communicating". Whenever I do this, there appears to be a deadlock that I can't seem to wrap my head around why. Would anyone be able to point me in the right direction for using channels and waitgroups together properly in order to save all of the created files to a shared data structure?

This is the code that produces the deadlock for me (fatal error: all goroutines are asleep - deadlock!):

wg := sync.WaitGroup{}

filenames := make([]string, 0)
ch := make(chan string)

for i := 0; i < totalFiles; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        ch <- createFile()
    }()
}

wg.Wait()

for i := range ch {
    filenames = append(filenames, i)
}

return filenames, nil

Thanks!

Body:
The first one has a race. You have to protect access to filenames:

mu:=sync.Mutex{}
for i := 0; i < totalFiles; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        filenames = append(filenames, createFile())
    }()
}

For the second case, you are waiting for the goroutines to finish, but goroutines can only finish once you read from the channel, so deadlock. You can fix it by reading from the channel in a separate goroutine.

go func() {
  for i := range ch {
      filenames = append(filenames, i)
  }
}()

wg.Wait()
close(ch) // Required, so the goroutine can terminate

return filenames, nil

There is a lock-free version, if the number of files is fixed:

filenames := make([]string, totalFiles)
for i := 0; i < totalFiles; i++ {
    wg.Add(1)
    go func(index int) {
        defer wg.Done()
        filenames[index]=createFile()
    }(i)
}
wg.Wait()


问:
Splash screen is woking on debug apk and is showing blank page on Release apk in flutter
I'm working on a flutter mobile application, while testing the mobile application on the Debug APK it shows the Splash screen perfectly when I created a Release APK the splash screen was not working perfectly. Here I'm showing the codes of the Splash screen.

```<code>import 'package:calculator_vault/globals.dart' as globals;
import 'package:calculator_vault/views/category.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';

class LoadingPage extends StatefulWidget {
  const LoadingPage({Key? key}) : super(key: key);

  @override
  _LoadingPageState createState() => _LoadingPageState();
}

class _LoadingPageState extends State<LoadingPage> {
  double value = 0;
  void downloadData() {
    new Timer.periodic(Duration(milliseconds: 50), (Timer timer) {
      if (globals.loadNow) {
        print('loading now');
        setState(() {
          if (value >= 1) {
            timer.cancel();

            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => MainPage()));
          } else {
            value = value + 0.015;

          }
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    downloadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(18.0),
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Positioned(
                bottom: MediaQuery.of(context).size.height / 22,
                child: Container(
                    height: 70,
                    width: 70,
                    child: Lottie.asset('assets/animations/loader.json'))
                    ),
            Positioned(
              bottom: 0,
              child: Text(
                'Version 2.7.3',
                style: TextStyle(fontSize: 10),
                textAlign: TextAlign.center,
              ),
            ),
            Center(
              child: Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Positioned(
                      child: Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              border: Border.all(
                                  width: 1.0, color: Color(0xffE8E3E3))),
                          width: 90,
                          height: 90,
                          child: ClipRRect(
                              borderRadius: BorderRadius.circular(20.0),
                              child: Image.asset(
                                  'assets/app_icons/app_icon_0.png'))),
                    ),
                    SizedBox(
                      height: 25,
                    ),
                    Positioned(
                      bottom: MediaQuery.of(context).size.height / 2.9,
                      child: Text(
                        'Calculator Lock',
                        style: TextStyle(fontSize: 25),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

I've no clue why is it happening, please let me know.

"HERE IS MY FLUTTER LOGS"

```<code>W/FlutterActivityAndFragmentDelegate( 9172): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
I/flutter ( 9172): Observatory listening on http://127.0.0.1:44415/EJIiR5NchMU=/
I/flutter ( 9172): Ad IDS: /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD ca-app-pub-5709217593772841/6100863205 ca-app-pub-5709217593772841/6100863205 /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD
I/flutter ( 9172): AppOpenAd failed to load: LoadAdError(code: 3, domain: com.google.android.gms.ads, message: No ad config., responseInfo: ResponseInfo(responseId: null, mediationAdapterClassName: , adapterResponses: []))
I/flutter ( 9172): Result : InterstitialAdResult.ERROR {error_message: No fill. We are not able to serve ads to this person. Please refer to https://developers.facebook.com/docs/audience-network/faq#a12. If you are integrating Audience Network for the first time, you can use test ads https://developers.facebook.com/docs/audience-network/testing., error_code: 1001, invalidated: true, placement_id: 3752483214787237_3752491351453090}
I/flutter ( 9172): 1 /storage/emulated/0/.CalculatorVault/hideFiles
I/flutter ( 9172): true
I/flutter ( 9172): ad is loaded
I/flutter ( 9172): Title Text :
</code>```

答:
Remove this code from your AndroidManifest.xml and it should work

```<code><meta-data
    android:name="io.flutter.embedding.android.SplashScreenDrawable"
    android:resource="@drawable/launch_background"
/>
</code>```

Ref: StackOverflow answer on deprecated Splash Api

Body:
I'm working on a flutter mobile application, while testing the mobile application on the Debug APK it shows the Splash screen perfectly when I created a Release APK the splash screen was not working perfectly. Here I'm showing the codes of the Splash screen.

import 'package:calculator_vault/globals.dart' as globals;
import 'package:calculator_vault/views/category.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';

class LoadingPage extends StatefulWidget {
  const LoadingPage({Key? key}) : super(key: key);

  @override
  _LoadingPageState createState() => _LoadingPageState();
}

class _LoadingPageState extends State<LoadingPage> {
  double value = 0;
  void downloadData() {
    new Timer.periodic(Duration(milliseconds: 50), (Timer timer) {
      if (globals.loadNow) {
        print('loading now');
        setState(() {
          if (value >= 1) {
            timer.cancel();

            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => MainPage()));
          } else {
            value = value + 0.015;

          }
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    downloadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(18.0),
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Positioned(
                bottom: MediaQuery.of(context).size.height / 22,
                child: Container(
                    height: 70,
                    width: 70,
                    child: Lottie.asset('assets/animations/loader.json'))
                    ),
            Positioned(
              bottom: 0,
              child: Text(
                'Version 2.7.3',
                style: TextStyle(fontSize: 10),
                textAlign: TextAlign.center,
              ),
            ),
            Center(
              child: Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Positioned(
                      child: Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              border: Border.all(
                                  width: 1.0, color: Color(0xffE8E3E3))),
                          width: 90,
                          height: 90,
                          child: ClipRRect(
                              borderRadius: BorderRadius.circular(20.0),
                              child: Image.asset(
                                  'assets/app_icons/app_icon_0.png'))),
                    ),
                    SizedBox(
                      height: 25,
                    ),
                    Positioned(
                      bottom: MediaQuery.of(context).size.height / 2.9,
                      child: Text(
                        'Calculator Lock',
                        style: TextStyle(fontSize: 25),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

I've no clue why is it happening, please let me know.

"HERE IS MY FLUTTER LOGS"

W/FlutterActivityAndFragmentDelegate( 9172): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
I/flutter ( 9172): Observatory listening on http://127.0.0.1:44415/EJIiR5NchMU=/
I/flutter ( 9172): Ad IDS: /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD ca-app-pub-5709217593772841/6100863205 ca-app-pub-5709217593772841/6100863205 /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD
I/flutter ( 9172): AppOpenAd failed to load: LoadAdError(code: 3, domain: com.google.android.gms.ads, message: No ad config., responseInfo: ResponseInfo(responseId: null, mediationAdapterClassName: , adapterResponses: []))
I/flutter ( 9172): Result : InterstitialAdResult.ERROR {error_message: No fill. We are not able to serve ads to this person. Please refer to https://developers.facebook.com/docs/audience-network/faq#a12. If you are integrating Audience Network for the first time, you can use test ads https://developers.facebook.com/docs/audience-network/testing., error_code: 1001, invalidated: true, placement_id: 3752483214787237_3752491351453090}
I/flutter ( 9172): 1 /storage/emulated/0/.CalculatorVault/hideFiles
I/flutter ( 9172): true
I/flutter ( 9172): ad is loaded
I/flutter ( 9172): Title Text :

Body:
Remove this code from your AndroidManifest.xml and it should work

<meta-data
    android:name="io.flutter.embedding.android.SplashScreenDrawable"
    android:resource="@drawable/launch_background"
/>

Ref: StackOverflow answer on deprecated Splash Api


问:
Subquery must have alias despite having alias?
I have an Alias at the bottom (AS crypto). However, I still get the "subquery in FROM must have an alias" error. And then HINT "For example, FROM (SELECT ...) [AS] foo." I see many other posts that say to "just add AS _" as an alias, but mine still isn't working. What am I doing wrong?</p>
```<code>  SELECT DISTINCT
  contact.account_id,
  contact.email,
  crypto.total_crypto
FROM
  (
    SELECT DISTINCT
      account_id,
      SUM(unit_count) as total_crypto
    FROM
      beta.asset_transaction
    WHERE
      (asset_transfer_type = 'bitcoin' AND SUM(unit_count) > '0.025' AND account_id != '22222')
    OR
      (asset_transfer_type = 'ethereum' AND SUM(unit_count) > '0.4' AND account_id != '22222')
    OR
      (asset_transfer_type = 'internal' AND SUM(unit_count) > '1000' AND account_id != '22222')
    OR
      asset_transfer_type = 'stellar' AND SUM(unit_count) > '5000' AND account_id != '22222')
    GROUP BY
      account_id
  ) AS crypto ---> Alias
  INNER JOIN beta.contact ON contact.account_id = crypto.account_id
  ORDER BY total_crypto DESC;
</code>```

答:
Remember:

We can't put an aggregate in a where clause

We can't use DISTINCT with aggregates

I believe what you want is "By account ID, the total unit count summed across the four listed asset transfer types for any account ID that has a unit count of more than 0.025 bitcoin, or more than 0.4 ethereum, or more than 1000 internal or more than 5000 stellar".

In which case:

```<code>  SELECT DISTINCT
         contact.account_id,
         contact.email,
         crypto.total_crypto
  FROM
   (
    SELECT
      account_id,
      asset_transfer_type,
      SUM(unit_count) AS asset_transfer_unit_count
      SUM(SUM(unit_count)) OVER (PARTITION BY account_id) as total_crypto
    FROM
      beta.asset_transaction
    WHERE account_id != '22222'
    AND asset_transfer_type IN ('bitcoin','ethereum','internal','stellar')
    GROUP BY account_id, asset_transfer_type
    ) crypto
  INNER JOIN beta.contact ON contact.account_id = crypto.account_id
    WHERE
      (asset_transfer_type = 'bitcoin' AND asset_transfer_unit_count > 0.025)
    OR
      (asset_transfer_type = 'ethereum' AND asset_transfer_unit_count > 0.4)
    OR
      (asset_transfer_type = 'internal' AND asset_transfer_unit_count > 1000)
    OR
      (asset_transfer_type = 'stellar' AND asset_transfer_unit_count > 5000)
  ORDER BY total_crypto DESC;
</code>```

Body:
I have an Alias at the bottom (AS crypto). However, I still get the "subquery in FROM must have an alias" error. And then HINT "For example, FROM (SELECT ...) [AS] foo." I see many other posts that say to "just add AS _" as an alias, but mine still isn't working. What am I doing wrong?

  SELECT DISTINCT
  contact.account_id,
  contact.email,
  crypto.total_crypto
FROM
  (
    SELECT DISTINCT
      account_id,
      SUM(unit_count) as total_crypto
    FROM
      beta.asset_transaction
    WHERE
      (asset_transfer_type = 'bitcoin' AND SUM(unit_count) > '0.025' AND account_id != '22222')
    OR
      (asset_transfer_type = 'ethereum' AND SUM(unit_count) > '0.4' AND account_id != '22222')
    OR
      (asset_transfer_type = 'internal' AND SUM(unit_count) > '1000' AND account_id != '22222')
    OR
      asset_transfer_type = 'stellar' AND SUM(unit_count) > '5000' AND account_id != '22222')
    GROUP BY
      account_id
  ) AS crypto ---> Alias
  INNER JOIN beta.contact ON contact.account_id = crypto.account_id
  ORDER BY total_crypto DESC;

Body:
Remember:

We can't put an aggregate in a where clause

We can't use DISTINCT with aggregates

I believe what you want is "By account ID, the total unit count summed across the four listed asset transfer types for any account ID that has a unit count of more than 0.025 bitcoin, or more than 0.4 ethereum, or more than 1000 internal or more than 5000 stellar".

In which case:

  SELECT DISTINCT
         contact.account_id,
         contact.email,
         crypto.total_crypto
  FROM
   (
    SELECT
      account_id,
      asset_transfer_type,
      SUM(unit_count) AS asset_transfer_unit_count
      SUM(SUM(unit_count)) OVER (PARTITION BY account_id) as total_crypto
    FROM
      beta.asset_transaction
    WHERE account_id != '22222'
    AND asset_transfer_type IN ('bitcoin','ethereum','internal','stellar')
    GROUP BY account_id, asset_transfer_type
    ) crypto
  INNER JOIN beta.contact ON contact.account_id = crypto.account_id
    WHERE
      (asset_transfer_type = 'bitcoin' AND asset_transfer_unit_count > 0.025)
    OR
      (asset_transfer_type = 'ethereum' AND asset_transfer_unit_count > 0.4)
    OR
      (asset_transfer_type = 'internal' AND asset_transfer_unit_count > 1000)
    OR
      (asset_transfer_type = 'stellar' AND asset_transfer_unit_count > 5000)
  ORDER BY total_crypto DESC;


问:
SQL Server 2019 - Connecting to Databricks Cluster using SSMS or Azure Data Studio
Has anyone used SSMS v18.2 or Azure Data Studio to connect to a DataBricks Cluster and so query on DataBricks tables and/or the DataBricks File System (dbfs)?

Would like to know how you can set this up to show a DataBricks server in connections and use PolyBase to connect to dbfs

I can connect to ADLS using the PolyBase commands like as follows:

```<code>-- Scoped Credential
CREATE DATABASE SCOPED CREDENTIAL myScopedCredential
WITH
    IDENTITY = '<MyId>@https://login.microsoftonline.com/<Id2>/oauth2/token',
    SECRET = '<MySecret>';

-- External Data Source
CREATE EXTERNAL DATA SOURCE myDataSource
WITH
(
    TYPE = HADOOP,
    LOCATION = 'adl://mydatalakeserver.azuredatalakestore.net',
    CREDENTIAL = myScopedCredential
)

-- Something similar to setup for dbfs?
-- What IDENTITY used for Scoped Credential?
</code>```

答:
This doesn't seem possible without the use of 3rd party tools or custom applications. Databricks SQL just doesn't expose the protocols necessary.

There are 3rd party tools (e.g. from CData) that can help you here. See this article: https://www.cdata.com/kb/tech/databricks-odbc-linked-server.rst

Body:
Has anyone used SSMS v18.2 or Azure Data Studio to connect to a DataBricks Cluster and so query on DataBricks tables and/or the DataBricks File System (dbfs)?

Would like to know how you can set this up to show a DataBricks server in connections and use PolyBase to connect to dbfs

I can connect to ADLS using the PolyBase commands like as follows:

-- Scoped Credential
CREATE DATABASE SCOPED CREDENTIAL myScopedCredential
WITH
    IDENTITY = '<MyId>@https://login.microsoftonline.com/<Id2>/oauth2/token',
    SECRET = '<MySecret>';

-- External Data Source
CREATE EXTERNAL DATA SOURCE myDataSource
WITH
(
    TYPE = HADOOP,
    LOCATION = 'adl://mydatalakeserver.azuredatalakestore.net',
    CREDENTIAL = myScopedCredential
)

-- Something similar to setup for dbfs?
-- What IDENTITY used for Scoped Credential?


问:
Row count in a csv file
I am probably making a stupid mistake, but I can't find where it is. I want to count the number of lines in my csv file. I wrote this, and obviously isn't working: I have row_count = 0 while it should be 400. Cheers.

```<code>f = open(adresse,"r")
reader = csv.reader(f,delimiter = ",")
data = [l for l in reader]
row_count = sum(1 for row in reader)

print row_count
</code>```

答:
The important stuff is hidden in comments section of solution which is marked correct.

Re-sharing Erdős-Bacon's solution here for better visibility.

Why ?
Because: It saves lot of memory without having to create list.

So I think it is better do this way

```<code>
def read_raw_csv(file_name):
    with open(file_name, 'r') as file:
        csvreader = csv.reader(file)

        # count number of rows
        entry_count = sum(1 for row in csvreader)
        print(entry_count-1)  # -1 is for discarding header row.
</code>```

Checkout this link for more info

Title: Row count in a csv file

Body:
I am probably making a stupid mistake, but I can't find where it is. I want to count the number of lines in my csv file. I wrote this, and obviously isn't working: I have row_count = 0 while it should be 400. Cheers.

f = open(adresse,"r")
reader = csv.reader(f,delimiter = ",")
data = [l for l in reader]
row_count = sum(1 for row in reader)

print row_count

Body:
The important stuff is hidden in comments section of solution which is marked correct.

Re-sharing Erdős-Bacon's solution here for better visibility.

Why ?
Because: It saves lot of memory without having to create list.

So I think it is better do this way

def read_raw_csv(file_name):
    with open(file_name, 'r') as file:
        csvreader = csv.reader(file)

        # count number of rows
        entry_count = sum(1 for row in csvreader)
        print(entry_count-1)  # -1 is for discarding header row.

Checkout this link for more info


问:
discord.py problems with on_member_join()
What am I doing wrong?

@bot.event
async def on_member_join(member):
    print(f"{member} join")
    role_1 = member.guild.get_role(start_role_id)
    await member.add_roles(role_1)
```

I searched for answers on the forums for a long time and nothing helped.

答:
Try this:</p>
```<code>bot = commands.Bot(command_prefix='PREFIX_HERE',
intents=discord.Intents.all())

@bot.event
async def on_member_join(member):
    print(f"{member} has joined")
    my_role = discord.utils.get(member.guild.roles, id=role_id)
    await member.add_roles(my_role)
</code>```

Body:
What am I doing wrong?

@bot.event
async def on_member_join(member):
    print(f"{member} join")
    role_1 = member.guild.get_role(start_role_id)
    await member.add_roles(role_1)

I searched for answers on the forums for a long time and nothing helped.

Body:
Try this:

bot = commands.Bot(command_prefix='PREFIX_HERE',
intents=discord.Intents.all())

@bot.event
async def on_member_join(member):
    print(f"{member} has joined")
    my_role = discord.utils.get(member.guild.roles, id=role_id)
    await member.add_roles(my_role)


问:
Tailwind - how to get version in js or php
My context
Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30 and Tailwind

I want to get Tailwind version in js such as getting Vue version by :

```<code>//app.js
require('./bootstrap');
import { createApp } from 'vue'
import { version } from 'vue'

let app = createApp({
    data() {
        return {
            vueVersion : version
        }
    },
}).mount('#app')
</code>```

and using version variable in vue and pass it to laravel view

There is also in Laravel

```<code>//uploadfiles.blade.php
...
<div class="mb-12 mt-12">
    <h1 class="text-lg">My app</h1>
    <h4 class="text-sm mt-4">powered by Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }}), Vue v${ vueVersion } and Tailwind</h4>
</div>
...
</code>```

Or get Tailwind version similar to php way to render php version and laravel version.

App build/compiled? in Laravel Mix/webpack?(npm run dev ) and laravel cli (./vendor/bin/sail up)

```<code>mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
    require('tailwindcss')
]).vue();
</code>```

//package.json
{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "axios": "^0.21",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "tailwindcss": "^3.0.18",
        "vue-loader": "^16.8.3"
    },
    "dependencies": {
        "vue": "^3.2.30"
    }
}
```

答:
You can require tailwind's package.json and get the version from there.

//app.js
require('./bootstrap');

const tailwindCssVersion = require('tailwindcss/package.json').version;

import { createApp } from 'vue'
import { version } from 'vue'

let app = createApp({
    data() {
        return {
            vueVersion: version,
            tailwindCssVersion: tailwindCssVersion
        }
    },
}).mount('#app')
```
<pre class="lang-xml prettyprint-override"><code><h4 class="text-sm mt-4">[...] TailwindCSS v${ tailwindCssVersion }</h4>
</code>```

Body:
My context
Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30 and Tailwind

I want to get Tailwind version in js such as getting Vue version by :

//app.js
require('./bootstrap');
import { createApp } from 'vue'
import { version } from 'vue'

let app = createApp({
    data() {
        return {
            vueVersion : version
        }
    },
}).mount('#app')

and using version variable in vue and pass it to laravel view

There is also in Laravel

//uploadfiles.blade.php
...

My app

powered by Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }}), Vue v${ vueVersion } and Tailwind

...

Or get Tailwind version similar to php way to render php version and laravel version.

App build/compiled? in Laravel Mix/webpack?(npm run dev ) and laravel cli (./vendor/bin/sail up)

mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
    require('tailwindcss')
]).vue();

//package.json
{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "axios": "^0.21",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "tailwindcss": "^3.0.18",
        "vue-loader": "^16.8.3"
    },
    "dependencies": {
        "vue": "^3.2.30"
    }
}

Body:
You can require tailwind's package.json and get the version from there.

//app.js
require('./bootstrap');

const tailwindCssVersion = require('tailwindcss/package.json').version;

import { createApp } from 'vue'
import { version } from 'vue'

let app = createApp({
    data() {
        return {
            vueVersion: version,
            tailwindCssVersion: tailwindCssVersion
        }
    },
}).mount('#app')

<h4 class="text-sm mt-4">[...] TailwindCSS v${ tailwindCssVersion }</h4>


问:
How to Display Picker when page load without tapping on title Xamarin.Forms
Hi I am using a Picker to display some values to be select.

```<code><Picker x:Name="selection" Title="Select Option">
    <Picker.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>Episode</x:String>
            <x:String>All</x:String>
            <x:String>Department</x:String>
            <x:String>Section</x:String>
        </x:Array>
    </Picker.ItemsSource>
</Picker>
</code>```

This is not displaying when page load only Title will display.

When I tap on title it will display the picker.

but I want to display picker when page load...

How can I do that?

答:
Just create an async Task for your picker to display. But you have to delay it a bit to make sure the page is fully loaded when focussing the picker:

In your page constructor:

```<code>public YourPageConstructor()
        {
            InitializeComponent();
            Task.Run(async () => await FocusAsync());
        }
</code>```

In your async Task:

```<code>public async Task FocusAsync()
        {
            await Task.Delay(300);
            selection.Focus();
        }
</code>```

PS: I am no pro at all but this worked for me.

Body:
Hi I am using a Picker to display some values to be select.

<Picker x:Name="selection" Title="Select Option">
    <Picker.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>Episode</x:String>
            <x:String>All</x:String>
            <x:String>Department</x:String>
            <x:String>Section</x:String>
        </x:Array>
    </Picker.ItemsSource>
</Picker>

This is not displaying when page load only Title will display.

When I tap on title it will display the picker.

but I want to display picker when page load...

How can I do that?

Body:
Just create an async Task for your picker to display. But you have to delay it a bit to make sure the page is fully loaded when focussing the picker:

In your page constructor:

public YourPageConstructor()
        {
            InitializeComponent();
            Task.Run(async () => await FocusAsync());
        }

In your async Task:

public async Task FocusAsync()
        {
            await Task.Delay(300);
            selection.Focus();
        }

PS: I am no pro at all but this worked for me.


问:
Jquery (this) help
Just wanted some quick help I'm 90% sure i need to use the (this) call/function because i need it to work on multiple objects on the page. but im not sure where or how to place it into my jquery code, im trying to create a hover state for a object once the user rolls over another , here is my jquery code, I hope this makes sense, thanks!

```<code>    $("li.projectpost").hover(function () {
    $("div.portfolio-title a").toggleClass("highlighter");
    });
</code>```

Basically all i really want to know is, I have more than one element on the page that I would like to apply a hover effect to, as is right now, when i hover over one item they all change, but I want to know is how to change the css in a child element when rolled over a parent I guess,  I have a Div wrapper, that when hovered  over an inside div changes, does that make better sense, Still trying to wrap my head around jquery thanks for the help! :)

Thanks for the help everyone! I just figured this out, I needed to use -
    jQuery(this).find(); thanks!

答:
```<code>$("li.projectpost").hover(function () {
    $(this).toggleClass("highlighter");
});
</code>```

The above should work, tell me how it goes.

Title: Jquery (this) help

Body:
Just wanted some quick help I'm 90% sure i need to use the (this) call/function because i need it to work on multiple objects on the page. but im not sure where or how to place it into my jquery code, im trying to create a hover state for a object once the user rolls over another , here is my jquery code, I hope this makes sense, thanks!

    $("li.projectpost").hover(function () {
    $("div.portfolio-title a").toggleClass("highlighter");
    });

Basically all i really want to know is, I have more than one element on the page that I would like to apply a hover effect to, as is right now, when i hover over one item they all change, but I want to know is how to change the css in a child element when rolled over a parent I guess,  I have a Div wrapper, that when hovered  over an inside div changes, does that make better sense, Still trying to wrap my head around jquery thanks for the help! :)

Thanks for the help everyone! I just figured this out, I needed to use -
    jQuery(this).find(); thanks!

Body:
$("li.projectpost").hover(function () {
    $(this).toggleClass("highlighter");
});

The above should work, tell me how it goes.


问:
MongoDB join two collections having JSON array data
I am able to write query for normal single key-value joining with $lookup. But my scenario is little bit complicated, and not sure how to achieve that.

product :

```<code>{
    "_id": ObjectId("6200a77598412e443c03f0ee"),
    "name": "1000",
    "sku_code": "22",
    "field_values": [{
        "field_id": ObjectId("61fd34cbbc787e45d256a270"),
        "key": "P4YZRK71CZAQ8IXJ3",
        "value": "54"
    }, {
        "field_id": ObjectId("61fb77b2384e2635f8a2d1ea"),
        "key": "SF_10KRUMSESSIONSPERMONTH",
        "value": "34"
    }]
}
</code>```

field :

```<code>{
    "_id": ObjectId("61fb77b1384e2635f8a2d1e9"),
    "description": "sf_infrastructureFunction__c",
    "is_read_only": false,
    "is_required": false,
    "name": "sf_infrastructureFunction",
    "key": "SF_INFRASTRUCTUREFUNCTION",
    "type": "number"
}, {
    "_id": ObjectId("61fb77b2384e2635f8a2d1ea"),
    "default": "123",
    "description": "sf_10KRumSessionsPerMonth__c",
    "is_read_only": false,
    "is_required": false,
    "name": "sf_10KRumSessionsPerMonth",
    "key": "SF_10KRUMSESSIONSPERMONTH",
    "type": "number"
}, {
    "_id": ObjectId("61fd34cbbc787e45d256a270"),
    "description": "UKXNVYBF7AXE1VOUH",
    "is_read_only": false,
    "is_required": true,
    "name": "P4YZRK71CZAQ8IXJ3",
    "key": "P4YZRK71CZAQ8IXJ3",
    "type": "number"
}
</code>```

Final expected output for product(6200a77598412e443c03f0ee) :

```<code>{
    "_id": ObjectId("61fb77b1384e2635f8a2d1e9"),
    "description": "sf_infrastructureFunction__c",
    "is_read_only": false,
    "is_required": false,
    "name": "sf_infrastructureFunction",
    "key": "SF_INFRASTRUCTUREFUNCTION",
    "type": "number",
}, {
    "_id": ObjectId("61fb77b2384e2635f8a2d1ea"),
    "default": "123",
    "description": "sf_10KRumSessionsPerMonth__c",
    "is_read_only": false,
    "is_required": false,
    "name": "sf_10KRumSessionsPerMonth",
    "key": "SF_10KRUMSESSIONSPERMONTH",
    "type": "number",
    "field_data" : {
        "key": "SF_10KRUMSESSIONSPERMONTH",
        "value": "34"
    }
}, {
    "_id": ObjectId("61fd34cbbc787e45d256a270"),
    "description": "UKXNVYBF7AXE1VOUH",
    "is_read_only": false,
    "is_required": true,
    "name": "P4YZRK71CZAQ8IXJ3",
    "key": "P4YZRK71CZAQ8IXJ3",
    "type": "number",
    "field_data" : {
        "key": "P4YZRK71CZAQ8IXJ3",
        "value": "54"
    }
}
</code>```

Kindly note in first JSON in sample output, product has not stored any field_values for that field. Overall, I want all fields data with their values for specific product id, and if it does not have values, then plain configuration of field.

答:
Something like this:

```<code>db.field.aggregate([
{
 "$lookup": {
  "from": "product",
  "localField": "_id",
  "foreignField": "field_values.field_id",
  "as": "field_data"
 }
 },
 {
   $unwind: {
    path: "$field_data",
    preserveNullAndEmptyArrays: true
 }
 },
 {
  "$addFields": {
  "field_data": {
    "$filter": {
      "input": "$field_data.field_values",
      "as": "fv",
      "cond": {
        $eq: [
          "$$fv.field_id",
          "$_id"
        ]
       }
      }
     }
    }
   },
   {
    $addFields: {
     field_data: {
      $cond: {
       if: {
        $eq: [
          "$field_data",
          null
        ]
       },
       then: "$$REMOVE",
       else: "$field_data"
      }
     }
    }
   }
 ])
</code>```

Explained:

$lookup to add the product to the field documents

$unwind to flatten the resulting array ( it contain product document ) preserving the null elements

$filter to keep only the matching products.

Remove the null field_data for those products that is null.

playground

Body:
I am able to write query for normal single key-value joining with $lookup. But my scenario is little bit complicated, and not sure how to achieve that.

product :

{
    "_id": ObjectId("6200a77598412e443c03f0ee"),
    "name": "1000",
    "sku_code": "22",
    "field_values": [{
        "field_id": ObjectId("61fd34cbbc787e45d256a270"),
        "key": "P4YZRK71CZAQ8IXJ3",
        "value": "54"
    }, {
        "field_id": ObjectId("61fb77b2384e2635f8a2d1ea"),
        "key": "SF_10KRUMSESSIONSPERMONTH",
        "value": "34"
    }]
}

field :

{
    "_id": ObjectId("61fb77b1384e2635f8a2d1e9"),
    "description": "sf_infrastructureFunction__c",
    "is_read_only": false,
    "is_required": false,
    "name": "sf_infrastructureFunction",
    "key": "SF_INFRASTRUCTUREFUNCTION",
    "type": "number"
}, {
    "_id": ObjectId("61fb77b2384e2635f8a2d1ea"),
    "default": "123",
    "description": "sf_10KRumSessionsPerMonth__c",
    "is_read_only": false,
    "is_required": false,
    "name": "sf_10KRumSessionsPerMonth",
    "key": "SF_10KRUMSESSIONSPERMONTH",
    "type": "number"
}, {
    "_id": ObjectId("61fd34cbbc787e45d256a270"),
    "description": "UKXNVYBF7AXE1VOUH",
    "is_read_only": false,
    "is_required": true,
    "name": "P4YZRK71CZAQ8IXJ3",
    "key": "P4YZRK71CZAQ8IXJ3",
    "type": "number"
}

Final expected output for product(6200a77598412e443c03f0ee) :

{
    "_id": ObjectId("61fb77b1384e2635f8a2d1e9"),
    "description": "sf_infrastructureFunction__c",
    "is_read_only": false,
    "is_required": false,
    "name": "sf_infrastructureFunction",
    "key": "SF_INFRASTRUCTUREFUNCTION",
    "type": "number",
}, {
    "_id": ObjectId("61fb77b2384e2635f8a2d1ea"),
    "default": "123",
    "description": "sf_10KRumSessionsPerMonth__c",
    "is_read_only": false,
    "is_required": false,
    "name": "sf_10KRumSessionsPerMonth",
    "key": "SF_10KRUMSESSIONSPERMONTH",
    "type": "number",
    "field_data" : {
        "key": "SF_10KRUMSESSIONSPERMONTH",
        "value": "34"
    }
}, {
    "_id": ObjectId("61fd34cbbc787e45d256a270"),
    "description": "UKXNVYBF7AXE1VOUH",
    "is_read_only": false,
    "is_required": true,
    "name": "P4YZRK71CZAQ8IXJ3",
    "key": "P4YZRK71CZAQ8IXJ3",
    "type": "number",
    "field_data" : {
        "key": "P4YZRK71CZAQ8IXJ3",
        "value": "54"
    }
}

Kindly note in first JSON in sample output, product has not stored any field_values for that field. Overall, I want all fields data with their values for specific product id, and if it does not have values, then plain configuration of field.

Body:
Something like this:

db.field.aggregate([
{
 "$lookup": {
  "from": "product",
  "localField": "_id",
  "foreignField": "field_values.field_id",
  "as": "field_data"
 }
 },
 {
   $unwind: {
    path: "$field_data",
    preserveNullAndEmptyArrays: true
 }
 },
 {
  "$addFields": {
  "field_data": {
    "$filter": {
      "input": "$field_data.field_values",
      "as": "fv",
      "cond": {
        $eq: [
          "$$fv.field_id",
          "$_id"
        ]
       }
      }
     }
    }
   },
   {
    $addFields: {
     field_data: {
      $cond: {
       if: {
        $eq: [
          "$field_data",
          null
        ]
       },
       then: "$$REMOVE",
       else: "$field_data"
      }
     }
    }
   }
 ])

Explained:

$lookup to add the product to the field documents

$unwind to flatten the resulting array ( it contain product document ) preserving the null elements

$filter to keep only the matching products.

Remove the null field_data for those products that is null.

playground


Title: How to print the elements of a tuple sided by side

Body:
I am able to print the elements one after the another but I want the result to be printed side by side: 1234, instead of:

1

2

3

4

Display which I am getting

Desired Output:

The code is to display 7 segment led display.

led_dict={
    '0':('###','# #','# #','# #','###'),
    '1':('  #','  #','  #','  #','  #'),
    '2':('###','  #','###','#  ','###'),
    '3':('###','  #','###','  #','###'),
    '4':('# #','# #','###','  #','  #'),
    '5':('###','#  ','###','  #','###'),
    '6':('###','#  ','###','# #','###'),
    '7':('###','  #','  #','  #','  #'),
    '8':('###','# #','###','# #','###'),
    '9':('###','# #','###','  #','###')
    }

x = input('Enter a number to be displayed: ')

d_list=[]

for num in str(x):
    d_list.append(led_dict[num])
print(d_list)
# for i in range(5):
#     for ab in d_list:
#         print(ab[i])

for ab in d_list:
    for i in range(5):
        print((ab[i]))

Body:
How about this one:

led_dict={
    '0':('###','# #','# #','# #','###'),
    '1':('  #','  #','  #','  #','  #'),
    '2':('###','  #','###','#  ','###'),
    '3':('###','  #','###','  #','###'),
    '4':('# #','# #','###','  #','  #'),
    '5':('###','#  ','###','  #','###'),
    '6':('###','#  ','###','# #','###'),
    '7':('###','  #','  #','  #','  #'),
    '8':('###','# #','###','# #','###'),
    '9':('###','# #','###','  #','###')
    }

x = input('Enter a number to be displayed: ')

d_list=[]
for num in str(x):
    d_list.append(led_dict[num])

for i in range(5):
    for ab in d_list:
        print(ab[i],end=' ')
    print()


问:
How to find whether a table has a given date range
I want to find out whether a table has rows within the range of dates passed to the query. The following is the data in MYTABLE. I am using SQL Server

```<code>DISPLAY_START_DATE      DISPLAY_END_DATE
2022-02-02 00:00:00.000     2022-02-28 00:00:00.000
2022-02-02 00:00:00.000     2022-02-06 10:34:01.653
2022-02-01 00:00:00.000     2022-02-17 00:00:00.000
2022-02-07 00:00:00.000     2022-02-25 00:00:00.000
</code>```

The following is my query

```<code>DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'
SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE = @startdate and  mt.DISPLAY_END_DATE = @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE > @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE < @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE < @enddate and
    mt.DISPLAY_END_DATE > @startdate)   OR
(mt.DISPLAY_START_DATE > @startdate and  mt.DISPLAY_END_DATE < @enddate) OR
(mt.DISPLAY_START_DATE > @startdate and mt.DISPLAY_START_DATE < @enddate and
    mt.DISPLAY_END_DATE < @enddate)
</code>```

This pulls only the second row corresponding to the following data

```<code>DISPLAY_START_DATE      DISPLAY_END_DATE
2022-02-02 00:00:00.000     2022-02-06 10:34:01.653
</code>```

答:
If you want to select all the rows having both the dates within given range you can try below query:

```<code>DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'

SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE between @startdate and @enddate)
</code>```

Or if you want a where condition to select all the rows from the table which have fully or partially in the range

```<code>SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE between @startdate and @enddate) or
(mt.DISPLAY_START_DATE <=@startdate and mt.DISPLAY_END_DATE >=@enddate) or
(mt.DISPLAY_START_DATE <=@startdate and mt.DISPLAY_END_DATE between @startdate and @enddate) or
(mt.DISPLAY_START_DATE between @startdate and @enddate  and mt.DISPLAY_END_DATE >=@enddate)
</code>```

Body:
I want to find out whether a table has rows within the range of dates passed to the query. The following is the data in MYTABLE. I am using SQL Server

DISPLAY_START_DATE      DISPLAY_END_DATE
2022-02-02 00:00:00.000     2022-02-28 00:00:00.000
2022-02-02 00:00:00.000     2022-02-06 10:34:01.653
2022-02-01 00:00:00.000     2022-02-17 00:00:00.000
2022-02-07 00:00:00.000     2022-02-25 00:00:00.000

The following is my query

DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'
SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE = @startdate and  mt.DISPLAY_END_DATE = @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE > @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE < @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE < @enddate and
    mt.DISPLAY_END_DATE > @startdate)   OR
(mt.DISPLAY_START_DATE > @startdate and  mt.DISPLAY_END_DATE < @enddate) OR
(mt.DISPLAY_START_DATE > @startdate and mt.DISPLAY_START_DATE < @enddate and
    mt.DISPLAY_END_DATE < @enddate)

This pulls only the second row corresponding to the following data

DISPLAY_START_DATE      DISPLAY_END_DATE
2022-02-02 00:00:00.000     2022-02-06 10:34:01.653

Body:
If you want to select all the rows having both the dates within given range you can try below query:

DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'

SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE between @startdate and @enddate)

Or if you want a where condition to select all the rows from the table which have fully or partially in the range

SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE between @startdate and @enddate) or
(mt.DISPLAY_START_DATE <=@startdate and mt.DISPLAY_END_DATE >=@enddate) or
(mt.DISPLAY_START_DATE <=@startdate and mt.DISPLAY_END_DATE between @startdate and @enddate) or
(mt.DISPLAY_START_DATE between @startdate and @enddate  and mt.DISPLAY_END_DATE >=@enddate)


问:
Rmarkdown PDF: add page number in landscape flextable PDF report
I have

```<code>---
title: ""
header-includes:
  - \usepackage{xcolor}
output: pdf_document
classoption: landscape, a4paper
geometry: left=1cm,right=1cm,top=1cm,bottom=0.2cm

---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(flextable)
library(datasets)
set_flextable_defaults(fonts_ignore=TRUE)
world_phones<-data.frame(WorldPhones)
```

```{r  echo=F}
flextable(world_phones)
```
\hfill \small Report generated:  `r Sys.time() `
</code>```

And I would like to add page numbers at the foot note center (bottom center of the page). If possible I would like to add the page number as Page X of Y.

However even \pagenumbering{arabic} does not seem to work, I suspect because of the narrow margins. How can I achieve this?

答:
You actually do have a page number on your page, but because you made the bottom margin so terrible tiny, you can't see as it gets pushed below the lower page boundary. If you increase your margin, you get the page number back:

```<code>---
title: ""
header-includes:
  - \usepackage{xcolor}
  - \usepackage{fancyhdr}
  - \pagestyle{fancy}
  - \usepackage{lastpage}
  - \fancyfoot[C]{\thepage\ of \pageref{LastPage}}
  - \renewcommand{\headrulewidth}{0pt}
output:
  pdf_document:
    keep_tex: true
classoption: landscape, a4paper
geometry: left=1cm,right=1cm,top=1cm,bottom=2.2cm
---

test
</code>```

Body:
I have

---
title: ""
header-includes:
  - \usepackage{xcolor}
output: pdf_document
classoption: landscape, a4paper
geometry: left=1cm,right=1cm,top=1cm,bottom=0.2cm

---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(flextable)
library(datasets)
set_flextable_defaults(fonts_ignore=TRUE)
world_phones<-data.frame(WorldPhones)
```

```{r  echo=F}
flextable(world_phones)
```
\hfill \small Report generated:  `r Sys.time() `

And I would like to add page numbers at the foot note center (bottom center of the page). If possible I would like to add the page number as Page X of Y.

However even \pagenumbering{arabic} does not seem to work, I suspect because of the narrow margins. How can I achieve this?

Body:
You actually do have a page number on your page, but because you made the bottom margin so terrible tiny, you can't see as it gets pushed below the lower page boundary. If you increase your margin, you get the page number back:

---
title: ""
header-includes:
  - \usepackage{xcolor}
  - \usepackage{fancyhdr}
  - \pagestyle{fancy}
  - \usepackage{lastpage}
  - \fancyfoot[C]{\thepage\ of \pageref{LastPage}}
  - \renewcommand{\headrulewidth}{0pt}
output:
  pdf_document:
    keep_tex: true
classoption: landscape, a4paper
geometry: left=1cm,right=1cm,top=1cm,bottom=2.2cm
---

test


问:
How can I check two arrays at the same index?
I want to determine how many of the items in these two arrays match, then store that in state as a number.

For example

const [score, setScore] = React.useState(0)

const selections = ["one", "two", "three"]
const allCorrectAnswers = ["four", "two", "three"]
// this should return 2
```
<p>I tried</p>
<pre class="lang-js prettyprint-override"><code>function checkSelectedAnswer(selections, allCorrectAnswers) {
  selections.map(eachChoice =>
    eachChoice === allCorrectAnswers.map(eachAnswer => eachAnswer)
      ? setScore(prevScore => prevScore + 1) : 0
  )
}
</code>```

Please explain why my code isn't working as well if you can.

答:
You can use filter method and its second parameter that is index. After you filter for all elements that match in two arrays, you can just return the length property witch will present the number of matches.

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];

const checkSelectedAnswer = (selections, allCorrectAnswers) => selections.filter((eachChoice,index) => eachChoice === allCorrectAnswers[index]).length;

const numberOfCorrectAnswers = checkSelectedAnswer(selections, allCorrectAnswers);
console.log(numberOfCorrectAnswers);```

Body:
I want to determine how many of the items in these two arrays match, then store that in state as a number.

For example

const [score, setScore] = React.useState(0)

const selections = ["one", "two", "three"]
const allCorrectAnswers = ["four", "two", "three"]
// this should return 2

I tried

function checkSelectedAnswer(selections, allCorrectAnswers) {
  selections.map(eachChoice =>
    eachChoice === allCorrectAnswers.map(eachAnswer => eachAnswer)
      ? setScore(prevScore => prevScore + 1) : 0
  )
}

Please explain why my code isn't working as well if you can.


问:
Making an image stay at the bottom of the page but not go over content
I have an a logo image that is supposed to remain at the bottom of a nav drawer. The only way I know to have it be at the bottom is with the absolute and bottom properties, but that's causing it to overlap the list items on a short device (shrink the height of the browser window until scroll bar appears). As soon as the scroll bars appear, the logo will go over top of the list items.

Here's my sandbox with a drawer and random fake image: https://codesandbox.io/s/drawer-with-image-at-bottom-xpuhp

Is there a way to start it at the bottom without using absolute? And/or a way keep it at the bottom until the window height necessitates scroll bars and then have it be part of that scrollable content behavior? If that makes sense. I've played around with variations of flex properties, but I don't really understand it. If I remove absolute it starts way up under the last list item in drawer and I need it at the bottom until scrollbar.

my css for the img:

```<code>logo: {
      width: "220px",
      height: "150px",
      marginLeft: "50px",
      marginRight: "50px",
      bottom: "24px",
      position: "absolute"
    }
</code>```

thanks

答:
Try changing position to relative and bottom to -24px:

```<code>logo: {
      width: "220px",
      height: "150px",
      marginLeft: "50px",
      marginRight: "50px",
      bottom: "-24px",
      position: "realtive"
    }
</code>```

Check out the code sandbox link with these changes. With this you can then tweak the bottom property to whatever you see fit, placing it how far to the bottom you like.

Body:
I have an a logo image that is supposed to remain at the bottom of a nav drawer. The only way I know to have it be at the bottom is with the absolute and bottom properties, but that's causing it to overlap the list items on a short device (shrink the height of the browser window until scroll bar appears). As soon as the scroll bars appear, the logo will go over top of the list items.

Here's my sandbox with a drawer and random fake image: https://codesandbox.io/s/drawer-with-image-at-bottom-xpuhp

Is there a way to start it at the bottom without using absolute? And/or a way keep it at the bottom until the window height necessitates scroll bars and then have it be part of that scrollable content behavior? If that makes sense. I've played around with variations of flex properties, but I don't really understand it. If I remove absolute it starts way up under the last list item in drawer and I need it at the bottom until scrollbar.

my css for the img:

logo: {
      width: "220px",
      height: "150px",
      marginLeft: "50px",
      marginRight: "50px",
      bottom: "24px",
      position: "absolute"
    }

thanks

Body:
Try changing position to relative and bottom to -24px:

logo: {
      width: "220px",
      height: "150px",
      marginLeft: "50px",
      marginRight: "50px",
      bottom: "-24px",
      position: "realtive"
    }

Check out the code sandbox link with these changes. With this you can then tweak the bottom property to whatever you see fit, placing it how far to the bottom you like.


问:
Terminated due to Timeout error in Finding perfect square within a range c++
I am trying to solve Sherlock and Square problem in Hackerrank (link) for finding the perfect square within a range of data. 4 test cases passed but i am getting a timeout error for large numbers. Please suggest something to improve its performance

My code is as follows:

```<code>#include<iostream>
#include<cmath>

using namespace std;

int squares(int a, int b) {
    long double i;
    long long int count=0;
    for(i=a;i<=b;i++)
    {
        long double b = sqrt(i);
        if(fmod(b,1)==0.000000)
        {
            count++;
        }
    }
    return count;
}

int main()
{
    int q,i,a,b;
    cin>>q;
    for(i=0;i<q;i++)
    {
        cin>>a>>b;
        int result = squares(a, b);
        cout<<result<<"\n";
    }
}
</code>```

答:
I realized that the square of the number a is the number of squares between 1 and a. For example a=9 then Math.square(9)=3 (1, 4 and 9). The same way with b.

Here is my code:

```<code>int result=0;
double sqrt_b=Math.sqrt(b);
double sqrt_a=Math.sqrt(a);
int int_sqrt_a=(int)sqrt_a;
if(sqrt_a-int_sqrt_a==0) {
    sqrt_a=sqrt_a-1;
}
result=(int)((int)sqrt_b-(int)sqrt_a);
</code>```

Body:
I am trying to solve Sherlock and Square problem in Hackerrank (link) for finding the perfect square within a range of data. 4 test cases passed but i am getting a timeout error for large numbers. Please suggest something to improve its performance

My code is as follows:

#include<iostream>
#include<cmath>

using namespace std;

int squares(int a, int b) {
    long double i;
    long long int count=0;
    for(i=a;i<=b;i++)
    {
        long double b = sqrt(i);
        if(fmod(b,1)==0.000000)
        {
            count++;
        }
    }
    return count;
}

int main()
{
    int q,i,a,b;
    cin>>q;
    for(i=0;i<q;i++)
    {
        cin>>a>>b;
        int result = squares(a, b);
        cout<<result<<"\n";
    }
}

Body:
I realized that the square of the number a is the number of squares between 1 and a. For example a=9 then Math.square(9)=3 (1, 4 and 9). The same way with b.

Here is my code:

int result=0;
double sqrt_b=Math.sqrt(b);
double sqrt_a=Math.sqrt(a);
int int_sqrt_a=(int)sqrt_a;
if(sqrt_a-int_sqrt_a==0) {
    sqrt_a=sqrt_a-1;
}
result=(int)((int)sqrt_b-(int)sqrt_a);


问:
React Django CORS not working : has been blocked by CORS policy
I've tried all the possible combinations of CORS between react and django api.
it is still not working.

im getting this error

```<code> has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
</code>```

settings.py

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'todos'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
</code>```

view.py

```<code>class StuffViewSet(APIView):

    def post(self, request):
        serializer = StuffSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data = "data saved", status=status.HTTP_201_CREATED)
        return Response(data = "data not saved", status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        snippets = Stuff.objects.all()
        serializer = StuffSerializer(snippets, many=True)
        return Response(data = json.dumps(serializer.data))
</code>```

I am calling the api from react like this

```<code>getAPI(e) {
    const headers = {
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,OPTIONS,POST,PUT"
    }
    axios.get('http://localhost:8000/api', {
        headers: headers
        }).then(function(response) {
            console.log("/api")
            console.log(response.data)
    });
}
</code>```

what did I do wrong here ?

答:
if corsheaders and verything is set correctly ,
please try this

```<code>axios.get('your-api', {headers: { 'Accept': 'application/json' }}).then(res => console.log(res.data).catch(err => alert(err))
</code>```

this worked for me , may work for others and save them from frustration.

Body:
I've tried all the possible combinations of CORS between react and django api.
it is still not working.

im getting this error

 has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'todos'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False

view.py

class StuffViewSet(APIView):

    def post(self, request):
        serializer = StuffSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data = "data saved", status=status.HTTP_201_CREATED)
        return Response(data = "data not saved", status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        snippets = Stuff.objects.all()
        serializer = StuffSerializer(snippets, many=True)
        return Response(data = json.dumps(serializer.data))

I am calling the api from react like this

getAPI(e) {
    const headers = {
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,OPTIONS,POST,PUT"
    }
    axios.get('http://localhost:8000/api', {
        headers: headers
        }).then(function(response) {
            console.log("/api")
            console.log(response.data)
    });
}

what did I do wrong here ?

Body:
if corsheaders and verything is set correctly ,
please try this

axios.get('your-api', {headers: { 'Accept': 'application/json' }}).then(res => console.log(res.data).catch(err => alert(err))

this worked for me , may work for others and save them from frustration.