问:
Add class to parent div that matches label text
I would like to add a class to each parent div and have that class match the content of the label within the div with a hyphen added between each word.

In the example below, the first div would have class child-1-name, the second child-1-last-name, the third child-1-age. Any direction would be greatly appreciated!

Note that the HTML is generated automatically.

    child 1 name
    <input type="text">

    child 1 last name
    <input type="text">

    child 1 age
    <input type="text">

```

答:
First you get all the label elements. After you fetch the parent div element and add the textContent of the label as className of that div.

;window.onload = function(){
  for(var tListOfLabels=document.querySelectorAll('label'), i=tListOfLabels.length-1; i>=0; i--){
    if(tListOfLabels[i].textContent){
      var tDiv = function fP(e){return e && e.tagName === 'DIV' ? e : fP(e.parentNode)}(tListOfLabels[i]);
      tDiv.className += tListOfLabels[i].textContent.split(' ').join('-')
    }
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div></code>```

Body:
First you get all the label elements. After you fetch the parent div element and add the textContent of the label as className of that div.

;window.onload = function(){
  for(var tListOfLabels=document.querySelectorAll('label'), i=tListOfLabels.length-1; i>=0; i--){
    if(tListOfLabels[i].textContent){
      var tDiv = function fP(e){return e && e.tagName === 'DIV' ? e : fP(e.parentNode)}(tListOfLabels[i]);
      tDiv.className += tListOfLabels[i].textContent.split(' ').join('-')
    }
  }
};

<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div>


来源: stackexchange

问:
Though col1 and col2 and indexes, how are duplicate entries still popping up from my table for the same?
I am working with a table which has 3 columns that I can see.
INVERTER_ID, TIME_STAMP and POWER

INVERTER_ID and TIME_STAMP are indexes.

This is a huge table. One of my codes was throwing an error because duplicate entries were being encountered.

I got the timestamp and inverter_id for which i had duplicate entries. '2019-05-04 21:00:00' and INV1020

I queried the table with :

```<code>SELECT `INVERTER_ID`,`TIME_STAMP`,`POWER`
FROM `INV_POWER`
WHERE `TIME_STAMP`='2019-05-04 21:00:00' and
      `INVERTER_ID` ='INV1020'
</code>```

Got only one result.

```<code>INV1020     2019-05-04 21:00:00     0.0
</code>```

Strange I thought, so I went and checked the sql query my code was using and queried with the same :

```<code>SELECT `INVERTER_ID`,`TIME_STAMP`,`POWER
FROM `INV_POWER`
WHERE `TIME_STAMP`<='2019-05-04 21:00:01' and
      `TIME_STAMP`>='2019-05-04 21:00:00' and
       `INVERTER_ID` ='INV1020'
</code>```

In this case i got two results:

```<code>INV1020     2019-05-04 21:00:00     0.0
INV1020     2019-05-04 21:00:00     0.0
</code>```

Curious af as to how and why this happens. when i have INVERTER_ID and TIME_STAMP as indexes, i checked the structure of table and found that,
AUTO_INDEX is primary_key and an index. So i queried again but this time with AUTO_INDEX, column in my select.

```<code>SELECT `AUTO_INDEX`, `INVERTER_ID`,`TIME_STAMP`,`POWER` FROM `INV_POWER` WHERE `TIME_STAMP`<='2019-05-04 21:00:01' and `TIME_STAMP`>='2019-05-04 21:00:00' and`INVERTER_ID` ='INV1020'

6081057323  INV1020     2019-05-04 21:00:00     0.0
25805384826     INV1020     2019-05-04 21:00:00     0.0
------------------------------------------------------------------
</code>```

Question:
Why is this happening? With the index set, how did it get even inserted in the first place? Why am i seeing duplicates when i use < and >; and not when i am using =.

ThankYou in advance :)

答:
I suspect datatype of TIME_STAMP column allows for fractional seconds, for example, datatype could be DATETIME(3). (We're just guessing here.)

https://dev.mysql.com/doc/refman/8.0/en/datetime.html

This would explain the observed behavior.

ContentLicense: CC BY-SA 4.0

Body:
I am working with a table which has 3 columns that I can see.
INVERTER_ID, TIME_STAMP and POWER

INVERTER_ID and TIME_STAMP are indexes.

This is a huge table. One of my codes was throwing an error because duplicate entries were being encountered.

I got the timestamp and inverter_id for which i had duplicate entries. '2019-05-04 21:00:00' and INV1020

I queried the table with :

SELECT `INVERTER_ID`,`TIME_STAMP`,`POWER`
FROM `INV_POWER`
WHERE `TIME_STAMP`='2019-05-04 21:00:00' and
      `INVERTER_ID` ='INV1020'

Got only one result.

INV1020     2019-05-04 21:00:00     0.0

Strange I thought, so I went and checked the sql query my code was using and queried with the same :

SELECT `INVERTER_ID`,`TIME_STAMP`,`POWER
FROM `INV_POWER`
WHERE `TIME_STAMP`<='2019-05-04 21:00:01' and
      `TIME_STAMP`>='2019-05-04 21:00:00' and
       `INVERTER_ID` ='INV1020'

In this case i got two results:

INV1020     2019-05-04 21:00:00     0.0
INV1020     2019-05-04 21:00:00     0.0

Curious af as to how and why this happens. when i have INVERTER_ID and TIME_STAMP as indexes, i checked the structure of table and found that,
AUTO_INDEX is primary_key and an index. So i queried again but this time with AUTO_INDEX, column in my select.

SELECT `AUTO_INDEX`, `INVERTER_ID`,`TIME_STAMP`,`POWER` FROM `INV_POWER` WHERE `TIME_STAMP`<='2019-05-04 21:00:01' and `TIME_STAMP`>='2019-05-04 21:00:00' and`INVERTER_ID` ='INV1020'

6081057323  INV1020     2019-05-04 21:00:00     0.0
25805384826     INV1020     2019-05-04 21:00:00     0.0
------------------------------------------------------------------

Question:
Why is this happening? With the index set, how did it get even inserted in the first place? Why am i seeing duplicates when i use < and >; and not when i am using =.

ThankYou in advance :)


问:
Android espresso test pass locally but fails on Firebase Test Lab
I have issue with android espresso test.
Test pass locally but fail on FTL. It's simple test

onView(allOf(withId(R.id.text_supercategory_name), withText("Air conditioners"))).
check(matches(withText("Air conditioners")));

this test pass locally. On FTL I have error:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (with id: blablabla:id/text_product_verdict and with text: is "Air conditioners")

I’m not understand whay I see ID which not used in my test id/text_product_verdict … and this ID from another activity …
Activity for test is correct

@Rule
public ActivityTestRule<HomeActivity> mActivityTestRule = new ActivityTestRule<>(HomeActivity.class);

I checked the video of the failed test on FTL and see a lot of notifications on emulator
img from FTL

I decide that the problem was a sticky notification from Google Hangouts and try run my test with --no-auto-google-login flag. But have the same results. With onView(withText("Air conditioners")).check(matches(isDisplayed())); test pass on FTL.

Is anyone can help with with issue?

答:
It happened to me as well. It seems Firebase Test Lab does not recognize the id at withId(R.id.text_supercategory_name) in some devices. We can use res-name instead.

Check out the view hierarchy in the log and grab the res-name in there with onView(withResourceName("res-name")).perform(click());

```<code>// change res-name to buttonPanel, button3, button2, or button1
+---->ScrollView{id=16908757, res-name=buttonPanel, visibility=VISIBLE, width=1008, height=217, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=1507.0, child-count=1}
|
+----->ButtonBarLayout{id=-1, visibility=VISIBLE, width=1008, height=217, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=4}
|
+------>AppCompatButton{id=16908315, res-name=button3, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=, input-type=0, ime-target=false, has-links=false}
|
+------>Space{id=16909293, res-name=spacer, visibility=INVISIBLE, width=429, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=42.0, y=203.0}
|
+------>AppCompatButton{id=16908314, res-name=button2, visibility=VISIBLE, width=271, height=189, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=471.0, y=14.0, text=Cancel, input-type=0, ime-target=false, has-links=false}
|
+------>AppCompatButton{id=16908313, res-name=button1, visibility=VISIBLE, width=224, height=189, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=742.0, y=14.0, text=OK, input-type=0, ime-target=false, has-links=false}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It happened to me as well. It seems Firebase Test Lab does not recognize the id at withId(R.id.text_supercategory_name) in some devices. We can use res-name instead.

Check out the view hierarchy in the log and grab the res-name in there with onView(withResourceName("res-name")).perform(click());

// change res-name to buttonPanel, button3, button2, or button1
+---->ScrollView{id=16908757, res-name=buttonPanel, visibility=VISIBLE, width=1008, height=217, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=1507.0, child-count=1}
|
+----->ButtonBarLayout{id=-1, visibility=VISIBLE, width=1008, height=217, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=4}
|
+------>AppCompatButton{id=16908315, res-name=button3, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=, input-type=0, ime-target=false, has-links=false}
|
+------>Space{id=16909293, res-name=spacer, visibility=INVISIBLE, width=429, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=42.0, y=203.0}
|
+------>AppCompatButton{id=16908314, res-name=button2, visibility=VISIBLE, width=271, height=189, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=471.0, y=14.0, text=Cancel, input-type=0, ime-target=false, has-links=false}
|
+------>AppCompatButton{id=16908313, res-name=button1, visibility=VISIBLE, width=224, height=189, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=742.0, y=14.0, text=OK, input-type=0, ime-target=false, has-links=false}


问:
RegEx for capturing special chars
I am trying to replace a string using regular expression what i need basically is to convert a code like assignment:

```<code>k*=i
</code>```

into

```<code>k=k+i
</code>```

In my example:

```<code>jregex.Pattern p=new jregex.Pattern("([a-z]|[A-Z])([a-z]|[A-Z]|\\d)*[\\+|\\*|\\-|\\/][=]([a-z]|[A-Z])*([a-z]|[A-Z]|\\d)");
Replacer r= new Replacer(p,"1=$1,2=$2,3=$3,4=$4,5=$5,6=$6,7=$7,8=$8");
String result=r.replace("k*=i");
</code>```

The regex seems to not extract the special chars.

(in this example: +, -, *, /, =)

So what I get as result is:

```<code>1=k,2=,3=,4=i,5=,6=,7=,8=
</code>```

(I can extract only the k & i)

How do I solve this problem?

答:
Here, we can design as expression similar to:

```<code>(.+)[*+-/]=(.+)
</code>```

where we are capturing our k and i using these two capturing groups in the start and end:

```<code>(.+)
</code>```

We can add more boundaries, if we wish, such as start and end char:

```<code>^(.+)[*+-/]=(.+)$
</code>```

Test

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(.+)[*+-/]=(.+)";
final String string = "k*=i\n"
     + "apple*=orange";
final String subst = "$1=$1+$2";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Title: RegEx for capturing special chars

Body:
I am trying to replace a string using regular expression what i need basically is to convert a code like assignment:

k*=i

into

k=k+i

In my example:

jregex.Pattern p=new jregex.Pattern("([a-z]|[A-Z])([a-z]|[A-Z]|\\d)*[\\+|\\*|\\-|\\/][=]([a-z]|[A-Z])*([a-z]|[A-Z]|\\d)");
Replacer r= new Replacer(p,"1=$1,2=$2,3=$3,4=$4,5=$5,6=$6,7=$7,8=$8");
String result=r.replace("k*=i");

The regex seems to not extract the special chars.

(in this example: +, -, *, /, =)

So what I get as result is:

1=k,2=,3=,4=i,5=,6=,7=,8=

(I can extract only the k & i)

How do I solve this problem?

Body:
Here, we can design as expression similar to:

(.+)[*+-/]=(.+)

where we are capturing our k and i using these two capturing groups in the start and end:

(.+)

We can add more boundaries, if we wish, such as start and end char:

^(.+)[*+-/]=(.+)$

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(.+)[*+-/]=(.+)";
final String string = "k*=i\n"
     + "apple*=orange";
final String subst = "$1=$1+$2";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);

DEMO

RegEx Circuit

jex.im visualizes regular expressions:


问:
OpenVPN: Authentication Failed?
When I use the plugin for authentication at server.conf, authentication wont work, but without it, non existent users can authenticate also.

I have added the following lines in the server conf and clinet

```<code>Commands in the server.conf file
================================
mode server
tls-server
plugin /usr/lib64/openvpn/plugin/lib/openvpn-auth-pam.so login
key-direction 0
================================

Commands in the client file
=================================
port 1194
proto udp
dev tun
nobind
key-direction 1
redirect-gateway def1
tls-version-min 1.2
auth SHA256
auth-user-pass
tls-client
remote-cert-tls server
resolv-retry infinite
persist-key
persist-tun
verb 3
===============================

Logs:
==============================================================
PLUGIN_CALL: POST /usr/lib64/openvpn/plugin/lib/openvpn-auth-pam.so/PLUGIN_AUTH_USER_PASS_VERIFY status=1
PLUGIN_CALL: plugin function PLUGIN_AUTH_USER_PASS_VERIFY failed with status 1: /usr/lib64/openvpn/plugin/lib/openvpn-auth-pam.so
TLS Auth Error: Auth Username/Password verification failed for peer
Authenticate/Decrypt packet error: bad packet ID (may be a replay): [ #7 / time = (1559124952) Wed May 29 10:15:52 2019 ] -- see the man page entry for --no-replay and --replay-window for more info or silence this warning with --mute-replay-warnings
TLS Error: incoming packet authentication failed from [AF_INET6]::ffff:

openvpn[10420]: pam_unix(login:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=  user=*****```
==============================================================
```

答:
I have used differen approached, although in production plugin /usr/lib64/openvpn/plugin/lib/openvpn-auth-pam.so login is recommended way, but I have taken one shell script and got authentication, but remember it is dangerous.

add following lines in your /etc/openvpn/server.conf file

```<code>--verify-cline-cert none
script-security 2
auth-user-pass-verify /etc/openvpn/example.sh via-file
</code>```

Now create a file in /etc/openvpn/example.sh with following content

```<code>!/bin/bash
echo "started"

username=`head -1 $1`
password=`tail -1 $1`

if grep "$username:$password" $0.passwd > /dev/null 2>&1
then
    exit 0
else
    if grep "$username" $0.passwd > /dev/null 2>&1
    then
        echo "auth-user-pass-verify: Wrong password entered for user '$username'"
    else
        echo "auth-user-pass-verify: Unknown user '$username'"
    fi
    exit 1
fi
</code>```

Now create username and password in /etc/openvpn/example.sh.passwd with following content

```<code>userone:securepassworduserone
usertwo:securepasswordusertwo
</code>```

Now create a client file and import and connect using your password, but this where I am stack as I don't want to provide client file.

Title: OpenVPN: Authentication Failed?

Body:
When I use the plugin for authentication at server.conf, authentication wont work, but without it, non existent users can authenticate also.

I have added the following lines in the server conf and clinet

Commands in the server.conf file
================================
mode server
tls-server
plugin /usr/lib64/openvpn/plugin/lib/openvpn-auth-pam.so login
key-direction 0
================================

Commands in the client file
=================================
port 1194
proto udp
dev tun
nobind
key-direction 1
redirect-gateway def1
tls-version-min 1.2
auth SHA256
auth-user-pass
tls-client
remote-cert-tls server
resolv-retry infinite
persist-key
persist-tun
verb 3
===============================

Logs:
==============================================================
PLUGIN_CALL: POST /usr/lib64/openvpn/plugin/lib/openvpn-auth-pam.so/PLUGIN_AUTH_USER_PASS_VERIFY status=1
PLUGIN_CALL: plugin function PLUGIN_AUTH_USER_PASS_VERIFY failed with status 1: /usr/lib64/openvpn/plugin/lib/openvpn-auth-pam.so
TLS Auth Error: Auth Username/Password verification failed for peer
Authenticate/Decrypt packet error: bad packet ID (may be a replay): [ #7 / time = (1559124952) Wed May 29 10:15:52 2019 ] -- see the man page entry for --no-replay and --replay-window for more info or silence this warning with --mute-replay-warnings
TLS Error: incoming packet authentication failed from [AF_INET6]::ffff:

openvpn[10420]: pam_unix(login:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=  user=*****```
==============================================================

Body:
I have used differen approached, although in production plugin /usr/lib64/openvpn/plugin/lib/openvpn-auth-pam.so login is recommended way, but I have taken one shell script and got authentication, but remember it is dangerous.

add following lines in your /etc/openvpn/server.conf file

--verify-cline-cert none
script-security 2
auth-user-pass-verify /etc/openvpn/example.sh via-file

Now create a file in /etc/openvpn/example.sh with following content

!/bin/bash
echo "started"

username=`head -1 $1`
password=`tail -1 $1`

if grep "$username:$password" $0.passwd > /dev/null 2>&1
then
    exit 0
else
    if grep "$username" $0.passwd > /dev/null 2>&1
    then
        echo "auth-user-pass-verify: Wrong password entered for user '$username'"
    else
        echo "auth-user-pass-verify: Unknown user '$username'"
    fi
    exit 1
fi

Now create username and password in /etc/openvpn/example.sh.passwd with following content

userone:securepassworduserone
usertwo:securepasswordusertwo

Now create a client file and import and connect using your password, but this where I am stack as I don't want to provide client file.


问:
What is the industry standard in serializing null attributes in REST based services?
Recently there was discussion with my colleague about proper industry standards, in dealing with XML/JSON format resonses, having elements with null values. My view is to ignore/not including the elements in XML and JSON responses, if a particular element has null values. My belief is it would reduce the payload size and lesser bandwidth in transmission.

Where as my colleagues argument is to include all the attributes/elements defined in JSON/XML, whether there is value or not.

So ideally, it is like

```<code><name>John Doe</name>
 vs
<name>John Doe</name>
<DOB/>
</code>```

Similarly

```<code>{
  "name":"John Doe"
}
vs
{
   "name":"John Doe",
   "DOB":null
}
</code>```

What is the correct approach and why ?

Thanks

答:
```<code><name>John Doe</name>
 vs
<name>John Doe</name>
<DOB/>
</code>```

Careful! Those two representations aren't quite equivalent.  <DOB/> denotes an empty element; it is equivalent to <DOB></DOB>.  Empty and null aren't generically interchangeable - this is why we have both 204 No Content and 404 Not Found, both -s and -e.

What is the correct approach and why ?

I believe you want to be thinking about this question within the larger context of messaging.  In an ideal world, we would have a schema that describes each of the fields in our message -- what the semantics of the fields are, the allowed range of values, which fields are required, and which are optional, and the default semantics when optional fields are absent.

In a distributed system, where clients and servers deploy at a different cadence, it is common to extend a schema with additional semantics over the lifetime of the contract.  But if the clients and servers are independently deployed, you will have situations where the client and server understand different versions of the same schema.  So we need to be careful about forward and backwards compatibility, and the constraints on our changes necessary to keep everything working.

(Of course, we'll eventually want to make an incompatible change.  So we'll need to introduce a new message schema, and that in turn implies that we need to be thinking about message life cycles).

What this implies is that, in general, we need to be prepared for any optional field to be missing -- because the message may have been produced by a process that only knows about schema versions prior to the introduction of the new field.

So for the optional case, should a producer that's aware of an optional field always include it in the message?  I don't know of any published arguments in favor of that, beyond the general advice that explicit improves upon implicit.

Body:
Recently there was discussion with my colleague about proper industry standards, in dealing with XML/JSON format resonses, having elements with null values. My view is to ignore/not including the elements in XML and JSON responses, if a particular element has null values. My belief is it would reduce the payload size and lesser bandwidth in transmission.

Where as my colleagues argument is to include all the attributes/elements defined in JSON/XML, whether there is value or not.

So ideally, it is like

<name>John Doe</name>
 vs
<name>John Doe</name>
<DOB/>

Similarly

{
  "name":"John Doe"
}
vs
{
   "name":"John Doe",
   "DOB":null
}

What is the correct approach and why ?

Thanks

Body:
<name>John Doe</name>
 vs
<name>John Doe</name>
<DOB/>

Careful! Those two representations aren't quite equivalent.  <DOB/> denotes an empty element; it is equivalent to <DOB></DOB>.  Empty and null aren't generically interchangeable - this is why we have both 204 No Content and 404 Not Found, both -s and -e.

What is the correct approach and why ?

I believe you want to be thinking about this question within the larger context of messaging.  In an ideal world, we would have a schema that describes each of the fields in our message -- what the semantics of the fields are, the allowed range of values, which fields are required, and which are optional, and the default semantics when optional fields are absent.

In a distributed system, where clients and servers deploy at a different cadence, it is common to extend a schema with additional semantics over the lifetime of the contract.  But if the clients and servers are independently deployed, you will have situations where the client and server understand different versions of the same schema.  So we need to be careful about forward and backwards compatibility, and the constraints on our changes necessary to keep everything working.

(Of course, we'll eventually want to make an incompatible change.  So we'll need to introduce a new message schema, and that in turn implies that we need to be thinking about message life cycles).

What this implies is that, in general, we need to be prepared for any optional field to be missing -- because the message may have been produced by a process that only knows about schema versions prior to the introduction of the new field.

So for the optional case, should a producer that's aware of an optional field always include it in the message?  I don't know of any published arguments in favor of that, beyond the general advice that explicit improves upon implicit.


问:
Find mismatching files in two folders with bash
I have two folders - FolderA and FolderB - each containing thousands of files that should be named exactly the same before the extension.  One folder contains files with .jpg extension and the other with .txt extension.

My objective is to find any files that are in one but not in the other.  So for example if FolderA contains:

```<code>foo.jpg
bar.jpg
baz.jpg
</code>```

and FolderB contains:

```<code>foo.txt
baz.txt
qux.txt
</code>```

The script should return:

```<code>FolderA/bar.jpg
FolderB/qux.txt
</code>```

How would it be possible with bash to create such an output by inputting two separate directories ?  I was hoping to somehow modify the diff command which would give the Only in ... output but in this case since the extensions are different, diff would output all files

```<code>diff -rq FolderA FolderB
</code>```

答:
This does what you ask, but reports the results in 3 columns - those unique to the first directory, those unique to the second and those common to both:

```<code>comm <(cd FolderA && printf "%s\n" *.jpg | sed 's/.jpg$//') <(cd FolderB && printf "%s\n" *.txt | sed 's/.txt$//')
</code>```

Sample Output

```<code>bar
        baz
        foo
    qux
</code>```

You could suppress printing of column 3 with:

```<code>comm -3 ...
</code>```

Body:
I have two folders - FolderA and FolderB - each containing thousands of files that should be named exactly the same before the extension.  One folder contains files with .jpg extension and the other with .txt extension.

My objective is to find any files that are in one but not in the other.  So for example if FolderA contains:

foo.jpg
bar.jpg
baz.jpg

and FolderB contains:

foo.txt
baz.txt
qux.txt

The script should return:

FolderA/bar.jpg
FolderB/qux.txt

How would it be possible with bash to create such an output by inputting two separate directories ?  I was hoping to somehow modify the diff command which would give the Only in ... output but in this case since the extensions are different, diff would output all files

diff -rq FolderA FolderB

Body:
This does what you ask, but reports the results in 3 columns - those unique to the first directory, those unique to the second and those common to both:

comm <(cd FolderA && printf "%s\n" *.jpg | sed 's/.jpg$//') <(cd FolderB && printf "%s\n" *.txt | sed 's/.txt$//')

Sample Output

bar
        baz
        foo
    qux

You could suppress printing of column 3 with:

comm -3 ...


问:
ggplot line graph with NA values
I'm having with trouble with ggplot trying to plot 2 incomplete time series on the same graph where the y data does not have the same values on the x-axis (year) - NAs are thus present for certain years :

```<code>test<-structure(list(YEAR = c(1937, 1938, 1942, 1943, 1947, 1948, 1952,
1953, 1957, 1958, 1962, 1963, 1967, 1968, 1972, 1973, 1977, 1978,
1982, 1983, 1986.5, 1987, 1993.5), A1 = c(NA, 24, NA, 32, 32,
NA, 34, NA, NA, 18, 12, NA, 10, NA, 11, NA, 15, NA, 24, NA, NA,
25, 26), A2 = c(40, NA, 38, NA, 25, NA, 26, NA, 20, NA, 17,
17, 17, NA, 16, 18, 21, 18, 17, 25, NA, NA, 26)), .Names = c("YEAR", "A1",
"A2"), row.names = c(NA, -23L), class = "data.frame")
</code>```

The following code I tried outputs a disjointed mess :

```<code>ggplot(test, aes(x=YEAR)) +
  geom_line(aes(y = A1), size=0.43, colour="red") +
  geom_line(aes(y = A2), size=0.43, colour="green") +
  xlab("Year") + ylab("Percent") +
  scale_x_continuous(limits=c(1935, 1995), breaks = seq(1935, 1995, 5),
                     expand = c(0, 0)) +
  scale_y_continuous(limits=c(0,50), breaks=seq(0, 50, 10), expand = c(0, 0))
</code>```

How can I solve this problem?

答:
You can remove them by subsetting your dataframe:

```<code>  ggplot(test, aes(x=YEAR)) +
  geom_line(data=subset(test, !is.na(A1)),aes(y = A1), size=0.43, colour="red") +
  geom_line(data=subset(test, !is.na(A2)),aes(y = A2), size=0.43, colour="green") +
  xlab("Year") + ylab("Percent") +
  scale_x_continuous(limits=c(1935, 1995), breaks = seq(1935, 1995, 5),
                     expand = c(0, 0)) +
  scale_y_continuous(limits=c(0,50), breaks=seq(0, 50, 10), expand = c(0, 0))
</code>```

Title: ggplot line graph with NA values

Body:
I'm having with trouble with ggplot trying to plot 2 incomplete time series on the same graph where the y data does not have the same values on the x-axis (year) - NAs are thus present for certain years :

test<-structure(list(YEAR = c(1937, 1938, 1942, 1943, 1947, 1948, 1952,
1953, 1957, 1958, 1962, 1963, 1967, 1968, 1972, 1973, 1977, 1978,
1982, 1983, 1986.5, 1987, 1993.5), A1 = c(NA, 24, NA, 32, 32,
NA, 34, NA, NA, 18, 12, NA, 10, NA, 11, NA, 15, NA, 24, NA, NA,
25, 26), A2 = c(40, NA, 38, NA, 25, NA, 26, NA, 20, NA, 17,
17, 17, NA, 16, 18, 21, 18, 17, 25, NA, NA, 26)), .Names = c("YEAR", "A1",
"A2"), row.names = c(NA, -23L), class = "data.frame")

The following code I tried outputs a disjointed mess :

ggplot(test, aes(x=YEAR)) +
  geom_line(aes(y = A1), size=0.43, colour="red") +
  geom_line(aes(y = A2), size=0.43, colour="green") +
  xlab("Year") + ylab("Percent") +
  scale_x_continuous(limits=c(1935, 1995), breaks = seq(1935, 1995, 5),
                     expand = c(0, 0)) +
  scale_y_continuous(limits=c(0,50), breaks=seq(0, 50, 10), expand = c(0, 0))

How can I solve this problem?

Body:
You can remove them by subsetting your dataframe:

  ggplot(test, aes(x=YEAR)) +
  geom_line(data=subset(test, !is.na(A1)),aes(y = A1), size=0.43, colour="red") +
  geom_line(data=subset(test, !is.na(A2)),aes(y = A2), size=0.43, colour="green") +
  xlab("Year") + ylab("Percent") +
  scale_x_continuous(limits=c(1935, 1995), breaks = seq(1935, 1995, 5),
                     expand = c(0, 0)) +
  scale_y_continuous(limits=c(0,50), breaks=seq(0, 50, 10), expand = c(0, 0))


问:
How to detect numbering in simple vba string replacement
I'm trying to replace numbering (Word's 1. , 2. , etc.). In a simple string and replace search but I can't seem to find the numbers.

This is for Word 365, and I'm using the VB editor in there.

```<code>Sub ayaya()
Documents.Open FileName:=ActiveDocument.Path + "\Doc1.docm"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "SSS"
    .Replacement.Text = "PPP"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
With Selection
    If .Find.Forward = True Then
        .Collapse Direction:=wdCollapseStart
    Else
        .Collapse Direction:=wdCollapseEnd
    End If
    .Find.Execute Replace:=wdReplaceAll
End With

End Sub

</code>```

My word document looked like this:

```<code>SSS
SSS
1.  SSS
</code>```

and turned to

```<code>PPP
PPP
1.  PPP
</code>```

but when I replace the search to any variation of

```<code>With Selection.Find
    .Text = "1. SSS"
</code>```

It does not find the text.

答:
You are not finding the number associated with the paragraph text because it most likely is a ListLevelNumber and these are automatically generated by the ListFormat style. In other words, they are not part of the physical text that can be found using a Search, at least the way you currently have it setup in your code.

A separate Search would be required to find the ListParagraph Style being used and then some additional code that would manipulate the ListLevelNumber if that is what you are attempting to do.

Below is example code that determines what the ListLevelNumber is on a given paragraph and then takes some action based on what the level actually is:

```<code>Sub IsSelectionListParagraph()
    Dim i As Integer
    If Selection.Range.ListParagraphs.Count > 0 Then
        For i = 1 To Selection.Range.ListParagraphs.Count
            Select Case Selection.Range.ListParagraphs(i).Range.ListFormat.ListLevelNumber
                Case Is = 1
                    Debug.Print Selection.Range.Text
                Case Is = 2
                    Debug.Print Selection.Range.Text
                Case Else
                    Debug.Print Selection.Range.Text
            End Select
        Next
    End If
End Sub
</code>```

Body:
I'm trying to replace numbering (Word's 1. , 2. , etc.). In a simple string and replace search but I can't seem to find the numbers.

This is for Word 365, and I'm using the VB editor in there.

Sub ayaya()
Documents.Open FileName:=ActiveDocument.Path + "\Doc1.docm"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "SSS"
    .Replacement.Text = "PPP"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
With Selection
    If .Find.Forward = True Then
        .Collapse Direction:=wdCollapseStart
    Else
        .Collapse Direction:=wdCollapseEnd
    End If
    .Find.Execute Replace:=wdReplaceAll
End With

End Sub

My word document looked like this:

SSS
SSS
1.  SSS

and turned to

PPP
PPP
1.  PPP

but when I replace the search to any variation of

With Selection.Find
    .Text = "1. SSS"

It does not find the text.

Body:
You are not finding the number associated with the paragraph text because it most likely is a ListLevelNumber and these are automatically generated by the ListFormat style. In other words, they are not part of the physical text that can be found using a Search, at least the way you currently have it setup in your code.

A separate Search would be required to find the ListParagraph Style being used and then some additional code that would manipulate the ListLevelNumber if that is what you are attempting to do.

Below is example code that determines what the ListLevelNumber is on a given paragraph and then takes some action based on what the level actually is:

Sub IsSelectionListParagraph()
    Dim i As Integer
    If Selection.Range.ListParagraphs.Count > 0 Then
        For i = 1 To Selection.Range.ListParagraphs.Count
            Select Case Selection.Range.ListParagraphs(i).Range.ListFormat.ListLevelNumber
                Case Is = 1
                    Debug.Print Selection.Range.Text
                Case Is = 2
                    Debug.Print Selection.Range.Text
                Case Else
                    Debug.Print Selection.Range.Text
            End Select
        Next
    End If
End Sub


问:
C++ how to sort vector<class *> with operator <
i have

```<code> class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())
</code>```

why it dosent sort ?

but if we had

```<code> bool operator < (c1 w)
    {
        return number < w.number;
    }
</code>```

and

```<code>vector<c1> vec = { ... }
</code>```

it would have been sorted !

答:
The most straightforward approach is to define a function

```<code>bool c1_ptr_less( c1 const *lhs, c1 const *rhs ) {
    return lhs->something < rhs->something;
}

std::sort( vec.begin(), vec.end(), & c1_ptr_less );
</code>```

What I would suggest is a generic functor to take care of all pointer arrays

```<code>struct pointer_less {
    template< typename T >
    bool operator()( T const *lhs, T const *rhs ) const
        { return * lhs < * rhs; }
};

std::sort( vec.begin(), vec.end(), pointer_less() );
</code>```

Armed with this, define the usual c1::operator< ( const c1 & ) and likewise for other classes.

Generally, best practice is to avoid pointers entirely, including arrays of pointers.

Body:
i have

 class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())

why it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !

Body:
The most straightforward approach is to define a function

bool c1_ptr_less( c1 const *lhs, c1 const *rhs ) {
    return lhs->something < rhs->something;
}

std::sort( vec.begin(), vec.end(), & c1_ptr_less );

What I would suggest is a generic functor to take care of all pointer arrays

struct pointer_less {
    template< typename T >
    bool operator()( T const *lhs, T const *rhs ) const
        { return * lhs < * rhs; }
};

std::sort( vec.begin(), vec.end(), pointer_less() );

Armed with this, define the usual c1::operator< ( const c1 & ) and likewise for other classes.

Generally, best practice is to avoid pointers entirely, including arrays of pointers.


问:
Remove duplicate elements by class with JQuery
I want to delete duplicate span.film-date elements using the secondary class. For example I only want to keep the first span with the classes of "film-date Wed29May" and the first span with the classes of "film-date Thur30May".

```<code><div class="film-time-list">
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">5.20pm</a>
<span class="film-date Thur30May">Thur 30 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Thur30May">Thur 30 May</span>
<a class="film-tickets" href="#">5.20pm</a>
</div>
</code>```

I thought this would be straight forward enough but as the class that is output dynamically could be any date this snippet won't work which was my initial thought.

```<code>$('.couldBeAnyClass').not(':first').remove();
</code>```

Any pointers would be great!

My output would be:

```<code>Wed 29 May 2.30pm 5.20pm
Thur 30 May 2.30pm 5.20pm
</code>```

答:
This should do it! Since the corresponding anchor elements are not part of the span elements they do not get removed unless they are appended to the element being removed:

```<code>$(this).append( $(this).next() ).remove();
</code>```

$(function() {
  var prevClass;
  $('span.film-date').each(function() {
    var index = $(this).index();
    if( index ) {
      if( this.className === prevClass ) {
        $(this).append( $(this).next() ).remove();
      } else {
        prevClass = this.className;
      }
    } else {
      prevClass = this.className;
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="film-time-list">
  <span class="film-date Wed29May">Wed 29 May</span>
  2.30pm
  <span class="film-date Wed29May">Wed 29 May</span>
  5.20pm
  <span class="film-date Thur30May">Thur 30 May</span>
  2.30pm
  <span class="film-date Thur30May">Thur 30 May</span>
  5.20pm
</div></code>```

In a case where the span elements are not in order, the following can be used:

$(function() {
  var prevClass = [];
  $('span.film-date').each(function() {
    var index = $(this).index();
    if( index ) {
      if( $.inArray(this.className, prevClass) !== -1 ) {
        $(this).append( $(this).next() ).remove();
      } else {
        prevClass.push( this.className );
      }
    } else {
      prevClass.push( this.className );
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <div class="film-time-list">
      <span class="film-date Wed29May">Wed 29 May</span>
      2.30pm
       <span class="film-date Thur30May">Thur 30 May</span>
      2.30pm
     <span class="film-date Wed29May">Wed 29 May</span>
      5.20pm
      <span class="film-date Thur30May">Thur 30 May</span>
      5.20pm
    </div></code>```

Body:
I want to delete duplicate span.film-date elements using the secondary class. For example I only want to keep the first span with the classes of "film-date Wed29May" and the first span with the classes of "film-date Thur30May".

Wed 29 May
2.30pm
Wed 29 May
5.20pm
Thur 30 May
2.30pm
Thur 30 May
5.20pm

I thought this would be straight forward enough but as the class that is output dynamically could be any date this snippet won't work which was my initial thought.

$('.couldBeAnyClass').not(':first').remove();

Any pointers would be great!

My output would be:

Wed 29 May 2.30pm 5.20pm
Thur 30 May 2.30pm 5.20pm

Body:
This should do it! Since the corresponding anchor elements are not part of the span elements they do not get removed unless they are appended to the element being removed:

$(this).append( $(this).next() ).remove();

$(function() {
  var prevClass;
  $('span.film-date').each(function() {
    var index = $(this).index();
    if( index ) {
      if( this.className === prevClass ) {
        $(this).append( $(this).next() ).remove();
      } else {
        prevClass = this.className;
      }
    } else {
      prevClass = this.className;
    }
  });
});

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="film-time-list">
  <span class="film-date Wed29May">Wed 29 May</span>
  <a class="film-tickets" href="#">2.30pm</a>
  <span class="film-date Wed29May">Wed 29 May</span>
  <a class="film-tickets" href="#">5.20pm</a>
  <span class="film-date Thur30May">Thur 30 May</span>
  <a class="film-tickets" href="#">2.30pm</a>
  <span class="film-date Thur30May">Thur 30 May</span>
  <a class="film-tickets" href="#">5.20pm</a>
</div>

In a case where the span elements are not in order, the following can be used:

$(function() {
  var prevClass = [];
  $('span.film-date').each(function() {
    var index = $(this).index();
    if( index ) {
      if( $.inArray(this.className, prevClass) !== -1 ) {
        $(this).append( $(this).next() ).remove();
      } else {
        prevClass.push( this.className );
      }
    } else {
      prevClass.push( this.className );
    }
  });
});

    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <div class="film-time-list">
      <span class="film-date Wed29May">Wed 29 May</span>
      <a class="film-tickets" href="#">2.30pm</a>
       <span class="film-date Thur30May">Thur 30 May</span>
      <a class="film-tickets" href="#">2.30pm</a>
     <span class="film-date Wed29May">Wed 29 May</span>
      <a class="film-tickets" href="#">5.20pm</a>
      <span class="film-date Thur30May">Thur 30 May</span>
      <a class="film-tickets" href="#">5.20pm</a>
    </div>


问:
Is there any way to prevent RouterEvent firing?
I've got an app where I needed to keep a state of a filter form in the URL string.

You can see the implementation here

While changing a form value I want to set it as a URL state but this.router.navigation([], { queryParams }) emits an event which is not needed there.

```<code>   data$ = merge(
    this.router.events.pipe(
      filter((e: NavigationEnd) => e instanceof NavigationEnd),
      map(({ url }: NavigationEnd) => {
        const { queryParams } = this.router.parseUrl(url);
        if (queryParams['completed']) {
          queryParams['completed'] = queryParams['completed'] === 'true';
        }
        this.form.patchValue(queryParams, { emitEvent: false });
        return queryParams;
      }),
    ),
    this.form.valueChanges.pipe(
      debounceTime(200),
      tap((queryParams: Task) => {
        this.router.navigate([], { queryParams })
      })
    )
  ).pipe(
    switchMap((query?: Task) => this.getData(query))
  );
</code>```

Is it possible somehow prevent the emitting of the navigation event?

Needs something similar with this.form.patchValue(queryParams, { emitEvent: false });

答:
location.go(url) is what you need.

You can always generate a proper url within router.createUrlTree() method

```<code>const url = this.router
        .createUrlTree(
          [{foo: 'bar'}],
          {relativeTo: this.activatedRoute}
        )
        .toString();
this.location.go(url);
</code>```

Body:
I've got an app where I needed to keep a state of a filter form in the URL string.

You can see the implementation here

While changing a form value I want to set it as a URL state but this.router.navigation([], { queryParams }) emits an event which is not needed there.

   data$ = merge(
    this.router.events.pipe(
      filter((e: NavigationEnd) => e instanceof NavigationEnd),
      map(({ url }: NavigationEnd) => {
        const { queryParams } = this.router.parseUrl(url);
        if (queryParams['completed']) {
          queryParams['completed'] = queryParams['completed'] === 'true';
        }
        this.form.patchValue(queryParams, { emitEvent: false });
        return queryParams;
      }),
    ),
    this.form.valueChanges.pipe(
      debounceTime(200),
      tap((queryParams: Task) => {
        this.router.navigate([], { queryParams })
      })
    )
  ).pipe(
    switchMap((query?: Task) => this.getData(query))
  );

Is it possible somehow prevent the emitting of the navigation event?

Needs something similar with this.form.patchValue(queryParams, { emitEvent: false });

Body:
location.go(url) is what you need.

You can always generate a proper url within router.createUrlTree() method

const url = this.router
        .createUrlTree(
          [{foo: 'bar'}],
          {relativeTo: this.activatedRoute}
        )
        .toString();
this.location.go(url);


问:
How do I mark (or) shade the area below the graph of Surface plot in Matlab?
I am trying to plot a 3D surface graph for the following equation
 t_t <= (xi_i - xi_j) . sqrt(rho). I have included my code. But I would like to mark or shade the area under the graph of this surface plot. How do I solve it?

```<code>[X,Y] = meshgrid(1:0.5:10,1:20);

Z = X.* sqrt(Y);

figure;

colormap(jet)

surf(X,Y,Z)

colorbar

xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');

ylabel('Density(\rho)');

zlabel('Transmission Delay (t_t)');
</code>```

答:
The only way I can think is by looping over the edges, and filling them accordingly.

```<code>[X,Y] = meshgrid(1:0.5:10,1:20);

Z = X.* sqrt(Y);

figure;

p=parula; % please do not use jet :(

surf(X,Y,Z)
hold on;

%XZ init
for ii=1:size(Z,2)-1
    patch([X(1,ii) X(1,ii+1)  X(1,ii+1) X(1,ii)],...
          [Y(1,1) Y(1,1) Y(1,1) Y(1,1)],...
          [0  0 Z(1,ii+1) Z(1,ii) ],[p(1,:)]);
end

%XZ end
for ii=1:size(Z,2)-1
    patch([X(end,ii) X(end,ii+1)  X(end,ii+1) X(end,ii)],...
          [Y(end,1) Y(end,1) Y(end,1) Y(end,1)],...
          [0  0 Z(end,ii+1) Z(end,ii) ],[p(1,:)]);
end

%YZ init
for ii=1:size(Z,1)-1
    patch([X(1,1) X(1,1) X(1,1) X(1,1)],...
          [Y(ii,1) Y(ii+1,1) Y(ii+1,1) Y(ii,1)],...
          [0  0 Z(ii+1,1) Z(ii,1) ],[p(1,:)]);
end

%YZ end
for ii=1:size(Z,1)-1
    patch([X(1,end) X(1,end) X(1,end) X(1,end)],...
          [Y(ii,end) Y(ii+1,end) Y(ii+1,end) Y(ii,end)],...
          [0  0 Z(ii+1,end) Z(ii,end) ],[p(1,:)]);
end
colorbar

xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');

ylabel('Density(\rho)');

zlabel('Transmission Delay (t_t)');
</code>```

There are a lot of style choices you can make now, like removing edges or changing the colors that I will leave to you as they can be found online.

If this is not exactly what you wanted, its still pretty much the way to do it. Using patch and appropriate coordinates.

Body:
I am trying to plot a 3D surface graph for the following equation
 t_t <= (xi_i - xi_j) . sqrt(rho). I have included my code. But I would like to mark or shade the area under the graph of this surface plot. How do I solve it?

[X,Y] = meshgrid(1:0.5:10,1:20);

Z = X.* sqrt(Y);

figure;

colormap(jet)

surf(X,Y,Z)

colorbar

xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');

ylabel('Density(\rho)');

zlabel('Transmission Delay (t_t)');

Body:
The only way I can think is by looping over the edges, and filling them accordingly.

[X,Y] = meshgrid(1:0.5:10,1:20);

Z = X.* sqrt(Y);

figure;

p=parula; % please do not use jet :(

surf(X,Y,Z)
hold on;

%XZ init
for ii=1:size(Z,2)-1
    patch([X(1,ii) X(1,ii+1)  X(1,ii+1) X(1,ii)],...
          [Y(1,1) Y(1,1) Y(1,1) Y(1,1)],...
          [0  0 Z(1,ii+1) Z(1,ii) ],[p(1,:)]);
end

%XZ end
for ii=1:size(Z,2)-1
    patch([X(end,ii) X(end,ii+1)  X(end,ii+1) X(end,ii)],...
          [Y(end,1) Y(end,1) Y(end,1) Y(end,1)],...
          [0  0 Z(end,ii+1) Z(end,ii) ],[p(1,:)]);
end

%YZ init
for ii=1:size(Z,1)-1
    patch([X(1,1) X(1,1) X(1,1) X(1,1)],...
          [Y(ii,1) Y(ii+1,1) Y(ii+1,1) Y(ii,1)],...
          [0  0 Z(ii+1,1) Z(ii,1) ],[p(1,:)]);
end

%YZ end
for ii=1:size(Z,1)-1
    patch([X(1,end) X(1,end) X(1,end) X(1,end)],...
          [Y(ii,end) Y(ii+1,end) Y(ii+1,end) Y(ii,end)],...
          [0  0 Z(ii+1,end) Z(ii,end) ],[p(1,:)]);
end
colorbar

xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');

ylabel('Density(\rho)');

zlabel('Transmission Delay (t_t)');

There are a lot of style choices you can make now, like removing edges or changing the colors that I will leave to you as they can be found online.

If this is not exactly what you wanted, its still pretty much the way to do it. Using patch and appropriate coordinates.


问:
Lister CRUD add other entity column to lister
How can I add a column value from another entity to the lister CRUD? I have a table company with the fields name and address and I want a column name from the entity customer into the lister. I want a header:

company.name, company.address and customer.name

I have two models with relation methods. I can't find it here.

https://laravel-backpack.readme.io/v3.0/docs/crud-full-api

Is that possible, and how can I achieve that?

答:
Create relationship in your Model and use whereHas

```<code>$this->crud->addClause('whereHas', 'customers', function($query) {
     $query->customers();
 });
</code>```

Body:
Create relationship in your Model and use whereHas

$this->crud->addClause('whereHas', 'customers', function($query) {
     $query->customers();
 });


问:
SQL Query: Only include PAIRS of rows in query
Im looking to find pairs of rows in a table like below

MS SQL 2012(maybe 2014)

```<code>Ref, Split
1, A
1, B
2, B
3, A
3, B
</code>```

Results

```<code>Ref, Split
1, A
1, B
3, A
3, B
</code>```

pairs of rows are partitioned by 'Ref' ie, 1 and 3 need to be returned, but 2 does not have a pair so should not be returned

I would by default use OVER but i believe this is overkill and not the most effective way of handling this.

What are the alternatives

答:
If your DBMS supports count() over() it's just the way to go.

```<code>select t.Ref, t.Split
from (
   select Ref, Split, count(distinct Split) over(partition by Ref) cnt
) t
where t.cnt > 1
-- cnt = 2  if exactly the pairs are required
</code>```

Body:
Im looking to find pairs of rows in a table like below

MS SQL 2012(maybe 2014)

Ref, Split
1, A
1, B
2, B
3, A
3, B

Results

Ref, Split
1, A
1, B
3, A
3, B

pairs of rows are partitioned by 'Ref' ie, 1 and 3 need to be returned, but 2 does not have a pair so should not be returned

I would by default use OVER but i believe this is overkill and not the most effective way of handling this.

What are the alternatives

Body:
If your DBMS supports count() over() it's just the way to go.

select t.Ref, t.Split
from (
   select Ref, Split, count(distinct Split) over(partition by Ref) cnt
) t
where t.cnt > 1
-- cnt = 2  if exactly the pairs are required


问:
Change timestamp TZ in spark
I have a dateframe containing timestamps (unix):

```<code>df = spark.createDataFrame(
    [
        (1527853209,),
        (1527852466,),
        (1527852178,),
        (1527851689,),
        (1527852214,),
    ],
    ["date_time"]
)
</code>```

and I use the spark configuration below :

```<code>OPT_SPARK = {
    'master': 'yarn',
    'spark.executor.extraJavaOptions': '-Duser.timezone=GMT',
    'spark.driver.extraJavaOptions': '-Duser.timezone=GMT',
}
</code>```

Without changing the spark options, I would like to convert my timestamp from "GMT" to "CET - Central Europe Time".

I tried below code :

```<code>from pyspark.sql import functions as F, types as T
from datetime import datetime
from dateutil import tz

def conv(in_ts):

    from_zone = tz.gettz('GMT')
    to_zone = tz.gettz('CET')

    utc = datetime.utcfromtimestamp(in_ts)
    utc = utc.replace(tzinfo=from_zone)
    n_ts = utc.astimezone(to_zone).replace(tzinfo=None)

    return n_ts

conv_udf = F.udf(conv, T.TimestampType())
</code>```

It works fine when I test the function, but not in spark :

```<code># 1527853209 is GMT: Friday 1 June 2018 11:40:09
conv(1527853209)
datetime.datetime(2018, 6, 1, 13, 40, 9)

df.select(
    "date_time",
    F.col("date_time").cast("timestamp"),
    conv_udf("date_time")
).show()

+----------+-------------------+-------------------+
| date_time|          date_time|    conv(date_time)|
+----------+-------------------+-------------------+
|1527853209|2018-06-01 11:40:09|2018-06-01 11:40:09|
|1527852466|2018-06-01 11:27:46|2018-06-01 11:27:46|
|1527852178|2018-06-01 11:22:58|2018-06-01 11:22:58|
|1527851689|2018-06-01 11:14:49|2018-06-01 11:14:49|
|1527852214|2018-06-01 11:23:34|2018-06-01 11:23:34|
+----------+-------------------+-------------------+
</code>```

I could not find any builtin function to achieve that, so using a UDF seemed to be the best solution but, apparently, it is not working as expected.

Expected result :

```<code>+----------+-------------------+-------------------+
| date_time|          date_time|    conv(date_time)|
+----------+-------------------+-------------------+
|1527853209|2018-06-01 11:40:09|2018-06-01 13:40:09|
|1527852466|2018-06-01 11:27:46|2018-06-01 13:27:46|
|1527852178|2018-06-01 11:22:58|2018-06-01 13:22:58|
|1527851689|2018-06-01 11:14:49|2018-06-01 13:14:49|
|1527852214|2018-06-01 11:23:34|2018-06-01 13:23:34|
+----------+-------------------+-------------------+
</code>```

答:
I think what you are doing is right, but when you print out the result using show() your conv(date_time) is getting traduced to your timezone (GMT).

If the only thing you need is to show the datetime in the new timezone (CET), you can rewrite the udf as a StringType:

```<code>def conv(in_ts):

from_zone = tz.gettz('GMT')
to_zone = tz.gettz('CET')

utc = datetime.utcfromtimestamp(in_ts)
utc = utc.replace(tzinfo=from_zone)
n_ts = utc.astimezone(to_zone)

return n_ts.strftime('%x %X')

conv_udf = F.udf(conv, T.StringType())
</code>```

Title: Change timestamp TZ in spark

Body:
I have a dateframe containing timestamps (unix):

df = spark.createDataFrame(
    [
        (1527853209,),
        (1527852466,),
        (1527852178,),
        (1527851689,),
        (1527852214,),
    ],
    ["date_time"]
)

and I use the spark configuration below :

OPT_SPARK = {
    'master': 'yarn',
    'spark.executor.extraJavaOptions': '-Duser.timezone=GMT',
    'spark.driver.extraJavaOptions': '-Duser.timezone=GMT',
}

Without changing the spark options, I would like to convert my timestamp from "GMT" to "CET - Central Europe Time".

I tried below code :

from pyspark.sql import functions as F, types as T
from datetime import datetime
from dateutil import tz

def conv(in_ts):

    from_zone = tz.gettz('GMT')
    to_zone = tz.gettz('CET')

    utc = datetime.utcfromtimestamp(in_ts)
    utc = utc.replace(tzinfo=from_zone)
    n_ts = utc.astimezone(to_zone).replace(tzinfo=None)

    return n_ts

conv_udf = F.udf(conv, T.TimestampType())

It works fine when I test the function, but not in spark :

# 1527853209 is GMT: Friday 1 June 2018 11:40:09
conv(1527853209)
datetime.datetime(2018, 6, 1, 13, 40, 9)

df.select(
    "date_time",
    F.col("date_time").cast("timestamp"),
    conv_udf("date_time")
).show()

+----------+-------------------+-------------------+
| date_time|          date_time|    conv(date_time)|
+----------+-------------------+-------------------+
|1527853209|2018-06-01 11:40:09|2018-06-01 11:40:09|
|1527852466|2018-06-01 11:27:46|2018-06-01 11:27:46|
|1527852178|2018-06-01 11:22:58|2018-06-01 11:22:58|
|1527851689|2018-06-01 11:14:49|2018-06-01 11:14:49|
|1527852214|2018-06-01 11:23:34|2018-06-01 11:23:34|
+----------+-------------------+-------------------+

I could not find any builtin function to achieve that, so using a UDF seemed to be the best solution but, apparently, it is not working as expected.

Expected result :

+----------+-------------------+-------------------+
| date_time|          date_time|    conv(date_time)|
+----------+-------------------+-------------------+
|1527853209|2018-06-01 11:40:09|2018-06-01 13:40:09|
|1527852466|2018-06-01 11:27:46|2018-06-01 13:27:46|
|1527852178|2018-06-01 11:22:58|2018-06-01 13:22:58|
|1527851689|2018-06-01 11:14:49|2018-06-01 13:14:49|
|1527852214|2018-06-01 11:23:34|2018-06-01 13:23:34|
+----------+-------------------+-------------------+

Body:
I think what you are doing is right, but when you print out the result using show() your conv(date_time) is getting traduced to your timezone (GMT).

If the only thing you need is to show the datetime in the new timezone (CET), you can rewrite the udf as a StringType:

def conv(in_ts):

from_zone = tz.gettz('GMT')
to_zone = tz.gettz('CET')

utc = datetime.utcfromtimestamp(in_ts)
utc = utc.replace(tzinfo=from_zone)
n_ts = utc.astimezone(to_zone)

return n_ts.strftime('%x %X')

conv_udf = F.udf(conv, T.StringType())


问:
Generate UUID values by default for each row on column of UUID type in H2 Database Engine
In the H2 database, on a table with a column of UUID data type, how do we specify that we want H2 to generate a UUID value by default when an INSERT omits that field?

I know how to generate a UUID.
I have read the Question, How to insert a specific UUID in h2 database?.

My question is about how to ask H2 to generate the UUID value on my behalf.

答:
In JPA/Hibernate

After googling for hours I've created a simple solution for JPA or Hibernate, according to @Thomas Mueller.

```<code>@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
        name = "UUID",
        strategy = "org.hibernate.id.UUIDGenerator"
)
@Column(name = "ID", updatable = false, nullable = false)
@ColumnDefault("random_uuid()")
@Type(type = "uuid-char")
@Getter
@Setter
private UUID id;
</code>```

So @Type(type = "uuid-char") makes your field a VARCHAR(255) if you need it (it's binary by default)

And @ColumnDefault("random_uuid()") puts the default value for generated table DDL

Body:
In JPA/Hibernate

After googling for hours I've created a simple solution for JPA or Hibernate, according to @Thomas Mueller.

@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
        name = "UUID",
        strategy = "org.hibernate.id.UUIDGenerator"
)
@Column(name = "ID", updatable = false, nullable = false)
@ColumnDefault("random_uuid()")
@Type(type = "uuid-char")
@Getter
@Setter
private UUID id;

So @Type(type = "uuid-char") makes your field a VARCHAR(255) if you need it (it's binary by default)

And @ColumnDefault("random_uuid()") puts the default value for generated table DDL


问:
Crop correct part of image while the PictureBox is in 'zoom' mode
I have a PictureBox1 with it's sizemode set to Stretch and PictureBox1. The PictureBox1 contains an image and let's me select part of it and then crop it and store the cropped part inside PictureBox2. It works great when the sizemode is set to Stretch and the picture is not zoomed, but not when I zoom it or set the sizemode to zoom.

working example - sizemode set to 'stretch'

The code I use to crop part of the picture (original source)

```<code>try
{
    float stretch1X = 1f * pictureBox1.Image.Width / pictureBox1.ClientSize.Width;
    float stretch1Y = 1f * pictureBox1.Image.Height / pictureBox1.ClientSize.Height;

    Point pt = new Point((int)(_mDown.X * stretch1X), (int)(_mDown.Y * stretch1Y));
    Size sz = new Size((int)((_mCurr.X - _mDown.X) * stretch1X),
                       (int)((_mCurr.Y - _mDown.Y) * stretch1Y));

    if (sz.Width > 0 && sz.Height > 0)
    {
        Rectangle rSrc = new Rectangle(pt, sz);
        Rectangle rDest = new Rectangle(Point.Empty, sz);

        Bitmap bmp = new Bitmap(sz.Width, sz.Height);
        using (Graphics G = Graphics.FromImage(bmp))
            G.DrawImage(pictureBox1.Image, rDest, rSrc, GraphicsUnit.Pixel);
        return bmp;
    }

    return null;
}
catch (Exception ex)
{
    throw ex;
}
</code>```

How do I calculate it properly? How can I make the crop function work in a way so it lets the user zoom in/out and still crop the correct part of the picture?

答:
You need to calculate the points using the stretch factor and maybe also the offset.

For Zoom there is only one factor as aspect ratio is always the same for Image and PictureBox, but there usually is an offset; for Stretch you need no offset but two factors.

Here is an example that goes all the way using two PictureBoxes two show a zoomed version and the cropped bitmap. It makes use of an all-purpose function ImageArea that determines size and offset.

Two class level variables:

```<code>Point pDown = Point.Empty;
Rectangle rect = Rectangle.Empty;
</code>```

Three mouse events:

```<code>private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    pDown = e.Location;
    pictureBox1.Refresh();
}

private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (!e.Button.HasFlag(MouseButtons.Left)) return;

    rect = new Rectangle(pDown, new Size(e.X - pDown.X, e.Y - pDown.Y));
    using (Graphics g = pictureBox1.CreateGraphics())
    {
        pictureBox1.Refresh();
        g.DrawRectangle(Pens.Orange, rect);
    }
}

private void PictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    Rectangle iR = ImageArea(pictureBox2);
    rect = new Rectangle(pDown.X - iR.X, pDown.Y - iR.Y,
                         e.X - pDown.X, e.Y - pDown.Y);
    Rectangle rectSrc = Scaled(rect, pictureBox2, true);
    Rectangle rectDest = new Rectangle(Point.Empty, rectSrc.Size);

    Bitmap bmp = new Bitmap(rectDest.Width, rectDest.Height);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.DrawImage(pictureBox2.Image, rectDest, rectSrc, GraphicsUnit.Pixel);
    }
    pictureBox2.Image = bmp;
}
</code>```

Here is a useful function that returns the area of the actual image inside a picturebox for any sizemode..:

```<code>Rectangle ImageArea(PictureBox pbox)
{
    Size si = pbox.Image.Size;
    Size sp = pbox.ClientSize;

    if (pbox.SizeMode == PictureBoxSizeMode.StretchImage)
       return pbox.ClientRectangle;
    if (pbox.SizeMode == PictureBoxSizeMode.Normal ||
        pbox.SizeMode == PictureBoxSizeMode.AutoSize)
       return new Rectangle(Point.Empty, si);
    if (pbox.SizeMode == PictureBoxSizeMode.CenterImage)
        return new Rectangle(new Point((sp.Width - si.Width) / 2,
                            (sp.Height - si.Height) / 2), si);

    //  PictureBoxSizeMode.Zoom
    float ri = 1f * si.Width / si.Height;
    float rp = 1f * sp.Width / sp.Height;
    if (rp > ri)
    {
        int width = si.Width * sp.Height / si.Height;
        int left = (sp.Width - width) / 2;
        return new Rectangle(left, 0, width, sp.Height);
    }
    else
    {
        int height = si.Height * sp.Width / si.Width;
        int top = (sp.Height - height) / 2;
        return new Rectangle(0, top, sp.Width, height);
    }
}
</code>```

We only need the offset to determine the rectangle unscaled. We also need to scale it:

```<code>Rectangle Scaled(Rectangle rect, PictureBox pbox, bool scale)
{
    float factor = GetFactor(pbox);
    if (!scale) factor = 1f / factor;
    return Rectangle.Round(new RectangleF(rect.X * factor, rect.Y * factor,
                               rect.Width * factor, rect.Height * factor));
}
</code>```

For this need to know the scaling factor, which depends on the aspect ratio:

```<code>float GetFactor(PictureBox pBox)
{
    if (pBox.Image == null) return 0;
    Size si = pBox.Image.Size;
    Size sp = pBox.ClientSize;
    float ri = 1f * si.Width / si.Height;
    float rp = 1f * sp.Width / sp.Height;
    float factor = 1f * pBox.Image.Width / pBox.ClientSize.Width;
    if (rp > ri) factor = 1f * pBox.Image.Height / pBox.ClientSize.Height;
    return factor;
}
</code>```

This solution will also work if the PictureBox is zoomed in or out by placing it inside a AutoScrolling Panel and changing the Pbox.Size.

Body:
I have a PictureBox1 with it's sizemode set to Stretch and PictureBox1. The PictureBox1 contains an image and let's me select part of it and then crop it and store the cropped part inside PictureBox2. It works great when the sizemode is set to Stretch and the picture is not zoomed, but not when I zoom it or set the sizemode to zoom.

working example - sizemode set to 'stretch'

The code I use to crop part of the picture (original source)

try
{
    float stretch1X = 1f * pictureBox1.Image.Width / pictureBox1.ClientSize.Width;
    float stretch1Y = 1f * pictureBox1.Image.Height / pictureBox1.ClientSize.Height;

    Point pt = new Point((int)(_mDown.X * stretch1X), (int)(_mDown.Y * stretch1Y));
    Size sz = new Size((int)((_mCurr.X - _mDown.X) * stretch1X),
                       (int)((_mCurr.Y - _mDown.Y) * stretch1Y));

    if (sz.Width > 0 && sz.Height > 0)
    {
        Rectangle rSrc = new Rectangle(pt, sz);
        Rectangle rDest = new Rectangle(Point.Empty, sz);

        Bitmap bmp = new Bitmap(sz.Width, sz.Height);
        using (Graphics G = Graphics.FromImage(bmp))
            G.DrawImage(pictureBox1.Image, rDest, rSrc, GraphicsUnit.Pixel);
        return bmp;
    }

    return null;
}
catch (Exception ex)
{
    throw ex;
}

How do I calculate it properly? How can I make the crop function work in a way so it lets the user zoom in/out and still crop the correct part of the picture?

Body:
You need to calculate the points using the stretch factor and maybe also the offset.

For Zoom there is only one factor as aspect ratio is always the same for Image and PictureBox, but there usually is an offset; for Stretch you need no offset but two factors.

Here is an example that goes all the way using two PictureBoxes two show a zoomed version and the cropped bitmap. It makes use of an all-purpose function ImageArea that determines size and offset.

Two class level variables:

Point pDown = Point.Empty;
Rectangle rect = Rectangle.Empty;

Three mouse events:

private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    pDown = e.Location;
    pictureBox1.Refresh();
}

private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (!e.Button.HasFlag(MouseButtons.Left)) return;

    rect = new Rectangle(pDown, new Size(e.X - pDown.X, e.Y - pDown.Y));
    using (Graphics g = pictureBox1.CreateGraphics())
    {
        pictureBox1.Refresh();
        g.DrawRectangle(Pens.Orange, rect);
    }
}

private void PictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    Rectangle iR = ImageArea(pictureBox2);
    rect = new Rectangle(pDown.X - iR.X, pDown.Y - iR.Y,
                         e.X - pDown.X, e.Y - pDown.Y);
    Rectangle rectSrc = Scaled(rect, pictureBox2, true);
    Rectangle rectDest = new Rectangle(Point.Empty, rectSrc.Size);

    Bitmap bmp = new Bitmap(rectDest.Width, rectDest.Height);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.DrawImage(pictureBox2.Image, rectDest, rectSrc, GraphicsUnit.Pixel);
    }
    pictureBox2.Image = bmp;
}

Here is a useful function that returns the area of the actual image inside a picturebox for any sizemode..:

Rectangle ImageArea(PictureBox pbox)
{
    Size si = pbox.Image.Size;
    Size sp = pbox.ClientSize;

    if (pbox.SizeMode == PictureBoxSizeMode.StretchImage)
       return pbox.ClientRectangle;
    if (pbox.SizeMode == PictureBoxSizeMode.Normal ||
        pbox.SizeMode == PictureBoxSizeMode.AutoSize)
       return new Rectangle(Point.Empty, si);
    if (pbox.SizeMode == PictureBoxSizeMode.CenterImage)
        return new Rectangle(new Point((sp.Width - si.Width) / 2,
                            (sp.Height - si.Height) / 2), si);

    //  PictureBoxSizeMode.Zoom
    float ri = 1f * si.Width / si.Height;
    float rp = 1f * sp.Width / sp.Height;
    if (rp > ri)
    {
        int width = si.Width * sp.Height / si.Height;
        int left = (sp.Width - width) / 2;
        return new Rectangle(left, 0, width, sp.Height);
    }
    else
    {
        int height = si.Height * sp.Width / si.Width;
        int top = (sp.Height - height) / 2;
        return new Rectangle(0, top, sp.Width, height);
    }
}

We only need the offset to determine the rectangle unscaled. We also need to scale it:

Rectangle Scaled(Rectangle rect, PictureBox pbox, bool scale)
{
    float factor = GetFactor(pbox);
    if (!scale) factor = 1f / factor;
    return Rectangle.Round(new RectangleF(rect.X * factor, rect.Y * factor,
                               rect.Width * factor, rect.Height * factor));
}

For this need to know the scaling factor, which depends on the aspect ratio:

float GetFactor(PictureBox pBox)
{
    if (pBox.Image == null) return 0;
    Size si = pBox.Image.Size;
    Size sp = pBox.ClientSize;
    float ri = 1f * si.Width / si.Height;
    float rp = 1f * sp.Width / sp.Height;
    float factor = 1f * pBox.Image.Width / pBox.ClientSize.Width;
    if (rp > ri) factor = 1f * pBox.Image.Height / pBox.ClientSize.Height;
    return factor;
}

This solution will also work if the PictureBox is zoomed in or out by placing it inside a AutoScrolling Panel and changing the Pbox.Size.


问:
Add class to parent div that matches label text
I would like to add a class to each parent div and have that class match the content of the label within the div with a hyphen added between each word.

In the example below, the first div would have class child-1-name, the second child-1-last-name, the third child-1-age. Any direction would be greatly appreciated!

Note that the HTML is generated automatically.

    child 1 name
    <input type="text">

    child 1 last name
    <input type="text">

    child 1 age
    <input type="text">

```

答:
The simplest way to achieve this would be to loop through all the .wrapable elements, retrieve their closest div ancestor and then set the class on that to the text of the label, with a basic replace() operation on the whitespace, something like this:

$('.wrapable').each(function() {
  var $el = $(this);
  $el.closest('div').addClass($el.text().trim().replace(/\s+/g, '-'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div></code>```

Body:
The simplest way to achieve this would be to loop through all the .wrapable elements, retrieve their closest div ancestor and then set the class on that to the text of the label, with a basic replace() operation on the whitespace, something like this:

$('.wrapable').each(function() {
  var $el = $(this);
  $el.closest('div').addClass($el.text().trim().replace(/\s+/g, '-'));
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div>


问:
Can a class inside a class call a getter method from the outer class?
I have a class inside a class.

The outer class does some processing to generate an array of values.

I want the inner class to be able to access the outer class' array.

Is there a clean way to achieve this?

I'm thinking to have a method in the outer class that calls a method in the inner class sending him the address of the array and the inner class needs to hold a pointer in its private member section in order to later point to it by assignment from the method that receives the address. But this feels a little clunky.

答:
Okay, here it is in full. Key points:

C++ has nested classes, however that's a 100% compile-time thing dealing with scoping and encapsulation, the class instances are 100% independent.

Therefore if you want either class to use the other in any way, it must either create an instance or accept one.

(and then, given an outer instance, the inner class is allowed to access its private parts that's the only thing that actually differs from normal scoping).

So knowing that, here is a concrete example.

 → Outer owns a vector of Inners.

 → Inner needs to use its owning Outer instance

 ➥ say Outer could be some kind of List and Inner some kind of Item

```<code>class Outer
{
public:  // can be private, in which case Inner won't be usable from outside
    class Inner
    {
        Outer & m_outer;
    public:
        Inner(Outer & outer) : m_outer(outer) {}
        void doOuterMagic() { m_outer.doMagic(); }
    };

public:
    void addInner() { m_inners.emplace_back(*this); }

private: // could be public, but I want to illustrate Inner access to private members
    void doMagic() { std::cout <<"magic"; }

private:
    std::vector<Inner> m_inners;
};
</code>```

As with any class, you may also define it below the outer class if it's more readable. You'd do it like this:

```<code>class Outer
{
public:  // can be private, in which case Inner won't be usable from outside
    class Inner;
public:

    // ... unchanged ...

};

class Outer::Inner  // note the scoping here
{
    // ... exactly what was in class Inner above
};
</code>```

Notes:

Any relationship Outer and Inner have it up to your design, C++ assumes none.

If Outer works in close relationship with Inner, it's pretty common to have Outer create Inner instances and pass itself to them, as I did in addInner here.

I made m_outer a reference, but this prevents Inner from satisfying *Assignable requirements. If you need the class to satisfy those, make it a pointer instead.

Body:
Okay, here it is in full. Key points:

C++ has nested classes, however that's a 100% compile-time thing dealing with scoping and encapsulation, the class instances are 100% independent.

Therefore if you want either class to use the other in any way, it must either create an instance or accept one.

(and then, given an outer instance, the inner class is allowed to access its private parts that's the only thing that actually differs from normal scoping).

So knowing that, here is a concrete example.

 → Outer owns a vector of Inners.

 → Inner needs to use its owning Outer instance

 ➥ say Outer could be some kind of List and Inner some kind of Item

class Outer
{
public:  // can be private, in which case Inner won't be usable from outside
    class Inner
    {
        Outer & m_outer;
    public:
        Inner(Outer & outer) : m_outer(outer) {}
        void doOuterMagic() { m_outer.doMagic(); }
    };

public:
    void addInner() { m_inners.emplace_back(*this); }

private: // could be public, but I want to illustrate Inner access to private members
    void doMagic() { std::cout <<"magic"; }

private:
    std::vector<Inner> m_inners;
};

As with any class, you may also define it below the outer class if it's more readable. You'd do it like this:

class Outer
{
public:  // can be private, in which case Inner won't be usable from outside
    class Inner;
public:

    // ... unchanged ...

};

class Outer::Inner  // note the scoping here
{
    // ... exactly what was in class Inner above
};

Notes:

Any relationship Outer and Inner have it up to your design, C++ assumes none.

If Outer works in close relationship with Inner, it's pretty common to have Outer create Inner instances and pass itself to them, as I did in addInner here.

I made m_outer a reference, but this prevents Inner from satisfying *Assignable requirements. If you need the class to satisfy those, make it a pointer instead.


问:
stargazer rounding errors
The stargazer package is rounding my regression output. For example, stargazer takes my regression coefficient of -3.56588 and outputs -3.600. Following a comment posted here, I attempted to resolve using digits=NA, however, received the following error:

Error in paste(first.part, .format.decimal.character, decimal.part, sep = "") :
  object 'decimal.part' not found.

Minimal working example with an error message as follows:

```<code>library(stargazer)
data(mtcars)

mylogit <- glm(vs ~ cyl + disp + hp, data = mtcars, family = "binomial")
summary(mylogit)
stargazer(mylogit, digits=NA)

mylogit2 <- glm(vs ~ disp + hp + qsec, data = mtcars, family = "binomial")
summary(mylogit2)
stargazer(mylogit2, digits=NA)
</code>```

Interestingly, the output works correctly for mylogit but not for mylogit2!

Any thoughts would be greatly appreciated!

答:
Just in case anyone in the future encounters a similar problem, after much deliberation and frustration I decided to use the package texreg instead.

texreg function

Overall a very easy package to export Rstudio tables to LaTeX and, more importantly, does not cause any rounding issues.

Title: stargazer rounding errors

Body:
The stargazer package is rounding my regression output. For example, stargazer takes my regression coefficient of -3.56588 and outputs -3.600. Following a comment posted here, I attempted to resolve using digits=NA, however, received the following error:

Error in paste(first.part, .format.decimal.character, decimal.part, sep = "") :
  object 'decimal.part' not found.

Minimal working example with an error message as follows:

library(stargazer)
data(mtcars)

mylogit <- glm(vs ~ cyl + disp + hp, data = mtcars, family = "binomial")
summary(mylogit)
stargazer(mylogit, digits=NA)

mylogit2 <- glm(vs ~ disp + hp + qsec, data = mtcars, family = "binomial")
summary(mylogit2)
stargazer(mylogit2, digits=NA)

Interestingly, the output works correctly for mylogit but not for mylogit2!

Any thoughts would be greatly appreciated!


问:
Hidden field not updated in updatepanel after putting listview into insert mode
I'm currently having a problem where a hidden field whose value is set in the code-behind does not propagate back to the client. The basic layout is as follows:

```<code><asp:UpdatePanel .....
<ContentTemplate ....
    <input id="myHiddenField" type="hidden" value="" runat="server" ....

    <asp:ListView ID="MyListView" .....
</code>```

I have a button with an on click event, in there I set the hidden field value. If I don't put the listview into insert mode, the value is propagated back to the client; however, if I do put the listview into insert mode, then nothing. I'm also rebinding the datasource on the listview.

```<code>void mybutton_click(object sender, eventargs e)
{
    myHiddenField.Value = "testing";
    MyList.InsertItemPosition = InsertItemPosition.FirstItem;
    MyList.DataSource = // my datasource
    MyList.DataBind();
}
</code>```

Side Note: I'm rebinding the listview so that the data bound delegate can be called and I can do extra stuff in there.

答: Instead of <input id="myHiddenField" type="hidden" value="" runat="server" use a <asp:HiddenField ID="myHiddenField" runat="server" /> and everything should be fine.

Body:
I'm currently having a problem where a hidden field whose value is set in the code-behind does not propagate back to the client. The basic layout is as follows:

<asp:UpdatePanel .....
<ContentTemplate ....
    <input id="myHiddenField" type="hidden" value="" runat="server" ....

    <asp:ListView ID="MyListView" .....

I have a button with an on click event, in there I set the hidden field value. If I don't put the listview into insert mode, the value is propagated back to the client; however, if I do put the listview into insert mode, then nothing. I'm also rebinding the datasource on the listview.

void mybutton_click(object sender, eventargs e)
{
    myHiddenField.Value = "testing";
    MyList.InsertItemPosition = InsertItemPosition.FirstItem;
    MyList.DataSource = // my datasource
    MyList.DataBind();
}

Side Note: I'm rebinding the listview so that the data bound delegate can be called and I can do extra stuff in there.


问:
Is there a R function to order by character or factor of intervals?
After several functions I get a table, which has ordered characters, some starting with "(" or "[" followed by numbers. (intervals, coming from a cut(x) on the data)

What i want to achieve is an order by the startvalue of the invervals, so that (100,124] does not come before (70,100] (see example)
edit: the order of column1 (class) should stay as it is.

well i tried to do it with the order and setorder from data.table but failed so far. I think I need to split the column with strsplit and then order by the first element of it, but that can't be the "best" solution

```<code>test <- data.frame(class = c("class1",   "class1",   "class1",   "class1",   "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2"),
                   attr = c("1","2","4","5","(100,124]", "(124,180]" ,"(180,Inf]", "(37,50]" ,  "(5,37]"  ,  "(50,56]"  , "(56,70]"  ,"(70,100]"  ,"[0,5]" ),
                  value = c(415.14,115.13,422.52,37.07,167.40,135.04,67.01,280.03,81.18,237.83,285.62,302.63,3.37))

</code>```

aim:

```<code>class   attr    value
class1  1   415.14
class1  2   115.13
class1  4   422.52
class1  5   37.07
class2  [0,5]   3.37
class2  (5,37]  81.18
class2  (37,50] 280.03
class2  (50,56] 237.83
class2  (56,70] 285.62
class2  (70,100]    302.63
class2  (100,124]   167.40
class2  (124,180]   135.04
class2  (180,Inf]   67.01
</code>```

Body:
After several functions I get a table, which has ordered characters, some starting with "(" or "[" followed by numbers. (intervals, coming from a cut(x) on the data)

What i want to achieve is an order by the startvalue of the invervals, so that (100,124] does not come before (70,100] (see example)
edit: the order of column1 (class) should stay as it is.

well i tried to do it with the order and setorder from data.table but failed so far. I think I need to split the column with strsplit and then order by the first element of it, but that can't be the "best" solution

test <- data.frame(class = c("class1",   "class1",   "class1",   "class1",   "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2"),
                   attr = c("1","2","4","5","(100,124]", "(124,180]" ,"(180,Inf]", "(37,50]" ,  "(5,37]"  ,  "(50,56]"  , "(56,70]"  ,"(70,100]"  ,"[0,5]" ),
                  value = c(415.14,115.13,422.52,37.07,167.40,135.04,67.01,280.03,81.18,237.83,285.62,302.63,3.37))

aim:

class   attr    value
class1  1   415.14
class1  2   115.13
class1  4   422.52
class1  5   37.07
class2  [0,5]   3.37
class2  (5,37]  81.18
class2  (37,50] 280.03
class2  (50,56] 237.83
class2  (56,70] 285.62
class2  (70,100]    302.63
class2  (100,124]   167.40
class2  (124,180]   135.04
class2  (180,Inf]   67.01

Body:
An option with tidyverse

library(tidyverse)
test %>%
   arrange(class, as.numeric(str_extract(attr, "\\d+")))
#  class      attr  value
#1  class1         1 415.14
#2  class1         2 115.13
#3  class1         4 422.52
#4  class1         5  37.07
#5  class2     [0,5]   3.37
#6  class2    (5,37]  81.18
#7  class2   (37,50] 280.03
#8  class2   (50,56] 237.83
#9  class2   (56,70] 285.62
#10 class2  (70,100] 302.63
#11 class2 (100,124] 167.40
#12 class2 (124,180] 135.04
#13 class2 (180,Inf]  67.01

NOTE: There was no set seed


问:
CSS transition on SVG causes flickering IE11 and Edge
I have a SVG image placed in my header. The image has a fixed width and when I scroll down I add a CSS class to my header to change the width of the image. It works fine except It flickers in IE11 and Edge, works fine in Chrome.

```<code>img {
  transition: width 5s ease;
}
</code>```

Any ideas how to solve this?

Fiddle:
https://jsfiddle.net/xpvt214o/980754/

答:
Instead of using img tag, give object a try. It even gives you a fallback option and resolves the flickeing issue on IE/Edge. It should work on older browsers too.

Example

```<code><object data="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/adobe.svg" type="image/svg+xml" width="200">
    <!--Fallback image for older browsers -->
    <img src="http://placehold.it/250x200" />
</object>
</code>```

I've updated you jsfiddle: https://jsfiddle.net/axdetm4h/

Body:
I have a SVG image placed in my header. The image has a fixed width and when I scroll down I add a CSS class to my header to change the width of the image. It works fine except It flickers in IE11 and Edge, works fine in Chrome.

img {
  transition: width 5s ease;
}

Any ideas how to solve this?

Fiddle:
https://jsfiddle.net/xpvt214o/980754/

Body:
Instead of using img tag, give object a try. It even gives you a fallback option and resolves the flickeing issue on IE/Edge. It should work on older browsers too.

Example

<object data="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/adobe.svg" type="image/svg+xml" width="200">
    <!--Fallback image for older browsers -->
    <img src="http://placehold.it/250x200" />
</object>

I've updated you jsfiddle: https://jsfiddle.net/axdetm4h/


问:
lazy loading with doctrine one to one mapping
I am having a hard time finding the correct result for this.

I have one to one mapping. There are two tables:

```<code>/**
* @ORM\Table(name="users")
* @ORM\Entity
*/
class Users {

   /**
    * @ORM\OneToOne(targetEntity="UsersSettings", mappedBy="user",cascade={"persist"})
   */
   private $userSetting;

   //getters and setters
}

/**
* @ORM\Table(name="notifications_settings")
* @ORM\Entity
*/
class UsersSettings {

   /**
   * @var Users
   *
   * @ORM\OneToOne(targetEntity="Users", inversedBy="userSetting")
   * @ORM\JoinColumns({
   *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
   * })
   */
   private $user;
}
</code>```

Whenever I fetch entity one as below:

```<code>$q = $this
            ->createQueryBuilder('u')
            ->select('u, r')
            ->leftJoin('u.roles', 'r')
            ->where('u.username = :username OR u.email = :email')
            ->setParameter('username', $username)
            ->setParameter('email', $username)
            ->getQuery();
</code>```

Doctrine immediately performs join to usersSettings entity which I dont want:

SELECT t0.id AS id1, t0.username AS username2, t0.email AS email3, t0.password AS password4, t29.id AS id30, t29.is_notify_by_email AS
  is_notify_by_email31, t29.user_id AS user_id32 FROM users t0 LEFT JOIN
  users_settings t29 ON t29.user_id = t0.id WHERE t0.id = ?

Other types of mapping like OneToMany and ManyToOne performs lazy loading but in case of one to one mapping, I could not configure to lazy load. How can I lazy load this relation? I am using doctrine 2.3 and Symfony 2.1

答:
Inverse sides of one-to-one associations can not be lazy.

Explanation:

This is expected behavior. There is no foreign key on the inverse side, hence it is impossible to decide whether to proxy it or not. We must query for the associated object or join it. Note that this only affects inverse sides of single-valued associations, that is, really only the inverse side of bidirectional one-to-one associations.

Why we cannot create proxy without FK?

It is pretty simple, in a one-to-many association where the one-side is the inverse side, it holds a collection. The collection may be empty or not but there can always be a collection so it easy and correct to always put a proxy collection there.

If you have a single-valued side that is the inverse side, how can you decide whether to put a proxy object there or not? Without seeing the foreign key you have no way to distinguish between: There is no associated object (and thus putting a proxy object in place would by simply wrong) or there is one and of which type it is, if inheritance is involved (since putting a proxy of the wrong type in is also wrong).

See discusion on https://github.com/doctrine/orm/issues/4389

Body:
I am having a hard time finding the correct result for this.

I have one to one mapping. There are two tables:

/**
* @ORM\Table(name="users")
* @ORM\Entity
*/
class Users {

   /**
    * @ORM\OneToOne(targetEntity="UsersSettings", mappedBy="user",cascade={"persist"})
   */
   private $userSetting;

   //getters and setters
}

/**
* @ORM\Table(name="notifications_settings")
* @ORM\Entity
*/
class UsersSettings {

   /**
   * @var Users
   *
   * @ORM\OneToOne(targetEntity="Users", inversedBy="userSetting")
   * @ORM\JoinColumns({
   *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
   * })
   */
   private $user;
}

Whenever I fetch entity one as below:

$q = $this
            ->createQueryBuilder('u')
            ->select('u, r')
            ->leftJoin('u.roles', 'r')
            ->where('u.username = :username OR u.email = :email')
            ->setParameter('username', $username)
            ->setParameter('email', $username)
            ->getQuery();

Doctrine immediately performs join to usersSettings entity which I dont want:

SELECT t0.id AS id1, t0.username AS username2, t0.email AS email3, t0.password AS password4, t29.id AS id30, t29.is_notify_by_email AS
  is_notify_by_email31, t29.user_id AS user_id32 FROM users t0 LEFT JOIN
  users_settings t29 ON t29.user_id = t0.id WHERE t0.id = ?

Other types of mapping like OneToMany and ManyToOne performs lazy loading but in case of one to one mapping, I could not configure to lazy load. How can I lazy load this relation? I am using doctrine 2.3 and Symfony 2.1


答:
You can fetch each .wrapable class and add a class to its closest 'div'.

Using Regex replace for spaces into hyphens.

$('.wrapable').each(function() {
  var _this = $(this);

  _this.closest('div').addClass(_this.text().replace(/\s+/g, '-'));
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div></code>```

Title: Add class to parent div that matches label text

Body:
I would like to add a class to each parent div and have that class match the content of the label within the div with a hyphen added between each word.

In the example below, the first div would have class child-1-name, the second child-1-last-name, the third child-1-age. Any direction would be greatly appreciated!

Note that the HTML is generated automatically.

    child 1 name
    <input type="text">

    child 1 last name
    <input type="text">

    child 1 age
    <input type="text">

Body:
You can fetch each .wrapable class and add a class to its closest 'div'.

Using Regex replace for spaces into hyphens.

$('.wrapable').each(function() {
  var _this = $(this);

  _this.closest('div').addClass(_this.text().replace(/\s+/g, '-'));
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div>


问:
Error while saving a matplolib plot to pdf
I am tryiny to save my matplotlib.pyplots to a pdf.  I am using PdfPages for it.

plot gets saved for :

```<code>pdf = PdfPages("Minion Plots - May 22.pdf")

fig = plt.figure()
plt.title('Counter')
plt.plot(data2['timestamp'],data2['counter'])
pdf.savefig(fig)

</code>```

throws an error for

```<code>ax = plt.figure().gca()
plt.title('Time to Restart')
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.ylabel('Time in Minutes')
fig = plt.plot(data1['Time to Restart'])
pdf.savefig(fig)
</code>```

I am using

```<code>ax = plt.figure().gca()

for

ax.xaxis.set_major_locator(MaxNLocator(integer=True))
</code>```

error is

```<code>TypeError: unhashable type: 'list'
</code>```

答:
```<code>fig,ax = plt.subplots()
plt.title('Time to Restart')
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.ylabel('Time in Minutes')
plt.plot(data1['Time to Restart'])
pdf.savefig(fig)
</code>```

this solves the issue

Body:
I am tryiny to save my matplotlib.pyplots to a pdf.  I am using PdfPages for it.

plot gets saved for :

pdf = PdfPages("Minion Plots - May 22.pdf")

fig = plt.figure()
plt.title('Counter')
plt.plot(data2['timestamp'],data2['counter'])
pdf.savefig(fig)

throws an error for

ax = plt.figure().gca()
plt.title('Time to Restart')
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.ylabel('Time in Minutes')
fig = plt.plot(data1['Time to Restart'])
pdf.savefig(fig)

I am using

ax = plt.figure().gca()

for

ax.xaxis.set_major_locator(MaxNLocator(integer=True))

error is

TypeError: unhashable type: 'list'

Body:
fig,ax = plt.subplots()
plt.title('Time to Restart')
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.ylabel('Time in Minutes')
plt.plot(data1['Time to Restart'])
pdf.savefig(fig)

this solves the issue


问:
finding multiples of a number in Python
I'm trying to write a code that lets me find the first few multiples of a number. This is one of my attempts:

```<code>def printMultiples(n, m):
for m in (n,m):
    print(n, end = ' ')
</code>```

I figured out that, by putting for m in (n, m):, it would run through the loop for whatever number was m.

```<code>def printMultiples(n, m):
'takes n and m as integers and finds all first m multiples of n'
for m in (n,m):
    if n % 2 == 0:
        while n < 0:
            print(n)
</code>```

After multiple searches, I was only able to find a sample code in java, so I tried to translate that into python, but I didn't get any results. I have a feeling I should be using the range() function somewhere in this, but I have no idea where.

答:
You can do:</p>

```<code>def mul_table(n,i=1):
    print(n*i)
    if i !=10:
        mul_table(n,i+1)
mul_table(7)
</code>```

Title: finding multiples of a number in Python

Body:
I'm trying to write a code that lets me find the first few multiples of a number. This is one of my attempts:

def printMultiples(n, m):
for m in (n,m):
    print(n, end = ' ')

I figured out that, by putting for m in (n, m):, it would run through the loop for whatever number was m.

def printMultiples(n, m):
'takes n and m as integers and finds all first m multiples of n'
for m in (n,m):
    if n % 2 == 0:
        while n < 0:
            print(n)

After multiple searches, I was only able to find a sample code in java, so I tried to translate that into python, but I didn't get any results. I have a feeling I should be using the range() function somewhere in this, but I have no idea where.

Body:
You can do:

def mul_table(n,i=1):
    print(n*i)
    if i !=10:
        mul_table(n,i+1)
mul_table(7)