问:
Calculate prior ties individuals have had with other team members prior to current team
I want to calculate the number of prior ties each member has had with other team members prior to the formation of the current team.

I have the following table

TeamId UserId Date
1     100   2/1/2017
1     101   2/1/2017
1     102   2/1/2017
2     100   2//1/2016
2     105   2//1/2016
3        100   2//1/2015
3     101   2//1/2015
3        102   2//1/2015
3        105   2//1/2015
3     106   2//1/2015
4     101   1/3/2015
4     102   1/3/2015
4     105   1/3/2015
4        106   1/3/2015```
</div>
</div>
</p>

<p>I want to get the following table</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>TeamId number of previous collaborations
1        4
2         1
3        6
4         0</code>```

For example for team 1:
user 100 has collaborated with user 101 once in team 3 and with user 102 once  in team 3therefore = 1+1=2
user 101 has collaborated with user 102 twice (once in team 3 and once in team 4)= 1+1=2

so the number of previous collaborations for this team is 4.

I do not know how to write the code. any help is appreciated

SELECT [TeamId],
COUNT( SELECT [Date] FROM [submissions] s1
       WHERE s.[UserId] = [submissions].[UserId]
       AND [Date]< [submissions].[Date]
       ORDER BY [DateSubmitted] DESC) as Num_Collaborations
     )
FROM [submissions]```

答:
You can get all the user collaborations with a self-join:

```<code>select s.userid, s2.userid as userid2, s.date,
       row_number() over (order by (select null)) as c_id
from submissions s join
     submissions s2
     on s2.teamid = s.teamid;
</code>```

Let's use this as a subquery to answer your question. The idea is to match the collaborations back to the submissions -- with the constraint that the two users are on the same team at a later date.  Then, you can aggregate:

```<code>with c as (
      select s.userid, s2.userid as userid2, s.date,
             row_number() over (order by (select null)) as c_id
      from submissions s join
           submissions s2
           on s2.teamid = s.teamid
     )
select s1.teamid, count(distinct c_id) as num_previous_collaborations
from c c join
     submissions s1
     on s1.userid = c.userid and
        s1.date > c.date join  -- they are later on a team
     submissions s2
     on s2.userid = c.userid2 and
        s2.teamid = s1.teamid
group by s1.teami;
</code>```

Body:
I want to calculate the number of prior ties each member has had with other team members prior to the formation of the current team.

I have the following table

TeamId UserId Date
1     100   2/1/2017
1     101   2/1/2017
1     102   2/1/2017
2     100   2//1/2016
2     105   2//1/2016
3        100   2//1/2015
3     101   2//1/2015
3        102   2//1/2015
3        105   2//1/2015
3     106   2//1/2015
4     101   1/3/2015
4     102   1/3/2015
4     105   1/3/2015
4        106   1/3/2015

I want to get the following table

TeamId number of previous collaborations
1        4
2         1
3        6
4         0

For example for team 1:
user 100 has collaborated with user 101 once in team 3 and with user 102 once  in team 3therefore = 1+1=2
user 101 has collaborated with user 102 twice (once in team 3 and once in team 4)= 1+1=2

so the number of previous collaborations for this team is 4.

I do not know how to write the code. any help is appreciated

SELECT [TeamId],
COUNT( SELECT [Date] FROM [submissions] s1
       WHERE s.[UserId] = [submissions].[UserId]
       AND [Date]< [submissions].[Date]
       ORDER BY [DateSubmitted] DESC) as Num_Collaborations
     )
FROM [submissions]

Body:
You can get all the user collaborations with a self-join:

select s.userid, s2.userid as userid2, s.date,
       row_number() over (order by (select null)) as c_id
from submissions s join
     submissions s2
     on s2.teamid = s.teamid;

Let's use this as a subquery to answer your question. The idea is to match the collaborations back to the submissions -- with the constraint that the two users are on the same team at a later date.  Then, you can aggregate:

with c as (
      select s.userid, s2.userid as userid2, s.date,
             row_number() over (order by (select null)) as c_id
      from submissions s join
           submissions s2
           on s2.teamid = s.teamid
     )
select s1.teamid, count(distinct c_id) as num_previous_collaborations
from c c join
     submissions s1
     on s1.userid = c.userid and
        s1.date > c.date join  -- they are later on a team
     submissions s2
     on s2.userid = c.userid2 and
        s2.teamid = s1.teamid
group by s1.teami;


来源: stackexchange

问:
jekyll 3.1.6 | Error: uninitialized constant Jekyll::Filters::URLFilters
Hello Jekyll support users

I need serve this repository on Jekyll, but I has this error on Ubuntu 17.04 Terminal

```<code>geraldo@geraldo-Dell-System-XPS-L322X:~/Documentos/activate.mozilla.community$ bundle exec jekyll serve --config ./_config-dev.yml
/var/lib/gems/2.3.0/gems/jekyll-3.4.3/lib/jekyll/drops/document_drop.rb:8: warning: already initialized constant Jekyll::Drops::DocumentDrop::NESTED_OBJECT_FIELD_BLACKLIST
/usr/lib/ruby/vendor_ruby/jekyll/drops/document_drop.rb:8: warning: previous definition of NESTED_OBJECT_FIELD_BLACKLIST was here
/var/lib/gems/2.3.0/gems/jekyll-3.4.3/lib/jekyll/drops/drop.rb:8: warning: already initialized constant Jekyll::Drops::Drop::NON_CONTENT_METHODS
/usr/lib/ruby/vendor_ruby/jekyll/drops/drop.rb:8: warning: previous definition of NON_CONTENT_METHODS was here
Configuration file: ./_config-dev.yml
Configuration file: ./_config-dev.yml
jekyll 3.1.6 | Error:  uninitialized constant Jekyll::Filters::URLFilters
</code>```

Anyone here to help me?

答:
I had this problem and it turned out to be that I was using Jekyll from Ubuntu (giving version 3.1.6, as you have) instead of a recent one (such as 3.6.2).  Removing jekyll with:

```<code>sudo apt-get remove jekyll
</code>```

and then strictly using bundle cleared things up.  Also maybe try bundle update.

ContentLicense: CC BY-SA 3.0

Body:
Hello Jekyll support users

I need serve this repository on Jekyll, but I has this error on Ubuntu 17.04 Terminal

geraldo@geraldo-Dell-System-XPS-L322X:~/Documentos/activate.mozilla.community$ bundle exec jekyll serve --config ./_config-dev.yml
/var/lib/gems/2.3.0/gems/jekyll-3.4.3/lib/jekyll/drops/document_drop.rb:8: warning: already initialized constant Jekyll::Drops::DocumentDrop::NESTED_OBJECT_FIELD_BLACKLIST
/usr/lib/ruby/vendor_ruby/jekyll/drops/document_drop.rb:8: warning: previous definition of NESTED_OBJECT_FIELD_BLACKLIST was here
/var/lib/gems/2.3.0/gems/jekyll-3.4.3/lib/jekyll/drops/drop.rb:8: warning: already initialized constant Jekyll::Drops::Drop::NON_CONTENT_METHODS
/usr/lib/ruby/vendor_ruby/jekyll/drops/drop.rb:8: warning: previous definition of NON_CONTENT_METHODS was here
Configuration file: ./_config-dev.yml
Configuration file: ./_config-dev.yml
jekyll 3.1.6 | Error:  uninitialized constant Jekyll::Filters::URLFilters

Anyone here to help me?

Body:
I had this problem and it turned out to be that I was using Jekyll from Ubuntu (giving version 3.1.6, as you have) instead of a recent one (such as 3.6.2).  Removing jekyll with:

sudo apt-get remove jekyll

and then strictly using bundle cleared things up.  Also maybe try bundle update.


问:
button on top of an image (but it's not staying put)
Editing my original post ---

I had an image with text made as an image, with a button on the image that wouldn't stay put for responsive scrolling.

So I put up just the image, set the text to div. I have set my image to relative and text to absolute. ???? Now I cannot get my text div ON my jumbo image and I'm so stinking tired of this. (I also need a transparency behind my text but have given up on positioning that as well.)

HTML

```<code><div class="w3-jumboimagecontainer>
<div class="w3-display-container w3-jumboimage w3-center">
<img src="images/assistingelder.jpg" style="width:100%"></div>
<h5 class="ontop">
<h5 class="jumbonow">Now hiring</h5> <h5
class="caregiversnow">Caregivers</h5>
<h5 class="birminghamnow">in the Birmingham area</h5></h5>
<div class="w3-jumbotextsquare"">
<div class="w3-jumbobutton w3-button w3-xlarge w3-center">
<a href="caregiversapp.html" class="w3-button w3-xlarge">apply now!
</a></div></div></div></div>
</code>```

CSS

```<code>.w3-jumboimagecontainer {width: 100%;}
.w3-jumboimage {position: relative;}
h5.ontop {position: absolute;}
.w3-jumbobutton .w3-button {
background-color: #d7d78f;
border-color: #d7d78f;
color: #FFF;
border-radius: 8px;
text-transform: uppercase;
letter-spacing: 1px;
object-position: center;
}
h5.jumbonow {font-family: "proxima-nova"; helvetica; arial; sans-
serif;
font-weight: 200;
font-style: normal;
font-size: 50pt;
letter-spacing: 2px;
text-transform: uppercase;
color: white;
text-align: center;
top:0px;}
h5.caregiversnow {
font-family: georgia; serif;
font-weight: 300;
font-style: italic;
text-transform: uppercase;
font-size: 60pt;
letter-spacing: 2px;
color: white;
text-align: center;
margin-top:px;}
h5.birminghamnow {font-family: "proxima-nova"; helvetica; arial;
sans-serif;
font-weight: 100;
font-style: normal;
font-size: 30pt;
letter-spacing: 2px;
color: white;
text-align: center;
margin-top:px;}
</code>```

答:
The reason it flies away, is that left:630px; is absolute. This means when the screen is smaller, the 630px won't be centered any more.

To solve this, use relative units. There are a lot of ways to center things in css and howtocenterincss.com does a good job in giving you the css you want.

Alternatively left: 50%; transform: translate(-50%, 0); should work.

Note that the same is true for bottom, but here it might not be a problem.

However, since you also have text over your image, it would probably just be better to make the button position with that in mind.

Basically make a wrapper around both: the text and the button and align that wrapper in the middle of the image. Then just lay them out the way you want them to.

Body:
Editing my original post ---

I had an image with text made as an image, with a button on the image that wouldn't stay put for responsive scrolling.

So I put up just the image, set the text to div. I have set my image to relative and text to absolute. ???? Now I cannot get my text div ON my jumbo image and I'm so stinking tired of this. (I also need a transparency behind my text but have given up on positioning that as well.)

HTML

Now hiring

Caregivers

in the Birmingham area

apply now!

CSS

.w3-jumboimagecontainer {width: 100%;}
.w3-jumboimage {position: relative;}
h5.ontop {position: absolute;}
.w3-jumbobutton .w3-button {
background-color: #d7d78f;
border-color: #d7d78f;
color: #FFF;
border-radius: 8px;
text-transform: uppercase;
letter-spacing: 1px;
object-position: center;
}
h5.jumbonow {font-family: "proxima-nova"; helvetica; arial; sans-
serif;
font-weight: 200;
font-style: normal;
font-size: 50pt;
letter-spacing: 2px;
text-transform: uppercase;
color: white;
text-align: center;
top:0px;}
h5.caregiversnow {
font-family: georgia; serif;
font-weight: 300;
font-style: italic;
text-transform: uppercase;
font-size: 60pt;
letter-spacing: 2px;
color: white;
text-align: center;
margin-top:px;}
h5.birminghamnow {font-family: "proxima-nova"; helvetica; arial;
sans-serif;
font-weight: 100;
font-style: normal;
font-size: 30pt;
letter-spacing: 2px;
color: white;
text-align: center;
margin-top:px;}


问:
Bootstrap 3 btn-group stacking vertically
I'm attempting to create an inline btn-group inside of a column with bootstrap3 classes, but the btn group isn't behaving as expected. Instead of being connected and displayed on the same row, the buttons are being vertically stacked and also appear bigger than they should. Here is a view of what is happening:
btn-group

And the html for this part of the page:

```<code><div class="btn-group">
  <button class="btn btn-primary">
    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
  </button>
  <button class="btn btn-primary">
    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
  </button>
</div>
</code>```

Also, no CSS has been applied to the buttons. Any help or suggestions are appreciated, Thanks.

答:
Switch:

```<code><div class="btn-group">
</code>```

To:

```<code><div class="btn-group-vertical">
</code>```

Body:
I'm attempting to create an inline btn-group inside of a column with bootstrap3 classes, but the btn group isn't behaving as expected. Instead of being connected and displayed on the same row, the buttons are being vertically stacked and also appear bigger than they should. Here is a view of what is happening:
btn-group

And the html for this part of the page:

  <button class="btn btn-primary">

  </button>
  <button class="btn btn-primary">

  </button>

Also, no CSS has been applied to the buttons. Any help or suggestions are appreciated, Thanks.

Body:
Switch:

<div class="btn-group">

To:

<div class="btn-group-vertical">


问:
Uploading scores with GameKit
How do I save and upload scores later if there is no connection available? In a WWDC session it says to use the following code if no connection is available:

```<code>NSData *archivedScore = [NSKeyedArchiver archivedDataWithRootObject:[NSData dataWithBytes:&score length:sizeof(score)]];
</code>```

I then save the NSData object to NSUSerDefaults. But how do I get an int score value back from that to report?

Thanks

答:
Use NSKeyedUnarchiver (from Archives and Serializations Programming Guide)

```<code>int score = 42;
NSData *archivedScore = [NSKeyedArchiver archivedDataWithRootObject:[NSData dataWithBytes:&score length:sizeof(score)]];
int *scorePtr = [[NSKeyedUnarchiver unarchiveObjectWithData:archivedScore] bytes];
NSLog(@"score = %d", *scorePtr); // Output: score = 42
</code>```

ContentLicense: CC BY-SA 2.5

Title: Uploading scores with GameKit

Body:
How do I save and upload scores later if there is no connection available? In a WWDC session it says to use the following code if no connection is available:

NSData *archivedScore = [NSKeyedArchiver archivedDataWithRootObject:[NSData dataWithBytes:&score length:sizeof(score)]];

I then save the NSData object to NSUSerDefaults. But how do I get an int score value back from that to report?

Thanks

Body:
Use NSKeyedUnarchiver (from Archives and Serializations Programming Guide)

int score = 42;
NSData *archivedScore = [NSKeyedArchiver archivedDataWithRootObject:[NSData dataWithBytes:&score length:sizeof(score)]];
int *scorePtr = [[NSKeyedUnarchiver unarchiveObjectWithData:archivedScore] bytes];
NSLog(@"score = %d", *scorePtr); // Output: score = 42


问:
How to trigger a jQuery autocomplete plugin using Tampermonkey?
I'm trying to Tampermonkey a website that has auto-complete input text-boxes.

When a user types something in one of these text-boxes it triggers a jQuery search widget, using jqueryui 1.8.2.

I couldn't find a solution to my problem at https://jqueryui.com/autocomplete/.

What I am trying to do is take a string from my userscript and insert it in one of the text-boxes.  Then I want to trigger the jQuery search automatically.  I can get the string into the textbox easily.

```<code>$('#website_Textbox').val('My String');
</code>```

Once I put the string in I can't figure out how to trigger the jquery search.

I've tried .change(), .trigger('change') I've also tried to focus the text-box and clicking in the text-box and nothing works.

The only way to get it to search is with a keypress.  I've tried creating an event keypress and that didn't work either.  I cant send actual key-presses with javascript.  Anyone know a solution to this?

答:
Just use JQUI's "search" methodDoc.  EG:

```<code>$('#website_Textbox').val ('My String').autocomplete ("search", "My String");
</code>```

Live Demo:

var wordList = [
    "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog.",
    "Several", "fabulous", "dixieland", "jazz", "groups", "played", "with", "quick", "tempo.",
];
$("#zWords").autocomplete ( {source: wordList} );

$("button").click ( function () {
    $("#zWords").val ("er").autocomplete ("search", "er");
} );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>

<p><button>jump-start autocomplete</button></p>
<div class="ui-widget">
  <label for="zWords">Words: </label><input id="zWords">
</div></code>```

Or in a Tampermonkey script:

```<code>// ==UserScript==
// @name     _autostart JQUI autocomplete value
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    none
// ==/UserScript==

$('#website_Textbox').val ('My String').autocomplete ("search", "My String");
</code>```

Note that in some instances, use of @grant other than none might require script injection.

Body:
I'm trying to Tampermonkey a website that has auto-complete input text-boxes.

When a user types something in one of these text-boxes it triggers a jQuery search widget, using jqueryui 1.8.2.

I couldn't find a solution to my problem at https://jqueryui.com/autocomplete/.

What I am trying to do is take a string from my userscript and insert it in one of the text-boxes.  Then I want to trigger the jQuery search automatically.  I can get the string into the textbox easily.

$('#website_Textbox').val('My String');

Once I put the string in I can't figure out how to trigger the jquery search.

I've tried .change(), .trigger('change') I've also tried to focus the text-box and clicking in the text-box and nothing works.

The only way to get it to search is with a keypress.  I've tried creating an event keypress and that didn't work either.  I cant send actual key-presses with javascript.  Anyone know a solution to this?

Body:
Just use JQUI's "search" methodDoc.  EG:

$('#website_Textbox').val ('My String').autocomplete ("search", "My String");

Live Demo:

var wordList = [
    "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog.",
    "Several", "fabulous", "dixieland", "jazz", "groups", "played", "with", "quick", "tempo.",
];
$("#zWords").autocomplete ( {source: wordList} );

$("button").click ( function () {
    $("#zWords").val ("er").autocomplete ("search", "er");
} );

<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>

<p><button>jump-start autocomplete</button></p>
<div class="ui-widget">
  <label for="zWords">Words: </label><input id="zWords">
</div>

Or in a Tampermonkey script:

// ==UserScript==
// @name     _autostart JQUI autocomplete value
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    none
// ==/UserScript==

$('#website_Textbox').val ('My String').autocomplete ("search", "My String");

Note that in some instances, use of @grant other than none might require script injection.


问:
CefSharp - Get result of AJAX request
I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.

My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has completed its work.

Here an example (just a sample code):

```<code>var tasks = pdBrowser.EvaluateScriptAsync(@"
    (function(){
        $.ajax({
            type: ""POST"",
            dataType: ""json"",
            cache: false,
            url: ""_resources/php/ajaxRequests.php"",
            async: false,
            data: {
                action: ""insertCrossPlatform"",
                type: """",
                values: JSON.stringify(""foo bar"")
            },
            success: function(response) {
                if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
                {
                    return response;
                }
                    else
                {
                    //pageReload();
                    return ""OK"";
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                return errorThrown + ""\n"" + xhr.responseText;
            },
            complete: function() {
                return ""COMPLETE"";
            }
        });
    })();", null);

tasks.ContinueWith(t =>
{
     if (!t.IsFaulted)
    {
        var response = t.Result;
        if (response.Success)
        {
            if (response.Result != null)
            {
                MessageBox.Show(response.Result.ToString());
            }
        }
        else
        {
            MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}, TaskScheduler.Default);
</code>```

Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?

Thanks in advance.

答:
Something that I did was create an element on the page through javascript with an ID that is the response of the ajax call. So for example, when you make an ajax call assign an ID to the ajax call.

When the ajax call returns, write an element on the page with the pre-assigned id and callback information. Then you can just use cefsharp to read the element content from the page and this will be your callback information.

```<code>var myDivElement =document.getElementById('textareaInfo');

if( myDivElement === null)
{
var input = document.createElement('textarea');
input.id = "textareaInfo";
input.value = "Test"
input.rows="4";
input.cols="50";
input.style="height:100%;width:900px;"

var dom = document.getElementsByClassName("page-body")[0];
dom.insertAdjacentElement('afterbegin', input)
}
</code>```

Then later with ajax

```<code>var root = 'https://jsonplaceholder.typicode.com';

var _holder = callbackObj;

callbackObj.showMessage(""ajax"");

$.ajax({

  url: root + '/posts/1',
 contentType: 'application/json; charset=utf-8',
  method: 'GET',
complete: function(data){

},
 success: function(response) {

     $(#'textareaInfo').value(response);
                        }
}).then(function(data) {
   callbackObj.showMessage(data);
});
</code>```

Then read the texarea from cefsharp in c#

chromeBrowser.GetMainFrame().EvaluateScriptAsync(function()...$(textareaInfo).value).Result

Title: CefSharp - Get result of AJAX request

Body:
I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.

My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has completed its work.

Here an example (just a sample code):

var tasks = pdBrowser.EvaluateScriptAsync(@"
    (function(){
        $.ajax({
            type: ""POST"",
            dataType: ""json"",
            cache: false,
            url: ""_resources/php/ajaxRequests.php"",
            async: false,
            data: {
                action: ""insertCrossPlatform"",
                type: """",
                values: JSON.stringify(""foo bar"")
            },
            success: function(response) {
                if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
                {
                    return response;
                }
                    else
                {
                    //pageReload();
                    return ""OK"";
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                return errorThrown + ""\n"" + xhr.responseText;
            },
            complete: function() {
                return ""COMPLETE"";
            }
        });
    })();", null);

tasks.ContinueWith(t =>
{
     if (!t.IsFaulted)
    {
        var response = t.Result;
        if (response.Success)
        {
            if (response.Result != null)
            {
                MessageBox.Show(response.Result.ToString());
            }
        }
        else
        {
            MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}, TaskScheduler.Default);

Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?

Thanks in advance.

Body:
Something that I did was create an element on the page through javascript with an ID that is the response of the ajax call. So for example, when you make an ajax call assign an ID to the ajax call.

When the ajax call returns, write an element on the page with the pre-assigned id and callback information. Then you can just use cefsharp to read the element content from the page and this will be your callback information.

var myDivElement =document.getElementById('textareaInfo');

if( myDivElement === null)
{
var input = document.createElement('textarea');
input.id = "textareaInfo";
input.value = "Test"
input.rows="4";
input.cols="50";
input.style="height:100%;width:900px;"

var dom = document.getElementsByClassName("page-body")[0];
dom.insertAdjacentElement('afterbegin', input)
}

Then later with ajax

var root = 'https://jsonplaceholder.typicode.com';

var _holder = callbackObj;

callbackObj.showMessage(""ajax"");

$.ajax({

  url: root + '/posts/1',
 contentType: 'application/json; charset=utf-8',
  method: 'GET',
complete: function(data){

},
 success: function(response) {

     $(#'textareaInfo').value(response);
                        }
}).then(function(data) {
   callbackObj.showMessage(data);
});

Then read the texarea from cefsharp in c#

chromeBrowser.GetMainFrame().EvaluateScriptAsync(function()...$(textareaInfo).value).Result


问:
Simple graphQL query gives error
I am trying to use graphql for one of the GET request based on an id. Here's the code:

```<code>const { graphql, buildSchema } = require('graphql');

EmployeeService.prototype.getEmployee = function() {
  // Construct a schema
  const schema = buildSchema(`
    type Query {
      employee(id="12345") {
        id
        items {
          id
          name
        }
      }
    }
  `);

  // The root provides a resolver function
  let root = {
    employee: () => id
  };

  // Run the GraphQL query
  graphql(schema, '{ employee }', root).then((response) => {
    console.log(response);
  });
};
</code>```

Trying to follow the documentation on http://graphql.org/graphql-js/.
I get a GraphQL error: "Syntax Error GraphQL request (3:19) Expected :, found =↵↵2:     type Query {↵3:       employee (id="12345") {↵                     ^↵4:       id↵"
Please advise.

答:
You are maybe mixing things a little bit up. The schema and resolvers are part of your API and are not needed to make a query on a client. Just for demonstration purposes here a valid schema definition (that would normally run on a API server):

```<code>let schema = buildSchema(`
  type Item {
    id: Int!
    name: String!
  }

  type Employee {
    id: Int!
    items: [Item]
  }

  type Query {
    employee(id: Int!): Employee
  }
`);
</code>```

You then define your types and resolvers (simplified examples):

```<code>class Employee {
    constructor(id, items) {
        this.id = id;
        this.items = items;
    }
}

let root = {
    employee: ({id}) => {
        return new Employee(id, [{id: 1, name: 'Item 1'}, {id: 2, name: 'Item2'}]);
    }
};
</code>```

You can then run a query:

```<code>const query = `
  {
    employee(id: 1) {
      id,
      items {
        id,
        name
      }
    }
  }
`;

graphql(schema, query, root).then((response) => {
    console.log(response.data);
});
</code>```

To run actual queries against a remote API have a look at GraphQL clients like Apollo or lokka

Title: Simple graphQL query gives error

Body:
I am trying to use graphql for one of the GET request based on an id. Here's the code:

const { graphql, buildSchema } = require('graphql');

EmployeeService.prototype.getEmployee = function() {
  // Construct a schema
  const schema = buildSchema(`
    type Query {
      employee(id="12345") {
        id
        items {
          id
          name
        }
      }
    }
  `);

  // The root provides a resolver function
  let root = {
    employee: () => id
  };

  // Run the GraphQL query
  graphql(schema, '{ employee }', root).then((response) => {
    console.log(response);
  });
};

Trying to follow the documentation on http://graphql.org/graphql-js/.
I get a GraphQL error: "Syntax Error GraphQL request (3:19) Expected :, found =↵↵2:     type Query {↵3:       employee (id="12345") {↵                     ^↵4:       id↵"
Please advise.

Body:
You are maybe mixing things a little bit up. The schema and resolvers are part of your API and are not needed to make a query on a client. Just for demonstration purposes here a valid schema definition (that would normally run on a API server):

let schema = buildSchema(`
  type Item {
    id: Int!
    name: String!
  }

  type Employee {
    id: Int!
    items: [Item]
  }

  type Query {
    employee(id: Int!): Employee
  }
`);

You then define your types and resolvers (simplified examples):

class Employee {
    constructor(id, items) {
        this.id = id;
        this.items = items;
    }
}

let root = {
    employee: ({id}) => {
        return new Employee(id, [{id: 1, name: 'Item 1'}, {id: 2, name: 'Item2'}]);
    }
};

You can then run a query:

const query = `
  {
    employee(id: 1) {
      id,
      items {
        id,
        name
      }
    }
  }
`;

graphql(schema, query, root).then((response) => {
    console.log(response.data);
});

To run actual queries against a remote API have a look at GraphQL clients like Apollo or lokka


问:
Why does this output 10 for each loop? Isn't int a value type?
I was browsing through some C# examples and came upon this:

```<code>using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        delegate void Printer();

        static void Main()
        {
            List<Printer> printers = new List<Printer>();

            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { var d = i; Console.WriteLine(d); });
            }

            foreach (var printer in printers)
            {
                printer();
            }
            Console.ReadLine();
        }
    }
}
</code>```

I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.

However, this outputs 10 ten times.

Why is this? Is the int not a reference instead inside the delegate?

Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.

Edit: Example of my confusion

```<code>int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);
</code>```

This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.

Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?

In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.

答: Here, Delegate was added 10 times and reference to the variable i is taken. when calling a delegate - it is considering the last value of i which would be 10 after the for loop. For More information, check it out closure.</p>

Body:
I was browsing through some C# examples and came upon this:

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        delegate void Printer();

        static void Main()
        {
            List<Printer> printers = new List<Printer>();

            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { var d = i; Console.WriteLine(d); });
            }

            foreach (var printer in printers)
            {
                printer();
            }
            Console.ReadLine();
        }
    }
}

I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.

However, this outputs 10 ten times.

Why is this? Is the int not a reference instead inside the delegate?

Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.

Edit: Example of my confusion

int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);

This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.

Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?

In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.


问:
Haxe / OpenFL solving CORS error without having access to the server?
I know there are tons of questions regarding CORS policy in HTML5 tag.

All of them are talking about the server side settings that you need to change the access headers in the server settings or put the headers yourself in the php file etc.

But i am loading images using Loader class and i don't have access to that server.

how do i change the :

Access-Control-Allow-Origin to *

i tried pushing the headers with the URL Request :

```<code>urlRequest.requestHeaders.push( new URLRequestHeader( 'Access-Control-Allow-Origin', '*' ) );
</code>```

but no matter what i did :

i get this error :

Complete code snippet:

```<code>loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoadComplete);

var request:URLRequest = new URLRequest();
request.url = "http://www.someserver.com/some_image.jpg";

request.contentType = "image/jpeg"; //tried it didn't make a difference
request.requestHeaders.push( new URLRequestHeader( 'Access-Control-Allow-Origin', '*' ) );

loader.load(request);
</code>```

答:
Is this for development purposes? I only ask because of the 127.0.0.1 URL involved. It looks like you are hosting your game on 127.0.0.1:3000 and requesting a URL at www.___.com/___.jpg, correct?

Not considering OpenFL specifically, one typical solution would be that the server at 127.0.0.1:3000 could have a proxy capability, fetching and serving images from another web server, so that the browser doesn't see the difference.

This wouldn't help you in the real world, but if you're talking about a development environment, perhaps it's be a workaround.

Body:
I know there are tons of questions regarding CORS policy in HTML5 tag.

All of them are talking about the server side settings that you need to change the access headers in the server settings or put the headers yourself in the php file etc.

But i am loading images using Loader class and i don't have access to that server.

how do i change the :

Access-Control-Allow-Origin to *

i tried pushing the headers with the URL Request :

urlRequest.requestHeaders.push( new URLRequestHeader( 'Access-Control-Allow-Origin', '*' ) );

but no matter what i did :

i get this error :

Complete code snippet:

loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoadComplete);

var request:URLRequest = new URLRequest();
request.url = "http://www.someserver.com/some_image.jpg";

request.contentType = "image/jpeg"; //tried it didn't make a difference
request.requestHeaders.push( new URLRequestHeader( 'Access-Control-Allow-Origin', '*' ) );

loader.load(request);


问:
Sequelize: Updating Model and its Associations
I have the following tables:

Event

Tasks

and the following association

```<code>Event.hasMany(models.Tasks, {
      as: 'tasks',
       foreignKey: 'event_id'
})
</code>```

I am using the following code to update an Event and an array of Tasks

```<code>db.Event.findOne({
    where: {
        id: eventToUpdate.id
    },
    include: [{
        model: db.Tasks,
        as: 'tasks',
    }]
}).then((existingEvent) => {
   // Loop through existingEvent attributes and existingEvent.dataValues.tasks and
   // updated the attributes
}
</code>```

However, when I update it:

```<code>        db.Event.update(existingEvent, { where: { id: existingEvent.id } })
            .then((updatedEvent) => {
                console.log(updatedEvent)
            }).catch((error) => {
                console.log("Error + error)
            })
</code>```

Only Event is updated in the database, but not its Tasks.

What am I doing wrong? or is there a better way to accomplish this?

答:
Difficult to update it in the comment. But this is what I would suggest to do,</p>

```<code>db.Event.findOne({
    where: {
        id: eventToUpdate.id
    },
    include: [{
        model: db.Tasks,
        as: 'tasks',
    }]
}).then((existingEvent) => {
   return Promise.all(existingEvent.tasks.map(task => task.updateAttributes(taskParams).then(console.log).catch(console.log));
}
</code>```

Body:
I have the following tables:

Event

Tasks

and the following association

Event.hasMany(models.Tasks, {
      as: 'tasks',
       foreignKey: 'event_id'
})

I am using the following code to update an Event and an array of Tasks

db.Event.findOne({
    where: {
        id: eventToUpdate.id
    },
    include: [{
        model: db.Tasks,
        as: 'tasks',
    }]
}).then((existingEvent) => {
   // Loop through existingEvent attributes and existingEvent.dataValues.tasks and
   // updated the attributes
}

However, when I update it:

        db.Event.update(existingEvent, { where: { id: existingEvent.id } })
            .then((updatedEvent) => {
                console.log(updatedEvent)
            }).catch((error) => {
                console.log("Error + error)
            })

Only Event is updated in the database, but not its Tasks.

What am I doing wrong? or is there a better way to accomplish this?

Body:
Difficult to update it in the comment. But this is what I would suggest to do,

db.Event.findOne({
    where: {
        id: eventToUpdate.id
    },
    include: [{
        model: db.Tasks,
        as: 'tasks',
    }]
}).then((existingEvent) => {
   return Promise.all(existingEvent.tasks.map(task => task.updateAttributes(taskParams).then(console.log).catch(console.log));
}


问:
MarkLogic: XDMP-UNSEARCHABLE error or searchable path expression
Help me to understand "fully searchable path expression".  Examples of  unsearchable path expressions are:

```<code>xquery version "1.0-ml";
(:constructed sequence :)
cts:search((<last_name>Mortensen</last_name>,<last_name>Hurt</last_name>,<last_name>Bello</last_name>),cts:word-query("Bello"))
</code>```

or

XPATH expression that uses variables like $doc/movies//country (called "dynamic path" in "Xquery" Priscilla Walmsley book)

or

XPATH expressions that use XPath axis different than child:: or descendant::, for example:

```<code>cts:search(doc("doc/movies")/descendant::year[. = '1995']/parent::movie ,cts:word-query("Tom Stall"))
</code>```

or
see example MarkLogic: Understanding searchable and unsearchable queries?

What is a  formal definition of "searchable path expression" ?

答:
The clear example of what searchable path expression means is defined under the conveniently named section 'Fully Searchable Paths and cts:search Operations'..

Looking at your code, I suggest that you have a read through the Search Developer's Guide. For convenience, here is the deep link to the cts:search section.

Furthermore, you mention xQuery and reference a book or other literature. There a re many versions of xQuery  - with the current W3C recommendation being version3.1. You probably want to have a look at the description of MarkLogic's
implementation as it is originally derived from the 1.0 dialect and has been enhanced throughout the years.

Edit:
The user has since asked for more guidance
 via the comments. Below is one (of many) possible solutions based on the original code sample:

```<code>xquery version "1.0-ml";
(:constructed sequence :)
let $last-name := ('Mortensen','Hurt','Bello')
return cts:search(fn:collection(),cts:and-query(
            (
              cts:element-word-query(xs:QName('last-name'),  $last-name),
              cts:word-query("Bello")
            )
          )
         )
</code>```

Body:
Help me to understand "fully searchable path expression".  Examples of  unsearchable path expressions are:

xquery version "1.0-ml";
(:constructed sequence :)
cts:search((<last_name>Mortensen</last_name>,<last_name>Hurt</last_name>,<last_name>Bello</last_name>),cts:word-query("Bello"))

or

XPATH expression that uses variables like $doc/movies//country (called "dynamic path" in "Xquery" Priscilla Walmsley book)

or

XPATH expressions that use XPath axis different than child:: or descendant::, for example:

cts:search(doc("doc/movies")/descendant::year[. = '1995']/parent::movie ,cts:word-query("Tom Stall"))

or
see example MarkLogic: Understanding searchable and unsearchable queries?

What is a  formal definition of "searchable path expression" ?

Body:
The clear example of what searchable path expression means is defined under the conveniently named section 'Fully Searchable Paths and cts:search Operations'..

Looking at your code, I suggest that you have a read through the Search Developer's Guide. For convenience, here is the deep link to the cts:search section.

Furthermore, you mention xQuery and reference a book or other literature. There a re many versions of xQuery  - with the current W3C recommendation being version3.1. You probably want to have a look at the description of MarkLogic's
implementation as it is originally derived from the 1.0 dialect and has been enhanced throughout the years.

Edit:
The user has since asked for more guidance
 via the comments. Below is one (of many) possible solutions based on the original code sample:

xquery version "1.0-ml";
(:constructed sequence :)
let $last-name := ('Mortensen','Hurt','Bello')
return cts:search(fn:collection(),cts:and-query(
            (
              cts:element-word-query(xs:QName('last-name'),  $last-name),
              cts:word-query("Bello")
            )
          )
         )


问:
Should executable Python script be named with .py?
I'm writing a Python script that is only meant to be run from the console. e.g.: $> myscript.

I'm wondering what is the leading conventions in Python for scripts of this sort. Should I call it myscript, or myscript.py?

答:
Yes

Why?

Portability

Python scripts in Linux environments are recognized as such, but NT is... special. If there's ever a need to move it to anything made by microsoft, you need the extension.

Readability

Appending a filename extension to it will make it obvious what kind of file it is, for when others look in your directories.

Useability

If ever you need to call it into python as a module, you NEED the .py extension.

Convention

It is the standard for all python scripts to have the .py or .pyc extension on them.


问:
How do I get yesterday date in Freeswitch?
In Freeswitch dialplan, I know I can get today date using ${strftime(%Y%m%d}, but how do I get yesterday date correctly?
I can do ${strftime(%Y%m)}${expr(${strftime(%d}-1)}, but what about yesterday date of Jan, 1st, 2017?
Thanks for all your helps.</p>

答:
var.xml

```<code><X-PRE-PROCESS cmd="exec-set" data="yesterday=date -d 'yesterday' +'%b %d %Y'">
</code>```

fs_cli

```<code>freeswitch@host> eval $${yesterday}
Nov 16 2017
</code>```

Body:
var.xml

<X-PRE-PROCESS cmd="exec-set" data="yesterday=date -d 'yesterday' +'%b %d %Y'">

fs_cli

freeswitch@host> eval $${yesterday}
Nov 16 2017


问:
What does "num_examples: 2000" mean in TensorFlow object detection config file?

In the sample pipeline config file of TensorFlow object detection, there is this snippet:

  eval_config: {
    num_examples: 2000
    # Note: The below line limits the evaluation process to 10 evaluations.
    # Remove the below line to evaluate indefinitely.
    max_evals: 10
  }
```

Does "num_examples" mean each evaluation run uses the same first 2000 images, or it treats the test set as a circular buffer and uses different 2000 images each time?

答: Actually this means only the same top num_examples samples in your evaluation dataset will be used in each run of evaluation.

Body:
In the sample pipeline config file of TensorFlow object detection, there is this snippet:

  eval_config: {
    num_examples: 2000
    # Note: The below line limits the evaluation process to 10 evaluations.
    # Remove the below line to evaluate indefinitely.
    max_evals: 10
  }

Does "num_examples" mean each evaluation run uses the same first 2000 images, or it treats the test set as a circular buffer and uses different 2000 images each time?


问:
Delphi & Twebbrowser - How to recover a security token supplied by a login page?
I am using the Twebbrowser in Delphi (2009) to log into cpanel on my ISP and add a new remote host IP address for a MySQL database. The user name and password are filled in by code as is clicking the submit button, using code gleaned from several places here.

Navigating directly to the hosts page causes the cpanel login page to be shown first. My program detects this and logs me in.

This uses a line like

```<code>WebBrowser1.Navigate'https://thedomain.sgcpanel.com:2083/cpsess1819495779/frontend/Crystal/sql/managehost.html');
</code>```

which reaches the hosts page OK but I notice that the security token (cpsess1819495779) is changed to something else each time, presumably being supplied by the login page.

However if I try to login first as a separate operation and then navigate to the hosts page using

```<code>WebBrowser1.Navigate('https://thedomain.sgcpanel.com:2083');
</code>```

followed by

```<code>WebBrowser1.Navigate'https://thedomain.sgcpanel.com:2083/cpsess1819495779/frontend/Crystal/sql/managehost.html');
</code>```

I get a server message saying the url for the hosts page has an invalid security token - presumably the cpsess1819495779 bit

Question

How can I use Twebbrowser to get hold of the security token generated by the login page in order to use it to build the correct url for the hosts page so that I pass the correct security token each time.

It's probably something to do with cookies etc but I don't know how to deal with those (yet)

BTW as the Twebbrowser is not visible I did spend quite a few days trying to do the same thing using Indy's TIdHTTP but have given up with that as am getting too many errors I can't sort out.

答:
I may as well answer this myself to close the question and maybe avoid any more down votes for posting a question after extensive research failed to produce the answer and that was framed without much of my code for brevity.

The API documentation for cpanel (the application used by many ISPs to manage MySQL, email etc) is here: https://documentation.cpanel.net/display/SDK/Guide+to+cPanel+API+2

part of that says

Security token     After you log in to your server, it automatically appends a security token to the URL for your session. Security tokens
  help prevent authorized use of a website through XSRF (Cross-Site
  Request Forgery). Security tokens contain the string cpsess and a
  10-digit number.

Logging in manually in IE / Chrome etc. does indeed show the token eg cpsess1819495779 inserted into the original url that was navigated to. So if I navigate to

https://thedomain.sgcpanel.com:2083/cpsess0000000000/frontend/Crystal/sql/managehost.html

(to logon to cpanel), the part of the url displayed in the browser after cpsess gets changed to something like this, where the number changes each time.

https://secureukm11.sgcpanel.com:2083/cpsess1819495779/frontend/Crystal/sql/managehost.html

However, using Twebbrowser to show that modified url using

```<code>memo1.Lines.Add(WebBrowser1.LocationURL);
</code>```

or

```<code>ShowMessage('URL: ' + Webbrowser1.OleObject.Document.Url);
</code>```

simply shows the original url with the zeros, not the real security token.

So the answer to my question seems to be it can't be done in Twebbrowser as the url is only changed at the server and and the security token is not transmitted back to the browser.

Body:
I am using the Twebbrowser in Delphi (2009) to log into cpanel on my ISP and add a new remote host IP address for a MySQL database. The user name and password are filled in by code as is clicking the submit button, using code gleaned from several places here.

Navigating directly to the hosts page causes the cpanel login page to be shown first. My program detects this and logs me in.

This uses a line like

WebBrowser1.Navigate'https://thedomain.sgcpanel.com:2083/cpsess1819495779/frontend/Crystal/sql/managehost.html');

which reaches the hosts page OK but I notice that the security token (cpsess1819495779) is changed to something else each time, presumably being supplied by the login page.

However if I try to login first as a separate operation and then navigate to the hosts page using

WebBrowser1.Navigate('https://thedomain.sgcpanel.com:2083');

followed by

WebBrowser1.Navigate'https://thedomain.sgcpanel.com:2083/cpsess1819495779/frontend/Crystal/sql/managehost.html');

I get a server message saying the url for the hosts page has an invalid security token - presumably the cpsess1819495779 bit

Question

How can I use Twebbrowser to get hold of the security token generated by the login page in order to use it to build the correct url for the hosts page so that I pass the correct security token each time.

It's probably something to do with cookies etc but I don't know how to deal with those (yet)

BTW as the Twebbrowser is not visible I did spend quite a few days trying to do the same thing using Indy's TIdHTTP but have given up with that as am getting too many errors I can't sort out.

Body:
I may as well answer this myself to close the question and maybe avoid any more down votes for posting a question after extensive research failed to produce the answer and that was framed without much of my code for brevity.

The API documentation for cpanel (the application used by many ISPs to manage MySQL, email etc) is here: https://documentation.cpanel.net/display/SDK/Guide+to+cPanel+API+2

part of that says

Security token     After you log in to your server, it automatically appends a security token to the URL for your session. Security tokens
  help prevent authorized use of a website through XSRF (Cross-Site
  Request Forgery). Security tokens contain the string cpsess and a
  10-digit number.

Logging in manually in IE / Chrome etc. does indeed show the token eg cpsess1819495779 inserted into the original url that was navigated to. So if I navigate to

https://thedomain.sgcpanel.com:2083/cpsess0000000000/frontend/Crystal/sql/managehost.html

(to logon to cpanel), the part of the url displayed in the browser after cpsess gets changed to something like this, where the number changes each time.

https://secureukm11.sgcpanel.com:2083/cpsess1819495779/frontend/Crystal/sql/managehost.html

However, using Twebbrowser to show that modified url using

memo1.Lines.Add(WebBrowser1.LocationURL);

or

ShowMessage('URL: ' + Webbrowser1.OleObject.Document.Url);

simply shows the original url with the zeros, not the real security token.

So the answer to my question seems to be it can't be done in Twebbrowser as the url is only changed at the server and and the security token is not transmitted back to the browser.


问:
Visual Studio Code Integrated Terminal: http-server : The term 'http-server' is not recognized
I am new to Angular and hence Visual Studio Code. I started with my first Angular application by following online tutorial. When I tried to execute http-server on VS code integrated terminal, I got the below error. I could not find, how to resolve.

PS C:\MyFolder\Learning\Angular> http-server
  http-server : The term 'http-server' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
  was included, verify that the path is correct and try again.
  At line:1 char:1
  + http-server
  + ~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (http-server:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

答:
Have you installed it globally?

npm i -g http-server

To be able to use a package in your terminal you need to have it installed globally on your machine.


问:
Why is no map function for dataframe in pyspark while the spark equivalent has it?
Currently working on PySpark. There is no map function on DataFrame, and one has to go to RDD for map function. In Scala there is a map on DataFrame, is there any reason for this?

答:
Dataset.map is not part of the DataFrame (Dataset[Row]) API. It transforms strongly typed Dataset[T] into strongly typed Dataset[U]:

```<code>def map[U](func: (T) ⇒ U)(implicit arg0: Encoder[U]): Dataset[U]
</code>```

and there is simply no place for Python in the strongly typed Dataset world. In general, Datasets are native JVM objects (unlike RDD it has not Python specific implementation) which depend heavily on rich Scala type system (even Java API is severely limited). Even if Python implemented some variant of the Encoder API, data would still have to be converted to RDD for computations.

In contrast Python implements its own map like mechanism with vectorized udfs, which should be released in Spark 2.3. It is focused on high performance serde implementation coupled with Pandas API.

That includes both typical udfs (in particular SCALAR and SCALAR_ITER variants) as well as map-like variants - GROUPED_MAP and MAP_ITER applied through GroupedData.apply and DataFrame.mapInPandas (Spark >= 3.0.0) respectively.

Body:
Dataset.map is not part of the DataFrame (Dataset[Row]) API. It transforms strongly typed Dataset[T] into strongly typed Dataset[U]:

def map[U](func: (T) ⇒ U)(implicit arg0: Encoder[U]): Dataset[U]

and there is simply no place for Python in the strongly typed Dataset world. In general, Datasets are native JVM objects (unlike RDD it has not Python specific implementation) which depend heavily on rich Scala type system (even Java API is severely limited). Even if Python implemented some variant of the Encoder API, data would still have to be converted to RDD for computations.

In contrast Python implements its own map like mechanism with vectorized udfs, which should be released in Spark 2.3. It is focused on high performance serde implementation coupled with Pandas API.

That includes both typical udfs (in particular SCALAR and SCALAR_ITER variants) as well as map-like variants - GROUPED_MAP and MAP_ITER applied through GroupedData.apply and DataFrame.mapInPandas (Spark >= 3.0.0) respectively.

ContentLicense: CC BY-SA 4.0


答:
Run this from within the terminal:

```<code>npm install -g http-server
</code>```

What this will do is install the latest version of http-server globally on your computer. Then you can run it from the terminal, or another command prompt, when you need to serve a web application.

See this for more information on the package, and how to use it.

Title: Visual Studio Code Integrated Terminal: http-server : The term 'http-server' is not recognized

Body:
I am new to Angular and hence Visual Studio Code. I started with my first Angular application by following online tutorial. When I tried to execute http-server on VS code integrated terminal, I got the below error. I could not find, how to resolve.

PS C:\MyFolder\Learning\Angular> http-server
  http-server : The term 'http-server' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
  was included, verify that the path is correct and try again.
  At line:1 char:1
  + http-server
  + ~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (http-server:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

Body:
Run this from within the terminal:

npm install -g http-server

What this will do is install the latest version of http-server globally on your computer. Then you can run it from the terminal, or another command prompt, when you need to serve a web application.

See this for more information on the package, and how to use it.


问:
Running an expensive method in the view VS in the controller - Rails
Running the risk of being tagged as "too broad", but this is an authentic doubt.

Say I have
@my_model.complex_calculation_result to show in a view.

What are the pros and cons of:

1 - Calculating the value on the controller and send it to the view

Controller:

@result = @my_model.complex_calculation_result # caching the value in the controller

View:

<%= @result %>

2 - Calculating it directly in the view

<%= @my_model.complex_calculation_result %>

I know the last alternative represents less code and I have one less instance variable hanging around.

But are there performance diferences?

Guess 1 - the view already takes more memory to render it all, so the calculation can take longer from inside the view if it is memory expensive.

Any light shed on this and comments will be highly appreciated. :)

答: While I'm not answering the performance part of your question, you are breaking the Rails MVC principle when going the 2nd way. The View is not meant to perform any (especially complex) calculations on Model data.</p>


问:
Images not loading when file is moved from one computer to the other
I have stored the links to images in a database so I can display them in my web application. The image folder is insider my project folder in htdocs. It works perfectly, but when I copy the project folder from the original htdocs and paste it in the htdocs of another computer, the images fail to load even though the path remains the same. I will be glad if the programmers here can explain to me what is happening. Thank you

here is the server response http://localhost:8080/folder/image/%2059f1c3840bf9b4.70759324.jpg Failed to load resource: the server responded with a status of 404 (Not Found)
NB: %20 is not part of the image name. It is a space

答:
Either your path is off, or the other machine is not using port 8080.

Most of the time, port 80 is the default, which does not need any port suffix.

You should try:

```<code>http://localhost/folder/image/%2059f1c3840bf9b4.70759324.jpg
</code>```

and if that does not do it, then open your command line and

cd path/to/localhost/folder/image/

then
pwd to get the current folder path from that location.

It should also be noted that %20 is a " " space character, and they tend to derp up file paths frequently. For ease of reference, try not to use file names with spaces for anything served on the web.

Body:
Either your path is off, or the other machine is not using port 8080.

Most of the time, port 80 is the default, which does not need any port suffix.

You should try:

http://localhost/folder/image/%2059f1c3840bf9b4.70759324.jpg

and if that does not do it, then open your command line and

cd path/to/localhost/folder/image/

then
pwd to get the current folder path from that location.

It should also be noted that %20 is a " " space character, and they tend to derp up file paths frequently. For ease of reference, try not to use file names with spaces for anything served on the web.


问:
NoHostAvailableException in Cassandra
I need to make a presentation+ connection to cassandra for classes. After quite a big hussle I left behind other kinds of errors, but I'm getting stuck here, where it seems not to get the address of the Keyspace.

```<code>import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;

public class conectaradb {

public static void main(String[] args) {
 try {
    Cluster cluster;
     Session sesion;

     cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).build();

     sesion= cluster.connect("ejemplodb");

     ResultSet resultado= sesion.execute("select * from empleados");
     String nombreemp,fecha,cargo;
     double comision,salario;
     int empno;

     for (Row row:resultado) {
         empno=row.getInt("empno");
         cargo=row.getString("cargo");
         comision=row.getDouble("comision");
         fecha=row.getString("fechaing");
         nombreemp=row.getString("nombreempno");
         salario=row.getDouble("salario");
         System.out.println(empno+" "+cargo+" "+comision+" "+fecha+" "+nombreemp+" "+salario);
     }
     cluster.close();

 }catch(NoHostAvailableException e) {
 System.out.println(e.getErrors());
}

}

}
</code>```

I'd be glad if someone can Identify where is the error, I think I have the yaml file right. I get the error when the code reaches the localhost on addcontactpoint: "All hosts tried for query failed".
After a .getError I get a "TransportException". I don't know how to proceed further.

答:
I looked at the yaml file in the comments. First of all the rpc_address is wrong, it should not be 0.0.0.0. But you fixed that already.

The next error is that you set native_transport_port: 9042 and rpc_port: 9042. You can't use the same port for both interfaces. Thrift (rpc) is the old interface and should not really be used so if I where you I would set start_rpc: false, but of course changing the port would be enough. Look here for more information: https://academy.datastax.com/planet-cassandra/making-the-change-from-thrift-to-cql

If you get any more errors let me know and I'll update the answer.

Title: NoHostAvailableException in Cassandra

Body:
I need to make a presentation+ connection to cassandra for classes. After quite a big hussle I left behind other kinds of errors, but I'm getting stuck here, where it seems not to get the address of the Keyspace.

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;

public class conectaradb {

public static void main(String[] args) {
 try {
    Cluster cluster;
     Session sesion;

     cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).build();

     sesion= cluster.connect("ejemplodb");

     ResultSet resultado= sesion.execute("select * from empleados");
     String nombreemp,fecha,cargo;
     double comision,salario;
     int empno;

     for (Row row:resultado) {
         empno=row.getInt("empno");
         cargo=row.getString("cargo");
         comision=row.getDouble("comision");
         fecha=row.getString("fechaing");
         nombreemp=row.getString("nombreempno");
         salario=row.getDouble("salario");
         System.out.println(empno+" "+cargo+" "+comision+" "+fecha+" "+nombreemp+" "+salario);
     }
     cluster.close();

 }catch(NoHostAvailableException e) {
 System.out.println(e.getErrors());
}

}

}

I'd be glad if someone can Identify where is the error, I think I have the yaml file right. I get the error when the code reaches the localhost on addcontactpoint: "All hosts tried for query failed".
After a .getError I get a "TransportException". I don't know how to proceed further.


问:
Cannot convert value of type 'String' to expected argument type 'NSStoryboard.Name'
I'm trying the following in swift:

```<code>var storyboard = NSStoryboard.init(name: "Actors", bundle: nil)
</code>```

This generates an error: Cannot convert value of type 'String' to expected argument type 'NSStoryboard.Name'

According to the class reference NSStoryboard.Name should be a string without the file extension, which I supply.

What is wrong?

答:
This should solve the issue </p>

```<code>var storyboard = NSStoryboard.init(name: NSStoryboard.Name(rawValue: "Actors"), bundle: nil)
</code>```

Body:
I'm trying the following in swift:

var storyboard = NSStoryboard.init(name: "Actors", bundle: nil)

This generates an error: Cannot convert value of type 'String' to expected argument type 'NSStoryboard.Name'

According to the class reference NSStoryboard.Name should be a string without the file extension, which I supply.

What is wrong?

Body:
This should solve the issue

var storyboard = NSStoryboard.init(name: NSStoryboard.Name(rawValue: "Actors"), bundle: nil)


问:
SQLite issue with Table Names using numbers?
I'm developing an app which requires that the user selects a year formatted like this 1992-1993 from a spinner. The tablename is also named 1992-1993 and the idea is that using SQL the values from this table are pulled through with a statement like this select * from 1992-1993. When I run the emulator however, it throws an error.

If I then relabel the Spinner item to NinetyTwo and rename the table to NinetyTwo and run the emulator it runs as expected and the data is pulled through from the table.

Does SQLite have an issue with numbers in table names?

答:
sorry for late post

There may be a deeper issue here - is the structure you are using (table name per item in spinner) the best one for the job?

You may find that you want a number of tables e.g.

spinner_value (id, value)
form_data(id, spinner_value_id, etc ....)


问:
Are HTML tables somehow defined to sit at the bottom of a containing cell?
I was using the following tutorial to improve some of my layout and learn more about CSS display properties: https://www.sitepoint.com/solving-layout-problems-css-table-property/

The info seems straightforward enough and I tried to reorganize my layout in one particular
 into one such wrapper, adding a Google Maps  in the middle section:

snip of my current webpage

As you can see from the screenshot, the HTML tables I'm using in the left and right CSS cells are sticking to the bottom, while the iframe is sticking to the top, and for the life of me I can't understand why.

I created a new page to test this out first by copying PRECISELY the code from the www.sitepoint.com tutorial. By default it worked exactly as the example did:

snip of exact code match

But when I wrap the paragraphs in HTML tables, the same behavior takes place:

snip of paragraphs wrapped in
 structure

Is there something about
 behavior that I don't understand? Why don't both of my tables lineup vertically with the ? Each of the three
 have identical CSS:

```<code>.wrapper-cell {
display: table-cell;
width: 33.33%;
padding: 10px;
float: none;
}
</code>```

None of it tells the data where to align vertically. I'm so utterly confused. Any clarity out there?

答:
The default value for vertical-align is baseline. The baseline for your Contact and Location tables are, approximately and hand-wavy, the bottom of the first line of text in the first row. But the baseline for an iframe is (apparently) its bottom edge. Notice that the bottom of Contact, Location, and the iframe are aligned.

So change the vertical-align property on the table cells to something else, like top or bottom.

https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align

And, yeah, as the other comments say, post your full HTML and CSS in the future.

Body:
I was using the following tutorial to improve some of my layout and learn more about CSS display properties: https://www.sitepoint.com/solving-layout-problems-css-table-property/

The info seems straightforward enough and I tried to reorganize my layout in one particular
 into one such wrapper, adding a Google Maps  in the middle section:

snip of my current webpage

As you can see from the screenshot, the HTML tables I'm using in the left and right CSS cells are sticking to the bottom, while the iframe is sticking to the top, and for the life of me I can't understand why.

I created a new page to test this out first by copying PRECISELY the code from the www.sitepoint.com tutorial. By default it worked exactly as the example did:

snip of exact code match

But when I wrap the paragraphs in HTML tables, the same behavior takes place:

snip of paragraphs wrapped in
 structure

Is there something about
 behavior that I don't understand? Why don't both of my tables lineup vertically with the ? Each of the three
 have identical CSS:

.wrapper-cell {
display: table-cell;
width: 33.33%;
padding: 10px;
float: none;
}

None of it tells the data where to align vertically. I'm so utterly confused. Any clarity out there?


问:
How can I force ggplot to show more levels on the legend?
I'm trying to create a complex ggplot plot but some things don't work as expected.

I have extracted the problematic part, the creation of points and its associated legend.

```<code>library(data.table)
library(ggplot2)
lev <- c("A", "B", "C", "D") # define levels.
bb <- c(40, 30,20,10,5)/100 # define breaks.
ll <- c("40%","30%","20%","10%","5%") # labels.
# Create data
nodos <- data.table(event = c("A", "B", "D", "C", "D"), ord = c(1, 2, 3, 3, 4),
NP = c(0.375, 0.25, 0.125, 0.125, 0.125))

ggplot() + geom_point(data=nodos,aes(x=ord,
 y=event, size=NP), color="black", shape=16) +
 ylim(lev)  + scale_size_continuous(name="Prop.",
 breaks=bb, labels=ll, range=c(0,6))+
 scale_x_continuous(limits=c(0.5, 4.5),
 breaks=seq(1,4,1))
</code>```

As you can see, no matter what breaks and labels I use I'm not able to force ggplot to paint a legend containing 0% or 10%.
scale_size_continuous keeps creating just two elements.

And the smaller points are very badly scaled.

I have also tried with scale_scale_area, but it doesn't work either.

I'm using R 3.4.2 and ggplot2 2.2.1 (also tried the latest github version).

How can I get it?

答:
If you set the limits to encompass the breaks you'll be able to alter the legend.  Current most of the breaks are outside the default limits of the scale.

```<code>ggplot() +
    geom_point(data = nodos,
               aes(x = ord, y = event, size = NP), color="black", shape = 16) +
    scale_size_continuous(name = "Prop.",
                          breaks = bb,
                          limits = c(.05, .4),
                          labels = ll,
                          range = c(0, 6) )
</code>```

Body:
I'm trying to create a complex ggplot plot but some things don't work as expected.

I have extracted the problematic part, the creation of points and its associated legend.

library(data.table)
library(ggplot2)
lev <- c("A", "B", "C", "D") # define levels.
bb <- c(40, 30,20,10,5)/100 # define breaks.
ll <- c("40%","30%","20%","10%","5%") # labels.
# Create data
nodos <- data.table(event = c("A", "B", "D", "C", "D"), ord = c(1, 2, 3, 3, 4),
NP = c(0.375, 0.25, 0.125, 0.125, 0.125))

ggplot() + geom_point(data=nodos,aes(x=ord,
 y=event, size=NP), color="black", shape=16) +
 ylim(lev)  + scale_size_continuous(name="Prop.",
 breaks=bb, labels=ll, range=c(0,6))+
 scale_x_continuous(limits=c(0.5, 4.5),
 breaks=seq(1,4,1))

As you can see, no matter what breaks and labels I use I'm not able to force ggplot to paint a legend containing 0% or 10%.
scale_size_continuous keeps creating just two elements.

And the smaller points are very badly scaled.

I have also tried with scale_scale_area, but it doesn't work either.

I'm using R 3.4.2 and ggplot2 2.2.1 (also tried the latest github version).

How can I get it?

Body:
If you set the limits to encompass the breaks you'll be able to alter the legend.  Current most of the breaks are outside the default limits of the scale.

ggplot() +
    geom_point(data = nodos,
               aes(x = ord, y = event, size = NP), color="black", shape = 16) +
    scale_size_continuous(name = "Prop.",
                          breaks = bb,
                          limits = c(.05, .4),
                          labels = ll,
                          range = c(0, 6) )


问:
How can I get last characters of a string
I have

```<code>var id="ctl03_Tabs1";
</code>```

Using JavaScript, how might I get the last five characters or last character?

答:
If you just want the last character or any character at know position you can simply trat string as an array! - strings are iteratorable in javascript -

```<code>Var x = "hello_world";
 x[0];                    //h
 x[x.length-1];   //d
</code>```

Yet if you need more than just one character then use splice is effective

```<code>x.slice(-5);      //world
</code>```

Regarding your example

```<code>"rating_element-<?php echo $id?>"
</code>```

To extract id you can easily use split + pop

```<code>Id= inputId.split('rating_element-')[1];
</code>```

This will return the id, or undefined if no id was after 'rating_element'
:)

Body:
I have

var id="ctl03_Tabs1";

Using JavaScript, how might I get the last five characters or last character?

Body:
If you just want the last character or any character at know position you can simply trat string as an array! - strings are iteratorable in javascript -

Var x = "hello_world";
 x[0];                    //h
 x[x.length-1];   //d

Yet if you need more than just one character then use splice is effective

x.slice(-5);      //world

Regarding your example

"rating_element-<?php echo $id?>"

To extract id you can easily use split + pop

Id= inputId.split('rating_element-')[1];

This will return the id, or undefined if no id was after 'rating_element'
:)


问:
How do I delete the last row of a group in r based on conditions in a different row in r
I have a data frame like this (NT and MCS are text placeholders for a certain species let's say)

```<code>A <- c("NT", "MCS","MCS","NT", "MCS", "MCS", "NT", "MCS", "MCS", "MCS",
       "NT", "MCS", "MCS","NT", "MCS","NT","NT","MCS", "MCS","NT")
B <- c("1", "3", "3","3","3", "3","3","4","4","4","4","3",
       "3","3","2","2","1","3","3","3")
C <- c("G1", "G2", "G2", "G2", "G3", "G3", "G3", "G4", "G4", "G4", "G4",
       "G5", "G5", "G5","G6", "G6", "G7","G8","G8","G8")

df <- data.frame(A,B,C)

A   B   C
NT  1   G1
MCS 3   G2
MCS 3   G2
NT  3   G2
MCS 3   G3
MCS 3   G3
NT  3   G3
MCS 4   G4
MCS 4   G4
MCS 4   G4
NT  4   G4
MCS 3   G5
MCS 3   G5
NT  3   G5
MCS 2   G6
NT  2   G6
NT  1   G7
MCS 3   G8
MCS 3   G8
NT  3   G8
</code>```

The A column represents the species. The B column represents an integer value that equals the the number of rows in each group. C column represents unique groups. The criteria is as follows: Delete the LAST row of every group/species IF B > 1. If B = 1, then NT (or the only row in that group) should remain. Here is what I need it to look like.

```<code>A   B   C
NT  1   G1
MCS 3   G2
MCS 3   G2
MCS 3   G3
MCS 3   G3
MCS 4   G4
MCS 4   G4
MCS 4   G4
MCS 3   G5
MCS 3   G5
MCS 2   G6
NT  1   G7
MCS 3   G8
MCS 3   G8

new<- df %>% group_by(A, B) %>% slice(if(any(numb > 1)) 1:n())
</code>```

The above is the closest code I've run but it doesn't evaluate to an integer or numeric vector (which is what I need it to do). I did it like this:

```<code>new <- df %>% group_by(A, B) %>%
              slice(if(any(B > 1)) 1 else 1:n())
</code>```

but it got rid of the repeated values (so all the ones in column A I did not want to delete - not the last row regardless of repetition). Is there something I'm missing in the code I've run or another method that would accomplish this (ideally in dplyr but I'd be curious about all methods)?

答:
```<code>df %>% group_by(C) %>% slice(if(n() > 1) 1:(n()-1) else 1)
</code>```

or

```<code>library(data.table)
setDT(df)

df[, if (.N > 1) head(.SD, -1) else .SD, by = C]
</code>```

or for max speed (and also incidentally keeping column order)

```<code>df[df[, if (.N > 1) head(.I, -1) else .I, by = C]$V1]
</code>```

Body:
I have a data frame like this (NT and MCS are text placeholders for a certain species let's say)

A <- c("NT", "MCS","MCS","NT", "MCS", "MCS", "NT", "MCS", "MCS", "MCS",
       "NT", "MCS", "MCS","NT", "MCS","NT","NT","MCS", "MCS","NT")
B <- c("1", "3", "3","3","3", "3","3","4","4","4","4","3",
       "3","3","2","2","1","3","3","3")
C <- c("G1", "G2", "G2", "G2", "G3", "G3", "G3", "G4", "G4", "G4", "G4",
       "G5", "G5", "G5","G6", "G6", "G7","G8","G8","G8")

df <- data.frame(A,B,C)

A   B   C
NT  1   G1
MCS 3   G2
MCS 3   G2
NT  3   G2
MCS 3   G3
MCS 3   G3
NT  3   G3
MCS 4   G4
MCS 4   G4
MCS 4   G4
NT  4   G4
MCS 3   G5
MCS 3   G5
NT  3   G5
MCS 2   G6
NT  2   G6
NT  1   G7
MCS 3   G8
MCS 3   G8
NT  3   G8

The A column represents the species. The B column represents an integer value that equals the the number of rows in each group. C column represents unique groups. The criteria is as follows: Delete the LAST row of every group/species IF B > 1. If B = 1, then NT (or the only row in that group) should remain. Here is what I need it to look like.

A   B   C
NT  1   G1
MCS 3   G2
MCS 3   G2
MCS 3   G3
MCS 3   G3
MCS 4   G4
MCS 4   G4
MCS 4   G4
MCS 3   G5
MCS 3   G5
MCS 2   G6
NT  1   G7
MCS 3   G8
MCS 3   G8

new<- df %>% group_by(A, B) %>% slice(if(any(numb > 1)) 1:n())

The above is the closest code I've run but it doesn't evaluate to an integer or numeric vector (which is what I need it to do). I did it like this:

new <- df %>% group_by(A, B) %>%
              slice(if(any(B > 1)) 1 else 1:n())

but it got rid of the repeated values (so all the ones in column A I did not want to delete - not the last row regardless of repetition). Is there something I'm missing in the code I've run or another method that would accomplish this (ideally in dplyr but I'd be curious about all methods)?

Body:
df %>% group_by(C) %>% slice(if(n() > 1) 1:(n()-1) else 1)

or

library(data.table)
setDT(df)

df[, if (.N > 1) head(.SD, -1) else .SD, by = C]

or for max speed (and also incidentally keeping column order)

df[df[, if (.N > 1) head(.I, -1) else .I, by = C]$V1]


问:
Oracle stored procedure help
HI am new to stored procedure.
Am using a dynamic sql with

```<code>select * from table into var
</code>```

var is a variable.the var contains more than one value ,when i try to run the proc with inputs i get an error:

```<code>ORA-01422: exact fetch returns more than requested number of rows
</code>```

Is there a way such that the variable can hold more than one row using dynamic sql.

答:
You can use a table variable, which provides you with an in-memory table of your results. You declare a table variable similar to a standard variable:</p>

```<code>declare @MyVar table (col1 col1type, col2 col2type, etc.)
</code>```

Title: Oracle stored procedure help

Body:
HI am new to stored procedure.
Am using a dynamic sql with

select * from table into var

var is a variable.the var contains more than one value ,when i try to run the proc with inputs i get an error:

ORA-01422: exact fetch returns more than requested number of rows

Is there a way such that the variable can hold more than one row using dynamic sql.

Body:
You can use a table variable, which provides you with an in-memory table of your results. You declare a table variable similar to a standard variable:

declare @MyVar table (col1 col1type, col2 col2type, etc.)


问:
I want to create multidimensional Array with different random numbers
I want to create multidimensional Array with Random r = new Random();

Each element should be generated randomly and they all must also be different elements. None of them should be same. Also I can not use any function.

Here is array but there are same elements. I want to all the elements were different.

```<code>   for (int i=0; i<3; i++)
        {
            for(int j=0; j<4; j++)
            {
                arr[i, j] = rand.Next(1,25);
            }
        }
</code>```

答:
In the lazy version, 1D shuffled array can be copied to 2D array:</p>

```<code>Random rand = new Random();
int[] shuffled = Enumerable.Range(1, 25).OrderBy(rand.Next).ToArray();

int[,] arr = new int[3, 4];
Buffer.BlockCopy(shuffled, 0, arr, 0, arr.Length * sizeof(int));
</code>```

Body:
I want to create multidimensional Array with Random r = new Random();

Each element should be generated randomly and they all must also be different elements. None of them should be same. Also I can not use any function.

Here is array but there are same elements. I want to all the elements were different.

   for (int i=0; i<3; i++)
        {
            for(int j=0; j<4; j++)
            {
                arr[i, j] = rand.Next(1,25);
            }
        }

Body:
In the lazy version, 1D shuffled array can be copied to 2D array:

Random rand = new Random();
int[] shuffled = Enumerable.Range(1, 25).OrderBy(rand.Next).ToArray();

int[,] arr = new int[3, 4];
Buffer.BlockCopy(shuffled, 0, arr, 0, arr.Length * sizeof(int));


问:
What is the best way to create a java.util.Enumeration out of a java stream?
My best solution is currently:

```<code>Collections.enumeration(stream.collect(Collectors.toList()))
</code>```

Hoping for a more concise method than this.

答:
You can use Guava's Iterators.asEnumeration():

```<code>Iterators.asEnumeration(stream.iterator())
</code>```

Body:
My best solution is currently:

Collections.enumeration(stream.collect(Collectors.toList()))

Hoping for a more concise method than this.

Body:
You can use Guava's Iterators.asEnumeration():

Iterators.asEnumeration(stream.iterator())


答:
NSStoryboard.Name got its own scope in the namespace to be able to do that:

```<code>extension NSStoryboard.Name {
    static let actors = NSStoryboard.Name(rawValue: "Actors")
}
</code>```

```<code>let storyboard = NSStoryboard(name: .actors, bundle: nil)
</code>```

Title: Cannot convert value of type 'String' to expected argument type 'NSStoryboard.Name'

Body:
NSStoryboard.Name got its own scope in the namespace to be able to do that:

extension NSStoryboard.Name {
    static let actors = NSStoryboard.Name(rawValue: "Actors")
}

let storyboard = NSStoryboard(name: .actors, bundle: nil)


问:
How do I track the time a person goes to a place?
I'm working on creating a database for a gym to track the members info. I want to be able to track the times that people go so you will be able to see when it is busiest. I'm not sure how to go about this. Do I need to make a new table for the information of when a member goes or do I add it into the members or gyms table?</p>

答: I would add this to a different table. You could make a new table with user_id which is the same as the users ID in the user table. It would then be quite easy to tie the visits to the users, if that’s a point.</p>


问:
How to disable the cache in cordova android app
I had used the Cordova 3.6.3 version for building my android app and i wnat to disable the caching of URL in cordova webview , I am using the default cordova project for that purpose and using the index.html file.
I tried this but it is crashing my app   </p>

```<code>public class MyClass extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
    mwebview=(WebView) findViewById(R.id.appView);
    WebSettings ws=mwebview.getSettings();
    ws.setAppCacheEnabled(false);
    ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
    // Set by <content src="index.html" /> in config.xml
    loadUrl(launchUrl);
    }
}
</code>```

答:
cordova-disable-http-cache

Cordova plugin to completely disable caching of HTTP requests and responses.

Just type this command in your Cordova CLI:

```<code>cordova plugin add cordova-disable-http-cache
</code>```

This will fetch plugin "cordova-disable-http-cache" via npm and install "cordova-disable-http-cache" for android.

It solved my problem with disabling cache in my application.
My cordova version is 6.5.0.

Body:
I had used the Cordova 3.6.3 version for building my android app and i wnat to disable the caching of URL in cordova webview , I am using the default cordova project for that purpose and using the index.html file.
I tried this but it is crashing my app

public class MyClass extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
    mwebview=(WebView) findViewById(R.id.appView);
    WebSettings ws=mwebview.getSettings();
    ws.setAppCacheEnabled(false);
    ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
    // Set by <content src="index.html" /> in config.xml
    loadUrl(launchUrl);
    }
}

Body:
cordova-disable-http-cache

Cordova plugin to completely disable caching of HTTP requests and responses.

Just type this command in your Cordova CLI:

cordova plugin add cordova-disable-http-cache

This will fetch plugin "cordova-disable-http-cache" via npm and install "cordova-disable-http-cache" for android.

It solved my problem with disabling cache in my application.
My cordova version is 6.5.0.


问:
MongoDB Notification in Python
I am using MongoDB with Python web application. I want to know notification from mongodb whatever i changed in mongodb. i am using the code:

```<code>from pymongo import Connection
import time
MONGO_CONNECTION = MongoClient(settings.MONGO_CONNECTION_URL+"/"+settings.MONGO_DATABASE['NAME'], safe=True, j=True)
MONGO_DB = MONGO_CONNECTION[settings.MONGO_DATABASE['NAME']]
collection = MONGO_DB["id_64"]
cursor = collection.find(tailable=True)
while cursor.alive:
    print "inside"
    try:
        doc = cursor.next()
        print "new doc"
        print doc
    except StopIteration:
        time.sleep(1)
</code>```

And i am getting the error:

```<code>OperationFailure: database error: Unable to execute query: error processing query: ns=scisphere.orgid_64 limit=0 skip=0
Tree: $and
Sort: {}
Proj: {}
 tailable cursor requested on non capped collection
</code>```

So help me what is the wrong i am doing.

Thanks.

答:
MongoDB 3.6 supports $changeStream feature to watch changes on a collection.

For example using PyMongo compatible with MongoDB 3.6:

```<code>   for change in db.collection.watch():
       print(change)
</code>```

The ChangeStream returned automatically resumes when it encounters a potentially recoverable error during iteration. The resume process is transparent to the application and ensures no change stream documents are lost.

Another example to watch all inserts that are happening on a collection using PyMongo:

```<code>    try:
        for insert_change in db.collection.watch(
                [{'$match': {'operationType': 'insert'}}]):
            print(insert_change)

    except pymongo.errors.PyMongoError:

        # We know it's unrecoverable:
        log.error('...')
</code>```

Title: MongoDB Notification in Python

Body:
I am using MongoDB with Python web application. I want to know notification from mongodb whatever i changed in mongodb. i am using the code:

from pymongo import Connection
import time
MONGO_CONNECTION = MongoClient(settings.MONGO_CONNECTION_URL+"/"+settings.MONGO_DATABASE['NAME'], safe=True, j=True)
MONGO_DB = MONGO_CONNECTION[settings.MONGO_DATABASE['NAME']]
collection = MONGO_DB["id_64"]
cursor = collection.find(tailable=True)
while cursor.alive:
    print "inside"
    try:
        doc = cursor.next()
        print "new doc"
        print doc
    except StopIteration:
        time.sleep(1)

And i am getting the error:

OperationFailure: database error: Unable to execute query: error processing query: ns=scisphere.orgid_64 limit=0 skip=0
Tree: $and
Sort: {}
Proj: {}
 tailable cursor requested on non capped collection

So help me what is the wrong i am doing.

Thanks.

Body:
MongoDB 3.6 supports $changeStream feature to watch changes on a collection.

For example using PyMongo compatible with MongoDB 3.6:

   for change in db.collection.watch():
       print(change)

The ChangeStream returned automatically resumes when it encounters a potentially recoverable error during iteration. The resume process is transparent to the application and ensures no change stream documents are lost.

Another example to watch all inserts that are happening on a collection using PyMongo:

    try:
        for insert_change in db.collection.watch(
                [{'$match': {'operationType': 'insert'}}]):
            print(insert_change)

    except pymongo.errors.PyMongoError:

        # We know it's unrecoverable:
        log.error('...')


问:
Is it possible to dynamically define a constant in Typescript?
I am trying to find a way to dynamically define a constant in Typescript but I'am starting to thing it's not possible.

I tried this :

```<code>  define(name: string, value: any): boolean {
    var undef;
    const name = value;
    return name == undef;
  }
</code>```

I am supposed to call:

```<code>define ('MY_CONST_NAME', 'foo_value);
</code>```

I get the following error :

```<code>Duplicate 'name' identifier.
</code>```

I think it's normal but i don't know how to achieve my goal.

答:
In short... No. Const is block scoped. When declared it becomes available and not until then. If you want to declare something as immutable it's not that hard, but this question shows a lack of knowledge possibly. I think what you may find more useful is how to deep freeze an object so things can't be added to, taken off of, or changed in it. However it is shallow, so deep changes would be an issue unless you want to freeze it recursively(CAREFUL) or on a path

From the MDN:

```<code>var obj = {
  prop: function() {},
  foo: 'bar'
};

// New properties may be added, existing properties may be
// changed or removed
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;

// Both the object being passed as well as the returned
// object will be frozen. It is unnecessary to save the
// returned object in order to freeze the original.
var o = Object.freeze(obj);

o === obj; // true
Object.isFrozen(obj); // === true

// Now any changes will fail
obj.foo = 'quux'; // silently does nothing
// silently doesn't add the property
obj.quaxxor = 'the friendly duck';

// In strict mode such attempts will throw TypeErrors
function fail(){
  'use strict';
  obj.foo = 'sparky'; // throws a TypeError
  delete obj.quaxxor; // throws a TypeError
  obj.sparky = 'arf'; // throws a TypeError
}

fail();

// Attempted changes through Object.defineProperty;
// both statements below throw a TypeError.
Object.defineProperty(obj, 'ohai', { value: 17 });
Object.defineProperty(obj, 'foo', { value: 'eit' });

// It's also impossible to change the prototype
// both statements below will throw a TypeError.
Object.setPrototypeOf(obj, { x: 20 })
obj.__proto__ = { x: 20 }
</code>```

Body:
I am trying to find a way to dynamically define a constant in Typescript but I'am starting to thing it's not possible.

I tried this :

  define(name: string, value: any): boolean {
    var undef;
    const name = value;
    return name == undef;
  }

I am supposed to call:

define ('MY_CONST_NAME', 'foo_value);

I get the following error :

Duplicate 'name' identifier.

I think it's normal but i don't know how to achieve my goal.

Body:
In short... No. Const is block scoped. When declared it becomes available and not until then. If you want to declare something as immutable it's not that hard, but this question shows a lack of knowledge possibly. I think what you may find more useful is how to deep freeze an object so things can't be added to, taken off of, or changed in it. However it is shallow, so deep changes would be an issue unless you want to freeze it recursively(CAREFUL) or on a path

From the MDN:

var obj = {
  prop: function() {},
  foo: 'bar'
};

// New properties may be added, existing properties may be
// changed or removed
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;

// Both the object being passed as well as the returned
// object will be frozen. It is unnecessary to save the
// returned object in order to freeze the original.
var o = Object.freeze(obj);

o === obj; // true
Object.isFrozen(obj); // === true

// Now any changes will fail
obj.foo = 'quux'; // silently does nothing
// silently doesn't add the property
obj.quaxxor = 'the friendly duck';

// In strict mode such attempts will throw TypeErrors
function fail(){
  'use strict';
  obj.foo = 'sparky'; // throws a TypeError
  delete obj.quaxxor; // throws a TypeError
  obj.sparky = 'arf'; // throws a TypeError
}

fail();

// Attempted changes through Object.defineProperty;
// both statements below throw a TypeError.
Object.defineProperty(obj, 'ohai', { value: 17 });
Object.defineProperty(obj, 'foo', { value: 'eit' });

// It's also impossible to change the prototype
// both statements below will throw a TypeError.
Object.setPrototypeOf(obj, { x: 20 })
obj.__proto__ = { x: 20 }


问:
HTML generator?
LESS is very cool. I always wondered if there are any good html generators that allow me to write a form more easily or do other things. Is there something somewhat similar but for html?</p>

答:
Check out Zen-Coding.

Uses a CSS style markup to generate HTML with some nice features.

Title: HTML generator?


问:
Calculating cummulative returns mid-year to mid-year Pandas
I have a Pandas dataframe of the size (80219 * 5) with the same structure as the image I have uploaded. The data can range from 2002-2016 for each company but if missing values appear the data either starts at a later date or ends at an earlier date as you can see in the image.

What I would like to do is to calculate yearly compounded returns measured from June to June for each company. If there is no data for the specific company for the full 12 months period from June to June the result should be nan. Below is my current code, but I don't know how to calculate the returns from June to June.

After having loaded the file and cleaned it I:

```<code>df[['Returns']] = df[['Returns']].apply(pd.to_numeric)
df['Names Date'] = pd.to_datetime(df['Names Date'])
df['Returns'] = df['Returns']+ 1
df = df[['Company Name','Returns','Names Date']]
df['year']=df['Names Date'].dt.year
df['cum_return'] = df.groupby(['Company Name','year']).cumprod()
df = df.groupby(['Company Name','year']).nth(11)
print(tabulate(df, headers='firstrow', tablefmt='psql'))
</code>```

Which calculates the annual return from 1st of january to 31st of december..

答:
I finally found a way to do it. The easiest way I could find is to calculate a rolling 12 month compounded return for each month and then slice the dataframe for to give me the 12 month returns of the months I want:</p>

```<code>def myfunc(arr):
    return np.cumprod(arr)[-1]

cum_ret = pd.Series()
grouped = df.groupby('Company Name')
for name, group in grouped:
    cum_ret = cum_ret.append(pd.rolling_apply(group['Returns'],12,myfunc))
df['Cum returns'] = cum_ret
df = df.loc[df['Names Date'].dt.month==6]
df['Names Date'] = df['Names Date'].dt.year
</code>```

Body:
I have a Pandas dataframe of the size (80219 * 5) with the same structure as the image I have uploaded. The data can range from 2002-2016 for each company but if missing values appear the data either starts at a later date or ends at an earlier date as you can see in the image.

What I would like to do is to calculate yearly compounded returns measured from June to June for each company. If there is no data for the specific company for the full 12 months period from June to June the result should be nan. Below is my current code, but I don't know how to calculate the returns from June to June.

After having loaded the file and cleaned it I:

df[['Returns']] = df[['Returns']].apply(pd.to_numeric)
df['Names Date'] = pd.to_datetime(df['Names Date'])
df['Returns'] = df['Returns']+ 1
df = df[['Company Name','Returns','Names Date']]
df['year']=df['Names Date'].dt.year
df['cum_return'] = df.groupby(['Company Name','year']).cumprod()
df = df.groupby(['Company Name','year']).nth(11)
print(tabulate(df, headers='firstrow', tablefmt='psql'))

Which calculates the annual return from 1st of january to 31st of december..

Body:
I finally found a way to do it. The easiest way I could find is to calculate a rolling 12 month compounded return for each month and then slice the dataframe for to give me the 12 month returns of the months I want:

def myfunc(arr):
    return np.cumprod(arr)[-1]

cum_ret = pd.Series()
grouped = df.groupby('Company Name')
for name, group in grouped:
    cum_ret = cum_ret.append(pd.rolling_apply(group['Returns'],12,myfunc))
df['Cum returns'] = cum_ret
df = df.loc[df['Names Date'].dt.month==6]
df['Names Date'] = df['Names Date'].dt.year


问:
Bash and Awk Strange Behavior (DD-WRT)
I am testing a small script in the DD-WRT Web interface that randomizes the router's MAC address. The script uses awk to do the randomization. The script works when awk is used without the shebang (#!/bin/bash), as well as vice versa (without awk but including the shebang). However, the script does not work when both the shebang and awk is used.

Works (uses awk, but no shebang):

```<code>nvram set mac_clone_enable=1;
nvram set def_hwaddr=$(awk 'function m(n){srand(systime()+n);return":"(10+int(rand()*99));}END{print "A4"m(1)m(2)m(3)m(4)m(5);}');
nvram commit;
rc restart;
</code>```

Also Works (has shebang, but no awk):

```<code>#!/bin/bash

nvram set mac_clone_enable=1;
nvram set def_hwaddr="02:44:55:66:77:88";
nvram commit;
rc restart;
</code>```

Doesn't Work (shebang and awk):

```<code>#!/bin/bash

nvram set mac_clone_enable=1;
nvram set def_hwaddr=$(awk 'function m(n){srand(systime()+n);return":"(10+int(rand()*99));}END{print "A4"m(1)m(2)m(3)m(4)m(5);}');
nvram commit;
rc restart;
</code>```

I need the script to use awk and have the shebang, so it can be used in a cron job. What could be the problem?

答:
awk is expecting an input file.  You can rewrite instead using the BEGIN block

```<code>awk 'function r() {return ":"(10+int(rand()*99))}
     BEGIN{srand(); print "A4" r() r() r() r() r()}'
</code>```

returned

```<code>A4:72:63:62:91:102
</code>```

you also do not need to reinitialize random seed each time; once is enough.

Title: Bash and Awk Strange Behavior (DD-WRT)

Body:
I am testing a small script in the DD-WRT Web interface that randomizes the router's MAC address. The script uses awk to do the randomization. The script works when awk is used without the shebang (#!/bin/bash), as well as vice versa (without awk but including the shebang). However, the script does not work when both the shebang and awk is used.

Works (uses awk, but no shebang):

nvram set mac_clone_enable=1;
nvram set def_hwaddr=$(awk 'function m(n){srand(systime()+n);return":"(10+int(rand()*99));}END{print "A4"m(1)m(2)m(3)m(4)m(5);}');
nvram commit;
rc restart;

Also Works (has shebang, but no awk):

#!/bin/bash

nvram set mac_clone_enable=1;
nvram set def_hwaddr="02:44:55:66:77:88";
nvram commit;
rc restart;

Doesn't Work (shebang and awk):

#!/bin/bash

nvram set mac_clone_enable=1;
nvram set def_hwaddr=$(awk 'function m(n){srand(systime()+n);return":"(10+int(rand()*99));}END{print "A4"m(1)m(2)m(3)m(4)m(5);}');
nvram commit;
rc restart;

I need the script to use awk and have the shebang, so it can be used in a cron job. What could be the problem?

Body:
awk is expecting an input file.  You can rewrite instead using the BEGIN block

awk 'function r() {return ":"(10+int(rand()*99))}
     BEGIN{srand(); print "A4" r() r() r() r() r()}'

returned

A4:72:63:62:91:102

you also do not need to reinitialize random seed each time; once is enough.