问:
My drop down doesn't work when I click on the second time on ReactJS
I need my drop-down button to show the text below if I press one, and another one for hiding. I tried to use the useState method, but it also doesn't work, and same with the non-useState method. Here is my code, hope someone can fix this, thanks</p>
```<code>    function AnnouncementCard(props) {
      const { announcement } = props;

      const triangleDown = <img src={DropDown} alt="No-img" />;
      const triangleUp = <img src={DropDownActive} alt="No-img" />;

      function Readmore() {
        console.log("inject", currentTriangle);
        if (currentTriangle == triangleDown) {
          DisplayText(null);
          ChangeTriangle(triangleUp);
          console.log(2, currentTriangle);
        } else if (currentTriangle == triangleUp) {
          DisplayText(<Text>{announcement.detail}</Text>);
          ChangeTriangle(triangleDown);
          console.log(1, currentTriangle);
        }
      }

      const [currentTriangle, ChangeTriangle] = useState(triangleUp);
      const [currentText, DisplayText] = useState(null);

      return (
        <Card>
          <CardBody>
            <PictureBox>
              <Picture src={announcement.img} alt="no-img" />
            </PictureBox>
            <TextBox>
              <Title>{announcement.title}</Title>
              <Date>{announcement.date}</Date>
              <ReadMore onClick={() => {Readmore();}}>
                Read more
                <Triangle>{currentTriangle}</Triangle>
              </ReadMore>
            </TextBox>
          </CardBody>
          <Textarea>{currentText}</Textarea>
        </Card>
      );
    }

    export default AnnouncementCard;
</code>```

答:
You cannot simply compare JSX elements using == operator (currentTriangle == triangleDown). To make it simple, I would use a boolean instead of saving the element in the state, and depending on that you can show up and down buttons.

Replace the ChangeTriangle state hook with the following.

```<code>const [toggleValue, setToggleValue] = useState(true);
</code>```

Update the ReadMore function as below.

```<code>  function Readmore() {
    if (toggleValue === false) {
      DisplayText(null);
      setToggleValue(true);
    } else if (toggleValue === true) {
      DisplayText(<Text>{announcement.detail}</Text>);
      setToggleValue(false);
    }
  }
</code>```

Set the triangle button as below using a ternary operator.

```<code><Triangle>{toggleValue ? triangleUp : triangleDown}</Triangle>
</code>```

Body:
I need my drop-down button to show the text below if I press one, and another one for hiding. I tried to use the useState method, but it also doesn't work, and same with the non-useState method. Here is my code, hope someone can fix this, thanks

    function AnnouncementCard(props) {
      const { announcement } = props;

      const triangleDown = ;
      const triangleUp = ;

      function Readmore() {
        console.log("inject", currentTriangle);
        if (currentTriangle == triangleDown) {
          DisplayText(null);
          ChangeTriangle(triangleUp);
          console.log(2, currentTriangle);
        } else if (currentTriangle == triangleUp) {
          DisplayText(<Text>{announcement.detail}</Text>);
          ChangeTriangle(triangleDown);
          console.log(1, currentTriangle);
        }
      }

      const [currentTriangle, ChangeTriangle] = useState(triangleUp);
      const [currentText, DisplayText] = useState(null);

      return (
        <Card>
          <CardBody>
            <PictureBox>
              <Picture src={announcement.img} alt="no-img" />
            </PictureBox>
            <TextBox>
              <Title>{announcement.title}</Title>
              <Date>{announcement.date}</Date>
              <ReadMore onClick={() => {Readmore();}}>
                Read more
                <Triangle>{currentTriangle}</Triangle>
              </ReadMore>
            </TextBox>
          </CardBody>
          <Textarea>{currentText}</Textarea>
        </Card>
      );
    }

    export default AnnouncementCard;

Body:
You cannot simply compare JSX elements using == operator (currentTriangle == triangleDown). To make it simple, I would use a boolean instead of saving the element in the state, and depending on that you can show up and down buttons.

Replace the ChangeTriangle state hook with the following.

const [toggleValue, setToggleValue] = useState(true);

Update the ReadMore function as below.

  function Readmore() {
    if (toggleValue === false) {
      DisplayText(null);
      setToggleValue(true);
    } else if (toggleValue === true) {
      DisplayText(<Text>{announcement.detail}</Text>);
      setToggleValue(false);
    }
  }

Set the triangle button as below using a ternary operator.

<Triangle>{toggleValue ? triangleUp : triangleDown}</Triangle>


来源: stackexchange

问:
Why do we use "for" attribute inside label tag?
I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand

Code1

<input id="indoor" type="radio" name="indoor-outdoor">
Indoor```
</div>
</div>
</p>
<p>Code2</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="loving"><input id="loving" type="checkbox" name="personality"> Loving</label>
<br>
<label><input type="checkbox" name="personality"> Loving</label></code>```

I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them.
Any help?

答:
It could be used without "for" attribute, and it will be fine, according to docs.
This is just one option how to use "for" to omit confusing developers.
Anyway, in case of placing checkbox inside label, you can skip "for" and it will be fine.

<input type="checkbox" name="personality"> Loving
```
<p><strong>"for"</strong> approach much preferable if you want to style it, f.e. using Bootstrap</p>
<pre class="lang-html prettyprint-override"><code><div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
  <label class="form-check-label" for="flexCheckDefault">
    Default checkbox
  </label>
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand

Code1

<input id="indoor" type="radio" name="indoor-outdoor">
Indoor

Code2

<input id="loving" type="checkbox" name="personality"> Loving

<input type="checkbox" name="personality"> Loving

I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them.
Any help?

Body:
It could be used without "for" attribute, and it will be fine, according to docs.
This is just one option how to use "for" to omit confusing developers.
Anyway, in case of placing checkbox inside label, you can skip "for" and it will be fine.

<!-- labelable form-relation still works -->
<label><input type="checkbox" name="personality"> Loving</label>

"for" approach much preferable if you want to style it, f.e. using Bootstrap

<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
  <label class="form-check-label" for="flexCheckDefault">
    Default checkbox
  </label>
</div>


问:
cant add Web User Control (vs 2010)
In my project, solution explorer I click on the folder and -> add new Item. I would like to add web user control but I cant see it. In previous versions of visual studio I didnt have such a problem,

any idead on how can I add this template ?

thanks for any help,
Bye

EDIT:

this is how it looks:

http://imageshack.us/photo/my-images/820/controlka.png/

in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\1033

I dont have any web zip files :/

But when I create new WebSite or asp.net Web Application tempaltes are available.

Project Im working on is converted from vs2008

答:
Is your project set for Client Profile in your project's properties? If so, change it not to.

Is Web selected in the tree to the right?

ContentLicense: CC BY-SA 3.0

Title: cant add Web User Control (vs 2010)


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

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

to

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

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

答:
I know it's an old thread but in case someone is looking for simpler version of this

Hash[Person.all(:id, :name)]
```

Tested in Rails 5.

Title: Ruby on Rails 4: Pluck results to hash

Body:
How can I turn:

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

to

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

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

Body:
I know it's an old thread but in case someone is looking for simpler version of this

Hash[Person.all(:id, :name)]

Tested in Rails 5.


问:
what is the default value of an array in C++?
If I were to create an array with int* array = new int[10]; and fill part of the array with values, how can I check how much of the array is filled? I want to loop through and check if each value is the default value but I'm not sure what the default value of each array element is. Would it be null 0 or garbage values?

答:
By default, the objects allocated by new are default initialized. This mean when you wrote:

```<code>int* array = new int[10]; //block of 10 uninitialized ints
</code>```

Here, all of the 10 ints are uninitialized. That is, they have indeterminate value.

It is possible to value initialize the elements by adding an empty pair of parenthesis as shown below:

```<code>int* array = new int[10](); //block of 10 ints value initialized to 0
</code>```

Here all of the 10 ints are initialized to 0.

But note that although we can use empty parentheses to value initialize the elements of an array, we cannot supply an element initializer inside the parentheses. This means for example,

```<code>int* array = new int[10](55); // INVALID
</code>```

The above statement is invalid because we cannot supply an element initializer inside the parenthesize.

You can use std::fill_n instead of supplying an element initializer inside the parentheses as shown below:

```<code>int* array = new int[10];                 //block of 10 uninitialized ints
std::fill_n(array, 10, 55);              // all elements will now hold 55
</code>```

Body:
By default, the objects allocated by new are default initialized. This mean when you wrote:

int* array = new int[10]; //block of 10 uninitialized ints

Here, all of the 10 ints are uninitialized. That is, they have indeterminate value.

It is possible to value initialize the elements by adding an empty pair of parenthesis as shown below:

int* array = new int[10](); //block of 10 ints value initialized to 0

Here all of the 10 ints are initialized to 0.

But note that although we can use empty parentheses to value initialize the elements of an array, we cannot supply an element initializer inside the parentheses. This means for example,

int* array = new int[10](55); // INVALID

The above statement is invalid because we cannot supply an element initializer inside the parenthesize.

You can use std::fill_n instead of supplying an element initializer inside the parentheses as shown below:

int* array = new int[10];                 //block of 10 uninitialized ints
std::fill_n(array, 10, 55);              // all elements will now hold 55


问:
Use Web NFC on Android Webview?
I made a React web app that reads the uid from RFID cards of my customers. This works fine with the Web NFC api on Goolge Chrome. To display the app in fullscreen mode on a tablet with NFC interface I created a simple Java App to output the web app with Webview.

The site is loading fine but Webview is not asking the user for NFC permission and I get this error message:

"NFC permission request denied."

I tried a few kiosk browser apps but they are also working with Webview and can't handle the Web NFC requests.

Is there any solution? Thank you!

Here an example:

MainActivity.java

```<code>package com.example.shop;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private WebView mywebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mywebView=(WebView) findViewById(R.id.webview);
        mywebView.setWebViewClient(new WebViewClient());
        mywebView.loadUrl("https://googlechrome.github.io/samples/web-nfc/");
        WebSettings webSettings=mywebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
    }
    public class mywebClient extends WebViewClient{
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon){
            super.onPageStarted(view,url,favicon);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view,String url){
            view.loadUrl(url);
            return true;
        }
    }
    @Override
    public void onBackPressed(){
        if(mywebView.canGoBack()) {
            mywebView.goBack();
        }
        else{
            super.onBackPressed();
        }
    }
}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.shop">
    <uses-permission  android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.NFC" />
    <uses-feature android:name="android.hardware.nfc" android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.shop">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
Web NFC is sadly not supported in Android WebView.

Source: https://chromestatus.com/feature/6261030015467520

Quick question: Why not using the Fullscreen API instead?

document.body.requestFullscreen();
```

Title: Use Web NFC on Android Webview?

Body:
I made a React web app that reads the uid from RFID cards of my customers. This works fine with the Web NFC api on Goolge Chrome. To display the app in fullscreen mode on a tablet with NFC interface I created a simple Java App to output the web app with Webview.

The site is loading fine but Webview is not asking the user for NFC permission and I get this error message:

"NFC permission request denied."

I tried a few kiosk browser apps but they are also working with Webview and can't handle the Web NFC requests.

Is there any solution? Thank you!

Here an example:

MainActivity.java

package com.example.shop;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private WebView mywebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mywebView=(WebView) findViewById(R.id.webview);
        mywebView.setWebViewClient(new WebViewClient());
        mywebView.loadUrl("https://googlechrome.github.io/samples/web-nfc/");
        WebSettings webSettings=mywebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
    }
    public class mywebClient extends WebViewClient{
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon){
            super.onPageStarted(view,url,favicon);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view,String url){
            view.loadUrl(url);
            return true;
        }
    }
    @Override
    public void onBackPressed(){
        if(mywebView.canGoBack()) {
            mywebView.goBack();
        }
        else{
            super.onBackPressed();
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.shop">
    <uses-permission  android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.NFC" />
    <uses-feature android:name="android.hardware.nfc" android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.shop">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
Array Prop Undefined - Mapping Array In Props
I am expecting to map over an array, and pass the data to a child component. The undesired outcome is it reads as undefined.

Parent Component:

```<code>import Tier from "./tier";
const data = [
  {
    title: "SAVER SALLY",
    subtitle: "22,000rmb/month",
    list: [
      "Income Tax: 3,295",
      "Income Tax: 3,295",
    ],
    bottom: {
      title: "Total Yearly Savings:",
      centralNumber: "144,480RMB",
      subtitle: "This is approximately £16,000 or 21,000USD",
    },
  }
];

const Tiers = ({ classes }) => {
    return (
        <>
        {data.map(set => <Tier objectInformation={set} />)}
        </>
    )
}

export default withStyles((theme) => ({}))(Tiers);
</code>```

The Child Component:

```<code>const Tier = ({ classes, objectInformation }) => {
  const {title, subtitle, list, bottom} = objectInformation
  console.log("OBJECT INFORMATION", objectInformation)
  return (
    <div>{title}</div>
  )
}
</code>```

The end goal is to have multiple objects in the data variable, that'll pass down as props to Tiers, the parents component.

答:
You can't render an object within a component in React.

Either stringify your object

```<code>    const Tier = ({ classes, objectInformation }) => {
      return (
        <div>{JSON.stringify(objectInformation)}</div>
      )
    }
</code>```

or only select a part of it.

```<code>    const Tier = ({ classes, objectInformation }) => {
      return (
        <div>{objectInformation.title}</div>
      )
    }
</code>```

Body:
I am expecting to map over an array, and pass the data to a child component. The undesired outcome is it reads as undefined.

Parent Component:

import Tier from "./tier";
const data = [
  {
    title: "SAVER SALLY",
    subtitle: "22,000rmb/month",
    list: [
      "Income Tax: 3,295",
      "Income Tax: 3,295",
    ],
    bottom: {
      title: "Total Yearly Savings:",
      centralNumber: "144,480RMB",
      subtitle: "This is approximately £16,000 or 21,000USD",
    },
  }
];

const Tiers = ({ classes }) => {
    return (
        <>
        {data.map(set => <Tier objectInformation={set} />)}
        </>
    )
}

export default withStyles((theme) => ({}))(Tiers);

The Child Component:

const Tier = ({ classes, objectInformation }) => {
  const {title, subtitle, list, bottom} = objectInformation
  console.log("OBJECT INFORMATION", objectInformation)
  return (

{title}

  )
}

The end goal is to have multiple objects in the data variable, that'll pass down as props to Tiers, the parents component.

Body:
You can't render an object within a component in React.

Either stringify your object

    const Tier = ({ classes, objectInformation }) => {
      return (
        <div>{JSON.stringify(objectInformation)}</div>
      )
    }

or only select a part of it.

    const Tier = ({ classes, objectInformation }) => {
      return (
        <div>{objectInformation.title}</div>
      )
    }


问:
Not in table between dates
I have 2 tables :

terminal

```<code>id   text
1    abc
2    def
3    dfg
</code>```

termusage

```<code>id  termid   date
1   1        2010-11-01
2   1        2010-10-13
3   2        2010-11-10
4   3        2010-11-13
</code>```

+ many more records (10 million) approv half are within the date (2010-11-01 and 2010-12-01)

What i want to do is find the terminal.id of the records that do not exist in the termusage table between 2010-11-01 and 2010-12-01

I have looked at select where not exists but nothing is being returned - example

```<code>select * from terminal
where not exists (
select * from termusage where date between '2010-11-01' and '2010-12-01' group by termid)
</code>```

Can anyone please explain how i need to use the where not exists clause or another method !! Cheers

答:
I think that using exists is a faster solution:

```<code>select * from terminal t
where not exists (
    select * from termusage tu
    where (t.id = tu.termid) and (date between '2010-11-01' and '2010-12-01')
)
</code>```

Title: Not in table between dates

Body:
I have 2 tables :

terminal

id   text
1    abc
2    def
3    dfg

termusage

id  termid   date
1   1        2010-11-01
2   1        2010-10-13
3   2        2010-11-10
4   3        2010-11-13

+ many more records (10 million) approv half are within the date (2010-11-01 and 2010-12-01)

What i want to do is find the terminal.id of the records that do not exist in the termusage table between 2010-11-01 and 2010-12-01

I have looked at select where not exists but nothing is being returned - example

select * from terminal
where not exists (
select * from termusage where date between '2010-11-01' and '2010-12-01' group by termid)

Can anyone please explain how i need to use the where not exists clause or another method !! Cheers

Body:
I think that using exists is a faster solution:

select * from terminal t
where not exists (
    select * from termusage tu
    where (t.id = tu.termid) and (date between '2010-11-01' and '2010-12-01')
)


问:
How to select multiple row in Table row ?Using(ctrl+click) and (Shift+click) in react js
Please help me, I have no idea how to solve that problem when user press ctrl +Left click  table row should highlight the row, and in shift + left click It should highlight all the row data where the user clicks from 1 row to 2 last row (example like react-Table multiple row selection).
Not using any 3 party library.

Code:-

```<code>  const ClickHighlight = (event, ID, ChannelName) => {
        if (event.ctrlKey) {

        }

      if(event.shiftKey) {
           console.log("helloShift");
        }

    }

    return (
        <div className="mainContent">
            <div className="tableHeaderBody">
                <div className="TableText">PlayList</div>  <div className="ClossIcon"><FaCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} /></div>
            </div>
            <div className="tableBody" >
                <table className="table" id="tableStudent" data-multiple-select-row="true"
                    data-click-to-select="true">
                    <Header
                        headers={headers}
                    />
                    <tbody>
                        {comments.map((comment) => {

                            return (
                                <tr key={comment.idx} tabIndex={comment.idx} className="border_bottom"  onMouseDown={(e) => ClickHighlight(e, comment.ClipName, comment.ChannelName)}>
                                    <td style={{ color: "white", width: "200px" }}>
                                        <img src={`data:image/jpeg;base64,${base64}`} alt="Clip Thumbnail" width="50%" />
                                    </td>
                                    <td style={{ color: "white", width: "440px" }}>{comment.ClipName}</td>
                                    <td style={{ color: "white", width: "250px" }}>{comment.SlugName}</td>
                                    <td style={{ color: "white", width: "250px" }}>{comment.ChannelName}</td>
</code>```

Please help.

答:
I've assumed your component is a functional one, but hopefully this gives you the idea on how to do it anyway. I've also assumed comments is a prop of your component:

```<code>const [highlightedRows, setHighlightedRows] = useState([]);

const ClickHighlight = (event, id, ChannelName) => {
  if (event.ctrlKey || event.shiftKey) {
    // add to highlighted
    setHighlightedRows((current) => {
      if (current.includes(id)) {
        // row is already highlighted. Unhighlight but keep the others
        return current.filter((entry) => entry !== id);
      } else {
        // add row to the current list of highlighted ones
        return [...current, id];
      }
    });
  } else {
    // highlight clicked row and de-highlight others
    setHighLightedRows([id]);
  }
}
</code>```

Now in your return statement you can use the state to either render the row as highlighted or not by matching to the comment's idx. Here i've just given each highlighted item a yellow background, but you can style this any way you want.

```<code><tbody>
  {comments.map((comment) => {
    const isHighlighted = highlightedRows.includes(comment.idx);
    // we can now conditionally render based on if this flag is true or not
    return (
      <tr
        key={comment.idx}
        tabIndex={comment.idx}
        className="border_bottom"
        onMouseDown={(e) => ClickHighlight(e, comment.idx, comment.ChannelName)}
        style={ isHighlighted ? { backgroundColor: 'yellow' } : {}}
        >
         <td style={{ color: "white", width: "200px" }}>
           <img src={`data:image/jpeg;base64,${base64}`} alt="Clip Thumbnail" width="50%" />
         </td>
         <td style={{ color: "white", width: "440px" }}>{comment.ClipName}</td>
         <td style={{ color: "white", width: "250px" }}>{comment.SlugName}</td>
         <td style={{ color: "white", width: "250px" }}>{comment.ChannelName}</td>
         ...

</code>```

Body:
Please help me, I have no idea how to solve that problem when user press ctrl +Left click  table row should highlight the row, and in shift + left click It should highlight all the row data where the user clicks from 1 row to 2 last row (example like react-Table multiple row selection).
Not using any 3 party library.

Code:-

  const ClickHighlight = (event, ID, ChannelName) => {
        if (event.ctrlKey) {

        }

      if(event.shiftKey) {
           console.log("helloShift");
        }

    }

    return (

PlayList

<FaCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} />

                        {comments.map((comment) => {

                            return (

 ClickHighlight(e, comment.ClipName, comment.ChannelName)}>

                                        <img src={`data:image/jpeg;base64,${base64}`} alt="Clip Thumbnail" width="50%" />

                                    {comment.ClipName}
                                    {comment.SlugName}
                                    {comment.ChannelName}

Please help.

Body:
I've assumed your component is a functional one, but hopefully this gives you the idea on how to do it anyway. I've also assumed comments is a prop of your component:

const [highlightedRows, setHighlightedRows] = useState([]);

const ClickHighlight = (event, id, ChannelName) => {
  if (event.ctrlKey || event.shiftKey) {
    // add to highlighted
    setHighlightedRows((current) => {
      if (current.includes(id)) {
        // row is already highlighted. Unhighlight but keep the others
        return current.filter((entry) => entry !== id);
      } else {
        // add row to the current list of highlighted ones
        return [...current, id];
      }
    });
  } else {
    // highlight clicked row and de-highlight others
    setHighLightedRows([id]);
  }
}

Now in your return statement you can use the state to either render the row as highlighted or not by matching to the comment's idx. Here i've just given each highlighted item a yellow background, but you can style this any way you want.

<tbody>
  {comments.map((comment) => {
    const isHighlighted = highlightedRows.includes(comment.idx);
    // we can now conditionally render based on if this flag is true or not
    return (
      <tr
        key={comment.idx}
        tabIndex={comment.idx}
        className="border_bottom"
        onMouseDown={(e) => ClickHighlight(e, comment.idx, comment.ChannelName)}
        style={ isHighlighted ? { backgroundColor: 'yellow' } : {}}
        >
         <td style={{ color: "white", width: "200px" }}>
           <img src={`data:image/jpeg;base64,${base64}`} alt="Clip Thumbnail" width="50%" />
         </td>
         <td style={{ color: "white", width: "440px" }}>{comment.ClipName}</td>
         <td style={{ color: "white", width: "250px" }}>{comment.SlugName}</td>
         <td style={{ color: "white", width: "250px" }}>{comment.ChannelName}</td>
         ...


问:
ADB freezes on any command
I somehow can't get ADB to work on my windows machine

everytime i try to run adb devices or adb start-server it freezes and does nothing, it only prints * daemon not running; starting now at tcp:5037

With logging it shows the following:

```<code>adb.exe D 02-10 19:06:54 21236 13536 adb_trace.cpp:187] Android Debug Bridge version 1.0.41
adb.exe D 02-10 19:06:54 21236 13536 adb_trace.cpp:187] Version 32.0.0-8006631
adb.exe D 02-10 19:06:54 21236 13536 adb_trace.cpp:187] Installed as C:\Users\Felix\AppData\Local\Android\Sdk\platform-tools\adb.exe
adb.exe D 02-10 19:06:54 21236 13536 adb_trace.cpp:187]
adb.exe D 02-10 19:06:54 21236 13536 adb_client.cpp:351] adb_connect: service: host:start-server
adb.exe D 02-10 19:06:54 21236 13536 adb_client.cpp:160] _adb_connect: host:version
adb.exe D 02-10 19:06:56 21236 13536 sysdeps_win32.cpp:1032] could not connect to tcp:5037: cannot connect to 127.0.0.1:5037: No connection could be made because the target machine actively refused it. (10061)
adb.exe D 02-10 19:06:56 21236 13536 sysdeps_win32.cpp:602] _socket_set_errno: mapping Windows error code 10061 to errno 22
* daemon not running; starting now at tcp:5037
adb D 02-10 19:06:56 22512  1472 adb_trace.cpp:187] Android Debug Bridge version 1.0.41
adb D 02-10 19:06:56 22512  1472 adb_trace.cpp:187] Version 32.0.0-8006631
adb D 02-10 19:06:56 22512  1472 adb_trace.cpp:187] Installed as C:\Users\Felix\AppData\Local\Android\Sdk\platform-tools\adb.exe
adb D 02-10 19:06:56 22512  1472 adb_trace.cpp:187]
</code>```

I have adb installed through android studio, but i also tried downloading it manually.
There is also no other program running, which could block the port.

I also tried

disabling ipv6, cause i read somewhere that this solved the issue.

running it from a different directory

run it from windows terminal, powershell, cmd

run it from an elevated terminal

The weird thing is, it sometimes works when android studio starts, but it will never work from the terminal.

i am really out of ideas, as to why this happens.

UPDATE: it seems to be a version issue, but i still don't know why
the version 29.0.6 seems to be the last working version everything newer has the issues stated above. Funnily enough, 29.0.6 still isn't working if started by android studio.

答:
Most likely again what you encounter is caused by one of the bugs introduced with adb of platform-version 32.0. There were quite a few questions on similar topics on all operating systems used by Android developers.

As at the moment (2022-02-11) there is no newer version of adb versions that fixes this problem the recommended way is to downgrade abd to version 31.0:

These are the download urls at Google for the 31.0.3 version:

Linux

MacOS

Windows

Title: ADB freezes on any command

Body:
I somehow can't get ADB to work on my windows machine

everytime i try to run adb devices or adb start-server it freezes and does nothing, it only prints * daemon not running; starting now at tcp:5037

With logging it shows the following:

adb.exe D 02-10 19:06:54 21236 13536 adb_trace.cpp:187] Android Debug Bridge version 1.0.41
adb.exe D 02-10 19:06:54 21236 13536 adb_trace.cpp:187] Version 32.0.0-8006631
adb.exe D 02-10 19:06:54 21236 13536 adb_trace.cpp:187] Installed as C:\Users\Felix\AppData\Local\Android\Sdk\platform-tools\adb.exe
adb.exe D 02-10 19:06:54 21236 13536 adb_trace.cpp:187]
adb.exe D 02-10 19:06:54 21236 13536 adb_client.cpp:351] adb_connect: service: host:start-server
adb.exe D 02-10 19:06:54 21236 13536 adb_client.cpp:160] _adb_connect: host:version
adb.exe D 02-10 19:06:56 21236 13536 sysdeps_win32.cpp:1032] could not connect to tcp:5037: cannot connect to 127.0.0.1:5037: No connection could be made because the target machine actively refused it. (10061)
adb.exe D 02-10 19:06:56 21236 13536 sysdeps_win32.cpp:602] _socket_set_errno: mapping Windows error code 10061 to errno 22
* daemon not running; starting now at tcp:5037
adb D 02-10 19:06:56 22512  1472 adb_trace.cpp:187] Android Debug Bridge version 1.0.41
adb D 02-10 19:06:56 22512  1472 adb_trace.cpp:187] Version 32.0.0-8006631
adb D 02-10 19:06:56 22512  1472 adb_trace.cpp:187] Installed as C:\Users\Felix\AppData\Local\Android\Sdk\platform-tools\adb.exe
adb D 02-10 19:06:56 22512  1472 adb_trace.cpp:187]

I have adb installed through android studio, but i also tried downloading it manually.
There is also no other program running, which could block the port.

I also tried

disabling ipv6, cause i read somewhere that this solved the issue.

running it from a different directory

run it from windows terminal, powershell, cmd

run it from an elevated terminal

The weird thing is, it sometimes works when android studio starts, but it will never work from the terminal.

i am really out of ideas, as to why this happens.

UPDATE: it seems to be a version issue, but i still don't know why
the version 29.0.6 seems to be the last working version everything newer has the issues stated above. Funnily enough, 29.0.6 still isn't working if started by android studio.


问:
Mesh creation in openGL iphone sdk
I am using this source code as my base and trying to change the code as per my requirements.  I have included the following code to create a mesh on image.

-(void)populateMesh{

```<code>verticalDivisions = kVerticalDivisions;
horizontalDivisions = kHorisontalDivisions;
unsigned int verticesArrsize = (kVerticalDivisions * ((2 + kHorisontalDivisions * 2) * 3));
unsigned int textureCoordsArraySize = kVerticalDivisions * ((2 + kHorisontalDivisions * 2) * 2);
verticesArr = (GLfloat *)malloc(verticesArrsize * sizeof(GLfloat));
textureCoordsArr = (GLfloat*)malloc(textureCoordsArraySize * sizeof(GLfloat));
if (verticesArr == NULL) {
    NSLog(@"verticesArr = NULL!");
}
float height = kWindowHeight/verticalDivisions;
float width = kWindowWidth/horizontalDivisions;
int i,j, count;
count = 0;
for (j=0; j<verticalDivisions; j++) {
    for (i=0; i<=horizontalDivisions; i++, count+=6) { //2 vertices each time...
        float currX = i * width;
        float currY = j * height;
        verticesArr[count] = currX;
        verticesArr[count+1] = currY + height;
        verticesArr[count+2] = 0.0f;
        verticesArr[count+3] = currX;
        verticesArr[count+4] = currY;
        verticesArr[count+5] = 0.0f;
    }
}
float xIncrease = 1.0f/horizontalDivisions;
float yIncrease = 1.0f/verticalDivisions;
int x,y;
//int elements;
count = 0;
for (y=0; y<verticalDivisions; y++) {
    for (x=0; x<horizontalDivisions+1; x++, count+=4) {
        float currX = x *xIncrease;
        float currY = y * yIncrease;
        textureCoordsArr[count] = (float)currX;
        textureCoordsArr[count+1] = (float)currY + yIncrease;
        textureCoordsArr[count+2] = (float)currX;
        textureCoordsArr[count+3] = (float)currY;
    }
}
//  int cnt;
//  int cnt = 0;
    NSLog(@"expected %i vertices, and %i vertices were done",(verticalDivisions * ((2 + horizontalDivisions*2 ) * 2) ) , count );
}
</code>```

Following is the drawView code.

```<code>- (void)drawView:(GLView*)view;
{
static GLfloat rot = 0.0;
glBindTexture(GL_TEXTURE_2D, texture[0]);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

glEnableClientState(GL_VERTEX_ARRAY);
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, textureCoordsArr);
glVertexPointer(3, GL_FLOAT, 0, verticesArr);
glPushMatrix();{
    int i;
    for (i=0; i<verticalDivisions; i++) {
        glDrawArrays(GL_TRIANGLE_STRIP, i*(horizontalDivisions*2+2), horizontalDivisions*2+2);
    }
}glPopMatrix();
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}
</code>```

In the setup view I have called [self populateMesh]; at the end of the function.
My problem is after changing the code, a blank rather say black view is appeared on the screen. Can anyone figure out where I am doing some mistake. I am newbie for openGL and trying to manipulate images through mesh. Please help asap.  Thanks in advance.

Following is the setup view code.

```<code>-(void)setupView:(GLView*)view {

 const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0;
 GLfloat size;
 glEnable(GL_DEPTH_TEST);
 glMatrixMode(GL_PROJECTION);
 size = zNear *  tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
 CGRect rect =  view.bounds;
 glFrustumf(-size, size, -size / (rect.size.width /  rect.size.height), size /    (rect.size.width / rect.size.height),  zNear, zFar);
 glViewport(0, 0, rect.size.width, rect.size.height);
 glMatrixMode(GL_MODELVIEW);
 glEnable(GL_TEXTURE_2D);
 glEnable(GL_BLEND);
 glBlendFunc(GL_ONE, GL_SRC_COLOR);
 glGenTextures(1, &texture[0]);
 glBindTexture(GL_TEXTURE_2D, texture[0]);
 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
 NSString *path = [[NSBundle mainBundle] pathForResource:@"texture" ofType:@"png"];
 NSData *texData = [[NSData alloc] initWithContentsOfFile:path];
 UIImage *image = [[UIImage alloc] initWithData:texData];
 if (image == nil)
 NSLog(@"Do real error checking here");
 GLuint width =  CGImageGetWidth(image.CGImage);
 GLuint height = CGImageGetHeight(image.CGImage);
 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
 void *imageData = malloc( height * width * 4 );
 CGContextRef context = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );

 CGContextTranslateCTM (context, 0, height);

 CGContextScaleCTM (context, 1.0, -1.0);

 CGColorSpaceRelease( colorSpace );

 CGContextClearRect( context, CGRectMake( 0, 0, width, height ) );

 CGContextDrawImage( context, CGRectMake( 0, 0, width, height ),image.CGImage );

 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

 CGContextRelease(context);

 free(imageData);
 [image release];
 [texData release];
 [self populateMesh];
}
</code>```

EDIT This is what I am getting as an out put. While expected is regular grid...

答:
Guessing the mesh is cut out with zNear value. Try to change z value to -2.

```<code>verticesArr[count+2] = -2.0f;
verticesArr[count+5] = -2.0f;
</code>```

By default, the camera is situated at the origin, points down the negative z-axis, and has an up-vector of (0, 1, 0).

Notice that your mesh is out of view frustum (pyramid). Check it out in OpenGL red book:

http://glprogramming.com/red/chapter03.html

Title: Mesh creation in openGL iphone sdk

Body:
I am using this source code as my base and trying to change the code as per my requirements.  I have included the following code to create a mesh on image.

-(void)populateMesh{

verticalDivisions = kVerticalDivisions;
horizontalDivisions = kHorisontalDivisions;
unsigned int verticesArrsize = (kVerticalDivisions * ((2 + kHorisontalDivisions * 2) * 3));
unsigned int textureCoordsArraySize = kVerticalDivisions * ((2 + kHorisontalDivisions * 2) * 2);
verticesArr = (GLfloat *)malloc(verticesArrsize * sizeof(GLfloat));
textureCoordsArr = (GLfloat*)malloc(textureCoordsArraySize * sizeof(GLfloat));
if (verticesArr == NULL) {
    NSLog(@"verticesArr = NULL!");
}
float height = kWindowHeight/verticalDivisions;
float width = kWindowWidth/horizontalDivisions;
int i,j, count;
count = 0;
for (j=0; j<verticalDivisions; j++) {
    for (i=0; i<=horizontalDivisions; i++, count+=6) { //2 vertices each time...
        float currX = i * width;
        float currY = j * height;
        verticesArr[count] = currX;
        verticesArr[count+1] = currY + height;
        verticesArr[count+2] = 0.0f;
        verticesArr[count+3] = currX;
        verticesArr[count+4] = currY;
        verticesArr[count+5] = 0.0f;
    }
}
float xIncrease = 1.0f/horizontalDivisions;
float yIncrease = 1.0f/verticalDivisions;
int x,y;
//int elements;
count = 0;
for (y=0; y<verticalDivisions; y++) {
    for (x=0; x<horizontalDivisions+1; x++, count+=4) {
        float currX = x *xIncrease;
        float currY = y * yIncrease;
        textureCoordsArr[count] = (float)currX;
        textureCoordsArr[count+1] = (float)currY + yIncrease;
        textureCoordsArr[count+2] = (float)currX;
        textureCoordsArr[count+3] = (float)currY;
    }
}
//  int cnt;
//  int cnt = 0;
    NSLog(@"expected %i vertices, and %i vertices were done",(verticalDivisions * ((2 + horizontalDivisions*2 ) * 2) ) , count );
}

Following is the drawView code.

- (void)drawView:(GLView*)view;
{
static GLfloat rot = 0.0;
glBindTexture(GL_TEXTURE_2D, texture[0]);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

glEnableClientState(GL_VERTEX_ARRAY);
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, textureCoordsArr);
glVertexPointer(3, GL_FLOAT, 0, verticesArr);
glPushMatrix();{
    int i;
    for (i=0; i<verticalDivisions; i++) {
        glDrawArrays(GL_TRIANGLE_STRIP, i*(horizontalDivisions*2+2), horizontalDivisions*2+2);
    }
}glPopMatrix();
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}

In the setup view I have called [self populateMesh]; at the end of the function.
My problem is after changing the code, a blank rather say black view is appeared on the screen. Can anyone figure out where I am doing some mistake. I am newbie for openGL and trying to manipulate images through mesh. Please help asap.  Thanks in advance.

Following is the setup view code.

-(void)setupView:(GLView*)view {

 const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0;
 GLfloat size;
 glEnable(GL_DEPTH_TEST);
 glMatrixMode(GL_PROJECTION);
 size = zNear *  tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
 CGRect rect =  view.bounds;
 glFrustumf(-size, size, -size / (rect.size.width /  rect.size.height), size /    (rect.size.width / rect.size.height),  zNear, zFar);
 glViewport(0, 0, rect.size.width, rect.size.height);
 glMatrixMode(GL_MODELVIEW);
 glEnable(GL_TEXTURE_2D);
 glEnable(GL_BLEND);
 glBlendFunc(GL_ONE, GL_SRC_COLOR);
 glGenTextures(1, &texture[0]);
 glBindTexture(GL_TEXTURE_2D, texture[0]);
 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
 NSString *path = [[NSBundle mainBundle] pathForResource:@"texture" ofType:@"png"];
 NSData *texData = [[NSData alloc] initWithContentsOfFile:path];
 UIImage *image = [[UIImage alloc] initWithData:texData];
 if (image == nil)
 NSLog(@"Do real error checking here");
 GLuint width =  CGImageGetWidth(image.CGImage);
 GLuint height = CGImageGetHeight(image.CGImage);
 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
 void *imageData = malloc( height * width * 4 );
 CGContextRef context = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );

 CGContextTranslateCTM (context, 0, height);

 CGContextScaleCTM (context, 1.0, -1.0);

 CGColorSpaceRelease( colorSpace );

 CGContextClearRect( context, CGRectMake( 0, 0, width, height ) );

 CGContextDrawImage( context, CGRectMake( 0, 0, width, height ),image.CGImage );

 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

 CGContextRelease(context);

 free(imageData);
 [image release];
 [texData release];
 [self populateMesh];
}

EDIT This is what I am getting as an out put. While expected is regular grid...

Body:
Guessing the mesh is cut out with zNear value. Try to change z value to -2.

verticesArr[count+2] = -2.0f;
verticesArr[count+5] = -2.0f;

By default, the camera is situated at the origin, points down the negative z-axis, and has an up-vector of (0, 1, 0).

Notice that your mesh is out of view frustum (pyramid). Check it out in OpenGL red book:

http://glprogramming.com/red/chapter03.html


问:
Customize zsh prompt
How can I remove the [ that is placed before my commands after they are entered (e.g. the top two lines in the picture). Looking for something to put in my .zshrc file.

答:
As per chepner, they are part of the terminal not zsh.

The way to remove them is:

Choose Edit > Marks > Automatically Mark Prompt Lines. The tick lets you know whether the option is enabled.

Title: Customize zsh prompt


问:
Given a list of numbers, how can I remove all multiples of primes (but not primes)?
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Question:
Given a list of natural numbers, remove from it all multiples of 2 (but not 2), multiples of 3 (but not 3), and so on, up to the multiples of 100, and print the remaining values.

From this question I take it that I should first make a list with all prime numbers and after that append the values that correspond to a new list. This is what I have until know:

```<code># Read list:
a = [5, 6, 7, 8, 9]

# First get a list with all primes
primes = []
for i in range(0, 101):
    for j in range(2, int(i ** 0.5) + 1):
         if i%j == 0:
             break
    else:
        primes.append(i)

# Next append to new list
b = []
for num in a:
    for prime in primes:
        if num == prime and num % prime == 0:
            b.append(num)
print(b)
</code>```

Now this works for this simple example, but upon testing it on another set (one of which I do not know the input values of the test case), my output is:

```<code>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
</code>```

Which is my original list with the prime numbers. So somewhere along the line I am making a mistake and I cannot see the logic behind it. Any help would be greatly appreciated.

答:
To solve the task all you need to do is filter out the numbers by using a generator and a for loop, which by itself is already finding the prime numbers</p>
```<code>a = [5,6,7,8,9]
for i in range(2,101):
    a = [j for j in a if (j==i or j%i!=0)]
</code>```

Body:
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Question:
Given a list of natural numbers, remove from it all multiples of 2 (but not 2), multiples of 3 (but not 3), and so on, up to the multiples of 100, and print the remaining values.

From this question I take it that I should first make a list with all prime numbers and after that append the values that correspond to a new list. This is what I have until know:

# Read list:
a = [5, 6, 7, 8, 9]

# First get a list with all primes
primes = []
for i in range(0, 101):
    for j in range(2, int(i ** 0.5) + 1):
         if i%j == 0:
             break
    else:
        primes.append(i)

# Next append to new list
b = []
for num in a:
    for prime in primes:
        if num == prime and num % prime == 0:
            b.append(num)
print(b)

Now this works for this simple example, but upon testing it on another set (one of which I do not know the input values of the test case), my output is:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Which is my original list with the prime numbers. So somewhere along the line I am making a mistake and I cannot see the logic behind it. Any help would be greatly appreciated.

Body:
To solve the task all you need to do is filter out the numbers by using a generator and a for loop, which by itself is already finding the prime numbers

a = [5,6,7,8,9]
for i in range(2,101):
    a = [j for j in a if (j==i or j%i!=0)]


问:
How to fix "ImportError: DLL load failed" while importing win32api
I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:

```<code>>>> import win32api
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
</code>```

I'm on Windows 10 Home 64x. I've already tried

```<code>pip install pypiwin32
</code>```

And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I import django, so I think it's a win32api issue only.

```<code>>>> import win32api
</code>```

I expect the output to be none, but the actual output is always that error ^^

答:
hi this question i'm solve as below:
1.check directory C:\Windows\System32, is exist these file?
pythoncom37.dll pywintypes37.dll  or pythoncom36.dll pywintypes36.dll
the number is python version .

if the file is exist delete it.

and then this issue will be solve.

Body:
I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:

>>> import win32api
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.

I'm on Windows 10 Home 64x. I've already tried

pip install pypiwin32

And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I import django, so I think it's a win32api issue only.

>>> import win32api

I expect the output to be none, but the actual output is always that error ^^


问:
How to convert list of fields into json object
I have list of fields as a string:

```<code>[
"Container.Description",
"Container.Groups.12.Users.11.Name",
"Container.Groups.12.Users.12.Name",
"Container.Groups.13.Users.21.Name",
"Container.Groups.13.Users.22.Name"
]
</code>```

Is there a way to convert this array of fields to json object like:

```<code>{
  "Container": {
    "Description": "",
    "Groups": [
      {
        "12": {
          "Users": [
            { "11": { "Name": "" }},
            { "12": { "Name": "" }}
          ]
        }
      },
      {
        "13": {
          "Users": [
            { "21": { "Name": "" }},
            { "22": { "Name": "" }}
          ]
        }
      }
    ]
  }
}
</code>```

I need this code into typescript or c#.
Thanks in advance.

答:
It maybe not a very good solution, but it indeed works...</p>
```<code>    handleData(data: string[]) {
        const res = {};

        data.forEach(dataItem => this.changeObjectByStr(res, dataItem));

        return res;
    }

    private changeObjectByStr(currentObject: { [key: string]: any }, str: string) {
        const keyList = str.split('.');
        let usedObject = currentObject;

        for (let i = 0; i < keyList.length; i++) {
            const key = keyList[i];

            // The key existed
            if (usedObject[key]) {
                usedObject = usedObject[key];
                continue;
            }

            // The key not exist:
            // This is the last key
            if (i === keyList.length - 1) {
                usedObject[key] = '';
            } else {
                // This is not the last key
                usedObject[key] = {};
                usedObject = usedObject[key];
            }
        }
    }

</code>```

Body:
I have list of fields as a string:

[
"Container.Description",
"Container.Groups.12.Users.11.Name",
"Container.Groups.12.Users.12.Name",
"Container.Groups.13.Users.21.Name",
"Container.Groups.13.Users.22.Name"
]

Is there a way to convert this array of fields to json object like:

{
  "Container": {
    "Description": "",
    "Groups": [
      {
        "12": {
          "Users": [
            { "11": { "Name": "" }},
            { "12": { "Name": "" }}
          ]
        }
      },
      {
        "13": {
          "Users": [
            { "21": { "Name": "" }},
            { "22": { "Name": "" }}
          ]
        }
      }
    ]
  }
}

I need this code into typescript or c#.
Thanks in advance.

Body:
It maybe not a very good solution, but it indeed works...

    handleData(data: string[]) {
        const res = {};

        data.forEach(dataItem => this.changeObjectByStr(res, dataItem));

        return res;
    }

    private changeObjectByStr(currentObject: { [key: string]: any }, str: string) {
        const keyList = str.split('.');
        let usedObject = currentObject;

        for (let i = 0; i < keyList.length; i++) {
            const key = keyList[i];

            // The key existed
            if (usedObject[key]) {
                usedObject = usedObject[key];
                continue;
            }

            // The key not exist:
            // This is the last key
            if (i === keyList.length - 1) {
                usedObject[key] = '';
            } else {
                // This is not the last key
                usedObject[key] = {};
                usedObject = usedObject[key];
            }
        }
    }


问:
Spring/React Web application wont load the page and get stack overflow error
```<code>import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class HomeController {
  @GetMapping(value = {"/"})
  public String forward() {
    return "forward:/";
  }
}
</code>```

When I start the server and try to load up the webpage it gives me this error over and over "ERROR 6880 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception"

I suspect it has something to do with my HomeController class not being able to communicate with the react side of things. I had this all working before and started the project back up recently and now it wont load properly.

Here is a snippet of my pom file.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>reviews</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>reviews</name>
    <description>Launch Group Project</description>
    <properties>
        <java.version>11</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <frontend-plugin.version>1.7.6</frontend-plugin.version>
        <node.version>v14.15.0</node.version>
        <yarn.version>v1.16.0</yarn.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
</code>```

And a snippet of the client side error

```<code>There was an unexpected error (type=Internal Server Error, status=500).
No message available
java.lang.StackOverflowError
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244)
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244)
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244)
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244)
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583)
</code>```

答:
aren't you forwarding to the same URL? when entering "/" endpoint you forward to "another" endpoint with address "/" which is the same... so infinite loop occurs?

you can test if app works correctly by switching to @RestController and as a response displaying some string message.

If you want to enter the app from react side, you might need to setup @CrossOrigin as well, you can use "*" (allow all) for testing.

Body:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class HomeController {
  @GetMapping(value = {"/"})
  public String forward() {
    return "forward:/";
  }
}

When I start the server and try to load up the webpage it gives me this error over and over "ERROR 6880 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception"

I suspect it has something to do with my HomeController class not being able to communicate with the react side of things. I had this all working before and started the project back up recently and now it wont load properly.

Here is a snippet of my pom file.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>reviews</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>reviews</name>
    <description>Launch Group Project</description>
    <properties>
        <java.version>11</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <frontend-plugin.version>1.7.6</frontend-plugin.version>
        <node.version>v14.15.0</node.version>
        <yarn.version>v1.16.0</yarn.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

And a snippet of the client side error

There was an unexpected error (type=Internal Server Error, status=500).
No message available
java.lang.StackOverflowError
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244)
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244)
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244)
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244)
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583)


问:
Chrome printing website, missing layout options
I've been creating a website and a portion of the site is designed to be printed on tabloid paper in portrait mode. The problem I'm having is when the print dialog comes up in Chrome it's missing the "Layout" options.

In this screen shot, the left side shows how my dialog box looks vs. how it looks when I print other websites. The ironic thing is even other sites I've created have the option as shown on the right, which is the desired behavior.

My question is, what controls this behavior? How do I correct it? In searching the web the only mention I've see of this is when Chrome is displaying PDF files, but I'm displaying a web page.

Any insight you can give would be greatly appreciated.

Thanks in advance

答:
Just a quick addition to the accepted answer..

For those who are unable to edit the css of the page you're trying to print, you can install the Chrome extension called 'Stylus' (link here), and create a new style with just the above suggestion:

```<code>@page {
  size: auto;
}
</code>```

This will enable the missing options from the print dialog on any/every web page..

Body:
Just a quick addition to the accepted answer..

For those who are unable to edit the css of the page you're trying to print, you can install the Chrome extension called 'Stylus' (link here), and create a new style with just the above suggestion:

@page {
  size: auto;
}

This will enable the missing options from the print dialog on any/every web page..


问:
c++ heuristic for estimating function inlining benefits
In c++, what is a good heuristic for estimating the compute time benefits of inlining a function, particularly when the function is called very frequently and accounts for >= 10% of the program's execution time (eg. the evaluation function of a brute force or stochastic optimization process). Even though inlining may be ultimately beyond my control, I am still curious.</p>

答: A function call and return on some architectures take as few as one instruction each (although they're generally not RISC-like single-cycle instructions.) In general, you can compare that to the number of cycles represented by the body of the function. A simple property access might be only a single instruction, and so putting it into a non-inlined function will triple the number of instructions to execute  it -- obviously a great candidate for inlining. On the other hand, a function that formats a string for printing might represent hundreds of instructions, so two more isn't going to make any difference at all.</p>


问:
Is it possible to draw 3d segments with CGAL?
I want to draw 3d segments, and the camera can rotate, so that I can observe the segments from various perspectives. I wonder if there is a way to draw them with CGAL? I know that CGAL is not specific for visualization, so the question itself may be some kind of silly. But it will be really helpful for me if it has this function, because I have some experience with CGAL.
I have tried to learn OpenGL, but it's not possible for me to master it in a short time. And I don't want to spend much time to learn OpenGL, because I will not use it again in future work.

If CGAL doesn't have this function, could you please recommend some lightweight open source libraries which can draw 3d segments? I don't need a very feature-rich, but huge library. One easy to use and lightweight is best for me. Thanks a lot!

答:
Following Marc Glisse's and gdamiand's advice, I imitated the class SimpleTriangulation3ViewerQt in file draw_triangulation3.h and wrote a class named SimpleSegments3ViewerQt. It does work. Thanks for your advice! Here is the code.

```<code>#pragma once
#include<CGAL/Qt/Basic_viewer_qt.h>

//a struct that describes 3d segment, Point is the data structure of vertex of segment.
template<typename Point>
struct mySegment3d {
    Point begin;
    Point end;
    mySegment3d() {}
    mySegment3d(Point b,Point e):begin(b),end(e){}
};

#ifdef CGAL_USE_BASIC_VIEWER

#include<CGAL/Qt/init_ogl_context.h>

//viewer for mySegment3d
//Segs3 is an array of mySegment3d which can be traveled by iterator, such as std::veector<mySegment3d>.
template<class Segs3,class point>
class SimpleSegments3ViewerQt :public CGAL::Basic_viewer_qt
{
    typedef Basic_viewer_qt         Base;
    typedef mySegment3d<point>      mySegment3d;

public:
    //construct the viewer
    SimpleSegments3ViewerQt(QWidget* parent,
        const Segs3& seg3,
        const char* title = "Basic Segs3 Viewer") :
        //First draw: vertices, edges, faces, multi-color, no inverse normal
        Base(parent, title, true, true, false, false, true),
        s3(seg3)
    {
        compute_elements();
    }
protected:
    const Segs3& s3;
protected:
    void compute_edge(const mySegment3d& seg) {
        add_segment(seg.begin, seg.end, CGAL::IO::blue());
    }
    void compute_vertex(const mySegment3d& seg) {
        add_point(seg.begin, CGAL::IO::red());
        add_point(seg.end,CGAL::IO::red());
    }
    void compute_elements() {
        clear();
        for (auto itor = s3.begin(); itor != s3.end(); ++itor) {
            compute_vertex(*itor);
            compute_edge(*itor);
        }
    }
    virtual void keyPressEvent(QKeyEvent* e) {
        Base::keyPressEvent(e);
    }
};

//draw function
template<typename Segs3,typename Point>
void draw(const Segs3& s3, const char* title = "Segs3 Basic Viewer") {
#if defined(CGAL_TEST_SUITE)
    bool cgal_test_suite = true;
#else
    bool cgal_test_suite = qEnvironmentVariableIsSet("CGAL_TEST_SUITE");
#endif
    if (!cgal_test_suite) {
        CGAL::Qt::init_ogl_context(4, 3);
        int argc = 1;
        const char* argv[2] = { "segs3_viewer","\0" };
        QApplication app(argc, const_cast<char**>(argv));

        SimpleSegments3ViewerQt<Segs3,Point> mainwindow(app.activeWindow(),
            s3, title);
        mainwindow.show();
        app.exec();
    }
}

#endif
</code>```

Here is an example of usage.

```<code>#include<vector>
#include<CGAL/Simple_cartesian.h>
#include"draw_segments_3.h"
typedef CGAL::Simple_cartesian<double> kernel;
typedef kernel::Point_3 Point_3;
//draw_segments3 test
int main() {
    std::vector<mySegment3d<Point_3>> segs;
    Point_3 p0(0, 0, 0), p1(1, 2, 3), p2(5, 3, 1), p3(3, 1, 10);
    mySegment3d<Point_3> s0(p0, p1), s1(p0, p2), s2(p0, p3);
    segs.emplace_back(s0);
    segs.emplace_back(s1);
    segs.emplace_back(s2);
    draw<std::vector<mySegment3d<Point_3>>,Point_3>(segs);
}
</code>```

Body:
Following Marc Glisse's and gdamiand's advice, I imitated the class SimpleTriangulation3ViewerQt in file draw_triangulation3.h and wrote a class named SimpleSegments3ViewerQt. It does work. Thanks for your advice! Here is the code.

#pragma once
#include<CGAL/Qt/Basic_viewer_qt.h>

//a struct that describes 3d segment, Point is the data structure of vertex of segment.
template<typename Point>
struct mySegment3d {
    Point begin;
    Point end;
    mySegment3d() {}
    mySegment3d(Point b,Point e):begin(b),end(e){}
};

#ifdef CGAL_USE_BASIC_VIEWER

#include<CGAL/Qt/init_ogl_context.h>

//viewer for mySegment3d
//Segs3 is an array of mySegment3d which can be traveled by iterator, such as std::veector<mySegment3d>.
template<class Segs3,class point>
class SimpleSegments3ViewerQt :public CGAL::Basic_viewer_qt
{
    typedef Basic_viewer_qt         Base;
    typedef mySegment3d<point>      mySegment3d;

public:
    //construct the viewer
    SimpleSegments3ViewerQt(QWidget* parent,
        const Segs3& seg3,
        const char* title = "Basic Segs3 Viewer") :
        //First draw: vertices, edges, faces, multi-color, no inverse normal
        Base(parent, title, true, true, false, false, true),
        s3(seg3)
    {
        compute_elements();
    }
protected:
    const Segs3& s3;
protected:
    void compute_edge(const mySegment3d& seg) {
        add_segment(seg.begin, seg.end, CGAL::IO::blue());
    }
    void compute_vertex(const mySegment3d& seg) {
        add_point(seg.begin, CGAL::IO::red());
        add_point(seg.end,CGAL::IO::red());
    }
    void compute_elements() {
        clear();
        for (auto itor = s3.begin(); itor != s3.end(); ++itor) {
            compute_vertex(*itor);
            compute_edge(*itor);
        }
    }
    virtual void keyPressEvent(QKeyEvent* e) {
        Base::keyPressEvent(e);
    }
};

//draw function
template<typename Segs3,typename Point>
void draw(const Segs3& s3, const char* title = "Segs3 Basic Viewer") {
#if defined(CGAL_TEST_SUITE)
    bool cgal_test_suite = true;
#else
    bool cgal_test_suite = qEnvironmentVariableIsSet("CGAL_TEST_SUITE");
#endif
    if (!cgal_test_suite) {
        CGAL::Qt::init_ogl_context(4, 3);
        int argc = 1;
        const char* argv[2] = { "segs3_viewer","\0" };
        QApplication app(argc, const_cast<char**>(argv));

        SimpleSegments3ViewerQt<Segs3,Point> mainwindow(app.activeWindow(),
            s3, title);
        mainwindow.show();
        app.exec();
    }
}

#endif

Here is an example of usage.

#include<vector>
#include<CGAL/Simple_cartesian.h>
#include"draw_segments_3.h"
typedef CGAL::Simple_cartesian<double> kernel;
typedef kernel::Point_3 Point_3;
//draw_segments3 test
int main() {
    std::vector<mySegment3d<Point_3>> segs;
    Point_3 p0(0, 0, 0), p1(1, 2, 3), p2(5, 3, 1), p3(3, 1, 10);
    mySegment3d<Point_3> s0(p0, p1), s1(p0, p2), s2(p0, p3);
    segs.emplace_back(s0);
    segs.emplace_back(s1);
    segs.emplace_back(s2);
    draw<std::vector<mySegment3d<Point_3>>,Point_3>(segs);
}


答:
Order the dataframe beforehand:

base R

currTab[order(currTab$`Age range`),]
```
<p><strong>dplyr</strong></p>
<pre class="lang-r prettyprint-override"><code>currTab %>%
  arrange(`Age range`)
</code>```

output

```<code>currTab %>%
  arrange(`Age range`) %>%
  gt(rowname_col = "Age range")  %>%
  tab_stubhead(label="Age range")  %>%
  tab_spanner(
    label = "Female speakers",
    columns = c(minF_Female,maxF_Female,nominalF1_Female,   nominalF2_Female,nominalF3_Female)
  ) %>%
  tab_spanner(
    label = "Male speakers",
    columns = c(minF_Male,maxF_Male,nominalF1_Male, nominalF2_Male,nominalF3_Male)
  ) %>%
  cols_label(
    minF_Female = "minF",
    maxF_Female = "maxF",
    nominalF1_Female = "nominalF1",
    nominalF2_Female = "nominalF2",
    nominalF3_Female = "nominalF3" ,
    minF_Male = "minF",
    maxF_Male = "maxF",
    nominalF1_Male = "nominalF1",
    nominalF2_Male = "nominalF2",
    nominalF3_Male = "nominalF3"
  ) %>%
  fmt_integer(
    columns = minF_Female:nominalF3_Male,
    use_seps=FALSE
  ) %>%
  fmt_missing(everything(),missing_text="---")
</code>```

Title: gt tables not honoring factors levels in row labels

Body:
I have a silly problem in making a table using the otherwise excellent gt package.

I have this table:

currTab <- structure(list(`Age range` = structure(c(5L, 6L, 7L, 8L, 9L,
10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 1L, 2L, 3L, 4L), .Label = c(" ≤1 year",
"2 yrs", "3 yrs", "4 yrs", "5 yrs", "6 yrs", "7-8 yrs", "9-10 yrs",
"11-12 yrs", "13-14 yrs", "15-16 yrs", "19-30 yrs", "31-40 yrs",
"41-50 yrs", "51-60 yrs", "61-70 yrs", " ≥70 yrs"), class = c("ordered",
"factor")), minF_Female = c(192.513259215355, 183.831034165788,
171.923523427238, 158.002976410505, 146.564781760376, 137.789704831087,
127.370737204799, 128.398075852923, 127.830665246427, 114.61707107954,
90.3633466641061, 78.010313243078, 78.1870193570691, NA, NA,
NA, NA), minF_Male = c(207.855719860607, 191.535711870608, 169.079769539432,
142.555089696259, 120.190679816665, 102.112304160514, 79.4522096443978,
74.5501293799995, 74.0560562513096, 69.8375905638724, 57.7437980326593,
49.4092475281028, 48.9416497200912, NA, NA, NA, NA), maxF_Female = c(488.066672846171,
489.629983633728, 490.630420606523, 489.6953109154, 485.997969341596,
479.493366060129, 457.131832057242, 386.052841894336, 356.20654778542,
432.373754791911, 550.984958319451, 599.030148485128, 622.392016651455,
NA, NA, NA, NA), maxF_Male = c(386.491941716704, 383.013074412721,
377.262604560802, 368.664103740006, 358.88619036232, 347.858049187743,
321.425630395873, 258.610024319393, 223.40438098279, 272.562362517114,
352.663065356397, 389.139726222453, 396.387425129329, NA, NA,
NA, NA), nominalF1_Female = c(792.606585070623, 774.67333252336,
748.978655452818, 716.766904166985, 687.067342631714, 659.942877422917,
613.464127049404, 549.839814945283, 524.453021680478, 524.604252664451,
511.016250159981, 490.803284150502, 486.151004978768, 870.189435502058,
849.931906280897, 830.243701660919, 811.132651353652), nominalF1_Male = c(754.927353762102,
735.91406180303, 708.672474530183, 674.554785316654, 643.185788473706,
614.682090933963, 565.988043403975, 499.441794119581, 471.850496193325,
467.279224258147, 461.886047442941, 458.911042417315, 509.566754276534,
837.039982744214, 815.632443409745, 794.801313106926, 774.561360377223
), nominalF2_Female = c(2316.79654051926, 2274.86292176996, 2214.51473531373,
2138.33574040433, 2067.34402899125, 2001.61879507854, 1885.76397373785,
1714.61348292451, 1625.93585114191, 1622.14234117408, 1641.9648727809,
1707.39999135551, 1820.70094063161, 2497.1503947177, 2450.18163132232,
2404.46219881265, 2359.99840070589), nominalF2_Male = c(2204.72154293521,
2158.60270220094, 2092.40242942714, 2009.22489043384, 1932.3313895761,
1861.92275643787, 1740.32902601832, 1567.84624090872, 1487.1049441955,
1467.78392743302, 1499.7012515019, 1581.48607357091, 1689.73201386241,
2403.51904879437, 2351.72182188825, 2301.30633827736, 2252.29783346018
), nominalF3_Female = c(3716.13980758452, 3629.61667155808, 3506.02757238294,
3351.95172828646, 3211.26448866239, 3084.53931579307, 2871.44540359288,
2591.76336829096, 2553.30039539724, 2581.55257096308, 2593.29167872634,
2617.84457067156, 2692.78060751014, 3695.7825841822, 3626.26881435704,
3558.60405424272, 3805.66484270251), nominalF3_Male = c(3398.97976277625,
3327.2795690819, 3224.61918529811, 3096.22641948377, 2978.49201056792,
2871.90468878882, 2690.5686257907, 2445.67764464339, 2369.21560078373,
2361.71802712342, 2414.55734269414, 2497.82856943456, 2539.1115058239,
3557.20819221567, 3480.54829639461, 3405.93338065049, 3473.04043452418
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-17L))

in which the Age range column is a factor:

> levels(currTab$`Age range`)
 [1] " ≤1 year"  "2 yrs"     "3 yrs"     "4 yrs"     "5 yrs"     "6 yrs"     "7-8 yrs"   "9-10 yrs"  "11-12 yrs" "13-14 yrs" "15-16 yrs"
[12] "19-30 yrs" "31-40 yrs" "41-50 yrs" "51-60 yrs" "61-70 yrs" " ≥70 yrs"

and apply this formating code:

currTab %>%
  gt(rowname_col = "Age range")  %>%
  tab_stubhead(label="Age range")  %>%
  tab_spanner(
    label = "Female speakers",
    columns = c(minF_Female,maxF_Female,nominalF1_Female,   nominalF2_Female,nominalF3_Female)
  ) %>%
  tab_spanner(
    label = "Male speakers",
    columns = c(minF_Male,maxF_Male,nominalF1_Male, nominalF2_Male,nominalF3_Male)
  ) %>%
    cols_label(
    minF_Female = "minF",
    maxF_Female = "maxF",
    nominalF1_Female = "nominalF1",
    nominalF2_Female = "nominalF2",
    nominalF3_Female = "nominalF3" ,
    minF_Male = "minF",
    maxF_Male = "maxF",
    nominalF1_Male = "nominalF1",
    nominalF2_Male = "nominalF2",
    nominalF3_Male = "nominalF3"
  ) %>%
  fmt_integer(
    columns = minF_Female:nominalF3_Male,
    use_seps=FALSE
  ) %>%
  fmt_missing(everything(),missing_text="---")

and get this table:

As you can imagine, I would prefer the Age range column to follow the factor levels, and not place the first ones with empty columns at the end like that.

Any ideas?

Fredrik

Body:
Order the dataframe beforehand:

base R

currTab[order(currTab$`Age range`),]

dplyr

currTab %>%
  arrange(`Age range`)

output

currTab %>%
  arrange(`Age range`) %>%
  gt(rowname_col = "Age range")  %>%
  tab_stubhead(label="Age range")  %>%
  tab_spanner(
    label = "Female speakers",
    columns = c(minF_Female,maxF_Female,nominalF1_Female,   nominalF2_Female,nominalF3_Female)
  ) %>%
  tab_spanner(
    label = "Male speakers",
    columns = c(minF_Male,maxF_Male,nominalF1_Male, nominalF2_Male,nominalF3_Male)
  ) %>%
  cols_label(
    minF_Female = "minF",
    maxF_Female = "maxF",
    nominalF1_Female = "nominalF1",
    nominalF2_Female = "nominalF2",
    nominalF3_Female = "nominalF3" ,
    minF_Male = "minF",
    maxF_Male = "maxF",
    nominalF1_Male = "nominalF1",
    nominalF2_Male = "nominalF2",
    nominalF3_Male = "nominalF3"
  ) %>%
  fmt_integer(
    columns = minF_Female:nominalF3_Male,
    use_seps=FALSE
  ) %>%
  fmt_missing(everything(),missing_text="---")


问:
Problem with "this" in JS
Consider the following code:

```<code>    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);
</code>```

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

答:
What your looking for is a constructor method/pattern.
Now when you call one of the instantiated objects methods (eg. newTable.removeStripes() ) the context (this) is set to newTable. I believe you can always change the context however with newTable.removeStripes.call(someOtherTableOrObject) which comes in handy in a lot of cases.</p>

```<code>function Table(tableId) {

    this.tableId = tableId;
    this.table = $("#" + tableId);

    this.removeStripes = function() {
        this.table.find(".alt").removeClass("alt");
    };

    this.addStripes = function () {
        this.table.find("tbody tr:even").addClass("alt");
    };

    this.resetStripes = function() {
        this.removeStripes();
        this.addStripes();
    };

    this.sort = function (options) {
        this.table.tablesorter(options);
        this.table.bind("sortEnd", this.resetStripes);
    };

}

var newTable = new Table("tableId");
var options = {};
newTable.sort(options);
</code>```

Title: Problem with "this" in JS

Body:
Consider the following code:

    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

Body:
What your looking for is a constructor method/pattern.
Now when you call one of the instantiated objects methods (eg. newTable.removeStripes() ) the context (this) is set to newTable. I believe you can always change the context however with newTable.removeStripes.call(someOtherTableOrObject) which comes in handy in a lot of cases.

function Table(tableId) {

    this.tableId = tableId;
    this.table = $("#" + tableId);

    this.removeStripes = function() {
        this.table.find(".alt").removeClass("alt");
    };

    this.addStripes = function () {
        this.table.find("tbody tr:even").addClass("alt");
    };

    this.resetStripes = function() {
        this.removeStripes();
        this.addStripes();
    };

    this.sort = function (options) {
        this.table.tablesorter(options);
        this.table.bind("sortEnd", this.resetStripes);
    };

}

var newTable = new Table("tableId");
var options = {};
newTable.sort(options);


问:
How to create a costum JSON response in Spring Java?
Currently, I am  trying to return a costum created response from my REST API. My goal is to create the following response.

```<code>{
   "status": "Success",
   "message": "More details here",
   "data": {
      "records": [
         {
            "record": "Lorem ipsum",
            "code": 0,
            "errors": null
         },
         {
            "record": "Lorem ipsum",
            "code": 1,
            "errors": [
               "First error",
               "Second error"
            ]
         }
      ]
   }
}
</code>```

My API endpoint looks like the following.

```<code>@PostMapping(value="/my-url",
   consumes=MediaType.APPLICATION_JSON_VALUE,
   produces=MediaType.APPLICATION_JSON_VALUE)
public Response check_records(@RequestBody(required=true) Records records) {
   // Do Stuff
}
</code>```

The 'Response' class:

```<code>public class Response {
   private String status;
   private String message;
   private Map<String, List<RecordResponse>> data;

   // Default getter / setter
}
</code>```

The 'RecordResponse' class:

```<code>public class RecordResponse {
   private String record;
   private Integer code;
   private String[] errors;
</code>```

The response itself is returning anything but JSON. Neither way it is returning an error or returns the object reference in the json:

```<code>{
   "status": "Success",
   "message": "More details here",
   "data": {com.example.restservice.data@2071af5d}
}
</code>```

答:
You can use generics to have a decent typecontroll for your response wrapper

```<code>public class Response<T> {
   private String status;
   private String message;
   private T data;

   //all args contructor
}
</code>```

and

```<code>public class Records{
  List<RecordResponse> records;
}

public class RecordResponse {
   private String record;
   private Integer code;
   private String[] errors;

public Response<Records> check_records(@RequestBody(required=true) Records records) {
    RecordResponse recordResponses=//build responses
    Records records=//build records
    return new Response<Records>(status,message,records);
}
</code>```

This should produce response close if not exact as you have requested

Body:
Currently, I am  trying to return a costum created response from my REST API. My goal is to create the following response.

{
   "status": "Success",
   "message": "More details here",
   "data": {
      "records": [
         {
            "record": "Lorem ipsum",
            "code": 0,
            "errors": null
         },
         {
            "record": "Lorem ipsum",
            "code": 1,
            "errors": [
               "First error",
               "Second error"
            ]
         }
      ]
   }
}

My API endpoint looks like the following.

@PostMapping(value="/my-url",
   consumes=MediaType.APPLICATION_JSON_VALUE,
   produces=MediaType.APPLICATION_JSON_VALUE)
public Response check_records(@RequestBody(required=true) Records records) {
   // Do Stuff
}

The 'Response' class:

public class Response {
   private String status;
   private String message;
   private Map<String, List<RecordResponse>> data;

   // Default getter / setter
}

The 'RecordResponse' class:

public class RecordResponse {
   private String record;
   private Integer code;
   private String[] errors;

The response itself is returning anything but JSON. Neither way it is returning an error or returns the object reference in the json:

{
   "status": "Success",
   "message": "More details here",
   "data": {com.example.restservice.data@2071af5d}
}

Body:
You can use generics to have a decent typecontroll for your response wrapper

public class Response<T> {
   private String status;
   private String message;
   private T data;

   //all args contructor
}

and

public class Records{
  List<RecordResponse> records;
}

public class RecordResponse {
   private String record;
   private Integer code;
   private String[] errors;

public Response<Records> check_records(@RequestBody(required=true) Records records) {
    RecordResponse recordResponses=//build responses
    Records records=//build records
    return new Response<Records>(status,message,records);
}

This should produce response close if not exact as you have requested


问:
Changing a specific property inside an object changes that same property in another object of the same type Typescript
I have a really weird problem, let me just explain:

```<code>Obj1: DetailsType = {property1: 123, property2: [{subProp1: 'a', subProp2: 'b'}]}
Obj2: DetailsType = new DetailsType(Obj1)
</code>```

This is the constructor of DetailsType:

```<code>constructor(value: DetailsType = <DetailsType>{}){
    this.property1 = (value.property1 !== undefined) ? value.property1 : null
    this.property2 = (value.property2 !== undefined) ? value.property2 : []
}
</code>```

Now I run the following code

```<code>this.Obj2.property1 = 987
this.Obj2.property2[0].subProp1 = 'z'
</code>```

At this point, for some reason, the value of Obj1.property2[0].subProp1 is 'z' Even though we changed the value of subProp1 for Obj2! However, Obj1.property1 is still 123

So why does changing property2 which is an array, affect the value on both objects?? How can property1, a number, work correctly, but property2 work so weirdly? It works vice versa, whether I change subProp1 for Obj1 or Obj2. I'm so confused.

Thanks for your help!

答:
The current answer (with JSON.stringify) is maybe not the worst, because it will work in this case. But we don't know, how your objects in the array of prop2 will actually look like. Because it is a TypeScript class, it could be, that you also add some methods to it. With JSON.stringify though, all methods/functions would be lost. Only the value-properties are retained, but also not in the right order. The result is just some anonymous object.

Because it is sometimes necessary to clone objects (and not have their properties referenced to the original object), it is pretty useful to add a .clone() function that can be used with every object and array.

This will work by just adding the following code:

```<code>(<any>Object.prototype).clone = function() {
  const clone = (this instanceof Array) ? [] : {};
  for (const propertyName in this) {
    if (propertyName == 'clone') continue;
    if (this[propertyName] && typeof this[propertyName] == "object") {
      clone[propertyName] = this[propertyName].clone();
    } else clone[propertyName] = this[propertyName]
  } return clone;
};
</code>```

With your given code, it will look like this (pretty clean):

```<code>class DetailsType {
  public prop1;
  public prop2;
  constructor(value) {
    this.prop1 = value.prop1 !== undefined ? value.prop1 : null;
    this.prop2 = value.prop2 !== undefined ? value.prop2.clone() : [];
  }
}
</code>```

The .clone() method works both for arrays and objects and will create a deep copy.

Body:
I have a really weird problem, let me just explain:

Obj1: DetailsType = {property1: 123, property2: [{subProp1: 'a', subProp2: 'b'}]}
Obj2: DetailsType = new DetailsType(Obj1)

This is the constructor of DetailsType:

constructor(value: DetailsType = <DetailsType>{}){
    this.property1 = (value.property1 !== undefined) ? value.property1 : null
    this.property2 = (value.property2 !== undefined) ? value.property2 : []
}

Now I run the following code

this.Obj2.property1 = 987
this.Obj2.property2[0].subProp1 = 'z'

At this point, for some reason, the value of Obj1.property2[0].subProp1 is 'z' Even though we changed the value of subProp1 for Obj2! However, Obj1.property1 is still 123

So why does changing property2 which is an array, affect the value on both objects?? How can property1, a number, work correctly, but property2 work so weirdly? It works vice versa, whether I change subProp1 for Obj1 or Obj2. I'm so confused.

Thanks for your help!

Body:
The current answer (with JSON.stringify) is maybe not the worst, because it will work in this case. But we don't know, how your objects in the array of prop2 will actually look like. Because it is a TypeScript class, it could be, that you also add some methods to it. With JSON.stringify though, all methods/functions would be lost. Only the value-properties are retained, but also not in the right order. The result is just some anonymous object.

Because it is sometimes necessary to clone objects (and not have their properties referenced to the original object), it is pretty useful to add a .clone() function that can be used with every object and array.

This will work by just adding the following code:

(<any>Object.prototype).clone = function() {
  const clone = (this instanceof Array) ? [] : {};
  for (const propertyName in this) {
    if (propertyName == 'clone') continue;
    if (this[propertyName] && typeof this[propertyName] == "object") {
      clone[propertyName] = this[propertyName].clone();
    } else clone[propertyName] = this[propertyName]
  } return clone;
};

With your given code, it will look like this (pretty clean):

class DetailsType {
  public prop1;
  public prop2;
  constructor(value) {
    this.prop1 = value.prop1 !== undefined ? value.prop1 : null;
    this.prop2 = value.prop2 !== undefined ? value.prop2.clone() : [];
  }
}

The .clone() method works both for arrays and objects and will create a deep copy.


问:
Find the largest Pair in an integer
I'm playing around with numbers, and I'm looking to write a small program that will return the largest double-digit of an integer that's passed in for example:

I pass in 2215487
it should return 87

I pass in 98765499
It should return 99

I've tried looking at Math.Max, but I don't believe that's what I'm looking for unless I have overlooked it

答:
A very simple solution would be as follows:

```<code>    var thenumber = 987654990;
    var s = thenumber.ToString();
    var max = 0;
    for (var i = 0; i < s.Length-1; i++) {
        int d1 = (int)(s[i] - '0');
        int d2 = (int)(s[i+1] - '0');
        max = Math.Max(max, 10*d1+ d2);
    }
    Console.WriteLine(max);
</code>```

Ie, just iterate over the number and calculate the "pair" at the current position (consisting of the current digit d1 and the next one d2) if the pair is greater than the current max, make it the new max ...

Title: Find the largest Pair in an integer

Body:
A very simple solution would be as follows:

    var thenumber = 987654990;
    var s = thenumber.ToString();
    var max = 0;
    for (var i = 0; i < s.Length-1; i++) {
        int d1 = (int)(s[i] - '0');
        int d2 = (int)(s[i+1] - '0');
        max = Math.Max(max, 10*d1+ d2);
    }
    Console.WriteLine(max);

Ie, just iterate over the number and calculate the "pair" at the current position (consisting of the current digit d1 and the next one d2) if the pair is greater than the current max, make it the new max ...


问:
I am facing issu with select2 clear function to remove manual selected option
select2 clear is not working when I am select option manually and clear t by js
Here is my function to clear select2 selected option

$('#select2_id option').removeAttr('selected');

答:
Try this

```<code>$('#select2_id').val('').trigger('change);
</code>```

Instead of

```<code>$('#select2_id option').removeAttr('selected');
</code>```

Body:
Try this

$('#select2_id').val('').trigger('change);

Instead of

$('#select2_id option').removeAttr('selected');


问:
Jupyter command `jupyter-lab` not found
I have tried to install jupyter lab on my Kubuntu machine.
If I install jupyter lab with 'pip3 install jupyter jupyterlab' the command 'jupyter notebook' works completly fine. But if I try to run 'jupyter lab' every time I get the message:

```<code>Traceback (most recent call last):
  File "/usr/local/bin/jupyter", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.6/dist-packages/jupyter_core/command.py", line 230, in main
    command = _jupyter_abspath(subcommand)
  File "/usr/local/lib/python3.6/dist-packages/jupyter_core/command.py", line 133, in _jupyter_abspath
    'Jupyter command `{}` not found.'.format(jupyter_subcommand)
Exception: Jupyter command `jupyter-lab` not found.
</code>```

What is wrong?

I tried to reinstall jupyter and jupyterlab multiple times with the same issue.

答:
Install with Anaconda</p>
```<code>conda install -c conda-forge notebook
conda install -c conda-forge jupyter
conda install -c conda-forge jupyter_contrib_nbextensions
</code>```

Title: Jupyter command `jupyter-lab` not found

Body:
I have tried to install jupyter lab on my Kubuntu machine.
If I install jupyter lab with 'pip3 install jupyter jupyterlab' the command 'jupyter notebook' works completly fine. But if I try to run 'jupyter lab' every time I get the message:

Traceback (most recent call last):
  File "/usr/local/bin/jupyter", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.6/dist-packages/jupyter_core/command.py", line 230, in main
    command = _jupyter_abspath(subcommand)
  File "/usr/local/lib/python3.6/dist-packages/jupyter_core/command.py", line 133, in _jupyter_abspath
    'Jupyter command `{}` not found.'.format(jupyter_subcommand)
Exception: Jupyter command `jupyter-lab` not found.

What is wrong?

I tried to reinstall jupyter and jupyterlab multiple times with the same issue.

Body:
Install with Anaconda

conda install -c conda-forge notebook
conda install -c conda-forge jupyter
conda install -c conda-forge jupyter_contrib_nbextensions