问:
Populating stateless child component props from parent component state to display nested unordered list in React (with Firebase)
I'm probably missing something very simple here, but I can't get my code to run properly. I'm trying to display a nested unordered list of referenceListItems for every referenceList. The main question I guess is how do I pass the state variable referenceListItems into the child component ReferenceListItems?

```<code>const ReferencePage = () => (
  <div>
    <h1>Reference</h1>
    <Reference />
  </div>
);

class ReferenceBase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      referenceLists: [],
      referenceListItems: [],
    };
  }

  componentDidMount() {
    this.onListenForReferenceLists();
    this.onListenForReferenceListItems();
  }

  onListenForReferenceLists() {
    this.setState({ loading: true });

    this.unsubscribeReferenceLists = this.props.firebase
      .referenceLists()
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let referenceLists = [];
          snapshot.forEach(doc =>
            referenceLists.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            referenceLists: referenceLists,
            loading: false
          });
        } else {
          this.setState({ referenceLists: null, loading: false });
        }
    });
  }

  onListenForReferenceListItems() {
    this.unsubscribeReferenceListsItems = this.props.firebase
      .referenceListItems()
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let referenceListItems = [];
          snapshot.forEach(doc =>
            referenceListItems.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            referenceListItems: referenceListItems,
            loading: false
          });
        } else {
          this.setState({ referenceListItems: null, loading: false });
        }
    });
  }

  componentWillUnmount() {
    this.unsubscribeReferenceLists();
    this.unsubscribeReferenceListsItems();
  }

  render() {
    const { referenceLists, referenceListItems, loading } = this.state;
    return (
      <div>
        {loading && <div>Loading ...</div>}
        {referenceLists ? (
          <ReferenceLists referenceLists={referenceLists} />
        ):(
          <div>There are no reference items ...</div>
        )}
      </div>
    );
  }
}

const Reference = withFirebase(ReferenceBase);

const ReferenceLists = ({ referenceLists }) => (
  <ul className="reference-lists">
    {referenceLists.map( referenceList => (
      <ReferenceList key={referenceList.uid} referenceList={referenceList} />
    ))}
  </ul>
);

const ReferenceList = ({ referenceList }) => (
  <li className="reference">
    <strong>{referenceList.userId}</strong> {referenceList.name}
    <ReferenceListItems />
  </li>
);

const ReferenceListItems =({ referenceListItems }) => (
  <ul className="reference-list-items">
    {referenceListItems.map( referenceListItem => (
      <ReferenceListItem key={referenceListItem.uid} referenceListItem={referenceListItem} />
    ))}
  </ul>
);

const ReferenceListItem = ({ referenceListItem }) => (
  <li className="reference-list-item">
    <strong>{referenceListItem.userId}</strong> {referenceListItem.name}
  </li>
);
</code>```

答:
You do not explicitly use your ReferenceListItems inside the parent ReferenceBase component. So you'll just have to pass it down as a property throughout the component tree.

```<code>  render() {
    const { referenceLists, referenceListItems, loading } = this.state;
    return (
      <div>
        {loading && <div>Loading ...</div>}
        {referenceLists ? (
          <ReferenceLists referenceLists={referenceLists} referenceListItems={referenceListItems} />
        ):(
          <div>There are no reference items ...</div>
        )}
      </div>
    );
</code>```

ReferenceLists

```<code>const ReferenceLists = ({ referenceLists, referenceListItems }) => (
  <ul className="reference-lists">
    {referenceLists.map( referenceList => (
      <ReferenceList key={referenceList.uid} referenceList={referenceList} referenceListItems={referenceListItems} />
    ))}
  </ul>
</code>```

ReferenceList

```<code>const ReferenceList = ({ referenceList, referenceListItems }) => (
  <li className="reference">
    <strong>{referenceList.userId}</strong> {referenceList.name}
    <ReferenceListItems referenceListItems={referenceListItems}/>
  </li>
);
</code>```

Body:
I'm probably missing something very simple here, but I can't get my code to run properly. I'm trying to display a nested unordered list of referenceListItems for every referenceList. The main question I guess is how do I pass the state variable referenceListItems into the child component ReferenceListItems?

const ReferencePage = () => (

Reference

    <Reference />

);

class ReferenceBase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      referenceLists: [],
      referenceListItems: [],
    };
  }

  componentDidMount() {
    this.onListenForReferenceLists();
    this.onListenForReferenceListItems();
  }

  onListenForReferenceLists() {
    this.setState({ loading: true });

    this.unsubscribeReferenceLists = this.props.firebase
      .referenceLists()
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let referenceLists = [];
          snapshot.forEach(doc =>
            referenceLists.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            referenceLists: referenceLists,
            loading: false
          });
        } else {
          this.setState({ referenceLists: null, loading: false });
        }
    });
  }

  onListenForReferenceListItems() {
    this.unsubscribeReferenceListsItems = this.props.firebase
      .referenceListItems()
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let referenceListItems = [];
          snapshot.forEach(doc =>
            referenceListItems.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            referenceListItems: referenceListItems,
            loading: false
          });
        } else {
          this.setState({ referenceListItems: null, loading: false });
        }
    });
  }

  componentWillUnmount() {
    this.unsubscribeReferenceLists();
    this.unsubscribeReferenceListsItems();
  }

  render() {
    const { referenceLists, referenceListItems, loading } = this.state;
    return (

        {loading &&
Loading ...
}
        {referenceLists ? (
          <ReferenceLists referenceLists={referenceLists} />
        ):(

There are no reference items ...

        )}

    );
  }
}

const Reference = withFirebase(ReferenceBase);

const ReferenceLists = ({ referenceLists }) => (

    {referenceLists.map( referenceList => (
      <ReferenceList key={referenceList.uid} referenceList={referenceList} />
    ))}

);

const ReferenceList = ({ referenceList }) => (

    {referenceList.userId} {referenceList.name}
    <ReferenceListItems />

);

const ReferenceListItems =({ referenceListItems }) => (

    {referenceListItems.map( referenceListItem => (
      <ReferenceListItem key={referenceListItem.uid} referenceListItem={referenceListItem} />
    ))}

);

const ReferenceListItem = ({ referenceListItem }) => (

    {referenceListItem.userId} {referenceListItem.name}

);

Body:
You do not explicitly use your ReferenceListItems inside the parent ReferenceBase component. So you'll just have to pass it down as a property throughout the component tree.

  render() {
    const { referenceLists, referenceListItems, loading } = this.state;
    return (
      <div>
        {loading && <div>Loading ...</div>}
        {referenceLists ? (
          <ReferenceLists referenceLists={referenceLists} referenceListItems={referenceListItems} />
        ):(
          <div>There are no reference items ...</div>
        )}
      </div>
    );

ReferenceLists

const ReferenceLists = ({ referenceLists, referenceListItems }) => (
  <ul className="reference-lists">
    {referenceLists.map( referenceList => (
      <ReferenceList key={referenceList.uid} referenceList={referenceList} referenceListItems={referenceListItems} />
    ))}
  </ul>

ReferenceList

const ReferenceList = ({ referenceList, referenceListItems }) => (
  <li className="reference">
    <strong>{referenceList.userId}</strong> {referenceList.name}
    <ReferenceListItems referenceListItems={referenceListItems}/>
  </li>
);


来源: stackexchange

问:
A relation between 3 tables Laravel
I'm trying to create an API resource, where I can view a response build from three tables.

Store

Orders

Purchases

Currently, I can go to a store (there are multiple stores) using routes (api/store/orders) and view the orders in a JSON response.

response

```<code>{
 data: [
  {
   id: 1,
   code: "1f",
   status: "waiting",
   user_name: "Salman",
   created_at: "",
   updated_at: ""
  },
  {
   id: 2,
   code: "2f",
   status: "waiting",
   user_name: "Jerome",
   created_at: "",
   updated_at: ""
  }
 ]
}
</code>```

However, when I try to add my purchases to the response with:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Orderresource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'code' => $this->code,
            'status' => $this->status,
            'user_name' => $this->user_name,
            // Added purchases
            'order' => $this->purchases,
            'created_at' => (string) $this->created_at,
            'updated_at' => (string) $this->updated_at,
        ];
    }
}
```

<p>I get met with an error response <code>Undefined property: stdClass::$purchases</code></p>

<p>Now I've added purchases to my order model with:</p>

```  public function purchases()
  {
    return $this->hasMany(Purchase::class);
  }
```

<p>However, I know that the order may lie with my <code>show_order_per_store.</code></p>

<p>function in my <code>OrderController</code></p>

```    public function show_order_per_club($id)
    {
      $order = DB::table('orders')->where('store_id', '=', $id)->get();

      return  Orderresource::collection($order);
    }
```

Now, this function gets all orders with similar stores, but how do I add the purchases to the stores API response?

In short, I'm trying to get an API response per store with the orders it has, and the purchases belong to that order.

答:
Instead of using DB:table for querying, try using the model directly:

```<code>Order::where('store_id', '=', $id)->get();
</code>```

Seems DB:table returns stdClass objects, so it lacks all the virtual attributes that a model might provide.

ContentLicense: CC BY-SA 4.0

Title: A relation between 3 tables Laravel

Body:
I'm trying to create an API resource, where I can view a response build from three tables.

Store

Orders

Purchases

Currently, I can go to a store (there are multiple stores) using routes (api/store/orders) and view the orders in a JSON response.

response

{
 data: [
  {
   id: 1,
   code: "1f",
   status: "waiting",
   user_name: "Salman",
   created_at: "",
   updated_at: ""
  },
  {
   id: 2,
   code: "2f",
   status: "waiting",
   user_name: "Jerome",
   created_at: "",
   updated_at: ""
  }
 ]
}

However, when I try to add my purchases to the response with:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Orderresource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'code' => $this->code,
            'status' => $this->status,
            'user_name' => $this->user_name,
            // Added purchases
            'order' => $this->purchases,
            'created_at' => (string) $this->created_at,
            'updated_at' => (string) $this->updated_at,
        ];
    }
}

I get met with an error response Undefined property: stdClass::$purchases

Now I've added purchases to my order model with:

  public function purchases()
  {
    return $this->hasMany(Purchase::class);
  }

However, I know that the order may lie with my show_order_per_store.

function in my OrderController

    public function show_order_per_club($id)
    {
      $order = DB::table('orders')->where('store_id', '=', $id)->get();

      return  Orderresource::collection($order);
    }

Now, this function gets all orders with similar stores, but how do I add the purchases to the stores API response?

In short, I'm trying to get an API response per store with the orders it has, and the purchases belong to that order.

Body:
Instead of using DB:table for querying, try using the model directly:

Order::where('store_id', '=', $id)->get();

Seems DB:table returns stdClass objects, so it lacks all the virtual attributes that a model might provide.


问:
selenium webdriver IE button issue
I have  been writing my scripts for FF but was hoping with little work they would also run on the other browsers but it seems IE driver has button issues?

I have a simple webelement.click() on a button that does not throw an error but does not click the button.  in FF its fine.  I can get text, get value so I know the find statement is ok it just will not click it.

thoughts or help would be great

Just doing

```<code>WebElement element;
element = driver.findElement(By.id("pageheader_login"));
element.click();
</code>```

HTML - The control has 3 buttons on it I am only interested for now with the login

```<code><div id="_ctl0_pageheader_navcontainer">
  <div id="phwelcome">

    <br class="clear" />
  </div>
  <span id="navtext">

    <a id="_ctl0_pageheader_lnkRegister" class="logichref"
       href="http://Register/1">Register Today</a>
    <label id="_ctl0_pageheader_lblRegisterBar" class="barhide">| </label>

    <a id="_ctl0_pageheader_customerconnection" class="logichref"
       href="http://test.com" target="_blank">Help & Training</a>
    <label class="bar">| </label>
    <a class="logichref" href="http://test.aspx"
       onmouseover="window.status='';return(true);"
       onmouseout="window.status='';return(false);"
       target="_blank">What's New</a>
    <label class="bar">| </label>
    <a id="_ctl0_pageheader_login" class="lbOn loginModal"
       href="http://test/loginlightbox.aspx">Login</a>
  </span>
</div>
</code>```

答:
Got the same problem, click does not work with my IE 8.
I found a workaround where I do a element.sendKeys("\n") to perform the click (basically I just press enter on the button).
Not very clean but it works until the bug is fixed!</p>

ContentLicense: CC BY-SA 3.0

Title: selenium webdriver IE button issue

Body:
I have  been writing my scripts for FF but was hoping with little work they would also run on the other browsers but it seems IE driver has button issues?

I have a simple webelement.click() on a button that does not throw an error but does not click the button.  in FF its fine.  I can get text, get value so I know the find statement is ok it just will not click it.

thoughts or help would be great

Just doing

WebElement element;
element = driver.findElement(By.id("pageheader_login"));
element.click();

HTML - The control has 3 buttons on it I am only interested for now with the login

    Register Today
    |

    Help & Training
    |
    What's New
    |
    Login


问:
.Net HttpWebRequest ClientCertificates not sent to API
I'm trying to call an API over HTTPS. The API expects a client certificate to be sent, which it will then validate. The API doesn't return some list of accepted CAs or so (like in a standard web server TLS flow), it just expects a certificate to validate.

On the client machine, where my app runs, the client certificate is installed in the local machine\personal store (where it also looks ok by checking it in certlm.msc). I'm able to get the certificate from the store and add it to my HttpWebRequest like so request.ClientCertificates.Add(cert). Inspecting the certificate in the app code at runtime it has a private key (HasPrivateKey is true and the PrivateKey property contains data). For testing purposes I granted everyone read access to the certificate to be sure they private key can be retrieved with the certificate from the app, seems to work.

However, the API complains no certificate was sent. Checking the request with Wireshark shows a TLSv1.2 handshake of type Certificate, however Certificate Length: 0. So indeed the certificate is not sent up.

Using Postman to call the exact same API with the exact same certificate (from a file, as Postman needs a file, the file being the .pfx from which the certificate was imported in the machine\personal store) DOES send the certificate. Wireshark shows Certificate Length: 770 and I'm able to view the certificate details.

So it seems that for some reason, even though I attach the certificate to the HttpWebRequest.ClientCertificates it doesn't get sent up from app code. There's no exception, it just won't get sent.

To recap:

HttpWebRequest.ClientCertificates contains a certificate retrieved from the machine\personal store

the certificate has a private key

the certificate (in certlm.msc) looks good (trusted CA etc)

the certificate doesn't get set up to the API

however the same certificate does get set up when calling the API from postman

the app is a .Net 4.6.1 wpf app

Any ideas what I'm missing? Thanks!

(later edit)

I debugged the SecureChannel class in the framework which is the one handling the sending of certificates and found some worrying stuff. First, some comments:

```<code>Here is how we work:
                case 0: Cert Selection delegate is present
                        Alwasys use its result as the client cert answer.
                        Try to use cached credential handle whenever feasible.
                        Do not use cached anonymous creds if the delegate has returned null
                        and the collection is not empty (allow responding with the cert later).

                case 1: Certs collection is empty
                        Always use the same statically acquired anonymous SSL Credential

                case 2: Before our Connection with the Server
                        If we have a cached credential handle keyed by first X509Certificate
                        **content** in the passed collection, then we use that cached
                        credential and hoping to restart a session.

                        Otherwise create a new anonymous (allow responding with the cert later).

                case 3: After our Connection with the Server (ie during handshake or re-handshake)
                        The server has requested that we send it a Certificate then
                        we Enumerate a list of server sent Issuers trying to match against
                        our list of Certificates, the first match is sent to the server.

                        Once we got a cert we again try to match cached credential handle if possible.
                        This will not restart a session but helps miminizing the number of handles we create.
</code>```

Debugging the code, the comments seem to hold:

first it checks for the cert selection delegate: there is none and the certificates collection contains my certificate so it moves on to step 2

here it takes my certificate, checks for a valid private key, is successful, then comes a new comment

```<code>// (see VsWhidbey#363953) For some (probably good) reason IIS does not renegotiate a restarted session if client cert is needed.
                    // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
                    // The following block happens if client did specify a certificate but no cached creds were found in the cache
                    // Since we don't restart a session the server side can still challenge for a client cert.
</code>```

... after which this code...

```<code>   if ((object)clientCertificate != (object)selectedCert)
                        selectedCert.Reset();
                    guessedThumbPrint = null;
                    selectedCert = null;
                    clientCertificate = null;
</code>```

So basically it will null the reference to the certificate I passed in. If I understand it correctly this is to work around some IIS issue and it means that it expects the server to send back a list of issuers to filter the certificates by (which would be case 3 from the comment), which is indeed what I see in the code. Only if this list of issuers comes down from the server will the code go through the client certificates and filter them by the issuers and then send the matching one(s) up.

Now I'm left wondering: is it only possible to send client certificates if the server asks for a list of issuers? Because in my case the API I'm calling does not do that, it simply expects a certificate. I hope I'm wrong and someone can shed light on this.

(even later edit)

The API I'm calling now returns a list of CAs. My test CA was added there and it is returned during the SSL handshake. Now debugging SecureChannel shows that my earlier assumptions were correct:

on first pass the certificate I added is not sent up

however after getting the CAs list from the server it's inspected for one matching my certificate's issuer and a match is indeed found!

follwing this successful match SecureChannel sets its m_SelectedClientCertificate successfully to my certificate but...

...unfortunately it STILL doesn't get sent to the server with the next step of the protocol :(

Once the SecureChannel.m_SelectedClientCertificate is set, it doesn't seem to be used from SecureChannel itself anymore but it is exposed:

```<code>internal X509Certificate LocalClientCertificate {
            get {
                return m_SelectedClientCertificate;
            }
        }
</code>```

Unfortunately this property is never called in my case :(

答: Found the problem: my certificate was signed with SHA1. Resigned with SHA256 and behold, it gets sent!</p>

Body:
I'm trying to call an API over HTTPS. The API expects a client certificate to be sent, which it will then validate. The API doesn't return some list of accepted CAs or so (like in a standard web server TLS flow), it just expects a certificate to validate.

On the client machine, where my app runs, the client certificate is installed in the local machine\personal store (where it also looks ok by checking it in certlm.msc). I'm able to get the certificate from the store and add it to my HttpWebRequest like so request.ClientCertificates.Add(cert). Inspecting the certificate in the app code at runtime it has a private key (HasPrivateKey is true and the PrivateKey property contains data). For testing purposes I granted everyone read access to the certificate to be sure they private key can be retrieved with the certificate from the app, seems to work.

However, the API complains no certificate was sent. Checking the request with Wireshark shows a TLSv1.2 handshake of type Certificate, however Certificate Length: 0. So indeed the certificate is not sent up.

Using Postman to call the exact same API with the exact same certificate (from a file, as Postman needs a file, the file being the .pfx from which the certificate was imported in the machine\personal store) DOES send the certificate. Wireshark shows Certificate Length: 770 and I'm able to view the certificate details.

So it seems that for some reason, even though I attach the certificate to the HttpWebRequest.ClientCertificates it doesn't get sent up from app code. There's no exception, it just won't get sent.

To recap:

HttpWebRequest.ClientCertificates contains a certificate retrieved from the machine\personal store

the certificate has a private key

the certificate (in certlm.msc) looks good (trusted CA etc)

the certificate doesn't get set up to the API

however the same certificate does get set up when calling the API from postman

the app is a .Net 4.6.1 wpf app

Any ideas what I'm missing? Thanks!

(later edit)

I debugged the SecureChannel class in the framework which is the one handling the sending of certificates and found some worrying stuff. First, some comments:

Here is how we work:
                case 0: Cert Selection delegate is present
                        Alwasys use its result as the client cert answer.
                        Try to use cached credential handle whenever feasible.
                        Do not use cached anonymous creds if the delegate has returned null
                        and the collection is not empty (allow responding with the cert later).

                case 1: Certs collection is empty
                        Always use the same statically acquired anonymous SSL Credential

                case 2: Before our Connection with the Server
                        If we have a cached credential handle keyed by first X509Certificate
                        **content** in the passed collection, then we use that cached
                        credential and hoping to restart a session.

                        Otherwise create a new anonymous (allow responding with the cert later).

                case 3: After our Connection with the Server (ie during handshake or re-handshake)
                        The server has requested that we send it a Certificate then
                        we Enumerate a list of server sent Issuers trying to match against
                        our list of Certificates, the first match is sent to the server.

                        Once we got a cert we again try to match cached credential handle if possible.
                        This will not restart a session but helps miminizing the number of handles we create.

Debugging the code, the comments seem to hold:

first it checks for the cert selection delegate: there is none and the certificates collection contains my certificate so it moves on to step 2

here it takes my certificate, checks for a valid private key, is successful, then comes a new comment

// (see VsWhidbey#363953) For some (probably good) reason IIS does not renegotiate a restarted session if client cert is needed.
                    // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
                    // The following block happens if client did specify a certificate but no cached creds were found in the cache
                    // Since we don't restart a session the server side can still challenge for a client cert.

... after which this code...

   if ((object)clientCertificate != (object)selectedCert)
                        selectedCert.Reset();
                    guessedThumbPrint = null;
                    selectedCert = null;
                    clientCertificate = null;

So basically it will null the reference to the certificate I passed in. If I understand it correctly this is to work around some IIS issue and it means that it expects the server to send back a list of issuers to filter the certificates by (which would be case 3 from the comment), which is indeed what I see in the code. Only if this list of issuers comes down from the server will the code go through the client certificates and filter them by the issuers and then send the matching one(s) up.

Now I'm left wondering: is it only possible to send client certificates if the server asks for a list of issuers? Because in my case the API I'm calling does not do that, it simply expects a certificate. I hope I'm wrong and someone can shed light on this.

(even later edit)

The API I'm calling now returns a list of CAs. My test CA was added there and it is returned during the SSL handshake. Now debugging SecureChannel shows that my earlier assumptions were correct:

on first pass the certificate I added is not sent up

however after getting the CAs list from the server it's inspected for one matching my certificate's issuer and a match is indeed found!

follwing this successful match SecureChannel sets its m_SelectedClientCertificate successfully to my certificate but...

...unfortunately it STILL doesn't get sent to the server with the next step of the protocol :(

Once the SecureChannel.m_SelectedClientCertificate is set, it doesn't seem to be used from SecureChannel itself anymore but it is exposed:

internal X509Certificate LocalClientCertificate {
            get {
                return m_SelectedClientCertificate;
            }
        }

Unfortunately this property is never called in my case :(


问:
How to remove duplicated words in csv rows in python?
I am working with csv file and I have many rows that contain duplicated words and I want to remove any duplicates (I also don't want to lose the order of the sentences).

csv file example (userID and description are the columns name):

```<code>userID, description

12, hello world hello world

13, I will keep the 2000 followers same I will keep the 2000 followers same

14, I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car

.

.
</code>```

I would like to have the output as:

```<code>userID, description

12, hello world

13, I will keep the 2000 followers same

14, I paid $2000 to the car

.

.
</code>```

I already tried the post such as 1 2 3 but none of them fixed my problem and did not change anything. (Order for my output file matters, since I don't want to lose the orders). It would be great if you can provide your help with a code sample that I can run in my side and learn.
Thank you

[I am using python 3.7 version]

答:
The code below works for me:

```<code>a = pd.Series(["hello world hello world",
               "I will keep the 2000 followers same I will keep the 2000 followers same",
               "I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car"])
a.apply(lambda x: " ".join([w for i, w in enumerate(x.split()) if x.split().index(w) == i]))
</code>```

Basically the idea is to, for each word, only keep it if its position is the first in the list (splitted from string using space). That means, if the word occurred the second (or more) time, the .index() function will return an index smaller than the position of current occurrence, and thus will be eliminated.

This will give you:

```<code>0                            hello world
1    I will keep the 2000 followers same
2                I paid $2000 to the car
dtype: object
</code>```

Body:
I am working with csv file and I have many rows that contain duplicated words and I want to remove any duplicates (I also don't want to lose the order of the sentences).

csv file example (userID and description are the columns name):

userID, description

12, hello world hello world

13, I will keep the 2000 followers same I will keep the 2000 followers same

14, I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car

.

.

I would like to have the output as:

userID, description

12, hello world

13, I will keep the 2000 followers same

14, I paid $2000 to the car

.

.

I already tried the post such as 1 2 3 but none of them fixed my problem and did not change anything. (Order for my output file matters, since I don't want to lose the orders). It would be great if you can provide your help with a code sample that I can run in my side and learn.
Thank you

[I am using python 3.7 version]

Body:
The code below works for me:

a = pd.Series(["hello world hello world",
               "I will keep the 2000 followers same I will keep the 2000 followers same",
               "I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car"])
a.apply(lambda x: " ".join([w for i, w in enumerate(x.split()) if x.split().index(w) == i]))

Basically the idea is to, for each word, only keep it if its position is the first in the list (splitted from string using space). That means, if the word occurred the second (or more) time, the .index() function will return an index smaller than the position of current occurrence, and thus will be eliminated.

This will give you:

0                            hello world
1    I will keep the 2000 followers same
2                I paid $2000 to the car
dtype: object


问:
Overlapping clipping issue
I have an issue where I am grabbing a users displayAvatar() and then I use an arc to make the image round. This works fine, however, I need to place a circle on top of that image, but it is getting cut in half because of the previous clip()

Without clip() : https://i.gyazo.com/b474c656f33a1f004f5e3becffcef527.png

With    clip() : https://i.gyazo.com/da13377cd3f6dc7516c2b8fd1f0f8ac9.png

I know that in the 'With clip()' image, it appears as if the arc border is showing outside of the clip, but that is hardcoded into the image, I put it as a guide with an image editor.

I tried moving around the code, I removed the line ctx.clip() and saw that my circle displays fine on top of the image.

        // circle around avatar
        ctx.beginPath();
        ctx.arc(122.5, 141.8, 81, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.clip();
        const avatar = await Canvas.loadImage(
            message.author.displayAvatarURL({ format: 'png' })
        );
        ctx.strokeStyle = '#ffffff';
        ctx.strokeRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(avatar, 41.5, 60.5, 162, 162);

        // presence circle
        ctx.beginPath();
        ctx.arc(184.5, 193.5, 19, 0, Math.PI * 2, true);
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 8;
        ctx.stroke();
        ctx.fillStyle = userStatusColor;
        ctx.fill();
```

答:
Take a look at the canvas clip() definition:

https://www.w3schools.com/tags/canvas_clip.asp

Tip: Once a region is clipped, all future drawing will be limited to the clipped region (no access to other regions on the canvas). You can however save the current canvas region using the save() method before using the clip() method, and restore it (with the restore() method) any time in the future.

Below is an example using the save and restore

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.arc(90, 90, 81, 0, Math.PI * 2, true);
ctx.stroke();

ctx.save();
ctx.clip();

ctx.beginPath();
ctx.arc(150, 50, 19, 0, Math.PI * 2, true);
ctx.fillStyle = '#0000ff';
ctx.lineWidth = 8;
ctx.stroke();
ctx.fill();

ctx.restore();

ctx.beginPath();
ctx.arc(170, 99, 19, 0, Math.PI * 2, true);
ctx.fillStyle = '#ff0000';
ctx.lineWidth = 8;
ctx.stroke();
ctx.fill();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas></code>```

Title: Overlapping clipping issue

Body:
Take a look at the canvas clip() definition:

https://www.w3schools.com/tags/canvas_clip.asp

Tip: Once a region is clipped, all future drawing will be limited to the clipped region (no access to other regions on the canvas). You can however save the current canvas region using the save() method before using the clip() method, and restore it (with the restore() method) any time in the future.

Below is an example using the save and restore

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.arc(90, 90, 81, 0, Math.PI * 2, true);
ctx.stroke();

ctx.save();
ctx.clip();

ctx.beginPath();
ctx.arc(150, 50, 19, 0, Math.PI * 2, true);
ctx.fillStyle = '#0000ff';
ctx.lineWidth = 8;
ctx.stroke();
ctx.fill();

ctx.restore();

ctx.beginPath();
ctx.arc(170, 99, 19, 0, Math.PI * 2, true);
ctx.fillStyle = '#ff0000';
ctx.lineWidth = 8;
ctx.stroke();
ctx.fill();

<canvas id="canvas"></canvas>


问:
How exactly does the onClick binding work in React?
I'm learning React JS for the first time as it is the likely approach my team will be taking at work on a new project. I am trying to understand this onClick binding behavior and what exactly it is doing.

I looked at some articles that try to explain binding specific instances of components/objects to their respective functions and they sort of make sense. But using 'this.props.onClick(i)' doesn't make much sense to me.

So does that code pass squares[i] as the props and somehow onClick within the Square component this updates the value of the button? When running the program that is what it seems to do but I just can't seem to wrap my head around this logic. Especially since I am coming from a back-end background with C# and Java. Any help would be greatly appreciated!

```<code>function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}
</code>```

Update:
The whole app. To give more context...

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null)
      }],
      xIsNext: true,
    };
  }

  handleClick(i) {
    const history = this.state.history;
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares
      }]),
      xIsNext: !this.state.xIsNext,
    });
  }

  render() {
    const history = this.state.history;
    const current = history[history.length - 1];
    const winner = calculateWinner(current.squares);

    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] == squares[b] && squares[a] == squares[c]) {
      return squares[a];
    }
  }
  return null;
}
</code>```

答:
The whole idea in react is to lift your state up.
In this code,

Game is the parent of all and it will define what happens when I click on child Square.  Instead of Square dealing with it itself,  Game keeps handling of onClick to itself and passes down to board as a prop like this.

```<code><Board squares={current.squares} onClick={(i) => this.handleClick(i)} />
</code>```

Now Board in turn passes the prop onClick it received when called from Game to it's child Square like this as a prop.

```<code><Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />
</code>```

So Game's handleClick is assigned to onClick prop of Board which is assigned to onClick prop of Square.  Thus Square tells Board that I was clicked but I don't know what to do with it.  So I will transfer responsibility to you and you can call whatever you passed me as a prop when you called me (Square).  Board does the same thing and passes responsibility to Game which actually knows that onClick I should call handleClick event that I have within me.

```<code>handleClick(i) {
    const history = this.state.history;
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares
      }]),
      xIsNext: !this.state.xIsNext,
    });
  }
</code>```

handleClick in Game passed to Board as onClick prop ->  onClick prop of Board passed to Square as onClick prop

Thus, clicking on Square becomes reverse operation then
Square says my onClick prop is actually passed by Board -> Board says my onClick prop is actually passed by Game -> Game says I know how to handleClick

Body:
I'm learning React JS for the first time as it is the likely approach my team will be taking at work on a new project. I am trying to understand this onClick binding behavior and what exactly it is doing.

I looked at some articles that try to explain binding specific instances of components/objects to their respective functions and they sort of make sense. But using 'this.props.onClick(i)' doesn't make much sense to me.

So does that code pass squares[i] as the props and somehow onClick within the Square component this updates the value of the button? When running the program that is what it seems to do but I just can't seem to wrap my head around this logic. Especially since I am coming from a back-end background with C# and Java. Any help would be greatly appreciated!

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (

          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}

          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}

          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}

    );
  }
}

Update:
The whole app. To give more context...

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (

          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}

          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}

          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}

    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null)
      }],
      xIsNext: true,
    };
  }

  handleClick(i) {
    const history = this.state.history;
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares
      }]),
      xIsNext: !this.state.xIsNext,
    });
  }

  render() {
    const history = this.state.history;
    const current = history[history.length - 1];
    const winner = calculateWinner(current.squares);

    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

    return (

          <Board
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
          />

{status}

{/* TODO */}

    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] == squares[b] && squares[a] == squares[c]) {
      return squares[a];
    }
  }
  return null;
}

Body:
The whole idea in react is to lift your state up.
In this code,

Game is the parent of all and it will define what happens when I click on child Square.  Instead of Square dealing with it itself,  Game keeps handling of onClick to itself and passes down to board as a prop like this.

<Board squares={current.squares} onClick={(i) => this.handleClick(i)} />

Now Board in turn passes the prop onClick it received when called from Game to it's child Square like this as a prop.

<Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />

So Game's handleClick is assigned to onClick prop of Board which is assigned to onClick prop of Square.  Thus Square tells Board that I was clicked but I don't know what to do with it.  So I will transfer responsibility to you and you can call whatever you passed me as a prop when you called me (Square).  Board does the same thing and passes responsibility to Game which actually knows that onClick I should call handleClick event that I have within me.

handleClick(i) {
    const history = this.state.history;
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares
      }]),
      xIsNext: !this.state.xIsNext,
    });
  }

handleClick in Game passed to Board as onClick prop ->  onClick prop of Board passed to Square as onClick prop

Thus, clicking on Square becomes reverse operation then
Square says my onClick prop is actually passed by Board -> Board says my onClick prop is actually passed by Game -> Game says I know how to handleClick


问:
Cannot find module 'mdb-calendar'
I have recently started working with Material Design Bootstrap with Angular 7. I am trying to use their calendar plugin. I copied their HTML and TS. When I run the app I get an error of:

Cannot find module 'mdb-calendar'.

I have tried to npm install mdb calendar, but it errors out. Any Ideas on how to fix this issue.

答:
It is mentioned on their site the Full Page Calendar is not included in  their MDB free bundle. So in order to use the plugin you have to buy it first. You can't use it unless you pay for it.

You can find more info here

Title: Cannot find module 'mdb-calendar'


问:
XAML For Reflection Effect
I'm a XAML/WPF newbie, and I thought I'd write an alarm clock application to get into it.  I want to get past the basic textboxes, dropdowns etc, which are fairly simple once you get the hang of the layout model, but I'd like to get into the graphics side of things.

I'd like to display alarm clock digits on a black backdrop, but importantly the alarm clock numbers to have that reflection effect like they're stood up on a piece of glass (like how Apple marketing often is implemented).

How do I get started with this?  I'm looking at Charles Petzold's stuff for inspiration but struggling a little.

答:
Actually I think that this might be easily adapted enough from an image to text:

http://www.codeproject.com/KB/WPF/WPFImageEffects.aspx

OwnerDisplayName: Neil Barnwell

ContentLicense: CC BY-SA 2.5

Title: XAML For Reflection Effect

LastEditorDisplayName: Neil Barnwell


问:
uniform keyword in HLSL
it seems that in HLSL i can but dont have to provide the uniform keyword for variables which come from the application. right?

why is that so?

答:
In HLSL global variables are considered uniform by default.

It's also settled that a variable coming out of the vertex shader stage for example is varying (HLSL doesn't need this keyword at all!).

Note that GLSL keywords uniform/varying are inherited from RSL
(RenderMan shading language).

Title: uniform keyword in HLSL


问:
Extract data from web without identifier?
How can I extract a table from a website https://www.lyngsat.com/tvchannels/in/Aaj-Tak.html to an excel which does not any identifier?

I want to Extract data from Table containing Satellite position, frequency, and encryption.

Previously, I tried using getElementsByTagName but there are too many tags for a different table on the page.

答:
I would use xmlhttp. The table you want is at index 11 (0 based indexing). I use clipboard as easy way to write out table. If you don't want to use clipboard you can loop rows and columns of the table as shown in WriteTable sub here

This

```<code>html.querySelectorAll("table").item(11)
</code>```

selects the table at that index in the response. Equivalent to

```<code>html.getElementsByTagName("table")(11)
</code>```

There is another unique identifier, when used in combination with table type selector, in the output which is the table border attribute value of 1:

so you could use

```<code>clipboard.SetText html.querySelector("table[border='1']").outerHTML
</code>```

VBA:

```<code>Option Explicit

Public Sub GetTable()
    Dim html As HTMLDocument, clipboard As Object '<  VBE > Tools > References > Microsoft HTML Object Library
    Set html = New HTMLDocument
    Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.lyngsat.com/tvchannels/in/Aaj-Tak.html", False
        .send
        html.body.innerHTML = .responseText
    End With
    clipboard.SetText html.querySelectorAll("table").item(11).outerHTML  ' html.querySelector("table[border='1']").outerHTML
    clipboard.PutInClipboard
    ThisWorkbook.Worksheets("Sheet1").Range("A1").PasteSpecial
End Sub
</code>```

Body:
I would use xmlhttp. The table you want is at index 11 (0 based indexing). I use clipboard as easy way to write out table. If you don't want to use clipboard you can loop rows and columns of the table as shown in WriteTable sub here

This

html.querySelectorAll("table").item(11)

selects the table at that index in the response. Equivalent to

html.getElementsByTagName("table")(11)

There is another unique identifier, when used in combination with table type selector, in the output which is the table border attribute value of 1:

so you could use

clipboard.SetText html.querySelector("table[border='1']").outerHTML

VBA:

Option Explicit

Public Sub GetTable()
    Dim html As HTMLDocument, clipboard As Object '<  VBE > Tools > References > Microsoft HTML Object Library
    Set html = New HTMLDocument
    Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.lyngsat.com/tvchannels/in/Aaj-Tak.html", False
        .send
        html.body.innerHTML = .responseText
    End With
    clipboard.SetText html.querySelectorAll("table").item(11).outerHTML  ' html.querySelector("table[border='1']").outerHTML
    clipboard.PutInClipboard
    ThisWorkbook.Worksheets("Sheet1").Range("A1").PasteSpecial
End Sub


问:
what is the best way to store a 8 queen problem's board in python
I'm trying to solve 8 queen problem with search algorithms such as iterative-deepening search or A* search.
I've given a board and I should find the minimum number of moves to get a board which in no queens threat each other.
I don't know what data structure or package should I use to store my board in python.

I'm going to print and save visited boards and I think I should use the best data structure for optimizing time and space.

I started with pandas.DataFrame because my data was given in csv.
Then I noticed I should check identical boards and I switched to numpy.array() for easy comparing boards. Another way is to use simple python list of tuples:

```<code>[(q1_x, q1_y), (q2_x, q2_y), ....(q8_x, q8_y)]
</code>```

But  I don't know which is this the best solution for this.

Thanks for any help.

答:
To represent legal states:

A fast and compact way of storing queen positions on a chessboard is a simple array (or list), where the index represents the column number, and the value the row number where a queen is located. you may want to use -1 to mark if no queen is present in a column:

For instance: queens = [0, 1, 2, 3, 4, 5, 6, 7] represents the following configuration:

```<code>  0 1 2 3 4 5 6 7
0 Q
1   Q
2     Q
3       Q
4         Q
5           Q
6             Q
7               Q
</code>```

You could similarly use a numpy array of 8 bits integers

[edit] to represent all states:

you can compactly use an array of 8 binary number between 0 and 255 where the ones represent the column position of a queen:

```<code>import random

class Queens:
    def __init__(self):
        self.config = [bin(random.randrange(0, 256))[2:].zfill(8) for _ in range(8)]

    def __repr__(self):
        return'\n'.join(self.config)

    def __str__(self):
        result = ['  ' + ' '.join(str(idx) for idx in range(8))]
        for rdx, elt in enumerate(self.config):
            a = elt.replace('1', 'Q ')
            a = a.replace('0', '  ')
            a = str(rdx) + ' ' + a
            result.append(a)
        return'\n'.join(result)

q = Queens()
print(repr(q), end='\n\n')
print(q)
</code>```

output:

```<code>01010001
10000010
01000010
10100001
01011110
10001110
01010110
11000000

  0 1 2 3 4 5 6 7
0   Q   Q       Q
1 Q           Q
2   Q         Q
3 Q   Q         Q
4   Q   Q Q Q Q
5 Q       Q Q Q
6   Q   Q   Q Q
7 Q Q
</code>```

Body:
I'm trying to solve 8 queen problem with search algorithms such as iterative-deepening search or A* search.
I've given a board and I should find the minimum number of moves to get a board which in no queens threat each other.
I don't know what data structure or package should I use to store my board in python.

I'm going to print and save visited boards and I think I should use the best data structure for optimizing time and space.

I started with pandas.DataFrame because my data was given in csv.
Then I noticed I should check identical boards and I switched to numpy.array() for easy comparing boards. Another way is to use simple python list of tuples:

[(q1_x, q1_y), (q2_x, q2_y), ....(q8_x, q8_y)]

But  I don't know which is this the best solution for this.

Thanks for any help.

Body:
To represent legal states:

A fast and compact way of storing queen positions on a chessboard is a simple array (or list), where the index represents the column number, and the value the row number where a queen is located. you may want to use -1 to mark if no queen is present in a column:

For instance: queens = [0, 1, 2, 3, 4, 5, 6, 7] represents the following configuration:

  0 1 2 3 4 5 6 7
0 Q
1   Q
2     Q
3       Q
4         Q
5           Q
6             Q
7               Q

You could similarly use a numpy array of 8 bits integers

[edit] to represent all states:

you can compactly use an array of 8 binary number between 0 and 255 where the ones represent the column position of a queen:

import random

class Queens:
    def __init__(self):
        self.config = [bin(random.randrange(0, 256))[2:].zfill(8) for _ in range(8)]

    def __repr__(self):
        return'\n'.join(self.config)

    def __str__(self):
        result = ['  ' + ' '.join(str(idx) for idx in range(8))]
        for rdx, elt in enumerate(self.config):
            a = elt.replace('1', 'Q ')
            a = a.replace('0', '  ')
            a = str(rdx) + ' ' + a
            result.append(a)
        return'\n'.join(result)

q = Queens()
print(repr(q), end='\n\n')
print(q)

output:

01010001
10000010
01000010
10100001
01011110
10001110
01010110
11000000

  0 1 2 3 4 5 6 7
0   Q   Q       Q
1 Q           Q
2   Q         Q
3 Q   Q         Q
4   Q   Q Q Q Q
5 Q       Q Q Q
6   Q   Q   Q Q
7 Q Q


问:
How to fix: OP-code isn't read out correctly
I'm currently trying to write a Ninja VM, a task which was given to me as an exercise. Opcode and value are saved in a 32-Bit unsigned int, with the first 8 bit being the opcode and the rest being the value. To deal with a negative value, I use a macro given to me with the exercise

#define SIGN_EXTEND(i) ((i) & 0x00800000 ? (i) | 0xFF000000 : (i))

However, when trying to retrieve the op-code of

unsigned int i = (PUSHC << 24) | SIGN_EXTEND(-2); (where PUSHC equals 1)

by using a bit-wise AND as seen here ->

int opcode = (i>>24)&0xff

my result is 255, although this extraction method works when the value is positive and reproduces the correct op-code in these cases.

While researching this, I found "How I get the value from the Immediate part of a 32 Bit sequence in C?", which seemingly deals with what I'm asking, however the answer given in that question is exactly what I'm doing, anyone know more?

答:
SIGN_EXTEND looks like it is intended to be used in decoding, to take the 24 bits that have been extracted from the instruction and convert them to a 32-bit signed integer. It looks like it is not intended to be used in encoding. For encoding, IMMEDIATE(x) appears to be intended for that. Given a 32-bit signed integer, it produces a 24-bit signed integer, providing the value fits.

So:

```<code>unsigned int i = (PUSHC << 24) | SIGN_EXTEND(-2);
</code>```

should be:

```<code>unsigned int i = (PUSHC << 24) | IMMEDIATE(-2);
</code>```

Body:
SIGN_EXTEND looks like it is intended to be used in decoding, to take the 24 bits that have been extracted from the instruction and convert them to a 32-bit signed integer. It looks like it is not intended to be used in encoding. For encoding, IMMEDIATE(x) appears to be intended for that. Given a 32-bit signed integer, it produces a 24-bit signed integer, providing the value fits.

So:

unsigned int i = (PUSHC << 24) | SIGN_EXTEND(-2);

should be:

unsigned int i = (PUSHC << 24) | IMMEDIATE(-2);


问:
Constraint for a many-to-many relationship table - both the related records need to reference the same dependent record?
There are three entities, Student, Class and  Department. Department and Student have a one-to-many relationship. Department and Class have a one-to-many relationship too. Student and Class have a many-to-many relationship.

```<code>create table Department
(
    Id int primary key,
    -- ...
)

create table Student
(
    Id int primary key,
    DepartmentId int not null references Department(Id),
    -- ....
)

create table Class
(
    Id int primary key,
    DepartmentId int not null references Department(Id),
    ....
)
</code>```

The following table is for the many-to-many relationship between Student and Class. Now user can put a pair of student/class which are from different (which shouldn't be allowed) departments in the table. Is it a way to prevent it besides using a trigger?

```<code>create table StudentAndClass
(
    StudentId int references Student(Id),
    ClassId int references Class(Id),
    -- ....
    primary key (StudentId, ClassId)
)
</code>```

答:
You can do this without a trigger or special functions.  The idea is to use foreign key relationships . . . by defining an extra set of keys and adding DepartmentId (redundantly) to the junction table:

```<code>create table Students (
    StudentId int primary key,
    DepartmentId int not null references Department(Id),
    -- ....
    unique (DepartmentId, StudentId)
);

create table Classes (
    ClassId int primary key,
    DepartmentId int not null references Department(Id),
    ....
    unique (DepartmentId, ClassId)
);

create table StudentClasses (
    DepartmentId int references Department(DepartmentId),
    StudentId int,
    ClassId int,
    -- ....
    primary key (StudentId, ClassId),
    foreign key (DepartmentId, StudentId) references (DepartmentId, StudentId),
    foreign key (DepartmentId, ClassId) references (DepartmentId, ClassId),
);
</code>```

You may not want the redundancy, but it is possible without triggers or special functions.

Body:
There are three entities, Student, Class and  Department. Department and Student have a one-to-many relationship. Department and Class have a one-to-many relationship too. Student and Class have a many-to-many relationship.

create table Department
(
    Id int primary key,
    -- ...
)

create table Student
(
    Id int primary key,
    DepartmentId int not null references Department(Id),
    -- ....
)

create table Class
(
    Id int primary key,
    DepartmentId int not null references Department(Id),
    ....
)

The following table is for the many-to-many relationship between Student and Class. Now user can put a pair of student/class which are from different (which shouldn't be allowed) departments in the table. Is it a way to prevent it besides using a trigger?

create table StudentAndClass
(
    StudentId int references Student(Id),
    ClassId int references Class(Id),
    -- ....
    primary key (StudentId, ClassId)
)

Body:
You can do this without a trigger or special functions.  The idea is to use foreign key relationships . . . by defining an extra set of keys and adding DepartmentId (redundantly) to the junction table:

create table Students (
    StudentId int primary key,
    DepartmentId int not null references Department(Id),
    -- ....
    unique (DepartmentId, StudentId)
);

create table Classes (
    ClassId int primary key,
    DepartmentId int not null references Department(Id),
    ....
    unique (DepartmentId, ClassId)
);

create table StudentClasses (
    DepartmentId int references Department(DepartmentId),
    StudentId int,
    ClassId int,
    -- ....
    primary key (StudentId, ClassId),
    foreign key (DepartmentId, StudentId) references (DepartmentId, StudentId),
    foreign key (DepartmentId, ClassId) references (DepartmentId, ClassId),
);

You may not want the redundancy, but it is possible without triggers or special functions.


问:
combine files with similar substring in filename
I would like to combine files that have similar ID before the FIRST underscore "_". Below is an example of two such files. I think cat is the tool to use.

in:

```<code>EIV105_S21_R1.fastq.gz
EIV105_2_S117_R1.fastq.gz
EIV10_S13_R1.fastq.gz
EIV10_2_S109_R1.fastq.gz
</code>```

out:

```<code>EIV105_R1.fastq.gz
EIV10_R1.fastq.gz
</code>```

答:
Here is a slight variation on jhnc's answer using process substitution to feed the while loop that creates the combined gzip files, e.g.

```<code>#!/bin/bash

suffix=R.fastq.gz
while read -r prefix; do
    cat "${prefix}_"* > "$prefix.$suffix"
done < <(for i in *.gz; do echo ${i%%_*}; done | sort -u)
</code>```

It uses the for loop to isolate and collect the unique prefixes for each existing gzip file in the current directory, and then redirects that unique list as input to the while loop.

(note: process substitution, e.g. <(process) is a bashism available in bash, but not in POSIX shell. When redirecting process substitution to fee the while loop, there must be a space between the redirection and process substitution, e.g. < <(process))

Body:
I would like to combine files that have similar ID before the FIRST underscore "_". Below is an example of two such files. I think cat is the tool to use.

in:

EIV105_S21_R1.fastq.gz
EIV105_2_S117_R1.fastq.gz
EIV10_S13_R1.fastq.gz
EIV10_2_S109_R1.fastq.gz

out:

EIV105_R1.fastq.gz
EIV10_R1.fastq.gz

Body:
Here is a slight variation on jhnc's answer using process substitution to feed the while loop that creates the combined gzip files, e.g.

#!/bin/bash

suffix=R.fastq.gz
while read -r prefix; do
    cat "${prefix}_"* > "$prefix.$suffix"
done < <(for i in *.gz; do echo ${i%%_*}; done | sort -u)

It uses the for loop to isolate and collect the unique prefixes for each existing gzip file in the current directory, and then redirects that unique list as input to the while loop.

(note: process substitution, e.g. <(process) is a bashism available in bash, but not in POSIX shell. When redirecting process substitution to fee the while loop, there must be a space between the redirection and process substitution, e.g. < <(process))


问:
is there any better way to do this js code?
I am making these panels to be resized to fit screen height as I click 'this' element. I feel like I hard coded those javascript, and I believe there must be better way. But couldn't really sort it out.

when one panel is clicked, its size is going to get bigger, and rest of pannels gonna get smaller

I would very much appreciate any suggestion of it.

I've tried making this function reusable, but then couldn't really come up with better solution as I am a begginer.

```<code>const panels = document.querySelectorAll('.panel');
        const panelsArr = Array.from(panels);

        panelsArr.forEach(panel => panel.addEventListener('click',getCurrentName))

        function getCurrentName(element) {
            const panel1 = document.querySelector('.panel1');
            const panel2 = document.querySelector('.panel2');
            const panel3 = document.querySelector('.panel3');
            const panel4 = document.querySelector('.panel4');

            console.log(this);
            if(this) {

                this.classList.toggle('active');

                if(this === panel1) {

                panel2.classList.toggle('inactive');
                panel3.classList.toggle('inactive');
                panel4.classList.toggle('inactive');
                } else if (this === panel2) {
                panel1.classList.toggle('inactive');
                panel3.classList.toggle('inactive');
                panel4.classList.toggle('inactive');

                } else if (this === panel3) {
                panel1.classList.toggle('inactive');
                panel2.classList.toggle('inactive');
                panel4.classList.toggle('inactive');

                } else if (this === panel4) {
                panel1.classList.toggle('inactive');
                panel2.classList.toggle('inactive');
                panel3.classList.toggle('inactive');
                }

            }

        }
</code>```

.panel {
    background-color: #002712;
    box-shadow: inset 0 0 0 .5rem rgba(255,255,255,0.1);
    min-height: 22.5vh;
    color: #fff;
    text-align: center;
    font-size: 2rem;
    background-size: cover;
    background-position: center;
    line-height: 8rem;
    transition:
    min-height .5s linear,
    font-size .2s linear .5s,
    line-height .2s linear .5s;
}

.panel1 { background-image: url("../images/steake.png"); }
.panel2 { background-image: url("../images/sundayRoast.png"); }
.panel3 { background-image: url("../images/image1(1).png"); }
.panel4 { background-image: url("../images/cannonbury.png"); }

.active {
    min-height: 37vh;
    line-height: 15rem;
    font-size: 2.3rem;
}

.inactive {
    min-height: 15vh;
    font-size: 1.2rem;
}
```

<pre class="lang-html prettyprint-override"><code><main>
            <section class="intro">
                <div class="intro-panels">
                    <section class="panel panel1">
                        <p>most original,</p>
                    </section>
                    <section class="panel panel2">
                        <p>best beer,</p>
                    </section>
                    <section class="panel panel3">
                        <p>grilled food</p>
                    </section>
                    <section class="panel panel4">
                        <p>Islington</p>
                    </section>
                </div>
            </section>
        </main>
</code>```

I expect simplified javascript code to achieve the same goal.

Here's how I've sorted it out by your answer. Thank you for your help guys.

```<code>
const panels = document.querySelectorAll('.panel');
        const panelsArr = Array.from(panels);

        panelsArr.forEach(panel => panel.addEventListener('click', getCurrentName))

        function getCurrentName(element) {
            if(this) {

                panelsArr.forEach(panel => panel.classList.toggle('inactive'));

                this.classList.toggle('inactive');
                this.classList.toggle('active');
            }

        }

</code>```

答:
You could mark them all as inactive and re-mark the current one as active.

```<code>Array.from(document.querySelectorAll('.panel')).forEach(element => {
  element.classList.remove('active');
  element.classList.add('inactive')
});
this.classList.remove('inactive');
this.classList.add('active');
</code>```

You could also filter out this from the array, but it wouldn't change the outcome.

Body:
I am making these panels to be resized to fit screen height as I click 'this' element. I feel like I hard coded those javascript, and I believe there must be better way. But couldn't really sort it out.

when one panel is clicked, its size is going to get bigger, and rest of pannels gonna get smaller

I would very much appreciate any suggestion of it.

I've tried making this function reusable, but then couldn't really come up with better solution as I am a begginer.

const panels = document.querySelectorAll('.panel');
        const panelsArr = Array.from(panels);

        panelsArr.forEach(panel => panel.addEventListener('click',getCurrentName))

        function getCurrentName(element) {
            const panel1 = document.querySelector('.panel1');
            const panel2 = document.querySelector('.panel2');
            const panel3 = document.querySelector('.panel3');
            const panel4 = document.querySelector('.panel4');

            console.log(this);
            if(this) {

                this.classList.toggle('active');

                if(this === panel1) {

                panel2.classList.toggle('inactive');
                panel3.classList.toggle('inactive');
                panel4.classList.toggle('inactive');
                } else if (this === panel2) {
                panel1.classList.toggle('inactive');
                panel3.classList.toggle('inactive');
                panel4.classList.toggle('inactive');

                } else if (this === panel3) {
                panel1.classList.toggle('inactive');
                panel2.classList.toggle('inactive');
                panel4.classList.toggle('inactive');

                } else if (this === panel4) {
                panel1.classList.toggle('inactive');
                panel2.classList.toggle('inactive');
                panel3.classList.toggle('inactive');
                }

            }

        }

.panel {
    background-color: #002712;
    box-shadow: inset 0 0 0 .5rem rgba(255,255,255,0.1);
    min-height: 22.5vh;
    color: #fff;
    text-align: center;
    font-size: 2rem;
    background-size: cover;
    background-position: center;
    line-height: 8rem;
    transition:
    min-height .5s linear,
    font-size .2s linear .5s,
    line-height .2s linear .5s;
}

.panel1 { background-image: url("../images/steake.png"); }
.panel2 { background-image: url("../images/sundayRoast.png"); }
.panel3 { background-image: url("../images/image1(1).png"); }
.panel4 { background-image: url("../images/cannonbury.png"); }

.active {
    min-height: 37vh;
    line-height: 15rem;
    font-size: 2.3rem;
}

.inactive {
    min-height: 15vh;
    font-size: 1.2rem;
}

most original,

best beer,

grilled food

Islington

I expect simplified javascript code to achieve the same goal.

Here's how I've sorted it out by your answer. Thank you for your help guys.

const panels = document.querySelectorAll('.panel');
        const panelsArr = Array.from(panels);

        panelsArr.forEach(panel => panel.addEventListener('click', getCurrentName))

        function getCurrentName(element) {
            if(this) {

                panelsArr.forEach(panel => panel.classList.toggle('inactive'));

                this.classList.toggle('inactive');
                this.classList.toggle('active');
            }

        }

Body:
You could mark them all as inactive and re-mark the current one as active.

Array.from(document.querySelectorAll('.panel')).forEach(element => {
  element.classList.remove('active');
  element.classList.add('inactive')
});
this.classList.remove('inactive');
this.classList.add('active');

You could also filter out this from the array, but it wouldn't change the outcome.


问:
Do `fgetc`, `fputc`, `fgets` and `fputs` require a file opened in text mode, and `fread` and `fwrite` require a file in binary mode?
When using fgetc, fputc, fgets and fputs for a file, do I need to ensure that I have opened the file in text mode not binary mode?

When using fread and fwrite, do I need to  opened the file in binary mode not text mode?

In Linux, I guess there is no difference. But what if in Windows which I currently have no access to?

答:
[edit after a try under windows using mingw]

The difference between text and binary mode only exist under Windows and not only concern fwrite and fread but also fgetc/fputc/.../_read/_write

On text mode if a file contains the sequence \r\n only the \n is get when you read like if the file does not contain the \r. In binary mode the two characters are return. Note fread Microsoft Docs and _read Microsoft Docs speak about that case but unfortunately nothing is said for fgetc in fget fgetwc Microsoft Docs

When writing if the stream is opened in text mode each \n is written as a \r\n pair. Note the replacement has no effect on the size return by fwrite. In binary mode \n is written unchanged, there is no \r added. Note fwrite Microsoft Docs and _write Microsoft Docs speak about that case but unfortunately nothing is said for fputc in fputc fputwc Microsoft Docs

Fortunately in text mode under Windows read and write functions are symmetric, when you write in text mode foo\nbar then you read the produced file still in text mode you get foo\nbar, but there is foo\r\nbar into the file.

So

When using fgetc, fputc, fgets and fputs for a file, do I need to ensure that I have opened the file in text mode not binary mode?

the mode has an impact

When using fread and fwrite, do I need to  opened the file in binary mode not text mode?

Like for the other functions it is your choice, but if the file is also read/write by an other tool it is may be better to open in text mode in case these tools expect a \r before a \n when reading or producing the pair when writing. Of course you can also open in binary mode and explicitly write a \r before a \n by yourself.

If the file is only for you using C to read/write it may be better to always open in binary mode to have in the file only what you explicitly ask for to have. This is enforced if you use ftell/fseek.

As said in ftell Microsoft Docs ftell and _ftelli64 may not reflect the physical byte offset for streams opened in text mode, because text mode causes carriage return-linefeed translation.

It is worst concerning fseek, as said in fseek Microsoft Docs :

for streams opened in text mode, fseek and _fseeki64 have limited use, because carriage return-linefeed translations can cause fseek and _fseeki64 to produce unexpected results. The only fseek and _fseeki64 operations guaranteed to work on streams opened in text mode are:

Seeking with an offset of 0 relative to any of the origin values.

Seeking from the beginning of the file with an offset value returned from a call to ftell when using fseek or _ftelli64 when using _fseeki64.


问:
Filter role based users in c# linq
we have multiple roles in our system and a user can have multiple roles assigned to it
and everything is managed custom. We are not using identity or so.

I am sending my api request with some roles like "guest", "admin".
Api should only returns users having these roles

this is how I am filtering users
List<string> roles -> this is a variable that have role names
coming from front-end suppose "admin"

roles = "admin" -> but can have more roles

UserRoleMappings is navigation property that holds user id and
role id combination to save roles of particular user

now while getting all users, I would like to filter them so that

```<code>query.Where(user => user.UserRoleMappings.Any(urm => roles.Contains(urm.UserRole.Name)));
</code>```

This query is fetching users having roles "admin" + "guests" as I have
applied contains. But i need users which only have "admin" role

beacuse

```<code>user

1  user1
2 user2

role
1 admin
2 guest

userMapping
1 1
1 2
2 1
</code>```

Api should only return user2 but it is also returning user1. This methid should be generic and should work formultiple roles

Thanks & Regards

答:
If you need users that only have the admin role and no other roles you can do

```<code>var adminUsers = query
    .Where(user => user.UserRoleMappings.All(urm => urm.UserRole.Name == "admin"));
</code>```

because if "all" of their roles are named "admin" it necessarily is the only role they have.

Title: Filter role based users in c# linq

Body:
we have multiple roles in our system and a user can have multiple roles assigned to it
and everything is managed custom. We are not using identity or so.

I am sending my api request with some roles like "guest", "admin".
Api should only returns users having these roles

this is how I am filtering users
List<string> roles -> this is a variable that have role names
coming from front-end suppose "admin"

roles = "admin" -> but can have more roles

UserRoleMappings is navigation property that holds user id and
role id combination to save roles of particular user

now while getting all users, I would like to filter them so that

query.Where(user => user.UserRoleMappings.Any(urm => roles.Contains(urm.UserRole.Name)));

This query is fetching users having roles "admin" + "guests" as I have
applied contains. But i need users which only have "admin" role

beacuse

user

1  user1
2 user2

role
1 admin
2 guest

userMapping
1 1
1 2
2 1

Api should only return user2 but it is also returning user1. This methid should be generic and should work formultiple roles

Thanks & Regards

Body:
If you need users that only have the admin role and no other roles you can do

var adminUsers = query
    .Where(user => user.UserRoleMappings.All(urm => urm.UserRole.Name == "admin"));

because if "all" of their roles are named "admin" it necessarily is the only role they have.


问:
Exporting symbols in static library that is linked to dynamic library
I have the following scenario in MSVC2017:

A static library with the function bool foo()

A dynamic link library that links to the static library above

An application that loads the dynamic link library using explicit run-time linking and calls foo() via GetProcAddress

In the static library, foo() is defined as follows:

```<code>extern "C" __declspec(dllexport) bool foo()
{
    return true;
}
</code>```

Now, because foo() is not used by the dynamic link library, its symbol is not exported and thus not findable when the application used GetProcAddress.

I have tried:

#pragma comment(linker, "/include:foo")

and:

#pragma comment(linker, "/export:foo")

I can see the exported foo() using Dependency Walker if I move the definition to the dynamic link library (not a viable solution) but I cannot seem to get the symbol exported when I keep the definition in the static library with the above linker switches. I presume this is because the symbol is still not used, and thus still not exported regardless?

I would like a solution for both MSVC on Windows and Clang on Linux. Thanks!

答: My solution in the end was to make a dummy function that called foo() to force all symbols in that compilation unit to be exported.

Body:
I have the following scenario in MSVC2017:

A static library with the function bool foo()

A dynamic link library that links to the static library above

An application that loads the dynamic link library using explicit run-time linking and calls foo() via GetProcAddress

In the static library, foo() is defined as follows:

extern "C" __declspec(dllexport) bool foo()
{
    return true;
}

Now, because foo() is not used by the dynamic link library, its symbol is not exported and thus not findable when the application used GetProcAddress.

I have tried:

#pragma comment(linker, "/include:foo")

and:

#pragma comment(linker, "/export:foo")

I can see the exported foo() using Dependency Walker if I move the definition to the dynamic link library (not a viable solution) but I cannot seem to get the symbol exported when I keep the definition in the static library with the above linker switches. I presume this is because the symbol is still not used, and thus still not exported regardless?

I would like a solution for both MSVC on Windows and Clang on Linux. Thanks!


问:
How to redirect to the root route
I am clicking on a hidden input and passing it to a function on the server side to preform a function and redirect it back to the same page I was on.

import random
from flask import Flask, render_template, redirect, request, session, url_for
app = Flask(__name__)
app.secret_key = '123456' # set a secret key for security purposes

@app.route("/")
def main_page():

    return render_template('index.html')
app.route("/process_money", methods = ["POST"])
def test_stuff():
    #will run function
    return redirect('/')
```

<pre class="lang-html prettyprint-override"><code>                    <form action="/process_money" method="post">
                        <input type="hidden" name="building" value="farm" />
                        <input type="submit" value="Find Gold!"/>
                    </form>
</code>```

I'm getting a 404 not found error upon hitting the input button.

答:
Your route needs @app:

```<code>@app.route("/process_money", methods = ["POST"])
</code>```

Title: How to redirect to the root route

Body:
I am clicking on a hidden input and passing it to a function on the server side to preform a function and redirect it back to the same page I was on.

import random
from flask import Flask, render_template, redirect, request, session, url_for
app = Flask(__name__)
app.secret_key = '123456' # set a secret key for security purposes

@app.route("/")
def main_page():

    return render_template('index.html')
app.route("/process_money", methods = ["POST"])
def test_stuff():
    #will run function
    return redirect('/')

                    <form action="/process_money" method="post">
                        <input type="hidden" name="building" value="farm" />
                        <input type="submit" value="Find Gold!"/>
                    </form>

I'm getting a 404 not found error upon hitting the input button.

Body:
Your route needs @app:

@app.route("/process_money", methods = ["POST"])


问:
R: set a column of a dataframe as date-time in order to create intervals
I have a dataframe called data that has date-time information in a column, in the following format: mm/dd/yyyy hh:mm:ss am/pm

What I want is to create put timeperiod values: within 1 hour, within 2 hours etc.

few lines of my dataframe:

```<code>        time                    timeperiod  refer x.x
1       05/07/2017 18:00:15         NA         1 23.97370
2       06/08/2017 06:21:12         NA         1 23.79394
3       06/08/2017 08:03:11         NA         1 23.79394
4       06/08/2017 08:12:47         NA         1 23.79394
5       07/07/2017 10:41:45         NA         1 23.54257
6      1/21/2017 8:10:20 AM         NA         1 21.06460
7      1/9/2013 10:01:32 PM         NA         2 23.99733
8      1/9/2013 10:01:32 PM         NA         2 23.99733
9      1/9/2013 10:01:32 PM         NA         2 21.06460
10     1/9/2013 10:01:32 PM         NA         2 21.06460
</code>```

I tried:
strftime(data$time., format = "%m/%d/%y %H:%M:%S" %r) but I am receiving the following error:

Error in as.POSIXlt.character(as.character(x), ...) :
  character string is not in a standard unambiguous format

Body:
I have a dataframe called data that has date-time information in a column, in the following format: mm/dd/yyyy hh:mm:ss am/pm

What I want is to create put timeperiod values: within 1 hour, within 2 hours etc.

few lines of my dataframe:

        time                    timeperiod  refer x.x
1       05/07/2017 18:00:15         NA         1 23.97370
2       06/08/2017 06:21:12         NA         1 23.79394
3       06/08/2017 08:03:11         NA         1 23.79394
4       06/08/2017 08:12:47         NA         1 23.79394
5       07/07/2017 10:41:45         NA         1 23.54257
6      1/21/2017 8:10:20 AM         NA         1 21.06460
7      1/9/2013 10:01:32 PM         NA         2 23.99733
8      1/9/2013 10:01:32 PM         NA         2 23.99733
9      1/9/2013 10:01:32 PM         NA         2 21.06460
10     1/9/2013 10:01:32 PM         NA         2 21.06460

I tried:
strftime(data$time., format = "%m/%d/%y %H:%M:%S" %r) but I am receiving the following error:

Error in as.POSIXlt.character(as.character(x), ...) :
  character string is not in a standard unambiguous format

Body:
An option would be

i1 <- grepl("AM|PM", df1$time)
out <- as.POSIXct(rep(NA_real_, nrow(df1)), origin = "1970-01-01")
out[i1] <- as.POSIXct(df1$time[i1], format = "%m/%d/%Y %I:%M:%S %p")
out[!i1] <- as.POSIXct(df1$time[!i1], format = '%m/%d/%Y %H:%M:%S')
droplevels(cut(out, breaks = "1 hour"))
#[1] 2017-05-07 18:00:00 2017-06-08 06:00:00 2017-06-08 08:00:00 2017-06-08 08:00:00 2017-07-07 10:00:00 2017-01-21 08:00:00
#[7] 2013-01-09 22:00:00 2013-01-09 22:00:00 2013-01-09 22:00:00 2013-01-09 22:00:00
#Levels: 2013-01-09 22:00:00 2017-01-21 08:00:00 2017-05-07 18:00:00 2017-06-08 06:00:00 2017-06-08 08:00:00 2017-07-07 10:00:00

Or another option is parse_date from parsedate and floor_date

library(lubridate)
library(parsedate)
floor_date(parse_date(df1$time), "hour")
#[1] "2017-05-07 18:00:00 UTC" "2017-06-08 06:00:00 UTC" "2017-06-08 08:00:00 UTC" "2017-06-08 08:00:00 UTC" "2017-07-07 10:00:00 UTC"
#[6] "2017-01-21 08:00:00 UTC" "2013-01-09 22:00:00 UTC" "2013-01-09 22:00:00 UTC" "2013-01-09 22:00:00 UTC" "2013-01-09 22:00:00 UTC"

data

df1 <- structure(list(time = c("05/07/2017 18:00:15", "06/08/2017 06:21:12",
"06/08/2017 08:03:11", "06/08/2017 08:12:47", "07/07/2017 10:41:45",
"1/21/2017 8:10:20 AM", "1/9/2013 10:01:32 PM", "1/9/2013 10:01:32 PM",
"1/9/2013 10:01:32 PM", "1/9/2013 10:01:32 PM"), timeperiod = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA), refer = c(1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L), x.x = c(23.9737, 23.79394, 23.79394,
23.79394, 23.54257, 21.0646, 23.99733, 23.99733, 21.0646, 21.0646
)), class = "data.frame", row.names = c("1", "2", "3", "4", "5",
"6", "7", "8", "9", "10"))


问:
Loop backwards using indices
I am trying to loop from 100 to 0. How do I do this in Python?

for i in range (100,0) doesn't work.

For discussion of why range works the way it does, see Why are slice and range upper-bound exclusive?.

答:
Oh okay read the question wrong, I guess it's about going backward in an array? if so, I have this:</p>

```<code>array = ["ty", "rogers", "smith", "davis", "tony", "jack", "john", "jill", "harry", "tom", "jane", "hilary", "jackson", "andrew", "george", "rachel"]

counter = 0

for loop in range(len(array)):
    if loop <= len(array):
        counter = -1
        reverseEngineering = loop + counter
        print(array[reverseEngineering])
</code>```

Title: Loop backwards using indices

Body:
Oh okay read the question wrong, I guess it's about going backward in an array? if so, I have this:

array = ["ty", "rogers", "smith", "davis", "tony", "jack", "john", "jill", "harry", "tom", "jane", "hilary", "jackson", "andrew", "george", "rachel"]

counter = 0

for loop in range(len(array)):
    if loop <= len(array):
        counter = -1
        reverseEngineering = loop + counter
        print(array[reverseEngineering])


问:
How to check if device has fingerprint feature and then use it in Android
I am using this permission

```<code><uses-permission android:name="android.permission.USE_FINGERPRINT" />
</code>```

to check if device has fingerprint or not. Thats how I check it in kotlin

```<code>val fingerSensorManager = FingerSensorManager(this)
fingerSensorManager.isFingerPrintAvailable()
</code>```

It works fine but in Android 8 and above it throws exception.

How can I check fingerprint and also use it in all versions? I know there is another method for Android 8 and above but I am confuse that how to implement it so that it works in every device

答:
You can use the biometric lib from Androidx. It's still in alpha, but is working well so far. The good thing is that you do not need two implementations for a specific Android API level.</p>

```<code>fun isAvailable(context: Context): Boolean {
    val fingerprintManager = FingerprintManagerCompat.from(context)
    return fingerprintManager.isHardwareDetected && fingerprintManager.hasEnrolledFingerprints()
}
</code>```

Body:
I am using this permission

<uses-permission android:name="android.permission.USE_FINGERPRINT" />

to check if device has fingerprint or not. Thats how I check it in kotlin

val fingerSensorManager = FingerSensorManager(this)
fingerSensorManager.isFingerPrintAvailable()

It works fine but in Android 8 and above it throws exception.

How can I check fingerprint and also use it in all versions? I know there is another method for Android 8 and above but I am confuse that how to implement it so that it works in every device

Body:
You can use the biometric lib from Androidx. It's still in alpha, but is working well so far. The good thing is that you do not need two implementations for a specific Android API level.

fun isAvailable(context: Context): Boolean {
    val fingerprintManager = FingerprintManagerCompat.from(context)
    return fingerprintManager.isHardwareDetected && fingerprintManager.hasEnrolledFingerprints()
}


问:
How to make Date object toString via stringify use the regular toString instead of toStringISO in javascript?
In javascript, when I convert a Date object to string via JSON.stringify, it uses toStringISO by default. How can I change the prototype of it so that it uses the basic toString?

I have

```<code>var f = new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)");
</code>```

then if I do JSON.stringify(f) it gives me "2019-05-28T00:11:13.000Z"

but I want it to give me "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" (which I can get from f.toString()), how do I get that?

Looking to override prototype, something like that.

Does anyone know?

Thanks

答:
JSON.stringify takes a function to replace values. Unfortunately, Date.prototype.toJSON gets called before it. If you want to avoid changing the prototype directly and can’t wrap/alter the date objects themselves, you can bypass this via the parent:

function replacer(key, value) {
    return typeof value === 'string' && this[key] instanceof Date ?
        String(this[key]) :
        value;
}

console.log(JSON.stringify({
    foo: 'bar',
    baz: new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)"),
}, replacer));```

Not the cleanest thing, but kind of contains the scope of altered behaviour.

Body:
In javascript, when I convert a Date object to string via JSON.stringify, it uses toStringISO by default. How can I change the prototype of it so that it uses the basic toString?

I have

var f = new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)");

then if I do JSON.stringify(f) it gives me "2019-05-28T00:11:13.000Z"

but I want it to give me "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" (which I can get from f.toString()), how do I get that?

Looking to override prototype, something like that.

Does anyone know?

Thanks

Body:
JSON.stringify takes a function to replace values. Unfortunately, Date.prototype.toJSON gets called before it. If you want to avoid changing the prototype directly and can’t wrap/alter the date objects themselves, you can bypass this via the parent:

function replacer(key, value) {
    return typeof value === 'string' && this[key] instanceof Date ?
        String(this[key]) :
        value;
}

console.log(JSON.stringify({
    foo: 'bar',
    baz: new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)"),
}, replacer));

Not the cleanest thing, but kind of contains the scope of altered behaviour.