问:
removeClass in timeout not working
I SOLVED THE PROBLEM

I added a timeout function on the next line where I empty the array.

I am new a javascript and this is my code

The array is an array with spans.

```<code>            pickedArray[0].removeClass('show');
            pickedArray[1].removeClass('show');
</code>```

and this works but too fast.

However when I do like this

```<code>        setTimeout(function(){
            pickedArray[0].removeClass('show');
            pickedArray[1].removeClass('show');

        }, 100);
</code>```

I get an error "Cannot read property 'removeClass' of undefined"

How Can I correct this?

Thanks

Here is my code, I know it's messy but I just want it to work.

```<code>var activeCards = 0;
var firstPick = 0;
var secondPick = 0;
var pickedArray = [];

$('.card').click(function() {
    console.log('I was clicked.' + ' ' + activeCards);
    activeCards++;
    var span = $(this).find('span');
    pickedArray.push(span);
    console.log(span.text())
    span.addClass('show')
    if (activeCards == 1) {
        firstPick = span.text();
    } else {
        secondPick = span.text();
        activeCards = 0;
        if (firstPick == secondPick) {
            console.log(firstPick + " " + secondPick)
            setTimeout(function() {
                alert("You got a match");
            }, 100);
            pickedArray[0].parent().addClass('matched');
            pickedArray[1].parent().addClass('matched');

        } else {

            setTimeout(function() {
                  pickedArray[0].removeClass('show');
                  pickedArray[1].removeClass('show');;

            }, 100);

        }
        pickedArray = []
    }
});
</code>```

答:
Immediately after calling setTimeout you say:

```<code>pickedArray = []
</code>```

which overwrites it with an empty array.

100ms later, pickedArray[0] is therefore undefined.

You could pass the array to your function as an argument:

```<code>setTimeout(function(myArray) {
      myArray[0].removeClass('show');
      myArray[1].removeClass('show');;

}.bind(null, pickedArray), 100);
</code>```

Title: removeClass in timeout not working

Body:
I SOLVED THE PROBLEM

I added a timeout function on the next line where I empty the array.

I am new a javascript and this is my code

The array is an array with spans.

            pickedArray[0].removeClass('show');
            pickedArray[1].removeClass('show');

and this works but too fast.

However when I do like this

        setTimeout(function(){
            pickedArray[0].removeClass('show');
            pickedArray[1].removeClass('show');

        }, 100);

I get an error "Cannot read property 'removeClass' of undefined"

How Can I correct this?

Thanks

Here is my code, I know it's messy but I just want it to work.

var activeCards = 0;
var firstPick = 0;
var secondPick = 0;
var pickedArray = [];

$('.card').click(function() {
    console.log('I was clicked.' + ' ' + activeCards);
    activeCards++;
    var span = $(this).find('span');
    pickedArray.push(span);
    console.log(span.text())
    span.addClass('show')
    if (activeCards == 1) {
        firstPick = span.text();
    } else {
        secondPick = span.text();
        activeCards = 0;
        if (firstPick == secondPick) {
            console.log(firstPick + " " + secondPick)
            setTimeout(function() {
                alert("You got a match");
            }, 100);
            pickedArray[0].parent().addClass('matched');
            pickedArray[1].parent().addClass('matched');

        } else {

            setTimeout(function() {
                  pickedArray[0].removeClass('show');
                  pickedArray[1].removeClass('show');;

            }, 100);

        }
        pickedArray = []
    }
});

Body:
Immediately after calling setTimeout you say:

pickedArray = []

which overwrites it with an empty array.

100ms later, pickedArray[0] is therefore undefined.

You could pass the array to your function as an argument:

setTimeout(function(myArray) {
      myArray[0].removeClass('show');
      myArray[1].removeClass('show');;

}.bind(null, pickedArray), 100);


来源: stackexchange

问:
Umbraco: Get value from a content child property
I'm creating a blog with the CMS Umbraco. To create a post i've in Umbraco's Content a Home where you have a Post as a child item.

When you create this Post you have a dropdown-picker for categories, I want to get the values from this categories dropdown-picker to my sidebar to display all categories avaliable on the blog.

I want my dropdownpickers-value on my sidebar. What's the easiest approach?
Thanks.

答:
I think this is what you are looking for:

UmbracoHelper - GetPreValues

Regards

Craig

ContentLicense: CC BY-SA 3.0


问:
Qt: TableWidget's ItemAt() acting weirdly
i'm working on a windows application, where in a dialog i query some data from Postgres, and manually show the output in a table widget.

```<code>m_ui->tableWidget->setRowCount(joinedData.count());
for(int i=0; i<joinedData.count(); i++) //for each row
{
        m_ui->tableWidget->setItem(i, 0, new QTableWidgetItem(joinedData[i].bobin.referenceNumber));
        m_ui->tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(joinedData[i].bobin.width)));
        m_ui->tableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getHole())));
        m_ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getLessThanZeroFive())));                      m_ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroFive_to_zeroSeven())));
        m_ui->tableWidget->setItem(i, 5, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroFive_to_zeroSeven_repetitive())));
        m_ui->tableWidget->setItem(i, 6, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroSeven_to_Three())));
        m_ui->tableWidget->setItem(i, 7, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getThree_to_five())));
        m_ui->tableWidget->setItem(i, 8, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getMoreThanFive())));
 }
</code>```

Also, based on row and column information, i paint some of these tablewidgetitems to some colors, but i don't think it's relevant.

I reimplemented the QDialog's contextMenuEvent, to obtain the right clicked tableWidgetItem's row and column coordinates:

```<code>void BobinFlanView::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(m_ui->tableWidget);
    //standard actions
    menu.addAction(this->markInactiveAction);
    menu.addAction(this->markActiveAction);
    menu.addSeparator();
    menu.addAction(this->exportAction);
    menu.addAction(this->exportAllAction);

    //obtain the rightClickedItem
    QTableWidgetItem* clickedItem = m_ui->tableWidget->itemAt(m_ui->tableWidget->mapFromGlobal(event->globalPos()));

    // if it's a colored one, add some more actions
    if (clickedItem && clickedItem->column()>1 && clickedItem->row()>0)
    {
        //this is a property, i'm keeping this for a later use
        this->lastRightClickedItem = clickedItem;
        //debug purpose:
        QMessageBox::information(this, "", QString("clickedItem = %1, %2").arg(clickedItem->row()).arg(clickedItem->column()));
        QMessageBox::information(this, "", QString("globalClick = %1, %2\ntransformedPos = %3, %4").arg(event->globalX()).arg(event->globalY())
                                 .arg(m_ui->tableWidget->mapFromGlobal(event->globalPos()).x()).arg(m_ui->tableWidget->mapFromGlobal(event->globalPos()).y()));

        menu.addSeparator();

        menu.addAction(this->changeSelectedToleranceToUygun);
        menu.addAction(this->changeSelectedToleranceToUyar);
        menu.addAction(this->changeSelectedToleranceToDurdurUyar);

        //... some other irrevelant 'enable/disable' activities

    menu.exec(event->globalPos());
}
</code>```

The problem is, when i right click on the same item i get the same global coordinates, but randomly different row-column information. For instance, the global pos is exactly 600,230 but row-column pair is randomly (5,3) and (4,3). I mean, what?!

Also, when i click to an item from the last to rows (later than 13, i guess) will never go into condition "if (clickedItem && clickedItem->column()>1 && clickedItem->row()>0)", i think it's mainly because 'clickedItem' is null.

I'll be more than glad to share any more information, or even the full cpp-h-ui trio in order to get help.

Thanks a lot.

答:
Came here to thank Lukáš Lalinský, as his explanation put an end to half a day of misery for me.

In my case, itemAt() when fed with QDropEvent::pos(), was returning items from a table row, offset by 1.

The reason was that I had a horizontal header, which shrunk the viewport, same with the vertical header, but since it was very narrow, I did not realize it caused an offset too.
The fix was to call QTableWidget's viewport()->mapFromParent( [drop pos] ), as the position was in QTableWidget coordinates already.

Again, thanks A LOT!

ContentLicense: CC BY-SA 2.5

Body:
i'm working on a windows application, where in a dialog i query some data from Postgres, and manually show the output in a table widget.

m_ui->tableWidget->setRowCount(joinedData.count());
for(int i=0; i<joinedData.count(); i++) //for each row
{
        m_ui->tableWidget->setItem(i, 0, new QTableWidgetItem(joinedData[i].bobin.referenceNumber));
        m_ui->tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(joinedData[i].bobin.width)));
        m_ui->tableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getHole())));
        m_ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getLessThanZeroFive())));                      m_ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroFive_to_zeroSeven())));
        m_ui->tableWidget->setItem(i, 5, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroFive_to_zeroSeven_repetitive())));
        m_ui->tableWidget->setItem(i, 6, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroSeven_to_Three())));
        m_ui->tableWidget->setItem(i, 7, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getThree_to_five())));
        m_ui->tableWidget->setItem(i, 8, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getMoreThanFive())));
 }

Also, based on row and column information, i paint some of these tablewidgetitems to some colors, but i don't think it's relevant.

I reimplemented the QDialog's contextMenuEvent, to obtain the right clicked tableWidgetItem's row and column coordinates:

void BobinFlanView::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(m_ui->tableWidget);
    //standard actions
    menu.addAction(this->markInactiveAction);
    menu.addAction(this->markActiveAction);
    menu.addSeparator();
    menu.addAction(this->exportAction);
    menu.addAction(this->exportAllAction);

    //obtain the rightClickedItem
    QTableWidgetItem* clickedItem = m_ui->tableWidget->itemAt(m_ui->tableWidget->mapFromGlobal(event->globalPos()));

    // if it's a colored one, add some more actions
    if (clickedItem && clickedItem->column()>1 && clickedItem->row()>0)
    {
        //this is a property, i'm keeping this for a later use
        this->lastRightClickedItem = clickedItem;
        //debug purpose:
        QMessageBox::information(this, "", QString("clickedItem = %1, %2").arg(clickedItem->row()).arg(clickedItem->column()));
        QMessageBox::information(this, "", QString("globalClick = %1, %2\ntransformedPos = %3, %4").arg(event->globalX()).arg(event->globalY())
                                 .arg(m_ui->tableWidget->mapFromGlobal(event->globalPos()).x()).arg(m_ui->tableWidget->mapFromGlobal(event->globalPos()).y()));

        menu.addSeparator();

        menu.addAction(this->changeSelectedToleranceToUygun);
        menu.addAction(this->changeSelectedToleranceToUyar);
        menu.addAction(this->changeSelectedToleranceToDurdurUyar);

        //... some other irrevelant 'enable/disable' activities

    menu.exec(event->globalPos());
}

The problem is, when i right click on the same item i get the same global coordinates, but randomly different row-column information. For instance, the global pos is exactly 600,230 but row-column pair is randomly (5,3) and (4,3). I mean, what?!

Also, when i click to an item from the last to rows (later than 13, i guess) will never go into condition "if (clickedItem && clickedItem->column()>1 && clickedItem->row()>0)", i think it's mainly because 'clickedItem' is null.

I'll be more than glad to share any more information, or even the full cpp-h-ui trio in order to get help.

Thanks a lot.


问:
Android Developing - Slow Internet Connection via 3G
I'm developing a Client/Server Application with Android/Rails and Communication via REST Json

When I'm testing my App via Emulator, all works fine.
Also when I deploy the app on my phone with WIFI on it works and the speed is ok.

But when I disconnect from WIFI and use the 3G connection, the phone becomes incredible Slow and it takes Minutes du get one JSON Response from the Server.

I'ved debug a little bit and the Problem seems to be the HTTPClient, which execute Method takes ulta long.

Other Apps with Network Access are working perfectly.

Any suggestions what to do?

```<code>HTC Magic
Android 1.6
</code>```

My Http Connection Code:

```<code>HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("URL");
        try {
            client.execute(get);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

答: Move to an area with better mobile data coverage?</p>

Body:
I'm developing a Client/Server Application with Android/Rails and Communication via REST Json

When I'm testing my App via Emulator, all works fine.
Also when I deploy the app on my phone with WIFI on it works and the speed is ok.

But when I disconnect from WIFI and use the 3G connection, the phone becomes incredible Slow and it takes Minutes du get one JSON Response from the Server.

I'ved debug a little bit and the Problem seems to be the HTTPClient, which execute Method takes ulta long.

Other Apps with Network Access are working perfectly.

Any suggestions what to do?

HTC Magic
Android 1.6

My Http Connection Code:

HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("URL");
        try {
            client.execute(get);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


问:
Mailboxer: recipient inbox not showing conversations
On the product listing page of my marketplace, i've create a button the send a message to the user of each product, with the link_to:

```<code><%= link_to "Contact", new_conversation_path(recipient_id: product.user.id) %>
</code>```

Here is my converations_controller:

```<code>class ConversationsController < ApplicationController
before_action :authenticate_user!

def index
@conversations = current_user.mailbox.conversations
end

def show
@conversation = current_user.mailbox.conversations.find(params[:id])
end

def new

@recipient = User.find(params[:recipient_id])
end

def create
recipient = User.find(params[:recipient_id]).id
receipt = current_user.send_message(@recipient, params[:body], params[:subject])
redirect_to conversation_path(receipt.conversation)
end

end
</code>```

My new conversation page:

```<code><h1>New conversation</h1>

<%= form_tag conversations_path, method: :post do %>
<div>

</div>

<div>
<%= text_field_tag :subject, nil, placeholder: "Subject" %>
</div>

<div>
<%= text_area_tag :body, nil, placeholder: "Your message" %>
</div>

<%= submit_tag "Send",:class=>"btn btn-warning" %>

<% end %>
</code>```

When i click on the link to send a message i am correctly redirect to the "conversation new" page, wich has on its url:

```<code>/conversations/new?recipient_id=7
</code>```

With the id of the correct user id, but when i send the message,

i have the following error:

could'n find user with 'id'=

答:
I make it working finally, here is my code, maybe it can help other:

(i'm on rails 5)

The link on my product page:

```<code><%= link_to "Contactar", new_conversation_path(recipient_id: service.user.id) %>
</code>```

My new and create action on my conversation controller:

```<code> def new
 @recipients = User.find(params[:recipient_id])

 end

 def create
 recipient = User.find_by(id: params[:recipient_id])
 receipt = current_user.send_message(recipient, params[:body],    params[:subject])
 redirect_to conversation_path(receipt.conversation)
 end
</code>```

On the new conversation:

```<code><%= hidden_field_tag(:recipient_id, "#{@recipients.id}") %>
</code>```

Body:
On the product listing page of my marketplace, i've create a button the send a message to the user of each product, with the link_to:

<%= link_to "Contact", new_conversation_path(recipient_id: product.user.id) %>

Here is my converations_controller:

class ConversationsController < ApplicationController
before_action :authenticate_user!

def index
@conversations = current_user.mailbox.conversations
end

def show
@conversation = current_user.mailbox.conversations.find(params[:id])
end

def new

@recipient = User.find(params[:recipient_id])
end

def create
recipient = User.find(params[:recipient_id]).id
receipt = current_user.send_message(@recipient, params[:body], params[:subject])
redirect_to conversation_path(receipt.conversation)
end

end

My new conversation page:

New conversation

<%= form_tag conversations_path, method: :post do %>

<%= text_field_tag :subject, nil, placeholder: "Subject" %>

<%= text_area_tag :body, nil, placeholder: "Your message" %>

<%= submit_tag "Send",:class=>"btn btn-warning" %>

<% end %>

When i click on the link to send a message i am correctly redirect to the "conversation new" page, wich has on its url:

/conversations/new?recipient_id=7

With the id of the correct user id, but when i send the message,

i have the following error:

could'n find user with 'id'=

Body:
I make it working finally, here is my code, maybe it can help other:

(i'm on rails 5)

The link on my product page:

<%= link_to "Contactar", new_conversation_path(recipient_id: service.user.id) %>

My new and create action on my conversation controller:

 def new
 @recipients = User.find(params[:recipient_id])

 end

 def create
 recipient = User.find_by(id: params[:recipient_id])
 receipt = current_user.send_message(recipient, params[:body],    params[:subject])
 redirect_to conversation_path(receipt.conversation)
 end

On the new conversation:

<%= hidden_field_tag(:recipient_id, "#{@recipients.id}") %>


问:
Split string with literal \n in a for loop
Please consider this string: foo\nbar\nbaz

How can I split it using \n as delimiter?

I have played with IFS without luck.

EDIT: I want to split it inside a for loop.

Ok, I'll explain what my situation is.

I need to feed a certain config file using data stored in a MySQL database.

I get the value from a TEXT type column. Each record in this column could be empty or multiple email address (foo@bar.tld), domain names (bar.tld), or placeholders for domain names including its subdomains (.bar.tld).

By design, the programmer decided this field should be multiline, hence the separator.

My job is to get those values individualy and proccess them. So I iterate over the values and do some things to them.

The REAL problem IS I'm getting a two bytes separator char just like this:

foo@bar.tld\nfoo.tld\n.foo.tld
So I can't access each element individually.

I hope you can understand now (English is not my native language).

EDIT2:

Right now I'm solving the issue with this code:

```<code>PERMITTED_SENDERS="foo@bar.tld\nfoo.tld\n.foo.tld"

for SENDER in ${PERMITTED_SENDERS//'\n'/ }
do
    if [[ "$SENDER" =~ @ ]]
    then
        printf "\tsender == $SENDER\n"
    elif [[ "$SENDER" =~ ^\. ]]
    then
        printf "\tsender =~ [@|.]$(to_tld_domain $SENDER)\$\n"
    else
        printf "\tsender =~ \@$(to_regex $SENDER)\$\n"
    fi
done
</code>```

@CharlesDuffy is the for loop still bad to solve this?

EDIT3

After reading mysql help thoroughly I ended passing -r to mysql command to get the results in raw format.

Now I have this:

```<code>while IFS='' read -r permitted_sender
do
    # Do stuff
done <<<"$permitted_senders"
</code>```

答:
A for loop is the wrong tool for this job. Consider a while loop instead:

```<code>str='foo\nbar\nbaz'

while [[ $str ]]; do            # iterate as long as we have input
  if [[ $str = *'\n'* ]]; then  # if there's a '\n' sequence later...
    first=${str%%'\n'*}         #   put everything before it into 'first'
    rest=${str#*'\n'}           #   and put everything after it in 'rest'
  else                          # if there's no '\n' later...
    first=$str                  #   then put the whole rest of the string in 'first'
    rest=''                     #   and there is no 'rest'
  fi
  echo "Processing piece: $first"
  str=$rest
done
</code>```

This properly emits:

Processing piece: foo
Processing piece: bar
Processing piece: baz
```

<hr>

<p>That said, if you <em>must</em> use a <code>for</code> loop:</p>

```str='foo\nbar\nbaz'
set -f                                        # disable globbing
printf -v str_literal '%b' "$str"             # replace '\n' with a literal newline
IFS=$'\n' read -r -a pieces <<<"$str_literal" # split on literal newlines
for piece in "${pieces[@]}"; do               # iterate over the pieces
  echo "Processing piece: $piece"
done
```

Note that this is not without side effects -- it will replace \t sequences with literal tabs, for instance. I'm assuming that that's what you actually want, since your data store is using \n to refer to newlines.

Body:
Please consider this string: foo\nbar\nbaz

How can I split it using \n as delimiter?

I have played with IFS without luck.

EDIT: I want to split it inside a for loop.

Ok, I'll explain what my situation is.

I need to feed a certain config file using data stored in a MySQL database.

I get the value from a TEXT type column. Each record in this column could be empty or multiple email address (foo@bar.tld), domain names (bar.tld), or placeholders for domain names including its subdomains (.bar.tld).

By design, the programmer decided this field should be multiline, hence the separator.

My job is to get those values individualy and proccess them. So I iterate over the values and do some things to them.

The REAL problem IS I'm getting a two bytes separator char just like this:

foo@bar.tld\nfoo.tld\n.foo.tld
So I can't access each element individually.

I hope you can understand now (English is not my native language).

EDIT2:

Right now I'm solving the issue with this code:

PERMITTED_SENDERS="foo@bar.tld\nfoo.tld\n.foo.tld"

for SENDER in ${PERMITTED_SENDERS//'\n'/ }
do
    if [[ "$SENDER" =~ @ ]]
    then
        printf "\tsender == $SENDER\n"
    elif [[ "$SENDER" =~ ^\. ]]
    then
        printf "\tsender =~ [@|.]$(to_tld_domain $SENDER)\$\n"
    else
        printf "\tsender =~ \@$(to_regex $SENDER)\$\n"
    fi
done

@CharlesDuffy is the for loop still bad to solve this?

EDIT3

After reading mysql help thoroughly I ended passing -r to mysql command to get the results in raw format.

Now I have this:

while IFS='' read -r permitted_sender
do
    # Do stuff
done <<<"$permitted_senders"

Body:
A for loop is the wrong tool for this job. Consider a while loop instead:

str='foo\nbar\nbaz'

while [[ $str ]]; do            # iterate as long as we have input
  if [[ $str = *'\n'* ]]; then  # if there's a '\n' sequence later...
    first=${str%%'\n'*}         #   put everything before it into 'first'
    rest=${str#*'\n'}           #   and put everything after it in 'rest'
  else                          # if there's no '\n' later...
    first=$str                  #   then put the whole rest of the string in 'first'
    rest=''                     #   and there is no 'rest'
  fi
  echo "Processing piece: $first"
  str=$rest
done

This properly emits:

Processing piece: foo
Processing piece: bar
Processing piece: baz

That said, if you must use a for loop:

str='foo\nbar\nbaz'
set -f                                        # disable globbing
printf -v str_literal '%b' "$str"             # replace '\n' with a literal newline
IFS=$'\n' read -r -a pieces <<<"$str_literal" # split on literal newlines
for piece in "${pieces[@]}"; do               # iterate over the pieces
  echo "Processing piece: $piece"
done

Note that this is not without side effects -- it will replace \t sequences with literal tabs, for instance. I'm assuming that that's what you actually want, since your data store is using \n to refer to newlines.


问:
Why url rewriting not working?
I want to change my url from

http://localhost/delhian/destinations_list.php?ref=monuments_in_delhi

to

http://localhost/delhian/destinations_list/monuments_in_delhi

I have written the following htaccess rules.

```<code>RewriteEngine on
RewriteRule ^destinations_list/([A-Za-z_]+)/?$      destinations_list.php?ref=$1
</code>```

I don't know what I'm doing wrong here but this isn't working.

When I'm accessing the URL

http://localhost/delhian/destinations_list/monuments_in_delhi

It is showing me Undefined index ref.

Can anyone tell me what I'm missing here, why it is not working and what is the meaning of this message Undefined index ref?

答:
Add that, at the top of your htaccess, to disable MultiViews:

```<code>Options -MultiViews
</code>```

The Apache docs on mod_negotiation, describes what the Multiviews Option does, when enabled:

If the
  server receives a request for /some/dir/foo and /some/dir/foo does not
  exist, then the server reads the directory looking for all files named
  foo.*, and effectively fakes up a type map which names all those
  files, assigning them the same media types and content-encodings it
  would have if the client had asked for one of them by name. It then
  chooses the best match to the client's requirements, and returns that
  document.

Title: Why url rewriting not working?

Body:
I want to change my url from

http://localhost/delhian/destinations_list.php?ref=monuments_in_delhi

to

http://localhost/delhian/destinations_list/monuments_in_delhi

I have written the following htaccess rules.

RewriteEngine on
RewriteRule ^destinations_list/([A-Za-z_]+)/?$      destinations_list.php?ref=$1

I don't know what I'm doing wrong here but this isn't working.

When I'm accessing the URL

http://localhost/delhian/destinations_list/monuments_in_delhi

It is showing me Undefined index ref.

Can anyone tell me what I'm missing here, why it is not working and what is the meaning of this message Undefined index ref?

Body:
Add that, at the top of your htaccess, to disable MultiViews:

Options -MultiViews

The Apache docs on mod_negotiation, describes what the Multiviews Option does, when enabled:

If the
  server receives a request for /some/dir/foo and /some/dir/foo does not
  exist, then the server reads the directory looking for all files named
  foo.*, and effectively fakes up a type map which names all those
  files, assigning them the same media types and content-encodings it
  would have if the client had asked for one of them by name. It then
  chooses the best match to the client's requirements, and returns that
  document.


问:
Why is this calling of a parent method not working? State not updating
Trying to call a parent method from a component, to update the state, and it doesn't seem to be updating the state. The function is being called as the console log is running, but the state isn't updating.

I'm trying to run the showFirstFive() function, found on the <CustomerTable /> component, from within its child component - <CustomerEntry /> (passed as a prop).

The buttons at the top change the state fine, but the buttons in the table (in the child components) do not.

Any help would be hugely appreciated!

codepen here

```<code>class CustomerEntry extends React.Component {
    modifyState(e) {
        e.preventDefault();
        console.log("test");
        this.props.changeState;
    }

    render() {
        return (
            <tr>
                <td>{this.props.name}</td>
                <td>{this.props.email}</td>
                <td>{this.props.postcode}</td>
                <td>
                    {this.props.product}
                    <button onClick={this.modifyState.bind(this)}>Show first 5 items</button>
                </td>
            </tr>
        );
    }
}

class CustomerTable extends React.Component {
    constructor(props) {
        super(props);
        let customers = this.props.customers;
        this.state = {
            customers
        };
    }

    showFirstFive() {
        let customers = this.props.customers;
        customers = customers.slice(0, 5);
        this.setState({ customers });
    }
    showAll() {
        let customers = this.props.customers;
        this.setState({ customers });
    }

    render() {
        console.log("this.props.customers", this.props.customers);
        let customerList;

        let thisComp = this;

        if (this.props.customers) {
            customerList = this.state.customers.map(function(customerData) {
                return (
                    <CustomerEntry
                        key={customerData.key}
                        changeState={thisComp.showFirstFive.bind(this)}
                        index={customerData.key}
                        name={customerData.name}
                        email={customerData.email}
                        postcode={customerData.postcode}
                        product={customerData.product}
                    />
                );
            });
        }

        return (
            <div>
                <button onClick={this.showFirstFive.bind(this)} >Show first 5 items</button>
                <button onClick={this.showAll.bind(this)} >Show all</button>
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Postcode</th>
                            <th>Product</th>
                        </tr>
                    </thead>
                    <tbody>
                        {customerList}
                    </tbody>
                </table>
            </div>
        );
    }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            customers: [
                {
                    key: "86464",
                    name: "Mr John Smith",
                    email: "test@test.com",
                    postcode: "LN47AT",
                    product: "apples",
                },
                {
                    key: "787862",
                    name: "Miss Sarah Jackson",
                    email: "sarah@hello.com",
                    postcode: "DN54LQ",
                    product: "apples",
                },
                {
                    key: "4454564",
                    name: "Dr Hugh James",
                    email: "hugh@test.com",
                    postcode: "S102AT",
                    product: "bananans",
                },              {
                    key: "11123134",
                    name: "Mr John Smith",
                    email: "test@test.com",
                    postcode: "LN47AT",
                    product: "apples",
                },
                {
                    key: "68868",
                    name: "Miss Sarah Jackson",
                    email: "sarah@hello.com",
                    postcode: "DN54LQ",
                    product: "apples",
                },
                {
                    key: "6876871",
                    name: "Dr Hugh James",
                    email: "hugh@test.com",
                    postcode: "S102AT",
                    product: "bananans",
                },
                                {
                    key: "17117",
                    name: "Mr John Smith",
                    email: "test@test.com",
                    postcode: "LN47AT",
                    product: "apples",
                },
                {
                    key: "17171716",
                    name: "Miss Sarah Jackson",
                    email: "sarah@hello.com",
                    postcode: "DN54LQ",
                    product: "apples",
                },
                {
                    key: "151571",
                    name: "Dr Hugh James",
                    email: "hugh@test.com",
                    postcode: "S102AT",
                    product: "bananans",
                },

            ]
        };
    }

    render() {
        return (
            <div>
                <CustomerTable customers={this.state.customers} />
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById("app"));
</code>```

答:
You need to call that method, missed ():

```<code>modifyState(e) {
    e.preventDefault();
    console.log("test");
    this.props.changeState();    //here
}
</code>```

Suggestion:

1. Instead of binding the methods by:

```<code>onClick = {this.showFirstFive.bind(this)}
</code>```

Define it in the constructor:

```<code>this.showFirstFive = this.showFirstFive.bind(this);
</code>```

Then use it like this: onClick = {this.showFirstFive}

2. Storing the reference of this keyword in a separate variable is not required, you are use arrow function like this:

```<code>customerList = this.state.customers.map((customerData) => {
      //now you can access this
}
</code>```

Body:
Trying to call a parent method from a component, to update the state, and it doesn't seem to be updating the state. The function is being called as the console log is running, but the state isn't updating.

I'm trying to run the showFirstFive() function, found on the <CustomerTable /> component, from within its child component - <CustomerEntry /> (passed as a prop).

The buttons at the top change the state fine, but the buttons in the table (in the child components) do not.

Any help would be hugely appreciated!

codepen here

class CustomerEntry extends React.Component {
    modifyState(e) {
        e.preventDefault();
        console.log("test");
        this.props.changeState;
    }

    render() {
        return (

                {this.props.name}
                {this.props.email}
                {this.props.postcode}

                    {this.props.product}
                    <button onClick={this.modifyState.bind(this)}>Show first 5 items</button>

        );
    }
}

class CustomerTable extends React.Component {
    constructor(props) {
        super(props);
        let customers = this.props.customers;
        this.state = {
            customers
        };
    }

    showFirstFive() {
        let customers = this.props.customers;
        customers = customers.slice(0, 5);
        this.setState({ customers });
    }
    showAll() {
        let customers = this.props.customers;
        this.setState({ customers });
    }

    render() {
        console.log("this.props.customers", this.props.customers);
        let customerList;

        let thisComp = this;

        if (this.props.customers) {
            customerList = this.state.customers.map(function(customerData) {
                return (
                    <CustomerEntry
                        key={customerData.key}
                        changeState={thisComp.showFirstFive.bind(this)}
                        index={customerData.key}
                        name={customerData.name}
                        email={customerData.email}
                        postcode={customerData.postcode}
                        product={customerData.product}
                    />
                );
            });
        }

        return (

                <button onClick={this.showFirstFive.bind(this)} >Show first 5 items</button>
                <button onClick={this.showAll.bind(this)} >Show all</button>

                            Name
                            Email
                            Postcode
                            Product

                        {customerList}

        );
    }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            customers: [
                {
                    key: "86464",
                    name: "Mr John Smith",
                    email: "test@test.com",
                    postcode: "LN47AT",
                    product: "apples",
                },
                {
                    key: "787862",
                    name: "Miss Sarah Jackson",
                    email: "sarah@hello.com",
                    postcode: "DN54LQ",
                    product: "apples",
                },
                {
                    key: "4454564",
                    name: "Dr Hugh James",
                    email: "hugh@test.com",
                    postcode: "S102AT",
                    product: "bananans",
                },              {
                    key: "11123134",
                    name: "Mr John Smith",
                    email: "test@test.com",
                    postcode: "LN47AT",
                    product: "apples",
                },
                {
                    key: "68868",
                    name: "Miss Sarah Jackson",
                    email: "sarah@hello.com",
                    postcode: "DN54LQ",
                    product: "apples",
                },
                {
                    key: "6876871",
                    name: "Dr Hugh James",
                    email: "hugh@test.com",
                    postcode: "S102AT",
                    product: "bananans",
                },
                                {
                    key: "17117",
                    name: "Mr John Smith",
                    email: "test@test.com",
                    postcode: "LN47AT",
                    product: "apples",
                },
                {
                    key: "17171716",
                    name: "Miss Sarah Jackson",
                    email: "sarah@hello.com",
                    postcode: "DN54LQ",
                    product: "apples",
                },
                {
                    key: "151571",
                    name: "Dr Hugh James",
                    email: "hugh@test.com",
                    postcode: "S102AT",
                    product: "bananans",
                },

            ]
        };
    }

    render() {
        return (

                <CustomerTable customers={this.state.customers} />

        );
    }
}

ReactDOM.render(<App />, document.getElementById("app"));

Body:
You need to call that method, missed ():

modifyState(e) {
    e.preventDefault();
    console.log("test");
    this.props.changeState();    //here
}

Suggestion:

1. Instead of binding the methods by:

onClick = {this.showFirstFive.bind(this)}

Define it in the constructor:

this.showFirstFive = this.showFirstFive.bind(this);

Then use it like this: onClick = {this.showFirstFive}

2. Storing the reference of this keyword in a separate variable is not required, you are use arrow function like this:

customerList = this.state.customers.map((customerData) => {
      //now you can access this
}


问:
Laravel Sentinel setModel accessing the wrong table
I am attempting to use multiple tables for my authentication based on a subdomain. Therefore, I am attempting to use Sentinel's setModel function during runtime to set the model instance.

So in my routes file I have some simple logic:

```<code>if (Request::getHost() == $url) {
    Sentinel::getUserRepository()->setModel('App\Client');
} else {
    Sentinel::getUserRepository()->setModel('App\User');
}
</code>```

The logic being one URL uses one model and the other uses the other model. Now, when I am attempting to load the App\Client by doing a dd(Sentinel::getUserRepository()); I get a return such as:

```<code>IlluminateUserRepository {#113 ▼
  #hasher: NativeHasher {#114}
  #model: "App\Client"
  #dispatcher: Dispatcher {#23 ▶}
  #dispatcherStatus: true
}
</code>```

This is great, however, when I call Sentinel::getUser();, I am left with the following output:

```<code>EloquentUser {#230 ▼
  #table: "users"
  #fillable: array:5 [▶]
  #hidden: array:1 [▶]
  #persistableKey: "user_id"
  #persistableRelationship: "persistences"
  #loginNames: array:1 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:12 [▶]
  #original: array:12 [▶]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
  #permissionsInstance: null
}
</code>```

This is referring to the App\User model rather than my App\Client model.

I don't understand why, but I can't seem to get functions of Sentinel to look at the model I am trying to reference.

Here is my Client model as a point of reference.

```<code>namespace App;

class Client extends \Cartalyst\Sentinel\Users\EloquentUser
{
    /**
     * The fields for sentinel to authenticate (login)
     *
     * @var array
     */
    protected $loginNames = ['email'];

    /**
    * The table associated with model.
    *
    * @var String
    */
    protected $table = 'clients';

    /**
    * Used for mass assignment fields.
    *
    * @var Array
    */
    protected $fillable = ['email', 'password', 'permissions', 'last_login', 'first_name', 'last_name'];
}
</code>```

I have used this guide from the Github Wiki, however as you can see Im not achieving what I am trying to do.

How can I use this approach of setting the model during runtime and use the correct model with all of sentinels commands?

答:
To anyone who encounters the same issue, i flagged this as an issue in the cartalyst/sentinel repository and some feedback was provided.

The solution is to not only set the user repository but also define the model on the persistence repository:

```<code>Sentinel::getUserRepository()->setUsersModel('App\Client');
Sentinel::getPersistenceRepository()->setUsersModel('App\Client');
</code>```

Through this methods such as Sentinel::getUser() will access the model specified above.

Please see the full response here: https://github.com/cartalyst/sentinel/issues/367

Body:
I am attempting to use multiple tables for my authentication based on a subdomain. Therefore, I am attempting to use Sentinel's setModel function during runtime to set the model instance.

So in my routes file I have some simple logic:

if (Request::getHost() == $url) {
    Sentinel::getUserRepository()->setModel('App\Client');
} else {
    Sentinel::getUserRepository()->setModel('App\User');
}

The logic being one URL uses one model and the other uses the other model. Now, when I am attempting to load the App\Client by doing a dd(Sentinel::getUserRepository()); I get a return such as:

IlluminateUserRepository {#113 ▼
  #hasher: NativeHasher {#114}
  #model: "App\Client"
  #dispatcher: Dispatcher {#23 ▶}
  #dispatcherStatus: true
}

This is great, however, when I call Sentinel::getUser();, I am left with the following output:

EloquentUser {#230 ▼
  #table: "users"
  #fillable: array:5 [▶]
  #hidden: array:1 [▶]
  #persistableKey: "user_id"
  #persistableRelationship: "persistences"
  #loginNames: array:1 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:12 [▶]
  #original: array:12 [▶]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
  #permissionsInstance: null
}

This is referring to the App\User model rather than my App\Client model.

I don't understand why, but I can't seem to get functions of Sentinel to look at the model I am trying to reference.

Here is my Client model as a point of reference.

namespace App;

class Client extends \Cartalyst\Sentinel\Users\EloquentUser
{
    /**
     * The fields for sentinel to authenticate (login)
     *
     * @var array
     */
    protected $loginNames = ['email'];

    /**
    * The table associated with model.
    *
    * @var String
    */
    protected $table = 'clients';

    /**
    * Used for mass assignment fields.
    *
    * @var Array
    */
    protected $fillable = ['email', 'password', 'permissions', 'last_login', 'first_name', 'last_name'];
}

I have used this guide from the Github Wiki, however as you can see Im not achieving what I am trying to do.

How can I use this approach of setting the model during runtime and use the correct model with all of sentinels commands?

Body:
To anyone who encounters the same issue, i flagged this as an issue in the cartalyst/sentinel repository and some feedback was provided.

The solution is to not only set the user repository but also define the model on the persistence repository:

Sentinel::getUserRepository()->setUsersModel('App\Client');
Sentinel::getPersistenceRepository()->setUsersModel('App\Client');

Through this methods such as Sentinel::getUser() will access the model specified above.

Please see the full response here: https://github.com/cartalyst/sentinel/issues/367


问:
Invoking powershell show-command from a batch script
I am trying to give helpdesk staff who are not familiar with Powershell the ability to run one-off Powershell functions by just executing a batch file. In the batch file I launch powershell with bypass executionpolicy, import and run the function. Additionally, I wanted to use Show-Command to give them a graphical UI that would make the parameters more obvious. This runs, but apparently any code that is invoked with the & operator runs in its own child scope. This means when the command with arguments is returned to the "parent" Powershell window, it will have lost knowledge of the function that was imported inside the child scope. Here's what I have in the batch file:

```<code>powershell.exe -noprofile -noexit -executionpolicy bypass -command "& {. \\server\share\New-DriveRemapScript.ps1;Show-Command New-DriveRemapScript}"
</code>```

The launched Powershell windows remains, but when I hit enter on the command text returned by Show-Command, I get "New-DriveRemapScript : The term 'New-DriveRemapScript' is not recognized ...."

答:
Try using -File - this is best if you want to launch a single powershell script.

```<code>powershell.exe -File "\\server\share\New-DriveRemapScript.ps1" -ExecutionPolicy Bypass
</code>```

then in New-DriveRemapScript.ps1 which probably just contains:

```<code>Function New-DriveRemapScript {
...
}
</code>```

at the end add in

Show-Command New-DriveRemapScript

this will ensure the command is loaded and then executed when the file is called.

Body:
I am trying to give helpdesk staff who are not familiar with Powershell the ability to run one-off Powershell functions by just executing a batch file. In the batch file I launch powershell with bypass executionpolicy, import and run the function. Additionally, I wanted to use Show-Command to give them a graphical UI that would make the parameters more obvious. This runs, but apparently any code that is invoked with the & operator runs in its own child scope. This means when the command with arguments is returned to the "parent" Powershell window, it will have lost knowledge of the function that was imported inside the child scope. Here's what I have in the batch file:

powershell.exe -noprofile -noexit -executionpolicy bypass -command "& {. \\server\share\New-DriveRemapScript.ps1;Show-Command New-DriveRemapScript}"

The launched Powershell windows remains, but when I hit enter on the command text returned by Show-Command, I get "New-DriveRemapScript : The term 'New-DriveRemapScript' is not recognized ...."

Body:
Try using -File - this is best if you want to launch a single powershell script.

powershell.exe -File "\\server\share\New-DriveRemapScript.ps1" -ExecutionPolicy Bypass

then in New-DriveRemapScript.ps1 which probably just contains:

Function New-DriveRemapScript {
...
}

at the end add in

Show-Command New-DriveRemapScript

this will ensure the command is loaded and then executed when the file is called.


问:
Continue to show angular default loading until angular2 router is resolved?
Angular2 cli provide default loading until it get bootstrapped <app-root>Loading...</app-root>.
Then angular2 route resolver initiate API call to check weather user is authenticated or not after that it goes to desired route.

But in between this process I can see blank screen.
Actually angular default Loading... is removed and resolver is taking some time to get resolved.

So is there anyway to continue showing angular default loading symbol until router is resolved.

答:
You can try below,

In your app-root component,

```<code>showSpinner = false;

constructor(private router: Router) {}

ngOnInit(){
   this.router.events
      .filter(e => {
        return (e instanceof NavigationStart)
          || (e instanceof NavigationEnd ||
            e instanceof NavigationCancel ||
            e instanceof NavigationError);
      })
      .map(e => (e instanceof NavigationStart))
      .distinctUntilChanged()
      .subscribe(showSpinner => {
        this.showSpinner = showSpinner;
      });
}
</code>```

In HTML, use showSpinner property to show some gif or animation, you may also use (not tested but should work) to show the Loading... message or what ever content you had initially,

```<code><ng-content *ngIf="showSpinner" ></ng-content>
</code>```

Hope this helps!!

Body:
You can try below,

In your app-root component,

showSpinner = false;

constructor(private router: Router) {}

ngOnInit(){
   this.router.events
      .filter(e => {
        return (e instanceof NavigationStart)
          || (e instanceof NavigationEnd ||
            e instanceof NavigationCancel ||
            e instanceof NavigationError);
      })
      .map(e => (e instanceof NavigationStart))
      .distinctUntilChanged()
      .subscribe(showSpinner => {
        this.showSpinner = showSpinner;
      });
}

In HTML, use showSpinner property to show some gif or animation, you may also use (not tested but should work) to show the Loading... message or what ever content you had initially,

<ng-content *ngIf="showSpinner" ></ng-content>

Hope this helps!!


问:
Exclude unnecessary node modules from war
I am creating a web application in which I using Maven, Spring, Hibernate, Angular. The size of war file if very large(151 MB) out of which 107 MB for node modules so please tell me how can I remove unnecessary node modules from war file to keep its size reasonable.
This is my npm dependencies : </p>

```<code>"dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.4",
    "angular2-datatable": "^0.6.0",
    "core-js": "^2.4.1",
    "lodash": "^4.17.4",
    "mydatepicker": "^1.6.1",
    "ng2-pdf-viewer": "^1.1.0",
    "rxjs": "5.0.1",
    "systemjs": "0.19.40",
    "zone.js": "^0.7.4",
    "ng2-auto-complete": "^0.10.9"

  }
</code>```

答:
I don't know how your directory structure is but in general it should work by adding something like this im your .pom:

```<code><project>
  ...
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>
          <packagingExcludes>node_modules/**</packagingExcludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>
</code>```

(see WAR Plugin Docs)

Besides node_modules/** you might also exclude src/**. I'd check the .war file to see if there are other directories/files you can also exclude.

If your Angular app is packaged in a separate .jar that is included in the .war this looks slightly different, e.g.:

```<code><build>
    <resources>
        <resource>
            <directory>${basedir}/src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <excludes>
                <exclude>node_modules/**</exclude>
                <exclude>src/**</exclude>
            </excludes>
        </resource>
    </resources>
</build>
</code>```

Body:
I am creating a web application in which I using Maven, Spring, Hibernate, Angular. The size of war file if very large(151 MB) out of which 107 MB for node modules so please tell me how can I remove unnecessary node modules from war file to keep its size reasonable.
This is my npm dependencies :

"dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.4",
    "angular2-datatable": "^0.6.0",
    "core-js": "^2.4.1",
    "lodash": "^4.17.4",
    "mydatepicker": "^1.6.1",
    "ng2-pdf-viewer": "^1.1.0",
    "rxjs": "5.0.1",
    "systemjs": "0.19.40",
    "zone.js": "^0.7.4",
    "ng2-auto-complete": "^0.10.9"

  }

Body:
I don't know how your directory structure is but in general it should work by adding something like this im your .pom:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>
          <packagingExcludes>node_modules/**</packagingExcludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>

(see WAR Plugin Docs)

Besides node_modules/** you might also exclude src/**. I'd check the .war file to see if there are other directories/files you can also exclude.

If your Angular app is packaged in a separate .jar that is included in the .war this looks slightly different, e.g.:

<build>
    <resources>
        <resource>
            <directory>${basedir}/src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <excludes>
                <exclude>node_modules/**</exclude>
                <exclude>src/**</exclude>
            </excludes>
        </resource>
    </resources>
</build>


问:
NodejS + PhantomJS warn: exit() was called before waiting for commands to finish. Make sure you are not calling exit() too soon
Try to use PhantomJS with NodeJS to check websites loading time.

But got this message after

```<code>phantom_instance.exit();
</code>```

Already tried to run this line after the Promise return

here are my codes:

```<code>function timer(url) {
return new Promise(function(resolve, reject) {
    let phantom_instance = null;
    let sitepage = null;
    let start_time = null;
    let end_time = null;
    let interval_obj = null;
    let loading_time = 0;
    phantom.create()
        .then(function(instance) {
            phantom_instance = instance;
            return phantom_instance.createPage();
        })
        .then(function(page) {
            sitepage = page;
            page.property('viewportSize', {
                width: 1280,
                height: 1024
            })
            start_time = Date.now();
            return page.open(url);
        })
        .then(function(status) {
            return new Promise(function(resolve, reject) {
                if (status == 'success') {
                    interval_obj = setInterval(function() {
                        //tell the browser to return document.readyStatue
                        sitepage.evaluate(function() {
                            return document.readyState;
                        })
                        .then(function(ready_state) {
                            if (ready_state == "complete") {
                                end_time = Date.now();
                                sitepage.close();
                                clearInterval(interval_obj);
                                loading_time = end_time - start_time;
                                return resolve(loading_time);
                            } else {
                                console.log(ready_state);
                            }
                        })
                    }, 1000);
                } else {
                    //phantom_instance.exit();
                    return reject(status);
                }
            });
        })
        .then(function(loading_time) {
            console.log("[Speed Tester] Completed in : " + loading_time);
            phantom_instance.exit();
            return resolve({time:loading_time});
        })
});
}
</code>```

any idea?

Thanks.

答: I could avoid the mentioned warning by executing var promise = page.close(); and waiting for the promise to resolve before executing phantom_instance.exit().

Body:
Try to use PhantomJS with NodeJS to check websites loading time.

But got this message after

phantom_instance.exit();

Already tried to run this line after the Promise return

here are my codes:

function timer(url) {
return new Promise(function(resolve, reject) {
    let phantom_instance = null;
    let sitepage = null;
    let start_time = null;
    let end_time = null;
    let interval_obj = null;
    let loading_time = 0;
    phantom.create()
        .then(function(instance) {
            phantom_instance = instance;
            return phantom_instance.createPage();
        })
        .then(function(page) {
            sitepage = page;
            page.property('viewportSize', {
                width: 1280,
                height: 1024
            })
            start_time = Date.now();
            return page.open(url);
        })
        .then(function(status) {
            return new Promise(function(resolve, reject) {
                if (status == 'success') {
                    interval_obj = setInterval(function() {
                        //tell the browser to return document.readyStatue
                        sitepage.evaluate(function() {
                            return document.readyState;
                        })
                        .then(function(ready_state) {
                            if (ready_state == "complete") {
                                end_time = Date.now();
                                sitepage.close();
                                clearInterval(interval_obj);
                                loading_time = end_time - start_time;
                                return resolve(loading_time);
                            } else {
                                console.log(ready_state);
                            }
                        })
                    }, 1000);
                } else {
                    //phantom_instance.exit();
                    return reject(status);
                }
            });
        })
        .then(function(loading_time) {
            console.log("[Speed Tester] Completed in : " + loading_time);
            phantom_instance.exit();
            return resolve({time:loading_time});
        })
});
}

any idea?

Thanks.


问:
Angular - read configuration from server variables at run time when hosted on Azure
We have an Angular app which is hosted using Asp.Net Core on Azure. The app requires several URIs that are dependent on the environment (deployment slot) in which it is running.

Azure provides a great mechanism for injecting environment variables for server side code where settings can be specified per deployment slot. We need to be able to configure the Angular app at run time using this configuration specified in Azure.

What is the best mechanism to forward Azure application configuration on to the Angular client app so they are detected when the Angular app bootstraps?

A quick and dirty approach is to specify the environment name variable in Azure then set some global variables in Index.htm using the Asp.Net Core Environment Tag helpers:

```<code><environment names="azure-development">
    <script type="text/javascript">
        (function (window) {
            window.__env = window.__env || {};
            window.__env.environmentName = 'azure-development';
            window.__env.apiUri = 'DevApiUriAddress';
        }(this));
    </script>
</environment>
<environment names="azure-test">
    <script type="text/javascript">
        (function (window) {
            window.__env = window.__env || {};
            window.__env.environmentName = 'azure-test';
            window.__env.apiUri = 'TestApiUriAddress';
        }(this));
    </script>
</environment>
</code>```

...and register some kind of injectable class Angular provider to access these:

```<code>import { Injectable } from '@angular/core';

function _window(): any {
    // return the global native browser window object
    return window;
}

@Injectable()
export class EnvConfig{

    get environmentName(): string {

        return _window().__env.environmentName;
    }
}
</code>```

However this feels like a big hack.

What better alternatives are there?

答:
You can just access the environment variables directly from Node, using

```<code>process.env.ENV_VAR_NAME
</code>```

To do this needs two steps:

Create your environment variables (called App Settings, in Azure)
You'll find these in the portal under your web app's menu
"Application Settings" -> "App settings"

Those settings are now available globally in your TypeScript code (or JS - whatever you happen to be running), and you can access them easily by name as in the following example:

Assuming I have set up an environment variable called "SuperSecretPassword", the I can access it ANYWHERE like this

```<code>const password: string = process.env.SuperSecretPassword;
</code>```

And thats all there is to it :)

Body:
We have an Angular app which is hosted using Asp.Net Core on Azure. The app requires several URIs that are dependent on the environment (deployment slot) in which it is running.

Azure provides a great mechanism for injecting environment variables for server side code where settings can be specified per deployment slot. We need to be able to configure the Angular app at run time using this configuration specified in Azure.

What is the best mechanism to forward Azure application configuration on to the Angular client app so they are detected when the Angular app bootstraps?

A quick and dirty approach is to specify the environment name variable in Azure then set some global variables in Index.htm using the Asp.Net Core Environment Tag helpers:

<environment names="azure-development">

</environment>
<environment names="azure-test">

</environment>

...and register some kind of injectable class Angular provider to access these:

import { Injectable } from '@angular/core';

function _window(): any {
    // return the global native browser window object
    return window;
}

@Injectable()
export class EnvConfig{

    get environmentName(): string {

        return _window().__env.environmentName;
    }
}

However this feels like a big hack.

What better alternatives are there?

Body:
You can just access the environment variables directly from Node, using

process.env.ENV_VAR_NAME

To do this needs two steps:

Create your environment variables (called App Settings, in Azure)
You'll find these in the portal under your web app's menu
"Application Settings" -> "App settings"

Those settings are now available globally in your TypeScript code (or JS - whatever you happen to be running), and you can access them easily by name as in the following example:

Assuming I have set up an environment variable called "SuperSecretPassword", the I can access it ANYWHERE like this

const password: string = process.env.SuperSecretPassword;

And thats all there is to it :)


问:
Suppress SQLPLUS <p> paragraph tags when spooling to HTML
I am using SQLPLUS with SET MARKUP HTML ON and I'll like to remove the paragraph tags that SQLPLUS adds before and after every table. The reason for this is because I am spooling the header of the data separately from the data (in order to avoid additional headers every 50 000 records), and I do not want a break between them.</p>

答:
I realize this is almost a year old already, but I came across the same (or a similar) issue and found a work-around.

Though I could not suppress the
 automatically generated by SQLPLUS, I found this to be effective in that it negated the extra lines associated with the
 tags:

HEAD " p {margin:0; padding:0; }"

Body:
I realize this is almost a year old already, but I came across the same (or a similar) issue and found a work-around.

Though I could not suppress the <p> automatically generated by SQLPLUS, I found this to be effective in that it negated the extra lines associated with the <p> tags:

HEAD " p {margin:0; padding:0; }"


问:
Extra bytes on stack when trying stack smashing in C
I am learning about stack smashing and found an example which for me does not work as expected.
I have the following code :

```<code>#include <stdio.h>

GetInput() {
  char buffer[8];
  gets(buffer);
  puts(buffer);
}

main() {
  GetInput();
  return 0;
}
</code>```

when running the code in GDB with break points at "GetInput()" and "gets(buffer)" and displaying the stack at the first and second break point  gives me the following: stack while running code with break points

Looking at the stack there are 20 bytes being pushed to it. That 20 byte should be the following: 8 bytes for the buffer, 4 bytes for the old value of EBP and another 4 bytes for the return address. and there is still another 4 bytes which I am not sure where it is coming from.
Could someone please explain why is there 20 bytes instead of 16.

答:
Padding

Depending on the compiler used and the version of that compiler and even the optimization flags, different amount of padding may be pushed on the stack in different places for different reasons.  Your compiler may be inserting stack canaries to detect buffer overflows.  It may be trying to improve alignment or cache behavior.  It may simply be inefficient and wasting space.

There's no way to say for certain, as every compiler is different, and the precise layout of local variables is not mandated by any spec or ABI.

Body:
I am learning about stack smashing and found an example which for me does not work as expected.
I have the following code :

#include <stdio.h>

GetInput() {
  char buffer[8];
  gets(buffer);
  puts(buffer);
}

main() {
  GetInput();
  return 0;
}

when running the code in GDB with break points at "GetInput()" and "gets(buffer)" and displaying the stack at the first and second break point  gives me the following: stack while running code with break points

Looking at the stack there are 20 bytes being pushed to it. That 20 byte should be the following: 8 bytes for the buffer, 4 bytes for the old value of EBP and another 4 bytes for the return address. and there is still another 4 bytes which I am not sure where it is coming from.
Could someone please explain why is there 20 bytes instead of 16.


问:
Is it possible to use Perl's Getopt::Std in 2 packages?
[perl script]
perl_script.pl -b "HELLO" -v

```<code>use package1;
use package2;

my $argb = GetPackage1Option;
my $argv = GetPackage2Option;

print "$argb\n";                                # Print -b argument
print "v is found!\n" if ( GetPackage2Option ); # Print
</code>```

[package1.pm]

```<code>use Getopt::Std;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw( GetPackage1Option );

sub GetPackage1Option {

    getopt('b');
    our ($opt_b);

    my $argb = $opt_b || '';

    return $argb;
}
</code>```

[package2.pm]

```<code>use Getopt::Std;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw( GetPackage2Option );

sub GetPackage2Option {

    my $bool = 0;
    my %opt;
    getopts('v', \%opt);

    return ( defined $optHash{v} ) ? $optHash{v} : $bool;
}
</code>```

I am calling 2 functions from 2 separate packages and each function uses a different option.

I tried this but I am only getting the option for -b. The -v option works if I remove the functions that use -b.

Apologies this only sort of a summary of my original code.

Please let me know if my question is confusing. Thanks :)

答:
The easiest way out of the conundrum is for command line argument parsing to happen at the entry point of your program where the values of the arguments can be saved in a hash, where you can provide default values for those not specified on the command line etc. Then, you can decide how to communicate the values each module is interested in (e.g. package variables or constructor arguments).

I would strongly recommend against this kind of action at a distance, but here's how one might go about automating the setting of values of package variables in different modules in response to values given on the command line. Each package is responsible for declaring the command line switches in which it is interested.

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

use strict;
use warnings;

package X;

our @PACKAGE_OPTS = qw( v x: );

our ($OPT_V, $OPT_X);

sub func {
    print "$OPT_V\t$OPT_X\n";
}

package Y;

our @PACKAGE_OPTS = qw( t y: z);

our ($OPT_T, $OPT_Y, $OPT_Z);

sub func {
    print join("\t", $OPT_T, $OPT_Y, $OPT_Z), "\n";
}

package main;

use Getopt::Std;

main();

sub main {
    init_opts(qw( X Y ));
    X::func();
    Y::func();
}

sub init_opts {
    my %opts;
    my $opt_string;
    my %opt_to_package;

    for my $pkg ( @_ ) {
        my @opts = eval "\@${pkg}::PACKAGE_OPTS";
        $opt_string .= join '', @opts;

        for my $opt ( @opts ) {
            (my $var = $opt) =~ s/[^A-Za-z]+//g;
            $opts{$var} = '-not provided-';
            $opt_to_package{$var} = $pkg;
        }
    }

    getopts($opt_string, \%opts);

    for my $opt (keys %opts) {
        my $pkg = $opt_to_package{$opt};
        my $var = 'OPT_' . uc $opt;
        eval "\$${pkg}::${var} = \$opts{\$opt}"
    }

    return;
}
</code>```

Output:

```<code>C:\...\Temp> perl tt.pl -zvx a -y b
1       a
-not provided-  b       1
</code>```

Body:
[perl script]
perl_script.pl -b "HELLO" -v

use package1;
use package2;

my $argb = GetPackage1Option;
my $argv = GetPackage2Option;

print "$argb\n";                                # Print -b argument
print "v is found!\n" if ( GetPackage2Option ); # Print

[package1.pm]

use Getopt::Std;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw( GetPackage1Option );

sub GetPackage1Option {

    getopt('b');
    our ($opt_b);

    my $argb = $opt_b || '';

    return $argb;
}

[package2.pm]

use Getopt::Std;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw( GetPackage2Option );

sub GetPackage2Option {

    my $bool = 0;
    my %opt;
    getopts('v', \%opt);

    return ( defined $optHash{v} ) ? $optHash{v} : $bool;
}

I am calling 2 functions from 2 separate packages and each function uses a different option.

I tried this but I am only getting the option for -b. The -v option works if I remove the functions that use -b.

Apologies this only sort of a summary of my original code.

Please let me know if my question is confusing. Thanks :)

Body:
The easiest way out of the conundrum is for command line argument parsing to happen at the entry point of your program where the values of the arguments can be saved in a hash, where you can provide default values for those not specified on the command line etc. Then, you can decide how to communicate the values each module is interested in (e.g. package variables or constructor arguments).

I would strongly recommend against this kind of action at a distance, but here's how one might go about automating the setting of values of package variables in different modules in response to values given on the command line. Each package is responsible for declaring the command line switches in which it is interested.

#!/usr/bin/env perl

use strict;
use warnings;

package X;

our @PACKAGE_OPTS = qw( v x: );

our ($OPT_V, $OPT_X);

sub func {
    print "$OPT_V\t$OPT_X\n";
}

package Y;

our @PACKAGE_OPTS = qw( t y: z);

our ($OPT_T, $OPT_Y, $OPT_Z);

sub func {
    print join("\t", $OPT_T, $OPT_Y, $OPT_Z), "\n";
}

package main;

use Getopt::Std;

main();

sub main {
    init_opts(qw( X Y ));
    X::func();
    Y::func();
}

sub init_opts {
    my %opts;
    my $opt_string;
    my %opt_to_package;

    for my $pkg ( @_ ) {
        my @opts = eval "\@${pkg}::PACKAGE_OPTS";
        $opt_string .= join '', @opts;

        for my $opt ( @opts ) {
            (my $var = $opt) =~ s/[^A-Za-z]+//g;
            $opts{$var} = '-not provided-';
            $opt_to_package{$var} = $pkg;
        }
    }

    getopts($opt_string, \%opts);

    for my $opt (keys %opts) {
        my $pkg = $opt_to_package{$opt};
        my $var = 'OPT_' . uc $opt;
        eval "\$${pkg}::${var} = \$opts{\$opt}"
    }

    return;
}

Output:

C:\...\Temp> perl tt.pl -zvx a -y b
1       a
-not provided-  b       1


问:
Is it possible to iterate through an array list with elements of different data types and put them out?
Without generics it is possible to create an ArrayList with elements of different types. I want to iterate through it and put out the elements. I can not use a for-each-loop, because it wants a specific type. I tried Iterator but wasn't successful.

So I have two questions:

Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which type they are?

Is it possible to iterate through an array list and put out only the elements which are of a specific type (e. g. only the Strings)?

答:
You can always use a Type all the Objects have in common. The last one will always be Object, since every Class extends Object.

But since we don't like to cast it's mostly the better approach to build a basic class for that:

```<code>public abstract class FileType
{
    public abstract String getTypeName();
    public abstract String getTypeDescription();
}

public class JSON extends FileType
{
    @Override
    public String getTypeName()
    {
        return "JSON";
    }

    @Override
    public String getTypeDescription()
    {
        return "JavaScript Object Notation";
    }
}

public class TXT extends FileType
{
    @Override
    public String getTypeName()
    {
        return "TXT";
    }

    @Override
    public String getTypeDescription()
    {
        return "Textfile";
    }
}
</code>```

Now you can make a List of FileType's and use the Methods of it:

```<code>List<FileType> fileTypes = new ArrayList<>();
list.add(new JSON()); // JSON fits good in here
list.add(new TXT()); // TXT also

for (FileType fileType : list)
{
    System.out.println(fileType.getTypeName()); // have the FileType-Methods savely available
}
</code>```

Body:
You can always use a Type all the Objects have in common. The last one will always be Object, since every Class extends Object.

But since we don't like to cast it's mostly the better approach to build a basic class for that:

public abstract class FileType
{
    public abstract String getTypeName();
    public abstract String getTypeDescription();
}

public class JSON extends FileType
{
    @Override
    public String getTypeName()
    {
        return "JSON";
    }

    @Override
    public String getTypeDescription()
    {
        return "JavaScript Object Notation";
    }
}

public class TXT extends FileType
{
    @Override
    public String getTypeName()
    {
        return "TXT";
    }

    @Override
    public String getTypeDescription()
    {
        return "Textfile";
    }
}

Now you can make a List of FileType's and use the Methods of it:

List<FileType> fileTypes = new ArrayList<>();
list.add(new JSON()); // JSON fits good in here
list.add(new TXT()); // TXT also

for (FileType fileType : list)
{
    System.out.println(fileType.getTypeName()); // have the FileType-Methods savely available
}


问:
How to display content from the current page on a new page
I have a webpage where a dynamic table is generated when the user specifies certain things. I want to display the results in a different format (in a report style) without running the queries again (to maintain consistent results).

I checked this question and related ones, but they pull content from a page, where as what I want is to push the content to a new page.

Basically what I want is to display #my-table on a new tab when the button is clicked.

答: You can store your data in localStorage or sessionStorage. later on, you can access same data on another page.</p>


问:
Server Configuration for WSO2 IOT Server with Postgresql
I have a aws ubuntu server with 4gb RAM and 2gb internal memory.  I want the wso2 iot server with postgresql configuration.  What kind of configuration needed for aws ubuntu server for this requirement. As per the wso2 iot documentation, 4gb RAM and 1gb, I have configured with that configuration which is not good right now.  Please do any one tell me the what kind of server optimisation needed for my requirement. </p>

答: When dealing with wso2 modules, I have found that they only work for me when deployed as individual servers. I was using local VirtualBox vms so that I had Data Services on one vm, Enterprise Service Bus on another, etc. Any attempt to combine them in the installer would result in Java dependency hell.</p>


问:
unable to query hive after adding sql server jar to pyspark's class path
Hive is set up correctly, I can query it using spark.sql after entering the repl using pyspark. I want to read a table from sql server and save it to hive. If start the repl passing in a jdbc jar like pyspark  --driver-class-path sqljdbc4.jar --jars sqljdbc4.jar I can read from sql server. However now spark is unable to access hive. Any query on the existing hive table leads to an Lzo Codec error (see below).

I want to know how I can query/pull down an external sql server table, then save it to an existing hive table.

```<code>spark.sql("select max(product_id) from table").show()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/spark/python/pyspark/sql/dataframe.py", line 287, in show
        print(self._jdf.showString(n, truncate))
      File "/usr/lib/spark/python/lib/py4j-0.10.3-src.zip/py4j/java_gateway.py", line 1133, in __call__
      File "/usr/lib/spark/python/pyspark/sql/utils.py", line 63, in deco
        return f(*a, **kw)
      File "/usr/lib/spark/python/lib/py4j-0.10.3-src.zip/py4j/protocol.py", line 319, in get_return_value
    py4j.protocol.Py4JJavaError: An error occurred while calling o95.showString.
    : org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
    Exchange SinglePartition
    +- *HashAggregate(keys=[], functions=[partial_max(product_id#35)], output=[max#45])
       +- HiveTableScan [product_id#35], MetastoreRelation db, table

        at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:56)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange.doExecute(ShuffleExchange.scala:114)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133)
        at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:114)
        at org.apache.spark.sql.execution.InputAdapter.inputRDDs(WholeStageCodegenExec.scala:233)
        at org.apache.spark.sql.execution.aggregate.HashAggregateExec.inputRDDs(HashAggregateExec.scala:138)
        at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:361)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133)
        at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:114)
        at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:240)
        at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:323)
        at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:39)
        at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2193)
        at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
        at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2546)
        at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2192)
        at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2199)
        at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:1935)
        at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:1934)
        at org.apache.spark.sql.Dataset.withTypedCallback(Dataset.scala:2576)
        at org.apache.spark.sql.Dataset.head(Dataset.scala:1934)
        at org.apache.spark.sql.Dataset.take(Dataset.scala:2149)
        at org.apache.spark.sql.Dataset.showString(Dataset.scala:239)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:280)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.RuntimeException: Error in configuring object
        at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:112)
        at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:78)
        at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:136)
        at org.apache.spark.rdd.HadoopRDD.getInputFormat(HadoopRDD.scala:185)
        at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:198)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.ShuffleDependency.<init>(Dependency.scala:91)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange$.prepareShuffleDependency(ShuffleExchange.scala:263)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange.prepareShuffleDependency(ShuffleExchange.scala:86)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange$$anonfun$doExecute$1.apply(ShuffleExchange.scala:123)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange$$anonfun$doExecute$1.apply(ShuffleExchange.scala:114)
        at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:52)
        ... 41 more
    Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
        ... 80 more
    Caused by: java.lang.IllegalArgumentException: Compression codec com.hadoop.compression.lzo.LzoCodec not found.
        at org.apache.hadoop.io.compress.CompressionCodecFactory.getCodecClasses(CompressionCodecFactory.java:139)
        at org.apache.hadoop.io.compress.CompressionCodecFactory.<init>(CompressionCodecFactory.java:179)
        at org.apache.hadoop.mapred.TextInputFormat.configure(TextInputFormat.java:45)
        ... 85 more
    Caused by: java.lang.ClassNotFoundException: Class com.hadoop.compression.lzo.LzoCodec not found
        at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2101)
        at org.apache.hadoop.io.compress.CompressionCodecFactory.getCodecClasses(CompressionCodecFactory.java:132)
        ... 87 more
</code>```

答:
The --driver-class-path flag replaces any values you have configured in your default settings.  It does not append new values.  You probably have the LZO jar added to the class path in your spark-defaults.conf file and it is being ignored because you are overwriting that setting with the flag.  You should either:

1) Include the entire driver classpath in your --driver-class-path setting

or

2) Add the SQL JDBC jar to the classpath in the spark.driver.extraClassPath setting in the spark-defaults.conf file

Also, as @Tim pointed out in the comment, you still need to provide your jar to the command line using the --jars flag.

Body:
Hive is set up correctly, I can query it using spark.sql after entering the repl using pyspark. I want to read a table from sql server and save it to hive. If start the repl passing in a jdbc jar like pyspark  --driver-class-path sqljdbc4.jar --jars sqljdbc4.jar I can read from sql server. However now spark is unable to access hive. Any query on the existing hive table leads to an Lzo Codec error (see below).

I want to know how I can query/pull down an external sql server table, then save it to an existing hive table.

spark.sql("select max(product_id) from table").show()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/spark/python/pyspark/sql/dataframe.py", line 287, in show
        print(self._jdf.showString(n, truncate))
      File "/usr/lib/spark/python/lib/py4j-0.10.3-src.zip/py4j/java_gateway.py", line 1133, in __call__
      File "/usr/lib/spark/python/pyspark/sql/utils.py", line 63, in deco
        return f(*a, **kw)
      File "/usr/lib/spark/python/lib/py4j-0.10.3-src.zip/py4j/protocol.py", line 319, in get_return_value
    py4j.protocol.Py4JJavaError: An error occurred while calling o95.showString.
    : org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
    Exchange SinglePartition
    +- *HashAggregate(keys=[], functions=[partial_max(product_id#35)], output=[max#45])
       +- HiveTableScan [product_id#35], MetastoreRelation db, table

        at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:56)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange.doExecute(ShuffleExchange.scala:114)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133)
        at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:114)
        at org.apache.spark.sql.execution.InputAdapter.inputRDDs(WholeStageCodegenExec.scala:233)
        at org.apache.spark.sql.execution.aggregate.HashAggregateExec.inputRDDs(HashAggregateExec.scala:138)
        at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:361)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133)
        at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:114)
        at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:240)
        at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:323)
        at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:39)
        at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2193)
        at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
        at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2546)
        at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2192)
        at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2199)
        at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:1935)
        at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:1934)
        at org.apache.spark.sql.Dataset.withTypedCallback(Dataset.scala:2576)
        at org.apache.spark.sql.Dataset.head(Dataset.scala:1934)
        at org.apache.spark.sql.Dataset.take(Dataset.scala:2149)
        at org.apache.spark.sql.Dataset.showString(Dataset.scala:239)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:280)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.RuntimeException: Error in configuring object
        at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:112)
        at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:78)
        at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:136)
        at org.apache.spark.rdd.HadoopRDD.getInputFormat(HadoopRDD.scala:185)
        at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:198)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
        at org.apache.spark.ShuffleDependency.<init>(Dependency.scala:91)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange$.prepareShuffleDependency(ShuffleExchange.scala:263)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange.prepareShuffleDependency(ShuffleExchange.scala:86)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange$$anonfun$doExecute$1.apply(ShuffleExchange.scala:123)
        at org.apache.spark.sql.execution.exchange.ShuffleExchange$$anonfun$doExecute$1.apply(ShuffleExchange.scala:114)
        at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:52)
        ... 41 more
    Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
        ... 80 more
    Caused by: java.lang.IllegalArgumentException: Compression codec com.hadoop.compression.lzo.LzoCodec not found.
        at org.apache.hadoop.io.compress.CompressionCodecFactory.getCodecClasses(CompressionCodecFactory.java:139)
        at org.apache.hadoop.io.compress.CompressionCodecFactory.<init>(CompressionCodecFactory.java:179)
        at org.apache.hadoop.mapred.TextInputFormat.configure(TextInputFormat.java:45)
        ... 85 more
    Caused by: java.lang.ClassNotFoundException: Class com.hadoop.compression.lzo.LzoCodec not found
        at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2101)
        at org.apache.hadoop.io.compress.CompressionCodecFactory.getCodecClasses(CompressionCodecFactory.java:132)
        ... 87 more


问:
Get list of subjects in NATS streaming server
I'm looking for a way to display all the subjects that currently exist on a NATS Streaming Server during operation. Have thoroughly looked through documentation but have been unable to find a mention of this so far.

Is there a way to find a list of all available subjects that can be subscribed to on the server?

答:
I have just merged a PR that adds Monitoring to the NATS Streaming server. If you start the server with a monitoring port, say -m 8222, then you can get the list of channels by pointing to http://localhost:8222/streaming/channelsz

This would return:

```<code>{
  "cluster_id": "test-cluster",
  "server_id": "d1dzRa72OpjGRROXKJtfSV",
  "now": "2017-06-08T18:14:54.206006151+02:00",
  "offset": 0,
  "limit": 1024,
  "count": 2,
  "total": 2,
  "names": [
    "bar",
    "foo"
  ]
}
</code>```

For more information, checkout https://github.com/nats-io/nats-streaming-server#monitoring

Body:
I have just merged a PR that adds Monitoring to the NATS Streaming server. If you start the server with a monitoring port, say -m 8222, then you can get the list of channels by pointing to http://localhost:8222/streaming/channelsz

This would return:

{
  "cluster_id": "test-cluster",
  "server_id": "d1dzRa72OpjGRROXKJtfSV",
  "now": "2017-06-08T18:14:54.206006151+02:00",
  "offset": 0,
  "limit": 1024,
  "count": 2,
  "total": 2,
  "names": [
    "bar",
    "foo"
  ]
}

For more information, checkout https://github.com/nats-io/nats-streaming-server#monitoring