问:
promox ufw ip routing
I try to setup a proxmox node with an external ip class map to an internal ip class :

62.xxx.yyy.zzz/24 <--> 192.168.yyy.zzz/24

each external ip match on internal ip, so each VM got her own external ip.
the proxmox host got is own external ip (outside the /24 range) and got a web access by himself.

if I use :
    # NAT table rules
    *nat
    :POSTROUTING ACCEPT [0:0]

```<code># Forward traffic through eth0 - Change to match you out-interface
-A POSTROUTING -s 192.168.0.0/16 -o vmbr0 -j MASQUERADE

# don't delete the 'COMMIT' line or these rules won't be processed
COMMIT
</code>```

all the VM with ip 192.168.x.x can access the web but with the ip address of the host.

If I change the -A POSTROUTING LINE with :

```<code>-A PREROUTING  -o vmbr0 -d 62.xxx.yyy.0/24 -j DNAT --to-destination 192.168.yyy.0/24
-A POSTROUTING -o vmbr1 -s 192.168.yyy.0/24 -j NETMAP DNAT --to-destination  62.xxx.yyy.0/24
</code>```

I got an error for the DNAT destination not being an ip but a class, it seems that the NETMAP is not supported ...

any idea to point me to ?

Thanks !

Stéphane

答:
You should try using iptables 1:1 NAT.

You will need a rule like this:

```<code>iptables -t nat -A PREROUTING -i internet_interface -d 62.xxx.yyy.0/24 -j NETMAP --to 192.168.yyy.zzz/24
</code>```

I think the link bellow will definetely help you to achieve your goal:
https://serverfault.com/questions/109569/iptables-massive-11-nat

ufw is just an easy way to implement ip tables rules. In your case I think the best approach is to create your own iptables rules without using ufw or any other similar firewall utilities (on linux they are all based on iptables).

Title: promox ufw ip routing

Body:
I try to setup a proxmox node with an external ip class map to an internal ip class :

62.xxx.yyy.zzz/24 <--> 192.168.yyy.zzz/24

each external ip match on internal ip, so each VM got her own external ip.
the proxmox host got is own external ip (outside the /24 range) and got a web access by himself.

if I use :
    # NAT table rules
    *nat
    :POSTROUTING ACCEPT [0:0]

# Forward traffic through eth0 - Change to match you out-interface
-A POSTROUTING -s 192.168.0.0/16 -o vmbr0 -j MASQUERADE

# don't delete the 'COMMIT' line or these rules won't be processed
COMMIT

all the VM with ip 192.168.x.x can access the web but with the ip address of the host.

If I change the -A POSTROUTING LINE with :

-A PREROUTING  -o vmbr0 -d 62.xxx.yyy.0/24 -j DNAT --to-destination 192.168.yyy.0/24
-A POSTROUTING -o vmbr1 -s 192.168.yyy.0/24 -j NETMAP DNAT --to-destination  62.xxx.yyy.0/24

I got an error for the DNAT destination not being an ip but a class, it seems that the NETMAP is not supported ...

any idea to point me to ?

Thanks !

Stéphane

Body:
You should try using iptables 1:1 NAT.

You will need a rule like this:

iptables -t nat -A PREROUTING -i internet_interface -d 62.xxx.yyy.0/24 -j NETMAP --to 192.168.yyy.zzz/24

I think the link bellow will definetely help you to achieve your goal:
https://serverfault.com/questions/109569/iptables-massive-11-nat

ufw is just an easy way to implement ip tables rules. In your case I think the best approach is to create your own iptables rules without using ufw or any other similar firewall utilities (on linux they are all based on iptables).


来源: stackexchange

问:
Load balancing: when should a user always connect to the same server?
I came across the "source" load balancing algorithm in HAProxy, which ensures that a user will connect to the same server, by choosing server based on a hash of the source IP.

Why and when is it important for a user to connect to the same server? I cannot think of a reason, assuming that all candidate servers serve identical content.

Furthermore, if  there was the need for a user to always connect to the same server, then wouldn't load balancing be completely irrelevant for this user?

答:
It is important for a user to connect to the same server if we want to achieve session persistence.

For example, when talking about a HTTP session, there are information/variables (think about a shopping cart) specific to the session in question.

This dynamic information is not shared by the candidate servers in case they are not configured to do so and it is simpler to deal with it at the load-balancing level.

The preferred way to deal with this in HAProxy is by using cookies, but this only works in HTTP mode. HAProxy offers the source load balancing algorithm, in case cookies can't be used. This can be used in TCP mode or with HTTP clients that refuse cookies.

Load balancing will be irrelevant for the user in question right, until the cookie expires. But we generally need load balancing when dealing with many users so that they can be served by multiple servers with each user sticking with one of them.

ContentLicense: CC BY-SA 3.0


Title: sorting python pandas dataframe by matching values of two different columns and calculate the mean

Body:
I have a text file that imported as pandas dataframe looks like:

       a   b  c   d      e
index
0      18  1  1 -30.47  0.746
1      19  1  1 -30.47  0.751
2      20  1  1 -30.47  0.801
3      33  2  1 -30.47  1.451
4      34  2  1 -30.47  1.534
5      35  2  1 -30.47  1.551
6      49  3  1 -30.47  2.297
7      50  3  1 -30.47  2.301
8      51  3  1 -30.47  2.351
9      64  4  1 -30.47  3.001
10     65  4  1 -30.47  3.085
11     66  4  1 -30.47  3.101
12    346  1  2 -28.47  0.601
13    347  1  2 -20     0.682
14    348  1  2 -28.47  0.701
15    362  2  2 -28.47  1.445
16    363  2  2 -28.47  1.451
17    364  2  2 -28.47  1.501
18    377  3  2 -28.47  2.151
19    378  3  2 -28.47  2.233
20    379  3  2 -28.47  2.251
21    392  4  2 -28.47  2.901
22    393  4  2 -28.47  2.996
23    394  4  2 -28.47  3.001
24    675  1  3 -25     0.596
25    676  1  3 -26     0.601
26    677  1  3 -22     0.651
27    690  2  3 -26.47  1.301
28    691  2  3 -26.47  1.384
29    692  2  3 -26.47  1.401
30    705  3  3 -26.47  2.051
31    706  3  3 -26.47  2.147
32    707  3  3 -26.47  2.151
33    721  4  3 -26.47  2.851
34    722  4  3 -26.47  2.935
35    723  4  3 -26.47  2.951

I have been trying to reorganize the dataframe as following: for each value in col two, for example value 1, there are multiple corresponding values in column three and four.For example

value 1 (col one) corresponds to: value 1 (col three), -3.47 (col four);
value 1 (col three), -3.47 (col four); value 1 (col three), -3.47 (col four).....value 3 (col three), -25  (col four); value 3 (col three), -26 (col four); value 3 (col three), -22 (col four)

and so on. I would like to create a new dataframe where for value 1 there are other three corresponding columns, 1,2 and 3, containing the mean of the three values of the original column four. The output should look like:

col 1, col 2,                    col 3,                  col 4

1      mean(-3.47,-3.47,-3.47)   mean(-28.47,-20,-20.47) mean(-25, -26,-22)

The output should contain all the values of column one, in this case 1,2,3 and 4 (table 4x3). I am not an expert in python, I have no idea how I should approach this task besides matching values in couple. Any help is more than welcome!

Body:
IIUC:

df.groupby([2,3])[4].mean().reset_index(name='Mean').pivot(columns=3,index=2,values='Mean')

Output:

3      1          2          3
2
1 -30.47 -25.646667 -24.333333
2 -30.47 -28.470000 -26.470000
3 -30.47 -28.470000 -26.470000
4 -30.47 -28.470000 -26.470000


问:
using jquery in masterpages
hello dear fellow programmers
i'm having a silly trouble using jquery in master pages which is i desire to call a function in masterpage itself not the related pages to the master page.
here is the head of my masterpage

```<code><%@ Master Language="C#" AutoEventWireup="true" CodeFile="CMS_master.master.cs" Inherits="CMS_master" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
    <link href="css/Exclusive_fonts.css" rel="stylesheet" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="css/CMS_Style.css" rel="stylesheet" />
    <script src="<%ResolveUrl("~/Scripts/jquery-3.1.1.min.js"); %>" type="text/javascript">
                   window.alert("a");
    </script>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
</code>```

the setback is that jquery and javascripts codes are not recognized and rendered.
i know there are questions that might have answered this problem but none of them worked for me.

答:
You made 2 typos in the script tag. You forgot the = sign and remove the ; at the end.

```<code><script src="<%= ResolveUrl("~/Scripts/jquery-3.1.1.min.js") %>" type="text/javascript"></script>
</code>```

This renders in html as src="/Scripts/jquery-3.1.1.min.js"

Title: using jquery in masterpages

Body:
hello dear fellow programmers
i'm having a silly trouble using jquery in master pages which is i desire to call a function in masterpage itself not the related pages to the master page.
here is the head of my masterpage

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="CMS_master.master.cs" Inherits="CMS_master" %>

    <title></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
    <link href="css/Exclusive_fonts.css" rel="stylesheet" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="css/CMS_Style.css" rel="stylesheet" />

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>

the setback is that jquery and javascripts codes are not recognized and rendered.
i know there are questions that might have answered this problem but none of them worked for me.

Body:
You made 2 typos in the script tag. You forgot the = sign and remove the ; at the end.

<script src="<%= ResolveUrl("~/Scripts/jquery-3.1.1.min.js") %>" type="text/javascript"></script>

This renders in html as src="/Scripts/jquery-3.1.1.min.js"


问:
HTML/CSS - Iframe fit screen
I use the code below in order to display a youtube video. I set its size at 560 width and 315 height. Code works good but when I try to resize the window, the iframe/video doesn't resize but instead scrollbars appear. How can I make the iframe also resize so it always fits the width of the screen?</p>

```<code><body>
    <iframe width="560" height="315" src="https://www.youtube.com/embed/a3ICNMQW7Ok?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</body>
</code>```

答:
Responsive With Device iframe

.container {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%;
}
.video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

<div class="container">
<iframe src="https://www.youtube.com/embed/a3ICNMQW7Ok?rel=0&showinfo=0"
frameborder="0" allowfullscreen  scrolling="auto" class="video"></iframe>
</div>

</body></code>```

Title: HTML/CSS - Iframe fit screen

Body:
Responsive With Device iframe

.container {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%;
}
.video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

<body>

<div class="container">
<iframe src="https://www.youtube.com/embed/a3ICNMQW7Ok?rel=0&amp;showinfo=0"
frameborder="0" allowfullscreen  scrolling="auto" class="video"></iframe>
</div>

</body>


问:
CSS: Let a child element with variable height and position absolute end at the top of the parent element?
In a website I have a "dropup" menu at the bottom of a website.

Have a look at the following fiddle:

body {
    background-color: #ccc;
}
ul {
    list-style-type:none;
    width:200px;
}
.spacer {
    height:150px;
    width:auto;
}
ul,li {
    margin:0;
    padding:0;
}
a {
    color:#fff;
    width:200px;
    background-color:#e4003d;
}
ul li a {
    text-decoration: none;
    display: block;
    padding: 10px;
}

ul li ul {
    z-index: 8888;
    position: absolute;
    background-color: #fff;
    display: none;
}

ul:hover li ul, ul:focus li ul {
    display:block;
}

ul li ul li {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}
ul li ul li a {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}

ul li ul li a:hover, ul li ul li a:focus {
    background-color: #e4003d;
    color: #fff !important;
}

ul li ul {
    margin-top: -100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="spacer"></div>
<ul class="page-switcher">
  <li>
    Sitamet
    <ul>
      <li>Lorem</li>
      <li>Ipsum</li>
      <li>Dolor</li>
    </ul>
  </li>
</ul>
<div class="spacer"></div></code>```

When the menu is hovered I want the submenu to end exactly at the top of the ul.page-switcher. There is no information about the number of items within the menu or their height.

In the example I have used margin-top:-100px; but this is just for demonstration as the number of pixels is not fixed.

Need a CSS only solution and should keep the position absolute. How would you solve this?

答:
Use  position: relative;bottom: 56px; 56px is the height of parent ul

body {
    background-color: #ccc;
}
ul {
    list-style-type:none;
    width:200px;
}
.spacer {
    height:100px;
    width:auto;
}
ul,li {
    margin:0;
    padding:0;
}
a {
    color:#fff;
    width:200px;
    background-color:#e4003d;
}
ul li a {
    text-decoration: none;
    display: block;
    padding: 10px;
}

ul li ul {
    z-index: 8888;
    background-color: #fff;
    display: none;
    position: relative;
    bottom: 56px;
}

ul:hover li ul, ul:focus li ul {
    display:block;
}

ul li ul li {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}
ul li ul li a {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}

ul li ul li a:hover, ul li ul li a:focus {
    background-color: #e4003d;
    color: #fff !important;
}

ul li ul {
    margin-top: -100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="spacer"></div>
<ul class="page-switcher">
  <li>
    Sitamet
    <ul>
      <li>Lorem</li>
      <li>Ipsum</li>
      <li>Dolor</li>
    </ul>
  </li>
</ul>
<div class="spacer"></div></code>```

Body:
In a website I have a "dropup" menu at the bottom of a website.

Have a look at the following fiddle:

body {
    background-color: #ccc;
}
ul {
    list-style-type:none;
    width:200px;
}
.spacer {
    height:150px;
    width:auto;
}
ul,li {
    margin:0;
    padding:0;
}
a {
    color:#fff;
    width:200px;
    background-color:#e4003d;
}
ul li a {
    text-decoration: none;
    display: block;
    padding: 10px;
}

ul li ul {
    z-index: 8888;
    position: absolute;
    background-color: #fff;
    display: none;
}

ul:hover li ul, ul:focus li ul {
    display:block;
}

ul li ul li {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}
ul li ul li a {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}

ul li ul li a:hover, ul li ul li a:focus {
    background-color: #e4003d;
    color: #fff !important;
}

ul li ul {
    margin-top: -100px;
}

    Sitamet

Lorem

Ipsum

Dolor

When the menu is hovered I want the submenu to end exactly at the top of the ul.page-switcher. There is no information about the number of items within the menu or their height.

In the example I have used margin-top:-100px; but this is just for demonstration as the number of pixels is not fixed.

Need a CSS only solution and should keep the position absolute. How would you solve this?

Body:
Use  position: relative;bottom: 56px; 56px is the height of parent ul

body {
    background-color: #ccc;
}
ul {
    list-style-type:none;
    width:200px;
}
.spacer {
    height:100px;
    width:auto;
}
ul,li {
    margin:0;
    padding:0;
}
a {
    color:#fff;
    width:200px;
    background-color:#e4003d;
}
ul li a {
    text-decoration: none;
    display: block;
    padding: 10px;
}

ul li ul {
    z-index: 8888;
    background-color: #fff;
    display: none;
    position: relative;
    bottom: 56px;
}

ul:hover li ul, ul:focus li ul {
    display:block;
}

ul li ul li {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}
ul li ul li a {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}

ul li ul li a:hover, ul li ul li a:focus {
    background-color: #e4003d;
    color: #fff !important;
}

ul li ul {
    margin-top: -100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="spacer"></div>
<ul class="page-switcher">
  <li>
    <a href="#">Sitamet</a>
    <ul>
      <li><a href="http://#">Lorem</a></li>
      <li><a href="http://#">Ipsum</a></li>
      <li><a href="http://#">Dolor</a></li>
    </ul>
  </li>
</ul>
<div class="spacer"></div>


问:
matplotlib split title on two lines with non ascii and LaTeX char
I need to split a figure title to two lines using matplotlib.pyplot with non ascii characters in it.

Here's what I've tried so far:

```<code>plt.title(u"Some very long string with non ascii chara éèàéüöëêâûô\n"
"and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")

plt.title(r"Some very long string with non ascii chara éèàéüöëêâûô\n"
"and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")
</code>```

Both statement versions returned me some errors.

答:
Ok, I finally figured out the only way it could work:

Thanks to Dimgold for its working solution as well but it works only when there is no LaTeX characters.

When you need LaTeX char, you must typeset the string with the 'r' tag before.

Then, newline character '\n' won't work anymore.

And you must import some extra from __future__.

Here is the valid solution for me:

```<code>#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
from __future__ import unicode_literals # It seems absolutely needed.

# some stuff to plot here

plt.title(r"""Some very long string with non ascii chara éèàéüöëêâûô
and the next line should be here, with maybe some LaTeX symbols like $\alpha$ or $\overrightarrow{vector}$ in addition éèàéüöëêâûô""")
</code>```

Body:
I need to split a figure title to two lines using matplotlib.pyplot with non ascii characters in it.

Here's what I've tried so far:

plt.title(u"Some very long string with non ascii chara éèàéüöëêâûô\n"
"and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")

plt.title(r"Some very long string with non ascii chara éèàéüöëêâûô\n"
"and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")

Both statement versions returned me some errors.

Body:
Ok, I finally figured out the only way it could work:

Thanks to Dimgold for its working solution as well but it works only when there is no LaTeX characters.

When you need LaTeX char, you must typeset the string with the 'r' tag before.

Then, newline character '\n' won't work anymore.

And you must import some extra from __future__.

Here is the valid solution for me:

#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
from __future__ import unicode_literals # It seems absolutely needed.

# some stuff to plot here

plt.title(r"""Some very long string with non ascii chara éèàéüöëêâûô
and the next line should be here, with maybe some LaTeX symbols like $\alpha$ or $\overrightarrow{vector}$ in addition éèàéüöëêâûô""")


问:
Javascript open tag not working?
https://pastebin.com/M21NAE2P

```<code> <script>
  // get input element
    let filterInput = getElementById('filterInput');
    // add event listenter
    filterInput.addEventLister('keyup', filterNames);

    function filterNames(){
      console.log(1);
    }
  </script>
</code>```

The  tag isn't being colored by the IDE and its not working when i run it either. Is it atom? or is it something that i can fix.

答:
You have closed the <input> tag in your markup. In HTML, the <input> tag has no end tag. You also cannot nest
's (which I noticed you have done)

Also, change:

```<code>let filterInput = getElementById('filterInput');
</code>```

to

```<code>let filterInput = document.getElementById('filterinput');
</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.css">
  <title>My Contacts</title>

      My contacts

    <input type="text" id="filterinput" placeholder="Search Names">

A

        Abe
        Adam
        Alan
        Anna

B

          Beth
          Beth
          Bill
          Bob

C

            Carry
            Cortany
            Crapy
            Cheese

```

Title: Javascript open tag not working?

Body:
https://pastebin.com/M21NAE2P

The  tag isn't being colored by the IDE and its not working when i run it either. Is it atom? or is it something that i can fix.

Body:
You have closed the <input> tag in your markup. In HTML, the <input> tag has no end tag. You also cannot nest <li>'s (which I noticed you have done)

Also, change:

let filterInput = getElementById('filterInput');

to

let filterInput = document.getElementById('filterinput');

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.css">
  <title>My Contacts</title>
</head>

<body>
  <div class="container">
    <h1 class="center-align">
      My contacts
    </h1>
    <input type="text" id="filterinput" placeholder="Search Names">
    <ul id="names" class="collection with-header">
      <li class="collection-header">
        <h5>A</h5>
      </li>
      <li class="collection-item">
        <a href="#">Abe</a>
        <a href="#">Adam</a>
        <a href="#">Alan</a>
        <a href="#">Anna</a>
        <li class="collection-header">
          <h5>B</h5>
        </li>
        <li class="collection-item">
          <a href="#">Beth</a>
          <a href="#">Beth</a>
          <a href="#">Bill</a>
          <a href="#">Bob</a>
          <li class="collection-header">
            <h5>C</h5>
          </li>
          <li class="collection-item">
            <a href="#">Carry</a>
            <a href="#">Cortany</a>
            <a href="#">Crapy</a>
            <a href="#">Cheese</a>
          </li>
    </ul>
  </div>

  <script>
    // get input element
    let filterInput = document.getElementById('filterinput');
    // add event listenter
    filterInput.addEventLister('keyup', filterNames);

    function filterNames() {
      console.log(1);
    }
  </script>
</body>

</html>


问:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
I have created my tables in my SQLiteOpenHelper onCreate() but receive

```<code>SQLiteException: no such table
</code>```

or

```<code>SQLiteException: no such column
</code>```

errors. Why?

NOTE:

(This is the amalgamated summary of tens of similar questions every week. Attempting to provide a "canonical" community wiki question/answer here so that all those questions can be directed to a good reference.)

答:
You can create database & table like

```<code>public class DbHelper extends SQLiteOpenHelper {
private static final String DBNAME = "testdatbase.db";
private static final int VERSION = 1;

public DbHelper(Context context) {
    super(context, DBNAME, null, VERSION);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("create table BookDb(id integer primary key autoincrement,BookName text,Author text,IssuedOn text,DueDate text,Fine text,Totalfine text");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS BookDb");
    onCreate(db);
  }
}
</code>```

Note : if you want create another table or add columns or no such table, just increment the VERSION

ContentLicense: CC BY-SA 4.0

Body:
I have created my tables in my SQLiteOpenHelper onCreate() but receive

SQLiteException: no such table

or

SQLiteException: no such column

errors. Why?

NOTE:

(This is the amalgamated summary of tens of similar questions every week. Attempting to provide a "canonical" community wiki question/answer here so that all those questions can be directed to a good reference.)

Body:
You can create database & table like

public class DbHelper extends SQLiteOpenHelper {
private static final String DBNAME = "testdatbase.db";
private static final int VERSION = 1;

public DbHelper(Context context) {
    super(context, DBNAME, null, VERSION);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("create table BookDb(id integer primary key autoincrement,BookName text,Author text,IssuedOn text,DueDate text,Fine text,Totalfine text");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS BookDb");
    onCreate(db);
  }
}

Note : if you want create another table or add columns or no such table, just increment the VERSION


问:
Exactly n encoding in Z3
I'm trying to encode 'EXACTLY N' in the UOD (here List) in Z3.
The way I used to achieve in CBMC (C Bounded model checker) is that I define List to be _Bool and use an unsigned int and just state B1 == N.

```<code>// L is the length of the List b1.
unsigned int B1 = 0
for i in range(L):
      B1 = b[i] + B1
....
__CPROVER_assume (B1 == N);
</code>```

It is not straight forward in Z3 as the variables are the expressions, not the type values themselves. So my initial attempt was to encode 'At least N' And 'At most N' and do conjunction of them to get 'ExACTLY N'. Improving over the initial idea and using my logic class I replaced 'At most N' by (Not) 'At least N+1'. But for N >= 5 with L =~ 600. The code running out of memory on my 4 Gb RAM machine.

```<code># b1 is the List
X_list = []
for i in range(L-3):
  for j in range(i+1,L-2):
    l = And ( b1[j], b1[i])
    for k in range(j+1,L-1):
        l1 = And ( l, b1[k])
        for l in range(k+1,L):
            X_list.append( And (b1[l], l1))
B1 = Or(X_list)
</code>```

File "file1.py", line 49, in <module>
     X_list.append( And (b1[l], l1))
    File "/usr/lib/python2.7/dist-packages/z3/z3.py", line 1611, in And
      return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
    File "/usr/lib/python2.7/dist-packages/z3/z3core.py", line 1653, in
    Z3_mk_and
    raise Z3Exception(lib().Z3_get_error_msg(a0, err))
    z3.z3types.Z3Exception: out of memory

Is there any better way to encode this in Z3. Maybe seasoned Z3 users have some great way to encode it. Thanks.

答:
It seems you want pseudo-boolean functions? At-most/at-least/exactly N things are true? And possibly with coefficients?

If so, Z3 has direct support for this functionality, both via SMT-Lib and also from various APIs. For Python see here: https://github.com/Z3Prover/z3/blob/b27a4a3593fd15c003d3e30da20b35ac96b7218e/src/api/python/z3/z3.py#L7718-L7793

For SMTLib see the discussion here: K-out-of-N constraint in Z3Py

Title: Exactly n encoding in Z3

Body:
I'm trying to encode 'EXACTLY N' in the UOD (here List) in Z3.
The way I used to achieve in CBMC (C Bounded model checker) is that I define List to be _Bool and use an unsigned int and just state B1 == N.

// L is the length of the List b1.
unsigned int B1 = 0
for i in range(L):
      B1 = b[i] + B1
....
__CPROVER_assume (B1 == N);

It is not straight forward in Z3 as the variables are the expressions, not the type values themselves. So my initial attempt was to encode 'At least N' And 'At most N' and do conjunction of them to get 'ExACTLY N'. Improving over the initial idea and using my logic class I replaced 'At most N' by (Not) 'At least N+1'. But for N >= 5 with L =~ 600. The code running out of memory on my 4 Gb RAM machine.

# b1 is the List
X_list = []
for i in range(L-3):
  for j in range(i+1,L-2):
    l = And ( b1[j], b1[i])
    for k in range(j+1,L-1):
        l1 = And ( l, b1[k])
        for l in range(k+1,L):
            X_list.append( And (b1[l], l1))
B1 = Or(X_list)

File "file1.py", line 49, in <module>
     X_list.append( And (b1[l], l1))
    File "/usr/lib/python2.7/dist-packages/z3/z3.py", line 1611, in And
      return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
    File "/usr/lib/python2.7/dist-packages/z3/z3core.py", line 1653, in
    Z3_mk_and
    raise Z3Exception(lib().Z3_get_error_msg(a0, err))
    z3.z3types.Z3Exception: out of memory

Is there any better way to encode this in Z3. Maybe seasoned Z3 users have some great way to encode it. Thanks.


问:
Should calculations be done within the insert method or the getter method within Ruby Class?
I am going through an Interview Cake question and they have the calculations done upon insertion of a new value. My instinct was to put that logic in the getter method and I was hoping for some insight on best practices.

Their Solution:

```<code># Write a class TempTracker with these methods:
#
# insert()—records a new temperature
# getMax()—returns the highest temp we've seen so far
# getMin()—returns the lowest temp we've seen so far
# getMean()—returns the mean of all temps we've seen so far
# getMode()—returns a mode of all temps we've seen so far

class TempTracker
  def initialize
    # for mode
    @occurrences = [0] * 111 # array of 0s at indices 0..110
    @max_occurrences = 0
    @mode = nil

    # for mean
    @total_numbers = 0
    @total_sum = 0.0 # mean should be float
    @mean = nil

    # for min and max
    @min_temp = nil
    @max_temp = nil
  end

  def insert(temperature)
    # for mode
    @occurrences[temperature] += 1
    if @occurrences[temperature] > @max_occurrences
      @mode = temperature
      @max_occurrences = @occurrences[temperature]
    end

    # for mean
    @total_numbers += 1
    @total_sum += temperature
    @mean = @total_sum / @total_numbers

    # for min and max
    @max_temp = temperature if @max_temp.nil? || temperature > @max_temp
    @min_temp = temperature if @min_temp.nil? || temperature < @min_temp
  end

  def get_max
    @max_temp
  end

  def get_min
    @min_temp
  end

  def get_mean
    @mean
  end

  def get_mode
    @mode
  end
end
</code>```

Insert and getter methods that I wrote initially:

```<code>// ...

  def insert(temp)
    @max = temp if @max.nil? || @max < temp
    @min = temp if @min.nil? || @min > temp

    @total_sum += temp
    @total_numbers += 1

    @occurrences[temp] += 1
  end

// ...

  def get_mean
    @total_sum / @total_numbers
  end

  def get_mode
    @occurrences.each_with_index.max[1]
  end
end
</code>```

Any help understanding if/ why having the calculation logic in the insert method would be hugely helpful!

答:
Insert is a state-changing operation. It makes sense to reflect all the changes right there on the spot. Get, on the other hand, does not change state, it simply reads it.

Imagine that you do one insert and a hundred reads. It is not very efficient to repeat calculations on each get, as the result can't possibly change since the last time. Waste of resources, but can make for somewhat cleaner code.

I just noticed that I assumed a read-heavy workload. In a write-heavy workload, where you write more than you read, it's the other way around. Efficiency dictates that you put calculations in the getter. There's no one true answer, it's always a tradeoff, is what I'm trying to say.

Body:
I am going through an Interview Cake question and they have the calculations done upon insertion of a new value. My instinct was to put that logic in the getter method and I was hoping for some insight on best practices.

Their Solution:

# Write a class TempTracker with these methods:
#
# insert()—records a new temperature
# getMax()—returns the highest temp we've seen so far
# getMin()—returns the lowest temp we've seen so far
# getMean()—returns the mean of all temps we've seen so far
# getMode()—returns a mode of all temps we've seen so far

class TempTracker
  def initialize
    # for mode
    @occurrences = [0] * 111 # array of 0s at indices 0..110
    @max_occurrences = 0
    @mode = nil

    # for mean
    @total_numbers = 0
    @total_sum = 0.0 # mean should be float
    @mean = nil

    # for min and max
    @min_temp = nil
    @max_temp = nil
  end

  def insert(temperature)
    # for mode
    @occurrences[temperature] += 1
    if @occurrences[temperature] > @max_occurrences
      @mode = temperature
      @max_occurrences = @occurrences[temperature]
    end

    # for mean
    @total_numbers += 1
    @total_sum += temperature
    @mean = @total_sum / @total_numbers

    # for min and max
    @max_temp = temperature if @max_temp.nil? || temperature > @max_temp
    @min_temp = temperature if @min_temp.nil? || temperature < @min_temp
  end

  def get_max
    @max_temp
  end

  def get_min
    @min_temp
  end

  def get_mean
    @mean
  end

  def get_mode
    @mode
  end
end

Insert and getter methods that I wrote initially:

// ...

  def insert(temp)
    @max = temp if @max.nil? || @max < temp
    @min = temp if @min.nil? || @min > temp

    @total_sum += temp
    @total_numbers += 1

    @occurrences[temp] += 1
  end

// ...

  def get_mean
    @total_sum / @total_numbers
  end

  def get_mode
    @occurrences.each_with_index.max[1]
  end
end

Any help understanding if/ why having the calculation logic in the insert method would be hugely helpful!


问:
All preprocessing worsens accuracy
I am performing a grid search cross validation with a logistic regression model. I have my default model first, then one that should preprocess the data. The data are random text documents that fall into one of 4 categories. My preprocessor seems to worsen my accuracy and f1 score even when I just have it return the data, as below. The regularization parameter C the gridsearch picks after passing this preprocessing which shouldn't be doing anything.

```<code>Cs = {'C' : [0.0001, 0.001, 0.01, 0.1, 0.5, 1.0, 2.0, 10.0]}
gs_clf_LR = GridSearchCV(LogisticRegression(penalty='l2'), Cs, refit=True)
gs_clf_LR.fit(transformed_train_data, train_labels)
preds = gs_clf_LR.predict(transformed_dev_data)
#print gs_clf_LR.score(transformed_dev_data, dev_labels)
print gs_clf_LR.best_params_
print 'With optimal C, accuracy score is: ', gs_clf_LR.best_score_
print 'f1 score: ', metrics.f1_score(dev_labels, preds, average='weighted')
print metrics.classification_report(dev_labels, preds)
print

def better_preprocessor(string):
    #return re.sub(r'^[A-Z]', '^[a-z]', string)
    #return re.sub(r'(ing)$', '', string)
    #return re.sub(r'(es)$', '', string)
    #return re.sub(r's$', '', string)
    #return re.sub(r'(ed)$', '', string)
    return string

vec = CountVectorizer(preprocessor=better_preprocessor)
transformed_preprocessed_train_data = vec.fit_transform(train_data)
transformed_preprocessed_dev_data = vec.transform(dev_data)

gs_clf_LR.fit(transformed_preprocessed_train_data, train_labels)
preds_pp = gs_clf_LR.predict(transformed_preprocessed_dev_data)
#print gs_clf_LR.score(transformed_preprocessed_dev_data, dev_labels)
print gs_clf_LR.best_params_
print 'With optimal C, accuracy score is: ', gs_clf_LR.best_score_
print 'f1 score: ', metrics.f1_score(dev_labels, preds_pp, average='weighted')
print metrics.classification_report(dev_labels, preds_pp)
</code>```

With some real preprocessing, such as the regex lines I have commented out, I also see a decrease in my accuracy and f1-score (plausible but I am getting rid of plurals and have been told this should improve my scores).

答: Have you separated a randomly generated test set from you data, that exists outside of the cross validation, to test both models on? Accuracy decrease could be a result of greater generalization by reducing overfitting to the data.</p>

Title: All preprocessing worsens accuracy

Body:
I am performing a grid search cross validation with a logistic regression model. I have my default model first, then one that should preprocess the data. The data are random text documents that fall into one of 4 categories. My preprocessor seems to worsen my accuracy and f1 score even when I just have it return the data, as below. The regularization parameter C the gridsearch picks after passing this preprocessing which shouldn't be doing anything.

Cs = {'C' : [0.0001, 0.001, 0.01, 0.1, 0.5, 1.0, 2.0, 10.0]}
gs_clf_LR = GridSearchCV(LogisticRegression(penalty='l2'), Cs, refit=True)
gs_clf_LR.fit(transformed_train_data, train_labels)
preds = gs_clf_LR.predict(transformed_dev_data)
#print gs_clf_LR.score(transformed_dev_data, dev_labels)
print gs_clf_LR.best_params_
print 'With optimal C, accuracy score is: ', gs_clf_LR.best_score_
print 'f1 score: ', metrics.f1_score(dev_labels, preds, average='weighted')
print metrics.classification_report(dev_labels, preds)
print

def better_preprocessor(string):
    #return re.sub(r'^[A-Z]', '^[a-z]', string)
    #return re.sub(r'(ing)$', '', string)
    #return re.sub(r'(es)$', '', string)
    #return re.sub(r's$', '', string)
    #return re.sub(r'(ed)$', '', string)
    return string

vec = CountVectorizer(preprocessor=better_preprocessor)
transformed_preprocessed_train_data = vec.fit_transform(train_data)
transformed_preprocessed_dev_data = vec.transform(dev_data)

gs_clf_LR.fit(transformed_preprocessed_train_data, train_labels)
preds_pp = gs_clf_LR.predict(transformed_preprocessed_dev_data)
#print gs_clf_LR.score(transformed_preprocessed_dev_data, dev_labels)
print gs_clf_LR.best_params_
print 'With optimal C, accuracy score is: ', gs_clf_LR.best_score_
print 'f1 score: ', metrics.f1_score(dev_labels, preds_pp, average='weighted')
print metrics.classification_report(dev_labels, preds_pp)

With some real preprocessing, such as the regex lines I have commented out, I also see a decrease in my accuracy and f1-score (plausible but I am getting rid of plurals and have been told this should improve my scores).


问:
Using Unity to create a singleton that is used in my Class
I have a class that needs an instance of a HttpClient class, which I want to be instantiated only once i.e. Singleton

```<code>public interface IMyClass {}
public class MyClass : IMyClass {
    private HttpClient client;
    public MyClass(HttpClient client)
    {
        this.client = client;
    }
}

IUnityContainer container = new UnityContainer();
container.RegisterType<IMyClass, MyClass>();

var httpClient = new HttpClient();
</code>```

How can I register the httpClient instance as a singleton to my MyClass can use it?

答:
Have you tried this?

```<code>container.RegisterType<IMyClass, MyClass>(new ContainerControlledLifetimeManager());
</code>```

https://msdn.microsoft.com/en-us/library/ff647854.aspx

Since there will be only one instance of your class, there will also one only one instance of HTTP client inside it.

Update:

In order to resolve HttpClient dependency itself, use

```<code>container.RegisterType<HttpClient, HttpClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor());
</code>```

That way any class that needs HttpClient will receive the same instance of it. I'm not sure about the order of parameters, but basically you have to tell Unity 2 things - to register HttpClient as a singleton and to use its default constructor.

Body:
I have a class that needs an instance of a HttpClient class, which I want to be instantiated only once i.e. Singleton

public interface IMyClass {}
public class MyClass : IMyClass {
    private HttpClient client;
    public MyClass(HttpClient client)
    {
        this.client = client;
    }
}

IUnityContainer container = new UnityContainer();
container.RegisterType<IMyClass, MyClass>();

var httpClient = new HttpClient();

How can I register the httpClient instance as a singleton to my MyClass can use it?

Body:
Have you tried this?

container.RegisterType<IMyClass, MyClass>(new ContainerControlledLifetimeManager());

https://msdn.microsoft.com/en-us/library/ff647854.aspx

Since there will be only one instance of your class, there will also one only one instance of HTTP client inside it.

Update:

In order to resolve HttpClient dependency itself, use

container.RegisterType<HttpClient, HttpClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor());

That way any class that needs HttpClient will receive the same instance of it. I'm not sure about the order of parameters, but basically you have to tell Unity 2 things - to register HttpClient as a singleton and to use its default constructor.


问:
When should this-> be used?
I was wondering if this-> should be used both:

```<code>void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}
</code>```

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks

答:
this is just a pointer to the object itself. It is made for readability, so that you know you're referencing to the object functions or variables, not something within the function.

I don't think there's any other good reason for it other than readability :-)

It's also good if you want to avoid ambiguous reference. Assume you have a global variable and a variable within the function that has the same name, then this-> would reference to the global variable.

ContentLicense: CC BY-SA 2.5

Title: When should this-> be used?

Body:
I was wondering if this-> should be used both:

void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks


问:
Unexpected error while executing
I searched for this question already but there were no answers that worked for me. Every time I debug my app it gives me this error.

```<code>Unexpected error while executing: am start -n "com.example.maomei.passusersystem/com.example.maomei.passusersystem.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Error while Launching activity
</code>```

Here is my MainActivity code:

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

    TextView textView1;
    Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView1 = (TextView) findViewById(R.id.textView1);
        Button button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button1:

                        Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
                        MainActivity.this.startActivity(myIntent);

                    }

            }

        });
    }
}
</code>```

and my Manifest code:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.maomei.passusersystem">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.example.maomei.passusersystem.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Main2Activity"
            android:label="@string/title_activity_main2"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Main4Activity"
            android:label="@string/title_activity_main4"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Main5Activity"
            android:label="@string/title_activity_main5"
            android:theme="@style/AppTheme.NoActionBar">

        </activity>
    </application>
</manifest>
</code>```

答:
Can you try this without passing the -a -c argument
adb shell am start -n com.package.name/com.package.name.ActivityName</p>

Title: Unexpected error while executing

Body:
I searched for this question already but there were no answers that worked for me. Every time I debug my app it gives me this error.

Unexpected error while executing: am start -n "com.example.maomei.passusersystem/com.example.maomei.passusersystem.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Error while Launching activity

Here is my MainActivity code:

public class MainActivity extends AppCompatActivity {

    TextView textView1;
    Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView1 = (TextView) findViewById(R.id.textView1);
        Button button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button1:

                        Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
                        MainActivity.this.startActivity(myIntent);

                    }

            }

        });
    }
}

and my Manifest code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.maomei.passusersystem">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.example.maomei.passusersystem.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Main2Activity"
            android:label="@string/title_activity_main2"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Main4Activity"
            android:label="@string/title_activity_main4"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Main5Activity"
            android:label="@string/title_activity_main5"
            android:theme="@style/AppTheme.NoActionBar">

        </activity>
    </application>
</manifest>


问:
How to create a modal popup using JavaScript?
How to create a modal popup window with background with gray color using JavaScript and CSS?

Can anyone show me an example?

答: Have a look to getbootstrap.com -> modal</p>


问:
How to have a button have a ripple as well as a custom shape
When I try to have the two of them together but they will either override each other or the background becomes transparent.

Button shape:

```<code><stroke
    android:width="1dp"
    android:color="#048403"/>
<corners
    android:radius="2dp" />

<padding
    android:left="5dp"
    android:right="5dp"
    android:top="3dp"
    android:bottom="3dp" />
<solid
    android:color="@color/safeGreen" />
</code>```

Button ripple:

```<code><ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/darkGreen">
    <item android:drawable="@color/safeGreen"/>
</ripple>
</code>```

答:
Shortly after posting this I found this solution that works in case anyone is interested. You create a new resource as below:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:attr/colorControlHighlight">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@color/darkGreen" />
            <corners android:radius="2dp" />
        </shape>
    </item>
    <item android:drawable="@drawable/button_shape" />
</ripple>
</code>```

Body:
When I try to have the two of them together but they will either override each other or the background becomes transparent.

Button shape:

<stroke
    android:width="1dp"
    android:color="#048403"/>
<corners
    android:radius="2dp" />

<padding
    android:left="5dp"
    android:right="5dp"
    android:top="3dp"
    android:bottom="3dp" />
<solid
    android:color="@color/safeGreen" />

Button ripple:

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/darkGreen">
    <item android:drawable="@color/safeGreen"/>
</ripple>

Body:
Shortly after posting this I found this solution that works in case anyone is interested. You create a new resource as below:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:attr/colorControlHighlight">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@color/darkGreen" />
            <corners android:radius="2dp" />
        </shape>
    </item>
    <item android:drawable="@drawable/button_shape" />
</ripple>


问:
I have been working on wordpress and stuck in an issue difficult to manage
Their is an issue in this wordpress url :

https://example.com/usa-drug-alcohol-testing-locations/ohio-oh/delaware-alcohol-drug-testing-screening-services-4/

https://example.com/usa-drug-alcohol-testing-locations/ohio-oh/delaware-alcohol-drug-testing-screening-services-2/

I want to hide -4 or -2 or -3 from title slug through .htaccess.

What should I do to get rid of this issue from following URLs?

答:
When more than one post or a page have the same slug, the WordPress inserts those unique identifiers.

So solution is to find those posts / pages and edit their permalinks to something unique.


问:
How does wsDualHttpBinding work?
Can anybody tell me how does wsDualHttpBinding work and what exactly is the difference between sockets and wsDualHttpBinding?

I think Microsoft did a great job. I never thought a web service would be able to call its client back again whenever it wishes. How is all this possible? I never saw any other language supporting this type of webservice, not in Java and not in PHP.

答: There is a nice article on idunno.org showing an example of how to use wsDualHttpBinding. It is showing you how to subscribe clients, push updates, etc.</p>

Title: How does wsDualHttpBinding work?


问:
What is the best way to get the first letter from a string in Java, returned as a string of length 1?
Assume the following:

String example      = "something";
String firstLetter  = "";
```

<p>Are there differences to be aware of with the following ways of assigning <code>firstLetter</code> that could impact performance; <strong>which would be best, and why?</strong></p>

<pre class="lang-java prettyprint-override"><code>firstLetter = String.valueOf(example.charAt(0));
firstLetter = Character.toString(example.charAt(0));
firstLetter = example.substring(0, 1);
</code>```

The reason the first letter is being returned as a String is that this is being run in Hadoop, and a string is required to assign to a Text type, firstLetter will be output as a key from a map() method, for example:

public class FirstLetterMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
    String line = new String();
    Text firstLetter = new Text();
    IntWritable wordLength = new IntWritable();

    @Override
    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {

        line = value.toString();

        for (String word : line.split("\\W+")){
            if (word.length() > 0) {

                // ---------------------------------------------
                // firstLetter assignment
                firstLetter.set(String.valueOf(word.charAt(0)).toLowerCase());
                // ---------------------------------------------

                wordLength.set(word.length());
                context.write(firstLetter, wordLength);
            }
        }
  }
}
```

答:
```<code>String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);
</code>```

Body:
Assume the following:

String example      = "something";
String firstLetter  = "";

Are there differences to be aware of with the following ways of assigning firstLetter that could impact performance; which would be best, and why?

firstLetter = String.valueOf(example.charAt(0));
firstLetter = Character.toString(example.charAt(0));
firstLetter = example.substring(0, 1);

The reason the first letter is being returned as a String is that this is being run in Hadoop, and a string is required to assign to a Text type, firstLetter will be output as a key from a map() method, for example:

public class FirstLetterMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
    String line = new String();
    Text firstLetter = new Text();
    IntWritable wordLength = new IntWritable();

    @Override
    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {

        line = value.toString();

        for (String word : line.split("\\W+")){
            if (word.length() > 0) {

                // ---------------------------------------------
                // firstLetter assignment
                firstLetter.set(String.valueOf(word.charAt(0)).toLowerCase());
                // ---------------------------------------------

                wordLength.set(word.length());
                context.write(firstLetter, wordLength);
            }
        }
  }
}


问:
Linking Tensorboard Embedding Metadata to checkpoint
I'm using the tflearn wrapper over tensorflow to build a model, and would like to add metadata (labels) to the resultant embedding visualization. Is there a way to link a metadata.tsv file to a saved checkpoint after the fact of running it?

I've created a projector_config.pbtxt file in the logdir of the checkpoint summaries, with the metadata.tsv being in the same folder. The config looks like this:

```<code>embeddings {
  tensor_name: "Embedding/W"
  metadata_path: "C:/tmp/tflearn_logs/shallow_lstm/"
}
</code>```

and was created using the code from the docs - https://www.tensorflow.org/how_tos/embedding_viz/

I've commented out the tf.Session part in the hopes of creating the metadata link without the need of doing so directly within a Session object, but I'm not sure if that's possible.

```<code>from tensorflow.contrib.tensorboard.plugins import projector
#with tf.Session() as sess:
config = projector.ProjectorConfig()
# One can add multiple embeddings.
embedding = config.embeddings.add()
embedding.tensor_name = 'Embedding/W'
# Link this tensor to its metadata file (e.g. labels).
embedding.metadata_path = 'C:/tmp/tflearn_logs/shallow_lstm/'
# Saves a config file that TensorBoard will read during startup.
projector.visualize_embeddings(tf.summary.FileWriter('/tmp/tflearn_logs/shallow_lstm/'), config)
</code>```

Below is a snap of the current embedding visualization. Note the empty metadata. Is there a way to directly attach the desired metafile to this embedding?

答:
I had the same problem and it is soloved now :)

Essentially, all you need to do is following 3 steps:

save model checkpoint, supposing ckeckpoint's directory is ckp_dir;

place projector_config.pbtxt and metadata.tsv in ckp_dir;

run tensorboard --logdir=ckp_dir and click the Embedding Tab

the content of projector_config.pbtxt is :

```<code>    embeddings {
      tensor_name: "embedding_name"
      metadata_path: "metatdata.tsv"
    }
</code>```

This is the key to link the embedding to metadata.tsv. In tf.Session(), we often get the embedding's value like sess.run('embedding_name:0'). But in projector_config.pbtxt, we just type tensor_name: "embedding_name".

Generally, we can specify the checkpoint path and metadata_path in projector_config.pbtxt so that we can place checkpoint, projector_config.pbtxt and metadata.tsv in different directories. But i think it is too complicated. I just solved it as above.

the result shown here

Body:
I'm using the tflearn wrapper over tensorflow to build a model, and would like to add metadata (labels) to the resultant embedding visualization. Is there a way to link a metadata.tsv file to a saved checkpoint after the fact of running it?

I've created a projector_config.pbtxt file in the logdir of the checkpoint summaries, with the metadata.tsv being in the same folder. The config looks like this:

embeddings {
  tensor_name: "Embedding/W"
  metadata_path: "C:/tmp/tflearn_logs/shallow_lstm/"
}

and was created using the code from the docs - https://www.tensorflow.org/how_tos/embedding_viz/

I've commented out the tf.Session part in the hopes of creating the metadata link without the need of doing so directly within a Session object, but I'm not sure if that's possible.

from tensorflow.contrib.tensorboard.plugins import projector
#with tf.Session() as sess:
config = projector.ProjectorConfig()
# One can add multiple embeddings.
embedding = config.embeddings.add()
embedding.tensor_name = 'Embedding/W'
# Link this tensor to its metadata file (e.g. labels).
embedding.metadata_path = 'C:/tmp/tflearn_logs/shallow_lstm/'
# Saves a config file that TensorBoard will read during startup.
projector.visualize_embeddings(tf.summary.FileWriter('/tmp/tflearn_logs/shallow_lstm/'), config)

Below is a snap of the current embedding visualization. Note the empty metadata. Is there a way to directly attach the desired metafile to this embedding?

Body:
I had the same problem and it is soloved now :)

Essentially, all you need to do is following 3 steps:

save model checkpoint, supposing ckeckpoint's directory is ckp_dir;

place projector_config.pbtxt and metadata.tsv in ckp_dir;

run tensorboard --logdir=ckp_dir and click the Embedding Tab

the content of projector_config.pbtxt is :

    embeddings {
      tensor_name: "embedding_name"
      metadata_path: "metatdata.tsv"
    }

This is the key to link the embedding to metadata.tsv. In tf.Session(), we often get the embedding's value like sess.run('embedding_name:0'). But in projector_config.pbtxt, we just type tensor_name: "embedding_name".

Generally, we can specify the checkpoint path and metadata_path in projector_config.pbtxt so that we can place checkpoint, projector_config.pbtxt and metadata.tsv in different directories. But i think it is too complicated. I just solved it as above.

the result shown here


问:
kernel panic on proxmox 4.4
I have recently upgraded my proxmox host from 3.3 to 4.4 and now the OS is not booting and it gives me a kernel panic error. I use a dedicated server from host.ag

How do I solve it?

答:
Reboot your server and hit e key while your server tries to boot and displays the grub menu. This permits you to edit the booting menu (grub) and you can select the other old kernel and boot your server. Then you can investigate and see what went wrong. You could also try a apt-get dist-upgrade and see if there were any packages kept back and not installed correctly. If running apt-get dist-upgrade results in any new packages installed then try rebooting your server again and see if this time boots.

Promox kernel 4.x works just fine on my server:

```<code>root@pve1:~# uname -a
Linux pve1 4.4.35-2-pve #1 SMP Fri Jan 20 13:58:17 CET 2017 x86_64 GNU/Linux
</code>```

Title: kernel panic on proxmox 4.4

Body:
Reboot your server and hit e key while your server tries to boot and displays the grub menu. This permits you to edit the booting menu (grub) and you can select the other old kernel and boot your server. Then you can investigate and see what went wrong. You could also try a apt-get dist-upgrade and see if there were any packages kept back and not installed correctly. If running apt-get dist-upgrade results in any new packages installed then try rebooting your server again and see if this time boots.

Promox kernel 4.x works just fine on my server:

root@pve1:~# uname -a
Linux pve1 4.4.35-2-pve #1 SMP Fri Jan 20 13:58:17 CET 2017 x86_64 GNU/Linux


问:
i want to select multiple images from phone write now i am using intent
I want to select multiple images from phone but I am only getting 1 image, now I am using an intent

```<code>Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
</code>```

but still it only selects one image at time .so how can I set a limit on image selection more than 1 and how I can handle it in onActivityResult.

答:
Try below code:</p>

```<code>      Intent intent = new Intent();
      intent.setType("image/*");
      intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
      intent.setAction(Intent.ACTION_GET_CONTENT);
      startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
</code>```

<p>//Override onActivityResult method </p>

```<code>                 @Override
                  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                   if(requestCode ==1)
                  if (data != null) {
                    ClipData clipData = null;
                    try {
                         clipData = data.getClipData();
                        } catch (Exception exception) {
                           e.printStackTrace();
                         }
                      if (clipData != null) {
                        for (int i = 0; i < clipData.getItemCount();i++) {
                             // Get Uri for the image
                         Uri selectedImage = data.getClipData().getItemAt(i).getUri();
                      try {
                      String imagePath = getRealPathFromURI(selectedImage, this); /* Do whatever you want to do with imagePath */
                          }
                         catch (Exception e) {
                                e.printStackTrace();
                           }
                         }
                     }
                   }
                }
              }

    private String getRealPathFromURI(Uri contentURI, Context context) {
    String filePath = "";

    Pattern p = Pattern.compile("(\\d+)$");
    Matcher m = p.matcher(contentURI.toString());
    if (!m.find()) {
        Log.e("", "ID for requested image not found: " +       contentURI.toString());
        return filePath;
    }
    String imgId = m.group();

    String[] column = { MediaStore.Images.Media.DATA };
    String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{imgId}, null);

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        }
        cursor.close();

    return filePath;

}
</code>```

Body:
I want to select multiple images from phone but I am only getting 1 image, now I am using an intent

Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);

but still it only selects one image at time .so how can I set a limit on image selection more than 1 and how I can handle it in onActivityResult.

Body:
Try below code:

      Intent intent = new Intent();
      intent.setType("image/*");
      intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
      intent.setAction(Intent.ACTION_GET_CONTENT);
      startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);

//Override onActivityResult method

                 @Override
                  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                   if(requestCode ==1)
                  if (data != null) {
                    ClipData clipData = null;
                    try {
                         clipData = data.getClipData();
                        } catch (Exception exception) {
                           e.printStackTrace();
                         }
                      if (clipData != null) {
                        for (int i = 0; i < clipData.getItemCount();i++) {
                             // Get Uri for the image
                         Uri selectedImage = data.getClipData().getItemAt(i).getUri();
                      try {
                      String imagePath = getRealPathFromURI(selectedImage, this); /* Do whatever you want to do with imagePath */
                          }
                         catch (Exception e) {
                                e.printStackTrace();
                           }
                         }
                     }
                   }
                }
              }

    private String getRealPathFromURI(Uri contentURI, Context context) {
    String filePath = "";

    Pattern p = Pattern.compile("(\\d+)$");
    Matcher m = p.matcher(contentURI.toString());
    if (!m.find()) {
        Log.e("", "ID for requested image not found: " +       contentURI.toString());
        return filePath;
    }
    String imgId = m.group();

    String[] column = { MediaStore.Images.Media.DATA };
    String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{imgId}, null);

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        }
        cursor.close();

    return filePath;

}


问:
Web crawlers overloading site
We have a problem with a number of our sites where Yahoo, Google, Yandex, Bing Ahrefs and others all index the site at the same time which kills the website.

I've configured fail2ban to block the source IPs, but these are forever changing so not ideal.  I have also tried using robots.txt but this makes little difference.

We have tried putting the site behind cloudflare, but again this makes little difference and all we can do is block the source IPs.

What else can I do?

Currently we're monitoring the site with Nagios, which restarts nginx when the site becomes un-responsive, but this seems far from ideal.

Ubuntu server running nginx

Robots.txt file is here:-

```<code>User-agent: *
Disallow: /
</code>```

Posting here in case there is anything that I can get our developers to try.

Thanks

答:
An easy approach is to rate limit them based on User-Agent header in their requests. Schematically this looks like the following.

At http level in Nginx configuration:

```<code>map $http_user_agent $bot_ua {
  default '';

  "~*Googlebot|Bing" Y;
}

limit_req_zone $bot_ua zone=bot:1m rate=1r/s;
</code>```

This will make sure that all requests with Googlebot or Bing in User-Agent will be rate limited to 1 request per second. Note that rate limiting will be "global" (vs. per-IP), i.e. all of the bots will wait in a single queue to access the web site. The configuration can be easily modified to rate limit on per-IP basis or to white list some user agents.

At server or location level:

```<code>limit_req zone=bot burst=5;
</code>```

Which means a "burst" of 5 requests is possible. You may drop this option if you want.

Nginx rate limit documentation

Nginx map documentation

Nginx will issue HTTP status code 429 when a request is rate limited. "Sane" web crawlers detect this and slow down scanning the site.

Though I should say this whole problem is much more complicated. There are a lot of malicious requests pretending they are from Google, Twitter, FB, etc. coming from various scanners and crawlers (e.g. see this question) and they respect neither robots.txt nor 429. Sometimes they are quite smart and have User-Agents mimicing browsers. In this case the approach above will not help you.

Title: Web crawlers overloading site

Body:
We have a problem with a number of our sites where Yahoo, Google, Yandex, Bing Ahrefs and others all index the site at the same time which kills the website.

I've configured fail2ban to block the source IPs, but these are forever changing so not ideal.  I have also tried using robots.txt but this makes little difference.

We have tried putting the site behind cloudflare, but again this makes little difference and all we can do is block the source IPs.

What else can I do?

Currently we're monitoring the site with Nagios, which restarts nginx when the site becomes un-responsive, but this seems far from ideal.

Ubuntu server running nginx

Robots.txt file is here:-

User-agent: *
Disallow: /

Posting here in case there is anything that I can get our developers to try.

Thanks

Body:
An easy approach is to rate limit them based on User-Agent header in their requests. Schematically this looks like the following.

At http level in Nginx configuration:

map $http_user_agent $bot_ua {
  default '';

  "~*Googlebot|Bing" Y;
}

limit_req_zone $bot_ua zone=bot:1m rate=1r/s;

This will make sure that all requests with Googlebot or Bing in User-Agent will be rate limited to 1 request per second. Note that rate limiting will be "global" (vs. per-IP), i.e. all of the bots will wait in a single queue to access the web site. The configuration can be easily modified to rate limit on per-IP basis or to white list some user agents.

At server or location level:

limit_req zone=bot burst=5;

Which means a "burst" of 5 requests is possible. You may drop this option if you want.

Nginx rate limit documentation

Nginx map documentation

Nginx will issue HTTP status code 429 when a request is rate limited. "Sane" web crawlers detect this and slow down scanning the site.

Though I should say this whole problem is much more complicated. There are a lot of malicious requests pretending they are from Google, Twitter, FB, etc. coming from various scanners and crawlers (e.g. see this question) and they respect neither robots.txt nor 429. Sometimes they are quite smart and have User-Agents mimicing browsers. In this case the approach above will not help you.


问:
Is Autofac ContainerBuilder.Build an expensive operation?
I'm starting to use Autofac and I can't seem to find an answer to this question.

Also, when should I call ContainerBuilder.Build() ?

After I call the ContainerBuilder.Build() is it possible to register another type or instance?

答:
ContainerBuilder.Build() should generally be called during application startup before you actually start invoking business behavior.

If you need to register additional components into an existing container you can.  To do this in Autofac v2.2 (or later), you can create another ContainerBuilder instancer and use the ContainerBuilder.Build(IContainer) overload method.


答:
try this

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><item>
    <shape android:shape="rectangle">
        <stroke
            android:width="1dp"
            android:color="#048403"/>
        <corners
            android:radius="2dp" />

        <padding
            android:left="5dp"
            android:right="5dp"
            android:top="3dp"
            android:bottom="3dp" />
        <solid
            android:color="#1b711b" />
    </shape>
</item>
</code>```

Title: How to have a button have a ripple as well as a custom shape

Body:
try this

<?xml version="1.0" encoding="utf-8"?>

<item>
    <shape android:shape="rectangle">
        <stroke
            android:width="1dp"
            android:color="#048403"/>
        <corners
            android:radius="2dp" />

        <padding
            android:left="5dp"
            android:right="5dp"
            android:top="3dp"
            android:bottom="3dp" />
        <solid
            android:color="#1b711b" />
    </shape>
</item>


问:
CSS - making div's background image look the same than the background image of HTML page
I have a HTML page with a background image.

```<code>body {
  background-color: #FFFFFF;
  background-image: url(bg_width900px_height675px.jpg);
  background-attachment: fixed;
  background-position: center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
</code>```

This works fine when the background image is a beautiful landscape. The left side is darker and the right side a little bit lighter.

I also have a div which is wider than my screen. I would like to use the same background image than the HTML page is using. In fact, background-attachment: fixed; should be used and the background image should look 100% same than the background of my HTML page. In other words, the size has to be same.

Please note that I'm not looking for debugging help. I just do not know if my vision is possible to achieve and create.

Update

Thanks to blizzyb, it seems to me that this is possible. Here is my best code so far:

```

答: I believe you can just add the inherit value on whatever property you need to be the same.

Body:
I have a HTML page with a background image.

body {
  background-color: #FFFFFF;
  background-image: url(bg_width900px_height675px.jpg);
  background-attachment: fixed;
  background-position: center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

This works fine when the background image is a beautiful landscape. The left side is darker and the right side a little bit lighter.

I also have a div which is wider than my screen. I would like to use the same background image than the HTML page is using. In fact, background-attachment: fixed; should be used and the background image should look 100% same than the background of my HTML page. In other words, the size has to be same.

Please note that I'm not looking for debugging help. I just do not know if my vision is possible to achieve and create.

Update

Thanks to blizzyb, it seems to me that this is possible. Here is my best code so far:


问:
Ruby On Rails, Making a Sortable List
Currently I'm working with a set of List Items that are created through Ruby. The list items are f.text_fields that allow the user to write what they want in them.

I'm having trouble making the list items sortable.
Have tried multiple methods but all seem mess up the functionality of the items.

This is what i currently have, any ideas or suggestions would be greatly appreciated.

```<code>    <div class = "row Answer sortable">
    <li>
      <div class="col-sm-10 sortable">
        <%= f.text_field :body, :class => "form-control" %>
      </div>
      <div class ="col-sm-1">
        <div class = "btn btn-default inline RemoveAnswer">×</div>
        <%= f.hidden_field :_destroy, :class => "destroy-answer" %>
      </div>
    </li>
</div>
</code>```

Thank You

答:
When you say sortable (sorry can't create comments yet)

do you mean in the form, like drag-and-drop sortable, or that they show up sorted?

EDITED!

Include this in your application.js html.sortable file

Then in your JS-file for your forms class you can create the functions:

Here is mine, let me know if you know coffee-script or if you need an explanation.

```<code>ready = undefined
set_positions = undefined

// create the
set_positions = ->
  $(".sortable-item").each (i) ->
    $(this).attr "data-pos", i + 1
    return

ready = ->
  set_positions()
  $(".sortable").sortable()
  $(".sortable").sortable().bind "sortupdate", (e, ui) ->
    updated_order = []
    set_positions()
    $(".sortable-item").each (i) ->
      updated_order.push
        id: $(this).data("id")
        position: i + 1
      return
    $.ajax
      type: "PUT"
      url: "/works/sort"
      data: order: updated_order
    return
  return

$(document).ready ready
</code>```

So very fast. You need to create the data on your sortable items (data-id="<%= item.id %>" if their in an each block) so the functions knows what to send to the action sort. And change the classes, so the functions match your form.

And in the route:

```<code>...
put :sort, on: :collection
</code>```

In the action sort when dragging an item you can now use the params[:order] values to update your items position.

Note!
You need to run a migration on your item table, so you can store the position for each item and then when you call the items remember to sort them.

Something like this will do (in the corresponding model):

```<code>def self.sort_by_position
  sort(position: :asc) # The new attr
end
</code>```

And remember only to call the script on your form-page. It's pretty heavy as you can see

I hope it can point you in the right direction!

Title: Ruby On Rails, Making a Sortable List

Body:
Currently I'm working with a set of List Items that are created through Ruby. The list items are f.text_fields that allow the user to write what they want in them.

I'm having trouble making the list items sortable.
Have tried multiple methods but all seem mess up the functionality of the items.

This is what i currently have, any ideas or suggestions would be greatly appreciated.

        <%= f.text_field :body, :class => "form-control" %>

×

        <%= f.hidden_field :_destroy, :class => "destroy-answer" %>

Thank You

Body:
When you say sortable (sorry can't create comments yet)

do you mean in the form, like drag-and-drop sortable, or that they show up sorted?

EDITED!

Include this in your application.js html.sortable file

Then in your JS-file for your forms class you can create the functions:

Here is mine, let me know if you know coffee-script or if you need an explanation.

ready = undefined
set_positions = undefined

// create the
set_positions = ->
  $(".sortable-item").each (i) ->
    $(this).attr "data-pos", i + 1
    return

ready = ->
  set_positions()
  $(".sortable").sortable()
  $(".sortable").sortable().bind "sortupdate", (e, ui) ->
    updated_order = []
    set_positions()
    $(".sortable-item").each (i) ->
      updated_order.push
        id: $(this).data("id")
        position: i + 1
      return
    $.ajax
      type: "PUT"
      url: "/works/sort"
      data: order: updated_order
    return
  return

$(document).ready ready

So very fast. You need to create the data on your sortable items (data-id="<%= item.id %>" if their in an each block) so the functions knows what to send to the action sort. And change the classes, so the functions match your form.

And in the route:

...
put :sort, on: :collection

In the action sort when dragging an item you can now use the params[:order] values to update your items position.

Note!
You need to run a migration on your item table, so you can store the position for each item and then when you call the items remember to sort them.

Something like this will do (in the corresponding model):

def self.sort_by_position
  sort(position: :asc) # The new attr
end

And remember only to call the script on your form-page. It's pretty heavy as you can see

I hope it can point you in the right direction!


问:
Firebase Security - How to allow to push to a node AND update subtree on that node?
I feel this is a pretty common question, but as I've been learning Firebase security, I still can't seem to hack this small issue where I have a tree node that I want to be able to push new data to, while simultaneously be able to update existing nodes. According to the Firebase documentation, if you put these rules in your top-level tree, you should be able to create/delete, but not update:

```<code>".write": "!data.exists() || !newData.exists()"
</code>```

So when I use the Firebase database simulator with authentication and everything, I go to simulate a "write" on a path /social/bands, however I get a Simulated write denied. I should note that in this path, data does exist.

My full rules for this example look like:

```<code>"social": {
   "bands": {
     ".read": "auth != null",
     ".write": "!data.exists() || !newData.exists() && auth != null",
     "$bandId": {
        ".write": "auth != null && data.child('admins').child(auth.uid).val() === true"
     }
   }
}
</code>```

Is there a way to be able to create/delete nodes on my /social/bands tree, while simultaneously being able to nodes that exist like /social/bands/$bandId, whether or not data exists in the path? I feel this is a common thing that happens.

I should note that I'm trying to implement these rules this inside the context of an Ionic 3 app, utilizing AngularFire, if that should make any difference at all (which I don't believe that it would, as the simulator is giving me the permission errors).

Update: Here is a screenshot of the simulator fail:

Here is the data I'm trying to write in the simulator

```<code>{
  "admins" : {
    "ruNdZP2Gx6bqsovL8gMlLJP9g0a2" : true
  },
  "creator_id" : "ruNdZP2Gx6bqsovL8gMlLJP9g0a2",
  "followers" : 2,
  "genres" : [ "Classical" ],
  "looking_for_musicians" : true,
  "members" : {
    "ruNdZP2Gx6bqsovL8gMlLJP9g0a2" : true
  },
  "name" : "Radiant and the beach",
  "social_profiles" : {
    "soundcloud" : ""
  }
}
</code>```

The path I'm writing to is /social/bands.

Here is the authentication state in the simulator:

Here is the existing data in the tree with one of the nodes expanded:

And the error message is just the Simulator write denied issue that I mentioned previously.

Any thoughts what I'm doing wrong here?

答:
You're trying to write to /social/bands. On that level you have a rule !data.exists(). There is already data under /social/bands, such as the band named My Awesome Band. Since data already exists, the !data.exists() evaluates to false and the write is rejected.

If you want users to be able to add new bands, you should move that rule down to the level of a specific band in your JSON:

```<code>"social": {
   "bands": {
     ".read": "auth != null",
     "$bandId": {
        ".write": "auth != null && (
          !data.exists() || !newData.exists() ||
          data.child('admins').child(auth.uid).val() === true
        )"
     }
   }
}
</code>```

In words: any authenticated user can add or delete a band, only admins can modify a band.

Body:
I feel this is a pretty common question, but as I've been learning Firebase security, I still can't seem to hack this small issue where I have a tree node that I want to be able to push new data to, while simultaneously be able to update existing nodes. According to the Firebase documentation, if you put these rules in your top-level tree, you should be able to create/delete, but not update:

".write": "!data.exists() || !newData.exists()"

So when I use the Firebase database simulator with authentication and everything, I go to simulate a "write" on a path /social/bands, however I get a Simulated write denied. I should note that in this path, data does exist.

My full rules for this example look like:

"social": {
   "bands": {
     ".read": "auth != null",
     ".write": "!data.exists() || !newData.exists() && auth != null",
     "$bandId": {
        ".write": "auth != null && data.child('admins').child(auth.uid).val() === true"
     }
   }
}

Is there a way to be able to create/delete nodes on my /social/bands tree, while simultaneously being able to nodes that exist like /social/bands/$bandId, whether or not data exists in the path? I feel this is a common thing that happens.

I should note that I'm trying to implement these rules this inside the context of an Ionic 3 app, utilizing AngularFire, if that should make any difference at all (which I don't believe that it would, as the simulator is giving me the permission errors).

Update: Here is a screenshot of the simulator fail:

Here is the data I'm trying to write in the simulator

{
  "admins" : {
    "ruNdZP2Gx6bqsovL8gMlLJP9g0a2" : true
  },
  "creator_id" : "ruNdZP2Gx6bqsovL8gMlLJP9g0a2",
  "followers" : 2,
  "genres" : [ "Classical" ],
  "looking_for_musicians" : true,
  "members" : {
    "ruNdZP2Gx6bqsovL8gMlLJP9g0a2" : true
  },
  "name" : "Radiant and the beach",
  "social_profiles" : {
    "soundcloud" : ""
  }
}

The path I'm writing to is /social/bands.

Here is the authentication state in the simulator:

Here is the existing data in the tree with one of the nodes expanded:

And the error message is just the Simulator write denied issue that I mentioned previously.

Any thoughts what I'm doing wrong here?

Body:
You're trying to write to /social/bands. On that level you have a rule !data.exists(). There is already data under /social/bands, such as the band named My Awesome Band. Since data already exists, the !data.exists() evaluates to false and the write is rejected.

If you want users to be able to add new bands, you should move that rule down to the level of a specific band in your JSON:

"social": {
   "bands": {
     ".read": "auth != null",
     "$bandId": {
        ".write": "auth != null && (
          !data.exists() || !newData.exists() ||
          data.child('admins').child(auth.uid).val() === true
        )"
     }
   }
}

In words: any authenticated user can add or delete a band, only admins can modify a band.