问:
Search index with python without a loop
I have a list in python, for example A = [-22,-10,0,3,8] and I want to find A[x]=x, that means that the index and number in the list have the same value. In this case x=3 because A[3]=3.

Can I find x without a loop?

EDIT: It's a academic problem and I have a clue "You don't need to visit each position in the array" and the numbers will be ordered and unique

答:
you can use a list comprehension (but that is really just hiding the loop):

this will give you all indexes where A[i] == i:

```<code>indexes = [i for i,a in enumerate(A) if i==a]  # [1, 2, 3]
</code>```

if you only want the first one you can use the next function:

```<code>index = next((i for i,a in enumerate(A) if i==a),None) # 1
</code>```

Title: Search index with python without a loop

Body:
you can use a list comprehension (but that is really just hiding the loop):

this will give you all indexes where A[i] == i:

indexes = [i for i,a in enumerate(A) if i==a]  # [1, 2, 3]

if you only want the first one you can use the next function:

index = next((i for i,a in enumerate(A) if i==a),None) # 1


来源: stackexchange

问:
Is it a good idea to use triggers to link to time dimension in fact tables in a dataware house?
I am in the middle of design a data-ware house. There are multiple fact tables and its highly likely that hundreds of facts are inserted into each fact table. Even though its a bit early but still I was thinking of optimizations.

I have two tables for time

date                      (unique row
for each day)

time of the day           (unique row
for each minute in a day)

in all my fact tables I do have the full date column.

What does your experience say, should I used select statements in code to query the dimension Ids from time dimension table or I allow the time dimension columns in fact tables to be null able and  use triggers  to fill in the values?

答:
Date and time-of-day dimensions are the (very unusual) case in the data warehousing when a surrogate key with "magic" values is beneficial. You can make primary keys in the date dimension integers with values like 20110516 and in the time-of-day dimensions either 1 - 1440 or 1 - 2400.

I suggest calculating corresponding values in your fact records and adding fields for them, say, CALENDAR_ID, TIME_OF_DAY_ID. Depending on the size of your data, you are likely to benefit from indexing on CALENDAR_ID and, maybe, even partitioning on it. If you are sure in the quality of your data, you can skip foreign key constraints on these fields to gain some performance during loading.

ContentLicense: CC BY-SA 3.0


问:
Delete all elements in a list except two o three
Assuming I have this list

```<code> [['GA', 11], ['GO', 25], ['GE', 23], ['DA', 22], ['DE', 33], ['DU', 54], ['DD', 55], ['DF', 27]
</code>```

Given this example of a short list compared to a list of 500 items, how could I remove all items from this list except for GA, GO?

ContentLicense: CC BY-SA 4.0

Body:
Assuming I have this list

 [['GA', 11], ['GO', 25], ['GE', 23], ['DA', 22], ['DE', 33], ['DU', 54], ['DD', 55], ['DF', 27]

Given this example of a short list compared to a list of 500 items, how could I remove all items from this list except for GA, GO?

Body:
Use sets for lookup

[i for i in [['GA', 11], ['GO', 25], ['GE', 23], ['DA', 22], ['DE', 33], ['DU', 54], ['DD', 55], ['DF', 27]] if i[0] in {'GA','GO'}]

Output

[['GA', 11], ['GO', 25]]


问:
Only run JavaScript function once
When a button is clicked, I'm displaying an image (in a JS function) however the function prints the image every time the button is clicked. I want the function to run only once so that the image can only be displayed once. What do I need to add to my code to do this?</p>

```<code><button class="colour-btn colour-btn--3" onClick="showImage3()"></button>
</code>```

```<code>function showImage3() {
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}
</code>```

答:
You can redefine the function once it is run the first time so it only runs once.</p>

```<code>function showImage3() {
    showImage3 = function() {};
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}
</code>```

Title: Only run JavaScript function once

Body:
When a button is clicked, I'm displaying an image (in a JS function) however the function prints the image every time the button is clicked. I want the function to run only once so that the image can only be displayed once. What do I need to add to my code to do this?

<button class="colour-btn colour-btn--3" onClick="showImage3()"></button>

function showImage3() {
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}

Body:
You can redefine the function once it is run the first time so it only runs once.

function showImage3() {
    showImage3 = function() {};
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}


问:
Cant assign missing values to string variable in SPSS using the GUI
I am strugling recoding missing values in SPSS using the graphical user interface.
I can easily recode numeric variables using the GUI and the dialogue box shown below:

But when i enter a string variable into the same dialogue box the option to define the new value as "System-missing" is not available:

Surely such a simple problem can be solved without using the syntax editor?

Im using SPSS version 19

答:
First open syntax editor

MISSING VALUES NAME_VAR1,NAME_VAR2 ("  ").
EXECUTE

Now you can easily recode string variables using the GUI.

IMPORTANT!!! only with variables whose length is eight or less


问:
How to detect dynamically changed input
I am working on the below snippet. Why am I not able to detect the input change using this?

```<code>$("#fname").on("change", function () {
   console.log("The text has been changed.");
});
</code>```

$("button").on("click", function () {
    $("#fname").text('Alex');
    $("#fname").val('Alex');
});

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input type="text" id="fname" name="fname"><br><br>
<button type="button">Click Me!</button></code>```

答:
You have to trigger change programmatically if you are applying the change programmatically.

$("button").on("click", function () {
    $("#fname").text('Alex').trigger('change');
    $("#fname").val('Alex').trigger('change');
});

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input type="text" id="fname" name="fname"><br><br>
<button type="button">Click Me!</button></code>```

Title: How to detect dynamically changed input

Body:
I am working on the below snippet. Why am I not able to detect the input change using this?

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});

$("button").on("click", function () {
    $("#fname").text('Alex');
    $("#fname").val('Alex');
});

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});

 <input type="text" id="fname" name="fname">

<button type="button">Click Me!</button>

Body:
You have to trigger change programmatically if you are applying the change programmatically.

$("button").on("click", function () {
    $("#fname").text('Alex').trigger('change');
    $("#fname").val('Alex').trigger('change');
});

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input type="text" id="fname" name="fname"><br><br>
<button type="button">Click Me!</button>


问:
How to set eval metrics for xgboost.train?
How can I set xgboost.train to opitimize for a specific evaluation metric similar to how I can set xgboost.fit(eval_metric = 'auc')?</p>

答:
See the document here. Where you can find metrics xgboost support under eval_metric.

If you want to use a custom objective function or metric see here.


问:
Pass values to fields from Screen Manager screens issue
I am developing Android app. It has about 40 screens. I have the Barcode scanner, it should be in about 20 of these screens. I need to pass value from barcode scanner screen to other screens with TextInput. Currently, I added to one screen:

```<code>labScreen = "page3"
self.manager.get_screen(labScreen).ids.labBarcode.text = self.barcodeData
self.manager.current = labScreen
</code>```

This code works, but it will require to create for every page new Barcode scanner screen + design and it is bad practice (concept), since I need to repeat myself. I want to use OOP (Object Oriented Programming), for example call/use it once and get data to TextInput fields from different screens. How to do it? Thanks.

答:
OK. I have fixed it by using:

```<code>MDApp.get_running_app().barcodeValue = self.barcodeData
self.manager.current = MDApp.get_running_app().previousScreen
</code>```

And set the previous screen as:

```<code>MDApp.get_running_app().previousScreen = self.manager.current
</code>```

Now it works well. The issue is resolved.

Body:
I am developing Android app. It has about 40 screens. I have the Barcode scanner, it should be in about 20 of these screens. I need to pass value from barcode scanner screen to other screens with TextInput. Currently, I added to one screen:

labScreen = "page3"
self.manager.get_screen(labScreen).ids.labBarcode.text = self.barcodeData
self.manager.current = labScreen

This code works, but it will require to create for every page new Barcode scanner screen + design and it is bad practice (concept), since I need to repeat myself. I want to use OOP (Object Oriented Programming), for example call/use it once and get data to TextInput fields from different screens. How to do it? Thanks.

Body:
OK. I have fixed it by using:

MDApp.get_running_app().barcodeValue = self.barcodeData
self.manager.current = MDApp.get_running_app().previousScreen

And set the previous screen as:

MDApp.get_running_app().previousScreen = self.manager.current

Now it works well. The issue is resolved.


问:
How to run multiple gremlin commands as a single transaction?
In Amazon Neptune I would like to run multiple Gremlin commands in Java as a single transactions. The document says that tx.commit() and tx.rollback() is not supported. It suggests this - Multiple statements separated by a semicolon (;) or a newline character (\n) are included in a single transaction.

Example from the document show that Gremlin is supported in Java but I don't understand how to "Multiple statements separated by a semicolon"

GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(cluster));

```<code>    // Add a vertex.
    // Note that a Gremlin terminal step, e.g. next(), is required to make a request to the remote server.
    // The full list of Gremlin terminal steps is at https://tinkerpop.apache.org/docs/current/reference/#terminal-steps
    g.addV("Person").property("Name", "Justin").next();

    // Add a vertex with a user-supplied ID.
    g.addV("Custom Label").property(T.id, "CustomId1").property("name", "Custom id vertex 1").next();
    g.addV("Custom Label").property(T.id, "CustomId2").property("name", "Custom id vertex 2").next();

    g.addE("Edge Label").from(g.V("CustomId1")).to(g.V("CustomId2")).next();
</code>```

答:
You can also use the SessionedClient, which will run all queries in the same transaction upon close().  </p>

<p>More information is here: https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-gremlin-sessions.html#access-graph-gremlin-sessions-glv </p>

Body:
In Amazon Neptune I would like to run multiple Gremlin commands in Java as a single transactions. The document says that tx.commit() and tx.rollback() is not supported. It suggests this - Multiple statements separated by a semicolon (;) or a newline character (\n) are included in a single transaction.

Example from the document show that Gremlin is supported in Java but I don't understand how to "Multiple statements separated by a semicolon"

GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(cluster));

    // Add a vertex.
    // Note that a Gremlin terminal step, e.g. next(), is required to make a request to the remote server.
    // The full list of Gremlin terminal steps is at https://tinkerpop.apache.org/docs/current/reference/#terminal-steps
    g.addV("Person").property("Name", "Justin").next();

    // Add a vertex with a user-supplied ID.
    g.addV("Custom Label").property(T.id, "CustomId1").property("name", "Custom id vertex 1").next();
    g.addV("Custom Label").property(T.id, "CustomId2").property("name", "Custom id vertex 2").next();

    g.addE("Edge Label").from(g.V("CustomId1")).to(g.V("CustomId2")).next();

Body:
You can also use the SessionedClient, which will run all queries in the same transaction upon close().

More information is here: https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-gremlin-sessions.html#access-graph-gremlin-sessions-glv


问:
Unable to delete kafka topic
I am using kafka, zookeeper and kafka-manager for managing clusters.

I have 3 nodes cluster. In all the cluster I set since very beginning delete.topic.enable=true

Now when I want to delete a topic it is showing following error.

topicxyz - marked for deletion

but it is not deleted.

I tried to delete from kafka-manager also and it says

Yikes! KeeperErrorCode = NodeExists for /admin/delete_topics/topicxyz

Error logs:

kafka-manager:

```<code>[ESC[31merrorESC[0m] k.m.ApiError$ - error : KeeperErrorCode = NodeExists for /admin/delete_topics/topicxyz
org.apache.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /admin/delete_topics/topicxyz
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:119) ~[org.apache.zookeeper.zookeeper-3.4.6.jar:3.4.6-1569965]
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:51) ~[org.apache.zookeeper.zookeeper-3.4.6.jar:3.4.6-1569965]
        at org.apache.zookeeper.ZooKeeper.create(ZooKeeper.java:783) ~[org.apache.zookeeper.zookeeper-3.4.6.jar:3.4.6-1569965]
        at org.apache.curator.framework.imps.CreateBuilderImpl$11.call(CreateBuilderImpl.java:721) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl$11.call(CreateBuilderImpl.java:704) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:108) ~[org.apache.curator.curator-client-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl.pathInForeground(CreateBuilderImpl.java:701) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl.protectedPathInForeground(CreateBuilderImpl.java:477) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:467) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:447) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
[ESC[37minfoESC[0m] k.m.a.KafkaManagerActor - Updating internal state...
</code>```

kafka has no error log. zookeeper stdout errorlog says only warning and stderr log says Invalid config, exiting abnormally

kafka-version:  kafka_2.12-0.10.2.0

Topic description:

```<code> $ bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic topicxyz
Topic:topicxyz  PartitionCount:1    ReplicationFactor:1 Configs:
    Topic: topicxyz Partition: 0    Leader: -1  Replicas: 3 Isr:
</code>```

Please help.

答:
This is sometimes caused by a corrupt ZooKeeper node found within /admin/delete_topics. Log into the ZK client and delete the misbehaving /admin/delete_topics/your_topic_name entry.
Depending on client version it will go something like this:

bin/zkCli.sh -server 127.0.0.1:2181
ls /admin/delete_topics
ls /brokers/topics
rmr /admin/delete_topics/your_topic_name

You should now be able to use Kafka Manager or Kafka-topics to delete your topics. You can also manually remove your topic by deleting the "/brokers/topics/your_topic_name" entry but I find that is unnecessary after removing the misbehaving "delete_topics" entry.

Title: Unable to delete kafka topic

Body:
I am using kafka, zookeeper and kafka-manager for managing clusters.

I have 3 nodes cluster. In all the cluster I set since very beginning delete.topic.enable=true

Now when I want to delete a topic it is showing following error.

topicxyz - marked for deletion

but it is not deleted.

I tried to delete from kafka-manager also and it says

Yikes! KeeperErrorCode = NodeExists for /admin/delete_topics/topicxyz

Error logs:

kafka-manager:

[ESC[31merrorESC[0m] k.m.ApiError$ - error : KeeperErrorCode = NodeExists for /admin/delete_topics/topicxyz
org.apache.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /admin/delete_topics/topicxyz
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:119) ~[org.apache.zookeeper.zookeeper-3.4.6.jar:3.4.6-1569965]
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:51) ~[org.apache.zookeeper.zookeeper-3.4.6.jar:3.4.6-1569965]
        at org.apache.zookeeper.ZooKeeper.create(ZooKeeper.java:783) ~[org.apache.zookeeper.zookeeper-3.4.6.jar:3.4.6-1569965]
        at org.apache.curator.framework.imps.CreateBuilderImpl$11.call(CreateBuilderImpl.java:721) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl$11.call(CreateBuilderImpl.java:704) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:108) ~[org.apache.curator.curator-client-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl.pathInForeground(CreateBuilderImpl.java:701) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl.protectedPathInForeground(CreateBuilderImpl.java:477) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:467) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
        at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:447) ~[org.apache.curator.curator-framework-2.10.0.jar:na]
[ESC[37minfoESC[0m] k.m.a.KafkaManagerActor - Updating internal state...

kafka has no error log. zookeeper stdout errorlog says only warning and stderr log says Invalid config, exiting abnormally

kafka-version:  kafka_2.12-0.10.2.0

Topic description:

 $ bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic topicxyz
Topic:topicxyz  PartitionCount:1    ReplicationFactor:1 Configs:
    Topic: topicxyz Partition: 0    Leader: -1  Replicas: 3 Isr:

Please help.


问:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.jalin.bank.model.Trx
My SQL goes like this select trx_date, card_number , count(card_number) as amount from trx_data_cons where trx_date ='161222' group by trx_date, card_number;

trx_date || card_number || amount

YYmmdd      xxxxx         x

and my HQL is like this

```<code>public List<Trx> listTrx() {

        List<Trx> list = (List<Trx>) getHibernateTemplate().find(
              "select trxD, trxC, count(trxC) from Trx where trxD = '161222' group by trxD, trxC");
    return list;
    }
</code>```

My Trx.java is

```<code>@Override
    public String toString() {
        return " || " + trxD+" || "+ trxC + " ||";
    }
</code>```

but how and where should i put the result of the count??

my main class is

```<code>List<Trx> list = trxBo.listTrx();
        for(Trx t1:list) {
            System.out.println(t1.toString());
        }
</code>```

i mean, i should define the count right? put it in the model..? but how to retrieve the result of the count??

答:
Since you are querying specific fields of an entity (and in this case, also an aggregation i.e. count), you'll get a List<Object[]> and not List<trx>. Hence the cast exception.

You can however define a DTO which just has the specific fields that you are querying from Trx entity (assuming trxD and trxC are of type String)

```<code>public class DTO {
     private String trxD;
     private String trxC;
     private Long countTrxC;
}
</code>```

and then use a ResultTransformer to transform the query results into the DTO class objects.

```<code>public List<DTO> getTrxData() {
     String queryStr = "select trx.trxD as trxD, trx.trxC as trxC, count(trx.trxC) as countTrxC from Trx trx where trx.trxD = '161222' group by trx.trxD, trx.trxC";
     Query query = sessionFactory.getCurrentSession().createQuery(queryStr);
     query.setResultTransformer(Transformers.aliasToBean(DTO.class));
     return query.list();
}
</code>```

Body:
My SQL goes like this select trx_date, card_number , count(card_number) as amount from trx_data_cons where trx_date ='161222' group by trx_date, card_number;

trx_date || card_number || amount

YYmmdd      xxxxx         x

and my HQL is like this

public List<Trx> listTrx() {

        List<Trx> list = (List<Trx>) getHibernateTemplate().find(
              "select trxD, trxC, count(trxC) from Trx where trxD = '161222' group by trxD, trxC");
    return list;
    }

My Trx.java is

@Override
    public String toString() {
        return " || " + trxD+" || "+ trxC + " ||";
    }

but how and where should i put the result of the count??

my main class is

List<Trx> list = trxBo.listTrx();
        for(Trx t1:list) {
            System.out.println(t1.toString());
        }

i mean, i should define the count right? put it in the model..? but how to retrieve the result of the count??

Body:
Since you are querying specific fields of an entity (and in this case, also an aggregation i.e. count), you'll get a List<Object[]> and not List<trx>. Hence the cast exception.

You can however define a DTO which just has the specific fields that you are querying from Trx entity (assuming trxD and trxC are of type String)

public class DTO {
     private String trxD;
     private String trxC;
     private Long countTrxC;
}

and then use a ResultTransformer to transform the query results into the DTO class objects.

public List<DTO> getTrxData() {
     String queryStr = "select trx.trxD as trxD, trx.trxC as trxC, count(trx.trxC) as countTrxC from Trx trx where trx.trxD = '161222' group by trx.trxD, trx.trxC";
     Query query = sessionFactory.getCurrentSession().createQuery(queryStr);
     query.setResultTransformer(Transformers.aliasToBean(DTO.class));
     return query.list();
}


问:
ASP.NET MVC: Model in strongly typed view not populating
I am brand spanking new to ASP.NET MVC and I'm working through a tutorial to get the basics.  The tutorial is in C# and I'm converting it to VB to stay consistent with some related projects.  I have to assume that I'm missing something in that conversion but can't figure out what it could be.

I have the following class:

```<code>Public Class GuestResponse
    Public Name As String
    Public Email As String
    Public Phone As String
    Public WillAttend As Boolean?
End Class
</code>```

and a strongly-typed view related to that class:

```<code>@ModelType PartyInvites.GuestResponse

@Code
    Layout = Nothing
End Code

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>RsvpForm</title>
</head>
<body>
    @Using Html.BeginForm
        @<p>Your name: @Html.TextBoxFor(Of String)(Function(x) x.Name)</p>
        @<p>Your email: @Html.TextBoxFor(Of String)(Function(x) x.Email)</p>
        @<p>Your phone: @Html.TextBoxFor(Of String)(Function(x) x.Phone)</p>
        @<p>
            Will you attend?
            @Html.DropDownListFor(Of Boolean?)(Function(x) x.WillAttend,
                                                        New SelectListItem() {New SelectListItem With {.Text = "Yes, I'll be there", .Value = Boolean.TrueString},
                                                        New SelectListItem With {.Text = "No, I can't come", .Value = Boolean.FalseString}}, "Choose an option")
        </p>
        @<input type="submit" value="Submit RSVP" />
    End Using
</body>
</html>
</code>```

My controller has a simple action method that takes that class and responds with another view:

```<code><HttpPost>
Function RsvpForm(g As GuestResponse) As ViewResult
    'TODO: Email response to the party organizer
    Return View("Thanks", g)
End Function
</code>```

Unfortunately, the form data from the post request isn't being populated in my GuestResponse class.  If I insert a breakpoint in that action method, all the GuestResponse properties are empty.  At the same time, the Request.Form values look as expected - they're just not filling in the GuestResponse object.

I'm sure it's something small I'm missing.  Any help is appreciated.

答:
I've figured it out.  Apparently, ASP.NET will only populate properties of an object - my object only had public fields.

So this:

```<code>Public Class GuestResponse
    Public Name As String
    Public Email As String
    Public Phone As String
    Public WillAttend As Boolean?
End Class
</code>```

should be:

```<code>Public Class GuestResponse
    Public Property Name As String
    Public Property Email As String
    Public Property Phone As String
    Public Property WillAttend As Boolean?
End Class
</code>```

Thanks to those of you who participated.

Body:
I am brand spanking new to ASP.NET MVC and I'm working through a tutorial to get the basics.  The tutorial is in C# and I'm converting it to VB to stay consistent with some related projects.  I have to assume that I'm missing something in that conversion but can't figure out what it could be.

I have the following class:

Public Class GuestResponse
    Public Name As String
    Public Email As String
    Public Phone As String
    Public WillAttend As Boolean?
End Class

and a strongly-typed view related to that class:

@ModelType PartyInvites.GuestResponse

@Code
    Layout = Nothing
End Code

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>RsvpForm</title>

    @Using Html.BeginForm
        @
Your name: @Html.TextBoxFor(Of String)(Function(x) x.Name)

        @
Your email: @Html.TextBoxFor(Of String)(Function(x) x.Email)

        @
Your phone: @Html.TextBoxFor(Of String)(Function(x) x.Phone)

        @

            Will you attend?
            @Html.DropDownListFor(Of Boolean?)(Function(x) x.WillAttend,
                                                        New SelectListItem() {New SelectListItem With {.Text = "Yes, I'll be there", .Value = Boolean.TrueString},
                                                        New SelectListItem With {.Text = "No, I can't come", .Value = Boolean.FalseString}}, "Choose an option")

        @<input type="submit" value="Submit RSVP" />
    End Using

My controller has a simple action method that takes that class and responds with another view:

<HttpPost>
Function RsvpForm(g As GuestResponse) As ViewResult
    'TODO: Email response to the party organizer
    Return View("Thanks", g)
End Function

Unfortunately, the form data from the post request isn't being populated in my GuestResponse class.  If I insert a breakpoint in that action method, all the GuestResponse properties are empty.  At the same time, the Request.Form values look as expected - they're just not filling in the GuestResponse object.

I'm sure it's something small I'm missing.  Any help is appreciated.

Body:
I've figured it out.  Apparently, ASP.NET will only populate properties of an object - my object only had public fields.

So this:

Public Class GuestResponse
    Public Name As String
    Public Email As String
    Public Phone As String
    Public WillAttend As Boolean?
End Class

should be:

Public Class GuestResponse
    Public Property Name As String
    Public Property Email As String
    Public Property Phone As String
    Public Property WillAttend As Boolean?
End Class

Thanks to those of you who participated.


答:
This gets Python to do the looping for you:</p>

```<code>list(map(lambda x: x[0], filter(lambda x: x[0] == x[1], enumerate([-2,1,2,3,8]))))
# [1, 2, 3]
</code>```

Title: Search index with python without a loop

Body:
I have a list in python, for example A = [-22,-10,0,3,8] and I want to find A[x]=x, that means that the index and number in the list have the same value. In this case x=3 because A[3]=3.

Can I find x without a loop?

EDIT: It's a academic problem and I have a clue "You don't need to visit each position in the array" and the numbers will be ordered and unique

Body:
This gets Python to do the looping for you:

list(map(lambda x: x[0], filter(lambda x: x[0] == x[1], enumerate([-2,1,2,3,8]))))
# [1, 2, 3]


问:
How to update product quantity after 'approved' status?
I have these tables:

products:

```<code>id - name - quantity - etc
2    watch      4
4    T-shirt    2
</code>```

orders:

```<code>id - user_id - address_id - etc
</code>```

pivot table between them called order_product

```<code>order_id - product_id - quantity
  1          2            3
  1          4            1
</code>```

The relation:

```<code>/**
 * Products table relation
 */
public function products()
{
    return $this->belongsToMany('App\Models\Product')->withPivot('quantity');
}

 /**
 * Orders table relation
 */
public function orders()
{
    return $this->belongsToMany('App\Models\Order')->withPivot('quantity');
}
</code>```

I need when I update the status to approved then update my quantity product!

My shut: ( Here I'm confused because the product can be many! the quantity as well )

```<code>public function status_orders(Order $order ,Request $request)
{

if($request->status == 'approved'){

  $product_quantity = $order->products->pluck('quantity');

   foreach($order->products as $order){
        $order_quantity = $order->pivot->quantity;
    }

    $final_quantity = $product_quantity - $order_quantity;

 }
}
</code>```

答:
you want to update product table quantity after an order is approved. right?? you can do it the following way</p>

```<code>public function status_orders(Order $order ,Request $request) {
    if($request->status == 'approved') {
        foreach($order->products as $product) {
            $product->update([
                'quantity' => $product->quantity - $product->pivot->quantity
            ]);
        }
    }
}
</code>```

Body:
I have these tables:

products:

id - name - quantity - etc
2    watch      4
4    T-shirt    2

orders:

id - user_id - address_id - etc

pivot table between them called order_product

order_id - product_id - quantity
  1          2            3
  1          4            1

The relation:

/**
 * Products table relation
 */
public function products()
{
    return $this->belongsToMany('App\Models\Product')->withPivot('quantity');
}

 /**
 * Orders table relation
 */
public function orders()
{
    return $this->belongsToMany('App\Models\Order')->withPivot('quantity');
}

I need when I update the status to approved then update my quantity product!

My shut: ( Here I'm confused because the product can be many! the quantity as well )

public function status_orders(Order $order ,Request $request)
{

if($request->status == 'approved'){

  $product_quantity = $order->products->pluck('quantity');

   foreach($order->products as $order){
        $order_quantity = $order->pivot->quantity;
    }

    $final_quantity = $product_quantity - $order_quantity;

 }
}

Body:
you want to update product table quantity after an order is approved. right?? you can do it the following way

public function status_orders(Order $order ,Request $request) {
    if($request->status == 'approved') {
        foreach($order->products as $product) {
            $product->update([
                'quantity' => $product->quantity - $product->pivot->quantity
            ]);
        }
    }
}


问:
Split array into different size chunks (4, 3, 3, 3, 4, 3, 3, 3, etc)
I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

```<code>[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]
</code>```

I have tried with this code I have customized:

```<code>const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);
</code>```

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

```<code>[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]
</code>```

答:
You could take two indices, one for the data array and one for sizes. Then slice the array with a given length and push the chunk to the chunks array.

Proceed until end of data.

var data = Array.from({ length: 26 }, (_, i) => i + 1),
    sizes = [4, 3, 3, 3],
    i = 0,
    j = 0,
    chunks = [];

while (i < data.length) chunks.push(data.slice(i, i += sizes[j++ % sizes.length]));

console.log(chunks);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]

I have tried with this code I have customized:

const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]

Body:
You could take two indices, one for the data array and one for sizes. Then slice the array with a given length and push the chunk to the chunks array.

Proceed until end of data.

var data = Array.from({ length: 26 }, (_, i) => i + 1),
    sizes = [4, 3, 3, 3],
    i = 0,
    j = 0,
    chunks = [];

while (i < data.length) chunks.push(data.slice(i, i += sizes[j++ % sizes.length]));

console.log(chunks);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to fix sqlpackage failure to restore bacpac file to Linux, but not Windows
I have a .bacpac file from an Azure SQL database and I'm trying to install it into SQL Server 2019 for Linux with this command:

```<code>sqlpackage /Action:Import /tsn:h-dev /tu:sa /tp:{sa password} /tdn:G_External /sf:G_External.bacpac
</code>```

This creates this output:

```<code>Importing to database 'G_External' on server 'h-dev'.
Creating deployment plan
Initializing deployment
*** The source contains users that rely on an external authentication provider that is not supported by the target. These users will be treated as users without logins.
Time elapsed 00:00:24.07
*** An unexpected failure occurred: Object reference not set to an instance of an object.
</code>```

When I do the same into an installation of SQL Server 2019 on Windows 10, it works:

```<code>SqlPackage.exe /Action:Import /tsn:DESKTOP-NM51MHA /tdn:G_External /sf:G_External.bacpac

Importing to database 'G_External' on server 'DESKTOP-NM51MHA'.
Creating deployment plan
Initializing deployment
*** The source contains users that rely on an external authentication provider that is not supported by the target. These users will be treated as users without logins.
Verifying deployment plan
Analyzing deployment plan
Importing package schema and data into database
Updating database
Importing data
Processing Import.
...
Successfully imported database.
Time elapsed 00:01:45.27
</code>```

How do I fix this? Alternatively, how can I get further information from sqlpackage in order to diagnose what's wrong?

SQLServer versions:

Linux:

```<code>sqlcmd -S localhost -U sa -P {sa password} -Q "SELECT @@VERSION"

Microsoft SQL Server 2019 (RTM-CU1) (KB4527376) - 15.0.4003.23 (X64)
    Dec  6 2019 14:53:33
    Copyright (C) 2019 Microsoft Corporation
    Developer Edition (64-bit) on Linux (Ubuntu 16.04.6 LTS) <X64>
</code>```

Windows:

```<code>SQLCMD.EXE -S localhost -Q "SELECT @@VERSION"

Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64)
        Sep 24 2019 13:48:23
        Copyright (C) 2019 Microsoft Corporation
        Developer Edition (64-bit) on Windows 10 Home 10.0 <X64> (Build 18363: ) (Hypervisor)
</code>```

答:
For anyone else who may be encountering this vague error message when using sqlpackage, there is a /Diagnostics switch that will dump out A LOT of debug messages of exactly what sqlpackage is doing.

/Diagnostics:true -> print out the diagnostic information

/Diagnostics:false -> print out only result information (default)

Using this switch should help you determine exactly where in the backup file the error is occurring. This switch appears in at least as far back as v17.4.0, but possibly earlier. v17.4.0 is as far back as the current release history shows.

Body:
I have a .bacpac file from an Azure SQL database and I'm trying to install it into SQL Server 2019 for Linux with this command:

sqlpackage /Action:Import /tsn:h-dev /tu:sa /tp:{sa password} /tdn:G_External /sf:G_External.bacpac

This creates this output:

Importing to database 'G_External' on server 'h-dev'.
Creating deployment plan
Initializing deployment
*** The source contains users that rely on an external authentication provider that is not supported by the target. These users will be treated as users without logins.
Time elapsed 00:00:24.07
*** An unexpected failure occurred: Object reference not set to an instance of an object.

When I do the same into an installation of SQL Server 2019 on Windows 10, it works:

SqlPackage.exe /Action:Import /tsn:DESKTOP-NM51MHA /tdn:G_External /sf:G_External.bacpac

Importing to database 'G_External' on server 'DESKTOP-NM51MHA'.
Creating deployment plan
Initializing deployment
*** The source contains users that rely on an external authentication provider that is not supported by the target. These users will be treated as users without logins.
Verifying deployment plan
Analyzing deployment plan
Importing package schema and data into database
Updating database
Importing data
Processing Import.
...
Successfully imported database.
Time elapsed 00:01:45.27

How do I fix this? Alternatively, how can I get further information from sqlpackage in order to diagnose what's wrong?

SQLServer versions:

Linux:

sqlcmd -S localhost -U sa -P {sa password} -Q "SELECT @@VERSION"

Microsoft SQL Server 2019 (RTM-CU1) (KB4527376) - 15.0.4003.23 (X64)
    Dec  6 2019 14:53:33
    Copyright (C) 2019 Microsoft Corporation
    Developer Edition (64-bit) on Linux (Ubuntu 16.04.6 LTS) <X64>

Windows:

SQLCMD.EXE -S localhost -Q "SELECT @@VERSION"

Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64)
        Sep 24 2019 13:48:23
        Copyright (C) 2019 Microsoft Corporation
        Developer Edition (64-bit) on Windows 10 Home 10.0 <X64> (Build 18363: ) (Hypervisor)


问:
Is there a semantic query tool for java/java IDEs?
For analyzing/refactoring tasks, I need some kind of semantic query tool (or eclipse plugin) for java to answer questions like:

Which classes call the equals() method
  of classes which reside in a package
  which name matches a specific pattern?

(or even more complex questions)

Are there some tools for these kind of jobs?

答: you can try and use the twouse plugin ,sparqlas will provide you the query support....</p>


问:
update existing model in DB
Hi every one I have an issue I want to update a specific model in the db like I want the user to
 change their phone number and picture...etc specific one not all the model and I am unable to do that in views.py, below is my code, can help pls?

models.py:

```<code>    # Create your models here.

    PHONE_REGEX = '^[0-9]*$'

    class Profile(AbstractUser):
        phone_number = models.CharField(
            max_length=14,
            help_text='Optional',
            blank=True,
            validators=[
                RegexValidator(
                    regex=PHONE_REGEX,
                    message=
                    'phone number must be only digit and from 10 to 14 digits only',
                    code='invalid-phone number'),
                MinLengthValidator(10)
            ])
        picture = models.ImageField(upload_to='upload/', blank=True, default=False)
        email = models.EmailField(max_length=254,
                                  unique=True,
                                  help_text='Required, pls enter a valid Email')
</code>```

forms.py:

```<code> class Change_pic_form(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('picture', )
</code>```

Views.py
here snippet of it

```<code>@login_required
def Change_picture(request):
    instance = Profile.objects.get(pk=request.user.pk)
    form = Change_pic_form(request.POST or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return redirect('change_pic')
    else:
        form = Change_pic_form(instance=instance)
    context = {
        'picture': instance.picture,
        'form': form,
        'instance': instance,
    }
    return render(request, 'account/change_picture.html', context)
</code>```

will maybe I didn't make it clear sorry for that, my site work OK I have login ,sign up ...etc, what I meant is I have user profile page where user can see his info and I want the user if he want to update his info like phone number , picture...etc

答:
Thanks anybody helped, I found the solution as for image or file you have to write in view
request.FILES and in your form that inside the template enctype="multipart/form-data"
its work fine now.

Views.py

```<code>def Change_picture(request, pk):
    prof = get_object_or_404(Profile, pk=pk)
    if request.method == "POST":
        form = Change_pic_form(request.POST,
                               request.FILES,
                               instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, f'Your Picture updated successfully')
            return redirect('profile')
    else:
        form = Change_pic_form(instance=request.user)
    return render(request, 'account/change_picture.html', {
        'prof': prof,
        'form': form
    })
</code>```

the Template

```<code><form enctype="multipart/form-data" method="POST">
            {% csrf_token %}
            <br />
            {{ form.as_p }}
            <button type="submit">Change!</button>
        </form>
</code>```

Title: update existing model in DB

Body:
Hi every one I have an issue I want to update a specific model in the db like I want the user to
 change their phone number and picture...etc specific one not all the model and I am unable to do that in views.py, below is my code, can help pls?

models.py:

    # Create your models here.

    PHONE_REGEX = '^[0-9]*$'

    class Profile(AbstractUser):
        phone_number = models.CharField(
            max_length=14,
            help_text='Optional',
            blank=True,
            validators=[
                RegexValidator(
                    regex=PHONE_REGEX,
                    message=
                    'phone number must be only digit and from 10 to 14 digits only',
                    code='invalid-phone number'),
                MinLengthValidator(10)
            ])
        picture = models.ImageField(upload_to='upload/', blank=True, default=False)
        email = models.EmailField(max_length=254,
                                  unique=True,
                                  help_text='Required, pls enter a valid Email')

forms.py:

 class Change_pic_form(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('picture', )

Views.py
here snippet of it

@login_required
def Change_picture(request):
    instance = Profile.objects.get(pk=request.user.pk)
    form = Change_pic_form(request.POST or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return redirect('change_pic')
    else:
        form = Change_pic_form(instance=instance)
    context = {
        'picture': instance.picture,
        'form': form,
        'instance': instance,
    }
    return render(request, 'account/change_picture.html', context)

will maybe I didn't make it clear sorry for that, my site work OK I have login ,sign up ...etc, what I meant is I have user profile page where user can see his info and I want the user if he want to update his info like phone number , picture...etc

Body:
Thanks anybody helped, I found the solution as for image or file you have to write in view
request.FILES and in your form that inside the template enctype="multipart/form-data"
its work fine now.

Views.py

def Change_picture(request, pk):
    prof = get_object_or_404(Profile, pk=pk)
    if request.method == "POST":
        form = Change_pic_form(request.POST,
                               request.FILES,
                               instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, f'Your Picture updated successfully')
            return redirect('profile')
    else:
        form = Change_pic_form(instance=request.user)
    return render(request, 'account/change_picture.html', {
        'prof': prof,
        'form': form
    })

the Template

<form enctype="multipart/form-data" method="POST">
            {% csrf_token %}
            <br />
            {{ form.as_p }}
            <button type="submit">Change!</button>
        </form>


问:
How can I return 3 degrees of precision from oracle number?
We have a scientific application that is in Access and I migrating to Oracle.  Access datatype is Number.  Oracle is number (20,12).

The data is small numbers that we what to show to user in a report as 1.000 E-5 for example.

However the number is actually something like 0.0000099999 which is 0.99999 E-5.

I can convert the number to scientific notation but it returns 0.99999 E-5 without rounding.  I'd like to be able to round this number.  Unfortunately the numbers are all over in terms of # of decimal points.  For example:

0.9999E-5

0.9999E-10

So just a straight ROUND(N,X) would not work I think.  I want to both round to 3 decimals and show in scientific notation.  Essentially this is the scientific concept of degrees of precision where the # of decimals varies but your # of significant figures is always 3.

Body:
I think this is what you want?

select to_char(0.0000099999 , '9.999EEEE') from dual

1.000E-05

select to_char(0.0000000000099999 , '9.999EEEE') from dual

1.000E-11


问:
When running an Async/Await Experiment, operations do not occur in expected order
I have created an experiment (run in XUnit) to test output. I use three methods - the test method, an asynchronous method that calls await, and an inner Task that sleeps for 5 seconds.

```<code>    [Fact]
    public void TestAsyncRunning()
    {
        _testOutput.WriteLine("Beginning Test");
        _testOutput.WriteLine("Calling RunningAsync");

        var t = RunningAsync();

        _testOutput.WriteLine("In outer method, after calling async method");

        t.Wait(); //IOW, Thread.Join();

        _testOutput.WriteLine("Exiting Test");
    }

    private async Task RunningAsync()
    {
        _testOutput.WriteLine("RunningAsync: Enter Method");
        _testOutput.WriteLine("RunningAsync: Calling and awaiting inner running");
        await InnerRunning();
        _testOutput.WriteLine("RunningAsync: Returning");
    }

    private Task InnerRunning()
    {
        _testOutput.WriteLine("InnerRunning: Begin method");
        _testOutput.WriteLine("InnerRunning: Sleeping For 5 seconds");
        var t = Task.Run(() => Thread.Sleep(5000));
        _testOutput.WriteLine("InnerRunning: Wake up and exit");
        return t;
    }
</code>```

In the following output, the lines with the asterisks is where the unexpected order occurs.

The output I expect is

```<code>Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*In outer method, after calling async method
*InnerRunning: Wake up and exit
RunningAsync: Returning
Exiting Test
</code>```

The output I get is

```<code>Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*InnerRunning: Wake up and exit
*In outer method, after calling async method
RunningAsync: Returning
Exiting Test
</code>```

It appears that the async method is actually running async but the method it calls is running synchronously. Does this have to do with the TaskScheduler? I am clearly missing something...….

答:
Ok, so I found the answer. My problem was I put the Debugger Lines in the wrong place. I change the innermost method to

```<code>    private Task InnerRunning()
    {

        _testOutput.WriteLine("InnerRunning: Begin method");

        _testOutput.WriteLine("InnerRunning: Starting Task");
        var t = Task.Run(() =>
        {
            _testOutput.WriteLine("InnerRunning Lambda: Sleeping For 5 seconds");
            Thread.Sleep(5000);
            _testOutput.WriteLine("InnerRunning Lambda: Wake up and exit");
        });
        _testOutput.WriteLine("InnerRunning: After Task");

        return t;
    }
</code>```

And I now get this Output:

```<code>Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Starting Task
InnerRunning: After Task
InnerRunning Lambda: Sleeping For 5 seconds
In outer method, after calling async method
InnerRunning Lambda: Wake up and exit
RunningAsync: Returning
Exiting Test
</code>```

Thank you everyone for your thought-provoking comments!

Body:
I have created an experiment (run in XUnit) to test output. I use three methods - the test method, an asynchronous method that calls await, and an inner Task that sleeps for 5 seconds.

    [Fact]
    public void TestAsyncRunning()
    {
        _testOutput.WriteLine("Beginning Test");
        _testOutput.WriteLine("Calling RunningAsync");

        var t = RunningAsync();

        _testOutput.WriteLine("In outer method, after calling async method");

        t.Wait(); //IOW, Thread.Join();

        _testOutput.WriteLine("Exiting Test");
    }

    private async Task RunningAsync()
    {
        _testOutput.WriteLine("RunningAsync: Enter Method");
        _testOutput.WriteLine("RunningAsync: Calling and awaiting inner running");
        await InnerRunning();
        _testOutput.WriteLine("RunningAsync: Returning");
    }

    private Task InnerRunning()
    {
        _testOutput.WriteLine("InnerRunning: Begin method");
        _testOutput.WriteLine("InnerRunning: Sleeping For 5 seconds");
        var t = Task.Run(() => Thread.Sleep(5000));
        _testOutput.WriteLine("InnerRunning: Wake up and exit");
        return t;
    }

In the following output, the lines with the asterisks is where the unexpected order occurs.

The output I expect is

Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*In outer method, after calling async method
*InnerRunning: Wake up and exit
RunningAsync: Returning
Exiting Test

The output I get is

Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*InnerRunning: Wake up and exit
*In outer method, after calling async method
RunningAsync: Returning
Exiting Test

It appears that the async method is actually running async but the method it calls is running synchronously. Does this have to do with the TaskScheduler? I am clearly missing something...….

Body:
Ok, so I found the answer. My problem was I put the Debugger Lines in the wrong place. I change the innermost method to

    private Task InnerRunning()
    {

        _testOutput.WriteLine("InnerRunning: Begin method");

        _testOutput.WriteLine("InnerRunning: Starting Task");
        var t = Task.Run(() =>
        {
            _testOutput.WriteLine("InnerRunning Lambda: Sleeping For 5 seconds");
            Thread.Sleep(5000);
            _testOutput.WriteLine("InnerRunning Lambda: Wake up and exit");
        });
        _testOutput.WriteLine("InnerRunning: After Task");

        return t;
    }

And I now get this Output:

Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Starting Task
InnerRunning: After Task
InnerRunning Lambda: Sleeping For 5 seconds
In outer method, after calling async method
InnerRunning Lambda: Wake up and exit
RunningAsync: Returning
Exiting Test

Thank you everyone for your thought-provoking comments!


问:
Java build a tree from ResultSet thats returnable as auto-json through Spring
I'm sure this can be done with additional wrapper classes but I'm trying to learn an efficient way to do this:

Sample rows

```<code>Country | State | City        | Zip
USA     |  NY   | Brooklyn    | 11210
USA     |  NY   | Brooklyn    | 11211
USA     |  NY   | Brooklyn    | 11212
USA     |  NY   | Brooklyn    | 11213
USA     |  NY   | Bronx       | 10450
USA     |  NY   | Bronx       | 10451
USA     |  NY   | Bronx       | 10452
USA     |  NJ   | Jersey City | 07310
USA     |  NJ   | Jersey City | 07311
Canada  |  ON   | Keswick     | L4P 4K3
</code>```

I have a Spring API endpoint:

@GetMapping("/all")
public ResponseEntity</*Whatever makes sense*/> getAllAddress() {
    return ResponseEntity.ok().body(server.getAllAddresses()); // select * from addresses as ResultSet
}
```

<p><strong>What would be an optimal way to generate nested Json arrays, something to the following effect:</strong></p>

```{
"addresses": {
      "USA": [ {
         "NY" : [ {
           "Brooklyn" :  [ 11210, 11211, 11212, 11213],
           "Bronx"    :  [ 10450, 10451, 10452]
          } ]
         "NJ" : [ {

           ...etc
}
```

Thank you.

(I'm using addresses as an example - my program is different column names but same structure many string to many string to many string to many string)

答:
You can stream your line, then collect them using nested Collectors.groupingBy. Something like this:

```<code>public static void main(String[] args) {
        String data = "USA     |  NY   | Brooklyn    | 11210\n" +
                "USA     |  NY   | Brooklyn    | 11211\n" +
                "USA     |  NY   | Brooklyn    | 11212\n" +
                "USA     |  NY   | Brooklyn    | 11213\n" +
                "USA     |  NY   | Bronx       | 10450\n" +
                "USA     |  NY   | Bronx       | 10451\n" +
                "USA     |  NY   | Bronx       | 10452\n" +
                "USA     |  NJ   | Jersey City | 07310\n" +
                "USA     |  NJ   | Jersey City | 07311\n" +
                "Canada  |  ON   | Keswick     | L4P 4K3";
        List<String[]> lines = Arrays.stream(data.split("\n"))
                .map(line -> line.split("\\|"))
                .map(lineParts -> Arrays.stream(lineParts).map(String::trim).toArray(String[]::new))
                .collect(Collectors.toList());

        Map<String, Map<String, Map<String, List<String[]>>>> nestedMap = lines.stream().collect(Collectors.groupingBy(
                line -> line[0],
                Collectors.groupingBy(
                        line -> line[1],
                        Collectors.groupingBy(line -> line[2])
                )
        ));

        Jsonb jsonb = JsonbBuilder.create();
        String json = jsonb.toJson(nestedMap);
        System.out.println(json);
    }
</code>```

Would ouput that:

```<code>{
  "Canada": {
    "ON": {
      "Keswick": [
        [
          "Canada",
          "ON",
          "Keswick",
          "L4P 4K3"
        ]
      ]
    }
  },
  "USA": {
    "NY": {
      "Brooklyn": [
        [
          "USA",
          "NY",
          "Brooklyn",
          "11210"
        ],
        [
          "USA",
          "NY",
          "Brooklyn",
          "11211"
        ],
        [
          "USA",
          "NY",
          "Brooklyn",
          "11212"
        ],
        [
          "USA",
          "NY",
          "Brooklyn",
          "11213"
        ]
      ],
      "Bronx": [
        [
          "USA",
          "NY",
          "Bronx",
          "10450"
        ],
        [
          "USA",
          "NY",
          "Bronx",
          "10451"
        ],
        [
          "USA",
          "NY",
          "Bronx",
          "10452"
        ]
      ]
    },
    "NJ": {
      "Jersey City": [
        [
          "USA",
          "NJ",
          "Jersey City",
          "07310"
        ],
        [
          "USA",
          "NJ",
          "Jersey City",
          "07311"
        ]
      ]
    }
  }
}
</code>```

Body:
I'm sure this can be done with additional wrapper classes but I'm trying to learn an efficient way to do this:

Sample rows

Country | State | City        | Zip
USA     |  NY   | Brooklyn    | 11210
USA     |  NY   | Brooklyn    | 11211
USA     |  NY   | Brooklyn    | 11212
USA     |  NY   | Brooklyn    | 11213
USA     |  NY   | Bronx       | 10450
USA     |  NY   | Bronx       | 10451
USA     |  NY   | Bronx       | 10452
USA     |  NJ   | Jersey City | 07310
USA     |  NJ   | Jersey City | 07311
Canada  |  ON   | Keswick     | L4P 4K3

I have a Spring API endpoint:

@GetMapping("/all")
public ResponseEntity</*Whatever makes sense*/> getAllAddress() {
    return ResponseEntity.ok().body(server.getAllAddresses()); // select * from addresses as ResultSet
}

What would be an optimal way to generate nested Json arrays, something to the following effect:

{
"addresses": {
      "USA": [ {
         "NY" : [ {
           "Brooklyn" :  [ 11210, 11211, 11212, 11213],
           "Bronx"    :  [ 10450, 10451, 10452]
          } ]
         "NJ" : [ {

           ...etc
}

Thank you.

(I'm using addresses as an example - my program is different column names but same structure many string to many string to many string to many string)

Body:
You can stream your line, then collect them using nested Collectors.groupingBy. Something like this:

public static void main(String[] args) {
        String data = "USA     |  NY   | Brooklyn    | 11210\n" +
                "USA     |  NY   | Brooklyn    | 11211\n" +
                "USA     |  NY   | Brooklyn    | 11212\n" +
                "USA     |  NY   | Brooklyn    | 11213\n" +
                "USA     |  NY   | Bronx       | 10450\n" +
                "USA     |  NY   | Bronx       | 10451\n" +
                "USA     |  NY   | Bronx       | 10452\n" +
                "USA     |  NJ   | Jersey City | 07310\n" +
                "USA     |  NJ   | Jersey City | 07311\n" +
                "Canada  |  ON   | Keswick     | L4P 4K3";
        List<String[]> lines = Arrays.stream(data.split("\n"))
                .map(line -> line.split("\\|"))
                .map(lineParts -> Arrays.stream(lineParts).map(String::trim).toArray(String[]::new))
                .collect(Collectors.toList());

        Map<String, Map<String, Map<String, List<String[]>>>> nestedMap = lines.stream().collect(Collectors.groupingBy(
                line -> line[0],
                Collectors.groupingBy(
                        line -> line[1],
                        Collectors.groupingBy(line -> line[2])
                )
        ));

        Jsonb jsonb = JsonbBuilder.create();
        String json = jsonb.toJson(nestedMap);
        System.out.println(json);
    }

Would ouput that:

{
  "Canada": {
    "ON": {
      "Keswick": [
        [
          "Canada",
          "ON",
          "Keswick",
          "L4P 4K3"
        ]
      ]
    }
  },
  "USA": {
    "NY": {
      "Brooklyn": [
        [
          "USA",
          "NY",
          "Brooklyn",
          "11210"
        ],
        [
          "USA",
          "NY",
          "Brooklyn",
          "11211"
        ],
        [
          "USA",
          "NY",
          "Brooklyn",
          "11212"
        ],
        [
          "USA",
          "NY",
          "Brooklyn",
          "11213"
        ]
      ],
      "Bronx": [
        [
          "USA",
          "NY",
          "Bronx",
          "10450"
        ],
        [
          "USA",
          "NY",
          "Bronx",
          "10451"
        ],
        [
          "USA",
          "NY",
          "Bronx",
          "10452"
        ]
      ]
    },
    "NJ": {
      "Jersey City": [
        [
          "USA",
          "NJ",
          "Jersey City",
          "07310"
        ],
        [
          "USA",
          "NJ",
          "Jersey City",
          "07311"
        ]
      ]
    }
  }
}


问:
show file size when download a file by php curl
I want to force download a file from server to local system by curl in php
everything is ok but the file size in which not shown when we start the download.
here is the code

```<code>    $file_url ='http://example.com/dl/dlfile.zip';

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file_url));
    // header('Content-Transfer-Encoding: chunked');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    $stream = fopen('php://output', 'w');
    $ch = curl_init($file_url);

    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_url));

    curl_setopt($ch, CURLOPT_READFUNCTION, function($ch, $fd, $length) use ($stream) {
        return fwrite($stream, fread($fd, $length));
    });
    curl_exec($ch);
    curl_close($ch);
    exit();
</code>```

when i use this snippet
the filesize() throw an error in downloaded file and therefore corrupt the file.
i know that filesize function work with absolute path not url path, but is there any way to solve this problem?

答:
Add the following header before the Content-Disposition header to send the filesize to the browser:

```<code>header("Content-Length: ".filesize($file_url));
</code>```

Source

Body:
I want to force download a file from server to local system by curl in php
everything is ok but the file size in which not shown when we start the download.
here is the code

    $file_url ='http://example.com/dl/dlfile.zip';

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file_url));
    // header('Content-Transfer-Encoding: chunked');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    $stream = fopen('php://output', 'w');
    $ch = curl_init($file_url);

    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_url));

    curl_setopt($ch, CURLOPT_READFUNCTION, function($ch, $fd, $length) use ($stream) {
        return fwrite($stream, fread($fd, $length));
    });
    curl_exec($ch);
    curl_close($ch);
    exit();

when i use this snippet
the filesize() throw an error in downloaded file and therefore corrupt the file.
i know that filesize function work with absolute path not url path, but is there any way to solve this problem?

Body:
Add the following header before the Content-Disposition header to send the filesize to the browser:

header("Content-Length: ".filesize($file_url));

Source


问:
System Architecture design
I am hard time understanding the concept of system complexity.

Can any one help me understand the relationship between the complexity of overall system and the complexity of all the subsystems?

Expressed as C(S) = C(SS1) + C(SS2)+..C(SSn)

C(S): Complexity of entire system

C(SS1): Complexity of simple subsystem

答:
All that equation is trying to say is that a systems complexity is the sum of its parts.

So

C(S) = X (overall complexity)

Now break it up into distinct sub systems

C(S) = C(SS1) + C(SS2)+..C(SSn)

Calculate each systems complexity:

C(SS1) = A

C(SS2) = B

C(SSn) = n

If we add those together it will be the same as C(S) aka:

X = A + B + ..n

C(S) = X =  A + B + .. + n =  C(SS1) + C(SS2)+..C(SSn)

Please make sure you note what S.Lott said above, that the equation by no means implies complexity as a linear relationship of a system to its subsystems, aka the system complexity doesn't necessarily grow linearly as you add new components.

Title: System Architecture design


问:
How to make each row a new set of variables and rename them dynamically in r
First, I want to convert this data:

```<code>datinput = read.table(header = TRUE, text = "
var1 var2 var3
A 3 10
B 2 6
")

datinput
  var1 var2 var3
1    A    3   10
2    B    2    6
</code>```

into this format:

```<code>datoutput = read.table(header = TRUE, text = "
var2.A var3.A Var2.B var3.B
3 10 2 6
")

  var2.A var3.A Var2.B var3.B
1      3     10      2      6
</code>```

I tried reshape2::dcast, but does not deliver the desired output.

Instead, dcast gives this:

```<code>datinput%>%reshape2::dcast(var1~var2, value.var="var3")

    var1  2  3
    1    A NA 10
    2    B  6 NA

datinput%>%reshape2::dcast(var1, value.var=c("var2", "var3"))
Error in is.formula(formula) : object 'var1' not found

datinput%>%reshape2::dcast(var1~var1, value.var=c("var2", "var3"))
Error in .subset2(x, i, exact = exact) : subscript out of bounds
In addition: Warning message:
In if (!(value.var %in% names(data))) { :
  the condition has length > 1 and only the first element will be used
</code>```

Then, I want to make the names_from come first in the new names.

I want to have these new columns named A.var2 B.var2 A.var3 B.var3. This is because I want to arrange the resulting variables using the variable names by alphabetical order into A.var2 A.var3 B.var2 B.var3

Thanks for any help.

答:
We can use pivot_wider

```<code>library(dplyr)
library(tidyr)
library(stringr)
datinput %>%
   pivot_wider( names_from = var1, values_from = c('var2', 'var3'), names_sep=".") %>%
   rename_all(~ str_replace(., '^(.*)\\.(.*)', '\\2.\\1'))
</code>```

The dcast from reshape2 do not use multiple value columns.  Instead, it can be done with data.table::dcast

```<code>library(data.table)
dcast(setDT(datinput), rowid(var1) ~ var1, value.var = c("var2", "var3"), sep=".")
#     var1 var2.A var2.B var3.A var3.B
#1:    1      3      2     10      6
</code>```

Body:
First, I want to convert this data:

datinput = read.table(header = TRUE, text = "
var1 var2 var3
A 3 10
B 2 6
")

datinput
  var1 var2 var3
1    A    3   10
2    B    2    6

into this format:

datoutput = read.table(header = TRUE, text = "
var2.A var3.A Var2.B var3.B
3 10 2 6
")

  var2.A var3.A Var2.B var3.B
1      3     10      2      6

I tried reshape2::dcast, but does not deliver the desired output.

Instead, dcast gives this:

datinput%>%reshape2::dcast(var1~var2, value.var="var3")

    var1  2  3
    1    A NA 10
    2    B  6 NA

datinput%>%reshape2::dcast(var1, value.var=c("var2", "var3"))
Error in is.formula(formula) : object 'var1' not found

datinput%>%reshape2::dcast(var1~var1, value.var=c("var2", "var3"))
Error in .subset2(x, i, exact = exact) : subscript out of bounds
In addition: Warning message:
In if (!(value.var %in% names(data))) { :
  the condition has length > 1 and only the first element will be used

Then, I want to make the names_from come first in the new names.

I want to have these new columns named A.var2 B.var2 A.var3 B.var3. This is because I want to arrange the resulting variables using the variable names by alphabetical order into A.var2 A.var3 B.var2 B.var3

Thanks for any help.

Body:
We can use pivot_wider

library(dplyr)
library(tidyr)
library(stringr)
datinput %>%
   pivot_wider( names_from = var1, values_from = c('var2', 'var3'), names_sep=".") %>%
   rename_all(~ str_replace(., '^(.*)\\.(.*)', '\\2.\\1'))

The dcast from reshape2 do not use multiple value columns.  Instead, it can be done with data.table::dcast

library(data.table)
dcast(setDT(datinput), rowid(var1) ~ var1, value.var = c("var2", "var3"), sep=".")
#     var1 var2.A var2.B var3.A var3.B
#1:    1      3      2     10      6


问:
How to load images into RAM for later use in .kv file (Kivy+Python)
Question:

I need to find a way to preload my .png files, because at some points of my code, graphics that should be buttons appear as black squares while at other points (exactly same code) they work perfectly.
I thougt of doing that in a python class at startup, and attach them later in my .kv files.
The crux is, that I use source: and "preloading" a string like 'assets/graphics/buttons/newImg.png'would store the string, not the image. And if I load the image another way, I don't know how to attach that later to my buttons.

Any hints and/or ideas are appreciated!

Background:

I created my buttons like this:

```<code><MyButton@ButtonBehavior+Image>
    widgetTarget: ''
    source: 'assets/graphics/buttons/' + self.widgetTarget + '.png'
    on_press:
        self.source = 'assets/graphics/buttons/' + self.widgetTarget + '_clicked.png'
    on_release:
        self.source = 'assets/graphics/buttons/' + self.widgetTarget + '.png'
</code>```

and use it like that in my .kv files:

```<code>CustomButtonNoTarget:
        id: meIsButton
        widgetTarget: 'stopSign'
        on_release:
           *do stuff here*
</code>```

Most of the time, that works like a charm, but at certain points in the program flow, instead of images only black squares (same size) appear.

Because the exact same code worked at other positions in program flow I focused on the images:
I tested:
different images - different image types - different image sizes

-> all results exactly the same.

Then I stumbled over a hint: If I used the same graphic BEFORE the problematic position, it's loaded perfectly later on. So I think the problem is that - why so ever that happens at just few positions and not all the time - the image can't be loaded fast enought. Because RAM is faster it works, when the image allready is in RAM.

So my idea to solve that would be to store all images in memory at startup, what leads me to obove asked question.

答:
I also encounter this issue as I try to add gif image onto ModalView in the code.

The solution I found is to use AsyncImage and set the color to transparent (1,1,1,0), nocache to True, and later set the color back by binding on_load. This works very well in my situation.

Body:
Question:

I need to find a way to preload my .png files, because at some points of my code, graphics that should be buttons appear as black squares while at other points (exactly same code) they work perfectly.
I thougt of doing that in a python class at startup, and attach them later in my .kv files.
The crux is, that I use source: and "preloading" a string like 'assets/graphics/buttons/newImg.png'would store the string, not the image. And if I load the image another way, I don't know how to attach that later to my buttons.

Any hints and/or ideas are appreciated!

Background:

I created my buttons like this:

<MyButton@ButtonBehavior+Image>
    widgetTarget: ''
    source: 'assets/graphics/buttons/' + self.widgetTarget + '.png'
    on_press:
        self.source = 'assets/graphics/buttons/' + self.widgetTarget + '_clicked.png'
    on_release:
        self.source = 'assets/graphics/buttons/' + self.widgetTarget + '.png'

and use it like that in my .kv files:

CustomButtonNoTarget:
        id: meIsButton
        widgetTarget: 'stopSign'
        on_release:
           *do stuff here*

Most of the time, that works like a charm, but at certain points in the program flow, instead of images only black squares (same size) appear.

Because the exact same code worked at other positions in program flow I focused on the images:
I tested:
different images - different image types - different image sizes

-> all results exactly the same.

Then I stumbled over a hint: If I used the same graphic BEFORE the problematic position, it's loaded perfectly later on. So I think the problem is that - why so ever that happens at just few positions and not all the time - the image can't be loaded fast enought. Because RAM is faster it works, when the image allready is in RAM.

So my idea to solve that would be to store all images in memory at startup, what leads me to obove asked question.


问:
Make clickable cell in dynamic table with JQuery
I would like to add a detailed link in specific cells in a dynamic table in JQuery.

This code works fine when adding a cell/row :

```<code>$('<td class="ploegen-details-naam" onclick="link_naar_info_speler(this.parentNode.childNodes[0].textContent)">
   </td>').text(speler_naam).appendTo(details_rows);
</code>```

But if I want to add dynamically detailed id's to the cell, this does not link anymore:

```<code>for (var x = 0; x < len; x ++) {
   $('<td>', {id:"naam_thuis" + x}, {class:"ploegen-details-naam"},
  {onclick:"link_naar_info_speler(this.parentNode.childNodes[0].textContent)"}).text(speler_naam).appendTo(details_rows);
}

</code>```

This function is exactly the same for the 2 examples :

```<code>function link_naar_info_speler(speler_id)
{
    location.href="/ADL/Info/Spelers/Spelers.html?" + speler_id;
}
</code>```

The part that doesn't work in the second example is the onclick with the link. I only posted the relevant code, since the rest of the code is the same in the 2 cases.

答:
You just need to combine your objects into a single one, rather than incorrectly trying to pass in an object per attribute.

Example:

for ( var i = 0; i < 4; i++ ) {
  $('
', { id: `id${i}`, class: 'my-class', onclick: 'echoMyId(this)' }).text(i).appendTo('#container');
}

function echoMyId (paragraph) {
  console.log(paragraph.id);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div></code>```

Body:
I would like to add a detailed link in specific cells in a dynamic table in JQuery.

This code works fine when adding a cell/row :

$('
   	').text(speler_naam).appendTo(details_rows);

But if I want to add dynamically detailed id's to the cell, this does not link anymore:

for (var x = 0; x < len; x ++) {
   $('', {id:"naam_thuis" + x}, {class:"ploegen-details-naam"},
  {onclick:"link_naar_info_speler(this.parentNode.childNodes[0].textContent)"}).text(speler_naam).appendTo(details_rows);
}

This function is exactly the same for the 2 examples :

function link_naar_info_speler(speler_id)
{
    location.href="/ADL/Info/Spelers/Spelers.html?" + speler_id;
}

The part that doesn't work in the second example is the onclick with the link. I only posted the relevant code, since the rest of the code is the same in the 2 cases.

Body:
You just need to combine your objects into a single one, rather than incorrectly trying to pass in an object per attribute.

Example:

for ( var i = 0; i < 4; i++ ) {
  $('<p>', { id: `id${i}`, class: 'my-class', onclick: 'echoMyId(this)' }).text(i).appendTo('#container');
}

function echoMyId (paragraph) {
  console.log(paragraph.id);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div>


问:
Using HTML5/Canvas/JavaScript to take in-browser screenshots
Google's "Report a Bug" or "Feedback Tool" lets you select an area of your browser window to create a screenshot that is submitted with your feedback about a bug.

Screenshot by Jason Small, posted in a duplicate question.

How are they doing this?  Google's JavaScript feedback API is loaded from here and their overview of the feedback module will demonstrate the screenshot capability.

答:
Get screenshot as Canvas or Jpeg Blob / ArrayBuffer using getDisplayMedia API:

FIX 1: Use the getUserMedia with chromeMediaSource only for Electron.js

FIX 2: Throw error instead return null object

FIX 3: Fix demo to prevent the error: getDisplayMedia must be called from a user gesture handler

```<code>// docs: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia
// see: https://www.webrtc-experiment.com/Pluginfree-Screen-Sharing/#20893521368186473
// see: https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Pluginfree-Screen-Sharing/conference.js

function getDisplayMedia(options) {
    if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
        return navigator.mediaDevices.getDisplayMedia(options)
    }
    if (navigator.getDisplayMedia) {
        return navigator.getDisplayMedia(options)
    }
    if (navigator.webkitGetDisplayMedia) {
        return navigator.webkitGetDisplayMedia(options)
    }
    if (navigator.mozGetDisplayMedia) {
        return navigator.mozGetDisplayMedia(options)
    }
    throw new Error('getDisplayMedia is not defined')
}

function getUserMedia(options) {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        return navigator.mediaDevices.getUserMedia(options)
    }
    if (navigator.getUserMedia) {
        return navigator.getUserMedia(options)
    }
    if (navigator.webkitGetUserMedia) {
        return navigator.webkitGetUserMedia(options)
    }
    if (navigator.mozGetUserMedia) {
        return navigator.mozGetUserMedia(options)
    }
    throw new Error('getUserMedia is not defined')
}

async function takeScreenshotStream() {
    // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/screen
    const width = screen.width * (window.devicePixelRatio || 1)
    const height = screen.height * (window.devicePixelRatio || 1)

    const errors = []
    let stream
    try {
        stream = await getDisplayMedia({
            audio: false,
            // see: https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints/video
            video: {
                width,
                height,
                frameRate: 1,
            },
        })
    } catch (ex) {
        errors.push(ex)
    }

    // for electron js
    if (navigator.userAgent.indexOf('Electron') >= 0) {
        try {
            stream = await getUserMedia({
                audio: false,
                video: {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                        // chromeMediaSourceId: source.id,
                        minWidth         : width,
                        maxWidth         : width,
                        minHeight        : height,
                        maxHeight        : height,
                    },
                },
            })
        } catch (ex) {
            errors.push(ex)
        }
    }

    if (errors.length) {
        console.debug(...errors)
        if (!stream) {
            throw errors[errors.length - 1]
        }
    }

    return stream
}

async function takeScreenshotCanvas() {
    const stream = await takeScreenshotStream()

    // from: https://stackoverflow.com/a/57665309/5221762
    const video = document.createElement('video')
    const result = await new Promise((resolve, reject) => {
        video.onloadedmetadata = () => {
            video.play()
            video.pause()

            // from: https://github.com/kasprownik/electron-screencapture/blob/master/index.js
            const canvas = document.createElement('canvas')
            canvas.width = video.videoWidth
            canvas.height = video.videoHeight
            const context = canvas.getContext('2d')
            // see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement
            context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
            resolve(canvas)
        }
        video.srcObject = stream
    })

    stream.getTracks().forEach(function (track) {
        track.stop()
    })

    if (result == null) {
        throw new Error('Cannot take canvas screenshot')
    }

    return result
}

// from: https://stackoverflow.com/a/46182044/5221762
function getJpegBlob(canvas) {
    return new Promise((resolve, reject) => {
        // docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
        canvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.95)
    })
}

async function getJpegBytes(canvas) {
    const blob = await getJpegBlob(canvas)
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader()

        fileReader.addEventListener('loadend', function () {
            if (this.error) {
                reject(this.error)
                return
            }
            resolve(this.result)
        })

        fileReader.readAsArrayBuffer(blob)
    })
}

async function takeScreenshotJpegBlob() {
    const canvas = await takeScreenshotCanvas()
    return getJpegBlob(canvas)
}

async function takeScreenshotJpegBytes() {
    const canvas = await takeScreenshotCanvas()
    return getJpegBytes(canvas)
}

function blobToCanvas(blob, maxWidth, maxHeight) {
    return new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = function () {
            const canvas = document.createElement('canvas')
            const scale = Math.min(
                1,
                maxWidth ? maxWidth / img.width : 1,
                maxHeight ? maxHeight / img.height : 1,
            )
            canvas.width = img.width * scale
            canvas.height = img.height * scale
            const ctx = canvas.getContext('2d')
            ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height)
            resolve(canvas)
        }
        img.onerror = () => {
            reject(new Error('Error load blob to Image'))
        }
        img.src = URL.createObjectURL(blob)
    })
}
</code>```

DEMO:

```<code>document.body.onclick = async () => {
    // take the screenshot
    var screenshotJpegBlob = await takeScreenshotJpegBlob()

    // show preview with max size 300 x 300 px
    var previewCanvas = await blobToCanvas(screenshotJpegBlob, 300, 300)
    previewCanvas.style.position = 'fixed'
    document.body.appendChild(previewCanvas)

    // send it to the server
    var formdata = new FormData()
    formdata.append("screenshot", screenshotJpegBlob)
    await fetch('https://your-web-site.com/', {
        method: 'POST',
        body: formdata,
        'Content-Type' : "multipart/form-data",
    })
}

// and click on the page
</code>```

Body:
Get screenshot as Canvas or Jpeg Blob / ArrayBuffer using getDisplayMedia API:

FIX 1: Use the getUserMedia with chromeMediaSource only for Electron.js

FIX 2: Throw error instead return null object

FIX 3: Fix demo to prevent the error: getDisplayMedia must be called from a user gesture handler

// docs: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia
// see: https://www.webrtc-experiment.com/Pluginfree-Screen-Sharing/#20893521368186473
// see: https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Pluginfree-Screen-Sharing/conference.js

function getDisplayMedia(options) {
    if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
        return navigator.mediaDevices.getDisplayMedia(options)
    }
    if (navigator.getDisplayMedia) {
        return navigator.getDisplayMedia(options)
    }
    if (navigator.webkitGetDisplayMedia) {
        return navigator.webkitGetDisplayMedia(options)
    }
    if (navigator.mozGetDisplayMedia) {
        return navigator.mozGetDisplayMedia(options)
    }
    throw new Error('getDisplayMedia is not defined')
}

function getUserMedia(options) {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        return navigator.mediaDevices.getUserMedia(options)
    }
    if (navigator.getUserMedia) {
        return navigator.getUserMedia(options)
    }
    if (navigator.webkitGetUserMedia) {
        return navigator.webkitGetUserMedia(options)
    }
    if (navigator.mozGetUserMedia) {
        return navigator.mozGetUserMedia(options)
    }
    throw new Error('getUserMedia is not defined')
}

async function takeScreenshotStream() {
    // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/screen
    const width = screen.width * (window.devicePixelRatio || 1)
    const height = screen.height * (window.devicePixelRatio || 1)

    const errors = []
    let stream
    try {
        stream = await getDisplayMedia({
            audio: false,
            // see: https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints/video
            video: {
                width,
                height,
                frameRate: 1,
            },
        })
    } catch (ex) {
        errors.push(ex)
    }

    // for electron js
    if (navigator.userAgent.indexOf('Electron') >= 0) {
        try {
            stream = await getUserMedia({
                audio: false,
                video: {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                        // chromeMediaSourceId: source.id,
                        minWidth         : width,
                        maxWidth         : width,
                        minHeight        : height,
                        maxHeight        : height,
                    },
                },
            })
        } catch (ex) {
            errors.push(ex)
        }
    }

    if (errors.length) {
        console.debug(...errors)
        if (!stream) {
            throw errors[errors.length - 1]
        }
    }

    return stream
}

async function takeScreenshotCanvas() {
    const stream = await takeScreenshotStream()

    // from: https://stackoverflow.com/a/57665309/5221762
    const video = document.createElement('video')
    const result = await new Promise((resolve, reject) => {
        video.onloadedmetadata = () => {
            video.play()
            video.pause()

            // from: https://github.com/kasprownik/electron-screencapture/blob/master/index.js
            const canvas = document.createElement('canvas')
            canvas.width = video.videoWidth
            canvas.height = video.videoHeight
            const context = canvas.getContext('2d')
            // see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement
            context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
            resolve(canvas)
        }
        video.srcObject = stream
    })

    stream.getTracks().forEach(function (track) {
        track.stop()
    })

    if (result == null) {
        throw new Error('Cannot take canvas screenshot')
    }

    return result
}

// from: https://stackoverflow.com/a/46182044/5221762
function getJpegBlob(canvas) {
    return new Promise((resolve, reject) => {
        // docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
        canvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.95)
    })
}

async function getJpegBytes(canvas) {
    const blob = await getJpegBlob(canvas)
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader()

        fileReader.addEventListener('loadend', function () {
            if (this.error) {
                reject(this.error)
                return
            }
            resolve(this.result)
        })

        fileReader.readAsArrayBuffer(blob)
    })
}

async function takeScreenshotJpegBlob() {
    const canvas = await takeScreenshotCanvas()
    return getJpegBlob(canvas)
}

async function takeScreenshotJpegBytes() {
    const canvas = await takeScreenshotCanvas()
    return getJpegBytes(canvas)
}

function blobToCanvas(blob, maxWidth, maxHeight) {
    return new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = function () {
            const canvas = document.createElement('canvas')
            const scale = Math.min(
                1,
                maxWidth ? maxWidth / img.width : 1,
                maxHeight ? maxHeight / img.height : 1,
            )
            canvas.width = img.width * scale
            canvas.height = img.height * scale
            const ctx = canvas.getContext('2d')
            ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height)
            resolve(canvas)
        }
        img.onerror = () => {
            reject(new Error('Error load blob to Image'))
        }
        img.src = URL.createObjectURL(blob)
    })
}

DEMO:

document.body.onclick = async () => {
    // take the screenshot
    var screenshotJpegBlob = await takeScreenshotJpegBlob()

    // show preview with max size 300 x 300 px
    var previewCanvas = await blobToCanvas(screenshotJpegBlob, 300, 300)
    previewCanvas.style.position = 'fixed'
    document.body.appendChild(previewCanvas)

    // send it to the server
    var formdata = new FormData()
    formdata.append("screenshot", screenshotJpegBlob)
    await fetch('https://your-web-site.com/', {
        method: 'POST',
        body: formdata,
        'Content-Type' : "multipart/form-data",
    })
}

// and click on the page


问:
How to separate PostgreSQL data for different Mac users?
When installing PostgreSQL on MacOS you need to create a data folder where it will store details about users, dbs and privileges, but this data is globally available.
Is there a way to separate this based on Mac users?

This way:

When logging in with UserA, PostgreSQL will only instantiate/see DB_A1 and DB_A2 and PostgreSQL users defined only for UserA's PostgreSQL instance.

When logging in with UserB, PostgreSQL will only instantiate/see DB_B1 and DB_B2 and PostgreSQL users defined only for UserB's PostgreSQL instance.

答:
according to my somewhat rusty knowledge about PostgreSQL your intention would lead to start a postmaster process for every user on his/her own reserved port. Although this is possible, it smells like smoke from administration hell (not counting the overhead of a fat RDBMS process reserved for a single user spending most of the time waiting). Positively expressed I propose considering one of the following options:

Add a line to pg_hba.conf like local all sameuser all md5 to allow all local users to only access their personal databaase (named like the user). Access to system data may be further restricted depending on the actual PostgreSQL version you're using (it's best to consult the documentation in this case).

Depending on the amount of data if concurrent access was not a critical must-have (which seems to be the case here) switch to sqlite3; it's performant, data sits in a single file, access is provided by a library instead of a full fledged RDBMS background process armada, and it comes ready to use with every Mac OS X.