问:
How to provide a generic url to jQuery ajax call from different directory of an ASP.NET application
I created a http handler file in following directory of my application

I am referring this handler from common.js file using jQuery ajax and  common.js file referred in aspx pages StoresSummary.aspx & EmoloyeeProfile.aspx

From EmoloyeeProfile.aspx I am able to call the handler and getting the output, but from StoresSummary.aspx jquery ajax call getting failed.

I know the cause of failure because the path of CommonHandler.ashx file does not map correctly due to location hierarchy of StoresSummary.aspx.

This is a sample code I am posting, the http handler file I need to call from jQuery ajax and aspx pages may exists in different directory of same web application.

How do I give path of CommonHandler.ashx in ajax jQuery call so any location hierarchy of my aspx page can call it.

This is my code

common.js

```<code>function GetMessage(key) {
var message = '';

$.ajax({
    type: 'POST',
    url: '../../Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: { 'MessageKey': key },
    success: onSucess,
    error: OnFailed,
    async: false
});

function onSucess(res) {
    message = res;
}

function OnFailed(res) {
    alert('failed');
}

return message;
}
</code>```

CommonHandler.ashx

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace DemoWebApp.Common.Handlers
{
    /// <summary>
    /// Summary description for CommonHandler
    /// </summary>
    public class CommonHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            string result = javaScriptSerializer.Serialize(GetData(context.Request["MessageKey"]));
            context.Response.ContentType = "text/html";
            context.Response.Write(result);
        }

        private string GetData(string Id)
        {
            return DateTime.Now.ToString(); //just to demostrate
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

}
</code>```

StoresSummary.aspx

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../../../Common/Scripts/common.js"></script>
    <script src="../../../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>

    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
    </div>
    </form>

    <script type="text/javascript">
         function CallMethod() {
             var msg = GetMessage('001');
             alert(msg);
             return false;
         }
    </script>

</body>
</html>
</code>```

EmoloyeeProfile.aspx

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../Common/Scripts/common.js"></script>
    <script src="../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
    </div>
    </form>

    <script type="text/javascript">
        function CallMethod() {
            var msg = GetMessage('001');
            alert(msg);
            return false;
        }
    </script>
</body>
</html>
</code>```

答:
Provide absolute path to the handler. You are providing relative path now. See the ajax url section.</p>

```<code>$.ajax({
    type: 'POST',
    url: '/Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: { 'MessageKey': key },
    success: onSucess,
    error: OnFailed,
    async: false
});
</code>```

Body:
I created a http handler file in following directory of my application

I am referring this handler from common.js file using jQuery ajax and  common.js file referred in aspx pages StoresSummary.aspx & EmoloyeeProfile.aspx

From EmoloyeeProfile.aspx I am able to call the handler and getting the output, but from StoresSummary.aspx jquery ajax call getting failed.

I know the cause of failure because the path of CommonHandler.ashx file does not map correctly due to location hierarchy of StoresSummary.aspx.

This is a sample code I am posting, the http handler file I need to call from jQuery ajax and aspx pages may exists in different directory of same web application.

How do I give path of CommonHandler.ashx in ajax jQuery call so any location hierarchy of my aspx page can call it.

This is my code

common.js

function GetMessage(key) {
var message = '';

$.ajax({
    type: 'POST',
    url: '../../Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: { 'MessageKey': key },
    success: onSucess,
    error: OnFailed,
    async: false
});

function onSucess(res) {
    message = res;
}

function OnFailed(res) {
    alert('failed');
}

return message;
}

CommonHandler.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace DemoWebApp.Common.Handlers
{
    ///
    /// Summary description for CommonHandler
    ///
    public class CommonHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            string result = javaScriptSerializer.Serialize(GetData(context.Request["MessageKey"]));
            context.Response.ContentType = "text/html";
            context.Response.Write(result);
        }

        private string GetData(string Id)
        {
            return DateTime.Now.ToString(); //just to demostrate
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

}

StoresSummary.aspx

    <title></title>

    <form id="form1" runat="server">

        <asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />

    </form>

EmoloyeeProfile.aspx

    <title></title>

    <form id="form1" runat="server">

        <asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />

    </form>

Body:
Provide absolute path to the handler. You are providing relative path now. See the ajax url section.

$.ajax({
    type: 'POST',
    url: '/Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: { 'MessageKey': key },
    success: onSucess,
    error: OnFailed,
    async: false
});


来源: stackexchange

问:
SSRS 2008 - How keep the SAME order enter in the parameter to be reflected in the report
I am working on a SSRS 2008 Report that when entering a list of ITEM numbers in a multiple data type parameter will return the Item Number, UPC, Description, and Item Status.

It works.
But my problem is that it sorts my data in my report. Example.
If I enter the following Item Numbers in the parameter:
ZZZ
DDD
AAA
HHH

My report shows the Data alphabetic as:
AAA
DDD
HHH
ZZZ

I want my data to be displayed in the order of the ITEM Number how I enter them.

I have One Data Set:
SELECT ItemNo, UPC, Description, Status
  FROM Product
    WHERE ItemNo IN (@ITEM)

I have One Parameter:
@ITEM
   Datatype: Text
   Allow multiple values

Please Help!

答:
You need to parse the string into a table and then set an order to the table you've created.  Then you have something to sort by.

First - create a function that you can call in your sp. (the answer to this question gives you exactly what you need)

then, in your query you can use the function just like a table.

```<code>DECLARE @x VARCHAR(100)
SELECT @x = 'ZZZ DDD AAA HHH'

SELECT * FROM f_split(@x,' ') param
WHERE param.seq > 1
ORDER BY param.val
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You need to parse the string into a table and then set an order to the table you've created.  Then you have something to sort by.

First - create a function that you can call in your sp. (the answer to this question gives you exactly what you need)

then, in your query you can use the function just like a table.

DECLARE @x VARCHAR(100)
SELECT @x = 'ZZZ DDD AAA HHH'

SELECT * FROM f_split(@x,' ') param
WHERE param.seq > 1
ORDER BY param.val


问:
set_value() default in CodeIgniter
I've used formigniter to generate a form for CI. http://formigniter.org/

That bit works great. However I want to set a default value for the name field.

The input code looks like this:

```<code><label for="forename">Forename</label>
<?php echo form_error('forename'); ?>
<br /><input id="forename" type="text" name="forename" maxlength="255" value="<?php echo set_value('forename'); ?>"  />
</code>```

and I'd want to add in the first name with $this->session->userdata('current_client');

Will it break my database insert if I just drop it into the set_value function?

Edit:

Sorry I don't think I was very clear there. I want the name field to be automatically filled in with the name from the session cookie.

答:
In CodeIgniter, if generate an error in controller code suppose username unfilled then return an error but the page can refresh, then set_value can set that text box value </p>

```<code><input type="text" name="username" placeholder="Username.." value="<?php echo set_value('username') ?>" class="form-control tx">
</code>```

Title: set_value() default in CodeIgniter

Body:
I've used formigniter to generate a form for CI. http://formigniter.org/

That bit works great. However I want to set a default value for the name field.

The input code looks like this:

Forename
<?php echo form_error('forename'); ?>

<input id="forename" type="text" name="forename" maxlength="255" value="<?php echo set_value('forename'); ?>"  />

and I'd want to add in the first name with $this->session->userdata('current_client');

Will it break my database insert if I just drop it into the set_value function?

Edit:

Sorry I don't think I was very clear there. I want the name field to be automatically filled in with the name from the session cookie.

Body:
In CodeIgniter, if generate an error in controller code suppose username unfilled then return an error but the page can refresh, then set_value can set that text box value

<input type="text" name="username" placeholder="Username.." value="<?php echo set_value('username') ?>" class="form-control tx">

ContentLicense: CC BY-SA 4.0


问:
Download 3000+ Images Using C#?
I have a list of around 3000 image URLs, where I need to download them to my desktop.

I'm a web dev, so naturally wrote a little asp.net c# download method to do this but the obvious problem happened and the page timed out before I got hardly any of them.

Was wondering if anyone else knew of a good, quick and robust way of me looping through all the image URL's and downloading them to a folder?  Open to any suggestions, WinForms, batch file although I'm a novice at both.

Any help greatly appreciated

答:
Write a C# command-line application (or Winforms, if that's your inclination), and use the WebClient class to retrieve the files.

Here are some tutorials:

C# WebClient Tutorial

Using WebClient to Download a File

or, just Google C# WebClient.

You'll either need to provide a list of files to download and loop through the list, issuing a request for each file and saving the result, or issue a request for the index page, parse it using something like HTML Agility Pack to find all of the image tags, and then issue a request for each image, saving the result somewhere on your local drive.

Edit

If you just want to do this once (as in, not as part of an application), mbeckish's answer makes the most sense.

ContentLicense: CC BY-SA 2.5

Title: Download 3000+ Images Using C#?


问:
Expand one row at a time in UITableView Swift
I am working on expanding row when tapped on table view row. My logic is simple I am adding an extra row when tapped on visible row(i.e Expanding) and I delete it i.e remove/collapse the added row when tapped on expanded visible row. Now I have 4 custom cells with separate XIB's i.e A, B, C, D and all of them are contained in one Class. Now the issue goes something like this consider I expand cell A at row 0 and next row is also of type A then the instance goes to the second open cell and when I tap on first open cell it crashes. Now I have 2 solutions first is to show only one cell at a time and collapse all the remaining open cell if any or else second is solve the crash issue that doesn't get the cells instance. I have tried to solve the first issue by creating

let indexPath : IndexPath = IndexPath(row: sender.view!.tag, section: 0)
self.expansionCell = self.myTableView.cellForRow(at: indexPath) as! CustomCell

But still it crashes.

Second one I tried the below

```<code>public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

    if isExpanded == true
    {
        print("Expanded Row",self.expandedIndex)
       //Function to contract Cell which holds old expanded cell index
       self.contractExpandedCell(tableView: tableView, index: self.expandedIndex)
    }

    //Setting Selected index path
    self.selectedIndexPath = indexPath as NSIndexPath

    if myArray[indexPath.row] != nil {
        let cell = myTableView.cellForRow(at: indexPath) as! CustomCell

        // If user clicked last cell, do not try to access cell+1 (out of range)
        if(indexPath.row + 1 >= (myArray.count)) {
            DispatchQueue.main.async {
                cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
            }
            self.isExpanded = true

            //Function to expand Cell
            expandCell(tableView: tableView, index: indexPath.row)

        }
        else {
            // If next cell is not nil, then cell is not expanded
            if(myArray[indexPath.row+1] != nil) {
                DispatchQueue.main.async {
                    cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))

                }
                self.isExpanded = true
                self.expandCell(tableView: tableView, index: indexPath.row)

            } else {
                // Close Cell (remove ExpansionCells)
                DispatchQueue.main.async {
                    cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(180.0 * M_PI))
                }
                self.isExpanded = false
                contractCell(tableView: tableView, index: indexPath.row)

            }
        }
    }

}
 //Function to expand cell
 private func expandCell(tableView: UITableView, index: Int) {
    // Expand Cell (add ExpansionCells)
    if (myArray[index]?.title) != nil {
        myArray.insert(nil, at: index + 1)
        self.expandedIndex = index + 1
        questionAnswerTable.insertRows(at: [IndexPath(row: index + 1, section: 0)], with: .top)
    }
}

//Function to contract cell
private func contractCell(tableView: UITableView, index: Int) {
    if (myArray[index]?.title) != nil {
        myArray.remove(at: index + 1)
        questionAnswerTable.deleteRows(at: [IndexPath(row: index + 1, section: 0 )], with: .top)
    }

}
</code>```

Even this doesn't work smoothly as when a row is added the row count changes and if I try to expand the next cell it opens the third one.

Any one solution will work.
Please help guys. TIA

答:
Add

var  currentExpandIndexpath : NSIndexpath?

and in didSelectRowAt  change

```<code>expandCell(tableView: tableView, index: indexPath.row)
</code>```

with

```<code>if currentExpandIndexpath == nil{
   currentExpandIndexpath = indexpath
}
if currentExpandIndexpath == indexpath{
   // do nothing
}else{
// contract expand cell before expand new cell
    contractCell(tableView: tableView, index: currentExpandIndexpath.row)
    self.expandCell(tableView: tableView, index: indexPath.row)
// update current expand cell
    currentExpandIndexpath = indexpath
}
</code>```

it 's just solution. Not correct code.

Body:
I am working on expanding row when tapped on table view row. My logic is simple I am adding an extra row when tapped on visible row(i.e Expanding) and I delete it i.e remove/collapse the added row when tapped on expanded visible row. Now I have 4 custom cells with separate XIB's i.e A, B, C, D and all of them are contained in one Class. Now the issue goes something like this consider I expand cell A at row 0 and next row is also of type A then the instance goes to the second open cell and when I tap on first open cell it crashes. Now I have 2 solutions first is to show only one cell at a time and collapse all the remaining open cell if any or else second is solve the crash issue that doesn't get the cells instance. I have tried to solve the first issue by creating

let indexPath : IndexPath = IndexPath(row: sender.view!.tag, section: 0)
self.expansionCell = self.myTableView.cellForRow(at: indexPath) as! CustomCell

But still it crashes.

Second one I tried the below

public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

    if isExpanded == true
    {
        print("Expanded Row",self.expandedIndex)
       //Function to contract Cell which holds old expanded cell index
       self.contractExpandedCell(tableView: tableView, index: self.expandedIndex)
    }

    //Setting Selected index path
    self.selectedIndexPath = indexPath as NSIndexPath

    if myArray[indexPath.row] != nil {
        let cell = myTableView.cellForRow(at: indexPath) as! CustomCell

        // If user clicked last cell, do not try to access cell+1 (out of range)
        if(indexPath.row + 1 >= (myArray.count)) {
            DispatchQueue.main.async {
                cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
            }
            self.isExpanded = true

            //Function to expand Cell
            expandCell(tableView: tableView, index: indexPath.row)

        }
        else {
            // If next cell is not nil, then cell is not expanded
            if(myArray[indexPath.row+1] != nil) {
                DispatchQueue.main.async {
                    cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))

                }
                self.isExpanded = true
                self.expandCell(tableView: tableView, index: indexPath.row)

            } else {
                // Close Cell (remove ExpansionCells)
                DispatchQueue.main.async {
                    cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(180.0 * M_PI))
                }
                self.isExpanded = false
                contractCell(tableView: tableView, index: indexPath.row)

            }
        }
    }

}
 //Function to expand cell
 private func expandCell(tableView: UITableView, index: Int) {
    // Expand Cell (add ExpansionCells)
    if (myArray[index]?.title) != nil {
        myArray.insert(nil, at: index + 1)
        self.expandedIndex = index + 1
        questionAnswerTable.insertRows(at: [IndexPath(row: index + 1, section: 0)], with: .top)
    }
}

//Function to contract cell
private func contractCell(tableView: UITableView, index: Int) {
    if (myArray[index]?.title) != nil {
        myArray.remove(at: index + 1)
        questionAnswerTable.deleteRows(at: [IndexPath(row: index + 1, section: 0 )], with: .top)
    }

}

Even this doesn't work smoothly as when a row is added the row count changes and if I try to expand the next cell it opens the third one.

Any one solution will work.
Please help guys. TIA

Body:
Add

var  currentExpandIndexpath : NSIndexpath?

and in didSelectRowAt  change

expandCell(tableView: tableView, index: indexPath.row)

with

if currentExpandIndexpath == nil{
   currentExpandIndexpath = indexpath
}
if currentExpandIndexpath == indexpath{
   // do nothing
}else{
// contract expand cell before expand new cell
    contractCell(tableView: tableView, index: currentExpandIndexpath.row)
    self.expandCell(tableView: tableView, index: indexPath.row)
// update current expand cell
    currentExpandIndexpath = indexpath
}

it 's just solution. Not correct code.


问:
Unable to ssh to master node in mesos local cluster installed system
I am a newbie to Mesos. I have installed a DCOS cluster locally in one system (Centos 7).

Everything went up properly and I am able to access the GUI of DCOS  but when I am trying to connect through CLI, it is asking me for password.

I have not been prompted for any kind of password during local installation through vagrant.

But when I issue the following command:

```<code>[root@blade7 dcos-vagrant]# dcos node ssh --master-proxy --leader

Running `ssh -A -t core@192.168.65.90 ssh -A -t core@192.168.65.90 `
core@192.168.65.90's password:
Permission denied, please try again.
core@192.168.65.90's password:
</code>```

I don’t know the password to be given.
Kindly help me in resolving this issue

答: The command shows that you are trying to login to the server using the userid "core". If you do not know the password of user "core", I suggest reset "core" user password and try it again.</p>

Body:
I am a newbie to Mesos. I have installed a DCOS cluster locally in one system (Centos 7).

Everything went up properly and I am able to access the GUI of DCOS  but when I am trying to connect through CLI, it is asking me for password.

I have not been prompted for any kind of password during local installation through vagrant.

But when I issue the following command:

[root@blade7 dcos-vagrant]# dcos node ssh --master-proxy --leader

Running `ssh -A -t core@192.168.65.90 ssh -A -t core@192.168.65.90 `
core@192.168.65.90's password:
Permission denied, please try again.
core@192.168.65.90's password:

I don’t know the password to be given.
Kindly help me in resolving this issue


问:
How to make div/popup to show once in the browser. Plain vanilla script
// JavaScript Document

I am trying to do when the user goes to the browser it only shows up once. I know it is something to do with local storage but all I see is jquery when I search something similar.

I really want to know how to do it in plain javascript no jquery.

```<code>(function() {
    "use strict";
    console.log("SEAF Fired");

    function popup (hideOrshow){
        if (hideOrshow == 'hide')
        document.getElementById("popupBox").style.display="none";
        else document.getElementById("popupBox").style.display="block";
    }

    window.onload = function (){
        setTimeout(function(){
            popup('show');
        },3000);

        document.getElementById('close').onclick=function(){
            document.getElementById('popupBox').style.display="none"
        };
    }
})();
</code>```

答:
You can use Cookie to do this. I've override value of hideOrshow in popup method by using Cookie functionality. If once show the popup and cookie is set then popup will not show next time.

Please check below code:

```<code>(function() {
        "use strict";
        console.log("SEAF Fired");

        function setCookie(cname, cvalue, exdays) {
                var d = new Date();
                d.setTime(d.getTime() + (exdays*24*60*60*1000));
                var expires = "expires="+ d.toUTCString();
                document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
        }

        function getCookie(cname) {
                var name = cname + "=";
                var decodedCookie = decodeURIComponent(document.cookie);
                var ca = decodedCookie.split(';');
                for(var i = 0; i <ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') {
                                c = c.substring(1);
                        }
                        if (c.indexOf(name) == 0) {
                                return c.substring(name.length, c.length);
                        }
                }
                return "";
        }

        function popup (hideOrshow){
                hideOrshow = getCookie("hideOrshow");
                if(hideOrshow == ""){
                    hideOrshow = "hide";
                    setCookie("hideOrshow", hideOrshow, 365);
                }
                if (hideOrshow == 'hide')
                document.getElementById("popupBox").style.display="none";
                else document.getElementById("popupBox").style.display="block";
        }

        window.onload = function (){
                setTimeout(function(){
                        popup('show');
                },3000);

                document.getElementById('close').onclick=function(){
                        document.getElementById('popupBox').style.display="none"
                };
        }
})();
</code>```

Body:
// JavaScript Document

I am trying to do when the user goes to the browser it only shows up once. I know it is something to do with local storage but all I see is jquery when I search something similar.

I really want to know how to do it in plain javascript no jquery.

(function() {
    "use strict";
    console.log("SEAF Fired");

    function popup (hideOrshow){
        if (hideOrshow == 'hide')
        document.getElementById("popupBox").style.display="none";
        else document.getElementById("popupBox").style.display="block";
    }

    window.onload = function (){
        setTimeout(function(){
            popup('show');
        },3000);

        document.getElementById('close').onclick=function(){
            document.getElementById('popupBox').style.display="none"
        };
    }
})();

Body:
You can use Cookie to do this. I've override value of hideOrshow in popup method by using Cookie functionality. If once show the popup and cookie is set then popup will not show next time.

Please check below code:

(function() {
        "use strict";
        console.log("SEAF Fired");

        function setCookie(cname, cvalue, exdays) {
                var d = new Date();
                d.setTime(d.getTime() + (exdays*24*60*60*1000));
                var expires = "expires="+ d.toUTCString();
                document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
        }

        function getCookie(cname) {
                var name = cname + "=";
                var decodedCookie = decodeURIComponent(document.cookie);
                var ca = decodedCookie.split(';');
                for(var i = 0; i <ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') {
                                c = c.substring(1);
                        }
                        if (c.indexOf(name) == 0) {
                                return c.substring(name.length, c.length);
                        }
                }
                return "";
        }

        function popup (hideOrshow){
                hideOrshow = getCookie("hideOrshow");
                if(hideOrshow == ""){
                    hideOrshow = "hide";
                    setCookie("hideOrshow", hideOrshow, 365);
                }
                if (hideOrshow == 'hide')
                document.getElementById("popupBox").style.display="none";
                else document.getElementById("popupBox").style.display="block";
        }

        window.onload = function (){
                setTimeout(function(){
                        popup('show');
                },3000);

                document.getElementById('close').onclick=function(){
                        document.getElementById('popupBox').style.display="none"
                };
        }
})();


问:
Wikitude Passing value from java to JavaScript to use it in AR.RelativeLocation
I passed an integer from java to javascript, and now I want to use the value to change the altitude of an object.

I added a to RelativeLoction var location = new AR.RelativeLocation(null, 8, 0, a);

The problem is it ignores the value that I passed which is 10 and take a as 0. I know that the value passed correctly from this var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a; which shows Altitude: 10.

Javascript code:

```<code>var World = {
    loaded: false,
    rotating: false,

    init: function initFn() {
        this.createModelAtLocation();
    },

    createModelAtLocation: function createModelAtLocationFn() {

        /*
            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        var location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};

    var a = 0;
    var altitude = 0;

       function setAltitude(altitude){
               a = altitude;
           }

World.init();
</code>```

Edit after Alex's answer:

Now the object and the altitude are not showing not sure if I'm missing something

```<code>var World = {
    location: null,
    loaded: false,
    rotating: false,

    init: function initFn() {
        this.createModelAtLocation();
    },

    createModelAtLocation: function createModelAtLocationFn() {

        /*

            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        //var location = new AR.RelativeLocation(null, 8, 0, a);
        World.location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};
    var a = 0;
    var altitude = 0;

       function setAltitude(altitude){
               //a = altitude;
               //World.location.altitudeDelta  = altitude;
               World.location.a = altitude;
           }

World.init();
</code>```

答:
I managed to fix the problem here is the answer if anyone is interested</p>

```<code>var World = {
    //location: null,
    loaded: false,
    rotating: false,

    loadValuesFromJava: function loadValuesFromJavaFn(Altitude){
        a = Altitude;
        this.createModelAtLocation();
    },

    /*init: function initFn() {
        this.createModelAtLocation();
    },*/

    createModelAtLocation: function createModelAtLocationFn() {

        /*

            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        var location = new AR.RelativeLocation(null, 8, 0, a);
        //World.location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};

var a = 0;
var Altitude = 0;
    /*var a = 0;
    var altitude = 0;

      function setAltitude(altitude){
               a = altitude;
               //World.location.altitudeDelta  = altitude;
               //World.location.altitudeDelta = altitude;
           }*/

//World.init();
//World.loadValuesFromJava();
</code>```

Body:
I passed an integer from java to javascript, and now I want to use the value to change the altitude of an object.

I added a to RelativeLoction var location = new AR.RelativeLocation(null, 8, 0, a);

The problem is it ignores the value that I passed which is 10 and take a as 0. I know that the value passed correctly from this var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a; which shows Altitude: 10.

Javascript code:

var World = {
    loaded: false,
    rotating: false,

    init: function initFn() {
        this.createModelAtLocation();
    },

    createModelAtLocation: function createModelAtLocationFn() {

        /*
            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        var location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};

    var a = 0;
    var altitude = 0;

       function setAltitude(altitude){
               a = altitude;
           }

World.init();

Edit after Alex's answer:

Now the object and the altitude are not showing not sure if I'm missing something

var World = {
    location: null,
    loaded: false,
    rotating: false,

    init: function initFn() {
        this.createModelAtLocation();
    },

    createModelAtLocation: function createModelAtLocationFn() {

        /*

            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        //var location = new AR.RelativeLocation(null, 8, 0, a);
        World.location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};
    var a = 0;
    var altitude = 0;

       function setAltitude(altitude){
               //a = altitude;
               //World.location.altitudeDelta  = altitude;
               World.location.a = altitude;
           }

World.init();

Body:
I managed to fix the problem here is the answer if anyone is interested

var World = {
    //location: null,
    loaded: false,
    rotating: false,

    loadValuesFromJava: function loadValuesFromJavaFn(Altitude){
        a = Altitude;
        this.createModelAtLocation();
    },

    /*init: function initFn() {
        this.createModelAtLocation();
    },*/

    createModelAtLocation: function createModelAtLocationFn() {

        /*

            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        var location = new AR.RelativeLocation(null, 8, 0, a);
        //World.location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};

var a = 0;
var Altitude = 0;
    /*var a = 0;
    var altitude = 0;

      function setAltitude(altitude){
               a = altitude;
               //World.location.altitudeDelta  = altitude;
               //World.location.altitudeDelta = altitude;
           }*/

//World.init();
//World.loadValuesFromJava();


问:
Java : Cast String Array to an Object
I'm trying to cast String Array to an Object.

```<code>Object string="[FIBER,CABLE]";
String[] strArray = (String[])string;
</code>```

I got ClassCastException.

I can get by splitting str by slash and comma

```<code>Object string="[FIBER,CABLE]";
String[] strArray = ((String)string).split("[,\\]\\[]");

for(int i=1;i<strArray.length;i++)
    System.out.println(strArray[i]);
</code>```

I wanted to know "Is there any better way to do it?"

答:
Actually, what you currently have has an empty string in the 1st array position.

I would do this instead:

```<code>Object string = "[FIBER,CABLE]";

// cleaner to just cast it in a separate statement.
String s = (String) string;

// replace the "[" and "]" with "" and split on ","
String[] strArray = s.replaceAll("[\\[\\]]", "").split(",");

// from i = 0 and not i = 1
for (int i = 0; i < strArray.length; i++)
    System.out.println(strArray[i]);
</code>```

Output:

```<code>FIBER
CABLE
</code>```

Title: Java : Cast String Array to an Object

Body:
I'm trying to cast String Array to an Object.

Object string="[FIBER,CABLE]";
String[] strArray = (String[])string;

I got ClassCastException.

I can get by splitting str by slash and comma

Object string="[FIBER,CABLE]";
String[] strArray = ((String)string).split("[,\\]\\[]");

for(int i=1;i<strArray.length;i++)
    System.out.println(strArray[i]);

I wanted to know "Is there any better way to do it?"

Body:
Actually, what you currently have has an empty string in the 1st array position.

I would do this instead:

Object string = "[FIBER,CABLE]";

// cleaner to just cast it in a separate statement.
String s = (String) string;

// replace the "[" and "]" with "" and split on ","
String[] strArray = s.replaceAll("[\\[\\]]", "").split(",");

// from i = 0 and not i = 1
for (int i = 0; i < strArray.length; i++)
    System.out.println(strArray[i]);

Output:

FIBER
CABLE


问:
What kind of vulnerabilities involve the attacker sending "php://input"?
My site was just bombarded by an attacker trying to pass "php://input" into any GET/POST variable they could think of. If this is trying to take advantage of a vulnerability, I'm unaware of it. What could this user be trying to exploit?</p>

答:
Perhaps anyone who runs an eval on php input?

```<code>$data = file_get_contents('php://input');
eval($data);
</code>```

I have not seen this personally but I bet someones done it at some point thinking it could be safe.

Body:
Perhaps anyone who runs an eval on php input?

$data = file_get_contents('php://input');
eval($data);

I have not seen this personally but I bet someones done it at some point thinking it could be safe.


问:
AngularJS disable double click
I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.

```<code><div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
    <a class="btn btn-danger" ng-click="vm.markDelivered()" ng-dblclick="return" ng-disabled="flag">{{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}</a>
</div>
</code>```

I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.

答:
Even I had the same issue,And solved using this approach.

```<code><div class="col-sm-4 form-group pull-right">
   <input type="submit" name="Submit" class="btn btn-primary"
    value="Submit" data-ng-disabled="myForm.$invalid"
    ng-click="myForm.$invalid=true;vm.markDelivered()" />
</div>
</code>```

So on first click myForm.$invalid=true will be set and button will be disabled. SO you will not have multiple calls to your server side code.

Title: AngularJS disable double click

Body:
I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.

    <button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
    {{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}

I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.

Body:
Even I had the same issue,And solved using this approach.

<div class="col-sm-4 form-group pull-right">
   <input type="submit" name="Submit" class="btn btn-primary"
    value="Submit" data-ng-disabled="myForm.$invalid"
    ng-click="myForm.$invalid=true;vm.markDelivered()" />
</div>

So on first click myForm.$invalid=true will be set and button will be disabled. SO you will not have multiple calls to your server side code.


问:
Input a CSV file into TensorFlow to construct Neural Network
The following is my input format of CVS file

```<code>Feature1, Feature2, ... Feature5, Label
Feature1, Feature2, ... Feature5, Label
</code>```

According the tutorial on the Internet, I modified the input file from MINST database to my CVS file, but I got the error message.

```<code>File "test5.py", line 95, in <module>
y: batch_y})
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 767, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 938, in _run
np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
File "/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py", line
531, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.
</code>```

I am wondering what i am doing wrong

The following is my code

```<code>import tensorflow as tf

filename_queue = tf.train.string_input_producer(["file0.csv"])

line_reader = tf.TextLineReader(skip_header_lines=1)
_, csv_row = line_reader.read(filename_queue)

# Type information and column names based on the decoded CSV.
[[0.0],[0.0],[0.0],[0.0],[0.0],[""]]

record_defaults = [[0.0],[0.0],[0.0],[0.0],[0.0],[0]]
in1,in2,in3,in4,in5,out = tf.decode_csv(csv_row, record_defaults=record_defaults)

# Turn the features back into a tensor.
features = tf.stack([in1,in2,in3,in4,in5])

# Parameters
learning_rate = 0.001
training_epochs = 5
batch_size = 3
display_step = 1
num_examples= 15

# Network Parameters
n_hidden_1 = 6 # 1st layer number of features
n_hidden_2 = 6 # 2nd layer number of features
n_input = 5 # MNIST data input (img shape: 28*28)
n_classes = 2 # MNIST total classes (0-9 digits)

# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])

# Create model
def multilayer_perceptron(x, weights, biases):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Hidden layer with RELU activation
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # Output layer with linear activation
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

# Construct model
pred = multilayer_perceptron(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

with tf.Session() as sess:
    #tf.initialize_all_variables().run()
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(num_examples/batch_size)
        # Loop over all batches

        for i in range(total_batch):
            batch_x = []
            batch_y = []
            for iteration in range(1, batch_size):
                example, label = sess.run([features, out])
                batch_x.append(example)
                #batch_y.append(label)
                onehot_labels = tf.one_hot(indices=tf.cast(label, tf.int32), depth=2)
                batch_y.append(onehot_labels)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print ("Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(avg_cost))
    print ("Optimization Finished!")
    coord.request_stop()
    coord.join(threads)
</code>```

答:
You cannot feed tensors into placeholder variables. You have two options:

Change the shape of the tensor y variable to accept labels. Then call tf.one_hot on that tensor:

```<code>y = tf.placeholder(tf.int32, [None])
y_one_hot = tf.one_hot(y, 2)
...
# batch_labels is a list of integer labels
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_labels})
</code>```

Keep the tensor y as is and get the one hot feed values using a different class (numpy array in this example):

```<code># batch_labels is a list of integer labels
batch_labels_one_hot = np.zeros((batch_size, 2))
batch_labels_one_hot[list(range(batch_size)), batch_labels] = 1
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_labels_one_hot})
</code>```

Body:
The following is my input format of CVS file

Feature1, Feature2, ... Feature5, Label
Feature1, Feature2, ... Feature5, Label

According the tutorial on the Internet, I modified the input file from MINST database to my CVS file, but I got the error message.

File "test5.py", line 95, in <module>
y: batch_y})
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 767, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 938, in _run
np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
File "/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py", line
531, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

I am wondering what i am doing wrong

The following is my code

import tensorflow as tf

filename_queue = tf.train.string_input_producer(["file0.csv"])

line_reader = tf.TextLineReader(skip_header_lines=1)
_, csv_row = line_reader.read(filename_queue)

# Type information and column names based on the decoded CSV.
[[0.0],[0.0],[0.0],[0.0],[0.0],[""]]

record_defaults = [[0.0],[0.0],[0.0],[0.0],[0.0],[0]]
in1,in2,in3,in4,in5,out = tf.decode_csv(csv_row, record_defaults=record_defaults)

# Turn the features back into a tensor.
features = tf.stack([in1,in2,in3,in4,in5])

# Parameters
learning_rate = 0.001
training_epochs = 5
batch_size = 3
display_step = 1
num_examples= 15

# Network Parameters
n_hidden_1 = 6 # 1st layer number of features
n_hidden_2 = 6 # 2nd layer number of features
n_input = 5 # MNIST data input (img shape: 28*28)
n_classes = 2 # MNIST total classes (0-9 digits)

# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])

# Create model
def multilayer_perceptron(x, weights, biases):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Hidden layer with RELU activation
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # Output layer with linear activation
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

# Construct model
pred = multilayer_perceptron(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

with tf.Session() as sess:
    #tf.initialize_all_variables().run()
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(num_examples/batch_size)
        # Loop over all batches

        for i in range(total_batch):
            batch_x = []
            batch_y = []
            for iteration in range(1, batch_size):
                example, label = sess.run([features, out])
                batch_x.append(example)
                #batch_y.append(label)
                onehot_labels = tf.one_hot(indices=tf.cast(label, tf.int32), depth=2)
                batch_y.append(onehot_labels)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print ("Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(avg_cost))
    print ("Optimization Finished!")
    coord.request_stop()
    coord.join(threads)

Body:
You cannot feed tensors into placeholder variables. You have two options:

Change the shape of the tensor y variable to accept labels. Then call tf.one_hot on that tensor:

y = tf.placeholder(tf.int32, [None])
y_one_hot = tf.one_hot(y, 2)
...
# batch_labels is a list of integer labels
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_labels})

Keep the tensor y as is and get the one hot feed values using a different class (numpy array in this example):

# batch_labels is a list of integer labels
batch_labels_one_hot = np.zeros((batch_size, 2))
batch_labels_one_hot[list(range(batch_size)), batch_labels] = 1
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_labels_one_hot})


问:
How to implement FFT algorithm in python?
I am trying to implement a function in python3, but I couldn't figure out the error in the argument.Following is my code and the error:

```<code>def FFT1(A,n,w):

    if n==1:
        return A
    AEven=[]
    for k in range(0,n,2):
        key1= A[k]
        AEven.append(key1)
    AOdd=[]
    for l in range(1,n,2):
        key2=A[l]
        AOdd.append(key2)
    VE=FFT1(AEven, n/2, w**2)
    VO=FFT1(AOdd, n/2, w**2)
    mult= complex(-1,1)
    V=[]*n
    for i in range(0,(n-2)/2):
        V[i]=VE[i]+(w**mult)*VO[i]
        V[n/2+i]=VE[i]-(w**mult)*VO[i]
    return V

FFT1(coeff, degree, rootunit)
</code>```

causes:

```<code>Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    FFT1(coeff, degree, rootunit)
  File "<pyshell#44>", line 12, in FFT1
    VE=FFT1(AEven, n/2, w**2)
  File "<pyshell#44>", line 5, in FFT1
    for k in range(0,n,2):
TypeError: 'float' object cannot be interpreted as an integer
</code>```

答:
Since various aspects of your FFT routine require n to be an integer, you should either assert that it is an integer, or coerce it to an integer.  My suggestion to to coerce to int like:

```<code>def FFT1(A,n,w):
    n = int(n)

    if n==1:
    ....
</code>```

Body:
I am trying to implement a function in python3, but I couldn't figure out the error in the argument.Following is my code and the error:

def FFT1(A,n,w):

    if n==1:
        return A
    AEven=[]
    for k in range(0,n,2):
        key1= A[k]
        AEven.append(key1)
    AOdd=[]
    for l in range(1,n,2):
        key2=A[l]
        AOdd.append(key2)
    VE=FFT1(AEven, n/2, w**2)
    VO=FFT1(AOdd, n/2, w**2)
    mult= complex(-1,1)
    V=[]*n
    for i in range(0,(n-2)/2):
        V[i]=VE[i]+(w**mult)*VO[i]
        V[n/2+i]=VE[i]-(w**mult)*VO[i]
    return V

FFT1(coeff, degree, rootunit)

causes:

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    FFT1(coeff, degree, rootunit)
  File "<pyshell#44>", line 12, in FFT1
    VE=FFT1(AEven, n/2, w**2)
  File "<pyshell#44>", line 5, in FFT1
    for k in range(0,n,2):
TypeError: 'float' object cannot be interpreted as an integer

Body:
Since various aspects of your FFT routine require n to be an integer, you should either assert that it is an integer, or coerce it to an integer.  My suggestion to to coerce to int like:

def FFT1(A,n,w):
    n = int(n)

    if n==1:
    ....


答:
You should remove the leading [ and the trailing ] before you splt the string.

```<code>Object obj = "[FIBER,CABLE]";

String str = (String) obj;
if (! str.startsWith("[") || ! str.endsWith("]"))
    throw new IllegalArgumentException("Bad data: " + str);
String[] strArray = str.substring(1, str.length() - 1).split(",", -1);

for (String s : strArray)
    System.out.println(s);
</code>```

Output

FIBER
CABLE
```

Title: Java : Cast String Array to an Object

Body:
You should remove the leading [ and the trailing ] before you splt the string.

Object obj = "[FIBER,CABLE]";

String str = (String) obj;
if (! str.startsWith("[") || ! str.endsWith("]"))
    throw new IllegalArgumentException("Bad data: " + str);
String[] strArray = str.substring(1, str.length() - 1).split(",", -1);

for (String s : strArray)
    System.out.println(s);

Output

FIBER
CABLE


问:
Form Input Element Not Working
I am making a small JSP page with a form in it. However, the "Full Name" text input field is not allowing me to type text into it? Does anyone know what the cause of the problem is? The code for my JSP page is below.</p>

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Billing Workflow Tracker</title>
<style>
    #formTitle {position: absolute;
    left: 10px;
    top: 10px;}
    #formPart1 {position: absolute;
    left: 10px;
    top: 80px;
    opacity: 1;
    transition: opacity 1s;}
    #formPart2 {position: absolute;
    left: 10px;
    top: 80px;
    opacity: 0;
    transition: opacity 1s;}
    #buttonPart1 {position: absolute;
    left: 10px;
    top: 180px;}
    #buttonPart2 {position: absolute;
    left: 70px;
    top: 180px;}
</style>
</head>
<body>
    <script>
        function showFormPart1()
        {
            document.getElementById("formPart1").style.opacity = 1;
            document.getElementById("formPart2").style.opacity = 0;
        }

        function showFormPart2()
        {
            document.getElementById("formPart1").style.opacity = 0;
            document.getElementById("formPart2").style.opacity = 1;
        }
    </script>
    <h1 id="formTitle">Billing Workflow Tracker</h1>
    <form id="formPart1">
        <label>Full Name <input type="text" name="name" id="name" /></label>
        <label>E-mail <input type="email" name="email" id="email" /></label>
    </form>
    <form id="formPart2">
        <p>Reason for Billing Test</p>
        <input type="radio" name="reasons" id="reason1" value="1" />
        <label for="reason1">New Customer</label>
        <input type="radio" name="reasons" id="reason2" value="2" />
        <label for="reason2">Migration</label>
        <input type="radio" name="reasons" id="reason3" value="3" />
        <label for="reason3">Other</label>
    </form>
    <button id="buttonPart1" onclick="showFormPart1()">Part 1</button>
    <button id="buttonPart2" onclick="showFormPart2()">Part 2</button>
</body>
</html>
</code>```

答:
How about using "display" instead of "opacity"?
For example:</p>

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Billing Workflow Tracker</title>
<style>
    #formTitle {position: absolute;
    left: 10px;
    top: 10px;}
    #formPart1 {position: absolute;
    left: 10px;
    top: 80px;
    display: block;}
    #formPart2 {position: absolute;
    left: 10px;
    top: 80px;
    display: none;}
    #buttonPart1 {position: absolute;
    left: 10px;
    top: 180px;}
    #buttonPart2 {position: absolute;
    left: 70px;
    top: 180px;}
</style>
</head>
<body>
    <script>
        function showFormPart1()
        {
            document.getElementById("formPart1").style.display = "block";
            document.getElementById("formPart2").style.display = "none";
        }

        function showFormPart2()
        {
            document.getElementById("formPart1").style.display = "none";
            document.getElementById("formPart2").style.display = "block";
        }
    </script>
    <h1 id="formTitle">Billing Workflow Tracker</h1>
    <form id="formPart1">
        <label>Full Name <input type="text" name="name" id="name" /></label>
        <label>E-mail <input type="email" name="email" id="email" /></label>
    </form>
    <form id="formPart2">
        <p>Reason for Billing Test</p>
        <input type="radio" name="reasons" id="reason1" value="1" />
        <label for="reason1">New Customer</label>
        <input type="radio" name="reasons" id="reason2" value="2" />
        <label for="reason2">Migration</label>
        <input type="radio" name="reasons" id="reason3" value="3" />
        <label for="reason3">Other</label>
    </form>
    <button id="buttonPart1" onclick="showFormPart1()">Part 1</button>
    <button id="buttonPart2" onclick="showFormPart2()">Part 2</button>
</body>
</html>
</code>```

Title: Form Input Element Not Working

Body:
I am making a small JSP page with a form in it. However, the "Full Name" text input field is not allowing me to type text into it? Does anyone know what the cause of the problem is? The code for my JSP page is below.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Billing Workflow Tracker</title>

Billing Workflow Tracker

    <form id="formPart1">
        Full Name <input type="text" name="name" id="name" />
        E-mail <input type="email" name="email" id="email" />
    </form>
    <form id="formPart2">

Reason for Billing Test

        <input type="radio" name="reasons" id="reason1" value="1" />
        New Customer
        <input type="radio" name="reasons" id="reason2" value="2" />
        Migration
        <input type="radio" name="reasons" id="reason3" value="3" />
        Other
    </form>
    <button id="buttonPart1" onclick="showFormPart1()">Part 1</button>
    <button id="buttonPart2" onclick="showFormPart2()">Part 2</button>

Body:
How about using "display" instead of "opacity"?
For example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Billing Workflow Tracker</title>
<style>
    #formTitle {position: absolute;
    left: 10px;
    top: 10px;}
    #formPart1 {position: absolute;
    left: 10px;
    top: 80px;
    display: block;}
    #formPart2 {position: absolute;
    left: 10px;
    top: 80px;
    display: none;}
    #buttonPart1 {position: absolute;
    left: 10px;
    top: 180px;}
    #buttonPart2 {position: absolute;
    left: 70px;
    top: 180px;}
</style>
</head>
<body>
    <script>
        function showFormPart1()
        {
            document.getElementById("formPart1").style.display = "block";
            document.getElementById("formPart2").style.display = "none";
        }

        function showFormPart2()
        {
            document.getElementById("formPart1").style.display = "none";
            document.getElementById("formPart2").style.display = "block";
        }
    </script>
    <h1 id="formTitle">Billing Workflow Tracker</h1>
    <form id="formPart1">
        <label>Full Name <input type="text" name="name" id="name" /></label>
        <label>E-mail <input type="email" name="email" id="email" /></label>
    </form>
    <form id="formPart2">
        <p>Reason for Billing Test</p>
        <input type="radio" name="reasons" id="reason1" value="1" />
        <label for="reason1">New Customer</label>
        <input type="radio" name="reasons" id="reason2" value="2" />
        <label for="reason2">Migration</label>
        <input type="radio" name="reasons" id="reason3" value="3" />
        <label for="reason3">Other</label>
    </form>
    <button id="buttonPart1" onclick="showFormPart1()">Part 1</button>
    <button id="buttonPart2" onclick="showFormPart2()">Part 2</button>
</body>
</html>


答:
It's a simple logic. Get an variable to store selected indexpath.

When any cell tapped on DidSelectRowAtIndexPath store selected indeapth to that variable and reload table.

When table reload on height row method check for the indexpath. if indexpath is equal to the indexpath store in variable then that row should have larger size then other.

It is just simple logic

Title: Expand one row at a time in UITableView Swift

Body:
I am working on expanding row when tapped on table view row. My logic is simple I am adding an extra row when tapped on visible row(i.e Expanding) and I delete it i.e remove/collapse the added row when tapped on expanded visible row. Now I have 4 custom cells with separate XIB's i.e A, B, C, D and all of them are contained in one Class. Now the issue goes something like this consider I expand cell A at row 0 and next row is also of type A then the instance goes to the second open cell and when I tap on first open cell it crashes. Now I have 2 solutions first is to show only one cell at a time and collapse all the remaining open cell if any or else second is solve the crash issue that doesn't get the cells instance. I have tried to solve the first issue by creating

let indexPath : IndexPath = IndexPath(row: sender.view!.tag, section: 0)
self.expansionCell = self.myTableView.cellForRow(at: indexPath) as! CustomCell

But still it crashes.

Second one I tried the below

public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

    if isExpanded == true
    {
        print("Expanded Row",self.expandedIndex)
       //Function to contract Cell which holds old expanded cell index
       self.contractExpandedCell(tableView: tableView, index: self.expandedIndex)
    }

    //Setting Selected index path
    self.selectedIndexPath = indexPath as NSIndexPath

    if myArray[indexPath.row] != nil {
        let cell = myTableView.cellForRow(at: indexPath) as! CustomCell

        // If user clicked last cell, do not try to access cell+1 (out of range)
        if(indexPath.row + 1 >= (myArray.count)) {
            DispatchQueue.main.async {
                cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
            }
            self.isExpanded = true

            //Function to expand Cell
            expandCell(tableView: tableView, index: indexPath.row)

        }
        else {
            // If next cell is not nil, then cell is not expanded
            if(myArray[indexPath.row+1] != nil) {
                DispatchQueue.main.async {
                    cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))

                }
                self.isExpanded = true
                self.expandCell(tableView: tableView, index: indexPath.row)

            } else {
                // Close Cell (remove ExpansionCells)
                DispatchQueue.main.async {
                    cell.forwardArrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(180.0 * M_PI))
                }
                self.isExpanded = false
                contractCell(tableView: tableView, index: indexPath.row)

            }
        }
    }

}
 //Function to expand cell
 private func expandCell(tableView: UITableView, index: Int) {
    // Expand Cell (add ExpansionCells)
    if (myArray[index]?.title) != nil {
        myArray.insert(nil, at: index + 1)
        self.expandedIndex = index + 1
        questionAnswerTable.insertRows(at: [IndexPath(row: index + 1, section: 0)], with: .top)
    }
}

//Function to contract cell
private func contractCell(tableView: UITableView, index: Int) {
    if (myArray[index]?.title) != nil {
        myArray.remove(at: index + 1)
        questionAnswerTable.deleteRows(at: [IndexPath(row: index + 1, section: 0 )], with: .top)
    }

}

Even this doesn't work smoothly as when a row is added the row count changes and if I try to expand the next cell it opens the third one.

Any one solution will work.
Please help guys. TIA


问:
Android music player application
I have created a music player app. While playing music if the user comes back to the previous activity the music still keeps playing. How to solve it?</p>

答:
Use the back press method and invoke the stop method of MediaPlayer

```<code>MediaPlayer player = MediaPlayer.create(this, R.raw.x);
@Override
public void onBackPressed() {
   player.stop();
}
</code>```

Try this

Title: Android music player application

Body:
Use the back press method and invoke the stop method of MediaPlayer

MediaPlayer player = MediaPlayer.create(this, R.raw.x);
@Override
public void onBackPressed() {
   player.stop();
}

Try this


问:
How to redirect in after executes the query php
Here is my code:

```<code>    $id = $_GET['id'];
$data = $_POST['name'];
$data1 = $_POST['id'];
$c = 0;

foreach ($data1 as $key => $value) {
    $sql = "UPDATE ".$table_comp." SET score = " . $data[$c][$value] . " where id = " . $value .";" ;
    mysqli_query($connect,$sql);
    $c++;
}
header('Location: http://www.csscorecard.com/admin/?id=$id');
</code>```

I have problem in my redirect there is an error:

Warning: Cannot modify header information - headers already sent by (output started at /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php:3) in /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php on line 54

答:
Its quite complex to give answer in this case without seeing whole file code. In many cases this error shown. but for header location you should put exit:</p>

```<code>exit(header("Location: http://www.csscorecard.com/admin/?id=$id"));
</code>```

Body:
Here is my code:

    $id = $_GET['id'];
$data = $_POST['name'];
$data1 = $_POST['id'];
$c = 0;

foreach ($data1 as $key => $value) {
    $sql = "UPDATE ".$table_comp." SET score = " . $data[$c][$value] . " where id = " . $value .";" ;
    mysqli_query($connect,$sql);
    $c++;
}
header('Location: http://www.csscorecard.com/admin/?id=$id');

I have problem in my redirect there is an error:

Warning: Cannot modify header information - headers already sent by (output started at /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php:3) in /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php on line 54

Body:
Its quite complex to give answer in this case without seeing whole file code. In many cases this error shown. but for header location you should put exit:

exit(header("Location: http://www.csscorecard.com/admin/?id=$id"));


问:
How to select a variable with an input and change its value in python(2.7)
How could I select a variable with an input and than change its value,
this is the best that I could come up with but it doesn't seem to work.

```<code>itm1 = 1
itm2 = 1
x = raw_input()
x += 1
print (itm1)
</code>```

I'm trying to get it so that anyone of the variables could be changed depending on the input.

答:
You could use 'exec'. This takes variable name through raw_input and executes "variable += 1"

```<code>itm1 = 1
itm2 = 1
exec(raw_input()+'+=1')
print(itm1)
</code>```

But this isn't the best method. Use dictionaries or lists instead

Body:
How could I select a variable with an input and than change its value,
this is the best that I could come up with but it doesn't seem to work.

itm1 = 1
itm2 = 1
x = raw_input()
x += 1
print (itm1)

I'm trying to get it so that anyone of the variables could be changed depending on the input.

Body:
You could use 'exec'. This takes variable name through raw_input and executes "variable += 1"

itm1 = 1
itm2 = 1
exec(raw_input()+'+=1')
print(itm1)

But this isn't the best method. Use dictionaries or lists instead


问:
Is it possible to remove a row depends on a particular value in AngularJs ui grid?
I want to display a list of data using ui grid. In that grid I want to filter some rows depends on the the value.

```<code>var app = angular.module('uigrid', ['ui.grid']);

app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.myData = [{name: "Moroni", age: 50},
                 {name: "Tiancum", age: 43},
                 {name: "Jacob", age: 27, visible: "false"},
                 {name: "Nephi", age: 29, visible: "false"},
                 {name: "Enos", age: 34}];

$scope.gridOptions = {
  enableRowSelection: true,
  enableSelectAll: true,
  multiSelect: true,
  enableColumnMenus: false,
  enableFiltering: true,
  rowHeight: 40,
  data : 'myData',
  columnDefs: [
    {
      name: 'name',
      displayName: 'Name'
    },
    {
      name: 'age',
      displayName: 'Age'
    },]
  };
}]);
</code>```

In this list I don't want to display two rows with that property visible: "false"? Which is the best way to remove that rows?
I have created the grid Example

Thanks in advance.

答:
You can use this in your $scope.gridOptions to show/hide rows

```<code>appScopeProvider: {
  showRow: function(row) {
    return row.visible !== 'false';
  }
},
</code>```

Here is the working plunker.

Body:
I want to display a list of data using ui grid. In that grid I want to filter some rows depends on the the value.

var app = angular.module('uigrid', ['ui.grid']);

app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.myData = [{name: "Moroni", age: 50},
                 {name: "Tiancum", age: 43},
                 {name: "Jacob", age: 27, visible: "false"},
                 {name: "Nephi", age: 29, visible: "false"},
                 {name: "Enos", age: 34}];

$scope.gridOptions = {
  enableRowSelection: true,
  enableSelectAll: true,
  multiSelect: true,
  enableColumnMenus: false,
  enableFiltering: true,
  rowHeight: 40,
  data : 'myData',
  columnDefs: [
    {
      name: 'name',
      displayName: 'Name'
    },
    {
      name: 'age',
      displayName: 'Age'
    },]
  };
}]);

In this list I don't want to display two rows with that property visible: "false"? Which is the best way to remove that rows?
I have created the grid Example

Thanks in advance.

Body:
You can use this in your $scope.gridOptions to show/hide rows

appScopeProvider: {
  showRow: function(row) {
    return row.visible !== 'false';
  }
},

Here is the working plunker.


问:
How to setup my phone as a hotspot
My phone is connected to a wifi network which provide internet. But it is password protected and my phone is selected as a user with unique password. That password cannot be used to connect another device to the wifi connection. Is there any way to share the internet (from wifi router) to another phone or laptop using my phone as a hotspot? How to share?</p>

答: No it is not possible to share internet from WiFi via phone, you can use your phone data and share it but you can't turn on hotspot when using WiFi and vice versa.</p>

Title: How to setup my phone as a hotspot


问:
How to create a code that tells two integers are co-prime?
Write a method that, when passed two positive integers m and n, returns true if m and n are co-prime. Two integers are co-prime when they don't have any positive integer common divisor expect 1.

You can assume that m≤n.

```<code>public static boolean coPrime( int m, int n) {
      if ( m%n == 0){
           return true;
      }
      return false;
</code>```

}

Here is what I have so far.
How do you realise that they are co-prime?

答:
```<code>/* The running time of the function is O(m) - linear */

public static boolean coPrime( int m, int n) {

      /* Since m <= n */
      int index = 2;
      bool is_coprime = true;
      while(index <= m){
         if(m % index == 0 and n % index == 0){
             is_coprime = false;
         }
         index = index + 1;
      }
      return is_coprime;
}
</code>```

Body:
Write a method that, when passed two positive integers m and n, returns true if m and n are co-prime. Two integers are co-prime when they don't have any positive integer common divisor expect 1.

You can assume that m≤n.

public static boolean coPrime( int m, int n) {
      if ( m%n == 0){
           return true;
      }
      return false;

}

Here is what I have so far.
How do you realise that they are co-prime?


问:
JBoss EAP 6.1 does not start in Eclipse Mars
After a lot of fixes and installations, I finally managed to install JBoss in Eclipse Mars running JRE 8. I created a Runtime Server environment which I have in my D drive and created a server in Eclipse. But when I try to start the server, it does not go beyond three lines of INFO . I googled and could not find any info regarding the same.

There are no stack traces or log which I can check to address the problem. I tried starting the server in cmd and it gives me the same three lines.

These are the line after which the JBoss server does not do anything:

```<code>18:58:05,721 INFO  [org.jboss.modules] (main) JBoss Modules version 1.2.0.Final-redhat-1
18:58:05,894 INFO  [org.jboss.msc] (main) JBoss MSC version 1.0.4.GA-redhat-1
18:58:05,942 INFO  [org.jboss.as] (MSC service thread 1-6) JBAS015899: JBoss EAP 6.1.0.GA (AS 7.2.0.Final-redhat-8) starting
</code>```

Please help me on how to get this working.

答: The problem was because I was using a JRE. JBoss needed a JDK to work properly. Once I changed it, the server was able to startup.</p>

Body:
After a lot of fixes and installations, I finally managed to install JBoss in Eclipse Mars running JRE 8. I created a Runtime Server environment which I have in my D drive and created a server in Eclipse. But when I try to start the server, it does not go beyond three lines of INFO . I googled and could not find any info regarding the same.

There are no stack traces or log which I can check to address the problem. I tried starting the server in cmd and it gives me the same three lines.

These are the line after which the JBoss server does not do anything:

18:58:05,721 INFO  [org.jboss.modules] (main) JBoss Modules version 1.2.0.Final-redhat-1
18:58:05,894 INFO  [org.jboss.msc] (main) JBoss MSC version 1.0.4.GA-redhat-1
18:58:05,942 INFO  [org.jboss.as] (MSC service thread 1-6) JBAS015899: JBoss EAP 6.1.0.GA (AS 7.2.0.Final-redhat-8) starting

Please help me on how to get this working.


问:
c++ parse int from string

Possible Duplicate:

  How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

```<code>string s = "10";
int i = s....?
</code>```

Thanks!

答:
You can use boost::lexical_cast:</p>

```<code>#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}
</code>```

Title: c++ parse int from string

Body:
Possible Duplicate:

  How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

string s = "10";
int i = s....?

Thanks!

Body:
You can use boost::lexical_cast:

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}


问:
Azure Web Apps - how to run script before deployment
I'm trying to use Azure Web Apps (Linux) to host a basic static site. I configured everything so a new deployment happens with every Git push. I put my pre-built pages in my repo to confirm everything works fine with this setup.

Now I've removed the pre-built pages and kept only the templates and the build script (which is basically just an npm install and a mustatic 'compile') and I'd like to run this build script in my web app. I've scoured the internet but can't find anything.

How can I run a script upon first deployment and after each Git-push-triggered deployment?

答:
How can I run a script upon first deployment and after each Git-push-triggered deployment?

First, you need to generate custom deployment script by using azure-cli tool.

1) Set the cli working mode to asm.

```<code>azure config mode asm
</code>```

2) Run the custom deployment script generator command.

```<code>azure site deploymentscript --node -t bash
</code>```

This will generate the files required to deploy your site.

.deployment - Contains the command to run for deploying your site.

deploy.sh   - Contains the deployment script.

Now you can edit the deploy.cmd file and add your custom steps.

After that done, add the generated files to your repository (.deployment and deploy.sh) and push your repository to your Azure Web App and see your custom deployment running.

For more details, please refer to this blog post.

Body:
How can I run a script upon first deployment and after each Git-push-triggered deployment?

First, you need to generate custom deployment script by using azure-cli tool.

1) Set the cli working mode to asm.

azure config mode asm

2) Run the custom deployment script generator command.

azure site deploymentscript --node -t bash

This will generate the files required to deploy your site.

.deployment - Contains the command to run for deploying your site.

deploy.sh   - Contains the deployment script.

Now you can edit the deploy.cmd file and add your custom steps.

After that done, add the generated files to your repository (.deployment and deploy.sh) and push your repository to your Azure Web App and see your custom deployment running.

For more details, please refer to this blog post.


答:
It's possible, but you really shouldn't do that in most cases. Nicer way is to store the parameters in a dictionary and do something like:

```<code>d = {
  'itm1': 1,
  'itm2': 1,
}
x = raw_input()
d[x] += 1
print (d['itm1'])
</code>```

If you really need to change the local variables and have a good reason not to rewrite it to a proper collection, you can use this: (but it's fugly)

```<code>locals()[x] += 1
</code>```

Title: How to select a variable with an input and change its value in python(2.7)

Body:
It's possible, but you really shouldn't do that in most cases. Nicer way is to store the parameters in a dictionary and do something like:

d = {
  'itm1': 1,
  'itm2': 1,
}
x = raw_input()
d[x] += 1
print (d['itm1'])

If you really need to change the local variables and have a good reason not to rewrite it to a proper collection, you can use this: (but it's fugly)

locals()[x] += 1


问:
Different radius to box-shadow and div
I want to apply different border-radius to box-shadow and div(on which box shadow is applied). Want to make something like this.
https://www.screencast.com/t/mEjBxMnbt

I make div and apply box-shadow and then apply border-radius:1px 0 0 1px to div which gives radius to box shadow which is fine but I want to give more border-radius to my div without changing my box-shadow radius.Can apply css only on div can't wrap it up or take parent container for it.

Please see link for more understanding.

Tried this is far

https://codepen.io/naveen_dharni/pen/Kqdyer

答:
hi border radius effects the box shadow of the div element ..
you could do something like this using the pseudo elements

html

```<code><div></div>
</code>```

css

```<code>div
{
  top:50px;
  height:300px;
  width:300px;
  border: 3px solid #000;
  box-shadow: 0 0 0 18px #DCD7E3;
  border-radius: 1px 0 0 1px;
  border-radius:500px;
  position: relative;
  margin:auto;
}

div::after
{
  content:"";
  position: absolute;
  top:0;
  left:-50%;
  right:-50%;
  bottom:0;
  margin:auto;
  display:inline-block;
  height:120%;
  width:120%;
  background-color: red;
  z-index:-1;
  border-radius:20px;
}
</code>```

Here is a link for reference codepen link

Hope this works..

Title: Different radius to box-shadow and div

Body:
hi border radius effects the box shadow of the div element ..
you could do something like this using the pseudo elements

html

<div></div>

css

div
{
  top:50px;
  height:300px;
  width:300px;
  border: 3px solid #000;
  box-shadow: 0 0 0 18px #DCD7E3;
  border-radius: 1px 0 0 1px;
  border-radius:500px;
  position: relative;
  margin:auto;
}

div::after
{
  content:"";
  position: absolute;
  top:0;
  left:-50%;
  right:-50%;
  bottom:0;
  margin:auto;
  display:inline-block;
  height:120%;
  width:120%;
  background-color: red;
  z-index:-1;
  border-radius:20px;
}

Here is a link for reference codepen link

Hope this works..


问:
Download 3000+ Images Using C#?
I have a list of around 3000 image URLs, where I need to download them to my desktop.

I'm a web dev, so naturally wrote a little asp.net c# download method to do this but the obvious problem happened and the page timed out before I got hardly any of them.

Was wondering if anyone else knew of a good, quick and robust way of me looping through all the image URL's and downloading them to a folder?  Open to any suggestions, WinForms, batch file although I'm a novice at both.

Any help greatly appreciated

答:
You might want to use an existing download manager like Orbit, rather than writing your own program for the purpose. (blasphemy, I know)

I've been pretty happy with Orbit. It lets you import a list of downloads from a text file. It'll manage the connections, downloading portions of each file in parallel with multiple connections, to increase the speed of each download. It'll take care of retrying if connections time out, etc. It seems like you'd have to go to a lot of effort to build these kind of features from scratch.

Title: Download 3000+ Images Using C#?


问:
Accordion in Javascript
I want to implement a simple accordion to my page, so I browsed w3schools and found the tutorial. But in it's javascript code there is a for loop that I can't understand what is does. can anyone explain it?
here is the code:

```<code>var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    }
}
</code>```

and here is the link to actual w3schools page:
https://www.w3schools.com/howto/howto_js_accordion.asp

答:
there have used 3 examples.so they put it in for loop.In normal way, single accordian

```<code> var acc = document.getElementsByClassName("accordion");
 acc.onclick = function(){
    /* Toggle between adding and removing the "active" class,
    to highlight the button that controls the panel */
    this.classList.toggle("active");

    /* Toggle between hiding and showing the active panel */
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
        panel.style.display = "none";
    } else {
        panel.style.display = "block";
    }
    }
</code>```

or (Simple Jquery method)

```<code>$('.accordian').on('click', function(){
  this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
        panel.style.display = "none";
    } else {
        panel.style.display = "block";
    }

});
</code>```

They have 3 accordian classes..so they are saved as array in this line.Then get the every element in the for loop

```<code>var acc = document.getElementsByClassName("accordion");
</code>```

Title: Accordion in Javascript

Body:
I want to implement a simple accordion to my page, so I browsed w3schools and found the tutorial. But in it's javascript code there is a for loop that I can't understand what is does. can anyone explain it?
here is the code:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    }
}

and here is the link to actual w3schools page:
https://www.w3schools.com/howto/howto_js_accordion.asp

Body:
there have used 3 examples.so they put it in for loop.In normal way, single accordian

 var acc = document.getElementsByClassName("accordion");
 acc.onclick = function(){
    /* Toggle between adding and removing the "active" class,
    to highlight the button that controls the panel */
    this.classList.toggle("active");

    /* Toggle between hiding and showing the active panel */
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
        panel.style.display = "none";
    } else {
        panel.style.display = "block";
    }
    }

or (Simple Jquery method)

$('.accordian').on('click', function(){
  this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
        panel.style.display = "none";
    } else {
        panel.style.display = "block";
    }

});

They have 3 accordian classes..so they are saved as array in this line.Then get the every element in the for loop

var acc = document.getElementsByClassName("accordion");