问:
How to build a p2p connection between 2 devices like torrent
I want to build a system with 2 or more devices. Devices in the system can send files to each other using p2p, not through the server (files to be sent are not uploaded to the server)

To clear, suppose my system has 2 PCs placed in 2 different places (not LAN network and no static ip), they can share files with each other via the internet without a server. I do not want shared files uploaded to the server (no time and memory required).

Of course my system will still have a server and a database that will store data and transfer some important information between the two devices via sockets.

I searched a lot on the internet, and all I found was around the torrent network. I don't know how to build a system like torrent.

I have not decided which language or framework I will use (Java, C#, Python, NodeJS).
Any suggestions on tutorial, languages, libraries, frameworks are welcome.

Thanks all

答:
Since you have a server, it's much easier.

Using your server to build a ICE structure to do NAT traversal

You may need some machines to release the pressure of server when finding other nodes, so LSD and DHT are both recommanded.

Using peer wire protocol to send files is really good.

There is an open source project libtorrent which may be useful for you. I think you can just use some part of it to realise your design. As for language, libtorrent is written by C++, but it's not really important.


来源: stackexchange

问:
split URL using Regular Expression in IIS
I am facing challenges in splitting the URL using regular expression.

I want to change the mid of the URL part since we changed the URL of the site pages.

```<code>      https://test.company.com/about/news/2015/test/award.aspx
</code>```

The above given URL needs to replace as below,

```<code>      https://test.company.com/en/about/media/news/2015/test/award.aspx
</code>```

I want to achieve this functionality using Regular Expression in IIS.

I tried the code as below in URL Rewrite in IIS,

```<code>      about/news/2015(.*.+?)
</code>```

Help to resolve this as required, thanks in advance.

答:
You could try below rule:

```<code> <rule name="rule11-1" stopProcessing="true">
                <match url="^about/news/2015/(.*)" />
                <conditions>
                    <add input="{REQUEST_URI}" pattern="^/about/(.*)" />
                </conditions>
                <action type="Redirect" url="https://test.company.com/en/about/media/{C:1}" />
            </rule>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am facing challenges in splitting the URL using regular expression.

I want to change the mid of the URL part since we changed the URL of the site pages.

      https://test.company.com/about/news/2015/test/award.aspx

The above given URL needs to replace as below,

      https://test.company.com/en/about/media/news/2015/test/award.aspx

I want to achieve this functionality using Regular Expression in IIS.

I tried the code as below in URL Rewrite in IIS,

      about/news/2015(.*.+?)

Help to resolve this as required, thanks in advance.

Body:
You could try below rule:

 <rule name="rule11-1" stopProcessing="true">
                <match url="^about/news/2015/(.*)" />
                <conditions>
                    <add input="{REQUEST_URI}" pattern="^/about/(.*)" />
                </conditions>
                <action type="Redirect" url="https://test.company.com/en/about/media/{C:1}" />
            </rule>


问:
Can we repeatedly hash an input and hash it indefinitely?
Was just wondering that if we are given an input string x and we hash it with function f to get f(x) can we repeat this process indefinitely i.e f(f(x)) and so on. Because most hash functions generate a different fixed output that is not the same as the input.
So by this premise, would we be able to carry this out indefinitely? One possible issue I can think is that it has to be fixed length and usually hashes are shorter than the input?
Please correct me if I am wrong. Would love an explanation!

答:
Yes you absolutely can hash the prior hash output.

When we do this with cryptographic keys it’s called ratcheting.

The output size of the hashing algo will determine how many outputs you can rehash before you get a collision.

Thus for a 256-bit hash function we will see a collision with 50% probability after 2^128 hashing calls.


问:
Java compiler for android phones
I have done a little googling but not found too much info on the subject so im asking here,

Does any body know of a phone based java or c/c++ compiler so a dev could effectively use his phone to do some preliminary dev work (or just to play around with when bored on the tube :))

答: Try ASE aka "Android Scripting" http://code.google.com/p/android-scripting/ (ok - it's not a java or c++ compiler but you can edit and run stuff directly on your phone and have pretty much full access to the APIs)</p>

ContentLicense: CC BY-SA 3.0

Title: Java compiler for android phones


问:
how to add one more plot in matplotlib script
My matplotlib script plots a file "band.hdf5", which is in hdf5 format, with

```<code>f = h5py.File('band.hdf5',  'r')
</code>```

I want to add one more hdf5 file "band-new.hdf5" here in such a way that the output plot will have one more plot on right side for new file. Y-axis label should be avoided for "band-new.hdf5" and X-axis label should be common for both file.

The header of the script is this

```<code>import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib
</code>```

This script is taken from the accepted answer

```<code>https://stackoverflow.com/questions/62099211/how-to-plot-two-case1-hdf5-and-case2-hdf5-files-in-matplotlib-seeking-help-to-c?rq=1
</code>```

答:
Is this the solution you needed?

I take the code from
and adapted it to draw two plots side-to-side from the data you shared.

```<code>import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib

warnings.filterwarnings("ignore") # Ignore all warnings

cmap = matplotlib.cm.get_cmap('jet', 4)

ticklabels=['A','B','C','D','E']

params = {
'mathtext.default': 'regular',
'axes.linewidth': 1.2,
'axes.edgecolor': 'Black',
'font.family' : 'serif'
}

#get the viridis cmap with a resolution of 3

#apply a scale to the y axis. I'm just picking an arbritrary number here
scale = 10
offset = 0 #set this to a non-zero value if you want to have your lines offset in a waterfall style effect

f_left = h5py.File('band-222.hdf5',  'r')
f_right = h5py.File('band-332.hdf5',  'r')

print ('datasets from left are:')
print(list(f_left.keys()))

print ('datasets from right are:')
print(list(f_right.keys()))

# PLOTTING
plt.rcParams.update(params)
fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(121)

# LEFT ONE
dist=f_left[u'distance']
freq=f_left[u'frequency']
kpt=f_left[u'path']

lbl = {0:'AB', 1:'BC', 2:'CD', 3:'fourth'}

for i, section in enumerate(dist):
    for nbnd, _ in enumerate(freq[i][0]):
        x = section # to_list() you may need to convert sample to list.
        y = (freq[i, :, nbnd] + offset*nbnd) * scale

        if (nbnd<3):
            color=f'C{nbnd}'
        else:
            color='black'

        ax1.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

ax1.legend()

# Labels and axis limit and ticks
ax1.set_ylabel(r'Frequency (THz)', fontsize=12)
ax1.set_xlabel(r'Wave Vector (q)', fontsize=12)
ax1.set_xlim([dist[0][0],dist[len(dist)-1][-1]])
xticks=[dist[i][0] for i in range(len(dist))]
xticks.append(dist[len(dist)-1][-1])
ax1.set_xticks(xticks)
ax1.set_xticklabels(ticklabels)
# Plot grid
ax1.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)

# RIGHT ONE
ax2 = fig.add_subplot(122)
dist=f_right[u'distance']
freq=f_right[u'frequency']
kpt=f_right[u'path']

lbl = {0:'AB', 1:'BC', 2:'CD', 3:'fourth'}

for i, section in enumerate(dist):
    for nbnd, _ in enumerate(freq[i][0]):
        x = section # to_list() you may need to convert sample to list.
        y = (freq[i, :, nbnd] + offset*nbnd) * scale

        if (nbnd<3):
            color=f'C{nbnd}'
        else:
            color='black'

        ax2.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

ax2.legend()
# remove y axis
ax2.axes.get_yaxis().set_visible(False)
ax2.set_xlabel(r'Wave Vector (q)', fontsize=12)
ax2.set_xlim([dist[0][0],dist[len(dist)-1][-1]])
xticks=[dist[i][0] for i in range(len(dist))]
xticks.append(dist[len(dist)-1][-1])
ax2.set_xticks(xticks)
ax2.set_xticklabels(ticklabels)
# Plot grid
ax2.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)

fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

# Save to pdf
plt.savefig('plots.pdf', bbox_inches='tight')
</code>```

The final figure is like this.

Body:
My matplotlib script plots a file "band.hdf5", which is in hdf5 format, with

f = h5py.File('band.hdf5',  'r')

I want to add one more hdf5 file "band-new.hdf5" here in such a way that the output plot will have one more plot on right side for new file. Y-axis label should be avoided for "band-new.hdf5" and X-axis label should be common for both file.

The header of the script is this

import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib

This script is taken from the accepted answer

https://stackoverflow.com/questions/62099211/how-to-plot-two-case1-hdf5-and-case2-hdf5-files-in-matplotlib-seeking-help-to-c?rq=1

Body:
Is this the solution you needed?

I take the code from
and adapted it to draw two plots side-to-side from the data you shared.

import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib

warnings.filterwarnings("ignore") # Ignore all warnings

cmap = matplotlib.cm.get_cmap('jet', 4)

ticklabels=['A','B','C','D','E']

params = {
'mathtext.default': 'regular',
'axes.linewidth': 1.2,
'axes.edgecolor': 'Black',
'font.family' : 'serif'
}

#get the viridis cmap with a resolution of 3

#apply a scale to the y axis. I'm just picking an arbritrary number here
scale = 10
offset = 0 #set this to a non-zero value if you want to have your lines offset in a waterfall style effect

f_left = h5py.File('band-222.hdf5',  'r')
f_right = h5py.File('band-332.hdf5',  'r')

print ('datasets from left are:')
print(list(f_left.keys()))

print ('datasets from right are:')
print(list(f_right.keys()))

# PLOTTING
plt.rcParams.update(params)
fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(121)

# LEFT ONE
dist=f_left[u'distance']
freq=f_left[u'frequency']
kpt=f_left[u'path']

lbl = {0:'AB', 1:'BC', 2:'CD', 3:'fourth'}

for i, section in enumerate(dist):
    for nbnd, _ in enumerate(freq[i][0]):
        x = section # to_list() you may need to convert sample to list.
        y = (freq[i, :, nbnd] + offset*nbnd) * scale

        if (nbnd<3):
            color=f'C{nbnd}'
        else:
            color='black'

        ax1.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

ax1.legend()

# Labels and axis limit and ticks
ax1.set_ylabel(r'Frequency (THz)', fontsize=12)
ax1.set_xlabel(r'Wave Vector (q)', fontsize=12)
ax1.set_xlim([dist[0][0],dist[len(dist)-1][-1]])
xticks=[dist[i][0] for i in range(len(dist))]
xticks.append(dist[len(dist)-1][-1])
ax1.set_xticks(xticks)
ax1.set_xticklabels(ticklabels)
# Plot grid
ax1.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)

# RIGHT ONE
ax2 = fig.add_subplot(122)
dist=f_right[u'distance']
freq=f_right[u'frequency']
kpt=f_right[u'path']

lbl = {0:'AB', 1:'BC', 2:'CD', 3:'fourth'}

for i, section in enumerate(dist):
    for nbnd, _ in enumerate(freq[i][0]):
        x = section # to_list() you may need to convert sample to list.
        y = (freq[i, :, nbnd] + offset*nbnd) * scale

        if (nbnd<3):
            color=f'C{nbnd}'
        else:
            color='black'

        ax2.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

ax2.legend()
# remove y axis
ax2.axes.get_yaxis().set_visible(False)
ax2.set_xlabel(r'Wave Vector (q)', fontsize=12)
ax2.set_xlim([dist[0][0],dist[len(dist)-1][-1]])
xticks=[dist[i][0] for i in range(len(dist))]
xticks.append(dist[len(dist)-1][-1])
ax2.set_xticks(xticks)
ax2.set_xticklabels(ticklabels)
# Plot grid
ax2.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)

fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

# Save to pdf
plt.savefig('plots.pdf', bbox_inches='tight')

The final figure is like this.


问:
Insert buyer's name into a PDF through Linux CLI?
I have a client who wants to sell PDF books with the buyer's name and timestamp embedded in the PDF so it would be visible on several pages through the PDF book. This would be purchased through PayPal. Is there Linux command line software to write a string into a PDF so that it is visible when viewed as a PDF document? Don't want to watermark the page, just a small section for it to print something like "Purchased by John Doe on MM/DD/YY'.</p>

答: My suggestion would be to take a look at the toolchain of commands Calibre uses when editing ebooks, of which PDF is one of the formats</p>


问:
C# - WHOIS server closing the connection early or not sending the whole response to my socket?
I'm sending the server 172.217.2.142\r\n and it's only responding with:

#

   # ARIN WHOIS data and services are subject to the Terms of Use

   # available at: https://www.arin.net/whois_tou.html

   #

   # If you see inaccuracies in the results, please report at

   # https://www.arin.net/public/whoisinaccuracy/index.xhtml

   #

My receive function:

```<code>private string getResponse(Socket sock)
{
    byte[] buffer = new byte[1024];
    string result = string.Empty;
    int bytesReceived = 0;

    do
    {
        bytesReceived = sock.Receive(buffer, 0, buffer.Length, SocketFlags.None);
        Debug.Print("Bytes read:" + bytesReceived.ToString());
        result += Encoding.ASCII.GetString(buffer);
        Array.Clear(buffer, 0, buffer.Length);
    } while (bytesReceived > 0);

    return result;
}
</code>```

答:
One popular way is to use WebClient to load data from the URL:

```<code>using (WebClient client = new WebClient())
{
    string value = client.DownloadString("url");
}
</code>```

The value returned is in JSON format for arin.net.

Body:
I'm sending the server 172.217.2.142\r\n and it's only responding with:

#

   # ARIN WHOIS data and services are subject to the Terms of Use

   # available at: https://www.arin.net/whois_tou.html

   #

   # If you see inaccuracies in the results, please report at

   # https://www.arin.net/public/whoisinaccuracy/index.xhtml

   #

My receive function:

private string getResponse(Socket sock)
{
    byte[] buffer = new byte[1024];
    string result = string.Empty;
    int bytesReceived = 0;

    do
    {
        bytesReceived = sock.Receive(buffer, 0, buffer.Length, SocketFlags.None);
        Debug.Print("Bytes read:" + bytesReceived.ToString());
        result += Encoding.ASCII.GetString(buffer);
        Array.Clear(buffer, 0, buffer.Length);
    } while (bytesReceived > 0);

    return result;
}

Body:
One popular way is to use WebClient to load data from the URL:

using (WebClient client = new WebClient())
{
    string value = client.DownloadString("url");
}

The value returned is in JSON format for arin.net.


问:
I have an if-else rules decision tree file , and want to visualize it, How can i do that?

I have generated a decision tree using the C4.5 algorithm, and the tree is generated and stored in rules.py as if-else rules.

Now I wanted to visualize the decision tree in rules.py. I have seen some tutorials of graphviz but I am not able to visualize it.

Below is the rules.py file :

```<code>def findDecision(obj): #obj[0]: Semester, obj[1]: Gender, obj[2]: Friend_time, obj[3]: Faculty_visit, obj[4]: avg_attendance, obj[5]: attentive_class, obj[6]: participation_corricular, obj[7]: study_time, obj[8]: social_time, obj[9]: cgpa, obj[10]: extra_crse, obj[11]: health, obj[12]: sleep, obj[13]: go_out_frnd, obj[14]: lib_time
   if obj[9]>2:
      if obj[14]>2:
         if obj[12]>1:
            if obj[3]>1:
               if obj[7]>1:
                  return 5
               elif obj[7]<=1:
                  return 4.5
               else:
                  return 4.5
            elif obj[3]<=1:
               return 5.666666666666667
            else:
               return 5.666666666666667
         elif obj[12]<=1:
            return 6.5
         else:
            return 6.5
      elif obj[14]<=2:
         if obj[11]>1:
            if obj[8]>1:
               if obj[2]>2:
                  return 6.0
               elif obj[2]<=2:
                  return 7
               else:
                  return 7.0
            elif obj[8]<=1:
               return 6
            else:
               return 6.0
         elif obj[11]<=1:
            return 8.0
         else:
            return 8.0
      else:
         return 6.7272727272727275
   elif obj[9]<=2:
      if obj[7]>1:
         if obj[1]>1:
            return 8
         elif obj[1]<=1:
            return 9
         else:
            return 9.0
      elif obj[7]<=1:
         return 7.0
      else:
         return 7.0
   else:
      return 8.125

</code>```

So can please help me how to visualize this ?

答: You can use pythontutor to visualize code.</p>

Body:
I have generated a decision tree using the C4.5 algorithm, and the tree is generated and stored in rules.py as if-else rules.

Now I wanted to visualize the decision tree in rules.py. I have seen some tutorials of graphviz but I am not able to visualize it.

Below is the rules.py file :

def findDecision(obj): #obj[0]: Semester, obj[1]: Gender, obj[2]: Friend_time, obj[3]: Faculty_visit, obj[4]: avg_attendance, obj[5]: attentive_class, obj[6]: participation_corricular, obj[7]: study_time, obj[8]: social_time, obj[9]: cgpa, obj[10]: extra_crse, obj[11]: health, obj[12]: sleep, obj[13]: go_out_frnd, obj[14]: lib_time
   if obj[9]>2:
      if obj[14]>2:
         if obj[12]>1:
            if obj[3]>1:
               if obj[7]>1:
                  return 5
               elif obj[7]<=1:
                  return 4.5
               else:
                  return 4.5
            elif obj[3]<=1:
               return 5.666666666666667
            else:
               return 5.666666666666667
         elif obj[12]<=1:
            return 6.5
         else:
            return 6.5
      elif obj[14]<=2:
         if obj[11]>1:
            if obj[8]>1:
               if obj[2]>2:
                  return 6.0
               elif obj[2]<=2:
                  return 7
               else:
                  return 7.0
            elif obj[8]<=1:
               return 6
            else:
               return 6.0
         elif obj[11]<=1:
            return 8.0
         else:
            return 8.0
      else:
         return 6.7272727272727275
   elif obj[9]<=2:
      if obj[7]>1:
         if obj[1]>1:
            return 8
         elif obj[1]<=1:
            return 9
         else:
            return 9.0
      elif obj[7]<=1:
         return 7.0
      else:
         return 7.0
   else:
      return 8.125

So can please help me how to visualize this ?


问:
problem in deleting a node in linked list (Python)
So below is a linked that removes an item from the list

class Node(object):
    def __init__(self, data=None):
        self.data = data
        self.next_node = None
class LinkedList(object):
    def __init__(self):
        self.head = None

    def remove(self,item_to_remove):
        n = self.head
        while n is not item_to_remove :
            n = n.next_node
        if n == item_to_remove:
            n = None
```

<p>In the process of looping through the nodes it returns me this ERROR</p>

```AttributeError: 'NoneType' object has no attribute 'next_node'
```

It would be great if you can help
Thanks in advance!!

答: You have to assign a value in self.head before trying to iterate it. Initialization value of it is None, therefore trying to iterate through a None type object is not possible.</p>

Body:
So below is a linked that removes an item from the list

class Node(object):
    def __init__(self, data=None):
        self.data = data
        self.next_node = None
class LinkedList(object):
    def __init__(self):
        self.head = None

    def remove(self,item_to_remove):
        n = self.head
        while n is not item_to_remove :
            n = n.next_node
        if n == item_to_remove:
            n = None

In the process of looping through the nodes it returns me this ERROR

AttributeError: 'NoneType' object has no attribute 'next_node'

It would be great if you can help
Thanks in advance!!


问:
Cannot apply animation on SVG g element
I have the following SVG file.

```<code>        <svg
            xmlns:dc="http://purl.org/dc/elements/1.1/"
            xmlns:cc="http://creativecommons.org/ns#"
            xmlns:rdf="htntp://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:svg="http://www.w3.org/2000/svg"
            xmlns="http://www.w3.org/2000/svg"
            version="1.1"
            width="1000"
            height="650"
            id="svgContainer">

            <g
                id="truck">
                <animate attributeName="fill" from="black" to="red" dur="5s"/>
                <path
                    d="m 655.589,484.36218 -6.18561,-128.61524 -110.99241,-15.79583 -34.55321,-87.58893 -94.74579,0 3.03024,178.75619 -322.238663,2.0203 0.145305,51.22351 z"
                    id="body"
                    fill="#000000"
                    stroke="#000000"
                    stroke-width="1px"
                    stroke-linecap="butt"
                    stroke-linejoin="miter"
                    stroke-opacity="1" />
                <animate attributeType="XML" attributeName="x" to="1000" begin="indefinite" dur="1s" />
                <animate attributeType="XML" attributeName="y" to="1000" begin="indefinite" dur="1s" />
            </g>
        </svg>
    </g>
</svg>
</code>```

I just want to move it to some other place with animation, but it does not work. Is there something that I am missing here? (I want to animate the g element with everything inside. I removed the rest of the elements for the sake of simplicity.)

答:
OK, I changed to animation here with following.

```<code><animateTransform
    attributeType="XML"
    attributeName="transform"
    type="translate"
    from="0,0" to="1000,1000"
    begin="0s" dur="1"
    repeatCount="indefinite"/>
</code>```

And it started to work.

UPDATE

I found a better solution. In the first one, after animation my group element is returning to its original position. With the follwing it stays where it is.

```<code><animateMotion
    from="0,0" to="500,0"
    dur="4s" fill="freeze"/>
</code>```

Title: Cannot apply animation on SVG g element

Body:
I have the following SVG file.

        <svg
            xmlns:dc="http://purl.org/dc/elements/1.1/"
            xmlns:cc="http://creativecommons.org/ns#"
            xmlns:rdf="htntp://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:svg="http://www.w3.org/2000/svg"
            xmlns="http://www.w3.org/2000/svg"
            version="1.1"
            width="1000"
            height="650"
            id="svgContainer">

            <g
                id="truck">
                <animate attributeName="fill" from="black" to="red" dur="5s"/>
                <path
                    d="m 655.589,484.36218 -6.18561,-128.61524 -110.99241,-15.79583 -34.55321,-87.58893 -94.74579,0 3.03024,178.75619 -322.238663,2.0203 0.145305,51.22351 z"
                    id="body"
                    fill="#000000"
                    stroke="#000000"
                    stroke-width="1px"
                    stroke-linecap="butt"
                    stroke-linejoin="miter"
                    stroke-opacity="1" />
                <animate attributeType="XML" attributeName="x" to="1000" begin="indefinite" dur="1s" />
                <animate attributeType="XML" attributeName="y" to="1000" begin="indefinite" dur="1s" />
            </g>
        </svg>
    </g>
</svg>

I just want to move it to some other place with animation, but it does not work. Is there something that I am missing here? (I want to animate the g element with everything inside. I removed the rest of the elements for the sake of simplicity.)

Body:
OK, I changed to animation here with following.

<animateTransform
    attributeType="XML"
    attributeName="transform"
    type="translate"
    from="0,0" to="1000,1000"
    begin="0s" dur="1"
    repeatCount="indefinite"/>

And it started to work.

UPDATE

I found a better solution. In the first one, after animation my group element is returning to its original position. With the follwing it stays where it is.

<animateMotion
    from="0,0" to="500,0"
    dur="4s" fill="freeze"/>


问:
Service Fabric Reverse Proxy HTTP Not Found
I have a SF project where I have two public services that are secured with HTTPS, and multiple "private" services that are not.

I'm running into an issue when I try to do a reverse proxy call to one of my public services from one of my private services I get a 404 Not Found.

The services are written in .Net core 3.1 and I use kestrel as my web server.

I'm presuming the issue has to do with the fact that my public service cannot be reached by the proxy because of the fact the HTTPS port is the only port being listened on by the kestrel server.

How would I allow kestrel to allow for HTTP calls from the reverse proxy and the public HTTPS endpoint?

答:
I found the answer over here on this question.

Just again too re-iterate the importance of setting the unique name for ServiceInstanceListener.


问:
Unable to access suspend Dao function from a CoroutineScope launch
i have a simple Dao interface of Room database in which I have suspend functions to insert and get data from the table.

in my DBHelper class I am trying to insert data using launch - CoroutineScope but does not seem to go within the launch and the functions within the launch are not executed.

any suggestions on what I might be doing wrong please

OfflineDataDao

```<code>@Dao
interface OfflineDataDao {

    @Query("SELECT * FROM offlineDatax")
    suspend fun getOfflineData(): List<OfflineDatax>

    @Insert
    suspend fun insertOfflineData(offlineData: OfflineDatax): Long
}
</code>```

Entity

```<code>@Entity
data class OfflineDatax (
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "requestJSON") val requestJSON: String?,
    @ColumnInfo(name = "requestCode") val requestCode: String?
)
</code>```

DBHelper
class where I am accessing the dao suspend methods

```<code>class DBHelper @Inject constructor(
    private val userDao: UserDao,
    private val offlineDataDao: OfflineDataDao
) : CoroutineScope {

    private var job: Job = Job()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    fun accessDBFunction() {

        var offlineDatax =  OfflineDatax(1, "rjson", "rCode")
        addOfflineData(offlineDatax)

        getOfflineData()
    }

    fun addOfflineData(offlineDatax: OfflineDatax): Long {
        var lng: Long = 0L
        launch {
            lng = offlineDataDao.insertOfflineData(offlineDatax) // IS NOT CALLED, DOES NOT GET INTO LAUNCH
        }
        return lng
    }

    fun getOfflineData (): List<OfflineDatax> {
        var offlineData = emptyList<OfflineDatax>()
        launch {
          offlineData = offlineDataDao.getOfflineData(); // IS NOT CALLED, DOES NOT GET INTO LAUNCH
        }
        Timber.d("offlinedata " + offlineData.toString())
        return offlineData
    }
}
</code>```

答:
Check your error logs please.

```<code>override val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + job
</code>```

Because of this i think that you are trying to communicate with database on Main thread.

```<code>fun getOfflineData() = withContext(Dispatchers.IO) {
    var offlineData = emptyList<OfflineDatax>()
    offlineData = offlineDataDao.getOfflineData();
    Timber.d("offlinedata " + offlineData.toString())
    offlineData // WHEN TASK FINISH THIS WILL BE RETURNED
}
</code>```

and then call getOfflineData() in your launch{}

Body:
i have a simple Dao interface of Room database in which I have suspend functions to insert and get data from the table.

in my DBHelper class I am trying to insert data using launch - CoroutineScope but does not seem to go within the launch and the functions within the launch are not executed.

any suggestions on what I might be doing wrong please

OfflineDataDao

@Dao
interface OfflineDataDao {

    @Query("SELECT * FROM offlineDatax")
    suspend fun getOfflineData(): List<OfflineDatax>

    @Insert
    suspend fun insertOfflineData(offlineData: OfflineDatax): Long
}

Entity

@Entity
data class OfflineDatax (
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "requestJSON") val requestJSON: String?,
    @ColumnInfo(name = "requestCode") val requestCode: String?
)

DBHelper
class where I am accessing the dao suspend methods

class DBHelper @Inject constructor(
    private val userDao: UserDao,
    private val offlineDataDao: OfflineDataDao
) : CoroutineScope {

    private var job: Job = Job()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    fun accessDBFunction() {

        var offlineDatax =  OfflineDatax(1, "rjson", "rCode")
        addOfflineData(offlineDatax)

        getOfflineData()
    }

    fun addOfflineData(offlineDatax: OfflineDatax): Long {
        var lng: Long = 0L
        launch {
            lng = offlineDataDao.insertOfflineData(offlineDatax) // IS NOT CALLED, DOES NOT GET INTO LAUNCH
        }
        return lng
    }

    fun getOfflineData (): List<OfflineDatax> {
        var offlineData = emptyList<OfflineDatax>()
        launch {
          offlineData = offlineDataDao.getOfflineData(); // IS NOT CALLED, DOES NOT GET INTO LAUNCH
        }
        Timber.d("offlinedata " + offlineData.toString())
        return offlineData
    }
}

Body:
Check your error logs please.

override val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + job

Because of this i think that you are trying to communicate with database on Main thread.

fun getOfflineData() = withContext(Dispatchers.IO) {
    var offlineData = emptyList<OfflineDatax>()
    offlineData = offlineDataDao.getOfflineData();
    Timber.d("offlinedata " + offlineData.toString())
    offlineData // WHEN TASK FINISH THIS WILL BE RETURNED
}

and then call getOfflineData() in your launch{}


问:
Python3.7: error while loading shared libraries: libpython3.7m.so.1.0
I have two versions Python-2.7 , Python-3.5  which I was able to access with python(pip) and python3(pip3) command respectively. Then I have installed an another version of python (i.e 3.7.5).

I have used these commands to install it.

```<code>sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \
xz-utils tk-dev libffi-dev liblzma-dev

wget https://www.python.org/ftp/python/3.7.5/Python-3.7.5.tgz
tar xvf Python-3.7.5.tgz
cd Python-3.7.5
./configure --enable-optimizations --enable-shared
make -j6
sudo make altinstall
</code>```

Everything was successful but the only issue is I was not able to access Python-3.7 using the command python3.7.

When I used python3.7 it returned this following error:

python3.7: error while loading shared libraries: libpython3.7m.so.1.0:
  cannot open shared object file: No such file or directory

Can anyone please help me regarding how to fix this issue?

Info: OS: Debian GNU/Linux 9.11 (stretch)

Output when I type:

```<code>user_83@debian-241:~$ whereis python
python: /usr/bin/python3.5m-config
/usr/bin/python3.5m
/usr/bin/python2.7-config
/usr/bin/python3.5
/usr/bin/python2.7
/usr/bin/python
/usr/bin/python3.5-config
/usr/lib/python3.5
/usr/lib/python2.7
/etc/python3.5
/etc/python2.7
/etc/python
/usr/local/bin/python3.7m
/usr/local/bin/python3.7
/usr/local/bin/python3.7m-config
/usr/local/lib/python3.5
/usr/local/lib/python2.7
/usr/local/lib/python3.7
/usr/include/python3.5m
/usr/include/python3.5
/usr/include/python2.7
/usr/share/python
/usr/share/man/man1/python.1.gz
</code>```

UPDATE:

```<code>locate libpython3.5m

/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/libpython3.5m-pic.a
/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/libpython3.5m.a
/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/libpython3.5m.so
/usr/lib/x86_64-linux-gnu/libpython3.5m.a
/usr/lib/x86_64-linux-gnu/libpython3.5m.so
/usr/lib/x86_64-linux-gnu/libpython3.5m.so.1
/usr/lib/x86_64-linux-gnu/libpython3.5m.so.1.0

locate libpython3.7m
/usr/local/lib/libpython3.7m.so
/usr/local/lib/libpython3.7m.so.1.0
/usr/local/lib/python3.7/config-3.7m-x86_64-linux-gnu/libpython3.7m.a

sudo ldconfig /usr/local/lib

ldconfig: /usr/lib/libnvinfer.so.5 is not a symbolic link
ldconfig: /usr/lib/libnvonnxparser_runtime.so.0 is not a symbolic link
ldconfig: /usr/lib/libnvonnxparser.so.0 is not a symbolic link
ldconfig: /usr/lib/libnvparsers.so.5 is not a symbolic link
ldconfig: /usr/lib/libnvinfer_plugin.so.5 is not a symbolic link
</code>```

答: I'm using homebrew/linuxbrew to manage my latest python3 version. Doing this export LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/home/linuxbrew/.linuxbrew/Cellar/python@3.8/3.8.3/lib works for me (no reboot need).

Body:
I have two versions Python-2.7 , Python-3.5  which I was able to access with python(pip) and python3(pip3) command respectively. Then I have installed an another version of python (i.e 3.7.5).

I have used these commands to install it.

sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \
xz-utils tk-dev libffi-dev liblzma-dev

wget https://www.python.org/ftp/python/3.7.5/Python-3.7.5.tgz
tar xvf Python-3.7.5.tgz
cd Python-3.7.5
./configure --enable-optimizations --enable-shared
make -j6
sudo make altinstall

Everything was successful but the only issue is I was not able to access Python-3.7 using the command python3.7.

When I used python3.7 it returned this following error:

python3.7: error while loading shared libraries: libpython3.7m.so.1.0:
  cannot open shared object file: No such file or directory

Can anyone please help me regarding how to fix this issue?

Info: OS: Debian GNU/Linux 9.11 (stretch)

Output when I type:

user_83@debian-241:~$ whereis python
python: /usr/bin/python3.5m-config
/usr/bin/python3.5m
/usr/bin/python2.7-config
/usr/bin/python3.5
/usr/bin/python2.7
/usr/bin/python
/usr/bin/python3.5-config
/usr/lib/python3.5
/usr/lib/python2.7
/etc/python3.5
/etc/python2.7
/etc/python
/usr/local/bin/python3.7m
/usr/local/bin/python3.7
/usr/local/bin/python3.7m-config
/usr/local/lib/python3.5
/usr/local/lib/python2.7
/usr/local/lib/python3.7
/usr/include/python3.5m
/usr/include/python3.5
/usr/include/python2.7
/usr/share/python
/usr/share/man/man1/python.1.gz

UPDATE:

locate libpython3.5m

/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/libpython3.5m-pic.a
/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/libpython3.5m.a
/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/libpython3.5m.so
/usr/lib/x86_64-linux-gnu/libpython3.5m.a
/usr/lib/x86_64-linux-gnu/libpython3.5m.so
/usr/lib/x86_64-linux-gnu/libpython3.5m.so.1
/usr/lib/x86_64-linux-gnu/libpython3.5m.so.1.0

locate libpython3.7m
/usr/local/lib/libpython3.7m.so
/usr/local/lib/libpython3.7m.so.1.0
/usr/local/lib/python3.7/config-3.7m-x86_64-linux-gnu/libpython3.7m.a

sudo ldconfig /usr/local/lib

ldconfig: /usr/lib/libnvinfer.so.5 is not a symbolic link
ldconfig: /usr/lib/libnvonnxparser_runtime.so.0 is not a symbolic link
ldconfig: /usr/lib/libnvonnxparser.so.0 is not a symbolic link
ldconfig: /usr/lib/libnvparsers.so.5 is not a symbolic link
ldconfig: /usr/lib/libnvinfer_plugin.so.5 is not a symbolic link


问:
do (tap) vs subscribe
Edit: Prior to RxJs 6, tap was called as do . Updated title to reflect tap too.

I would like to understand what is the best practice of using .subscribe and .do methods of Observables.

For example if I need to do some job after initial data is loaded from server

```<code>const init$: Observable<MyData> = this._dataService.getData();

init$
  .do((initialData: MyData) => {
    this.data = initialData; // at this step I am initializing the view
  })
  .switchMap(() => loadExtraData)
  .subscribe((extraData) => {
     doSomething(extraData, this._data); // I need this._data here
  });
</code>```

I can do the same with .subscribe

```<code>const init$: Observable<MyData> = this._dataService.getData()
  .shareReplay(1);

init$
  .subscribe((initialData: MyData) => {
    this.data = initialData; // at this step I am initializing the view
  })

init$
  .combineLatest(loadExtraData)
  .subscribe(([initialData, extraData]) => {
     doSomething(extraData, initialData); // I need this._data here
  });
</code>```

Which one is better and why?

答:
I do everything in tap (do), because it allows to return observable, and later concat it with other additional pipes. For example, you can use tap in service, always returning observable as result. It gives you more flexibility to process it as you want, and if tomorrow you decide to add more there, you don't have refactor subscribe to tap. Finally, I put subscribe only at the final end (before rendering) with just .subscribe() (nothing in the parentheses).
Also, it makes the code consistent - so you know all your side-effects are always in tap, not "something in tap and something in subscribe".

P.S. If you use Angular, often you can use | async pipe in view, which subscribes automatically, so it's one more reason to use .tap instead of .subscribe for side-effects.

Title: do (tap) vs subscribe

Body:
Edit: Prior to RxJs 6, tap was called as do . Updated title to reflect tap too.

I would like to understand what is the best practice of using .subscribe and .do methods of Observables.

For example if I need to do some job after initial data is loaded from server

const init$: Observable<MyData> = this._dataService.getData();

init$
  .do((initialData: MyData) => {
    this.data = initialData; // at this step I am initializing the view
  })
  .switchMap(() => loadExtraData)
  .subscribe((extraData) => {
     doSomething(extraData, this._data); // I need this._data here
  });

I can do the same with .subscribe

const init$: Observable<MyData> = this._dataService.getData()
  .shareReplay(1);

init$
  .subscribe((initialData: MyData) => {
    this.data = initialData; // at this step I am initializing the view
  })

init$
  .combineLatest(loadExtraData)
  .subscribe(([initialData, extraData]) => {
     doSomething(extraData, initialData); // I need this._data here
  });

Which one is better and why?


问:
Page not found: Running a php file on an Apache sever
I get page not found error when I try to run my php file running on the root folder of my apache. Other php files run fine(anyway this is a magento based site). Is it because i transferred the file through FTP?
Can a server be configured not to run some specific files? How can i get round this? has is got something to do with .htacess?</p>

答:
Be sure you uploaded your file into the /www or /httpdocs subdirectory.
If so, check the permissions of your file.</p>


问:
Flutter: Unhandled exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
My Flutter application uses the Flutter SharedPreferences plugin and send values to the iOS side with platform.invokeMethod. If I start the application, I have this error:

```<code>[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
#0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:278:7)
<asynchronous suspension>
#1      SharedPreferences.getInstance (package:shared_preferences/shared_preferences.dart:25:27)
<asynchronous suspension>
#2      main (file:///Users/Developer/workspace/flutter-app/q_flutter2/lib/main.dart:25:53)
<asynchronous suspension>
#3      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)
</code>```

If I comment the function to send the value to iOS side, the error is not displayed and the SharedPreferences is working.

Someone can help me?

答:
I had this issue before and this is what I have done to fix it:

Run flutter clean

Run flutter pub get

after that delete your debug app from the device.

Body:
My Flutter application uses the Flutter SharedPreferences plugin and send values to the iOS side with platform.invokeMethod. If I start the application, I have this error:

[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
#0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:278:7)
<asynchronous suspension>
#1      SharedPreferences.getInstance (package:shared_preferences/shared_preferences.dart:25:27)
<asynchronous suspension>
#2      main (file:///Users/Developer/workspace/flutter-app/q_flutter2/lib/main.dart:25:53)
<asynchronous suspension>
#3      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

If I comment the function to send the value to iOS side, the error is not displayed and the SharedPreferences is working.

Someone can help me?


问:
How to insert a specific text at the end of exisitng data in a specific column?
I am using SQL Server 2014. Assume I have a table called T1 with 2 columns, IdNumber and Notes. Table T1 contains around 300,000 records.

The Notes column is a free text column, meaning users have entered therein free text. Some records have this column empty (no text entered).

I now have a list of IdNumbers where I need to add this specific text "(TOC)" in the Notes column of T1, ideally at the end of any text already present therein. I have created a table called tempID which contains the list of all these IdNumbers.

Here is how table T1 looks (extract):

```<code>IdNumber        Notes
--------------------------------------------------------------------
   101          Guest does not like beer
   154          wedding anniversary - to prepare a cake - 03052020
   160
</code>```

IdNumber = 160 has a blank/empty Notes column.

Here is what I want to achieve (assuming "(TOC)" need to be added to these 3 IdNumbers):

```<code>IdNumber        Notes
------------------------------------------------------------------------
  101           Guest does not like beer (TOC)
  154           wedding anniversary - to prepare a cake - 03052020 (TOC)
  160           (TOC)
</code>```

How can I do this (I have a list of around 1500 IdNumbers)?

This is where I am stuck with my SQL query:

```<code>UPDATE T1
INSERT INTO [Notes]
VALUE ('(TOC)') ----stuck here!
WHERE [IdNumber] in (Select [IdNumber] from [tempID]
</code>```

I think it should be done differently since my above query will simply overwrite the existing content of the Notes column with "(TOC)".

答:
try this:</p>

```<code>UPDATE T1
SET T1.Notes = ISNULL(T1.Notes + ' ', '') + '(TOC)'
from T1 inner join dbo.tempID T2 on T1.IdNumber=T2.IdNumber
</code>```

Body:
I am using SQL Server 2014. Assume I have a table called T1 with 2 columns, IdNumber and Notes. Table T1 contains around 300,000 records.

The Notes column is a free text column, meaning users have entered therein free text. Some records have this column empty (no text entered).

I now have a list of IdNumbers where I need to add this specific text "(TOC)" in the Notes column of T1, ideally at the end of any text already present therein. I have created a table called tempID which contains the list of all these IdNumbers.

Here is how table T1 looks (extract):

IdNumber        Notes
--------------------------------------------------------------------
   101          Guest does not like beer
   154          wedding anniversary - to prepare a cake - 03052020
   160

IdNumber = 160 has a blank/empty Notes column.

Here is what I want to achieve (assuming "(TOC)" need to be added to these 3 IdNumbers):

IdNumber        Notes
------------------------------------------------------------------------
  101           Guest does not like beer (TOC)
  154           wedding anniversary - to prepare a cake - 03052020 (TOC)
  160           (TOC)

How can I do this (I have a list of around 1500 IdNumbers)?

This is where I am stuck with my SQL query:

UPDATE T1
INSERT INTO [Notes]
VALUE ('(TOC)') ----stuck here!
WHERE [IdNumber] in (Select [IdNumber] from [tempID]

I think it should be done differently since my above query will simply overwrite the existing content of the Notes column with "(TOC)".

Body:
try this:

UPDATE T1
SET T1.Notes = ISNULL(T1.Notes + ' ', '') + '(TOC)'
from T1 inner join dbo.tempID T2 on T1.IdNumber=T2.IdNumber


问:
python error: argument must be a string or a number, not function
I have the following code:

```<code>import numpy as np
import math
x = np.arange(0, 1.1, h) #point in space
t = np.arange(0, 1.1, k) #point in time
#nodes in matrix form
m = len(x)
n = len(t)
T = np.zeros((m,n))

def ft0 (x):
f = lambda x: math.sin(math.pi*x)# Initial Condition at t=0
return f

for i in range (m-1):
   T[0][i] = ft0[i]
</code>```

When I run the code I get:

TypeError: float() argument must be a string or a number, not
  'function'

I've been searching through the web for solution but I don't really understand the error.

答:
There is multiple issues in the code.

h, k are not defined in the code that you supplied, I assumed them both to be 0.1

As I mentioned in the comment, you should call the function as ft0(i) and not the way you did.

You return the lambda function you defined rather than the result, so you should change it to ...return f(x) rather than ...return f which cause the mentioned error.

You can see the above in the following code:

```<code>import numpy as np
import math

def ft0(x):
    f = lambda x: math.sin(math.pi*x)# Initial Condition at t=0
    return f(x)

h=0.1
k=0.1

x = np.arange(0, 1.1, h) #point in space
t = np.arange(0, 1.1, k) #point in time

#nodes in matrix form
#nodes in matrix form
m = len(x)
n = len(t)
T = np.zeros((m,n))

for i in range(m-1):
   T[i][0] = ft0(i)

print(T)
</code>```

Note

You only assign to the first column, you should probably use double for loop

In the case of lambda inside a function like what you did is unnecessary, you could just use the lambda as a function. I suggest you to read about it int the following link https://realpython.com/python-lambda/

Body:
I have the following code:

import numpy as np
import math
x = np.arange(0, 1.1, h) #point in space
t = np.arange(0, 1.1, k) #point in time
#nodes in matrix form
m = len(x)
n = len(t)
T = np.zeros((m,n))

def ft0 (x):
f = lambda x: math.sin(math.pi*x)# Initial Condition at t=0
return f

for i in range (m-1):
   T[0][i] = ft0[i]

When I run the code I get:

TypeError: float() argument must be a string or a number, not
  'function'

I've been searching through the web for solution but I don't really understand the error.

Body:
There is multiple issues in the code.

h, k are not defined in the code that you supplied, I assumed them both to be 0.1

As I mentioned in the comment, you should call the function as ft0(i) and not the way you did.

You return the lambda function you defined rather than the result, so you should change it to ...return f(x) rather than ...return f which cause the mentioned error.

You can see the above in the following code:

import numpy as np
import math

def ft0(x):
    f = lambda x: math.sin(math.pi*x)# Initial Condition at t=0
    return f(x)

h=0.1
k=0.1

x = np.arange(0, 1.1, h) #point in space
t = np.arange(0, 1.1, k) #point in time

#nodes in matrix form
#nodes in matrix form
m = len(x)
n = len(t)
T = np.zeros((m,n))

for i in range(m-1):
   T[i][0] = ft0(i)

print(T)

Note

You only assign to the first column, you should probably use double for loop

In the case of lambda inside a function like what you did is unnecessary, you could just use the lambda as a function. I suggest you to read about it int the following link https://realpython.com/python-lambda/


问:
how does the cross-validation work in learning curve? Python sklearn
Say I have a learning curve that is sklearn learning curve SVM. And I'm also doing 5-fold cross-validation, which as far as I understand, it means splitting your training data into 5 pieces, train on four of them and testing on the last one.

So my question is, since for each data point in the LearningCurve, the size of the training set is different (Because we want to see how will the model perform with the increasing amount of data), how does the cross-validation work in that case? Does it still split the whole training set into 5 equal pieces? Or it splits the current point training set into five different small pieces, then computes the test score? Is it possible to get a confusion matrix for each data point? (i.e. True Positive, True Negative etc.). I don't see a way to do that yet based on the sklearn learning curve code.

Does how many folds of cross-validation relate to how many pieces of training set we are splitting in train_sizes = np.linspace(0.1, 1.0, 5).

```<code>train_sizes, train_scores, test_scores, fit_times, _ = learning_curve(estimator,
                                                                      X, y, cv,
                                                                      n_jobs, scoring,
                                                                      train_sizes)
</code>```

Thank you!

答:
No, it does the split the training data into 5 folds again. Instead, for a particular combination of training folds (for example - folds 1,2,3 and 4 as training), it will pick only k number of data points (x- ticks) as training from those 4 training folds. Test fold would be used as such as the testing data.

If you look at the code here it would become clearer for you.

```<code>for train, test in cv_iter:
     for n_train_samples in train_sizes_abs:
          train_test_proportions.append((train[:n_train_samples], test))
</code>```

n_train_samples would be something like [200,400,...1400] for the plot that you had mentioned.

Does how many folds of cross-validation relate to how many pieces of training set we are splitting in train_sizes = np.linspace(0.1, 1.0, 5)?

we can't assign any number of folds for a certain train_sizes. It is just a subset of datapoints from all the training folds.

Body:
Say I have a learning curve that is sklearn learning curve SVM. And I'm also doing 5-fold cross-validation, which as far as I understand, it means splitting your training data into 5 pieces, train on four of them and testing on the last one.

So my question is, since for each data point in the LearningCurve, the size of the training set is different (Because we want to see how will the model perform with the increasing amount of data), how does the cross-validation work in that case? Does it still split the whole training set into 5 equal pieces? Or it splits the current point training set into five different small pieces, then computes the test score? Is it possible to get a confusion matrix for each data point? (i.e. True Positive, True Negative etc.). I don't see a way to do that yet based on the sklearn learning curve code.

Does how many folds of cross-validation relate to how many pieces of training set we are splitting in train_sizes = np.linspace(0.1, 1.0, 5).

train_sizes, train_scores, test_scores, fit_times, _ = learning_curve(estimator,
                                                                      X, y, cv,
                                                                      n_jobs, scoring,
                                                                      train_sizes)

Thank you!

Body:
No, it does the split the training data into 5 folds again. Instead, for a particular combination of training folds (for example - folds 1,2,3 and 4 as training), it will pick only k number of data points (x- ticks) as training from those 4 training folds. Test fold would be used as such as the testing data.

If you look at the code here it would become clearer for you.

for train, test in cv_iter:
     for n_train_samples in train_sizes_abs:
          train_test_proportions.append((train[:n_train_samples], test))

n_train_samples would be something like [200,400,...1400] for the plot that you had mentioned.

Does how many folds of cross-validation relate to how many pieces of training set we are splitting in train_sizes = np.linspace(0.1, 1.0, 5)?

we can't assign any number of folds for a certain train_sizes. It is just a subset of datapoints from all the training folds.


问:
How do I Bind a Collection (IEnumerable) of a custom type?
I have the following Action to display a form with 3 items :

```<code>[HttpGet]
    public ActionResult ReferAFriend()
    {
        List<ReferAFriendModel> friends = new List<ReferAFriendModel>();
        ReferAFriendModel f1 = new ReferAFriendModel();
        ReferAFriendModel f2 = new ReferAFriendModel();
        ReferAFriendModel f3 = new ReferAFriendModel();

        friends.Add(f1);
        friends.Add(f2);
        friends.Add(f3);
        return View(friends);
    }
</code>```

and then a Post action

```<code>[HttpPost]
    public ActionResult ReferAFriend(IEnumerable<ReferAFriendModel> friends)
    {
        if(ModelState.IsValid){
</code>```

EDIT
My View looks like this:

```<code>@model IEnumerable<Models.ReferAFriendModel>
@for(int i=0;i<Model.Count();i++)
    {
        @Html.Partial("_ReferAFriend", Model.ElementAt(i));
    }
</code>```

The partial looks like this:

```<code>@model Models.ReferAFriendModel
<p>
   @Html.LabelFor(i => i.FullName) @Html.TextBoxFor(i => i.FullName)<br />
   @Html.LabelFor(i => i.EmailAddress) @Html.TextBoxFor(i => i.EmailAddress)
   @Html.HiddenFor(i=>i.Id)
</p>
</code>```

When I post, I can see the fields are posted in the Request.Form object e.g Request.Form["FullName"] will show: "David Beckham","Thierry Henry". "Chicharito Fergurson" which are the  values I entered in the form. But, the in the Post action,the value for 'friends' is always null. The ReferAFriendModel has three public properties Id, EmailAddress and FullName.

What am I doing wrong?

答:
You may take a look at the following blog post about the wire format for arrays and dictionaries. Personally I always use editor templates in my views which take care of generating proper names of the input fields so that the default model binder is able to bind the values correctly.

```<code>@model IEnumerable<ReferAFriendModel>
@using (Html.BEginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}
</code>```

and in the corresponding editor template (~/Views/Shared/EditorTemplates/ReferAFriendModel.cshtml):

```<code>@model ReferAFriendModel
@Html.EditorFor(x => x.Prop1)
@Html.EditorFor(x => x.Prop2)
...
</code>```

Body:
I have the following Action to display a form with 3 items :

[HttpGet]
    public ActionResult ReferAFriend()
    {
        List<ReferAFriendModel> friends = new List<ReferAFriendModel>();
        ReferAFriendModel f1 = new ReferAFriendModel();
        ReferAFriendModel f2 = new ReferAFriendModel();
        ReferAFriendModel f3 = new ReferAFriendModel();

        friends.Add(f1);
        friends.Add(f2);
        friends.Add(f3);
        return View(friends);
    }

and then a Post action

[HttpPost]
    public ActionResult ReferAFriend(IEnumerable<ReferAFriendModel> friends)
    {
        if(ModelState.IsValid){

EDIT
My View looks like this:

@model IEnumerable<Models.ReferAFriendModel>
@for(int i=0;i<Model.Count();i++)
    {
        @Html.Partial("_ReferAFriend", Model.ElementAt(i));
    }

The partial looks like this:

@model Models.ReferAFriendModel

   @Html.LabelFor(i => i.FullName) @Html.TextBoxFor(i => i.FullName)

   @Html.LabelFor(i => i.EmailAddress) @Html.TextBoxFor(i => i.EmailAddress)
   @Html.HiddenFor(i=>i.Id)

When I post, I can see the fields are posted in the Request.Form object e.g Request.Form["FullName"] will show: "David Beckham","Thierry Henry". "Chicharito Fergurson" which are the  values I entered in the form. But, the in the Post action,the value for 'friends' is always null. The ReferAFriendModel has three public properties Id, EmailAddress and FullName.

What am I doing wrong?

Body:
You may take a look at the following blog post about the wire format for arrays and dictionaries. Personally I always use editor templates in my views which take care of generating proper names of the input fields so that the default model binder is able to bind the values correctly.

@model IEnumerable<ReferAFriendModel>
@using (Html.BEginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}

and in the corresponding editor template (~/Views/Shared/EditorTemplates/ReferAFriendModel.cshtml):

@model ReferAFriendModel
@Html.EditorFor(x => x.Prop1)
@Html.EditorFor(x => x.Prop2)
...


问:
Why system.profile collection is not updated in mongodb?
I have enabled profiling for mongodb cluster with 3 servers by using below configuration:
operationProfiling:
  mode: all
  slowOpThresholdMs: 200
  slowOpSampleRate: 0.98

Only 50 entries are visible in system.profile collection. After couple of hours, there are no more updates. Current size of collection :1.5 KB, default is 1MB.
What could be possible reasons for this and how i can find the root cause ?

2.In a replica of three, I am able to run queries against profile collection only on primary server.
What is the reason for this ?

Any help in resolving above queries is highly appreciated.

答:
There should be a 'system.profile' collection for each database where operations for that database are entered.

Make sure you are checking the right database.

Check with the profile database command or the getProfilingLevel shell helper to make sure it is set the way you expect.


问:
How to merge columns in Mongo
I've got this problem and I can't seem to solve it.

A sample of my data:

```<code>[
{'item': 'U',
'field_1': 3,
'field_2': 1,
'field_3': 1,
'field_4': 2,
'field_5': 5,
   :
   :
   :
},
{'item': 'Y',
'field_1': 9,
'field_2': 2,
'field_3': 3,
'field_4': 5,
'field_5': 1,
   :
   :
   :
}
]
</code>```

I would like to create a new field called REST, which will be the sum of fields not in my input array ([field_1, field_5]).

My desired result is this (for input [field_1, field_5]):

```<code>[
{'item': 'U',
'REST': 13,
},
{'item': 'Y',
'REST': 20
}
]
</code>```

Mongo gurus please help!, Deeply appreciate it. Thanks!

答:
You can use $objectToArray and $filter to achieve this:</p>

```<code>db.collection.aggregate([
    {
        $addFields: {
            rootAsArray: {
                $filter: {
                    input: {$objectToArray: "$$ROOT"},
                    as: "field",
                    cond: {
                        $and: [
                            {$ne: ["$$field.k", "_id"]},
                            {$ne: ["$$field.k", "item"]},
                            ...any other field that's not relevant, you can also just add these to input arr ...

                            {$not: {$setIsSubset: [["$$field.k"], ["field_1", "field_5"]]}}
                        ]
                    }
                }
            }
        }
    },
    {
        $project: {
            item: "$item",
            OTHER: {
                $sum: {
                    $map: {
                        input: "$rootAsArray",
                        as: "value",
                        in: "$$value.v"
                    }
                }
            }
        }
    }
]);
</code>```

Title: How to merge columns in Mongo

Body:
I've got this problem and I can't seem to solve it.

A sample of my data:

[
{'item': 'U',
'field_1': 3,
'field_2': 1,
'field_3': 1,
'field_4': 2,
'field_5': 5,
   :
   :
   :
},
{'item': 'Y',
'field_1': 9,
'field_2': 2,
'field_3': 3,
'field_4': 5,
'field_5': 1,
   :
   :
   :
}
]

I would like to create a new field called REST, which will be the sum of fields not in my input array ([field_1, field_5]).

My desired result is this (for input [field_1, field_5]):

[
{'item': 'U',
'REST': 13,
},
{'item': 'Y',
'REST': 20
}
]

Mongo gurus please help!, Deeply appreciate it. Thanks!

Body:
You can use $objectToArray and $filter to achieve this:

db.collection.aggregate([
    {
        $addFields: {
            rootAsArray: {
                $filter: {
                    input: {$objectToArray: "$$ROOT"},
                    as: "field",
                    cond: {
                        $and: [
                            {$ne: ["$$field.k", "_id"]},
                            {$ne: ["$$field.k", "item"]},
                            ...any other field that's not relevant, you can also just add these to input arr ...

                            {$not: {$setIsSubset: [["$$field.k"], ["field_1", "field_5"]]}}
                        ]
                    }
                }
            }
        }
    },
    {
        $project: {
            item: "$item",
            OTHER: {
                $sum: {
                    $map: {
                        input: "$rootAsArray",
                        as: "value",
                        in: "$$value.v"
                    }
                }
            }
        }
    }
]);


问:
Not Adding Element to Dictionary - RPG Item System
I am implementing an inventory system into my RPG, I am trying to make it so that it gives me the item name, weight, the number of items, etc. I am having trouble with getting the number of items. So here is my code;

```<code>class Item():
    def __init__(self, name, damage, armor, weight, value, itype, rarity):
        self.name = name
        self.damage = damage
        self.armor = armor
        self.weight = weight
        self.value = value
        self.itype = itype
        self.rarity = rarity

class Inventory():

    def __init__(self):
        self.items = {}

    def add_item(self, item):

        self.items[item.name] = item

    def print_items(self):
        print('\t'.join(['Name', 'Atk', 'Arm', 'Kg', 'Val', 'Type', 'Rarity']))

        for item in self.items.values():
            print('\t'.join([str(x) for x in [item.name, item.damage, item.armor, item.weight, item.value, item.itype, item.rarity]]))

Items = {
    'dragonbane': Item('Dragon bane', 60, 0, 5, 1000, 'Weapon', '.oOo. LEGENDARY .oOo.'), # Name, Damage, Armour, Weight, Type, Rarity
    'trainingsword': Item('Training Sword', 2, 0, 5, 10, 'Weapon', '[ Common ]')}

inventory = Inventory()

inventory.add_item(Items['dragonbane']

inventory.print_items()
</code>```

Output:

```<code>Name    Atk Arm Kg  Val Type    Rarity
Dragon bane 60  0   5   1000    Weapon  .oOo. LEGENDARY .oOo.
</code>```

But if I were to add two Dragon Banes, it would only print Dragon Banes once. I simply cannot figure out how to add a system that counts how many of one item the player has.

Thanks in advance :D

答:
You should better use and UID ( Unique ID ) instead of the item name as Identifier for the Items.

also for example:

```<code>def get_uid():
    return random.randint(123456789,987654321)
#here you need to check also for already existing numbers - it's just an example

self.items[get_uid()] = item
</code>```

Body:
I am implementing an inventory system into my RPG, I am trying to make it so that it gives me the item name, weight, the number of items, etc. I am having trouble with getting the number of items. So here is my code;

class Item():
    def __init__(self, name, damage, armor, weight, value, itype, rarity):
        self.name = name
        self.damage = damage
        self.armor = armor
        self.weight = weight
        self.value = value
        self.itype = itype
        self.rarity = rarity

class Inventory():

    def __init__(self):
        self.items = {}

    def add_item(self, item):

        self.items[item.name] = item

    def print_items(self):
        print('\t'.join(['Name', 'Atk', 'Arm', 'Kg', 'Val', 'Type', 'Rarity']))

        for item in self.items.values():
            print('\t'.join([str(x) for x in [item.name, item.damage, item.armor, item.weight, item.value, item.itype, item.rarity]]))

Items = {
    'dragonbane': Item('Dragon bane', 60, 0, 5, 1000, 'Weapon', '.oOo. LEGENDARY .oOo.'), # Name, Damage, Armour, Weight, Type, Rarity
    'trainingsword': Item('Training Sword', 2, 0, 5, 10, 'Weapon', '[ Common ]')}

inventory = Inventory()

inventory.add_item(Items['dragonbane']

inventory.print_items()

Output:

Name    Atk Arm Kg  Val Type    Rarity
Dragon bane 60  0   5   1000    Weapon  .oOo. LEGENDARY .oOo.

But if I were to add two Dragon Banes, it would only print Dragon Banes once. I simply cannot figure out how to add a system that counts how many of one item the player has.

Thanks in advance :D

Body:
You should better use and UID ( Unique ID ) instead of the item name as Identifier for the Items.

also for example:

def get_uid():
    return random.randint(123456789,987654321)
#here you need to check also for already existing numbers - it's just an example

self.items[get_uid()] = item


问:
Fluent Bit part of a string in one of the output field?
I am using AWS Firelens to send logs to Cloudwatch. Firelens sends these below fields by default to fluentbit container along with the log message.

```<code>{
    "container_id": "asdfasdfasdfadsf",
    "container_name": "/ecs-microservice-ms-233-microservice-ms-e8e2e9e3b3c9e5e02100",
    "ecs_cluster": "arn:aws:ecs:us-east-1:1234:cluster/app-microservices",
    "ecs_task_arn": "arn:aws:ecs:us-east-1:1234:task/asdf",
    "ecs_task_definition": "microservice-ms:233"
}
</code>```

I want to do something like this in output section,

```<code>[OUTPUT]
    Name cloudwatch
    Match **
    region us-east-1
    log_group_name /ecs/${microservice}
    log_stream_prefix ${TAG}
    auto_create_group true
</code>```

Where, log group name should be the ecs service name. But I don't have any fields with service name. ecs_task_definition is the closest but it has task revision number.

Is it possible to achieve what I am trying to do?

答:
Fluentbit allows us to use environment variables in the output section. Being said that, the solution to the problem is pass an environment variable to the Firelens container.

In AWS ECS this has to be passed from the task definition section, inside the firelens sidecar container definition,

```<code>    {
        "name": "firelens_log_router",
        "image": "<account_id>.dkr.ecr.us-east-1.amazonaws.com/accel-aws-for-fluent-bit:latest",
        "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
                "awslogs-group": "firelens-container",
                "awslogs-region": "us-east-1",
                "awslogs-create-group": "true",
                "awslogs-stream-prefix": "firelens"
            }
        },
        "memory": 100,
        "memoryReservation": 50,
        "firelensConfiguration": {
            "type": "fluentbit",
            "options": {
                "config-file-type": "file",
                "config-file-value": "/fluent-bit/etc/fluent-bit-accel.conf"
            }
        },
        "environment": [
            {
                "name": "MICROSERVICE_NAME",
                "value": "${microservice_name}"
            }
        ]
    }
</code>```

Then in the OUTPUT section of Fluentbit configuration file,

```<code>[OUTPUT]
    Name cloudwatch
    Match **
    region us-east-1
    log_group_name /ecs/${MICROSERVICE_NAME}
    log_stream_prefix fluentbit.
    auto_create_group true
</code>```

Body:
I am using AWS Firelens to send logs to Cloudwatch. Firelens sends these below fields by default to fluentbit container along with the log message.

{
    "container_id": "asdfasdfasdfadsf",
    "container_name": "/ecs-microservice-ms-233-microservice-ms-e8e2e9e3b3c9e5e02100",
    "ecs_cluster": "arn:aws:ecs:us-east-1:1234:cluster/app-microservices",
    "ecs_task_arn": "arn:aws:ecs:us-east-1:1234:task/asdf",
    "ecs_task_definition": "microservice-ms:233"
}

I want to do something like this in output section,

[OUTPUT]
    Name cloudwatch
    Match **
    region us-east-1
    log_group_name /ecs/${microservice}
    log_stream_prefix ${TAG}
    auto_create_group true

Where, log group name should be the ecs service name. But I don't have any fields with service name. ecs_task_definition is the closest but it has task revision number.

Is it possible to achieve what I am trying to do?

Body:
Fluentbit allows us to use environment variables in the output section. Being said that, the solution to the problem is pass an environment variable to the Firelens container.

In AWS ECS this has to be passed from the task definition section, inside the firelens sidecar container definition,

    {
        "name": "firelens_log_router",
        "image": "<account_id>.dkr.ecr.us-east-1.amazonaws.com/accel-aws-for-fluent-bit:latest",
        "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
                "awslogs-group": "firelens-container",
                "awslogs-region": "us-east-1",
                "awslogs-create-group": "true",
                "awslogs-stream-prefix": "firelens"
            }
        },
        "memory": 100,
        "memoryReservation": 50,
        "firelensConfiguration": {
            "type": "fluentbit",
            "options": {
                "config-file-type": "file",
                "config-file-value": "/fluent-bit/etc/fluent-bit-accel.conf"
            }
        },
        "environment": [
            {
                "name": "MICROSERVICE_NAME",
                "value": "${microservice_name}"
            }
        ]
    }

Then in the OUTPUT section of Fluentbit configuration file,

[OUTPUT]
    Name cloudwatch
    Match **
    region us-east-1
    log_group_name /ecs/${MICROSERVICE_NAME}
    log_stream_prefix fluentbit.
    auto_create_group true


问:
R time series from day to month
I'm new to R and i need help with an R time series. I have daily data that I want to sum up to one month.
How can I sum up the days to a month?
In the end I want to use the TS as monthly frequency.

```<code>library(data.table)

#read csv "ProductList-B1-134564"
coffeedata = fread("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

#Formating date
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")

#dailycounter
countcoffee = function(timeStamps) {
Dates = as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
allDates = seq(from = min(Dates), to = max(Dates), by = "day")
coffee.count = sapply(allDates, FUN = function(X) sum(Dates == X))
data.frame(day = allDates, coffee.count = coffee.count)}
dailycounter = countcoffee(df$coffee.date)

#time series
demand <- ts(dailycounter$coffee.count, start = c(2018, 1), frequency = 365)
plot(demand, type="l", xlab = "Year", col = "orange", lwd = "1", ylab = "Products a day")
</code>```

I appreciate your help.

答:
You could group by month and sum up the daily counter over months, then model this as a time series like this:</p>

```<code>library(data.table)
library(tidyverse)

#read csv "ProductList-B1-134564"
coffeedata = fread("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

#Formating date
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")

#dailycounter
countcoffee = function(timeStamps) {
  Dates = as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
  allDates = seq(from = min(Dates), to = max(Dates), by = "day")
  coffee.count = sapply(allDates, FUN = function(X) sum(Dates == X))
  data.frame(day = allDates, coffee.count = coffee.count)}
dailycounter = countcoffee(df$coffee.date)

monthlycounter <- dailycounter %>%
  group_by(month(ymd(day))) %>%
  summarise(coffe.count_month = sum(coffee.count))

demand <- ts(monthlycounter$coffe.count_month, start = c(2018, 1), frequency = 12)
plot(demand, type="l", xlab = "Year", col = "orange", lwd = "1", ylab = "Products per month")
</code>```

Title: R time series from day to month

Body:
I'm new to R and i need help with an R time series. I have daily data that I want to sum up to one month.
How can I sum up the days to a month?
In the end I want to use the TS as monthly frequency.

library(data.table)

#read csv "ProductList-B1-134564"
coffeedata = fread("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

#Formating date
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")

#dailycounter
countcoffee = function(timeStamps) {
Dates = as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
allDates = seq(from = min(Dates), to = max(Dates), by = "day")
coffee.count = sapply(allDates, FUN = function(X) sum(Dates == X))
data.frame(day = allDates, coffee.count = coffee.count)}
dailycounter = countcoffee(df$coffee.date)

#time series
demand <- ts(dailycounter$coffee.count, start = c(2018, 1), frequency = 365)
plot(demand, type="l", xlab = "Year", col = "orange", lwd = "1", ylab = "Products a day")

I appreciate your help.

Body:
You could group by month and sum up the daily counter over months, then model this as a time series like this:

library(data.table)
library(tidyverse)

#read csv "ProductList-B1-134564"
coffeedata = fread("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

#Formating date
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")

#dailycounter
countcoffee = function(timeStamps) {
  Dates = as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
  allDates = seq(from = min(Dates), to = max(Dates), by = "day")
  coffee.count = sapply(allDates, FUN = function(X) sum(Dates == X))
  data.frame(day = allDates, coffee.count = coffee.count)}
dailycounter = countcoffee(df$coffee.date)

monthlycounter <- dailycounter %>%
  group_by(month(ymd(day))) %>%
  summarise(coffe.count_month = sum(coffee.count))

demand <- ts(monthlycounter$coffe.count_month, start = c(2018, 1), frequency = 12)
plot(demand, type="l", xlab = "Year", col = "orange", lwd = "1", ylab = "Products per month")


问:
Cypher aggregate function on different nodes to evaluate condition for multiple nodes
Metagraph of the database

I have a Neo4j database of Reddit over a specific time period.

I start from a specific subreddit, let's call it X. From X, I define the top_users of this subreddit as the users who have at least 1 post with a score higher than the average score of posts on this subreddit.
Next, I want to look for the other subreddits where the top_users of subreddit X are also top_users but now based on the average score of those subreddits' posts and the top_users' posts on those subreddits.

This is what I already have, but not sure how to proceed.
How should I best do this query?

```<code>MATCH (p:Post)-[:Submitted]->(:Subreddit {display_name: 'X'})
WITH avg(toFloat(p.score)) as score_avg
MATCH (u:User)-[:Submitted]->(p:Post)-[:Submitted]->(:Subreddit {display_name: 'X'})
WHERE p.score > score_avg
WITH DISTINCT u as top_users
MATCH (top_users)-[:Submitted]->(:Post)-[:Submitted]->(sub:Subreddit)
WITH sub as top_users_subs
MATCH (p:Post)-[:Submitted]->(top_users_subs)
WITH avg(toFloat(p.score)) as subs_score, top_users_subs
</code>```

答:
You need a subquery like apoc.cypher.run to not mess with your cardinality.

```<code>MATCH (p:Post)-[:Submitted]->(:Subreddit {display_name: 'X'})
WITH avg(toFloat(p.score)) as score_avg
MATCH (u:User)-[:Submitted]->(p:Post)-[:Submitted]->(:Subreddit {display_name: 'X'})
WHERE p.score > score_avg
WITH DISTINCT u as top_users
MATCH (top_users)-[:Submitted]->(:Post)-[:Submitted]->(sub:Subreddit)
// You need to run a subquery to get the average score for each subreddit
CALL apoc.cypher.run("MATCH (p:Post)-[:Submitted]->(s:Subreddit) WHERE s.display_name = $reddit RETURN avg(toFloat(p.score)) as score_avg",{reddit:sub.display_name}) yield value
// now we have top users and we have average score
// You can do whatever you want to now...
</code>```

Body:
Metagraph of the database

I have a Neo4j database of Reddit over a specific time period.

I start from a specific subreddit, let's call it X. From X, I define the top_users of this subreddit as the users who have at least 1 post with a score higher than the average score of posts on this subreddit.
Next, I want to look for the other subreddits where the top_users of subreddit X are also top_users but now based on the average score of those subreddits' posts and the top_users' posts on those subreddits.

This is what I already have, but not sure how to proceed.
How should I best do this query?

MATCH (p:Post)-[:Submitted]->(:Subreddit {display_name: 'X'})
WITH avg(toFloat(p.score)) as score_avg
MATCH (u:User)-[:Submitted]->(p:Post)-[:Submitted]->(:Subreddit {display_name: 'X'})
WHERE p.score > score_avg
WITH DISTINCT u as top_users
MATCH (top_users)-[:Submitted]->(:Post)-[:Submitted]->(sub:Subreddit)
WITH sub as top_users_subs
MATCH (p:Post)-[:Submitted]->(top_users_subs)
WITH avg(toFloat(p.score)) as subs_score, top_users_subs

Body:
You need a subquery like apoc.cypher.run to not mess with your cardinality.

MATCH (p:Post)-[:Submitted]->(:Subreddit {display_name: 'X'})
WITH avg(toFloat(p.score)) as score_avg
MATCH (u:User)-[:Submitted]->(p:Post)-[:Submitted]->(:Subreddit {display_name: 'X'})
WHERE p.score > score_avg
WITH DISTINCT u as top_users
MATCH (top_users)-[:Submitted]->(:Post)-[:Submitted]->(sub:Subreddit)
// You need to run a subquery to get the average score for each subreddit
CALL apoc.cypher.run("MATCH (p:Post)-[:Submitted]->(s:Subreddit) WHERE s.display_name = $reddit RETURN avg(toFloat(p.score)) as score_avg",{reddit:sub.display_name}) yield value
// now we have top users and we have average score
// You can do whatever you want to now...


问:
My vue.js code is getting data repeatedly from the server
I am new to Vue.js and do not understand this completely (please don't mind the indentation)

```<code>  methods:{
getdata() {
  if (this.myPage.month === 5) {
    axios.get("http://www.amock.io/api/maymock").then(response => {
      this.Month = response.data.checkInData.Month;
      this.Stat = response.data.checkInData.CheckedInStat;
      this.TotalTarget = response.data.checkInData.TotalTarget;
      this.$emit("TotTarget", this.TotalTarget);
      this.TargetForMonth = response.data.checkInData.CurrentAchieved;
      this.$emit("TotCount", this.TargetForMonth);
  })
}
  if (this.myPage.month === 4) {
    axios.get("http://www.amock.io/api/aprilmock").then(response => {
      this.Month = response.data.checkInData.Month;
      this.Stat = response.data.checkInData.CheckedInStat;
      this.TotalTarget = response.data.checkInData.TotalTarget;
      this.$emit("TotTarget", this.TotalTarget);
      this.TargetForMonth = response.data.checkInData.CurrentAchieved;
      this.$emit("TotCount", this.TargetForMonth);
  })
     }

   },
},

computed: {
attributes() {
  this.getdata();
  let checkindata = [];
  if (this.Click === 0) {
    var entry = new Object();
    (entry.highlight = "red"), (entry.dates = new Date());
    checkindata.push(entry);
    for (var day = 0; day < this.Stat.length; ++day) {
      entry = new Object();
      (entry.highlight = this.Stat[day] === 0 ? "red" : "green"),
        (entry.dates = new Date(2020, this.Month, day + 1));
      checkindata.push(entry);
    }
  }
  if (this.Click === 1) {
    var entry1 = new Object();
    (entry.highlight = "green"), (entry.dates = new Date());
    checkindata.push(entry1);
    for (day = 0; day < this.Stat.length; ++day) {
      entry1 = new Object();
      (entry.highlight = this.Stat[day] === 0 ? "red" : "green"),
        (entry.dates = new Date(2020, this.Month, day + 1));
      checkindata.push(entry1);
    }
  }
  return checkindata;
 }
},

  data() {
return {
  myPage: {},
  Stat: [],
  Month: null,
  TotalTarget: null,
  TargetForMonth: null,
  responded: null
  };
}
</code>```

I am using a v-calendar plugin and passing data via the attributes function to the Calendar. However, I want the method getdata to get data from the link provided when the variable myPage.month changes and it should do so only once. How myPage changes isn't given here as it is dynamic with the calendar plugin. Currently, it is doing this an infinite number of times which is troublesome. Is there any way to solve this?

答:
You're calling getData() inside a computed property. This is not correct; you should not be mutating state inside a computed property, not to mention it will be called every time the property needs to be recalculated.

This is something you should do with a watcher instead. Just watch myPage.month for changes and then call getData() in response to those changes.

Something like this:

watch: {
  'myPage.month': {
    immediate: true,
    handler() {
      this.getData();
    }
  }
}
```

<p>A couple of other improvements:</p>

<ul>
<li>Instead of <code>new Object()</code> just do <code>{}</code> instead.</li>
<li>Code like <code>(x = 1), (y = 2)</code> should be 2 separate statements (separated by <code>;</code> not <code>,</code>) ideally on separate lines. The <code>()</code> aren't necessary.</li>
<li>Actually you can construct the object in one go like this:</li>
</ul>

<pre class="lang-js prettyprint-override"><code>var entry = {
  highlight: "red",
  dates: new Date(),
};
checkindata.push(entry);
</code>```

Try reducing the duplicated code as much as possible:

getData() {
  let api;
  switch (this.myPage.month) {
    case 4: api = 'aprilmock'; break;
    case 5: api = 'maymock'; break;
    default: return;
  }

  axios.get(`http://www.amock.io/api/${api}`).then(response => {
    this.Month = response.data.checkInData.Month;
    this.Stat = response.data.checkInData.CheckedInStat;
    this.TotalTarget = response.data.checkInData.TotalTarget;
    this.$emit("TotTarget", this.TotalTarget);
    this.TargetForMonth = response.data.checkInData.CurrentAchieved;
    this.$emit("TotCount", this.TargetForMonth);
  });
}
```

Body:
I am new to Vue.js and do not understand this completely (please don't mind the indentation)

  methods:{
getdata() {
  if (this.myPage.month === 5) {
    axios.get("http://www.amock.io/api/maymock").then(response => {
      this.Month = response.data.checkInData.Month;
      this.Stat = response.data.checkInData.CheckedInStat;
      this.TotalTarget = response.data.checkInData.TotalTarget;
      this.$emit("TotTarget", this.TotalTarget);
      this.TargetForMonth = response.data.checkInData.CurrentAchieved;
      this.$emit("TotCount", this.TargetForMonth);
  })
}
  if (this.myPage.month === 4) {
    axios.get("http://www.amock.io/api/aprilmock").then(response => {
      this.Month = response.data.checkInData.Month;
      this.Stat = response.data.checkInData.CheckedInStat;
      this.TotalTarget = response.data.checkInData.TotalTarget;
      this.$emit("TotTarget", this.TotalTarget);
      this.TargetForMonth = response.data.checkInData.CurrentAchieved;
      this.$emit("TotCount", this.TargetForMonth);
  })
     }

   },
},

computed: {
attributes() {
  this.getdata();
  let checkindata = [];
  if (this.Click === 0) {
    var entry = new Object();
    (entry.highlight = "red"), (entry.dates = new Date());
    checkindata.push(entry);
    for (var day = 0; day < this.Stat.length; ++day) {
      entry = new Object();
      (entry.highlight = this.Stat[day] === 0 ? "red" : "green"),
        (entry.dates = new Date(2020, this.Month, day + 1));
      checkindata.push(entry);
    }
  }
  if (this.Click === 1) {
    var entry1 = new Object();
    (entry.highlight = "green"), (entry.dates = new Date());
    checkindata.push(entry1);
    for (day = 0; day < this.Stat.length; ++day) {
      entry1 = new Object();
      (entry.highlight = this.Stat[day] === 0 ? "red" : "green"),
        (entry.dates = new Date(2020, this.Month, day + 1));
      checkindata.push(entry1);
    }
  }
  return checkindata;
 }
},

  data() {
return {
  myPage: {},
  Stat: [],
  Month: null,
  TotalTarget: null,
  TargetForMonth: null,
  responded: null
  };
}

I am using a v-calendar plugin and passing data via the attributes function to the Calendar. However, I want the method getdata to get data from the link provided when the variable myPage.month changes and it should do so only once. How myPage changes isn't given here as it is dynamic with the calendar plugin. Currently, it is doing this an infinite number of times which is troublesome. Is there any way to solve this?

Body:
You're calling getData() inside a computed property. This is not correct; you should not be mutating state inside a computed property, not to mention it will be called every time the property needs to be recalculated.

This is something you should do with a watcher instead. Just watch myPage.month for changes and then call getData() in response to those changes.

Something like this:

watch: {
  'myPage.month': {
    immediate: true,
    handler() {
      this.getData();
    }
  }
}

A couple of other improvements:

Instead of new Object() just do {} instead.

Code like (x = 1), (y = 2) should be 2 separate statements (separated by ; not ,) ideally on separate lines. The () aren't necessary.

Actually you can construct the object in one go like this:

var entry = {
  highlight: "red",
  dates: new Date(),
};
checkindata.push(entry);

Try reducing the duplicated code as much as possible:

getData() {
  let api;
  switch (this.myPage.month) {
    case 4: api = 'aprilmock'; break;
    case 5: api = 'maymock'; break;
    default: return;
  }

  axios.get(`http://www.amock.io/api/${api}`).then(response => {
    this.Month = response.data.checkInData.Month;
    this.Stat = response.data.checkInData.CheckedInStat;
    this.TotalTarget = response.data.checkInData.TotalTarget;
    this.$emit("TotTarget", this.TotalTarget);
    this.TargetForMonth = response.data.checkInData.CurrentAchieved;
    this.$emit("TotCount", this.TargetForMonth);
  });
}


问:
How to test write to file with rspec?
I have my function code like this :

```<code>      Dir.mkdir('config') unless File.exist?('config')
      File.open('config/brakeman.yml', 'wb') do |file|
        file.write(response.body)
</code>```

How can I test the line which is file.write(response.body)?
I tried to mock and stub like this:

```<code>  allow(response).to receive(:body).and_return(body)
  allow(File).to receive(:open).with('config/brakeman.yml', 'wb') do |file|
    file.write(response.body)
  end
  expect(File).to receive(:open).with('config/brakeman.yml', 'wb')
  subject.create_config(response)
  expect(file).to receive(:write).with(body)
  expect(File.open('config/brakeman.yml')).to eq(body)
</code>```

答:
I think it is not a good idea to test standard library methods. Just cover it with

allow(File).to receive(:open).with('config/brakeman.yml', 'wb') do |file|
  expect(file).to receive(:write).with(response.body)
end
```

And that should be enough, I think

Do not test code that already tested :)

Title: How to test write to file with rspec?

Body:
I have my function code like this :

      Dir.mkdir('config') unless File.exist?('config')
      File.open('config/brakeman.yml', 'wb') do |file|
        file.write(response.body)

How can I test the line which is file.write(response.body)?
I tried to mock and stub like this:

  allow(response).to receive(:body).and_return(body)
  allow(File).to receive(:open).with('config/brakeman.yml', 'wb') do |file|
    file.write(response.body)
  end
  expect(File).to receive(:open).with('config/brakeman.yml', 'wb')
  subject.create_config(response)
  expect(file).to receive(:write).with(body)
  expect(File.open('config/brakeman.yml')).to eq(body)

Body:
I think it is not a good idea to test standard library methods. Just cover it with

allow(File).to receive(:open).with('config/brakeman.yml', 'wb') do |file|
  expect(file).to receive(:write).with(response.body)
end

And that should be enough, I think

Do not test code that already tested :)


问:
summing number of different columns
I want to return the list of data frames with the number of different columns apart from the name column, which I want to return the same. So for this example, it would return </p>

```<code>list3$dfa

     names X  Y   Z
1    Ben   1  1   2

list3$dfb

   names  X  Y  Z
1  John   2  2  2

</code>```

<p>Kindly let me know how I would do this, please.  </p>

答:
You can use Map :

```<code>Map(function(x, y) data.frame(Name = x[[1]][1],
                       t(colMeans(x[-1] != y[-1])) * 100), list1, list2)

#$dfa
#  Name    X    Y    Z
#1  Ben 33.3 33.3 66.7

#$dfb
#  Name  X  Y  Z
#1 John 50 50 75
</code>```

Title: summing number of different columns

Body:
I want to return the list of data frames with the number of different columns apart from the name column, which I want to return the same. So for this example, it would return

list3$dfa

     names X  Y   Z
1    Ben   1  1   2

list3$dfb

   names  X  Y  Z
1  John   2  2  2

Kindly let me know how I would do this, please.

Body:
You can use Map :

Map(function(x, y) data.frame(Name = x[[1]][1],
                       t(colMeans(x[-1] != y[-1])) * 100), list1, list2)

#$dfa
#  Name    X    Y    Z
#1  Ben 33.3 33.3 66.7

#$dfb
#  Name  X  Y  Z
#1 John 50 50 75


问:
Passing a Parameter to the function
I am trying to pass the parameter name to the function, but I am unable to pass</p>

```<code>function interfaceName(x,y,z){
return "<div class='iconRow2 linkrow'><a href='javascript:mcrloadgraphdata('+x+'')'>"+x+"</a></div>";
}

function mcrloadgraphdata(interfaceName)
{
    alert(interfaceName);
}
</code>```

答:
replace your return statement by this :</p>

```<code>return "<div class='iconRow2 linkrow'><a href='javascript:mcrloadgraphdata('"+x+"')'>" + x + "</a></div>";
</code>```

Title: Passing a Parameter to the function

Body:
I am trying to pass the parameter name to the function, but I am unable to pass

function interfaceName(x,y,z){
return "
"+x+"
";
}

function mcrloadgraphdata(interfaceName)
{
    alert(interfaceName);
}

Body:
replace your return statement by this :

return "<div class='iconRow2 linkrow'><a href='javascript:mcrloadgraphdata('"+x+"')'>" + x + "</a></div>";


问:
How can I transfer a stacktrace betwen Scala ExecutionContexts?
I have written a small utility wrapper around the Scala ExecutionContext to enable transfer of MDC contexts across Future instances. It works as expected but an undesired side-effect is that we now don't seem to get stack traces that go across Futures. How can I ensure that the stack trace is propagated along with the MDC?

Here's my code for reference:

```<code>import org.slf4j.MDC

import scala.concurrent.ExecutionContext
import scala.jdk.CollectionConverters._

object MdcOps {

  implicit class ExecutionContextExt(value: ExecutionContext) {
    def withMdc: ExecutionContext = new MdcExecutionContext(value)
  }

  def withMdc[A](mdc: Map[String, Any], replace: Boolean)(doIt: => A): A = {
    val currentMdcContext = getMdc
    val newMdc = if(replace) mdc else mdc ++ currentMdcContext
    try { setMdc(newMdc); doIt }
    finally { setMdc(currentMdcContext) }
  }

  def setMdc(mdc: Map[String, Any]): Unit = {
    if(mdc.isEmpty) {
      MDC.clear()
    } else
      MDC.setContextMap(mdc.view.mapValues(_.toString).toMap.asJava)
  }

  def getMdc: Map[String, String] = Option(MDC.getCopyOfContextMap).map(_.asScala.toMap).getOrElse(Map.empty)
}

class MdcExecutionContext(underlying: ExecutionContext, context: Map[String, String] = Map.empty) extends ExecutionContext {
  override def prepare(): ExecutionContext = new MdcExecutionContext(underlying, MdcOps.getMdc)
  override def execute(runnable: Runnable): Unit = underlying.execute { () =>
    MdcOps.withMdc(context, replace = true)(runnable.run())
  }
  override def reportFailure(t: Throwable): Unit = underlying.reportFailure(t)
}
</code>```

答:
In general it is hard. ZIO implemented it - see: https://www.slideshare.net/jdegoes/error-management-future-vs-zio from slide 53 to see the result - but creation of stacks, and passing it around causes performance penalty x2.4.

Since you cannot change API to e.g. generate stack trace in compile times using macros (using e.g. sourcode library), on each .map/.flatMap you would have to create a stack trace, remove irrelevant frames from it, maybe combine it with frames from previous context and set it in MDC. Putting technical details aside - this is hard to get right and heavy weight, more like a material for a whole library than simple utility. If it could be done cheaply this would be a build in.

If you are very interested in it, either pick ZIO or analyze how it implements it - from what I see it required a lot of effort and building this functionality into the library, and even then it causes performance penalty. I can only imagine that penalty by using JVM stack traces and passing them around would be even greater.

Body:
I have written a small utility wrapper around the Scala ExecutionContext to enable transfer of MDC contexts across Future instances. It works as expected but an undesired side-effect is that we now don't seem to get stack traces that go across Futures. How can I ensure that the stack trace is propagated along with the MDC?

Here's my code for reference:

import org.slf4j.MDC

import scala.concurrent.ExecutionContext
import scala.jdk.CollectionConverters._

object MdcOps {

  implicit class ExecutionContextExt(value: ExecutionContext) {
    def withMdc: ExecutionContext = new MdcExecutionContext(value)
  }

  def withMdc[A](mdc: Map[String, Any], replace: Boolean)(doIt: => A): A = {
    val currentMdcContext = getMdc
    val newMdc = if(replace) mdc else mdc ++ currentMdcContext
    try { setMdc(newMdc); doIt }
    finally { setMdc(currentMdcContext) }
  }

  def setMdc(mdc: Map[String, Any]): Unit = {
    if(mdc.isEmpty) {
      MDC.clear()
    } else
      MDC.setContextMap(mdc.view.mapValues(_.toString).toMap.asJava)
  }

  def getMdc: Map[String, String] = Option(MDC.getCopyOfContextMap).map(_.asScala.toMap).getOrElse(Map.empty)
}

class MdcExecutionContext(underlying: ExecutionContext, context: Map[String, String] = Map.empty) extends ExecutionContext {
  override def prepare(): ExecutionContext = new MdcExecutionContext(underlying, MdcOps.getMdc)
  override def execute(runnable: Runnable): Unit = underlying.execute { () =>
    MdcOps.withMdc(context, replace = true)(runnable.run())
  }
  override def reportFailure(t: Throwable): Unit = underlying.reportFailure(t)
}


问:
Is IIS Form Authentication related anonymous authentication account?
Some resources (images) don't appear when I visit the main page after login (using form authentication)
However, setting the attribute of anonymous authentication to 'application pool id' in iis manager works

what windows account is used for form authentication in iis?

答:
Only the login Page need anonymous authorization access. It sounds like you didn't set anonymous authentication correctly.

When we implement form authentication in IIS, Both form authentication and anonymous authentication are enabled side-by-side. Then we will create allow auth rule for all user and deny anonymous user in site level.

```<code><authentication mode="Forms">
  <forms name=".MyCookie" loginUrl="Login" protection="All" timeout="60" />
</authentication>
<authorization>
  <deny users="?" />
  <allow users="*" />
</authorization>
</code>```

Secondly, we need to create a authorization  rule to allow anonymous access to login page.

```<code> <location path="Login">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
</code>```

When you pass the form authentication, IIS will send a form authentication cookie with the username which is decided by your application. It can be a key in appsetting or a username from database.

1.

```<code>FormsAuthentication.SetAuthCookie(UserInfo.UserName, false, FormsAuthentication.FormsCookiePath);
</code>```

2.

```<code>FormsAuthenticationTicket
</code>```

3.

```<code>FormsAuthentication.RedirectFromLoginPage(UserInfo.UserName, false);
</code>```

You need to make sure the auth_user and application pool identity have permission to access the  image sources.
https://support.microsoft.com/en-us/help/301240/how-to-implement-forms-based-authentication-in-your-asp-net-applicatio

Body:
Only the login Page need anonymous authorization access. It sounds like you didn't set anonymous authentication correctly.

When we implement form authentication in IIS, Both form authentication and anonymous authentication are enabled side-by-side. Then we will create allow auth rule for all user and deny anonymous user in site level.

<authentication mode="Forms">
  <forms name=".MyCookie" loginUrl="Login" protection="All" timeout="60" />
</authentication>
<authorization>
  <deny users="?" />
  <allow users="*" />
</authorization>

Secondly, we need to create a authorization  rule to allow anonymous access to login page.

 <location path="Login">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

When you pass the form authentication, IIS will send a form authentication cookie with the username which is decided by your application. It can be a key in appsetting or a username from database.

1.

FormsAuthentication.SetAuthCookie(UserInfo.UserName, false, FormsAuthentication.FormsCookiePath);

2.

FormsAuthenticationTicket

3.

FormsAuthentication.RedirectFromLoginPage(UserInfo.UserName, false);

You need to make sure the auth_user and application pool identity have permission to access the  image sources.
https://support.microsoft.com/en-us/help/301240/how-to-implement-forms-based-authentication-in-your-asp-net-applicatio