问:
iOS Animate UIPicker height change
I have UITableView with static cells. I have set equal Content View height constraint equals to UIPicker view height. I have also implemented didSelectRowAt method with changing UITableViewCell content view.

https://youtu.be/lJuTLQ1oTaE

Magic happens, changing height of TableViewCell is animated. But the following change of UIPickerView height is happening simultaneously, with no animation. I have tried to put UIView.animate with layoutIfNeeded(), but it did not help.

How to animate such auto change of UIPickerView height?

```<code>// TableView functions
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        let reuseIdentifier = cell.reuseIdentifier
        guard reuseIdentifier != nil else {return}

    if reuseIdentifier == "currencyPickerTableViewCell" && self.selectedCellIndexPath == nil {
        self.skipCellsFromGestureRecognition.append(indexPath)
        self.selectedCellIndexPath = indexPath
        print(currencyPicker.constraints)
        tableView.beginUpdates()
        tableView.endUpdates()
    } else if reuseIdentifier == "currencyPickerTableViewCell" && self.selectedCellIndexPath != nil {
        self.selectedCellIndexPath = nil
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
    }
}
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if self.selectedCellIndexPath == indexPath {
        return self.selectedCellHeight
    } else {
        return self.unselectedCellHeight
    }
}
</code>```

答: The animation actually happens but as the font of the UIPicker stays the same you can't see it , so change the font inside UIView.animate , also note that your width of the picker is static so, number of trimmed characters will be increased as the font becomes larger . . .

Title: iOS Animate UIPicker height change

Body:
I have UITableView with static cells. I have set equal Content View height constraint equals to UIPicker view height. I have also implemented didSelectRowAt method with changing UITableViewCell content view.

https://youtu.be/lJuTLQ1oTaE

Magic happens, changing height of TableViewCell is animated. But the following change of UIPickerView height is happening simultaneously, with no animation. I have tried to put UIView.animate with layoutIfNeeded(), but it did not help.

How to animate such auto change of UIPickerView height?

// TableView functions
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        let reuseIdentifier = cell.reuseIdentifier
        guard reuseIdentifier != nil else {return}

    if reuseIdentifier == "currencyPickerTableViewCell" && self.selectedCellIndexPath == nil {
        self.skipCellsFromGestureRecognition.append(indexPath)
        self.selectedCellIndexPath = indexPath
        print(currencyPicker.constraints)
        tableView.beginUpdates()
        tableView.endUpdates()
    } else if reuseIdentifier == "currencyPickerTableViewCell" && self.selectedCellIndexPath != nil {
        self.selectedCellIndexPath = nil
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
    }
}
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if self.selectedCellIndexPath == indexPath {
        return self.selectedCellHeight
    } else {
        return self.unselectedCellHeight
    }
}


来源: stackexchange

问:
React-Native FlatList render a zero state when data is empty
Is it possible to render an alternate component when the data is empty?  The only reason I would not just render the list or not render the list is that the ListHeaderComponent is necessary in both scenarios (data.length and !data.length)...

```<code>const data = []
<FlatList
  contentContainerStyle={styles.list}
  data={data} // if empty or !data.length render <ZeroComponent/>
</code>```

答:
You can do something like this

{data.length > 0 ? <FlatList ... /> : <EmptyList />}

Hope it helps

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to render an alternate component when the data is empty?  The only reason I would not just render the list or not render the list is that the ListHeaderComponent is necessary in both scenarios (data.length and !data.length)...

const data = []
<FlatList
  contentContainerStyle={styles.list}
  data={data} // if empty or !data.length render <ZeroComponent/>

ContentLicense: CC BY-SA 3.0


问:
iOS Simulator Sound
Is there a way to tell the iOS simulator which audio device connected to your computer you want it to use?  </p>

<p>The simulator seems to pick whatever audio device is last connected to your machine.  I've got a USB audio device (fasttrack pro) I use for my main sound playback and then a USB headset I use for my skype calls.  More often than not, the simulator's audio is played on the headset instead of my  main speakers. </p>

答: I doubt the simulator has a setting for that, but you can set the main output device in System Preferences > Sound.</p>

ContentLicense: CC BY-SA 2.5

Title: iOS Simulator Sound

Body:
Is there a way to tell the iOS simulator which audio device connected to your computer you want it to use?

The simulator seems to pick whatever audio device is last connected to your machine.  I've got a USB audio device (fasttrack pro) I use for my main sound playback and then a USB headset I use for my skype calls.  More often than not, the simulator's audio is played on the headset instead of my  main speakers.


问:
Javascript passing var on click in a table
Trying to pass a variable when a
 in clicked, am getting "undefined".
Works if I remove the onclick="fnselect()" and use a submit button, which I don't want.

function highlight(e) {
  if (selected[0]) selected[0].className = '';
  e.target.parentNode.className = 'selected';
}

var table = document.getElementById('table'),
  selected = table.getElementsByClassName('selected');
table.onclick = highlight;

function fnselect(){
  var phpValue = $("tr.selected td:first" ).html();
  window.location.href = "http://website/test.php?phpValue="+phpValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table">
     <tr onclick="fnselect()">
      <td>1 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
     <tr onclick="fnselect()">
      <td>2 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
     <tr onclick="fnselect()">
      <td>3 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
    </table></code>```

答:
use Jquery which is flexible and easy to use

function fun1(elem){

var result=$(elem).find("td").first().text();
alert(result);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr onclick="fun1(this)">
<td>A</td>
<td>B</td>
</tr>
<tr onclick="fun1(this)">
<td>C</td>
<td>D</td>
</tr>
<table></code>```

Body:
Trying to pass a variable when a
 in clicked, am getting "undefined".
Works if I remove the onclick="fnselect()" and use a submit button, which I don't want.

function highlight(e) {
  if (selected[0]) selected[0].className = '';
  e.target.parentNode.className = 'selected';
}

var table = document.getElementById('table'),
  selected = table.getElementsByClassName('selected');
table.onclick = highlight;

function fnselect(){
  var phpValue = $("tr.selected td:first" ).html();
  window.location.href = "http://website/test.php?phpValue="+phpValue;
}

      1 Ferrari F138
      1 000€
      1 200€
      Model monopostu stajne Scuderia Ferrari pre sezónu 2013
      1
      F138
      Klik pre detaily

      2 Ferrari F138
      1 000€
      1 200€
      Model monopostu stajne Scuderia Ferrari pre sezónu 2013
      1
      F138
      Klik pre detaily

      3 Ferrari F138
      1 000€
      1 200€
      Model monopostu stajne Scuderia Ferrari pre sezónu 2013
      1
      F138
      Klik pre detaily

Body:
use Jquery which is flexible and easy to use

function fun1(elem){

var result=$(elem).find("td").first().text();
alert(result);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr onclick="fun1(this)">
<td>A</td>
<td>B</td>
</tr>
<tr onclick="fun1(this)">
<td>C</td>
<td>D</td>
</tr>
<table>


问:
Create a list of objects in acrobat using javascript not same as regular javascript?
I am trying to create a list of objects using javascript for an acrobat form. But the usual javascript code used does not work.
This is the code that I am using:

```<code>function updatePage1(totalRows)
{
    var B = [];

    var totalRows = 25;
    for(var i = 1; i <= 1; ++i)
    {
        app.alert(i);
        app.alert(this.getField("CostHead"+i.toString()).value);
        var costhead = this.getField("CostHead"+i.toString()).value;
        B.push({
            1 : { cost : 0.00, val: costhead }
        });

    }

    var valu = B[1].cost;
    app.alert(valu);
}
</code>```

Can anyone help ?

答:
There are two ways to fix this... If you MUST use the row number as the key and you have an array of objects, you're going to need to change the row number to a string.

```<code>function updatePage1(totalRows)
{
    var B = [];

    var totalRows = 25;
    for(var i = 1; i <= 1; ++i)
    {
        app.alert(i);
        app.alert(this.getField("CostHead"+i.toString()).value);
        var costhead = this.getField("CostHead"+i.toString()).value;
        B.push({
            "1" : { cost : 0.00, val: costhead }
        });

    }

    var valu = B["1"].cost;
    app.alert(valu);
}
</code>```

But a better fix is to ditch the row number altogether and just rely on the array order to get the object you need. Start your increment at 0.

```<code>function updatePage1(totalRows)
{
    var B = [];
    var totalRows = 25;
    for(var i = 0; i < totalRows; ++i)
    {
        app.alert(i);
        app.alert(this.getField("CostHead")+(i+1).toString()).value);
        var costhead = this.getField("CostHead"+(i+1).toString()).value;
        B.push({ cost : 0.00, val: costhead });
        var valu = B[i].cost;
        app.alert(valu);
    }
}
</code>```

Body:
I am trying to create a list of objects using javascript for an acrobat form. But the usual javascript code used does not work.
This is the code that I am using:

function updatePage1(totalRows)
{
    var B = [];

    var totalRows = 25;
    for(var i = 1; i <= 1; ++i)
    {
        app.alert(i);
        app.alert(this.getField("CostHead"+i.toString()).value);
        var costhead = this.getField("CostHead"+i.toString()).value;
        B.push({
            1 : { cost : 0.00, val: costhead }
        });

    }

    var valu = B[1].cost;
    app.alert(valu);
}

Can anyone help ?

Body:
There are two ways to fix this... If you MUST use the row number as the key and you have an array of objects, you're going to need to change the row number to a string.

function updatePage1(totalRows)
{
    var B = [];

    var totalRows = 25;
    for(var i = 1; i <= 1; ++i)
    {
        app.alert(i);
        app.alert(this.getField("CostHead"+i.toString()).value);
        var costhead = this.getField("CostHead"+i.toString()).value;
        B.push({
            "1" : { cost : 0.00, val: costhead }
        });

    }

    var valu = B["1"].cost;
    app.alert(valu);
}

But a better fix is to ditch the row number altogether and just rely on the array order to get the object you need. Start your increment at 0.

function updatePage1(totalRows)
{
    var B = [];
    var totalRows = 25;
    for(var i = 0; i < totalRows; ++i)
    {
        app.alert(i);
        app.alert(this.getField("CostHead")+(i+1).toString()).value);
        var costhead = this.getField("CostHead"+(i+1).toString()).value;
        B.push({ cost : 0.00, val: costhead });
        var valu = B[i].cost;
        app.alert(valu);
    }
}


问:
Trying to get permissions from printer, view as username not sid
I have a script to get permissions from printers on my printer server, but the output is returning SIDs, is there something that I can pipe in to get the user names as the output? I'll be doing this for multiple printers at a time so running each SID through a script to convert them is overly time consuming. Below is my script. </p>

```<code>(Get-Printer 'brem-pt-8106H' -Full).PermissionSDDL
</code>```

答:
Assumption: user exists in the domain

```<code>#Requires -Version 5
$SID = [System.Security.Principal.SecurityIdentifier]::new(
    (Get-Printer 'brem-pt-8106H' -Full).PermissionSDDL
)
$User = ($SID.Translate([System.Security.Principal.NTAccount])).Value
</code>```

Cleaned up as a function you can pipe to:

```<code>Function Get-UsernameFromSddl
{
    [CmdletBinding()]
    [OutputType([String])]
    Param(
        [Parameter(Mandatory,ValueFromPipeline,Position=0)]
        [String]$Sddl
    )

    $Sid = New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList $Sddl
    $User = $Sid.Translate([System.Security.Principal.NTAccount])

    Return $User.Value
}
</code>```

Body:
I have a script to get permissions from printers on my printer server, but the output is returning SIDs, is there something that I can pipe in to get the user names as the output? I'll be doing this for multiple printers at a time so running each SID through a script to convert them is overly time consuming. Below is my script.

(Get-Printer 'brem-pt-8106H' -Full).PermissionSDDL

Body:
Assumption: user exists in the domain

#Requires -Version 5
$SID = [System.Security.Principal.SecurityIdentifier]::new(
    (Get-Printer 'brem-pt-8106H' -Full).PermissionSDDL
)
$User = ($SID.Translate([System.Security.Principal.NTAccount])).Value

Cleaned up as a function you can pipe to:

Function Get-UsernameFromSddl
{
    [CmdletBinding()]
    [OutputType([String])]
    Param(
        [Parameter(Mandatory,ValueFromPipeline,Position=0)]
        [String]$Sddl
    )

    $Sid = New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList $Sddl
    $User = $Sid.Translate([System.Security.Principal.NTAccount])

    Return $User.Value
}


问:
finding if an anniversary is coming up in n days in MySql
I have a table with anniversary dates. I want a query that returns me rows of anniversaries coming up in the next 10 days. For instance:

```<code>birthdate
---------
1965-10-10
1982-05-25

SELECT birthdate FROM Anniversaries WHERE mystical_magical_mumbo_jumbo <= 10

+------------+
| birthdate  |
+------------+
| 1982-05-25 |
+------------+
1 row in set (0.01 sec)
</code>```

I'd like to keep the query in the form x <= 10, because I'll use that number 10 in other parts of the query, and if I set it to a variable, I can change it once everywhere by changing the variable, and not have to re-write the query.

答:
What we want to achieve is a list of anniversaries occurring in a recent date range.
To achieve this and to accommodate rollover we need to generate a list of all anniversaries that cover the date range.
The solution that I have used, generates anniversary records for last year, this year and next year
and outputs only those records that fall within the given date range.  The union query looks like this:

```<code>SELECT Date_Add(birth_date,INTERVAL (Year(now())-Year(birth_date)-1) YEAR) as dt,
FROM Anniversaries
WHERE Date_Add(birth_date,INTERVAL (Year(now())-Year(Date)-1) YEAR)
BETWEEN Date_sub(now(), INTERVAL 7 Day) AND Date_add(now(), INTERVAL 21 Day)
UNION
SELECT Date_Add(birth_date,INTERVAL (Year(now())-Year(birth_date)) YEAR) as dt,
FROM Anniversaries
WHERE Date_Add(birth_date,INTERVAL (Year(now())-Year(Date)) YEAR)
BETWEEN Date_sub(now(), INTERVAL 7 Day) AND Date_add(now(), INTERVAL 21 Day)
UNION
SELECT Date_Add(birth_date,INTERVAL (Year(now())-Year(birth_date)+1) YEAR) as dt,
FROM Anniversaries
WHERE Date_Add(birth_date,INTERVAL (Year(now())-Year(Date)+1) YEAR)
BETWEEN Date_sub(now(), INTERVAL 7 Day) AND Date_add(now(), INTERVAL 21 Day)
ORDER BY dt
</code>```

The first SELECT statement increments all the dates to last year and selects any items that fall into the date range provided
The next SELECT statement increments all the dates to the current year and selects any items that fall into the date range provided
The last SELECT statement increments all the dates to next year and selects any items that fall into the date range provided
Finally it is all ordered by date.

There you have it.  This will reliably select anniversaries in the given period.  If a longer period is required,
it may be necessary to generate additional SELECT statements and join them with UNION.
I have modified my code to match the example above but have not tested it since modification.

Body:
I have a table with anniversary dates. I want a query that returns me rows of anniversaries coming up in the next 10 days. For instance:

birthdate
---------
1965-10-10
1982-05-25

SELECT birthdate FROM Anniversaries WHERE mystical_magical_mumbo_jumbo <= 10

+------------+
| birthdate  |
+------------+
| 1982-05-25 |
+------------+
1 row in set (0.01 sec)

I'd like to keep the query in the form x <= 10, because I'll use that number 10 in other parts of the query, and if I set it to a variable, I can change it once everywhere by changing the variable, and not have to re-write the query.

Body:
What we want to achieve is a list of anniversaries occurring in a recent date range.
To achieve this and to accommodate rollover we need to generate a list of all anniversaries that cover the date range.
The solution that I have used, generates anniversary records for last year, this year and next year
and outputs only those records that fall within the given date range.  The union query looks like this:

SELECT Date_Add(birth_date,INTERVAL (Year(now())-Year(birth_date)-1) YEAR) as dt,
FROM Anniversaries
WHERE Date_Add(birth_date,INTERVAL (Year(now())-Year(Date)-1) YEAR)
BETWEEN Date_sub(now(), INTERVAL 7 Day) AND Date_add(now(), INTERVAL 21 Day)
UNION
SELECT Date_Add(birth_date,INTERVAL (Year(now())-Year(birth_date)) YEAR) as dt,
FROM Anniversaries
WHERE Date_Add(birth_date,INTERVAL (Year(now())-Year(Date)) YEAR)
BETWEEN Date_sub(now(), INTERVAL 7 Day) AND Date_add(now(), INTERVAL 21 Day)
UNION
SELECT Date_Add(birth_date,INTERVAL (Year(now())-Year(birth_date)+1) YEAR) as dt,
FROM Anniversaries
WHERE Date_Add(birth_date,INTERVAL (Year(now())-Year(Date)+1) YEAR)
BETWEEN Date_sub(now(), INTERVAL 7 Day) AND Date_add(now(), INTERVAL 21 Day)
ORDER BY dt

The first SELECT statement increments all the dates to last year and selects any items that fall into the date range provided
The next SELECT statement increments all the dates to the current year and selects any items that fall into the date range provided
The last SELECT statement increments all the dates to next year and selects any items that fall into the date range provided
Finally it is all ordered by date.

There you have it.  This will reliably select anniversaries in the given period.  If a longer period is required,
it may be necessary to generate additional SELECT statements and join them with UNION.
I have modified my code to match the example above but have not tested it since modification.


问:
Update Pivot Table Source Data
I'm sorry that this seems to be a duplicate question, but I've tried 2 separate methods and neither work. Here's the first:

```<code>Set wbGen = ThisWorkbook
Set wsPivot = wbGen.Sheets("Pivot")
Set rData = wbGen.Sheets("Fan Data").Range("A1")
Set rData = Range(rData, rData.End(xlDown).End(xlToRight))
NewRange = wbGen.Sheets("Fan Data").Name & "!" & _
    rData.Address(ReferenceStyle:=xlR1C1)
wsPivot.PivotTables("FanPivot").ChangePivotCache _
    wsPivot.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
</code>```

And here's the second:

```<code>Set wbGen = ThisWorkbook
Set wsPivot = wbGen.Sheets("Pivot")
Set rData = wbGen.Sheets("Fan Data").Range("A1")
Set rData = Range(rData, rData.End(xlDown).End(xlToRight))
wsPivot.PivotTables("FanPivot").ChangePivotCache _
    wsPivot.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rData)
</code>```

Both methods snag on the last line and return

Run Time Error 438: Object doesn't support method or property

答:
```<code>Set wbGen = ThisWorkbook
Set wsPivot = wbGen.Sheets("Pivot")
Set rData = wbGen.Sheets("Fan Data").Range("A1")
Set rData = Range(rData, rData.End(xlDown).End(xlToRight))
wsPivot.PivotTables("FanPivot").ChangePivotCache _
    wbGen.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rData)
</code>```

Title: Update Pivot Table Source Data

Body:
I'm sorry that this seems to be a duplicate question, but I've tried 2 separate methods and neither work. Here's the first:

Set wbGen = ThisWorkbook
Set wsPivot = wbGen.Sheets("Pivot")
Set rData = wbGen.Sheets("Fan Data").Range("A1")
Set rData = Range(rData, rData.End(xlDown).End(xlToRight))
NewRange = wbGen.Sheets("Fan Data").Name & "!" & _
    rData.Address(ReferenceStyle:=xlR1C1)
wsPivot.PivotTables("FanPivot").ChangePivotCache _
    wsPivot.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)

And here's the second:

Set wbGen = ThisWorkbook
Set wsPivot = wbGen.Sheets("Pivot")
Set rData = wbGen.Sheets("Fan Data").Range("A1")
Set rData = Range(rData, rData.End(xlDown).End(xlToRight))
wsPivot.PivotTables("FanPivot").ChangePivotCache _
    wsPivot.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rData)

Both methods snag on the last line and return

Run Time Error 438: Object doesn't support method or property


问:
jupyter notebook display cells horizontal

I have issues on jupyter notebook conversion. It looks fine on jupyter notebook. However if I convert it to html or upload to github, it displays like photo above.
Instead of vertical(scroll up and down), I have to scroll left and right and each cell are really narrowed.
Any suggestion?

Thanks in advance!

答:
This is typical of a library you use emitting invalid HTML. I would suggest opening an issue or contacting the Jupyter mailing list to help you debug this as StackOverflow will not be the right place to have a back and forth.

You should be able to narrow down which library does that by:
 - backup your notebook.
 - Delete cells one and until notebook looks normal. (tip use nbconvert locally instead of uploading, and use python -m http.server)
 - the last cell you delete have a issue.

It may be a bug in nbconvert but I doubt it.


问:
Google Drive API "watch"ing a folder, how to know what file was added
I have a test endpoint running and when I drop a file into the watched folder I get a request with the header X-Goog-Resource-State: update, but I don't seem to get an Id for the added file.

I get X-Goog-Resource-Id which I'd thought might be the new file, but I get a 404 if I try to get() it

I get X-Goog-Resource-Uri, but that belongs to the watched folder

I get an X-Goog-Channel-Id, but that clearly belongs to the channel not the file

And X-Request-Id, but that's just an opaque UUID

Am I required to fetch a complete list of files for the watched folder on every update and compare to a saved list? That doesn't feel right, but I'm at a loss.

Any guidance would be much appreciated.

答:
Is there any better way of doing this today?  After searching the Drive API Docs it doesn't appear that it has changed.

I'll throw another idea out there if it has not changed.  What I will probably end up doing is creating 2 folders, one for New Items and one for Processed Items.  I'll watch the New Items folder and when notified, I'll process any files in the folder and move them to the Processed Items folder.  Just personal preference on this one but I'd prefer not to change the files' properties or modify them in any way and I'd be a little paranoid that if I get them by time created I'd either process some files more than once or somehow one would get left out here or there.

It would be great to be able to receive notifications of added files including their IDs though!


问:
plot count of discrete data by date
I am new to ggplot2 and trying to plot a continuous histogram showing the evolution of reviews by date and rating.

My data set look like this:

```<code>        date rating reviews
1 2017-11-24      1 some text here
2 2017-11-24      1 some text here
3 2017-12-02      5 some text here
4 2017-11-24      3 some text here
5 2017-11-24      3 some text here
6 2017-11-24      4 some text here
</code>```

What I want to get is something like this:

for rating == 1

```<code>        date    count
1  2017-11-24      2
2  2017-11-25      7
.
.
.
</code>```

and so on for rating == 2 and 3

I've tried

```<code>ggplot(aes(x = date, y = rating), data = df) + geom_line()
</code>```

but it gives me only rating on the y axis and not counts:

答:
Just using some dummy data:</p>

```<code>  library(tidyverse)
  set.seed(999)
  df <- data.frame(date = sample(seq(as.Date('2017/01/01'), as.Date('2017/04/01'), by="day"), 2000, replace = T),
             rating = sample(1:5,2000,replace = T))
  df$rating <- as.factor(df$rating)

  df %>%
  group_by(date,rating) %>%
  summarise(n = length(rating)) %>%
  ggplot(aes(date,n, color = rating)) +
  geom_line() +
  geom_point()
</code>```

Title: plot count of discrete data by date

Body:
I am new to ggplot2 and trying to plot a continuous histogram showing the evolution of reviews by date and rating.

My data set look like this:

        date rating reviews
1 2017-11-24      1 some text here
2 2017-11-24      1 some text here
3 2017-12-02      5 some text here
4 2017-11-24      3 some text here
5 2017-11-24      3 some text here
6 2017-11-24      4 some text here

What I want to get is something like this:

for rating == 1

        date    count
1  2017-11-24      2
2  2017-11-25      7
.
.
.

and so on for rating == 2 and 3

I've tried

ggplot(aes(x = date, y = rating), data = df) + geom_line()

but it gives me only rating on the y axis and not counts:

Body:
Just using some dummy data:

  library(tidyverse)
  set.seed(999)
  df <- data.frame(date = sample(seq(as.Date('2017/01/01'), as.Date('2017/04/01'), by="day"), 2000, replace = T),
             rating = sample(1:5,2000,replace = T))
  df$rating <- as.factor(df$rating)

  df %>%
  group_by(date,rating) %>%
  summarise(n = length(rating)) %>%
  ggplot(aes(date,n, color = rating)) +
  geom_line() +
  geom_point()


问:
Filtering Moments in a PHAssetCollection
Using iOS 11 / Swift 4, I am trying to filter a collection of moments from a photo library.  I just want the Places.  Retrieving a collection of moments with nil options, I get 13 moments, with 8 moments having a non-nil title (location).  When I do the fetch moments with a simple predicate localizedTitle != nil, the result is always nil. Substituting an empty String ("") for the nil also yields an empty result.

Here is sample code and console results:

```<code>let momentOptions = PHFetchOptions()
momentOptions.predicate = NSPredicate(format:"localizedTitle != nil")
momentList = PHAssetCollection.fetchMoments(with: nil)
let momentListFiltered = PHAssetCollection.fetchMoments(with: momentOptions)
let assetCount = momentList.count

for index in 0...assetCount-1 {
    let a = momentList[index]
    let sta = a.localizedTitle
    let stb = a.localizedLocationNames
    print(index, sta ?? "--", stb)
}
</code>```

Results on Console:

```<code>0 -- []
1 -- []
2 Point Reyes National Seashore ["Point Reyes Station, CA"]
3 Þingeyjarsveit, Northeast Iceland ["Goðafossvegur"]
4 Djúpavogshreppur ["East Iceland"]
5 Rangárþing eystra ["South Iceland"]
6 New York - Washington Heights ["W 168th St"]
7 -- []
8 -- []
9 Jacksonville, NC ["Western Blvd"]
10 -- []
11 Locust Shade Park ["Triangle, VA"]
12 Piedmont Triad International Airport ["Friendship, NC"]

(lldb) po momentListFiltered
<PHFetchResult: 0x60c0002e2100> count=0
</code>```

finally, just to confirm the correct comparison:

```<code>p momentList[7].localizedTitle == nil
(Bool) $R2 = true
</code>```

答:
That does seem to be a bug or undocumented limitation in the Photos API. I would encourage you to submit a bug to Apple via the Bug Reporter.

You may find this alternate method useful:

```<code>let momentLists = PHCollectionList.fetchMomentLists(with: .momentListCluster, options: nil)
if momentLists.count > 0 {
    for index in 0...momentLists.count - 1 {
        let a = momentLists[index]
        print(index, a.localizedTitle ?? "--", a.localizedLocationNames)
    }
} else {
    print("-- No moment lists! --")
}
</code>```

This gets a list of moment clusters, which seems to group photos by place and time.

Body:
Using iOS 11 / Swift 4, I am trying to filter a collection of moments from a photo library.  I just want the Places.  Retrieving a collection of moments with nil options, I get 13 moments, with 8 moments having a non-nil title (location).  When I do the fetch moments with a simple predicate localizedTitle != nil, the result is always nil. Substituting an empty String ("") for the nil also yields an empty result.

Here is sample code and console results:

let momentOptions = PHFetchOptions()
momentOptions.predicate = NSPredicate(format:"localizedTitle != nil")
momentList = PHAssetCollection.fetchMoments(with: nil)
let momentListFiltered = PHAssetCollection.fetchMoments(with: momentOptions)
let assetCount = momentList.count

for index in 0...assetCount-1 {
    let a = momentList[index]
    let sta = a.localizedTitle
    let stb = a.localizedLocationNames
    print(index, sta ?? "--", stb)
}

Results on Console:

0 -- []
1 -- []
2 Point Reyes National Seashore ["Point Reyes Station, CA"]
3 Þingeyjarsveit, Northeast Iceland ["Goðafossvegur"]
4 Djúpavogshreppur ["East Iceland"]
5 Rangárþing eystra ["South Iceland"]
6 New York - Washington Heights ["W 168th St"]
7 -- []
8 -- []
9 Jacksonville, NC ["Western Blvd"]
10 -- []
11 Locust Shade Park ["Triangle, VA"]
12 Piedmont Triad International Airport ["Friendship, NC"]

(lldb) po momentListFiltered
<PHFetchResult: 0x60c0002e2100> count=0

finally, just to confirm the correct comparison:

p momentList[7].localizedTitle == nil
(Bool) $R2 = true

Body:
That does seem to be a bug or undocumented limitation in the Photos API. I would encourage you to submit a bug to Apple via the Bug Reporter.

You may find this alternate method useful:

let momentLists = PHCollectionList.fetchMomentLists(with: .momentListCluster, options: nil)
if momentLists.count > 0 {
    for index in 0...momentLists.count - 1 {
        let a = momentLists[index]
        print(index, a.localizedTitle ?? "--", a.localizedLocationNames)
    }
} else {
    print("-- No moment lists! --")
}

This gets a list of moment clusters, which seems to group photos by place and time.


问:
pandas drop values in a columns based other columns
Is there a way to drop a single entry in a df?

```<code>df1:
ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 4   15  6   25
113 6   7   4   10
114 3   8   2   1
115 7   1   8   10
</code>```

I want to drop any Value1 if Count1 < 5 and drop any Value2 if Count2 < 5.  The result would be like this:

```<code>ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 NA  NA  6   25
113 6   7   4   NA
114 NA  NA  NA  NA
115 7   1   8   10
</code>```

Thanks!

答:
Try this:

df1= df1[df1['Count1'] < 5 & df1['Count2'] < 5]

Body:
Is there a way to drop a single entry in a df?

df1:
ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 4   15  6   25
113 6   7   4   10
114 3   8   2   1
115 7   1   8   10

I want to drop any Value1 if Count1 < 5 and drop any Value2 if Count2 < 5.  The result would be like this:

ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 NA  NA  6   25
113 6   7   4   NA
114 NA  NA  NA  NA
115 7   1   8   10

Thanks!


问:
Can I use cognito AccessToken get Cognito identity ID?
I now use cognito user pool as “account system”, and also created a identity pool, Use IOS app I can make user sign up , sign in , get the account identity id, sync dataset and other operations.

Then I use Cognito user pool as Oauth2.0 server to achieve Alexa Smart Skill Account link, it has been able to achieve account login, get AccessToken. (I have a post in the Alexa forum, they reply I can only get AccessToken, https://forums.developer.amazon.com/questions/81362/get-id-token-from-alexa-request-when-account-link.html )

But according to my previous experience, if you want to visit Identity pool, get Identity ID, need ID_token, so I would like to ask, Is there a way I can get Id_Token or identity ID by AccessToken or user name?

```<code>AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-1:79abd6b8-f141-4756-9272-a09ed0671d1b',
    region: 'us-east-1',
    Logins:{
         'cognito-idp.us-east-1.amazonaws.com/us-east-1_S5kbwuSkN' : id_token
    }
});
</code>```

答: You can only use id_token to get identity id to visit an identity pool. To get id_token, you need to configure your app client in Cognito User Pool to have 'openid' as a scope. </p>

Body:
I now use cognito user pool as “account system”, and also created a identity pool, Use IOS app I can make user sign up , sign in , get the account identity id, sync dataset and other operations.

Then I use Cognito user pool as Oauth2.0 server to achieve Alexa Smart Skill Account link, it has been able to achieve account login, get AccessToken. (I have a post in the Alexa forum, they reply I can only get AccessToken, https://forums.developer.amazon.com/questions/81362/get-id-token-from-alexa-request-when-account-link.html )

But according to my previous experience, if you want to visit Identity pool, get Identity ID, need ID_token, so I would like to ask, Is there a way I can get Id_Token or identity ID by AccessToken or user name?

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-1:79abd6b8-f141-4756-9272-a09ed0671d1b',
    region: 'us-east-1',
    Logins:{
         'cognito-idp.us-east-1.amazonaws.com/us-east-1_S5kbwuSkN' : id_token
    }
});


问:
How to input a list of lists with different sizes in tf.data.Dataset
I have a long list of lists of integers (representing sentences, each one of different sizes) that I want to feed using the tf.data library. Each list (of the lists of list) has different length, and I get an error, which I can reproduce here:

```<code>t = [[4,2], [3,4,5]]
dataset = tf.data.Dataset.from_tensor_slices(t)
</code>```

The error I get is:

```<code>ValueError: Argument must be a dense tensor: [[4, 2], [3, 4, 5]] - got shape [2], but wanted [2, 2].
</code>```

Is there a way to do this?

EDIT 1: Just to be clear, I don't want to pad the input list of lists (it's a list of sentences containing over a million elements, with varying lengths) I want to use the tf.data library to feed, in a proper way, a list of lists with varying length.

答:
You can use tf.data.Dataset.from_generator() to convert any iterable Python object (like a list of lists) into a Dataset:

```<code>t = [[4, 2], [3, 4, 5]]

dataset = tf.data.Dataset.from_generator(lambda: t, tf.int32, output_shapes=[None])

iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()

with tf.Session() as sess:
  print(sess.run(next_element))  # ==> '[4, 2]'
  print(sess.run(next_element))  # ==> '[3, 4, 5]'
</code>```

Body:
I have a long list of lists of integers (representing sentences, each one of different sizes) that I want to feed using the tf.data library. Each list (of the lists of list) has different length, and I get an error, which I can reproduce here:

t = [[4,2], [3,4,5]]
dataset = tf.data.Dataset.from_tensor_slices(t)

The error I get is:

ValueError: Argument must be a dense tensor: [[4, 2], [3, 4, 5]] - got shape [2], but wanted [2, 2].

Is there a way to do this?

EDIT 1: Just to be clear, I don't want to pad the input list of lists (it's a list of sentences containing over a million elements, with varying lengths) I want to use the tf.data library to feed, in a proper way, a list of lists with varying length.

Body:
You can use tf.data.Dataset.from_generator() to convert any iterable Python object (like a list of lists) into a Dataset:

t = [[4, 2], [3, 4, 5]]

dataset = tf.data.Dataset.from_generator(lambda: t, tf.int32, output_shapes=[None])

iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()

with tf.Session() as sess:
  print(sess.run(next_element))  # ==> '[4, 2]'
  print(sess.run(next_element))  # ==> '[3, 4, 5]'


问:
pycharm packages not displayed in the project interpreter window
I am using pycharm 5.0.4 community edition.
I wanted to install package fuzzywuzzy.
But when i go to project interpreter window and try to install package, it shows me no available packages.
Can it be issue because I am using my work desktop.

Thanksenter image description here

答:
Below are some steps you can try, which worked for me:

Step-1 Activate your intelpython using:

```<code>source <your installation path>/bin/activate
</code>```

Step-2 Clone the environment using conda clone command and make sure the pwd is ~/:

```<code>conda create -n <source_environment> --clone <destination_environment>
</code>```

Step-3 Activate the cloned environment:

```<code>source ~/.conda/envs/<your_environment>/bin/activate
</code>```

Step-4 Provide read-wite permissions to intelpython and cloned enviroment using:

```<code>sudo chown -R <user_name>:<group_name> /<path_to_directory i.e. /opt/intel and ~/.conda/envs>
</code>```

Step-5 Open Pycharm and in System Interpreter add the path to above created enviroment and then you can use pip or Pycharm itself, it should work.

Body:
Below are some steps you can try, which worked for me:

Step-1 Activate your intelpython using:

source <your installation path>/bin/activate

Step-2 Clone the environment using conda clone command and make sure the pwd is ~/:

conda create -n <source_environment> --clone <destination_environment>

Step-3 Activate the cloned environment:

source ~/.conda/envs/<your_environment>/bin/activate

Step-4 Provide read-wite permissions to intelpython and cloned enviroment using:

sudo chown -R <user_name>:<group_name> /<path_to_directory i.e. /opt/intel and ~/.conda/envs>

Step-5 Open Pycharm and in System Interpreter add the path to above created enviroment and then you can use pip or Pycharm itself, it should work.


问:
Quickbooks SQL dump Code from QODBC
I need to extract Quickbooks SQL structure to make a Diagram about the tables that I need to work with. Could this be possible ?
I think QODC could solve my connection issue but I don't know how to extract SQL dump from it.

Thanks in advance

答: With QuickBooks Enterprise 2011 this changed, and you can have real ODBC access (although with limited rights and to a limited amount of tables) and then use an SQL tool to map via the ODBC access.</p>

Title: Quickbooks SQL dump Code from QODBC


问:
how to write to new files sequentially
I have a directory of files (files dir below) each with data that is being processed (and mixed with data from the initial file data/phrase.js) before the transformed data is written (actually appended) to new files in the output dir. My problem is that all of the data for each file is being written to file at the very end (after all the processing is complete). I would rather have the first file processed then written to disk, then the second file processed and written to disk etc, so that less data is held in memory. (Although very few files are involved in this example, in my actual application, there are many more files)

Question: Why is the data being written to file at the very end (once all of the files have been processed)? is there a way to write the data to file as soon as it is ready, rather than holding it all in memory until all the data for each file is ready?

```<code>    var fs = require('fs');
    //file with some data
    fs.readFile('./data/phrase.js', function(err, data){
        var somephrase = data.toString();
         //directory of many files
        fs.readdir('./files/', (err, files) => {
             files.forEach(file => {
                let f = './files/' + file;
                fs.readFile(f, (err, data2) => {
                    let somenumber = data2.toString();
                    //intermingle the data from initial file (phrase.js) with each of the files in files dir
                    let output = somenumber + somephrase;
                    //write output to new files
                    let output_file = './output/' + somenumber + 'js';
                    fs.appendFile(output_file, output,function(err){
                        if (err){
                                console.log("err")
                            }
                    });
                });
             });
        });
    });
</code>```

phrase.js

```<code>cow jumped over the moon
</code>```

files/one.js
1

files/two.js
2

output

```<code>output/1.js   (1 cow jumped over the moon)
output/2.js   (2 cow jumped over the moon)
</code>```

答:
Why is the data being written to file at the very end (once all of the files have been processed)?

Your loops are synchronous.  Your file operations are asynchronous.  As such, you run all your loops and start all the file operations and then they all run somewhat in parallel together so they all finish some time later.

is there a way to write the data to file as soon as it is ready, rather than holding it all in memory until all the data for each file is ready?

Using Promises and Await in ES6

To sequence your file writes, you have to write the asynchronous code differently.  With ES6, it's a bit easier using promises and await.  Here's an example:

```<code>const fs = require('fs');
const util = require('util');

// create promisified versions of fs methods we will use
const readFile = util.promisify(fs.readFile);
const readdir = util.promisify(fs.readdir);
const appendfile = util.promisify(fs.appendFile);

async function run() {
    let somephrase = await readFile('./data/phrase.js').toString();
    let files = await readdir('./files');
    for (let file of files) {
        try {
            let f = './files/' + file;
            let somenumber = await readFile(f).toString();
            //intermingle the data from initial file (phrase.js) with each of the files in files dir
            let output = somenumber + somephrase;
            //write output to new files
            let output_file = './output/' + somenumber + 'js';
            await appendFile(output_file, output);
        } catch(e) {
            console.log("error in loop", e);
        }
    }
}

run().then(() => {
   // all done here
}).catch(err => {
   // error occurred here
});
</code>```

Using Promises and .reduce() to serialize

If you wanted to do this without using await, you would have to manually sequence the operations.  A common design pattern for doing that with promises is to use .reduce() with chained promises.  The general pattern looks like this:

```<code>array.reduce((p, item) => {
    return p.then(() => {
        return fn(item);
    })
}, Promise.resolve().then(() => {
    // iteration all done here
}).catch(err => {
    // process error here
});
</code>```

Where:

fn(item) is your function that returns a promise that is called for each item in the array.  You can add more arguments to the function call if desired.

And, this pattern could be applied to your specific code like this:

```<code>const fs = require('fs');
const readFile = util.promisify(fs.readFile);
const readdir = util.promisify(fs.readdir);
const appendfile = util.pro

readFile('./data/phrase.js').then(data => {
    return data.toString();
}).then(somephrase => {
    return readdir('./files').then(files => {
        return files.reduce((p, file) => {
            return p.then(() => {
                let f = './files/' + file;
                return readFile(f).then(data => {
                    let output_file = './output/' + data.toString() + 'js';
                    let output = somenumber + somephrase;
                    return appendFile(output_file, output);
                });
            });
        }, Promise.resolve());
    });
}).then(() => {
   // all done here
}).catch(err => {
   // error occurred here
});
</code>```

Using Bluebird promise library

There is also a promise library called Bluebird that can make this a bit easier because it contains serialization features and promisification features:

```<code>const Promise = require('bluebird');
const fs = Promise.promsifyAll(require('fs'));

fs.readFileAsync('./data/phrase.js').then(data => {
    let somephrase = data.toString();
    return fs.readdirAsync('./files').then(files => {
        // iterate array serially
        return Promise.each(files, file => {
            let f = './files/' + file;
            return fs.readFileAsync(f).then(data => {
                let output_file = './output/' + data.toString() + 'js';
                let output = somenumber + somephrase;
                return fs.appendFileAsync(output_file, output);
            });
        });
    });
})
</code>```

Title: how to write to new files sequentially

Body:
I have a directory of files (files dir below) each with data that is being processed (and mixed with data from the initial file data/phrase.js) before the transformed data is written (actually appended) to new files in the output dir. My problem is that all of the data for each file is being written to file at the very end (after all the processing is complete). I would rather have the first file processed then written to disk, then the second file processed and written to disk etc, so that less data is held in memory. (Although very few files are involved in this example, in my actual application, there are many more files)

Question: Why is the data being written to file at the very end (once all of the files have been processed)? is there a way to write the data to file as soon as it is ready, rather than holding it all in memory until all the data for each file is ready?

    var fs = require('fs');
    //file with some data
    fs.readFile('./data/phrase.js', function(err, data){
        var somephrase = data.toString();
         //directory of many files
        fs.readdir('./files/', (err, files) => {
             files.forEach(file => {
                let f = './files/' + file;
                fs.readFile(f, (err, data2) => {
                    let somenumber = data2.toString();
                    //intermingle the data from initial file (phrase.js) with each of the files in files dir
                    let output = somenumber + somephrase;
                    //write output to new files
                    let output_file = './output/' + somenumber + 'js';
                    fs.appendFile(output_file, output,function(err){
                        if (err){
                                console.log("err")
                            }
                    });
                });
             });
        });
    });

phrase.js

cow jumped over the moon

files/one.js
1

files/two.js
2

output

output/1.js   (1 cow jumped over the moon)
output/2.js   (2 cow jumped over the moon)

Body:
Why is the data being written to file at the very end (once all of the files have been processed)?

Your loops are synchronous.  Your file operations are asynchronous.  As such, you run all your loops and start all the file operations and then they all run somewhat in parallel together so they all finish some time later.

is there a way to write the data to file as soon as it is ready, rather than holding it all in memory until all the data for each file is ready?

Using Promises and Await in ES6

To sequence your file writes, you have to write the asynchronous code differently.  With ES6, it's a bit easier using promises and await.  Here's an example:

const fs = require('fs');
const util = require('util');

// create promisified versions of fs methods we will use
const readFile = util.promisify(fs.readFile);
const readdir = util.promisify(fs.readdir);
const appendfile = util.promisify(fs.appendFile);

async function run() {
    let somephrase = await readFile('./data/phrase.js').toString();
    let files = await readdir('./files');
    for (let file of files) {
        try {
            let f = './files/' + file;
            let somenumber = await readFile(f).toString();
            //intermingle the data from initial file (phrase.js) with each of the files in files dir
            let output = somenumber + somephrase;
            //write output to new files
            let output_file = './output/' + somenumber + 'js';
            await appendFile(output_file, output);
        } catch(e) {
            console.log("error in loop", e);
        }
    }
}

run().then(() => {
   // all done here
}).catch(err => {
   // error occurred here
});

Using Promises and .reduce() to serialize

If you wanted to do this without using await, you would have to manually sequence the operations.  A common design pattern for doing that with promises is to use .reduce() with chained promises.  The general pattern looks like this:

array.reduce((p, item) => {
    return p.then(() => {
        return fn(item);
    })
}, Promise.resolve().then(() => {
    // iteration all done here
}).catch(err => {
    // process error here
});

Where:

fn(item) is your function that returns a promise that is called for each item in the array.  You can add more arguments to the function call if desired.

And, this pattern could be applied to your specific code like this:

const fs = require('fs');
const readFile = util.promisify(fs.readFile);
const readdir = util.promisify(fs.readdir);
const appendfile = util.pro

readFile('./data/phrase.js').then(data => {
    return data.toString();
}).then(somephrase => {
    return readdir('./files').then(files => {
        return files.reduce((p, file) => {
            return p.then(() => {
                let f = './files/' + file;
                return readFile(f).then(data => {
                    let output_file = './output/' + data.toString() + 'js';
                    let output = somenumber + somephrase;
                    return appendFile(output_file, output);
                });
            });
        }, Promise.resolve());
    });
}).then(() => {
   // all done here
}).catch(err => {
   // error occurred here
});

Using Bluebird promise library

There is also a promise library called Bluebird that can make this a bit easier because it contains serialization features and promisification features:

const Promise = require('bluebird');
const fs = Promise.promsifyAll(require('fs'));

fs.readFileAsync('./data/phrase.js').then(data => {
    let somephrase = data.toString();
    return fs.readdirAsync('./files').then(files => {
        // iterate array serially
        return Promise.each(files, file => {
            let f = './files/' + file;
            return fs.readFileAsync(f).then(data => {
                let output_file = './output/' + data.toString() + 'js';
                let output = somenumber + somephrase;
                return fs.appendFileAsync(output_file, output);
            });
        });
    });
})


问:
Regex to match "maybe valid month"
Basically I want to match the following:

```<code>const regex = /(?=.*[0-1])(?=.*[^0{2}])|(0[1-9]|1[012])$/
console.log('0, should be True: ', regex.test('0'))
console.log('1, should be True: ', regex.test('1'))
console.log('00, should be False: ', regex.test('00'))
console.log('01, should be True: ', regex.test('01'))
console.log('12, should be True: ', regex.test('12'))
console.log('99, should be False: ', regex.test('99'))
</code>```

Valid: 0, 1, 01-09, 10-12
Invalid: 00, >12

Anyone know how to do this?

答:
This will do:

```<code>const regex = /^([01]|0[1-9]|1[012])$/;
</code>```

That is, either of:

Single digit 0 or 1

0 followed by single digit 1 .. 9

1 followed by 0, 1 or 2

Output of your tests:

```<code>0, should be True:  true
1, should be True:  true
00, should be False:  false
01, should be True:  true
12, should be True:  true
99, should be False:  false
</code>```

Title: Regex to match "maybe valid month"

Body:
Basically I want to match the following:

const regex = /(?=.*[0-1])(?=.*[^0{2}])|(0[1-9]|1[012])$/
console.log('0, should be True: ', regex.test('0'))
console.log('1, should be True: ', regex.test('1'))
console.log('00, should be False: ', regex.test('00'))
console.log('01, should be True: ', regex.test('01'))
console.log('12, should be True: ', regex.test('12'))
console.log('99, should be False: ', regex.test('99'))

Valid: 0, 1, 01-09, 10-12
Invalid: 00, >12

Anyone know how to do this?

Body:
This will do:

const regex = /^([01]|0[1-9]|1[012])$/;

That is, either of:

Single digit 0 or 1

0 followed by single digit 1 .. 9

1 followed by 0, 1 or 2

Output of your tests:

0, should be True:  true
1, should be True:  true
00, should be False:  false
01, should be True:  true
12, should be True:  true
99, should be False:  false


问:
linear search on array of object c++
i have a problem with a function ..
I want the function to have two arguments ..
one will be a array of objects and the second one will be the code given by the user
and into the function to run a linear search and check if the user's code exists and if the code exists will return his position in the array else returns -1...

this is what i have try already:

```<code>int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
    if(pinPro[i].getPasswd()==pass)
    {
        found=true;
        return i;
    }
    else
        return -1;
    i++;

}
</code>```

}

i want the function return the position if password exist else return symbolic number -1

The problem is that the code return position only for the first element of array and for the 4 others element function return -1

答:
The else will always be activated if the element is not the first one in the array. you should delete it, and return -1 after the while.

```<code>int passwdSearch(Eidos pinPro[], int pass)
{
    int i=0;
    bool found;
    found=false;
    while(i<N && found==false)
    {
        if(pinPro[i].getPasswd()==pass)
        {
            found=true;
            return i;
        }
    }
    return -1;
}
</code>```

This way, if you pass through the whole array and you don't find the required element, then you would return -1.

Edit

And as NathanOliver mentioned, found is useless because you are returning anyways when you find an element. So the code becomes:

```<code>    int passwdSearch(Eidos pinPro[], int pass)
    {
        int i=0;
        while(i<N)
        {
            if(pinPro[i].getPasswd()==pass)
                return i;
            i++;
        }
        return -1;
    }
</code>```

Title: linear search on array of object c++

Body:
i have a problem with a function ..
I want the function to have two arguments ..
one will be a array of objects and the second one will be the code given by the user
and into the function to run a linear search and check if the user's code exists and if the code exists will return his position in the array else returns -1...

this is what i have try already:

int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
    if(pinPro[i].getPasswd()==pass)
    {
        found=true;
        return i;
    }
    else
        return -1;
    i++;

}

}

i want the function return the position if password exist else return symbolic number -1

The problem is that the code return position only for the first element of array and for the 4 others element function return -1

Body:
The else will always be activated if the element is not the first one in the array. you should delete it, and return -1 after the while.

int passwdSearch(Eidos pinPro[], int pass)
{
    int i=0;
    bool found;
    found=false;
    while(i<N && found==false)
    {
        if(pinPro[i].getPasswd()==pass)
        {
            found=true;
            return i;
        }
    }
    return -1;
}

This way, if you pass through the whole array and you don't find the required element, then you would return -1.

Edit

And as NathanOliver mentioned, found is useless because you are returning anyways when you find an element. So the code becomes:

    int passwdSearch(Eidos pinPro[], int pass)
    {
        int i=0;
        while(i<N)
        {
            if(pinPro[i].getPasswd()==pass)
                return i;
            i++;
        }
        return -1;
    }


问:
How to search in nested JSON data in vuejs?
I have nested JSON data like:

```<code>[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]
</code>```

I want to filter the JSON by province_id and put it in another variable. Is there any solutions in VueJS such as Vue.filter(); ?
I know we have "linq" which does the job but I do not want to use it.

答:
what you're looking for is the javascript Array's filter() function. You should definitely spend some time getting familiar with filter, along with others like map and reduce. It'll make slicing and dicing your data much easier.

```<code>var serializedData = `[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]`;
var data = JSON.parse(serializedData);

var provinceAbc = data.filter(d => d.province_id === 'ABC');
</code>```

That line will get you all objects where its province_id is "ABC"

Also, since you mentioned "linq" in your post, filter() is like IEnumerable.Where(), and map() is like IEnumerable.Select() in .NET Linq terms

Body:
I have nested JSON data like:

[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]

I want to filter the JSON by province_id and put it in another variable. Is there any solutions in VueJS such as Vue.filter(); ?
I know we have "linq" which does the job but I do not want to use it.

Body:
what you're looking for is the javascript Array's filter() function. You should definitely spend some time getting familiar with filter, along with others like map and reduce. It'll make slicing and dicing your data much easier.

var serializedData = `[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]`;
var data = JSON.parse(serializedData);

var provinceAbc = data.filter(d => d.province_id === 'ABC');

That line will get you all objects where its province_id is "ABC"

Also, since you mentioned "linq" in your post, filter() is like IEnumerable.Where(), and map() is like IEnumerable.Select() in .NET Linq terms


问:
Browser does not recoginize JQuery prettyPhoto() when using asp.net Masterpage
```<code><script src="Scripts/jquery.prettyPhoto.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>

<a href="http://www.youtube-nocookie.com/v/Bkjv9SscotY&hl=it_IT&fs=1?rel=0" rel="prettyPhoto" title="">you tube
</a>
<script type="text/javascript">

    $(document).ready(
function () {
    $(
"a[rel^='prettyPhoto']").prettyPhoto();
});

</script>
</code>```

答:
ResolveUrl is a good option but it is not the ideal solution it would be best if you use the correct path of the js. As you would be using friendly url's then take it from the root and use ~ sign it basically tell's the server to start from root of the folder so even though you have published the app earlier with one less folder lets say inetpub/wwwroot/AppName/WebUI/

and now changed it to inetpub/wwwroot/AppName/ your app wont crash and any time you get a similar error just open the source of the page on the browser and then click on your js file links if you are able to navigate to the js file great else there could be other scenario's like authentication is setup and iis is not allowing you to access it .

Body: you tube


问:
Using RAML to describe a JSON-RPC service over HTTPS
I am trying to use RAML to concretely describe various cryptocurrency exchange APIs who that all use a different format (non standardized) to present and document their API. I have had an easy time doing this for RESTful APIs (as that is mostly what RAML is for to my understanding) but am having a difficult time doing this for an API that uses JSON-RPC over https.

First off...is this possible and/or feasible?

If it is possible and/or feasible, is the following the correct way to do it? It seems to be limiting because I don't know of a way to enumerate the possible methods and their respective parameters, I can only declare that there is a method parameter.

As suggested by David Dossot, I tried using a JSON schema instead of queryParameters. Here is my attempt (I still do not see a way to enumerate/describe the individual methods of the API, I only have the power to express that there is a method keyword and it is a string (similar to the limitation I had with the queryParameters route).

```<code>#%RAML 0.8

title: BTC-China API
baseUri: https://data.btcchina.com/data/

baseUri: https://api.btcchina.com/api_trade_v1.php

/api_trade_v1.php:
  post:
    description: The JSON-RPC BTC-China API.
    headers:
      Authorization:
        description: |
          Blah blah

        example: Basic PGFjY2Vzc2tleT46PGhhc2g+
    body:
      application/json:
        schema: |
          {
           "$schema" : "http://json-schema.org/draft-04/schema#",
           "title": "JSON-RPC Request",
           "description" : "A JSON-RPC request to the BTC-China API.",

           "type" : "object",
           "required" : ["jsonrpc", "method"],
           "properties" : {
             "jsonrpc" : { "enum" : ["2.0"] },
             "method" : {
               "type" : "string"
              },
              "id" : {
                "type" : "number"
              },
              "params" : {
                "type" : ["array", "object"]
              }
            }
          }

    responses:
       200:
          body:
            application/json:
              example: |
                {"result":12345,"id":"1"}

        401:
          body:
            text/plain:
              example: 401 Unauthorized - invalid access key
</code>```

Now that I am using a schema, I still do not see a way that I can enumerate or describe the individual methods of the API.

Update 8/13/2014:

Attempt to use JSON $refs and sub-schemas (still running into an issue of how to link the method with its associated parameters and how to describe the method, etc. as the JSON Schema v4 only has 3 validation parameters for a string (the type that method is in JSON-RPC, it's not an object), maxLength, minLength, and pattern. None are expressive enough to explain what the method is/does and the option/available parameters for it)

```<code>body:
  application/json:
    schema: |
      {
       "$schema" : "http://json-schema.org/draft-04/schema#",
       "title": "JSON-RPC Request",
       "description" : "A JSON-RPC request to the BTC-China API.",

       "type" : "object",
       "required" : ["jsonrpc", "method"],
       "properties" : {
         "jsonrpc" : {
           "enum" : ["2.0"]
         },
         "method" : {
           "type" : "string",
           "oneOf" : [
               { "$ref": "#/definitions/getbalance" },
               { "$ref": "#/definitions/withdrawal" },
               { "$ref": "#/definitions/depositaddress" }
             ]
          },
          "id" : {
            "type" : "number"
          },
          "params" : {
            "type" : ["array", "object"]
          }
        }
        "definitions" : {
          "getbalance": {},
          "withdrawal": {},
          "depositaddress": {}
      }
</code>```

答:
You may describe your JSON RPC service with another one specifications:

https://en.wikipedia.org/wiki/JSON-WSP

http://www.simple-is-better.org/json-rpc/jsonrpc20-schema-service-descriptor.html

https://ru.wikipedia.org/wiki/WADL

RAML is very powerful and over engineering for common usage. How about using JSON-WSP for example?

Body:
I am trying to use RAML to concretely describe various cryptocurrency exchange APIs who that all use a different format (non standardized) to present and document their API. I have had an easy time doing this for RESTful APIs (as that is mostly what RAML is for to my understanding) but am having a difficult time doing this for an API that uses JSON-RPC over https.

First off...is this possible and/or feasible?

If it is possible and/or feasible, is the following the correct way to do it? It seems to be limiting because I don't know of a way to enumerate the possible methods and their respective parameters, I can only declare that there is a method parameter.

As suggested by David Dossot, I tried using a JSON schema instead of queryParameters. Here is my attempt (I still do not see a way to enumerate/describe the individual methods of the API, I only have the power to express that there is a method keyword and it is a string (similar to the limitation I had with the queryParameters route).

#%RAML 0.8

title: BTC-China API
baseUri: https://data.btcchina.com/data/

baseUri: https://api.btcchina.com/api_trade_v1.php

/api_trade_v1.php:
  post:
    description: The JSON-RPC BTC-China API.
    headers:
      Authorization:
        description: |
          Blah blah

        example: Basic PGFjY2Vzc2tleT46PGhhc2g+
    body:
      application/json:
        schema: |
          {
           "$schema" : "http://json-schema.org/draft-04/schema#",
           "title": "JSON-RPC Request",
           "description" : "A JSON-RPC request to the BTC-China API.",

           "type" : "object",
           "required" : ["jsonrpc", "method"],
           "properties" : {
             "jsonrpc" : { "enum" : ["2.0"] },
             "method" : {
               "type" : "string"
              },
              "id" : {
                "type" : "number"
              },
              "params" : {
                "type" : ["array", "object"]
              }
            }
          }

    responses:
       200:
          body:
            application/json:
              example: |
                {"result":12345,"id":"1"}

        401:
          body:
            text/plain:
              example: 401 Unauthorized - invalid access key

Now that I am using a schema, I still do not see a way that I can enumerate or describe the individual methods of the API.

Update 8/13/2014:

Attempt to use JSON $refs and sub-schemas (still running into an issue of how to link the method with its associated parameters and how to describe the method, etc. as the JSON Schema v4 only has 3 validation parameters for a string (the type that method is in JSON-RPC, it's not an object), maxLength, minLength, and pattern. None are expressive enough to explain what the method is/does and the option/available parameters for it)

body:
  application/json:
    schema: |
      {
       "$schema" : "http://json-schema.org/draft-04/schema#",
       "title": "JSON-RPC Request",
       "description" : "A JSON-RPC request to the BTC-China API.",

       "type" : "object",
       "required" : ["jsonrpc", "method"],
       "properties" : {
         "jsonrpc" : {
           "enum" : ["2.0"]
         },
         "method" : {
           "type" : "string",
           "oneOf" : [
               { "$ref": "#/definitions/getbalance" },
               { "$ref": "#/definitions/withdrawal" },
               { "$ref": "#/definitions/depositaddress" }
             ]
          },
          "id" : {
            "type" : "number"
          },
          "params" : {
            "type" : ["array", "object"]
          }
        }
        "definitions" : {
          "getbalance": {},
          "withdrawal": {},
          "depositaddress": {}
      }


问:
jqGrid. Checkbox SelectAll
How to programmatically in jqgrid to set the value (checked/not) of the SelectAll checkbox (see picture https://drive.google.com/open?id=1fEb1qaskPyz88uuqSCYscCiaCFdjktis).

How to know the status of the SelectAll checkbox without previous saving to a variable the result onSelectAll

答:
The id of the selectAll checkbox is combination of cb_ plus the id of the grid.

By example if the grid has id = jqGrid, then the id of the selectAll checkbox is cb_jqGrid

To change the status just trigger a click

```<code>var $selectall = $("#cb_jqGrid");
$selectall.click()
</code>```

to get the state use jQuery .is

```<code>if( $selectall.is(":checked") ) {
    alert("Is checked");
}
</code>```

Title: jqGrid. Checkbox SelectAll

Body:
The id of the selectAll checkbox is combination of cb_ plus the id of the grid.

By example if the grid has id = jqGrid, then the id of the selectAll checkbox is cb_jqGrid

To change the status just trigger a click

var $selectall = $("#cb_jqGrid");
$selectall.click()

to get the state use jQuery .is

if( $selectall.is(":checked") ) {
    alert("Is checked");
}


问:
Producing multiple joins with sqlalchemy statement and expression api
Consider you have the following sql to represent:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id

Now having the orm models as below:

```<code>from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    address_name = Column(String(64))
    user_id = Column(Integer)

class PostalCode(Base):
    __tablename__ = 'postal_code'
    id = Column(Integer, primary_key=True)
    code = Column(Integer)
</code>```

When doing simple join like:

```<code>from sqlalchemy import select, join
u = User
add = Address
po = PostalCode

query = select([u.id, u.name]).select_from(join(u,add, u.id = add.user_id))
print(query)
</code>```

Will yield eqvivalent expression to above original sql.

However if I want to do something like:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
JOIN postal_code ON postal_code.id = address.id

By writing:

```<code>query = select([u.id, u.name]).select_from(join(u,add, u.id = add.user_id).join(po, po.id = add.id))
print(query)
</code>```

This yield an error saying something like:

```<code>Attributeerror: type object ____ has no attribute '_from_objects`
</code>```

Any idea what is wrong with my syntax for using of two joins?

The explanation of how using one join is here.

答:
Consider predefined your foreign key fields and relationships with your models like this:

```<code>from sqlalchemy import Column, Integer, String, ForiegnKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    address = relationship('address')

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    address_name = Column(String(64))
    user_id = Column(Integer, ForeignKey('user.id'))
    postal_code = relationship('postal_code')

class PostalCode(Base):
    __tablename__ = 'postal_code'
    id = Column(Integer, ForeignKey('address.id'), primary_key=True)
    code = Column(Integer)
    address = relationship('address')

query = select(user.id, user.name).\
    join(address).\
    join(postal_code)

print(query)
</code>```

Running this should produce the query from the original post.

Then magically, you can stop using join in your selects all together!

```<code>query = select(user.name,
    user.address.address_name,
    user.address.postal_code.code)
</code>```

Body:
Consider you have the following sql to represent:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id

Now having the orm models as below:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    address_name = Column(String(64))
    user_id = Column(Integer)

class PostalCode(Base):
    __tablename__ = 'postal_code'
    id = Column(Integer, primary_key=True)
    code = Column(Integer)

When doing simple join like:

from sqlalchemy import select, join
u = User
add = Address
po = PostalCode

query = select([u.id, u.name]).select_from(join(u,add, u.id = add.user_id))
print(query)

Will yield eqvivalent expression to above original sql.

However if I want to do something like:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
JOIN postal_code ON postal_code.id = address.id

By writing:

query = select([u.id, u.name]).select_from(join(u,add, u.id = add.user_id).join(po, po.id = add.id))
print(query)

This yield an error saying something like:

Attributeerror: type object ____ has no attribute '_from_objects`

Any idea what is wrong with my syntax for using of two joins?

The explanation of how using one join is here.

Body:
Consider predefined your foreign key fields and relationships with your models like this:

from sqlalchemy import Column, Integer, String, ForiegnKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    address = relationship('address')

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    address_name = Column(String(64))
    user_id = Column(Integer, ForeignKey('user.id'))
    postal_code = relationship('postal_code')

class PostalCode(Base):
    __tablename__ = 'postal_code'
    id = Column(Integer, ForeignKey('address.id'), primary_key=True)
    code = Column(Integer)
    address = relationship('address')

query = select(user.id, user.name).\
    join(address).\
    join(postal_code)

print(query)

Running this should produce the query from the original post.

Then magically, you can stop using join in your selects all together!

query = select(user.name,
    user.address.address_name,
    user.address.postal_code.code)


问:
Writing into text file on web server using urllib/urllib3
I am wondering if there is a way to write into .txt file on web server using urllib or urllib3. I tried using urllib3 POST but that doesnt do anything. Does any of these libraries have ability to write into files or do I have to use some other library?

答:
It's not clear from your question, but I'm assuming that the Python code in question is not running on the web server. (Otherwise, it would be a matter of using the regular open() call.)

The answer is no, HTTP servers do not usually provide the ability to update files, and urllib does not support writing files over FTP / SCP.  You will need to be either running some sort of an upload service on the server that exposes an API over HTTP (via a POST entry point or otherwise) that allows you to make requests to the server in a way that causes the file to be updated on the server's filesystem.  Alternatively, you would need to use a protocol other than HTTP, such as FTP or SCP, and use an appropriate Python library for that protocol such as ftplib.


问:
Dask performances: workflow doubts
I'm confused about how to get the best from dask.

The problem
I have a dataframe which contains several timeseries (every one has its own key) and I need to run a function my_fun on every each of them. One way to solve it with pandas involves
df = list(df.groupby("key")) and then apply my_fun
 with multiprocessing. The performances, despite the huge usage of RAM, are pretty good on my machine and terrible on google cloud compute.

On Dask my current workflow is:

```<code>import dask.dataframe as dd
from dask.multiprocessing import get
</code>```

Read data from S3. 14 files -> 14 partitions

`df.groupby("key").apply(my_fun).to_frame.compute(get=get)

As I didn't set the indices df.known_divisions is False

The resulting graph is

and I don't understand if what I see it is a bottleneck or not.

Questions:

Is it better to have df.npartitions as a multiple of ncpu or it doesn't matter?

From this it seems that is better to set the index as key. My guess is that I can do something like

df["key2"] = df["key"]
df = df.set_index("key2")

but, again, I don't know if this is the best way to do it.

答:
For questions like "what is taking time" in Dask, you are generally recommended to use the "distributed" scheduler rather than multiprocessing - you can run with any number of processes/threads you like, but you have much more information available via the diagnostics dashboard.

For your specific questions, if you are grouping over a column that is not nicely split between partitions and applying anything other than the simple aggregations, you will inevitably need a shuffle. Setting the index does this shuffle for you as a explicit step, or you get the implicit shuffle apparent in your task graph. This is a many-to-many operation, each aggregation tasks needs input from every original partition, hence the bottle-neck. There is no getting around that.

As for number of partitions, yes you can have sub-optimal conditions like 9 partitions on 8 cores (you will calculate 8 tasks, and then perhaps block for the final task on one core while the others are idle); but in general you can depend on dask to make reasonable scheduling decisions so long as you are not using a very small number of partitions. In many cases, it will not matter much.

Title: Dask performances: workflow doubts

Body:
I'm confused about how to get the best from dask.

The problem
I have a dataframe which contains several timeseries (every one has its own key) and I need to run a function my_fun on every each of them. One way to solve it with pandas involves
df = list(df.groupby("key")) and then apply my_fun
 with multiprocessing. The performances, despite the huge usage of RAM, are pretty good on my machine and terrible on google cloud compute.

On Dask my current workflow is:

import dask.dataframe as dd
from dask.multiprocessing import get

Read data from S3. 14 files -> 14 partitions

`df.groupby("key").apply(my_fun).to_frame.compute(get=get)

As I didn't set the indices df.known_divisions is False

The resulting graph is

and I don't understand if what I see it is a bottleneck or not.

Questions:

Is it better to have df.npartitions as a multiple of ncpu or it doesn't matter?

From this it seems that is better to set the index as key. My guess is that I can do something like

df["key2"] = df["key"]
df = df.set_index("key2")

but, again, I don't know if this is the best way to do it.


问:
Angular 4 + RxJS filtering
I am trying to wrap my head around RxJS and I have a question.  To better understand how everything works, I started a new blank Angular 4 application generated with Angular CLI.  In it, I am running the following code:

this.http.get('./src/app/data/products.json')
    .map(res => res.json())
    .filter((item: any) => {
      let price = parseFloat(item.price);
      return price < 5.0 && price >= 2.5;
    })
    .subscribe((list: Array<ProductModel>) => {
      this.error = '';
      this.products = list;
    },
    error => {
      this.error = error;
    });```
</div>
</div>
</p>

<p>The problem is that filter receives the whole object as a parameter and I cannot filter the individual items.  Using RxJS in a non-angular solution, I used this code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let products = Observable.create(observer => {
    let xhr = new XMLHttpRequest();

    let onLoad = () => {
        let productsList = JSON.parse(xhr.responseText);
        observer.next(productsList);
        observer.complete();
    }

    xhr.addEventListener('load', onLoad);

    xhr.open('GET', 'products.json');
    xhr.send();

    return () => {
        console.log('cleanup');
        xhr.removeEventListener('load', onLoad);
        xhr.abort();
    }
})
.flatMap(Observable.from)
.filter(item => {
    let price = parseFloat(item.price);
    return price < 5.0 && price >= 2.5;
});

let subscr = products.subscribe(
    product => {
        let li = document.createElement('li');
        li.innerText = product.product_name + ' ' + product.price;
        list$.appendChild(li);
    },
    error => {
        console.log(`Error: ${error}`);
    },
    () => {
        console.log('complete');
        subscr.unsubscribe();
    }
);</code>```

The difference here is that I used flatMap, but if I try the same code in the Angular version I get:
Argument of type '{ (ish: ObservableInput, scheduler?: IScheduler): Observable; (ish: ArrayLike, ...' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.
  Types of parameters 'scheduler' and 'index' are incompatible.
    Type 'number' is not assignable to type 'IScheduler'.

I was just wondering why the same scenario produces different results.  Is Angular using a different flavor of RxJS?  What is the most efficient way to filter the results in the Angular version?

Thank you.

答:
The reason why your second implementation works is because of the from method. To better understand how this is all working, you first need to understand how from works. from takes in an iterable and emits each iteration one at a time. So for example, if you have

```<code>Observable.from([1, 2, 3]).subscribe(res => console.log('onNext: ', res));
</code>```

your output will be

```<code>// onNext: 1
// onNext: 2
// onNext: 3
</code>```

Now say we add the rxjs filter operator. The filter method is applied on each emitted value.

```<code>Observable.from([1, 2, 3])
    .filter(res => {
        console.log('filter: ', res);
        return res === 3; // we only want items that === 3 to continue to next step in sequence
    })
    .subscribe(res => console.log('onNext: ', res);
</code>```

your output will be

```<code>// filter: 1
// filter: 2
// filter: 3
// onNext: 3
</code>```

In your first implementation you are calling your json, and lets say it returns [1, 2, 3]. That entire array is passed to the rxjs filter method (Not each iteration). So you are checking your condition price < 5.0 && price >= 2.5 on the entire array, which you can't do.

The proper solution is to do a js filter method on your output

```<code>this.http.get('/./src/app/data/products.json')
    .map(res => {
        let data = res.json();
        return data.filter((item: any) => {
            let price = parseFloat(item.price);
            return price < 5.0 && price >= 2.5;
        });
    })
    .subscribe(list => {
        this.products = list;
    });
</code>```

TLDR: rxjs filter works the same as a native js filter, you just have to be aware of how your observable sequences emits so you know which one you should choose.

Title: Angular 4 + RxJS filtering

Body:
I am trying to wrap my head around RxJS and I have a question.  To better understand how everything works, I started a new blank Angular 4 application generated with Angular CLI.  In it, I am running the following code:

this.http.get('./src/app/data/products.json')
    .map(res => res.json())
    .filter((item: any) => {
      let price = parseFloat(item.price);
      return price < 5.0 && price >= 2.5;
    })
    .subscribe((list: Array<ProductModel>) => {
      this.error = '';
      this.products = list;
    },
    error => {
      this.error = error;
    });

The problem is that filter receives the whole object as a parameter and I cannot filter the individual items.  Using RxJS in a non-angular solution, I used this code:

let products = Observable.create(observer => {
    let xhr = new XMLHttpRequest();

    let onLoad = () => {
        let productsList = JSON.parse(xhr.responseText);
        observer.next(productsList);
        observer.complete();
    }

    xhr.addEventListener('load', onLoad);

    xhr.open('GET', 'products.json');
    xhr.send();

    return () => {
        console.log('cleanup');
        xhr.removeEventListener('load', onLoad);
        xhr.abort();
    }
})
.flatMap(Observable.from)
.filter(item => {
    let price = parseFloat(item.price);
    return price < 5.0 && price >= 2.5;
});

let subscr = products.subscribe(
    product => {
        let li = document.createElement('li');
        li.innerText = product.product_name + ' ' + product.price;
        list$.appendChild(li);
    },
    error => {
        console.log(`Error: ${error}`);
    },
    () => {
        console.log('complete');
        subscr.unsubscribe();
    }
);

The difference here is that I used flatMap, but if I try the same code in the Angular version I get:
Argument of type '{ (ish: ObservableInput, scheduler?: IScheduler): Observable; (ish: ArrayLike, ...' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.
  Types of parameters 'scheduler' and 'index' are incompatible.
    Type 'number' is not assignable to type 'IScheduler'.

I was just wondering why the same scenario produces different results.  Is Angular using a different flavor of RxJS?  What is the most efficient way to filter the results in the Angular version?

Thank you.

Body:
The reason why your second implementation works is because of the from method. To better understand how this is all working, you first need to understand how from works. from takes in an iterable and emits each iteration one at a time. So for example, if you have

Observable.from([1, 2, 3]).subscribe(res => console.log('onNext: ', res));

your output will be

// onNext: 1
// onNext: 2
// onNext: 3

Now say we add the rxjs filter operator. The filter method is applied on each emitted value.

Observable.from([1, 2, 3])
    .filter(res => {
        console.log('filter: ', res);
        return res === 3; // we only want items that === 3 to continue to next step in sequence
    })
    .subscribe(res => console.log('onNext: ', res);

your output will be

// filter: 1
// filter: 2
// filter: 3
// onNext: 3

In your first implementation you are calling your json, and lets say it returns [1, 2, 3]. That entire array is passed to the rxjs filter method (Not each iteration). So you are checking your condition price < 5.0 && price >= 2.5 on the entire array, which you can't do.

The proper solution is to do a js filter method on your output

this.http.get('/./src/app/data/products.json')
    .map(res => {
        let data = res.json();
        return data.filter((item: any) => {
            let price = parseFloat(item.price);
            return price < 5.0 && price >= 2.5;
        });
    })
    .subscribe(list => {
        this.products = list;
    });

TLDR: rxjs filter works the same as a native js filter, you just have to be aware of how your observable sequences emits so you know which one you should choose.


问:
compare value from arrayvalues in javascript
I have requirement in ServiceNow application that user has manager and that manager has another manager so i'am getting New Manager ( field in table) managers and storing in array.

I am trying to match that If login user ( user logged in ServiceNow) is one of the New Manager managers

Script:

```<code>var NewReportsTo  ='';
NewReportsTo = current.variables.new_manager;

var item = [];

    for ( var i =1 ; i<=6;i++){
        NewReportsTo = NewReportsTo.manager;
        var Newmanager = NewReportsTo.toString();
        item.push(Newmanager);
        //var list = item.split(',');
        gs.log('Check ACL:'+Newmanager, 'TEST ACL TCR');
        if(item.indexOf(gs.getUserID())){
            gs.log('Check ACL:'+current.sys_id, 'TEST ACL INSIDE TCR');
            answer = true;
        }

    }
</code>```

getUserID() is the login user and item array has all the manager for New manager field

答:
Array.indexOf() returns the first index at which the given item can be found in the array, or -1 if it's not found.

You should change your code to:

```<code>if(item.indexOf(gs.getUserID() != -1)){
   ...
}
</code>```

Body:
I have requirement in ServiceNow application that user has manager and that manager has another manager so i'am getting New Manager ( field in table) managers and storing in array.

I am trying to match that If login user ( user logged in ServiceNow) is one of the New Manager managers

Script:

var NewReportsTo  ='';
NewReportsTo = current.variables.new_manager;

var item = [];

    for ( var i =1 ; i<=6;i++){
        NewReportsTo = NewReportsTo.manager;
        var Newmanager = NewReportsTo.toString();
        item.push(Newmanager);
        //var list = item.split(',');
        gs.log('Check ACL:'+Newmanager, 'TEST ACL TCR');
        if(item.indexOf(gs.getUserID())){
            gs.log('Check ACL:'+current.sys_id, 'TEST ACL INSIDE TCR');
            answer = true;
        }

    }

getUserID() is the login user and item array has all the manager for New manager field

Body:
Array.indexOf() returns the first index at which the given item can be found in the array, or -1 if it's not found.

You should change your code to:

if(item.indexOf(gs.getUserID() != -1)){
   ...
}


问:
How to create a date within a Formula in Excel
So what I'm trying to do is create a formula that reflects off of two dates (Start date and end date), if its shorter than 49 days, Find the exact middle date, if it's greater than that number add 30 days to the start date. So far I have the formula down it looks like:

```<code>=IF(C3-B3>49,IF(B3+30<=C3,"Report Date: "&B3+30,"Report Date: "&C3),"Report Date: "&((C3-B3)/2)+B3)
</code>```

The C Column is the End Date, the B Column is the Start date. What currently comes out for example if the Start date is, 4/2/2017 and the end date is, 2/3/2018, It comes out with, Report Date: 42857

When I want it to actually come out as, 5/2/2017 instead. So how exactly do I go about doing this within the formula itself to automatically set the date for me?

Thanks in advance!

Maykid

答:
The key to this question is to understand how Excel handles dates. Dates in Excel are actually numbers where 1-jan-1900 = 1. Excel then takes a number and formats it as something more meaningful but it is still, in essence, a number. This way it doesn't matter what your regional setting the number always references the same day.

Excel usually recognizes these numbers, when they are on their own, to be dates and automatically formats them according to your regional settings or custom settings. 42857 with dd/mmm/yyy gives 02/May/2017 and with mm-d-yy it becomes 05-2-17

Wit that in mind if a date is included in a string (bit of text) Excel just sees a number and since it's not only a number but also a bit of text, the whole output is considered to be a string and excel cannot format a string like a date.

For this reason you need to enclose the bits in your code that generate the date in the TEXT formula. The TEXT formula takes the number and formats it accordingly and then spits it out as a string. For this reason, Excel can then no longer do any calculations with this text.

I think the formula for your case should be something like

```<code>=IF(C3-B3>49,IF(B3+30<=C3,"Report Date: "&TEXT(B3+30,"dd/mm/yy"),"Report Date: "&TEXT(C3,"dd/mm/yy")),"Report Date: "&TEXT(((C3-B3)/2)+B3,"dd/mm/yy"))
</code>```

You can alter the output format by altering the "dd/mm/yy" parts of the formula.

Body:
So what I'm trying to do is create a formula that reflects off of two dates (Start date and end date), if its shorter than 49 days, Find the exact middle date, if it's greater than that number add 30 days to the start date. So far I have the formula down it looks like:

=IF(C3-B3>49,IF(B3+30<=C3,"Report Date: "&B3+30,"Report Date: "&C3),"Report Date: "&((C3-B3)/2)+B3)

The C Column is the End Date, the B Column is the Start date. What currently comes out for example if the Start date is, 4/2/2017 and the end date is, 2/3/2018, It comes out with, Report Date: 42857

When I want it to actually come out as, 5/2/2017 instead. So how exactly do I go about doing this within the formula itself to automatically set the date for me?

Thanks in advance!

Maykid

Body:
The key to this question is to understand how Excel handles dates. Dates in Excel are actually numbers where 1-jan-1900 = 1. Excel then takes a number and formats it as something more meaningful but it is still, in essence, a number. This way it doesn't matter what your regional setting the number always references the same day.

Excel usually recognizes these numbers, when they are on their own, to be dates and automatically formats them according to your regional settings or custom settings. 42857 with dd/mmm/yyy gives 02/May/2017 and with mm-d-yy it becomes 05-2-17

Wit that in mind if a date is included in a string (bit of text) Excel just sees a number and since it's not only a number but also a bit of text, the whole output is considered to be a string and excel cannot format a string like a date.

For this reason you need to enclose the bits in your code that generate the date in the TEXT formula. The TEXT formula takes the number and formats it accordingly and then spits it out as a string. For this reason, Excel can then no longer do any calculations with this text.

I think the formula for your case should be something like

=IF(C3-B3>49,IF(B3+30<=C3,"Report Date: "&TEXT(B3+30,"dd/mm/yy"),"Report Date: "&TEXT(C3,"dd/mm/yy")),"Report Date: "&TEXT(((C3-B3)/2)+B3,"dd/mm/yy"))

You can alter the output format by altering the "dd/mm/yy" parts of the formula.