问:
How can I implement AsyncTask into my current Activity
An Activity in my Android application is incredibly slow to load, it's loading Tweets into a RecyclerView using TwitterKit.   LogCat displays the following message: "

Skipped 1491 frames! The application may be doing too much work  on its main thread"

After some research, I understand that I need to Implement AsyncTask to move the workload away from the main thread. I've attempted to implement it, however, I cannot get it to work.  A point in the correct direction would be much appreciated. Please see code below

```<code>import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

//twitter imports

import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.tweetui.TweetTimelineRecyclerViewAdapter;
import com.twitter.sdk.android.tweetui.UserTimeline;

public class travel_updates extends AppCompatActivity{

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.custom_line_info);
        View view = getSupportActionBar().getCustomView();

        Twitter.initialize(this);

workHorse workhorse = new workHorse();
        workHorse.execute(UserTimeline);

        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

    }

    private class workHorse extends AsyncTask<String, Void, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {

            final UserTimeline searchTimeline = new UserTimeline.Builder().screenName("TflTravelAlerts")
                    .maxItemsPerRequest(20)
                    .build();

            final TweetTimelineRecyclerViewAdapter adapter =
                    new TweetTimelineRecyclerViewAdapter.Builder(this)
                            .setTimeline(searchTimeline)
                            .setViewStyle(R.style.tw__TweetLightWithActionsStyle)
                            .build();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }
}
</code>```

答:
You can perform below task to get exact problem,

Just execute AsyncTask and comment whole remaining code. So you can actually get to know, is your AsyncTask is OK or not.

Try to execute AsyncTask at last when all other tasks get completed.

Try to optimize your Activity to get out from slow performance.

Body:
An Activity in my Android application is incredibly slow to load, it's loading Tweets into a RecyclerView using TwitterKit.   LogCat displays the following message: "

Skipped 1491 frames! The application may be doing too much work  on its main thread"

After some research, I understand that I need to Implement AsyncTask to move the workload away from the main thread. I've attempted to implement it, however, I cannot get it to work.  A point in the correct direction would be much appreciated. Please see code below

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

//twitter imports

import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.tweetui.TweetTimelineRecyclerViewAdapter;
import com.twitter.sdk.android.tweetui.UserTimeline;

public class travel_updates extends AppCompatActivity{

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.custom_line_info);
        View view = getSupportActionBar().getCustomView();

        Twitter.initialize(this);

workHorse workhorse = new workHorse();
        workHorse.execute(UserTimeline);

        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

    }

    private class workHorse extends AsyncTask<String, Void, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {

            final UserTimeline searchTimeline = new UserTimeline.Builder().screenName("TflTravelAlerts")
                    .maxItemsPerRequest(20)
                    .build();

            final TweetTimelineRecyclerViewAdapter adapter =
                    new TweetTimelineRecyclerViewAdapter.Builder(this)
                            .setTimeline(searchTimeline)
                            .setViewStyle(R.style.tw__TweetLightWithActionsStyle)
                            .build();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }
}


来源: stackexchange

问:
Return from inside an observable
I'm think fundamentally i'm doing something wrong. I'm trying to find a single entity by pulling it from filtered list, if there isn't an entity there I need to create one.

I feel like this function is wrong because I should be returning an observable but instead returning nothing

```<code>getOrCreateNew(receiverId: number) : Observable<Conversation> {
    var userId = this.identity.userInfo.id;

    //TODO: you should be using an expression here, and having a builder for generating your
    //filters in case you want to switch them in the future
    var employerFilter = new PropertyFilterNode("EmployerUserId", FilterCondition.Equal, receiverId.toString());
    var employeeFilter = new PropertyFilterNode("EmployeeUserId", FilterCondition.Equal, userId.toString());
    let conversationFilter = new BinaryFilterNode(employerFilter, employeeFilter, Combiner.Or);

    this.getList(conversationFilter).subscribe(entities => {
        if (entities == null || entities.length == 0) {
            let conversation: Conversation;
            conversation.employerUserId = receiverId;
            conversation.employeeUserId = userId;
            return this.create(conversation);
        }
        else {
            let entity = entities[0];
            return Observable.of(entity); //.Return(entity)
        }
    });

    return null;
}
</code>```

How can I return an observable which is return from inside subscribe?

答:
The way getList subscription works suggests that it is supposed to be mergeMap or switchMap (considering that create returns an observable as well):

```<code>return this.getList(conversationFilter).mergeMap(entities => {
    if (entities == null || entities.length == 0) {
        let conversation: Conversation;
        conversation.employerUserId = receiverId;
        conversation.employeeUserId = userId;
        return this.create(conversation);
    }
    else {
        let entity = entities[0];
        return Observable.of(entity); //.Return(entity)
    }
});
</code>```

In this case an observable that is returned from getOrCreateNew should be subscribed in order to emit values because it isn't subscribed internally.

ContentLicense: CC BY-SA 3.0

Title: Return from inside an observable

Body:
I'm think fundamentally i'm doing something wrong. I'm trying to find a single entity by pulling it from filtered list, if there isn't an entity there I need to create one.

I feel like this function is wrong because I should be returning an observable but instead returning nothing

getOrCreateNew(receiverId: number) : Observable<Conversation> {
    var userId = this.identity.userInfo.id;

    //TODO: you should be using an expression here, and having a builder for generating your
    //filters in case you want to switch them in the future
    var employerFilter = new PropertyFilterNode("EmployerUserId", FilterCondition.Equal, receiverId.toString());
    var employeeFilter = new PropertyFilterNode("EmployeeUserId", FilterCondition.Equal, userId.toString());
    let conversationFilter = new BinaryFilterNode(employerFilter, employeeFilter, Combiner.Or);

    this.getList(conversationFilter).subscribe(entities => {
        if (entities == null || entities.length == 0) {
            let conversation: Conversation;
            conversation.employerUserId = receiverId;
            conversation.employeeUserId = userId;
            return this.create(conversation);
        }
        else {
            let entity = entities[0];
            return Observable.of(entity); //.Return(entity)
        }
    });

    return null;
}

How can I return an observable which is return from inside subscribe?

Body:
The way getList subscription works suggests that it is supposed to be mergeMap or switchMap (considering that create returns an observable as well):

return this.getList(conversationFilter).mergeMap(entities => {
    if (entities == null || entities.length == 0) {
        let conversation: Conversation;
        conversation.employerUserId = receiverId;
        conversation.employeeUserId = userId;
        return this.create(conversation);
    }
    else {
        let entity = entities[0];
        return Observable.of(entity); //.Return(entity)
    }
});

In this case an observable that is returned from getOrCreateNew should be subscribed in order to emit values because it isn't subscribed internally.


问:
How to get DropDownList selected Text in MVC controller
I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID

```<code> @Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control" })
</code>```

On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.

Controller side code line:

```<code>detailsConfig.Project = Convert.ToString(form["Project"]);
</code>```

For example:
If the dropdownlist values are

```<code>Project     ID
test        1
testagain   2
</code>```

In controller I should get test, not 1. Please help

答:
```<code>new SelectList(Model.dropConfig, "Project", "Project")
</code>```

The above change solves my problem. Thanks @StephenMuecke :)

Body:
I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID

 @Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, @class = "form-control" })

On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.

Controller side code line:

detailsConfig.Project = Convert.ToString(form["Project"]);

For example:
If the dropdownlist values are

Project     ID
test        1
testagain   2

In controller I should get test, not 1. Please help

Body:
new SelectList(Model.dropConfig, "Project", "Project")

The above change solves my problem. Thanks @StephenMuecke :)


问:
Ignore rows with NULL join columns in hive query
I have three tables A, B and C.  A is having 1 billion records,  B is having 10 million records and C is having 5 million records.
My query is like

select *
   from tableA a
       left outer join tableB b on a.id=b.id
       left outer join tableC c on b.id=c.id;

After first join i will be having more than 990 million NULL b.id columns. Now the second join on table C will require all 990 million NULL rows (b.Id) to be processed and this causes one reducer to be loaded for a very long time.  Is there a way i can avoid rows with NULL  join columns?

答:
We have used rand() for NULL ; so our join condition will be

coalesce(b.id, rand()) = c.id

Thus null values got distributed by its own, but i am wondering why the skewjoin settings didnot help (we have tried coalesce(b.id, 'SomeString') = c.id with skewjoin enable )


问:
Regex (en-US) to find all punctuation EXCEPT if part of word
I've found the regex to locate all hyphenated and "apostrophied" words:

```<code>(?=\S*['-])([a-zA-Z'-]+)
</code>```

Examples: l'Equipe and action-oriented

I'm not sure how to utilize this information to get what I want after a bit of searching...

答:
Try this regex

```<code>(?<=\b)[,.'-:"]+(?=\s|$)|"
</code>```

Demo: https://regex101.com/r/mDhl17/1/

Here are some details

This regex will start with Positive Lookbehind with a word boundary token in order to exclude any punctuation that has letters before it.

We add the targeted punctuation mark afterward [,.'-:"]+. You can add to the list whatever you prefer to catch.

We expect the punctuation marks to be followed by either a space or to be at the end of the sentence (?=\s|$).

An exception to this, is the quotation marks " ", we want to catch them whenever they are there, so I added the OR | condition at the end.

Body:
I've found the regex to locate all hyphenated and "apostrophied" words:

(?=\S*['-])([a-zA-Z'-]+)

Examples: l'Equipe and action-oriented

I'm not sure how to utilize this information to get what I want after a bit of searching...

Body:
Try this regex

(?<=\b)[,.'-:"]+(?=\s|$)|"

Demo: https://regex101.com/r/mDhl17/1/

Here are some details

This regex will start with Positive Lookbehind with a word boundary token in order to exclude any punctuation that has letters before it.

We add the targeted punctuation mark afterward [,.'-:"]+. You can add to the list whatever you prefer to catch.

We expect the punctuation marks to be followed by either a space or to be at the end of the sentence (?=\s|$).

An exception to this, is the quotation marks " ", we want to catch them whenever they are there, so I added the OR | condition at the end.


问:
Queries in MS Access 2003
I am working on a database for a small hotel. Once a guest gets a room reserved they are given a parking lot card that needs to be returned as the guest check-out. I need help on  writing a query that would let the user know that Parking Lot card 01 (or any card #, that has already been given out to a guest) is unavailable. Can anyone please help me set this up. Thanks.

Tbls used

Guest tbl

GuestID PK

Check in date

Check out date

Room #

Room Type
Access Key Id

Access Key tbl

Access Key ID PK

Distributed - yes or no

答:
From your tables it seems that it is possible to get the room access key, and if Access Key table hold parking lot cards, it is possible to get that information, but these tables could be better structured.

```<code> SELECT [Access Key ID]
 FROM [Access Key tbl]
 WHERE Distributed = True
</code>```

It is never a good idea to have spaces in table names or field names, because it just leads to stress remembering to put square brackets round everything.

Consider a table set up like so:

```<code>Guests
GuestID
Etc.

Cards
CardID
CardType (Room or Parking)

CardsIssued
CardID
GuestID
IssueDate
ReturnDate
</code>```

ContentLicense: CC BY-SA 2.5

Title: Queries in MS Access 2003

Body:
From your tables it seems that it is possible to get the room access key, and if Access Key table hold parking lot cards, it is possible to get that information, but these tables could be better structured.

 SELECT [Access Key ID]
 FROM [Access Key tbl]
 WHERE Distributed = True

It is never a good idea to have spaces in table names or field names, because it just leads to stress remembering to put square brackets round everything.

Consider a table set up like so:

Guests
GuestID
Etc.

Cards
CardID
CardType (Room or Parking)

CardsIssued
CardID
GuestID
IssueDate
ReturnDate


问:
Output 'NaN' Incrementing state value by using ReactJS
In React I am trying to make a button increment a value stored in state. However using the code below function. When I click "minusbutton" or "plusbutton" and the output is 'NaN' when using buttonplus_quantity and buttonminus_quantity.

Here is my code:

```<code>class EnterOrder extends Component {

    constructor(props) {
      super(props)
      this.buttonplus_quantity = this.buttonplus_quantity.bind(this);
      this.buttonminus_quantity = this.buttonminus_quantity.bind(this);

      this.state= {
          num_quantity :0
      }

      buttonplus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity +1});
      console.log("a");
    }

    buttonminus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity -1});
      console.log("b");
    }
}
</code>```

And the Render():

```<code> render(){
  let {num_quantity} = this.state;
   return(
    <Button onClick={this.buttonminus_quantity} name="minus" id="minus"
    value="-">-</Button>
    <p id='num'>{this.state.num_quantity}</p>
    <Button  onClick={this.buttonplus_quantity} name="plus" id="plus"
    value="+">+</Button>
    );
}
</code>```

And the output when I click is 'NaN' like this picture below:

What I am doing wrong? Thank you guys so much for helping.

答:
There is no <Button /> component imported in this JSX file. I think you mean <button></button> and if you are not using react 16 don't forget wrapper element in render() return . as you can see it's working with no problem in code snippet:

"use strict";

class EnterOrder extends React.Component {

  constructor(props) {
    super(props)
    this.buttonplus_quantity = this.buttonplus_quantity.bind(this);
    this.buttonminus_quantity = this.buttonminus_quantity.bind(this);

    this.state = {
      num_quantity: 0
    }
  }

  buttonplus_quantity = () => {
    this.setState({
      num_quantity: this.state.num_quantity + 1
    });
    console.log("a");
  }

  buttonminus_quantity = () => {
    this.setState({
      num_quantity: this.state.num_quantity - 1
    });
    console.log("b");
  }

  render() {
    let {num_quantity} = this.state;
    return (

        <button onClick = {this.buttonminus_quantity} name = "minus" id = "minus" value = "-" > - </button>

 {this.state.num_quantity}

        <button onClick = {this.buttonplus_quantity} name = "plus" id = "plus" value = "+" > + </button>

    );
  }
}

ReactDOM.render( <EnterOrder / > , document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div></code>```

Body:
In React I am trying to make a button increment a value stored in state. However using the code below function. When I click "minusbutton" or "plusbutton" and the output is 'NaN' when using buttonplus_quantity and buttonminus_quantity.

Here is my code:

class EnterOrder extends Component {

    constructor(props) {
      super(props)
      this.buttonplus_quantity = this.buttonplus_quantity.bind(this);
      this.buttonminus_quantity = this.buttonminus_quantity.bind(this);

      this.state= {
          num_quantity :0
      }

      buttonplus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity +1});
      console.log("a");
    }

    buttonminus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity -1});
      console.log("b");
    }
}

And the Render():

 render(){
  let {num_quantity} = this.state;
   return(
    <Button onClick={this.buttonminus_quantity} name="minus" id="minus"
    value="-">-</Button>

{this.state.num_quantity}

    <Button  onClick={this.buttonplus_quantity} name="plus" id="plus"
    value="+">+</Button>
    );
}

And the output when I click is 'NaN' like this picture below:

What I am doing wrong? Thank you guys so much for helping.

Body:
There is no <Button /> component imported in this JSX file. I think you mean <button></button> and if you are not using react 16 don't forget wrapper element in render() return . as you can see it's working with no problem in code snippet:

"use strict";

class EnterOrder extends React.Component {

  constructor(props) {
    super(props)
    this.buttonplus_quantity = this.buttonplus_quantity.bind(this);
    this.buttonminus_quantity = this.buttonminus_quantity.bind(this);

    this.state = {
      num_quantity: 0
    }
  }

  buttonplus_quantity = () => {
    this.setState({
      num_quantity: this.state.num_quantity + 1
    });
    console.log("a");
  }

  buttonminus_quantity = () => {
    this.setState({
      num_quantity: this.state.num_quantity - 1
    });
    console.log("b");
  }

  render() {
    let {num_quantity} = this.state;
    return (
      <div>
        <button onClick = {this.buttonminus_quantity} name = "minus" id = "minus" value = "-" > - </button>
        <p id = 'num' > {this.state.num_quantity} </p>
        <button onClick = {this.buttonplus_quantity} name = "plus" id = "plus" value = "+" > + </button>
     </div>
    );
  }
}

ReactDOM.render( <EnterOrder / > , document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>


问:
Getting text inside p element inside div
I have following rendered html

```<code><div class="footer text-center">
  <p>By signing up, you agree to abc's <b>Terms of Service</b>, <b>Cookie Policy</b>, <b>Privacy Policy and Content Policies.</b></p>
</div>
</code>```

I am trying following to validate text is appearing as expected.
But getAttribute('value') returns Null and hence test failing.

```<code>element(by.tagName('p')).getAttribute('value').then(function (text) {
    expect(text).toBe("By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.");
});
</code>```

答: You can use getText. It will return you all text from inner tags as well.</p>

Body:
I have following rendered html

By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.

I am trying following to validate text is appearing as expected.
But getAttribute('value') returns Null and hence test failing.

element(by.tagName('p')).getAttribute('value').then(function (text) {
    expect(text).toBe("By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.");
});


问:
Drag and drop columns between QHeaderView and QListWidget
I am having troubled using the QHeaderView drag & drop feature. When I subclass a QHeaderView, I am able to accept drops with no issue. However, when I click on the QHeaderView and try to drag from one of the columns, nothing appears to happen.

Below I have re-implemented several drag events to simply print if they were called. However, only the dragEnterEvent is successful. No other event such as startDrag is ever called. My ultimate goal is to have a QTableView where I can drag columns from and to a QListWidget (essentially hiding the column) and the user can then drag the QListWidget item back onto the QTableView if they want the column and its data to be visible again. However, I can’t move forward until I can understand why the QHeaderView is not allowing me to drag. Any help would be greatly appreciated.

```<code>class MyHeader(QHeaderView):
    def __init__(self, parent=None):
        super().__init__(Qt.Horizontal, parent)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)

    def startDrag(self, *args, **kwargs):
        print('start drag success')

    def dragEnterEvent(self, event):
        print('drag enter success')

    def dragLeaveEvent(self, event):
        print('drag leave success')

    def dragMoveEvent(self, event):
        print('drag move success')

class Form(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        listWidget = QListWidget()
        listWidget.setDragEnabled(True)
        listWidget.setAcceptDrops(True)
        listWidget.addItem('item #1')
        listWidget.addItem('item #2')

        tableWidget = QTableWidget()
        header = MyHeader()
        tableWidget.setHorizontalHeader(header)
        tableWidget.setRowCount(5)
        tableWidget.setColumnCount(2)
        tableWidget.setHorizontalHeaderLabels(["Column 1", "Column 2"])

        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(listWidget)
        splitter.addWidget(tableWidget)
        layout = QHBoxLayout()
        layout.addWidget(splitter)
        self.setLayout(layout)

if __name__=='__main__':
    import sys
    app = QApplication(sys.argv)
    form= Form()
    form.show()
    sys.exit(app.exec_())
</code>```

答:
The QHeaderView class does not use the drag and drop methods inherited from QAbstractItemView, because it never needs to initiate a drag operation. Drag and drop is only used for rearranging columns, and it is not necessary to use the QDrag mechanism for that.

Given this, it will be necessary to implement custom drag and drop handling (using mousePressEvent, mouseMoveEvent and dropEvent), and also provide functions for encoding and decoding the mime-data format that Qt uses to pass items between views. An event-filter will be needed for the table-widget, so that dropping is still possible when all columns are hidden; and also for the list-widget, to stop it copying items to itself.

The demo script below implements all of that. There are probably some more refinements needed, but it should be enough to get you started:

```<code>import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class MyHeader(QHeaderView):
    MimeType = 'application/x-qabstractitemmodeldatalist'
    columnsChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        super().__init__(Qt.Horizontal, parent)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self._dragstartpos = None

    def encodeMimeData(self, items):
        data = QByteArray()
        stream = QDataStream(data, QIODevice.WriteOnly)
        for column, label in items:
            stream.writeInt32(0)
            stream.writeInt32(column)
            stream.writeInt32(2)
            stream.writeInt32(int(Qt.DisplayRole))
            stream.writeQVariant(label)
            stream.writeInt32(int(Qt.UserRole))
            stream.writeQVariant(column)
        mimedata = QMimeData()
        mimedata.setData(MyHeader.MimeType, data)
        return mimedata

    def decodeMimeData(self, mimedata):
        data = []
        stream = QDataStream(mimedata.data(MyHeader.MimeType))
        while not stream.atEnd():
            row = stream.readInt32()
            column = stream.readInt32()
            item = {}
            for count in range(stream.readInt32()):
                key = stream.readInt32()
                item[key] = stream.readQVariant()
            data.append([item[Qt.UserRole], item[Qt.DisplayRole]])
        return data

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._dragstartpos = event.pos()
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if (event.buttons() & Qt.LeftButton and
            self._dragstartpos is not None and
            (event.pos() - self._dragstartpos).manhattanLength() >=
            QApplication.startDragDistance()):
            column = self.logicalIndexAt(self._dragstartpos)
            data = [column, self.model().headerData(column, Qt.Horizontal)]
            self._dragstartpos = None
            drag = QDrag(self)
            drag.setMimeData(self.encodeMimeData([data]))
            action = drag.exec(Qt.MoveAction)
            if action != Qt.IgnoreAction:
                self.setColumnHidden(column, True)

    def dropEvent(self, event):
        mimedata = event.mimeData()
        if mimedata.hasFormat(MyHeader.MimeType):
            if event.source() is not self:
                for column, label in self.decodeMimeData(mimedata):
                    self.setColumnHidden(column, False)
                event.setDropAction(Qt.MoveAction)
                event.accept()
            else:
                event.ignore()
        else:
            super().dropEvent(event)

    def setColumnHidden(self, column, hide=True):
        count = self.count()
        if 0 <= column < count and hide != self.isSectionHidden(column):
            if hide:
                self.hideSection(column)
            else:
                self.showSection(column)
            self.columnsChanged.emit(count - self.hiddenSectionCount())

class Form(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.listWidget = QListWidget()
        self.listWidget.setAcceptDrops(True)
        self.listWidget.setDragEnabled(True)
        self.listWidget.viewport().installEventFilter(self)

        self.tableWidget = QTableWidget()
        header = MyHeader(self)
        self.tableWidget.setHorizontalHeader(header)
        self.tableWidget.setRowCount(5)
        self.tableWidget.setColumnCount(4)

        labels = ["Column 1", "Column 2", "Column 3", "Column 4"]
        self.tableWidget.setHorizontalHeaderLabels(labels)
        for column, label in enumerate(labels):
            if column > 1:
                item = QListWidgetItem(label)
                item.setData(Qt.UserRole, column)
                self.listWidget.addItem(item)
                header.hideSection(column)

        header.columnsChanged.connect(
            lambda count: self.tableWidget.setAcceptDrops(not count))
        self.tableWidget.viewport().installEventFilter(self)

        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(self.listWidget)
        splitter.addWidget(self.tableWidget)
        layout = QHBoxLayout()
        layout.addWidget(splitter)
        self.setLayout(layout)

    def eventFilter(self, source, event):
        if event.type() == QEvent.Drop:
            if source is self.tableWidget.viewport():
                self.tableWidget.horizontalHeader().dropEvent(event)
                return True
            else:
                event.setDropAction(Qt.MoveAction)
        return super().eventFilter(source, event)

if __name__=='__main__':

    app = QApplication(sys.argv)
    form = Form()
    form.setGeometry(600, 50, 600, 200)
    form.show()
    sys.exit(app.exec_())
</code>```

Body:
I am having troubled using the QHeaderView drag & drop feature. When I subclass a QHeaderView, I am able to accept drops with no issue. However, when I click on the QHeaderView and try to drag from one of the columns, nothing appears to happen.

Below I have re-implemented several drag events to simply print if they were called. However, only the dragEnterEvent is successful. No other event such as startDrag is ever called. My ultimate goal is to have a QTableView where I can drag columns from and to a QListWidget (essentially hiding the column) and the user can then drag the QListWidget item back onto the QTableView if they want the column and its data to be visible again. However, I can’t move forward until I can understand why the QHeaderView is not allowing me to drag. Any help would be greatly appreciated.

class MyHeader(QHeaderView):
    def __init__(self, parent=None):
        super().__init__(Qt.Horizontal, parent)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)

    def startDrag(self, *args, **kwargs):
        print('start drag success')

    def dragEnterEvent(self, event):
        print('drag enter success')

    def dragLeaveEvent(self, event):
        print('drag leave success')

    def dragMoveEvent(self, event):
        print('drag move success')

class Form(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        listWidget = QListWidget()
        listWidget.setDragEnabled(True)
        listWidget.setAcceptDrops(True)
        listWidget.addItem('item #1')
        listWidget.addItem('item #2')

        tableWidget = QTableWidget()
        header = MyHeader()
        tableWidget.setHorizontalHeader(header)
        tableWidget.setRowCount(5)
        tableWidget.setColumnCount(2)
        tableWidget.setHorizontalHeaderLabels(["Column 1", "Column 2"])

        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(listWidget)
        splitter.addWidget(tableWidget)
        layout = QHBoxLayout()
        layout.addWidget(splitter)
        self.setLayout(layout)

if __name__=='__main__':
    import sys
    app = QApplication(sys.argv)
    form= Form()
    form.show()
    sys.exit(app.exec_())

Body:
The QHeaderView class does not use the drag and drop methods inherited from QAbstractItemView, because it never needs to initiate a drag operation. Drag and drop is only used for rearranging columns, and it is not necessary to use the QDrag mechanism for that.

Given this, it will be necessary to implement custom drag and drop handling (using mousePressEvent, mouseMoveEvent and dropEvent), and also provide functions for encoding and decoding the mime-data format that Qt uses to pass items between views. An event-filter will be needed for the table-widget, so that dropping is still possible when all columns are hidden; and also for the list-widget, to stop it copying items to itself.

The demo script below implements all of that. There are probably some more refinements needed, but it should be enough to get you started:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class MyHeader(QHeaderView):
    MimeType = 'application/x-qabstractitemmodeldatalist'
    columnsChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        super().__init__(Qt.Horizontal, parent)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self._dragstartpos = None

    def encodeMimeData(self, items):
        data = QByteArray()
        stream = QDataStream(data, QIODevice.WriteOnly)
        for column, label in items:
            stream.writeInt32(0)
            stream.writeInt32(column)
            stream.writeInt32(2)
            stream.writeInt32(int(Qt.DisplayRole))
            stream.writeQVariant(label)
            stream.writeInt32(int(Qt.UserRole))
            stream.writeQVariant(column)
        mimedata = QMimeData()
        mimedata.setData(MyHeader.MimeType, data)
        return mimedata

    def decodeMimeData(self, mimedata):
        data = []
        stream = QDataStream(mimedata.data(MyHeader.MimeType))
        while not stream.atEnd():
            row = stream.readInt32()
            column = stream.readInt32()
            item = {}
            for count in range(stream.readInt32()):
                key = stream.readInt32()
                item[key] = stream.readQVariant()
            data.append([item[Qt.UserRole], item[Qt.DisplayRole]])
        return data

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._dragstartpos = event.pos()
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if (event.buttons() & Qt.LeftButton and
            self._dragstartpos is not None and
            (event.pos() - self._dragstartpos).manhattanLength() >=
            QApplication.startDragDistance()):
            column = self.logicalIndexAt(self._dragstartpos)
            data = [column, self.model().headerData(column, Qt.Horizontal)]
            self._dragstartpos = None
            drag = QDrag(self)
            drag.setMimeData(self.encodeMimeData([data]))
            action = drag.exec(Qt.MoveAction)
            if action != Qt.IgnoreAction:
                self.setColumnHidden(column, True)

    def dropEvent(self, event):
        mimedata = event.mimeData()
        if mimedata.hasFormat(MyHeader.MimeType):
            if event.source() is not self:
                for column, label in self.decodeMimeData(mimedata):
                    self.setColumnHidden(column, False)
                event.setDropAction(Qt.MoveAction)
                event.accept()
            else:
                event.ignore()
        else:
            super().dropEvent(event)

    def setColumnHidden(self, column, hide=True):
        count = self.count()
        if 0 <= column < count and hide != self.isSectionHidden(column):
            if hide:
                self.hideSection(column)
            else:
                self.showSection(column)
            self.columnsChanged.emit(count - self.hiddenSectionCount())

class Form(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.listWidget = QListWidget()
        self.listWidget.setAcceptDrops(True)
        self.listWidget.setDragEnabled(True)
        self.listWidget.viewport().installEventFilter(self)

        self.tableWidget = QTableWidget()
        header = MyHeader(self)
        self.tableWidget.setHorizontalHeader(header)
        self.tableWidget.setRowCount(5)
        self.tableWidget.setColumnCount(4)

        labels = ["Column 1", "Column 2", "Column 3", "Column 4"]
        self.tableWidget.setHorizontalHeaderLabels(labels)
        for column, label in enumerate(labels):
            if column > 1:
                item = QListWidgetItem(label)
                item.setData(Qt.UserRole, column)
                self.listWidget.addItem(item)
                header.hideSection(column)

        header.columnsChanged.connect(
            lambda count: self.tableWidget.setAcceptDrops(not count))
        self.tableWidget.viewport().installEventFilter(self)

        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(self.listWidget)
        splitter.addWidget(self.tableWidget)
        layout = QHBoxLayout()
        layout.addWidget(splitter)
        self.setLayout(layout)

    def eventFilter(self, source, event):
        if event.type() == QEvent.Drop:
            if source is self.tableWidget.viewport():
                self.tableWidget.horizontalHeader().dropEvent(event)
                return True
            else:
                event.setDropAction(Qt.MoveAction)
        return super().eventFilter(source, event)

if __name__=='__main__':

    app = QApplication(sys.argv)
    form = Form()
    form.setGeometry(600, 50, 600, 200)
    form.show()
    sys.exit(app.exec_())


问:
unzip source code in Iphone
I think I found some discussions on the above topic but nothing very clear. But I would like to know if there is any open source code for unzippping multiple files. I am trying to come up with utility that could download a zip file (with multiple iamges) and extract it in the Iphone .</p>

答:
I recommend my library SSZipArchive.

Usage:

```<code>NSString *path = @"path_to_your_zip_file";
NSString *destination = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:path toDestination:destination];
</code>```

Pretty simple.

Title: unzip source code in Iphone

Body:
I recommend my library SSZipArchive.

Usage:

NSString *path = @"path_to_your_zip_file";
NSString *destination = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:path toDestination:destination];

Pretty simple.


问:
How to access elements in the table cell
I have an HTML table to traverse using DOM.
I begin accessing using my table id and then I am able to access a particular cell.

```<code>'<td><a onclick=send_symbol_2(\"'+comp+'\")>'+comp+'</a></td>'
</code>```

I am confused on how to access the data contained within anchor tags. I had earlier constructed the table by adding strings.
eg: '
	'+arr[4]+'
'
I understand toString() would been called.
I am unsure how to proceed further.
I used

```<code>rows[i].getElementsByTagName("td")[0]
</code>```

to access the cell data.

答:
Try This :

var tableObj = document.getElementById("testTable");
var rows = tableObj.getElementsByTagName("tr");
for(var i=0; i< rows.length ; i++){
  var cells = rows[i].getElementsByTagName("td");
  for (var j=0; j<cells.length ; j++) {
    console.log(cells[j].innerText);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="testTable">
  <tr>
    <td>1</td><td>2</td>
  </tr>
   <tr>
    <td>3</td><td>4</td>
  </tr>
</table></code>```

Body:
I have an HTML table to traverse using DOM.
I begin accessing using my table id and then I am able to access a particular cell.

''+comp+'	'

I am confused on how to access the data contained within anchor tags. I had earlier constructed the table by adding strings.
eg: '
	'+arr[4]+'
'
I understand toString() would been called.
I am unsure how to proceed further.
I used

rows[i].getElementsByTagName("td")[0]

to access the cell data.

Body:
Try This :

var tableObj = document.getElementById("testTable");
var rows = tableObj.getElementsByTagName("tr");
for(var i=0; i< rows.length ; i++){
  var cells = rows[i].getElementsByTagName("td");
  for (var j=0; j<cells.length ; j++) {
    console.log(cells[j].innerText);
  }
}

<table id="testTable">
  <tr>
    <td>1</td><td>2</td>
  </tr>
   <tr>
    <td>3</td><td>4</td>
  </tr>
</table>


问:
Admin Panel for Laravel + Angular
Now I'm building web project using Laravel (API) + Angular.
And I need to add admin panel on my project now.
I'm thinking 2 ways to do this.

Admin Panel in Laravel

Admin Panel in Angular

Which is the recommended way to add Admin panel in my project?
And Why?

Please help me.

Thanks.

答:
There are some packages that give you admin panel in laravel out of the box, I've never used them but a quick google search did show some promising results like Laravel-admin, QuickAdmin

You can also do it in Angular, but you'd also need to:

build your own UI

authorise requests on server-side (Passport)

bright side is you can admin whatever you want with your custom built solution, also somewhat easier to make it into a mobile app if that's even relevant :)

Title: Admin Panel for Laravel + Angular


问:
How should I use FormatMessage() properly in C++?
Without:

MFC

ATL

How can I use FormatMessage() to get the error text for a HRESULT?

```<code> HRESULT hresult = application.CreateInstance("Excel.Application");

 if (FAILED(hresult))
 {
     // what should i put here to obtain a human-readable
     // description of the error?
     exit (hresult);
 }
</code>```

答:
The code below is code is the C++ equivalent I've written out in contrast to Microsoft's ErrorExit() but slightly altered to avoid all macros and use unicode. The idea here is to avoid unnecessary casts and mallocs. I couldn't escape all of the C casts but this is the best I could muster. Pertaining to FormatMessageW(), which requires a pointer to be allocated by the format function and the Error Id from the GetLastError(). The pointer after static_cast can be used like a normal wchar_t pointer. </p>

```<code>#include <string>
#include <windows.h>

void __declspec(noreturn) error_exit(const std::wstring FunctionName)
{
    // Retrieve the system error message for the last-error code
    const DWORD ERROR_ID = GetLastError();
    void* MsgBuffer = nullptr;
    LCID lcid;
    GetLocaleInfoEx(L"en-US", LOCALE_RETURN_NUMBER | LOCALE_ILANGUAGE, (wchar_t*)&lcid, sizeof(lcid));

    //get error message and attach it to Msgbuffer
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, ERROR_ID, lcid, (wchar_t*)&MsgBuffer, 0, NULL);
    //concatonate string to DisplayBuffer
    const std::wstring DisplayBuffer = FunctionName + L" failed with error " + std::to_wstring(ERROR_ID) + L": " + static_cast<wchar_t*>(MsgBuffer);

    // Display the error message and exit the process
    MessageBoxExW(NULL, DisplayBuffer.c_str(), L"Error", MB_ICONERROR | MB_OK, static_cast<WORD>(lcid));

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

OwnerDisplayName: Atklin

Body:
Without:

MFC

ATL

How can I use FormatMessage() to get the error text for a HRESULT?

 HRESULT hresult = application.CreateInstance("Excel.Application");

 if (FAILED(hresult))
 {
     // what should i put here to obtain a human-readable
     // description of the error?
     exit (hresult);
 }

LastEditorDisplayName: Atklin

Body:
The code below is code is the C++ equivalent I've written out in contrast to Microsoft's ErrorExit() but slightly altered to avoid all macros and use unicode. The idea here is to avoid unnecessary casts and mallocs. I couldn't escape all of the C casts but this is the best I could muster. Pertaining to FormatMessageW(), which requires a pointer to be allocated by the format function and the Error Id from the GetLastError(). The pointer after static_cast can be used like a normal wchar_t pointer.

#include <string>
#include <windows.h>

void __declspec(noreturn) error_exit(const std::wstring FunctionName)
{
    // Retrieve the system error message for the last-error code
    const DWORD ERROR_ID = GetLastError();
    void* MsgBuffer = nullptr;
    LCID lcid;
    GetLocaleInfoEx(L"en-US", LOCALE_RETURN_NUMBER | LOCALE_ILANGUAGE, (wchar_t*)&lcid, sizeof(lcid));

    //get error message and attach it to Msgbuffer
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, ERROR_ID, lcid, (wchar_t*)&MsgBuffer, 0, NULL);
    //concatonate string to DisplayBuffer
    const std::wstring DisplayBuffer = FunctionName + L" failed with error " + std::to_wstring(ERROR_ID) + L": " + static_cast<wchar_t*>(MsgBuffer);

    // Display the error message and exit the process
    MessageBoxExW(NULL, DisplayBuffer.c_str(), L"Error", MB_ICONERROR | MB_OK, static_cast<WORD>(lcid));

    ExitProcess(ERROR_ID);
}


问:
Use of uninitialized value $a in concatenation (.) or string
I am trying to remove the old files in a dir if the count is more than 3 over SSH

Kindly suggest how to resolve the issue.

Please refer the code snippet

```<code>#!/usr/bin/perl
use strict;
use warnings;

my $HOME="/opt/app/latest";
my $LIBS="${HOME}/libs";
my $LIBS_BACKUP_DIR="${HOME}/libs_backups";
my $a;
my $b;
my $c;
my $d;

my $command =qq(sudo /bin/su - jenkins -c "ssh username\@server 'my $a=ls ${LIBS_BACKUP_DIR} | wc -l;my $b=`$a`;if ($b > 3); { print " Found More than 3 back up files , removing older files..";my $c=ls -tr ${LIBS_BACKUP_DIR} | head -1;my $d=`$c`;print "Old file name $d";}else { print "No of back up files are less then 3 .";} '");

print "$command\n";
system($command);
</code>```

output:

```<code>sudo /bin/su - jenkins -c "ssh username@server 'my ; =ls /opt/app/latest/libs_backups | wc -l;my ; =``;if ( > 3); { print " Found More than 3 back up files , removing older files..";my ; =ls -tr /opt/app/latest/libs_backups | head -1;my ; =``;print "Old file name ";}else { print "No of back up files are less then 3 .";} '"
Found: -c: line 0: unexpected EOF while looking for matching `''
Found: -c: line 1: syntax error: unexpected end of file
</code>```

答:
If you have three levels of escaping, you're bound to get it wrong if you do it manually. Use String::ShellQuote's shell_quote instead.

Furthermore, avoid generating code. You're bound to get it wrong! Pass the necessary information using arguments, the environment or some other channel of communication instead.

There were numerous errors in the interior Perl script on top of the fact that you tried to execute a Perl script without actually invoking perl!

```<code>#!/usr/bin/perl

use strict;
use warnings;

use String::ShellQuote qw( shell_quote );

my $HOME = "/opt/app/latest";
my $LIBS = "$HOME/libs";
my $LIBS_BACKUP_DIR = "$HOME/libs_backups";

my $perl_script = <<'__EOI__';
   use strict;
   use warnings;

   use String::ShellQuote qw( shell_quote );

   my ($LIBS_BACKUP_DIR) = @ARGV;

   my $cmd = shell_quote("ls", "-tr", "--", $LIBS_BACKUP_DIR);
   chomp( my @files =  `$cmd` );
   if (@files > 3) {
      print "Found more than 3 back up files. Removing older files...\n";
      print "$_\n" for @files;
   } else {
      print "Found three or fewer backup files.\n";
   }
__EOI__

my $remote_cmd = shell_quote("perl", "-e", $perl_script, "--", $LIBS_BACKUP_DIR);
my $ssh_cmd = shell_quote("ssh", 'username@server', "--", $remote_cmd);
my $local_cmd = shell_quote("sudo", "su", "-c", $ssh_ccmd);
system($local_cmd);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to remove the old files in a dir if the count is more than 3 over SSH

Kindly suggest how to resolve the issue.

Please refer the code snippet

#!/usr/bin/perl
use strict;
use warnings;

my $HOME="/opt/app/latest";
my $LIBS="${HOME}/libs";
my $LIBS_BACKUP_DIR="${HOME}/libs_backups";
my $a;
my $b;
my $c;
my $d;

my $command =qq(sudo /bin/su - jenkins -c "ssh username\@server 'my $a=ls ${LIBS_BACKUP_DIR} | wc -l;my $b=`$a`;if ($b > 3); { print " Found More than 3 back up files , removing older files..";my $c=ls -tr ${LIBS_BACKUP_DIR} | head -1;my $d=`$c`;print "Old file name $d";}else { print "No of back up files are less then 3 .";} '");

print "$command\n";
system($command);

output:

sudo /bin/su - jenkins -c "ssh username@server 'my ; =ls /opt/app/latest/libs_backups | wc -l;my ; =``;if ( > 3); { print " Found More than 3 back up files , removing older files..";my ; =ls -tr /opt/app/latest/libs_backups | head -1;my ; =``;print "Old file name ";}else { print "No of back up files are less then 3 .";} '"
Found: -c: line 0: unexpected EOF while looking for matching `''
Found: -c: line 1: syntax error: unexpected end of file

Body:
If you have three levels of escaping, you're bound to get it wrong if you do it manually. Use String::ShellQuote's shell_quote instead.

Furthermore, avoid generating code. You're bound to get it wrong! Pass the necessary information using arguments, the environment or some other channel of communication instead.

There were numerous errors in the interior Perl script on top of the fact that you tried to execute a Perl script without actually invoking perl!

#!/usr/bin/perl

use strict;
use warnings;

use String::ShellQuote qw( shell_quote );

my $HOME = "/opt/app/latest";
my $LIBS = "$HOME/libs";
my $LIBS_BACKUP_DIR = "$HOME/libs_backups";

my $perl_script = <<'__EOI__';
   use strict;
   use warnings;

   use String::ShellQuote qw( shell_quote );

   my ($LIBS_BACKUP_DIR) = @ARGV;

   my $cmd = shell_quote("ls", "-tr", "--", $LIBS_BACKUP_DIR);
   chomp( my @files =  `$cmd` );
   if (@files > 3) {
      print "Found more than 3 back up files. Removing older files...\n";
      print "$_\n" for @files;
   } else {
      print "Found three or fewer backup files.\n";
   }
__EOI__

my $remote_cmd = shell_quote("perl", "-e", $perl_script, "--", $LIBS_BACKUP_DIR);
my $ssh_cmd = shell_quote("ssh", 'username@server', "--", $remote_cmd);
my $local_cmd = shell_quote("sudo", "su", "-c", $ssh_ccmd);
system($local_cmd);


问:
Issue while invoking chrome browser with Selenium Driver
When i am trying to invoke chrome browser in eclipse using selenium driver with Java , i am getting an error.

Please help me out in resolving this issue.

Below is my code -

```<code>package packagedefault;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ChromeBrowser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.get("https://google.com");

    }

}
</code>```

Below is the error message i am getting -

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/config/RegistryBuilder
    at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:69)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:57)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:60)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.getDefaultHttpClientFactory(ApacheHttpClient.java:242)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.<init>(ApacheHttpClient.java:219)
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:63)
    at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:36)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at packagedefault.ChromeBrowser.main(ChromeBrowser.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.http.config.RegistryBuilder
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 13 more
</code>```

答:
Exception you mentioned

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/apache/http/config/RegistryBuilder

Occured when jars files are not available.
Import only the selenium-server-standalone- jars and try your code .

```<code> System.setProperty("webdriver.chrome.driver", "Path of chromedriver.exe");
 WebDriver driver=new ChromeDriver();
 driver.get("https://google.com");
</code>```

Body:
When i am trying to invoke chrome browser in eclipse using selenium driver with Java , i am getting an error.

Please help me out in resolving this issue.

Below is my code -

package packagedefault;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ChromeBrowser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.get("https://google.com");

    }

}

Below is the error message i am getting -

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/config/RegistryBuilder
    at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:69)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:57)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:60)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.getDefaultHttpClientFactory(ApacheHttpClient.java:242)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.<init>(ApacheHttpClient.java:219)
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:63)
    at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:36)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at packagedefault.ChromeBrowser.main(ChromeBrowser.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.http.config.RegistryBuilder
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 13 more

Body:
Exception you mentioned

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/apache/http/config/RegistryBuilder

Occured when jars files are not available.
Import only the selenium-server-standalone- jars and try your code .

 System.setProperty("webdriver.chrome.driver", "Path of chromedriver.exe");
 WebDriver driver=new ChromeDriver();
 driver.get("https://google.com");


问:
Return undefined or throw error upon invalid function input?
I know this is a duplicate but the anwser over here simply does not satisfy me:

JS library best practice: Return undefined or throw error on bad function input?

I'd like to talk about a few things that were pointed out and what remained unclear to me.

First off I'd like to present one example where I personally would rather throw an error then return undefined.

```<code>function sum(a, b)
</code>```

Say the consumer passes a string because he passed the direct value of an input box and the end user typed in something other than a number.

If I as the author of sum had returned undefined upon string input, then even if the dev had typed in a string at some point, nothing would have happened and he wouldnt have cared, as thats what was to be expected. But in this case, had I thrown an error, the dev would have realised that thats actually an edge case that had to be handled, because after all, no one wants errors in their program.

So basicly, why not make devs aware of edge cases by actually throwing errors?

This was a comment on the question mentioned above which pretty much is exactly what I am asking but no one replied yet:

"But since it takes 1 extra min for me to throw an error instead of dying silently, won't that save hours in debugging time for those who didn't take the time to read the docs?"

Another point that is in the accepted anwser from above:

"Catching an exception is a lot slower than testing a return value so if an error is a common occurrence, then exceptions will be a lot slower."

The only case I can think of where this qoute applies to is with I/O or networky stuff where the input is always in the correct format but e.g. a user does not exist with that id.

In cases like that, I understand why throwing an error would slow down the process. But again, what about a math library consisting of only pure, synchronous functions?

Isn't it smarter to check the input instead of checking the output? (Make sure the input will work instead of running the function and checking if undefined is returned)

A lot of my confusion really stems from type checking actually as I do come from the C# world and think a library should be used in its exact way as intended rather than it being merciful and working anyway.

答:
I would argue that for an OO language it's common to return null even though that's bad practice and the inventor of null calls it the billion dollar mistake.

Functional languages have solved this problem before OO even existed by having a Maybe type.

When composing functions you could use a variation of a Maybe that contains a Success or Failure, Scott Wlaschin calls this railway orientated programming and Promises are a kind of railway orientated programming.

The problem with using Maybe in OO is that you don't have union types. In F# your code would look like this:

```<code>let x =
  // 9/0 throws so divideBy returns None the caller of divideBy can
  //decide what to do this this.
  match (divideBy 9 0) with
  | Some result -> //process result
  | None -> //handle this case
</code>```

When matching something in F# you'll get a compile time error if you forget a case (not handle the None). In OO you won't and are stuck with runtime errors or failing quietly. Improvements in C# may come with the compiler warning you when you try to access nullable types but that only takes care of the if not null, it does not force you to provide an else.

So in JavaScript I would advice using Promises or returning a result object. Promises are native to modern browsers and nodejs. In the browser it will shout at you in the console when you do not handle failed promises (errors in console and break at uncaught rejection in sources). In the future; for nodejs; it will cause your process to stop as with an unhandled exception.

```<code>//example with promises
const processNumber = compose([
  //assuming divideBy returns a promise that is rejected when dividing by zero
  divideBy(9)
  ,plus(1)
  ,minus(2)
  ,toString
])
// 9/0 returns rejected promise so plus,minus and toString are never executed
processNumber(0)
.then(
  success => //do something with the success value
  ,fail => //do something with the failure
);

//example of result type:
const Success = {}
,Failure = {}
,result = (type) => (value) =>
  (type === Failure)
    //Failure type should throw when trying to get a value out of it
    ? Object.create({type:type,error:value}, {
      value: {
        configurable: false,
        get: function() {
          throw "Cannot get value from Failure type"
        }
      }
    })
    : ({
      type:type
      ,value:value
    })
;
//convert a function (T->T) to (result T->result T)
const lift = fn => arg => {
  //do not call funcion if argument is of type Failure
  if(arg.type === Failure){
    return arg;
  }
  try {
    const r = fn(arg.value);
    //return a success result
    return result(Success)(r);
  } catch (e) {
    //return a failure result
    return result(Failure)(e);
  }
};
//takes a result and returns a result
const processNumber = compose(
  [
    //assuming divideBy throws error when dividing by zero
    divideBy(9)
    ,plus(1)
    ,minus(2)
    ,toString
  ].map( //lift (T->T) to (result T -> result T)
    x => lift(x)
  )
);

const r = processNumber(result(Success)(0));//returns result of type Failure
if(r.type === Failure){
  //handle failure
} else {
  //handle r.value
}
</code>```

You could just return null or throw but more and more people in OO start to realize that's not the best way to handle things. Throwing is a side effect so makes the function impure (the more impure functions the harder it is maintain your code).

Null is not good type to reflect functions that could fail. You don't know why it failed to return the expected type and now have to make assumptions as to why, making assumptions in code makes your code harder to maintain.

Body:
I know this is a duplicate but the anwser over here simply does not satisfy me:

JS library best practice: Return undefined or throw error on bad function input?

I'd like to talk about a few things that were pointed out and what remained unclear to me.

First off I'd like to present one example where I personally would rather throw an error then return undefined.

function sum(a, b)

Say the consumer passes a string because he passed the direct value of an input box and the end user typed in something other than a number.

If I as the author of sum had returned undefined upon string input, then even if the dev had typed in a string at some point, nothing would have happened and he wouldnt have cared, as thats what was to be expected. But in this case, had I thrown an error, the dev would have realised that thats actually an edge case that had to be handled, because after all, no one wants errors in their program.

So basicly, why not make devs aware of edge cases by actually throwing errors?

This was a comment on the question mentioned above which pretty much is exactly what I am asking but no one replied yet:

"But since it takes 1 extra min for me to throw an error instead of dying silently, won't that save hours in debugging time for those who didn't take the time to read the docs?"

Another point that is in the accepted anwser from above:

"Catching an exception is a lot slower than testing a return value so if an error is a common occurrence, then exceptions will be a lot slower."

The only case I can think of where this qoute applies to is with I/O or networky stuff where the input is always in the correct format but e.g. a user does not exist with that id.

In cases like that, I understand why throwing an error would slow down the process. But again, what about a math library consisting of only pure, synchronous functions?

Isn't it smarter to check the input instead of checking the output? (Make sure the input will work instead of running the function and checking if undefined is returned)

A lot of my confusion really stems from type checking actually as I do come from the C# world and think a library should be used in its exact way as intended rather than it being merciful and working anyway.

Body:
I would argue that for an OO language it's common to return null even though that's bad practice and the inventor of null calls it the billion dollar mistake.

Functional languages have solved this problem before OO even existed by having a Maybe type.

When composing functions you could use a variation of a Maybe that contains a Success or Failure, Scott Wlaschin calls this railway orientated programming and Promises are a kind of railway orientated programming.

The problem with using Maybe in OO is that you don't have union types. In F# your code would look like this:

let x =
  // 9/0 throws so divideBy returns None the caller of divideBy can
  //decide what to do this this.
  match (divideBy 9 0) with
  | Some result -> //process result
  | None -> //handle this case

When matching something in F# you'll get a compile time error if you forget a case (not handle the None). In OO you won't and are stuck with runtime errors or failing quietly. Improvements in C# may come with the compiler warning you when you try to access nullable types but that only takes care of the if not null, it does not force you to provide an else.

So in JavaScript I would advice using Promises or returning a result object. Promises are native to modern browsers and nodejs. In the browser it will shout at you in the console when you do not handle failed promises (errors in console and break at uncaught rejection in sources). In the future; for nodejs; it will cause your process to stop as with an unhandled exception.

//example with promises
const processNumber = compose([
  //assuming divideBy returns a promise that is rejected when dividing by zero
  divideBy(9)
  ,plus(1)
  ,minus(2)
  ,toString
])
// 9/0 returns rejected promise so plus,minus and toString are never executed
processNumber(0)
.then(
  success => //do something with the success value
  ,fail => //do something with the failure
);

//example of result type:
const Success = {}
,Failure = {}
,result = (type) => (value) =>
  (type === Failure)
    //Failure type should throw when trying to get a value out of it
    ? Object.create({type:type,error:value}, {
      value: {
        configurable: false,
        get: function() {
          throw "Cannot get value from Failure type"
        }
      }
    })
    : ({
      type:type
      ,value:value
    })
;
//convert a function (T->T) to (result T->result T)
const lift = fn => arg => {
  //do not call funcion if argument is of type Failure
  if(arg.type === Failure){
    return arg;
  }
  try {
    const r = fn(arg.value);
    //return a success result
    return result(Success)(r);
  } catch (e) {
    //return a failure result
    return result(Failure)(e);
  }
};
//takes a result and returns a result
const processNumber = compose(
  [
    //assuming divideBy throws error when dividing by zero
    divideBy(9)
    ,plus(1)
    ,minus(2)
    ,toString
  ].map( //lift (T->T) to (result T -> result T)
    x => lift(x)
  )
);

const r = processNumber(result(Success)(0));//returns result of type Failure
if(r.type === Failure){
  //handle failure
} else {
  //handle r.value
}

You could just return null or throw but more and more people in OO start to realize that's not the best way to handle things. Throwing is a side effect so makes the function impure (the more impure functions the harder it is maintain your code).

Null is not good type to reflect functions that could fail. You don't know why it failed to return the expected type and now have to make assumptions as to why, making assumptions in code makes your code harder to maintain.


答:
The details you give do not specify any relationships so based on the information you have provided I am assuming that all you want to be able to do is tell which keys are available/unavailable at any given time.

For starters you can use the following query to list all keys that have not been distributed.

```<code>SELECT tblKey.KeyID, tblKey.Distributed
FROM tblKey
WHERE (((tblKey.Distributed)=False));
</code>```

Change the =False to =True to reverse the logic and show all cards that have been distributed.

If you want to look for a specific key ID to find out if it has been distributed or not use the following:

```<code>SELECT tblKey.KeyID, tblKey.Distributed
FROM tblKey
WHERE (((tblKey.KeyID)=[Enter Key ID]));
</code>```

This will present the user with a window where the key ID can be entered. Query Parameters are explained in greater detail here

Title: Queries in MS Access 2003

Body:
I am working on a database for a small hotel. Once a guest gets a room reserved they are given a parking lot card that needs to be returned as the guest check-out. I need help on  writing a query that would let the user know that Parking Lot card 01 (or any card #, that has already been given out to a guest) is unavailable. Can anyone please help me set this up. Thanks.

Tbls used

Guest tbl

GuestID PK

Check in date

Check out date

Room #

Room Type
Access Key Id

Access Key tbl

Access Key ID PK

Distributed - yes or no

Body:
The details you give do not specify any relationships so based on the information you have provided I am assuming that all you want to be able to do is tell which keys are available/unavailable at any given time.

For starters you can use the following query to list all keys that have not been distributed.

SELECT tblKey.KeyID, tblKey.Distributed
FROM tblKey
WHERE (((tblKey.Distributed)=False));

Change the =False to =True to reverse the logic and show all cards that have been distributed.

If you want to look for a specific key ID to find out if it has been distributed or not use the following:

SELECT tblKey.KeyID, tblKey.Distributed
FROM tblKey
WHERE (((tblKey.KeyID)=[Enter Key ID]));

This will present the user with a window where the key ID can be entered. Query Parameters are explained in greater detail here


问:
getting 'Invariant Violation: `refreshing` prop must be set as a boolean in order to use `onRefresh`, but got `undefined`'
When the home screen loads I get 'Invariant Violation: refreshing prop must be set as a boolean in order to use onRefresh, but got undefined'  please help.

```<code>class Home extends Component {

constructor(props) {
    super(props)

    this.state = {
      suggestionList:[],
      refreshing:false,
    };
}

componentWillReceiveProps(nextProps){

    this.setState({

      suggestionList: nextProps.result.suggestionsArray ,
      lastSuggestionKey : nextProps.result.lastSuggestionKey,
      refreshing : false

    });

}

handleRowPress = (item) => {
  this.props.navigation.navigate('UserDetails', item);
};

handleMoreRequest = () => {
  this.props.getOld(this.state.lastSuggestionKey);
};

handleRefresh = () => {

  this.setState({
    lastSuggestionKey: '',
    refreshing: true
  });

  this.props.getAll();
};

componentWillMount() {

  this.props.getAll();

}

 render() {

  return (
    <View style={styles.containerStyle}>

      <FlatList
        style={{backgroundColor: colors.background}}
        data={this.state.suggestionList}
        renderItem={(item) =>
          <CardItem contact={item.item}
                    onPress={() => this.handleRowPress(item)}
                    onCommentPress={() => this.props.navigation.navigate('SuggestionList')}/>
        }
        keyExtractor={item => item.suggestionid}
        refeshing={this.state.refreshing}
        onRefresh={() => this.handleRefresh()}
        onEndReached={this.handleMoreRequest}
        onEndReachedThreshold={0.7}
      />

    </View>
  );

  }
   }

const styles = StyleSheet.create({
  containerStyle:{
    flex:1,
    backgroundColor: colors.background
  },
});

function mapStateToProps({ suggestion }) {
  return {
    result: suggestion.result,
  };
}

export default connect(mapStateToProps, actions)(Home);
</code>```

答: You have a typo on your FlatList props, it should be refreshing instead of refeshing.

Body:
When the home screen loads I get 'Invariant Violation: refreshing prop must be set as a boolean in order to use onRefresh, but got undefined'  please help.

class Home extends Component {

constructor(props) {
    super(props)

    this.state = {
      suggestionList:[],
      refreshing:false,
    };
}

componentWillReceiveProps(nextProps){

    this.setState({

      suggestionList: nextProps.result.suggestionsArray ,
      lastSuggestionKey : nextProps.result.lastSuggestionKey,
      refreshing : false

    });

}

handleRowPress = (item) => {
  this.props.navigation.navigate('UserDetails', item);
};

handleMoreRequest = () => {
  this.props.getOld(this.state.lastSuggestionKey);
};

handleRefresh = () => {

  this.setState({
    lastSuggestionKey: '',
    refreshing: true
  });

  this.props.getAll();
};

componentWillMount() {

  this.props.getAll();

}

 render() {

  return (
    <View style={styles.containerStyle}>

      <FlatList
        style={{backgroundColor: colors.background}}
        data={this.state.suggestionList}
        renderItem={(item) =>
          <CardItem contact={item.item}
                    onPress={() => this.handleRowPress(item)}
                    onCommentPress={() => this.props.navigation.navigate('SuggestionList')}/>
        }
        keyExtractor={item => item.suggestionid}
        refeshing={this.state.refreshing}
        onRefresh={() => this.handleRefresh()}
        onEndReached={this.handleMoreRequest}
        onEndReachedThreshold={0.7}
      />

    </View>
  );

  }
   }

const styles = StyleSheet.create({
  containerStyle:{
    flex:1,
    backgroundColor: colors.background
  },
});

function mapStateToProps({ suggestion }) {
  return {
    result: suggestion.result,
  };
}

export default connect(mapStateToProps, actions)(Home);


问:
Securing Express API
I'm writing a web app with a separate frontend and backend. The frontend is written in React, and the backend is a node.js server running an Express endpoint. How do I ensure that only my frontend can access the API, and not anyone else? My API URL is exposed in my frontend client side code, so anyone can see that.

I added JWT authentication to my API, but I still need to have an unprotected /login endpoint in order to generate the JWT token, and in order to login to generate the token, I must post both a username and password from my frontend, which other users can see, since it's done from the client side.

What is the proper way of securing an API that is hosted on a separate backend like this, so that only my frontend can access it, in a way where nobody can see what credentials are being used to access the endpoint?

答:
You can't. Your API is on the internet. Anyone can access it. You can require an account and login credentials for the account before allowing access to the API, but once someone has an account and credentials, they can access the API from their own script rather than via your web page. This is how the web works. Not much you can do about it. And credentials being used by the client cannot be hidden. All data that is EVER on the client can be looked at by a hacker on the client. This is the way of the web.

Larger companies will typically monitor their API usage to look for inappropriate use. This includes rate limiting, detecting behaviors and sequences that are not typical of a regular human user. When they detect inappropriate use, they will often disable that action or ban the offending account, either temporarily or permanently. This is also why some pages use techniques to detect if an actual human is individually causing the operation such as reCaptcha.  For example, on stack overflow, when editing comments or posts, I often run into rate limiting where it tells me that I have to wait a bit before it will accept my edit.

There is no absolutely secure way to store credentials in a client.  The most common scheme for credentials is to require username and password (securely over https) and then when that is accepted on the server as legit credentials, some sort of token is issued to the client which can be used for future API calls.  That token may be in a cookie or may need to be manually included with each subsequent API call (the advantage of a cookie when using APIs from a browser is that the cookie is automatically sent with each subsequent request).

If the token is a cookie, then the cookie is stored in the browser's cookie storage and an expiration can be set for it.  The browser's cookie storage is protected from access by web pages from other sites, but can be accessed by someone on the local computer (it's stored in the file system).

If the token is not a cookie, just returned as a token, and the client wishes to store it, there are a few other places that Javascript provides access to in order to store it.  Local storage has similar security as cookie storage.  It is protected from access by other web sites, but can be accessed by a person on the local computer.

Title: Securing Express API


问:
adonisjs migration issue with mysql
I'm trying to get the hang of adonisjs through this tutorial

I set up everything properly as instructed in there but I run into a problem when I type adonis migration:run.
The error I get on Terminal is Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: NO)

I have 0 experience with mysql and this confuses me. I'd appreciate some guidance/help here.

Cheers!

答:
@katotopark, this means your MySQL server is rejecting the connection from the Adonisjs application. check for a file called (.env) in the root folder of your project and inside you will need to add the credentials for the connection the MySQL server. (probably user: root, password: the password you use when you installed MySQL)

your .env should look similar to this.

```<code>DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=root/or-another-mysql-user
DB_PASSWORD=your-database-user-password***
DB_DATABASE=the_name_of_your_database
</code>```

Regards.

Title: adonisjs migration issue with mysql

Body:
@katotopark, this means your MySQL server is rejecting the connection from the Adonisjs application. check for a file called (.env) in the root folder of your project and inside you will need to add the credentials for the connection the MySQL server. (probably user: root, password: the password you use when you installed MySQL)

your .env should look similar to this.

DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=root/or-another-mysql-user
DB_PASSWORD=your-database-user-password***
DB_DATABASE=the_name_of_your_database

Regards.


问:
Django create instance from views.py not working
I have a Django app that is basically a list app for tracking jobs that the user is applying for.  Users have applications and applications have questions that the user wants to ask to the interviewers should they get an interview.  So I have created a many to many relationship between the models 'Application' and 'Question' called 'Ask'. Models.py:

```<code>class Application(models.Model):
    status_choices = (
        ('NS','Not Started'),
        ('IP','In Progress'),
        ('OH','On Hold'),
        ('CO','Complete'),
    )
    app_status = models.CharField(max_length=2,choices=status_choices)
    position = models.CharField(max_length=255)
    company = models.ForeignKey(Company)
    applied_date = models.DateField(null=True)
    isDeleted = models.BooleanField(default=False, blank=True)
    user = models.ForeignKey(User)
    def __str__(self):
        return self.position

class Questions(models.Model):
    question = models.CharField(max_length=255)
    category = models.CharField(max_length=25)
    isDeleted = models.BooleanField(default=False, blank=True)

class Ask(models.Model): #joining table
    question = models.ForeignKey(Questions)
    app = models.ForeignKey(Application)
    isDeleted = models.BooleanField(default=False, blank=True)
</code>```

So the idea is that the user creates a list of questions and then when they get an interview, they prepare for it by looking at their list of questions and assigning them to the application through a template. Questions.html:

```<code>{% extends 'base.html' %}

{% block body %}
<h1> Questions </h1>
    <div class="table-responsive" align="center">
        <table class="table-hover" width="75%">
            <tr>
                <th> Category </th>
                <th> Question </th>
                <th> <a href="{% url 'JQ:create_question' %}" class="btn btn-success"> Create Question</a></th>
                <form method="POST">
                    {% csrf_token %}
                    <input type="text" name="app" value="{{ request.META.HTTP_REFERER }}">
                <th><input type='submit' value='Add Selected'></th>
            </tr>
            {% for item in query %}
            <tr>
                <td> {{ item.category }} </td>
                <td> {{ item.question }} </td>
                <td> <input type="checkbox" name="selected_q" value="{{ item.id }}"></td>
                <td> <a href="{% url 'JQ:delete_question' item.id %}"> Delete </a> </td>
                <td> <a href="{% url 'JQ:edit_question' item.id %}"> Edit </a> </td>
            </tr>
            </form>
            {% endfor %}
        </table>
    </div>
{% endblock %}
</code>```

Which is called from views.py:

```<code>class QuestionView(TemplateView):
    template_name = 'question.html'

    def get(self, request):
        query = Questions.objects.all().order_by('category')
        args = {'query': query}
        return render(request, self.template_name, args)

    def post(self, request):
        id_list = request.POST.getlist('selected_q')
        return_url = request.POST.get('app')
        app = int(return_url.rsplit('/')[-1])
        myApp = Application.objects.get(pk=app)
        if id_list != None:
            for item in id_list:
                myQuestion = Questions.objects.get(pk=int(item))
                Ask.objects.create(app=myApp,question=myQuestion)
            return HttpResponseRedirect(return_url)
        else:
            query = Questions.objects.all().order_by('category')
            args = {'query': query}
            return render(request, self.template_name, args)
</code>```

The user can only get to the questions page by going through the Application view and when that happens Questions.html captures the link that the user came from.  Users then select one or more questions through a checkbox on questions.html which is captured in the post as id_list - So this should give me the two keys I need to create an instance of Ask.

However, when trying to do this it looks like everything works properly, but no instance of Ask is created and I don't get any error messages.  I have tried creating a record from the python shell and it works just fine. I have also tried other methods such as using a form and instantiating Ask to call .save() afterwards, but it does not insert a record. For testing, I took out the query in views.py to check to make sure valid values are getting passed to myApp and myQuestion, so I believe that the data is all there and accurate, but it isn't creating a record for some reason.

I appreciate any help you might offer, or maybe just different ideas on how to debug this problem so I can get some error messages.

答: Blurb was right - wrapping the table in the form tag resolved the issue. Thanks!</p>

Body:
I have a Django app that is basically a list app for tracking jobs that the user is applying for.  Users have applications and applications have questions that the user wants to ask to the interviewers should they get an interview.  So I have created a many to many relationship between the models 'Application' and 'Question' called 'Ask'. Models.py:

class Application(models.Model):
    status_choices = (
        ('NS','Not Started'),
        ('IP','In Progress'),
        ('OH','On Hold'),
        ('CO','Complete'),
    )
    app_status = models.CharField(max_length=2,choices=status_choices)
    position = models.CharField(max_length=255)
    company = models.ForeignKey(Company)
    applied_date = models.DateField(null=True)
    isDeleted = models.BooleanField(default=False, blank=True)
    user = models.ForeignKey(User)
    def __str__(self):
        return self.position

class Questions(models.Model):
    question = models.CharField(max_length=255)
    category = models.CharField(max_length=25)
    isDeleted = models.BooleanField(default=False, blank=True)

class Ask(models.Model): #joining table
    question = models.ForeignKey(Questions)
    app = models.ForeignKey(Application)
    isDeleted = models.BooleanField(default=False, blank=True)

So the idea is that the user creates a list of questions and then when they get an interview, they prepare for it by looking at their list of questions and assigning them to the application through a template. Questions.html:

{% extends 'base.html' %}

{% block body %}

 Questions

                 Category
                 Question
                  Create Question
                <form method="POST">
                    {% csrf_token %}
                    <input type="text" name="app" value="{{ request.META.HTTP_REFERER }}">
                <input type='submit' value='Add Selected'>

            {% for item in query %}

                 {{ item.category }}
                 {{ item.question }}
                 <input type="checkbox" name="selected_q" value="{{ item.id }}">
                  Delete
                  Edit

            </form>
            {% endfor %}

{% endblock %}

Which is called from views.py:

class QuestionView(TemplateView):
    template_name = 'question.html'

    def get(self, request):
        query = Questions.objects.all().order_by('category')
        args = {'query': query}
        return render(request, self.template_name, args)

    def post(self, request):
        id_list = request.POST.getlist('selected_q')
        return_url = request.POST.get('app')
        app = int(return_url.rsplit('/')[-1])
        myApp = Application.objects.get(pk=app)
        if id_list != None:
            for item in id_list:
                myQuestion = Questions.objects.get(pk=int(item))
                Ask.objects.create(app=myApp,question=myQuestion)
            return HttpResponseRedirect(return_url)
        else:
            query = Questions.objects.all().order_by('category')
            args = {'query': query}
            return render(request, self.template_name, args)

The user can only get to the questions page by going through the Application view and when that happens Questions.html captures the link that the user came from.  Users then select one or more questions through a checkbox on questions.html which is captured in the post as id_list - So this should give me the two keys I need to create an instance of Ask.

However, when trying to do this it looks like everything works properly, but no instance of Ask is created and I don't get any error messages.  I have tried creating a record from the python shell and it works just fine. I have also tried other methods such as using a form and instantiating Ask to call .save() afterwards, but it does not insert a record. For testing, I took out the query in views.py to check to make sure valid values are getting passed to myApp and myQuestion, so I believe that the data is all there and accurate, but it isn't creating a record for some reason.

I appreciate any help you might offer, or maybe just different ideas on how to debug this problem so I can get some error messages.


问:
Regexp exec not work in Edge
I have a regexp, it works fine in Chrome/Firefox, but get null in Edge.

var regexp = new RegExp("<header.*(?=)(.|\n)*?", "g");
var str = "
Title
footer";

var result = regexp.exec(str);
console.log(result[0]);```

JSFiddle demo:
https://jsfiddle.net/JSDavi/k391qs72/2/

Please open it in different browsers. It's weird in Edge.

答:
This regex works in all browsers.

var regexp = new RegExp("]*\>((.|\n)*?)\", "g");
var str = "
Title
footer";

var result = regexp.exec(str);
console.log(result[1]);```

Title: Regexp exec not work in Edge

Body:
I have a regexp, it works fine in Chrome/Firefox, but get null in Edge.

var regexp = new RegExp("<header.*(?=)(.|\n)*?", "g");
var str = "
Title
footer";

var result = regexp.exec(str);
console.log(result[0]);

JSFiddle demo:
https://jsfiddle.net/JSDavi/k391qs72/2/

Please open it in different browsers. It's weird in Edge.

Body:
This regex works in all browsers.

var regexp = new RegExp("<header[^\>]*\>((.|\n)*?)\</header\>", "g");
var str = "<body><header><h2>Title</h2></header><footer>footer</footer></body>";

var result = regexp.exec(str);
console.log(result[1]);


问:
How can I detect if Microsoft Edge is installed?
I'm writing a windows form application (c#) and I need to detect whether the user have "Microsoft-Edge" installed in his/her machine or not.

I'm currently using this registry location:

```<code>[HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\Microsoft.MicrosoftEdge_20.10240.16384.0_neutral__8wekyb3d8bbwe]
"Path"="C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe"
</code>```

With a regex after the "Microsoft.MicrosoftEdge". If the "path" exist then I know edge is installed.

Is there a better way to detect edge? would it be better if I detect that I'm running on Windows 10 and by default Win10 come with edge? What is the best way for that?

答:
In reference to other answers: my installation of Windows 10 does not have this key:  Microsoft.MicrosoftEdge_20.10240.16384.0_neutral__8wekyb3d8bbwe

In:

```<code>[HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\]
</code>```

Instead, it has the following keys:

```<code>Microsoft.MicrosoftEdge_38.14393.0.0_neutral__8wekyb3d8bbwe
Microsoft.MicrosoftEdge_40.15063.674.0_neutral__8wekyb3d8bbwe
</code>```

The following code could be used to detect if Edge is installed:

```<code>class Program
{
    static void Main(string[] args)
    {
        var edgeFound = false;
        using (var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\"))
        {
            if (key != null)
            {
                foreach (var subkey in key.GetSubKeyNames())
                {
                    if (subkey.StartsWith("Microsoft.MicrosoftEdge_"))
                    {
                        edgeFound = true;
                        break;
                    }
                }
            }
        }
        Console.Write(edgeFound);
        Console.ReadLine();
    }
}
</code>```

Body:
I'm writing a windows form application (c#) and I need to detect whether the user have "Microsoft-Edge" installed in his/her machine or not.

I'm currently using this registry location:

[HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\Microsoft.MicrosoftEdge_20.10240.16384.0_neutral__8wekyb3d8bbwe]
"Path"="C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe"

With a regex after the "Microsoft.MicrosoftEdge". If the "path" exist then I know edge is installed.

Is there a better way to detect edge? would it be better if I detect that I'm running on Windows 10 and by default Win10 come with edge? What is the best way for that?

Body:
In reference to other answers: my installation of Windows 10 does not have this key:  Microsoft.MicrosoftEdge_20.10240.16384.0_neutral__8wekyb3d8bbwe

In:

[HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\]

Instead, it has the following keys:

Microsoft.MicrosoftEdge_38.14393.0.0_neutral__8wekyb3d8bbwe
Microsoft.MicrosoftEdge_40.15063.674.0_neutral__8wekyb3d8bbwe

The following code could be used to detect if Edge is installed:

class Program
{
    static void Main(string[] args)
    {
        var edgeFound = false;
        using (var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\"))
        {
            if (key != null)
            {
                foreach (var subkey in key.GetSubKeyNames())
                {
                    if (subkey.StartsWith("Microsoft.MicrosoftEdge_"))
                    {
                        edgeFound = true;
                        break;
                    }
                }
            }
        }
        Console.Write(edgeFound);
        Console.ReadLine();
    }
}