问:
CSS Alignment Issue on Navigation Bar
I'm currently creating a navigation bar that expands and collapses whether the mouse is over or out of the navbar. My issue is that when the navbar is expanded, my icons are aligned to the center but I wish for them to be positioned exactly where they are before the navbar is expanded. I have them aligned to the center because the icons are not the same size and look 'out of place' without it, when the navbar is collapsed.

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
  //document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: center;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

```

And JSFiddle link:
https://jsfiddle.net/h86zf4d3/

I tried to float my icons to the left as you can see from the commented out JS code, however, for some reason, this gets rid of the block display for the list items.

答:
To make it works, change the #links{text-align:left}
And your issue about the icon's size put the fa-fw class. it will makeall the icons the same size.

```<code>Check the snippest below:
</code>```

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
  //document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Navigation Bar</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

```

Title: CSS Alignment Issue on Navigation Bar

Body:
I'm currently creating a navigation bar that expands and collapses whether the mouse is over or out of the navbar. My issue is that when the navbar is expanded, my icons are aligned to the center but I wish for them to be positioned exactly where they are before the navbar is expanded. I have them aligned to the center because the icons are not the same size and look 'out of place' without it, when the navbar is collapsed.

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
  //document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};

#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: center;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

And JSFiddle link:
https://jsfiddle.net/h86zf4d3/

I tried to float my icons to the left as you can see from the commented out JS code, however, for some reason, this gets rid of the block display for the list items.

Body:
To make it works, change the #links{text-align:left}
And your issue about the icon's size put the fa-fw class. it will makeall the icons the same size.

Check the snippest below:

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
  //document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};

#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

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

  <head>
    <meta charset="UTF-8" />
    <title>Navigation Bar</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <script src="https://kit.fontawesome.com/6cc49d804e.js" crossorigin="anonymous"></script>
    <script src="js/scripts.js"></script>
  </head>

  <body>
    <div id="sidenav">
      <div id="sidenav-brand">
        <div id="sidenav-heading" style="display:none;">
          <h2>Expanded</h2>
        </div>
        <div id="sidenav-expand">
          <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
        </div>
      </div>

      <div id="sidenav-links">
        <ul id="links">
          <li>
            <i class="fas fa-fw fa-id-card fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-graduation-cap fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-briefcase fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-smile-beam fa-2x"></i>
          </li>
        </ul>
      </div>
    </div>
  </body>

</html>


来源: stackexchange

问:
setContentView(R.layout.main); error
```<code>package com.elfapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button btn_Login;
    private EditText et_UserName;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn_Login = (Button) findViewById(R.id.button_login);
        btn_Login.setOnClickListener(this);

        et_UserName = (EditText) findViewById(R.id.editText_userName);
    }

    public void onClick(View v) {
        if (v.equals(btn_Login)) {
                // skriver ut en toast när man klickar på knappen
            Toast.makeText(MainActivity.this, "Ansluter till server...", Toast.LENGTH_SHORT).show();

                // används i debuggern för att påvisa att programmet exekverat hit
            Log.v("ThisApp", "onClick Successful");

                // TODO skickar det som står i et_UserName till controller (genom TCP/IP), som ska kolla om användaren finns
            // send et_UserName.getText().toString() to controller

                // if(username exists)
            Intent intent = new Intent(this, RoomActivity.class);
            this.startActivity(intent);
        }
    }

}
</code>```

I'm getting an error on the line containing setContentView(R.layout.main);
Not sure about what the error/exception is because I'm not used to working in Eclipse..

答:
Just take 2 steps and problem would be more likely to get solved:

Step 1:
Clean your project by clicking Project -> Clean.

Step 2:
Rebuild your project by clicking Project -> Build All.

Also make sure that your layout xml files are syntax error free and you don't have any image which has non-acceptable names (such as a "-" between image name).

Also I request you to have a look at problems window and let me know what errors are being shown there.

ContentLicense: CC BY-SA 3.0

Title: setContentView(R.layout.main); error

Body:
package com.elfapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button btn_Login;
    private EditText et_UserName;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn_Login = (Button) findViewById(R.id.button_login);
        btn_Login.setOnClickListener(this);

        et_UserName = (EditText) findViewById(R.id.editText_userName);
    }

    public void onClick(View v) {
        if (v.equals(btn_Login)) {
                // skriver ut en toast när man klickar på knappen
            Toast.makeText(MainActivity.this, "Ansluter till server...", Toast.LENGTH_SHORT).show();

                // används i debuggern för att påvisa att programmet exekverat hit
            Log.v("ThisApp", "onClick Successful");

                // TODO skickar det som står i et_UserName till controller (genom TCP/IP), som ska kolla om användaren finns
            // send et_UserName.getText().toString() to controller

                // if(username exists)
            Intent intent = new Intent(this, RoomActivity.class);
            this.startActivity(intent);
        }
    }

}

I'm getting an error on the line containing setContentView(R.layout.main);
Not sure about what the error/exception is because I'm not used to working in Eclipse..


答:
I've simpy added float: left to the CSS for #links and it looks fine to me.

They are still center-aligned on the collapsed version, because I haven't removed the line directly above it which says text-align: center;. However, they no longer change position when the menu opens.

See the snippet below:

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: center;
  float: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

```

ContentLicense: CC BY-SA 4.0

Title: CSS Alignment Issue on Navigation Bar

Body:
I've simpy added float: left to the CSS for #links and it looks fine to me.

They are still center-aligned on the collapsed version, because I haven't removed the line directly above it which says text-align: center;. However, they no longer change position when the menu opens.

See the snippet below:

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};

#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: center;
  float: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

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

<head>
  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />
  <script src="https://kit.fontawesome.com/6cc49d804e.js" crossorigin="anonymous"></script>
  <script src="js/scripts.js"></script>
</head>

<body>
  <div id="sidenav">
    <div id="sidenav-brand">
      <div id="sidenav-heading" style="display:none;">
        <h2>Expanded</h2>
      </div>
      <div id="sidenav-expand">
        <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
      </div>
    </div>

    <div id="sidenav-links">
      <ul id="links">
        <li>
          <i class="fas fa-id-card fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-graduation-cap fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-briefcase fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-smile-beam fa-2x"></i>
        </li>
      </ul>
    </div>
  </div>
</body>

</html>


问:
How to dismiss keyboard on button press in Xamarin Forms
After much searching, I worked out a way to hide the keyboard on a button press in Xamarin Forms for iOS. So it's shared below.

If anyone can improve it, or share a solution for the Android side, that would be great.

答:
```<code> view.Unfocus();
</code>```

That's it.

Some people report this not working, but it's worked like gangbusters for me.

Body:
 view.Unfocus();

That's it.

Some people report this not working, but it's worked like gangbusters for me.


问:
How to return a numpy array with values derived from the source array of max values of different arrays of same shape
I'm have trouble writing this question out so maybe best just to illustrate. In short I have two sets of three arrays of the same shape. Using the first set, for each element, I would like to find which array has the max value in that position and return the value from the second set. While the example has each 3 x 3 shaped array as a different object they could just as easily be a (3 ,3 ,3).

The set to find the max value:

```<code>import numpy as np
A1 = np.array([[13, 16, 17], [32, 16, 11], [46, 30, 14]], dtype='uint8')
B1 = np.array([[31, 46, 41], [19, 29, 45], [36, 30, 46]], dtype='uint8')
C1 = np.array([[36, 35, 26], [19, 40, 24], [5, 20, 46]], dtype='uint8')
</code>```

The set to use as the return value:

```<code>A2 = np.array([[1, 1, 4], [3, 1, 4], [1, 3, 2]], dtype='uint8')
B2 = np.array([[2, 3, 1], [4, 4, 2], [1, 1, 3]], dtype='uint8')
C2 = np.array([[3, 2, 3], [1, 2, 3], [2, 4, 4]], dtype='uint8')
</code>```

If it's a two step solution the first would return an array like:

```<code>mx1
array([['C', 'B', 'B'],
       ['A', 'C', 'B'],
       ['A', 'A', 'B']], dtype='<U1')
</code>```

Then the desired output is:

```<code>out1
array([[3, 3, 1],
       [3, 2, 2],
       [1, 3, 3]])
</code>```

Note that in the event of a tie for max value(the last two elements) the value from the first encountered array is the accepted value.

I thought this would be a simple task using some np.max and np.where type magic but I can't seem to wrap my head around this problem correctly.

答:
```<code>import numpy as np

A1 = np.array([[13, 16, 17], [32, 16, 11], [46, 30, 14]], dtype='uint8')
B1 = np.array([[31, 46, 41], [19, 29, 45], [36, 30, 46]], dtype='uint8')
C1 = np.array([[36, 35, 26], [19, 40, 24], [5, 20, 46]], dtype='uint8')

A2 = np.array([[1, 1, 4], [3, 1, 4], [1, 3, 2]], dtype='uint8')
B2 = np.array([[2, 3, 1], [4, 4, 2], [1, 1, 3]], dtype='uint8')
C2 = np.array([[3, 2, 3], [1, 2, 3], [2, 4, 4]], dtype='uint8')

D=np.array([A1,B1,C1])
F=np.array([A2,B2,C2])

amax=np.argmax(D,axis=0)
# array( [[2, 1, 1],
#         [0, 2, 1],
#         [0, 0, 1]] )

#There should be a better way to do this.
idx=np.array([ (y,x[0],x[1]) for x,y in np.ndenumerate(amax)])
# array([[2, 0, 0],
#        [1, 0, 1],
#        [1, 0, 2],
#        [0, 1, 0],
#        [2, 1, 1],
#        [1, 1, 2],
#        [0, 2, 0],
#        [0, 2, 1],
#        [1, 2, 2]] )

flat_answer=F[(idx[:,0],idx[:,1 ],idx[:,2])]
# array( [3, 3, 1, 3, 2, 2, 1, 3, 3] )

answer = np.reshape(flat_answer,np.shape(amax)))
# array( [[3, 3, 1],
#         [3, 2, 2],
#         [1, 3, 3]] )
</code>```

The trick is to make a 3D array, form A1, A2, A3. then use argmax() to get the proper index.

I'm sure there is a "smart" numpy indexing way to reduce the dimension of F based on argmax() result. But my work around was to use ndenumerate() and list comprehension to build a flattened array with the correct values via multidimensional indexing, then reshape it to (3,3) again.

Edit, better explanation:

ndenumerate() returns a generator of tuples with the coordinate and value for each position in the array, ie. for the array

```<code>[ [ 1, 2 ],
  [ 3, 4 ] ]
</code>```

It will return the tuples:

```<code>( ( 0, 0 ), 1 )
( ( 0, 1 ), 2 )
( ( 1, 0 ), 3 )
( ( 1, 1 ), 4 )
</code>```

But the values of amax are already coordinates in the 3rd dimension of D and F, so we concatenate the outputs of ndenumerate(amax) to build a coordinates of F

```<code>ndenumerate        coordinate
((x1, x2 ), v ) -> (v, x1, x2)
</code>```

The last 2 lines of code, use the coordinates to project the answers from the 3x3x3 array F to a 3x3 answer using numpy indexing rules.

It's equivalent to doing the following mapping:

```<code>clearer_answer = np.zeros(np.shape(amax))
for x,y in np.ndenumerate(amax):
    clearer_answer[x] = F[(y,x[0],x[1])]
</code>```

Body:
I'm have trouble writing this question out so maybe best just to illustrate. In short I have two sets of three arrays of the same shape. Using the first set, for each element, I would like to find which array has the max value in that position and return the value from the second set. While the example has each 3 x 3 shaped array as a different object they could just as easily be a (3 ,3 ,3).

The set to find the max value:

import numpy as np
A1 = np.array([[13, 16, 17], [32, 16, 11], [46, 30, 14]], dtype='uint8')
B1 = np.array([[31, 46, 41], [19, 29, 45], [36, 30, 46]], dtype='uint8')
C1 = np.array([[36, 35, 26], [19, 40, 24], [5, 20, 46]], dtype='uint8')

The set to use as the return value:

A2 = np.array([[1, 1, 4], [3, 1, 4], [1, 3, 2]], dtype='uint8')
B2 = np.array([[2, 3, 1], [4, 4, 2], [1, 1, 3]], dtype='uint8')
C2 = np.array([[3, 2, 3], [1, 2, 3], [2, 4, 4]], dtype='uint8')

If it's a two step solution the first would return an array like:

mx1
array([['C', 'B', 'B'],
       ['A', 'C', 'B'],
       ['A', 'A', 'B']], dtype='<U1')

Then the desired output is:

out1
array([[3, 3, 1],
       [3, 2, 2],
       [1, 3, 3]])

Note that in the event of a tie for max value(the last two elements) the value from the first encountered array is the accepted value.

I thought this would be a simple task using some np.max and np.where type magic but I can't seem to wrap my head around this problem correctly.

Body:
import numpy as np

A1 = np.array([[13, 16, 17], [32, 16, 11], [46, 30, 14]], dtype='uint8')
B1 = np.array([[31, 46, 41], [19, 29, 45], [36, 30, 46]], dtype='uint8')
C1 = np.array([[36, 35, 26], [19, 40, 24], [5, 20, 46]], dtype='uint8')

A2 = np.array([[1, 1, 4], [3, 1, 4], [1, 3, 2]], dtype='uint8')
B2 = np.array([[2, 3, 1], [4, 4, 2], [1, 1, 3]], dtype='uint8')
C2 = np.array([[3, 2, 3], [1, 2, 3], [2, 4, 4]], dtype='uint8')

D=np.array([A1,B1,C1])
F=np.array([A2,B2,C2])

amax=np.argmax(D,axis=0)
# array( [[2, 1, 1],
#         [0, 2, 1],
#         [0, 0, 1]] )

#There should be a better way to do this.
idx=np.array([ (y,x[0],x[1]) for x,y in np.ndenumerate(amax)])
# array([[2, 0, 0],
#        [1, 0, 1],
#        [1, 0, 2],
#        [0, 1, 0],
#        [2, 1, 1],
#        [1, 1, 2],
#        [0, 2, 0],
#        [0, 2, 1],
#        [1, 2, 2]] )

flat_answer=F[(idx[:,0],idx[:,1 ],idx[:,2])]
# array( [3, 3, 1, 3, 2, 2, 1, 3, 3] )

answer = np.reshape(flat_answer,np.shape(amax)))
# array( [[3, 3, 1],
#         [3, 2, 2],
#         [1, 3, 3]] )

The trick is to make a 3D array, form A1, A2, A3. then use argmax() to get the proper index.

I'm sure there is a "smart" numpy indexing way to reduce the dimension of F based on argmax() result. But my work around was to use ndenumerate() and list comprehension to build a flattened array with the correct values via multidimensional indexing, then reshape it to (3,3) again.

Edit, better explanation:

ndenumerate() returns a generator of tuples with the coordinate and value for each position in the array, ie. for the array

[ [ 1, 2 ],
  [ 3, 4 ] ]

It will return the tuples:

( ( 0, 0 ), 1 )
( ( 0, 1 ), 2 )
( ( 1, 0 ), 3 )
( ( 1, 1 ), 4 )

But the values of amax are already coordinates in the 3rd dimension of D and F, so we concatenate the outputs of ndenumerate(amax) to build a coordinates of F

ndenumerate        coordinate
((x1, x2 ), v ) -> (v, x1, x2)

The last 2 lines of code, use the coordinates to project the answers from the 3x3x3 array F to a 3x3 answer using numpy indexing rules.

It's equivalent to doing the following mapping:

clearer_answer = np.zeros(np.shape(amax))
for x,y in np.ndenumerate(amax):
    clearer_answer[x] = F[(y,x[0],x[1])]


问:
Make jackson fail on serialization attempt of a class
Is there is any simple way to make Jackson fail to serialize a specific class?

Basically I want to make sure that class containing some sensitive data doesn't leak anywhere and since we log both in text and json I'm afraid it may end up getting logged as json as a part of some bigger object. (sure I could make it serialize to ***** string, but I think error makes it more clear that it's not supposed to even be used there).

My only idea right now is custom Serizalizer that just throws an exception but I was wondering if there is some simpler way to tell Jackson to stay away from that class.

答:
```<code>public class YourBlackListingSerializer extends StdSerializer<YourPojo> {

    public YourBlackListingSerializer() {
        this(null);
    }

    public YourBlackListingSerializer(Class<YourPojo> t) {
        super(t);
    }

    @Override
    public void serialize(
      Item value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        throw new CustomException("This class can't be serialized");
    }
}
</code>```

This should work.

Then you register the serializer

```<code>ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addSerializer(YourPojo.class, newYourBlackListingSerializer());
mapper.registerModule(module);
</code>```

However if you want to ignore just the fields then

```<code>@JsonIgnore
private String password;

@JsonIgnore
public String getPassword() {
    return password;
}

@JsonProperty
public void setPassword(final String password) {
    this.password = password;
}
</code>```

Body:
public class YourBlackListingSerializer extends StdSerializer<YourPojo> {

    public YourBlackListingSerializer() {
        this(null);
    }

    public YourBlackListingSerializer(Class<YourPojo> t) {
        super(t);
    }

    @Override
    public void serialize(
      Item value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        throw new CustomException("This class can't be serialized");
    }
}

This should work.

Then you register the serializer

ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addSerializer(YourPojo.class, newYourBlackListingSerializer());
mapper.registerModule(module);

However if you want to ignore just the fields then

@JsonIgnore
private String password;

@JsonIgnore
public String getPassword() {
    return password;
}

@JsonProperty
public void setPassword(final String password) {
    this.password = password;
}


问:
How to track down how fiddler's auto responder works?
Which win32 API should I set bp on to investigate how it does http proxy?

UPDATE

How does fiddler manage to capture all http requests of all processes?

I know it has a built-in http proxy server,but how does it make all processes use its http proxy?

答:
See this for How to programmatically query and set proxy settings under Internet Explorer

I would guess that it uses [GetTcpTable2][2] and looks up the entries for the connection in the table.


问:
Missing type map configuration or unsupported mapping.while trying to assign the data to DTO object
I am using AutoMapper.Extensions.Microsoft.DependencyInjection. I am using the Automapper NuGet package: AutoMapper.Extensions.Microsoft.DependencyInjection (7.0.0) for ASP.NET Core 3.1 application.

Here goes my domain object: file ResourceGroup.cs

```<code>public class ResourceGroups
{
    public string id
    {
        get;
        set;
    }

    public int ResourceGroupId
    {
        get;
        set;
    }

    public bool IsPublished
    {
        get;
        set;
    }

    public int? Position
    {
        get;
        set;
    }

    public string CreatedBy
    {
        get;
        set;
    }

    public string CreatedDate
    {
        get;
        set;
    }

    public string UpdatedBy
    {
        get;
        set;
    }

    public string UpdatedDate
    {
        get;
        set;
    }

    public int? ResourceGroupContentId
    {
        get;
        set;
    }

    public int LanguageId
    {
        get;
        set;
    }

    public string GroupName
    {
        get;
        set;
    }
}
</code>```

Here goes my DTO object: file ResourceGroupDTO.cs

```<code>public class ResourceGroupDTO
{
    public int ResourceGroupId
    {
        get;
        set;
    }

    public int? Position
    {
        get;
        set;
    }

    [JsonProperty("groupname")]
    [RegularExpression(Constants.GeneralStringRegularExpression)]
    public string GroupName
    {
        get;
        set;
    }
}
</code>```

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    // Auto Mapper Configurations
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new MappingProfile());
    }

    );
    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);
}
</code>```

MappingProfile.cs

```<code>public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<ResourceGroups, ResourceGroupDTO>();
        CreateMap<List<ResourceGroups>, List<ResourceGroupDTO>>();
    }
}
</code>```

file ResourceGroupService.cs

```<code>public class ResourceGroupService : IResourceGroupService
{
    private readonly DemoDbContext _dbContext;
    private readonly ICommonService _commonService;
    private readonly IMapper _mapper;
    public ResourceGroupService(DemoDbContext dbContext, ICommonService commonService, IMapper mapper)
    {
        _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
        _commonService = commonService ?? throw new ArgumentNullException(nameof(commonService));
        _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
    }

    public async Task<ResourceGroupDTO> GetResourceGroupDetailsAsync(int resourceGroupId, int languageId)
    {
        var resourceGroup = await _dbContext.ResourceGroups.Where(rg => rg.ResourceGroupId.Equals(resourceGroupId) && rg.IsPublished.Equals(true))
                                                               .Select(rg => new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId })
                                                               .AsNoTracking().ToListAsync();
        var resGroup = resourceGroup.FirstOrDefault(rg => rg.LanguageId.Equals(languageId));
        return _mapper.Map<ResourceGroupDTO>(resGroup);
    }
}
</code>```

While debugging the above code I get the below error:

```<code>Missing type map configuration or unsupported mapping. \n \nMapping types :  \
n<> f__AnonymousType4 ` 4 ->
ResourceGroupDTO \n<> f__AnonymousType4 ` 4
[
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ,
[System.Nullable ` 1[
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ] ,
System.Private.CoreLib , Version =  4.0  .0  .0 ,  Culture =  neutral , PublicKeyToken =  7  cec85d7bea7798e ] , [System.String, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ,
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ] ->
Author.Query.Persistence.DTO.ResourceGroupDTO \n --  ->AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping. \n \nMapping types :  \
n<> f__AnonymousType4 ` 4 ->
</code>```

答:
You're trying to map an anonymous type, i.e.

```<code>new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId }
</code>```

onto a ResourceGroupDTO, hence the error.
To quickly fix your error you could just change the above to

```<code>new ResourceGroupDTO { ResourceGroupId = rg.ResourceGroupId, Position = rg.Position, GroupName = rg.GroupName, LanguageId = rg.LanguageId }
</code>```

and then add LanguageId to ResourceGroupDTO and get rid of the mapper.

But what you should really be using is ProjectTo and you should change your .FirstOrDefault to a .Where - to make your query more efficient, in the format shown below:

```<code>await _dbContext.ResourceGroups
.AsNoTracking()
.Where(/* Put your where here */)
.ProjectTo<ResourceGroupDTO>(_mapper.Configuration)
.FirstOrDefaultAsync();
</code>```

You can also simplify your startup

Body:
I am using AutoMapper.Extensions.Microsoft.DependencyInjection. I am using the Automapper NuGet package: AutoMapper.Extensions.Microsoft.DependencyInjection (7.0.0) for ASP.NET Core 3.1 application.

Here goes my domain object: file ResourceGroup.cs

public class ResourceGroups
{
    public string id
    {
        get;
        set;
    }

    public int ResourceGroupId
    {
        get;
        set;
    }

    public bool IsPublished
    {
        get;
        set;
    }

    public int? Position
    {
        get;
        set;
    }

    public string CreatedBy
    {
        get;
        set;
    }

    public string CreatedDate
    {
        get;
        set;
    }

    public string UpdatedBy
    {
        get;
        set;
    }

    public string UpdatedDate
    {
        get;
        set;
    }

    public int? ResourceGroupContentId
    {
        get;
        set;
    }

    public int LanguageId
    {
        get;
        set;
    }

    public string GroupName
    {
        get;
        set;
    }
}

Here goes my DTO object: file ResourceGroupDTO.cs

public class ResourceGroupDTO
{
    public int ResourceGroupId
    {
        get;
        set;
    }

    public int? Position
    {
        get;
        set;
    }

    [JsonProperty("groupname")]
    [RegularExpression(Constants.GeneralStringRegularExpression)]
    public string GroupName
    {
        get;
        set;
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Auto Mapper Configurations
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new MappingProfile());
    }

    );
    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);
}

MappingProfile.cs

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<ResourceGroups, ResourceGroupDTO>();
        CreateMap<List<ResourceGroups>, List<ResourceGroupDTO>>();
    }
}

file ResourceGroupService.cs

public class ResourceGroupService : IResourceGroupService
{
    private readonly DemoDbContext _dbContext;
    private readonly ICommonService _commonService;
    private readonly IMapper _mapper;
    public ResourceGroupService(DemoDbContext dbContext, ICommonService commonService, IMapper mapper)
    {
        _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
        _commonService = commonService ?? throw new ArgumentNullException(nameof(commonService));
        _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
    }

    public async Task<ResourceGroupDTO> GetResourceGroupDetailsAsync(int resourceGroupId, int languageId)
    {
        var resourceGroup = await _dbContext.ResourceGroups.Where(rg => rg.ResourceGroupId.Equals(resourceGroupId) && rg.IsPublished.Equals(true))
                                                               .Select(rg => new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId })
                                                               .AsNoTracking().ToListAsync();
        var resGroup = resourceGroup.FirstOrDefault(rg => rg.LanguageId.Equals(languageId));
        return _mapper.Map<ResourceGroupDTO>(resGroup);
    }
}

While debugging the above code I get the below error:

Missing type map configuration or unsupported mapping. \n \nMapping types :  \
n<> f__AnonymousType4 ` 4 ->
ResourceGroupDTO \n<> f__AnonymousType4 ` 4
[
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ,
[System.Nullable ` 1[
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ] ,
System.Private.CoreLib , Version =  4.0  .0  .0 ,  Culture =  neutral , PublicKeyToken =  7  cec85d7bea7798e ] , [System.String, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ,
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ] ->
Author.Query.Persistence.DTO.ResourceGroupDTO \n --  ->AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping. \n \nMapping types :  \
n<> f__AnonymousType4 ` 4 ->

Body:
You're trying to map an anonymous type, i.e.

new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId }

onto a ResourceGroupDTO, hence the error.
To quickly fix your error you could just change the above to

new ResourceGroupDTO { ResourceGroupId = rg.ResourceGroupId, Position = rg.Position, GroupName = rg.GroupName, LanguageId = rg.LanguageId }

and then add LanguageId to ResourceGroupDTO and get rid of the mapper.

But what you should really be using is ProjectTo and you should change your .FirstOrDefault to a .Where - to make your query more efficient, in the format shown below:

await _dbContext.ResourceGroups
.AsNoTracking()
.Where(/* Put your where here */)
.ProjectTo<ResourceGroupDTO>(_mapper.Configuration)
.FirstOrDefaultAsync();

You can also simplify your startup


问:
How can I add exception for when user inputs a negative number
I'm trying to add an exception to recognise when someone inputs a negative number, and respond with something to say you can only input a positive number

```<code>print('How many cats do you have?')
numCats = input()
try:
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')
</code>```

At the moment it will respond to the user inputting a string instead of an integer but I want it to be able to respond to the user inputting something like -4 by printing 'You cant use negative numbers'.

Totally new to Python, so any advice on how to add this in would be very much appreciated, thank you.

答:
print('How many cats do you have?')
try:
    numCats = int(input()) #Moving the int() around input() means we aren't calling int() for every if branch.
    #Also, need to move that in here, so it gets caught by the try/except
    if numCats >= 4:
        print('Thats a lot of cats.')
    elif numCats < 0:
        print('You need a positive amount of cats.') #just printing instead of using a raise statement, an exception is unnecessary
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')
```

Body:
I'm trying to add an exception to recognise when someone inputs a negative number, and respond with something to say you can only input a positive number

print('How many cats do you have?')
numCats = input()
try:
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')

At the moment it will respond to the user inputting a string instead of an integer but I want it to be able to respond to the user inputting something like -4 by printing 'You cant use negative numbers'.

Totally new to Python, so any advice on how to add this in would be very much appreciated, thank you.


问:
Split Comma Separated values into multiple column
I have a requirement where I have a column in my SQL table in this format:

How to split the data using comma delimiter and insert it into newly added columns in the same table?

答:
Demo on db<>fiddle

It seems to me you need to use CASE WHEN END to achieve it.

```<code>select value, case when CHARINDEX('1', value) > 0 then '1' else '' end col1,
       case when CHARINDEX('2', value) > 0 then '2' else '' end col2,
       case when CHARINDEX('3', value) > 0 then '3' else '' end col3,
       case when CHARINDEX('4', value) > 0 then '4' else '' end col4
from #a
</code>```

Output

Updated
Demo

In case of the value may be ('11,2,3'), You should use STRING_SPLIT like below to get the exact result.

```<code>select value,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '1') then '1' else '' end col1,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '2') then '2' else '' end col2,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '3') then '3' else '' end col3,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '4') then '4' else '' end col4
from #a
</code>```

Body:
Demo on db<>fiddle

It seems to me you need to use CASE WHEN END to achieve it.

select value, case when CHARINDEX('1', value) > 0 then '1' else '' end col1,
       case when CHARINDEX('2', value) > 0 then '2' else '' end col2,
       case when CHARINDEX('3', value) > 0 then '3' else '' end col3,
       case when CHARINDEX('4', value) > 0 then '4' else '' end col4
from #a

Output

Updated
Demo

In case of the value may be ('11,2,3'), You should use STRING_SPLIT like below to get the exact result.

select value,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '1') then '1' else '' end col1,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '2') then '2' else '' end col2,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '3') then '3' else '' end col3,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '4') then '4' else '' end col4
from #a


问:
Add a new column in parquet and import into HBase
Should I do something special to notify HBase that a new column has been added to the parquet (schema changed)?

Or it's like MongoDB that I can directly insert the new parquet in HBase (using BufferedMutator)?

答:
As long as you are writing to the existing column family then No need to notify HBase, As HBase dynamically stores all columns into defined column family (we just need to define column family and no need to define any column qualifier to Column families).

Just write the parquet data to HBase then HBase table will have the new column added for the specific rowkey.


问:
How to have different banner on top of my site using @media?
I am trying to get my website to have a separate top banner when in desktop mode to mobile mode with responsive @media tags

So, I have been struggling to understand what I am doing wrong?  I am trying to make it so that in desktop mode it will use the desktop top header banner which it does but then when it gets to about 850px width it will then switch to the mobile top header which are icons instead of text along the header.

No matter what I try it doesn't seem to work and both headers are present no matter what width the website is at.

I have tried using code such as this;

```<code>@media (max-width:850px){
.mobile_menu{
    display:none !important;
    }
}

@media (max-width:2000px min-width:850px){
.top-menu-container{
    display:none !important;
    }
}
</code>```

Please if anyone can help much appreciated and I apologize in advance if I am just being stupid and not realizing something as I am fairly new to the whole @media coding in CSS.

答:
This is what you are looking for:

```<code>@media only screen and (max-width:850px) {
    /* STYLES HERE */
}

@media only screen and (min-width:851px) and (max-width:2000px) {
    /* STYLES HERE */
}
</code>```

you need to use and.

Body:
I am trying to get my website to have a separate top banner when in desktop mode to mobile mode with responsive @media tags

So, I have been struggling to understand what I am doing wrong?  I am trying to make it so that in desktop mode it will use the desktop top header banner which it does but then when it gets to about 850px width it will then switch to the mobile top header which are icons instead of text along the header.

No matter what I try it doesn't seem to work and both headers are present no matter what width the website is at.

I have tried using code such as this;

@media (max-width:850px){
.mobile_menu{
    display:none !important;
    }
}

@media (max-width:2000px min-width:850px){
.top-menu-container{
    display:none !important;
    }
}

Please if anyone can help much appreciated and I apologize in advance if I am just being stupid and not realizing something as I am fairly new to the whole @media coding in CSS.

Body:
This is what you are looking for:

@media only screen and (max-width:850px) {
    /* STYLES HERE */
}

@media only screen and (min-width:851px) and (max-width:2000px) {
    /* STYLES HERE */
}

you need to use and.


问:
System.MissingMethodException - 3.5 SP1 versioning hell
After deploying an ASP.net webservice to my production server i got this exception:

System.MissingMethodException

Method not found: 'Boolean
  System.Threading.WaitHandle.WaitOne(Int32)'

The MSDN documentation states:

Version Information
  .NET Framework
  Supported in: 3.5 SP1, 3.0 SP2, 2.0 SP2

so the reason of this error is that my server was not updated to the latest service pack.

The question is:

Why does the code start? IMO if the target framework version is different the app should not start at all.

How can I assure that my code can run on the target machine framework version before JIT?

This is crazy. I think Microsoft should take versioning issues more seriously.

答:
I agree. The problem is that the assembly version numbers did not change.

When transitioning to .NET 3.5 SP1 I made sure that developers were not using SP1-specific APIs by ensuring the build server did not have the SP installed (ie. the build server framework version matched the target machine framework version). Then, once we were ready, SP1 was installed on the build server. A similar approach could have saved you from the pain.

OwnerDisplayName: Luca Martinetti

OwnerDisplayName: Kent Boogaart

LastEditorDisplayName: Kent Boogaart


问:
How to get permission to debug postgres?
I have a system that uses C methods as functions in a Postgres database.  When I try to run gdb with my user account I get this:
ptrace: Operation not permitted

It looks like a permission thing.  It seemed to work when I ran gdb as the "postgres" user.  I would like to continue running postgres as the "postgres" user and not have to su postgres when I want to debug.  Can I somehow grant my user account "ptrace" permission for the process in question?  Adding myself to the "postgres" group didn't seem to help.

EDIT:  I found this on the ptrace man page:

```
EPERM  The specified process cannot be traced.  This could  be  because
              the  parent has insufficient privileges (the required capability
              is CAP_SYS_PTRACE); non-root processes  cannot  trace  processes
              that  they  cannot  send  signals  to or those running set-user-
              ID/set-group-ID programs, for obvious  reasons.   Alternatively,
              the process may already be being traced, or be init(8) (PID 1).
```

So how can I give CAP_SYS_TRACE privileges to my user?

答:
It seems CAP_SYS_TRACE is controlled by LIDS which may or may not be installed on your computer.

If you are doing heavy development on postgres you might prefer to run an instance of postgres under your own account - this is what I do with a number of servers I work on.

ContentLicense: CC BY-SA 2.5

Body:
I have a system that uses C methods as functions in a Postgres database.  When I try to run gdb with my user account I get this:
ptrace: Operation not permitted

It looks like a permission thing.  It seemed to work when I ran gdb as the "postgres" user.  I would like to continue running postgres as the "postgres" user and not have to su postgres when I want to debug.  Can I somehow grant my user account "ptrace" permission for the process in question?  Adding myself to the "postgres" group didn't seem to help.

EDIT:  I found this on the ptrace man page:

EPERM  The specified process cannot be traced.  This could  be  because
              the  parent has insufficient privileges (the required capability
              is CAP_SYS_PTRACE); non-root processes  cannot  trace  processes
              that  they  cannot  send  signals  to or those running set-user-
              ID/set-group-ID programs, for obvious  reasons.   Alternatively,
              the process may already be being traced, or be init(8) (PID 1).

So how can I give CAP_SYS_TRACE privileges to my user?


问:
Get set of unique values after joining float64 and integer64
I'm trying to group and aggregate a df composed of object, float64 and int64

```<code>(example df)
Number    Day        Colour   City    ...
123       Monday     Red      London  ...
234       Monday     Blue     Paris   ...
234       Wednesday  Yellow   Paris   ...
345       Tuesday    Green    Berlin  ...
</code>```

produce a new df like this

```<code>Number    Day                Colour        City    ...
123       Monday             Red           London  ...
234       Monday, Wednesday  Blue, Yellow  Paris   ...
345       Tuesday            Green         Berlin  ...
</code>```

I initially tried

df.groupby('Number').agg(lambda s: ', '.join({*s}))

However, .join does not handle int64 and float64 well and results in loss of columns.

df = df.groupby('Number', as_index=False).agg(lambda x: ', '.join([str(i) for i in x])) solves the issue of joining float64 and int64 but results in this

```<code>Number    Day                Colour        City           ...
123       Monday             Red           London         ...
234       Monday, Wednesday  Blue, Yellow  Paris, Paris   ...
345       Tuesday            Green         Berlin         ...
</code>```

Is there a way to get a set of unique values ({*s}) and join while dealing with floats and integers? What I don't want are duplicate strings where rows have been aggregated (i.e. Paris, Paris).

答:
Let us use unique

```<code>df.groupby('Number').agg(lambda s: ', '.join(s.unique().astype(str)))
</code>```

Body:
I'm trying to group and aggregate a df composed of object, float64 and int64

(example df)
Number    Day        Colour   City    ...
123       Monday     Red      London  ...
234       Monday     Blue     Paris   ...
234       Wednesday  Yellow   Paris   ...
345       Tuesday    Green    Berlin  ...

produce a new df like this

Number    Day                Colour        City    ...
123       Monday             Red           London  ...
234       Monday, Wednesday  Blue, Yellow  Paris   ...
345       Tuesday            Green         Berlin  ...

I initially tried

df.groupby('Number').agg(lambda s: ', '.join({*s}))

However, .join does not handle int64 and float64 well and results in loss of columns.

df = df.groupby('Number', as_index=False).agg(lambda x: ', '.join([str(i) for i in x])) solves the issue of joining float64 and int64 but results in this

Number    Day                Colour        City           ...
123       Monday             Red           London         ...
234       Monday, Wednesday  Blue, Yellow  Paris, Paris   ...
345       Tuesday            Green         Berlin         ...

Is there a way to get a set of unique values ({*s}) and join while dealing with floats and integers? What I don't want are duplicate strings where rows have been aggregated (i.e. Paris, Paris).

Body:
Let us use unique

df.groupby('Number').agg(lambda s: ', '.join(s.unique().astype(str)))


问:
How to early break reduce() method?
How can I break the iteration of reduce() method?

for:

```<code>for (var i = Things.length - 1; i >= 0; i--) {
  if(Things[i] <= 0){
    break;
  }
};
</code>```

reduce()

```<code>Things.reduce(function(memo, current){
  if(current <= 0){
    //break ???
    //return; <-- this will return undefined to memo, which is not what I want
  }
}, 0)
</code>```

答:
I solved it like follows, for example in the some method where short circuiting can save a lot:

const someShort = (list, fn) => {
  let t;
  try {
    return list.reduce((acc, el) => {
      t = fn(el);
      console.log('found ?', el, t)
      if (t) {
        throw ''
      }
      return t
    }, false)
  } catch (e) {
    return t
  }
}

const someEven = someShort([1, 2, 3, 1, 5], el => el % 2 === 0)

console.log(someEven)```
</div>
</div>
</p>
<p>UPDATE</p>
<p>Away more generic answer could be  something like the following</p>
<pre class="lang-js prettyprint-override"><code>const escReduce = (arr, fn, init, exitFn) => {
    try {
      return arr.reduce((...args) => {
          if (exitFn && exitFn(...args)) {
              throw args[0]
          }
          return fn(...args)
        }, init)
    } catch(e){ return e }
}

escReduce(
  Array.from({length: 100}, (_, i) => i+1),
  (acc, e, i) => acc * e,
    1,
    acc => acc > 1E9
); // 6227020800
</code>```

give we pass an optional exitFn which decides to break or not

Title: How to early break reduce() method?

Body:
How can I break the iteration of reduce() method?

for:

for (var i = Things.length - 1; i >= 0; i--) {
  if(Things[i] <= 0){
    break;
  }
};

reduce()

Things.reduce(function(memo, current){
  if(current <= 0){
    //break ???
    //return; <-- this will return undefined to memo, which is not what I want
  }
}, 0)

Body:
I solved it like follows, for example in the some method where short circuiting can save a lot:

const someShort = (list, fn) => {
  let t;
  try {
    return list.reduce((acc, el) => {
      t = fn(el);
      console.log('found ?', el, t)
      if (t) {
        throw ''
      }
      return t
    }, false)
  } catch (e) {
    return t
  }
}

const someEven = someShort([1, 2, 3, 1, 5], el => el % 2 === 0)

console.log(someEven)

UPDATE

Away more generic answer could be  something like the following

const escReduce = (arr, fn, init, exitFn) => {
    try {
      return arr.reduce((...args) => {
          if (exitFn && exitFn(...args)) {
              throw args[0]
          }
          return fn(...args)
        }, init)
    } catch(e){ return e }
}

escReduce(
  Array.from({length: 100}, (_, i) => i+1),
  (acc, e, i) => acc * e,
    1,
    acc => acc > 1E9
); // 6227020800

give we pass an optional exitFn which decides to break or not


问:
How does one add certificate_authorities to CertificateRequest message in TLSv1.3
I'm setting up mutual authentication using TLS 1.3 using a spring boot server and curl client for testing. My truststore containts two certificate chains which are loaded correctly - in fact the mutual authentication works in this test setup.

However, based on the RFC8446 spec I'm trying to get the CertificateRequest message in the SSL Handshake to contain the  certificate_authorities extension.

The logging (-Djavax.net.debug=all) shows the certificate request message from the sever, without certificate_authorities.

```<code>javax.net.ssl|DEBUG|13|https-jsse-nio-8443-exec-2|2020-02-17 14:24:15.419 CET|CertificateRequest.java:864|Produced CertificateRequest message (
"CertificateRequest": {
  "certificate_request_context": "",
  "extensions": [
    "signature_algorithms (13)": {
      "signature schemes": [ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp521r1_sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa_pss_pss_sha256, rsa_pss_pss_sha384, rsa_pss_pss_sha512, rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, ecdsa_sha1, rsa_pkcs1_sha1]
    },
    "signature_algorithms_cert (50)": {
      "signature schemes": [ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp521r1_sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa_pss_pss_sha256, rsa_pss_pss_sha384, rsa_pss_pss_sha512, rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, ecdsa_sha1, rsa_pkcs1_sha1]
    }
  ]
}
)
</code>```

This extension is optional to send in the CertificateRequest, but I would like to include it in this message so that the real client device will be able to send the correct certificate to the server based on this.

答:
While researching this issue I came across JDK-8206925 which states that

The current TLS 1.3 implementation does not support this function [...]

So apparently its just an open issue for java (or at least the openJDK java that I use).

I'm happy to be proven wrong though..

Body:
I'm setting up mutual authentication using TLS 1.3 using a spring boot server and curl client for testing. My truststore containts two certificate chains which are loaded correctly - in fact the mutual authentication works in this test setup.

However, based on the RFC8446 spec I'm trying to get the CertificateRequest message in the SSL Handshake to contain the  certificate_authorities extension.

The logging (-Djavax.net.debug=all) shows the certificate request message from the sever, without certificate_authorities.

javax.net.ssl|DEBUG|13|https-jsse-nio-8443-exec-2|2020-02-17 14:24:15.419 CET|CertificateRequest.java:864|Produced CertificateRequest message (
"CertificateRequest": {
  "certificate_request_context": "",
  "extensions": [
    "signature_algorithms (13)": {
      "signature schemes": [ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp521r1_sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa_pss_pss_sha256, rsa_pss_pss_sha384, rsa_pss_pss_sha512, rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, ecdsa_sha1, rsa_pkcs1_sha1]
    },
    "signature_algorithms_cert (50)": {
      "signature schemes": [ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp521r1_sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa_pss_pss_sha256, rsa_pss_pss_sha384, rsa_pss_pss_sha512, rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, ecdsa_sha1, rsa_pkcs1_sha1]
    }
  ]
}
)

This extension is optional to send in the CertificateRequest, but I would like to include it in this message so that the real client device will be able to send the correct certificate to the server based on this.


问:
not able to make a call to POST from async task

Possible Duplicate:

  Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I am getting the following exception on making a call to a method, which eventually makes a  POST method call from my async task:

"Cant Create Handler Inside Thread That Has Not Called Looper Prepare in Android" .

I am using async task to show progress dialog.

Can you please help me.

Thanks

答:
Duplicate of Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

In short: the progress dialog's show() method must be called from the UI thread, not from the background thread. Use onProgressUpdate or onPreExecute for that.


问:
Check for condition in GROUP BY?
Take this example data:

```<code>ID    Status    Date
1     Pending   2/10/2020
2     Pending   2/10/2020
3     Pending   2/10/2020
2     Pending   2/10/2020
2     Pending   2/10/2020
1     Complete  2/15/2020
</code>```

I need an SQL statement that will group all the data but bring back the current status. So for ID 1 the group by needs a condition that only returns the Completed row and also returned the pending rows for ID 2 and 3.

I am not 100% how to write in the condition for this.

Maybe something like:

```<code>SELECT ID, Status, Date
FROM table
GROUP BY ID, Status, Date
ORDER BY ID
</code>```

The problem with this is the resulting data would look like:

```<code>ID    Status    Date
1     Pending   2/10/2020
1     Complete  2/15/2020
2     Pending   2/10/2020
3     Pending   2/10/2020
</code>```

But I need:

```<code>ID    Status    Date
1     Complete  2/15/2020
2     Pending   2/10/2020
3     Pending   2/10/2020
</code>```

What can I do to check for the Completed status so I can only return Completed in the group by?

答:
Do only GROUP BY the ID column. Use MIN() to chose Complete before Pending.

```<code>SELECT ID, MIN(Status)
FROM table
GROUP BY ID
ORDER BY ID
</code>```

Title: Check for condition in GROUP BY?

Body:
Take this example data:

ID    Status    Date
1     Pending   2/10/2020
2     Pending   2/10/2020
3     Pending   2/10/2020
2     Pending   2/10/2020
2     Pending   2/10/2020
1     Complete  2/15/2020

I need an SQL statement that will group all the data but bring back the current status. So for ID 1 the group by needs a condition that only returns the Completed row and also returned the pending rows for ID 2 and 3.

I am not 100% how to write in the condition for this.

Maybe something like:

SELECT ID, Status, Date
FROM table
GROUP BY ID, Status, Date
ORDER BY ID

The problem with this is the resulting data would look like:

ID    Status    Date
1     Pending   2/10/2020
1     Complete  2/15/2020
2     Pending   2/10/2020
3     Pending   2/10/2020

But I need:

ID    Status    Date
1     Complete  2/15/2020
2     Pending   2/10/2020
3     Pending   2/10/2020

What can I do to check for the Completed status so I can only return Completed in the group by?

Body:
Do only GROUP BY the ID column. Use MIN() to chose Complete before Pending.

SELECT ID, MIN(Status)
FROM table
GROUP BY ID
ORDER BY ID


问:
FullCalendar v4 add onclick eventListener to events displayed on eventLimitClick popover
I have a custom development with FullCalendar v4 js and I'm encountering a problem with eventLimitClick method.

When I click on it I want all events displayed inside popover to have a custom onclick eventListener for me to display aditional information of this current event in another custom popup.

This is my method so far:

```<code>eventLimitClick : function(info){
    info.segs.forEach(function(seg){
        seg.el.querySelector('div.fc-content').addEventListener('click', function(event){
            console.log('event definition', event);
        });
    });
    return "popover";
}
</code>```

But this is adding the listener to the elements I already see in my calendar. I also tried with hiddenSegs instead of segs but it's not working.

So is there any way to achieve this without having to create a custom popup with all the events?

** EDIT ** [included code]

calendar object

```<code>     {
        locale : 'en',
        plugins : ['dayGrid','timeGrid','list','interaction'],
        header : {
            left : 'prev,next today',
            center : 'title',
            right : 'dayGridWeek, dayGridMonth, dayGridDay'
        },
        allDaySlot : false,
        aspectRatio : 1.8,
        displayEventTime : false,
        editable : false,
        navLinks : true,
        eventLimit : true,
        views : {
            dayGridMonth : {
                eventLimit : 2
            }
        },
        events : this.eventLIST,
        datesRender : this.calendarviewRender,
        eventClick : this.calendareventClick,
        eventRender : this.calendareventRender
     }
</code>```

datesRender, eventClick and eventRender functions:

```<code>calendarviewRender = (info) => {
    //set current and end dates
    this.endDate = info.view.activeEnd;
    this.currentDate = info.view.activeStart;
    //retrieve fresh event/task info
    this.refreshCalendar();
}
calendareventClick = (info) => {
    this.info = {id : info.event.id,
                 tipo : info.event.extendedProps.tipo,
                 tipoObj : info.event.extendedProps.tipoObj,
                 isClosed : info.event.extendedProps.isClosed && info.event.extendedProps.isClosed !== null ? (info.event.extendedProps.isClosed === 'false' ? false : true) : false,
                 campos : info.event.extendedProps.lCamposInfo};
    //allow second button
    this.info.displaysecondbutton = !this.info.isClosed && this.info.tipoObj === 'Task';
    //allow popup display
    this.allowpopup = true;
    info.jsEvent.preventDefault();
}
calendareventRender = (info) => {
    let html = "<i class='fa fa-" + info.event.extendedProps.icon + " fa-lg'></i>";
    info.el.querySelector('div.fc-content').style.cssText = 'height: 100%;';
    //if month view apply padding
    if(info.view.type.includes('dayGrid')) info.el.querySelector('div.fc-content').classList.add('slds-p-around_x-small');
    //center elements
    info.el.querySelector('div.fc-content').classList.add('slds-align_absolute-center');
    //append icon
    info.el.querySelector('div.fc-content').innerHTML = html;
}
</code>```

I also removed eventLimitClick.

答:
Based on your comments i see you were working with lightning-web-components.

I was facing same issue as you when working with LWC on salesforce.

I was able to solve this by editing main.js in daygrid package and add delay when Popover was getting hidden.

Here is snippet of code

```<code>function Popover(options) {
        var _this = this;
        this.isHidden = true;
        this.margin = 10; // the space required between the popover and the edges of the scroll container
        // Triggered when the user clicks *anywhere* in the document, for the autoHide feature
        this.documentMousedown = function (ev) {
            if (_this.el && !_this.el.contains(ev.target)) {
                setTimeout(function () {
                    _this.hide();
                }, 1000);
            }
        };
        this.options = options;
    }
</code>```

functions starts in line 100 of main.js.
I was using Fullcalendar v4

Body:
I have a custom development with FullCalendar v4 js and I'm encountering a problem with eventLimitClick method.

When I click on it I want all events displayed inside popover to have a custom onclick eventListener for me to display aditional information of this current event in another custom popup.

This is my method so far:

eventLimitClick : function(info){
    info.segs.forEach(function(seg){
        seg.el.querySelector('div.fc-content').addEventListener('click', function(event){
            console.log('event definition', event);
        });
    });
    return "popover";
}

But this is adding the listener to the elements I already see in my calendar. I also tried with hiddenSegs instead of segs but it's not working.

So is there any way to achieve this without having to create a custom popup with all the events?

** EDIT ** [included code]

calendar object

     {
        locale : 'en',
        plugins : ['dayGrid','timeGrid','list','interaction'],
        header : {
            left : 'prev,next today',
            center : 'title',
            right : 'dayGridWeek, dayGridMonth, dayGridDay'
        },
        allDaySlot : false,
        aspectRatio : 1.8,
        displayEventTime : false,
        editable : false,
        navLinks : true,
        eventLimit : true,
        views : {
            dayGridMonth : {
                eventLimit : 2
            }
        },
        events : this.eventLIST,
        datesRender : this.calendarviewRender,
        eventClick : this.calendareventClick,
        eventRender : this.calendareventRender
     }

datesRender, eventClick and eventRender functions:

calendarviewRender = (info) => {
    //set current and end dates
    this.endDate = info.view.activeEnd;
    this.currentDate = info.view.activeStart;
    //retrieve fresh event/task info
    this.refreshCalendar();
}
calendareventClick = (info) => {
    this.info = {id : info.event.id,
                 tipo : info.event.extendedProps.tipo,
                 tipoObj : info.event.extendedProps.tipoObj,
                 isClosed : info.event.extendedProps.isClosed && info.event.extendedProps.isClosed !== null ? (info.event.extendedProps.isClosed === 'false' ? false : true) : false,
                 campos : info.event.extendedProps.lCamposInfo};
    //allow second button
    this.info.displaysecondbutton = !this.info.isClosed && this.info.tipoObj === 'Task';
    //allow popup display
    this.allowpopup = true;
    info.jsEvent.preventDefault();
}
calendareventRender = (info) => {
    let html = "";
    info.el.querySelector('div.fc-content').style.cssText = 'height: 100%;';
    //if month view apply padding
    if(info.view.type.includes('dayGrid')) info.el.querySelector('div.fc-content').classList.add('slds-p-around_x-small');
    //center elements
    info.el.querySelector('div.fc-content').classList.add('slds-align_absolute-center');
    //append icon
    info.el.querySelector('div.fc-content').innerHTML = html;
}

I also removed eventLimitClick.

Body:
Based on your comments i see you were working with lightning-web-components.

I was facing same issue as you when working with LWC on salesforce.

I was able to solve this by editing main.js in daygrid package and add delay when Popover was getting hidden.

Here is snippet of code

function Popover(options) {
        var _this = this;
        this.isHidden = true;
        this.margin = 10; // the space required between the popover and the edges of the scroll container
        // Triggered when the user clicks *anywhere* in the document, for the autoHide feature
        this.documentMousedown = function (ev) {
            if (_this.el && !_this.el.contains(ev.target)) {
                setTimeout(function () {
                    _this.hide();
                }, 1000);
            }
        };
        this.options = options;
    }

functions starts in line 100 of main.js.
I was using Fullcalendar v4


问:
Call an object in a list with name
I need to know if there is a way to use a name for as an index for each member of an object list as in dictionaries.

```<code>import numpy as np

class Marker(object):
    def __init__(self):
        self.name: str
        self.location: np.ndarray

locations = np.random.rand(5,3)
names = ['apple','body','wear','orange','bear']

markers= []
for n,l in zip(names, locations):
    marker = Marker()
    marker.name = n
    marker.location = l
    markers.append(marker)
</code>```

For example, in the above list is there a way to call objects in list with their names? like markers['apple'] instead of markers[0]?

答:
If you want to check if an object exists in a list, you can do so using the in operator:

if marker in markers:
    # do stuff here
```

<p>it seems you want to store a key-value pair of a <code>name</code> being a lookup for a <code>marker</code>. You could instead make <code>markers</code> a dictionary:</p>

<pre class="lang-py prettyprint-override"><code>markers= {}
for n,l in zip(names, locations):
    marker = Marker()
    marker.name = n
    marker.location = l
    markers[n] =marker
</code>```

Then to access a given marker, do a lookup based on the name:

marker = markers['apple']
```

<p>If the only 2 data points being stroed in your <code>Marker</code> class, maybe drop the <code>Marker</code> object altogether and just store the <code>location</code> in the dict instead:</p>

<pre class="lang-py prettyprint-override"><code>markers['apple'] = location
</code>```

Title: Call an object in a list with name

Body:
I need to know if there is a way to use a name for as an index for each member of an object list as in dictionaries.

import numpy as np

class Marker(object):
    def __init__(self):
        self.name: str
        self.location: np.ndarray

locations = np.random.rand(5,3)
names = ['apple','body','wear','orange','bear']

markers= []
for n,l in zip(names, locations):
    marker = Marker()
    marker.name = n
    marker.location = l
    markers.append(marker)

For example, in the above list is there a way to call objects in list with their names? like markers['apple'] instead of markers[0]?

Body:
If you want to check if an object exists in a list, you can do so using the in operator:

if marker in markers:
    # do stuff here

it seems you want to store a key-value pair of a name being a lookup for a marker. You could instead make markers a dictionary:

markers= {}
for n,l in zip(names, locations):
    marker = Marker()
    marker.name = n
    marker.location = l
    markers[n] =marker

Then to access a given marker, do a lookup based on the name:

marker = markers['apple']

If the only 2 data points being stroed in your Marker class, maybe drop the Marker object altogether and just store the location in the dict instead:

markers['apple'] = location


问:
How to search two columns in the same input using Laravel?
I have a function for search in a single column

Here is:

```<code>public function resultados_asesores(Request $request){
  $busqueda = $request->asesor;
  $asesores = strtoupper($busqueda);
  $perimetro = DB::table('tbl_perimetros as a')
    ->select('a.id','a.rif','a.cod_cliente','a.razon_social','a.holdings_id')
    ->leftjoin('tbl_holdings as b','b.id','=','a.holdings_id')
    ->leftjoin('tbl_equipo_postventaatcs as c','c.id','=','a.postventaatc_id')
    ->leftjoin('users as e','e.id','=','c.asesor_id')
    ->select(array('a.id','b.hrif','b.hrazon_social','a.rif','a.razon_social','a.estatus'))
    ->where('e.name','like', '%' . $asesores . '%')
    ->orWhere('e.apellido', 'like', '%' . $asesores . '%')
    ->orWhere('e.idop', 'like', '%' . $asesores . '%')
    ->get();

  if($perimetro->count()) {

    return view('Busqueda.resultados_busquedag',compact('perimetro','busqueda'));
  }

      return view('Busqueda.index');
}
</code>```

I have a problem because I would like to be able to search name and apellido at the same time in the same search... but in this way I can only search name or apellido... if I write in the search both (name and apellido) it returns me and error.. How could I search the two columns at the same time?

this is my input

```<code><form id="asesor" class="form-horizontal" action="{{route('resultados_asesores')}}" method="post">
@csrf
<div class="form-group row">
  <label class="col-md-6 col-form-label" for="asesor"></label>
  <div class="col-md-12">
    <input form="asesor" maxlength="100" autocomplete="off" class="form-control" id="asesor" type="text" name="asesor" placeholder="Introduzca el nombre, apellido o IDOP del asesor a buscar">
    <br>
    <div class="pull-right">
    <button form="asesor" class="btn btn-sm btn-info" type="submit">
      Buscar</button>
  </div>
</div>
</code>```

答:
Write your query like this</p>

```<code>$perimetro = DB::table('tbl_perimetros as a')
        ->select('a.id', 'a.rif', 'a.cod_cliente', 'a.razon_social', 'a.holdings_id')
        ->leftjoin('tbl_holdings as b', 'b.id', '=', 'a.holdings_id')
        ->leftjoin('tbl_equipo_postventaatcs as c', 'c.id', '=', 'a.postventaatc_id')
        ->leftjoin('users as e', 'e.id', '=', 'c.asesor_id')
        ->select(['a.id', 'b.hrif', 'b.hrazon_social', 'a.rif', 'a.razon_social', 'a.estatus'])
        ->where('e.name', 'like', '%'.$asesores.'%')
        ->where('e.apellido', 'like', '%'.$asesores.'%')
        ->orWhere('e.idop', 'like', '%'.$asesores.'%')
        ->get();
</code>```

Body:
I have a function for search in a single column

Here is:

public function resultados_asesores(Request $request){
  $busqueda = $request->asesor;
  $asesores = strtoupper($busqueda);
  $perimetro = DB::table('tbl_perimetros as a')
    ->select('a.id','a.rif','a.cod_cliente','a.razon_social','a.holdings_id')
    ->leftjoin('tbl_holdings as b','b.id','=','a.holdings_id')
    ->leftjoin('tbl_equipo_postventaatcs as c','c.id','=','a.postventaatc_id')
    ->leftjoin('users as e','e.id','=','c.asesor_id')
    ->select(array('a.id','b.hrif','b.hrazon_social','a.rif','a.razon_social','a.estatus'))
    ->where('e.name','like', '%' . $asesores . '%')
    ->orWhere('e.apellido', 'like', '%' . $asesores . '%')
    ->orWhere('e.idop', 'like', '%' . $asesores . '%')
    ->get();

  if($perimetro->count()) {

    return view('Busqueda.resultados_busquedag',compact('perimetro','busqueda'));
  }

      return view('Busqueda.index');
}

I have a problem because I would like to be able to search name and apellido at the same time in the same search... but in this way I can only search name or apellido... if I write in the search both (name and apellido) it returns me and error.. How could I search the two columns at the same time?

this is my input

<form id="asesor" class="form-horizontal" action="{{route('resultados_asesores')}}" method="post">
@csrf

    <input form="asesor" maxlength="100" autocomplete="off" class="form-control" id="asesor" type="text" name="asesor" placeholder="Introduzca el nombre, apellido o IDOP del asesor a buscar">

    <button form="asesor" class="btn btn-sm btn-info" type="submit">
      Buscar</button>

Body:
Write your query like this

$perimetro = DB::table('tbl_perimetros as a')
        ->select('a.id', 'a.rif', 'a.cod_cliente', 'a.razon_social', 'a.holdings_id')
        ->leftjoin('tbl_holdings as b', 'b.id', '=', 'a.holdings_id')
        ->leftjoin('tbl_equipo_postventaatcs as c', 'c.id', '=', 'a.postventaatc_id')
        ->leftjoin('users as e', 'e.id', '=', 'c.asesor_id')
        ->select(['a.id', 'b.hrif', 'b.hrazon_social', 'a.rif', 'a.razon_social', 'a.estatus'])
        ->where('e.name', 'like', '%'.$asesores.'%')
        ->where('e.apellido', 'like', '%'.$asesores.'%')
        ->orWhere('e.idop', 'like', '%'.$asesores.'%')
        ->get();


问:
Firebase Tasks in Swift / iOS
I'm an android developer learning to write my app for iOS using swift. I'm unsure how to run multiple firebase (firestore and realtime database) write tasks asynchronous and return a completion handler. In android I use the Tasks API and have it written as follows:

```<code>Task<Void> firestoreTask = firestoreDB.getDocument("users/someId").update("name", "some name");

Task<Void> realtimeTask = realtimeDB.child("users/someId/name/").setValue("some name");

Tasks.whenAll(firestoreTask, realtimeTask).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // if both tasks are successful
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if at least one of the two task fails
            }
        });
</code>```

I can't seem to figure out how to write such a task in swift. Can someone please point me in the right direction? Thank you.

答:
Following code will help you to solve this problem</p>

```<code>import Foundation

// Create a dispatch group object and add a didset observer to catch error in operation

var dispatchGroup:DispatchGroup? = DispatchGroup(){
    didSet{
        if dispatchGroup == nil{
            // here you can do whetever after at least one of the two task fails
            print("error in FirestoreTask or realtimeTask")
        }
    }
}

// do your firestoreTask in this method
func dofirestoreTask (){
    // Implement your firestore task here //

    let taskResponse = true // Remove this variable with your firestore task response status
    if taskResponse == true{
        dispatchGroup?.leave()
    }else{
        dispatchGroup = nil
    }
}

func dorealtimeTask(){
    // Implement your realTimeTask here task here //
    let taskResponse = true // Remove this variable with your realTime task response status
    if taskResponse == true{
        dispatchGroup?.leave()
    }else{
        dispatchGroup = nil
    }
}

dispatchGroup?.enter()
dofirestoreTask()
dispatchGroup?.enter()
dorealtimeTask()

dispatchGroup?.notify(queue: .main) {
    // here you can do whetever after both tasks are successful
    print("Both Success")
}
</code>```

Title: Firebase Tasks in Swift / iOS

Body:
I'm an android developer learning to write my app for iOS using swift. I'm unsure how to run multiple firebase (firestore and realtime database) write tasks asynchronous and return a completion handler. In android I use the Tasks API and have it written as follows:

Task<Void> firestoreTask = firestoreDB.getDocument("users/someId").update("name", "some name");

Task<Void> realtimeTask = realtimeDB.child("users/someId/name/").setValue("some name");

Tasks.whenAll(firestoreTask, realtimeTask).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // if both tasks are successful
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if at least one of the two task fails
            }
        });

I can't seem to figure out how to write such a task in swift. Can someone please point me in the right direction? Thank you.

Body:
Following code will help you to solve this problem

import Foundation

// Create a dispatch group object and add a didset observer to catch error in operation

var dispatchGroup:DispatchGroup? = DispatchGroup(){
    didSet{
        if dispatchGroup == nil{
            // here you can do whetever after at least one of the two task fails
            print("error in FirestoreTask or realtimeTask")
        }
    }
}

// do your firestoreTask in this method
func dofirestoreTask (){
    // Implement your firestore task here //

    let taskResponse = true // Remove this variable with your firestore task response status
    if taskResponse == true{
        dispatchGroup?.leave()
    }else{
        dispatchGroup = nil
    }
}

func dorealtimeTask(){
    // Implement your realTimeTask here task here //
    let taskResponse = true // Remove this variable with your realTime task response status
    if taskResponse == true{
        dispatchGroup?.leave()
    }else{
        dispatchGroup = nil
    }
}

dispatchGroup?.enter()
dofirestoreTask()
dispatchGroup?.enter()
dorealtimeTask()

dispatchGroup?.notify(queue: .main) {
    // here you can do whetever after both tasks are successful
    print("Both Success")
}


问:
I have downloaded a fastq file from SRA and I have problems reading it into my workspace. Is there another way for reading fastq files into R?

fqsample <- readFastq("/cloud/project/sra_data.fastq.", pattern = "fastq")
  Error: Input/Output
    no input files found
    dirPath: /cloud/project/sra_data.fastq.
    pattern: fastq

答:
It seems like your path or filename is wrong.

Is the . at the end of your filename (.fastq.) intentional or a typo?

Try it without the .:

```<code>fqsample <- readFastq("/cloud/project/sra_data.fastq", pattern = "fastq")
</code>```

Edit

I have just tried the readFastq function myself on a single file. You don't need to specify pattern = "fastq".

To explain it in more detail, you could read your file in two ways:

readFastq("/cloud/project/", pattern = "sra_data.fastq")

Here the first argument is just the path and the second is the file name. If you only provide the path, it would read all files inside the directory.

or:

readFastq("/cloud/project/sra_data.fastq")

Hope this helps.

Body:
It seems like your path or filename is wrong.

Is the . at the end of your filename (.fastq.) intentional or a typo?

Try it without the .:

fqsample <- readFastq("/cloud/project/sra_data.fastq", pattern = "fastq")

Edit

I have just tried the readFastq function myself on a single file. You don't need to specify pattern = "fastq".

To explain it in more detail, you could read your file in two ways:

readFastq("/cloud/project/", pattern = "sra_data.fastq")

Here the first argument is just the path and the second is the file name. If you only provide the path, it would read all files inside the directory.

or:

readFastq("/cloud/project/sra_data.fastq")

Hope this helps.


问:
Android eclipse DDMS - Can't access data/data/ on phone to pull files
While testing my apps, I use emulators and my own phone to see if everything is working ok.  My apps are also writing data to shared preferences and a text file.

I can pull the data from my emulators through the DDMS in eclipse so I can read the data files on my computer, but when I try to open those folders through the DDMS on my phone, nothing happens.  I click the data folder and nothing happens.

My phone is rooted.  Is there any way I could pull the files from my phone?  I know that Android keeps these folders private, but there must be a way.  The emulator is just way too slow.

答:
When I say file system I meant the whole file system. But you can only browse part of the file system on a retail phone, perhaps even most of file system but not ./data. Sorry for any confusion this may have caused.

This is alarming to me because I have a rooted my retail Nexus One and a developer/unlocked Nexus One. Since I rooted my retail Nexus One I can't figure out why I can't browse the whole file system like I can on my developer Nexus One.


问:
Using recursive type alias in generic results in error
TypeScript v3.7.5 throws Type instantiation is excessively deep and possibly infinite.(2589) when I'm trying to use recursive type alias in generic function.

```<code>type State = {
    head: {
        title: string;
        description: string;
        metadata: { type: string; value: string }[];
    };
    body: {
        title: string;
    };
};

cons...
</code>```

Playground Link

Why does this happen? Is there a way to fix this without providing maximum depth value(iterator)?

答:
We can make it finite by introduction of some iterator. In below example I limit recursion to 5 levels:

```<code>type I = 0 | 1 | 2 | 3 | 4 | 5;
type Iterate<A extends I = 0> =
    A extends 0 ? 1
    : A extends 1 ? 2
    : A extends 2 ? 3
    : A extends 3 ? 4
    : A extends 4 ? 5
    : A extends 5 ? 5
    : 5

type Paths<Obj, X extends I = 0> = Iterate<X> extends 5 ? [] : Obj extends object
    ? {
          [Key in keyof Obj]: Prepend<Paths<Obj[Key], Iterate<X>>, Key>;
      }[keyof Obj]
    : [];
</code>```

Core part is

Iterate<X> extends 5 ? [] it means that at fifth level we stop the recursion.

Paths<Obj[Key], Iterate<X>> every use of Paths gets incremented I

Few things why. TS is behaving like that from 3.4 version. Some info about that

When we hit the instantiation depth limiter we force the type to terminate by resolving to an any. The only change in 3.4 is that we now report an error to let you know that we are delivering truncated (and unpredictable) results. Previously we'd just silently let it pass. So, I'm quite certain you were triggering the limiter before, it's just that you weren't hearing about it.

TS has implicit limit for recursive types equal 50 iterations, but they want to prevent such kind getting to the limit, as such types can slow significantly the compiler. That is why now developer needs to limit the type in order to free the compiler time.

More info can be found here

Body:
TypeScript v3.7.5 throws Type instantiation is excessively deep and possibly infinite.(2589) when I'm trying to use recursive type alias in generic function.

type State = {
    head: {
        title: string;
        description: string;
        metadata: { type: string; value: string }[];
    };
    body: {
        title: string;
    };
};

cons...

<a href="https://www.typescriptlang.org/play/#code/C4TwDgpgBAysCGxoF4oG8CwAoKuoAsJ4ATALnWzyqmAEtgAbCcgZ2ACdaA7AcwG5K1XMQgsAxpzB0A9l1Ydu-QUIC2EBMUTxyaGuGZQ2nXnygA3eAwCuBo4qgBfANoBdATjwP3VAEbTiIDrK1HSMtgomwV7Y0VjYYrJshghI5HCIKBQeuIQkQdkh9EzkAOShTCUANMFUIuKSMnJQJXUStFK0slU1eGoaWuROPUK6oJClYOwQDNIkVeaWNqXSYCWO1QVCuKP6E1Mzc5UL1gYlK2sOG1tQLleed7h+AfnX5adPIAAqRRDdBZcxdzYMbQAAKU0gXGIAB5PlYwEwjgBpCAgAB8UFQcIR0AgAA8kFCWFApiRZAwQFB4FwQK5ggB+KAACiZuTIUBRICOADpefB2DwWORsUwAJSYjHUkDi-GE4jEpm87n8wXkbgAMwg7CgAFVxchJTThlBGTrjeQuBAzFrgharVqgVgQVBQYh8CxoQB5HwAKwxqG9PqgsogRKg0l9EDEwAZWWuuCcnKg3CgAGtUdJ1VBAy5yOCIJCYa7gO6vb7E6iXGjkai0d5qM50yBM9nfS5bVBXI7nZ7QZiXW6PekkHXsPFEsBksYeLR1ZTULD+2gHGimWA3XnB7C0aL5NOJXG8FNgFZ2FwoOuS9yfdJuEyStySqLTAB6F9a9jSdiAsdYOy8WcQGhYcIFXJwSjZeYyh+EoXGfIA" rel="nofollow noreferrer">Playground Link

Why does this happen? Is there a way to fix this without providing maximum depth value(iterator)?

Body:
We can make it finite by introduction of some iterator. In below example I limit recursion to 5 levels:

type I = 0 | 1 | 2 | 3 | 4 | 5;
type Iterate<A extends I = 0> =
    A extends 0 ? 1
    : A extends 1 ? 2
    : A extends 2 ? 3
    : A extends 3 ? 4
    : A extends 4 ? 5
    : A extends 5 ? 5
    : 5

type Paths<Obj, X extends I = 0> = Iterate<X> extends 5 ? [] : Obj extends object
    ? {
          [Key in keyof Obj]: Prepend<Paths<Obj[Key], Iterate<X>>, Key>;
      }[keyof Obj]
    : [];

Core part is

Iterate<X> extends 5 ? [] it means that at fifth level we stop the recursion.

Paths<Obj[Key], Iterate<X>> every use of Paths gets incremented I

Few things why. TS is behaving like that from 3.4 version. Some info about that

When we hit the instantiation depth limiter we force the type to terminate by resolving to an any. The only change in 3.4 is that we now report an error to let you know that we are delivering truncated (and unpredictable) results. Previously we'd just silently let it pass. So, I'm quite certain you were triggering the limiter before, it's just that you weren't hearing about it.

TS has implicit limit for recursive types equal 50 iterations, but they want to prevent such kind getting to the limit, as such types can slow significantly the compiler. That is why now developer needs to limit the type in order to free the compiler time.

More info can be found here


问:
ReferenceError: document is not defined (in plain JavaScript)
I get the a "ReferenceError: document is not defined" while trying to

```<code>var body = document.getElementsByTagName("body")[0];
</code>```

I have seen this before in others code and didn't cause any trouble. Why is it now?
The companied HTML page is just a div inside the body.

```<code><!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
    <script type="text/javascript" src="js/quiz.js"></script>
</head>
<body>

    <div id="divid">Next</div>

</body>
</html>
</code>```

the code is the following:

```<code>(function(){
        var body = document.getElementsByTagName("body")[0];

        function Question(question, choices, correctAns) {
            this.question = question;
            this.choices = choices;
            this.correctAns = correctAns;
        }

        Question.prototype.checkAns = function(givenAns){
            if (this.correctAns === givenAns) {
                console.log("OK");
            }
        };

        function Quiz() {
            this.questions = [];
        }

        Quiz.prototype.showAllQuestions = function(){
            this.questions.forEach(function(questions){
                console.log(questions.question);
            });
        };

        Quiz.prototype.showQuiz = function(){
            this.questions.forEach(function(questions){

                for (var i=0; i < questions.choices.length; i+=1) {
                    body.innerHTML(
                            "<input type=\"radio\" name=\"sex\" value=\"male\">"
                            + questions.choices[i] + "<br>");
                }

            });
        };

        var q1 = new Question("What is red?", ["Color","Animal","Building"],1);
        var q2 = new Question("Most popular music?", ["Latin","Pop","Rock"],2);
        var quiz = new Quiz();

        quiz.questions.push(q1);
        quiz.questions.push(q2);
        quiz.showAllQuestions();

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

Try the whole code in this link HERE

答:
This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />
```

<p>If you are using any other server side rendering library. Then add the code that you want to run at the client side in <code>componentDidMount</code>. If you are using React Hooks then use <code>useEffects</code> in the place of <code>componentsDidMount</code>.</p>

```import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });

return (<>{a}<>)
}
```

References :

https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

https://reactjs.org/docs/hooks-effect.html

Body:
I get the a "ReferenceError: document is not defined" while trying to

var body = document.getElementsByTagName("body")[0];

I have seen this before in others code and didn't cause any trouble. Why is it now?
The companied HTML page is just a div inside the body.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />

Next

the code is the following:

(function(){
        var body = document.getElementsByTagName("body")[0];

        function Question(question, choices, correctAns) {
            this.question = question;
            this.choices = choices;
            this.correctAns = correctAns;
        }

        Question.prototype.checkAns = function(givenAns){
            if (this.correctAns === givenAns) {
                console.log("OK");
            }
        };

        function Quiz() {
            this.questions = [];
        }

        Quiz.prototype.showAllQuestions = function(){
            this.questions.forEach(function(questions){
                console.log(questions.question);
            });
        };

        Quiz.prototype.showQuiz = function(){
            this.questions.forEach(function(questions){

                for (var i=0; i < questions.choices.length; i+=1) {
                    body.innerHTML(
                            "<input type=\"radio\" name=\"sex\" value=\"male\">"
                            + questions.choices[i] + "
");
                }

            });
        };

        var q1 = new Question("What is red?", ["Color","Animal","Building"],1);
        var q2 = new Question("Most popular music?", ["Latin","Pop","Rock"],2);
        var quiz = new Quiz();

        quiz.questions.push(q1);
        quiz.questions.push(q2);
        quiz.showAllQuestions();

        })();

Try the whole code in this link HERE

Body:
This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />

If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount. If you are using React Hooks then use useEffects in the place of componentsDidMount.

import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });

return (<>{a}<>)
}

References :

https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

https://reactjs.org/docs/hooks-effect.html


问:
Log with exception data
I need to log fatal in python standard logging module but with exception details.

I can use log.exception() but it's an error and not fatal.

答:
```<code>logger.fatal(msg, exc_info=True)
</code>```

Note that the log level FATAL is an (apparently undocumented) alias for the log level CRITICAL (source). Accordingly, Logger.fatal() is an alias to Logger.critical() (source).

Title: Log with exception data

Body:
logger.fatal(msg, exc_info=True)

Note that the log level FATAL is an (apparently undocumented) alias for the log level CRITICAL (source). Accordingly, Logger.fatal() is an alias to Logger.critical() (source).