问:
swift: recursive animation
In my app I want to animate an array of Strings to give some instruction to users. My expectation is the first string fades in, maintains for seconds and fades out then the first string is removed from the array and the next shows and so on until the array gets empty. There is something wrong with my implementation however it's hard to debug (it seems the program would not be executed line by line), here is my code:

```<code>var text = [Text.text1, Text.text2]
@IBOutlet weak var paragraph: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    paragraph.alpha = 0
    showText(text: text)
}

private func showText(text: [String]) {
    if text.first == nil {
        return
    } else {
        paragraph.text = text.first
        UIView.animate(withDuration: 1.5, delay: 1.5, options: .curveEaseInOut, animations: {
            self.paragraph.alpha = 1
        }, completion: { (_) in
            UIView.animate(withDuration: 1.5, delay: 0.5, options: .curveEaseInOut, animations: {
                self.paragraph.alpha = 0
            }, completion: { (_) in
                self.text.remove(at: 0)
                self.showText(text: text)
            })
        })
    }
}
</code>```

The problem is the first string shows three times and then I get an index out of range error. When I try setting breakpoints and click step over, it will skip the animation and completion blocks, and I don't know how to debug a function with a block as its parameter. And also even though I have

```<code>paragraph.text = text.first
</code>```

after the first round, paragraph.text has been the second string but still the first string shows.
Similarly, it seems my terminate condition doesn't work: after two iterations, I've noticed the count of the self.text array has become 0, but the function didn't return, it goes to else...

```<code>if text.count == 0 {
            return
        } else { ... }
</code>```

I'm a newbie and don't know how to debug blocks...

答:
The problem is subtle and it's all in the second completion block. You have:

```<code>self.text.remove(at: 0)
self.showText(text: text)
</code>```

You update the text property but you then pass the local text parameter which hasn't been changed.

Change the 2nd line to pass self.text instead of just text.

But referencing self.text inside showText negates to need to even have the text parameter. Either write showText to only use the text property of the class or better, only reference the text parameter. The latter has the advantage of not modifying the property.

To implement the latter option, change the two lines in the second completion block from:

```<code>self.text.remove(at: 0)
self.showText(text: text)
</code>```

to just:

```<code>self.showText(text: Array(text[1...]))
</code>```

Title: swift: recursive animation

Body:
In my app I want to animate an array of Strings to give some instruction to users. My expectation is the first string fades in, maintains for seconds and fades out then the first string is removed from the array and the next shows and so on until the array gets empty. There is something wrong with my implementation however it's hard to debug (it seems the program would not be executed line by line), here is my code:

var text = [Text.text1, Text.text2]
@IBOutlet weak var paragraph: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    paragraph.alpha = 0
    showText(text: text)
}

private func showText(text: [String]) {
    if text.first == nil {
        return
    } else {
        paragraph.text = text.first
        UIView.animate(withDuration: 1.5, delay: 1.5, options: .curveEaseInOut, animations: {
            self.paragraph.alpha = 1
        }, completion: { (_) in
            UIView.animate(withDuration: 1.5, delay: 0.5, options: .curveEaseInOut, animations: {
                self.paragraph.alpha = 0
            }, completion: { (_) in
                self.text.remove(at: 0)
                self.showText(text: text)
            })
        })
    }
}

The problem is the first string shows three times and then I get an index out of range error. When I try setting breakpoints and click step over, it will skip the animation and completion blocks, and I don't know how to debug a function with a block as its parameter. And also even though I have

paragraph.text = text.first

after the first round, paragraph.text has been the second string but still the first string shows.
Similarly, it seems my terminate condition doesn't work: after two iterations, I've noticed the count of the self.text array has become 0, but the function didn't return, it goes to else...

if text.count == 0 {
            return
        } else { ... }

I'm a newbie and don't know how to debug blocks...

Body:
The problem is subtle and it's all in the second completion block. You have:

self.text.remove(at: 0)
self.showText(text: text)

You update the text property but you then pass the local text parameter which hasn't been changed.

Change the 2nd line to pass self.text instead of just text.

But referencing self.text inside showText negates to need to even have the text parameter. Either write showText to only use the text property of the class or better, only reference the text parameter. The latter has the advantage of not modifying the property.

To implement the latter option, change the two lines in the second completion block from:

self.text.remove(at: 0)
self.showText(text: text)

to just:

self.showText(text: Array(text[1...]))


来源: stackexchange

问:
Show hide multiple divs based on select value
Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

I think data attributes would be a good route to go down but a little unsure of where to start.

```<code><form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div data-response="op1">
      This is content for option 1.
    </div>
    <div data-response="op2">
      This is content for option 2.
    </div>
    <div data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>
</code>```

答:
I highly recommend reading Decoupling Your HTML, CSS, and JavaScript.  You can make some really simple and reusable jQuery that does some pretty cool stuff, without a lot of duplicate code or tightly coupled code.  The following is very extensible, reusable, easy to read and maintain.

$(document).ready(()=>{
  $('.js-revealer').on('change', function(){
    var $select = $(this);
    var $selected = $select.find('option:selected');
    var hideSelector = $selected.data('r-hide-target');
    var showSelector = $selected.data('r-show-target');

    $(hideSelector).addClass('is-hidden');
    $(showSelector).removeClass('is-hidden');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.is-hidden{
  display: none;
}</code>```

<form>

      <select id="select-box" class="js-revealer">
      <option value="0" data-r-show-target="" data-r-hide-target=".opt-1, .opt-2, .opt-3, .opt-other">- please select -</option>
      <option value="1" data-r-show-target=".opt-1, .opt-other" data-r-hide-target=".opt-2, .opt-3">Option 1</option>
      <option value="2" data-r-show-target=".opt-2, .opt-other" data-r-hide-target=".opt-1, .opt-3">Option 2</option>
      <option value="3" data-r-show-target=".opt-3, .opt-other" data-r-hide-target=".opt-1, .opt-2">Option 3</option>
    </select>

      This is content for option 1.

      This is content for option 2.

      This is content for option 3.

    Rest of form content. This area should show when option values 1-3 are selected in the select field.

</form>```

ContentLicense: CC BY-SA 3.0

Body:
Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

I think data attributes would be a good route to go down but a little unsure of where to start.

<form>

      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>

      This is content for option 1.

      This is content for option 2.

      This is content for option 3.

    Rest of form content. This area should show when option values 1-3 are selected in the select field.

</form>

Body:
I highly recommend reading Decoupling Your HTML, CSS, and JavaScript.  You can make some really simple and reusable jQuery that does some pretty cool stuff, without a lot of duplicate code or tightly coupled code.  The following is very extensible, reusable, easy to read and maintain.

$(document).ready(()=>{
  $('.js-revealer').on('change', function(){
    var $select = $(this);
    var $selected = $select.find('option:selected');
    var hideSelector = $selected.data('r-hide-target');
    var showSelector = $selected.data('r-show-target');

    $(hideSelector).addClass('is-hidden');
    $(showSelector).removeClass('is-hidden');
  });
});

.is-hidden{
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box" class="js-revealer">
      <option value="0" data-r-show-target="" data-r-hide-target=".opt-1, .opt-2, .opt-3, .opt-other">- please select -</option>
      <option value="1" data-r-show-target=".opt-1, .opt-other" data-r-hide-target=".opt-2, .opt-3">Option 1</option>
      <option value="2" data-r-show-target=".opt-2, .opt-other" data-r-hide-target=".opt-1, .opt-3">Option 2</option>
      <option value="3" data-r-show-target=".opt-3, .opt-other" data-r-hide-target=".opt-1, .opt-2">Option 3</option>
    </select>
    </div>

    <div data-response="op1" class="opt-1 is-hidden">
      This is content for option 1.
    </div>
    <div data-response="op2" class="opt-2 is-hidden">
      This is content for option 2.
    </div>
    <div data-response="op3" class="opt-3 is-hidden">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions" class="opt-other is-hidden">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>


问:
Ubuntu on Windows as VS Code terminal - executable path
There is a related question but it details the approach for WSL, in newer versions of Windows, the Linux distributions are not beta anymore and they are provided through the MS app store.

Where do I find the path to Ubuntu on Windows executable? (Not WSL.) I tried right-clicking on the icon to find Properties, but it is not there, it seems to be some special kind of a shortcut.

答:
Open VSCode Settings Ctrl + , or File > Prefrences > Settings

User Settings will open up. Add the following in that file:

"terminal.integrated.shell.windows": "C:\Windows\System32\bash.exe"

Save and close the user settings file.

Enjoy bash in VSCode!


问:
Count subarray elements and sum deep subarray elements
I'm working with an API that returns a JSON object which I then decode into an array using

I need to get a count of all the [data] items in the array, and then generate a total of all the [Total] values contained in each

Here's my array:-

```<code>Array
(
    [errorCode] => 0
    [result] => OK
    [data] => Array
        (
            [0] => Array
                (
                    [fieldData] => Array
                        (
                            [Due Date] => 11/30/2017
                            [Date] => 11/30/2017
                            [Total] => 128.97
                            [Customers::Company] => A B C Lock & Key
                            [Status] => Paid
                            [Date Payment] => 11/30/2017
                        )

                    [portalData] => Array
                        (
                        )

                    [recordId] => 1
                    [modId] => 4
                )

            [1] => Array
                (
                    [fieldData] => Array
                        (
                            [Due Date] => 12/01/2017
                            [Date] => 12/01/2017
                            [Total] => 256
                            [Customers::Company] => Kim Peacock Beringhause
                            [Status] => Paid
                            [Date Payment] => 12/01/2017
                        )

                    [portalData] => Array
                        (
                        )

                    [recordId] => 2
                    [modId] => 3
                )

            [2] => Array
                (
                    [fieldData] => Array
                        (
                            [Due Date] => 11/30/2017
                            [Date] => 11/30/2017
                            [Total] => 1880
                            [Customers::Company] => Norton, Robert L Esq
                            [Status] => Unpaid Overdue
                            [Date Payment] =>
                        )

                    [portalData] => Array
                        (
                        )

                    [recordId] => 3
                    [modId] => 0
                )

            [3] => Array
                (
                    [fieldData] => Array
                        (
                            [Due Date] => 12/22/2017
                            [Date] => 12/22/2017
                            [Total] => 1278
                            [Customers::Company] => Shapiro, Mark R Esq
                            [Status] => Unpaid
                            [Date Payment] =>
                        )

                    [portalData] => Array
                        (
                        )

                    [recordId] => 10
                    [modId] => 1
                )

        )

)
</code>```

I've tried:

```<code>count($array)
</code>```

which returns 3 which I can see are the count of the 3 items in that parent array (errorCode, result and data), but I can't work out how to focus on the data only.

The count value I'm after is 4 and the total value is 3542.97.

答:
For count you need to do:

```<code>count($array['data']);
</code>```

And for getting sum of all Total index values:

```<code>echo array_sum(
         array_column(
             array_column(
                 $array['data'],
                 'fieldData'
             ),
             'Total'
         )
     );
</code>```

Reference:- PHP: array_column - Manual

ContentLicense: CC BY-SA 4.0

Body:
I'm working with an API that returns a JSON object which I then decode into an array using

I need to get a count of all the [data] items in the array, and then generate a total of all the [Total] values contained in each

Here's my array:-

Array
(
    [errorCode] => 0
    [result] => OK
    [data] => Array
        (
            [0] => Array
                (
                    [fieldData] => Array
                        (
                            [Due Date] => 11/30/2017
                            [Date] => 11/30/2017
                            [Total] => 128.97
                            [Customers::Company] => A B C Lock & Key
                            [Status] => Paid
                            [Date Payment] => 11/30/2017
                        )

                    [portalData] => Array
                        (
                        )

                    [recordId] => 1
                    [modId] => 4
                )

            [1] => Array
                (
                    [fieldData] => Array
                        (
                            [Due Date] => 12/01/2017
                            [Date] => 12/01/2017
                            [Total] => 256
                            [Customers::Company] => Kim Peacock Beringhause
                            [Status] => Paid
                            [Date Payment] => 12/01/2017
                        )

                    [portalData] => Array
                        (
                        )

                    [recordId] => 2
                    [modId] => 3
                )

            [2] => Array
                (
                    [fieldData] => Array
                        (
                            [Due Date] => 11/30/2017
                            [Date] => 11/30/2017
                            [Total] => 1880
                            [Customers::Company] => Norton, Robert L Esq
                            [Status] => Unpaid Overdue
                            [Date Payment] =>
                        )

                    [portalData] => Array
                        (
                        )

                    [recordId] => 3
                    [modId] => 0
                )

            [3] => Array
                (
                    [fieldData] => Array
                        (
                            [Due Date] => 12/22/2017
                            [Date] => 12/22/2017
                            [Total] => 1278
                            [Customers::Company] => Shapiro, Mark R Esq
                            [Status] => Unpaid
                            [Date Payment] =>
                        )

                    [portalData] => Array
                        (
                        )

                    [recordId] => 10
                    [modId] => 1
                )

        )

)

I've tried:

count($array)

which returns 3 which I can see are the count of the 3 items in that parent array (errorCode, result and data), but I can't work out how to focus on the data only.

The count value I'm after is 4 and the total value is 3542.97.

Body:
For count you need to do:

count($array['data']);

And for getting sum of all Total index values:

echo array_sum(
         array_column(
             array_column(
                 $array['data'],
                 'fieldData'
             ),
             'Total'
         )
     );

Reference:- PHP: array_column - Manual


问:
Turn a set of 3d coordinates into polygonal "landscape" in Java
I'm working on a visualization project. From the data I have calculated the X, Y, and Z coordinates for a large set of points. Using Processing it was very simple to draw this out with lines and dots.

From the top it looks like this:

And from a side angle you can see how it occupies 3D space

The part I'm struggling with is turning this into polygons. I need the end result to be something I can export as a .obj file, and then later open in Blender or similar 3D modelling programs.

The two main issues are that these points are not on a grid, but are instead organized in a circle based on radian angles, and that the triangle structure isn't all that simple.

I tried drawing out my own polygons (it's kinda sorta working), but I'm getting to the point where the maths are getting a bit too complex to handle and my code is bloated with arrays, if statements, and for loops...

Surely there must be a better way? Are there any plugins maybe that would help me with this task? Or some techniques I should take a look at?

答: Processing has screenX() and screenY() functions that take a 3D point and return a 2D point. That sounds like pretty much exactly what you're looking for. Please see the reference for more info.


问:
R modify value in one column if content in another column contains string
I am working with a large data set where I want to determine if a column containing text strings passes a logical test where I can subset it out later. Currently, I'm trying to build the test column for each row. The test is based on if the cell contains less than 2 relevant characters, but I want to keep the full set of characters in the actual cell. The following is a simplified example of what I am trying to do:

Suppose I have the following data frame:

```<code>df <- data.frame(matrix(NA, nrow = 5, ncol = 1))
colnames(df) <- "test"
df$test <- c("one", "two", "three", "one", "onetwo")
df$hyp <- ("two", "one", "onetwo", "one", "two")
df$testcount <- sapply(df$test, str_length)
df$hypcount <- sapply(df$hyp, str_length)
df

    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         3        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         6        3
</code>```

I want to identify a text string, like "two", and if a row in the test column or hyp column (depending on the test I'm running. I don't want this to run on both columns) contains the string (though is not identical to the string), then I want that same row to subtract the number of characters in the string I identified from the testcount or hypcount columns.

For example, if I run this function on the text string "two" in the test column, then I should get the following output:

```<code>    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         0        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         3        3
</code>```

And if I were to run this on the hyp column, then I should get the following output:

```<code>    test    hyp testcount hypcount
1    one    two         3        0
2    two    one         3        3
3  three onetwo         5        3
4    one    one         3        3
5 onetwo    two         6        0
</code>```

I have tried three approaches. First I tried using an if function to run the replacement conditionally (on this test I tested for the string "one" instead of "two"):

```<code>if(grepl("one", df$test)) {
  df[which(grepl("one", df$test)), ]$testcount = df[which(grepl("one", df$test)), ]$testcount - 3
  }
</code>```

But this returns the warning:
"In if (grepl("one", df$test)) { :
  the condition has length > 1 and only the first element will be used"

This leads to a correct substitution for the string "one", but not the string "two". Further, if I substitute for string "two" in the hyp column, the function works, but not if I run the substitution for string "one". I suspect this is because it only runs the test on the first row, and if it is true, then it checks the entire data frame.

Next I tried running the function within an lapply function:

```<code>df <- data.frame(lapply(df, function(x) {
  if(grepl("one", df$test)) {
    df[which(grepl("one", df$test)), ]$testcount = df[which(grepl("one", df$test)), ]$testcount - 3
  }}))
</code>```

This also didn't work, though I don't fully understand why. Somehow it ends up returning the output:

```<code>  test hyp testcount hypcount
1    0   0         0        0
2    0   0         0        0
3    3   3         3        3
</code>```

Lastly, I tried running it as an ifelse operation (here I switched to replacing for string "two" so I don't mistakenly think the function works on all rows):

```<code>df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3))
</code>```

The strange thing is, this worked when I first applied it a few days ago. I tested it for the strings "two", "on", and "one", and it worked properly. Now, when I got around to applying it to my actual data, it didn't work. Further, when I went back to the testing to see what went wrong, it no longer is working. It simply returns the error:
  "Error in ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)),  :
  argument "no" is missing, with no default"

I have tried two solutions to this. First, I tried adding a statement into the "no" argument that would have no impact on my data:

```<code> df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3), T)
</code>```

However, this causes it to return the output:

```<code>    test    hyp testcount hypcount
1    one    two         1        3
2    two    one         3        3
3  three onetwo         1        6
4    one    one         1        3
5 onetwo    two         0        3
</code>```

Next I tried substituting a meaningful "no" argument:

```<code> df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount))
</code>```

But now it returns the output:

```<code>    test    hyp testcount hypcount
1    one    two        -3        3
2    two    one         0        3
3  three onetwo        -3        6
4    one    one         0        3
5 onetwo    two        -3        3
</code>```

I don't understand this output.

My question is, can anyone help me to understand why this is not working, and offer a solution? Thanks in advance!

答:
Try this function:</p>

```<code>subtract_match <- function(column1, column2, text, df) {
  df2 <- df
  df2[, column2] <- ifelse(grepl(text, df[, column1]),
                           df[, column2] - nchar(text),
                           df[, column2])
  df2
}

subtract_match("test", "testcount", "two", df1)

    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         0        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         3        3

subtract_match("hyp", "hypcount", "two", df1)

    test    hyp testcount hypcount
1    one    two         3        0
2    two    one         3        3
3  three onetwo         5        3
4    one    one         3        3
5 onetwo    two         6        0
</code>```

Body:
I am working with a large data set where I want to determine if a column containing text strings passes a logical test where I can subset it out later. Currently, I'm trying to build the test column for each row. The test is based on if the cell contains less than 2 relevant characters, but I want to keep the full set of characters in the actual cell. The following is a simplified example of what I am trying to do:

Suppose I have the following data frame:

df <- data.frame(matrix(NA, nrow = 5, ncol = 1))
colnames(df) <- "test"
df$test <- c("one", "two", "three", "one", "onetwo")
df$hyp <- ("two", "one", "onetwo", "one", "two")
df$testcount <- sapply(df$test, str_length)
df$hypcount <- sapply(df$hyp, str_length)
df

    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         3        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         6        3

I want to identify a text string, like "two", and if a row in the test column or hyp column (depending on the test I'm running. I don't want this to run on both columns) contains the string (though is not identical to the string), then I want that same row to subtract the number of characters in the string I identified from the testcount or hypcount columns.

For example, if I run this function on the text string "two" in the test column, then I should get the following output:

    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         0        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         3        3

And if I were to run this on the hyp column, then I should get the following output:

    test    hyp testcount hypcount
1    one    two         3        0
2    two    one         3        3
3  three onetwo         5        3
4    one    one         3        3
5 onetwo    two         6        0

I have tried three approaches. First I tried using an if function to run the replacement conditionally (on this test I tested for the string "one" instead of "two"):

if(grepl("one", df$test)) {
  df[which(grepl("one", df$test)), ]$testcount = df[which(grepl("one", df$test)), ]$testcount - 3
  }

But this returns the warning:
"In if (grepl("one", df$test)) { :
  the condition has length > 1 and only the first element will be used"

This leads to a correct substitution for the string "one", but not the string "two". Further, if I substitute for string "two" in the hyp column, the function works, but not if I run the substitution for string "one". I suspect this is because it only runs the test on the first row, and if it is true, then it checks the entire data frame.

Next I tried running the function within an lapply function:

df <- data.frame(lapply(df, function(x) {
  if(grepl("one", df$test)) {
    df[which(grepl("one", df$test)), ]$testcount = df[which(grepl("one", df$test)), ]$testcount - 3
  }}))

This also didn't work, though I don't fully understand why. Somehow it ends up returning the output:

  test hyp testcount hypcount
1    0   0         0        0
2    0   0         0        0
3    3   3         3        3

Lastly, I tried running it as an ifelse operation (here I switched to replacing for string "two" so I don't mistakenly think the function works on all rows):

df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3))

The strange thing is, this worked when I first applied it a few days ago. I tested it for the strings "two", "on", and "one", and it worked properly. Now, when I got around to applying it to my actual data, it didn't work. Further, when I went back to the testing to see what went wrong, it no longer is working. It simply returns the error:
  "Error in ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)),  :
  argument "no" is missing, with no default"

I have tried two solutions to this. First, I tried adding a statement into the "no" argument that would have no impact on my data:

 df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3), T)

However, this causes it to return the output:

    test    hyp testcount hypcount
1    one    two         1        3
2    two    one         3        3
3  three onetwo         1        6
4    one    one         1        3
5 onetwo    two         0        3

Next I tried substituting a meaningful "no" argument:

 df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount))

But now it returns the output:

    test    hyp testcount hypcount
1    one    two        -3        3
2    two    one         0        3
3  three onetwo        -3        6
4    one    one         0        3
5 onetwo    two        -3        3

I don't understand this output.

My question is, can anyone help me to understand why this is not working, and offer a solution? Thanks in advance!

Body:
Try this function:

subtract_match <- function(column1, column2, text, df) {
  df2 <- df
  df2[, column2] <- ifelse(grepl(text, df[, column1]),
                           df[, column2] - nchar(text),
                           df[, column2])
  df2
}

subtract_match("test", "testcount", "two", df1)

    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         0        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         3        3

subtract_match("hyp", "hypcount", "two", df1)

    test    hyp testcount hypcount
1    one    two         3        0
2    two    one         3        3
3  three onetwo         5        3
4    one    one         3        3
5 onetwo    two         6        0


问:
Showing 0 to 0 of 0 entries in DataTable
Hi I am new and i am using dataTable to display my, mysql data.So My Data are display correctly but here my dataTable footer doesn't work correctly.

Here is my code

```<code>UI_CRUD.prototype.refreshTable = function(params = {}){
    var tableBody = $('.view-datatable tbody');
    var dataUrl = this.moduleURL+'/alenter code herel';
    var title = this.moduleTitle;
    // console.log(this.moduleTitle);
    console.log('all ..');
    $.ajax({
        url: dataUrl,
        data : params,
    })
    .done(function(data) {
        var html = '';
            $.each(data, function(index, item) {
                 html+= '<tr>';
                    $.each(item, function(index, data) {
                        (index != 'id') ? html+= '<td>'+data+'</td>' : html+='';
                    });
                    html+= '<td class="actions">' +
                                '<i class="icon-eye text-primary view-btn" data-id="'+item.id+'">'+
                                '</i>'+
                                '<span></span>'+
                                '<i class="icon-pencil7 text-primary edit-btn" data-id="'+item.id+'">' +
                                '</i>'+
                                '<span></span>'+
                                '<i class="icon-bin sweet_combine text-danger delete-btn" data-id="'+item.id+'">' +
                                '</i>'+
                            '</td>';
                 html+= '</tr>';

            });
        tableBody.html(html);
    })
    .fail(function(res) {
        console.error(res,'UI_CRUD ERR : ');
    });
}
</code>```

This is the table in blade file.

```<code><table class="table view-datatable" id="mytable">
        <thead>
            <tr>
                <th>Company Code              </th>
                <th>Company Name              </th>
                <th>Company Address           </th>
                <th>Telephone No.             </th>
                <th>Fax No.                   </th>

                <th style="text-align: center;">Actions</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</code>```

this is the laravel controller

```<code>public function getAll()
    {
        $company = $this->getCompanies();
        return response()->json($company,200);
    }

public function getCompanies()
    {
        $company = Company::select("id", "CO_COMCODE", "CO_NAME",
            DB::raw("CONCAT(CO_ADD1, ',', CO_ADD2, ',', CO_ADD3, ',', CO_ADD4)  AS Address"),
            "CO_TELNO", "CO_FAXNO")
            ->get();

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

This is response json
 [{"id":39,"CO_COMCODE":"FFDE","CO_NAME":"dsfsdf","Address":"fsdfsd,fsdf,fdsf,fsdf","CO_TELNO":"123456789","CO_FAXNO":"123456789"},{"id":41,"CO_COMCODE":"AAAA","CO_NAME":"fdfdsf","Address":"dsfdsf,dfdsf,dsffdsf,fdsfsd","CO_TELNO":"123456789","CO_FAXNO":"123456789"}]

This is My Output page

This is the response

JSon Response preview and
JSon Response

答:
After many efforts, I fixed error

Issues was with applying dataTable plugin. After I remove that js file and add new dataTable.

```<code><table class="table view-datatable">
    <thead>
        <tr>
            <th>Company Code              </th>
            <th>Company Name              </th>
            <th>Company Address           </th>
            <th>Telephone No.             </th>
            <th>Fax No.                   </th>
        </tr>
    </thead>
    <tbody></tbody>
</code>```

```<code>var table = $('.view-datatable').DataTable( {
           "processing" : true,
           "retrieve": true,
           "ajax" : {
               "url" : ajax_url
           },
           "columns" : [  {
               "data" : "CO_COMCODE"
           }, {
               "data" : "CO_NAME"
           }, {
               "data" : "Address"
           }, {
               "data" : "CO_TELNO"
           }, {
               "data" : "CO_FAXNO"
           }, {
               data: null,
               className: "dataTable-center",
           },],
           "rowCallback": function( row, data, index ) {
               $('td:eq(5)', row).html(
                   '<i class="icon-eye text-primary view-btn" data-id="'+data.id+'">'+
                   '</i>'+
                   '<span>    </span>'+
                   '<i class="icon-pencil7 text-primary edit-btn" data-id="'+data.id+'">' +
                   '</i>'+
                   '<span>    </span>'+
                   '<i class="icon-bin sweet_combine text-danger delete-btn" data-id="'+data.id+'">' +
                   '</i>'
               );
           },
           "pagingType": "full_numbers",
           buttons: {
               buttons: [
                   {
                       extend: 'colvis',
                       className: 'btn btn-default'
                   },
                   {
                       text: 'Add New',
                       className: 'add-new btn bg-blue-800 ui-add-new',
                       action: function(e) {
                           // UI_addModel('show');
                       }
                   },
                   {extend: 'copy'},
                   // {extend: 'csv'},
                   {extend: 'excel'},
                   {extend: 'pdf'},
                   {extend: 'print'}
               ]
           }
       } );
</code>```

Body:
Hi I am new and i am using dataTable to display my, mysql data.So My Data are display correctly but here my dataTable footer doesn't work correctly.

Here is my code

UI_CRUD.prototype.refreshTable = function(params = {}){
    var tableBody = $('.view-datatable tbody');
    var dataUrl = this.moduleURL+'/alenter code herel';
    var title = this.moduleTitle;
    // console.log(this.moduleTitle);
    console.log('all ..');
    $.ajax({
        url: dataUrl,
        data : params,
    })
    .done(function(data) {
        var html = '';
            $.each(data, function(index, item) {
                 html+= '
';
                    $.each(item, function(index, data) {
                        (index != 'id') ? html+= ''+data+'	' : html+='';
                    });
                    html+= '' +
                                ''+
                                ''+
                                ''+
                                '' +
                                ''+
                                ''+
                                '' +
                                ''+
                            '	';
                 html+= '
';

            });
        tableBody.html(html);
    })
    .fail(function(res) {
        console.error(res,'UI_CRUD ERR : ');
    });
}

This is the table in blade file.

                Company Code
                Company Name
                Company Address
                Telephone No.
                Fax No.

                Actions

this is the laravel controller

public function getAll()
    {
        $company = $this->getCompanies();
        return response()->json($company,200);
    }

public function getCompanies()
    {
        $company = Company::select("id", "CO_COMCODE", "CO_NAME",
            DB::raw("CONCAT(CO_ADD1, ',', CO_ADD2, ',', CO_ADD3, ',', CO_ADD4)  AS Address"),
            "CO_TELNO", "CO_FAXNO")
            ->get();

        return $company;
    }

This is response json
 [{"id":39,"CO_COMCODE":"FFDE","CO_NAME":"dsfsdf","Address":"fsdfsd,fsdf,fdsf,fsdf","CO_TELNO":"123456789","CO_FAXNO":"123456789"},{"id":41,"CO_COMCODE":"AAAA","CO_NAME":"fdfdsf","Address":"dsfdsf,dfdsf,dsffdsf,fdsfsd","CO_TELNO":"123456789","CO_FAXNO":"123456789"}]

This is My Output page

This is the response

JSon Response preview and
JSon Response

Body:
After many efforts, I fixed error

Issues was with applying dataTable plugin. After I remove that js file and add new dataTable.

<table class="table view-datatable">
    <thead>
        <tr>
            <th>Company Code              </th>
            <th>Company Name              </th>
            <th>Company Address           </th>
            <th>Telephone No.             </th>
            <th>Fax No.                   </th>
        </tr>
    </thead>
    <tbody></tbody>

var table = $('.view-datatable').DataTable( {
           "processing" : true,
           "retrieve": true,
           "ajax" : {
               "url" : ajax_url
           },
           "columns" : [  {
               "data" : "CO_COMCODE"
           }, {
               "data" : "CO_NAME"
           }, {
               "data" : "Address"
           }, {
               "data" : "CO_TELNO"
           }, {
               "data" : "CO_FAXNO"
           }, {
               data: null,
               className: "dataTable-center",
           },],
           "rowCallback": function( row, data, index ) {
               $('td:eq(5)', row).html(
                   '<i class="icon-eye text-primary view-btn" data-id="'+data.id+'">'+
                   '</i>'+
                   '<span>    </span>'+
                   '<i class="icon-pencil7 text-primary edit-btn" data-id="'+data.id+'">' +
                   '</i>'+
                   '<span>    </span>'+
                   '<i class="icon-bin sweet_combine text-danger delete-btn" data-id="'+data.id+'">' +
                   '</i>'
               );
           },
           "pagingType": "full_numbers",
           buttons: {
               buttons: [
                   {
                       extend: 'colvis',
                       className: 'btn btn-default'
                   },
                   {
                       text: 'Add New',
                       className: 'add-new btn bg-blue-800 ui-add-new',
                       action: function(e) {
                           // UI_addModel('show');
                       }
                   },
                   {extend: 'copy'},
                   // {extend: 'csv'},
                   {extend: 'excel'},
                   {extend: 'pdf'},
                   {extend: 'print'}
               ]
           }
       } );


问:
SQL: show description in text instead of bit value
I have an attribute declared as bit: (true or false).

For example:

```<code>SELECT myBit FROM [table]
</code>```

=> it will show: 1 or 0

I would like to show: 'Valid' and 'Invalid' for 1 and 0 respectively.

How could I add IF ELSE statement in the SELECT statement?

答:
For SQL Server, you can use a CASE statement:

```<code>SELECT CASE myBit WHEN 1 THEN 'Valid' WHEN 0 THEN 'Invalid' END As MyColumn
FROM [table]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an attribute declared as bit: (true or false).

For example:

SELECT myBit FROM [table]

=> it will show: 1 or 0

I would like to show: 'Valid' and 'Invalid' for 1 and 0 respectively.

How could I add IF ELSE statement in the SELECT statement?

Body:
For SQL Server, you can use a CASE statement:

SELECT CASE myBit WHEN 1 THEN 'Valid' WHEN 0 THEN 'Invalid' END As MyColumn
FROM [table]


问:
vitamio unable to play udp streaming in android
I am using vitamio library to play video streaming in android . Though I can play rtsp streaming with it, but I can't play udp streaming .

I integrated vitamio via gradle

```<code>compile 'me.neavo:vitamio:4.2.2'
</code>```

And using it on activity like following

```<code>        setContentView(R.layout.activity_main);
        if (!io.vov.vitamio.LibsChecker.checkVitamioLibs(this)) //it will check the include library of Vitamio
            return;

        mVideoView = (VideoView) findViewById(R.id.videoView);
        Vitamio.initialize(this);
        mVideoView.setVideoPath("udp://@192.168.0.104:1234");
        //mVideoView.setVideoPath("rtsp://192.168.0.104:8554/ss");
        mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
        mVideoView.setBufferSize(2048);
        mVideoView.requestFocus();
        mVideoView.start();
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.setPlaybackSpeed(1.0f);
            }

        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
</code>```

Here is my code for layout

```<code><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="me.example.vitamiotest.MainActivity">

    <io.vov.vitamio.widget.VideoView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/videoView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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

I tried chaning url to udp://@192.168.0.104:1234 (removing @) with no luck . rtsp streaming is playing well .

Here is one thing to be noted that those streaming aren't actually live streaming in some remote url . I am streaming from my PC using vlc  and 192.168.0.104 is my PC's local ip .In case of rtsp I can play rtsp://192.168.0.104:8554/ss this url but for udp nothing worked, no error msg in the log .

答:
try this udp stream on your Pc or use other SoftWare;
in my app,udp steam is playing right.

mVideoView.setVideoPath("udp://@238.0.0.1:1234");

Body:
I am using vitamio library to play video streaming in android . Though I can play rtsp streaming with it, but I can't play udp streaming .

I integrated vitamio via gradle

compile 'me.neavo:vitamio:4.2.2'

And using it on activity like following

        setContentView(R.layout.activity_main);
        if (!io.vov.vitamio.LibsChecker.checkVitamioLibs(this)) //it will check the include library of Vitamio
            return;

        mVideoView = (VideoView) findViewById(R.id.videoView);
        Vitamio.initialize(this);
        mVideoView.setVideoPath("udp://@192.168.0.104:1234");
        //mVideoView.setVideoPath("rtsp://192.168.0.104:8554/ss");
        mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
        mVideoView.setBufferSize(2048);
        mVideoView.requestFocus();
        mVideoView.start();
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.setPlaybackSpeed(1.0f);
            }

        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });

Here is my code for layout

<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="me.example.vitamiotest.MainActivity">

    <io.vov.vitamio.widget.VideoView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/videoView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

I tried chaning url to udp://@192.168.0.104:1234 (removing @) with no luck . rtsp streaming is playing well .

Here is one thing to be noted that those streaming aren't actually live streaming in some remote url . I am streaming from my PC using vlc  and 192.168.0.104 is my PC's local ip .In case of rtsp I can play rtsp://192.168.0.104:8554/ss this url but for udp nothing worked, no error msg in the log .


问:
Converting date format: conversion error in Java?
I am trying to convert this date to a different format. unfortuantely havnt been successful parsing the date and retaining all the information correctly.

06-Dec-2017 07:14:56.656PM
to
2017-12-06 19:14:56.656

If I try to parse the input date

```<code>LocalDateTime.parse("06-Dec-2017 07:14:56.656PM",
        DateTimeFormatter.ofPattern("D-MMM-yyyy HH:mm:ss.SSSa"));
</code>```

I get the following error - not sure what it means?

```<code>Exception in thread "main" java.time.format.DateTimeParseException: Text '06-Dec-2017 07:14:56.656PM' could not be parsed: Conflict found: Field MonthOfYear 1 differs from MonthOfYear 12 derived from 2017-01-06
    at java.time.format.DateTimeFormatter.createError(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)
    at com.cordys.coe.alf.logger.DBLogger.main(DBLogger.java:366)
Caused by: java.time.DateTimeException: Conflict found: Field MonthOfYear 1 differs from MonthOfYear 12 derived from 2017-01-06
    at java.time.format.Parsed.crossCheck(Unknown Source)
    at java.time.format.Parsed.crossCheck(Unknown Source)
</code>```

and if try

```<code>System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
        .format((new SimpleDateFormat("DD-MMM-yyyy HH:mm:ss.SSSa")
                .parse("06-Dec-2017 07:14:56.656PM"))));
</code>```

It give the following which is confusing, and probably not correct.
2017-01-06 07:14:56:656

答:
You have 2 problems

D should be d

D represents day of year

d represents day-of-month

HH should be hh

H represents hour-of-day (0-23)

h represents clock-hour-of-am-pm (1-12)

Please change D-MMM-yyyy HH:mm:ss.SSSa to d-MMM-yyyy hh:mm:ss.SSSa

For more information , check the oracle docs

Body:
I am trying to convert this date to a different format. unfortuantely havnt been successful parsing the date and retaining all the information correctly.

06-Dec-2017 07:14:56.656PM
to
2017-12-06 19:14:56.656

If I try to parse the input date

LocalDateTime.parse("06-Dec-2017 07:14:56.656PM",
        DateTimeFormatter.ofPattern("D-MMM-yyyy HH:mm:ss.SSSa"));

I get the following error - not sure what it means?

Exception in thread "main" java.time.format.DateTimeParseException: Text '06-Dec-2017 07:14:56.656PM' could not be parsed: Conflict found: Field MonthOfYear 1 differs from MonthOfYear 12 derived from 2017-01-06
    at java.time.format.DateTimeFormatter.createError(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)
    at com.cordys.coe.alf.logger.DBLogger.main(DBLogger.java:366)
Caused by: java.time.DateTimeException: Conflict found: Field MonthOfYear 1 differs from MonthOfYear 12 derived from 2017-01-06
    at java.time.format.Parsed.crossCheck(Unknown Source)
    at java.time.format.Parsed.crossCheck(Unknown Source)

and if try

System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
        .format((new SimpleDateFormat("DD-MMM-yyyy HH:mm:ss.SSSa")
                .parse("06-Dec-2017 07:14:56.656PM"))));

It give the following which is confusing, and probably not correct.
2017-01-06 07:14:56:656


问:
Vuex how to pass state/getter in data prop
I retrieved my data from database using axios under my vuex

```<code>const state = {
    giveaways: null
}

const actions = {
    getGiveAways : ({commit}) =>{

        axios({
            url : '/prod/api/thresholds_settings',
            method: 'post',
            data : {
            },
            config: 'JOSN'
        })
        .then(response=>{
            if(response.status == 200){
                //console.log(response.data.total_giveaways);
                commit('SET_GIVEAWAYS', response.data.total_giveaways)
            }
        })
        .catch(error=>{
            if(error.response){
                console.log('something happened')
            }
        });
    }
}

const mutations = {
    SET_GIVEAWAYS : (state, obj)=>{
        state.giveaways = obj
    }

}

const getters = {
    doneGiveAways(state){
        return state.giveaways
    }
}
</code>```

In my Dashboard.vue I have

```<code>import {mapState,mapGetters} from 'vuex'
export default{
    data: () => ({
        cards: [],
        giveaways: ''
    }),
    computed:{
        ...mapState({
            Giveaway: state => state.Threshold.giveaways
        }),
        doneGiveAways(){
            return this.$store.getters.doneGiveAways
        }
    },
    ready(){
        //giveaways: this.Giveaways
        //console.log(this.Giveaways);
    },
    created(){
        const self = this
        this.cards[0].result_val = 2
        this.cards[2].result_val = 2;

    },
    mounted(){
        this.$store.dispatch('getGiveAways');
        console.log(this.giveaways);

    }
}
</code>```

My problem is I need to pass the value from the mapState Giveaway to my returning data giveaways: '' so when page fires I can get the response value using this.giveaways. If I just call {{ Giveaway }} in my html it shows the value. But I need to make something like this.giveaways = this.$store.state.Thresholds.giveaways

答:
I would use Stephan-v's recommendation and delete the local copy of giveaways. But I don't know what your specific reason is for declaring an extra copy of giveaways, so here is a solution that will work:

In your Dashboard.vue add:

```<code>export default {
    ...
    watch: {
        Giveaway(value) {
            this.giveaways = value
        }
    },
    ...
}
</code>```

Body:
I retrieved my data from database using axios under my vuex

const state = {
    giveaways: null
}

const actions = {
    getGiveAways : ({commit}) =>{

        axios({
            url : '/prod/api/thresholds_settings',
            method: 'post',
            data : {
            },
            config: 'JOSN'
        })
        .then(response=>{
            if(response.status == 200){
                //console.log(response.data.total_giveaways);
                commit('SET_GIVEAWAYS', response.data.total_giveaways)
            }
        })
        .catch(error=>{
            if(error.response){
                console.log('something happened')
            }
        });
    }
}

const mutations = {
    SET_GIVEAWAYS : (state, obj)=>{
        state.giveaways = obj
    }

}

const getters = {
    doneGiveAways(state){
        return state.giveaways
    }
}

In my Dashboard.vue I have

import {mapState,mapGetters} from 'vuex'
export default{
    data: () => ({
        cards: [],
        giveaways: ''
    }),
    computed:{
        ...mapState({
            Giveaway: state => state.Threshold.giveaways
        }),
        doneGiveAways(){
            return this.$store.getters.doneGiveAways
        }
    },
    ready(){
        //giveaways: this.Giveaways
        //console.log(this.Giveaways);
    },
    created(){
        const self = this
        this.cards[0].result_val = 2
        this.cards[2].result_val = 2;

    },
    mounted(){
        this.$store.dispatch('getGiveAways');
        console.log(this.giveaways);

    }
}

My problem is I need to pass the value from the mapState Giveaway to my returning data giveaways: '' so when page fires I can get the response value using this.giveaways. If I just call {{ Giveaway }} in my html it shows the value. But I need to make something like this.giveaways = this.$store.state.Thresholds.giveaways

Body:
I would use Stephan-v's recommendation and delete the local copy of giveaways. But I don't know what your specific reason is for declaring an extra copy of giveaways, so here is a solution that will work:

In your Dashboard.vue add:

export default {
    ...
    watch: {
        Giveaway(value) {
            this.giveaways = value
        }
    },
    ...
}


问:
Android Drawing text with opengl es crashes after a few minutes
I've created an opengl surface and everything works fine, however when I try to draw text onto it using the following method:

```<code>public void loadFPSTexture(GL10 gl){

    Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.RGB_565);
    bitmap.eraseColor(Color.BLACK);
    Canvas canvas = new Canvas(bitmap);

    Paint textPaint = new Paint();
    textPaint.setTextSize(35);
    textPaint.setFakeBoldText(true);
    textPaint.setAntiAlias(true);
    textPaint.setARGB(255, 255, 255, 255);
    canvas.drawText("FPS "+reportedFramerate, 10,35, textPaint);
    gl.glGenTextures(1, texturesFPS, 0);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesFPS[0]);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();
}
</code>```

Then used in my onDraw function with:

```<code>gl.glPushMatrix();
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesFPS[0]);
gl.glTranslatef(-surfaceSize.x/1.5f, surfaceSize.y/1.5f, 0.0f);
gl.glScalef(10, 10, 1.0f);
gl.glColor4f(1.0f, 1.0f, 1.0f, saturation_head);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0,vertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureFPSBuffer);
gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,GL10.GL_UNSIGNED_SHORT, indexBuffer);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glPopMatrix();
</code>```

I get a weird crash and the surface is unable to be drawn after this point. Logcat shows a constant stream of the following:

```<code>E/Adreno200-EGL( 2578): eglLockWindowSurface: failed to map the memory for fd=32 offs=1536000
E/SurfaceFlinger( 2578): GL error 0x0505
E/Adreno200-EGL( 2578): eglLockWindowSurface: failed to map the memory for fd=32 offs=1536000
E/Adreno200-EGL( 2578): egliSwapWindowSurface: oglSwapBuffer failed
E/SurfaceFlinger( 2578): eglSwapBuffers: EGL error 0x3003 (EGL_BAD_ALLOC)
</code>```

I'm not sure why this is happening? any help would be much appreciated!

答:
Looks like you're creating a new texture each time you call loadFPSTexture(), and never release it. After some time this will cause you to run out of memory, which could explain the EGL_BAD_ALLOC in your logs.

It would be better to create your bitmap, canvas and texturesFPS variables just once, and reuse them in the loadFPSTexture() function. In that case, you should probably use GLUtils.texSubImage2D() instead of GLUtils.texImage2D(), to upload new bitmap data to the existing texture.

Body:
I've created an opengl surface and everything works fine, however when I try to draw text onto it using the following method:

public void loadFPSTexture(GL10 gl){

    Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.RGB_565);
    bitmap.eraseColor(Color.BLACK);
    Canvas canvas = new Canvas(bitmap);

    Paint textPaint = new Paint();
    textPaint.setTextSize(35);
    textPaint.setFakeBoldText(true);
    textPaint.setAntiAlias(true);
    textPaint.setARGB(255, 255, 255, 255);
    canvas.drawText("FPS "+reportedFramerate, 10,35, textPaint);
    gl.glGenTextures(1, texturesFPS, 0);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesFPS[0]);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();
}

Then used in my onDraw function with:

gl.glPushMatrix();
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesFPS[0]);
gl.glTranslatef(-surfaceSize.x/1.5f, surfaceSize.y/1.5f, 0.0f);
gl.glScalef(10, 10, 1.0f);
gl.glColor4f(1.0f, 1.0f, 1.0f, saturation_head);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0,vertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureFPSBuffer);
gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,GL10.GL_UNSIGNED_SHORT, indexBuffer);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glPopMatrix();

I get a weird crash and the surface is unable to be drawn after this point. Logcat shows a constant stream of the following:

E/Adreno200-EGL( 2578): eglLockWindowSurface: failed to map the memory for fd=32 offs=1536000
E/SurfaceFlinger( 2578): GL error 0x0505
E/Adreno200-EGL( 2578): eglLockWindowSurface: failed to map the memory for fd=32 offs=1536000
E/Adreno200-EGL( 2578): egliSwapWindowSurface: oglSwapBuffer failed
E/SurfaceFlinger( 2578): eglSwapBuffers: EGL error 0x3003 (EGL_BAD_ALLOC)

I'm not sure why this is happening? any help would be much appreciated!


问:
Not able to resolve Unsupported major.minor version 52.0
I am trying to execute a Groovy Script in SoapUI 5.3.0 which imports a jar file compiled in JDK 1.8. However, since SoapUI 5.3.0 is using 1.7; I am getting an exception "Unsupported major.minor version 52.0".

I have tried to follow the below link, but was not able to solve it.

https://chat.stackoverflow.com/rooms/127289/discussion-between-rao-and-user5653362

I understand I need to modify soapui.bat in C:\Program Files\SmartBear\SoapUI-5.3.0/bin folder; so SoapUI starts using Java 1.8; but not exactly sure which property to change.

My soaupui.bat looks like below:

*

```<code>@echo off
set SOAPUI_HOME=%~dp0
if exist "%SOAPUI_HOME%..\jre\bin" goto SET_BUNDLED_JAVA
if exist "%JAVA_HOME%" goto SET_SYSTEM_JAVA
echo JAVA_HOME is not set, unexpected results may occur.
echo Set JAVA_HOME to the directory of your local JDK to avoid this message.
goto SET_SYSTEM_JAVA
:SET_BUNDLED_JAVA
set JAVA=%SOAPUI_HOME%..\jre\bin\java
goto END_SETTING_JAVA
:SET_SYSTEM_JAVA
set JAVA=java
:END_SETTING_JAVA
rem init classpath
set OLDDIR=%CD%
cd /d %SOAPUI_HOME%
set CLASSPATH=%SOAPUI_HOME%soapui-5.3.0.jar;%SOAPUI_HOME%..\lib\*
"%JAVA%" -cp "%CLASSPATH%" com.eviware.soapui.tools.JfxrtLocator > %TEMP%\jfxrtpath
set /P JFXRTPATH= < %TEMP%\jfxrtpath
del %TEMP%\jfxrtpath
set CLASSPATH=%CLASSPATH%;%JFXRTPATH%
rem JVM parameters, modify as appropriate
set JAVA_OPTS=-Xms128m -Xmx1024m -XX:MinHeapFreeRatio=20 -XX:MaxHeapFreeRatio=40 -Dsoapui.properties=soapui.properties "-Dsoapui.home=%SOAPUI_HOME%\" -splash:SoapUI-Spashscreen.png
if "%SOAPUI_HOME%" == "" goto START
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.libraries="%SOAPUI_HOME%ext"
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.listeners="%SOAPUI_HOME%listeners"
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.actions="%SOAPUI_HOME%actions"
    set JAVA_OPTS=%JAVA_OPTS% -Djava.library.path="%SOAPUI_HOME%\"
    set JAVA_OPTS=%JAVA_OPTS% -Dwsi.dir="%SOAPUI_HOME%..\wsi-test-tools"
rem uncomment to disable browser component
rem    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.browser.disabled="true"
:START
rem ********* run soapui ***********
"%JAVA%" %JAVA_OPTS% com.eviware.soapui.SoapUI %*
cd /d %OLDDIR%
</code>```

The path variable is as follows:

```<code>G:......;E:\Learning\JAVA\jdk1.8\bin
</code>```

Please help.

答:
You need to uninstall the old version of SoapUI.

And please check the latest version 5.4.0 of soapUI from here.

I faced the same issue and solved by trying with the latest version which is working with Java 1.8.

Hope this will help you !!

Body:
I am trying to execute a Groovy Script in SoapUI 5.3.0 which imports a jar file compiled in JDK 1.8. However, since SoapUI 5.3.0 is using 1.7; I am getting an exception "Unsupported major.minor version 52.0".

I have tried to follow the below link, but was not able to solve it.

https://chat.stackoverflow.com/rooms/127289/discussion-between-rao-and-user5653362

I understand I need to modify soapui.bat in C:\Program Files\SmartBear\SoapUI-5.3.0/bin folder; so SoapUI starts using Java 1.8; but not exactly sure which property to change.

My soaupui.bat looks like below:

*

@echo off
set SOAPUI_HOME=%~dp0
if exist "%SOAPUI_HOME%..\jre\bin" goto SET_BUNDLED_JAVA
if exist "%JAVA_HOME%" goto SET_SYSTEM_JAVA
echo JAVA_HOME is not set, unexpected results may occur.
echo Set JAVA_HOME to the directory of your local JDK to avoid this message.
goto SET_SYSTEM_JAVA
:SET_BUNDLED_JAVA
set JAVA=%SOAPUI_HOME%..\jre\bin\java
goto END_SETTING_JAVA
:SET_SYSTEM_JAVA
set JAVA=java
:END_SETTING_JAVA
rem init classpath
set OLDDIR=%CD%
cd /d %SOAPUI_HOME%
set CLASSPATH=%SOAPUI_HOME%soapui-5.3.0.jar;%SOAPUI_HOME%..\lib\*
"%JAVA%" -cp "%CLASSPATH%" com.eviware.soapui.tools.JfxrtLocator > %TEMP%\jfxrtpath
set /P JFXRTPATH= < %TEMP%\jfxrtpath
del %TEMP%\jfxrtpath
set CLASSPATH=%CLASSPATH%;%JFXRTPATH%
rem JVM parameters, modify as appropriate
set JAVA_OPTS=-Xms128m -Xmx1024m -XX:MinHeapFreeRatio=20 -XX:MaxHeapFreeRatio=40 -Dsoapui.properties=soapui.properties "-Dsoapui.home=%SOAPUI_HOME%\" -splash:SoapUI-Spashscreen.png
if "%SOAPUI_HOME%" == "" goto START
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.libraries="%SOAPUI_HOME%ext"
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.listeners="%SOAPUI_HOME%listeners"
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.actions="%SOAPUI_HOME%actions"
    set JAVA_OPTS=%JAVA_OPTS% -Djava.library.path="%SOAPUI_HOME%\"
    set JAVA_OPTS=%JAVA_OPTS% -Dwsi.dir="%SOAPUI_HOME%..\wsi-test-tools"
rem uncomment to disable browser component
rem    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.browser.disabled="true"
:START
rem ********* run soapui ***********
"%JAVA%" %JAVA_OPTS% com.eviware.soapui.SoapUI %*
cd /d %OLDDIR%

The path variable is as follows:

G:......;E:\Learning\JAVA\jdk1.8\bin

Please help.


问:
CreateTransportFailure with PortSip
I am trying to create a basic calling app on Android with PortSip but get an error from the setUser method (error -60098: CreateTransportFailure).  I think I've followed all the steps as their sample app, and I've used the same credentials that work with the sample app.  I've tried using a different local port (as suggested in another post), but haven't had any success.  These are my steps:</p>

```<code>context = this.getApplicationContext();
callingSDK = new PortSipSdk();
callingSDK.setOnPortSIPEvent(this);
callingSDK.CreateCallManager(context);

int initStatus = callingSDK.initialize(PortSipEnumDefine.ENUM_TRANSPORT_UDP,
      "0.0.0.0", 5771, PortSipEnumDefine.ENUM_LOG_LEVEL_DEBUG, LogPath, 200,
      "PortSIP VoIP Calling App", 0, 0, "", "", false);
// initialize returns ECoreErrorNone

callingSDK.setSrtpPolicy(PortSipEnumDefine.ENUM_SRTPPOLICY_NONE);

int licenseStatus = callingSDK.setLicenseKey("PORTSIP_TEST_LICENSE");
// setLicenseKey return ECoreTrialVersionLicenseKey, as expected

int userStatus = callingSDK.setUser(accountName, displayName, authName, password,
      domain, server, 5060, "", 0, null, 5060);
</code>```

答:
Apparently, another factor in this error condition is assuring the app that the appropriate permissions.  Adding these to the manifest gets past the issue with setUser.</p>

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
</code>```

Title: CreateTransportFailure with PortSip

Body:
I am trying to create a basic calling app on Android with PortSip but get an error from the setUser method (error -60098: CreateTransportFailure).  I think I've followed all the steps as their sample app, and I've used the same credentials that work with the sample app.  I've tried using a different local port (as suggested in another post), but haven't had any success.  These are my steps:

context = this.getApplicationContext();
callingSDK = new PortSipSdk();
callingSDK.setOnPortSIPEvent(this);
callingSDK.CreateCallManager(context);

int initStatus = callingSDK.initialize(PortSipEnumDefine.ENUM_TRANSPORT_UDP,
      "0.0.0.0", 5771, PortSipEnumDefine.ENUM_LOG_LEVEL_DEBUG, LogPath, 200,
      "PortSIP VoIP Calling App", 0, 0, "", "", false);
// initialize returns ECoreErrorNone

callingSDK.setSrtpPolicy(PortSipEnumDefine.ENUM_SRTPPOLICY_NONE);

int licenseStatus = callingSDK.setLicenseKey("PORTSIP_TEST_LICENSE");
// setLicenseKey return ECoreTrialVersionLicenseKey, as expected

int userStatus = callingSDK.setUser(accountName, displayName, authName, password,
      domain, server, 5060, "", 0, null, 5060);

Body:
Apparently, another factor in this error condition is assuring the app that the appropriate permissions.  Adding these to the manifest gets past the issue with setUser.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />


问:
Is there way to select only id from parentReference
Request

GET /drive/root/children?select=name,size,parentReference

returns, for parentReference, for example,

"parentReference:{

"driveId":"3e2dd398785a81d",

"id":"3E2DD398785A81D!103",

"path":"/drive/root:"

}

Is there way that parentReference in reponse contains only id:

"parentReference:{

"id":"3E2DD398785A81D!103",

}

答: Ideally you should be able to ?select=name,size,parentReference/id but that currently doesn't work (it'll behave like ?select=name,size,parentReference). We aim to fix that at some point though, and so you're more than welcome to use the former syntax and it should start working when we fix it. Until then you'll just get back some extra things you don't actually care about.


问:
What server does ng serve use when using Angular CLI 1.6.0?
What server does this Angular CLI command use, when using Angular CLI 1.6.0?

```<code>ng serve
</code>```

Since webpack is now being used by the Angular CLI for the website bundling, does that mean ng-serve is using the webpack-dev-server (which is a Node.js Express server)? There is some indication in the following Q/A that ng serve possibly used to piggyback off a server used by Ember:

What happens when you run ng serve?

答:
Yup, its using webpack-dev-server. You can look at the source-code of the ng eject command:

https://github.com/angular/angular-cli/blob/6449a753641340d8fc19a752e1a1ced75f974efa/docs/documentation/1-x/eject.md

Body:
What server does this Angular CLI command use, when using Angular CLI 1.6.0?

ng serve

Since webpack is now being used by the Angular CLI for the website bundling, does that mean ng-serve is using the webpack-dev-server (which is a Node.js Express server)? There is some indication in the following Q/A that ng serve possibly used to piggyback off a server used by Ember:

What happens when you run ng serve?


问:
Getting nodes without edges
I have a ton of nodes in a graph, and with some filters I am able to remove some edges by some condition, using cy.remove(myCollection).

It happens sometimes that all edges to a node is removed and therefore its sitting alone without edges. Is there any way in Cytoscape to find these nodes without edges?

I was out in something like:

```<code>cy.nodes(/*:inside*/).filter(node => node.connectedEdges().size() === 0)
</code>```

But this returns an empty collection?

答:
A solution to this (so far) is that instead of manipulating whats inside the graph, I will do the filtering by setting an data property on the node/edge and style with display: "none" using the data property as a condition. Then this is working:

```<code>const nodesWithoutEdges = cy.nodes().filter(node => node.connectedEdges(":visible").size() === 0)
</code>```

Title: Getting nodes without edges

Body:
I have a ton of nodes in a graph, and with some filters I am able to remove some edges by some condition, using cy.remove(myCollection).

It happens sometimes that all edges to a node is removed and therefore its sitting alone without edges. Is there any way in Cytoscape to find these nodes without edges?

I was out in something like:

cy.nodes(/*:inside*/).filter(node => node.connectedEdges().size() === 0)

But this returns an empty collection?

Body:
A solution to this (so far) is that instead of manipulating whats inside the graph, I will do the filtering by setting an data property on the node/edge and style with display: "none" using the data property as a condition. Then this is working:

const nodesWithoutEdges = cy.nodes().filter(node => node.connectedEdges(":visible").size() === 0)


问:
C# How to get the Coordinates of a specific Point on Screen. (not mouselocation)
I have the following problem:
I'm writing a WinForms application with C# and i want to get the Screen - Coordinates of a part of a picture, in this case the top of this hand (marked by the red point).

Does anybody know how i can do this programmaticaly?

("Koordinaten dieses Punktes" = Coordinates of this Point)

EDIT:
sry for confusing you, the picture above should only demonstrate my problem. The actual target of my program is to move the mouse-controlled-hand of a dart game to the right position, but it isn't possible by only setting the MouseLocation to a fix Point, because every turn the dart-hand gets another x:y distance to the MouseLocation. So I need to find the Location of the dart (-arrow).

I hope that everybody knows what my problem is now.

Picture of the dart game

答:
In some event of the form use: </p>

```<code>this.PointToScreen(new System.Drawing.Point(250, 300));
</code>```

<p>Replace the Point by the point (relative to the form) you are interested in. </p>

Body:
In some event of the form use:

this.PointToScreen(new System.Drawing.Point(250, 300));

Replace the Point by the point (relative to the form) you are interested in.


问:
c# - Ignore exception on client side when server is down
I use RestSharp to pass data between the clien-side (Xamarin android app) and my server.

When there is an error (usually because the server is down) the method that execute the request throw an exception.

I want the exception to go back all the way to the method who called it, so I can throw an error to the user.

For example, I want to login, but lets say the server is down.

A - The method that execute the request

```<code>public Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient
    {
        BaseUrl = new Uri(BaseUrl),
        Authenticator = new HttpBasicAuthenticator(_accountName, _password)
    };

    var taskCompletionSource = new TaskCompletionSource<T>();
    client.ExecuteAsync<T>(request, restResponse =>
    {
        if (restResponse.ErrorException != null)
        {
            throw (new Exception("Server returned an error"));
        }
        taskCompletionSource.SetResult(restResponse.Data);
    });
    return taskCompletionSource.Task;
}
</code>```

B - Method that uses method A to execute a request

```<code>public static async Task<LoginObject> Login(string accessNumber, string password, string token)
{
    var request = new RestRequest
    {
        Method = Method.POST,
        Resource = "Login"
    };
    request.AddJsonBody(
        new
        {
            accessNumber = accessNumber,
            password = password,
            token = token
        });

    var isDone = await Api.ExecuteAsync<LoginObject>(request);
    return isDone;
}
</code>```

C - The method where I want to handle the exception

```<code>public async Task Login(string PhoneNumber, string Password)
{
    try
    {
        LoginObject login = await LoginServices.Login(PhoneNumber, Password, Token);
        if (login.IsOk)
        {
            // Move to next activity
        }
        else
        {
        Toast.MakeText(this, "Login Error", ToastLength.Short).Show();
        }
    }
    catch (Exception ex) // Here I want to throw the server error
    {
        Toast.MakeText(this, "Server Error", ToastLength.Short).Show();
        return null;
    }
}
</code>```

Now when I run the code, the error is being thrown in A, and the app crash,

I want it to go from A to B and from B to C, and then I'll show an error to the user.

Edit: I tried to put a try/catch block but it still throws the exception in A.

答:
In your A-method, please use taskCompletionSource.SetException like this:

```<code>if (restResponse.ErrorException != null)
 {
   //throw new Exception("Server returned an error");
    taskCompletionSource.SetException(new Exception("Server returned an error"));
 }
 else
 {
    taskCompletionSource.SetResult(restResponse.Data);
 }
</code>```

In your B-method replace this line:

```<code>var isDone = await Api.ExecuteAsync<LoginObject>(request);
</code>```

with this to re-throw the exception to you C-method:

```<code>LoginObject isDone=null;
try
{
  isDone = await Api.ExecuteAsync<LoginObject>(request);
}
catch (Exception e)
{
   throw e;
}
</code>```

This article is talking about TaskCompletionSource

Body:
I use RestSharp to pass data between the clien-side (Xamarin android app) and my server.

When there is an error (usually because the server is down) the method that execute the request throw an exception.

I want the exception to go back all the way to the method who called it, so I can throw an error to the user.

For example, I want to login, but lets say the server is down.

A - The method that execute the request

public Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient
    {
        BaseUrl = new Uri(BaseUrl),
        Authenticator = new HttpBasicAuthenticator(_accountName, _password)
    };

    var taskCompletionSource = new TaskCompletionSource<T>();
    client.ExecuteAsync<T>(request, restResponse =>
    {
        if (restResponse.ErrorException != null)
        {
            throw (new Exception("Server returned an error"));
        }
        taskCompletionSource.SetResult(restResponse.Data);
    });
    return taskCompletionSource.Task;
}

B - Method that uses method A to execute a request

public static async Task<LoginObject> Login(string accessNumber, string password, string token)
{
    var request = new RestRequest
    {
        Method = Method.POST,
        Resource = "Login"
    };
    request.AddJsonBody(
        new
        {
            accessNumber = accessNumber,
            password = password,
            token = token
        });

    var isDone = await Api.ExecuteAsync<LoginObject>(request);
    return isDone;
}

C - The method where I want to handle the exception

public async Task Login(string PhoneNumber, string Password)
{
    try
    {
        LoginObject login = await LoginServices.Login(PhoneNumber, Password, Token);
        if (login.IsOk)
        {
            // Move to next activity
        }
        else
        {
        Toast.MakeText(this, "Login Error", ToastLength.Short).Show();
        }
    }
    catch (Exception ex) // Here I want to throw the server error
    {
        Toast.MakeText(this, "Server Error", ToastLength.Short).Show();
        return null;
    }
}

Now when I run the code, the error is being thrown in A, and the app crash,

I want it to go from A to B and from B to C, and then I'll show an error to the user.

Edit: I tried to put a try/catch block but it still throws the exception in A.

Body:
In your A-method, please use taskCompletionSource.SetException like this:

if (restResponse.ErrorException != null)
 {
   //throw new Exception("Server returned an error");
    taskCompletionSource.SetException(new Exception("Server returned an error"));
 }
 else
 {
    taskCompletionSource.SetResult(restResponse.Data);
 }

In your B-method replace this line:

var isDone = await Api.ExecuteAsync<LoginObject>(request);

with this to re-throw the exception to you C-method:

LoginObject isDone=null;
try
{
  isDone = await Api.ExecuteAsync<LoginObject>(request);
}
catch (Exception e)
{
   throw e;
}

This article is talking about TaskCompletionSource


问:
Displaying data from SQLite database incrementally
I want to be able to display values from my SQL database five at a time and then on button click be able to display the next five until I have display all of the courses. Right now this is how I am trying to display them: </p>

```<code> <%= form_for(Stc.new, action:'stcs#create') do |form| %>

 <%= collection_check_boxes(:course_id, Course.all, :id, :title,{}) do
 |form| %>

 form.label { form.check_box }

 <% end %>
 <%= form.collection_select(:course_id, Course.all,:id, :title, {}, {
 :multiple => false}) %>

 <%= form.select(:semester, options_for_select([['Fall', 'Fall'],
 ['Spring', 'Spring'],['Summer', 'Summer']]), :id => 'sel1') %>

 <%= form.select(:year, options_for_select([['2012', '2012'], ['2013',
'2013'], ['2014', '2014'], ['2015', '2015'], ['2016', '2016'], ['2017',
'2017']]), :id => 'sel2') %>

<%= form.select(:user_id, options_for_select([[1,@user.id]])) %>
<div class="actions">

 <form id="my_sample_form">

</form>

  <input type="submit" value="Submit" form="my_sample_form">

   <% end %>

 </div>
</code>```

答:
You can try Kaminari gem for pagination.Refer this:

https://github.com/kaminari/kaminari

Body:
I want to be able to display values from my SQL database five at a time and then on button click be able to display the next five until I have display all of the courses. Right now this is how I am trying to display them:

 <%= form_for(Stc.new, action:'stcs#create') do |form| %>

 <%= collection_check_boxes(:course_id, Course.all, :id, :title,{}) do
 |form| %>

 form.label { form.check_box }

 <% end %>
 <%= form.collection_select(:course_id, Course.all,:id, :title, {}, {
 :multiple => false}) %>

 <%= form.select(:semester, options_for_select([['Fall', 'Fall'],
 ['Spring', 'Spring'],['Summer', 'Summer']]), :id => 'sel1') %>

 <%= form.select(:year, options_for_select([['2012', '2012'], ['2013',
'2013'], ['2014', '2014'], ['2015', '2015'], ['2016', '2016'], ['2017',
'2017']]), :id => 'sel2') %>

<%= form.select(:user_id, options_for_select([[1,@user.id]])) %>

 <form id="my_sample_form">

</form>

  <input type="submit" value="Submit" form="my_sample_form">

   <% end %>


问:
How to get a specific json key value from post request response in Android?
I have following response from post request using HttpURLConnection:

Post Request Response:

```<code>{
    "LatestData": [{
        "ExtraData": null,
        "ID": 0,
        "season": false,
        "latest": 0,
        "url": "http://www.awebsite.com/images/12.jpg"
    }]
}
</code>```

How to get value of URL? I tried following but Android Studio keeps giving me error:

```<code>String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
</code>```

Android Studio Error:

```<code>error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)
</code>```

could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks

android code:

```<code> if (myURLConnection.getResponseCode() == 200) {
                br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
                while (true) {
                    line = br.readLine();
                    if (line != null) {
                        sb.append(line + "\n");

                        //String newURL = sb.getJSONObject("LatestData").getString("url");
                        String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
                        mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
                    } else {
                        br.close();
                        return sb.toString();
                    }
                }
            }
</code>```

答:
```<code>try {
            JSONObject jsonObject = new JSONObject(sb);
            String url = jsonObject.optJSONArray("LatestData").getJSONObject(0).optString("url");
        } catch (JSONException e) {
            e.printStackTrace();
        }
</code>```

Body:
I have following response from post request using HttpURLConnection:

Post Request Response:

{
    "LatestData": [{
        "ExtraData": null,
        "ID": 0,
        "season": false,
        "latest": 0,
        "url": "http://www.awebsite.com/images/12.jpg"
    }]
}

How to get value of URL? I tried following but Android Studio keeps giving me error:

String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");

Android Studio Error:

error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)

could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks

android code:

 if (myURLConnection.getResponseCode() == 200) {
                br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
                while (true) {
                    line = br.readLine();
                    if (line != null) {
                        sb.append(line + "\n");

                        //String newURL = sb.getJSONObject("LatestData").getString("url");
                        String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
                        mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
                    } else {
                        br.close();
                        return sb.toString();
                    }
                }
            }


答:
You need to convert sb to a JSONObject to access properties:

```<code>JSONOjbect jsonResponse = new JSONObject(new String(sb));
</code>```

and then:

```<code>try {
    JSONArray jsonArray = jsonResponse.getJSONArray("LatestData");
    if (jsonArray != null && jsonArray.length() > 0) {
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject dataOjbect = jsonArray.getJSONObject(i);
            String url = dataOjbect.getString("url");
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Title: How to get a specific json key value from post request response in Android?

Body:
You need to convert sb to a JSONObject to access properties:

JSONOjbect jsonResponse = new JSONObject(new String(sb));

and then:

try {
    JSONArray jsonArray = jsonResponse.getJSONArray("LatestData");
    if (jsonArray != null && jsonArray.length() > 0) {
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject dataOjbect = jsonArray.getJSONObject(i);
            String url = dataOjbect.getString("url");
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}


问:
How to handle form submission vuejs

I created a form that is supposed to get onSubmit into a database (or get it someplace so we can use the data). I tried connecting my VueJS app with Firebase, to get it inserted on the Database, however I can't accomplish it.

My form

```<code><div class="form-group">
            <label for="billing-first-name">First Name</label>
            <input type="text" class="form-control" id="billing-first-name" v-model="checkoutData.personal.first_name" required>
 </div>
</code>```

My

答:
The normal method is to use a third party library to post stuff.  Axios comes with the usual high recommendations for being easy to use and really light weight.

Check out https://alligator.io/vuejs/rest-api-axios/

Title: How to handle form submission vuejs

Body:
I created a form that is supposed to get onSubmit into a database (or get it someplace so we can use the data). I tried connecting my VueJS app with Firebase, to get it inserted on the Database, however I can't accomplish it.

My form

            First Name
            <input type="text" class="form-control" id="billing-first-name" v-model="checkoutData.personal.first_name" required>

My


问:
how to Transpose NSData in objective-c?
I have a NSString which i have to convert into NSData. After converting into NSData, I need to transpose the NSData in objective-c.
How do i transpose NSData in objective -c ?

Thanks

答:
It seems you wish to reverse the order of the bytes, here is an outline algorithm:

Use NSData's length to get the number of bytes

Allocate a C-array of type Byte to hold the bytes. Use one of the malloc() family.

Use getBytes:length: to get a copy of the bytes

Set a C Byte * variable, say frontPtr, to point at the first byte; set another, say rearPtr to point at the last byte.

Now iterate, exchanging the bytes referenced by the two pointers, then increment frontPtr, decrement rearPtr, and keep iterating while rearPtr > frontPtr.

Create a new NSData from the working buffer using NSData's + dataWithBytesNoCopy:length:freeWhenDone: passing YES as the last argument - this will take ownership of the malloc'ed buffer so there is no need for you to free it.

The algorithm simply moves two pointers from the ends of the buffer towards the middle exchanging bytes as it goes. The termination condition make it work for even and odd lengths (in the latter case the middle byte doesn't need to be swapped).

If one the other hand you didn't wish to reverse the order of the bytes, but instead reverse the order of bits in each byte Google "C bit reverse" and follow the same general structure as the above algorithm but do bit reversing in the loop.

If after coding the above you have a problem ask a new question, include your code, and explain your issue. Someone will undoubtedly help you.

HTH

Title: how to Transpose NSData in objective-c?


问:
Accessing the result of a returned promise
I'm trying to understand promises better and have implemented code that basically looks like this:

console.log(getRemoteData())

function getRemoteData (){
  return fetch('http://w.x.y.z')
  .then(response => {
    return response.json();
  });
}```

Assuming that getRemoteData() returns a promise, how do I access the value of that response? I've tried to resolve the promise before logging to the console and I can't get it to do anything but log the promise obj. I think I'm missing a fundamental component of how promises work.

I've tried searching SO and all the answers I find point to a //do something with the returned data comment in the .then() method but I'd like to learn what I should do from there. The returned value is an array[].

答:
Or use co if you are still on ES2015</p>

```<code>var co = require('co');

co(function *(){
    // yield any promise
    var result = yield getRemoteData();
}).catch(onerror);
</code>```

Body:
I'm trying to understand promises better and have implemented code that basically looks like this:

console.log(getRemoteData())

function getRemoteData (){
  return fetch('http://w.x.y.z')
  .then(response => {
    return response.json();
  });
}

Assuming that getRemoteData() returns a promise, how do I access the value of that response? I've tried to resolve the promise before logging to the console and I can't get it to do anything but log the promise obj. I think I'm missing a fundamental component of how promises work.

I've tried searching SO and all the answers I find point to a //do something with the returned data comment in the .then() method but I'd like to learn what I should do from there. The returned value is an array[].

Body:
Or use co if you are still on ES2015

var co = require('co');

co(function *(){
    // yield any promise
    var result = yield getRemoteData();
}).catch(onerror);


问:
Date is not defined error in angularjs

I am trying to print a date and time in my page with values coming from an Sql Server. The format of the date that is returned is like so:

```<code>/Date(1510563600000)/
</code>```

angular

```<code>$filter('date')(date, format, timezone)

$scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) {
    var obj = { "userId": userId, "projectId": projectId }
    $http.post('/Admin/GetTimelineByUserIdAndProjectId', obj)
    .then(function (response) {
        $scope.userTimeline = response.data;
    })
}
</code>```

html

```<code><ul class="timeline timeline-inverse" ng-repeat="u in userTimeline">
<li class="time-label">
    <span class="bg-red">
        {{u.StartDateTime | date:'medium'}}
    </span>
</li>
<li>
    <i class="fa fa-clock-o bg-gray"></i>
</li>
</code>```

I want the date format to be day/month/year hour:minutes.

When I run this program, I got the $filter is not defined so I place it in my controller like this:

```<code>var app = angular.module('adminApp', []);
app.controller('adminController', function ($scope, $http, $filter) {
</code>```

but it then gives me an error of angular.js:14642 ReferenceError: date is not defined

答:
I assume you are getting date like1510563600000 if you are getting like /Date(1510563600000)/ then you have to simple convert this string to date in filter using javascript

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.varDate='1510563600000';
});

myApp.filter('date',function(){
return function(date,format){
var d=new Date(parseInt(date));
return d.getDate()+'/'+d.getMonth()+'/'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes()
}

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
{{varDate | date}}
</div></code>```

Title: Date is not defined error in angularjs

Body:
I am trying to print a date and time in my page with values coming from an Sql Server. The format of the date that is returned is like so:

/Date(1510563600000)/

angular

$filter('date')(date, format, timezone)

$scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) {
    var obj = { "userId": userId, "projectId": projectId }
    $http.post('/Admin/GetTimelineByUserIdAndProjectId', obj)
    .then(function (response) {
        $scope.userTimeline = response.data;
    })
}

html

        {{u.StartDateTime | date:'medium'}}

I want the date format to be day/month/year hour:minutes.

When I run this program, I got the $filter is not defined so I place it in my controller like this:

var app = angular.module('adminApp', []);
app.controller('adminController', function ($scope, $http, $filter) {

but it then gives me an error of angular.js:14642 ReferenceError: date is not defined

Body:
I assume you are getting date like1510563600000 if you are getting like /Date(1510563600000)/ then you have to simple convert this string to date in filter using javascript

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.varDate='1510563600000';
});

myApp.filter('date',function(){
return function(date,format){
var d=new Date(parseInt(date));
return d.getDate()+'/'+d.getMonth()+'/'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes()
}

})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
{{varDate | date}}
</div>


问:
How to compare two array and alert the result?
I have two simple arrays:

```<code>var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.
</code>```

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

```<code>arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)
</code>```

I use $.each but it's only check the array. Not comparing them.

```<code>$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});
</code>```

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)

答:
You can find the array of missing items like below:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
var missing = arr_must_exist.filter(e => arr_created.indexOf(e) < 0);

console.log(missing);```

Body:
I have two simple arrays:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)

I use $.each but it's only check the array. Not comparing them.

$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)


问:
Find the file name in specific directory
```<code>import os, re
fileregex = re.compile(r"b(\D)+v.txt")
os.chdir("F:\\")
for file in os.listdir("."):
     mo = fileregex.search(file)
     print(mo.group())
</code>```

It is keep giving me "NonType" Error. I just want to find a file which starts from letter 'b' and ends with 'c'. File name is: brgv.txt and it is located in "Local Dish: F".

What am I doing wrong?

答:
You don't need to use regex in this case. str.endswith is enough.

```<code>if filename.endswith('.txt'):
    filename = filename[:-4]
    if filename[0] == 'b' and filename[-1] == 'v':
        pass # do your work
</code>```

Body:
import os, re
fileregex = re.compile(r"b(\D)+v.txt")
os.chdir("F:\\")
for file in os.listdir("."):
     mo = fileregex.search(file)
     print(mo.group())

It is keep giving me "NonType" Error. I just want to find a file which starts from letter 'b' and ends with 'c'. File name is: brgv.txt and it is located in "Local Dish: F".

What am I doing wrong?

Body:
You don't need to use regex in this case. str.endswith is enough.

if filename.endswith('.txt'):
    filename = filename[:-4]
    if filename[0] == 'b' and filename[-1] == 'v':
        pass # do your work