问:
filter for rows with n largest values for each group

Context

I want, for each team, the rows of the data frame that contains the top three scoring players.

In my head, it is a combination of Dataframe.nlargest() and Dataframe.groupby() but I don't think this is supported.
My ideal solution is:

performed directly on df without having to create other dataframes

legible, and

relatively performant (real df shape is 7M rows and 5 col)

Input

import pandas as pd
df = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"A","4":"A","5":"B","6":"B","7":"B","8":"B","9":"B","10":"C","11":"C","12":"C","13":"C","14":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Donna","4":"Elizabeth","5":"Fran","6":"Greta","7":"Heather","8":"Iris","9":"Jackie","10":"Kelly","11":"Lucy","12":"Molly","13":"Nina","14":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":8,"4":10,"5":28,"6":29,"7":18,"8":25,"9":9,"10":12,"11":23,"12":18,"13":10,"14":15}}')
```

```| team | player    | points |
|------|-----------|--------|
| A    | Alice     | 15     |
| A    | Becky     | 11     |
| A    | Carmen    | 13     |
| A    | Donna     | 8      |
| A    | Elizabeth | 10     |
| B    | Fran      | 28     |
| B    | Greta     | 29     |
| B    | Heather   | 18     |
| B    | Iris      | 25     |
| B    | Jackie    | 9      |
| C    | Kelly     | 12     |
| C    | Lucy      | 23     |
| C    | Molly     | 18     |
| C    | Nina      | 10     |
| C    | Ophelia   | 15     |
```

<h3>Desired Output</h3>

<pre class="lang-py prettyprint-override"><code>df_output = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"B","4":"B","5":"B","6":"C","7":"C","8":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Fran","4":"Greta","5":"Iris","6":"Lucy","7":"Molly","8":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":28,"4":29,"5":25,"6":23,"7":18,"8":15}}')
df_output
</code>```

```<code>| team | player  | points |
|------|---------|--------|
| A    | Alice   | 15     |
| A    | Becky   | 11     |
| A    | Carmen  | 13     |
| B    | Fran    | 28     |
| B    | Greta   | 29     |
| B    | Iris    | 25     |
| C    | Lucy    | 23     |
| C    | Molly   | 18     |
| C    | Ophelia | 15     |
</code>```

答:
Something like this might work - </p>

```<code>df.loc[df.groupby(['team'])['points'].nlargest(3).reset_index().drop(['team','points'], axis=1)['level_1'].values]
   team   player  points
0     A    Alice      15
2     A   Carmen      13
1     A    Becky      11
6     B    Greta      29
5     B     Fran      28
8     B     Iris      25
11    C     Lucy      23
12    C    Molly      18
14    C  Ophelia      15
</code>```

Body:
Context

I want, for each team, the rows of the data frame that contains the top three scoring players.

In my head, it is a combination of Dataframe.nlargest() and Dataframe.groupby() but I don't think this is supported.
My ideal solution is:

performed directly on df without having to create other dataframes

legible, and

relatively performant (real df shape is 7M rows and 5 col)

Input

import pandas as pd
df = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"A","4":"A","5":"B","6":"B","7":"B","8":"B","9":"B","10":"C","11":"C","12":"C","13":"C","14":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Donna","4":"Elizabeth","5":"Fran","6":"Greta","7":"Heather","8":"Iris","9":"Jackie","10":"Kelly","11":"Lucy","12":"Molly","13":"Nina","14":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":8,"4":10,"5":28,"6":29,"7":18,"8":25,"9":9,"10":12,"11":23,"12":18,"13":10,"14":15}}')

| team | player    | points |
|------|-----------|--------|
| A    | Alice     | 15     |
| A    | Becky     | 11     |
| A    | Carmen    | 13     |
| A    | Donna     | 8      |
| A    | Elizabeth | 10     |
| B    | Fran      | 28     |
| B    | Greta     | 29     |
| B    | Heather   | 18     |
| B    | Iris      | 25     |
| B    | Jackie    | 9      |
| C    | Kelly     | 12     |
| C    | Lucy      | 23     |
| C    | Molly     | 18     |
| C    | Nina      | 10     |
| C    | Ophelia   | 15     |

Desired Output

df_output = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"B","4":"B","5":"B","6":"C","7":"C","8":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Fran","4":"Greta","5":"Iris","6":"Lucy","7":"Molly","8":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":28,"4":29,"5":25,"6":23,"7":18,"8":15}}')
df_output

| team | player  | points |
|------|---------|--------|
| A    | Alice   | 15     |
| A    | Becky   | 11     |
| A    | Carmen  | 13     |
| B    | Fran    | 28     |
| B    | Greta   | 29     |
| B    | Iris    | 25     |
| C    | Lucy    | 23     |
| C    | Molly   | 18     |
| C    | Ophelia | 15     |

Body:
Something like this might work -

df.loc[df.groupby(['team'])['points'].nlargest(3).reset_index().drop(['team','points'], axis=1)['level_1'].values]
   team   player  points
0     A    Alice      15
2     A   Carmen      13
1     A    Becky      11
6     B    Greta      29
5     B     Fran      28
8     B     Iris      25
11    C     Lucy      23
12    C    Molly      18
14    C  Ophelia      15


来源: stackexchange

问:
how to make django dynamic URL works properly with django form
This is my form

```<code><form action="{%url 'topicname' %}" method="GET">
              <input type="search" placeholder="Search topics" name="searchtopic">
              <button type="submit">Search</button>
 </form>
</code>```

This is my View

```<code>def searchtopic(request):
    if request.method == 'GET':
        mysearchtopic = request.GET['searchtopic']

        mydata = myhashtaglist.objects.filter(slug = mysearchtopic)
        context = {
            'mydata':mydata,
            }
    return render(request, 'hzone/result.html',context)
</code>```

This is my result.html page

```<code>{% for m in mydata %}
<a href="{% url 'topicname' m.slug %}">{{ m.title }}</a>
{% endfor %}
</code>```

This is my urls.py

```<code>urlpatterns = [
    path('', views.apphome, name = 'homepage'),
    path('topic/', views.searchtopic, name = 'topicname'),
]
</code>```

This is my model

```<code>class myhashtaglist(models.Model):
    title = models.CharField(max_length = 200)
    slug = models.SlugField(max_length = 150, null=True, blank = True)
    topicdetails = models.TextField(max_length = 500)
</code>```

what i want is whenever user click on any of the topic on result page this topic should open.
my reult page looks like

```<code>intro to django
django tutorial 1
django tutorial 2
django tutorial 3
</code>```

but when i am clicking on any of the topic its not taking me to that topic.

答:
You need new view and path with a primary key for this purpose.

First of all, start with correcting your result.html

```<code>{% for m in mydata %}
<a href="{% url 'viewTopic' m.slug %}">{{ m.title }}</a>
{% endfor %}
</code>```

Define viewTopic in urls.py

```<code> path("topic/<pk>", views.viewTopic, name= "viewTopic")
</code>```

Write viewTopic function in views.py

```<code>def viewTopic (request, pk):
    topic = myhashtaglist.objects.filter(slug = pk)
    context = { "topic":topic }
    return render (request, "newfile.html", context)
</code>```

And finally, use {{topic.title}} {{topic.slug}} {{topic.topicdetail}} in your new html file.

ContentLicense: CC BY-SA 4.0

Body:
This is my form

<form action="{%url 'topicname' %}" method="GET">
              <input type="search" placeholder="Search topics" name="searchtopic">
              <button type="submit">Search</button>
 </form>

This is my View

def searchtopic(request):
    if request.method == 'GET':
        mysearchtopic = request.GET['searchtopic']

        mydata = myhashtaglist.objects.filter(slug = mysearchtopic)
        context = {
            'mydata':mydata,
            }
    return render(request, 'hzone/result.html',context)

This is my result.html page

{% for m in mydata %}
{{ m.title }}
{% endfor %}

This is my urls.py

urlpatterns = [
    path('', views.apphome, name = 'homepage'),
    path('topic/', views.searchtopic, name = 'topicname'),
]

This is my model

class myhashtaglist(models.Model):
    title = models.CharField(max_length = 200)
    slug = models.SlugField(max_length = 150, null=True, blank = True)
    topicdetails = models.TextField(max_length = 500)

what i want is whenever user click on any of the topic on result page this topic should open.
my reult page looks like

intro to django
django tutorial 1
django tutorial 2
django tutorial 3

but when i am clicking on any of the topic its not taking me to that topic.

Body:
You need new view and path with a primary key for this purpose.

First of all, start with correcting your result.html

{% for m in mydata %}
<a href="{% url 'viewTopic' m.slug %}">{{ m.title }}</a>
{% endfor %}

Define viewTopic in urls.py

 path("topic/<pk>", views.viewTopic, name= "viewTopic")

Write viewTopic function in views.py

def viewTopic (request, pk):
    topic = myhashtaglist.objects.filter(slug = pk)
    context = { "topic":topic }
    return render (request, "newfile.html", context)

And finally, use {{topic.title}} {{topic.slug}} {{topic.topicdetail}} in your new html file.


问:
Disable placeholder text to be read by all accessibility API(screen reader)
Some screen readers read placeholder value and some do not. Is there a way in which reading placeholder value can be disabled for All screen reader(in context with HTML input). Especially the IOS screen reader reads placeholder value, in that case, the same information repeated twice.

What I want is to show placeholders for screen users and hidden labels for screen reader users.

Edit: When I asked the question it was the first time working on accessibility, to just fix an issue. On further exploration, I find out that we can just use a hidden label and associate it with the input element using for the attribute. Here the w3 documentation link.

答:
If you really want to get creative, you could in theory use JS to manage the placeholder attribute(s). It would slow down the loading of the page somewhat, but you could then remove the placeholder attribute whenever the input receives focus and re-add it when the input loses focus. That would have the effect of disabling the placeholder attribute for assistive technology (at least in interactive forms mode). Sighted visitors probably wouldn't notice the difference. Here's an example in a fiddle. I tested in NVDA/Chrome and it worked, but I can't speak for any other screen-reader/browser combinations.

```<code>// on document load, add the placeholder text
document.addEventListener("DOMContentLoaded", function(){
   myInput.setAttribute("placeholder", myPlaceholder)
});

// when receiving focus, remove the placeholder text
myInput.addEventListener('focus', (event) => {
    myInput.removeAttribute("placeholder");
});

// when losing focus, re-add the placeholder text
myInput.addEventListener('blur', (event) => {
   myInput.setAttribute("placeholder", myPlaceholder)
});
</code>```

As others have stated, using placeholders is not a suitable replacement for using labels. If you really don't like the look of labels, you can position them off-screen or use the clip technique and continue using placeholders. The downside is that some screen readers may read both the label and the placeholder, which isn't ideal, but being overly descriptive is better than being under-descriptive. I would personally be okay with some things being read twice if it only occurs on some browser/screen-reader combinations, and my code is otherwise valid and meets WCAG requirements.

Body:
If you really want to get creative, you could in theory use JS to manage the placeholder attribute(s). It would slow down the loading of the page somewhat, but you could then remove the placeholder attribute whenever the input receives focus and re-add it when the input loses focus. That would have the effect of disabling the placeholder attribute for assistive technology (at least in interactive forms mode). Sighted visitors probably wouldn't notice the difference. Here's an example in a fiddle. I tested in NVDA/Chrome and it worked, but I can't speak for any other screen-reader/browser combinations.

// on document load, add the placeholder text
document.addEventListener("DOMContentLoaded", function(){
   myInput.setAttribute("placeholder", myPlaceholder)
});

// when receiving focus, remove the placeholder text
myInput.addEventListener('focus', (event) => {
    myInput.removeAttribute("placeholder");
});

// when losing focus, re-add the placeholder text
myInput.addEventListener('blur', (event) => {
   myInput.setAttribute("placeholder", myPlaceholder)
});

As others have stated, using placeholders is not a suitable replacement for using labels. If you really don't like the look of labels, you can position them off-screen or use the clip technique and continue using placeholders. The downside is that some screen readers may read both the label and the placeholder, which isn't ideal, but being overly descriptive is better than being under-descriptive. I would personally be okay with some things being read twice if it only occurs on some browser/screen-reader combinations, and my code is otherwise valid and meets WCAG requirements.


问:
use managed identity to access azure keyvault in kubernetes cluster which is hosted on azure
I know with Azure Kubernetes service we can use managed identities to access azure resources like keyvaults. But i'm trying to learn if same procedure can be applied to a kubernetes cluster which is hosted on azure. My aim is to have kubernetes cluster in azure with 2 worker and 2 controller nodes but pods residing on those nodes should access azure keyvault with managed identity method similar to AKS. Is there anyway we can do it without coding in application?

I understand the scope of this question is big but it is really helpful if somebody provide any high level steps ?

thanks,
Santosh

答:
That's totally possible. AAD Pod identities rely on AAD (Azure Active Directory) and its permissions.

At the end AKS will have an infrastructure behind the scenes. So if you plan to not use AKS but install a cluster by yourself, for example with AKS engine, you can use AAD Pod Identities  / Managed Instances.

All you need is that those machines reside in "Azure" and rely on what is called Azure Instance Metadata Service (IMDS). Even you can enroll new machine instances coming outside from Azure with the project ARC. Anyway I cannot talk about it with Managed instances since I have not used it, anyway it should follow a similar pattern.

Here you have a good article that explains AAD Pod identities:

https://itnext.io/the-right-way-of-accessing-azure-services-from-inside-your-azure-kubernetes-cluster-14a335767680


问:
How to get every first element in 2 dimensional list
I have a list like this:

```<code>a = [[4.0, 4, 4.0], [3.0, 3, 3.6], [3.5, 6, 4.8]]
</code>```

I want an outcome like this (EVERY first element in the list):

```<code>4.0, 3.0, 3.5
</code>```

I tried a[::1][0], but it doesn't work

答:
If you have access to numpy,

import numpy as np
a_transposed = a.T
# Get first row
print(a_transposed[0])
```

The benefit of this method is that if you want the "second" element in a 2d list, all you have to do now is a_transposed[1]. The a_transposed object is already computed, so you do not need to recalculate.

Description

Finding the first element in a 2-D list can be rephrased as find the first column in the 2d list. Because your data structure is a list of rows, an easy way of sampling the value at the first index in every row is just by transposing the matrix and sampling the first list.

Body:
I have a list like this:

a = [[4.0, 4, 4.0], [3.0, 3, 3.6], [3.5, 6, 4.8]]

I want an outcome like this (EVERY first element in the list):

4.0, 3.0, 3.5

I tried a[::1][0], but it doesn't work

Body:
If you have access to numpy,

import numpy as np
a_transposed = a.T
# Get first row
print(a_transposed[0])

The benefit of this method is that if you want the "second" element in a 2d list, all you have to do now is a_transposed[1]. The a_transposed object is already computed, so you do not need to recalculate.

Description

Finding the first element in a 2-D list can be rephrased as find the first column in the 2d list. Because your data structure is a list of rows, an easy way of sampling the value at the first index in every row is just by transposing the matrix and sampling the first list.


问:
weird behaviour with svelte store and routify $params,
Im doing some kind of a forum where all the messages are linked to each other in some way. To save DB reads, I'm storing messages in a $messageStore as $messageStore[messageId].
I'm using routify's $params to navigate from /message/id1 to /message/id2 etc, where each page contains the message identified in the $params, but also other linked messages that might or might not already be in the store..

My problem is:

1st, the components are not unmounting, so I trigger that when $params change by flicking a value for 1ms that disables the rendering of the main component and forces the init() function to check what it needs to fetch on the DB or not.. It is ugly, it seems to work so far, but I bet this will fail one day depending on the machine it runs on.

2nd, after doing that, I ran into things that I didn't understand. The $messageStore doesn't change while the page is changing, but all of a sudden I get plenty of undefined value. It seems like the $params are going from value1 to nothing to value2.
Also if I check in the init() function if($messageStore[$params.id].someKey==="someValue"), it doesn't pass, although I'm sure it's in the store.

If I did

console.log($messageStore[$params.id].someKey) console.log($messageStore[$params.id].someKey==="someValue") if($messageStore[$params.id].someKey==="someValue"){console.log('passed')}else{console.log("failed")}

I got:

```<code>"someValue"
true
"failed"
</code>```

It is like if console.log() is not giving the result at the time of execution..

Before using Routify, I had the same king of stuff with svelte-spa-router, so It might be something that I don't get with svelte and changing store values and order of execution..

I seemed to find a way around by passing the params with a scoped prop from the top component that flickers on page change, but if somebody could teach me something there, I would be really grateful..

答:
I think I do the same thing with images, but I'm a little confused as to your use case. For me, I have a folder gallery white an index.svelte and a [image].svelte. So you can go to gallery/1, gallery/2, etc. and see different images. Instead of using params, just use export let image (or in your case export let id, to access the message id. Then you can use your id to get the correct index in your $messagestore with something like:

```<code>//this will get the the url param
export let id
//this will change every time your id chages, i.e. message/1 to message/2
$: if (id) {
    getIndex();
}

 async function getIndex() {
//make sure the message store has finished loading, you'd set this in the store
await waitFor(() => $messageStoreLoaded === true);

sIndex = await $messageStore.findIndex(p => p.id === id);
//if for whatever reason the message is not in the store, do some error handling
if (sIndex == -1) sIndex = -2;

//keep a store of what index you're on, this is another writable store
await messageStoreIndex.update(n => (n = sIndex));

//load the new message data from the store
newMessage = $storePics[$storePicsIndex];
}

function waitFor(conditionFunction) {
  const poll = (resolve) => {
    if (conditionFunction()) resolve("The Thing Finished");
//you can get rid of the console.log, and change the millisenconds to whatever, I usually stick to 100 to 400 for most things
    else console.log("Still Wating..."), setTimeout((_) => poll(resolve), 200);
  };
  return new Promise(poll);
}
</code>```

Hopefully that gives you a starting point. You can make one database call to populate your messageStore, and then just keep track of what index you're on with the function.

Body:
Im doing some kind of a forum where all the messages are linked to each other in some way. To save DB reads, I'm storing messages in a $messageStore as $messageStore[messageId].
I'm using routify's $params to navigate from /message/id1 to /message/id2 etc, where each page contains the message identified in the $params, but also other linked messages that might or might not already be in the store..

My problem is:

1st, the components are not unmounting, so I trigger that when $params change by flicking a value for 1ms that disables the rendering of the main component and forces the init() function to check what it needs to fetch on the DB or not.. It is ugly, it seems to work so far, but I bet this will fail one day depending on the machine it runs on.

2nd, after doing that, I ran into things that I didn't understand. The $messageStore doesn't change while the page is changing, but all of a sudden I get plenty of undefined value. It seems like the $params are going from value1 to nothing to value2.
Also if I check in the init() function if($messageStore[$params.id].someKey==="someValue"), it doesn't pass, although I'm sure it's in the store.

If I did

console.log($messageStore[$params.id].someKey) console.log($messageStore[$params.id].someKey==="someValue") if($messageStore[$params.id].someKey==="someValue"){console.log('passed')}else{console.log("failed")}

I got:

"someValue"
true
"failed"

It is like if console.log() is not giving the result at the time of execution..

Before using Routify, I had the same king of stuff with svelte-spa-router, so It might be something that I don't get with svelte and changing store values and order of execution..

I seemed to find a way around by passing the params with a scoped prop from the top component that flickers on page change, but if somebody could teach me something there, I would be really grateful..

Body:
I think I do the same thing with images, but I'm a little confused as to your use case. For me, I have a folder gallery white an index.svelte and a [image].svelte. So you can go to gallery/1, gallery/2, etc. and see different images. Instead of using params, just use export let image (or in your case export let id, to access the message id. Then you can use your id to get the correct index in your $messagestore with something like:

//this will get the the url param
export let id
//this will change every time your id chages, i.e. message/1 to message/2
$: if (id) {
    getIndex();
}

 async function getIndex() {
//make sure the message store has finished loading, you'd set this in the store
await waitFor(() => $messageStoreLoaded === true);

sIndex = await $messageStore.findIndex(p => p.id === id);
//if for whatever reason the message is not in the store, do some error handling
if (sIndex == -1) sIndex = -2;

//keep a store of what index you're on, this is another writable store
await messageStoreIndex.update(n => (n = sIndex));

//load the new message data from the store
newMessage = $storePics[$storePicsIndex];
}

function waitFor(conditionFunction) {
  const poll = (resolve) => {
    if (conditionFunction()) resolve("The Thing Finished");
//you can get rid of the console.log, and change the millisenconds to whatever, I usually stick to 100 to 400 for most things
    else console.log("Still Wating..."), setTimeout((_) => poll(resolve), 200);
  };
  return new Promise(poll);
}

Hopefully that gives you a starting point. You can make one database call to populate your messageStore, and then just keep track of what index you're on with the function.


问:
Embedding video using embed tag not working in modern browsers
I have a very simple html page with following content:

```<code><embed width="260" height="282" src="rtuner.wmv" showstatusbar="true" showgotobar="true" showdisplay="true" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" type="application/x-mplayer2" name="rTuner" />
</code>```

Note that 'src' attribute of embed element takes a relative url. This very simple html element plays the video in older browsers like Firefox 10, IE8 etc., but it doesn't play in FF 17 and Chrome 27. If 'src' attribute is assigned a absolute URL then the video works again.

Any ideas why so?

EDIT: Observed Firebug console shows this warning - 'Error: Permission denied to access object'. Does this message give any hint?

答:
```<code><h1>Video examples:</h1>
<iframe src="https://www.youtube.com/embed/j6gNKR0TMMo"></iframe>

<img src="https://cdn.sstatic.net/Sites/stackoverflow/Img/error-lolcat-problemz.jpg">
<embed src="https://www.youtube.com/embed/j6gNKR0TMMo" width="1000" height="600">
<h1>Image examples:</h1>
<h1>Link examples:</h1>
<a href="https://area51.stackexchange.com">Link</a>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a very simple html page with following content:

<embed width="260" height="282" src="rtuner.wmv" showstatusbar="true" showgotobar="true" showdisplay="true" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" type="application/x-mplayer2" name="rTuner" />

Note that 'src' attribute of embed element takes a relative url. This very simple html element plays the video in older browsers like Firefox 10, IE8 etc., but it doesn't play in FF 17 and Chrome 27. If 'src' attribute is assigned a absolute URL then the video works again.

Any ideas why so?

EDIT: Observed Firebug console shows this warning - 'Error: Permission denied to access object'. Does this message give any hint?


问:
Is there a way to tell SQL Server to check the table for a duplicate before inserting each new row?
I tried using the SQL below to insert values from one table, importTable, into another table, POInvoicing. It appears that the way this query below works is it checks the POInvoicing table for any possible duplicates from the importTable and for those entries that are not duplicates, it inserts them into the table. The end result is SQL inserting duplicates that already exist in importTable. Is there a way to tell SQL Server to check the table for a possible duplicate entry, if not, add the next row. Then check the table for a duplicate entry, if not, add the next row. I know this will be slower but speed isn't an issue.

INSERT INTO POInvoicing
    (VendorID, InvoiceNo)
SELECT dbo.importTable.VendorID,
       dbo.importTable.InvoiceNo
  FROM dbo.importTable
WHERE NOT EXISTS (SELECT VendorID,
                         InvoiceNo
                    FROM POInvoicing
                   WHERE POInvoicing.VendorID = dbo.importTable.VendorID AND
                         POInvoicing.InvoiceNo = dbo.importTable.InvoiceNo)
```

This isn't exactly the functionality I was hoping for. What I want is for the query to insert a row into the table and then check for "duplicates" before inserting the next row. What constitutes a duplicate in the importTable would be the combination of VendorID and InvoiceNo. There are about a dozen different columns in importTable and technically each row is distinct, so DISTINCT won't work here.

I can't simply remove duplicates from the importTable for a couple of reasons not relevant to the question above (though I can provide it if necessary), so that method is out.

答:
Adding a primary key constraint or unique key constraint in your table to avoid duplicate data insertion.

Also use distinct keyword in your select query to avoid this.

Duplicate rows can also be eliminated by using group by or row_number() functions in SQL.

Using DISTINCT Keyword

```<code> INSERT INTO POInvoicing
 (VendorID, InvoiceNo, InvoiceDate)
 SELECT DISTINCT dbo.importTable.VendorID,
   dbo.importTable.InvoiceNo,
   dbo.importTable.InvoiceDate
  FROM dbo.importTable
 WHERE NOT EXISTS (SELECT VendorID,
                     InvoiceNo
                FROM POInvoicing
               WHERE POInvoicing.VendorID = dbo.importTable.VendorID
 AND
                     POInvoicing.InvoiceNo = dbo.importTable.InvoiceNo)
</code>```

Try this INNER JOIN

```<code> INSERT INTO POInvoicing
 (VendorID, InvoiceNo, InvoiceDate)
 SELECT dbo.importTable.VendorID,
   dbo.importTable.InvoiceNo,
   dbo.importTable.InvoiceDate
  FROM dbo.importTable IM
  INNER JOIN POInvoicing S ON S.POInvoicing.VendorID <>
  dbo.importTable.VendorID
 AND
                     S.POInvoicing.InvoiceNo <> dbo.importTable.InvoiceN
</code>```

Body:
I tried using the SQL below to insert values from one table, importTable, into another table, POInvoicing. It appears that the way this query below works is it checks the POInvoicing table for any possible duplicates from the importTable and for those entries that are not duplicates, it inserts them into the table. The end result is SQL inserting duplicates that already exist in importTable. Is there a way to tell SQL Server to check the table for a possible duplicate entry, if not, add the next row. Then check the table for a duplicate entry, if not, add the next row. I know this will be slower but speed isn't an issue.

INSERT INTO POInvoicing
    (VendorID, InvoiceNo)
SELECT dbo.importTable.VendorID,
       dbo.importTable.InvoiceNo
  FROM dbo.importTable
WHERE NOT EXISTS (SELECT VendorID,
                         InvoiceNo
                    FROM POInvoicing
                   WHERE POInvoicing.VendorID = dbo.importTable.VendorID AND
                         POInvoicing.InvoiceNo = dbo.importTable.InvoiceNo)

This isn't exactly the functionality I was hoping for. What I want is for the query to insert a row into the table and then check for "duplicates" before inserting the next row. What constitutes a duplicate in the importTable would be the combination of VendorID and InvoiceNo. There are about a dozen different columns in importTable and technically each row is distinct, so DISTINCT won't work here.

I can't simply remove duplicates from the importTable for a couple of reasons not relevant to the question above (though I can provide it if necessary), so that method is out.

Body:
Adding a primary key constraint or unique key constraint in your table to avoid duplicate data insertion.

Also use distinct keyword in your select query to avoid this.

Duplicate rows can also be eliminated by using group by or row_number() functions in SQL.

Using DISTINCT Keyword

 INSERT INTO POInvoicing
 (VendorID, InvoiceNo, InvoiceDate)
 SELECT DISTINCT dbo.importTable.VendorID,
   dbo.importTable.InvoiceNo,
   dbo.importTable.InvoiceDate
  FROM dbo.importTable
 WHERE NOT EXISTS (SELECT VendorID,
                     InvoiceNo
                FROM POInvoicing
               WHERE POInvoicing.VendorID = dbo.importTable.VendorID
 AND
                     POInvoicing.InvoiceNo = dbo.importTable.InvoiceNo)

Try this INNER JOIN

 INSERT INTO POInvoicing
 (VendorID, InvoiceNo, InvoiceDate)
 SELECT dbo.importTable.VendorID,
   dbo.importTable.InvoiceNo,
   dbo.importTable.InvoiceDate
  FROM dbo.importTable IM
  INNER JOIN POInvoicing S ON S.POInvoicing.VendorID <>
  dbo.importTable.VendorID
 AND
                     S.POInvoicing.InvoiceNo <> dbo.importTable.InvoiceN


问:
Ocaml count trie elements
I'm trying to find how many characters i have in my Trie.

This is my Trie type.

```<code>type 'a t = Node of 'a list * ('a arc list) and 'a arc = char * 'a t
</code>```

This is my implementation that is not exhaustive:

```<code>let arc_size trie =
let rec count_arcs counter trie =
match trie with
| Node (_,[]) -> counter
| Node (_,[(_,x)] -> count_arcs (counter+1) trie
in
count_arcs 0 trie;;
</code>```

This would work if the trie contained only 1 word. The problem is if the trie branches out and one of the nodes has this type Node(_,[(_,x)] :: _ :: _)

I can't seem to find a match pattern for this case since if i match the trie with Node(_,x) the x in this case is a arc list but my function has a trie as argument. I'm having trouble branching out towards the other 'a arcs in my 'a arc list.

答:
You shall call your count_arcs function recursively on each subarc of the node (you're calling it recursively on the same trie which remains invariant during recursion, thus your function will never terminate if it hit the second branch of your example).

You can rely on List.fold_left and for a node x that has a list of arcs xs define the number of arcs as a sum of the number of arcs each arc in xs has, plus the number of arcs that x has.

Alternatively, you can use pattern-matching and manually deconstruct the list of arcs, but it is better to split the complex task into small subtasks and then combine them. If you're not allowed to use the functions from the standard library (for didactic purposes) then it is a good time to implement your own fold function.

Title: Ocaml count trie elements

Body:
I'm trying to find how many characters i have in my Trie.

This is my Trie type.

type 'a t = Node of 'a list * ('a arc list) and 'a arc = char * 'a t

This is my implementation that is not exhaustive:

let arc_size trie =
let rec count_arcs counter trie =
match trie with
| Node (_,[]) -> counter
| Node (_,[(_,x)] -> count_arcs (counter+1) trie
in
count_arcs 0 trie;;

This would work if the trie contained only 1 word. The problem is if the trie branches out and one of the nodes has this type Node(_,[(_,x)] :: _ :: _)

I can't seem to find a match pattern for this case since if i match the trie with Node(_,x) the x in this case is a arc list but my function has a trie as argument. I'm having trouble branching out towards the other 'a arcs in my 'a arc list.


问:
Jmeter redirection challenges

JMeter URL redirection challenges from 302 to 200 status code

I'm trying to perform URL HTTP connection authentication with JMETER and facing challenges on redirection URL with JMeter from 302 to 200 status code within the organization environment. The office environment using windows authentication NTLM2 methods.

However I’m facing URL redirection blockage when I tried to navigate through an internal website as it stops when it reaches 302 status code and failed to navigate further to status code 200 through JMeter but when I display the same URL with chrome browser, it able to successfully display the web with status code 200 using chrome browser.

How does the URL Authentication work?

at 1st the given URL which includes end-user parameters were entered to display the web messages.[shows HTTP status code 302]

The URL then redirects to another portal login URL to acknowledge the authentication.[shows HTTP status code 302]

Problem/Issue:-

The URL only successfully performing the 1st 2 options but it failed to perform the final redirection to have status code 200

At the moment the HTTP result in Jmeter through "View Result Tree" and "View Result Table" is both showing status code 302

Limitation

I couldnt install any external chrome pluggin due to the security restriction within the given operating system environment

proxy has been included. in both "HTTP default Advance" option and "HTTP Advance" option with the relavent user proxy details, id and password

Additional Details

The website were build part of the liferay framework using java spring.

We notice through jmeter logs viewer that the "Pooling HTTP Connection Manager" being shut down as well.

I've included the log viewer from the JMETER in here

Challenges

I'm not sure what further configuration i should do to allow the 3rd redirection to be happened.

答:
You need to add HTTP Authorization Manager, change "Mechanism" to BASIC_DIGEST and provide your domain and Windows credentials there

This way JMeter will be able to build a proper Authorization header and you will be able to proceed to your application

More information: Windows Authentication with Apache JMeter

Title: Jmeter redirection challenges


问:
How to get the foreign key in Entity Framework?
I am developing StudentApp in .NET 3.5 SP1 MVC Application.

I have two tables

Course

    CourseID, course_Name

Students

    studentID, student_Name, courseID(fk)

Now I made StudentApp.dbml which is having both table as entities.

As Foreign key will not be present in student entity,
I can not display courseID in student model, more over i can not generate add, edit, list views.

So tell me how to display courseID(fk) in student & i also want course name instead.

And also dropdownbox showing course name & storing courseID in edit view .

答: if you create the correct relationship in your SQL server database, then when you add the tables to your DBML designer, the relationships will be copied across also and your code will link up automatically.</p>

OwnerDisplayName: Vikas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chad Moran

OwnerDisplayName: cottsak


问:
pip install does not install required dependencies declared with install_requires
My question is similar to this question, yet different.

I am the maintainer of the Python package omrdatasettools where I provide users with small helper scripts to perform dataset downloads, etc. My scripts have dependencies on their own, e.g., lxml or tqdm. I want people to be able to install my library and use it, however when you create a new conda environment and call pip install omrdatasettools the installation fails because it does not find the necessary packages.

What I've done so far: I've added all necessary libraries into the install_requires-section of my setup.py

setup(
   ...
   install_requires=['Pillow', 'muscima', "mung", "numpy", "tqdm", "scikit-image", "lxml"]
   ...
)

```

<p>and I am building and distributing the package with the commands:</p>

```python setup.py sdist
twine upload --repository pypi dist/*
```

<p>Uploading works as expected and now users should be able to run </p>

```conda create --name tempTest python==3.7
activate tempTest
pip install omrdatasettools
```

<p>and use my library. However, when you run these lines, you get the following error:</p>

```Collecting omrdatasettools
  Downloading omrdatasettools-1.2.tar.gz (39 kB)
    ERROR: Command errored out with exit status 1:
     command: /Users/alex/opt/anaconda3/envs/tempTest/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/setup.py'"'"'; __file__='"'"'/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/pip-egg-info
         cwd: /private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/
    Complete output (9 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/setup.py", line 8, in <module>
        import omrdatasettools
      File "/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/omrdatasettools/__init__.py", line 3, in <module>
        from .Downloader import *
      File "/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/omrdatasettools/Downloader.py", line 9, in <module>
        from lxml import etree
    ModuleNotFoundError: No module named 'lxml'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
```

I read something about pip not finding the right repository to download those dependencies, but I am not sure what I am missing here. If you install all necessary dependencies first and then my package, everything works.

Any help would be highly appreciated!

答:
You do import omrdatasettools in your setup.py, omrdatasettools/__init__.py imports .Downloader and omrdatasettools/Downloader.py imports lxml which is not yet installed.

Short resume: do not import (directly or indirectly) uninstalled modules in setup.py.

Ways to workaround:

Do not import your submodules in __init__.py so when setup.py imports omrdatasettools it only imports __init__.py but not submodules.

In your setup.py you probably only need the version so do not import it but read from a file. You can even read it from a Python module by evaluating code without triggering import from __init__.py. Like this:

```<code>from os.path import abspath, dirname, join
from setuptools import setup

versionpath = join(abspath(dirname(__file__)), 'omrdatasettools', '__version__.py')
version_dict = {}

exec(open(versionpath, 'r').read(), version_dict)
</code>```

Now you have version_dict['__version__'].

Body:
My question is similar to this question, yet different.

I am the maintainer of the Python package omrdatasettools where I provide users with small helper scripts to perform dataset downloads, etc. My scripts have dependencies on their own, e.g., lxml or tqdm. I want people to be able to install my library and use it, however when you create a new conda environment and call pip install omrdatasettools the installation fails because it does not find the necessary packages.

What I've done so far: I've added all necessary libraries into the install_requires-section of my setup.py

setup(
   ...
   install_requires=['Pillow', 'muscima', "mung", "numpy", "tqdm", "scikit-image", "lxml"]
   ...
)

and I am building and distributing the package with the commands:

python setup.py sdist
twine upload --repository pypi dist/*

Uploading works as expected and now users should be able to run

conda create --name tempTest python==3.7
activate tempTest
pip install omrdatasettools

and use my library. However, when you run these lines, you get the following error:

Collecting omrdatasettools
  Downloading omrdatasettools-1.2.tar.gz (39 kB)
    ERROR: Command errored out with exit status 1:
     command: /Users/alex/opt/anaconda3/envs/tempTest/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/setup.py'"'"'; __file__='"'"'/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/pip-egg-info
         cwd: /private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/
    Complete output (9 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/setup.py", line 8, in <module>
        import omrdatasettools
      File "/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/omrdatasettools/__init__.py", line 3, in <module>
        from .Downloader import *
      File "/private/var/folders/bs/1t82d5697dn_nd32ngbq_9bh0000gn/T/pip-install-s56i2r4e/omrdatasettools/omrdatasettools/Downloader.py", line 9, in <module>
        from lxml import etree
    ModuleNotFoundError: No module named 'lxml'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

I read something about pip not finding the right repository to download those dependencies, but I am not sure what I am missing here. If you install all necessary dependencies first and then my package, everything works.

Any help would be highly appreciated!

Body:
You do import omrdatasettools in your setup.py, omrdatasettools/__init__.py imports .Downloader and omrdatasettools/Downloader.py imports lxml which is not yet installed.

Short resume: do not import (directly or indirectly) uninstalled modules in setup.py.

Ways to workaround:

Do not import your submodules in __init__.py so when setup.py imports omrdatasettools it only imports __init__.py but not submodules.

In your setup.py you probably only need the version so do not import it but read from a file. You can even read it from a Python module by evaluating code without triggering import from __init__.py. Like this:

from os.path import abspath, dirname, join
from setuptools import setup

versionpath = join(abspath(dirname(__file__)), 'omrdatasettools', '__version__.py')
version_dict = {}

exec(open(versionpath, 'r').read(), version_dict)

Now you have version_dict['__version__'].


问:
Create a new pandas DataFrame from an existing one based on whether it's multiIndex appears in a list
I want to be able to take a large DataFrame which has a multiIndex and create two new ones based on whether or not the index appears in a list.

As an example, lets say I have a DataFrame which has a MultiIndex of ['Name', 'Surname'] and columns of different test results ['Score1', 'Score2'].
Given a list of names I want to be able to create two new DataFrames, one containing entries whose names are in the list and one whose names are not.

```<code>In [1]:
data = {'Name':['Jake', 'Jack', 'June', 'Jane'],
        'Surname': ['Scott', 'Smith', 'Saint', 'Smith'],
        'Score1':[85, 78, 95, 90],
        'Score2': [79, 91, 83, 68]}
df = pd.DataFrame(data)
df = df.set_index(['Name', 'Surname'])
Males = [['Jake', 'Scott'], ['Jack', 'Smith']]
df

Out [1]:
            Score1  Score2
Name    Surname
Jake    Scott   85  79
Jack    Smith   78  91
June    Saint   95  83
Jane    Smith   90  68
</code>```

Then if a row index is in the Males it will be put into MalesDF else it will be put into FemalesDF

```<code>In [2]:    MalesDF

Out [2]:
             Score1 Score2
Name    Surname
Jake    Scott   85  79
Jack    Smith   78  91
</code>```

Obviously in this small example it might be simple enough to do with a for loop but in my actual case I have thousands of names and a list about a quarter of the size. So a for loop would be too inefficient

答:
Use, index.isin to create a boolean mask, and filter the df to create the male and female df based on this boolean mask:

```<code>m = df.index.isin(Males)
df_males = df[m]
df_females = df[~m]
</code>```

Result:

```<code># df_males
              Score1  Score2
Name Surname
Jake Scott        85      79
Jack Smith        78      91

# df_females
              Score1  Score2
Name Surname
June Saint        95      83
Jane Smith        90      68
</code>```

Body:
I want to be able to take a large DataFrame which has a multiIndex and create two new ones based on whether or not the index appears in a list.

As an example, lets say I have a DataFrame which has a MultiIndex of ['Name', 'Surname'] and columns of different test results ['Score1', 'Score2'].
Given a list of names I want to be able to create two new DataFrames, one containing entries whose names are in the list and one whose names are not.

In [1]:
data = {'Name':['Jake', 'Jack', 'June', 'Jane'],
        'Surname': ['Scott', 'Smith', 'Saint', 'Smith'],
        'Score1':[85, 78, 95, 90],
        'Score2': [79, 91, 83, 68]}
df = pd.DataFrame(data)
df = df.set_index(['Name', 'Surname'])
Males = [['Jake', 'Scott'], ['Jack', 'Smith']]
df

Out [1]:
            Score1  Score2
Name    Surname
Jake    Scott   85  79
Jack    Smith   78  91
June    Saint   95  83
Jane    Smith   90  68

Then if a row index is in the Males it will be put into MalesDF else it will be put into FemalesDF

In [2]:    MalesDF

Out [2]:
             Score1 Score2
Name    Surname
Jake    Scott   85  79
Jack    Smith   78  91

Obviously in this small example it might be simple enough to do with a for loop but in my actual case I have thousands of names and a list about a quarter of the size. So a for loop would be too inefficient

Body:
Use, index.isin to create a boolean mask, and filter the df to create the male and female df based on this boolean mask:

m = df.index.isin(Males)
df_males = df[m]
df_females = df[~m]

Result:

# df_males
              Score1  Score2
Name Surname
Jake Scott        85      79
Jack Smith        78      91

# df_females
              Score1  Score2
Name Surname
June Saint        95      83
Jane Smith        90      68


问:
How to read a string value with a delimiter on Arduino?
I have to manage servos from a computer.

So I have to send manage messages from computer to Arduino. I need manage the number of servo and the corner. I'm thinking of sendin something like this : "1;130" (first servo and corner 130, delimeter ";").

Are there any better methods to accomplish this?

Here is my this code :

String foo = "";
void setup(){
   Serial.begin(9600);
}

void loop(){
   readSignalFromComp();
}

void readSignalFromComp() {
  if (Serial.available() > 0)
      foo = '';
  while (Serial.available() > 0){
     foo += Serial.read();
  }
  if (!foo.equals(""))
    Serial.print(foo);
}
```

This doesn't work. What's the problem?

答:
This code reads string until it sees '>' character

```<code>void loop() {
  // put your main code here, to run repeatedly:
  String msg = getMessage();
}

String getMessage() {
  String msg = "";

  while (Serial.available()>0) {
    msg =  Serial.readStringUntil('>');
  }
  return msg;
}
</code>```

Body:
I have to manage servos from a computer.

So I have to send manage messages from computer to Arduino. I need manage the number of servo and the corner. I'm thinking of sendin something like this : "1;130" (first servo and corner 130, delimeter ";").

Are there any better methods to accomplish this?

Here is my this code :

String foo = "";
void setup(){
   Serial.begin(9600);
}

void loop(){
   readSignalFromComp();
}

void readSignalFromComp() {
  if (Serial.available() > 0)
      foo = '';
  while (Serial.available() > 0){
     foo += Serial.read();
  }
  if (!foo.equals(""))
    Serial.print(foo);
}

This doesn't work. What's the problem?

Body:
This code reads string until it sees '>' character

void loop() {
  // put your main code here, to run repeatedly:
  String msg = getMessage();
}

String getMessage() {
  String msg = "";

  while (Serial.available()>0) {
    msg =  Serial.readStringUntil('>');
  }
  return msg;
}


问:
No such file to load -- azure/storage.rb
We're trying to use azure azure-storage-blob with Rails active storage and we're getting an error during puma booting process:

```<code>/usr/local/bundle/gems/activesupport-5.2.4.3/lib/active_support/dependencies.rb:291:in `require': No such file to load -- azure/storage.rb (LoadError)`
</code>```

Rails version: 5.2.4.3
azure-storage-blob version: 2.0.0

Adding the old azure-storage gem and downgrading the azure-storage-blob to 1.1.0 fixes it. But it requires to downgrade other gems (faraday).

Related github issue: https://github.com/Azure/azure-storage-ruby/issues/166

Any idea what could cause it?

答:
Figured this thing out. It's an ActiveStorage issue - when they changed from active-storage to active-storage-blob, they never backported the change back to Rails 5.2. Or, at least not yet

For anyone still having this issue, until it is backported, anyone can monkey-patch it:
Add two empty files:
lib/azure/storage/core/auth/shared_access_signature.rb, and lib/azure/storage.rb

Add this to config/initializers/active_storage_6_patch.rb (this is the current master version of the ActiveStorage module):

```<code>require "azure/storage/blob"
require 'active_storage/service/azure_storage_service'
module ActiveStorage
  # Wraps the Microsoft Azure Storage Blob Service as an Active Storage service.
  # See ActiveStorage::Service for the generic API documentation that applies to all services.
  class Service::AzureStorageService < Service
    attr_reader :client, :container, :signer

    def initialize(storage_account_name:, storage_access_key:, container:, public: false, **options)
      @client = Azure::Storage::Blob::BlobService.create(storage_account_name: storage_account_name, storage_access_key: storage_access_key, **options)
      @signer = Azure::Storage::Common::Core::Auth::SharedAccessSignature.new(storage_account_name, storage_access_key)
      @container = container
      @public = public
    end

    def upload(key, io, checksum: nil, filename: nil, content_type: nil, disposition: nil, **)
      instrument :upload, key: key, checksum: checksum do
        handle_errors do
          content_disposition = content_disposition_with(filename: filename, type: disposition) if disposition && filename

          client.create_block_blob(container, key, IO.try_convert(io) || io, content_md5: checksum, content_type: content_type, content_disposition: content_disposition)
        end
      end
    end

    def download(key, &block)
      if block_given?
        instrument :streaming_download, key: key do
          stream(key, &block)
        end
      else
        instrument :download, key: key do
          handle_errors do
            _, io = client.get_blob(container, key)
            io.force_encoding(Encoding::BINARY)
          end
        end
      end
    end

    def download_chunk(key, range)
      instrument :download_chunk, key: key, range: range do
        handle_errors do
          _, io = client.get_blob(container, key, start_range: range.begin, end_range: range.exclude_end? ? range.end - 1 : range.end)
          io.force_encoding(Encoding::BINARY)
        end
      end
    end

    def delete(key)
      instrument :delete, key: key do
        client.delete_blob(container, key)
      rescue Azure::Core::Http::HTTPError => e
        raise unless e.type == "BlobNotFound"
        # Ignore files already deleted
      end
    end

    def delete_prefixed(prefix)
      instrument :delete_prefixed, prefix: prefix do
        marker = nil

        loop do
          results = client.list_blobs(container, prefix: prefix, marker: marker)

          results.each do |blob|
            client.delete_blob(container, blob.name)
          end

          break unless marker = results.continuation_token.presence
        end
      end
    end

    def exist?(key)
      instrument :exist, key: key do |payload|
        answer = blob_for(key).present?
        payload[:exist] = answer
        answer
      end
    end

    def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
      instrument :url, key: key do |payload|
        generated_url = signer.signed_uri(
          uri_for(key), false,
          service: "b",
          permissions: "rw",
          expiry: format_expiry(expires_in)
        ).to_s

        payload[:url] = generated_url

        generated_url
      end
    end

    def headers_for_direct_upload(key, content_type:, checksum:, filename: nil, disposition: nil, **)
      content_disposition = content_disposition_with(type: disposition, filename: filename) if filename

      { "Content-Type" => content_type, "Content-MD5" => checksum, "x-ms-blob-content-disposition" => content_disposition, "x-ms-blob-type" => "BlockBlob" }
    end

    private
      def private_url(key, expires_in:, filename:, disposition:, content_type:, **)
        signer.signed_uri(
          uri_for(key), false,
          service: "b",
          permissions: "r",
          expiry: format_expiry(expires_in),
          content_disposition: content_disposition_with(type: disposition, filename: filename),
          content_type: content_type
        ).to_s
      end

      def public_url(key, **)
        uri_for(key).to_s
      end

      def uri_for(key)
        client.generate_uri("#{container}/#{key}")
      end

      def blob_for(key)
        client.get_blob_properties(container, key)
      rescue Azure::Core::Http::HTTPError
        false
      end

      def format_expiry(expires_in)
        expires_in ? Time.now.utc.advance(seconds: expires_in).iso8601 : nil
      end

      # Reads the object for the given key in chunks, yielding each to the block.
      def stream(key)
        blob = blob_for(key)

        chunk_size = 5.megabytes
        offset = 0

        raise ActiveStorage::FileNotFoundError unless blob.present?

        while offset < blob.properties[:content_length]
          _, chunk = client.get_blob(container, key, start_range: offset, end_range: offset + chunk_size - 1)
          yield chunk.force_encoding(Encoding::BINARY)
          offset += chunk_size
        end
      end

      def handle_errors
        yield
      rescue Azure::Core::Http::HTTPError => e
        case e.type
        when "BlobNotFound"
          raise ActiveStorage::FileNotFoundError
        when "Md5Mismatch"
          raise ActiveStorage::IntegrityError
        else
          raise
        end
      end
  end
end
</code>```

Body:
We're trying to use azure azure-storage-blob with Rails active storage and we're getting an error during puma booting process:

/usr/local/bundle/gems/activesupport-5.2.4.3/lib/active_support/dependencies.rb:291:in `require': No such file to load -- azure/storage.rb (LoadError)`

Rails version: 5.2.4.3
azure-storage-blob version: 2.0.0

Adding the old azure-storage gem and downgrading the azure-storage-blob to 1.1.0 fixes it. But it requires to downgrade other gems (faraday).

Related github issue: https://github.com/Azure/azure-storage-ruby/issues/166

Any idea what could cause it?

Body:
Figured this thing out. It's an ActiveStorage issue - when they changed from active-storage to active-storage-blob, they never backported the change back to Rails 5.2. Or, at least not yet

For anyone still having this issue, until it is backported, anyone can monkey-patch it:
Add two empty files:
lib/azure/storage/core/auth/shared_access_signature.rb, and lib/azure/storage.rb

Add this to config/initializers/active_storage_6_patch.rb (this is the current master version of the ActiveStorage module):

require "azure/storage/blob"
require 'active_storage/service/azure_storage_service'
module ActiveStorage
  # Wraps the Microsoft Azure Storage Blob Service as an Active Storage service.
  # See ActiveStorage::Service for the generic API documentation that applies to all services.
  class Service::AzureStorageService < Service
    attr_reader :client, :container, :signer

    def initialize(storage_account_name:, storage_access_key:, container:, public: false, **options)
      @client = Azure::Storage::Blob::BlobService.create(storage_account_name: storage_account_name, storage_access_key: storage_access_key, **options)
      @signer = Azure::Storage::Common::Core::Auth::SharedAccessSignature.new(storage_account_name, storage_access_key)
      @container = container
      @public = public
    end

    def upload(key, io, checksum: nil, filename: nil, content_type: nil, disposition: nil, **)
      instrument :upload, key: key, checksum: checksum do
        handle_errors do
          content_disposition = content_disposition_with(filename: filename, type: disposition) if disposition && filename

          client.create_block_blob(container, key, IO.try_convert(io) || io, content_md5: checksum, content_type: content_type, content_disposition: content_disposition)
        end
      end
    end

    def download(key, &block)
      if block_given?
        instrument :streaming_download, key: key do
          stream(key, &block)
        end
      else
        instrument :download, key: key do
          handle_errors do
            _, io = client.get_blob(container, key)
            io.force_encoding(Encoding::BINARY)
          end
        end
      end
    end

    def download_chunk(key, range)
      instrument :download_chunk, key: key, range: range do
        handle_errors do
          _, io = client.get_blob(container, key, start_range: range.begin, end_range: range.exclude_end? ? range.end - 1 : range.end)
          io.force_encoding(Encoding::BINARY)
        end
      end
    end

    def delete(key)
      instrument :delete, key: key do
        client.delete_blob(container, key)
      rescue Azure::Core::Http::HTTPError => e
        raise unless e.type == "BlobNotFound"
        # Ignore files already deleted
      end
    end

    def delete_prefixed(prefix)
      instrument :delete_prefixed, prefix: prefix do
        marker = nil

        loop do
          results = client.list_blobs(container, prefix: prefix, marker: marker)

          results.each do |blob|
            client.delete_blob(container, blob.name)
          end

          break unless marker = results.continuation_token.presence
        end
      end
    end

    def exist?(key)
      instrument :exist, key: key do |payload|
        answer = blob_for(key).present?
        payload[:exist] = answer
        answer
      end
    end

    def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
      instrument :url, key: key do |payload|
        generated_url = signer.signed_uri(
          uri_for(key), false,
          service: "b",
          permissions: "rw",
          expiry: format_expiry(expires_in)
        ).to_s

        payload[:url] = generated_url

        generated_url
      end
    end

    def headers_for_direct_upload(key, content_type:, checksum:, filename: nil, disposition: nil, **)
      content_disposition = content_disposition_with(type: disposition, filename: filename) if filename

      { "Content-Type" => content_type, "Content-MD5" => checksum, "x-ms-blob-content-disposition" => content_disposition, "x-ms-blob-type" => "BlockBlob" }
    end

    private
      def private_url(key, expires_in:, filename:, disposition:, content_type:, **)
        signer.signed_uri(
          uri_for(key), false,
          service: "b",
          permissions: "r",
          expiry: format_expiry(expires_in),
          content_disposition: content_disposition_with(type: disposition, filename: filename),
          content_type: content_type
        ).to_s
      end

      def public_url(key, **)
        uri_for(key).to_s
      end

      def uri_for(key)
        client.generate_uri("#{container}/#{key}")
      end

      def blob_for(key)
        client.get_blob_properties(container, key)
      rescue Azure::Core::Http::HTTPError
        false
      end

      def format_expiry(expires_in)
        expires_in ? Time.now.utc.advance(seconds: expires_in).iso8601 : nil
      end

      # Reads the object for the given key in chunks, yielding each to the block.
      def stream(key)
        blob = blob_for(key)

        chunk_size = 5.megabytes
        offset = 0

        raise ActiveStorage::FileNotFoundError unless blob.present?

        while offset < blob.properties[:content_length]
          _, chunk = client.get_blob(container, key, start_range: offset, end_range: offset + chunk_size - 1)
          yield chunk.force_encoding(Encoding::BINARY)
          offset += chunk_size
        end
      end

      def handle_errors
        yield
      rescue Azure::Core::Http::HTTPError => e
        case e.type
        when "BlobNotFound"
          raise ActiveStorage::FileNotFoundError
        when "Md5Mismatch"
          raise ActiveStorage::IntegrityError
        else
          raise
        end
      end
  end
end


问:
Docker php with apache on localhost: ERR_SSL_PROTOCOL_ERROR
I am trying to serve a hello_world.php file with apache and php in a docker container on Windows 10 with Docker Desktop.

Here's the Dockerfile:

```<code>FROM php:7.3-apache
# install git and zip, both needed for composer
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y git && \
    apt-get install zip unzip
# install composer
RUN curl -sS https://getcomposer.org/installer | php -- \
--install-dir=/usr/bin --filename=composer && chmod +x /usr/bin/composer

RUN a2enmod headers
RUN echo 'ServerName localhost' >> /etc/apache2/apache2.conf
COPY . /var/www/html
WORKDIR /var/www/html

#RUN composer install
EXPOSE 80
</code>```

As you can see, some of the additional code for setting up composer etc. (so I can dockerize an existing PHP application) is even commented out but it does not work with even a basic hello world php file and no other files (no .htaccess for example).

Firstly, I build the image with docker build .. When I then execute docker run -it -p 8000:80 d7cd1255a20f, I get the console output

```<code>[Tue Jun 02 16:01:29.592455 2020] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.38 (Debian) PHP/7.3.18 configured -- resuming normal operations
[Tue Jun 02 16:01:29.592531 2020] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'
</code>```

Looks fine to me.
I open http://localhost:8000in my browser and get "Can't establish a secure connection. ERR_SSL_PROTOCOL_ERROR". The server log shows (two lines each time I load the page in my browser):

```<code>172.17.0.1 - - [02/Jun/2020:16:02:55 +0000] "\x16\x03\x01\x02" 400 0 "-" "-"
172.17.0.1 - - [02/Jun/2020:16:02:55 +0000] "\x16\x03\x01\x02" 400 0 "-" "-"
</code>```

I have already researched this and it looks like it's the beginning of a TLS handshake.

How can I get this to work?

答: Do you have any .htaccess file inside /var/www/html? It looks like Apache is performing an automated redirect to HTTPS. Building the image with an empty directory as /var/www/html and running docker run -it -p 8000:80 d7cd1255a20f correctly runs over HTTP.

Body:
I am trying to serve a hello_world.php file with apache and php in a docker container on Windows 10 with Docker Desktop.

Here's the Dockerfile:

FROM php:7.3-apache
# install git and zip, both needed for composer
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y git && \
    apt-get install zip unzip
# install composer
RUN curl -sS https://getcomposer.org/installer | php -- \
--install-dir=/usr/bin --filename=composer && chmod +x /usr/bin/composer

RUN a2enmod headers
RUN echo 'ServerName localhost' >> /etc/apache2/apache2.conf
COPY . /var/www/html
WORKDIR /var/www/html

#RUN composer install
EXPOSE 80

As you can see, some of the additional code for setting up composer etc. (so I can dockerize an existing PHP application) is even commented out but it does not work with even a basic hello world php file and no other files (no .htaccess for example).

Firstly, I build the image with docker build .. When I then execute docker run -it -p 8000:80 d7cd1255a20f, I get the console output

[Tue Jun 02 16:01:29.592455 2020] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.38 (Debian) PHP/7.3.18 configured -- resuming normal operations
[Tue Jun 02 16:01:29.592531 2020] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'

Looks fine to me.
I open http://localhost:8000in my browser and get "Can't establish a secure connection. ERR_SSL_PROTOCOL_ERROR". The server log shows (two lines each time I load the page in my browser):

172.17.0.1 - - [02/Jun/2020:16:02:55 +0000] "\x16\x03\x01\x02" 400 0 "-" "-"
172.17.0.1 - - [02/Jun/2020:16:02:55 +0000] "\x16\x03\x01\x02" 400 0 "-" "-"

I have already researched this and it looks like it's the beginning of a TLS handshake.

How can I get this to work?


问:
Is there a Haskell equivalent way of iterable unpacking like in Python?
I wonder if it is possible to create variables from an iterable of things in Haskell. I found this when I search for it but I couldn't adapt it for my case. Maybe it's not possible or I'm missing something since I'm a beginner. Basically, I'm wondering if something like this is possible in Haskell:

>>> list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a, b, c = list_of_lists
>>> print(a)
[1, 2, 3]
```

Body:
ghci> list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
ghci> [a,b,c] = list_of_lists
ghci> print a
[1,2,3]


问:
Is there any practical reason to check if something is destructible before calling its destructor?
So I've been messing around trying to implement a variant/tagged union class and needed a way to write generic destructors and made what I thought was a silly mistake forgetting that some types don't have destructors, doing something like

```<code>template<typename T>
void destruct(T& thing) {
    thing.~T();
}
</code>```

Yet, this worked fine even with types that didn't have destructors, like int or struct A {int b;};. I still think it's more readable and easier to reason with something that uses something like this

```<code>template<typename T>
void destruct(T& thing) {
    if constexpr(std::is_destructible<T>::value) {
        thing.~T();
    }
}
</code>```

But is there actually any difference between the code? The first one feels pretty undefined behavoiry/just wrong to me.

答:
Yet, this worked fine even with types that didn't have destructors, like int or struct A {int b;};

Those are examples of types that are trivially destructible. It is well defined to invoke their "destructor". It has no effects.

But is there actually any difference between the code?

Only for types that are not destructible. Trivially destructible types are destructible.

For non-destructible types such as void, function types, or types with ~T() = delete;, the first function is ill-formed while the latter is well-formed with empty body. It depends on the use case which one is more useful, but silently ignoring attempt to destroy something that is not destructible seems dubious to me.

Body:
So I've been messing around trying to implement a variant/tagged union class and needed a way to write generic destructors and made what I thought was a silly mistake forgetting that some types don't have destructors, doing something like

template<typename T>
void destruct(T& thing) {
    thing.~T();
}

Yet, this worked fine even with types that didn't have destructors, like int or struct A {int b;};. I still think it's more readable and easier to reason with something that uses something like this

template<typename T>
void destruct(T& thing) {
    if constexpr(std::is_destructible<T>::value) {
        thing.~T();
    }
}

But is there actually any difference between the code? The first one feels pretty undefined behavoiry/just wrong to me.


问:
Adjustable row heights with bootstrap 4
I'm using bootstrap columns to display expanding cards.  When one expands though, it pushes the whole row underneath it down.

Unexpanded:

Currently how it behaves expanded:

How I'd like it to behave:

I've been reading about flexbox, but I cant find any good examples of the desired behavior, while maintaining responsive design.

Currently the code is along the lines of

```<code><div class="row">
    <div class="col-xl-4 col-lg-5 col-12">
        expanding content...
    </div>
    .
    .
    .
    <div class="col-xl-4 col-lg-5 col-12">
        expanding content...
    </div>
</div>
</code>```

答:
Ok, so after some trial and error I managed

--HTML--

This is a div

--JavaScript--

var onWindowLoaded = () =>{
    document.getElementById("redDiv").setAttribute("style", "height: 150px; background-
    color:red; width: 10%;");
}
window.addEventListener("load", onWindowLoaded);

So it's important to note that I used a red background in order to tell how long my div was, I see you're using a greyish background (It was hard to see them to be honest). So basically once the page loads it will set the div to the height indicated in the setAttribute() function, I had to re-add the colour because modifying the div height through javascript made the colour disappear completely. Hope this helps :)

Title: Adjustable row heights with bootstrap 4

Body:
I'm using bootstrap columns to display expanding cards.  When one expands though, it pushes the whole row underneath it down.

Unexpanded:

Currently how it behaves expanded:

How I'd like it to behave:

I've been reading about flexbox, but I cant find any good examples of the desired behavior, while maintaining responsive design.

Currently the code is along the lines of

        expanding content...

    .
    .
    .

        expanding content...

Body:
Ok, so after some trial and error I managed

--HTML--

<div id="redDiv" style="background-color: red; height: 100px; width: 10%; float:
    left;">
    <p>This is a div</p>
  </div>

--JavaScript--

var onWindowLoaded = () =>{
    document.getElementById("redDiv").setAttribute("style", "height: 150px; background-
    color:red; width: 10%;");
}
window.addEventListener("load", onWindowLoaded);

So it's important to note that I used a red background in order to tell how long my div was, I see you're using a greyish background (It was hard to see them to be honest). So basically once the page loads it will set the div to the height indicated in the setAttribute() function, I had to re-add the colour because modifying the div height through javascript made the colour disappear completely. Hope this helps :)


问:
C# connecting to a database
I Am Trying to create a program using c# that needs to connect to a database running on a Solaris server, I am not too familiar with the server, we normally use dbVisualizer to connect to it. the driver it uses to connect is mysql-connector-java-5.1.10, which is a jdbc driver. was wondering what drivers to use to connect to the database using C# and what is the syntax used to establish the connection. as far as I know I will be unable to install any drivers on the server side, and i will only be able to make changes/Install what is required on the client. </p>

答:
If I read your question correctly you are trying to connect to a MySql database from c#. This can be achieved by downloading the .net connector for MySql - Connector/Net. When you install this driver it will "integrate" with Visual Studio and you will be able to connect to the server directly from Visual Studio and your Program that will use the driver.

On the question on the syntax to connect you will either need to use MySqlConnection, with a tutorial here - http://bitdaddys.com/MySQL-ConnectorNet.html, or use something like the ADO.NET Entity Framework. But that depends on your Tastes.

I am assuming this Server can be access over the network.

Update User Confused about Connection String

```<code>Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
</code>```

You pass that string to the connection without any JDBC:// prefixes.

Please Note haven't done this in a while so the connection string could be wrong (So correct me If I'm wrong) and if you forget any connection string in the future you can always use a website like http://www.connectionstrings.com/ which shows them all for you. That is where I got the string above.

Hope that helps.

Title: C# connecting to a database

Body:
If I read your question correctly you are trying to connect to a MySql database from c#. This can be achieved by downloading the .net connector for MySql - Connector/Net. When you install this driver it will "integrate" with Visual Studio and you will be able to connect to the server directly from Visual Studio and your Program that will use the driver.

On the question on the syntax to connect you will either need to use MySqlConnection, with a tutorial here - http://bitdaddys.com/MySQL-ConnectorNet.html, or use something like the ADO.NET Entity Framework. But that depends on your Tastes.

I am assuming this Server can be access over the network.

Update User Confused about Connection String

Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

You pass that string to the connection without any JDBC:// prefixes.

Please Note haven't done this in a while so the connection string could be wrong (So correct me If I'm wrong) and if you forget any connection string in the future you can always use a website like http://www.connectionstrings.com/ which shows them all for you. That is where I got the string above.

Hope that helps.


问:
How do I use arrow functions in React
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

```<code>import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(
      <div>this is my div</div>
    );
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;
</code>```

and the error message i'm getting is:

```<code>./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed
</code>```

any assistance will be highly appreciated

答:
Instead of <Trial /> you need to call as a function as you defined, Trial isn't a component.

Try as the following:

```<code><div className="App">
   <p>{this.state.apiResponse}</p>

   { this.Trial() }
</div>
</code>```

Title: How do I use arrow functions in React

Body:
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(

this is my div

    );
  }

render(){
  return (

{this.state.apiResponse}

      <Trial />

  );
}
}

export default App;

and the error message i'm getting is:

./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed

any assistance will be highly appreciated

Body:
Instead of <Trial /> you need to call as a function as you defined, Trial isn't a component.

Try as the following:

<div className="App">
   <p>{this.state.apiResponse}</p>

   { this.Trial() }
</div>


问:
Ruby on Rails 4: Pluck results to hash
How can I turn:

```<code>Person.all.pluck(:id, :name)
</code>```

to

```<code>[{id: 1, name: 'joe'}, {id: 2, name: 'martin'}]
</code>```

without having to .map every value (since when I add or remove from the .pluck I have to do he same with the .map)

答:
The easiest way is to use the pluck method combined with the zip method.

attrs_array = %w(id name)
Person.all.pluck(attrs_array).map { |ele| attrs_array.zip(ele).to_h }
```

<p>You can also create a helper method if you are using this method through out your application.</p>

<pre class="lang-rb prettyprint-override"><code>def pluck_to_hash(object, *attrs)
  object.pluck(*attrs).map { |ele| attrs.zip(ele).to_h }
end
</code>```

Consider modifying by declaring self as the default receiver rather than passing Person.all as the object variable.

Read more about zip.

Title: Ruby on Rails 4: Pluck results to hash

Body:
How can I turn:

Person.all.pluck(:id, :name)

to

[{id: 1, name: 'joe'}, {id: 2, name: 'martin'}]

without having to .map every value (since when I add or remove from the .pluck I have to do he same with the .map)

Body:
The easiest way is to use the pluck method combined with the zip method.

attrs_array = %w(id name)
Person.all.pluck(attrs_array).map { |ele| attrs_array.zip(ele).to_h }

You can also create a helper method if you are using this method through out your application.

def pluck_to_hash(object, *attrs)
  object.pluck(*attrs).map { |ele| attrs.zip(ele).to_h }
end

Consider modifying by declaring self as the default receiver rather than passing Person.all as the object variable.

Read more about zip.


问:
While i am trying to open my react app the CMD showing an npm err! Saying 'npm err! missing script:start' can anyone help me?
enter image description here

I've searched in previous answers and tried to solve this for many hours but with no success. I've typed in the terminal npm create-react-app, moved to the correct cd, and it gives me this error:

'npm ERR! missing script: start'

答:
Start by validating that the 'start' script exists inside the package.json. That's where the script gets invoked. It should be under the key "scripts". If it's not there then that's the problem.

Should look something like this (if using react-scripts dependency):

```<code>"scripts": {
    "start": "react-scripts start",
    ....
}
</code>```

And if you're missing dependencies then run the following command inside the project directory to install them:

```<code>npm install
</code>```

Body:
Start by validating that the 'start' script exists inside the package.json. That's where the script gets invoked. It should be under the key "scripts". If it's not there then that's the problem.

Should look something like this (if using react-scripts dependency):

"scripts": {
    "start": "react-scripts start",
    ....
}

And if you're missing dependencies then run the following command inside the project directory to install them:

npm install


问:
MailKit unsuccessful SMTP OAuth with Microsoft 365 server
I'm using MailKit 2.6.0.0 to connect to Microsoft 365 using OAuth for authentication with POP3, IMAP, and SMTP.  The ImapClient and Pop3Client authenticate successfully but the SmtpClient does not.  Here's the protocol log from MailKit:

```<code>Connected to smtp://smtp.office365.com:587/?starttls=always
S: 220 MN2PR04CA0011.outlook.office365.com Microsoft ESMTP MAIL Service ready at Sat, 30 May 2020 07:48:32 +0000
C: EHLO [192.168.1.240]
S: 250-MN2PR04CA0011.outlook.office365.com Hello [my-ip]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-STARTTLS
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: STARTTLS
S: 220 2.0.0 SMTP server ready
C: EHLO [192.168.1.240]
S: 250-MN2PR04CA0011.outlook.office365.com Hello [my-ip]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-AUTH LOGIN XOAUTH2
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: AUTH XOAUTH2 BASE64USERANDTOKEN
S: 535 5.7.3 Authentication unsuccessful [MN2PR04CA0011.namprd04.prod.outlook.com]
C: QUIT
S: 221 2.0.0 Service closing transmission channel
</code>```

I've cracked open the BASE64USERANDTOKEN value and it looks exactly like that provided in the successful POP3/IMAP connections.  I don't know whether the unsuccessful SMTP authentication is caused by a mis-configuration of Microsoft 365 or a problem in the protocol dialogue.  I'm using the Microsoft 365 Developer Subscription provided as a benefit of my MSDN subscription.  I can't find any configuration setting specific to SMTP and I've used the correct scope (https://outlook.office365.com/SMTP.Send} when exchanging an authorization code for the access toke.  I also can't find any error log entries in Microsoft 365 which would help in diagnosing the problem.

As for the protocol dialogue, I noticed Microsoft's description at https://learn.microsoft.com/en-gb/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth

```<code>[connection begins]
C: auth xoauth2
S: 334
C: dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5LnZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ==
S: 235 2.7.0 Authentication successful
[connection continues...]
</code>```

differs from Google's at https://developers.google.com/gmail/imap/xoauth2-protocol which is like the MailKit protocol log:

```<code>[connection begins]
S: 220 mx.google.com ESMTP 12sm2095603fks.9
C: EHLO sender.example.com
S: 250-mx.google.com at your service, [172.31.135.47]
S: 250-SIZE 35651584
S: 250-8BITMIME
S: 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
S: 250-ENHANCEDSTATUSCODES
S: 250 PIPELINING
C: AUTH XOAUTH2 dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5LnZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ==
S: 235 2.7.0 Accepted
[connection continues...]
</code>```

Is this a possible cause of the authentiation failure?

答: Found the actual cause of unsuccessful authentication.  As mentioned in the original post I'm using my Microsoft 365 Developer Subscription, which gives me a domain looking something like schlagermeier.onmicrosoft.com (not real, folks).  I went into the Microsoft 365 admin portal for that account and was offered a "guided configuration" experience or somesuch.  This was a sort of wizard ui as a series of webpages.  One page had a "choose domain" with two radio buttons.  One button was labelled "Use schlagermeier.onmicrosoft.com" and the other was "Enter domain" with an input box for a domain you're already registered and own (e.g. schlagermeier.com).  So it appears that you have to explicitly set a domain for SMTP to work, which makes sense.  I just assumed the onmicrosoft domain would be used.</p>

Body:
I'm using MailKit 2.6.0.0 to connect to Microsoft 365 using OAuth for authentication with POP3, IMAP, and SMTP.  The ImapClient and Pop3Client authenticate successfully but the SmtpClient does not.  Here's the protocol log from MailKit:

Connected to smtp://smtp.office365.com:587/?starttls=always
S: 220 MN2PR04CA0011.outlook.office365.com Microsoft ESMTP MAIL Service ready at Sat, 30 May 2020 07:48:32 +0000
C: EHLO [192.168.1.240]
S: 250-MN2PR04CA0011.outlook.office365.com Hello [my-ip]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-STARTTLS
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: STARTTLS
S: 220 2.0.0 SMTP server ready
C: EHLO [192.168.1.240]
S: 250-MN2PR04CA0011.outlook.office365.com Hello [my-ip]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-AUTH LOGIN XOAUTH2
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: AUTH XOAUTH2 BASE64USERANDTOKEN
S: 535 5.7.3 Authentication unsuccessful [MN2PR04CA0011.namprd04.prod.outlook.com]
C: QUIT
S: 221 2.0.0 Service closing transmission channel

I've cracked open the BASE64USERANDTOKEN value and it looks exactly like that provided in the successful POP3/IMAP connections.  I don't know whether the unsuccessful SMTP authentication is caused by a mis-configuration of Microsoft 365 or a problem in the protocol dialogue.  I'm using the Microsoft 365 Developer Subscription provided as a benefit of my MSDN subscription.  I can't find any configuration setting specific to SMTP and I've used the correct scope (https://outlook.office365.com/SMTP.Send} when exchanging an authorization code for the access toke.  I also can't find any error log entries in Microsoft 365 which would help in diagnosing the problem.

As for the protocol dialogue, I noticed Microsoft's description at https://learn.microsoft.com/en-gb/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth

[connection begins]
C: auth xoauth2
S: 334
C: dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5LnZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ==
S: 235 2.7.0 Authentication successful
[connection continues...]

differs from Google's at https://developers.google.com/gmail/imap/xoauth2-protocol which is like the MailKit protocol log:

[connection begins]
S: 220 mx.google.com ESMTP 12sm2095603fks.9
C: EHLO sender.example.com
S: 250-mx.google.com at your service, [172.31.135.47]
S: 250-SIZE 35651584
S: 250-8BITMIME
S: 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
S: 250-ENHANCEDSTATUSCODES
S: 250 PIPELINING
C: AUTH XOAUTH2 dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5LnZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ==
S: 235 2.7.0 Accepted
[connection continues...]

Is this a possible cause of the authentiation failure?


问:
filter for rows with n largest values for each group

Context

I want, for each team, the rows of the data frame that contains the top three scoring players.

In my head, it is a combination of Dataframe.nlargest() and Dataframe.groupby() but I don't think this is supported.
My ideal solution is:

performed directly on df without having to create other dataframes

legible, and

relatively performant (real df shape is 7M rows and 5 col)

Input

import pandas as pd
df = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"A","4":"A","5":"B","6":"B","7":"B","8":"B","9":"B","10":"C","11":"C","12":"C","13":"C","14":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Donna","4":"Elizabeth","5":"Fran","6":"Greta","7":"Heather","8":"Iris","9":"Jackie","10":"Kelly","11":"Lucy","12":"Molly","13":"Nina","14":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":8,"4":10,"5":28,"6":29,"7":18,"8":25,"9":9,"10":12,"11":23,"12":18,"13":10,"14":15}}')
```

```| team | player    | points |
|------|-----------|--------|
| A    | Alice     | 15     |
| A    | Becky     | 11     |
| A    | Carmen    | 13     |
| A    | Donna     | 8      |
| A    | Elizabeth | 10     |
| B    | Fran      | 28     |
| B    | Greta     | 29     |
| B    | Heather   | 18     |
| B    | Iris      | 25     |
| B    | Jackie    | 9      |
| C    | Kelly     | 12     |
| C    | Lucy      | 23     |
| C    | Molly     | 18     |
| C    | Nina      | 10     |
| C    | Ophelia   | 15     |
```

<h3>Desired Output</h3>

<pre class="lang-py prettyprint-override"><code>df_output = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"B","4":"B","5":"B","6":"C","7":"C","8":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Fran","4":"Greta","5":"Iris","6":"Lucy","7":"Molly","8":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":28,"4":29,"5":25,"6":23,"7":18,"8":15}}')
df_output
</code>```

```<code>| team | player  | points |
|------|---------|--------|
| A    | Alice   | 15     |
| A    | Becky   | 11     |
| A    | Carmen  | 13     |
| B    | Fran    | 28     |
| B    | Greta   | 29     |
| B    | Iris    | 25     |
| C    | Lucy    | 23     |
| C    | Molly   | 18     |
| C    | Ophelia | 15     |
</code>```

答:
Another way is sort_values and groupby().tail/head:

```<code>df.sort_values('points').groupby('team').tail(3)
</code>```

Output:

```<code>   team   player  points
1     A    Becky      11
2     A   Carmen      13
0     A    Alice      15
14    C  Ophelia      15
12    C    Molly      18
11    C     Lucy      23
8     B     Iris      25
5     B     Fran      28
6     B    Greta      29
</code>```

Or

```<code>df.sort_values('points', ascending=False).groupby('team').head(3)
</code>```

Output:

```<code>   team   player  points
6     B    Greta      29
5     B     Fran      28
8     B     Iris      25
11    C     Lucy      23
12    C    Molly      18
0     A    Alice      15
14    C  Ophelia      15
2     A   Carmen      13
1     A    Becky      11
</code>```

Body:
Context

I want, for each team, the rows of the data frame that contains the top three scoring players.

In my head, it is a combination of Dataframe.nlargest() and Dataframe.groupby() but I don't think this is supported.
My ideal solution is:

performed directly on df without having to create other dataframes

legible, and

relatively performant (real df shape is 7M rows and 5 col)

Input

import pandas as pd
df = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"A","4":"A","5":"B","6":"B","7":"B","8":"B","9":"B","10":"C","11":"C","12":"C","13":"C","14":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Donna","4":"Elizabeth","5":"Fran","6":"Greta","7":"Heather","8":"Iris","9":"Jackie","10":"Kelly","11":"Lucy","12":"Molly","13":"Nina","14":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":8,"4":10,"5":28,"6":29,"7":18,"8":25,"9":9,"10":12,"11":23,"12":18,"13":10,"14":15}}')

| team | player    | points |
|------|-----------|--------|
| A    | Alice     | 15     |
| A    | Becky     | 11     |
| A    | Carmen    | 13     |
| A    | Donna     | 8      |
| A    | Elizabeth | 10     |
| B    | Fran      | 28     |
| B    | Greta     | 29     |
| B    | Heather   | 18     |
| B    | Iris      | 25     |
| B    | Jackie    | 9      |
| C    | Kelly     | 12     |
| C    | Lucy      | 23     |
| C    | Molly     | 18     |
| C    | Nina      | 10     |
| C    | Ophelia   | 15     |

Desired Output

df_output = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"B","4":"B","5":"B","6":"C","7":"C","8":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Fran","4":"Greta","5":"Iris","6":"Lucy","7":"Molly","8":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":28,"4":29,"5":25,"6":23,"7":18,"8":15}}')
df_output

| team | player  | points |
|------|---------|--------|
| A    | Alice   | 15     |
| A    | Becky   | 11     |
| A    | Carmen  | 13     |
| B    | Fran    | 28     |
| B    | Greta   | 29     |
| B    | Iris    | 25     |
| C    | Lucy    | 23     |
| C    | Molly   | 18     |
| C    | Ophelia | 15     |

Body:
Another way is sort_values and groupby().tail/head:

df.sort_values('points').groupby('team').tail(3)

Output:

   team   player  points
1     A    Becky      11
2     A   Carmen      13
0     A    Alice      15
14    C  Ophelia      15
12    C    Molly      18
11    C     Lucy      23
8     B     Iris      25
5     B     Fran      28
6     B    Greta      29

Or

df.sort_values('points', ascending=False).groupby('team').head(3)

Output:

   team   player  points
6     B    Greta      29
5     B     Fran      28
8     B     Iris      25
11    C     Lucy      23
12    C    Molly      18
0     A    Alice      15
14    C  Ophelia      15
2     A   Carmen      13
1     A    Becky      11


问:
MySQL update with subselect too slow
Having an issue with an update query taking more than 20 minutes (I kill it after that).

Scenario:

Table one has some 300K records.

Table two contains the same set of records (copied over), but with an extra field that needs to contain the id of the record that matches a number of fields, and has the highest value of another (a score). To clarify, the end result should be table two containing 300K records with each record having the id of another record that has the same set of basic properties, and the highest score within the set of records with those properties.

The below completes in ~5s when I only copy 2K records instead of the full 300k records into table two.

UPDATE vtable2 v1 SET v1.buddy = (
    SELECT v2.id FROM vtable1 v2
    WHERE
    v2.group_id = v1.group_id AND
    // 6 more basic comparisons
    ORDER BY score DESC LIMIT 1
)
```

I need to find buddies for the full 300K records. All fields involved in joining and sorting have indexes.

Help much appreciated.

答:
MySQL sub-queries tend to be a little slower. I prefer using joins in such cases. I am not exactly clear on your schema design - but you can try something like this - </p>

```<code>UPDATE vtable2 v1
[INNER] JOIN vtable1 v2
ON v2.group_id = v1.group_id
AND //OTHER JOIN CONDITIONS IF ANY
WHERE
//any other conditions
SET
v1.buddy = v2.id
</code>```

<p>PS - Of-course you need to make sure you have proper indexes on your columns. If you need help with that, you can post the whole query with an explain plan. </p>

Title: MySQL update with subselect too slow

Body:
Having an issue with an update query taking more than 20 minutes (I kill it after that).

Scenario:

Table one has some 300K records.

Table two contains the same set of records (copied over), but with an extra field that needs to contain the id of the record that matches a number of fields, and has the highest value of another (a score). To clarify, the end result should be table two containing 300K records with each record having the id of another record that has the same set of basic properties, and the highest score within the set of records with those properties.

The below completes in ~5s when I only copy 2K records instead of the full 300k records into table two.

UPDATE vtable2 v1 SET v1.buddy = (
    SELECT v2.id FROM vtable1 v2
    WHERE
    v2.group_id = v1.group_id AND
    // 6 more basic comparisons
    ORDER BY score DESC LIMIT 1
)

I need to find buddies for the full 300K records. All fields involved in joining and sorting have indexes.

Help much appreciated.

Body:
MySQL sub-queries tend to be a little slower. I prefer using joins in such cases. I am not exactly clear on your schema design - but you can try something like this -

UPDATE vtable2 v1
[INNER] JOIN vtable1 v2
ON v2.group_id = v1.group_id
AND //OTHER JOIN CONDITIONS IF ANY
WHERE
//any other conditions
SET
v1.buddy = v2.id

PS - Of-course you need to make sure you have proper indexes on your columns. If you need help with that, you can post the whole query with an explain plan.


问:
Amazon AWS domain not working without www
I have website hosted on Amazon AWS and have created hosting zones for the domains.  However, for a particular domain (www.mohawkhonda.com) the website DNS can not be reached if we just type in mohawkhonda.com.  It required the www.  -  This is a weird issue esp on elastic beanstalk as there are no static ips.

What is the best solution to make sure both pull up perfectly?  Any help is appreciated.  Thank you

答:
The OPs pattern can also happen when no A record(s) is/are set for ns:

ns1.domainserver.tld    A    17.917.70.448

ns2.domainserver.tld    A    17.917.70.448


问:
Changing username, hostname, and path color in iterm2
How can I change the username, hostname, and path color in iTerm2? I'm using the built-in Solarized colorscheme.

In Ubuntu, the same built-in colorscheme is highlighted like:

In iTerm2:

Current iTerm2 settings:

and

I've been playing around the settings but can't get it to work. I've also gone through numerous links, but those also settings don't work.

I'm on macOS 10.15.4

答:
This is what I am using now. Colours for prompt and ls command.

```<code>RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
PURPLE='\033[1;35m'
CYAN='\033[1;36m'
WHITE='\033[1;37m'
RESET='\033[0m'

export PS1="$RED\u:$BLUE\w $GREEN\h$RESET$ "
export CLICOLOR=1
export LSCOLORS=GxFxCxDxbxegedabagaced
</code>```

Output:

Body:
This is what I am using now. Colours for prompt and ls command.

RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
PURPLE='\033[1;35m'
CYAN='\033[1;36m'
WHITE='\033[1;37m'
RESET='\033[0m'

export PS1="$RED\u:$BLUE\w $GREEN\h$RESET$ "
export CLICOLOR=1
export LSCOLORS=GxFxCxDxbxegedabagaced

Output: