问:
different overlay content based on json file
I have an overlay structure that I want to get populated by the content of a json file via jquery ajax. The overlay is triggered by a class:

```<code><div class="js-overlay-start" data-overlay="js-overlay--type1">
  open overlay
</div>
</code>```

This triggers the overlay and opens the html structure for it which looks like this:

```<code><div class="overlay" data-open-overlay="js-overlay--type1">
    <img class="json-front" src="">
    <img class="json-back" src="">
</div>
</code>```

the js for it is:

```<code>$(".js-overlay-start").unbind("click").bind("click", function(e) {
    e.preventDefault();
    $("body,html").css("overflow","hidden").css("position","fixed");
    var dataOverlay = $(this).attr("data-overlay");
    $("body").find("[data-open-overlay='" + dataOverlay + "']").show();

    $.ajax({
        url: 'json/overlay.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {
            var item = data.items[0];

            $('.json-front').attr("src", "");
            $('.json-back').attr("src", "");
            $('.json-front').attr("src", item.front);
            $('.json-back').attr("src", item.back);
        } //success
    });//ajax

    setTimeout(function() {
        $(".overlay").addClass("o1");
    }, 100);
});
</code>```

and the json file looks like this:

```<code>{
    "items": [{
        "title": "first",
        "front": "http://placehold.it/810x2028?text=front",
        "back": "http://placehold.it/810x2028?text=back"
    },
    {
        "title": "second",
        "front": "http://placehold.it/810x2028",
        "back": "http://placehold.it/810x2028"
    }]
}
</code>```

basically I'm looking for a way to open the overlay and the img src to be populated based on the title in the json (or something else if it's more convenient) so it can choose the appropriate srcs. I'm successful when the item is only one, but I have no idea how to manage this distinction.

any heads up or solution is greatly appreciated. thanks a lot :)

答:
It might be more efficient if you make the ajax request first and store the data ready for the click events (rather than making an ajax request for each click). I havn't done this as it wasn't what you were asking, but something to consider.

Below I've grabbed the unique identifier for your click (ie. type1 from data-overlay) then used this to select the right object from your json file.

$(".js-overlay-start").unbind("click").bind("click", function(e) {
    e.preventDefault();
    $("body,html").css("overflow","hidden").css("position","fixed");
    var dataOverlay = $(this).attr("data-overlay");
    $("body").find("[data-open-overlay='" + dataOverlay + "']").show();
    var itemId = $(this).attr("data-overlay").split('--')[1]; // This is where you can grab the unique identifier

    $.ajax({
        url: 'json/overlay.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {
            $('.json-front').attr("src", "");
            $('.json-back').attr("src", "");
            $('.json-front').attr("src", data['items'][itemId].front);
            $('.json-back').attr("src", data['items'][itemId].back);
        } //success
    });//ajax

    setTimeout(function() {
        $(".overlay").addClass("o1");
    }, 100);
});```
</div>
</div>
</p>

<p>And a few changes to your json file so it's easier to traverse</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{ items: {
     type1: {
        "title": "first",
        "front": "http://placehold.it/810x2028?text=front",
        "back": "http://placehold.it/810x2028?text=back"
        },
     type2: {
        "title": "second",
        "front": "http://placehold.it/810x2028",
        "back": "http://placehold.it/810x2028"
    }
 }
}</code>```

Body:
I have an overlay structure that I want to get populated by the content of a json file via jquery ajax. The overlay is triggered by a class:

  open overlay

This triggers the overlay and opens the html structure for it which looks like this:

the js for it is:

$(".js-overlay-start").unbind("click").bind("click", function(e) {
    e.preventDefault();
    $("body,html").css("overflow","hidden").css("position","fixed");
    var dataOverlay = $(this).attr("data-overlay");
    $("body").find("[data-open-overlay='" + dataOverlay + "']").show();

    $.ajax({
        url: 'json/overlay.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {
            var item = data.items[0];

            $('.json-front').attr("src", "");
            $('.json-back').attr("src", "");
            $('.json-front').attr("src", item.front);
            $('.json-back').attr("src", item.back);
        } //success
    });//ajax

    setTimeout(function() {
        $(".overlay").addClass("o1");
    }, 100);
});

and the json file looks like this:

{
    "items": [{
        "title": "first",
        "front": "http://placehold.it/810x2028?text=front",
        "back": "http://placehold.it/810x2028?text=back"
    },
    {
        "title": "second",
        "front": "http://placehold.it/810x2028",
        "back": "http://placehold.it/810x2028"
    }]
}

basically I'm looking for a way to open the overlay and the img src to be populated based on the title in the json (or something else if it's more convenient) so it can choose the appropriate srcs. I'm successful when the item is only one, but I have no idea how to manage this distinction.

any heads up or solution is greatly appreciated. thanks a lot :)

Body:
It might be more efficient if you make the ajax request first and store the data ready for the click events (rather than making an ajax request for each click). I havn't done this as it wasn't what you were asking, but something to consider.

Below I've grabbed the unique identifier for your click (ie. type1 from data-overlay) then used this to select the right object from your json file.

$(".js-overlay-start").unbind("click").bind("click", function(e) {
    e.preventDefault();
    $("body,html").css("overflow","hidden").css("position","fixed");
    var dataOverlay = $(this).attr("data-overlay");
    $("body").find("[data-open-overlay='" + dataOverlay + "']").show();
    var itemId = $(this).attr("data-overlay").split('--')[1]; // This is where you can grab the unique identifier

    $.ajax({
        url: 'json/overlay.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {
            $('.json-front').attr("src", "");
            $('.json-back').attr("src", "");
            $('.json-front').attr("src", data['items'][itemId].front);
            $('.json-back').attr("src", data['items'][itemId].back);
        } //success
    });//ajax

    setTimeout(function() {
        $(".overlay").addClass("o1");
    }, 100);
});

And a few changes to your json file so it's easier to traverse

{ items: {
     type1: {
        "title": "first",
        "front": "http://placehold.it/810x2028?text=front",
        "back": "http://placehold.it/810x2028?text=back"
        },
     type2: {
        "title": "second",
        "front": "http://placehold.it/810x2028",
        "back": "http://placehold.it/810x2028"
    }
 }
}


来源: stackexchange

问:
How do I programmatically add a view right under the navigation bar?
I'm trying to add a view to a UINavigationController with its top aligned with the navigation bar's bottom.

I tried using constraints by adding the following to my UINavigationController subclass:

```<code>override func viewDidAppear(_ animated: Bool) {
           self.label = UILabel()
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
    let horConstraint = NSLayoutConstraint(item: label!, attribute: .top, relatedBy: .equal,
                                           toItem: topLayoutGuide, attribute: .bottom,
                                           multiplier: 1.0, constant: 0.0)
    let widthConstr = NSLayoutConstraint(item: label!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)

    let heightConstr = NSLayoutConstraint(item: label!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
    view.addConstraints([horConstraint, widthConstr, heightConstr])
}
</code>```

With this being the result:

And I tried by setting the frame of my subview:

```<code>override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)

}
</code>```

And this came out:

In both cases my label covers part of the navigation bar. How to I fix this?

答: You're not calculating the height of the status bar with the navigation bar. In total they are 64, 44 nav bar and 20 for the status bar</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to add a view to a UINavigationController with its top aligned with the navigation bar's bottom.

I tried using constraints by adding the following to my UINavigationController subclass:

override func viewDidAppear(_ animated: Bool) {
           self.label = UILabel()
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
    let horConstraint = NSLayoutConstraint(item: label!, attribute: .top, relatedBy: .equal,
                                           toItem: topLayoutGuide, attribute: .bottom,
                                           multiplier: 1.0, constant: 0.0)
    let widthConstr = NSLayoutConstraint(item: label!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)

    let heightConstr = NSLayoutConstraint(item: label!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
    view.addConstraints([horConstraint, widthConstr, heightConstr])
}

With this being the result:

And I tried by setting the frame of my subview:

override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)

}

And this came out:

In both cases my label covers part of the navigation bar. How to I fix this?


问:
How can you emulate object serialization on java in C#
I need to call a servlet call for an automation of a java applet using c#. What the java applet is it calls a servlet using a URL Connection object.

```<code>URL servlet = new URL(servletProtocol, servletHost, servletPort, "/" + ServletName);
URLConnection con = servlet.openConnection();
con.setDoOutput(true);
ObjectOutputStream out = new ObjectOutputStream(con.getOutputStream());
// Write several parameters strings
out.writeObject(param[0]);
out.writeObject(param[1]);
out.flush();
out.close();
</code>```

The problem is i need to simulate this using c#. I believe the counterpart object would be HttpWebRequest

```<code>HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(servletPath);
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(param[0],0,param[0].length);
newStream.Write(param[1],0,param[1].length);
newStream.Close();
</code>```

How do I write the string as a serialized java string? Is there any workaround here? According to the documentation of ObjectOutputStream in java, it serialize the object except for primitive type. I know String is class, so does it serialzie it like an object or some special case?

I have tried one solution, I have imported the IKVM (http://www.ikvm.net/) java virtual machine in my reference and am trying to use the java.io library in Java. Unforunately, when the ObjectInputStream constructor is called, a "invalid stream header" is thrown.

Here is my altered code:

```<code>myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();

// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();

List<byte> lByte = new List<byte>();
using (StreamReader sr = new StreamReader(myRequest.GetResponse().GetResponseStream()))
{
    while (sr.Peek() >= 0)
    {
        lByte.Add((byte)sr.Read());
    }
}

byte[] bArr = lByte.ToArray();
ObjectInputStream inputStream = null;

try
{
    //Construct the ObjectInputStream object
    inputStream = new ObjectInputStream(new ByteArrayInputStream(bArr));

    Object obj = null;

    while ((obj = inputStream.readObject()) != null)
    {
        string objStr = obj as string;
    }

}
catch (java.lang.Exception ex)
</code>```

答:
I finally got to get this to work.

The problem is on reading the data in .NET instead of using StreamReader, I need to use the Stream object immediately. Anyway just leaving it here in case it helps others with their problem:

Wrong Code:

```<code>List<byte> lByte = new List<byte>();
using (StreamReader sr = new StreamReader(myRequest.GetResponse().GetResponseStream()))
{
    while (sr.Peek() >= 0)
    {
        lByte.Add((byte)sr.Read());
    }
}
</code>```

Correct Code:

```<code>byte[] buffer = new byte[1000];
using (Stream sr = myRequest.GetResponse().GetResponseStream())
{
    sr.Read(buffer, 0, 1000);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to call a servlet call for an automation of a java applet using c#. What the java applet is it calls a servlet using a URL Connection object.

URL servlet = new URL(servletProtocol, servletHost, servletPort, "/" + ServletName);
URLConnection con = servlet.openConnection();
con.setDoOutput(true);
ObjectOutputStream out = new ObjectOutputStream(con.getOutputStream());
// Write several parameters strings
out.writeObject(param[0]);
out.writeObject(param[1]);
out.flush();
out.close();

The problem is i need to simulate this using c#. I believe the counterpart object would be HttpWebRequest

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(servletPath);
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(param[0],0,param[0].length);
newStream.Write(param[1],0,param[1].length);
newStream.Close();

How do I write the string as a serialized java string? Is there any workaround here? According to the documentation of ObjectOutputStream in java, it serialize the object except for primitive type. I know String is class, so does it serialzie it like an object or some special case?

I have tried one solution, I have imported the IKVM (http://www.ikvm.net/) java virtual machine in my reference and am trying to use the java.io library in Java. Unforunately, when the ObjectInputStream constructor is called, a "invalid stream header" is thrown.

Here is my altered code:

myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();

// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();

List<byte> lByte = new List<byte>();
using (StreamReader sr = new StreamReader(myRequest.GetResponse().GetResponseStream()))
{
    while (sr.Peek() >= 0)
    {
        lByte.Add((byte)sr.Read());
    }
}

byte[] bArr = lByte.ToArray();
ObjectInputStream inputStream = null;

try
{
    //Construct the ObjectInputStream object
    inputStream = new ObjectInputStream(new ByteArrayInputStream(bArr));

    Object obj = null;

    while ((obj = inputStream.readObject()) != null)
    {
        string objStr = obj as string;
    }

}
catch (java.lang.Exception ex)

Body:
I finally got to get this to work.

The problem is on reading the data in .NET instead of using StreamReader, I need to use the Stream object immediately. Anyway just leaving it here in case it helps others with their problem:

Wrong Code:

List<byte> lByte = new List<byte>();
using (StreamReader sr = new StreamReader(myRequest.GetResponse().GetResponseStream()))
{
    while (sr.Peek() >= 0)
    {
        lByte.Add((byte)sr.Read());
    }
}

Correct Code:

byte[] buffer = new byte[1000];
using (Stream sr = myRequest.GetResponse().GetResponseStream())
{
    sr.Read(buffer, 0, 1000);
}


问:
Adding checkbox validation to a form
I'm having trouble figuring out how to add validation on my form, that sends data to a payment system.

I have validation added to the form on text and numeric fields, but i simply can't figure out to get validation on the checkbox.

Below you can see the HTML and javascript code, some information has been left out - what am i doing wrong??

Thanks

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="ePay" style="max-width: 600px;">
    <b><u>Online betaling</u></b>
    Alle felter, undtaget kommentarfelt skal udfyldes.
    <br /><br />
    <table cellspacing="4" cellpadding="4">
     <tr>
         <td style="max-width: 700px; border: 0px;"><input type="text" placeholder="Fakturanummer" name="orderid" maxlength="20" style="width: 200px;" /></td>
        </tr>
        <tr>
         <td style="border: 0px;"><input type="text" placeholder="Beløb i DKK"name="useramount" style="width: 200px;" /></td>
        </tr>
        <tr>
         <td style="border: 0px;"><input type="text" placeholder="Navn" name="customername" style="width: 200px;" maxlength="50" /></td>
        </tr>
        <tr>
         <td style="border: 0px;"><textarea name="customercomment"  placeholder="Evt. kommentar" style="width: 300px; height: 100px;"></textarea></td>
        </tr>
        <tr>
               <td  style="border: 0px;">
        <input type="checkbox" name="checkbox" value="check" id="terms" required />Jeg har læst og accepteret alle <u>handelsbetingelser</u></td></tr>
              <tr> <td colspan="3" style="text-align: left; padding-top: 10px; border: 0px;"><input type="button" value="Betal" onclick="startPayment(3)" style="width: 180px;" /></td>
        </tr>
        <tr>
            <td colspan="3" style="padding-top: 30px; border: 0px;">
                <table cellspacing="0" cellpadding="0">
                    <tr>
                        <td style="vertical-align: top; padding-right: 20px; border: 0px;"><img src="/epay/epay-payment-solutions.gif" width="75" height="44" style="border: 0px;" alt="ePay / Payment Solutions" /></td>
                        <td style="vertical-align: top; font-size: 11px; padding-top: 2px; border: 0px;">
                            <b>SIKKER BETALING</b>
                            <br />
                            <span class="notranslate">ePay / Payment Solutions</span> er PCI certificeret af VISA / Mastercard,<br />og al kommunikation foregår krypteret via en sikker forbindelse.
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    <input type="hidden" name="merchantnumber" value="8025944"/>
    <input type="hidden" name="accepturl" value="" />
    <input type="hidden" name="cancelurl" value="" />
    <input type="hidden" name="textonstatement" value=""/>
</form></code>```

答:
Shouldn't this be very simple ? (Apart from the security gaps)

<form>
    Needed Checkbox: <input type="checkbox" required>
    <input type="submit" />
</form>
```
</div>
</div>
</p>

<p>Alternativ: https://jsfiddle.net/w7baj016/</p>

<p>According to your comment, here is a jquery sample i made. May this helps you for your behavior</p>

<p>You should care if your document is fully loaded: $(document).ready()</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//care if fully loaded
$("#myForm").on('submit',function(e){

    e.preventDefault();
    //i guess in js you can simply call event.preventDefault();

    if($("#some").prop("checked") == false){
        alert("You need to Check this first");
    }else{
        this.submit();
    }
});</code>```

<form id="myForm">
    <input id="some" type="checkbox">
    <input type="submit" />
</form>```
</div>
</div>
</p>

<p>Simple JS code</p>

<p>How to care about the document load state with js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//you should care that the document is fully loaded (ready)
document.querySelector("#myForm").addEventListener("submit", function(e){

    e.preventDefault();    //stop form from submitting
    var isValid = document.getElementById("some").checked;

    if(isValid){
        this.submit();
    }else{
        alert("please check the checkbox befor");
    }
});</code>```

<form id="myForm">
<input id="some" type="checkbox">
<input type="submit" />
</form>```

I hope this helps you to solve this :)

Title: Adding checkbox validation to a form

Body:
I'm having trouble figuring out how to add validation on my form, that sends data to a payment system.

I have validation added to the form on text and numeric fields, but i simply can't figure out to get validation on the checkbox.

Below you can see the HTML and javascript code, some information has been left out - what am i doing wrong??

Thanks

<form id="ePay" style="max-width: 600px;">
    Online betaling
    Alle felter, undtaget kommentarfelt skal udfyldes.

         <input type="text" placeholder="Fakturanummer" name="orderid" maxlength="20" style="width: 200px;" />

         <input type="text" placeholder="Beløb i DKK"name="useramount" style="width: 200px;" />

         <input type="text" placeholder="Navn" name="customername" style="width: 200px;" maxlength="50" />

         <textarea name="customercomment"  placeholder="Evt. kommentar" style="width: 300px; height: 100px;"></textarea>

        <input type="checkbox" name="checkbox" value="check" id="terms" required />Jeg har læst og accepteret alle handelsbetingelser

 <input type="button" value="Betal" onclick="startPayment(3)" style="width: 180px;" />

                            SIKKER BETALING

                            ePay / Payment Solutions er PCI certificeret af VISA / Mastercard,
og al kommunikation foregår krypteret via en sikker forbindelse.

    <input type="hidden" name="merchantnumber" value="8025944"/>
    <input type="hidden" name="accepturl" value="" />
    <input type="hidden" name="cancelurl" value="" />
    <input type="hidden" name="textonstatement" value=""/>
</form>

Body:
Shouldn't this be very simple ? (Apart from the security gaps)

<form>
    Needed Checkbox: <input type="checkbox" required>
    <input type="submit" />
</form>
<!-- brings up its own error when it fails -->

Alternativ: https://jsfiddle.net/w7baj016/

According to your comment, here is a jquery sample i made. May this helps you for your behavior

You should care if your document is fully loaded: $(document).ready()

//care if fully loaded
$("#myForm").on('submit',function(e){

    e.preventDefault();
    //i guess in js you can simply call event.preventDefault();

    if($("#some").prop("checked") == false){
        alert("You need to Check this first");
    }else{
        this.submit();
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
    <input id="some" type="checkbox">
    <input type="submit" />
</form>

Simple JS code

How to care about the document load state with js

//you should care that the document is fully loaded (ready)
document.querySelector("#myForm").addEventListener("submit", function(e){

    e.preventDefault();    //stop form from submitting
    var isValid = document.getElementById("some").checked;

    if(isValid){
        this.submit();
    }else{
        alert("please check the checkbox befor");
    }
});

<form id="myForm">
<input id="some" type="checkbox">
<input type="submit" />
</form>

I hope this helps you to solve this :)


问:
How do you get centered content using Twitter Bootstrap?
I'm trying to follow a very basic example.  Using the starter page and the grid system, I was hoping the following:

Bootstrap starter template

Example text.

```

...would produce centered text.

However, it still appears on the far left. What am I doing wrong?

答:
Simply use a class, text-center, for the div or tag which you want. I think it may work fine. It is a Bootstrap class for text align center.

Here are some text alignment Bootstrap classes:

```<code>text-left, text-right, text-justify, etc.
<div class="row">
 <div class="col-md-12 text-center">
  <h1>Bootstrap starter template</h1>
  <p>Example text.</p>
 </div>
</div>
</code>```

Body:
I'm trying to follow a very basic example.  Using the starter page and the grid system, I was hoping the following:

Bootstrap starter template

Example text.

...would produce centered text.

However, it still appears on the far left. What am I doing wrong?

Body:
Simply use a class, text-center, for the div or tag which you want. I think it may work fine. It is a Bootstrap class for text align center.

Here are some text alignment Bootstrap classes:

text-left, text-right, text-justify, etc.
<div class="row">
 <div class="col-md-12 text-center">
  <h1>Bootstrap starter template</h1>
  <p>Example text.</p>
 </div>
</div>


问:
Edit DB Rows in SSRS
Is there any way to create a SSRS Report that edit DB Rows?

At the moment i use ssrs to update Row per Row but now i need to change more rows at the same time.

When there are no way, please can you help me, saying what you are using to edit more DB Rows via Webbrowser at the same time?

thx

答:
Yes you can. The query of a dataset can have stored procedures, update statements etc. You can probably even use sp_executesql and supply your query using a parameter.

You can, but you shouldn't.

Title: Edit DB Rows in SSRS


问:
Redirect user to another page once increment value reach 100
I have created a UI where when service return true value, I have created a loading bar which will reach 100%, after reaching 100% user should be redirect to another page.

lets assume, If the service return false value, the status bar stay at 10% loaded.

Link to jsfiddle

I have created function were I have written the progress bar logic and I am returning true value when service return true and redirecting to other URL.

everything is working great. But I want the progress bar to reach 100% and after that only user should be redirected. Below is the code (And above is jsfiddle link):

```<code>var serviceStatus = true; // Suppose value from service
var elem = document.getElementById("blueBar");
var perNum = document.getElementById("progressPercentage");

var width = 10; // intial progress bar width
var id = setInterval(progressBar, 10);
function progressBar() {
    if (width >= 100 || serviceStatus === false) {
        clearInterval(id);
        return false;
    } else {
        width ++;
        elem.style.width = width + '%';
        perNum.innerHTML = width * 1  + '%';
        //return true;
    }
}

function redirectUser(progressBar) {
    console.log(progressBar);
    // if (frame === true) {
    //  window.location = "http://www.google.com";
    // };
}

redirectUser(progressBar());
</code>```

Thanks, any questions? please ask.

答:
var blueProgressBar = {

 initialize: function() {
  var serviceStatus = true; // Suppose value from service
  var elem = document.getElementById("blueBar");
  var perNum = document.getElementById("progressPercentage");

  var width = 10; // intial progress bar width
  var id = setInterval(progressBar, 10);
  function progressBar() {
   if (width >= 100 || serviceStatus === false) {
    clearInterval(id);
    return false;
   } else {
    width ++;
    elem.style.width = width + '%';
    perNum.innerHTML = width * 1  + '%';
    //return true;
   }
   if(width >= 100 && serviceStatus){
    window.location = "redirect url";
   }
  }

  function redirectUser(progressBar) {
   console.log(progressBar);

  }

  redirectUser();
 }

}

$(function() {
 blueProgressBar.initialize();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.upgrade-service-level-bar {
    background-color: #f8f8f8;
    width: 80%;
    padding: 20px 40px 20px 20px;
    border-bottom: 1px solid #ebebeb;
}

.bar-full-witdh {
    width: 100%;
    background-color: #ffffff;
    position: relative;
}

#blueBar {
    width: 10%;
    height: 6px;
    background-color: #007cba;
    display: block;
}

.bar-full-witdh span:last-child {
    font-size: 12px;
    position: absolute;
    top: -3px;
    right: -30px;
}</code>```

 <title></title>

  10%

Once progress bar reaches 100% the redirect should happen.

```

Body:
I have created a UI where when service return true value, I have created a loading bar which will reach 100%, after reaching 100% user should be redirect to another page.

lets assume, If the service return false value, the status bar stay at 10% loaded.

Link to jsfiddle

I have created function were I have written the progress bar logic and I am returning true value when service return true and redirecting to other URL.

everything is working great. But I want the progress bar to reach 100% and after that only user should be redirected. Below is the code (And above is jsfiddle link):

var serviceStatus = true; // Suppose value from service
var elem = document.getElementById("blueBar");
var perNum = document.getElementById("progressPercentage");

var width = 10; // intial progress bar width
var id = setInterval(progressBar, 10);
function progressBar() {
    if (width >= 100 || serviceStatus === false) {
        clearInterval(id);
        return false;
    } else {
        width ++;
        elem.style.width = width + '%';
        perNum.innerHTML = width * 1  + '%';
        //return true;
    }
}

function redirectUser(progressBar) {
    console.log(progressBar);
    // if (frame === true) {
    //  window.location = "http://www.google.com";
    // };
}

redirectUser(progressBar());

Thanks, any questions? please ask.

Body:
var blueProgressBar = {

 initialize: function() {
  var serviceStatus = true; // Suppose value from service
  var elem = document.getElementById("blueBar");
  var perNum = document.getElementById("progressPercentage");

  var width = 10; // intial progress bar width
  var id = setInterval(progressBar, 10);
  function progressBar() {
   if (width >= 100 || serviceStatus === false) {
    clearInterval(id);
    return false;
   } else {
    width ++;
    elem.style.width = width + '%';
    perNum.innerHTML = width * 1  + '%';
    //return true;
   }
   if(width >= 100 && serviceStatus){
    window.location = "redirect url";
   }
  }

  function redirectUser(progressBar) {
   console.log(progressBar);

  }

  redirectUser();
 }

}

$(function() {
 blueProgressBar.initialize();
});

.upgrade-service-level-bar {
    background-color: #f8f8f8;
    width: 80%;
    padding: 20px 40px 20px 20px;
    border-bottom: 1px solid #ebebeb;
}

.bar-full-witdh {
    width: 100%;
    background-color: #ffffff;
    position: relative;
}

#blueBar {
    width: 10%;
    height: 6px;
    background-color: #007cba;
    display: block;
}

.bar-full-witdh span:last-child {
    font-size: 12px;
    position: absolute;
    top: -3px;
    right: -30px;
}

<html>
<head>
 <title></title>

</head>
<body>
<div class="upgrade-service-level-bar">
 <div class="bar-full-witdh">
  <span id="blueBar"></span>
  <span id="progressPercentage">10%</span>
 </div>
</div>
<br>
<p>
Once progress bar reaches 100% the redirect should happen.
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>


问:
Cannot read property 'style' of null - Javascript
I can't find why it is creating this error for the life of me. I am trying to change the position of "snake" with css bottom and left in javascript. Here is my code:

https://jsfiddle.net/9zewsf3x/2/

This is the what is causing the errors apparently.

```<code>snakeObject.style.bottom = x_pos + "px";
snakeObject.style.left = y_pos + "px";
</code>```

答:
just use style.cssText</p>

```<code>snakeObject.style.cssText = "left: 50px; right: 50px;"
</code>```

Body:
I can't find why it is creating this error for the life of me. I am trying to change the position of "snake" with css bottom and left in javascript. Here is my code:

https://jsfiddle.net/9zewsf3x/2/

This is the what is causing the errors apparently.

snakeObject.style.bottom = x_pos + "px";
snakeObject.style.left = y_pos + "px";

Body:
just use style.cssText

snakeObject.style.cssText = "left: 50px; right: 50px;"


问:
Null pointer exception in suggestions popup window on Samsung Galaxy Android 7
I'm seeing an unusual crash occur regularly in my app, but only on Samsung Galaxy devices running Android 7. Since my app's code doesn't feature in the stacktrace, I'm finding it very hard to track down short of going out and buying one of these expensive devices. Are there any clues to follow here?

It appears to be an internal bug happening inside the suggestions popup associated with an input control, presumably the EditText that features on my app's primary screen. That EditText should not be presenting suggestions, since I'm also using

```<code>searchBox.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        searchBox.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
</code>```

The stacktrace follows:

```<code>java.lang.NullPointerException:
    at android.widget.Editor$SuggestionsPopupWindow.initContentView(Editor.java:3729)
    at android.widget.Editor$PinnedPopupWindow.<init>(Editor.java:3390)
    at android.widget.Editor$SuggestionsPopupWindow.<init>(Editor.java:3675)
    at android.widget.Editor.replace(Editor.java:431)
    at android.widget.Editor$3.run(Editor.java:2354)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method:0)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

答:
It's possible a bug in Samsung Android system.
For this kind of platform's bug I believe, I would like to use try{} catch{} to handle them, then the app should be able to sustain at least.
Of course, if the exception happens during your application booting sequence, then it's impossible to handle it with try{} catch..., it's better to locate the root cause and find a true solution to fix or work around it. But if the exception happens in your application feature, it's easy to find a way to handle it after you catch this exception, then your application will not crash.
I like to use the "try...catch" to handle this kind of unexpected situations.</p>

Body:
I'm seeing an unusual crash occur regularly in my app, but only on Samsung Galaxy devices running Android 7. Since my app's code doesn't feature in the stacktrace, I'm finding it very hard to track down short of going out and buying one of these expensive devices. Are there any clues to follow here?

It appears to be an internal bug happening inside the suggestions popup associated with an input control, presumably the EditText that features on my app's primary screen. That EditText should not be presenting suggestions, since I'm also using

searchBox.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        searchBox.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

The stacktrace follows:

java.lang.NullPointerException:
    at android.widget.Editor$SuggestionsPopupWindow.initContentView(Editor.java:3729)
    at android.widget.Editor$PinnedPopupWindow.<init>(Editor.java:3390)
    at android.widget.Editor$SuggestionsPopupWindow.<init>(Editor.java:3675)
    at android.widget.Editor.replace(Editor.java:431)
    at android.widget.Editor$3.run(Editor.java:2354)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method:0)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)


问:
How to list network interfaces, its configuration IP,netmask and gateway in Python/Windows
I wanna develop a small application to monitor arp and scan arp list in local network.

Currently, I need to retrieve the list of network interfaces and its configuration.

Most of the time I work with Linux, so I don't know much about Win32 API, is there anyway to do this in python way ? I'm using Python 2.6 with PyQt and Scapy (has pywin32 aswell, so if you provide the detail way with win32, I will try)

I found pcapy.findalldevs(), but it cannot retrive configuration. I don't care much about the name, just configuration(IP,netmask) is OK.

答:
Not sure exactly what info you want, but ipconfig /all certainly sounds like what you want:

```<code>import subprocess
subprocess.call('ipconfig /all')
</code>```

Body:
Not sure exactly what info you want, but ipconfig /all certainly sounds like what you want:

import subprocess
subprocess.call('ipconfig /all')


问:
How to find and modify specific rows using fields in that row in pandas dataframe?
I have this dataset

```<code>time_in     time_out     total_mins
8AM         10AM         120
6AM         8AM          120
6AM         8AM          -231
</code>```

What I am trying to do is get the wrong total_mins values, in this case the one that became negative. I wish to

identify the records with negative total_mins (Im ok with this)

recompute the timein and timeout difference and overwrite the existing total_mins value

I'm finding a lot of examples on how to use ix to get certain records based on a condition but what I am not sure about is how to use fields from that row, and use them to modify a certain field on a row. so basically, no. 2

only option that I can think of right now is to loop through the records, and perform test and modification but the documentation advises not to do this.

答:
Compute the difference of all rows first:

```<code>total_mins_computed = (pd.to_datetime(df.time_out, format='%H%p') - pd.to_datetime(df.time_in', format='%H%p')).dt.total_seconds()
</code>```

If you only want to correct the negative entries, use np.where():

```<code>df['total_mins'] = np.where(df.total_mins > 0, df.total_mins, total_mins_computed)
</code>```

Body:
I have this dataset

time_in     time_out     total_mins
8AM         10AM         120
6AM         8AM          120
6AM         8AM          -231

What I am trying to do is get the wrong total_mins values, in this case the one that became negative. I wish to

identify the records with negative total_mins (Im ok with this)

recompute the timein and timeout difference and overwrite the existing total_mins value

I'm finding a lot of examples on how to use ix to get certain records based on a condition but what I am not sure about is how to use fields from that row, and use them to modify a certain field on a row. so basically, no. 2

only option that I can think of right now is to loop through the records, and perform test and modification but the documentation advises not to do this.

Body:
Compute the difference of all rows first:

total_mins_computed = (pd.to_datetime(df.time_out, format='%H%p') - pd.to_datetime(df.time_in', format='%H%p')).dt.total_seconds()

If you only want to correct the negative entries, use np.where():

df['total_mins'] = np.where(df.total_mins > 0, df.total_mins, total_mins_computed)


问:
Why is the KNN implementation in sklearn slower when I use a smaller float?
I'm using KNN search in my application. Big arrays would consume a lot of memory and I'm trying to reduce the size of the array.

It's too hard for me to reduce the number of dimensions without affecting the result. So I look to reduce the the size by using a smaller dtype:

```<code>In [46]: features = np.random.random((500000, 128)).astype('float32')

In [47]: smaller = features.astype('float16')

In [48]: nbrs = NearestNeighbors(n_neighbors=20, algorithm='brute', metric='l2').fit(f
    ...: eatures)

In [49]: smaller_nbrs = NearestNeighbors(n_neighbors=20, algorithm='brute', metric='l2
    ...: ').fit(smaller)

In [50]: %timeit nbrs.kneighbors(features[3:4])
10 loops, best of 3: 61.7 ms per loop

In [51]: %timeit smaller_nbrs.kneighbors(smaller[3:4])
1 loop, best of 3: 526 ms per loop
</code>```

As you can see, switching to float16 makes the kneighbors call about 10 times slower.

Why is this the case? Is there anything I can do to make it run as fast as when using float32?

答:
The reason why 32b float works faster than 16b float is that 32b floats are natively supported by most of the modern CPUs whereas 16b float may require some special handling (e.g. converting to float32). Thusly, while you save the RAM you spend significantly more on computation.
This can be alleviated when proper CPU instructions are used, which might not be the case here (Intel introduced special half-precision opcodes in 2012; see). The caveat is that you can achieve any noticeable speed-up only once your array is larger than 256K (which obviously is your case) but the improvement is between 20 and 40% which can easily be lost via non-optimal traversal of the array (cache misses).

Also, another factor to take into account is the memory data alignment that typically works much better with a full word (for many of the CPUs: 32b or 64b). Plenty of details on the impact of memory alignment and cache usage you can find in Scott Myers' presentation.

Body:
I'm using KNN search in my application. Big arrays would consume a lot of memory and I'm trying to reduce the size of the array.

It's too hard for me to reduce the number of dimensions without affecting the result. So I look to reduce the the size by using a smaller dtype:

In [46]: features = np.random.random((500000, 128)).astype('float32')

In [47]: smaller = features.astype('float16')

In [48]: nbrs = NearestNeighbors(n_neighbors=20, algorithm='brute', metric='l2').fit(f
    ...: eatures)

In [49]: smaller_nbrs = NearestNeighbors(n_neighbors=20, algorithm='brute', metric='l2
    ...: ').fit(smaller)

In [50]: %timeit nbrs.kneighbors(features[3:4])
10 loops, best of 3: 61.7 ms per loop

In [51]: %timeit smaller_nbrs.kneighbors(smaller[3:4])
1 loop, best of 3: 526 ms per loop

As you can see, switching to float16 makes the kneighbors call about 10 times slower.

Why is this the case? Is there anything I can do to make it run as fast as when using float32?


问:
Converting more than one image to binary with just one method
For my Little application, i have written a method to convert an image to binary and then save it in database. What i want to do now , is to find of way of making that same method be reuseable by other fileUpload. Which means, if i have two fileUploads eg.

                Image 1

```<code>        <div class="col-md-3">
            <div class="form-group">
                <label for="image2">Image 2</label>
                <asp:FileUpload ID="Upload2" runat="server" ForeColor="Blue" />
            </div>
        </div>
</code>```

i should be able to modify the method below to process the the images without having to rewrite the method again

```<code> private byte[]ConvertImage()
        {

            byte[] bytes = null;
           // byte[] bytes2 = null;
            try
            {

                HttpPostedFile postedFile = Upload1.PostedFile;

                string filename = Path.GetFileName(postedFile.FileName);
                string fileExtension = Path.GetExtension(filename);
                int filesize = postedFile.ContentLength;

                Stream stream = postedFile.InputStream;
                BinaryReader binaryreader = new BinaryReader(stream);

                bytes = binaryreader.ReadBytes((int)stream.Length);
                return bytes;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
</code>```

The above code is what i'm using to just one fileUpload but i want to use it two without having to rewrite the whole code

答:
private byte[]ConvertImage(FileUpload file)
        {

```<code>        byte[] bytes = null;
       // byte[] bytes2 = null;
        try
        {

            HttpPostedFile postedFile = file.PostedFile;

            string filename = Path.GetFileName(postedFile.FileName);
            string fileExtension = Path.GetExtension(filename);
            int filesize = postedFile.ContentLength;

            Stream stream = postedFile.InputStream;
            BinaryReader binaryreader = new BinaryReader(stream);

            bytes = binaryreader.ReadBytes((int)stream.Length);
            return bytes;
        }
        catch (Exception ex)
        {
            return null;
        }

    }
</code>```

that's all i had to make it work

Body:
For my Little application, i have written a method to convert an image to binary and then save it in database. What i want to do now , is to find of way of making that same method be reuseable by other fileUpload. Which means, if i have two fileUploads eg.

                Image 1

                Image 2
                <asp:FileUpload ID="Upload2" runat="server" ForeColor="Blue" />

i should be able to modify the method below to process the the images without having to rewrite the method again

 private byte[]ConvertImage()
        {

            byte[] bytes = null;
           // byte[] bytes2 = null;
            try
            {

                HttpPostedFile postedFile = Upload1.PostedFile;

                string filename = Path.GetFileName(postedFile.FileName);
                string fileExtension = Path.GetExtension(filename);
                int filesize = postedFile.ContentLength;

                Stream stream = postedFile.InputStream;
                BinaryReader binaryreader = new BinaryReader(stream);

                bytes = binaryreader.ReadBytes((int)stream.Length);
                return bytes;
            }
            catch (Exception ex)
            {
                return null;
            }

        }

The above code is what i'm using to just one fileUpload but i want to use it two without having to rewrite the whole code

Body:
private byte[]ConvertImage(FileUpload file)
        {

        byte[] bytes = null;
       // byte[] bytes2 = null;
        try
        {

            HttpPostedFile postedFile = file.PostedFile;

            string filename = Path.GetFileName(postedFile.FileName);
            string fileExtension = Path.GetExtension(filename);
            int filesize = postedFile.ContentLength;

            Stream stream = postedFile.InputStream;
            BinaryReader binaryreader = new BinaryReader(stream);

            bytes = binaryreader.ReadBytes((int)stream.Length);
            return bytes;
        }
        catch (Exception ex)
        {
            return null;
        }

    }

that's all i had to make it work


问:
R geo: from points to SpatialPolygonsDataFrame
I am trying to create a SpatialPolygonDataFrame starting from a data.frame with points, but I am not sure about the methodologies. I succeeded in obtaining a list of spatial polygons, but failed to convert them in a SpatialPolygonsDataframe.

Here my data structure:

```<code>               coordinates parcours_id   tm_cid         date_mesure tm_type tm_mnc tm_dbm
34268 (2.670962, 48.48172)             24680199 2017-07-04 01:38:36     lte      1   -113
34269 (2.670522, 48.48981)             24680199 2017-07-04 01:38:44     lte      1   -117
34270 (2.668994, 48.49398)             24657926 2017-07-04 01:38:59     lte      1   -116
34271 (2.668994, 48.49398)             24657926 2017-07-04 01:39:05     lte      1   -116
34272 (2.668069, 48.49653)             24657926 2017-07-04 01:39:17     lte      1   -116
34273  (2.667893, 48.5005)             24657926 2017-07-04 01:39:29     lte      1   -108
</code>```

I want to create polygons by tm_cid. I have tried to follow ?SpatialPolygons

```<code>    polygons=c()
    for (value in unique(mesures.sp$tm_cid)){
      sub=subset(mesures.sp,mesures.sp$tm_cid==value)
      x=Polygon(sub@coords)
      polygons=c(polygons,x)
    }

    polygons=as.list(polygons)
#polygons my srl (list with Polygon Class Objects)
    ID=unique(mesures.sp$tm_cid)
    all_poly=c()
    for(value in 1:length(polygons)){
    poly=Polygons(polygons[value], ID[value])
    all_poly=c(all_poly,poly)}

    all_poly=as.list(all_poly)
#all_poly is my sr (list of object of class SpatialPolygons-class, shouldn't be a list but I failed to do otherwise)

    spatPoly=c()
    for(value in 1:length(polygons)){
      spol=SpatialPolygons(all_poly[value])
      spatPoly=c(spatPoly,spol)}

    ID=as.data.frame(ID)
    spdf=c()
    for(value in 1:length(polygons)){
      data=ID[value,1]
      df=SpatialPolygonsDataFrame(spatPoly[[value]],data=data)
      spdf=c(spdf,df)
    }
</code>```

I am getting this error:

Error in if (length(Sr@polygons) != nrow(data)) stop(paste("Object
  length mismatch:\n    ",  :    argument is of length zero

Any idea?

答:
```<code>require(rgeos)
require(rgdal)
require(maptools)
</code>```

(mesure.sp is a SpatialPontDataFrame)

```<code>   polygons=c()
    for (value in unique(mesures.sp$tm_cid)){
      sub=subset(mesures.sp,mesures.sp$tm_cid==value)
      x=Polygon(sub@coords)
      polygons=c(polygons,x)
    }

    polygons=as.list(polygons)
#polygons my srl (list with Polygon Class Objects)
    ID=unique(mesures.sp$tm_cid)
    all_poly=c()
    for(value in 1:length(polygons)){
    poly=Polygons(polygons[value], ID[value])
    all_poly=c(all_poly,poly)}

    all_poly=as.list(all_poly)
#all_poly is my sr (list of object of class SpatialPolygons-class, shouldn't be a list but I failed to do otherwise)

    spatPoly=c()
    for(value in 1:length(polygons)){
      spol=SpatialPolygons(all_poly[value])
      spol@proj4string=CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
      spatPoly=c(spatPoly,spol)}

    spoly=spatPoly[[1]]
for(value in 2:length(spatPoly)){
  spoly=c(spoly,spatPoly[[value]])
}

    spoly=as.list(spoly)
spdf=c()
    for(value in 1:length(polygons)){
        data=as.data.frame(ID[value])
  row.names(data)=data$ID

      df=SpatialPolygonsDataFrame(spatPoly[[value]],data=data)
      spdf=c(spdf,df)
    }

    final_spdf=spdf[[1]]
for(value in 2:length(spdf)){
  final_spdf=spRbind(final_spdf,spdf[[value]])}
</code>```

Body:
I am trying to create a SpatialPolygonDataFrame starting from a data.frame with points, but I am not sure about the methodologies. I succeeded in obtaining a list of spatial polygons, but failed to convert them in a SpatialPolygonsDataframe.

Here my data structure:

               coordinates parcours_id   tm_cid         date_mesure tm_type tm_mnc tm_dbm
34268 (2.670962, 48.48172)             24680199 2017-07-04 01:38:36     lte      1   -113
34269 (2.670522, 48.48981)             24680199 2017-07-04 01:38:44     lte      1   -117
34270 (2.668994, 48.49398)             24657926 2017-07-04 01:38:59     lte      1   -116
34271 (2.668994, 48.49398)             24657926 2017-07-04 01:39:05     lte      1   -116
34272 (2.668069, 48.49653)             24657926 2017-07-04 01:39:17     lte      1   -116
34273  (2.667893, 48.5005)             24657926 2017-07-04 01:39:29     lte      1   -108

I want to create polygons by tm_cid. I have tried to follow ?SpatialPolygons

    polygons=c()
    for (value in unique(mesures.sp$tm_cid)){
      sub=subset(mesures.sp,mesures.sp$tm_cid==value)
      x=Polygon(sub@coords)
      polygons=c(polygons,x)
    }

    polygons=as.list(polygons)
#polygons my srl (list with Polygon Class Objects)
    ID=unique(mesures.sp$tm_cid)
    all_poly=c()
    for(value in 1:length(polygons)){
    poly=Polygons(polygons[value], ID[value])
    all_poly=c(all_poly,poly)}

    all_poly=as.list(all_poly)
#all_poly is my sr (list of object of class SpatialPolygons-class, shouldn't be a list but I failed to do otherwise)

    spatPoly=c()
    for(value in 1:length(polygons)){
      spol=SpatialPolygons(all_poly[value])
      spatPoly=c(spatPoly,spol)}

    ID=as.data.frame(ID)
    spdf=c()
    for(value in 1:length(polygons)){
      data=ID[value,1]
      df=SpatialPolygonsDataFrame(spatPoly[[value]],data=data)
      spdf=c(spdf,df)
    }

I am getting this error:

Error in if (length(Sr@polygons) != nrow(data)) stop(paste("Object
  length mismatch:\n    ",  :    argument is of length zero

Any idea?

Body:
require(rgeos)
require(rgdal)
require(maptools)

(mesure.sp is a SpatialPontDataFrame)

   polygons=c()
    for (value in unique(mesures.sp$tm_cid)){
      sub=subset(mesures.sp,mesures.sp$tm_cid==value)
      x=Polygon(sub@coords)
      polygons=c(polygons,x)
    }

    polygons=as.list(polygons)
#polygons my srl (list with Polygon Class Objects)
    ID=unique(mesures.sp$tm_cid)
    all_poly=c()
    for(value in 1:length(polygons)){
    poly=Polygons(polygons[value], ID[value])
    all_poly=c(all_poly,poly)}

    all_poly=as.list(all_poly)
#all_poly is my sr (list of object of class SpatialPolygons-class, shouldn't be a list but I failed to do otherwise)

    spatPoly=c()
    for(value in 1:length(polygons)){
      spol=SpatialPolygons(all_poly[value])
      spol@proj4string=CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
      spatPoly=c(spatPoly,spol)}

    spoly=spatPoly[[1]]
for(value in 2:length(spatPoly)){
  spoly=c(spoly,spatPoly[[value]])
}

    spoly=as.list(spoly)
spdf=c()
    for(value in 1:length(polygons)){
        data=as.data.frame(ID[value])
  row.names(data)=data$ID

      df=SpatialPolygonsDataFrame(spatPoly[[value]],data=data)
      spdf=c(spdf,df)
    }

    final_spdf=spdf[[1]]
for(value in 2:length(spdf)){
  final_spdf=spRbind(final_spdf,spdf[[value]])}


问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答:
* symbol is reused for two different purpuses in your snippet. First time it is used as a part of type declaration int *, declaring a pointer to int. Second time it is used to dereference a pointer *q, invoking indirection operator.

* can also be used to invoke multiplication operator *q = *q * *q;;

To assign a value to an integer pointed by pointer you need to dereference it. And to assigning integral value other than 0 to a pointer itself (that is what int *q = 8; is doing) requires reinterpret_cast, hence you get this error.


问:
How do I get Composer command arguments for custom scripts?
My goal is to change the current user directory after a project has been created.

I am running composer create-project vendor/repo some-directory, and I have the following section, in the composer.json file.

```<code>{
    "scripts": {
        "post-create-project-cmd": [
            "cd /some/destination"
        ]
    }
}
</code>```

So I need dynamically replace /some/destination with some-directory, specified in the command line arguments.

Is it possible?

答:
What Composer does when you run composer create-project vendor/repo some-directory is (simplifying):

Create the some-directory directory (If the directory is not empty, Composer raises the exception Project directory some-directory/ is not empty.)

Change the current directory to some-directory

Execute the scripts reported in the scripts section of the project composer.json file (In your case the one used from vendor/repo.)

So, if you are showing the scripts section used from the vendor/repo, changing the current directory to the directory where the project is being created is not necessary, since Composer already does that.

If you need to get the current directory from a Bash script listed in the scripts section of the project being created, you just check the content of the variable $PWD, which is the equivalent of getcwd() in PHP.

As example of what done from a Composer project, see the content of ScriptHandler.php, used from the Composer project drupal-composer/drupal-project. It creates some files in the directory whose filename is returned from getcwd().

```<code>$fs = new Filesystem();
$drupalFinder = new DrupalFinder();
$drupalFinder->locateRoot(getcwd());
$drupalRoot = $drupalFinder->getDrupalRoot();
$dirs = [
  'modules',
  'profiles',
  'themes',
];
// Required for unit testing
foreach ($dirs as $dir) {
  if (!$fs->exists($drupalRoot . '/'. $dir)) {
    $fs->mkdir($drupalRoot . '/'. $dir);
    $fs->touch($drupalRoot . '/'. $dir . '/.gitkeep');
  }
}
</code>```

Actually, it is creating the directories inside a directory found inside the current directory, but this doesn't change that the directory where the project is created is set as current directory from Composer.

Body:
My goal is to change the current user directory after a project has been created.

I am running composer create-project vendor/repo some-directory, and I have the following section, in the composer.json file.

{
    "scripts": {
        "post-create-project-cmd": [
            "cd /some/destination"
        ]
    }
}

So I need dynamically replace /some/destination with some-directory, specified in the command line arguments.

Is it possible?

Body:
What Composer does when you run composer create-project vendor/repo some-directory is (simplifying):

Create the some-directory directory (If the directory is not empty, Composer raises the exception Project directory some-directory/ is not empty.)

Change the current directory to some-directory

Execute the scripts reported in the scripts section of the project composer.json file (In your case the one used from vendor/repo.)

So, if you are showing the scripts section used from the vendor/repo, changing the current directory to the directory where the project is being created is not necessary, since Composer already does that.

If you need to get the current directory from a Bash script listed in the scripts section of the project being created, you just check the content of the variable $PWD, which is the equivalent of getcwd() in PHP.

As example of what done from a Composer project, see the content of ScriptHandler.php, used from the Composer project drupal-composer/drupal-project. It creates some files in the directory whose filename is returned from getcwd().

$fs = new Filesystem();
$drupalFinder = new DrupalFinder();
$drupalFinder->locateRoot(getcwd());
$drupalRoot = $drupalFinder->getDrupalRoot();
$dirs = [
  'modules',
  'profiles',
  'themes',
];
// Required for unit testing
foreach ($dirs as $dir) {
  if (!$fs->exists($drupalRoot . '/'. $dir)) {
    $fs->mkdir($drupalRoot . '/'. $dir);
    $fs->touch($drupalRoot . '/'. $dir . '/.gitkeep');
  }
}

Actually, it is creating the directories inside a directory found inside the current directory, but this doesn't change that the directory where the project is created is set as current directory from Composer.


答:
Statement int *q defines a variable of type "pointer to integer", and an initialisation therefore needs to be a pointer value, not an integral value.
So int *q = 8 is not the same as int *q; *q = 8 (which would be undefined behaviour because it dereferences an uninitialized pointer), but more like int *q; q = 8, which makes the misunderstanding more transparent.

Title: Why can't I directly assign an int to an int pointer like this: int *p = 6;?

Body:
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?


问:
Padding ascii characters with spaces in a mix unicode-ascii string
Given a mixed string of unicode and ascii chars, e.g.:

```<code>它看灵魂塑Nike造得和学问同等重要。
</code>```

The goal is to pad the ascii substrings with spaces, i.e.:

```<code>它看灵魂塑 Nike 造得和学问同等重要。
</code>```

I've tried using the ([^[:ascii:]]) regex,  it looks fine in matching the substrings, e.g. https://regex101.com/r/FVHhU1/1

But in code, the substitution with ' \1 ' is not achieving the desired output.

```<code>>>> import re
>>> patt = re.compile('([^[:ascii:]])')
>>> s = u'它看灵魂塑Nike造得和学问同等重要。'
>>> print (patt.sub(' \1 ', s))
它看灵魂塑Nike造得和学问同等重要。
</code>```

How to pad ascii characters with spaces in a mix unicode-ascii string?

答:
The pattern should be:

```<code>([\x00-\x7f]+)
</code>```

So you can use:

```<code>patt = re.compile('([\x00-\x7f]+)')
patt.sub(r' \1 ',s)
</code>```

This generates:

```<code>>>> print(patt.sub(r' \1 ',s))
它看灵魂塑 Nike 造得和学问同等重要。
</code>```

ASCII is defined as a range of characters with hex codes between 00 and 7f. So we define such a range as [\x00-\x7f], use + to denote one or more, and replace the matching group with r' \1 ' to add two spaces.

Body:
Given a mixed string of unicode and ascii chars, e.g.:

它看灵魂塑Nike造得和学问同等重要。

The goal is to pad the ascii substrings with spaces, i.e.:

它看灵魂塑 Nike 造得和学问同等重要。

I've tried using the ([^[:ascii:]]) regex,  it looks fine in matching the substrings, e.g. https://regex101.com/r/FVHhU1/1

But in code, the substitution with ' \1 ' is not achieving the desired output.

>>> import re
>>> patt = re.compile('([^[:ascii:]])')
>>> s = u'它看灵魂塑Nike造得和学问同等重要。'
>>> print (patt.sub(' \1 ', s))
它看灵魂塑Nike造得和学问同等重要。

How to pad ascii characters with spaces in a mix unicode-ascii string?

Body:
The pattern should be:

([\x00-\x7f]+)

So you can use:

patt = re.compile('([\x00-\x7f]+)')
patt.sub(r' \1 ',s)

This generates:

>>> print(patt.sub(r' \1 ',s))
它看灵魂塑 Nike 造得和学问同等重要。

ASCII is defined as a range of characters with hex codes between 00 and 7f. So we define such a range as [\x00-\x7f], use + to denote one or more, and replace the matching group with r' \1 ' to add two spaces.


问:
Grep data from multiple file then feed into a log in Python
I'm new to Python, hopefully someone can help me in this.
I want to grep data from multiple files then combine the data I grep into a single log.

My input files as such:

Input file1 (200MHz)

```<code>Cell_a  freq_100  50
Cell_a  freq_200  6.8
Cell_b  freq_100  70
</code>```

Input file2 (100MHz)

Cell_a  freq_100  100

   Cell_a  freq_200  10.5

   Cell_b  freq_100  60

This is my expected output

[cell]  [freq] [value_frm_file1] [value_frm_file2] [value_frm_file3] [etc...]

Example expected output:-

Cell_a  freq_100 50 100     #50 is taken from file1, 100 from file2

   Cell_a  freq_200 6.8 10.5

   Cell_b  freq_100 70 60

I guess the best way is to store in Python dictionary? Can you give me example or show me how to do this? Here is my code, but I'm only able to get the value one at a time, how to combined them accordingly to it's respective freq type?

```<code>for i in cmaxFreqList: #this is the list base on it's frq type, IE 200MHz, 100MHz etc
    file = path + freqfile
    with open (file) as f:
        data = f.readlines()

    for line in data:
        line = line.rstrip('\n')
        freqlength = len(line.split())
        if freqlength == 3:
            searchFreqValue =re.search("(\S+)\s+(\S+)\s+(\S+)",line)
            cell = searchFreqValue.group(1)
            freq = searchFreqValue.group(2)
            value = searchFreqValue.group(3)
            print ('cell + ' ' + freq + ' ' + value)  #only can get up to printing out one value at a time
</code>```

Thank you for your help!

答:
That's a relatively simple task provided your files are not extremely huge (i.e. their combined data can fit into the working memory while concatenating them). All you need is to create a (cell_name, freq) map (you can use a dict for that) and then append the matching values to it. Once you go through all your files just write to the combined output file the map->value elements and Bob's your uncle:

```<code>import os
import collections

path = "."  # current folder
freq_list = ["100.dat", "200.dat"]  # a list of files to concatenate

result = collections.defaultdict(list)  # a map to hold a list of our results
for file_name in freq_list:  # go through each file name
    with open(os.path.join(path, file_name), "r") as f:  # open the file
        for line in f:  # go through it line by line
            try:
                cell, freq, value = line.split()  # split it by whitespace into 3 elements
            except ValueError:  # invalid line - it didn't have exactly 3 elements
                continue  # ignore the current line and continue with the next
            result[(cell, freq)].append(value)  # append the value to our result map
with open(os.path.join(path, "combined.dat"), "w") as f:  # open our output file for writing
    # Python dictionaries are unsorted (<v3.6), sort the keys when looping through them
    for element in sorted(result):  # loop through each key in our result map
        # write the key (cell name and frequency) separated by space, add space,
        # write the values separated by space and finally add a new line:
        f.write("{} {}\n".format(" ".join(element), " ".join(result[element])))
</code>```

It's unclear from your code what cmaxFreqList contains, but in my example it (freq_list) holds the actual file names - you can of course construct your input file names any way you want (just make sure that os.path.join(path, file_name) constructs a valid path). For example, if the above-listed 100.dat contained:

```Cell_a  freq_100  50
Cell_a  freq_200  6.8
Cell_b  freq_100  70```

and the 200.dat contained:

```Cell_a freq_100 100
Cell_a freq_200 10.5
Cell_b freq_100 60```

the "combined.dat" file will end up as:

```Cell_a freq_100 50 100
Cell_a freq_200 6.8 10.5
Cell_b freq_100 70 60```

Body:
I'm new to Python, hopefully someone can help me in this.
I want to grep data from multiple files then combine the data I grep into a single log.

My input files as such:

Input file1 (200MHz)

Cell_a  freq_100  50
Cell_a  freq_200  6.8
Cell_b  freq_100  70

Input file2 (100MHz)

Cell_a  freq_100  100

   Cell_a  freq_200  10.5

   Cell_b  freq_100  60

This is my expected output

[cell]  [freq] [value_frm_file1] [value_frm_file2] [value_frm_file3] [etc...]

Example expected output:-

Cell_a  freq_100 50 100     #50 is taken from file1, 100 from file2

   Cell_a  freq_200 6.8 10.5

   Cell_b  freq_100 70 60

I guess the best way is to store in Python dictionary? Can you give me example or show me how to do this? Here is my code, but I'm only able to get the value one at a time, how to combined them accordingly to it's respective freq type?

for i in cmaxFreqList: #this is the list base on it's frq type, IE 200MHz, 100MHz etc
    file = path + freqfile
    with open (file) as f:
        data = f.readlines()

    for line in data:
        line = line.rstrip('\n')
        freqlength = len(line.split())
        if freqlength == 3:
            searchFreqValue =re.search("(\S+)\s+(\S+)\s+(\S+)",line)
            cell = searchFreqValue.group(1)
            freq = searchFreqValue.group(2)
            value = searchFreqValue.group(3)
            print ('cell + ' ' + freq + ' ' + value)  #only can get up to printing out one value at a time

Thank you for your help!

Body:
That's a relatively simple task provided your files are not extremely huge (i.e. their combined data can fit into the working memory while concatenating them). All you need is to create a (cell_name, freq) map (you can use a dict for that) and then append the matching values to it. Once you go through all your files just write to the combined output file the map->value elements and Bob's your uncle:

import os
import collections

path = "."  # current folder
freq_list = ["100.dat", "200.dat"]  # a list of files to concatenate

result = collections.defaultdict(list)  # a map to hold a list of our results
for file_name in freq_list:  # go through each file name
    with open(os.path.join(path, file_name), "r") as f:  # open the file
        for line in f:  # go through it line by line
            try:
                cell, freq, value = line.split()  # split it by whitespace into 3 elements
            except ValueError:  # invalid line - it didn't have exactly 3 elements
                continue  # ignore the current line and continue with the next
            result[(cell, freq)].append(value)  # append the value to our result map
with open(os.path.join(path, "combined.dat"), "w") as f:  # open our output file for writing
    # Python dictionaries are unsorted (<v3.6), sort the keys when looping through them
    for element in sorted(result):  # loop through each key in our result map
        # write the key (cell name and frequency) separated by space, add space,
        # write the values separated by space and finally add a new line:
        f.write("{} {}\n".format(" ".join(element), " ".join(result[element])))

It's unclear from your code what cmaxFreqList contains, but in my example it (freq_list) holds the actual file names - you can of course construct your input file names any way you want (just make sure that os.path.join(path, file_name) constructs a valid path). For example, if the above-listed 100.dat contained:

Cell_a  freq_100  50
Cell_a  freq_200  6.8
Cell_b  freq_100  70

and the 200.dat contained:

Cell_a freq_100 100
Cell_a freq_200 10.5
Cell_b freq_100 60

the "combined.dat" file will end up as:

Cell_a freq_100 50 100
Cell_a freq_200 6.8 10.5
Cell_b freq_100 70 60


问:
dialog - show piped output immediately
(This is about the ncurses-based Linux tool 'dialog')

I would like to run a program and print its output in a "dialog --programbox" as soon as this output is available. I use this example for testing:

dummyoutput | dialog --programbox "output" 20 70
```

<p>where 'dummyoutput' is a small Python script, that slowly prints 0 to 4:</p>

<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python
import time
for i in range(5):
    time.sleep(0.5)
    print i
</code>```

Currently, the programbox is displayed but all the output is only shown after 'dummyoutput' finishes.

Can it be achieved that each line is shown in the programbox as soon as it is available (one number after every half second)?

答:
The comment by @jordanm is great and it worked. Then we can easily apply the same principle in the real project.

It is a Java application which uses the log4j logging framework. Besides a FileAppender, I also use a ConsoleAppender to show specific messages directly on the console. The appender has a ImmediateFlush property. If set to true the output appears on the console - and in the dialog programbox - as soon as it is available.

Title: dialog - show piped output immediately

Body:
(This is about the ncurses-based Linux tool 'dialog')

I would like to run a program and print its output in a "dialog --programbox" as soon as this output is available. I use this example for testing:

dummyoutput | dialog --programbox "output" 20 70

where 'dummyoutput' is a small Python script, that slowly prints 0 to 4:

#!/usr/bin/env python
import time
for i in range(5):
    time.sleep(0.5)
    print i

Currently, the programbox is displayed but all the output is only shown after 'dummyoutput' finishes.

Can it be achieved that each line is shown in the programbox as soon as it is available (one number after every half second)?


答:
Because the types don't match.

The 6 itself is not a value of pointer type, it's an integer so it cannot be directly stored in a pointer.

When you do *q = 6 the * dereferences the pointer, so the type becomes int (or rather an lvalue int, i.e. something that can be assigned to).


问:
Changing dropdown options
I am developing a musical store. In that application in makepayment.jsp I have four links for user choice and based on user choice I want change the options in my dropdown. How can I do that?

答: Look at the onChange event of the input component, and JavaScript.

Title: Changing dropdown options


问:
Pattern Matching - Regex
User input Format:

[fieldname1] comparator [fieldvalue1,fieldvalue2,value3],[fieldname2]
  comparator [fieldvalue1,value2,..],..

Need to parse this into:

1.[fieldname1] comparator [fieldvalue1,fieldvalue2,value3]

2.[fieldname2] comparator [fieldvalue1,value2,..] and so on

(ie)each field along with its comparator and value has to be separated.
whereas comparator will be any one of the below:

<=|>=|=|is|<|>|startswith|Starts with|Beginswith|Begins with|Ends
  with|Endswith|

contains

Regex used by me :

([(.)+?](\s)(<=|>=|=|is|<|>|startswith|Starts
  with|Beginswith|Begins with|Ends
  with|Endswith|contains)(\s)[(.)+?](\,)*)

Example:
[company] contains [abc,efg],[email] contains [cdf,test]
above is parsed properly no issues.

Problem:
When field name or field value contains symbol "[" or "]" the parsing goes wrong .

example :
[company] contains [ab[]c,efg],[email] contains [siva,test]

Above is valid but since [] is used as delimiter it stops parsing till [company] contains [ab[] but i want it to parse properly as above eg,

1.[company] contains [ab[]c,efg]

2.[email] contains [siva,test]

Thanks.

答:
First, we must define a regexp that matches the name, another one that matches the comparator, and a third one that matches a value:

```<code>private static final String NAME_RE = "[A-Za-z0-9_]+";
private static final String VALUE_RE = "[A-Za-z0-9_\\[\\]\\.]+";
private static final String COMPARATOR_RE
        = "<=|>=|=|is|<|>|startswith|Starts with|Beginswith|Begins with|Ends with|Endswith|Contains";
</code>```

We can now create the pattern that combines these sub-regexps:

```<code>private static final String RE = "\\s*\\[(" + NAME_RE + ")\\]\\s*"
        + "(" + COMPARATOR_RE + ")\\s*\\[\\s*("
        + VALUE_RE + "(?:\\s*,\\s*" + VALUE_RE + ")*)\\s*\\]"
        + "(?:\\s*,\\s*(.*))?";
private static final Pattern PATTERN
        = Pattern.compile(RE, Pattern.CASE_INSENSITIVE);
</code>```

Note that it matches a single rule that may or may not be followed by a comma and the other rules.

The parsing of a source string must iterate the rules:

```<code>private static void parse(String source) {
    String s = source;
    while (s != null) {
        Matcher matcher = PATTERN.matcher(s);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Invalid syntax: " + source);
        }
        String name = matcher.group(1);
        String comparator = matcher.group(2);
        String values = matcher.group(3);
        s = matcher.group(4);
        System.out.println("[" + name + "] " + comparator + " [" + values + "]");
    }
}
</code>```

Now let's try to parse your two examples:

```<code>private static final String EXAMPLE1 = "[company] contains [abc,efg],[email] contains [cdf,test]";
private static final String EXAMPLE2 = "[company] contains [ab[]c,efg],[email] contains [siva,test]";

public static void main(String[] args) {
    parse(EXAMPLE1);
    parse(EXAMPLE2);
}
</code>```

It produces the following output:

```<code>[company] contains [abc,efg]
[email] contains [cdf,test]
[company] contains [ab[]c,efg]
[email] contains [siva,test]
</code>```

UPDATE:

Note that the contents of a value must be restricted because if "efg]" and "[email] contains [cdf" are both acceptable value, then there is no way to know if these examples are composed of one or two rules.

UPDATE 2:

Here is a pretty loose regexp for VALUE_RE:

```<code>private static final String VALUE_RE
        = "[^,\\[\\]]*(?:\\[[^,\\[\\]]*\\][^,\\[\\]]*)*";
</code>```

Here a value cannot contain any comma, and only balanced brackets, without nesting.

Title: Pattern Matching - Regex

Body:
First, we must define a regexp that matches the name, another one that matches the comparator, and a third one that matches a value:

private static final String NAME_RE = "[A-Za-z0-9_]+";
private static final String VALUE_RE = "[A-Za-z0-9_\\[\\]\\.]+";
private static final String COMPARATOR_RE
        = "<=|>=|=|is|<|>|startswith|Starts with|Beginswith|Begins with|Ends with|Endswith|Contains";

We can now create the pattern that combines these sub-regexps:

private static final String RE = "\\s*\\[(" + NAME_RE + ")\\]\\s*"
        + "(" + COMPARATOR_RE + ")\\s*\\[\\s*("
        + VALUE_RE + "(?:\\s*,\\s*" + VALUE_RE + ")*)\\s*\\]"
        + "(?:\\s*,\\s*(.*))?";
private static final Pattern PATTERN
        = Pattern.compile(RE, Pattern.CASE_INSENSITIVE);

Note that it matches a single rule that may or may not be followed by a comma and the other rules.

The parsing of a source string must iterate the rules:

private static void parse(String source) {
    String s = source;
    while (s != null) {
        Matcher matcher = PATTERN.matcher(s);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Invalid syntax: " + source);
        }
        String name = matcher.group(1);
        String comparator = matcher.group(2);
        String values = matcher.group(3);
        s = matcher.group(4);
        System.out.println("[" + name + "] " + comparator + " [" + values + "]");
    }
}

Now let's try to parse your two examples:

private static final String EXAMPLE1 = "[company] contains [abc,efg],[email] contains [cdf,test]";
private static final String EXAMPLE2 = "[company] contains [ab[]c,efg],[email] contains [siva,test]";

public static void main(String[] args) {
    parse(EXAMPLE1);
    parse(EXAMPLE2);
}

It produces the following output:

[company] contains [abc,efg]
[email] contains [cdf,test]
[company] contains [ab[]c,efg]
[email] contains [siva,test]

UPDATE:

Note that the contents of a value must be restricted because if "efg]" and "[email] contains [cdf" are both acceptable value, then there is no way to know if these examples are composed of one or two rules.

UPDATE 2:

Here is a pretty loose regexp for VALUE_RE:

private static final String VALUE_RE
        = "[^,\\[\\]]*(?:\\[[^,\\[\\]]*\\][^,\\[\\]]*)*";

Here a value cannot contain any comma, and only balanced brackets, without nesting.


问:
Kafka Proper Way to Poll No Records
for keeping my consumer alive (very long variable length processing) I'm implementing a empty poll() call in a background thread that will keep the broker from rebalancing if I spend too much time between polls().  I have set my poll-interval to be very long, but I don't want to just keep increasing it forever for longer and longer processing.

What's the proper way to poll for no records?  Currently I'm calling poll(), then re-seeking back to the earliest offsets for each partition returned in the poll call() so they can be read properly by the main thread once it's done processing the previous messages.

```<code>ConsumerRecords<String, String> msgs = kafkaConsumer.poll(timeout);
Map<Integer, Long> partitionToOffsets = getEarliestPartitionOffsets(msgs); // helper method
seekToOffsets(partitionToOffsets);
</code>```

答:
The proper way to handle long processing time (and avoiding consumer rebalance)  is to use KafkaConsumer.pause() / KafkaConsumer.resume() methods. You can read more about it here:

KafkaConsumer JavaDoc

Apache Kafka JIRA

Title: Kafka Proper Way to Poll No Records

Body:
for keeping my consumer alive (very long variable length processing) I'm implementing a empty poll() call in a background thread that will keep the broker from rebalancing if I spend too much time between polls().  I have set my poll-interval to be very long, but I don't want to just keep increasing it forever for longer and longer processing.

What's the proper way to poll for no records?  Currently I'm calling poll(), then re-seeking back to the earliest offsets for each partition returned in the poll call() so they can be read properly by the main thread once it's done processing the previous messages.

ConsumerRecords<String, String> msgs = kafkaConsumer.poll(timeout);
Map<Integer, Long> partitionToOffsets = getEarliestPartitionOffsets(msgs); // helper method
seekToOffsets(partitionToOffsets);


问:
Sort array by value within secondary array php
Below I have an array that I generate, I need to order each by the 3rd [2] values.

Array:

```<code>{
aknox: {
    0: "28",
    1: "39",
    2: "71.79"
    },
    lphillips: {
    0: "81",
    1: "106",
    2: "76.42"
    }
}
</code>```

Expected result:

```<code>{
    lphillips: {
    0: "81",
    1: "106",
    2: "76.42"
    },
    aknox: {
    0: "28",
    1: "39",
    2: "71.79"
    }
}
</code>```

I have tried the following:

```<code>usort($ccstats, function($a, $b) {
   return strcmp($a[2], $b[2]);
});
</code>```

$ccstats being the array.

This returns the array in ascending order when I tried to make array keys in descending order i.e. "akonx" and "lphillips" get lost and turned into 0 and 1

Any help appreciated

答:
To preserve keys use uasort:

```<code>uasort($ccstats, function($a, $b) {
   return strcmp($a[2], $b[2]);
});
</code>```

If you say that you have ascending order but want descending, then just swap arguments in strcmp

```<code>uasort($ccstats, function($a, $b) {
   return strcmp($b[2], $a[2]);
});
</code>```

Body:
Below I have an array that I generate, I need to order each by the 3rd [2] values.

Array:

{
aknox: {
    0: "28",
    1: "39",
    2: "71.79"
    },
    lphillips: {
    0: "81",
    1: "106",
    2: "76.42"
    }
}

Expected result:

{
    lphillips: {
    0: "81",
    1: "106",
    2: "76.42"
    },
    aknox: {
    0: "28",
    1: "39",
    2: "71.79"
    }
}

I have tried the following:

usort($ccstats, function($a, $b) {
   return strcmp($a[2], $b[2]);
});

$ccstats being the array.

This returns the array in ascending order when I tried to make array keys in descending order i.e. "akonx" and "lphillips" get lost and turned into 0 and 1

Any help appreciated

Body:
To preserve keys use uasort:

uasort($ccstats, function($a, $b) {
   return strcmp($a[2], $b[2]);
});

If you say that you have ascending order but want descending, then just swap arguments in strcmp

uasort($ccstats, function($a, $b) {
   return strcmp($b[2], $a[2]);
});


问:
android cardview showing border around card
Android cardview is showing unnecessary border around the card. I have tried different things but I am not able to remove it.
It happens when I give the card a custom background color.
When I remove the cardBackgroundColor, and when default is used. Then unnecessary border is not visible.

I have to use shadow and tranparent color code.

Here is my layout CardView

```<code>         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="@dimen/margin"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/user" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etEmail"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/username"
                                android:singleLine="true"
                                android:maxLines="1"/>

                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/margin_large"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/password" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilPassword"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etPassword"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/password"
                                android:singleLine="true"
                                android:maxLines="1"
                                android:inputType="textPassword"/>
                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView >

            <LinearLayout
                android:id="@+id/llGo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:orientation="vertical"
                android:elevation="@dimen/margin_large"
                >

                <include layout="@layout/go_button" />

            </LinearLayout>

        </RelativeLayout>
</code>```

And the view created is this

See the extra border on left, right and top of cardview and inside the card shadow.

答:
try this.</p>

```<code>  <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                android:elevation="0dp"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="0dp"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >
</code>```

Body:
Android cardview is showing unnecessary border around the card. I have tried different things but I am not able to remove it.
It happens when I give the card a custom background color.
When I remove the cardBackgroundColor, and when default is used. Then unnecessary border is not visible.

I have to use shadow and tranparent color code.

Here is my layout CardView

         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="@dimen/margin"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/user" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etEmail"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/username"
                                android:singleLine="true"
                                android:maxLines="1"/>

                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/margin_large"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/password" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilPassword"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etPassword"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/password"
                                android:singleLine="true"
                                android:maxLines="1"
                                android:inputType="textPassword"/>
                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView >

            <LinearLayout
                android:id="@+id/llGo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:orientation="vertical"
                android:elevation="@dimen/margin_large"
                >

                <include layout="@layout/go_button" />

            </LinearLayout>

        </RelativeLayout>

And the view created is this

See the extra border on left, right and top of cardview and inside the card shadow.

Body:
try this.

  <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                android:elevation="0dp"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="0dp"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >


问:
Can I host two separate web servers on a LAN to the outside world through 1 IP address?
I am a web programmer with a home web dev operation. I have multiple web servers in my house on a FIOS connection. I have my own domain pointed to my router through dyndns.org's custom domain service.

My ISP gives me ONE static IP address, which at the moment allows me to configure my router to direct outbound web traffic from one server through port 80 and another server through port 8080. This sucks because many companies block port 8080 these days causing some of my corporate clients to not be able to hit my second web server.

Is there any way for me to direct regular old port 80 web traffic to TWO SEPARATE web servers internally on my network using two separate host names?

For instance. I want http://webserver1.mydomain.com to hit one web server on my network, and http://webserver2.mydomain.com to hit another web server and have both sets of traffic served on port 80.

Is this even possible? If not, can I do a hack by programmatically routing traffic from one web server transparently to another?

For the record I run MS Windows Server 2008 IIS 7.0 stack, a D-link DIR-655 router, and use DynDNS for my domain needs.

答: Yes, use IIS7's Rewrite module to do this</p>

OwnerDisplayName: Matias Nino

OwnerDisplayName: Paul Betts