问:
Algorithm for possible permutations based on percentages
Im looking to find all the possible permutations of the following 6 letters in 7 letter sets. [a,b,c,d,e,f].

The problem is that each letter corresponds to a certain percentage. The total percentage for each 7 letter set needs to be 100%

A: 0% <= a < 1%

B: 1% <= b <= 5%

C: 5% < c <= 25%

D: 25% < d <= 50%

E: 50% < e <= 75%

F: 75% < f <= 100%

For example, these are possible sets:

[a,a,a,a,a,a,f] : all the A's could be 0% and the F could be 100%

[d,d,b,a,a,a,a] : D's could be 47% each. B could be 5% and the A's could make up the remaining 1%.

But these are impossible: [f,a,a,a,a,a,f] or [e,e,e,a,a,a,a] because their totals are more than 100%.

Ive been trying to do it in javascript but haven't had much luck. I was able to generate all the possible permutations using this fiddle: https://jsfiddle.net/v4s6xk5x/. Unfortunately, this doesn't take into account the percentages.

I really just want the permutations and don't need code. But code in any language would be helpful so that I can understand what is going on.

Let me know if you need any more information.

答:
Example of a recursive solution:

As input you have:

```<code>size: 7
letters: [a,b,c,d,e,f]
minval: [0,1,5,25,50,75]
maxval: [1,5,25,50,75,100]
</code>```

Start by making an empty set and a minimum and maximum value of this set:

```<code>set: []
min: 0
max: 0
</code>```

Then pass this set to the recursive function, which should:

Iterate over every letter.

Check whether the set's min value + the letter's min value <= 100.

If it is, create a copy of the set, min and max with the letter and the letter's min and max value added; otherwise, continue with next letter.

If the length of the set copy equals size, and its max value >= 100, this is a valid set; print or add to output.

if the length of the set copy is smaller than size, recurse with set_copy, min_copy and max_copy.

This should work for any size, any number of letters, and any set of min and max values, whether they are ordered or not.

This will produce duplicates, like:

```<code>[a,a,a,a,a,a,f]
[a,a,a,a,a,f,a]
[a,a,a,a,f,a,a]
...
</code>```

If you  only want to generate unique solutions, start iterating over the letters from the previous letter that was added to the set.

Here's a code example. It's a literal translation of the steps laid out above, with the added feature that it only generates unique solutions by passing the index of the previously added letter to the recursion (variable prev) and then starts iterating from that letter to the last. If you want non-unique solutions, start iterating from 0 each time.

Checking whether the minimum values are < 100 instead of <= 100 makes sure that all ranges exclude the low threshold and include the high threshold.

Note that all variables received as arguments by addLetter() or declared with var inside addLetter() are local variables, and seperate for each recursion.

function rangeSet(size, letters, minval, maxval) {
    addLetter([], 0, 0, 0);

    function addLetter(set, min, max, prev) {
        for (var lt = prev; lt < letters.length; lt++) {
            if (min + minval[lt] < 100) {
                var set_copy = set.concat([letters[lt]]);
                var min_copy = min + minval[lt];
                var max_copy = max + maxval[lt];
                if (set_copy.length == size) {
                    if (max_copy >= 100) {
                        document.write(set_copy + "
");
                    }
                }
                else addLetter(set_copy, min_copy, max_copy, lt);
            }
        }
    }
}

rangeSet(7, ['a','b','c','d','e','f'], [0,1,5,25,50,75], [1,5,25,50,75,100]);```

Body:
Example of a recursive solution:

As input you have:

size: 7
letters: [a,b,c,d,e,f]
minval: [0,1,5,25,50,75]
maxval: [1,5,25,50,75,100]

Start by making an empty set and a minimum and maximum value of this set:

set: []
min: 0
max: 0

Then pass this set to the recursive function, which should:

Iterate over every letter.

Check whether the set's min value + the letter's min value <= 100.

If it is, create a copy of the set, min and max with the letter and the letter's min and max value added; otherwise, continue with next letter.

If the length of the set copy equals size, and its max value >= 100, this is a valid set; print or add to output.

if the length of the set copy is smaller than size, recurse with set_copy, min_copy and max_copy.

This should work for any size, any number of letters, and any set of min and max values, whether they are ordered or not.

This will produce duplicates, like:

[a,a,a,a,a,a,f]
[a,a,a,a,a,f,a]
[a,a,a,a,f,a,a]
...

If you  only want to generate unique solutions, start iterating over the letters from the previous letter that was added to the set.

Here's a code example. It's a literal translation of the steps laid out above, with the added feature that it only generates unique solutions by passing the index of the previously added letter to the recursion (variable prev) and then starts iterating from that letter to the last. If you want non-unique solutions, start iterating from 0 each time.

Checking whether the minimum values are < 100 instead of <= 100 makes sure that all ranges exclude the low threshold and include the high threshold.

Note that all variables received as arguments by addLetter() or declared with var inside addLetter() are local variables, and seperate for each recursion.

function rangeSet(size, letters, minval, maxval) {
    addLetter([], 0, 0, 0);

    function addLetter(set, min, max, prev) {
        for (var lt = prev; lt < letters.length; lt++) {
            if (min + minval[lt] < 100) {
                var set_copy = set.concat([letters[lt]]);
                var min_copy = min + minval[lt];
                var max_copy = max + maxval[lt];
                if (set_copy.length == size) {
                    if (max_copy >= 100) {
                        document.write(set_copy + "<br>");
                    }
                }
                else addLetter(set_copy, min_copy, max_copy, lt);
            }
        }
    }
}

rangeSet(7, ['a','b','c','d','e','f'], [0,1,5,25,50,75], [1,5,25,50,75,100]);


来源: stackexchange

问:
Find file and line of 'unexpectedly found nil'
I updated to Xcode 8.3.3 and updated my OS, a bunch of pods, and so on.  Now when I crash on unexpectedly found nil it takes me to a stack trace with it stopped on 'exc_breakpoint' (see screen shot).  I have no breakpoints set.

I can't effectively troubleshoot these 'nil' errors because I don't know where they're occurring in my project (I can do it slowly by using a back trace and trying to sort through the messages, but this is way slower than if it just landed me on the right line like it used to do.)

Do I have some setting turned on by accident?  Is this a bug?  How can I get Xcode to go straight to the line of the nil crash?

Thanks!

答:
Yes, I'm also faced this issues in  my project. I just used to solve this by setting breakpoint in my code and I run manually line by line. Finally it will shows the nil value passing line.

If I faced crash issue while clicking any action button i will set breakpoint and run it line by line.

else if I faced crash issue while page loading. I will set breakpoint in viewdidload & viewdidappear

else I will set breakpoint in functions.

or try to use exception breakpoint

Through this above method I will solve crash issue in my project.

ContentLicense: CC BY-SA 3.0


问:
How to Convert factors to Dates in R
I have a set of dates from this csv file and want to convert them to a date format in R

```<code>BPL16_17 <- read.csv("BPL16:17.csv")
attach(BPL16_17)
newdate<-strptime(Date,format =("%Y-%m-%d"))
newdate
</code>```

for newdate i get; [1] NA NA NA NA NA NA NA NA...

答:
Try using the option stringsAsFactors=FALSE inside read.csv to read the Date column as a string and not as a factor.

Or, convert the Date column from factor to character using as.character(BPL16_17$Date)

Title: How to Convert factors to Dates in R

Body:
I have a set of dates from this csv file and want to convert them to a date format in R

BPL16_17 <- read.csv("BPL16:17.csv")
attach(BPL16_17)
newdate<-strptime(Date,format =("%Y-%m-%d"))
newdate

for newdate i get; [1] NA NA NA NA NA NA NA NA...


问:
.getText() not retrieving the text message from div class tag
From the following HTML code

```<code><div class="message-main-contents">
  <div class="message-title">Title Message</div>
  <div class="message-content">
    <div class="licenseexpiryannouncement">
        <div>
            Message Content 1
            <a class="licenseexpiryannouncement-installlicenselink">Link that can be clicked</a>
            under Home> Upload.
        </div>
        <div>Message Content 2</div>
    </div>
</div>
</code>```

I am trying to retrieve the "Title Message" text using the following code but is returning empty string

```<code>@FindBy(how = How.XPATH, using = "//div[contains(@class, 'message-title')]")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getText();
System.out.println(titleMessage);
</code>```

答:
I have also encountered this sometimes in my code that the getText() method do not return you with the text and instead return an empty string. I have found a workaround for this by reading the attribute value "textContent".

you can read the text using a workaround

```<code>String titleMessage = contentMessageTitle.getAttribute("textContent");
</code>```

This way you can read the content of the 'contentMessageTitle' locator.

Body:
From the following HTML code

Title Message

            Message Content 1
            Link that can be clicked
            under Home> Upload.

Message Content 2

I am trying to retrieve the "Title Message" text using the following code but is returning empty string

@FindBy(how = How.XPATH, using = "//div[contains(@class, 'message-title')]")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getText();
System.out.println(titleMessage);

Body:
I have also encountered this sometimes in my code that the getText() method do not return you with the text and instead return an empty string. I have found a workaround for this by reading the attribute value "textContent".

you can read the text using a workaround

String titleMessage = contentMessageTitle.getAttribute("textContent");

This way you can read the content of the 'contentMessageTitle' locator.


问:
Adding custom sizes to Media Uploader to select it when inserting new image
I am building a custom theme and trying to customize the sizes list of media library,but did not work for me, i`m using the code in codex

```<code>add_image_size( 'custom-size', 220, 180, true );
add_filter( 'image_size_names_choose', 'my_custom_sizes' );

function my_custom_sizes( $sizes ) {
  return array_merge( $sizes, array(
     'custom-size' => __( 'Your Custom Size Name' ),
  ) );
}
</code>```

Note: I`m using Wordpress 4.1 :)

答:
A lot of time has passed (and I'm on WordPress 4.7), but I was having the same issue tonight and found a solution. Instead of

```<code>add_image_size( 'custom-size', 220, 180, true );
add_filter( 'image_size_names_choose', 'my_custom_sizes' );

function my_custom_sizes( $sizes ) {
  return array_merge( $sizes, array(
     'custom-size' => __( 'Your Custom Size Name' ),
  ) );
}
</code>```

I had to refactor my code to pass my function as the second parameter to add_filter, like so:

```<code>add_image_size( 'custom-size', 220, 180, true );
add_filter( 'image_size_names_choose', function ( $sizes ) {
  return array_merge( $sizes, array(
     'custom-size' => __( 'Your Custom Size Name' ),
  ) );
} );
</code>```

I came up with this solution after right-clicking the empty 'Size' dropdown on the Media select screen and choosing 'Inspect Element', which allowed me to see the error. I'm not sure if changes in WordPress or my host (Site5) caused the issue, but I hope this answer will help someone.

Body:
I am building a custom theme and trying to customize the sizes list of media library,but did not work for me, i`m using the code in codex

add_image_size( 'custom-size', 220, 180, true );
add_filter( 'image_size_names_choose', 'my_custom_sizes' );

function my_custom_sizes( $sizes ) {
  return array_merge( $sizes, array(
     'custom-size' => __( 'Your Custom Size Name' ),
  ) );
}

Note: I`m using Wordpress 4.1 :)

Body:
A lot of time has passed (and I'm on WordPress 4.7), but I was having the same issue tonight and found a solution. Instead of

add_image_size( 'custom-size', 220, 180, true );
add_filter( 'image_size_names_choose', 'my_custom_sizes' );

function my_custom_sizes( $sizes ) {
  return array_merge( $sizes, array(
     'custom-size' => __( 'Your Custom Size Name' ),
  ) );
}

I had to refactor my code to pass my function as the second parameter to add_filter, like so:

add_image_size( 'custom-size', 220, 180, true );
add_filter( 'image_size_names_choose', function ( $sizes ) {
  return array_merge( $sizes, array(
     'custom-size' => __( 'Your Custom Size Name' ),
  ) );
} );

I came up with this solution after right-clicking the empty 'Size' dropdown on the Media select screen and choosing 'Inspect Element', which allowed me to see the error. I'm not sure if changes in WordPress or my host (Site5) caused the issue, but I hope this answer will help someone.


问:
HTML Input Submit Button Won't Change Color
I have a form with a submit button that I'm trying to change the color to. This should be very simple, but my css isn't working and I can't figure out why.

The CSS:

```<code>input[type="submit"]{color: red;}
</code>```

Fiddle:
https://jsfiddle.net/zn7xrv60/

This is driving me nuts, any help would be appreciated.

答:
since your login button is disabled at the time you need to do something like this.</p>

```<code>.login_content .container .submit input:disabled {
//css
}
</code>```

Body:
I have a form with a submit button that I'm trying to change the color to. This should be very simple, but my css isn't working and I can't figure out why.

The CSS:

input[type="submit"]{color: red;}

Fiddle:
https://jsfiddle.net/zn7xrv60/

This is driving me nuts, any help would be appreciated.

Body:
since your login button is disabled at the time you need to do something like this.

.login_content .container .submit input:disabled {
//css
}


问:
Using the DTM tool to load a synchronous third party javascript before DOM ready
I am looking to use the DTM tool to load a synchronous third party javascript before DOM ready and not on page load. Is this possible?</p>

答:
Adobe DTM has four main Load Order Types for controlling when a page rule is evaluated, two of which occur before DOM ready: "Top of Page" and "Bottom of Page".

Within the rule, for 3rd party script tags, you can choose various options for loading the tag sequentially (synchronously): "Sequential HTML", "Sequential Javascript Local", and "Sequential Javascript Global".

Note: DTM makes use document.write to accomplish this functionality, which may be blocked by users who use Chrome on slow internet connections.


问:
How to specify output bindings of Azure Function from Visual studio 2017 preview 2?
In Azure portal, one can easily configure the output bindings of an Azure function, from the 'Integrate' page of that function.
These settings Eventually go into the function.json.

My question is, how can I set these values from Visual studio ?
The code looks like this:

```<code>public static class SomeEventProcessor
{
    [FunctionName("SomeEventProcessor")]

    public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req,
        TraceWriter log,
        IAsyncCollector<EventInfo> outputQueue)
    {
        log.Info("C# HTTP trigger function processed a request.");

        EventInfo eventInfo = new EventInfo(); //Just a container
        eventInfo.SomeID = req.Headers.Contains("SomeID") ? req.Headers.GetValues("SomeID").First() : null;

        //Write to a queue and promptly return
        await outputQueue.AddAsync(eventInfo);

        return req.CreateResponse(HttpStatusCode.OK);

    }
}
</code>```

I want to specify which queue and which storage to use, from VS, so that I can source control my code and config. I have checked out similar questions, suggested questions etc, but none proved handy.

I am using
Visual studio 2017 preview, Version 15.3.0 Preview 3

VS Extension: Azure Function tools for VS, version 0.2

答:
The bindings are specified just as your trigger, using attributes on the parameters they should be bound to. The binding configuration (e.g. the queue name, connection, etc.) is provided as attribute parameters/properties.

Using your code as an example, a queue output binding would look like this:

```<code>public static class SomeEventProcessor
{
    [FunctionName("SomeEventProcessor")]

    public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post")]HttpRequestMessage req,
        TraceWriter log,
        [Queue("myQueueName", Connection = "myconnection")] IAsyncCollector<EventInfo> outputQueue)
    {
        log.Info("C# HTTP trigger function processed a request.");

        EventInfo eventInfo = new EventInfo(); //Just a container
        eventInfo.SomeID = req.Headers.Contains("SomeID") ? req.Headers.GetValues("SomeID").First() : null;

        //Write to a queue and promptly return
        await outputQueue.AddAsync(eventInfo);

        return req.CreateResponse(HttpStatusCode.OK);

    }
}
</code>```

If you're just returning a 200 from your HTTP function (Ok), you can furtner simplify your code by applying the attribute to the method's return value, which, again using your code as an example, would look like this:

```<code>[FunctionName("SomeEventProcessor")]
[return: Queue("myQueueName", Connection = "myconnection")]
public static EventInfo Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post")]HttpRequestMessage req,
    TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    EventInfo eventInfo = new EventInfo(); //Just a container
    eventInfo.SomeID = req.Headers.Contains("SomeID") ? req.Headers.GetValues("SomeID").First() : null;

    return eventInfo;
}
</code>```

Using the code above, Azure Functions will automatically return a 200 when your functions succeeds and a 500 when/if an exception is thrown.

Body:
In Azure portal, one can easily configure the output bindings of an Azure function, from the 'Integrate' page of that function.
These settings Eventually go into the function.json.

My question is, how can I set these values from Visual studio ?
The code looks like this:

public static class SomeEventProcessor
{
    [FunctionName("SomeEventProcessor")]

    public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req,
        TraceWriter log,
        IAsyncCollector<EventInfo> outputQueue)
    {
        log.Info("C# HTTP trigger function processed a request.");

        EventInfo eventInfo = new EventInfo(); //Just a container
        eventInfo.SomeID = req.Headers.Contains("SomeID") ? req.Headers.GetValues("SomeID").First() : null;

        //Write to a queue and promptly return
        await outputQueue.AddAsync(eventInfo);

        return req.CreateResponse(HttpStatusCode.OK);

    }
}

I want to specify which queue and which storage to use, from VS, so that I can source control my code and config. I have checked out similar questions, suggested questions etc, but none proved handy.

I am using
Visual studio 2017 preview, Version 15.3.0 Preview 3

VS Extension: Azure Function tools for VS, version 0.2

Body:
The bindings are specified just as your trigger, using attributes on the parameters they should be bound to. The binding configuration (e.g. the queue name, connection, etc.) is provided as attribute parameters/properties.

Using your code as an example, a queue output binding would look like this:

public static class SomeEventProcessor
{
    [FunctionName("SomeEventProcessor")]

    public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post")]HttpRequestMessage req,
        TraceWriter log,
        [Queue("myQueueName", Connection = "myconnection")] IAsyncCollector<EventInfo> outputQueue)
    {
        log.Info("C# HTTP trigger function processed a request.");

        EventInfo eventInfo = new EventInfo(); //Just a container
        eventInfo.SomeID = req.Headers.Contains("SomeID") ? req.Headers.GetValues("SomeID").First() : null;

        //Write to a queue and promptly return
        await outputQueue.AddAsync(eventInfo);

        return req.CreateResponse(HttpStatusCode.OK);

    }
}

If you're just returning a 200 from your HTTP function (Ok), you can furtner simplify your code by applying the attribute to the method's return value, which, again using your code as an example, would look like this:

[FunctionName("SomeEventProcessor")]
[return: Queue("myQueueName", Connection = "myconnection")]
public static EventInfo Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post")]HttpRequestMessage req,
    TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    EventInfo eventInfo = new EventInfo(); //Just a container
    eventInfo.SomeID = req.Headers.Contains("SomeID") ? req.Headers.GetValues("SomeID").First() : null;

    return eventInfo;
}

Using the code above, Azure Functions will automatically return a 200 when your functions succeeds and a 500 when/if an exception is thrown.


问:
Best way to apply a transform to every element in a list at the same time in Kotlin
Basically I'm trying to apply a long-running transformation to a list of elements in Kotlin. Right now I'm using the .map function, but this causes all of the transformations to run serially, when I need them to run simultaneously because of time.

Here's how it works now:

```<code>async {
    val list = await { list.execute().items.map { initialValue ->
        getResultAfterALongTime(initialValue)
    }}
    onCompletion(list)
}
</code>```

As I explained, the function .map runs the transformation and then waits for it to finish before preceding to the next element. How should I alter this to allow the transformations to run concurrently and the proced when they're all finished?

答:
parallelStream should help.

```<code>async {
    val list = await { list.execute().items.parallelStream().map { initialValue ->
        getResultAfterALongTime(initialValue)
    }}
    onCompletion(list)
}
</code>```

Body:
Basically I'm trying to apply a long-running transformation to a list of elements in Kotlin. Right now I'm using the .map function, but this causes all of the transformations to run serially, when I need them to run simultaneously because of time.

Here's how it works now:

async {
    val list = await { list.execute().items.map { initialValue ->
        getResultAfterALongTime(initialValue)
    }}
    onCompletion(list)
}

As I explained, the function .map runs the transformation and then waits for it to finish before preceding to the next element. How should I alter this to allow the transformations to run concurrently and the proced when they're all finished?

Body:
parallelStream should help.

async {
    val list = await { list.execute().items.parallelStream().map { initialValue ->
        getResultAfterALongTime(initialValue)
    }}
    onCompletion(list)
}


问:
Undefined method `title=' for #<Post id: nil, created_at: nil, updated_at: nil>
BoardController code:

Error message:

答:
here is the correction for your post controller

```<code>  def create
    @post = Post.new(post_params)
    @post.save
    redirect_to :back
  end

  def post_params
    params.require(:perusahaan).permit(:title,:content)
  end
</code>```

you should put post_params with new

and if you don't have post_params, you can create on bottom of your controller see sample code above

Body:
BoardController code:

Error message:

Body:
here is the correction for your post controller

  def create
    @post = Post.new(post_params)
    @post.save
    redirect_to :back
  end

  def post_params
    params.require(:perusahaan).permit(:title,:content)
  end

you should put post_params with new

and if you don't have post_params, you can create on bottom of your controller see sample code above


问:
Object reference not set to an instance of an object. ListViewItem VB.NET
```<code>Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
    Dim myList As ListViewItem

    Dim JmlList As Integer
    Dim i As Integer

    JmlList = lst_detail.Items.Count - 1
    i = 0

    myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1)) // error at this
    myList.SubItems.Add(txtKodeObat.Text.Trim)
    myList.SubItems.Add(txtNamaObat.Text.Trim)
    myList.SubItems.Add(txtHarga.Text.Trim)
    myList.SubItems.Add(txtQty.Text.Trim)
    myList.SubItems.Add(txtJumlah.Text.Trim)

    Dim subtotal As Double = 0

    JmlList = lst_detail.Items.Count - 1
    For i = 0 To JmlList
        subtotal = subtotal + Val(lst_detail.Items(i).SubItems(5).Text)
    Next
    txtSubTotal.Text = Format(subtotal, "##########")
    txtPPn.Text = Format(subtotal * 0.1, "##########")
    txtTotal.Text = Val(txtSubTotal.Text) + Val(txtPPn.Text)
    txtKodeObat.Text = ""
    txtNamaObat.Text = ""
    txtHarga.Text = "0"
    txtQty.Text = ""
    txtJumlah.Text = "0"
    txtKodeObat.Focus()

End Sub
</code>```

I got error at         myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1))

i want to add from text to listitem but got null error
i have fill that textbox

答: lst_detail or lst_detail.Items seems to be null. Debug the code and you should be able see one of these null. If lst_detail is null and you are trying to access lst_detail.Items it will throw "Null reference" execption - which means you are trying to access something from a object with null value.</p>

Body:
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
    Dim myList As ListViewItem

    Dim JmlList As Integer
    Dim i As Integer

    JmlList = lst_detail.Items.Count - 1
    i = 0

    myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1)) // error at this
    myList.SubItems.Add(txtKodeObat.Text.Trim)
    myList.SubItems.Add(txtNamaObat.Text.Trim)
    myList.SubItems.Add(txtHarga.Text.Trim)
    myList.SubItems.Add(txtQty.Text.Trim)
    myList.SubItems.Add(txtJumlah.Text.Trim)

    Dim subtotal As Double = 0

    JmlList = lst_detail.Items.Count - 1
    For i = 0 To JmlList
        subtotal = subtotal + Val(lst_detail.Items(i).SubItems(5).Text)
    Next
    txtSubTotal.Text = Format(subtotal, "##########")
    txtPPn.Text = Format(subtotal * 0.1, "##########")
    txtTotal.Text = Val(txtSubTotal.Text) + Val(txtPPn.Text)
    txtKodeObat.Text = ""
    txtNamaObat.Text = ""
    txtHarga.Text = "0"
    txtQty.Text = ""
    txtJumlah.Text = "0"
    txtKodeObat.Focus()

End Sub

I got error at         myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1))

i want to add from text to listitem but got null error
i have fill that textbox


问:
How to handle strings with a block ( awk )
Each block starts with 'COL ID' in an input data.
I need to print 'COL ID' and JOB_subid if there is. As you can see in input data, 'COLID=2' has a job_subid(1 / left of table name) but 'COLID=3' or 'COLID=4' doesn't have.
For COLID=3/4, I want to print 'no_data' as it doesn't have any job_subid.
How can I handle this data?

AWK

```<code>/COL ID/        {JOBID=$4;}

/^[0-9]/ {
    JOB_SUBID=$1;
    printf "%s#%s",JOBID,JOB_SUBID;
    printf "\n";
}

END {

if (JOB_SUBID="") then
  JOB_SUBID="no_data";
  printf "%s#%s",JOBID,JOB_SUBID;
  printf "\n";
end if;

}
</code>```

input data

```<code>COL ID    : 2
PID       : 26788

ID     TABLE
------ ------------------------------
1      "SCOTT"."PRINCE01"

COL ID    : 3
PID       : 26788

COL ID    : 4
PID       : 26788
</code>```

Incorrect result

```<code>2#1
4#no_data
</code>```

Required result

```<code>2#1
3#no_data
4#no_data
</code>```

答:
If you want to keep the same style as listed then just add this statement.

/^[^0-9]/ {JOB_SUBID = ""}
and get rid of the END block

Body:
Each block starts with 'COL ID' in an input data.
I need to print 'COL ID' and JOB_subid if there is. As you can see in input data, 'COLID=2' has a job_subid(1 / left of table name) but 'COLID=3' or 'COLID=4' doesn't have.
For COLID=3/4, I want to print 'no_data' as it doesn't have any job_subid.
How can I handle this data?

AWK

/COL ID/        {JOBID=$4;}

/^[0-9]/ {
    JOB_SUBID=$1;
    printf "%s#%s",JOBID,JOB_SUBID;
    printf "\n";
}

END {

if (JOB_SUBID="") then
  JOB_SUBID="no_data";
  printf "%s#%s",JOBID,JOB_SUBID;
  printf "\n";
end if;

}

input data

COL ID    : 2
PID       : 26788

ID     TABLE
------ ------------------------------
1      "SCOTT"."PRINCE01"

COL ID    : 3
PID       : 26788

COL ID    : 4
PID       : 26788

Incorrect result

2#1
4#no_data

Required result

2#1
3#no_data
4#no_data


问:
How to make ImageButton clickable in Android Studio?
I have done an immense amount of research and for whatever reason whatever I try I cannot get an ImageButton to be clickable in Android studio. I have tried numerous things but I must be missing something. I will past XML file below and then Java below that. When I put setOnClickListener method I get a cannot resolve message and same for when I do onClickListener. I would like the button to link to a webpage. Please help!

```<code>   <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.autismacademyed.www.autismacademy.AutismAcademy">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.173" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.0" />

    <ImageButton
        android:id="@+id/imageButtonYellow"
        android:layout_width="109dp"
        android:layout_height="125dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:background="@null"
        android:scaleType="centerCrop"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@mipmap/ic_yellowpuzzlepiece"
        android:onClick="onClick"/>

</android.support.constraint.ConstraintLayout>
</code>```

Here is Java:

```<code>package com.autismacademyed.www.autismacademy;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class AutismAcademy extends AppCompatActivity {

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

    ImageButton imageButtonYellow = (ImageButton)findViewById(R.id.imageButtonYellow);
   imageButtonYellow.setOnClickListener(new View.onClickListener()

    public void onClick (View v) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.aaed.org"));
        startActivity(browserIntent);
    }

}
</code>```

答:
Just copy and paste this two file will work for you. You declare two click listener that's why its not working.

xml file

```<code>  <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.autismacademyed.www.autismacademy.AutismAcademy">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.173" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.0" />

    <ImageButton
        android:id="@+id/imageButtonYellow"
        android:layout_width="109dp"
        android:layout_height="125dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:background="@null"
        android:scaleType="centerCrop"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@mipmap/ic_yellowpuzzlepiece"
        android:onClick="buttonClick"/>

</android.support.constraint.ConstraintLayout>
</code>```

jAVAFILE

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

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

    public void buttonClick(View v) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.aaed.org"));
        startActivity(browserIntent);
    }

}
</code>```

Body:
I have done an immense amount of research and for whatever reason whatever I try I cannot get an ImageButton to be clickable in Android studio. I have tried numerous things but I must be missing something. I will past XML file below and then Java below that. When I put setOnClickListener method I get a cannot resolve message and same for when I do onClickListener. I would like the button to link to a webpage. Please help!

   <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.autismacademyed.www.autismacademy.AutismAcademy">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.173" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.0" />

    <ImageButton
        android:id="@+id/imageButtonYellow"
        android:layout_width="109dp"
        android:layout_height="125dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:background="@null"
        android:scaleType="centerCrop"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@mipmap/ic_yellowpuzzlepiece"
        android:onClick="onClick"/>

</android.support.constraint.ConstraintLayout>

Here is Java:

package com.autismacademyed.www.autismacademy;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class AutismAcademy extends AppCompatActivity {

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

    ImageButton imageButtonYellow = (ImageButton)findViewById(R.id.imageButtonYellow);
   imageButtonYellow.setOnClickListener(new View.onClickListener()

    public void onClick (View v) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.aaed.org"));
        startActivity(browserIntent);
    }

}

Body:
Just copy and paste this two file will work for you. You declare two click listener that's why its not working.

xml file

  <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.autismacademyed.www.autismacademy.AutismAcademy">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.173" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.0" />

    <ImageButton
        android:id="@+id/imageButtonYellow"
        android:layout_width="109dp"
        android:layout_height="125dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:background="@null"
        android:scaleType="centerCrop"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@mipmap/ic_yellowpuzzlepiece"
        android:onClick="buttonClick"/>

</android.support.constraint.ConstraintLayout>

jAVAFILE

public class AutismAcademy extends AppCompatActivity {

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

    public void buttonClick(View v) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.aaed.org"));
        startActivity(browserIntent);
    }

}


问:
How to use numpy array divide?
```<code>In [2]: x = np.array([5,4,3,2])

In [3]: y = np.array([2,2,2,2])
</code>```

Both are int format and when I use x/y, the output are floor int of every element.
How to divide each element and get the float result. For example : 2.5, 2, 1.5, 1.

答:
You can use np.true_divide -

```<code>np.true_divide(x,y)
</code>```

Sample run -

```<code>In [53]: x = np.array([5,4,3,2])

In [54]: y = np.array([2,2,2,2])

In [55]: np.true_divide(x,y)
Out[55]: array([ 2.5,  2. ,  1.5,  1. ])
</code>```

Alternatively, you can also use from __future__ import division, but this will keep the divisions as floating one for the rest of the session -

```<code>In [56]: x/y
Out[56]: array([2, 2, 1, 1])

In [57]: from __future__ import division

In [58]: x/y
Out[58]: array([ 2.5,  2. ,  1.5,  1. ])
</code>```

Title: How to use numpy array divide?

Body:
In [2]: x = np.array([5,4,3,2])

In [3]: y = np.array([2,2,2,2])

Both are int format and when I use x/y, the output are floor int of every element.
How to divide each element and get the float result. For example : 2.5, 2, 1.5, 1.

Body:
You can use np.true_divide -

np.true_divide(x,y)

Sample run -

In [53]: x = np.array([5,4,3,2])

In [54]: y = np.array([2,2,2,2])

In [55]: np.true_divide(x,y)
Out[55]: array([ 2.5,  2. ,  1.5,  1. ])

Alternatively, you can also use from __future__ import division, but this will keep the divisions as floating one for the rest of the session -

In [56]: x/y
Out[56]: array([2, 2, 1, 1])

In [57]: from __future__ import division

In [58]: x/y
Out[58]: array([ 2.5,  2. ,  1.5,  1. ])


问:
Converting JSON Data in VB.NET
I am trying to convert This Data to a structure.

I have the structure as so:

```<code>Public Structure cChartData
    Public cUDate As String
    Public cOpen As Double
    Public cClose As Double
    Public cHigh As Double
    Public cLow As Double
End Structure
</code>```

and the class as so:

```<code>Friend Class ChartData
Public Property uDate() As String
    Get
        Return m_date
    End Get
    Set
        m_date = Value
    End Set
End Property
Private m_date As String
Public Property high() As String
    Get
        Return m_high
    End Get
    Set
        m_high = Value
    End Set
End Property
Private m_high As String
Public Property low() As String
    Get
        Return m_low
    End Get
    Set
        m_low = Value
    End Set
End Property
Private m_low As String
Public Property open() As String
    Get
        Return m_open
    End Get
    Set
        m_open = Value
    End Set
End Property
Private m_open As String
Public Property close() As String
    Get
        Return m_close
    End Get
    Set
        m_close = Value
    End Set
End Property
Private m_close As String
Public Property volume() As String
    Get
        Return m_volume
    End Get
    Set
        m_volume = Value
    End Set
End Property
Private m_volume As String
Public Property quoteVolume() As String
    Get
        Return m_quoteVolume
    End Get
    Set
        m_quoteVolume = Value
    End Set
End Property
Private m_quoteVolume As String
Public Property weightedAverage() As String
    Get
        Return m_weightedAverage
    End Get
    Set
        m_weightedAverage = Value
    End Set
End Property
Private m_weightedAverage As String
End Class
</code>```

I am trying to retrieve all variables from each line. I get all of them except the date. I am using the following code (where chartInfo = JSON Data):

```<code>Dim cdata = JsonConvert.DeserializeObject(Of List(Of ChartData))(chartInfo)
        Dim cResData(cdata.Count - 1) As cChartData
        For i = 0 To cdata.Count - 1
            cResData(i).cUDate = cdata(i).uDate
            cResData(i).cOpen = Convert.ToDouble(cdata(i).open)
            cResData(i).cClose = Convert.ToDouble(cdata(i).close)
            cResData(i).cHigh = Convert.ToDouble(cdata(i).high)
            cResData(i).cLow = Convert.ToDouble(cdata(i).low)
        Next
        Return cResData
</code>```

The date returns a "blank" value, or nothing, when displayed, but all other values return properly. It is the first value so I wonder if it has something to do with it...

Any help is greatly appreciated.

答:
When a property can be serialized it will be be left null by the JSON serializer.

So either the dates in your JSON are empty or null or they are in a DateFormat that .NET can't serialize by default.

In your posted JSON, the date field is what is numeric format, such as '1438992000' meaning it is a timestamp.

Additionally, the field name is 'date' but you have defined your property as uDate. For serialization to work the property name must match the JSON key unless you are overriding the default serialization. Change the definition as follows and it will serialize:

```<code>    Public Property [date] As String
    Get
        Return m_date
    End Get
    Set
        m_date = Value
    End Set
End Property
</code>```

Title: Converting JSON Data in VB.NET

Body:
I am trying to convert This Data to a structure.

I have the structure as so:

Public Structure cChartData
    Public cUDate As String
    Public cOpen As Double
    Public cClose As Double
    Public cHigh As Double
    Public cLow As Double
End Structure

and the class as so:

Friend Class ChartData
Public Property uDate() As String
    Get
        Return m_date
    End Get
    Set
        m_date = Value
    End Set
End Property
Private m_date As String
Public Property high() As String
    Get
        Return m_high
    End Get
    Set
        m_high = Value
    End Set
End Property
Private m_high As String
Public Property low() As String
    Get
        Return m_low
    End Get
    Set
        m_low = Value
    End Set
End Property
Private m_low As String
Public Property open() As String
    Get
        Return m_open
    End Get
    Set
        m_open = Value
    End Set
End Property
Private m_open As String
Public Property close() As String
    Get
        Return m_close
    End Get
    Set
        m_close = Value
    End Set
End Property
Private m_close As String
Public Property volume() As String
    Get
        Return m_volume
    End Get
    Set
        m_volume = Value
    End Set
End Property
Private m_volume As String
Public Property quoteVolume() As String
    Get
        Return m_quoteVolume
    End Get
    Set
        m_quoteVolume = Value
    End Set
End Property
Private m_quoteVolume As String
Public Property weightedAverage() As String
    Get
        Return m_weightedAverage
    End Get
    Set
        m_weightedAverage = Value
    End Set
End Property
Private m_weightedAverage As String
End Class

I am trying to retrieve all variables from each line. I get all of them except the date. I am using the following code (where chartInfo = JSON Data):

Dim cdata = JsonConvert.DeserializeObject(Of List(Of ChartData))(chartInfo)
        Dim cResData(cdata.Count - 1) As cChartData
        For i = 0 To cdata.Count - 1
            cResData(i).cUDate = cdata(i).uDate
            cResData(i).cOpen = Convert.ToDouble(cdata(i).open)
            cResData(i).cClose = Convert.ToDouble(cdata(i).close)
            cResData(i).cHigh = Convert.ToDouble(cdata(i).high)
            cResData(i).cLow = Convert.ToDouble(cdata(i).low)
        Next
        Return cResData

The date returns a "blank" value, or nothing, when displayed, but all other values return properly. It is the first value so I wonder if it has something to do with it...

Any help is greatly appreciated.

Body:
When a property can be serialized it will be be left null by the JSON serializer.

So either the dates in your JSON are empty or null or they are in a DateFormat that .NET can't serialize by default.

In your posted JSON, the date field is what is numeric format, such as '1438992000' meaning it is a timestamp.

Additionally, the field name is 'date' but you have defined your property as uDate. For serialization to work the property name must match the JSON key unless you are overriding the default serialization. Change the definition as follows and it will serialize:

    Public Property [date] As String
    Get
        Return m_date
    End Get
    Set
        m_date = Value
    End Set
End Property


问:
TSQL puzzle, why is my update not random?
I was looking at postgres question and it called for updating a table with random values.

I only noticed it was targeted at postgres after answering it, but in answering it I hit a mystery.

Here is my sample code in question:

```<code>create table #Buildings([Use] varchar(50), n int)

insert #Buildings
select null,null from sysobjects

update #Buildings
set [Use] =
        case (ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6)
            when 0 then null
            when 1 then 'warehouse'
            when 2 then 'office'
            when 3 then 'market'
            when 4 then 'retail'
            when 5 then 'workshop'
            else 'HOW IS THIS POSSIBLE'
        end,
    n = ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6

select [Use], count(*) from
#Buildings
group by [Use]

select n, count(*) from
#Buildings
group by n
</code>```

It returns a very odd result set:

```<code>Use
-------------------------------------------------- -----------
workshop                                           128
HOW IS THIS POSSIBLE                               633
NULL                                               287
retail                                             140
warehouse                                          258
market                                             177
office                                             209
</code>```

And a second result set that makes complete sense:

```<code>n
----------- -----------
0           292
3           300
1           313
4           277
5           311
2           339
</code>```

The data for both result sets was generated in the same update statement.

So my question is why is a number out of the range of 0 - 5 hitting my case statement? What is that number? Why when I update the int directly is stuff distributed properly?

答:
John is likely right... though it's worrying the "WHEN" would be so inefficient.

Also note that the NewId() function returns a new value each time you call it. You're calling it twice (not counting the "when" wierdness). The following is more stable:
drop table #Buildings
go

create table #Buildings([Use] varchar(50), n int)

insert #Buildings
select null,null from sysobjects

declare @nid as uniqueidentifier

update #Buildings
set @nid = newid(),
    [Use] =
        case (ABS(CAST(CAST(NewId() AS VARBINARY) AS int)) % 6)
                when 0 then null
                when 1 then 'warehouse'
                when 2 then 'office'
                when 3 then 'market'
                when 4 then 'retail'
                when 5 then 'workshop'
                else 'HOW IS THIS POSSIBLE'
        end,
    n = ABS(CAST(CAST(NewId() AS VARBINARY) AS int)) % 6

select [Use], count(*) from

Buildings

group by [Use]

select n, count(*) from

Buildings

group by n

ContentLicense: CC BY-SA 2.5

Body:
I was looking at postgres question and it called for updating a table with random values.

I only noticed it was targeted at postgres after answering it, but in answering it I hit a mystery.

Here is my sample code in question:

create table #Buildings([Use] varchar(50), n int)

insert #Buildings
select null,null from sysobjects

update #Buildings
set [Use] =
        case (ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6)
            when 0 then null
            when 1 then 'warehouse'
            when 2 then 'office'
            when 3 then 'market'
            when 4 then 'retail'
            when 5 then 'workshop'
            else 'HOW IS THIS POSSIBLE'
        end,
    n = ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6

select [Use], count(*) from
#Buildings
group by [Use]

select n, count(*) from
#Buildings
group by n

It returns a very odd result set:

Use
-------------------------------------------------- -----------
workshop                                           128
HOW IS THIS POSSIBLE                               633
NULL                                               287
retail                                             140
warehouse                                          258
market                                             177
office                                             209

And a second result set that makes complete sense:

n
----------- -----------
0           292
3           300
1           313
4           277
5           311
2           339

The data for both result sets was generated in the same update statement.

So my question is why is a number out of the range of 0 - 5 hitting my case statement? What is that number? Why when I update the int directly is stuff distributed properly?


问:
textarea resize upon content inside
How would I get a <textarea> to resize upon the content inside? Like how facebook does it also so there is no scrollbar? If anyone could give me an insight or a link of how to do this It would be greatly appreciated. Not really looking for a JS answer really but if u know any solutions I don't mind.

Thanks

Title: textarea resize upon content inside

Body: jQuery plugin: http://james.padolsey.com/javascript/jquery-plugin-autoresize/


答:
The problem is in your input text shadow, try changing it like below then make changes what you want it to be.

From

```<code>input{
        color: #f08200;
        text-shadow: 0px 0px 0px #000;
        -webkit-text-fill-color: transparent;
    }
</code>```

To

```<code>input{
    color: #f08200;
    text-shadow: 0px 0px 0px red;
    -webkit-text-fill-color: transparent;
}
</code>```

Title: HTML Input Submit Button Won't Change Color

Body:
I have a form with a submit button that I'm trying to change the color to. This should be very simple, but my css isn't working and I can't figure out why.

The CSS:

input[type="submit"]{color: red;}

Fiddle:
https://jsfiddle.net/zn7xrv60/

This is driving me nuts, any help would be appreciated.

Body:
The problem is in your input text shadow, try changing it like below then make changes what you want it to be.

From

input{
        color: #f08200;
        text-shadow: 0px 0px 0px #000;
        -webkit-text-fill-color: transparent;
    }

To

input{
    color: #f08200;
    text-shadow: 0px 0px 0px red;
    -webkit-text-fill-color: transparent;
}


问:
TokenMismatchException in VerifyCsrfToken.php Line 67
I know that this is a known error with things like forms in Laravel. But I am facing an issue with basic authentication in Laravel 5.2.

I created the auth using Laravel;

```<code>php artisan make:auth
</code>```

Now I have the same copy of code on my server and my local. On my local I am getting no issue whatsoever. However on my server, when I try to register a user I get the error saying TokenMismatchException in VerifyCsrfToken.php Line 67

Both my local and server environments are in sync, yet I keep getting the error on registration. Any help on how I can fix this?

答:
Go to app/provides.

Then, in file RouteServiceProvider.php, you'll have to delete 'middleware' => 'web' in protected function mapWebRoutes(Router $router)

Body:
I know that this is a known error with things like forms in Laravel. But I am facing an issue with basic authentication in Laravel 5.2.

I created the auth using Laravel;

php artisan make:auth

Now I have the same copy of code on my server and my local. On my local I am getting no issue whatsoever. However on my server, when I try to register a user I get the error saying TokenMismatchException in VerifyCsrfToken.php Line 67

Both my local and server environments are in sync, yet I keep getting the error on registration. Any help on how I can fix this?


答:
Remove the setOnClickListener since you already specify in your view that the onclick function for the button is onClick. To avoid confusion rename your button android:onClick="onClick", like android:onClick="imageButtonOnClick".

And in your java code you can just use this

```<code>package com.autismacademyed.www.autismacademy;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class AutismAcademy extends AppCompatActivity {

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

    public void imageButtonOnClick(View v) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.aaed.org"));
        startActivity(browserIntent);
    }

}
</code>```

Title: How to make ImageButton clickable in Android Studio?

Body:
Remove the setOnClickListener since you already specify in your view that the onclick function for the button is onClick. To avoid confusion rename your button android:onClick="onClick", like android:onClick="imageButtonOnClick".

And in your java code you can just use this

package com.autismacademyed.www.autismacademy;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class AutismAcademy extends AppCompatActivity {

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

    public void imageButtonOnClick(View v) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.aaed.org"));
        startActivity(browserIntent);
    }

}


问:
What is a simple way to show an MvxDialogFragment?
I am trying to use an MvxDialogFragment to show a data bound dialog from an activity.  My Dialog ViewModel is as follows:

```<code>public class ContainerDialogViewModel : MvxViewModel
{

    public string ShipperName;

    public void Init(string Name)
    {
        ShipperName = Name;
        LoadData();
    }

    public void LoadData()
    {
        Survey = SurveyDataSource.CurrSurvey;
    }

    private ShipmentSurvey _Survey;
    public ShipmentSurvey Survey
    {
        get
        {
            return _Survey;
        }
        set
        {
            _Survey = value;
            RaisePropertyChanged(() => Survey);
            RaisePropertyChanged(() => Containers);
        }
    }

    public List<ShipmentSurveyContainer> Containers
    {
        get
        {
            if (Survey == null)
                return new List<ShipmentSurveyContainer>();
            else
                return Survey.SurveyContainers.ToList();
        }
    }

}
</code>```

The MvxDialogFragment is coded as follows:

```<code>public class ContainerDialog : MvxDialogFragment<ContainerDialogViewModel>
{
    public override Dialog OnCreateDialog(Bundle savedState)
    {
        base.EnsureBindingContextSet(savedState);

        this.BindingInflate(Resource.Layout.ContainerDialog, null);

        return base.OnCreateDialog(savedState);
    }

}
</code>```

In my activity, I am trying to figure out the simplest way to launch the dialog.  Here is what I have tried:

```<code>public class SurveyView : MvxActivity
{
    public void ShowContainerDialog()
    {
        ContainerDialogViewModel vm = new ViewModels.ContainerDialogViewModel();
        vm.Init("Test Name");
        var dialogFragment = new ContainerDialog()
        {
            DataContext = vm
        };
        dialogFragment.Show(FragmentManager, "Containers");
    }
}
</code>```

I'm pretty sure my method of creating the view model is unorthodox, but I don't know another way to do it.  The biggest issue is that FragmentManager is cast to the wrong version.  Show is looking for an Android.Support.V4.App.FragmentManager and the FragmentManager that is exposed is an Android.App.FragmentManager.  I tried changing the MvxActivity to an MvxFragmentActivity, but this didn't seem to help.  Can someone point me in the right direction?

答:
I tried changing the MvxActivity to an MvxFragmentActivity

This was the correct first step. Then instead of passing in FragmentManager, pass in SupportFragmentManager.

If you are not familiar with Support Libraries, You can read more about what they are and how to use them with Xamarin here

Body:
I am trying to use an MvxDialogFragment to show a data bound dialog from an activity.  My Dialog ViewModel is as follows:

public class ContainerDialogViewModel : MvxViewModel
{

    public string ShipperName;

    public void Init(string Name)
    {
        ShipperName = Name;
        LoadData();
    }

    public void LoadData()
    {
        Survey = SurveyDataSource.CurrSurvey;
    }

    private ShipmentSurvey _Survey;
    public ShipmentSurvey Survey
    {
        get
        {
            return _Survey;
        }
        set
        {
            _Survey = value;
            RaisePropertyChanged(() => Survey);
            RaisePropertyChanged(() => Containers);
        }
    }

    public List<ShipmentSurveyContainer> Containers
    {
        get
        {
            if (Survey == null)
                return new List<ShipmentSurveyContainer>();
            else
                return Survey.SurveyContainers.ToList();
        }
    }

}

The MvxDialogFragment is coded as follows:

public class ContainerDialog : MvxDialogFragment<ContainerDialogViewModel>
{
    public override Dialog OnCreateDialog(Bundle savedState)
    {
        base.EnsureBindingContextSet(savedState);

        this.BindingInflate(Resource.Layout.ContainerDialog, null);

        return base.OnCreateDialog(savedState);
    }

}

In my activity, I am trying to figure out the simplest way to launch the dialog.  Here is what I have tried:

public class SurveyView : MvxActivity
{
    public void ShowContainerDialog()
    {
        ContainerDialogViewModel vm = new ViewModels.ContainerDialogViewModel();
        vm.Init("Test Name");
        var dialogFragment = new ContainerDialog()
        {
            DataContext = vm
        };
        dialogFragment.Show(FragmentManager, "Containers");
    }
}

I'm pretty sure my method of creating the view model is unorthodox, but I don't know another way to do it.  The biggest issue is that FragmentManager is cast to the wrong version.  Show is looking for an Android.Support.V4.App.FragmentManager and the FragmentManager that is exposed is an Android.App.FragmentManager.  I tried changing the MvxActivity to an MvxFragmentActivity, but this didn't seem to help.  Can someone point me in the right direction?


问:
Retrieve and check whether a particular user enter email is present in firebase
I am developing an android application and using Firebase to store my data. I want to query the firebase instance to check whether the user entered email address matches one of the email in Firebase. Attaching the Firebase backend data.

My requirement is, I want to loop through the "guardians", which is the direct child of the Database instance and check whether the user entered email matches any one of the email address in that child. In the attached image, if the user entered email matches either "ram@gmail.com" or the other one, I want to do something.

```<code>databaseReference = FirebaseDatabase.getInstance().getReference().child("guardians");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot data: dataSnapshot.getChildren()){
                if (**I am unable to figure out how to search through entire guardians child for the email**) {

                } else {

                }
              }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

I am unable to figure out how to search through the entire guardians child to see whether the email matches the user entered email. Any help is appreciated. Thanks in advance.

答:
If you made your current approach work (it's a matter of adding the correct if statement) you'd be downloading the entire list of users, just to check if a specific email address is in use. This is incredibly wasteful of bandwidth, especially as your user list grows.

You should instead use a Firebase Database query to only return the user with the requested email address:

```<code>databaseReference = FirebaseDatabase.getInstance().getReference().child("guardians");
Query query = databaseReference.orderByChild("guardianEmail").equalTo("guardian@example.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                ... the email address is already in use
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });
</code>```

Be sure to add an index for the guardianEmail field, as otherwise you'll still end up downloading all data for the query.

Note that this topic has been covered quite a few times before, and there are better ways to do this check. Most of these involve creating a so-called inverted index, where you use the (encoded) email address of the user as the key. With that structure you can prevent duplicates in Firebase's server-side security rules, which is even more efficient.

For more on this and other approaches, see:

Enforcing unique usernames with Firebase simplelogin

Firebase android : make username unique

How do you prevent duplicate user properties in Firebase?

Usernames with Firebase Simple Login (email/password)

What Firebase rule will prevent duplicates in a collection based on other fields?

Body:
I am developing an android application and using Firebase to store my data. I want to query the firebase instance to check whether the user entered email address matches one of the email in Firebase. Attaching the Firebase backend data.

My requirement is, I want to loop through the "guardians", which is the direct child of the Database instance and check whether the user entered email matches any one of the email address in that child. In the attached image, if the user entered email matches either "ram@gmail.com" or the other one, I want to do something.

databaseReference = FirebaseDatabase.getInstance().getReference().child("guardians");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot data: dataSnapshot.getChildren()){
                if (**I am unable to figure out how to search through entire guardians child for the email**) {

                } else {

                }
              }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

I am unable to figure out how to search through the entire guardians child to see whether the email matches the user entered email. Any help is appreciated. Thanks in advance.

Body:
If you made your current approach work (it's a matter of adding the correct if statement) you'd be downloading the entire list of users, just to check if a specific email address is in use. This is incredibly wasteful of bandwidth, especially as your user list grows.

You should instead use a Firebase Database query to only return the user with the requested email address:

databaseReference = FirebaseDatabase.getInstance().getReference().child("guardians");
Query query = databaseReference.orderByChild("guardianEmail").equalTo("guardian@example.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                ... the email address is already in use
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });

Be sure to add an index for the guardianEmail field, as otherwise you'll still end up downloading all data for the query.

Note that this topic has been covered quite a few times before, and there are better ways to do this check. Most of these involve creating a so-called inverted index, where you use the (encoded) email address of the user as the key. With that structure you can prevent duplicates in Firebase's server-side security rules, which is even more efficient.

For more on this and other approaches, see:

Enforcing unique usernames with Firebase simplelogin

Firebase android : make username unique

How do you prevent duplicate user properties in Firebase?

Usernames with Firebase Simple Login (email/password)

What Firebase rule will prevent duplicates in a collection based on other fields?


问:
Taking value from Excel to python
Hi I'm a newbie in python and trying to take values from excel file to python array. (Using python 3.6)

I did like below code,

```<code>file_location = "170515_data.xlsx"

workbook = xlrd.open_workbook(file_location)

sheet = workbook.sheet_by_name('Sheet1')

x = []

for rownum in range(1, sheet.nrows):
    x.append(sheet.cell(rownum, 1))
</code>```

and output gives me like

```<code>[number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, ...]
</code>```

I don't want to have number: in the array.

How can I take that 'number:' out from array?

Or is there any ways for taking all values of row in each column instead of above code?

Thanks in advance.

答:
I got it. :) I was really stupid...

```<code>for value in sheet.col_values(1):
    x.append(value)
</code>```

This is how I did it. :) and it gives me an output perfectly.

Title: Taking value from Excel to python

Body:
Hi I'm a newbie in python and trying to take values from excel file to python array. (Using python 3.6)

I did like below code,

file_location = "170515_data.xlsx"

workbook = xlrd.open_workbook(file_location)

sheet = workbook.sheet_by_name('Sheet1')

x = []

for rownum in range(1, sheet.nrows):
    x.append(sheet.cell(rownum, 1))

and output gives me like

[number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, number:380.0, ...]

I don't want to have number: in the array.

How can I take that 'number:' out from array?

Or is there any ways for taking all values of row in each column instead of above code?

Thanks in advance.

Body:
I got it. :) I was really stupid...

for value in sheet.col_values(1):
    x.append(value)

This is how I did it. :) and it gives me an output perfectly.


问:
Auto-populate in backend a WooCommerce Custom Product setting selector
In connection to my previous question that was successfully answered at Retrieving WC Custom Field I now have select fields and wanting also to add auto-complete custom fields(I have yet to research on this)

Questions:
1.) How to auto-populate the custom select fields?

```<code>//Adding the custom field select
woocommerce_wp_select(
array(
'id' => '_select',
'label' => __( 'SIM Type', 'woocommerce' ),
'options' => array(
'one' => __( 'Regular', 'woocommerce' ),
'two' => __( 'Nano', 'woocommerce' ),
'three' => __( 'Micro', 'woocommerce' )
)
)
);

//Saving
$woocommerce_select = $_POST['_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );

// Display Custom Field Value
echo get_post_meta( $post->ID, '_select', true );
</code>```

答:
Update: Set programmatically the <option> in an select field:

1) You will need to store an associative array of your option key values:

```<code>// The associative array to store (once)
$options_array = array(
    '' => __( 'Select a value', 'woocommerce' ), // default empty value
    'one' => __( 'Regular', 'woocommerce' ),
    'two' => __( 'Nano', 'woocommerce' ),
    'three' => __( 'Micro', 'woocommerce' )
);

// Serialize the array as a string
$option_str = maybe_serialize( $options_array );

// Save this array in Wordpress options
update_option( 'my_custom_selector_options', $option_str );
</code>```

2) Get and unserialize your selector options:

```<code>// Get your options select data
$select_options_str = get_option( 'my_custom_selector_options' );

// Unserialize this data:
$select_options_arr = maybe_unserialize( $select_options_str );

// Get the saved  selected 'value' if it exist
$value = get_post_meta( $post->ID, '_select', true );
if( empty( $value ) ) $value = ''; // When 'value' is not defined

//
woocommerce_wp_select(
    array(
        'id' => '_select',
        'label' => __( 'SIM Type', 'woocommerce' ),
        'options' => $select_options_arr,
        'value' => $value,
    )
);
</code>```

So now your field selector options have been populated by the data that you get from WordPress options.

To autofill the woocommerce_wp_select(), you have to add a 'value' key this way:

```<code>## 1. The select (dropdown)

// Get the 'value' data if it exist
$value = get_post_meta( $post->ID, '_select', true );
if( empty( $value ) ) $value = ''; // When 'value' is not defined

woocommerce_wp_select(
    array(
        'id' => '_select',
        'label' => __( 'SIM Type', 'woocommerce' ),
        'options' => array(
            '' => __( 'Select a value', 'woocommerce' ), // Added a default empty value
            'one' => __( 'Regular', 'woocommerce' ),
            'two' => __( 'Nano', 'woocommerce' ),
            'three' => __( 'Micro', 'woocommerce' )
        ),
        'value' => $value, // <===  ===  ===  ===  ===  HERE set the 'value' key (autofill)
    )
);

## ---------------------------------

## 2. SAVING

$woocommerce_select = $_POST['_select'];
// The Default empty value is not saved (added in this condition below)
if( !empty( $woocommerce_select ) || $woocommerce_select  != '' )
    update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );
</code>```

A quick test:

  To see it in action, replace for example: 'value' => $value, by 'value' => 'two',

  Then selected value will be: Nano …

Body:
In connection to my previous question that was successfully answered at Retrieving WC Custom Field I now have select fields and wanting also to add auto-complete custom fields(I have yet to research on this)

Questions:
1.) How to auto-populate the custom select fields?

//Adding the custom field select
woocommerce_wp_select(
array(
'id' => '_select',
'label' => __( 'SIM Type', 'woocommerce' ),
'options' => array(
'one' => __( 'Regular', 'woocommerce' ),
'two' => __( 'Nano', 'woocommerce' ),
'three' => __( 'Micro', 'woocommerce' )
)
)
);

//Saving
$woocommerce_select = $_POST['_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );

// Display Custom Field Value
echo get_post_meta( $post->ID, '_select', true );

Body:
Update: Set programmatically the <option> in an select field:

1) You will need to store an associative array of your option key values:

// The associative array to store (once)
$options_array = array(
    '' => __( 'Select a value', 'woocommerce' ), // default empty value
    'one' => __( 'Regular', 'woocommerce' ),
    'two' => __( 'Nano', 'woocommerce' ),
    'three' => __( 'Micro', 'woocommerce' )
);

// Serialize the array as a string
$option_str = maybe_serialize( $options_array );

// Save this array in Wordpress options
update_option( 'my_custom_selector_options', $option_str );

2) Get and unserialize your selector options:

// Get your options select data
$select_options_str = get_option( 'my_custom_selector_options' );

// Unserialize this data:
$select_options_arr = maybe_unserialize( $select_options_str );

// Get the saved  selected 'value' if it exist
$value = get_post_meta( $post->ID, '_select', true );
if( empty( $value ) ) $value = ''; // When 'value' is not defined

//
woocommerce_wp_select(
    array(
        'id' => '_select',
        'label' => __( 'SIM Type', 'woocommerce' ),
        'options' => $select_options_arr,
        'value' => $value,
    )
);

So now your field selector options have been populated by the data that you get from WordPress options.

To autofill the woocommerce_wp_select(), you have to add a 'value' key this way:

## 1. The select (dropdown)

// Get the 'value' data if it exist
$value = get_post_meta( $post->ID, '_select', true );
if( empty( $value ) ) $value = ''; // When 'value' is not defined

woocommerce_wp_select(
    array(
        'id' => '_select',
        'label' => __( 'SIM Type', 'woocommerce' ),
        'options' => array(
            '' => __( 'Select a value', 'woocommerce' ), // Added a default empty value
            'one' => __( 'Regular', 'woocommerce' ),
            'two' => __( 'Nano', 'woocommerce' ),
            'three' => __( 'Micro', 'woocommerce' )
        ),
        'value' => $value, // <===  ===  ===  ===  ===  HERE set the 'value' key (autofill)
    )
);

## ---------------------------------

## 2. SAVING

$woocommerce_select = $_POST['_select'];
// The Default empty value is not saved (added in this condition below)
if( !empty( $woocommerce_select ) || $woocommerce_select  != '' )
    update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );

A quick test:

  To see it in action, replace for example: 'value' => $value, by 'value' => 'two',

  Then selected value will be: Nano …


问:
Localizable.strings key-value pair
I want to localize "1 of 9", and 1 and 9 are int parameters, my code is as below

```<code>context = [NSString stringWithFormat:NSLocalizedString(@"%d of %d",
          "This text will be used to show page number on the screen"),
          currentPageIndex + 1, pageCount];
</code>```

And the generated Localizable.strings show like that

```<code>/* This text will be used to show page number on the screen */
"%d of %d" = "%1$d of %2$d";
</code>```

I think the thing on the left of "=" is key and the the thing on the right of "=" is value, but I want the key looks like "show_page_number" not included the format "%d", how can I do? I try to replace "%d of %d" with "show_page_number", but it does not work. Any advice?

答:
If you want full control over the key and its initial value you need to use NSLocalizedStringWithDefaultValue instead of NSLocalizedString (which uses the key as the initial value).

Change your code to:

```<code>NSString *format = NSLocalizedStringWithDefaultValue(@"show_page_number", @"Localizable", NSBundle.mainBundle, @"%1$d of %2$d", @"This text will be used to show page number on the screen")
context = [NSString stringWithFormat:format, currentPageIndex + 1, pageCount];
</code>```

When you run genstrings, you will get:

```<code>/* This text will be used to show page number on the screen */
"show_page_number" = "%1$d of %2$d";
</code>```

Title: Localizable.strings key-value pair

Body:
I want to localize "1 of 9", and 1 and 9 are int parameters, my code is as below

context = [NSString stringWithFormat:NSLocalizedString(@"%d of %d",
          "This text will be used to show page number on the screen"),
          currentPageIndex + 1, pageCount];

And the generated Localizable.strings show like that

/* This text will be used to show page number on the screen */
"%d of %d" = "%1$d of %2$d";

I think the thing on the left of "=" is key and the the thing on the right of "=" is value, but I want the key looks like "show_page_number" not included the format "%d", how can I do? I try to replace "%d of %d" with "show_page_number", but it does not work. Any advice?

Body:
If you want full control over the key and its initial value you need to use NSLocalizedStringWithDefaultValue instead of NSLocalizedString (which uses the key as the initial value).

Change your code to:

NSString *format = NSLocalizedStringWithDefaultValue(@"show_page_number", @"Localizable", NSBundle.mainBundle, @"%1$d of %2$d", @"This text will be used to show page number on the screen")
context = [NSString stringWithFormat:format, currentPageIndex + 1, pageCount];

When you run genstrings, you will get:

/* This text will be used to show page number on the screen */
"show_page_number" = "%1$d of %2$d";


问:
Programmatically determine if std::string uses Copy-On-Write (COW) mechanism
Following up on the discussion from this question, I was wondering how does one using native C++ determine programmatically whether or not the std::string implementation they are using utilizes Copy-On-Write (COW)

I have the following function:

```<code>#include <iostream>
#include <string>

bool stdstring_supports_cow()
{
   //make sure the string is longer than the size of potential
   //implementation of small-string.
   std::string s1 = "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789";
   std::string s2 = s1;
   std::string s3 = s2;

   bool result1 = (&s1[0]) == (&s2[0]);
   bool result2 = (&s1[0]) == (&s3[0]);

   s2[0] = 'X';

   bool result3 = (&s1[0]) != (&s2[0]);
   bool result4 = (&s1[0]) == (&s3[0]);

   s3[0] = 'X';

   bool result5 = (&s1[0]) != (&s3[0]);

   return result1 && result2 &&
          result3 && result4 &&
          result5;
}

int main()
{
  if (stdstring_supports_cow())
      std::cout << "std::string is COW." << std::endl;
   else
      std::cout << "std::string is NOT COW." << std::endl;
   return 0;
}
</code>```

The problem is I can't seem to find a C++ tool chain where it returns true. Is there a flaw in my assumption about how COW is implemented for std::string?

Update: Based on kotlinski comments, I've changed the use of writeble references to data() in the function, it now seems to return "true" for some implementations.

```<code>bool stdstring_supports_cow()
{
   //make sure the string is longer than the size of potential
   //implementation of small-string.
   std::string s1 = "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789";
   std::string s2 = s1;
   std::string s3 = s2;

   bool result1 = s1.data() == s2.data();
   bool result2 = s1.data() == s3.data();

   s2[0] = 'X';

   bool result3 = s1.data() != s2.data();
   bool result4 = s1.data() == s3.data();

   s3[0] = 'X';

   bool result5 = s1.data() != s3.data();

   return result1 && result2 &&
          result3 && result4 &&
          result5;
}
</code>```

Note: According N2668: "Concurrency Modifications to Basic String", in the upcoming C++0x standard, COW option will be removed from basic_string. thanks to James and Beldaz for bringing that up.

答:
The copy-on-write paradigm is dependent on knowing when you are doing a write. This will occur whenever the object is returning a writable reference.

If you work with const references to the strings, you may be able to compare the addresses if the class was specialized to disable the copy when returning a const reference to the data.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

Body:
Following up on the discussion from this question, I was wondering how does one using native C++ determine programmatically whether or not the std::string implementation they are using utilizes Copy-On-Write (COW)

I have the following function:

#include <iostream>
#include <string>

bool stdstring_supports_cow()
{
   //make sure the string is longer than the size of potential
   //implementation of small-string.
   std::string s1 = "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789";
   std::string s2 = s1;
   std::string s3 = s2;

   bool result1 = (&s1[0]) == (&s2[0]);
   bool result2 = (&s1[0]) == (&s3[0]);

   s2[0] = 'X';

   bool result3 = (&s1[0]) != (&s2[0]);
   bool result4 = (&s1[0]) == (&s3[0]);

   s3[0] = 'X';

   bool result5 = (&s1[0]) != (&s3[0]);

   return result1 && result2 &&
          result3 && result4 &&
          result5;
}

int main()
{
  if (stdstring_supports_cow())
      std::cout << "std::string is COW." << std::endl;
   else
      std::cout << "std::string is NOT COW." << std::endl;
   return 0;
}

The problem is I can't seem to find a C++ tool chain where it returns true. Is there a flaw in my assumption about how COW is implemented for std::string?

Update: Based on kotlinski comments, I've changed the use of writeble references to data() in the function, it now seems to return "true" for some implementations.

bool stdstring_supports_cow()
{
   //make sure the string is longer than the size of potential
   //implementation of small-string.
   std::string s1 = "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789";
   std::string s2 = s1;
   std::string s3 = s2;

   bool result1 = s1.data() == s2.data();
   bool result2 = s1.data() == s3.data();

   s2[0] = 'X';

   bool result3 = s1.data() != s2.data();
   bool result4 = s1.data() == s3.data();

   s3[0] = 'X';

   bool result5 = s1.data() != s3.data();

   return result1 && result2 &&
          result3 && result4 &&
          result5;
}

Note: According N2668: "Concurrency Modifications to Basic String", in the upcoming C++0x standard, COW option will be removed from basic_string. thanks to James and Beldaz for bringing that up.


问:
Web Scraping with Python BeautifulSoup 4
I am fairly new to Webscraping and gave my attempt after watching some tutorial videos online. I decided to use Tripadvisor.com and try to gather data from customer reviews.

This is what I came up with (code):

```<code>from urllib.request import urlopen as uReq

from bs4 import BeautifulSoup as soup

my_url = 'https://www.tripadvisor.com.sg/Attraction_Review-g293916-d12033454-
Reviews-SHOW_DC-Bangkok.html'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")

containers = page_soup.findAll("div",{"class":"ui_column is-9"})

for container in containers:
   rating = container.div.div.div.span["class"]

    comment_container = container.p
    comment = comment_container[0]

    print("rating" + rating)
    print("comment" + comment)
</code>```

This was the output of my code:

```<code>Traceback (most recent call last):
  File "trip_advisor.py", line 18, in <module>
    comment = comment_container[0]
  File "/anaconda/lib/python3.6/site-packages/bs4/element.py", line 1011, in
__getitem__
    return self.attrs[key]
KeyError: 0
</code>```

Can anyone help me fix this problem? Thanks.

答:
You won't be able to access the contents by using the index in a <class bs4.element.Tag'>, you need .contents for that:

```<code>>>> container.p
<p class="partial_entry">I was there couple of weeks ago on the weekend. There was an event but it was not very crowded thought and I actually like it. What drawn my attention is the PUB on the roof top. A Pub in a department store sound pretty...<span class="taLnk ulBlueLinks" onclick="ta.prwidgets.call('handlers.clickExpand',event,this);">More</span></p>
>>> container.p.contents[0]
'I was there couple of weeks ago on the weekend. There was an event but it was not very crowded thought and I actually like it. What drawn my attention is the PUB on the roof top. A Pub in a department store sound pretty...'
</code>```

Besides this issue, I'm not sure if your rating scraping is really getting what you want, but this solves the main error:

```<code>for container in containers:
    rating = container.div.div.div.span["class"]
    comment_container = container.p.contents
    comment = comment_container[0]
    print("Rating: ", rating)
    print("Comment: " + comment)
</code>```

This prints:

```<code>Rating:  ['ui_bubble_rating', 'bubble_40']
Comment: I was there couple of weeks ago on the weekend. There was an event but it was not very crowded thought and I actually like it. What drawn my attention is the PUB on the roof top. A Pub in a department store sound pretty...
Rating:  ['ui_bubble_rating', 'bubble_50']
Comment: Show dc is very fascinating place that you must to go. The mega complex is very special from the others mall in thailand. I think you can touching and feeling of the hapiness. I went there few days ago for find some dining and spending...
</code>```

Body:
I am fairly new to Webscraping and gave my attempt after watching some tutorial videos online. I decided to use Tripadvisor.com and try to gather data from customer reviews.

This is what I came up with (code):

from urllib.request import urlopen as uReq

from bs4 import BeautifulSoup as soup

my_url = 'https://www.tripadvisor.com.sg/Attraction_Review-g293916-d12033454-
Reviews-SHOW_DC-Bangkok.html'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")

containers = page_soup.findAll("div",{"class":"ui_column is-9"})

for container in containers:
   rating = container.div.div.div.span["class"]

    comment_container = container.p
    comment = comment_container[0]

    print("rating" + rating)
    print("comment" + comment)

This was the output of my code:

Traceback (most recent call last):
  File "trip_advisor.py", line 18, in <module>
    comment = comment_container[0]
  File "/anaconda/lib/python3.6/site-packages/bs4/element.py", line 1011, in
__getitem__
    return self.attrs[key]
KeyError: 0

Can anyone help me fix this problem? Thanks.

Body:
You won't be able to access the contents by using the index in a <class bs4.element.Tag'>, you need .contents for that:

>>> container.p
<p class="partial_entry">I was there couple of weeks ago on the weekend. There was an event but it was not very crowded thought and I actually like it. What drawn my attention is the PUB on the roof top. A Pub in a department store sound pretty...<span class="taLnk ulBlueLinks" onclick="ta.prwidgets.call('handlers.clickExpand',event,this);">More</span></p>
>>> container.p.contents[0]
'I was there couple of weeks ago on the weekend. There was an event but it was not very crowded thought and I actually like it. What drawn my attention is the PUB on the roof top. A Pub in a department store sound pretty...'

Besides this issue, I'm not sure if your rating scraping is really getting what you want, but this solves the main error:

for container in containers:
    rating = container.div.div.div.span["class"]
    comment_container = container.p.contents
    comment = comment_container[0]
    print("Rating: ", rating)
    print("Comment: " + comment)

This prints:

Rating:  ['ui_bubble_rating', 'bubble_40']
Comment: I was there couple of weeks ago on the weekend. There was an event but it was not very crowded thought and I actually like it. What drawn my attention is the PUB on the roof top. A Pub in a department store sound pretty...
Rating:  ['ui_bubble_rating', 'bubble_50']
Comment: Show dc is very fascinating place that you must to go. The mega complex is very special from the others mall in thailand. I think you can touching and feeling of the hapiness. I went there few days ago for find some dining and spending...


问:
How to clear the array index using jquery?
```<code>var items=[];

items.push(data);
</code>```

I am using an array to store my data, and then submit using ajax. For the first time submission, it works fine. But when submit subsequently, it will submit null value together with data passing to server.

I am using the method below to clear the array, but i found that the previous data just set to null. For example, for the first time i passed value 1, successful. For the second submission, i clear the array and store new value, e.g. i pushed value 2 to the items[], when submit it will submit null and 2.

```<code>items.splice(0);
</code>```

How can i fix it? I need to reset the array every time submit the value.

Code:

```<code>var items=[];
$("#selection").click(function(e) {
       $(":checkbox").each(function() {
            if(this.checked === false) {
                this.checked = true;
                items.push(this.id);
            }
        });
});

$('#grid').submit(function(e){
            e.preventDefault();
            var formdata = {
                data:items
            };
            $.ajax({
                type: "POST",
                url: "/add",
                data: formdata ,
                dataType:'html',
                success: function(data) {
                    alert("added");
                }
            });
        });
</code>```

答:
You simply set the array to a empty array after the ajax

```<code>success: function(data) {
    alert("added");
    items=[];
}
</code>```

or better empty it at each click

```<code>$("#selection").click(function(e) {
items=[];
// rest of the code
</code>```

Body:
var items=[];

items.push(data);

I am using an array to store my data, and then submit using ajax. For the first time submission, it works fine. But when submit subsequently, it will submit null value together with data passing to server.

I am using the method below to clear the array, but i found that the previous data just set to null. For example, for the first time i passed value 1, successful. For the second submission, i clear the array and store new value, e.g. i pushed value 2 to the items[], when submit it will submit null and 2.

items.splice(0);

How can i fix it? I need to reset the array every time submit the value.

Code:

var items=[];
$("#selection").click(function(e) {
       $(":checkbox").each(function() {
            if(this.checked === false) {
                this.checked = true;
                items.push(this.id);
            }
        });
});

$('#grid').submit(function(e){
            e.preventDefault();
            var formdata = {
                data:items
            };
            $.ajax({
                type: "POST",
                url: "/add",
                data: formdata ,
                dataType:'html',
                success: function(data) {
                    alert("added");
                }
            });
        });

Body:
You simply set the array to a empty array after the ajax

success: function(data) {
    alert("added");
    items=[];
}

or better empty it at each click

$("#selection").click(function(e) {
items=[];
// rest of the code

ContentLicense: CC BY-SA 4.0


问:
AWS Bandwidth data transfer out beyond the global free tier dramatically increased
I'm new to AWS. I launched a EC2 instance and some S3 buckets in April.

The cost of AWS in April and May are normal, but the cost of AWS in June are doubly increased.

I went to the Bills Page to check and I found that the data transfer is abnormal.

Here are the pictures about the cost in May and June:

I didn't change anything except the ssh setting of EC2's (myip -> anywhere).

Can anyone tell me where should I check my setting first?

答:
I assume you are referring to:

Data Transfer in May: 48 GB for $4.36

Data Transfer in June: 319 GB for $28.71

Data Transfer is charged for outbound traffic to the Internet. The AWS Free Usage Tier provides an initial 15GB at no charge. Thereafter, the charge depends upon your Region. It appears that you are in the USA, where the rate is $0.09/GB.

There has been no price increase on AWS. In fact, AWS just announced their 62nd price reduction. Rather, the cause of the increased charge is the fact that your account consumed more data transfer in June (319 GB) than in May (45 GB).

Data transfer would include users on the Internet accessing your web servers, any downloads from AWS (eg from Amazon S3) and everything else causing data to go from AWS to the Internet.

If you think this is too high, you should examine the services you are running and, in particular, make sure you are not serving large content from Amazon S3.