问:
Whenever I try to navigate to a link, the entire page moves, not the material in the scrolling div
My goal is to have a scrolling Div with my main content. At the top of that content is my Table of Contents that links to the other material in the scrolling Div. I found some code that automates the ToC, however I can not for the life of me figure out how to get only the scrolling Div to move when I attempt to navigate. Ultimately, I intend to have the ToC navigate to the FAQ question and add a button that appears later to bring the user back to the top.

Is there a technique or Tutorial somewhere that will allow me to do what I want to do?

$(document).ready(function() {
  $("#toc").append('
')
  $("h3").each(function(i) {
    var current = $(this);
    current.attr("id", "title" + i);

    $("#toc").append("
" + current.html() + "
");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="contentarea">
  <div class="title" id="newstitle">
    <h1>Frequently Asked Questions</h1>
  </div>
  <div id="toc"></div>
  <div class="article" id="content">
    <h3>How does sponsorship work at this event?</h3>
    <p>Sponsorship is available to businesses who wish to contribute to the success of the event. If you or your business wish to become a sponsor for HonorCon 2017, please contact the convention chair committee at conchair2@gmail.com.
      Our sponsors receive the most benefit from their donations, as only sponsors are advertised on our website as compared to the space for sale in our program. There are 3 levels of sponsorship available:</p>
    <br>
    <br>
    <h3>What are the convention space rules?/Do you have a harrassment policy?</h3>
    <p>The staff of HonorCon wishes to ensure a safe and comfortable environment for all attendees. We encourage you to come to have a good time and to be whomever you wish to be. We believe that conventions should be safe spaces to enjoy and explore science
      fiction, cosplay, and gaming. If at any time you feel that your safety or the safety of others is in jeopardy, please contact Convention Security immediately (Shore Patrol), who will then contact the Police and Hotel Security as required. To that
      end, however, certain forms of behavior have been deemed inappropriate by the convention committee.</p>
    <br>
    <br>
    <h3>Who are those guys in the yellow berets and brassards?</h3>
    <p>Both HonorCon and MantiCon are put on by the Royal Manticoran Navy: the Official Honor Harrington Association. Because the setting in the Honor Harrington series is primarily based on a futuristic space navy, it stands to reason that our convention's
      security and all-around help-force would be called "Shore Patrol" in honor of the naval military police's peace-keeping function when ships come into port. HonorCon's Shore Patrol performs security functions for the convention in cooperation with
      the venue's management and should be the go-to people should you have any concerns or feel in need of help of any kind.If at ay time you feel that your safety or the safety of others is in jeopardy, please contact Shore Patrol emmediately.</p>
    <br>
    <br>
    <h3>Where is the event?</h3>
    <div>
      <p>HonorCon 2017 will be held in the luxurious Hilton North Raleigh/Midtown. The address is:</p>
      <br>
      <p>3415 Wake Forest Road</p>
      <p>Raleigh, North Carolina 27609-7330</p>
      <p>USA</p>
      <p>Telephone: 1(919)872-2323</p>
      <p>Fax: 1(919)876-0890</p>
    </div>
    <br>
    <br>
    <h3>My question isn't here, who do I contact for an answer?</h3>
    <p>If we've overlooked something that you are dying to know or an explanation is unclear, you have three possible courses of action. The first is to go to the "Contact Us!" page of this website and click on the
      picture of the person whose department best fits the category of your question. This will help set up and address an e-mail to the person most likely to be able to answer your question on the staff. If you are unable to find an appropriate representative
      who seems like they can meet your needs send an e-mail to conchair2@gmail.com. And finally, if time is of the essence, feel free to message us on Facebook using Facebook messenger. Click
      <a
        target="_self" href="https://www.facebook.com/HonorCon/">here</a> to go to our Facebook page!</p>
  </div></code>```

Thanks for your time!

答:
I believe you mean that when user clicks on a link, the page should scroll instead of jumping to the relevant paragraph.

Here is the solution for that:

```<code>// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
      &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
</code>```

refer article: https://css-tricks.com/snippets/jquery/smooth-scrolling/

Body:
My goal is to have a scrolling Div with my main content. At the top of that content is my Table of Contents that links to the other material in the scrolling Div. I found some code that automates the ToC, however I can not for the life of me figure out how to get only the scrolling Div to move when I attempt to navigate. Ultimately, I intend to have the ToC navigate to the FAQ question and add a button that appears later to bring the user back to the top.

Is there a technique or Tutorial somewhere that will allow me to do what I want to do?

$(document).ready(function() {
  $("#toc").append('
')
  $("h3").each(function(i) {
    var current = $(this);
    current.attr("id", "title" + i);

    $("#toc").append("
" + current.html() + "
");
  });
});

Frequently Asked Questions

How does sponsorship work at this event?

Sponsorship is available to businesses who wish to contribute to the success of the event. If you or your business wish to become a sponsor for HonorCon 2017, please contact the convention chair committee at conchair2@gmail.com.
      Our sponsors receive the most benefit from their donations, as only sponsors are advertised on our website as compared to the space for sale in our program. There are 3 levels of sponsorship available:

What are the convention space rules?/Do you have a harrassment policy?

The staff of HonorCon wishes to ensure a safe and comfortable environment for all attendees. We encourage you to come to have a good time and to be whomever you wish to be. We believe that conventions should be safe spaces to enjoy and explore science
      fiction, cosplay, and gaming. If at any time you feel that your safety or the safety of others is in jeopardy, please contact Convention Security immediately (Shore Patrol), who will then contact the Police and Hotel Security as required. To that
      end, however, certain forms of behavior have been deemed inappropriate by the convention committee.

Who are those guys in the yellow berets and brassards?

Both HonorCon and MantiCon are put on by the Royal Manticoran Navy: the Official Honor Harrington Association. Because the setting in the Honor Harrington series is primarily based on a futuristic space navy, it stands to reason that our convention's
      security and all-around help-force would be called "Shore Patrol" in honor of the naval military police's peace-keeping function when ships come into port. HonorCon's Shore Patrol performs security functions for the convention in cooperation with
      the venue's management and should be the go-to people should you have any concerns or feel in need of help of any kind.If at ay time you feel that your safety or the safety of others is in jeopardy, please contact Shore Patrol emmediately.

Where is the event?

HonorCon 2017 will be held in the luxurious Hilton North Raleigh/Midtown. The address is:

3415 Wake Forest Road

Raleigh, North Carolina 27609-7330

USA

Telephone: 1(919)872-2323

Fax: 1(919)876-0890

My question isn't here, who do I contact for an answer?

If we've overlooked something that you are dying to know or an explanation is unclear, you have three possible courses of action. The first is to go to the "Contact Us!" page of this website and click on the
      picture of the person whose department best fits the category of your question. This will help set up and address an e-mail to the person most likely to be able to answer your question on the staff. If you are unable to find an appropriate representative
      who seems like they can meet your needs send an e-mail to conchair2@gmail.com. And finally, if time is of the essence, feel free to message us on Facebook using Facebook messenger. Click
      here to go to our Facebook page!

Thanks for your time!

Body:
I believe you mean that when user clicks on a link, the page should scroll instead of jumping to the relevant paragraph.

Here is the solution for that:

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
      &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

refer article: https://css-tricks.com/snippets/jquery/smooth-scrolling/


来源: stackexchange

问:
How to trigger page refresh from another component in ReactJS?
I am newbie to React. In my CRUD aplication I have a Main component. Then in the List Component I make an API call to load item from server. The problem is that after a new item submitting in Create component I need to refresh my List in order to see a new item added. What is the possible non-flux solution?

Main.jsx

```<code>export default class Main extends React.Component {
constructor(props, context) {
    super(props, context);

    this.state = {
        showModal: false,
    };

    this.openModal = this.openModal.bind(this);
    this.closeModal = this.closeModal.bind(this);
}

openModal() {
    this.setState({showModal: true});
}

closeModal() {
    this.setState({showModal: false});
}

render() {
        return (
            <div>
                <div class="navbar">
                     <div class="nav-item"onClick={this.openModal}>Create</div>
                </div>

                <div class="modal" show={this.state.showModal} onHide={this.closeModal}>
                  <div class="modal-body">
                      <Create onItemCreate={this.closeModal}/>
                  </div>
                </div>

                <List />

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

UPDATE:

List.jsx

```<code>export default class List extends React.Component {

constructor(props, context) {
    super(props, context);

    this.state = {
        items: []
    };
}
refreshList() {
    $.ajax({
        url      : apiPrefix,
        dataType : 'json',
        type     : 'GET',

        success: data => {
            this.setState({items: data.items});
        },

        error: (xhr, status, err) => {
            console.error(apiPrefix, status, err.toString());
        }
    });
}

render() {
    if( this.state.findings === undefined ) {
        return <div>Loading...</div>
    } else {
        return(
            <div>
                <div>
                    {
                        this.state.findings.map((item) => {
                            return <Item key={item._id} item={item} />
                        })
                    }
                </div>
            </div>

        );
    }
}

componentWillMount() {
    this.refreshList();
}

}
</code>```

Create.jsx

```<code>export default class Create extends React.Component {

    constructor(props, context) {
        super(props, context);

        this.state = {

        };
    }

    // Perform a post request to save a formData
    onSubmit({formData}) {
        formData.type = this.state.selectValue;
        axios.post(apiPrefix, formData)
            .then(() => {
                this.closeModal();
                // THIS LIST NEED TO BE REFRESHED
            });
    }

    closeModal() {
        this.props.onFindingCreated();
    }

    render() {
        return (
            <div>
                <div class="form"></div>
            </div>
        )
    }
}
</code>```

答:
when your control reaches to Create page you can check it conditionally in render as:-

Create a variable that will store your state initially when your create page will be loaded first

```<code>render{
if(var==null) //will load your var when this class will run first
{
var=this.props.onItemCreate.showModal
return()..
}
else if(this.props.onItemCreate.showModal!=var and var!=null)
{
var=[] //empty variable and update it to new props
var=this.props.onItemCreate.showModal
}
}
</code>```

Or
 you can use
componentWillReceiveProps in your child class and check if props has been updated then simply set your state to that props and hence your list also

ContentLicense: CC BY-SA 3.0

Body:
I am newbie to React. In my CRUD aplication I have a Main component. Then in the List Component I make an API call to load item from server. The problem is that after a new item submitting in Create component I need to refresh my List in order to see a new item added. What is the possible non-flux solution?

Main.jsx

export default class Main extends React.Component {
constructor(props, context) {
    super(props, context);

    this.state = {
        showModal: false,
    };

    this.openModal = this.openModal.bind(this);
    this.closeModal = this.closeModal.bind(this);
}

openModal() {
    this.setState({showModal: true});
}

closeModal() {
    this.setState({showModal: false});
}

render() {
        return (

Create

                      <Create onItemCreate={this.closeModal}/>

                <List />

        );
    }
}

UPDATE:

List.jsx

export default class List extends React.Component {

constructor(props, context) {
    super(props, context);

    this.state = {
        items: []
    };
}
refreshList() {
    $.ajax({
        url      : apiPrefix,
        dataType : 'json',
        type     : 'GET',

        success: data => {
            this.setState({items: data.items});
        },

        error: (xhr, status, err) => {
            console.error(apiPrefix, status, err.toString());
        }
    });
}

render() {
    if( this.state.findings === undefined ) {
        return
Loading...

    } else {
        return(

                    {
                        this.state.findings.map((item) => {
                            return <Item key={item._id} item={item} />
                        })
                    }

        );
    }
}

componentWillMount() {
    this.refreshList();
}

}

Create.jsx

export default class Create extends React.Component {

    constructor(props, context) {
        super(props, context);

        this.state = {

        };
    }

    // Perform a post request to save a formData
    onSubmit({formData}) {
        formData.type = this.state.selectValue;
        axios.post(apiPrefix, formData)
            .then(() => {
                this.closeModal();
                // THIS LIST NEED TO BE REFRESHED
            });
    }

    closeModal() {
        this.props.onFindingCreated();
    }

    render() {
        return (

        )
    }
}

Body:
when your control reaches to Create page you can check it conditionally in render as:-

Create a variable that will store your state initially when your create page will be loaded first

render{
if(var==null) //will load your var when this class will run first
{
var=this.props.onItemCreate.showModal
return()..
}
else if(this.props.onItemCreate.showModal!=var and var!=null)
{
var=[] //empty variable and update it to new props
var=this.props.onItemCreate.showModal
}
}

Or
 you can use
componentWillReceiveProps in your child class and check if props has been updated then simply set your state to that props and hence your list also


问:
Error on train() function in R
I am trying to learn from an online example and got stuck on one part. Particularly when i use train() function. I got an error saying train isn't a function. I did research and believe train is a function.
The code i copied was :
    xgb_tree_model =  train(SalePrice~., data=train, method="xgbTree", trControl=control, tuneGrid=grid, metric="rmsle", maximize = FALSE)

The site I am using is http://hamelg.blogspot.com/2016/09/kaggle-home-price-prediction-tutorial.html

答:
You can check step by step.

Check if package is installed. Check using following command.

find.package(c("caret"),lib.loc=NULL,quiet=FALSE, verbose = getOption("verbose"))

it will show you package path if found else show you error message.

If package is not installed, install it by using install.packages("caret")
this will install package.

Now load your caret package using library(caret)

call train() function. Now you should not get error message.

Title: Error on train() function in R


问:
javascript to show hide Ul>li on anchor tag click
I want to open a ul which will have dynamic li when I click on a anchor tag.

```<code><a href="javascript:void(0);" class="shop-category"><i class="fa fa-bars" aria-hidden="true"></i><span>SHOP ALL CATEGORIES</span></a>
<ul>
    <li>
        <a href="{{ tree_category.get_absolute_url }}">
            <i class="fa fa-shopping-basket"></i>
            <span class="title">{{tree_category}}</span>
</a>
    </li>
</ul>
</code>```

What I have done so far is :

```<code><script>
    $(".shop-category").filter(function(){
        return ( $(this).siblings('ul').length > 0 );
        }).on("click", function(e) {
        e.preventDefault();
        // hide sibling ul element (if it exists)
        $(this).siblings("ul").toggle();
    });
</script>
</code>```

But No luck.

答:
Hey I think you are missing something inside script tag. Please replace below codes. Hope your issue will be solved. Have a good luck. here is the code.</p>

```<code>$(document).ready(function() {
$(".shop-category").filter(function(){
  return ( $(this).siblings('ul').length > 0 );
  }).on("click", function(e) {
  e.preventDefault();
  // hide sibling ul element (if it exists)
  $(this).siblings("ul").toggle();
});
});
</code>```

Body:
I want to open a ul which will have dynamic li when I click on a anchor tag.

SHOP ALL CATEGORIES

            {{tree_category}}

What I have done so far is :

But No luck.

Body:
Hey I think you are missing something inside script tag. Please replace below codes. Hope your issue will be solved. Have a good luck. here is the code.

$(document).ready(function() {
$(".shop-category").filter(function(){
  return ( $(this).siblings('ul').length > 0 );
  }).on("click", function(e) {
  e.preventDefault();
  // hide sibling ul element (if it exists)
  $(this).siblings("ul").toggle();
});
});


问:
Attach a file with that mail function. Is that possible?
I am using mailto function within anchor tag. I can write subject, cc bcc, body things with that. But I want to attach a file with that mail function. Is that possible?</p>

答:
You cannot attach files in the mailto: protocol, and it would be a gaping security hole if it were possible.

You can use php mail function to send mail with attachment.


问:
Parameter can't pass using ajax in Cross Domain
I have used cross domain to call one domain to another as below ,

My ajax call from mvc project as done below,

```<code>var tableparameter = '{TableName: "' + $("#tableOneTableName").val() + '" }';
$.ajax({
            type: "POST",
            url: "http://localhost:55016/api/ajaxapi/onchangetableone",
            data: tableparameter,
            success: function (response) {
               alert("hi");
            }
});
</code>```

Then i added below code in web.config file within web api project as below,

```<code><httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</code>```

Then i written action as below,

```<code>[HttpPost]
[Route("api/ajaxapi/onchangetableone")]
public List<DropDownListValuesForQuery> OnChangeTableOne(TableNameFormCustomFilters TableParameter)
{
        CaseModel query = new CaseModel();
        List<DropDownListValuesForQuery> listValues = new List<DropDownListValuesForQuery>();
        listValues = query.GetColumnNames(TableParameter.TableName);
        return listValues;
}
</code>```

And list values as below,

```<code>public class TableNameFormCustomFilters
{
        public int TableName { get; set; }
}
</code>```

Here i can access the webapi source using cross domain but the parameter value not come from script. Please give your suggestion.

Thanks in advance.....

答:
change your javascript obj little bit ,

```<code>    var TableParameter =
                {
                    TableName: $("#tableOneTableName").val()
                };
</code>```

Ajax

```<code>$.ajax({
        type: "POST",
        url: "http://localhost:55016/api/ajaxapi/onchangetableone",
        data: TableParameter ,
        success: function (response) {
           alert("hi");
        }
  });
</code>```

' TableParameter ' must be same as model parameter

Body:
I have used cross domain to call one domain to another as below ,

My ajax call from mvc project as done below,

var tableparameter = '{TableName: "' + $("#tableOneTableName").val() + '" }';
$.ajax({
            type: "POST",
            url: "http://localhost:55016/api/ajaxapi/onchangetableone",
            data: tableparameter,
            success: function (response) {
               alert("hi");
            }
});

Then i added below code in web.config file within web api project as below,

<httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>

Then i written action as below,

[HttpPost]
[Route("api/ajaxapi/onchangetableone")]
public List<DropDownListValuesForQuery> OnChangeTableOne(TableNameFormCustomFilters TableParameter)
{
        CaseModel query = new CaseModel();
        List<DropDownListValuesForQuery> listValues = new List<DropDownListValuesForQuery>();
        listValues = query.GetColumnNames(TableParameter.TableName);
        return listValues;
}

And list values as below,

public class TableNameFormCustomFilters
{
        public int TableName { get; set; }
}

Here i can access the webapi source using cross domain but the parameter value not come from script. Please give your suggestion.

Thanks in advance.....

Body:
change your javascript obj little bit ,

    var TableParameter =
                {
                    TableName: $("#tableOneTableName").val()
                };

Ajax

$.ajax({
        type: "POST",
        url: "http://localhost:55016/api/ajaxapi/onchangetableone",
        data: TableParameter ,
        success: function (response) {
           alert("hi");
        }
  });

' TableParameter ' must be same as model parameter


问:
Paypal IPN always return "payment_status: Pending" on sandbox?
I'm trying to implement PayPal on my website.

I use this class: http://www.micahcarrick.com/php-paypal-ipn-integration-class.html

Right now I'm testing using the PayPal sandbox.

Here is the problem:

User makes payment  - ok

User returns to my website succesfully - ok

After a few seconds PayPal calls my website using IPN - ok

My class successfully validate incoming IPN data.

PayPal returns "payment_status: Pending"

I don't know why PayPal IPN calls back with the payment status of "pending"?

Does anyone know what I'm doing wrong?

答:
You can resolve it by the following instruction.

Login to your Developer Central.

Click on Test Accounts tab on the left. You should have created these test accounts for testing on Sandbox.

Find the column ‘Payment Review’.

Find the sandbox account you are using  and click on “Enabled” in the ‘Payment Review’ column.

This should change to “Disabled” and now payments funded from your balance and credit card will complete instantly.


问:
How to implement such use case by Java Concurrency Lock
In the test case below, the update() method is called outside of the class which in running for every hour by one thread only. But there have multiple threads calling getKey1() and getKey2() at the same time.

So for this use case:

The most important is since getKey1() and getKey2() are calling almost at the same time, we must make sure

if flag is true, update both key1 and key2 and return the new key

if not, get the old key1 and key2

We donot want such case exist: update the key1 and get the old key2, but it's ok to get the old key1 and key2 for few request even we already update it.

```<code>public class Test {

    private Lock lock = new ReentrantLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        lock.lock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
        }
    }

    public String getKey1() {
        // TODO if the lock is holding... block over here
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

    public String getKey2() {
        // TODO if the lock is holding... block over here
        if (flag2.get()) {
            // doing something for key 1
            key2 = getFromFile();
            flag2.set(false);
        }
        return key1;
    }
}
</code>```

My idea is:

when update() is running, block both getKey1() and getKey2(), waiting to get the update key

when update() is not running, getKey1() and getKey2() should both be ok and return directly.

when calling either getKey1() or getKey2(), I think we do not need to block the update() method.

Anyone have any ideas about the implementation?

答:
As already said java.util.concurrent.locks.ReentrantReadWriteLock suits you best.

To put it in your example :

```<code>import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test {

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        Lock writeLock = lock.writeLock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            writeLock.unlock();
        }
    }

    public String getKey1() {
        Lock readLock = lock.readLock();
        try {
            if (flag1.get()) {
                // doing something for key 1
                key1 = getFromFile();
                flag1.set(false);
            }
            return key1;
        } finally {
            readLock.unlock();
        }
    }

    public String getKey2() {
        Lock readLock = lock.readLock();
        try {
            if (flag2.get()) {
                // doing something for key 1
                key2 = getFromFile();
                flag2.set(false);
            }
            return key1;
        } finally {
            readLock.unlock();
        }
    }
}
</code>```

From docs of ReadWriteLock interface:

The read lock may be held simultaneously by multiple reader threads,
  so long as there are no writers. The write lock is exclusive.

Body:
In the test case below, the update() method is called outside of the class which in running for every hour by one thread only. But there have multiple threads calling getKey1() and getKey2() at the same time.

So for this use case:

The most important is since getKey1() and getKey2() are calling almost at the same time, we must make sure

if flag is true, update both key1 and key2 and return the new key

if not, get the old key1 and key2

We donot want such case exist: update the key1 and get the old key2, but it's ok to get the old key1 and key2 for few request even we already update it.

public class Test {

    private Lock lock = new ReentrantLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        lock.lock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
        }
    }

    public String getKey1() {
        // TODO if the lock is holding... block over here
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

    public String getKey2() {
        // TODO if the lock is holding... block over here
        if (flag2.get()) {
            // doing something for key 1
            key2 = getFromFile();
            flag2.set(false);
        }
        return key1;
    }
}

My idea is:

when update() is running, block both getKey1() and getKey2(), waiting to get the update key

when update() is not running, getKey1() and getKey2() should both be ok and return directly.

when calling either getKey1() or getKey2(), I think we do not need to block the update() method.

Anyone have any ideas about the implementation?

Body:
As already said java.util.concurrent.locks.ReentrantReadWriteLock suits you best.

To put it in your example :

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test {

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        Lock writeLock = lock.writeLock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            writeLock.unlock();
        }
    }

    public String getKey1() {
        Lock readLock = lock.readLock();
        try {
            if (flag1.get()) {
                // doing something for key 1
                key1 = getFromFile();
                flag1.set(false);
            }
            return key1;
        } finally {
            readLock.unlock();
        }
    }

    public String getKey2() {
        Lock readLock = lock.readLock();
        try {
            if (flag2.get()) {
                // doing something for key 1
                key2 = getFromFile();
                flag2.set(false);
            }
            return key1;
        } finally {
            readLock.unlock();
        }
    }
}

From docs of ReadWriteLock interface:

The read lock may be held simultaneously by multiple reader threads,
  so long as there are no writers. The write lock is exclusive.


问:
Reduction in the number of records using range join
Following the my question
I have the following tables the first (Range) includes range of values and additional columns:

```<code>row  | From   |  To     | Country ....
-----|--------|---------|---------
1    | 1200   |   1500  |
2    | 2200   |   2700  |
3    | 1700   |   1900  |
4    | 2100   |   2150  |
...
</code>```

The From and To are bigint and are exclusive. The Range table includes 1.8M records. Additional table (Values) contains 2.7M records and looks like:

```<code> row     | Value  | More columns....
 --------|--------|----------------
    1    | 1777   |
    2    | 2122   |
    3    | 1832   |
    4    | 1340   |
    ...
</code>```

I would like to create one table as followed:

```<code>row      | Value  | From   | To    | More columns....
 --------|--------|--------|-------|---
    1    | 1777   | 1700   | 1900  |
    2    | 2122   | 2100   | 2150  |
    3    | 1832   | 1700   | 1900  |
    4    | 1340   | 1200   | 1500  |
    ...
</code>```

I used the left outer join in the following code:

```<code>set n=1000;

select      v.id
           ,v.val
           ,r.from_val
           ,r.to_val

from      val v
        left outer join

 (select  r.*
                   ,floor(from_val/${hiveconf:n}) + pe.i    as match_val

            from    val_range r
                    lateral view    posexplode
                                    (
                                        split
                                        (
                                            space
                                            (
                                                cast
                                                (
                                                    floor(to_val/${hiveconf:n})
                                                  - floor(from_val/${hiveconf:n})

                                                    as int
                                                )
                                            )
                                           ,' '
                                        )
                                    ) pe as i,x
            ) r

            on      floor(v.val/${hiveconf:n})    =
                    r.match_val

where       v.val between r.from_val and r.to_val

order by    v.id
;
</code>```

However there is a vast reduction in the number of records of the new table ~31k records out of 2.7M. How can it be if I use the left outer join? How can I fix it?

答:
Assuming we have a v.id

```<code>set n=1000;

select      v.id
           ,r.from_val
           ,r.to_val

from                    val     v

            left join  (select      v.id
                                   ,r.from_val
                                   ,r.to_val

                        from                val     v

                                    join    (...)   r

                                    on      floor(v.val/${hiveconf:n})    =
                                            r.match_val

                        where       v.val between r.from_val and r.to_val
                        ) r

            on          r.id    =
                        v.id

order by    v.id
</code>```

As for the OP request, here is the full query:

```<code>set n=1000;

select      v.id
           ,r.from_val
           ,r.to_val

from                    val     v

            left join  (select      v.id
                                   ,r.from_val
                                   ,r.to_val

                        from                val     v

                                    join   (select  r.*
                                                   ,floor(from_val/${hiveconf:n}) + pe.i    as match_val

                                            from    val_range r
                                                    lateral view    posexplode
                                                                    (
                                                                        split
                                                                        (
                                                                            space
                                                                            (
                                                                                cast
                                                                                (
                                                                                floor(to_val/${hiveconf:n})
                                                                                - floor(from_val/${hiveconf:n})

                                                                                as int
                                                                                )
                                                                            )
                                                                           ,' '
                                                                        )
                                                                    ) pe as i,x
                                            ) r

                                    on      floor(v.val/${hiveconf:n})    =
                                            r.match_val

                        where       v.val between r.from_val and r.to_val
                        ) r

            on          r.id    =
                        v.id

order by    v.id
</code>```

Body:
Following the my question
I have the following tables the first (Range) includes range of values and additional columns:

row  | From   |  To     | Country ....
-----|--------|---------|---------
1    | 1200   |   1500  |
2    | 2200   |   2700  |
3    | 1700   |   1900  |
4    | 2100   |   2150  |
...

The From and To are bigint and are exclusive. The Range table includes 1.8M records. Additional table (Values) contains 2.7M records and looks like:

 row     | Value  | More columns....
 --------|--------|----------------
    1    | 1777   |
    2    | 2122   |
    3    | 1832   |
    4    | 1340   |
    ...

I would like to create one table as followed:

row      | Value  | From   | To    | More columns....
 --------|--------|--------|-------|---
    1    | 1777   | 1700   | 1900  |
    2    | 2122   | 2100   | 2150  |
    3    | 1832   | 1700   | 1900  |
    4    | 1340   | 1200   | 1500  |
    ...

I used the left outer join in the following code:

set n=1000;

select      v.id
           ,v.val
           ,r.from_val
           ,r.to_val

from      val v
        left outer join

 (select  r.*
                   ,floor(from_val/${hiveconf:n}) + pe.i    as match_val

            from    val_range r
                    lateral view    posexplode
                                    (
                                        split
                                        (
                                            space
                                            (
                                                cast
                                                (
                                                    floor(to_val/${hiveconf:n})
                                                  - floor(from_val/${hiveconf:n})

                                                    as int
                                                )
                                            )
                                           ,' '
                                        )
                                    ) pe as i,x
            ) r

            on      floor(v.val/${hiveconf:n})    =
                    r.match_val

where       v.val between r.from_val and r.to_val

order by    v.id
;

However there is a vast reduction in the number of records of the new table ~31k records out of 2.7M. How can it be if I use the left outer join? How can I fix it?

Body:
Assuming we have a v.id

set n=1000;

select      v.id
           ,r.from_val
           ,r.to_val

from                    val     v

            left join  (select      v.id
                                   ,r.from_val
                                   ,r.to_val

                        from                val     v

                                    join    (...)   r

                                    on      floor(v.val/${hiveconf:n})    =
                                            r.match_val

                        where       v.val between r.from_val and r.to_val
                        ) r

            on          r.id    =
                        v.id

order by    v.id

As for the OP request, here is the full query:

set n=1000;

select      v.id
           ,r.from_val
           ,r.to_val

from                    val     v

            left join  (select      v.id
                                   ,r.from_val
                                   ,r.to_val

                        from                val     v

                                    join   (select  r.*
                                                   ,floor(from_val/${hiveconf:n}) + pe.i    as match_val

                                            from    val_range r
                                                    lateral view    posexplode
                                                                    (
                                                                        split
                                                                        (
                                                                            space
                                                                            (
                                                                                cast
                                                                                (
                                                                                floor(to_val/${hiveconf:n})
                                                                                - floor(from_val/${hiveconf:n})

                                                                                as int
                                                                                )
                                                                            )
                                                                           ,' '
                                                                        )
                                                                    ) pe as i,x
                                            ) r

                                    on      floor(v.val/${hiveconf:n})    =
                                            r.match_val

                        where       v.val between r.from_val and r.to_val
                        ) r

            on          r.id    =
                        v.id

order by    v.id


问:
VHDL process style
I have been reading through various questions on here, as I am learning VHDL and always looking to improve. However, this comment made me curious:

Simple State Machine Problem

I was told, in my brief VHDL course at university, that separate processes was best form, to separate the synchronous aspects.

Obviously this is personal preference, but I was hoping that some more experienced users may be able to shed some light on the pros/cons, with their own preferences? Is one more common than the other?

Thanks!

答:
I'm in the keep it separate camp. In my code I have a single synchronous process which does reset and clocking behaviour. Everything else is async. A register process looks something like this:

```<code>Wait for Clock;
If Reset then
    Value <= '0';
else
    Value <= nextValue;
endif
</code>```

Things I like:

It's obvious which signals are flops. They are the ones in the clocked process.

I write the register process once and forget about it.

All your async processes are "pure" functions with no retained state.

Forces you to split logic at registers, separating pipeline stages, etc

It promotes a style which is many, small, simple, async processes.

Due to this logic cones are easier to understand and optimise.

Big processes are likely to be the ones that have problems with timing closure. Early alarm bells.

Negatives:

Sensitivity lists, but Emacs has a macro for this, and it comes out in warnings. If the list is huge your process is too big.

Defaults for every output, but that actually serves as documentation. Right at the start of a process, these are my outputs and defaults. Again, caught by warnings if I get it wrong. It's also far easier to catch a latch (which you almost never want) than a extra flip-flop because and async term wasn't assigned in one path.

Things I don't quite understand from Martin's answer:

The logic is split up, so if you add a state to a state machine, you have to put the new state in both processes

I change the type of my state variable (i.e. add an enum) and move on. Exactly the same as in unified style.

If you want a signal to be used both registered and unregistered, you end up duplicated it. Witha single process you can use variables to achieve this.

In split style you already have the registered and unregistered versions. They are the input and output to the register process. No extra work at all.

ContentLicense: CC BY-SA 2.5

Title: VHDL process style

Body:
I'm in the keep it separate camp. In my code I have a single synchronous process which does reset and clocking behaviour. Everything else is async. A register process looks something like this:

Wait for Clock;
If Reset then
    Value <= '0';
else
    Value <= nextValue;
endif

Things I like:

It's obvious which signals are flops. They are the ones in the clocked process.

I write the register process once and forget about it.

All your async processes are "pure" functions with no retained state.

Forces you to split logic at registers, separating pipeline stages, etc

It promotes a style which is many, small, simple, async processes.

Due to this logic cones are easier to understand and optimise.

Big processes are likely to be the ones that have problems with timing closure. Early alarm bells.

Negatives:

Sensitivity lists, but Emacs has a macro for this, and it comes out in warnings. If the list is huge your process is too big.

Defaults for every output, but that actually serves as documentation. Right at the start of a process, these are my outputs and defaults. Again, caught by warnings if I get it wrong. It's also far easier to catch a latch (which you almost never want) than a extra flip-flop because and async term wasn't assigned in one path.

Things I don't quite understand from Martin's answer:

The logic is split up, so if you add a state to a state machine, you have to put the new state in both processes

I change the type of my state variable (i.e. add an enum) and move on. Exactly the same as in unified style.

If you want a signal to be used both registered and unregistered, you end up duplicated it. Witha single process you can use variables to achieve this.

In split style you already have the registered and unregistered versions. They are the input and output to the register process. No extra work at all.


问:
Find Id of View in Child Activity
I have an issue , need your help , my question is : I have a multiple activity , so i have created one abstract class which hold the view . Now my question i am able to pass the view to the Base Activity but how to finds view id in Child Activity Class.

I Tried like this :

```<code>public abstract class BaseActivity extends Activity {
   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(getLayoutResourceId());
   }

   public abstract int getLayoutResourceId();

}
My Activity Class:
    public class ServiceActivity extends BaseActivity {
        Button startSerice_btn, stopService_btn;
        MyService myService;

        @Override
        public int getLayoutResourceId() {
            return R.layout.service_xml;
        }

    }
</code>```

答:
You can access your views after the super.onCreate() call in the ServiceActivity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Access them here
}
</code>```

Title: Find Id of View in Child Activity

Body:
I have an issue , need your help , my question is : I have a multiple activity , so i have created one abstract class which hold the view . Now my question i am able to pass the view to the Base Activity but how to finds view id in Child Activity Class.

I Tried like this :

public abstract class BaseActivity extends Activity {
   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(getLayoutResourceId());
   }

   public abstract int getLayoutResourceId();

}
My Activity Class:
    public class ServiceActivity extends BaseActivity {
        Button startSerice_btn, stopService_btn;
        MyService myService;

        @Override
        public int getLayoutResourceId() {
            return R.layout.service_xml;
        }

    }

Body:
You can access your views after the super.onCreate() call in the ServiceActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Access them here
}


问:
What is the difference between Php $this->$propery_name and $this->propery_name
```<code>    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }
</code>```

I am following a tutorial on object-oriented programming, however, the instructor came up with a new code structure that I have not seen before without a clear explanation of why he did so. if you notice within the if(statement) the
$this->$protected_property_name statement has two $ signs one for the $this and the other for the  $protected_property_name normally it should only be
$this->protected_property_name without having a dollar sign on the protected_property_name variable. when I tried to remove the $ sign from the protected_property_name variable an error was triggered. the complete code looks like this

```<code>class Addrress{

  protected $_postal_code;

  function __get($name){
    if(!$this->_postal_code){
        $this->_postal_code = $this->_postal_code_guess();
    }

    //Attempt to return protected property by name

    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }

    //Unable to access property; trigger error.
    trigger_error('Undefined property via __get:() '. $name);
    return NULL;
}
}
</code>```

答:
This is an example class:

```<code>class Example {
    public $property_one = 1;
    public $property_two = 2;
}
</code>```

You can see difference in following codes:

```<code>$example = new Example();
echo $example->property_one; //echo 1

$other_property = 'property_two';
echo $example->$other_property; // equal to $example->property_two and echo 2
</code>```

Non-OOP example:

```<code>$variable_one = 100;
$variable_name = 'variable_one';
echo $$variable_name; // equal to echo $variable_one and echo 100
</code>```

Body:
    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }

I am following a tutorial on object-oriented programming, however, the instructor came up with a new code structure that I have not seen before without a clear explanation of why he did so. if you notice within the if(statement) the
$this->$protected_property_name statement has two $ signs one for the $this and the other for the  $protected_property_name normally it should only be
$this->protected_property_name without having a dollar sign on the protected_property_name variable. when I tried to remove the $ sign from the protected_property_name variable an error was triggered. the complete code looks like this

class Addrress{

  protected $_postal_code;

  function __get($name){
    if(!$this->_postal_code){
        $this->_postal_code = $this->_postal_code_guess();
    }

    //Attempt to return protected property by name

    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }

    //Unable to access property; trigger error.
    trigger_error('Undefined property via __get:() '. $name);
    return NULL;
}
}

Body:
This is an example class:

class Example {
    public $property_one = 1;
    public $property_two = 2;
}

You can see difference in following codes:

$example = new Example();
echo $example->property_one; //echo 1

$other_property = 'property_two';
echo $example->$other_property; // equal to $example->property_two and echo 2

Non-OOP example:

$variable_one = 100;
$variable_name = 'variable_one';
echo $$variable_name; // equal to echo $variable_one and echo 100


问:
What should I type in header file path when header file not found happened?
I am developing on Objective-C , and my app runs on my iPhone 5C. However, it shows "header file not found" when I run archive in Xcode - see the following picture:

Specifically, it shows MobileVLCKit/VLCMediaPlayer.h file not found in AITPreviewViewController.m when I run archive, but MobileVLCKit/VLCMediaPlayer.h is in the project MobileVLCKit. How do I solve this?

--------------EDIT------------------

And the folder of my project is like the following:

The header file of VLC is in the importedSources -> VLCKit -> Headers

答:
Please check below steps to fix it:

1.Copy the downloaded MobileVLCKit.framework file, into your project root folder.

2.Go to your project's target build settings->Header Search Paths add following lines(add the quotes too)

```<code>"$(PROJECT_DIR)/MobileVLCKit.framework/Headers"
"$(BUILT_PRODUCTS_DIR)"
</code>```

3.build settings->framework search paths(add the quotes too)

```<code>"$(SRCROOT)/MobileVLCKit.framework"
"$(PROJECT_DIR)"
</code>```

4.build settings->other linker flags add the following lines

```<code>-l"bz2"
-l"iconv"
-framework
"MobileVLCKit"
</code>```

5.In General->Linked Frameworks and Libraries add the following library by clicking on the + icon

```<code>libstdc++.6.tbd
</code>```

6.If you are using Swift, most important of all add the reference to the Bridging-Header.h by including the following line

```<code>#import "MobileVLCKit/MobileVLCKit.h"
</code>```

Test by typing VLCMediaPlayerDelegate, see if that auto completes. If so help others by pointing them here, else retrace your steps to see what you have missed.

Hope that helps.

Body:
Please check below steps to fix it:

1.Copy the downloaded MobileVLCKit.framework file, into your project root folder.

2.Go to your project's target build settings->Header Search Paths add following lines(add the quotes too)

"$(PROJECT_DIR)/MobileVLCKit.framework/Headers"
"$(BUILT_PRODUCTS_DIR)"

3.build settings->framework search paths(add the quotes too)

"$(SRCROOT)/MobileVLCKit.framework"
"$(PROJECT_DIR)"

4.build settings->other linker flags add the following lines

-l"bz2"
-l"iconv"
-framework
"MobileVLCKit"

5.In General->Linked Frameworks and Libraries add the following library by clicking on the + icon

libstdc++.6.tbd

6.If you are using Swift, most important of all add the reference to the Bridging-Header.h by including the following line

#import "MobileVLCKit/MobileVLCKit.h"

Test by typing VLCMediaPlayerDelegate, see if that auto completes. If so help others by pointing them here, else retrace your steps to see what you have missed.

Hope that helps.


问:
Passing a function pointer as parameter to fopen
I created a small C program for creating a time stamp and append it to a file text name:

```<code>#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

void time_stamp(){
    time_t rawtime;
    struct tm * timeinfo;
    char buffer [80];
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    strftime (buffer,80,"myFile_%F.txt",timeinfo);
    printf ("%s", buffer);
}

int main ()
{
    void (*filename_ptr)();
    filename_ptr = &time_stamp;

    FILE * fp;

    fp = fopen (filename_ptr, "w+");
    fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

    fclose(fp);

    return 0;
}
</code>```

But I can't get fopen to accept the pointer to the function creating the name with the time stamp. It is expecting a const char. How can i cast my function pointer to it?

答:
You can't, but you can just call the function through the pointer appending (). For this to work, change your function to actually return const char * (or char *)

Note you can't just return a pointer to your buffer because this is a local variable that is no longer existent when the function returns. You could pass a pointer to buffer from outside the function. Your prototype then should be

```<code>char *time_stamp(char *buf, size_t len);
</code>```

modified code:

```<code>#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

char *time_stamp(char *buf, size_t len){
    time_t rawtime;
    struct tm * timeinfo;
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    strftime (buf,len,"myFile_%F.txt",timeinfo);
    return buf;
}

int main ()
{
    char *(*filename_ptr)(char *, size_t);
    filename_ptr = &time_stamp;
    char buffer[80];

    FILE * fp;

    fp = fopen (filename_ptr(buffer, 80), "w+");
    fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

    fclose(fp);

    return 0;
}
</code>```

There are other alternatives how to design this function. Neroku's answer is good when you are sure you never need the function in a threaded context. It simplifies the usage and there are even some standard C library functions designed in that way.

The third way would be to make the buffer an allocated object by obtaining it from malloc(). This has the advantage of being thread-safe and not needing any extra arguments, the function itself controls the size of the buffer like in your original broken version. The disadvantage is that the caller must free() the memory when done with it. Example code for this (I don't recommend it here):

```<code>#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

char *time_stamp(){
    time_t rawtime;
    struct tm * timeinfo;
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    char *buf = malloc(80);
    strftime (buf,80,"myFile_%F.txt",timeinfo);
    return buf;
}

int main ()
{
    char *(*filename_ptr)();
    filename_ptr = &time_stamp;

    FILE * fp;

    char *filename = filename_ptr();
    fp = fopen (filename, "w+");
    free(filename);
    fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

    fclose(fp);

    return 0;
}
</code>```

Body:
I created a small C program for creating a time stamp and append it to a file text name:

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

void time_stamp(){
    time_t rawtime;
    struct tm * timeinfo;
    char buffer [80];
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    strftime (buffer,80,"myFile_%F.txt",timeinfo);
    printf ("%s", buffer);
}

int main ()
{
    void (*filename_ptr)();
    filename_ptr = &time_stamp;

    FILE * fp;

    fp = fopen (filename_ptr, "w+");
    fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

    fclose(fp);

    return 0;
}

But I can't get fopen to accept the pointer to the function creating the name with the time stamp. It is expecting a const char. How can i cast my function pointer to it?

Body:
You can't, but you can just call the function through the pointer appending (). For this to work, change your function to actually return const char * (or char *)

Note you can't just return a pointer to your buffer because this is a local variable that is no longer existent when the function returns. You could pass a pointer to buffer from outside the function. Your prototype then should be

char *time_stamp(char *buf, size_t len);

modified code:

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

char *time_stamp(char *buf, size_t len){
    time_t rawtime;
    struct tm * timeinfo;
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    strftime (buf,len,"myFile_%F.txt",timeinfo);
    return buf;
}

int main ()
{
    char *(*filename_ptr)(char *, size_t);
    filename_ptr = &time_stamp;
    char buffer[80];

    FILE * fp;

    fp = fopen (filename_ptr(buffer, 80), "w+");
    fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

    fclose(fp);

    return 0;
}

There are other alternatives how to design this function. Neroku's answer is good when you are sure you never need the function in a threaded context. It simplifies the usage and there are even some standard C library functions designed in that way.

The third way would be to make the buffer an allocated object by obtaining it from malloc(). This has the advantage of being thread-safe and not needing any extra arguments, the function itself controls the size of the buffer like in your original broken version. The disadvantage is that the caller must free() the memory when done with it. Example code for this (I don't recommend it here):

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

char *time_stamp(){
    time_t rawtime;
    struct tm * timeinfo;
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    char *buf = malloc(80);
    strftime (buf,80,"myFile_%F.txt",timeinfo);
    return buf;
}

int main ()
{
    char *(*filename_ptr)();
    filename_ptr = &time_stamp;

    FILE * fp;

    char *filename = filename_ptr();
    fp = fopen (filename, "w+");
    free(filename);
    fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

    fclose(fp);

    return 0;
}


问:
ChartObject.Deactivate doesnt work?
I can activate a chart very easily:

```<code>Sheet10.ChartObjects("Chart 2").Activate
</code>```

Now when I try to deactivate:

```<code>Sheet10.ChartObjects("Chart 2").Deactivate
</code>```

I get an error:

"object doesn't support property or method"

What have I done wrong?

答:
As stated in the comments, there is no such method as Deactivate.

So a solution for Chart 2 to be not in the Activate state is to create another object, possibly hidden, let's say in Sheet99:

```<code>Sheet99.ChartObjects("hiddenChart").Activate
</code>```

Hope this helps.

Title: ChartObject.Deactivate doesnt work?

Body:
I can activate a chart very easily:

Sheet10.ChartObjects("Chart 2").Activate

Now when I try to deactivate:

Sheet10.ChartObjects("Chart 2").Deactivate

I get an error:

"object doesn't support property or method"

What have I done wrong?

Body:
As stated in the comments, there is no such method as Deactivate.

So a solution for Chart 2 to be not in the Activate state is to create another object, possibly hidden, let's say in Sheet99:

Sheet99.ChartObjects("hiddenChart").Activate

Hope this helps.


问:
Fast linq query with join and count
I have this SQL query witch is running fast if executed from TOAD in Oracle database where Jobs table contains more than 2 million records.

```<code>select * from Technicians  A
left join
  (select TechnicianCode,count(*)JobCount from Jobs
   where TxnCode in ('Jc','Jcd') group by TechnicianCode) B
on B.TechnicianCode =A.TechnicianCode
</code>```

Not able to translate it to linq in efficient way.
Can anybody help with it?

答:
You can try this

```<code>var txnDetails =  from job in jobs
                  where job.TxnCode == "Jc" || job.TxnCode == "Jcd"
                  group job by job.TechnicianCode into g
                  select new { TechnicianCode = g.Key, count = g.Count() };
</code>```

Then you can just do normal select with join

```<code> from technician in Technicians
 join txn in txnDetails on technician.TechnicianCode equals
   txn.TechnicianCode into tg
 from t in tg.DefaultIfEmpty()
 select new {Count = t==null? 0: t.count, ...}
</code>```

Title: Fast linq query with join and count

Body:
I have this SQL query witch is running fast if executed from TOAD in Oracle database where Jobs table contains more than 2 million records.

select * from Technicians  A
left join
  (select TechnicianCode,count(*)JobCount from Jobs
   where TxnCode in ('Jc','Jcd') group by TechnicianCode) B
on B.TechnicianCode =A.TechnicianCode

Not able to translate it to linq in efficient way.
Can anybody help with it?

Body:
You can try this

var txnDetails =  from job in jobs
                  where job.TxnCode == "Jc" || job.TxnCode == "Jcd"
                  group job by job.TechnicianCode into g
                  select new { TechnicianCode = g.Key, count = g.Count() };

Then you can just do normal select with join

 from technician in Technicians
 join txn in txnDetails on technician.TechnicianCode equals
   txn.TechnicianCode into tg
 from t in tg.DefaultIfEmpty()
 select new {Count = t==null? 0: t.count, ...}


问:
HttpPostedFileBase to Image throws exceptions
I am uploading a big image ~10Mb and I have the following code:

```<code>public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        var image = Image.FromStream(file.InputStream, true, true);
        ...
    }
}
</code>```

Sometime it throws Out of Memory, sometimes GDI+ generic errors. I cannot reproduce this in a console app with the following code:

```<code>using (FileStream stream = File.Open(@"d:\test.jpg", FileMode.Open))
{
    var image = Image.FromStream(stream);
}
</code>```

What can be the cause for those exceptions? One note: for small images everything works great.

答:
I have read answers on many similar exceptions and none could be applied to my case. Image itself was not corrupted or with incorrect bits. The thing was that I was debugging in 32 bit mode. As soon as I change this setting in VS2015 it worked like a charm. Seems Image.FromStream requires a lot of RAM for big images.

Tools -> Options -> Projects and Solutions -> Web Projects -> Use the
  64 bit...

Body:
I am uploading a big image ~10Mb and I have the following code:

public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        var image = Image.FromStream(file.InputStream, true, true);
        ...
    }
}

Sometime it throws Out of Memory, sometimes GDI+ generic errors. I cannot reproduce this in a console app with the following code:

using (FileStream stream = File.Open(@"d:\test.jpg", FileMode.Open))
{
    var image = Image.FromStream(stream);
}

What can be the cause for those exceptions? One note: for small images everything works great.


问:
java.lang.IllegalArgumentException, i got that in my crash report from play store, suggest me to how resolve that....
play store show that exception error occurred in crash report. please help me to resolve that. log and java code are following.In this i got youtube url from my created api but it may be be exception on dialog.dismis method

log report

```<code>java.lang.IllegalArgumentException:
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:412)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:338)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:118)
at android.app.Dialog.dismissDialog(Dialog.java:509)
at android.app.Dialog.dismiss(Dialog.java:492)
at com.sevakk.www.msg.Home$2.onResponse(Home.java:112)
at com.sevakk.www.msg.Home$2.onResponse(Home.java:104)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6838)
at java.lang.reflect.Method.invoke(Native Method:0)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
</code>```

Java Code

```<code> public class Home extends AppCompatActivity {

 InterstitialAd mInterstitialAd;
 String url = "http://xxxxxxxx/xxxxxx.php";
 private RecyclerView recyclerView;
 private RecyclerView.LayoutManager layoutManager;
 private RecyclerView.Adapter adapter;

 List<Post_Data> list;

 private InterstitialAd interstitial;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    AdView mAdView = (AdView) findViewById(R.id.adView);

    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    // Prepare the Interstitial Ad
    interstitial = new InterstitialAd(Home.this);
    // Insert the Ad Unit ID
    interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));

    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    list = new ArrayList<Post_Data>();

    getInfo();

    interstitial.loadAd(adRequest);
    // Prepare an Interstitial Ad Listener
    interstitial.setAdListener(new AdListener() {
        public void onAdLoaded() {
            // Call displayInterstitial() function
            displayInterstitial();
        }
    });
}

private void getInfo() {
    final ProgressDialog dialog = new ProgressDialog(Home.this);
    dialog.setMessage("please wait...");
    dialog.show();
    final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONObject object = new JSONObject(response);
                JSONArray jsonArray = object.getJSONArray("server_response");
                dialog.dismiss();

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    Post_Data data = new Post_Data();
                    data.id = object1.getString("id");
                    data.url = object1.getString("url");
                    data.date = object1.getString("date");
                    data.postImageId = object1.getString("time");
                    data.text = object1.getString("desc");
                    data.eventdate = object1.getString("duration");
                    list.add(data);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            adapter = new YoutTubeAdapter(Home.this, list);
            recyclerView.setAdapter(adapter);
        }
    }, new Response.ErrorListener()

    {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.e(">>>", "error is :" + error.toString());

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> map = new HashMap<>();
            return map;
        }
    };

    RequestQueue queue = Volley.newRequestQueue(this);
    int socketTimeout = 120000;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    request.setRetryPolicy(policy);
    queue.add(request);
}

public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
    if (interstitial.isLoaded()) {
        interstitial.show();
    }
}

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    //super.onBackPressed();
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
        return;
    }
    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "press back again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2000);
    }
    }
</code>```

答:
Try replacing the below code on line 112.

```<code> try {
      if (!Home.this.isDestroyed()) {

        if ((dialog != null) && dialog.isShowing()) {
            dialog.dismiss();
        }
} catch (IllegalArgumentException e) {
    Log.e("Custom Tag", "Custom Message", e);
} catch ( Exception e) {
    Log.e("Custom Tag", "Custom Message", e);
} finally {
    dialog = null;
}
</code>```

General idea is like, check whether your activity is destroyed, and if not destroyed, check whether your dialog is showing or not then dismiss your dialog.

Body:
play store show that exception error occurred in crash report. please help me to resolve that. log and java code are following.In this i got youtube url from my created api but it may be be exception on dialog.dismis method

log report

java.lang.IllegalArgumentException:
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:412)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:338)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:118)
at android.app.Dialog.dismissDialog(Dialog.java:509)
at android.app.Dialog.dismiss(Dialog.java:492)
at com.sevakk.www.msg.Home$2.onResponse(Home.java:112)
at com.sevakk.www.msg.Home$2.onResponse(Home.java:104)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6838)
at java.lang.reflect.Method.invoke(Native Method:0)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

Java Code

 public class Home extends AppCompatActivity {

 InterstitialAd mInterstitialAd;
 String url = "http://xxxxxxxx/xxxxxx.php";
 private RecyclerView recyclerView;
 private RecyclerView.LayoutManager layoutManager;
 private RecyclerView.Adapter adapter;

 List<Post_Data> list;

 private InterstitialAd interstitial;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    AdView mAdView = (AdView) findViewById(R.id.adView);

    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    // Prepare the Interstitial Ad
    interstitial = new InterstitialAd(Home.this);
    // Insert the Ad Unit ID
    interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));

    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    list = new ArrayList<Post_Data>();

    getInfo();

    interstitial.loadAd(adRequest);
    // Prepare an Interstitial Ad Listener
    interstitial.setAdListener(new AdListener() {
        public void onAdLoaded() {
            // Call displayInterstitial() function
            displayInterstitial();
        }
    });
}

private void getInfo() {
    final ProgressDialog dialog = new ProgressDialog(Home.this);
    dialog.setMessage("please wait...");
    dialog.show();
    final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONObject object = new JSONObject(response);
                JSONArray jsonArray = object.getJSONArray("server_response");
                dialog.dismiss();

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    Post_Data data = new Post_Data();
                    data.id = object1.getString("id");
                    data.url = object1.getString("url");
                    data.date = object1.getString("date");
                    data.postImageId = object1.getString("time");
                    data.text = object1.getString("desc");
                    data.eventdate = object1.getString("duration");
                    list.add(data);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            adapter = new YoutTubeAdapter(Home.this, list);
            recyclerView.setAdapter(adapter);
        }
    }, new Response.ErrorListener()

    {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.e(">>>", "error is :" + error.toString());

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> map = new HashMap<>();
            return map;
        }
    };

    RequestQueue queue = Volley.newRequestQueue(this);
    int socketTimeout = 120000;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    request.setRetryPolicy(policy);
    queue.add(request);
}

public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
    if (interstitial.isLoaded()) {
        interstitial.show();
    }
}

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    //super.onBackPressed();
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
        return;
    }
    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "press back again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2000);
    }
    }

Body:
Try replacing the below code on line 112.

 try {
      if (!Home.this.isDestroyed()) {

        if ((dialog != null) && dialog.isShowing()) {
            dialog.dismiss();
        }
} catch (IllegalArgumentException e) {
    Log.e("Custom Tag", "Custom Message", e);
} catch ( Exception e) {
    Log.e("Custom Tag", "Custom Message", e);
} finally {
    dialog = null;
}

General idea is like, check whether your activity is destroyed, and if not destroyed, check whether your dialog is showing or not then dismiss your dialog.


答:
I think you no need to set content view in BaseActivity like below :

```<code>public abstract class MyAppBaseActivity extends AppCompatActivity implements View.OnClickListener {

   @Override
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}
</code>```

And you just extends Activity like below :

```<code>    // for MyCustomActivity1
   public class MyCustomActivity1 extends MyAppBaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void onClick(View view) {
    }
}

    // for MyCustomActivity2

     public class MyCustomActivity2 extends MyAppBaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void onClick(View view) {
    }
}
</code>```

Title: Find Id of View in Child Activity

Body:
I think you no need to set content view in BaseActivity like below :

public abstract class MyAppBaseActivity extends AppCompatActivity implements View.OnClickListener {

   @Override
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

And you just extends Activity like below :

    // for MyCustomActivity1
   public class MyCustomActivity1 extends MyAppBaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void onClick(View view) {
    }
}

    // for MyCustomActivity2

     public class MyCustomActivity2 extends MyAppBaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void onClick(View view) {
    }
}


问:
Starting multiple sessions in PHP
I'm trying to start 3 sessions when the user logs in.

But the only session that is being started is the $email=$_POST['email']

Here is my code.

```<code>if(isset($_POST['log'])) // code to be executed when login button is clicked
{
    $email=$_POST['email'];
    $password=$_POST['Password'];

    $query= "SELECT * FROM student
    WHERE EmailAddress = '$email' AND Password = '$password'";

    $query_run = mysqli_query($con,$query);
    if(mysqli_num_rows($query_run)>0)
    {
        //checks the database where this user exist or not

        $_SESSION['email']=$email;
        $_SESSION['StudentID']=$student;
        $_SESSION['OfferingID']=$Offering;

        header('location: profile.php'); //
    }
    else
    {
        echo '<script type = "text/javascript"> alert("Invalid Credentials or Not yet registered!") </script>';
    }
}
</code>```

答:
```<code>session_start();

if(isset($_POST['log']))
{
    $email=$_POST['email'];
    $password=$_POST['Password'];

    $query= "SELECT * FROM student WHERE EmailAddress = '$email' AND Password = '$password'";

    $query_run = mysqli_query($con,$query);
    if(mysqli_num_rows($query_run)>0)
    {
        $fetch_student_data = mysqli_fetch_assoc($query_run);
        $select_offer_id = mysqli_query($con,"SELECT * FROM Participants where studentID=".$fetch_student_data['StudentID']);
        $fetch_offer_id = mysqli_fetch_assoc($select_offer_id);

        $_SESSION['email']=$email;
        $_SESSION['StudentID']=$fetch_student_data['StudentID'];
        $_SESSION['OfferingID']=$fetch_offer_id['OfferingID'];

        header('location: profile.php'); //
    }
    else
    {
        echo '<script type = "text/javascript"> alert("Invalid Credentials or Not yet registered!") </script>';
    }
}
</code>```

I've edited my answer..

Just check for proper field and table names..

Rest of the code are set

Happy Coding...

Title: Starting multiple sessions in PHP

Body:
I'm trying to start 3 sessions when the user logs in.

But the only session that is being started is the $email=$_POST['email']

Here is my code.

if(isset($_POST['log'])) // code to be executed when login button is clicked
{
    $email=$_POST['email'];
    $password=$_POST['Password'];

    $query= "SELECT * FROM student
    WHERE EmailAddress = '$email' AND Password = '$password'";

    $query_run = mysqli_query($con,$query);
    if(mysqli_num_rows($query_run)>0)
    {
        //checks the database where this user exist or not

        $_SESSION['email']=$email;
        $_SESSION['StudentID']=$student;
        $_SESSION['OfferingID']=$Offering;

        header('location: profile.php'); //
    }
    else
    {
        echo '';
    }
}

Body:
session_start();

if(isset($_POST['log']))
{
    $email=$_POST['email'];
    $password=$_POST['Password'];

    $query= "SELECT * FROM student WHERE EmailAddress = '$email' AND Password = '$password'";

    $query_run = mysqli_query($con,$query);
    if(mysqli_num_rows($query_run)>0)
    {
        $fetch_student_data = mysqli_fetch_assoc($query_run);
        $select_offer_id = mysqli_query($con,"SELECT * FROM Participants where studentID=".$fetch_student_data['StudentID']);
        $fetch_offer_id = mysqli_fetch_assoc($select_offer_id);

        $_SESSION['email']=$email;
        $_SESSION['StudentID']=$fetch_student_data['StudentID'];
        $_SESSION['OfferingID']=$fetch_offer_id['OfferingID'];

        header('location: profile.php'); //
    }
    else
    {
        echo '<script type = "text/javascript"> alert("Invalid Credentials or Not yet registered!") </script>';
    }
}

I've edited my answer..

Just check for proper field and table names..

Rest of the code are set

Happy Coding...


问:
Error while iterating with *ngFor in angular2
I have json response like, Im trying to iterate over json response but it is giving errors

I don't know if angular2 don't suport iteration like this as I'm new to angular2

serive call

```<code>return this.http.post(this.url,params)
        .map(res => res.json())
</code>```

Assigning response to travelGuides

```<code>.subscribe(travelGuides => {
        this.travelGuides = travelGuides.resultData;
}
</code>```

JSON

```<code>{
  "resultCode": 1,
  "resultData": {
    "TravelGuide": [
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      },
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      }
    ],
    "TravelGuide_Img": [
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Radisson Blu ",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1",
        "AltText": "Radisson Blu ",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Radisson Blu Plaza Bangkok",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-62",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-1"
      },
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Text Over Image",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2",
        "AltText": "Text Over Image",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Pullman Bangkok Hotel G",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-63",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-2"
      }
    ]
  }
}
</code>```

here is *ngFor im trying

```<code> <div *ngFor="let travelguide of travelGuides">
   {{travelguide.TravelGuide.Category}}
 </div>
</code>```

but getting this

```<code>Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
</code>```

also tried

```<code> <div *ngFor="let travelguide of travelGuides.TravelGuide">
   {{travelguide.Category}}
 </div>
</code>```

for this getting error

```<code>Cannot read property 'TravelGuide' of undefined
</code>```

答:
Try this    </p>

```<code><div *ngFor="let travelguide of travelGuides?.["TravelGuide"]">
 {{travelguide?.Category}}
 ....
</div>
</code>```

Body:
I have json response like, Im trying to iterate over json response but it is giving errors

I don't know if angular2 don't suport iteration like this as I'm new to angular2

serive call

return this.http.post(this.url,params)
        .map(res => res.json())

Assigning response to travelGuides

.subscribe(travelGuides => {
        this.travelGuides = travelGuides.resultData;
}

JSON

{
  "resultCode": 1,
  "resultData": {
    "TravelGuide": [
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      },
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      }
    ],
    "TravelGuide_Img": [
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Radisson Blu ",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1",
        "AltText": "Radisson Blu ",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Radisson Blu Plaza Bangkok",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-62",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-1"
      },
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Text Over Image",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2",
        "AltText": "Text Over Image",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Pullman Bangkok Hotel G",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-63",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-2"
      }
    ]
  }
}

here is *ngFor im trying

   {{travelguide.TravelGuide.Category}}

but getting this

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

also tried

   {{travelguide.Category}}

for this getting error

Cannot read property 'TravelGuide' of undefined

Body:
Try this

<div *ngFor="let travelguide of travelGuides?.["TravelGuide"]">
 {{travelguide?.Category}}
 ....
</div>


问:
How to reference javadocs to dependencies in Maven's eclipse plugin when javadoc not attached to dependency
I use Eclipse, Maven, and Java in my development. I use Maven to download dependencies (jar files and javadoc when available) and Maven's eclipse plug-in to generate the .project and .classpath files for Eclipse. When the dependency downloaded does not have attached javadoc I manually add a link for the javadoc in the .classpath file so that I can see the javadoc for the dependency in Eclipse. Then when I run Maven's eclipse plugin to regenerate the .classpath file it of course wipes out that change.

Is there a way to configure Maven's eclipse plug-in to automatically add classpath attributes for javadoc when running Maven's eclipse plug-in?

I'm only interested in answers  where the javadoc and/or sources are not provided for the dependency in the maven repository, which is the case most often for me. Using downloadSources and/or downloadJavadocs properties won't help this problem.

答: Would having the sources for the dependency help? You can tell the eclipse plugin to download those (and refer to them in the .classpath) with -DdownloadSources=true

LastEditorDisplayName: John in MD

OwnerDisplayName: matt b


问:
In .net, is there an opposite function to Server.HTMLEncode()?
.Net's Server.HTMLEncode() is the very helpful function that takes an HTML string and replaces special characters with their entity equivalents - "<" becomes &lt ; and so forth.

Is there a (built-in) function that does the reverse?  There doesn't seem to be, and I am incredulous.  While I could certainly write my own (and have in the past) Server.HTMLEncode has all kinds of cool handling for different string encodings and high-level unicode characters that I would really not have crash my hand-rolled decoder in a year's time.

What do other people do when they need the plain HTML back?

Update:
To answer the first batch of questions, I present the MSDN article on the
Server object, which has Encode but no Decode...  I'm as amazed as anyone.

Update2: as several alert readers have pointed out, the docs I was looking at were for classic ASP, not ASP.Net.  Thanks guys, that's an important MSDN safety tip.

答:
You're looking at the wrong docs. Check this out:

http://msdn.microsoft.com/en-us/library/system.web.httpserverutility_methods.aspx
  http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.htmlencode.aspx
  http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.htmldecode.aspx

LastEditorDisplayName: Eddie

OwnerDisplayName: Michael Haren


问:
openwhisk cluster setup and load balancing
I am able to run openwhisk in my local dev machine. I like to extend this to production environment. Is there any concept of openwhisk cluster?. I am not able to find good documentation on this. How auto-load balancing is achieved, etcc..</p>

答:
OpenWhisk is deployed via ansible and as such can be distributed across multiple VMs in a straightforward way.

Check the README on distributed deployments for further information and guidance.