答:
Try:

```<code>for i in range(0,j):
</code>```

Instead of:

```<code>for i in range(0,N[j]):
</code>```

Since N[j] will access way beyond whats in the list, such as N[80], which doesn't exist. This is why you're getting a IndexError: list index out of range error.

To fix this, you need to apply range() on your outer loop:

```<code>for i in range(len(N)):
    print(i)
    for j in range(0, N[i]):
        print(j)
</code>```

Which only looks at the indexes i of N when applying it to range() in the inner loop, instead of the actual elements, which are a lot larger.

If you want to access whats actually in the list with respect to an index, try this:

```<code>N = [20,40,60,80]
for i in range(len(N)):
    print(i, "->", N[i])
</code>```

Which outputs:

```<code>0 -> 20
1 -> 40
2 -> 60
3 -> 80
</code>```

If you want just the numbers:

```<code>for number in N:
    print(number)
</code>```

If you want both the index and the number in a more pythonic manner:

```<code>for index, number in enumerate(N):
    print(index, "->", number)
</code>```

Which outputs:

```<code>0 -> 20
1 -> 40
2 -> 60
3 -> 80
</code>```

Title: List index out of range error on simple python for loop

Body:
Try:

for i in range(0,j):

Instead of:

for i in range(0,N[j]):

Since N[j] will access way beyond whats in the list, such as N[80], which doesn't exist. This is why you're getting a IndexError: list index out of range error.

To fix this, you need to apply range() on your outer loop:

for i in range(len(N)):
    print(i)
    for j in range(0, N[i]):
        print(j)

Which only looks at the indexes i of N when applying it to range() in the inner loop, instead of the actual elements, which are a lot larger.

If you want to access whats actually in the list with respect to an index, try this:

N = [20,40,60,80]
for i in range(len(N)):
    print(i, "->", N[i])

Which outputs:

0 -> 20
1 -> 40
2 -> 60
3 -> 80

If you want just the numbers:

for number in N:
    print(number)

If you want both the index and the number in a more pythonic manner:

for index, number in enumerate(N):
    print(index, "->", number)

Which outputs:

0 -> 20
1 -> 40
2 -> 60
3 -> 80


来源: stackexchange

问:
Download file for offline use Cordova/PhoneGap build
I'm a novice when it comes to the development of apps. I made a simple audio player app for android and iOS and build it with phonegap build.

The app uses the <audio> html tag to load mp3 files that are located on a remote server like so:

```<code>            <div class="mobileui-music-cover-controls">
    <audio ontimeupdate="udpateProgress()" id="player">
        <source src="http://www.myserver.com/audiofile.mp3" type="audio/mpeg">
    </audio>
            <a id="playKnop" href="JavaScript:playMusic()" class="play"><i class="ion-ios-play"></i></a>
            <a id="pauseKnop" href="JavaScript:pauseMusic()" class="play"><i class="ion-ios-pause"></i></a>
        </div>
</code>```

obviously, I changed the scr for this example.

It works fine as long as you have a stable internet connection but a few people are experiencing connection drops etc.
I would like to make the files offline available on user request. So it has to be optional (by clicking a button or something like that).
The app should detect if the file is present on the device and if so choose the local file over the remote file.

In short, I have 2 questions.

How can I download a specific file on user request?

How can I check whether the file is there or not and play the right file?

I can't seem to figure out how to do this I'm working on it for the last couple of days but I honestly have no clue on how to achieve this. Any help would be greatly appreciated.

答:
As you said you need to download the file to your device. Since your using cordova you could use fileTransfer to download the audio. This is very straight forward (this is the offical example code):

```<code>// !! Assumes variable fileURL contains a valid URL to a path on the device,
//    for example, cdvfile://localhost/persistent/path/to/downloads/

var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");

fileTransfer.download(
    uri,
    fileURL,
    function(entry) {
        console.log("download complete: " + entry.toURL());
    },
    function(error) {
        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("download error code" + error.code);
    },
    false,
    {
        headers: {
            "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
        }
    }
);
</code>```

The next time you want to play the audio you need to check if there is a local version. Either you check your device if that file exists (there are many ways, e.g. Cordova check if file in url exists) or you make use of something like localStorage which basically is a simple lil database.

```<code>// more or less pseudo code!!!

// callback from fileTransfer when your file was downloaded
function downloadSuccess(entry) {
    // save it to localStorage
    // key: the remote URL, value: the local URL
    localStorage.setItem(remoteURL, entry.toURL());
}

...
...

// the check if there is a cached file
var remoteSrc = "http://www.myserver.com/audiofile.mp3";
var localSrc = localStorage.getItem(remoteSrc);

if(localSrc === null) {
    // when there is NO cached version, use remote
    audioElement.src = remoteSrc;
} else {
    // when there IS a cached version, use local
    audioElement.src = localSrc;
}
</code>```

I hope this helps and gives you an idea how to accomplish simple caching yourself :)

ContentLicense: CC BY-SA 3.0

Body:
I'm a novice when it comes to the development of apps. I made a simple audio player app for android and iOS and build it with phonegap build.

The app uses the <audio> html tag to load mp3 files that are located on a remote server like so:

    <audio ontimeupdate="udpateProgress()" id="player">
        <source src="http://www.myserver.com/audiofile.mp3" type="audio/mpeg">
    </audio>

obviously, I changed the scr for this example.

It works fine as long as you have a stable internet connection but a few people are experiencing connection drops etc.
I would like to make the files offline available on user request. So it has to be optional (by clicking a button or something like that).
The app should detect if the file is present on the device and if so choose the local file over the remote file.

In short, I have 2 questions.

How can I download a specific file on user request?

How can I check whether the file is there or not and play the right file?

I can't seem to figure out how to do this I'm working on it for the last couple of days but I honestly have no clue on how to achieve this. Any help would be greatly appreciated.

Body:
As you said you need to download the file to your device. Since your using cordova you could use fileTransfer to download the audio. This is very straight forward (this is the offical example code):

// !! Assumes variable fileURL contains a valid URL to a path on the device,
//    for example, cdvfile://localhost/persistent/path/to/downloads/

var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");

fileTransfer.download(
    uri,
    fileURL,
    function(entry) {
        console.log("download complete: " + entry.toURL());
    },
    function(error) {
        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("download error code" + error.code);
    },
    false,
    {
        headers: {
            "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
        }
    }
);

The next time you want to play the audio you need to check if there is a local version. Either you check your device if that file exists (there are many ways, e.g. Cordova check if file in url exists) or you make use of something like localStorage which basically is a simple lil database.

// more or less pseudo code!!!

// callback from fileTransfer when your file was downloaded
function downloadSuccess(entry) {
    // save it to localStorage
    // key: the remote URL, value: the local URL
    localStorage.setItem(remoteURL, entry.toURL());
}

...
...

// the check if there is a cached file
var remoteSrc = "http://www.myserver.com/audiofile.mp3";
var localSrc = localStorage.getItem(remoteSrc);

if(localSrc === null) {
    // when there is NO cached version, use remote
    audioElement.src = remoteSrc;
} else {
    // when there IS a cached version, use local
    audioElement.src = localSrc;
}

I hope this helps and gives you an idea how to accomplish simple caching yourself :)


问:
Animate the fractionComplete of UIViewPropertyAnimator for blurring the background
So I'm using the new UIViewPropertyAnimator and UIVisualEffectView to achieve the same thing as the Spotlight search when you scrolling down on the home screen and it blurs the background.

I'm using the fractionComplete property to set the procent of how much to blur when panning a UIView.

```<code>    animator = UIViewPropertyAnimator(duration: 1, curve: .linear) {
        self.blurEffectView.effect = nil
    }
</code>```

And the amount of blurriness is changed with a value between 0.0 - 1.0.

```<code>        animator?.fractionComplete = blurValue
</code>```

But when I cancel the pan gesture I want the blur to animate back from where it is to no blur (e.g ~ -> 1.0) with a duration of something like 0.4 milliseconds.

Right now I just set the fractionComplete to 1.0 when the pan gesture is cancelled. Instead I want to animate it.

I have tried the UIView.animate(withDuration.. but it doesn't affect the UIViewPropertyAnimators fractionComplete, and thats the only way to blur an UIVisualEffectView.

Any ideas?

答: If you're still looking for a way to actually animate fractionComplete without the use of a slider or a gesture, I was quite happy with my results using a CADisplayLink. You can see my results here: https://gist.github.com/vegather/07993d15c83ffcd5182c8c27f1aa600b</p>

Body:
So I'm using the new UIViewPropertyAnimator and UIVisualEffectView to achieve the same thing as the Spotlight search when you scrolling down on the home screen and it blurs the background.

I'm using the fractionComplete property to set the procent of how much to blur when panning a UIView.

    animator = UIViewPropertyAnimator(duration: 1, curve: .linear) {
        self.blurEffectView.effect = nil
    }

And the amount of blurriness is changed with a value between 0.0 - 1.0.

        animator?.fractionComplete = blurValue

But when I cancel the pan gesture I want the blur to animate back from where it is to no blur (e.g ~ -> 1.0) with a duration of something like 0.4 milliseconds.

Right now I just set the fractionComplete to 1.0 when the pan gesture is cancelled. Instead I want to animate it.

I have tried the UIView.animate(withDuration.. but it doesn't affect the UIViewPropertyAnimators fractionComplete, and thats the only way to blur an UIVisualEffectView.

Any ideas?


问:
Dependency between fields in model using Factoryboy
I have a Django Model that I would like to test using Factoryboy.

The issue here is that the fields depend on each other.

```<code>class SearchPreferences(models.Model):
    min_age = models.PositiveSmallIntegerField(null=True)
    max_age = models.PositiveSmallIntegerField(null=True)
</code>```

In this case, max_age cannot be smaller then min_age.

```<code>class SearchPreferencesFactory(DjangoModelFactory):
    min_age = FuzzyInteger(30, 90)
    max_age = FuzzyInteger(SelfAttribute('min_age'), 100)
</code>```

This is what I have tried to do, which should give me a value for max_age between min_age and 100, but what happens is a TypeError:

```<code>TypeError: unsupported operand type(s) for +: 'SelfAttribute' and 'int'
</code>```

This makes sense to me, but I can't really figure out how to get this to work?

Could someone explain what would be the best approach here?

答:
You could use a LazyAttribute on your max_age, ie:</p>

```<code>class SearchPreferencesFactory(DjangoModelFactory):
    min_age = FuzzyInteger(30, 90)
    max_age = LazyAttribute(lambda x: FuzzyInteger(x.min_age, 100).fuzz())
</code>```

Body:
I have a Django Model that I would like to test using Factoryboy.

The issue here is that the fields depend on each other.

class SearchPreferences(models.Model):
    min_age = models.PositiveSmallIntegerField(null=True)
    max_age = models.PositiveSmallIntegerField(null=True)

In this case, max_age cannot be smaller then min_age.

class SearchPreferencesFactory(DjangoModelFactory):
    min_age = FuzzyInteger(30, 90)
    max_age = FuzzyInteger(SelfAttribute('min_age'), 100)

This is what I have tried to do, which should give me a value for max_age between min_age and 100, but what happens is a TypeError:

TypeError: unsupported operand type(s) for +: 'SelfAttribute' and 'int'

This makes sense to me, but I can't really figure out how to get this to work?

Could someone explain what would be the best approach here?

Body:
You could use a LazyAttribute on your max_age, ie:

class SearchPreferencesFactory(DjangoModelFactory):
    min_age = FuzzyInteger(30, 90)
    max_age = LazyAttribute(lambda x: FuzzyInteger(x.min_age, 100).fuzz())


问:
Avoiding having Swing Highlighters spill into newly added text
I am implementing a simple highlighter over a JTextPane. I want it to highlight special keywords such as if, case, etc as I type them. As IDEs do.

The problem I'm facing is that when I detect a special keyword was just written and I highlight it (this does work well) then everything I type afterwards is also highlighted. Looking at the API I would assume this would not be the case. How to avoid this?

Here's the offending code:

```<code>if (word.equals("if")) {
    textPane.getHighlighter().addHighlight(wordStartIdx, pos+1, highlightPainter);
    textPane.getHighlighter().addHighlight(pos+2, pos+2, noHightlighter); // tried this to see if it would help, but it doesn't change anything.. anything typed after the word "if" will still be hightlighted!
}
</code>```

Thanks

答:
Instead of using a Highlighter you can try using attributes:</p>

```<code>SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setForeground(green, Color.GREEN);

//  Change attributes on some existing text

StyledDocument doc = textPane.getStyledDocument();
int offset = textPane.getCaretPosition(); // should be after the "f"
doc.setCharacterAttributes(offset-2, 2, green, false);
</code>```

Body:
I am implementing a simple highlighter over a JTextPane. I want it to highlight special keywords such as if, case, etc as I type them. As IDEs do.

The problem I'm facing is that when I detect a special keyword was just written and I highlight it (this does work well) then everything I type afterwards is also highlighted. Looking at the API I would assume this would not be the case. How to avoid this?

Here's the offending code:

if (word.equals("if")) {
    textPane.getHighlighter().addHighlight(wordStartIdx, pos+1, highlightPainter);
    textPane.getHighlighter().addHighlight(pos+2, pos+2, noHightlighter); // tried this to see if it would help, but it doesn't change anything.. anything typed after the word "if" will still be hightlighted!
}

Thanks

Body:
Instead of using a Highlighter you can try using attributes:

SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setForeground(green, Color.GREEN);

//  Change attributes on some existing text

StyledDocument doc = textPane.getStyledDocument();
int offset = textPane.getCaretPosition(); // should be after the "f"
doc.setCharacterAttributes(offset-2, 2, green, false);


问:
Cassandra gives no data even if data exists
I have a keyspace with replication factor of 3. I am inserting data into Cassandra (4 node cluster with single data center) with write consistency level one. After completion of insertions I am reading data with consistency level quorum (2). But I am not getting data sometimes even if data exists, after some time I am getting data with same query. I don't know why Cassandra behaves like this.

My column family schema

```<code>CREATE TABLE input_data_profile.input_log_profile_1 (
    cid text,
    ctdon bigint,
    ctdat bigint,
    email text,
    addrs set<frozen<udt_addrs>>,
    asset set<frozen<udt_asset>>,
    cntno set<frozen<udt_cntno>>,
    dob frozen<udt_date>,
    dvc set<frozen<udt_dvc>>,
    eaka set<text>,
    edmn text,
    educ set<frozen<udt_educ>>,
    gen tinyint,
    hobby set<text>,
    income set<frozen<udt_income>>,
    interest set<text>,
    lang set<frozen<udt_lang>>,
    levnt set<frozen<udt_levnt>>,
    like map<text, frozen<set<text>>>,
    loc set<frozen<udt_loc>>,
    mapp set<text>,
    name frozen<udt_name>,
    params map<text, frozen<set<text>>>,
    prfsn set<frozen<udt_prfsn>>,
    rel set<frozen<udt_rel>>,
    rel_s tinyint,
    skills_prfsn set<frozen<udt_skill_prfsn>>,
    snw set<frozen<udt_snw>>,
    sport set<text>,
    status tinyint,
    z_addrs tinyint,
    z_asset tinyint,
    z_cntno tinyint,
    z_dob tinyint,
    z_dvc tinyint,
    z_eaka tinyint,
    z_educ tinyint,
    z_email tinyint,
    z_gen tinyint,
    z_hobby tinyint,
    z_income tinyint,
    z_interest tinyint,
    z_lang tinyint,
    z_levnt tinyint,
    z_like tinyint,
    z_loc tinyint,
    z_mapp tinyint,
    z_name tinyint,
    z_params tinyint,
    z_prfsn tinyint,
    z_rel tinyint,
    z_rel_s tinyint,
    z_skills_prfsn tinyint,
    z_snw tinyint,
    z_sport tinyint,
    PRIMARY KEY (cid, ctdon, ctdat, email)
) WITH CLUSTERING ORDER BY (ctdon ASC, ctdat ASC, email ASC)
CREATE INDEX input_log_profile_1_z_snw_idx ON input_data_profile.input_log_profile_1 (z_snw);
CREATE INDEX input_log_profile_1_z_prfsn_idx ON input_data_profile.input_log_profile_1 (z_prfsn);
CREATE INDEX input_log_profile_1_z_hobby_idx ON input_data_profile.input_log_profile_1 (z_hobby);
CREATE INDEX input_log_profile_1_z_rel_idx ON input_data_profile.input_log_profile_1 (z_rel);
CREATE INDEX input_log_profile_1_z_gen_idx ON input_data_profile.input_log_profile_1 (z_gen);
CREATE INDEX input_log_profile_1_z_mapp_idx ON input_data_profile.input_log_profile_1 (z_mapp);
CREATE INDEX input_log_profile_1_z_dvc_idx ON input_data_profile.input_log_profile_1 (z_dvc);
CREATE INDEX input_log_profile_1_z_skills_prfsn_idx ON input_data_profile.input_log_profile_1 (z_skills_prfsn);
CREATE INDEX input_log_profile_1_z_eaka_idx ON input_data_profile.input_log_profile_1 (z_eaka);
CREATE INDEX input_log_profile_1_z_name_idx ON input_data_profile.input_log_profile_1 (z_name);
CREATE INDEX input_log_profile_1_z_cntno_idx ON input_data_profile.input_log_profile_1 (z_cntno);
CREATE INDEX input_log_profile_1_z_educ_idx ON input_data_profile.input_log_profile_1 (z_educ);
CREATE INDEX input_log_profile_1_z_loc_idx ON input_data_profile.input_log_profile_1 (z_loc);
CREATE INDEX input_log_profile_1_z_email_idx ON input_data_profile.input_log_profile_1 (z_email);
CREATE INDEX input_log_profile_1_z_interest_idx ON input_data_profile.input_log_profile_1 (z_interest);
CREATE INDEX input_log_profile_1_z_asset_idx ON input_data_profile.input_log_profile_1 (z_asset);
CREATE INDEX input_log_profile_1_z_like_idx ON input_data_profile.input_log_profile_1 (z_like);
CREATE INDEX input_log_profile_1_z_rel_s_idx ON input_data_profile.input_log_profile_1 (z_rel_s);
CREATE INDEX input_log_profile_1_z_lang_idx ON input_data_profile.input_log_profile_1 (z_lang);
CREATE INDEX input_log_profile_1_z_addrs_idx ON input_data_profile.input_log_profile_1 (z_addrs);
CREATE INDEX input_log_profile_1_z_dob_idx ON input_data_profile.input_log_profile_1 (z_dob);
CREATE INDEX input_log_profile_1_z_income_idx ON input_data_profile.input_log_profile_1 (z_income);
CREATE INDEX input_log_profile_1_z_sport_idx ON input_data_profile.input_log_profile_1 (z_sport);
CREATE INDEX input_log_profile_1_z_params_idx ON input_data_profile.input_log_profile_1 (z_params);
</code>```

I need to process fields wise so I indexed the every field status. I want to improve the read and write tps. Suggest me some modifications in schema.

答:
If I understand you correctly then you are really asking two questions here:

First, you are writing data with a CL=1 and reading it with a CL=Quorum and wondering why you are not always retrieving the data you have written but then can retrieve it later.  If this is correct then this is the expected behavior of Cassandra.  When writing with a CL=1 then the first of the 3 replicas to respond will return a successful write to the client.  If you then tried to read using Quorum prior to the data being written to the other replicas then its possible you could get nothing (or stale) data returned to you.  This is the eventual consistency part of Cassandra.  If you are trying to read the data immediately after a successful write then this is likely the cause of your problems as "Read after Write" is an anti-pattern in Cassandra and most other distributed systems.

Second, in your data schema you are using Indexes incorrectly.  If you are using indexes to allow you to query on those fields then this is an anti-pattern especially with the large number that you have.  Indexes in Cassandra are an expensive operation that should only be used in rare cases where the column being indexed has low-cardinality.  See this https://docs.datastax.com/en/cql/3.1/cql/ddl/ddl_when_use_index_c.html

If you need to query by that large number of columns then you need to reevaluate your data model as Cassandra is optimized on a table-per-query methodology where you query on the fields in the primary key alone.  This requires you to denormalize your data into multiple different tables in order to build any application of reasonable complexity.  This is one of the tradeoffs you make when choosing the performance, high availability and scalability that Cassandra provides.  If you truly need the ability to perform ad-hoc queries on your data I suggest you look at a different datastore.

Body:
I have a keyspace with replication factor of 3. I am inserting data into Cassandra (4 node cluster with single data center) with write consistency level one. After completion of insertions I am reading data with consistency level quorum (2). But I am not getting data sometimes even if data exists, after some time I am getting data with same query. I don't know why Cassandra behaves like this.

My column family schema

CREATE TABLE input_data_profile.input_log_profile_1 (
    cid text,
    ctdon bigint,
    ctdat bigint,
    email text,
    addrs set<frozen<udt_addrs>>,
    asset set<frozen<udt_asset>>,
    cntno set<frozen<udt_cntno>>,
    dob frozen<udt_date>,
    dvc set<frozen<udt_dvc>>,
    eaka set<text>,
    edmn text,
    educ set<frozen<udt_educ>>,
    gen tinyint,
    hobby set<text>,
    income set<frozen<udt_income>>,
    interest set<text>,
    lang set<frozen<udt_lang>>,
    levnt set<frozen<udt_levnt>>,
    like map<text, frozen<set<text>>>,
    loc set<frozen<udt_loc>>,
    mapp set<text>,
    name frozen<udt_name>,
    params map<text, frozen<set<text>>>,
    prfsn set<frozen<udt_prfsn>>,
    rel set<frozen<udt_rel>>,
    rel_s tinyint,
    skills_prfsn set<frozen<udt_skill_prfsn>>,
    snw set<frozen<udt_snw>>,
    sport set<text>,
    status tinyint,
    z_addrs tinyint,
    z_asset tinyint,
    z_cntno tinyint,
    z_dob tinyint,
    z_dvc tinyint,
    z_eaka tinyint,
    z_educ tinyint,
    z_email tinyint,
    z_gen tinyint,
    z_hobby tinyint,
    z_income tinyint,
    z_interest tinyint,
    z_lang tinyint,
    z_levnt tinyint,
    z_like tinyint,
    z_loc tinyint,
    z_mapp tinyint,
    z_name tinyint,
    z_params tinyint,
    z_prfsn tinyint,
    z_rel tinyint,
    z_rel_s tinyint,
    z_skills_prfsn tinyint,
    z_snw tinyint,
    z_sport tinyint,
    PRIMARY KEY (cid, ctdon, ctdat, email)
) WITH CLUSTERING ORDER BY (ctdon ASC, ctdat ASC, email ASC)
CREATE INDEX input_log_profile_1_z_snw_idx ON input_data_profile.input_log_profile_1 (z_snw);
CREATE INDEX input_log_profile_1_z_prfsn_idx ON input_data_profile.input_log_profile_1 (z_prfsn);
CREATE INDEX input_log_profile_1_z_hobby_idx ON input_data_profile.input_log_profile_1 (z_hobby);
CREATE INDEX input_log_profile_1_z_rel_idx ON input_data_profile.input_log_profile_1 (z_rel);
CREATE INDEX input_log_profile_1_z_gen_idx ON input_data_profile.input_log_profile_1 (z_gen);
CREATE INDEX input_log_profile_1_z_mapp_idx ON input_data_profile.input_log_profile_1 (z_mapp);
CREATE INDEX input_log_profile_1_z_dvc_idx ON input_data_profile.input_log_profile_1 (z_dvc);
CREATE INDEX input_log_profile_1_z_skills_prfsn_idx ON input_data_profile.input_log_profile_1 (z_skills_prfsn);
CREATE INDEX input_log_profile_1_z_eaka_idx ON input_data_profile.input_log_profile_1 (z_eaka);
CREATE INDEX input_log_profile_1_z_name_idx ON input_data_profile.input_log_profile_1 (z_name);
CREATE INDEX input_log_profile_1_z_cntno_idx ON input_data_profile.input_log_profile_1 (z_cntno);
CREATE INDEX input_log_profile_1_z_educ_idx ON input_data_profile.input_log_profile_1 (z_educ);
CREATE INDEX input_log_profile_1_z_loc_idx ON input_data_profile.input_log_profile_1 (z_loc);
CREATE INDEX input_log_profile_1_z_email_idx ON input_data_profile.input_log_profile_1 (z_email);
CREATE INDEX input_log_profile_1_z_interest_idx ON input_data_profile.input_log_profile_1 (z_interest);
CREATE INDEX input_log_profile_1_z_asset_idx ON input_data_profile.input_log_profile_1 (z_asset);
CREATE INDEX input_log_profile_1_z_like_idx ON input_data_profile.input_log_profile_1 (z_like);
CREATE INDEX input_log_profile_1_z_rel_s_idx ON input_data_profile.input_log_profile_1 (z_rel_s);
CREATE INDEX input_log_profile_1_z_lang_idx ON input_data_profile.input_log_profile_1 (z_lang);
CREATE INDEX input_log_profile_1_z_addrs_idx ON input_data_profile.input_log_profile_1 (z_addrs);
CREATE INDEX input_log_profile_1_z_dob_idx ON input_data_profile.input_log_profile_1 (z_dob);
CREATE INDEX input_log_profile_1_z_income_idx ON input_data_profile.input_log_profile_1 (z_income);
CREATE INDEX input_log_profile_1_z_sport_idx ON input_data_profile.input_log_profile_1 (z_sport);
CREATE INDEX input_log_profile_1_z_params_idx ON input_data_profile.input_log_profile_1 (z_params);

I need to process fields wise so I indexed the every field status. I want to improve the read and write tps. Suggest me some modifications in schema.


问:
Program in C that reads binary file and outputs only zeros in float notation instead of file contents
I am not that comfortable with the C language or really writing code. I am trying to read a file in binary and output it to the screen. I am using fread and fopen since these work well with binary. I have this code that compiles but when i run my code as ./a.out data1 i only get 0.0000. The file contents are 4, 1.1, 2.2, 3.3, 4.4. This is what is supposed to be outputted. 1.1000 2.2000 3.3000 4.40000 only the floats. I supspect the problem is that im not passing the values in the file to the array correctly. I would appreciate any help or comments. My code is below.</p>

```<code>#include <stdio.h>
#include <malloc.h>

int main (int argc, char *argv[])
{
    FILE *ifile;
    int cnt, i;
    float *fptr;
    fptr = malloc (cnt * sizeof (float));
    ifile = fopen (argv[1], "rb");
    fread (fptr, sizeof (float), cnt, ifile);
    printf ("%f\n", *fptr);
}

// new code that works
#include <stdio.h>
#include <malloc.h>

int main (int argc, char *argv[])
{
    FILE *ifile;
    int cnt, i;
    float *fptr;
    ifile = fopen (argv[1], "rb");
    if (fread (&cnt, sizeof (int), 1, ifile) != 1) {
        printf ("%d\n", cnt);
    }
    fptr = malloc (cnt * sizeof (float));
    fread (fptr, sizeof (float), cnt, ifile);
    for (i = 0; i < cnt; i++) {
        printf ("%f\n", *fptr[i]);
    }
}
</code>```

答:
You don't set cnt anywhere so you read an unspecified number of floats which may or may not be correct.  If I hard code it to 4 and use a binary data file with 4 floats in it, it works fine:

```<code>#include <stdio.h>
#include <malloc.h>
int main (int argc, char *argv[]){
    FILE *ifile;
    int cnt = 4, i;
    float *fptr;
    fptr= malloc(cnt*sizeof(float));
    ifile=fopen(argv[1], "rb");
    fread(fptr, sizeof(float), cnt, ifile);
    printf("%f\n", *fptr);
    printf("%f\n", fptr[1]);
    printf("%f\n", fptr[2]);
    printf("%f\n", fptr[3]);
}
</code>```

running the program:

```<code>$ ./test-prog data
1.100000
2.200000
3.300000
4.400000
$ hd data
00000000  cd cc 8c 3f cd cc 0c 40  33 33 53 40 cd cc 8c 40  |...?...@33S@...@|
00000010
</code>```

Body:
I am not that comfortable with the C language or really writing code. I am trying to read a file in binary and output it to the screen. I am using fread and fopen since these work well with binary. I have this code that compiles but when i run my code as ./a.out data1 i only get 0.0000. The file contents are 4, 1.1, 2.2, 3.3, 4.4. This is what is supposed to be outputted. 1.1000 2.2000 3.3000 4.40000 only the floats. I supspect the problem is that im not passing the values in the file to the array correctly. I would appreciate any help or comments. My code is below.

#include <stdio.h>
#include <malloc.h>

int main (int argc, char *argv[])
{
    FILE *ifile;
    int cnt, i;
    float *fptr;
    fptr = malloc (cnt * sizeof (float));
    ifile = fopen (argv[1], "rb");
    fread (fptr, sizeof (float), cnt, ifile);
    printf ("%f\n", *fptr);
}

// new code that works
#include <stdio.h>
#include <malloc.h>

int main (int argc, char *argv[])
{
    FILE *ifile;
    int cnt, i;
    float *fptr;
    ifile = fopen (argv[1], "rb");
    if (fread (&cnt, sizeof (int), 1, ifile) != 1) {
        printf ("%d\n", cnt);
    }
    fptr = malloc (cnt * sizeof (float));
    fread (fptr, sizeof (float), cnt, ifile);
    for (i = 0; i < cnt; i++) {
        printf ("%f\n", *fptr[i]);
    }
}

Body:
You don't set cnt anywhere so you read an unspecified number of floats which may or may not be correct.  If I hard code it to 4 and use a binary data file with 4 floats in it, it works fine:

#include <stdio.h>
#include <malloc.h>
int main (int argc, char *argv[]){
    FILE *ifile;
    int cnt = 4, i;
    float *fptr;
    fptr= malloc(cnt*sizeof(float));
    ifile=fopen(argv[1], "rb");
    fread(fptr, sizeof(float), cnt, ifile);
    printf("%f\n", *fptr);
    printf("%f\n", fptr[1]);
    printf("%f\n", fptr[2]);
    printf("%f\n", fptr[3]);
}

running the program:

$ ./test-prog data
1.100000
2.200000
3.300000
4.400000
$ hd data
00000000  cd cc 8c 3f cd cc 0c 40  33 33 53 40 cd cc 8c 40  |...?...@33S@...@|
00000010


问:
How can I programmatically change UIFont of UISearchBar or UITableViewHeader?
I have a UITableView to which I add programmatically a UISearchController as a header. Since I'm adding it programmatically, I can't change the font from the storyboard. I need to change the UISearchBar font to match the font of the rest of the app.  I would need to either change the font of a UISearchBar or of the whole tableViewHeader

I saw that there's a similar question with an answer in objective-c, however I'm developing my app in Swift and I tried to convert the answer on the other question to the following code but it still won't work :

```<code>let lightFont = UIFont(name: "GothamRounded-Light", size: 15)

        for subview in searchController.searchBar.subviews {
            if subview is UITextField{

                (subview as! UITextField).font = lightFont

            }

        }
</code>```

答:
Try this: </p>

```<code>let textFieldInSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInSearchBar?.font = UIFont.systemFont(ofSize: 10)
</code>```

Body:
I have a UITableView to which I add programmatically a UISearchController as a header. Since I'm adding it programmatically, I can't change the font from the storyboard. I need to change the UISearchBar font to match the font of the rest of the app.  I would need to either change the font of a UISearchBar or of the whole tableViewHeader

I saw that there's a similar question with an answer in objective-c, however I'm developing my app in Swift and I tried to convert the answer on the other question to the following code but it still won't work :

let lightFont = UIFont(name: "GothamRounded-Light", size: 15)

        for subview in searchController.searchBar.subviews {
            if subview is UITextField{

                (subview as! UITextField).font = lightFont

            }

        }

Body:
Try this:

let textFieldInSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInSearchBar?.font = UIFont.systemFont(ofSize: 10)


问:
React Router 4: Pass route props to layout component

I'm trying to pass the route props to a layout component which performs initial API requests with the route props, the problem is that these route props are only passed to the child routes.

```<code><BrowserRouter>
    <Switch>
        <AppLayout> // This AppLayout performs API requests
                    // with the :route param in the child routes.
            <Route path="/some/:route" component={SomeComponent} />
            <Route path="/some/other/:route" component={OtherComponent} />
        </AppLayout>
    </Switch>
</BrowserRouter>
</code>```

Obviously, once the user hits the /some/:route route, the layout would have been already rendered. I tried doing something like this:

```<code><BrowserRouter>
    <Route path="/some/:route" render={(props) =>
        (<AppLayout {...props}><SomeComponent /></AppLayout>)} />
</BrowserRouter>
</code>```

This works but the AppLayout would be unmounted and remounted every time I go to another route using the same layout.

With react-router 3, I could do something like this:

```<code><Router history={browserHistory}>
    <Route path="/" component={AppLayout}>
        <Route path="/some/:route" component={SomeComponent} />
        <Route path="/some/other/:route" component={OtherComponent} />
    </Route>
</Router>
</code>```

And the route props would be available on the AppLayout component.

Is there a way of actually achieving this with react-router 4?

答:
Since you want to nest routes you should do something like this:

```<code><BrowserRouter>
    <Switch>
        <Route exact path="/" render={props => <AppLayout {...this.props} />} />
        <Route exact path="/some/:route" component={AppLayout} />
        <Route exact path="/some/other/:route" component={AppLayout}/>
    </Switch>
</BrowserRouter>
</code>```

Notice how I am passing the router props to AppLayout and using the AppLayout component as a handler for both the routes. Now inside the AppLayout component you'll have to mention these routes again with their respective components, like this:

```<code><Switch>
  <Route exact path="/some/:route" render={props => <SomeComponent {...this.props} />} />
  <Route exact path="/some/other/:route" render={props => <OtherComponent {...this.props} />} />
</Switch>
</code>```

Body:
I'm trying to pass the route props to a layout component which performs initial API requests with the route props, the problem is that these route props are only passed to the child routes.

<BrowserRouter>
    <Switch>
        <AppLayout> // This AppLayout performs API requests
                    // with the :route param in the child routes.
            <Route path="/some/:route" component={SomeComponent} />
            <Route path="/some/other/:route" component={OtherComponent} />
        </AppLayout>
    </Switch>
</BrowserRouter>

Obviously, once the user hits the /some/:route route, the layout would have been already rendered. I tried doing something like this:

<BrowserRouter>
    <Route path="/some/:route" render={(props) =>
        (<AppLayout {...props}><SomeComponent /></AppLayout>)} />
</BrowserRouter>

This works but the AppLayout would be unmounted and remounted every time I go to another route using the same layout.

With react-router 3, I could do something like this:

<Router history={browserHistory}>
    <Route path="/" component={AppLayout}>
        <Route path="/some/:route" component={SomeComponent} />
        <Route path="/some/other/:route" component={OtherComponent} />
    </Route>
</Router>

And the route props would be available on the AppLayout component.

Is there a way of actually achieving this with react-router 4?

Body:
Since you want to nest routes you should do something like this:

<BrowserRouter>
    <Switch>
        <Route exact path="/" render={props => <AppLayout {...this.props} />} />
        <Route exact path="/some/:route" component={AppLayout} />
        <Route exact path="/some/other/:route" component={AppLayout}/>
    </Switch>
</BrowserRouter>

Notice how I am passing the router props to AppLayout and using the AppLayout component as a handler for both the routes. Now inside the AppLayout component you'll have to mention these routes again with their respective components, like this:

<Switch>
  <Route exact path="/some/:route" render={props => <SomeComponent {...this.props} />} />
  <Route exact path="/some/other/:route" render={props => <OtherComponent {...this.props} />} />
</Switch>


问:
fulltext index returning no results from pdf filestream
I have a filestream table running on SQL Server 2012 on a Windows 8.1 x64 machine, which already have a few PDF and TXT files stored, so I decided to create a fulltext index to search through these files by using the following command:

```<code>CREATE FULLTEXT CATALOG FileStreamFTSCatalog AS DEFAULT;

CREATE FULLTEXT INDEX ON storage
(FileName Language 1046, File TYPE COLUMN FileExtension Language 1046)
KEY INDEX PK__storage__3214EC077DADCE3C
ON FileStreamFTSCatalog
WITH CHANGE_TRACKING AUTO;
</code>```

Then I sent these commands after reading some people having the same problem as me:

```<code>EXEC sp_fulltext_service @action='load_os_resources', @value=1;
EXEC sp_fulltext_service 'verify_signature', 0;
EXEC sp_fulltext_service 'update_languages';
Exec sp_fulltext_service 'ft_timeout', 600000;
Exec sp_fulltext_service 'ism_size',@value=16;
EXEC sp_fulltext_service 'restart_all_fdhosts';
EXEC sp_help_fulltext_system_components 'filter';
reconfigure with override
</code>```

I can see the PDF IFilter configured

```<code>filter  .pdf    E8978DA6-047F-4E3D-9C78-CDBE46041603    C:\Program Files\Adobe\Adobe PDF iFilter 11 for 64-bit platforms\bin\PDFFilter.dll  11.0.1.36   Adobe Systems, Inc.
</code>```

and I can even do a

```<code>select * from storage
where contains(*, 'data')
</code>```

but it's returning only the TXT files indexed, so I'm wondering: is there anything else I need to do to start indexing my PDFs? Or is it necessary to create another table and reinsert all these PDFs which I already had stored, even though the TXT files are getting indexed justfined?

UPDATE 1:

Opening the SQLFTXXX.LOG I get this message (for the FileTable):

```<code>2014-08-20 06:32:09.48 spid29s     Warning: No appropriate filter was found during full-text index population for table or indexed view '[text_storage].[dbo].[storage_table]' (table or indexed view ID '355584405', database ID '7'), full-text key value '篰磧'. Some columns of the row were not indexed.
</code>```

And this one (for the FileStream table):

```<code>2014-08-19 22:14:50.58 spid20s     Warning: No appropriate filter was found during full-text index population for table or indexed view '[text_storage].[dbo].[storage]' (table or indexed view ID '674101442', database ID '7'), full-text key value '1797'. Some columns of the row were not indexed.
</code>```

答:
There is another possible fix to this problem; installing some versions of Acrobat or Reader can break the PDF iFilter. Adobe posts this workaround:

https://helpx.adobe.com/acrobat/kb/pdf-search-breaks-110-install.html

Solution

Do one of the following:

Update to Acrobat/Reader 11.0.4 or higher. The issue is fixed in version 11.0.4.
  PDF iFilter 9 is not supported on Windows 8, update to PDF iFilter 11 from here.
  If you cannot update your Acrobat/Reader or PDF iFilter, here is the workaround.

Workaround: Restore the registry entry to the Windows 8 native entry as follows:

Go to HKEY_CLASSES_ROOT\.pdf\PersistentHandler. Create the key if it does not exist.

Verify that the value is 1AA9BF05-9A97-48c1-BA28-D9DCE795E93C. If the Acrobat or Reader install overwrote the entry with F6594A6D-D57F-4EFD-B2C3-DCD9779E382E, return it to its original value.

If you have any third-party PDF iFilters installed, reinstall them.

Restart the Windows Search service:

Go to Task Manager > Services.

Select WSearch.

Right-click, and then choose Restart.

Body:
I have a filestream table running on SQL Server 2012 on a Windows 8.1 x64 machine, which already have a few PDF and TXT files stored, so I decided to create a fulltext index to search through these files by using the following command:

CREATE FULLTEXT CATALOG FileStreamFTSCatalog AS DEFAULT;

CREATE FULLTEXT INDEX ON storage
(FileName Language 1046, File TYPE COLUMN FileExtension Language 1046)
KEY INDEX PK__storage__3214EC077DADCE3C
ON FileStreamFTSCatalog
WITH CHANGE_TRACKING AUTO;

Then I sent these commands after reading some people having the same problem as me:

EXEC sp_fulltext_service @action='load_os_resources', @value=1;
EXEC sp_fulltext_service 'verify_signature', 0;
EXEC sp_fulltext_service 'update_languages';
Exec sp_fulltext_service 'ft_timeout', 600000;
Exec sp_fulltext_service 'ism_size',@value=16;
EXEC sp_fulltext_service 'restart_all_fdhosts';
EXEC sp_help_fulltext_system_components 'filter';
reconfigure with override

I can see the PDF IFilter configured

filter  .pdf    E8978DA6-047F-4E3D-9C78-CDBE46041603    C:\Program Files\Adobe\Adobe PDF iFilter 11 for 64-bit platforms\bin\PDFFilter.dll  11.0.1.36   Adobe Systems, Inc.

and I can even do a

select * from storage
where contains(*, 'data')

but it's returning only the TXT files indexed, so I'm wondering: is there anything else I need to do to start indexing my PDFs? Or is it necessary to create another table and reinsert all these PDFs which I already had stored, even though the TXT files are getting indexed justfined?

UPDATE 1:

Opening the SQLFTXXX.LOG I get this message (for the FileTable):

2014-08-20 06:32:09.48 spid29s     Warning: No appropriate filter was found during full-text index population for table or indexed view '[text_storage].[dbo].[storage_table]' (table or indexed view ID '355584405', database ID '7'), full-text key value '篰磧'. Some columns of the row were not indexed.

And this one (for the FileStream table):

2014-08-19 22:14:50.58 spid20s     Warning: No appropriate filter was found during full-text index population for table or indexed view '[text_storage].[dbo].[storage]' (table or indexed view ID '674101442', database ID '7'), full-text key value '1797'. Some columns of the row were not indexed.


问:
Running Total with subtraction
I have a data set with closing and opening dates of public schools in California. Available here or dput() at the bottom of the question. The data also lists what type of school it is and where it is. I am trying to create a running total column which also takes into account school closings as well as school type.

Here is the solution I've come up with, which basically entails me encoding a lot of different 1's and 0's based on the conditions using ifelse:

```<code># open charter schools
pubschls$open_chart <-  ifelse(pubschls$Charter=="Y" & is.na(pubschls$ClosedDate)==TRUE, 1, 0)
# open public schools
pubschls$open_pub <- ifelse(pubschls$Charter=="N" & is.na(pubschls$ClosedDate)==TRUE, 1, 0)
# closed charters
pubschls$closed_chart <- ifelse(pubschls$Charter=="Y" & is.na(pubschls$ClosedDate)==FALSE, 1,  0)
# closed public schools
pubschls$closed_pub <- ifelse(pubschls$Charter=="N" & is.na(pubschls$ClosedDate)==FALSE, 1,  0)
lausd <- filter(pubschls, NCESDist=="0622710")
# count number open during each year
</code>```

Then I subtract the columns from each other to get totals.

```<code>la_schools_count <- aggregate(lausd[c('open_chart','closed_chart','open_pub','closed_pub')],
 by=list(year(lausd$OpenDate)), sum)

    # find net charters by subtracting closed from open
    la_schools_count$net_chart <- la_schools_count$open_chart - la_schools_count$closed_chart
    # find net public schools by subtracting closed from open
    la_schools_count$net_pub <- la_schools_count$open_pub - la_schools_count$closed_pub
    # add running totals
    la_schools_count$cum_chart <- cumsum(la_schools_count$net_chart)
    la_schools_count$cum_pub <- cumsum(la_schools_count$net_pub)
    # total totals
    la_schools_count$total <- la_schools_count$cum_chart + la_schools_count$cum_pub
</code>```

My output looks like this:

```<code>la_schools_count <- select(la_schools_count, "year", "cum_chart", "cum_pub", "pen_rate", "total")
     year cum_chart cum_pub  pen_rate total
1  1952         1       0 100.00000     1
2  1956         1       1  50.00000     2
3  1969         1       2  33.33333     3
4  1980        55     469  10.49618   524
5  1989        55     470  10.47619   525
6  1990        55     470  10.47619   525
7  1991        55     473  10.41667   528
8  1992        55     476  10.35782   531
9  1993        55     477  10.33835   532
10 1994        56     478  10.48689   534
11 1995        57     478  10.65421   535
12 1996        57     479  10.63433   536
13 1997        58     481  10.76067   539
14 1998        59     480  10.94620   539
15 1999        61     480  11.27542   541
16 2000        61     481  11.25461   542
17 2001        62     482  11.39706   544
18 2002        64     484  11.67883   548
19 2003        73     485  13.08244   558
20 2004        83     496  14.33506   579
21 2005        90     524  14.65798   614
22 2006        96     532  15.28662   628
23 2007        90     534  14.42308   624
24 2008        97     539  15.25157   636
25 2009       108     546  16.51376   654
26 2010       124     566  17.97101   690
27 2011       140     580  19.44444   720
28 2012       144     605  19.22563   749
29 2013       162     609  21.01167   771
30 2014       179     611  22.65823   790
31 2015       195     611  24.19355   806
32 2016       203     614  24.84700   817
33 2017       211     619  25.42169   830
</code>```

I'm just wondering if this could be done in a better way. Like an apply statement to all rows based on the conditions?

```<code>dput:
structure(list(CDSCode = c("19647330100289", "19647330100297",
"19647330100669", "19647330100677", "19647330100743", "19647330100750"
), OpenDate = structure(c(12324, 12297, 12240, 12299, 12634,
12310), class = "Date"), ClosedDate = structure(c(NA, 15176,
NA, NA, NA, NA), class = "Date"), Charter = c("Y", "Y", "Y",
"Y", "Y", "Y")), .Names = c("CDSCode", "OpenDate", "ClosedDate",
"Charter"), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

答:
I followed your code and learned what you were doing except pen_rate. It seems that pen_rate is calculated dividing cum_chart by total. I download the original data set and did the following. I called the data set foo. Whenclosed_pub), I combined Charter and ClosedDate. I checked if ClosedDate is NA or not, and converted the logical output to numbers (1 = open, 0 = closed). This is how I created the four groups (i.e., open_chart, closed_chart, open_pub, and closed_pub). I guess this would ask you to do less typing. Since the dates are in character, I extracted year using substr(). If you have a date object, you need to do something else. Once you have year, you group the data with it and calculate how many schools exist for each type of school using count(). This part is the equivalent of your aggregate() code. Then, Convert the output to a wide-format data with spread() and did the rest of the calculation as you demonstrated in your codes. The final output seems different from what you have in your question, but my outcome was identical to one that I obtained by running your codes. I hope this will help you.

```<code>library(dplyr)
library(tidyr)
library(readxl)

# Get the necessary data
foo <- read_xls("pubschls.xls") %>%
       select(NCESDist, CDSCode, OpenDate, ClosedDate, Charter) %>%
       filter(NCESDist == "0622710" & (!Charter %in% NA))

mutate(foo, group = paste(Charter, as.numeric(is.na(ClosedDate)), sep = "_"),
       year = substr(OpenDate, star = nchar(OpenDate) - 3, stop = nchar(OpenDate))) %>%
count(year, group) %>%
spread(key = group, value = n, fill = 0) %>%
mutate(net_chart = Y_1 - Y_0,
       net_pub = N_1 - N_0,
       cum_chart = cumsum(net_chart),
       cum_pub = cumsum(net_pub),
       total = cum_chart + cum_pub,
       pen_rate = cum_chart / total)

# A part of the outcome
#    year N_0 N_1 Y_0 Y_1 net_chart net_pub cum_chart cum_pub total   pen_rate
#1   1866   0   1   0   0         0       1         0       1     1 0.00000000
#2   1873   0   1   0   0         0       1         0       2     2 0.00000000
#3   1878   0   1   0   0         0       1         0       3     3 0.00000000
#4   1881   0   1   0   0         0       1         0       4     4 0.00000000
#5   1882   0   2   0   0         0       2         0       6     6 0.00000000
#110 2007   0   2  15   9        -6       2        87     393   480 0.18125000
#111 2008   2   8   9  15         6       6        93     399   492 0.18902439
#112 2009   1   9   4  15        11       8       104     407   511 0.20352250
#113 2010   5  26   5  21        16      21       120     428   548 0.21897810
#114 2011   2  16   2  18        16      14       136     442   578 0.23529412
#115 2012   2  27   3   7         4      25       140     467   607 0.23064250
#116 2013   1   5   1  19        18       4       158     471   629 0.25119237
#117 2014   1   3   1  18        17       2       175     473   648 0.27006173
#118 2015   0   0   2  18        16       0       191     473   664 0.28765060
#119 2016   0   3   0   8         8       3       199     476   675 0.29481481
#120 2017   0   5   0   9         9       5       208     481   689 0.30188679
</code>```

Title: Running Total with subtraction

Body:
I have a data set with closing and opening dates of public schools in California. Available here or dput() at the bottom of the question. The data also lists what type of school it is and where it is. I am trying to create a running total column which also takes into account school closings as well as school type.

Here is the solution I've come up with, which basically entails me encoding a lot of different 1's and 0's based on the conditions using ifelse:

# open charter schools
pubschls$open_chart <-  ifelse(pubschls$Charter=="Y" & is.na(pubschls$ClosedDate)==TRUE, 1, 0)
# open public schools
pubschls$open_pub <- ifelse(pubschls$Charter=="N" & is.na(pubschls$ClosedDate)==TRUE, 1, 0)
# closed charters
pubschls$closed_chart <- ifelse(pubschls$Charter=="Y" & is.na(pubschls$ClosedDate)==FALSE, 1,  0)
# closed public schools
pubschls$closed_pub <- ifelse(pubschls$Charter=="N" & is.na(pubschls$ClosedDate)==FALSE, 1,  0)
lausd <- filter(pubschls, NCESDist=="0622710")
# count number open during each year

Then I subtract the columns from each other to get totals.

la_schools_count <- aggregate(lausd[c('open_chart','closed_chart','open_pub','closed_pub')],
 by=list(year(lausd$OpenDate)), sum)

    # find net charters by subtracting closed from open
    la_schools_count$net_chart <- la_schools_count$open_chart - la_schools_count$closed_chart
    # find net public schools by subtracting closed from open
    la_schools_count$net_pub <- la_schools_count$open_pub - la_schools_count$closed_pub
    # add running totals
    la_schools_count$cum_chart <- cumsum(la_schools_count$net_chart)
    la_schools_count$cum_pub <- cumsum(la_schools_count$net_pub)
    # total totals
    la_schools_count$total <- la_schools_count$cum_chart + la_schools_count$cum_pub

My output looks like this:

la_schools_count <- select(la_schools_count, "year", "cum_chart", "cum_pub", "pen_rate", "total")
     year cum_chart cum_pub  pen_rate total
1  1952         1       0 100.00000     1
2  1956         1       1  50.00000     2
3  1969         1       2  33.33333     3
4  1980        55     469  10.49618   524
5  1989        55     470  10.47619   525
6  1990        55     470  10.47619   525
7  1991        55     473  10.41667   528
8  1992        55     476  10.35782   531
9  1993        55     477  10.33835   532
10 1994        56     478  10.48689   534
11 1995        57     478  10.65421   535
12 1996        57     479  10.63433   536
13 1997        58     481  10.76067   539
14 1998        59     480  10.94620   539
15 1999        61     480  11.27542   541
16 2000        61     481  11.25461   542
17 2001        62     482  11.39706   544
18 2002        64     484  11.67883   548
19 2003        73     485  13.08244   558
20 2004        83     496  14.33506   579
21 2005        90     524  14.65798   614
22 2006        96     532  15.28662   628
23 2007        90     534  14.42308   624
24 2008        97     539  15.25157   636
25 2009       108     546  16.51376   654
26 2010       124     566  17.97101   690
27 2011       140     580  19.44444   720
28 2012       144     605  19.22563   749
29 2013       162     609  21.01167   771
30 2014       179     611  22.65823   790
31 2015       195     611  24.19355   806
32 2016       203     614  24.84700   817
33 2017       211     619  25.42169   830

I'm just wondering if this could be done in a better way. Like an apply statement to all rows based on the conditions?

dput:
structure(list(CDSCode = c("19647330100289", "19647330100297",
"19647330100669", "19647330100677", "19647330100743", "19647330100750"
), OpenDate = structure(c(12324, 12297, 12240, 12299, 12634,
12310), class = "Date"), ClosedDate = structure(c(NA, 15176,
NA, NA, NA, NA), class = "Date"), Charter = c("Y", "Y", "Y",
"Y", "Y", "Y")), .Names = c("CDSCode", "OpenDate", "ClosedDate",
"Charter"), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))

Body:
I followed your code and learned what you were doing except pen_rate. It seems that pen_rate is calculated dividing cum_chart by total. I download the original data set and did the following. I called the data set foo. Whenclosed_pub), I combined Charter and ClosedDate. I checked if ClosedDate is NA or not, and converted the logical output to numbers (1 = open, 0 = closed). This is how I created the four groups (i.e., open_chart, closed_chart, open_pub, and closed_pub). I guess this would ask you to do less typing. Since the dates are in character, I extracted year using substr(). If you have a date object, you need to do something else. Once you have year, you group the data with it and calculate how many schools exist for each type of school using count(). This part is the equivalent of your aggregate() code. Then, Convert the output to a wide-format data with spread() and did the rest of the calculation as you demonstrated in your codes. The final output seems different from what you have in your question, but my outcome was identical to one that I obtained by running your codes. I hope this will help you.

library(dplyr)
library(tidyr)
library(readxl)

# Get the necessary data
foo <- read_xls("pubschls.xls") %>%
       select(NCESDist, CDSCode, OpenDate, ClosedDate, Charter) %>%
       filter(NCESDist == "0622710" & (!Charter %in% NA))

mutate(foo, group = paste(Charter, as.numeric(is.na(ClosedDate)), sep = "_"),
       year = substr(OpenDate, star = nchar(OpenDate) - 3, stop = nchar(OpenDate))) %>%
count(year, group) %>%
spread(key = group, value = n, fill = 0) %>%
mutate(net_chart = Y_1 - Y_0,
       net_pub = N_1 - N_0,
       cum_chart = cumsum(net_chart),
       cum_pub = cumsum(net_pub),
       total = cum_chart + cum_pub,
       pen_rate = cum_chart / total)

# A part of the outcome
#    year N_0 N_1 Y_0 Y_1 net_chart net_pub cum_chart cum_pub total   pen_rate
#1   1866   0   1   0   0         0       1         0       1     1 0.00000000
#2   1873   0   1   0   0         0       1         0       2     2 0.00000000
#3   1878   0   1   0   0         0       1         0       3     3 0.00000000
#4   1881   0   1   0   0         0       1         0       4     4 0.00000000
#5   1882   0   2   0   0         0       2         0       6     6 0.00000000
#110 2007   0   2  15   9        -6       2        87     393   480 0.18125000
#111 2008   2   8   9  15         6       6        93     399   492 0.18902439
#112 2009   1   9   4  15        11       8       104     407   511 0.20352250
#113 2010   5  26   5  21        16      21       120     428   548 0.21897810
#114 2011   2  16   2  18        16      14       136     442   578 0.23529412
#115 2012   2  27   3   7         4      25       140     467   607 0.23064250
#116 2013   1   5   1  19        18       4       158     471   629 0.25119237
#117 2014   1   3   1  18        17       2       175     473   648 0.27006173
#118 2015   0   0   2  18        16       0       191     473   664 0.28765060
#119 2016   0   3   0   8         8       3       199     476   675 0.29481481
#120 2017   0   5   0   9         9       5       208     481   689 0.30188679


问:
Unable to load IRKernel in Jupyter notebook
I'm pretty new to the forum, so I'm sorry if this question has already been answered. I looked around, and although I saw that some had similar issues, I couldn't find the solution to my problem on any previous posts. So - here goes...

I'm running Mac OS X 10.11.5, Jupyter notebook version 4.2.1, R version 3.2.2

I installed the R kernel for Jupyter notebook with the following command -

```<code>conda install -c r r-irkernel
</code>```

Now, when I launch Jupyter notebook, I see 'R' appears as one of the options in the drop down menu on the right hand side under 'notebooks.' However, when I try to create an R notebook, the kernel crashes and I get the following error in terminal:

```<code>WARNING:root:kernel b42781ab-ebb1-45eb-8a54-d3801106fb94 restarted
Error: .onLoad failed in loadNamespace() for 'pbdZMQ', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Users/avislova/anaconda/lib/R/library/pbdZMQ/libs/pbdZMQ.so':
  dlopen(/Users/avislova/anaconda/lib/R/library/pbdZMQ/libs/pbdZMQ.so,     6): Library not loaded: @rpath/libzmq.5.dylib
  Referenced from: /Users/avislova/anaconda/lib/R/library/pbdZMQ/libs/pbdZMQ.so
  Reason: image not found
Execution halted
 [W 16:19:12.382 NotebookApp] KernelRestarter: restart failed
 [W 16:19:12.382 NotebookApp] Kernel b42781ab-ebb1-45eb-8a54-d3801106fb94 died, removing from map.
ERROR:root:kernel b42781ab-ebb1-45eb-8a54-d3801106fb94 restarted failed!
 [W 16:19:12.390 NotebookApp] Kernel deleted before session
 [W 16:19:12.390 NotebookApp] 410 DELETE /api/sessions/2236e334-e33a-483b-87f3-31c461d4903b (::1) 1.32ms referer=http://localhost:8888/notebooks/Untitled5.ipynb?kernel_name=ir
</code>```

Any idea where I can go from here?

Thank you!

答:
After installing devtools in R:

```<code>> install.packages("devtools")
</code>```

Try installing the following from github:

```<code>> library("devtools")
> devtools::install_github("IRkernel/repr")
> devtools::install_github("IRkernel/IRdisplay")
> devtools::install_github("IRkernel/IRkernel")
</code>```

The last line installed pdbZMQ for me, even though using install.packages("pdbZMQ") reported that none existed for any of the versions of R I tried.

More details and troubleshooting are available on github where I found this solution.

Body:
I'm pretty new to the forum, so I'm sorry if this question has already been answered. I looked around, and although I saw that some had similar issues, I couldn't find the solution to my problem on any previous posts. So - here goes...

I'm running Mac OS X 10.11.5, Jupyter notebook version 4.2.1, R version 3.2.2

I installed the R kernel for Jupyter notebook with the following command -

conda install -c r r-irkernel

Now, when I launch Jupyter notebook, I see 'R' appears as one of the options in the drop down menu on the right hand side under 'notebooks.' However, when I try to create an R notebook, the kernel crashes and I get the following error in terminal:

WARNING:root:kernel b42781ab-ebb1-45eb-8a54-d3801106fb94 restarted
Error: .onLoad failed in loadNamespace() for 'pbdZMQ', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Users/avislova/anaconda/lib/R/library/pbdZMQ/libs/pbdZMQ.so':
  dlopen(/Users/avislova/anaconda/lib/R/library/pbdZMQ/libs/pbdZMQ.so,     6): Library not loaded: @rpath/libzmq.5.dylib
  Referenced from: /Users/avislova/anaconda/lib/R/library/pbdZMQ/libs/pbdZMQ.so
  Reason: image not found
Execution halted
 [W 16:19:12.382 NotebookApp] KernelRestarter: restart failed
 [W 16:19:12.382 NotebookApp] Kernel b42781ab-ebb1-45eb-8a54-d3801106fb94 died, removing from map.
ERROR:root:kernel b42781ab-ebb1-45eb-8a54-d3801106fb94 restarted failed!
 [W 16:19:12.390 NotebookApp] Kernel deleted before session
 [W 16:19:12.390 NotebookApp] 410 DELETE /api/sessions/2236e334-e33a-483b-87f3-31c461d4903b (::1) 1.32ms referer=http://localhost:8888/notebooks/Untitled5.ipynb?kernel_name=ir

Any idea where I can go from here?

Thank you!

Body:
After installing devtools in R:

> install.packages("devtools")

Try installing the following from github:

> library("devtools")
> devtools::install_github("IRkernel/repr")
> devtools::install_github("IRkernel/IRdisplay")
> devtools::install_github("IRkernel/IRkernel")

The last line installed pdbZMQ for me, even though using install.packages("pdbZMQ") reported that none existed for any of the versions of R I tried.

More details and troubleshooting are available on github where I found this solution.


问:
How to list dependencies for a python library without installing?
Is there a way to get a list of dependencies for a given python package without installing it first?

I can currently get a list of requirements, but it requires installing the packages.  For example, I can use pip to show basic requirements info, but it doesn't include version information:

```<code>$ pip show pytest
Name: pytest
Version: 3.0.6
...
Requires: colorama, setuptools, py
</code>```

I've tried a library called pipdeptree that includes much better output on requirements, but it also requires installation of the packages

```<code>$ pipdeptree -p pytest
pytest==3.0.6
- colorama [required: Any, installed: 0.3.7]
- py [required: >=1.4.29, installed: 1.4.32]
- setuptools [required: Any, installed: 34.0.0]
  - appdirs [required: >=1.4.0, installed: 1.4.0]
...
</code>```

Ideally, I would get the level of detail that pipdeptree provides.  Also, being able to produce a requirements.txt file from a python wheel or from pypi with pip would suffice as well.

I'm interested in the dependency constraints for a given package, not the final downloaded packages after resolving the dependency requirements.  For example, I don't really care that pip downloaded package-2.3.4, I would rather know that package>=2.1 was a requirement.

答:
If you don't mind installing conda, this might do the trick for you:

```<code>$ conda info numpy=1.11.1 python=3.6.3
</code>```

The version numbers of the package or of python are optional (all versions will then be described)

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to get a list of dependencies for a given python package without installing it first?

I can currently get a list of requirements, but it requires installing the packages.  For example, I can use pip to show basic requirements info, but it doesn't include version information:

$ pip show pytest
Name: pytest
Version: 3.0.6
...
Requires: colorama, setuptools, py

I've tried a library called pipdeptree that includes much better output on requirements, but it also requires installation of the packages

$ pipdeptree -p pytest
pytest==3.0.6
- colorama [required: Any, installed: 0.3.7]
- py [required: >=1.4.29, installed: 1.4.32]
- setuptools [required: Any, installed: 34.0.0]
  - appdirs [required: >=1.4.0, installed: 1.4.0]
...

Ideally, I would get the level of detail that pipdeptree provides.  Also, being able to produce a requirements.txt file from a python wheel or from pypi with pip would suffice as well.

I'm interested in the dependency constraints for a given package, not the final downloaded packages after resolving the dependency requirements.  For example, I don't really care that pip downloaded package-2.3.4, I would rather know that package>=2.1 was a requirement.

Body:
If you don't mind installing conda, this might do the trick for you:

$ conda info numpy=1.11.1 python=3.6.3

The version numbers of the package or of python are optional (all versions will then be described)


问:
In an AppDelegate, how is the main UIWindow instantiated?
A snippet of the default code in a Master-Detail Xcode project

AppDelegate.m

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
 UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;  // *** here ***
    MasterViewController *controller = (MasterViewController *)navigationController.topViewController;
    controller.managedObjectContext = self.managedObjectContext;
    return YES;
}
</code>```

AppDelegate.h

```<code>@property (strong, nonatomic) UIWindow *window;
</code>```

I am aware that @synthesize just sets the accessor methods, and no initialization happens automagically. But how does window have a non-nil rootViewController if it is never explicitly initialized? Is this just Xcode init'ing behind the scenes?

答:
The above answers only who sets the window variable without answering the main questions: "But how does window have a non-nil rootViewController if it is never explicitly initialized? Is this just Xcode init'ing behind the scenes?" and seem to suggest that there is magic afoot. Not a satisfactory answer for me, and so with a little digging, all becomes clear.

The generated code defines AppDelegate as

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
     ...
}
</code>```

When you search the project, there is no other reference to window, so apparently it should remain nil, but actually is set to the correct value (by the methods outlined above). The "magic" is that AppDelegate conforms to the UIApplicationDelegate which includes an declaration:

```<code>    optional public var window: UIWindow? { get set }
</code>```

Part of conforming to the UIApplicationDelegate is the redeclaration of the public variable window. When the underlying Application references the variable window in the protocol, it is actually linked to the variable window in our class. When the calling Application updates that variable window in the protocol, it is actually updating our variable window. So when we need to access the value in our program it is ready and waiting.

This is not Xcode magic, but an integral part of the Swift language. When using protocols we can employ the same techniques in our own Swift programs. This is just the same as our implementations of various functions in our classes which we do all the time: e.g. UIApplicationDelegate defines

optional public func applicationDidEnterBackground(_ application: UIApplication)

so we can write our own implementation which is then "magically" called!

For completeness, note the @UIApplicationMain tag on the class. This defines the entry point for the application and is what makes everything work together. The actual class name is irrelevant, and can be given any name you require, as long as it is of type UIResponder and conforms to the UIApplicationDelegate.

Body:
A snippet of the default code in a Master-Detail Xcode project

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
 UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;  // *** here ***
    MasterViewController *controller = (MasterViewController *)navigationController.topViewController;
    controller.managedObjectContext = self.managedObjectContext;
    return YES;
}

AppDelegate.h

@property (strong, nonatomic) UIWindow *window;

I am aware that @synthesize just sets the accessor methods, and no initialization happens automagically. But how does window have a non-nil rootViewController if it is never explicitly initialized? Is this just Xcode init'ing behind the scenes?

Body:
The above answers only who sets the window variable without answering the main questions: "But how does window have a non-nil rootViewController if it is never explicitly initialized? Is this just Xcode init'ing behind the scenes?" and seem to suggest that there is magic afoot. Not a satisfactory answer for me, and so with a little digging, all becomes clear.

The generated code defines AppDelegate as

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
     ...
}

When you search the project, there is no other reference to window, so apparently it should remain nil, but actually is set to the correct value (by the methods outlined above). The "magic" is that AppDelegate conforms to the UIApplicationDelegate which includes an declaration:

    optional public var window: UIWindow? { get set }

Part of conforming to the UIApplicationDelegate is the redeclaration of the public variable window. When the underlying Application references the variable window in the protocol, it is actually linked to the variable window in our class. When the calling Application updates that variable window in the protocol, it is actually updating our variable window. So when we need to access the value in our program it is ready and waiting.

This is not Xcode magic, but an integral part of the Swift language. When using protocols we can employ the same techniques in our own Swift programs. This is just the same as our implementations of various functions in our classes which we do all the time: e.g. UIApplicationDelegate defines

optional public func applicationDidEnterBackground(_ application: UIApplication)

so we can write our own implementation which is then "magically" called!

For completeness, note the @UIApplicationMain tag on the class. This defines the entry point for the application and is what makes everything work together. The actual class name is irrelevant, and can be given any name you require, as long as it is of type UIResponder and conforms to the UIApplicationDelegate.


问:
react-native-firebase install - package io.invertase.firebase does not exist?
I am getting the following issues when running "react-native run-android" in my project.  I've gone through the react-native-firebase per normal but in this case I can't quite see what I might have done wrong?

```<code>:app:incrementalDebugJavaCompilationSafeguard UP-TO-DATE
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:11: error: package io.invertase.firebase does not exist
import io.invertase.firebase.RNFirebasePackage;
                            ^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:12: error: package io.invertase.firebase.auth does not exist
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
                                 ^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:13: error: package io.invertase.firebase.firestore does not exist
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;
                                      ^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:30: error: cannot find symbol
          new RNFirebasePackage(),
              ^
  symbol: class RNFirebasePackage
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:31: error: cannot find symbol
          new RNFirebaseAuthPackage(),
              ^
  symbol: class RNFirebaseAuthPackage
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:32: error: cannot find symbol
          new RNFirebaseFirestorePackage()
              ^
  symbol: class RNFirebaseFirestorePackage
6 errors
:app:compileDebugJavaWithJavac FAILED
</code>```

MainApplication.java is for exampe:

```<code>package com.gctodo;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new RNFirebasePackage(),
          new RNFirebaseAuthPackage(),
          new RNFirebaseFirestorePackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}
</code>```

答:
It appears that RNFirebasePackage is missing and cannot be found during compile step.

Try running

```<code>react-native link
</code>```

after install, followed by clean and then run the build.

Body:
I am getting the following issues when running "react-native run-android" in my project.  I've gone through the react-native-firebase per normal but in this case I can't quite see what I might have done wrong?

:app:incrementalDebugJavaCompilationSafeguard UP-TO-DATE
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:11: error: package io.invertase.firebase does not exist
import io.invertase.firebase.RNFirebasePackage;
                            ^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:12: error: package io.invertase.firebase.auth does not exist
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
                                 ^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:13: error: package io.invertase.firebase.firestore does not exist
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;
                                      ^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:30: error: cannot find symbol
          new RNFirebasePackage(),
              ^
  symbol: class RNFirebasePackage
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:31: error: cannot find symbol
          new RNFirebaseAuthPackage(),
              ^
  symbol: class RNFirebaseAuthPackage
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:32: error: cannot find symbol
          new RNFirebaseFirestorePackage()
              ^
  symbol: class RNFirebaseFirestorePackage
6 errors
:app:compileDebugJavaWithJavac FAILED

MainApplication.java is for exampe:

package com.gctodo;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new RNFirebasePackage(),
          new RNFirebaseAuthPackage(),
          new RNFirebaseFirestorePackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

Body:
It appears that RNFirebasePackage is missing and cannot be found during compile step.

Try running

react-native link

after install, followed by clean and then run the build.


问:
How to return top 3 rows if last row is tied
Suppose my table contains data like that

```<code>  ID    MovieName                      Rating
  --------------------------------------------
  1     The Shawshank Redemption       9.20
  2     The Godfather: Part II         9.00
  3     12 Angry Men                   8.90
  4     Pulp Fiction                   8.90
  5     The Good, the Bad and the Ugly 8.80
</code>```

I want to select top 3 movies according to highest rating which contains both '12 Angry Men' and 'Pulp Fiction' movies.So query should return 4 rows instead of 3.

答:
Just use TOP WITH TIES

```<code>SELECT TOP 3 WITH TIES ID, MovieName, Rating
FROM MyMoviesDB
ORDER BY Rating DESC
</code>```

Only thing is you have to use ORDER BY

Body:
Suppose my table contains data like that

  ID    MovieName                      Rating
  --------------------------------------------
  1     The Shawshank Redemption       9.20
  2     The Godfather: Part II         9.00
  3     12 Angry Men                   8.90
  4     Pulp Fiction                   8.90
  5     The Good, the Bad and the Ugly 8.80

I want to select top 3 movies according to highest rating which contains both '12 Angry Men' and 'Pulp Fiction' movies.So query should return 4 rows instead of 3.

Body:
Just use TOP WITH TIES

SELECT TOP 3 WITH TIES ID, MovieName, Rating
FROM MyMoviesDB
ORDER BY Rating DESC

Only thing is you have to use ORDER BY


问:
When exactly should I refresh the EWS URL while using managed API
I am getting the EWS URL as below:

```<code>var response = myAutodiscoverService.GetUserSettings(
                        "userA@domain.com",
                        UserSettingName.ExternalEwsUrl,
                        UserSettingName.InternalEwsUrl,
                        UserSettingName.EwsSupportedSchemas);

string settingValue;
if (response.TryGetSettingValue(UserSettingName.ExternalEwsUrl, out settingValue)
    || response.TryGetSettingValue(UserSettingName.InternalEwsUrl, out settingValue))
{
    // If ExternalEwsUrl is not returned in the response,
    // we consider InternalEwsUrl for auto-discover
    string ewsurl = settingValue;
}
</code>```

Now, I am caching this ewsurl I get with this request as recommended since auto-discovery is really slow. What happens when this ewsurl expires (because let's say user's mailbox was moved to a different endpoint). What error should I expect in order to implement a failure mechanism to get the new updated ews url?

Edit: I am using the ews url to subscribe for new mail events on EWS using ExchangeService.SubscribeToPushNotifications So I have another question, suppose if the ews url was changed after user subscribed for notifications, will I get a notification for that user for a new mail event on the callback url of my application?

答: I seem to recall the ROT from MSFT was you should re-autodiscover every 24 hours, but I've not seen anything recently.  As to the Push notifications:  since there is a "heartbeat" facility in Push notifications, if you miss two heartbeats in a row, it's safe to say you should tear down the subscription and re-subscribe, which to be safe, implies re-autodiscovery.  Of course with O365, since the EWS URL seems (for now) to always be the same, re-autodiscovery is less of a concern.</p>

Body:
I am getting the EWS URL as below:

var response = myAutodiscoverService.GetUserSettings(
                        "userA@domain.com",
                        UserSettingName.ExternalEwsUrl,
                        UserSettingName.InternalEwsUrl,
                        UserSettingName.EwsSupportedSchemas);

string settingValue;
if (response.TryGetSettingValue(UserSettingName.ExternalEwsUrl, out settingValue)
    || response.TryGetSettingValue(UserSettingName.InternalEwsUrl, out settingValue))
{
    // If ExternalEwsUrl is not returned in the response,
    // we consider InternalEwsUrl for auto-discover
    string ewsurl = settingValue;
}

Now, I am caching this ewsurl I get with this request as recommended since auto-discovery is really slow. What happens when this ewsurl expires (because let's say user's mailbox was moved to a different endpoint). What error should I expect in order to implement a failure mechanism to get the new updated ews url?

Edit: I am using the ews url to subscribe for new mail events on EWS using ExchangeService.SubscribeToPushNotifications So I have another question, suppose if the ews url was changed after user subscribed for notifications, will I get a notification for that user for a new mail event on the callback url of my application?


问:
ggplot2: Using formular in aes mapping
With data iris I want to the color of point of setosa specie different to other species. The command works with != operator but =operator does not.

I have two color with:

```<code>ggplot(iris)+ geom_point(aes(x=Sepal.Length,y=Petal.Length,**color=Species!="setosa"**))
</code>```

I have only one color:

```<code>ggplot(iris)+ geom_point(aes(x=Sepal.Length,y=Petal.Length,**color=Species="setosa"**))
</code>```

答: did you tried using == instead of =, becuase != for sure returns a boolean, but = alone is changing the value of Species to setosa and then asigning setosa to color. you can double check by doing it outside ggplot</p>

Title: ggplot2: Using formular in aes mapping

Body:
With data iris I want to the color of point of setosa specie different to other species. The command works with != operator but =operator does not.

I have two color with:

ggplot(iris)+ geom_point(aes(x=Sepal.Length,y=Petal.Length,**color=Species!="setosa"**))

I have only one color:

ggplot(iris)+ geom_point(aes(x=Sepal.Length,y=Petal.Length,**color=Species="setosa"**))


问:
ValueError: Error when checking input: expected dense_1_input to have shape (None, None, 9000) but got array with shape (9000, 1, 4)

I simply want to make my model work, but running it produces following error:

```<code>ValueError: Error when checking input: expected dense_1_input to have shape (None, None, 9000) but got array with shape (9000, 1, 4)
</code>```

I've read every thread about problems with shape 3 times, but got no answer that would help me.

Here is my code.

What should I change to get proper shape? Any help will be very appreciated.

答:
You have given the input shape as (None,9000) in this line

```<code>model.add(Dense(units = 64, input_shape = (None, 9000)))
</code>```

But your input data is of the shape (9000,1,4).Hence you should change the input shape as

```<code>model.add(Dense(units = 64, input_shape = (1, 4)))
</code>```

The first dimension need not be specified in input_shape

Body:
I simply want to make my model work, but running it produces following error:

ValueError: Error when checking input: expected dense_1_input to have shape (None, None, 9000) but got array with shape (9000, 1, 4)

I've read every thread about problems with shape 3 times, but got no answer that would help me.

Here is my code.

What should I change to get proper shape? Any help will be very appreciated.

Body:
You have given the input shape as (None,9000) in this line

model.add(Dense(units = 64, input_shape = (None, 9000)))

But your input data is of the shape (9000,1,4).Hence you should change the input shape as

model.add(Dense(units = 64, input_shape = (1, 4)))

The first dimension need not be specified in input_shape


问:
Trust a self signed certificate using Httpclient
I'm attempting to make a web request that's failing because of a self signed certificate :

```<code>Client = new HttpClient();
HttpResponseMessage Response = await Client.GetAsync(Uri)//defined elsewhere
</code>```

This throws a trust failure exception.

I tried again using httpclienthandler as suggested here Allowing Untrusted SSL Certificates with HttpClient:

```<code> var handler = new HttpClientHandler();

 handler.ServerCertificateCustomValidationCallback =
 (
   HttpRequestMessage message,
   X509Certificate2 cert,
   X509Chain chain,
   SslPolicyErrors errors
  ) =>{return true; };//remove if this makes it to production

  Client = new HttpClient(handler);
</code>```

This blows up throwing a system not implemented exception.

Are there any other ways to trust a self signed cert? I've even installed the certificate on the machine making the request but no luck.

答:
I have seen so many question regarding this I figured I write up as a  complete answer and example as I can.

Note: Using WKWebView with self-sign certs, see this answer

HttpClient Implementation

Note: Using badssl.com in this example

Managed (Default)

System.Net.Http.HttpRequestException: An error occurred while sending the request --->
  System.Net.WebException: Error: TrustFailure (One or more errors occurred.) --->
  System.AggregateException: One or more errors occurred. --->
  System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. --->
  Mono.Security.Interface.Tl

The original Mono Managed provider is getting really long in the tooth and only supports TLS1.0, in terms of security & performance I would move to using the NSUrlSession implementation.

CFNetwork (iOS 6+)

Note: As this iOS version is fairly old now and I personally do not target it anymore, so I leave this blank... (unless someone really needs me to lookup my notes for it ;-)

NSUrlSession (iOS 7+)

Xamarin provides a HttpMessageHandler subclass (NSUrlSessionHandler) that is based upon iOS' NSUrlSession.

Using it by itself against a self-signed cert will result in:

System.Net.WebException: An SSL error has occurred and a secure connection to the server cannot be made. --->
  Foundation.NSErrorException:
  Exception of type 'Foundation.NSErrorException' was thrown.

The problem is that a self-sign cert is considered insecure and non-trusted by iOS, thus you have to apply an ATS exception to your app so iOS knows that your app is untrusted in the Info.plist.

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>self-signed.badssl.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>
</code>```

Now that iOS knows that your app is making untrusted calls, a HttpClient request will now result in this error:

System.Net.WebException: The certificate for this server is invalid. You might be connecting to a server that is pretending to be‚ self-signed.badssl.com‚ which could put your confidential information at risk. --->
  Foundation.NSErrorException: Exception of type 'Foundation.NSErrorException' was thrown.

This error is due to the fact that even though the ATS exception has been allow, the default NSUrlSession provided by iOS will apply its standard  NSUrlAuthenticationChallenge to the certificate and fail since a self-signed cert can never be truly authenticated (even via client pinning) since it does not include a root certificate authority (CA) in its chain that is trusted by iOS.

Thus you need to intercept and bypass the certificate security checking provided by iOS (Yes, a big security alert, flashing red lights, etc...)

But, you can do this via creating a NSUrlSessionDataDelegate subclass that does the bypass.

```<code>public class SelfSignedSessionDataDelegate : NSUrlSessionDataDelegate, INSUrlSessionDelegate
{
    const string host = "self-signed.badssl.com";
    public override void DidReceiveChallenge(NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
    {
        switch (challenge.ProtectionSpace.Host)
        {
            case host:
                using (var cred = NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust))
                {
                    completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.UseCredential, cred);
                }
                break;
            default:
                completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
                break;
        }
    }
}
</code>```

Now you need to apply that NSUrlSessionDataDelegate to a NSUrlSession and use that new session in the creation of your NSUrlSessionHandler that will be provided in the constructor of the HttpClient.

```<code>var url = "https://self-signed.badssl.com";
using (var selfSignedDelegate = new SelfSignedSessionDataDelegate())
using (var session = NSUrlSession.FromConfiguration(NSUrlSession.SharedSession.Configuration, (INSUrlSessionDelegate)selfSignedDelegate, NSOperationQueue.MainQueue))
using (var handler = new NSUrlSessionHandler(session))
using (var httpClient = new HttpClient(handler))
using (var response = await httpClient.GetAsync(url))
using (var content = response.Content)
{
    var result = await content.ReadAsStringAsync();
    Console.WriteLine(result);
}
</code>```

Note: Example only, normally you would create a single Delegate, NSUrlSession, HttpClient, NSUrlSessionHandler and re-use it for all your requests (i.e. Singleton pattern)

Your request now works:

```<code><html>
   <head>
    <title>self-signed.badssl.com</title>
  </head>
  <body><div id="content"><h1 style="font-size: 12vw;">
    self-signed.<br>badssl.com
    </h1></div>
  </body>
</html>
</code>```

Note: The option to supply your own custom NSUrlSession to Xamarin's  NSUrlSessionHandler is really new (Nov. 2017) and not currently in a release build (alpha, beta or stable), but of course, source is available at:

xamarin-macios/src/Foundation/NSUrlSessionHandler.cs

Using NSUrlSession instead of HttpClient:

You can also directly use a NSUrlSession instead of HttpClient against a self-signed cert.

```<code>var url = "https://self-signed.badssl.com";
using (var selfSignedDelegate = new SelfSignedSessionDataDelegate())
using (var session = NSUrlSession.FromConfiguration(NSUrlSession.SharedSession.Configuration, (INSUrlSessionDelegate)selfSignedDelegate, NSOperationQueue.MainQueue))
{
    var request = await session.CreateDataTaskAsync(new NSUrl(url));
    var cSharpString = NSString.FromData(request.Data, NSStringEncoding.UTF8).ToString();
    Console.WriteLine(cSharpString);
}
</code>```

Note: Example only, normally you would create a single Delegate and NSUrlSession and re-use it for all your requests, i.e. Singleton pattern

Real Solution? Use Free Secure Certificates:

IHMO, avoid self-signed certs all together, even in a development environment and use one of the free certificate services and avoid all the headaches of applying ATS exceptions, custom code to intercept/bypass iOS security, etc... and make your app web services actually secure.

I personally use Let’s Encrypt:

https://letsencrypt.org

Body:
I'm attempting to make a web request that's failing because of a self signed certificate :

Client = new HttpClient();
HttpResponseMessage Response = await Client.GetAsync(Uri)//defined elsewhere

This throws a trust failure exception.

I tried again using httpclienthandler as suggested here Allowing Untrusted SSL Certificates with HttpClient:

 var handler = new HttpClientHandler();

 handler.ServerCertificateCustomValidationCallback =
 (
   HttpRequestMessage message,
   X509Certificate2 cert,
   X509Chain chain,
   SslPolicyErrors errors
  ) =>{return true; };//remove if this makes it to production

  Client = new HttpClient(handler);

This blows up throwing a system not implemented exception.

Are there any other ways to trust a self signed cert? I've even installed the certificate on the machine making the request but no luck.

Body:
I have seen so many question regarding this I figured I write up as a  complete answer and example as I can.

Note: Using WKWebView with self-sign certs, see this answer

HttpClient Implementation

Note: Using badssl.com in this example

Managed (Default)

System.Net.Http.HttpRequestException: An error occurred while sending the request --->
  System.Net.WebException: Error: TrustFailure (One or more errors occurred.) --->
  System.AggregateException: One or more errors occurred. --->
  System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. --->
  Mono.Security.Interface.Tl

The original Mono Managed provider is getting really long in the tooth and only supports TLS1.0, in terms of security & performance I would move to using the NSUrlSession implementation.

CFNetwork (iOS 6+)

Note: As this iOS version is fairly old now and I personally do not target it anymore, so I leave this blank... (unless someone really needs me to lookup my notes for it ;-)

NSUrlSession (iOS 7+)

Xamarin provides a HttpMessageHandler subclass (NSUrlSessionHandler) that is based upon iOS' NSUrlSession.

Using it by itself against a self-signed cert will result in:

System.Net.WebException: An SSL error has occurred and a secure connection to the server cannot be made. --->
  Foundation.NSErrorException:
  Exception of type 'Foundation.NSErrorException' was thrown.

The problem is that a self-sign cert is considered insecure and non-trusted by iOS, thus you have to apply an ATS exception to your app so iOS knows that your app is untrusted in the Info.plist.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>self-signed.badssl.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

Now that iOS knows that your app is making untrusted calls, a HttpClient request will now result in this error:

System.Net.WebException: The certificate for this server is invalid. You might be connecting to a server that is pretending to be‚ self-signed.badssl.com‚ which could put your confidential information at risk. --->
  Foundation.NSErrorException: Exception of type 'Foundation.NSErrorException' was thrown.

This error is due to the fact that even though the ATS exception has been allow, the default NSUrlSession provided by iOS will apply its standard  NSUrlAuthenticationChallenge to the certificate and fail since a self-signed cert can never be truly authenticated (even via client pinning) since it does not include a root certificate authority (CA) in its chain that is trusted by iOS.

Thus you need to intercept and bypass the certificate security checking provided by iOS (Yes, a big security alert, flashing red lights, etc...)

But, you can do this via creating a NSUrlSessionDataDelegate subclass that does the bypass.

public class SelfSignedSessionDataDelegate : NSUrlSessionDataDelegate, INSUrlSessionDelegate
{
    const string host = "self-signed.badssl.com";
    public override void DidReceiveChallenge(NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
    {
        switch (challenge.ProtectionSpace.Host)
        {
            case host:
                using (var cred = NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust))
                {
                    completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.UseCredential, cred);
                }
                break;
            default:
                completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
                break;
        }
    }
}

Now you need to apply that NSUrlSessionDataDelegate to a NSUrlSession and use that new session in the creation of your NSUrlSessionHandler that will be provided in the constructor of the HttpClient.

var url = "https://self-signed.badssl.com";
using (var selfSignedDelegate = new SelfSignedSessionDataDelegate())
using (var session = NSUrlSession.FromConfiguration(NSUrlSession.SharedSession.Configuration, (INSUrlSessionDelegate)selfSignedDelegate, NSOperationQueue.MainQueue))
using (var handler = new NSUrlSessionHandler(session))
using (var httpClient = new HttpClient(handler))
using (var response = await httpClient.GetAsync(url))
using (var content = response.Content)
{
    var result = await content.ReadAsStringAsync();
    Console.WriteLine(result);
}

Note: Example only, normally you would create a single Delegate, NSUrlSession, HttpClient, NSUrlSessionHandler and re-use it for all your requests (i.e. Singleton pattern)

Your request now works:

<html>
   <head>
    <title>self-signed.badssl.com</title>
  </head>
  <body><div id="content"><h1 style="font-size: 12vw;">
    self-signed.<br>badssl.com
    </h1></div>
  </body>
</html>

Note: The option to supply your own custom NSUrlSession to Xamarin's  NSUrlSessionHandler is really new (Nov. 2017) and not currently in a release build (alpha, beta or stable), but of course, source is available at:

xamarin-macios/src/Foundation/NSUrlSessionHandler.cs

Using NSUrlSession instead of HttpClient:

You can also directly use a NSUrlSession instead of HttpClient against a self-signed cert.

var url = "https://self-signed.badssl.com";
using (var selfSignedDelegate = new SelfSignedSessionDataDelegate())
using (var session = NSUrlSession.FromConfiguration(NSUrlSession.SharedSession.Configuration, (INSUrlSessionDelegate)selfSignedDelegate, NSOperationQueue.MainQueue))
{
    var request = await session.CreateDataTaskAsync(new NSUrl(url));
    var cSharpString = NSString.FromData(request.Data, NSStringEncoding.UTF8).ToString();
    Console.WriteLine(cSharpString);
}

Note: Example only, normally you would create a single Delegate and NSUrlSession and re-use it for all your requests, i.e. Singleton pattern

Real Solution? Use Free Secure Certificates:

IHMO, avoid self-signed certs all together, even in a development environment and use one of the free certificate services and avoid all the headaches of applying ATS exceptions, custom code to intercept/bypass iOS security, etc... and make your app web services actually secure.

I personally use Let’s Encrypt:

https://letsencrypt.org