问:
RxJava2 Flowable.combineLatest behavior if all Flowables don't emit
I am following this code to do some error validation. Here's the combineLatest implementation which accepts inputs from 3 fields and does error validation on each of them.

```<code>Flowable.combineLatest(
            _emailChangeObservable,
            _passwordChangeObservable,
            _numberChangeObservable,
            (newEmail, newPassword, newNumber) -> {
              boolean emailValid = !isEmpty(newEmail) && EMAIL_ADDRESS.matcher(newEmail).matches();
              if (!emailValid) {
                _email.setError("Invalid Email!");
              }

              boolean passValid = !isEmpty(newPassword) && newPassword.length() > 8;
              if (!passValid) {
                _password.setError("Invalid Password!");
              }

              boolean numValid = !isEmpty(newNumber);
              if (numValid) {
                int num = Integer.parseInt(newNumber.toString());
                numValid = num > 0 && num <= 100;
              }
              if (!numValid) {
                _number.setError("Invalid Number!");
              }

              return emailValid && passValid && numValid;
            })
        .subscribe(_disposableObserver);
</code>```

My problem is that the combiner function is not triggered unless all 3 input field observables have emitted at least once. So when users enter an incorrect email address, they are not notified until they have entered some data in all the 3 fields.

答:
combineLatest() must have all values for starting emitting something, as by definition the combiner function gets n values that emitted from n sources.

When RxBInding wraps TextView events with RxTextView, it emits an initial value (contents of the TextView) when subscribed, so without the skip(1), you will have your desired logic, the thing is the validation logic in this sample do not expect that, and display error for empty values (by the !isEmpty(newXXX) checks).

My hunch based on the explicit skip(1) transformation is that in this example this is the desired behavior - meaning just when all fields has been entered we need to display errors.

In your case if you want to implement your logic, you need to skip empty values from displaying errors while still emit false at the end as the whole input is not yet valid, then - with any change at any fields independent of the others, while not empty you will the errors .

Body:
I am following this code to do some error validation. Here's the combineLatest implementation which accepts inputs from 3 fields and does error validation on each of them.

Flowable.combineLatest(
            _emailChangeObservable,
            _passwordChangeObservable,
            _numberChangeObservable,
            (newEmail, newPassword, newNumber) -> {
              boolean emailValid = !isEmpty(newEmail) && EMAIL_ADDRESS.matcher(newEmail).matches();
              if (!emailValid) {
                _email.setError("Invalid Email!");
              }

              boolean passValid = !isEmpty(newPassword) && newPassword.length() > 8;
              if (!passValid) {
                _password.setError("Invalid Password!");
              }

              boolean numValid = !isEmpty(newNumber);
              if (numValid) {
                int num = Integer.parseInt(newNumber.toString());
                numValid = num > 0 && num <= 100;
              }
              if (!numValid) {
                _number.setError("Invalid Number!");
              }

              return emailValid && passValid && numValid;
            })
        .subscribe(_disposableObserver);

My problem is that the combiner function is not triggered unless all 3 input field observables have emitted at least once. So when users enter an incorrect email address, they are not notified until they have entered some data in all the 3 fields.


来源: stackexchange

问:
Extract string between nth and ith instance of delimiter
I have a vector of strings, similar to this one, but with many more elements:

```<code>s <- c("CGA-DV-558_T_90.67.0_DV_1541_07", "TC-V-576_T_90.0_DV_151_0", "TCA-DV-X_T_6.0_D_A2_07", "T-V-Z_T_2_D_A_0", "CGA-DV-AW0_T.1_24.4.0_V_A6_7", "ACGA-DV-A4W0_T_274.46.0_DV_A266_07")
</code>```

And I would like to use a function that extracts the string between the nth and ith instances of the delimiter "_". For example, the string between the 2nd (n = 2) and 3rd (i = 3) instances, to get this:

```<code>[1] "90.67.0"  "90.0"     "6.0"      "2"        "24.4.0"   "274.46.0"
</code>```

Or if n = 4 and i = 5"

```<code>[1] "1541" "151"  "A2"   "A"    "A"    "A266"
</code>```

Any suggestions?

ContentLicense: CC BY-SA 4.0

Body:
I have a vector of strings, similar to this one, but with many more elements:

s <- c("CGA-DV-558_T_90.67.0_DV_1541_07", "TC-V-576_T_90.0_DV_151_0", "TCA-DV-X_T_6.0_D_A2_07", "T-V-Z_T_2_D_A_0", "CGA-DV-AW0_T.1_24.4.0_V_A6_7", "ACGA-DV-A4W0_T_274.46.0_DV_A266_07")

And I would like to use a function that extracts the string between the nth and ith instances of the delimiter "_". For example, the string between the 2nd (n = 2) and 3rd (i = 3) instances, to get this:

[1] "90.67.0"  "90.0"     "6.0"      "2"        "24.4.0"   "274.46.0"

Or if n = 4 and i = 5"

[1] "1541" "151"  "A2"   "A"    "A"    "A266"

Any suggestions?

Body:
You can do this with gsub

n = 2
i = 3

pattern1 = paste0("(.*?_){", n,  "}")
temp = gsub(pattern1, "", s)
pattern2 = paste0("((.*?_){", i-n,  "}).*")
temp = gsub(pattern2, "\\1", temp)
temp = gsub("_$", "", temp)
[1] "1541" "151"  "A2"   "A"    "A6"   "A266"

ContentLicense: CC BY-SA 3.0


问:
Xamarin iOS - PrepareForSegue compile error
I'm having issues when trying to implement PrepareForSegue ... it can't find a suitable method to override (and/or NSStoryboardSegue and NSObject) ... Thoughts on the following?

Do I need to add a "using" include statement or something similar?

答:
The right signature is:</p>

```<code>public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
    base.PrepareForSegue(segue, sender);
}
</code>```

Body:
The right signature is:

public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
    base.PrepareForSegue(segue, sender);
}


问:
Efficient way to produce facetted bar plots
Is there a way to produce facetted bar plots as rapidly as you can produce facetted box plots?

For instance this code will produce box plots facetted by a grouping variable:

```<code>library(tidyverse)

mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_boxplot() +
  facet_grid(~ cyl)
</code>```

But the "same" code for a bar plot fails because geom_col() expects to have means provided, which would take considerably more time to calculate:

```<code>mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_col() +
  facet_grid(~ cyl)
</code>```

If there is a way to produce facetted bar plots at the speed of facetted box plots, I'd love to hear your methods.

答:
Thank you to @hrbrmstr for your suggestion to use stat_summary(). That was the perfect solution.

```<code>mtcars %>%
  ggplot(aes(x = as.factor(am), y = mpg)) +
  stat_summary(fun.y = "mean", geom = "col") +
  facet_grid(~ cyl)
</code>```

Body:
Is there a way to produce facetted bar plots as rapidly as you can produce facetted box plots?

For instance this code will produce box plots facetted by a grouping variable:

library(tidyverse)

mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_boxplot() +
  facet_grid(~ cyl)

But the "same" code for a bar plot fails because geom_col() expects to have means provided, which would take considerably more time to calculate:

mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_col() +
  facet_grid(~ cyl)

If there is a way to produce facetted bar plots at the speed of facetted box plots, I'd love to hear your methods.

Body:
Thank you to @hrbrmstr for your suggestion to use stat_summary(). That was the perfect solution.

mtcars %>%
  ggplot(aes(x = as.factor(am), y = mpg)) +
  stat_summary(fun.y = "mean", geom = "col") +
  facet_grid(~ cyl)


问:
Knockout dropdown list empty
I've followed the very basic example here to populate a dropdown list on an mvc site.

My dropdownlist doesn't have any items in it, even though I appear to have done everything correctly - but obviously I haven't.

Here's my code:

```<code><p>
    Your country:
    <select data-bind="options: availableCountries,
                       optionsText: 'name',
                       value: selectedCountry,
                       optionsCaption: 'Choose...'"></select>

</p>
<div data-bind="visible: selectedCountry">
    <!-- Appears when you select something -->
    You have chosen a country:
    <span data-bind="text: selectedCountry() ? selectedCountry().name : 'unknown'"></span>.
</div>

@section scripts
{
    <script type="text/javascript">

        $(function () {

        });

        // Constructor for an object with two properties
        var Country = function (name, isocode) {
            this.name = name;
            this.isocode = isocode;
        };

        var viewModel = {
            availableCountries: ko.observableArray([
                new Country("UK", "isoUK"),
                new Country("USA", "isoUSA"),
                new Country("Sweden", "isoSweden")
            ]),
            selectedCountry: ko.observable() // Nothing selected by default
        };

    </script>

}
</code>```

I used F12 to check the countries were being created and they are - anyone see where I'm going wrong?

答:
You have not bound the view model to the view.

At the end of the script do this

```<code><script type="text/javascript">

    $(function () {

    });

    // Constructor for an object with two properties
    var Country = function (name, isocode) {
        this.name = name;
        this.isocode = isocode;
    };
    var selected = new Country("USA", "isoUSA");
    var viewModel = {
        availableCountries: ko.observableArray([
            new Country("UK", "isoUK"),
            selected,
            new Country("Sweden", "isoSweden")
        ]),
        selectedCountry: ko.observable(selected) // USA selected by default
    };
    //now bind the view model to the view
    ko.applyBindings(viewModel);
</script>
</code>```

Title: Knockout dropdown list empty

Body:
I've followed the very basic example here to populate a dropdown list on an mvc site.

My dropdownlist doesn't have any items in it, even though I appear to have done everything correctly - but obviously I haven't.

Here's my code:

    Your country:
    <select data-bind="options: availableCountries,
                       optionsText: 'name',
                       value: selectedCountry,
                       optionsCaption: 'Choose...'"></select>

    You have chosen a country:
    .

@section scripts
{

}

I used F12 to check the countries were being created and they are - anyone see where I'm going wrong?

Body:
You have not bound the view model to the view.

At the end of the script do this

<script type="text/javascript">

    $(function () {

    });

    // Constructor for an object with two properties
    var Country = function (name, isocode) {
        this.name = name;
        this.isocode = isocode;
    };
    var selected = new Country("USA", "isoUSA");
    var viewModel = {
        availableCountries: ko.observableArray([
            new Country("UK", "isoUK"),
            selected,
            new Country("Sweden", "isoSweden")
        ]),
        selectedCountry: ko.observable(selected) // USA selected by default
    };
    //now bind the view model to the view
    ko.applyBindings(viewModel);
</script>


问:
How to check of a column in a data frame equals a certain data type in Pandas?
I need to convert all my columns that are of the data type objects into strings.

For simplicity, here is the column headers:

```<code>keys= [Name, Age, Passport, Date, Location, Height]
</code>```

'Name' and 'Location' are of type object. I need to identify these columns are of type object, and convert the columns into strings.

My loop that I attempted to write:

```<code>while variable_1 < len(keys):
  if df[variable_1].dtypes == object:
    df[variable_1] = df[variable_1].astype(str)
    variable_1 = variable_1 + 1
</code>```

This is throwing an obvious error, I am sort of stuck on the syntax.

答:
why you are usingwhile ? rather than simply using for ?

```<code>for i in df.columns:
    if df[i].dtype==object:
        df[i]= df[i].astype(str)
</code>```

Body:
I need to convert all my columns that are of the data type objects into strings.

For simplicity, here is the column headers:

keys= [Name, Age, Passport, Date, Location, Height]

'Name' and 'Location' are of type object. I need to identify these columns are of type object, and convert the columns into strings.

My loop that I attempted to write:

while variable_1 < len(keys):
  if df[variable_1].dtypes == object:
    df[variable_1] = df[variable_1].astype(str)
    variable_1 = variable_1 + 1

This is throwing an obvious error, I am sort of stuck on the syntax.

Body:
why you are usingwhile ? rather than simply using for ?

for i in df.columns:
    if df[i].dtype==object:
        df[i]= df[i].astype(str)


答:
```<code>#FUNCTION
foo = function(x, n, i){
    do.call(c, lapply(x, function(X)
        paste(unlist(strsplit(X, "_"))[(n+1):(i)], collapse = "_")))
}

#USAGE
foo(x = s, n = 3, i = 5)
#[1] "DV_1541" "DV_151"  "D_A2"    "D_A"     "V_A6"    "DV_A266"
</code>```

Title: Extract string between nth and ith instance of delimiter


问:
Compile separate files
In the case to have three files:

```<code>File1
    >TAIR:175_a
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:175_b
     ZZZLAALSKDJFALKSDJFL;KJEIURALKDJFNVALKSDJFKZZZ
    >TAIR:175_c
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF

File2
    >TAIR:674_a
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:674_b
     ASLALKSDGHDJGDGSDDFIEURALKSDHGLANVALKSDJGHKLJA

File3
    >TAIR:812_a
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ
    >TAIR:812_c
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA

File4
    >TAIR:975_b
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ

File5
    >TAIR:444_b
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA
    >TAIR:444_c
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA
</code>```

I wrote this code to extract the name of all sequences in the directory:

```<code>#!/usr/bin/env python
from Bio import SeqIO
filenames = ["file1","file2","file3"]
ids = []

for record in filenames:
    f = SeqIO.parse(record, 'fasta')
    ids.append(f.id)

print ids
</code>```

And the output is this:

```<code> python search_list.py
[<generator object parse at 0x7f32836018c0>, <generator object parse at 0x7f3283601910>, <generator object parse at 0x7f3283601960>]
</code>```

And the output that I expect is:

```<code>file_a
    >TAIR:175_a
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:674_a
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA

file_b
    >TAIR:175_b
     ZZZLAALSKDJFALKSDJFL;KJEIURALKDJFNVALKSDJFKZZZ
    >TAIR:674_b
     ASLALKSDGHDJGDGSDDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:975_b
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ
    >TAIR:444_b
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA

file_c
    >TAIR:175_c
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:812_c
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:444_c
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA
</code>```

Any suggestion to solve this opening the files in the list "ids" and compile them?

答:
(Ignoring the print parentheses issue,) Your code breaks on my system (Python 3.6.0; Biopython 1.69) with:

```<code>AttributeError: 'generator' object has no attribute 'id'
</code>```

as SeqIO.parse() returns a generator.  Also your "output that I expect" is completely wrong.  What you're expecting, given this code, is:

```<code>['TAIR:175_a', 'TAIR:674_a', 'TAIR:812_a', 'TAIR:975_b', 'TAIR:175_b', 'TAIR:444_b', 'TAIR:175_c', 'TAIR:444_c']
</code>```

And in my environment, the following code will get it for you:

```<code>from Bio import SeqIO

filenames = ["file1.fasta", "file2.fasta", "file3.fasta"]

ids = []

for filename in filenames:
    records = SeqIO.parse(filename, 'fasta')

    for record in records:
        ids.append(record.id)

print(ids)
</code>```

Title: Compile separate files

Body:
In the case to have three files:

File1
    >TAIR:175_a
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:175_b
     ZZZLAALSKDJFALKSDJFL;KJEIURALKDJFNVALKSDJFKZZZ
    >TAIR:175_c
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF

File2
    >TAIR:674_a
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:674_b
     ASLALKSDGHDJGDGSDDFIEURALKSDHGLANVALKSDJGHKLJA

File3
    >TAIR:812_a
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ
    >TAIR:812_c
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA

File4
    >TAIR:975_b
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ

File5
    >TAIR:444_b
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA
    >TAIR:444_c
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA

I wrote this code to extract the name of all sequences in the directory:

#!/usr/bin/env python
from Bio import SeqIO
filenames = ["file1","file2","file3"]
ids = []

for record in filenames:
    f = SeqIO.parse(record, 'fasta')
    ids.append(f.id)

print ids

And the output is this:

 python search_list.py
[<generator object parse at 0x7f32836018c0>, <generator object parse at 0x7f3283601910>, <generator object parse at 0x7f3283601960>]

And the output that I expect is:

file_a
    >TAIR:175_a
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:674_a
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA

file_b
    >TAIR:175_b
     ZZZLAALSKDJFALKSDJFL;KJEIURALKDJFNVALKSDJFKZZZ
    >TAIR:674_b
     ASLALKSDGHDJGDGSDDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:975_b
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ
    >TAIR:444_b
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA

file_c
    >TAIR:175_c
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:812_c
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:444_c
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA

Any suggestion to solve this opening the files in the list "ids" and compile them?

Body:
(Ignoring the print parentheses issue,) Your code breaks on my system (Python 3.6.0; Biopython 1.69) with:

AttributeError: 'generator' object has no attribute 'id'

as SeqIO.parse() returns a generator.  Also your "output that I expect" is completely wrong.  What you're expecting, given this code, is:

['TAIR:175_a', 'TAIR:674_a', 'TAIR:812_a', 'TAIR:975_b', 'TAIR:175_b', 'TAIR:444_b', 'TAIR:175_c', 'TAIR:444_c']

And in my environment, the following code will get it for you:

from Bio import SeqIO

filenames = ["file1.fasta", "file2.fasta", "file3.fasta"]

ids = []

for filename in filenames:
    records = SeqIO.parse(filename, 'fasta')

    for record in records:
        ids.append(record.id)

print(ids)


问:
how to check if data exist in mysql database before enter
Table 1 is loaded with data as seen below, there is TABLE 2 which is empty but contain same structure as TABLE1 my problem is if i want to insert data inTABLE 2 i want to to check first in TABLE 1 if records to be entered in TABLE 2 have same name as NAME column from TABLE 1 if NAME are not same data should be ignored and not entered into database.

```<code> TABLE 1
 ST_ID   NAME          MATHS   GEOGRAPHY   ENGLISH
  1001   Alan Wegman    80       85          70
  1002   Robert Franko  79       65          60
  1003   Francis John   90       75          67
  1004   Finn Harry     88       87          93

  TABLE 2
  ST2_ID   NAME   MATHS   GEOGRAPHY   ENGLISH   ST_ID
</code>```

These are my codes so far, even if there is alternative way of doing what i want i will appreciate if you share with me.

```<code>`$query="insert into student_info (NAME, MATHS, GEOGRAPHY, ENGLISH)  VALUES ('$name','$maths','$geog','$english')";

 if (mysql_query($query))
 {
   echo "<b>";
   echo "<h3>";
   echo "RECORD ADDED ";
   echo "<h3>";
   echo "</b>";
 }
   else
 {
 echo "<b>";
 echo "<h3>";
 echo "RECORD NOT ENTERED SOMETHING WENT WRONG";
 echo "</h3>";
 echo "</b>";
 echo "<br>";
 echo mysql_error();
  }
 ?>
</code>```

`

NOTE:ST2_ID is auto increment

I need your thought guys.

答:
Or you can do this in your SQL by adding a WHERE condition on your insert statement.  Perhaps something like this:</p>

```<code> insert into student_info (
                           NAME
                         , MATHS
                         , GEOGRAPHY
                         , ENGLISH
                           )
 VALUES ('$name'
        ,'$maths'
        ,'$geog'
        ,'$english')"
 WHERE NOT EXIST (select *
                  from table2
                  where name = '$name');
</code>```

Body:
Table 1 is loaded with data as seen below, there is TABLE 2 which is empty but contain same structure as TABLE1 my problem is if i want to insert data inTABLE 2 i want to to check first in TABLE 1 if records to be entered in TABLE 2 have same name as NAME column from TABLE 1 if NAME are not same data should be ignored and not entered into database.

 TABLE 1
 ST_ID   NAME          MATHS   GEOGRAPHY   ENGLISH
  1001   Alan Wegman    80       85          70
  1002   Robert Franko  79       65          60
  1003   Francis John   90       75          67
  1004   Finn Harry     88       87          93

  TABLE 2
  ST2_ID   NAME   MATHS   GEOGRAPHY   ENGLISH   ST_ID

These are my codes so far, even if there is alternative way of doing what i want i will appreciate if you share with me.

`$query="insert into student_info (NAME, MATHS, GEOGRAPHY, ENGLISH)  VALUES ('$name','$maths','$geog','$english')";

 if (mysql_query($query))
 {
   echo "";
   echo "
";
   echo "RECORD ADDED ";
   echo "
";
   echo "";
 }
   else
 {
 echo "";
 echo "
";
 echo "RECORD NOT ENTERED SOMETHING WENT WRONG";
 echo "
";
 echo "";
 echo "
";
 echo mysql_error();
  }
 ?>

`

NOTE:ST2_ID is auto increment

I need your thought guys.

Body:
Or you can do this in your SQL by adding a WHERE condition on your insert statement.  Perhaps something like this:

 insert into student_info (
                           NAME
                         , MATHS
                         , GEOGRAPHY
                         , ENGLISH
                           )
 VALUES ('$name'
        ,'$maths'
        ,'$geog'
        ,'$english')"
 WHERE NOT EXIST (select *
                  from table2
                  where name = '$name');


问:
Convert Varchar to Ascii
I'm trying to convert the contents of a VARCHAR field to be unique number that can be easily referenced by a 3rd party.

How can I convert a varchar to the ascii string equivalent? In TSQL? The ASCII() function converts a single character but what can I do to convert an entire string?

I've tried using

```<code>CAST(ISNULL(ASCII(Substring(RTRIM(LTRIM(PrimaryContactRegion)),1,1)),'')AS VARCHAR(3))
+ CAST(ISNULL(ASCII(Substring(RTRIM(LTRIM(PrimaryContactRegion)),2,1)),'')AS VARCHAR(3))
</code>```

....but this is tedious, stupid looking, and just doesn't really work if I had long strings.  Or if it is better how would I do the same thing in SSRS?

答:
try something like this:

```<code>DECLARE @YourString   varchar(500)

SELECT @YourString='Hello World!'

;WITH AllNumbers AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<LEN(@YourString)
)
SELECT
       (SELECT
            ASCII(SUBSTRING(@YourString,Number,1))
            FROM AllNumbers
            ORDER BY Number
            FOR XML PATH(''), TYPE
       ).value('.','varchar(max)') AS NewValue
       --OPTION (MAXRECURSION 500) --<<needed if you have a string longer than 100
</code>```

OUTPUT:

```<code>NewValue
---------------------------------------
72101108108111328711111410810033

(1 row(s) affected)
</code>```

just to test it out:

```<code>;WITH AllNumbers AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<LEN(@YourString)
)
SELECT SUBSTRING(@YourString,Number,1),ASCII(SUBSTRING(@YourString,Number,1)),* FROM AllNumbers
</code>```

OUTPUT:

```<code>                 Number
---- ----------- -----------
H    72          1
e    101         2
l    108         3
l    108         4
o    111         5
     32          6
W    87          7
o    111         8
r    114         9
l    108         10
d    100         11
!    33          12

(12 row(s) affected)
</code>```

Also, you might want to use this:

```<code>RIGHT('000'+CONVERT(varchar(max),ASCII(SUBSTRING(@YourString,Number,1))),3)
</code>```

to force all ASCII values into 3 digits, I'm not sure if this is necessary based on your usage or not.

Output using 3 digits per character:

```<code>NewValue
-------------------------------------
072101108108111032087111114108100033

(1 row(s) affected)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Convert Varchar to Ascii

Body:
I'm trying to convert the contents of a VARCHAR field to be unique number that can be easily referenced by a 3rd party.

How can I convert a varchar to the ascii string equivalent? In TSQL? The ASCII() function converts a single character but what can I do to convert an entire string?

I've tried using

CAST(ISNULL(ASCII(Substring(RTRIM(LTRIM(PrimaryContactRegion)),1,1)),'')AS VARCHAR(3))
+ CAST(ISNULL(ASCII(Substring(RTRIM(LTRIM(PrimaryContactRegion)),2,1)),'')AS VARCHAR(3))

....but this is tedious, stupid looking, and just doesn't really work if I had long strings.  Or if it is better how would I do the same thing in SSRS?

Body:
try something like this:

DECLARE @YourString   varchar(500)

SELECT @YourString='Hello World!'

;WITH AllNumbers AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<LEN(@YourString)
)
SELECT
       (SELECT
            ASCII(SUBSTRING(@YourString,Number,1))
            FROM AllNumbers
            ORDER BY Number
            FOR XML PATH(''), TYPE
       ).value('.','varchar(max)') AS NewValue
       --OPTION (MAXRECURSION 500) --<<needed if you have a string longer than 100

OUTPUT:

NewValue
---------------------------------------
72101108108111328711111410810033

(1 row(s) affected)

just to test it out:

;WITH AllNumbers AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<LEN(@YourString)
)
SELECT SUBSTRING(@YourString,Number,1),ASCII(SUBSTRING(@YourString,Number,1)),* FROM AllNumbers

OUTPUT:

                 Number
---- ----------- -----------
H    72          1
e    101         2
l    108         3
l    108         4
o    111         5
     32          6
W    87          7
o    111         8
r    114         9
l    108         10
d    100         11
!    33          12

(12 row(s) affected)

Also, you might want to use this:

RIGHT('000'+CONVERT(varchar(max),ASCII(SUBSTRING(@YourString,Number,1))),3)

to force all ASCII values into 3 digits, I'm not sure if this is necessary based on your usage or not.

Output using 3 digits per character:

NewValue
-------------------------------------
072101108108111032087111114108100033

(1 row(s) affected)


问:
SQL - counts and sum for different values of count and name
I have a table with results from various tournaments (only showing the relevant fields for this case):

name, lugar, id, formato

I need to do a table giving different values according to the number of players and their result.

name is the tournament name, lugar the place the player got, id the player identifier and formato its a tournament specific field.

quick example:

for formato = X, lugar  = 1 => 8 points if the sum of ids for name > 32.

I was trying to do with count and cases, searched but didn't find a suitable answer.

Maybe i should do separate tables ?

at this moment i have this that works to sum the points, but doesn't check the # of players of the formato.

```<code>SELECT name, id, ROUND((sum(pontos)/((sum(rondas)+sum(byes))*3)*100),2) as Performance,
    sum(case
              when lugar = '1' then 8
              when lugar = '2' then 6
              when lugar > '2' AND  lugar < '5' then 4
              when lugar > '4' AND lugar < '9' then 2
              else null end)as Pontos
FROM players
WHERE season='0'
GROUP BY id
ORDER BY `Pontos` DESC, `Performance` DESC
</code>```

I've tried add an case with formato = 'X' then the sum but i got an sql error.

example populated table:

```<code>name    id  format  lugar
maio    1   STD 1
maio    2   STD 2
abril   1   STD 4
abril   3   STD 1
junho   1   MDR 5
junho   2   MDR 1
julho   3   MDR 2
julho   4   MDR 8
</code>```

expect result with conditions:
 if format = STD, when lugar =  1, gives 8 points, lugar = 2 gives 6 points.
if format = MDR, when lugar = 1, gives 5 points, lugar = 2 gives 3 points
and if count id where format = STD greater than 3 (just and example) 1 extra point

And if count id where format = STD (example) the points that are given according the lugar would give different points.

so, with that populated table it would give something like:

```<code>id  points  performance
1   17  50
2   10  40
3   4   60
4   1   40
</code>```

(didn't check values, just example of the expected result).

There were the kind of conditions i would wnat to implement.

答:
If I understand correctly, you are looking for a nested case when:

```<code>  SELECT
        name
        , id
        , ROUND((sum(pontos)/((sum(rondas)+sum(byes))*3)*100),2) as Performance,
        sum(  case when formato ='X' THEN
             (case
                when lugar = '1' then 8
                when lugar = '2' then 6
                when lugar > '2' AND  lugar < '5' then 4
                when lugar > '4' AND lugar < '9' then 2
                else null end)
                END
      ) as Pontos
  FROM players
  WHERE season='0'
  GROUP BY dci
  ORDER BY `Pontos` DESC, `Performance` DESC
</code>```

and you can use different case for formato

```<code>  SELECT
        name
        , id
        , ROUND((sum(pontos)/((sum(rondas)+sum(byes))*3)*100),2) as Performance,
        sum(  case
                when formato ='X' THEN
                 (case
                    when lugar = '1' then 8
                    when lugar = '2' then 6
                    when lugar > '2' AND  lugar < '5' then 4
                    when lugar > '4' AND lugar < '9' then 2
                    else null end)
                when formato = 'Y' THEN 100 END

                END
      ) as Pontos
  FROM players
  WHERE season='0'
  GROUP BY dci
  ORDER BY `Pontos` DESC, `Performance` DESC
</code>```

Body:
I have a table with results from various tournaments (only showing the relevant fields for this case):

name, lugar, id, formato

I need to do a table giving different values according to the number of players and their result.

name is the tournament name, lugar the place the player got, id the player identifier and formato its a tournament specific field.

quick example:

for formato = X, lugar  = 1 => 8 points if the sum of ids for name > 32.

I was trying to do with count and cases, searched but didn't find a suitable answer.

Maybe i should do separate tables ?

at this moment i have this that works to sum the points, but doesn't check the # of players of the formato.

SELECT name, id, ROUND((sum(pontos)/((sum(rondas)+sum(byes))*3)*100),2) as Performance,
    sum(case
              when lugar = '1' then 8
              when lugar = '2' then 6
              when lugar > '2' AND  lugar < '5' then 4
              when lugar > '4' AND lugar < '9' then 2
              else null end)as Pontos
FROM players
WHERE season='0'
GROUP BY id
ORDER BY `Pontos` DESC, `Performance` DESC

I've tried add an case with formato = 'X' then the sum but i got an sql error.

example populated table:

name    id  format  lugar
maio    1   STD 1
maio    2   STD 2
abril   1   STD 4
abril   3   STD 1
junho   1   MDR 5
junho   2   MDR 1
julho   3   MDR 2
julho   4   MDR 8

expect result with conditions:
 if format = STD, when lugar =  1, gives 8 points, lugar = 2 gives 6 points.
if format = MDR, when lugar = 1, gives 5 points, lugar = 2 gives 3 points
and if count id where format = STD greater than 3 (just and example) 1 extra point

And if count id where format = STD (example) the points that are given according the lugar would give different points.

so, with that populated table it would give something like:

id  points  performance
1   17  50
2   10  40
3   4   60
4   1   40

(didn't check values, just example of the expected result).

There were the kind of conditions i would wnat to implement.

Body:
If I understand correctly, you are looking for a nested case when:

  SELECT
        name
        , id
        , ROUND((sum(pontos)/((sum(rondas)+sum(byes))*3)*100),2) as Performance,
        sum(  case when formato ='X' THEN
             (case
                when lugar = '1' then 8
                when lugar = '2' then 6
                when lugar > '2' AND  lugar < '5' then 4
                when lugar > '4' AND lugar < '9' then 2
                else null end)
                END
      ) as Pontos
  FROM players
  WHERE season='0'
  GROUP BY dci
  ORDER BY `Pontos` DESC, `Performance` DESC

and you can use different case for formato

  SELECT
        name
        , id
        , ROUND((sum(pontos)/((sum(rondas)+sum(byes))*3)*100),2) as Performance,
        sum(  case
                when formato ='X' THEN
                 (case
                    when lugar = '1' then 8
                    when lugar = '2' then 6
                    when lugar > '2' AND  lugar < '5' then 4
                    when lugar > '4' AND lugar < '9' then 2
                    else null end)
                when formato = 'Y' THEN 100 END

                END
      ) as Pontos
  FROM players
  WHERE season='0'
  GROUP BY dci
  ORDER BY `Pontos` DESC, `Performance` DESC


问:
How to Create BQL Function for Math.Ceiling or any Math class methods in Acumatica
Looking for a Bql function to use Math Ceiling in a formula. Need help with this line in the larger example below.

```<code>graph.SqlDialect.scriptFunction(Math.Ceiling(Convert.ToDecimal()), text, this.getTypeCodeForOperand<Operand1>(graph), text1.ToString());
</code>```

Here is the full example I am working with.

```<code>public sealed class MathCeiling<Operand1> : BqlFunction, IBqlOperand, IBqlCreator
        where Operand1 : IBqlOperand
{
        private IBqlCreator a;

    public void Verify(PXCache cache, object item, List<object> pars, ref bool? result, ref object value)
    {
        value = (object)null;
        object obj1;
        if (!BqlFunction.getValue<Operand1>(ref this.a, cache, item, pars, ref result, out obj1) || obj1 == null)
            return;
        value = MathCeiling<Operand1>.calculateValue(obj1);
    }

    internal static object calculateValue(object value1)
    {
        return (object)(Math.Ceiling(Convert.ToDecimal(value1)));
    }

    public void Parse(PXGraph graph, List<IBqlParameter> pars, List<System.Type> tables, List<System.Type> fields, List<IBqlSortColumn> sortColumns, StringBuilder text, BqlCommand.Selection selection)
    {
        if (graph != null && text != null)
        {
            StringBuilder text1 = new StringBuilder();
            this.parseOperand<Operand1>(ref this.a, graph, pars, tables, fields, sortColumns, text1, selection);
            graph.SqlDialect.scriptFunction(Math.Ceiling(Convert.ToDecimal()), text, this.getTypeCodeForOperand<Operand1>(graph), text1.ToString());
        }
        else
        {
            this.parseOperand<Operand1>(ref this.a, graph, pars, tables, fields, sortColumns, text, selection);
        }
    }
}
</code>```

答:
I was able to get the MathCeiling BQL Function to work by commenting out the following line:
graph.SqlDialect.scriptFunction(Math.Ceiling(Convert.ToDecimal()), text, this.getTypeCodeForOperand(graph), text1.ToString());

The MathCeiling BQL Function now works correctly

Body:
Looking for a Bql function to use Math Ceiling in a formula. Need help with this line in the larger example below.

graph.SqlDialect.scriptFunction(Math.Ceiling(Convert.ToDecimal()), text, this.getTypeCodeForOperand<Operand1>(graph), text1.ToString());

Here is the full example I am working with.

public sealed class MathCeiling<Operand1> : BqlFunction, IBqlOperand, IBqlCreator
        where Operand1 : IBqlOperand
{
        private IBqlCreator a;

    public void Verify(PXCache cache, object item, List<object> pars, ref bool? result, ref object value)
    {
        value = (object)null;
        object obj1;
        if (!BqlFunction.getValue<Operand1>(ref this.a, cache, item, pars, ref result, out obj1) || obj1 == null)
            return;
        value = MathCeiling<Operand1>.calculateValue(obj1);
    }

    internal static object calculateValue(object value1)
    {
        return (object)(Math.Ceiling(Convert.ToDecimal(value1)));
    }

    public void Parse(PXGraph graph, List<IBqlParameter> pars, List<System.Type> tables, List<System.Type> fields, List<IBqlSortColumn> sortColumns, StringBuilder text, BqlCommand.Selection selection)
    {
        if (graph != null && text != null)
        {
            StringBuilder text1 = new StringBuilder();
            this.parseOperand<Operand1>(ref this.a, graph, pars, tables, fields, sortColumns, text1, selection);
            graph.SqlDialect.scriptFunction(Math.Ceiling(Convert.ToDecimal()), text, this.getTypeCodeForOperand<Operand1>(graph), text1.ToString());
        }
        else
        {
            this.parseOperand<Operand1>(ref this.a, graph, pars, tables, fields, sortColumns, text, selection);
        }
    }
}


问:
Making grid triangular mesh quickly with Numpy
Consider a regular matrix that represents nodes numbered as shown in the figure:

I want to make a list with all the triangles represented in the figure. Which would result in the following 2 dimensional list:[[0,1,4],[1,5,4],[1,2,5],[2,6,5],...,[11,15,14]]

Assuming that the dimensions of the matrix are (NrXNc) ((4X4) in this case), I was able to achieve this result with the following code:

```<code>def MakeFaces(Nr,Nc):
    Nfaces=(Nr-1)*(Nc-1)*2
    Faces=np.zeros((Nfaces,3),dtype=np.int32)
    for r in range(Nr-1):
        for c in range(Nc-1):
            fi=(r*(Nc-1)+c)*2
            l1=r*Nc+c
            l2=l1+1
            l3=l1+Nc
            l4=l3+1
            Faces[fi]=[l1,l2,l3]
            Faces[fi+1]=[l2,l4,l3]
    return Faces
</code>```

However, the double loop operations make this approach quite slow. Is there a way of using numpy in a smart way to do this faster?

答:
You can achieve a similar result without any explicit loops if you recast the problem correctly. One way would be to imagine the result as three arrays, each containing one of the vertices: first, second and third. You can then zip up or otherwise convert the arrays into whatever format you like in a fairly inexpensive operation.

You start with the actual matrix. This will make indexing and selecting elements much easier:

```<code>m = np.arange(Nr * Nc).reshape(Nr, Nc)
</code>```

The first array will contain all the 90-degree corners:

```<code>c1 = np.concatenate((m[:-1, :-1].ravel(), m[1:, 1:].ravel()))
</code>```

m[:-1, :-1] are the corners that are at the top, m[1:, 1:] are the corners that are at the bottom.

The second array will contain the corresponding top acute corners:

```<code>c2 = np.concatenate((m[:-1, 1:].ravel(), m[:-1, 1:].ravel()))
</code>```

And the third array will contain the bottom corners:

```<code>c2 = np.concatenate((m[1:, :-1].ravel(), m[1:, :-1].ravel()))
</code>```

You can now get an array like your original one back by zipping:

```<code>faces = list(zip(c1, c2, c3))
</code>```

I am sure that you can find ways to improve this algorithm, but it is a start.

Body:
Consider a regular matrix that represents nodes numbered as shown in the figure:

I want to make a list with all the triangles represented in the figure. Which would result in the following 2 dimensional list:[[0,1,4],[1,5,4],[1,2,5],[2,6,5],...,[11,15,14]]

Assuming that the dimensions of the matrix are (NrXNc) ((4X4) in this case), I was able to achieve this result with the following code:

def MakeFaces(Nr,Nc):
    Nfaces=(Nr-1)*(Nc-1)*2
    Faces=np.zeros((Nfaces,3),dtype=np.int32)
    for r in range(Nr-1):
        for c in range(Nc-1):
            fi=(r*(Nc-1)+c)*2
            l1=r*Nc+c
            l2=l1+1
            l3=l1+Nc
            l4=l3+1
            Faces[fi]=[l1,l2,l3]
            Faces[fi+1]=[l2,l4,l3]
    return Faces

However, the double loop operations make this approach quite slow. Is there a way of using numpy in a smart way to do this faster?

Body:
You can achieve a similar result without any explicit loops if you recast the problem correctly. One way would be to imagine the result as three arrays, each containing one of the vertices: first, second and third. You can then zip up or otherwise convert the arrays into whatever format you like in a fairly inexpensive operation.

You start with the actual matrix. This will make indexing and selecting elements much easier:

m = np.arange(Nr * Nc).reshape(Nr, Nc)

The first array will contain all the 90-degree corners:

c1 = np.concatenate((m[:-1, :-1].ravel(), m[1:, 1:].ravel()))

m[:-1, :-1] are the corners that are at the top, m[1:, 1:] are the corners that are at the bottom.

The second array will contain the corresponding top acute corners:

c2 = np.concatenate((m[:-1, 1:].ravel(), m[:-1, 1:].ravel()))

And the third array will contain the bottom corners:

c2 = np.concatenate((m[1:, :-1].ravel(), m[1:, :-1].ravel()))

You can now get an array like your original one back by zipping:

faces = list(zip(c1, c2, c3))

I am sure that you can find ways to improve this algorithm, but it is a start.


问:
Use a variable in cursor SELECT statement
I've written a stored procedure that will take a parent part, go through the  bill-of-materials records for that part and conditionally concatenate matching child-records (i.e. the parts which are included in this part's BOM), but only child-records that meet certain criteria (using our naming convention, anything starting with '.', 'E', or 'ZG').

I have created the SP and it works beautifully, but only when I pass in an [optional] parent part number. I need to run this SP for all parts, so my thought was to execute the SP inside of a cursor, and keep passing in the next part until there are none left to process. I can't work out how to do this, or if it's even possible, because in the cursor's SELECT statement, (in which I'm using the stored procedure code) I need to pass in a variable for it to work.

Here is the code for the stored procedure:

```<code>CREATE PROCEDURE dbo.usp_BuildBOMLit
@item_no CHAR(8) = NULL
AS
BEGIN
WITH CTE AS (
        SELECT DISTINCT
            LTRIM(RTRIM(lvl1.item_no)) as item_no, LTRIM(RTRIM(lvl1.comp_item_no)) as comp_item_no,
            CASE
                WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE '.%'
                    THEN
                        LTRIM(RTRIM(lvl1.comp_item_no))
                WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE 'E%'
                    THEN
                        (SELECT TOP 1 LTRIM(RTRIM(comp_item_no)) FROM bmprdstr_sql WHERE LTRIM(RTRIM(item_no))=LTRIM(RTRIM(lvl1.comp_item_no))  AND LTRIM(RTRIM(comp_item_no)) LIKE '.%')
                WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE 'ZG%'
                    THEN
                        (SELECT TOP 1 LTRIM(RTRIM(comp_item_no)) FROM bmprdstr_sql WHERE LTRIM(RTRIM(item_no))=LTRIM(RTRIM(lvl1.comp_item_no))  AND LTRIM(RTRIM(comp_item_no)) LIKE '.%')
                    ELSE
                        NULL
            END as lvl_2_comp_item_no
        FROM
            bmprdstr_sql as lvl1
            LEFT JOIN bmprdstr_sql lvl2 ON lvl1.comp_item_no=lvl2.item_no
        WHERE
            (lvl1.item_no = @item_no)
            AND (lvl1.comp_item_no LIKE '.%' OR lvl1.comp_item_no LIKE 'ZG%' OR lvl1.comp_item_no LIKE 'E%')
    )
    SELECT DISTINCT
        CASE
            WHEN LEFT(item_no,1)='.'
                THEN STUFF(item_no,1,1,'')
            ELSE
                item_no
        END as item_no,
        part_no =
            STUFF((SELECT DISTINCT ',' +
                    CASE
                        WHEN LEFT(lvl_2_comp_item_no,1)='.'
                            THEN STUFF(lvl_2_comp_item_no,1,1,'')
                        ELSE lvl_2_comp_item_no
                        END
                    FROM CTE where item_no=@item_no FOR XML PATH('')),1,1,'')
    FROM
        CTE
    WHERE
        lvl_2_comp_item_no IS NOT NULL AND item_no IS NOT NULL
END
</code>```

Output is exactly the format I need:

 item_no | part_no

JM9027  | GS10702,LB2391,LB2704,LB2834,LB2896,LB6996

When I create the cursor, I'm using the same code in the cursor's SELECT statement, but as you can see if requires the parent (@itemno) to be passed in. I have tried this, to no avail:

```<code> SET NOCOUNT ON;
 DECLARE @itemno CHAR(15);
 DECLARE @partno VARCHAR(254);
 DECLARE @outside_cursor AS CURSOR;

SET @outside_cursor = CURSOR FAST_FORWARD FOR
WITH CTE AS
(SELECT DISTINCT
        LTRIM(RTRIM(lvl1.item_no)) AS item_no,
        LTRIM(RTRIM(lvl1.comp_item_no)) AS comp_item_no,
        CASE
            WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE '.%'
                THEN LTRIM(RTRIM(lvl1.comp_item_no))
            WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE 'E%'
                THEN
                    (SELECT TOP 1
                        LTRIM(RTRIM(comp_item_no))
                    FROM
                        bmprdstr_sql
                    WHERE

LTRIM(RTRIM(item_no))=LTRIM(RTRIM(lvl1.comp_item_no))
                        AND LTRIM(RTRIM(comp_item_no)) LIKE '.%'
                    )
            WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE 'ZG%'
                THEN
                    (SELECT TOP 1
                        LTRIM(RTRIM(comp_item_no))
                    FROM
                        bmprdstr_sql
                    WHERE

LTRIM(RTRIM(item_no))=LTRIM(RTRIM(lvl1.comp_item_no))
                        AND LTRIM(RTRIM(comp_item_no)) LIKE '.%'
                    )
            ELSE NULL
        END AS lvl_2_comp_item_no
 FROM
    bmprdstr_sql AS lvl1
    LEFT JOIN bmprdstr_sql lvl2 ON lvl1.comp_item_no=lvl2.item_no
 WHERE
    (lvl1.item_no = @itemno) -- <-- problem
     AND (lvl1.comp_item_no LIKE '.%' OR lvl1.comp_item_no LIKE 'ZG%'
OR lvl1.comp_item_no LIKE 'E%')
)
SELECT DISTINCT
    CASE
        WHEN LEFT(item_no,1)='.'
            THEN STUFF(item_no,1,1,'')
        ELSE item_no
    END AS item_no,
    part_no =
        STUFF(
            (SELECT DISTINCT ',' +
                CASE
                    WHEN LEFT(lvl_2_comp_item_no,1)='.'
                        THEN STUFF(lvl_2_comp_item_no,1,1,'')
                    ELSE lvl_2_comp_item_no
                END
            FROM
                CTE
            WHERE
                item_no=@itemno FOR XML PATH('')),1,1,'')
                     -- ^ problem
FROM
    CTE
WHERE
    lvl_2_comp_item_no IS NOT NULL
    AND item_no IS NOT NULL

OPEN @outside_cursor;
FETCH NEXT FROM @outside_cursor INTO @itemno, @partno;

WHILE @@FETCH_STATUS = 0
    BEGIN
        INSERT INTO items_parts (item_no, part_no)
        VALUES (@itemno, @partno)
    FETCH NEXT FROM @outside_cursor INTO @itemno,  @partno
    END
CLOSE @outside_cursor
DEALLOCATE @outside_cursor
</code>```

Any advice on how this can be accomplished?

答: I appreciate the help with this issue. I went back to the drawing board and was able to accomplish what I needed with the stored procedure and a self-joining query - no cursor needed.</p>

Body:
I've written a stored procedure that will take a parent part, go through the  bill-of-materials records for that part and conditionally concatenate matching child-records (i.e. the parts which are included in this part's BOM), but only child-records that meet certain criteria (using our naming convention, anything starting with '.', 'E', or 'ZG').

I have created the SP and it works beautifully, but only when I pass in an [optional] parent part number. I need to run this SP for all parts, so my thought was to execute the SP inside of a cursor, and keep passing in the next part until there are none left to process. I can't work out how to do this, or if it's even possible, because in the cursor's SELECT statement, (in which I'm using the stored procedure code) I need to pass in a variable for it to work.

Here is the code for the stored procedure:

CREATE PROCEDURE dbo.usp_BuildBOMLit
@item_no CHAR(8) = NULL
AS
BEGIN
WITH CTE AS (
        SELECT DISTINCT
            LTRIM(RTRIM(lvl1.item_no)) as item_no, LTRIM(RTRIM(lvl1.comp_item_no)) as comp_item_no,
            CASE
                WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE '.%'
                    THEN
                        LTRIM(RTRIM(lvl1.comp_item_no))
                WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE 'E%'
                    THEN
                        (SELECT TOP 1 LTRIM(RTRIM(comp_item_no)) FROM bmprdstr_sql WHERE LTRIM(RTRIM(item_no))=LTRIM(RTRIM(lvl1.comp_item_no))  AND LTRIM(RTRIM(comp_item_no)) LIKE '.%')
                WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE 'ZG%'
                    THEN
                        (SELECT TOP 1 LTRIM(RTRIM(comp_item_no)) FROM bmprdstr_sql WHERE LTRIM(RTRIM(item_no))=LTRIM(RTRIM(lvl1.comp_item_no))  AND LTRIM(RTRIM(comp_item_no)) LIKE '.%')
                    ELSE
                        NULL
            END as lvl_2_comp_item_no
        FROM
            bmprdstr_sql as lvl1
            LEFT JOIN bmprdstr_sql lvl2 ON lvl1.comp_item_no=lvl2.item_no
        WHERE
            (lvl1.item_no = @item_no)
            AND (lvl1.comp_item_no LIKE '.%' OR lvl1.comp_item_no LIKE 'ZG%' OR lvl1.comp_item_no LIKE 'E%')
    )
    SELECT DISTINCT
        CASE
            WHEN LEFT(item_no,1)='.'
                THEN STUFF(item_no,1,1,'')
            ELSE
                item_no
        END as item_no,
        part_no =
            STUFF((SELECT DISTINCT ',' +
                    CASE
                        WHEN LEFT(lvl_2_comp_item_no,1)='.'
                            THEN STUFF(lvl_2_comp_item_no,1,1,'')
                        ELSE lvl_2_comp_item_no
                        END
                    FROM CTE where item_no=@item_no FOR XML PATH('')),1,1,'')
    FROM
        CTE
    WHERE
        lvl_2_comp_item_no IS NOT NULL AND item_no IS NOT NULL
END

Output is exactly the format I need:

 item_no | part_no

JM9027  | GS10702,LB2391,LB2704,LB2834,LB2896,LB6996

When I create the cursor, I'm using the same code in the cursor's SELECT statement, but as you can see if requires the parent (@itemno) to be passed in. I have tried this, to no avail:

 SET NOCOUNT ON;
 DECLARE @itemno CHAR(15);
 DECLARE @partno VARCHAR(254);
 DECLARE @outside_cursor AS CURSOR;

SET @outside_cursor = CURSOR FAST_FORWARD FOR
WITH CTE AS
(SELECT DISTINCT
        LTRIM(RTRIM(lvl1.item_no)) AS item_no,
        LTRIM(RTRIM(lvl1.comp_item_no)) AS comp_item_no,
        CASE
            WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE '.%'
                THEN LTRIM(RTRIM(lvl1.comp_item_no))
            WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE 'E%'
                THEN
                    (SELECT TOP 1
                        LTRIM(RTRIM(comp_item_no))
                    FROM
                        bmprdstr_sql
                    WHERE

LTRIM(RTRIM(item_no))=LTRIM(RTRIM(lvl1.comp_item_no))
                        AND LTRIM(RTRIM(comp_item_no)) LIKE '.%'
                    )
            WHEN LTRIM(RTRIM(lvl1.comp_item_no)) LIKE 'ZG%'
                THEN
                    (SELECT TOP 1
                        LTRIM(RTRIM(comp_item_no))
                    FROM
                        bmprdstr_sql
                    WHERE

LTRIM(RTRIM(item_no))=LTRIM(RTRIM(lvl1.comp_item_no))
                        AND LTRIM(RTRIM(comp_item_no)) LIKE '.%'
                    )
            ELSE NULL
        END AS lvl_2_comp_item_no
 FROM
    bmprdstr_sql AS lvl1
    LEFT JOIN bmprdstr_sql lvl2 ON lvl1.comp_item_no=lvl2.item_no
 WHERE
    (lvl1.item_no = @itemno) -- <-- problem
     AND (lvl1.comp_item_no LIKE '.%' OR lvl1.comp_item_no LIKE 'ZG%'
OR lvl1.comp_item_no LIKE 'E%')
)
SELECT DISTINCT
    CASE
        WHEN LEFT(item_no,1)='.'
            THEN STUFF(item_no,1,1,'')
        ELSE item_no
    END AS item_no,
    part_no =
        STUFF(
            (SELECT DISTINCT ',' +
                CASE
                    WHEN LEFT(lvl_2_comp_item_no,1)='.'
                        THEN STUFF(lvl_2_comp_item_no,1,1,'')
                    ELSE lvl_2_comp_item_no
                END
            FROM
                CTE
            WHERE
                item_no=@itemno FOR XML PATH('')),1,1,'')
                     -- ^ problem
FROM
    CTE
WHERE
    lvl_2_comp_item_no IS NOT NULL
    AND item_no IS NOT NULL

OPEN @outside_cursor;
FETCH NEXT FROM @outside_cursor INTO @itemno, @partno;

WHILE @@FETCH_STATUS = 0
    BEGIN
        INSERT INTO items_parts (item_no, part_no)
        VALUES (@itemno, @partno)
    FETCH NEXT FROM @outside_cursor INTO @itemno,  @partno
    END
CLOSE @outside_cursor
DEALLOCATE @outside_cursor

Any advice on how this can be accomplished?


问:
How do I use an external module's types in TypeScript definition file?
I am trying to reference Mongoose types in a TypeScript definition file. Currently I'm using a regular .ts file so that I can just do

```<code>import mongoose from 'mongoose'
</code>```

but I want it to be a proper definition file (.d.ts). Problem is that imports are not allowed in definition files. So I've tried this

```<code>/// <reference types="mongoose" />
interface doc extends mongoose {}
interface doc extends mongoose.Document {}
</code>```

and

```<code>/// <reference path="../../node_modules/@types/mongoose/index.d.ts" />
interface doc extends mongoose { }
interface doc extends mongoose.Document {}
</code>```

but neither of them work - regardless of whether I use mongoose or Mongoose. VS Code just says cannot find name 'mongoose' or cannot find namespace 'mongoose'.

I'm at a loss here. How can I use definitions from an external module in my definition file?

答: I don't think that the mongoose typings have a default export, which may be causing this issue. Try adding import * as mongoose from 'mongoose' or import mongoose = require('mongoose') in your d.ts file

Body:
I am trying to reference Mongoose types in a TypeScript definition file. Currently I'm using a regular .ts file so that I can just do

import mongoose from 'mongoose'

but I want it to be a proper definition file (.d.ts). Problem is that imports are not allowed in definition files. So I've tried this

/// <reference types="mongoose" />
interface doc extends mongoose {}
interface doc extends mongoose.Document {}

and

/// <reference path="../../node_modules/@types/mongoose/index.d.ts" />
interface doc extends mongoose { }
interface doc extends mongoose.Document {}

but neither of them work - regardless of whether I use mongoose or Mongoose. VS Code just says cannot find name 'mongoose' or cannot find namespace 'mongoose'.

I'm at a loss here. How can I use definitions from an external module in my definition file?


问:
Access violation reading location 0xFFFFFFFFFFFFFFFF when using FAST feature detector in OpenCV
I am beginner using opencv, and was using the FAST feature detector in opencv to simply get the keypoints of an image.

```<code>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d.hpp"

std::vector<cv::KeyPoint> kp;

int main()
{
    cv::Mat img = cv::imread("im.jpg", 0);
    cv::FAST(img, kp, 100, true);

    cv::Mat img2;
    cv::drawKeypoints(img, kp, img2 , CV_RGB(255, 0, 0));
    cv::imshow("Display", img2);
    cv::waitKey(0);
    cv::destroyWindow("Display");

    return 0;
}
</code>```

But when debugging the code (Debug mode):
I found out that the vector kp (passed as the keypoints vector) in to FAST() has a large size ( kp = { size=658812287755660302 }) which is not possible. But the image denoting correct keypoints is generated. The above mentioned access violation error message comes at the end of debugging.

In Release mode:
The code runs fine at first showing the keypoints in the image. At the end when image window is closed, the program is crashed. When debugged, kp has a reasonable size (kp = { size=427 }).

When the code is run in debug mode without debugging, an application error pops out stating that memory at 0xffffffff could not be read.

The call stack is as shown here, which doesn't make any sense to me.

What am I doing wrong? Is it related to the way I'm initializing the vector or something else?

答:
I was unable to reproduce this issue either using my own image or using the image you provided. I therefore have to conclude that there's a problem with your build environment.

Make sure that you've set up your project includes and libraries correctly, including the shared libraries that OpenCV uses by default.

Make sure that you're using Visual Studio 2015 (or the binary-compatible VS2017) to compile your code.

Body:
I am beginner using opencv, and was using the FAST feature detector in opencv to simply get the keypoints of an image.

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d.hpp"

std::vector<cv::KeyPoint> kp;

int main()
{
    cv::Mat img = cv::imread("im.jpg", 0);
    cv::FAST(img, kp, 100, true);

    cv::Mat img2;
    cv::drawKeypoints(img, kp, img2 , CV_RGB(255, 0, 0));
    cv::imshow("Display", img2);
    cv::waitKey(0);
    cv::destroyWindow("Display");

    return 0;
}

But when debugging the code (Debug mode):
I found out that the vector kp (passed as the keypoints vector) in to FAST() has a large size ( kp = { size=658812287755660302 }) which is not possible. But the image denoting correct keypoints is generated. The above mentioned access violation error message comes at the end of debugging.

In Release mode:
The code runs fine at first showing the keypoints in the image. At the end when image window is closed, the program is crashed. When debugged, kp has a reasonable size (kp = { size=427 }).

When the code is run in debug mode without debugging, an application error pops out stating that memory at 0xffffffff could not be read.

The call stack is as shown here, which doesn't make any sense to me.

What am I doing wrong? Is it related to the way I'm initializing the vector or something else?


问:
check if a number is present in a list, app engine templates
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?

Update

Lukes answer solved my problem of automatically inserting the break.

But I still need to find a way to check for each number if it is present in a list and give it a specific class. Is there any way to achieve something like this:

```<code>{% for number in list }
  <td {% if number in another_list %}class="special"{% endif %}>{{number}}</td>
{% endfor }
</code>```

答: Include a counter (i) which increments during each loop and use an if statement to reset i to 1 and draw the break when it reaches 10.</p>

Body:
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?

Update

Lukes answer solved my problem of automatically inserting the break.

But I still need to find a way to check for each number if it is present in a list and give it a specific class. Is there any way to achieve something like this:

{% for number in list }
  {{number}}
{% endfor }


问:
Convert decimal to string for comparison in U-SQL
I am trying to convert data from a loaded in CSV file to an Azure table, but I'm running into problems where one of the values is loading in a string and the equivalent value in the table is decimal.

```<code>@ProdOutput =
    EXTRACT
    [p_description] string,
    [p_code] string,
    [p_price] string,
    [p_colour] string
FROM "testing/martin/items.csv"
USING Extractors.Csv(skipFirstNRows:1);

// @items has been brought in from a table in Data Lake Analytics
@holdings_query =
    SELECT ROW_NUMBER() OVER (ORDER BY h.code) AS rn,
       h.description AS Description,
       h.cd AS Code,
       h.priceGBP  AS Price,
       h.col AS Colour
FROM   @items AS h;

@result =
    SELECT
    p_description == Description ? p_description : String.Concat("Mismatch", p_description, " !! ", Description)  AS [Desc],
    p_code == Code ? p_description : String.Concat("Mismatch", p_code, " !! ", Code)  AS [Code],
    p_price == Price ? p_price: String.Concat("Mismatch", p_price, " !! ", Price)  AS [Price]
FROM @holdings_query AS h
LEFT OUTER JOIN @prod_data AS p ON h.Code == p.p_code;
</code>```

The problem is I want the EXTRACT statement to bring everything in generically as a string, as I'm not always going to know the type of each of the columns. So when I do the comparison in the final statement, I would like to convert the Price from decimal (as it is in the table) to string to compare with what is coming out of the CSV.

I have tried ToString(), ToString("G"), (string?) but they all throw up errors. what am I doing wrong?

TIA
Martin

Example data:

Items.csv:

"Item1","IT1","3.65"

"Item2","IT2","4.00"

"Item3","IT3","524.2123"

@items table:

"Item1", "IT1", 3.65

"Item2", "IT2", 4.00

"Item3", "IT3", 524.2123

答:
Try Decimal.Parse on the string type.  This method "...converts the string representation of a number to its Decimal equivalent".  I got the following statement to work, where p_price is the string value:

```<code>@result =
    SELECT
            Decimal.Parse(p.p_price) == h.Price ? 1 : 0 AS isEqual
...
</code>```

Body:
I am trying to convert data from a loaded in CSV file to an Azure table, but I'm running into problems where one of the values is loading in a string and the equivalent value in the table is decimal.

@ProdOutput =
    EXTRACT
    [p_description] string,
    [p_code] string,
    [p_price] string,
    [p_colour] string
FROM "testing/martin/items.csv"
USING Extractors.Csv(skipFirstNRows:1);

// @items has been brought in from a table in Data Lake Analytics
@holdings_query =
    SELECT ROW_NUMBER() OVER (ORDER BY h.code) AS rn,
       h.description AS Description,
       h.cd AS Code,
       h.priceGBP  AS Price,
       h.col AS Colour
FROM   @items AS h;

@result =
    SELECT
    p_description == Description ? p_description : String.Concat("Mismatch", p_description, " !! ", Description)  AS [Desc],
    p_code == Code ? p_description : String.Concat("Mismatch", p_code, " !! ", Code)  AS [Code],
    p_price == Price ? p_price: String.Concat("Mismatch", p_price, " !! ", Price)  AS [Price]
FROM @holdings_query AS h
LEFT OUTER JOIN @prod_data AS p ON h.Code == p.p_code;

The problem is I want the EXTRACT statement to bring everything in generically as a string, as I'm not always going to know the type of each of the columns. So when I do the comparison in the final statement, I would like to convert the Price from decimal (as it is in the table) to string to compare with what is coming out of the CSV.

I have tried ToString(), ToString("G"), (string?) but they all throw up errors. what am I doing wrong?

TIA
Martin

Example data:

Items.csv:

"Item1","IT1","3.65"

"Item2","IT2","4.00"

"Item3","IT3","524.2123"

@items table:

"Item1", "IT1", 3.65

"Item2", "IT2", 4.00

"Item3", "IT3", 524.2123

Body:
Try Decimal.Parse on the string type.  This method "...converts the string representation of a number to its Decimal equivalent".  I got the following statement to work, where p_price is the string value:

@result =
    SELECT
            Decimal.Parse(p.p_price) == h.Price ? 1 : 0 AS isEqual
...


问:
PDF to Texture2D array?
```<code>        //add icon
        byte[] fileBytes;
        Texture2D tex = null;

        if (File.Exists(*path to file*))
        {
            fileData = File.ReadAllBytes(*path to file*);
            tex = new Texture2D(2, 2);
            tex.LoadImage(fileBytes);
        }

        //Read Texture into RawImage component
        GameObject.GetComponent<RawImage>().material.mainTexture = tex;
</code>```

The above code can dynamically create and display images (jpeg, jpg, png) in Unity. I'm seeking to do the same for a PDF.

As far as I've seen through my research, there are PDF renderers available on the asset store however, they are expensive. Unfortunately there aren't any low grade or free options that load PDFs.

When I try to run my code on PDFs, it returns what looks like a factory image of a red question mark icon on a blank white background.

My code isn't reading the PDF into an array, creating an image/texture for each page. Before I dive head first and do this, I'm reaching out to you. Is this plausible? Are there better options? Am I SOL and my time would be better spent buying a pre-made asset?

答:
Instead of working with the PDF directly it may be easier to convert to an image file, and use your code to convert the new image to the Texture2D array. I have not personally done this but this SO question seems to outline it pretty well:

Save pdf to jpeg using c#

Title: PDF to Texture2D array?

Body:
        //add icon
        byte[] fileBytes;
        Texture2D tex = null;

        if (File.Exists(*path to file*))
        {
            fileData = File.ReadAllBytes(*path to file*);
            tex = new Texture2D(2, 2);
            tex.LoadImage(fileBytes);
        }

        //Read Texture into RawImage component
        GameObject.GetComponent<RawImage>().material.mainTexture = tex;

The above code can dynamically create and display images (jpeg, jpg, png) in Unity. I'm seeking to do the same for a PDF.

As far as I've seen through my research, there are PDF renderers available on the asset store however, they are expensive. Unfortunately there aren't any low grade or free options that load PDFs.

When I try to run my code on PDFs, it returns what looks like a factory image of a red question mark icon on a blank white background.

My code isn't reading the PDF into an array, creating an image/texture for each page. Before I dive head first and do this, I'm reaching out to you. Is this plausible? Are there better options? Am I SOL and my time would be better spent buying a pre-made asset?


问:
What's the best way to save set of objects locally in react-native?
AsyncStorage is unable to retain data and I have run out of options to save
a set of objects and update them with new entries to the list. Please help</p>

答:
Realm could be your solution: https://realm.io/docs/javascript/latest/index.html

Realm is a mobile database that runs directly inside phones, tablets or wearables. This project hosts the JavaScript versions of Realm.

Currently we only support React Native (both iOS & Android) and Node.js (on MacOS and Linux) but we are considering adding support for Cordova/PhoneGap/Ionic as well.

Features

Mobile-first: Realm is the first database built from the ground up to run directly inside phones, tablets and wearables.

Simple: Data is directly exposed as objects and queryable by code, removing the need for ORM's riddled with performance & maintenance issues.

Modern: Realm supports relationships, generics, and vectorization.
Fast: Realm is faster than even raw SQLite on common operations, while maintaining an extremely rich feature set.


问:
Javascript promise confusion for executing two functions in order
Right now I have funcA, funcB, arrayA and arrayB. In funcA, arrayB will populate itself by requesting some external information and the time for doing this is varied. I want it to execute funcB after arrayB.length == arrayA.length, and arrayB is a global variable that its content will be used in funcB. I assume that I need to use JQuery deferred and promise..so I tried this

```<code>     var arrayB = [];
     var hi = funcA();
     hi.then(funcB());

     funcA(){
            var Dfd = $.Deferred();
            arrayB.forEach(function(x, i){
                   some external retrieval;
                   if (arrayB.length == arrayA.length){
                         Dfd.resolve(arrayB);
                   }
             })

        return Dfd;
     }
</code>```

But this doesn't help. How should I change it?

答:
I resolved the problem by doing this:</p>

```<code>  hi.done(function(){funcA()});
</code>```

Body:
Right now I have funcA, funcB, arrayA and arrayB. In funcA, arrayB will populate itself by requesting some external information and the time for doing this is varied. I want it to execute funcB after arrayB.length == arrayA.length, and arrayB is a global variable that its content will be used in funcB. I assume that I need to use JQuery deferred and promise..so I tried this

     var arrayB = [];
     var hi = funcA();
     hi.then(funcB());

     funcA(){
            var Dfd = $.Deferred();
            arrayB.forEach(function(x, i){
                   some external retrieval;
                   if (arrayB.length == arrayA.length){
                         Dfd.resolve(arrayB);
                   }
             })

        return Dfd;
     }

But this doesn't help. How should I change it?

Body:
I resolved the problem by doing this:

  hi.done(function(){funcA()});


问:
Resolution of implicit within class body
At a high-level, I'm curious to know how implicits defined inside a class body are resolved? I assumed they would be considered part of the current scope (as per the awesome answer here), but I am wrong.

For a specific example, why doesn't the following work:

```<code>trait Convert[T, U] {
  final def value(record: T)(implicit f: T => U): U = f(record)
}

case class ConvertMap(key: String)
  extends Convert[Map[String, String], Boolean] {
  implicit def a2b(m: Map[String, String]): Boolean = m.contains(key)
}
</code>```

I can instantiate the class ConvertMap, but when I call the value method I get an error stating that the view from Map[String, String] => Boolean can't be found.

```<code>scala> val c = ConvertMap("key")
c: ConvertMap = ConvertMap(key)

scala> c.value(Map("key" -> "value"))
<console>:13: error: No implicit view available from Map[String,String] => Boolean.
</code>```

答:
If you re-read the answer you provided for implicit resolution scope, you see that there are a couple of things which happen here causing the implicit you've defined not to be found.

First, if the implicit isn't found in the local scope of the call-site, we defer to "category 2" lookup for implicits which involves the types underlying the implicit. We're searching for an implicit conversion of type Map[String, String] => Boolean. According to the implicit scoping rules, the following is applicable to our use case:

If T is a parameterized type S[T1, ..., Tn], the union of the parts of S and T1, ..., Tn.

Our S[T1.. Tn] is a Map[String, String] (and it's base classes), so we have both Map and String as a candidate type for implicit lookup, but neither of them hold the conversion. Further, the return type is also considered, meaning Boolean is also in scope, but again, it doesn't hold the implicit and hence why the compiler complains.

The simplest thing that can be done to help the compiler find it is to place the implicit inside the companion object of ConvertMap, but that means we can no longer accept a value key in the constructor, which makes your example a bit contrived.

Body:
At a high-level, I'm curious to know how implicits defined inside a class body are resolved? I assumed they would be considered part of the current scope (as per the awesome answer here), but I am wrong.

For a specific example, why doesn't the following work:

trait Convert[T, U] {
  final def value(record: T)(implicit f: T => U): U = f(record)
}

case class ConvertMap(key: String)
  extends Convert[Map[String, String], Boolean] {
  implicit def a2b(m: Map[String, String]): Boolean = m.contains(key)
}

I can instantiate the class ConvertMap, but when I call the value method I get an error stating that the view from Map[String, String] => Boolean can't be found.

scala> val c = ConvertMap("key")
c: ConvertMap = ConvertMap(key)

scala> c.value(Map("key" -> "value"))
<console>:13: error: No implicit view available from Map[String,String] => Boolean.


问:
xAxis auto label dropping has stopped working after upgrading to Highcharts 5.0.8
The label looks good in Highcharts 4 but after upgrading to Highcharts 5 I started to Ellipses.

The xAxis.label property looks something like this. Is there any way I can force the label to render horizontally and drop if there is not enough room for them to be rendered ? I can't use step:1

```<code> labels: {
    rotation: 0

  }
</code>```

Highcharts-4

Highcharts-5

Rotation value I'm using for different Label Angle options are below:

Auto - I'm using autoRatate:[-10, -20, -30, -40, -50, -60, -70, -80, -90]

--  : rotate:0 -- I've problem with this option

/// : rotate:-45

||| : rotate:90

\\ : rotate:45

答:
Looks like staggerLines can take care of this, but needs to be set manually.

Fiddle:

http://jsfiddle.net/jlbriggs/a8g87gm8/14/

Reference:

http://api.highcharts.com/highcharts/xAxis.labels.staggerLines

Body:
The label looks good in Highcharts 4 but after upgrading to Highcharts 5 I started to Ellipses.

The xAxis.label property looks something like this. Is there any way I can force the label to render horizontally and drop if there is not enough room for them to be rendered ? I can't use step:1

 labels: {
    rotation: 0

  }

Highcharts-4

Highcharts-5

Rotation value I'm using for different Label Angle options are below:

Auto - I'm using autoRatate:[-10, -20, -30, -40, -50, -60, -70, -80, -90]

--  : rotate:0 -- I've problem with this option

/// : rotate:-45

||| : rotate:90

\\ : rotate:45


问:
React Render Components on Switch function
I am attempting to create a page that renders components based on a selection.  Here is the main page that would watch the for the change.

```<code>const data = [{ number: 0, text: 'Content Type' },  { number: 1, text: 'Content Publishing Status' },  { number: 2, text: 'Geo Locations' },  { number: 3, text: 'Tags' },  { number: 4, text: 'Change Reason' },
  { number: 5, text: 'Delievery Status' },  { number: 6, text: 'Content Record' }];

export default class ReqEngineAdmin extends Component {
  constructor(props) {
    super(props);
    this.state = {
      adminSelect: 0,
    };
  }
  shouldComponentUpdate(nextProps, nextState) {
    log.debug('updateding to :', nextState.adminSelect);
    return this.state.adminSelect !== nextState.adminSelect;
  }

  handleChange = (e, i, v) => {
    log.debug('in handle Change', v);
    this.setState(() => ({ adminSelect: v }));
  };

  render() {
    const selected = this.state.adminSelect;

    return (
      <div className={styles.bodyContent}>
        <MainHeader title="Requirements Engine Admin" />
        <DropDownMenu value={this.state.adminSelect} onChange={this.handleChange}>
          {data.map((d, i) =>
            <MenuItem key={`AdminSelect_${i + 1}`} value={d.number} primaryText={d.text} />
          )}
        </DropDownMenu>
        <Divder />
        <RenderPanel panelNo={selected} {...this.props} />
      </div>
    );
  }
}
</code>```

The page that would handle the switch currently looks like so:

```<code>const renderPanel = (props) => {
  switch (props.panelNo) {
    case 0:
      return (
        <div>
          <ContentTypePanel {...props} />
          <Divider />
          <ContentTypeTable {...props} />
        </div>
      );
    case 1:
      return (
        <div>
          <PubStatusPanel {...props} />
          <Divider />
          <PubStatusTable {...props} />
        </div>
      );
    case 2:
      return (
        <div>
          <GeoLocationPanel {...props} />
          <Divider />
          <GeoLocationTable {...props} />
        </div>
      );
    case 3:
      return (
        <div>
          <TagsPanel {...props} />
          <Divider />
          <TagsTable {...props} />
        </div>
      );
    case 4:
      return (
        <div>
          <ChangeReasonPanel {...props} />
          <Divider />
          <ChangeReasonTable {...props} />
        </div>
      );
    case 5:
      return (
        <div>
          <DelieveryStatusPanel {...props} />
          <Divider />
          <DelieveryStatusTable {...props} />
        </div>
      );
    case 6:
      return (
        <div>
          <ContentRecordPanel {...props} />
          <Divider />
          <ContentRecordTable {...props} />
        </div>
      );
    default:
      return null;
  }
};

renderPanel.propTypes = {
  panelNo: PropTypes.number,
};
export default renderPanel;
</code>```

I'm trying to just past the changed state, but I'm lost on a solution to get the page to render the new Components.

答:
Fixed by using the componentWillUpdate method:

```<code>componentWillupdate(nextProps,nextState){
 this.selectedPanel(nextState.selected, nextProps)
}

selectPanel(panelNo,props) =>{
 switch(panelNo){
  case 1:
   return (
      <div>
        <PubStatusPanel {...props} /> <Divider /> <PubStatusTable />
      </div>
    );}
...
 case 0:
  default:
    return (
      <div>
        <ContentTypePanel {...props} /> <Divider /> <ContentTypeTable />
      </div>
    );
}
</code>```

};

Body:
I am attempting to create a page that renders components based on a selection.  Here is the main page that would watch the for the change.

const data = [{ number: 0, text: 'Content Type' },  { number: 1, text: 'Content Publishing Status' },  { number: 2, text: 'Geo Locations' },  { number: 3, text: 'Tags' },  { number: 4, text: 'Change Reason' },
  { number: 5, text: 'Delievery Status' },  { number: 6, text: 'Content Record' }];

export default class ReqEngineAdmin extends Component {
  constructor(props) {
    super(props);
    this.state = {
      adminSelect: 0,
    };
  }
  shouldComponentUpdate(nextProps, nextState) {
    log.debug('updateding to :', nextState.adminSelect);
    return this.state.adminSelect !== nextState.adminSelect;
  }

  handleChange = (e, i, v) => {
    log.debug('in handle Change', v);
    this.setState(() => ({ adminSelect: v }));
  };

  render() {
    const selected = this.state.adminSelect;

    return (

        <MainHeader title="Requirements Engine Admin" />
        <DropDownMenu value={this.state.adminSelect} onChange={this.handleChange}>
          {data.map((d, i) =>
            <MenuItem key={`AdminSelect_${i + 1}`} value={d.number} primaryText={d.text} />
          )}
        </DropDownMenu>
        <Divder />
        <RenderPanel panelNo={selected} {...this.props} />

    );
  }
}

The page that would handle the switch currently looks like so:

const renderPanel = (props) => {
  switch (props.panelNo) {
    case 0:
      return (

          <ContentTypePanel {...props} />
          <Divider />
          <ContentTypeTable {...props} />

      );
    case 1:
      return (

          <PubStatusPanel {...props} />
          <Divider />
          <PubStatusTable {...props} />

      );
    case 2:
      return (

          <GeoLocationPanel {...props} />
          <Divider />
          <GeoLocationTable {...props} />

      );
    case 3:
      return (

          <TagsPanel {...props} />
          <Divider />
          <TagsTable {...props} />

      );
    case 4:
      return (

          <ChangeReasonPanel {...props} />
          <Divider />
          <ChangeReasonTable {...props} />

      );
    case 5:
      return (

          <DelieveryStatusPanel {...props} />
          <Divider />
          <DelieveryStatusTable {...props} />

      );
    case 6:
      return (

          <ContentRecordPanel {...props} />
          <Divider />
          <ContentRecordTable {...props} />

      );
    default:
      return null;
  }
};

renderPanel.propTypes = {
  panelNo: PropTypes.number,
};
export default renderPanel;

I'm trying to just past the changed state, but I'm lost on a solution to get the page to render the new Components.

Body:
Fixed by using the componentWillUpdate method:

componentWillupdate(nextProps,nextState){
 this.selectedPanel(nextState.selected, nextProps)
}

selectPanel(panelNo,props) =>{
 switch(panelNo){
  case 1:
   return (
      <div>
        <PubStatusPanel {...props} /> <Divider /> <PubStatusTable />
      </div>
    );}
...
 case 0:
  default:
    return (
      <div>
        <ContentTypePanel {...props} /> <Divider /> <ContentTypeTable />
      </div>
    );
}

};


问:
Get CMake to not be silent about sources it doesn't understand?
Suppose you have a very simple CMakeLists.txt

```<code>add_executable(silent T.cpp A.asm)
</code>```

CMake will happily generate a C++ target for building silent, with T.cpp in it, but will silently drop any and all reference to A.asm, because it doesn't know what to do with the suffix.

Is there any way to get CMake to loudly complain about this source file it doesn't understand (to aid in porting a Makefile to CMake).

答:
Ignoring unknown file extensions is - unfortunately for your case - by design.

If I look at the code of cmGeneratorTarget::ComputeKindedSources() anything unknown ends up to be classified as SourceKindExtra (to be added as such to generated IDE files).

So I tested a little and came up with the following script that evaluates your executable target source files for valid file extensions by overwriting add_executable() itself:

cmake_minimum_required(VERSION 3.3)

project(silent CXX)

file(WRITE T.cpp "int main() { return 0; }")
file(WRITE T.h "")
file(WRITE A.asm "")

function(add_executable _target)
    _add_executable(${_target} ${ARGN})

    get_property(_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
    foreach(_lang IN LISTS _langs)
        list(APPEND _ignore "${CMAKE_${_lang}_IGNORE_EXTENSIONS}")
    endforeach()

    get_target_property(_srcs ${_target} SOURCES)
    foreach(_src IN LISTS _srcs)
        get_source_file_property(_lang "${_src}" LANGUAGE)
        get_filename_component(_ext "${_src}" EXT)
        string(SUBSTRING "${_ext}" 1 -1 _ext) # remove leading dot
        if (NOT _lang AND NOT _ext IN_LIST _ignore)
            message(FATAL_ERROR "Target ${_target}: Unknown source file type '${_src}'")
        endif()
    endforeach()
endfunction()

add_executable(silent T.cpp T.h A.asm)
```

Since you wanted a rather loudly complain by CMake I declared it an FATAL_ERROR in this example implementation.

Body:
Suppose you have a very simple CMakeLists.txt

add_executable(silent T.cpp A.asm)

CMake will happily generate a C++ target for building silent, with T.cpp in it, but will silently drop any and all reference to A.asm, because it doesn't know what to do with the suffix.

Is there any way to get CMake to loudly complain about this source file it doesn't understand (to aid in porting a Makefile to CMake).

Body:
Ignoring unknown file extensions is - unfortunately for your case - by design.

If I look at the code of cmGeneratorTarget::ComputeKindedSources() anything unknown ends up to be classified as SourceKindExtra (to be added as such to generated IDE files).

So I tested a little and came up with the following script that evaluates your executable target source files for valid file extensions by overwriting add_executable() itself:

cmake_minimum_required(VERSION 3.3)

project(silent CXX)

file(WRITE T.cpp "int main() { return 0; }")
file(WRITE T.h "")
file(WRITE A.asm "")

function(add_executable _target)
    _add_executable(${_target} ${ARGN})

    get_property(_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
    foreach(_lang IN LISTS _langs)
        list(APPEND _ignore "${CMAKE_${_lang}_IGNORE_EXTENSIONS}")
    endforeach()

    get_target_property(_srcs ${_target} SOURCES)
    foreach(_src IN LISTS _srcs)
        get_source_file_property(_lang "${_src}" LANGUAGE)
        get_filename_component(_ext "${_src}" EXT)
        string(SUBSTRING "${_ext}" 1 -1 _ext) # remove leading dot
        if (NOT _lang AND NOT _ext IN_LIST _ignore)
            message(FATAL_ERROR "Target ${_target}: Unknown source file type '${_src}'")
        endif()
    endforeach()
endfunction()

add_executable(silent T.cpp T.h A.asm)

Since you wanted a rather loudly complain by CMake I declared it an FATAL_ERROR in this example implementation.


问:
Default page available over Internet using angularjs
If user enter "https://apnabank.bank.com/Transfer/#/" URL then application working fine.But user dont know proper URL.If they give only  "https://apnabank.bank.com" then IBM http server error displaying.I have to show there dafault page "URL not found" like that.Please help me out.</p>

答:
@Priyanka, as you are using ngRouter i am giving you a sample example:

Assuming you have created error.html and other html templates.

```<code>$routeProvider.when('/login', {
        title: 'MyLogin',
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        controllerAs: 'vm'
    });
    $routeProvider.when('/error', {
        title: 'Error Page',
        templateUrl: 'views/error.html',
        controller: 'errorController',//needed only if you want to do something in your error page.
        controllerAs: 'vm'
    });

$routeProvider.otherwise({
        redirectTo: '/error'
    });
</code>```

Description:
First /login is sample route usually be in any example like many others, it is just for example.

Then if user hits the url that is not handled by you, then you can redirect the user to your application's error page using otherwise like i handled in above code.otherwise then redirect all your non handled url's to the error page.

You just create an error.html somewhere in the project( Prefer in views directory) and give its path in the rout handler as in above example.

Hope This will help you. . .

Body:
@Priyanka, as you are using ngRouter i am giving you a sample example:

Assuming you have created error.html and other html templates.

$routeProvider.when('/login', {
        title: 'MyLogin',
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        controllerAs: 'vm'
    });
    $routeProvider.when('/error', {
        title: 'Error Page',
        templateUrl: 'views/error.html',
        controller: 'errorController',//needed only if you want to do something in your error page.
        controllerAs: 'vm'
    });

$routeProvider.otherwise({
        redirectTo: '/error'
    });

Description:
First /login is sample route usually be in any example like many others, it is just for example.

Then if user hits the url that is not handled by you, then you can redirect the user to your application's error page using otherwise like i handled in above code.otherwise then redirect all your non handled url's to the error page.

You just create an error.html somewhere in the project( Prefer in views directory) and give its path in the rout handler as in above example.

Hope This will help you. . .


问:
Azure AD B2C application vs Azure App Registration app
I don’t really understand the difference between Azure AD B2C Application and Azure App Registration Application.
I can see some of my Azure AD B2C applications in the Azure App Registration page, but the opposite is not true.

The good part of Azure App Registration is that you can request the Graph API if you have the right permissions and it’s not true for an Azure AD B2C Application.

https://learn.microsoft.com/azure/active-directory-b2c/active-directory-b2c-devquickstarts-graph-dotnet

But it seems to be not possible to be authenticated with Azure AD B2C with an Azure App Registration application.

Do you know if there is a possibly to have all-in-one ? An application which can authorize AAD B2C authentication and request the Graph API.

答:
1)  Currently it is not possible to use the same app registration for both Microsoft Graph API and Azure AD B2C.

a.  Azure AD B2C Apps  must be registered using the Azure AD B2C blade in the Azure portal.

b.  Graph API applications can be registered either at https://apps.dev.microsoft.com/ or by creating an application in your Azure Active Directory tenant (but not under the Azure AD B2C blade).

2)  Graph API currently does not accept tokens issued by Azure AD B2C.  This means you may need a separate micro-service that will authenticate with Microsoft Graph using the ClientId / ClientSecret of your Graph API Application Registration.  The instructions in the documentation will have you configure “create, read and update permissions” for your Graph API app registration.  (https://learn.microsoft.com/azure/active-directory-b2c/active-directory-b2c-devquickstarts-graph-dotnet)


问:
Trying to filter (tons of) noise from accelerometers and gyroscopes
My project:

I'm developing a slot car with 3-axis accelerometer and gyroscope, trying to estimate the car pose (x, y, z, yaw, pitch) but I have a big problem with my vibration noise (while the car is running, the gears induce vibration and the track also gets it worse) because the noise takes values between ±4[g] (where g = 9.81 [m/s^2]) for the accelerometers, for example.

I know (because I observe it), the noise is correlated for all of my sensors

In my first attempt, I tried to work it out with a Kalman filter, but it didn't work because values of my state vectors had a really big noise.

EDIT2: In my second attempt I tried a low pass filter before the Kalman filter, but it only slowed down my system and didn't filter the low components of the noise. At this point I realized this noise might be composed of low and high frecuency components.

I was learning about adaptive filters (LMS and RLS) but I realized I don't have a noise signal and if I use one accelerometer signal to filter other axis' accelerometer, I don't get absolute values, so It doesn't work.

EDIT: I'm having problems trying to find some example code for adaptive filters. If anyone knows about something similar, I will be very thankful.

Here is my question:

Does anyone know about a filter or have any idea about how I could fix it and filter my signals correctly?

Thank you so much in advance,

XNor

PD: I apologize for any mistake I could have, english is not my mother tongue

答:
I had similar problems with noise with low and high frequencies and I managed to decently remove it without removing good signal too by using an universal microphone shock mount. It does a good job with gyroscope too especially if you find one which fits it (or you can put it in a small case then mount it)
It basically uses elastic strings to remove shocks and vibration.


问:
.Htaccess rewrite to username
I'm a beginner in php and primarily with htaccess part. It's pretty darn confusing.

So I have this file :-

```<code>www.domain.com/profile.php?username=my_username
</code>```

How can I make the above accessible using only :-

```<code>wwww.domain.com/my_username
</code>```

Any kind of directions would be helpful

Something that I tried :-

```<code>RewriteEngine on
RewriteRule ^/([0-9]+)$ /profile.php?username=$1
</code>```

答:
you can achieve this by .htaccess</p>

```<code>Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^/(\d+)*$ ./profile.php?username=$1
</code>```

Title: .Htaccess rewrite to username

Body:
I'm a beginner in php and primarily with htaccess part. It's pretty darn confusing.

So I have this file :-

www.domain.com/profile.php?username=my_username

How can I make the above accessible using only :-

wwww.domain.com/my_username

Any kind of directions would be helpful

Something that I tried :-

RewriteEngine on
RewriteRule ^/([0-9]+)$ /profile.php?username=$1

Body:
you can achieve this by .htaccess

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^/(\d+)*$ ./profile.php?username=$1


问:
ASP.net Membership provider client or serverside authentication
I am developing an MVC2 application an am using the built in Membership provider. I am just asking myself if the authentication is on the server or the client?</p>

答: As stated above, this occurs on the server as part of the Authentication/Authorization process build into Asp.net.  Override BeginRequest and AuthenticateRequest within your application class (Global.asax.cs) to compare the state of the current user (HttpContext.Current.User) before and after authentication.  For more information check out the documentation on the HttpApplication class.</p>


问:
Remove unwanted part of String. Regex / JS
If I have a string which looks like this:

```<code>var myString = '73gf9y::-8auhTHIS_IS_WHAT_I_WANT'
</code>```

What regex would I need to end up with:

```<code>'THIS_IS_WHAT_I_WANT'
</code>```

The first part of my String will always be a random assortment of characters. Is there some regex which will remove everything up to THIS?

答:
Adding to Amit Joki's excellent solution (sorry I don't have the rep yet to comment): since match returns an array of results, if you need to remove unwanted characters from within the string, you can use join:

```<code>input = '(800) 555-1212';
result = input.match(/[0-9]+/g).join('');
console.log(result); // '8005551212'
</code>```

Body:
If I have a string which looks like this:

var myString = '73gf9y::-8auhTHIS_IS_WHAT_I_WANT'

What regex would I need to end up with:

'THIS_IS_WHAT_I_WANT'

The first part of my String will always be a random assortment of characters. Is there some regex which will remove everything up to THIS?

Body:
Adding to Amit Joki's excellent solution (sorry I don't have the rep yet to comment): since match returns an array of results, if you need to remove unwanted characters from within the string, you can use join:

input = '(800) 555-1212';
result = input.match(/[0-9]+/g).join('');
console.log(result); // '8005551212'


问:
Unity Raycast2D ignored instantiated Prefab object
I'm currently making a small game for a university assignment. It's a simple 2D game where you shoot birds using the mouse.

I did collission detection by hand at first (check for x/y boundaries) but now I wanna use a collider.

So I added a CircleCollider2D to my objects and I perform the Raycast like so

```<code>Vector3 mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);

RaycastHit2D[] hits = Physics2D.RaycastAll (mousePosition, Vector3.forward, Mathf.Infinity);
        Debug.Log (hits.Length);
</code>```

Now when I add my prefabs manually into my scene it works as expected. The log outputs 1, or even 2 if I have multiple birds on top of each other.

But my game instantiated a lot of birds randomly and they are not detected when performing the raycast. I already checked, they definitely have colliders.

The instantiation code looks like the following:

```<code>Bird bird = Instantiate (birdPrefab, birdPosition, Quaternion.identity) as Bird;
</code>```

I googled around for 2 hours now, but nothing could actually solve my problem.

I don't know if this is important, but the collision detection does not happen within the bird object's attached script.

I'm really cofused because it works with manually put objects, but not with instantiated ones. Has anybody experienced this before?

Edit:

The mouse position is on (x, y, -10) and the birds are on (x, y, 0) and both the manually placed ones and the instantiated ones are direct children of the scene.

Edit2:

Bird start

```<code>// Use this for initialization
void Start () {
    this.animator = this.GetComponent<Animator> ();

    this.camera = Camera.main;

    this.rigidBody = this.GetComponent<Rigidbody2D> ();
    // get the ammunition script
    this.ammunition = GameObject.Find ("Ammunition").GetComponent<Ammunition> ();
    // get the score script
    this.score      = GameObject.Find("Score").GetComponent<Score>();
}
</code>```

Manually Placed Bird

Instantiated Bird

Both have the collider and both are on the same Z level for the RayCast.

答:
There do not seem to be any issues with your raycast or instantiation of the Bird, given the information you have provided. This leads me to believe there is a problem elsewhere in the code or in the way the scene is set up, especially if the non-instantiated bird works as expected.

If you can post a screenshot of both the manually placed Bird and instantiated Bird Gameobject information during gameplay, as well as any code performed on "bird" after instantiation, we can take a closer look.

Body:
I'm currently making a small game for a university assignment. It's a simple 2D game where you shoot birds using the mouse.

I did collission detection by hand at first (check for x/y boundaries) but now I wanna use a collider.

So I added a CircleCollider2D to my objects and I perform the Raycast like so

Vector3 mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);

RaycastHit2D[] hits = Physics2D.RaycastAll (mousePosition, Vector3.forward, Mathf.Infinity);
        Debug.Log (hits.Length);

Now when I add my prefabs manually into my scene it works as expected. The log outputs 1, or even 2 if I have multiple birds on top of each other.

But my game instantiated a lot of birds randomly and they are not detected when performing the raycast. I already checked, they definitely have colliders.

The instantiation code looks like the following:

Bird bird = Instantiate (birdPrefab, birdPosition, Quaternion.identity) as Bird;

I googled around for 2 hours now, but nothing could actually solve my problem.

I don't know if this is important, but the collision detection does not happen within the bird object's attached script.

I'm really cofused because it works with manually put objects, but not with instantiated ones. Has anybody experienced this before?

Edit:

The mouse position is on (x, y, -10) and the birds are on (x, y, 0) and both the manually placed ones and the instantiated ones are direct children of the scene.

Edit2:

Bird start

// Use this for initialization
void Start () {
    this.animator = this.GetComponent<Animator> ();

    this.camera = Camera.main;

    this.rigidBody = this.GetComponent<Rigidbody2D> ();
    // get the ammunition script
    this.ammunition = GameObject.Find ("Ammunition").GetComponent<Ammunition> ();
    // get the score script
    this.score      = GameObject.Find("Score").GetComponent<Score>();
}

Manually Placed Bird

Instantiated Bird

Both have the collider and both are on the same Z level for the RayCast.