问:
SPFx JQuery Dialog button click does not find public function
I am new to TypeScript and Sharepoint SPFx development.  I have a jquery UI dialog box and a public function in the same class that makes some MSGRAPH calls after the button has been clicked. The button click returns with error this.addAlert is not a function.  I think the problem is that the dialog code executes outside the web part context and hence does not know about the function available in the webpart context.  How can I use the button click to run within the webpart context?

Here is the Dialog code.

```<code>    export default class YlsSpAlertWebPart extends BaseClientSideWebPart<IYlsSpAlertWebPartProps> {

      public constructor() {
        super();
        SPComponentLoader.loadCss('//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css');
      }

public render(): void {

    this.domElement.innerHTML = AlertTemplate.templateHtml;
    const dialogOptions: JQueryUI.DialogOptions = {
      width: "50%",
      height: "auto",
      buttons: {
        "Subscribe": function (e) {
          this.addAlert("Yes");
          jQuery(this).dialog("close");
        },
        "No Thanks": function (e) {
          console.log("moo");
          this.addAlert("No");
          jQuery(this).dialog("close");
        },
        "Ask me later": function (e) {
          this.addAlert("Ask Me Later");
          jQuery(this).dialog("close");
        }
      }
    };

    jQuery('.dialog', this.domElement).dialog(dialogOptions);
    jQuery(".ui-dialog-titlebar").hide();
  }

     public addAlert(status: string): void {
        var url = "/sites/" + this.context.pageContext.site.id + "/lists";
        var listId = "";
        var email = this.getCurrentUserEmail();
        var recordExists = false;
        let item: SubscriptionListItem;
        this.context.msGraphClientFactory
          .getClient()
          .then((client: MSGraphClient): void => {
            client
              .api(url)
              .top(1)
              .filter("equals=(displayName, 'Subscriptions'")
              .version("v1.0")
              .get((err, res) => {
                if (err) {
                  console.error(err);
                  return;
                }
                console.log(res);
                listId = res.id;
              });
          });

}
</code>```

...skipping the rest of the boilerplate generated by the template

答:
This worked answered at sharepoint spfx forum</p>

```<code>public onDialogButtonClick(status: string, e): void {
    this.addAlert(status);
    jQuery('.dialog', this.domElement).dialog("close");
}
public render(): void {
    this.domElement.innerHTML = AlertTemplate.templateHtml;
    const dialogOptions: JQueryUI.DialogOptions = {
      width: "50%",
      height: "auto",
      buttons: {
        "Subscribe": this.onDialogButtonClick.bind(this, "Subscribe"),
        "No Thanks": this.onDialogButtonClick.bind(this, "No Thanks"),
        "Ask me later": this.onDialogButtonClick.bind(this, "Ask me later")
      }
    };

    jQuery('.dialog', this.domElement).dialog(dialogOptions);
    jQuery(".ui-dialog-titlebar").hide();
}
</code>```

Body:
I am new to TypeScript and Sharepoint SPFx development.  I have a jquery UI dialog box and a public function in the same class that makes some MSGRAPH calls after the button has been clicked. The button click returns with error this.addAlert is not a function.  I think the problem is that the dialog code executes outside the web part context and hence does not know about the function available in the webpart context.  How can I use the button click to run within the webpart context?

Here is the Dialog code.

    export default class YlsSpAlertWebPart extends BaseClientSideWebPart<IYlsSpAlertWebPartProps> {

      public constructor() {
        super();
        SPComponentLoader.loadCss('//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css');
      }

public render(): void {

    this.domElement.innerHTML = AlertTemplate.templateHtml;
    const dialogOptions: JQueryUI.DialogOptions = {
      width: "50%",
      height: "auto",
      buttons: {
        "Subscribe": function (e) {
          this.addAlert("Yes");
          jQuery(this).dialog("close");
        },
        "No Thanks": function (e) {
          console.log("moo");
          this.addAlert("No");
          jQuery(this).dialog("close");
        },
        "Ask me later": function (e) {
          this.addAlert("Ask Me Later");
          jQuery(this).dialog("close");
        }
      }
    };

    jQuery('.dialog', this.domElement).dialog(dialogOptions);
    jQuery(".ui-dialog-titlebar").hide();
  }

     public addAlert(status: string): void {
        var url = "/sites/" + this.context.pageContext.site.id + "/lists";
        var listId = "";
        var email = this.getCurrentUserEmail();
        var recordExists = false;
        let item: SubscriptionListItem;
        this.context.msGraphClientFactory
          .getClient()
          .then((client: MSGraphClient): void => {
            client
              .api(url)
              .top(1)
              .filter("equals=(displayName, 'Subscriptions'")
              .version("v1.0")
              .get((err, res) => {
                if (err) {
                  console.error(err);
                  return;
                }
                console.log(res);
                listId = res.id;
              });
          });

}

...skipping the rest of the boilerplate generated by the template

Body:
This worked answered at sharepoint spfx forum

public onDialogButtonClick(status: string, e): void {
    this.addAlert(status);
    jQuery('.dialog', this.domElement).dialog("close");
}
public render(): void {
    this.domElement.innerHTML = AlertTemplate.templateHtml;
    const dialogOptions: JQueryUI.DialogOptions = {
      width: "50%",
      height: "auto",
      buttons: {
        "Subscribe": this.onDialogButtonClick.bind(this, "Subscribe"),
        "No Thanks": this.onDialogButtonClick.bind(this, "No Thanks"),
        "Ask me later": this.onDialogButtonClick.bind(this, "Ask me later")
      }
    };

    jQuery('.dialog', this.domElement).dialog(dialogOptions);
    jQuery(".ui-dialog-titlebar").hide();
}


来源: stackexchange

问:
How to create a color box in front of a radiobutton in html?
I want to create a radiobutton with a small color box in front of it.
This is the current code that I have written:

```<code><label class="container"  style="color: #0B9BCD">
   <div class="foo"></div>
   <input type="radio" name="radiobutton" id="highlight1" value="highlight1"/>
   <span class="checkmark"></span>
</label>
</code>```

where the class foo has the following style:

```<code>.foo {
     float: left;
     width: 20px;
     height: 20px;
     margin: 5px;
     border: 1px solid black;
     background: #13b4ff;
  }
</code>```

And the output I am getting is something like this:

How can I move the color box to the right of the radiobutton?

答: Change the order. Your foo is ordered before your input. </p>

ContentLicense: CC BY-SA 4.0

Body:
I want to create a radiobutton with a small color box in front of it.
This is the current code that I have written:

   <input type="radio" name="radiobutton" id="highlight1" value="highlight1"/>

where the class foo has the following style:

.foo {
     float: left;
     width: 20px;
     height: 20px;
     margin: 5px;
     border: 1px solid black;
     background: #13b4ff;
  }

And the output I am getting is something like this:

How can I move the color box to the right of the radiobutton?


问:
Unauthorized nuget package from Visual Studio Team Services using asp.net core rc2
I am unable to install/restore nuget packages from a Visual Studio Team Services feed in an asp.net core web application (RC2). I receive the following:

error:   Response status code does not indicate success: 401
  (Unauthorized).

I am running Visual Studio Community 2015 Update 2 and nuget version 3.4.4. I am able to install/restore packages from this feed in other project types.

Do I need to do something else to pass my credentials for an asp.net core web app?

Steps to reproduce:

From Team Services package tab I select "Connect to Feed" and copy the NuGet package source URL

In visual studio -> Tools -> NuGet Package Manager -> Package Manager settings -> Package sources and add the feed url from vso

Then from my ASP.NET Core Web Application (.NET Framework) project right click references -> Manage NuGet Packages
-> Select my feed from Package source (packages are listed) -> Click to install

In output:

```<code>Installing NuGet package xxxxx
Successfully installed xxxxx to WebApplication1
========== Finished ==========
</code>```

Then it will try to restore the package at which point I get:

```<code>error: Response status code does not indicate success: 401 (Unauthorized).
error: Failed to retrieve information from remote source
</code>```

And inside web project references - package has warning icon - NU1001 The dependency xxxxx could not be resolved

答: Try restarting the computer before you try any of the above. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am unable to install/restore nuget packages from a Visual Studio Team Services feed in an asp.net core web application (RC2). I receive the following:

error:   Response status code does not indicate success: 401
  (Unauthorized).

I am running Visual Studio Community 2015 Update 2 and nuget version 3.4.4. I am able to install/restore packages from this feed in other project types.

Do I need to do something else to pass my credentials for an asp.net core web app?

Steps to reproduce:

From Team Services package tab I select "Connect to Feed" and copy the NuGet package source URL

In visual studio -> Tools -> NuGet Package Manager -> Package Manager settings -> Package sources and add the feed url from vso

Then from my ASP.NET Core Web Application (.NET Framework) project right click references -> Manage NuGet Packages
-> Select my feed from Package source (packages are listed) -> Click to install

In output:

Installing NuGet package xxxxx
Successfully installed xxxxx to WebApplication1
========== Finished ==========

Then it will try to restore the package at which point I get:

error: Response status code does not indicate success: 401 (Unauthorized).
error: Failed to retrieve information from remote source

And inside web project references - package has warning icon - NU1001 The dependency xxxxx could not be resolved


问:
Is HTML5 backwards compatible with XHTML?
Short question: Can I change the DOCTYPE of my existing XHTML 1.0 website to HTML5? Will this cause any problems?

Long story:

We've got a website written in ASP.NET webforms. Since it's pretty old, the default DOCTYPE is set to XHTML (default for Visual Studio) and all the controls render XHTML as well. Not extremely valid, but we've had no problems under any browsers so far.

That is, until recently we noticed some odd behavior on different machines under IE. Turns out that IE by default renders intranet websites in "compatibility mode", which breaks things down.

Now, I've got two choices. I can either add:

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge" >
</code>```

Or I can add

```<code><!DOCTYPE html>
</code>```

I'd prefer the DOCTYPE route, since it would open the doors for a lot of neat HTML5 features. However I wonder if it won't have incompatibility problems with our existing XHTML layout.

答: As far as I know, HTML5 is pretty much xhtml plus the extras so yeah, I think you can change the doctype and it would still work. They answered it here: If I use HTML 5's doctype, what will happen?</p>

Body:
Short question: Can I change the DOCTYPE of my existing XHTML 1.0 website to HTML5? Will this cause any problems?

Long story:

We've got a website written in ASP.NET webforms. Since it's pretty old, the default DOCTYPE is set to XHTML (default for Visual Studio) and all the controls render XHTML as well. Not extremely valid, but we've had no problems under any browsers so far.

That is, until recently we noticed some odd behavior on different machines under IE. Turns out that IE by default renders intranet websites in "compatibility mode", which breaks things down.

Now, I've got two choices. I can either add:

<meta http-equiv="X-UA-Compatible" content="IE=edge" >

Or I can add

<!DOCTYPE html>

I'd prefer the DOCTYPE route, since it would open the doors for a lot of neat HTML5 features. However I wonder if it won't have incompatibility problems with our existing XHTML layout.


答:
```<code>df$newColumn=ifelse(grepl("PRD-C1",df$id),"CHD","healthy")
</code>```

If "PRD-C1" and "PRD-S1" are the only two options.

Title: Create a new variable according another column in R

Body:
Hi have this dataframe

            id power     hr    fr    VE     VO2    VCO2  PETCO2 percent_VO2 percent_power
1  AC12-PRD-C1    25  88.75 22.75 22.75 0.73900 0.66700 39.2925    49.34068      21.73913
2  AC12-PRD-C1    40  93.25 23.00 23.75 0.81975 0.71500 39.6200    54.73210      34.78261
3  AC12-PRD-C1    55  99.75 22.75 26.75 0.95125 0.85400 41.4100    63.51193      47.82609
4  AC12-PRD-C1    70 109.75 23.00 32.50 1.07525 1.04700 42.0150    71.79102      60.86957
5  AC12-PRD-C1    85 118.75 22.75 39.50 1.19900 1.25125 41.8425    80.05341      73.91304
6  AC12-PRD-C1   100 127.00 26.00 48.25 1.34575 1.51850 41.0950    89.85144      86.95652
7  AC12-PRD-C1   115 135.75 28.00 55.75 1.49775 1.76025 40.7275   100.00000     100.00000
8  AL13-PRD-C1    25  69.50 16.50 24.00 0.66125 0.58050 31.2275    41.36691      19.23077
9  AL13-PRD-C1    40  73.00 17.50 26.50 0.74850 0.66425 32.1025    46.82515      30.76923
10 AL13-PRD-C1    55  83.25 15.50 29.00 0.85500 0.79425 33.6650    53.48764      42.30769
11 AL13-PRD-C1    70  93.75 16.00 36.50 0.98450 0.99925 34.5325    61.58899      53.84615
12 AL13-PRD-C1    85 104.50 16.00 44.75 1.14950 1.23475 34.4225    71.91117      65.38462
13 AL13-PRD-C1   100 114.25 19.25 55.25 1.34650 1.48375 33.1800    84.23522      76.92308
14 AL13-PRD-C1   115 125.25 20.75 63.75 1.45100 1.65775 32.6450    90.77260      88.46154
15 AL13-PRD-C1   130 136.25 24.75 78.00 1.59850 1.89075 30.9000   100.00000     100.00000
16 BM06-PRD-S1    25 119.25 18.25 19.00 0.61675 0.58225 37.6425    48.87084      25.00000
17 BM06-PRD-S1    40 126.00 18.00 20.75 0.71700 0.65950 39.2175    56.81458      40.00000
18 BM06-PRD-S1    55 133.50 20.75 25.00 0.86275 0.82750 41.2150    68.36371      55.00000
19 BM06-PRD-S1    70 147.25 18.25 29.00 0.98575 1.04550 41.7050    78.11014      70.00000
20 BM06-PRD-S1    85 158.50 22.25 39.25 1.13000 1.30525 41.1425    89.54041      85.00000
21 BM06-PRD-S1   100 168.75 27.75 51.00 1.26200 1.61150 38.8925   100.00000     100.00000
22 CB19-PRD-S1    25  98.75 18.50 25.00 0.88350 0.80475 40.7550    36.15715      13.15789
23 CB19-PRD-S1    40  98.25 20.00 25.50 0.94575 0.82900 41.4675    38.70473      21.05263
24 CB19-PRD-S1    55 102.00 19.75 28.50 1.08125 0.95800 42.2775    44.25005      28.94737
25 CB19-PRD-S1    70 107.50 20.50 34.25 1.24400 1.14275 42.6450    50.91058      36.84211
26 CB19-PRD-S1    85 111.00 21.25 35.50 1.30475 1.19925 43.3600    53.39677      44.73684
27 CB19-PRD-S1   100 117.25 21.50 40.25 1.47350 1.42225 44.2650    60.30284      52.63158
28 CB19-PRD-S1   115 123.00 22.75 47.00 1.67900 1.68475 44.6400    68.71291      60.52632
29 CB19-PRD-S1   130 129.50 24.50 52.50 1.79075 1.87950 44.3425    73.28627      68.42105
30 CB19-PRD-S1   145 135.50 25.25 59.50 1.96000 2.13525 44.7300    80.21281      76.31579
31 CB19-PRD-S1   160 145.25 26.75 64.50 2.04050 2.28350 43.8825    83.50726      84.21053
32 CB19-PRD-S1   175 151.25 30.50 83.00 2.34425 2.76050 41.6025    95.93820      92.10526
33 CB19-PRD-S1   190 161.75 33.75 92.25 2.44350 2.96850 40.0400   100.00000     100.00000

I would like to create a new column with CHD or healthyvalue based on what it is written in the idcolumn.
If it "PRD-C1", it should be CHD, if it is "PRD-S1", it should be healthy.

Thank you !

Body:
df$newColumn=ifelse(grepl("PRD-C1",df$id),"CHD","healthy")

If "PRD-C1" and "PRD-S1" are the only two options.


问:
How to access table in laravel using eloquent with is not directly attached
I have the following table structure and i want to access Portal which is assigned to specific case but using patient info. For example i have the following query

```<code>$data['patients'] = Patient::with('operator')->where('case_id', $case_id)->get();
</code>```

this query returns the operator assigned to the patient now hare i want the portal name assigned to the patient using case.

Portal Table

```<code>id   Name
1   A
2   B
</code>```

Cases

```<code>id     Name    case_number     patient_name     user_id     portal_id
1      Farz       456            sania             5           1
</code>```

Patient

```<code>id    case_id   operator_id
2     456            5
</code>```

答:
You have to use another relationship

$data['patients'] = Patient::with('operator', 'cases.portal')
                             ->get();
```

<p>In Patient : </p>

<pre class="lang-php prettyprint-override"><code>public function cases(){
    return $this->hasMany(Case::class);
}
</code>```

In Case :

public function portal(){
    return $this->belongsTo(Portal::class);
}
```

<p>then you can access it with : </p>

<pre class="lang-php prettyprint-override"><code>foreach($data['patients'] as $patient){
    foreach($patient->cases as case){
         $var = $case->name;
    }
}
</code>```

or if you just want all portal names :

$portals_names = $data['patient'][0]->pluck('cases.portal.name')

Body:
I have the following table structure and i want to access Portal which is assigned to specific case but using patient info. For example i have the following query

$data['patients'] = Patient::with('operator')->where('case_id', $case_id)->get();

this query returns the operator assigned to the patient now hare i want the portal name assigned to the patient using case.

Portal Table

id   Name
1   A
2   B

Cases

id     Name    case_number     patient_name     user_id     portal_id
1      Farz       456            sania             5           1

Patient

id    case_id   operator_id
2     456            5

Body:
You have to use another relationship

$data['patients'] = Patient::with('operator', 'cases.portal')
                             ->get();

In Patient :

public function cases(){
    return $this->hasMany(Case::class);
}

In Case :

public function portal(){
    return $this->belongsTo(Portal::class);
}

then you can access it with :

foreach($data['patients'] as $patient){
    foreach($patient->cases as case){
         $var = $case->name;
    }
}

or if you just want all portal names :

$portals_names = $data['patient'][0]->pluck('cases.portal.name')


问:
Making indexes to my sql table for a query with "where" and "order by" clauses
I have a table in a mysql db. My query looks like

```<code>SELECT device_id,date,timestamp,power,floor
from tableData
where date=%s
and floor=%s
order by timestamp desc
limit 1
</code>```

I have created index on my table for quicker results . My indexes:

```<code>+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table      | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| minionData |          1 | idx1     |            1 | date        | A         |        9447 |     NULL | NULL   | YES  | BTREE      |         |               |
| minionData |          1 | idx1     |            2 | floor       | A         |       12072 |     NULL | NULL   | YES  | BTREE      |         |               |
+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
</code>```

So my question is for the particular query I am using, indexes on data and floor columns are good enough or should i index on timestamp column also, for increasing the query performance?

答:
Adding an index to each single column doesn't guarantee database optimization, timestamp maybe used for sorting or filtering.

Just use
tableData(date, floor)

Body:
I have a table in a mysql db. My query looks like

SELECT device_id,date,timestamp,power,floor
from tableData
where date=%s
and floor=%s
order by timestamp desc
limit 1

I have created index on my table for quicker results . My indexes:

+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table      | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| minionData |          1 | idx1     |            1 | date        | A         |        9447 |     NULL | NULL   | YES  | BTREE      |         |               |
| minionData |          1 | idx1     |            2 | floor       | A         |       12072 |     NULL | NULL   | YES  | BTREE      |         |               |
+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

So my question is for the particular query I am using, indexes on data and floor columns are good enough or should i index on timestamp column also, for increasing the query performance?


问:
Python: How do I modify iterator value after some condition in 'for' loop
In such a loop, if the variable no is equal to 8, how can I return the 8th loop again? I couldn't do it, I'm confused.

no -= 1 command not working

```<code>for no in range(0,100):
    print("No:",no)
    if no == 8:
      no -= 1
      print("8 done return again")
</code>```

答:
This should infinitely repeat "8 done return again". By switching the if statement to a while one.</p>

```<code>for no in range(0,100):
    print("No:",no)
    while (no == 8):
      print("8 done return again")
</code>```

Body:
In such a loop, if the variable no is equal to 8, how can I return the 8th loop again? I couldn't do it, I'm confused.

no -= 1 command not working

for no in range(0,100):
    print("No:",no)
    if no == 8:
      no -= 1
      print("8 done return again")

Body:
This should infinitely repeat "8 done return again". By switching the if statement to a while one.

for no in range(0,100):
    print("No:",no)
    while (no == 8):
      print("8 done return again")


问:
Saving form field data (string) in database column
I'm having problems while submitting the form and saving the filled fields within my database. Actually, this is happening just for one of my fields (model.CampoExtra), which in this case is a multiple select dropdowlist (lPagamentos). I need to save the keys of user selected items in my database, but when the user select more than one item I'm saving just a single key(the first one) and losing the rest of them.

The string containing the selected keys has this format 'key1,key2,keyN, ....'. The column in question that must receive these values has enough size, it was declared as [varchar] (80), so I really do not understand where I'm missing. I'll share sample of the code and hopefully someone can point out a mistake.

Sample of Form code (View)

```<code>@{

    List<SelectListItem> lPagamentos = new List<SelectListItem>();

    DropDownList DDList = new DropDownList();

    lPagamentos = DDList.GetListaCampoExtraFormasPGTO();

}

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="~/Scripts/select2.min.js"></script>
<link href="~/Content/CSS/select2.css" rel="stylesheet" />

<div id="Form" class="form-container @ViewBag.Acao">
        <div class="page-header">
            <h1>Cadastro de Mensagens</h1>
        </div>
        @using (Html.BeginForm(Acao, "SMS", FormMethod.Post, new { id = "FRMSms" }))
        {
            @Html.AntiForgeryToken()
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h4>Preencha com as informações do formulário!</h4>
                </div>
                <div class="panel-body">
                    @Html.HiddenFor(model => Model.MensagemID)
                    <input type="text" id="TotalFP" name="TotalFP" value="@ViewBag.TotalFP" />
                    **<!--THIS RETURNS MY DESIRED RECORD<input type="text" id="PgtoID" name="PgtoID" value="@ViewBag.PgtoID" />-->**

                    @if (Area == "MAS")
                    {
                        <div class="form-group col-md-6">
                            @Html.LabelFor(model => model.EmpresaID, htmlAttributes: new { @class = "control-label" }) <!--Cria tag Label-->
                            @Html.ValidationMessageFor(model => model.EmpresaID, "", new { @class = "text-danger" }) <!--Cria tag span-->
                            @Html.DropDownListFor(model => model.EmpresaID, (List<SelectListItem>)lEmpresas, " - SELECIONE - ", new { @class = "form-control" }) <!--Cria tag select-->
                        </div>
                    }
                    else
                    { @Html.HiddenFor(model => model.EmpresaID)}

                    <div class="form-group col-md-6 CampoForm">
                        @Html.LabelFor(model => model.Tipo, htmlAttributes: new { @class = "control-label" })
                        @Html.ValidationMessageFor(model => model.Tipo, "", new { @class = "text-danger" })
                        @Html.EditorFor(model => model.Tipo, new { htmlAttributes = new { @class = "form-control", placeholder = "Tipo" } })
                    </div>

                    <div class="form-group col-md-12 CampoForm">
                        <label for="Descricao" class="control-label">Descrição <span id="caracteres">120</span> caracteres restantes.</label>
                        @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control", maxlength = 120 } })
                    </div>

                    <div class="form-group col-md-12 CampoForm">
                        <label for="Texto" class="control-label">Mensagem <span id="rchars">155</span> caracteres restantes.</label>
                        @Html.ValidationMessageFor(model => model.Texto, "", new { @class = "text-danger" })
                        @Html.TextAreaFor(model => model.Texto, new { @class = "form-control", maxlength = 155 })
                    </div>

                    <div class="form-group col-md-9 CampoForm">
                        <label for="PgtoIDD" class="control-label">Formas de Pagamento - <input type="checkbox" id="chkTodos" /> Selecionar todos</label>
                        <input type="hidden" id="PgtoID" name="PgtoID" />
                        @Html.DropDownListFor(model => model.CampoExtra, (List<SelectListItem>)lPagamentos, new { @class = "form-control mySelect2", name = "CampoExtra", multiple = "multiple", style = "width:100%;" })
                    </div>

                    <div class="form-group col-md-3 CampoForm">
                        @Html.LabelFor(model => model.Situacao, htmlAttributes: new { @class = "control-label" })
                        @Html.ValidationMessageFor(model => model.Situacao, "", new { @class = "text-danger", maxlength = 1 })
                        @Html.DropDownListFor(model => model.Situacao, (List<SelectListItem>)lSituacao, " - SELECIONE - ", new { @class = "form-control" })
                    </div>
                    <div class="form-group col-md-3 CampoForm">
                        <label class="form-label">Cadastro</label>
                        <input id="Cadastro" name="Cadastro" tabindex="-1" type="text" readonly class="form-control" value="@Cadastro" />
                    </div>

                </div>
                <div class="panel-footer">
                    <input type="submit" value="@ViewBag.Label" class="btn btn-primary"> | @Html.ActionLink("Cancelar", "../Sms/", new { id = "", acao = "" }, new { @class = "btn btn-primary" })
                </div>
            </div>
        }
    </div>

<script>

    $("#Form #CampoExtra").select2({
        placeholder: "Selecione uma(s) forma(s) de pagamento.",
        allowClear: true,
        theme: "classic",
    });

    $("#chkTodos").on("click", function () {
        if (this.checked) {
            $("#Form #CampoExtra").select2('destroy').find('option').prop('selected', 'selected').end().select2();
            var CsID = $("#Form #CampoExtra").val();
            $("#Form #TotalFP").val("S");
            $("#PgtoID").val(CsID);
        } else {
            $("#Form #CampoExtra").select2('destroy').find('option').prop('selected', false).end().select2();
            $("#PgtoID").val('');
            $("#Form #TotalFP").val("");
        }
    })

    $("#Form #CampoExtra").on("change", function () {
        var PgtoID = $(this).val();
        $("#PgtoID").val(PgtoID);

        var isChange = ($("#Form #CampoExtra option:checked").length == $("#Form #CampoExtra option").length);
        $("#chkTodos")[0].checked = isChange;
        var TotalFP = (isChange) ? "S" : "";
        $("#Form #TotalFP").val(TotalFP);
    });

    if ('@ViewBag.PgtoID'.length > 0) {
        $("#Form #CampoExtra").val([@ViewBag.PgtoID]);
        $('#Form #CampoExtra').trigger('change');
    };

</script>

</code>```

Controller

```<code>public ActionResult CadastrarSMS(Sms_Mensagens SmsMensagem)
        {
            bool IsLogado = (Session["IsLogado"] is null);
            if (IsLogado)
            {
                return RedirectToAction("Login", "User", new { acao = "ErroSessao" });
            };
            if (!ModelState.IsValid)
            {
                return View("FormSms", SmsMensagem);
            }

            int MensagemID = SmsMensagem.MensagemID;

            if (MensagemID == 0)
            {
                DBCtx.MensagensDB.Add(SmsMensagem);
            }
            else
            {
                DBCtx.Entry(SmsMensagem).State = EntityState.Modified;
            }

            DBCtx.SaveChanges();

            ViewModelSucesso ViewMS = new ViewModelSucesso();
            ViewMS.Controller = "SMS";
            ViewMS.View = "Index";
            return View("Sucesso", ViewMS);

        }

        public ActionResult FormSMS(int id = 0, string acao = "")
        {

            bool IsLogado = (Session["IsLogado"] is null);
            if (IsLogado)
            {
                return RedirectToAction("Login", "User", new { acao = "ErroSessao" });
            };
            ViewBag.Id = id;
            ViewBag.Acao = acao;

            ViewBag.Label = "Cadastrar";
            if (acao == "Editar") { ViewBag.Label = "Atualizar"; };
            if (id == 0)
            {
                ViewBag.EmID = 0;
                ViewBag.FiID = 0;
                return View();
            }

            Sms_Mensagens SmsMensagem = DBCtx.MensagensDB.Find(id);
            ViewBag.EmID = SmsMensagem.EmpresaID;

            if (SmsMensagem == null)
            {
                return View();
            }
            return View(SmsMensagem);
        }
</code>```

Model

```<code>public class Sms_Mensagens
    {

        [Key]
        [Display(Name = "ID Mensagem")]
        public int MensagemID { get; set; }

        [Display(Name = "Empresa")]
        public int EmpresaID { get; set; }

        public string Tipo { get; set; }

        [Required(ErrorMessage = " - Preencha a descrição da mensagem!")]
        [Display(Name = "Descrição (até 120 caracteres)")]
        public string Descricao { get; set; }

        [Required(ErrorMessage = " - Descreva o texto da mensagem")]
        [MaxLength(155, ErrorMessage = " - O texto deve conter até {1} caracteres.")]
        [Display(Name = "Mensagem (até 155 caracteres)")]
        public string Texto { get; set; }

        [Required(ErrorMessage = " - Selecione uma ou mais areas!")]
        [Display(Name = "Areas")]
        public string CampoExtra { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}", ApplyFormatInEditMode = true)]
        public DateTime Cadastro { get; set; }

        [Required(ErrorMessage = " - Selecione a Situação")]
        [Display(Name = "Situação")]

        public string Situacao { get; set; }
        public virtual Empresas Empresas { get; set; }

    }

</code>```
```<code>public List<SelectListItem> GetListaCampoExtraFormasPGTO()
        {
            List<SelectListItem> Lista = new List<SelectListItem>();
            var data = new[]{
                new SelectListItem{Value = "CC", Text = "CARTÃO DE CRÉDITO" },
                new SelectListItem{Value = "BB", Text = "BOLETOS" },
                new SelectListItem{Value = "DC", Text = "DÉBITO EM CONTA" },
                new SelectListItem{Value = "TE", Text = "TRANSFERÊNCIA ELETRÔNICA" },
                new SelectListItem{Value = "CE", Text = "CONTA DE ENERGIA" },
                new SelectListItem{Value = "CT", Text = "CONTA DE TELEFONE" }
            };
            Lista = data.ToList();
            return Lista;
        }
</code>```

答:
When your form is submitted, selected options from your CampoExtra dropdown are sent one by one. So the body of your request will contain something like this:

```<code>CampoExtra=key1&CampoExtra=key2&CampoExtra=key3
</code>```

Your Sms_Mensagens.CampoExtra has a string type so it accepts a single string. Try to change this property to have IEnumerable<string> or string[] type. Of course, you'll have to join your selected options manually(string.Join(",", SmsMensagem.CampoExtra)) in order to save it as a single value in the DB.

Note that it might not be a good idea to store comma-separated values in one column(at least in the relational database), maybe it's better to propper normalize your tables.

Body:
I'm having problems while submitting the form and saving the filled fields within my database. Actually, this is happening just for one of my fields (model.CampoExtra), which in this case is a multiple select dropdowlist (lPagamentos). I need to save the keys of user selected items in my database, but when the user select more than one item I'm saving just a single key(the first one) and losing the rest of them.

The string containing the selected keys has this format 'key1,key2,keyN, ....'. The column in question that must receive these values has enough size, it was declared as [varchar] (80), so I really do not understand where I'm missing. I'll share sample of the code and hopefully someone can point out a mistake.

Sample of Form code (View)

@{

    List<SelectListItem> lPagamentos = new List<SelectListItem>();

    DropDownList DDList = new DropDownList();

    lPagamentos = DDList.GetListaCampoExtraFormasPGTO();

}

<link href="~/Content/CSS/select2.css" rel="stylesheet" />

Cadastro de Mensagens

        @using (Html.BeginForm(Acao, "SMS", FormMethod.Post, new { id = "FRMSms" }))
        {
            @Html.AntiForgeryToken()

Preencha com as informações do formulário!

                    @Html.HiddenFor(model => Model.MensagemID)
                    <input type="text" id="TotalFP" name="TotalFP" value="@ViewBag.TotalFP" />
                    ****

                    @if (Area == "MAS")
                    {

                            @Html.LabelFor(model => model.EmpresaID, htmlAttributes: new { @class = "control-label" })
                            @Html.ValidationMessageFor(model => model.EmpresaID, "", new { @class = "text-danger" })
                            @Html.DropDownListFor(model => model.EmpresaID, (List<SelectListItem>)lEmpresas, " - SELECIONE - ", new { @class = "form-control" })

                    }
                    else
                    { @Html.HiddenFor(model => model.EmpresaID)}

                        @Html.LabelFor(model => model.Tipo, htmlAttributes: new { @class = "control-label" })
                        @Html.ValidationMessageFor(model => model.Tipo, "", new { @class = "text-danger" })
                        @Html.EditorFor(model => model.Tipo, new { htmlAttributes = new { @class = "form-control", placeholder = "Tipo" } })

                        Descrição 120 caracteres restantes.
                        @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control", maxlength = 120 } })

                        Mensagem 155 caracteres restantes.
                        @Html.ValidationMessageFor(model => model.Texto, "", new { @class = "text-danger" })
                        @Html.TextAreaFor(model => model.Texto, new { @class = "form-control", maxlength = 155 })

                        Formas de Pagamento - <input type="checkbox" id="chkTodos" /> Selecionar todos
                        <input type="hidden" id="PgtoID" name="PgtoID" />
                        @Html.DropDownListFor(model => model.CampoExtra, (List<SelectListItem>)lPagamentos, new { @class = "form-control mySelect2", name = "CampoExtra", multiple = "multiple", style = "width:100%;" })

                        @Html.LabelFor(model => model.Situacao, htmlAttributes: new { @class = "control-label" })
                        @Html.ValidationMessageFor(model => model.Situacao, "", new { @class = "text-danger", maxlength = 1 })
                        @Html.DropDownListFor(model => model.Situacao, (List<SelectListItem>)lSituacao, " - SELECIONE - ", new { @class = "form-control" })

                        Cadastro
                        <input id="Cadastro" name="Cadastro" tabindex="-1" type="text" readonly class="form-control" value="@Cadastro" />

                    <input type="submit" value="@ViewBag.Label" class="btn btn-primary"> | @Html.ActionLink("Cancelar", "../Sms/", new { id = "", acao = "" }, new { @class = "btn btn-primary" })

        }

Controller

public ActionResult CadastrarSMS(Sms_Mensagens SmsMensagem)
        {
            bool IsLogado = (Session["IsLogado"] is null);
            if (IsLogado)
            {
                return RedirectToAction("Login", "User", new { acao = "ErroSessao" });
            };
            if (!ModelState.IsValid)
            {
                return View("FormSms", SmsMensagem);
            }

            int MensagemID = SmsMensagem.MensagemID;

            if (MensagemID == 0)
            {
                DBCtx.MensagensDB.Add(SmsMensagem);
            }
            else
            {
                DBCtx.Entry(SmsMensagem).State = EntityState.Modified;
            }

            DBCtx.SaveChanges();

            ViewModelSucesso ViewMS = new ViewModelSucesso();
            ViewMS.Controller = "SMS";
            ViewMS.View = "Index";
            return View("Sucesso", ViewMS);

        }

        public ActionResult FormSMS(int id = 0, string acao = "")
        {

            bool IsLogado = (Session["IsLogado"] is null);
            if (IsLogado)
            {
                return RedirectToAction("Login", "User", new { acao = "ErroSessao" });
            };
            ViewBag.Id = id;
            ViewBag.Acao = acao;

            ViewBag.Label = "Cadastrar";
            if (acao == "Editar") { ViewBag.Label = "Atualizar"; };
            if (id == 0)
            {
                ViewBag.EmID = 0;
                ViewBag.FiID = 0;
                return View();
            }

            Sms_Mensagens SmsMensagem = DBCtx.MensagensDB.Find(id);
            ViewBag.EmID = SmsMensagem.EmpresaID;

            if (SmsMensagem == null)
            {
                return View();
            }
            return View(SmsMensagem);
        }

Model

public class Sms_Mensagens
    {

        [Key]
        [Display(Name = "ID Mensagem")]
        public int MensagemID { get; set; }

        [Display(Name = "Empresa")]
        public int EmpresaID { get; set; }

        public string Tipo { get; set; }

        [Required(ErrorMessage = " - Preencha a descrição da mensagem!")]
        [Display(Name = "Descrição (até 120 caracteres)")]
        public string Descricao { get; set; }

        [Required(ErrorMessage = " - Descreva o texto da mensagem")]
        [MaxLength(155, ErrorMessage = " - O texto deve conter até {1} caracteres.")]
        [Display(Name = "Mensagem (até 155 caracteres)")]
        public string Texto { get; set; }

        [Required(ErrorMessage = " - Selecione uma ou mais areas!")]
        [Display(Name = "Areas")]
        public string CampoExtra { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}", ApplyFormatInEditMode = true)]
        public DateTime Cadastro { get; set; }

        [Required(ErrorMessage = " - Selecione a Situação")]
        [Display(Name = "Situação")]

        public string Situacao { get; set; }
        public virtual Empresas Empresas { get; set; }

    }

public List<SelectListItem> GetListaCampoExtraFormasPGTO()
        {
            List<SelectListItem> Lista = new List<SelectListItem>();
            var data = new[]{
                new SelectListItem{Value = "CC", Text = "CARTÃO DE CRÉDITO" },
                new SelectListItem{Value = "BB", Text = "BOLETOS" },
                new SelectListItem{Value = "DC", Text = "DÉBITO EM CONTA" },
                new SelectListItem{Value = "TE", Text = "TRANSFERÊNCIA ELETRÔNICA" },
                new SelectListItem{Value = "CE", Text = "CONTA DE ENERGIA" },
                new SelectListItem{Value = "CT", Text = "CONTA DE TELEFONE" }
            };
            Lista = data.ToList();
            return Lista;
        }

Body:
When your form is submitted, selected options from your CampoExtra dropdown are sent one by one. So the body of your request will contain something like this:

CampoExtra=key1&CampoExtra=key2&CampoExtra=key3

Your Sms_Mensagens.CampoExtra has a string type so it accepts a single string. Try to change this property to have IEnumerable<string> or string[] type. Of course, you'll have to join your selected options manually(string.Join(",", SmsMensagem.CampoExtra)) in order to save it as a single value in the DB.

Note that it might not be a good idea to store comma-separated values in one column(at least in the relational database), maybe it's better to propper normalize your tables.


答:
Solution using dplyr:

```<code>library(dplyr)
df %>%
mutate(new_column = ifelse(grepl(".*-PRD-C1", ID), "CHD", "healthy"))
</code>```

Edit:

1.Create reproducible minimal example data:

```<code>df <- data.frame(ID = c("AC12-PRD-C1", "CB19-PRD-S1"),
                 stringsAsFactors = FALSE)
</code>```

2.Solution using dplyr

```<code>library(dplyr)
df %>%
  mutate(new_column = ifelse(grepl(".*-PRD-C1", ID), "CHD", "healthy"))
</code>```

Returns:

```<code>           ID new_column
1 AC12-PRD-C1        CHD
2 CB19-PRD-S1    healthy
</code>```

Body:
Solution using dplyr:

library(dplyr)
df %>%
mutate(new_column = ifelse(grepl(".*-PRD-C1", ID), "CHD", "healthy"))

Edit:

1.Create reproducible minimal example data:

df <- data.frame(ID = c("AC12-PRD-C1", "CB19-PRD-S1"),
                 stringsAsFactors = FALSE)

2.Solution using dplyr

library(dplyr)
df %>%
  mutate(new_column = ifelse(grepl(".*-PRD-C1", ID), "CHD", "healthy"))

Returns:

           ID new_column
1 AC12-PRD-C1        CHD
2 CB19-PRD-S1    healthy


问:
How do I HTTP post stream data from memory in Ruby?
I would like to upload data I generated at runtime in Ruby, something like feeding the upload from a block.

All examples I found only show how to stream a file that must be on disk prior to the request but I do not want to buffer the file.

What is the best solution besides rolling my own socket connection?

This a pseudocode example:

```<code>post_stream('127.0.0.1', '/stream/') do |body|
  generate_xml do |segment|
    body << segment
  end
end
</code>```

答:
Code that works.</p>

```<code>    require 'thread'
    require 'net/http'
    require 'base64'
    require 'openssl'

    class Producer
      def initialize
       @mutex = Mutex.new
       @body = ''
       @eof = false
      end

      def eof!()
        @eof = true
      end

      def eof?()
        @eof
      end

      def read(size)
        @mutex.synchronize {
          @body.slice!(0,size)
        }
      end

      def produce(str)
        if @body.empty? && @eof
          nil
        else
          @mutex.synchronize { @body.slice!(0,size) }
        end
      end
    end

    data = "--60079\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test.file\"\r\nContent-Type: application/x-ruby\r\n\r\nthis is just a test\r\n--60079--\r\n"

    req = Net::HTTP::Post.new('/')
    producer = Producer.new
    req.body_stream = producer
    req.content_length = data.length
    req.content_type = "multipart/form-data; boundary=60079"

    t1 = Thread.new do
      producer.produce(data)
      producer.eof!
    end

    res = Net::HTTP.new('127.0.0.1', 9000).start {|http| http.request(req) }
    puts res
</code>```

Body:
I would like to upload data I generated at runtime in Ruby, something like feeding the upload from a block.

All examples I found only show how to stream a file that must be on disk prior to the request but I do not want to buffer the file.

What is the best solution besides rolling my own socket connection?

This a pseudocode example:

post_stream('127.0.0.1', '/stream/') do |body|
  generate_xml do |segment|
    body << segment
  end
end

Body:
Code that works.

    require 'thread'
    require 'net/http'
    require 'base64'
    require 'openssl'

    class Producer
      def initialize
       @mutex = Mutex.new
       @body = ''
       @eof = false
      end

      def eof!()
        @eof = true
      end

      def eof?()
        @eof
      end

      def read(size)
        @mutex.synchronize {
          @body.slice!(0,size)
        }
      end

      def produce(str)
        if @body.empty? && @eof
          nil
        else
          @mutex.synchronize { @body.slice!(0,size) }
        end
      end
    end

    data = "--60079\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test.file\"\r\nContent-Type: application/x-ruby\r\n\r\nthis is just a test\r\n--60079--\r\n"

    req = Net::HTTP::Post.new('/')
    producer = Producer.new
    req.body_stream = producer
    req.content_length = data.length
    req.content_type = "multipart/form-data; boundary=60079"

    t1 = Thread.new do
      producer.produce(data)
      producer.eof!
    end

    res = Net::HTTP.new('127.0.0.1', 9000).start {|http| http.request(req) }
    puts res


问:
How can I return only one record per type?
I have a table with multiple records per one account type and I want to return only one by latest date. I have:

```<code>SELECT
id_nbr AS ID,
contact_type AS contype,
last_update AS date
FROM table
WHERE (contact_type = 'AAA' OR contact_type = 'BBB' OR contact_type = 'CCC');
</code>```

It may return something like this:

```<code>ID          contype     date
111111111   AAA         2020-01-30
111111111   AAA         2019-05-05
111111111   BBB         2020-01-02
111111111   CCC         2020-02-17
</code>```

Looking at this data, I only want 3 rows because contype has multiple AAA records but I only want the latest date. Something like:

```<code>ID          contype     date
111111111   AAA         2020-01-30
111111111   BBB         2020-01-02
111111111   CCC         2020-02-17
</code>```

This is obviously very high-level but how can I achieve this? This would help me tremendously. Thanks in advance!!

答:
```<code>-- create a new column (temp_tab) with max date and
-- select the rows where the date is equal to temp_tab

select ID, contype, date from
(select ID, contype, date, max(date) over (partition by ID, contype) as temp_tab from table)
where date = temp_tab
</code>```

Body:
I have a table with multiple records per one account type and I want to return only one by latest date. I have:

SELECT
id_nbr AS ID,
contact_type AS contype,
last_update AS date
FROM table
WHERE (contact_type = 'AAA' OR contact_type = 'BBB' OR contact_type = 'CCC');

It may return something like this:

ID          contype     date
111111111   AAA         2020-01-30
111111111   AAA         2019-05-05
111111111   BBB         2020-01-02
111111111   CCC         2020-02-17

Looking at this data, I only want 3 rows because contype has multiple AAA records but I only want the latest date. Something like:

ID          contype     date
111111111   AAA         2020-01-30
111111111   BBB         2020-01-02
111111111   CCC         2020-02-17

This is obviously very high-level but how can I achieve this? This would help me tremendously. Thanks in advance!!


问:
Why is a join ON false much slower that a join with an ON condition that refers the columns but always evaluates to false in Snowflake?
This two queries have the same result but very different execution times, in both cases the ON clause always evaluate to false. In the first query there is a explicit ON false and the second query the ON t1.c1 = t2.c2 will always evaluate to false as well.

```<code>-- query 1
with t1 as (
  select seq4()*2 as c1 from table(generator(rowcount => 1000000))
)
,t2 as (
  select (seq4()*2)+1 as c2 from table(generator(rowcount => 1000000))
)
select * from t1 FULL JOIN t2 ON false; -- takes 16 minutes on a small warehouse

--query 2
with t1 as (
  select seq4()*2 as c1 from table(generator(rowcount => 1000000))
)
,t2 as (
  select (seq4()*2)+1 as c2 from table(generator(rowcount => 1000000))
)
select * from t1 FULL JOIN t2 ON t1.c1 = t2.c2 -- Instantaneous , same results
;
</code>```

According to the snowflake profiler the only difference is that in query 1 we get a FULL OUTER join node with Additional Join Condition 1=0 and in query 2 we get a FULL OUTER join node with Equality Join Condition SYS_VW.C1_0 = SYS_VW.C2_0.

I guess that query 1 is really doing a CROSS JOIN first (1000000 * 1000000 = 10ˆ12 rows) and then filtering that. While query2 is doing just doing a UNION of sorts evaluating only 1000000+1000000 = 2M rows.

But the question is: why? I mean, it's this behaviour specified / required by SQL in general or it's just a miss from the Snowflake query planner / optimizer ?

答:
After consulting with Snowflake support (case 96930) I got the takeaway points

ON FALSE is not a syntax they support right now.

Snowflake don't interpret the keyword FALSE like other SQL languages and it's reserved for outside of the JOIN clauses. That is way it gets translated to 1=0

Since it's not supported, this is why query1 results in 56 more optimization steps that query2.

Fortunately the support engineer agrees that there is an opportunity to have this conditions ON FALSE , ON t1.c1=t2.c2 to be handled exactly the same and he will deliver the suggestion to the engineering deparment.

So, in short, ON FALSE is not supported although it doesn't produce an error. They recommend using a proper ON clause for all JOINs except CROSS JOIN. And maybe in the future they will recognize ON FALSE and optimize it away.

Body:
This two queries have the same result but very different execution times, in both cases the ON clause always evaluate to false. In the first query there is a explicit ON false and the second query the ON t1.c1 = t2.c2 will always evaluate to false as well.

-- query 1
with t1 as (
  select seq4()*2 as c1 from table(generator(rowcount => 1000000))
)
,t2 as (
  select (seq4()*2)+1 as c2 from table(generator(rowcount => 1000000))
)
select * from t1 FULL JOIN t2 ON false; -- takes 16 minutes on a small warehouse

--query 2
with t1 as (
  select seq4()*2 as c1 from table(generator(rowcount => 1000000))
)
,t2 as (
  select (seq4()*2)+1 as c2 from table(generator(rowcount => 1000000))
)
select * from t1 FULL JOIN t2 ON t1.c1 = t2.c2 -- Instantaneous , same results
;

According to the snowflake profiler the only difference is that in query 1 we get a FULL OUTER join node with Additional Join Condition 1=0 and in query 2 we get a FULL OUTER join node with Equality Join Condition SYS_VW.C1_0 = SYS_VW.C2_0.

I guess that query 1 is really doing a CROSS JOIN first (1000000 * 1000000 = 10ˆ12 rows) and then filtering that. While query2 is doing just doing a UNION of sorts evaluating only 1000000+1000000 = 2M rows.

But the question is: why? I mean, it's this behaviour specified / required by SQL in general or it's just a miss from the Snowflake query planner / optimizer ?


问:
Springboot getting UTC+1 instead of GMT when called from endpoint
I actually have an issue with dates when they are called from an endpoint :

The date returned is one hour before UTC+1

But on the database the date is correct (UTC+1)

And when debugging the date from my object is also correct (UTC+1)

I have the following setUp  :

Main.java :

```<code>@SpringBootApplication
@Slf4j
public class Main extends SpringBootServletInitializer
{
  @PostConstruct
  void started() {
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris"));
  }

</code>```

I have set Hibernate to the following timezone :

application.properties :

```<code>spring.jpa.properties.hibernate.jdbc.time_zone = Europe/Paris

</code>```

I get the correct date before posting it :

Date from database (took 4 minutes to post because the programm was on pause) :

Date from postman when calling endpoint

Anyone has any idea on why the date when returned throught an endpoint seems to be a GMT ?

答:
The comment from vickirk pointed that the problem was related to Jackson

You need to add a timezone to your JsonFormat annotation
Like this :

```<code>@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss", timezone = "Europe/Paris")
@Column(name = "date_creation", nullable = true)
protected Date dateCreation;
</code>```

The related issue can be found there :
https://stackoverflow.com/a/31838669/5186678

Body:
I actually have an issue with dates when they are called from an endpoint :

The date returned is one hour before UTC+1

But on the database the date is correct (UTC+1)

And when debugging the date from my object is also correct (UTC+1)

I have the following setUp  :

Main.java :

@SpringBootApplication
@Slf4j
public class Main extends SpringBootServletInitializer
{
  @PostConstruct
  void started() {
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris"));
  }

I have set Hibernate to the following timezone :

application.properties :

spring.jpa.properties.hibernate.jdbc.time_zone = Europe/Paris

I get the correct date before posting it :

Date from database (took 4 minutes to post because the programm was on pause) :

Date from postman when calling endpoint

Anyone has any idea on why the date when returned throught an endpoint seems to be a GMT ?

Body:
The comment from vickirk pointed that the problem was related to Jackson

You need to add a timezone to your JsonFormat annotation
Like this :

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss", timezone = "Europe/Paris")
@Column(name = "date_creation", nullable = true)
protected Date dateCreation;

The related issue can be found there :
https://stackoverflow.com/a/31838669/5186678


问:
Insert element in Python list after every nth element
Say I have a Python list like this:

```<code>letters = ['a','b','c','d','e','f','g','h','i','j']
</code>```

I want to insert an 'x' after every nth element, let's say three characters in that list. The result should be:

```<code>letters = ['a','b','c','x','d','e','f','x','g','h','i','x','j']
</code>```

I understand that I can do that with looping and inserting. What I'm actually looking for is a Pythonish-way, a one-liner maybe?

答:
It's worth stating the simple implementation too:

```<code>letters = ['a','b','c','d','e','f','g','h','i','j']

i = 3   #initial step
while i < len(letters):
    letters.insert(i,'x')
    i = i + 3 + 1  #increment step by one for every loop to account for the added element
</code>```

It does use basic looping and inserting, but it also looks much simpler and comfortable to read than the one-liner examples, which IMHO makes it more Pythonish as requested in the first place.

Body:
Say I have a Python list like this:

letters = ['a','b','c','d','e','f','g','h','i','j']

I want to insert an 'x' after every nth element, let's say three characters in that list. The result should be:

letters = ['a','b','c','x','d','e','f','x','g','h','i','x','j']

I understand that I can do that with looping and inserting. What I'm actually looking for is a Pythonish-way, a one-liner maybe?

Body:
It's worth stating the simple implementation too:

letters = ['a','b','c','d','e','f','g','h','i','j']

i = 3   #initial step
while i < len(letters):
    letters.insert(i,'x')
    i = i + 3 + 1  #increment step by one for every loop to account for the added element

It does use basic looping and inserting, but it also looks much simpler and comfortable to read than the one-liner examples, which IMHO makes it more Pythonish as requested in the first place.


问:
Angular2 - Forward field validation in custom Component
I am creating a custom form control component (email) that contains an input field, I forward the value of the input field (done correctly) but also want to forward its errors.

Using the following code I successfully pass the field's errors when the input changes but it does not pick up the initial errors correctly.

For example this email field will still report errors = {'required':true} even after the view is fully loaded and a value of 'example@email.com' is passed to it. Starting to type in the field and it will pass the errors correctly.

So my question is, how can I pass the errors after the initial load of data?

note: the problem is resolved by running this.propagateChange(this.value); in DoCheck lifecycle but I don't like it, I need something that is more efficient but no other hook seems to do the trick.

Here is the example:

```<code>import {Component, forwardRef, Input, ViewChild} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, NgModel} from '@angular/forms';

@Component({
  selector: 'input-email',
  template:`<form-group
  [errors]="{'required':'Email required', 'email':'Invalid email format'}"
  [info]="'Email*'"
>

  <input
    type        = "email"
    name        = "email"
    class       = "form-control"
    [(ngModel)] = "value"
    placeholder = "{{placeholder}}"
    (input)="onChange()"
    email
    required
    #f          = "ngModel"
  >
  {{f.errors | json}}
</form-group>`,
  styleUrls: ['./email.component.css'],
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputEmailComponent), multi: true },
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => InputEmailComponent), multi: true }
  ]
})
export class InputEmailComponent implements ControlValueAccessor {

  value:String = null;

  @ViewChild('f') f:NgModel;

  @Input()
  placeholder:String = "Email";

  propagateChange:any = (val) => {};

  constructor() {}

  onChange(){
    this.propagateChange(this.value);
  }

  /**
   * Write a passed NgValue value to the element.
   */
  writeValue(value) {
    if (value && this.value != value) {
      this.value = value;
    }
  }

  /**
   * Set the function to be called
   * when the control receives a change event.
   * registers 'fn' that will be fired when changes are made
   * this is how we emit the changes back to the form
   */
  registerOnChange(fn) {
    this.propagateChange = fn;
  }

  /**
   * Set the function to be called
   * when the control receives a touch event.
   */
  registerOnTouched(fn) {}

  /**
   * Set the function to be called
   * to validate if input has errors.
   */
  validate(c: FormControl):any {

    console.log('validate email');
    return this.f.errors;

  }
}
</code>```

答:
I got around this by calling the onValidatorChange callback (from the Validator interface) in ngAfterViewInit:

```<code>  ngAfterViewInit(): void {
    // Force the validation to trigger after the view has been initialised
    // otherwise the initial value is not marked as invalid
    if (this.onValidatorChange) {
      // you need a setTimeout here to make the change after Angular's change detection
      setTimeout(() => {
        this.onValidatorChange();
        this.cdr.markForCheck();
      }, 0);
    }
  }

  registerOnValidatorChange(fn: () => void): void {
    this.onValidatorChange = fn
  }
</code>```

Body:
I am creating a custom form control component (email) that contains an input field, I forward the value of the input field (done correctly) but also want to forward its errors.

Using the following code I successfully pass the field's errors when the input changes but it does not pick up the initial errors correctly.

For example this email field will still report errors = {'required':true} even after the view is fully loaded and a value of 'example@email.com' is passed to it. Starting to type in the field and it will pass the errors correctly.

So my question is, how can I pass the errors after the initial load of data?

note: the problem is resolved by running this.propagateChange(this.value); in DoCheck lifecycle but I don't like it, I need something that is more efficient but no other hook seems to do the trick.

Here is the example:

import {Component, forwardRef, Input, ViewChild} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, NgModel} from '@angular/forms';

@Component({
  selector: 'input-email',
  template:`<form-group
  [errors]="{'required':'Email required', 'email':'Invalid email format'}"
  [info]="'Email*'"
>

  <input
    type        = "email"
    name        = "email"
    class       = "form-control"
    [(ngModel)] = "value"
    placeholder = "{{placeholder}}"
    (input)="onChange()"
    email
    required
    #f          = "ngModel"
  >
  {{f.errors | json}}
</form-group>`,
  styleUrls: ['./email.component.css'],
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputEmailComponent), multi: true },
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => InputEmailComponent), multi: true }
  ]
})
export class InputEmailComponent implements ControlValueAccessor {

  value:String = null;

  @ViewChild('f') f:NgModel;

  @Input()
  placeholder:String = "Email";

  propagateChange:any = (val) => {};

  constructor() {}

  onChange(){
    this.propagateChange(this.value);
  }

  /**
   * Write a passed NgValue value to the element.
   */
  writeValue(value) {
    if (value && this.value != value) {
      this.value = value;
    }
  }

  /**
   * Set the function to be called
   * when the control receives a change event.
   * registers 'fn' that will be fired when changes are made
   * this is how we emit the changes back to the form
   */
  registerOnChange(fn) {
    this.propagateChange = fn;
  }

  /**
   * Set the function to be called
   * when the control receives a touch event.
   */
  registerOnTouched(fn) {}

  /**
   * Set the function to be called
   * to validate if input has errors.
   */
  validate(c: FormControl):any {

    console.log('validate email');
    return this.f.errors;

  }
}

Body:
I got around this by calling the onValidatorChange callback (from the Validator interface) in ngAfterViewInit:

  ngAfterViewInit(): void {
    // Force the validation to trigger after the view has been initialised
    // otherwise the initial value is not marked as invalid
    if (this.onValidatorChange) {
      // you need a setTimeout here to make the change after Angular's change detection
      setTimeout(() => {
        this.onValidatorChange();
        this.cdr.markForCheck();
      }, 0);
    }
  }

  registerOnValidatorChange(fn: () => void): void {
    this.onValidatorChange = fn
  }


问:
handleClick in React
I have a MenuCard component which contains a handleClick which returns the names and images of the various menus. I also have a LikeButton component which has a counter and increments each time the button is pressed.

I am having problems trying to use this LikeButton in the MenuCard as every time I click the button, it goes to the selected menu's id page, which it should do if the user clicks on the card.

But how can I have it avoid that when I click LikeButton? I am just not sure where to call LikeButton in MenuCard.

MenuCard Component:

```<code>import React from 'react';

import Card from 'react-bootstrap/Card'

import LikeButton from "../components/LikeButton";

const MenuCard = props => {

    const handleClick = () => {
        props.view(props.info.id, "menus", 'DISPLAY_MENUS');
    };

    return (
        <Card onClick={handleClick} style={{ width: '18rem' }}>
            <Card.Body>
                <Card.Title>{props.info.name}<LikeButton /></Card.Title>
            </Card.Body>
            <Card.Img variant="bottom" style={{ height: '12rem' }} src={props.info.image} />
        </Card>
    )
}

export default MenuCard
</code>```

LikeButton Component:

```<code>import React, { Component } from 'react';

import Button from 'react-bootstrap/Button'

class LikeButton extends Component {
  state = {
      count: 0
    }

increment = () => {
      let newCount = this.state.count + 1
      this.setState({
        count: newCount
      })
    }

render() {
  return (
   <div>
     <button onClick={this.increment}>Likes: {this.state.count} </button>
   </div>
  )
}

}

export default LikeButton;
</code>```

答:
I would suggest not to use stop propagation to handle this issue. Instead you can add an id to the like button and check the value of event.target.id in menu click to avoid it triggering.

why should you avoid stop propagation - In case you add a analytics tool to your web page, they rely on event bubbling to capture data.

Title: handleClick in React

Body:
I have a MenuCard component which contains a handleClick which returns the names and images of the various menus. I also have a LikeButton component which has a counter and increments each time the button is pressed.

I am having problems trying to use this LikeButton in the MenuCard as every time I click the button, it goes to the selected menu's id page, which it should do if the user clicks on the card.

But how can I have it avoid that when I click LikeButton? I am just not sure where to call LikeButton in MenuCard.

MenuCard Component:

import React from 'react';

import Card from 'react-bootstrap/Card'

import LikeButton from "../components/LikeButton";

const MenuCard = props => {

    const handleClick = () => {
        props.view(props.info.id, "menus", 'DISPLAY_MENUS');
    };

    return (
        <Card onClick={handleClick} style={{ width: '18rem' }}>
            <Card.Body>
                <Card.Title>{props.info.name}<LikeButton /></Card.Title>
            </Card.Body>
            <Card.Img variant="bottom" style={{ height: '12rem' }} src={props.info.image} />
        </Card>
    )
}

export default MenuCard

LikeButton Component:

import React, { Component } from 'react';

import Button from 'react-bootstrap/Button'

class LikeButton extends Component {
  state = {
      count: 0
    }

increment = () => {
      let newCount = this.state.count + 1
      this.setState({
        count: newCount
      })
    }

render() {
  return (

     <button onClick={this.increment}>Likes: {this.state.count} </button>

  )
}

}

export default LikeButton;


问:
Change series point colour on hover
I am trying to get the points on my graph in a particular series to change colour when the any point in the series is hovered over. i.e. hovering over a point in series 1 makes all points in series 1 change colour (and are hence highlighted).

This is made a little more difficult as I initially colour the points based on their value.

I tried to adapt the answer from highcharter change highlight color on hover, but it doesnt seem to be working with points that have been coloured in as they do not change on hover.

```<code>library(highcharter)
library(data.table)
library(dplyr)

# generate data
data = data.table(
  CJ(x = seq(as.Date("2019-01-01"), as.Date("2019-01-10"), by = "day"),
     group = seq(1,2))
)
data[, value := round(runif(n=20, -5,5),4)]

# color points based on value
data = data.table(data %>% mutate(cat=cut(value, breaks=quantile(data[value!=0]$value, seq(0,1,0.1)), labels=seq(1,10))))
colf = colorRampPalette(colors = c("red","yellow", "green"))
cols = colf(10)
data[, color := as.factor(cols[cat])]

# get point position
data$x = datetime_to_timestamp(data$x)
data = data.table(data %>% group_by(x) %>% mutate(y = order(order(value))-sum(value<0,na.rm=T)))

# plot data
highchart() %>%
  hc_xAxis(type = "datetime", dateTimeLabelFormats = list(day = '%d of %b')) %>%
  hc_add_series(data[group==1], name = "group 1", marker = list(symbol = fa_icon("circle"))) %>%
  hc_add_series(data[group==2], name = "group 2", marker = list(symbol = fa_icon("circle"))) %>%
  hc_chart(type = "scatter") %>%
  hc_tooltip(pointFormat = "Performance = <b>{point.value}</b> <br> Group = <b>{point.name}</b>") %>%
  # hover over part
  hc_plotOptions(
    series = list(
      stickyTracking = FALSE,
      events = list(
        mouseOver = JS("function() { if(this.options.color !== 'red') {this.update({color: 'red'})} }"),
        mouseOut = JS("function() { if(this.options.color === 'red') {this.update({color: '#ddd'})} }")
      ),
      states = list(
        hover = list(
          enabled = TRUE,
          lineWidth = 10
        )
      )
    ))
</code>```

The graph:

答:
You can use Inactive State: https://api.highcharts.com/highcharts/series.scatter.states.inactive

It's been included in Highcharts since 7.1.0 and enabled by default so all you need to do is to make sure that you are using the newest Highcharter.

Here you have an example of it: https://jsfiddle.net/BlackLabel/2wu3jrmt

```<code>Highcharts.chart('container', {

  chart: {
    type: 'scatter'
  },

  series: [{
    data: [4, 3, 5, 6, 2, 5]
  }, {
    data: [2, 5, 3, 7, 3, 1]
  }, {
    data: [1, 1, 6, 3, 4, 3]
  }]

});
</code>```

Title: Change series point colour on hover

Body:
I am trying to get the points on my graph in a particular series to change colour when the any point in the series is hovered over. i.e. hovering over a point in series 1 makes all points in series 1 change colour (and are hence highlighted).

This is made a little more difficult as I initially colour the points based on their value.

I tried to adapt the answer from highcharter change highlight color on hover, but it doesnt seem to be working with points that have been coloured in as they do not change on hover.

library(highcharter)
library(data.table)
library(dplyr)

# generate data
data = data.table(
  CJ(x = seq(as.Date("2019-01-01"), as.Date("2019-01-10"), by = "day"),
     group = seq(1,2))
)
data[, value := round(runif(n=20, -5,5),4)]

# color points based on value
data = data.table(data %>% mutate(cat=cut(value, breaks=quantile(data[value!=0]$value, seq(0,1,0.1)), labels=seq(1,10))))
colf = colorRampPalette(colors = c("red","yellow", "green"))
cols = colf(10)
data[, color := as.factor(cols[cat])]

# get point position
data$x = datetime_to_timestamp(data$x)
data = data.table(data %>% group_by(x) %>% mutate(y = order(order(value))-sum(value<0,na.rm=T)))

# plot data
highchart() %>%
  hc_xAxis(type = "datetime", dateTimeLabelFormats = list(day = '%d of %b')) %>%
  hc_add_series(data[group==1], name = "group 1", marker = list(symbol = fa_icon("circle"))) %>%
  hc_add_series(data[group==2], name = "group 2", marker = list(symbol = fa_icon("circle"))) %>%
  hc_chart(type = "scatter") %>%
  hc_tooltip(pointFormat = "Performance = {point.value}
 Group = {point.name}") %>%
  # hover over part
  hc_plotOptions(
    series = list(
      stickyTracking = FALSE,
      events = list(
        mouseOver = JS("function() { if(this.options.color !== 'red') {this.update({color: 'red'})} }"),
        mouseOut = JS("function() { if(this.options.color === 'red') {this.update({color: '#ddd'})} }")
      ),
      states = list(
        hover = list(
          enabled = TRUE,
          lineWidth = 10
        )
      )
    ))

The graph:

Body:
You can use Inactive State: https://api.highcharts.com/highcharts/series.scatter.states.inactive

It's been included in Highcharts since 7.1.0 and enabled by default so all you need to do is to make sure that you are using the newest Highcharter.

Here you have an example of it: https://jsfiddle.net/BlackLabel/2wu3jrmt

Highcharts.chart('container', {

  chart: {
    type: 'scatter'
  },

  series: [{
    data: [4, 3, 5, 6, 2, 5]
  }, {
    data: [2, 5, 3, 7, 3, 1]
  }, {
    data: [1, 1, 6, 3, 4, 3]
  }]

});


问:
How can I print ■ in visual studio c?
I want to print ■(in ascii code 254) in c visual studio project with function printf, but my program can't print. Just like(? instead of ■)

My program can print ascii character 32 ~ 128.

I think since 129~254 is extended ascii, it requires more code(header?other function?).

How can i print ■? help me please.

here is my code.

```<code>#include<stdio.h>
int main() {
    unsigned char count;
    for (count = 32; count < 255; count++) {
        printf("  %3d - %c", count, count);
        if (count % 6 == 0) {
            printf("\n");
        }
    }
    return 0;
}
</code>```

答:
I just have solved by adding system("chcp 437"), which changes language Korean to English in cmd(dos window).

here is my code

```<code>#include<stdio.h>
#include<Windows.h>
int main() {
    unsigned char count;
    system("chcp 437");
    for (count = 32; count < 255; count++) {
        printf("  %3d - %c", count, count);
        if (count % 6 == 0) {
            printf("\n");
        }
    }
    return 0;
}
</code>```

Title: How can I print ■ in visual studio c?

Body:
I want to print ■(in ascii code 254) in c visual studio project with function printf, but my program can't print. Just like(? instead of ■)

My program can print ascii character 32 ~ 128.

I think since 129~254 is extended ascii, it requires more code(header?other function?).

How can i print ■? help me please.

here is my code.

#include<stdio.h>
int main() {
    unsigned char count;
    for (count = 32; count < 255; count++) {
        printf("  %3d - %c", count, count);
        if (count % 6 == 0) {
            printf("\n");
        }
    }
    return 0;
}

Body:
I just have solved by adding system("chcp 437"), which changes language Korean to English in cmd(dos window).

here is my code

#include<stdio.h>
#include<Windows.h>
int main() {
    unsigned char count;
    system("chcp 437");
    for (count = 32; count < 255; count++) {
        printf("  %3d - %c", count, count);
        if (count % 6 == 0) {
            printf("\n");
        }
    }
    return 0;
}


问:
How to construct an empty data.table with the colum names of an existing data.table?
I would like to create an empty data.table in R with colum names from another existing data.table.
Somehow I could not find a solution for that.

I would like to do something like that:

```<code>require(data.table)

dt1 <- data.table(fn = c("A","B","C"), x = c(1,2,3), y = c(2,3,4), a = 1, b = 2, c = 3)
dt2 <- data.table(names=colnames(dt1)) # Gives 6 rows instead of 6 cols
</code>```

How can this be achieved?

Thanks!

答:
You can also take your old dt1, clear it and keep as dt2

```<code>dt2 <- dt1[0,]
dt2
Empty data.table (0 rows and 6 cols): fn,x,y,a,b,c
</code>```

It isn't precisely what did you want, but it always some solution.

Body:
I would like to create an empty data.table in R with colum names from another existing data.table.
Somehow I could not find a solution for that.

I would like to do something like that:

require(data.table)

dt1 <- data.table(fn = c("A","B","C"), x = c(1,2,3), y = c(2,3,4), a = 1, b = 2, c = 3)
dt2 <- data.table(names=colnames(dt1)) # Gives 6 rows instead of 6 cols

How can this be achieved?

Thanks!

Body:
You can also take your old dt1, clear it and keep as dt2

dt2 <- dt1[0,]
dt2
Empty data.table (0 rows and 6 cols): fn,x,y,a,b,c

It isn't precisely what did you want, but it always some solution.


问:
How to get date given only the day of year number in flutter
I am fairly new to flutter. In android, I could easily use the Calendar class set using cal.set(Calendar.DAY_OF_YEAR, number) and it will return the date for that particular day_of_year number. How can I do the same in Flutter.

In Android, this is what I would have done

```<code>Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_YEAR,1);  //set date using day of year
return cal.getTime(); //2020-01-01
</code>```

How do I implement this in Flutter.

答:
I gave this a go for fun, I don't normally do Dart, so apologies if its wrong!

```<code>var dayOfYear = 1;
var millisInADay = Duration(days: 1).inMilliseconds; // 86400000
var millisDayOfYear = dayOfYear * millisInADay;
var millisecondsSinceEpoch = DateTime(DateTime.now().year).millisecondsSinceEpoch;

var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch + millisDayOfYear);
</code>```

For the day of year == 1.

When there are 86400000 milliseconds in a day.

Then there are 86400000 millis in that year (1 x 86400000).

Create a new date for the first day of the year.

Add the number of millis in the year, to the number of millis to the start of the year since epoch. Create a new date using this milliseconds since epoch.

Reference:

https://api.dart.dev/stable/2.7.1/dart-core/DateTime-class.html

Body:
I am fairly new to flutter. In android, I could easily use the Calendar class set using cal.set(Calendar.DAY_OF_YEAR, number) and it will return the date for that particular day_of_year number. How can I do the same in Flutter.

In Android, this is what I would have done

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_YEAR,1);  //set date using day of year
return cal.getTime(); //2020-01-01

How do I implement this in Flutter.

Body:
I gave this a go for fun, I don't normally do Dart, so apologies if its wrong!

var dayOfYear = 1;
var millisInADay = Duration(days: 1).inMilliseconds; // 86400000
var millisDayOfYear = dayOfYear * millisInADay;
var millisecondsSinceEpoch = DateTime(DateTime.now().year).millisecondsSinceEpoch;

var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch + millisDayOfYear);

For the day of year == 1.

When there are 86400000 milliseconds in a day.

Then there are 86400000 millis in that year (1 x 86400000).

Create a new date for the first day of the year.

Add the number of millis in the year, to the number of millis to the start of the year since epoch. Create a new date using this milliseconds since epoch.

Reference:

https://api.dart.dev/stable/2.7.1/dart-core/DateTime-class.html


问:
How to enable/disable tool tips with code
How to enable/disable tooltips with code.
I am able to enable tooltips for a button with code on form load, but cannot turn tooltips off with code for a checkbox.

```<code>private void Form1_Load(object sender, EventArgs e)
{
    // Create the ToolTip and associate with the Form container.
    ToolTip toolTip1 = new ToolTip();

    // Set up the ToolTip text for a Button.
    toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
}
</code>```

Works perfectly.

I am now trying to make a user option to turn on/off the tooltip with a checkbox.

```<code>private void ChkEnableTips_CheckedChanged(object sender, EventArgs e)
{
    ToolTip toolTip1 = new ToolTip();

    if (ChkEnableTips.Checked == true)
    {
        toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
    }
    if (ChkEnableTips.Checked == false)
    {
        toolTip1.SetToolTip(this.btnRunExtApp, null);
    }
}
</code>```

Maybe it is because I am declaring toolTip1 again?
I tried to change it to toolTip2 but this did not work either.
But if I do not declare it at all in ChkEnableTips_CheckedChanged then I get an error (The name 'toolTip1' does not exist in the current context).

答:
Yes it is because you declare it again. Write to the top of your class a global variable.

```<code>ToolTip toolTip1 = new ToolTip();
</code>```

Then events (also the constructor) can use it:

```<code>private void ChkEnableTips_CheckedChanged(object sender, EventArgs e)
{
    if (ChkEnableTips.Checked == true)
        toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
    if (ChkEnableTips.Checked == false)
        toolTip1.SetToolTip(this.btnRunExtApp, null);
}
</code>```

Do not set toolTip1 in Load event, go to the designer view instead and set your checkbox to be ticked by default. This will raise the event anyway and the handler above does the job for you. Also this way you avoid a 2nd call to SetToolTip().

(Btw, some info for your future design when you want init in constructor - instead of Load -: the field initialization happens before the lines in the constructor.)

Edit:

Maybe there is a component in the Toolbox called ToolTip. You can drag and drop. It does not change anything! just moves this line:

```<code>ToolTip toolTip1 = new ToolTip();
</code>```

To the designer.cs

Body:
How to enable/disable tooltips with code.
I am able to enable tooltips for a button with code on form load, but cannot turn tooltips off with code for a checkbox.

private void Form1_Load(object sender, EventArgs e)
{
    // Create the ToolTip and associate with the Form container.
    ToolTip toolTip1 = new ToolTip();

    // Set up the ToolTip text for a Button.
    toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
}

Works perfectly.

I am now trying to make a user option to turn on/off the tooltip with a checkbox.

private void ChkEnableTips_CheckedChanged(object sender, EventArgs e)
{
    ToolTip toolTip1 = new ToolTip();

    if (ChkEnableTips.Checked == true)
    {
        toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
    }
    if (ChkEnableTips.Checked == false)
    {
        toolTip1.SetToolTip(this.btnRunExtApp, null);
    }
}

Maybe it is because I am declaring toolTip1 again?
I tried to change it to toolTip2 but this did not work either.
But if I do not declare it at all in ChkEnableTips_CheckedChanged then I get an error (The name 'toolTip1' does not exist in the current context).

Body:
Yes it is because you declare it again. Write to the top of your class a global variable.

ToolTip toolTip1 = new ToolTip();

Then events (also the constructor) can use it:

private void ChkEnableTips_CheckedChanged(object sender, EventArgs e)
{
    if (ChkEnableTips.Checked == true)
        toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
    if (ChkEnableTips.Checked == false)
        toolTip1.SetToolTip(this.btnRunExtApp, null);
}

Do not set toolTip1 in Load event, go to the designer view instead and set your checkbox to be ticked by default. This will raise the event anyway and the handler above does the job for you. Also this way you avoid a 2nd call to SetToolTip().

(Btw, some info for your future design when you want init in constructor - instead of Load -: the field initialization happens before the lines in the constructor.)

Edit:

Maybe there is a component in the Toolbox called ToolTip. You can drag and drop. It does not change anything! just moves this line:

ToolTip toolTip1 = new ToolTip();

To the designer.cs


问:
How can I set the default timezone in node.js?
How do I set the default timezone in node.js? </p>

答:
You can config global timezone with the library tzdata:

```<code>npm install tzdata -y
</code>```

After set your environment with the variable for example: TZ=America/Bogota

And testing in your project:

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

I hope helpyou

Body:
You can config global timezone with the library tzdata:

npm install tzdata -y

After set your environment with the variable for example: TZ=America/Bogota

And testing in your project:

new Date()

I hope helpyou


问:
Pyspark dataframe operator "IS NOT IN"
I would like to rewrite this from R to Pyspark, any nice looking suggestions?</p>

```<code>array <- c(1,2,3)
dataset <- filter(!(column %in% array))
</code>```

答:
* is not needed. So:

```<code>list = [1, 2, 3]
dataframe.filter(~dataframe.column.isin(list))
</code>```

Title: Pyspark dataframe operator "IS NOT IN"

Body:
I would like to rewrite this from R to Pyspark, any nice looking suggestions?

array <- c(1,2,3)
dataset <- filter(!(column %in% array))

Body:
* is not needed. So:

list = [1, 2, 3]
dataframe.filter(~dataframe.column.isin(list))


答:
Modifying the variable no doesn't do what you want here, because Python's for no in range(...): loop gets the values for no from the range iterator. That iterator doesn't know about the variable no, and will keep yielding the values from the range regardless of what you do to no.

One way to solve your problem is to use a while loop and explicitly control the loop variable no yourself. A more "Pythonic" way is to use itertools to construct an infinite iterator that yields the numbers

0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8...

For example:

from itertools import chain, repeat

for no in chain(range(8), repeat(8)):
    print("No:", no)
```

Keep in mind that you will still need some way out of the infinite loop.

Title: Python: How do I modify iterator value after some condition in 'for' loop

Body:
In such a loop, if the variable no is equal to 8, how can I return the 8th loop again? I couldn't do it, I'm confused.

no -= 1 command not working

for no in range(0,100):
    print("No:",no)
    if no == 8:
      no -= 1
      print("8 done return again")

Body:
Modifying the variable no doesn't do what you want here, because Python's for no in range(...): loop gets the values for no from the range iterator. That iterator doesn't know about the variable no, and will keep yielding the values from the range regardless of what you do to no.

One way to solve your problem is to use a while loop and explicitly control the loop variable no yourself. A more "Pythonic" way is to use itertools to construct an infinite iterator that yields the numbers

0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8...

For example:

from itertools import chain, repeat

for no in chain(range(8), repeat(8)):
    print("No:", no)

Keep in mind that you will still need some way out of the infinite loop.


问:
How to get last access time of application in WebSphere Liberty Server 19.0.0.11
Am developing application in Java 8, JSF, Maven. Build application as war and deploying it in WebSphere Liberty Server 19.0.0.11. I got requirement to get application last access time.? Is there any way to get this detail.?</p>

答:
One way you could do that is by watching the vendor_servlet_request_total metric (provided by the mpMetrics-2.x feature).  There is a separately labeled time series for each servlet (a time series is a sequence of metric values in chronological order) -- by periodically polling the /metrics endpoint, and totalling the values across all servlets you would be able to tell when traffic has stopped.

10:17am

```<code>vendor_servlet_request_total{servlet=MyServletA} 100
vendor_servlet_request_total{servlet=MyServletB} 205
</code>```

10:18am

```<code>vendor_servlet_request_total{servlet=MyServletA} 102
vendor_servlet_request_total{servlet=MyServletB} 209
</code>```

10:19am

```<code>vendor_servlet_request_total{servlet=MyServletA} 102
vendor_servlet_request_total{servlet=MyServletB} 209
</code>```

In the example above, since the servlet request counts didn't change between 10:18am and 10:19am you can conclude that the last access was before 10:18am.

see https://openliberty.io/docs/ref/general/#metrics-catalog.html for more detail on the available metrics from mpMetrics-2.x.

Body:
One way you could do that is by watching the vendor_servlet_request_total metric (provided by the mpMetrics-2.x feature).  There is a separately labeled time series for each servlet (a time series is a sequence of metric values in chronological order) -- by periodically polling the /metrics endpoint, and totalling the values across all servlets you would be able to tell when traffic has stopped.

10:17am

vendor_servlet_request_total{servlet=MyServletA} 100
vendor_servlet_request_total{servlet=MyServletB} 205

10:18am

vendor_servlet_request_total{servlet=MyServletA} 102
vendor_servlet_request_total{servlet=MyServletB} 209

10:19am

vendor_servlet_request_total{servlet=MyServletA} 102
vendor_servlet_request_total{servlet=MyServletB} 209

In the example above, since the servlet request counts didn't change between 10:18am and 10:19am you can conclude that the last access was before 10:18am.

see https://openliberty.io/docs/ref/general/#metrics-catalog.html for more detail on the available metrics from mpMetrics-2.x.


问:
notifyDataSetChanged() is not working in MVP android
I have a refresh button which gets the updated list of items. Refresh button is on the fragment header on click of this I update the adapter.

Adapter code inside Fragment(FragmentView)

```<code> @Override
    public void setList(List<Entity> List, LangAdapter.OnlangClickedListener listener) {
        langAdapter = new LangAdapter(getContext(), langList, listener);

        rvLang.setLayoutManager(new LinearLayoutManager(getContext()));
        rvLang.addItemDecoration(new DividerItemDecoration(rvLang.getContext(), DividerItemDecoration.VERTICAL));
        rvLang.setAdapter(langAdapter);
        langAdapter.notifyDataSetChanged();

    }
</code>```

My code inside Fragment onClick inside Fragment(FragmentView)

```<code> presenter.onLanguageAutoRenewClicked();
</code>```

Inside Presenter this is the implementation

```<code>public void onLanguageAutoRenewClicked() {

// Retrofit call
onResponseSuccess() {

                   FragmentView.reloadData();
}

}
</code>```

and from here inside my FragmentView I have reloadData

```<code> @Override
    public void reloadData() {

               langAdapter.notifyDataSetChanged();

    }
</code>```

I am calling a WS on click of button which is giving me the new list items which I am calling reloadData and on the fragment class I am setting notifyDataSetChanged but still I am not able to update the items in the adapter.

答:
According to your comment:

list is updated but how to pass the updated list to adapter since we can not create the new adapter – Vish

I think your problem is the list that passed to the adapter. To call notify's methods, you should update the list that passed to the adapter.

You can implement your adapter like below with DiffUtil to increase the simplicity of the manipulation.

This code developed by Kotlin language. If you need it with Java, I can rewrite it for you :)

With DiffUtil you don't need to call notifyDataSetChanged() or other notify methods anymore.

```<code>class FooRvAdapter(
    private val dataList: ArrayList<Fee>
      ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    fun updateItems(newDataList: List<Fee>) {
        val diffCallback = FooRvAdapterDiffCallback(dataList, newDataList)
        val diffResult = DiffUtil.calculateDiff(diffCallback, false)
        dataList.clear()
        dataList.addAll(newDataList)
        diffResult.dispatchUpdatesTo(this@FooRvAdapter)
    }

     /*
      OnBind(),ViewHolder, etc.
      ...
     */

    inner class FooRvAdapterDiffCallback(
        private val oldList: List<Fee>,
        private val newList: List<Fee>
    ) : DiffUtil.Callback() {

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
            newList[newItemPosition].id == oldList[oldItemPosition].id

        override fun getOldListSize() = oldList.size

        override fun getNewListSize() = newList.size

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
            newList[newItemPosition] == oldList[oldItemPosition]
    }

    interface FooCallBack {
        fun onItemClick(data: Fee)
    }
}

</code>```

Body:
I have a refresh button which gets the updated list of items. Refresh button is on the fragment header on click of this I update the adapter.

Adapter code inside Fragment(FragmentView)

 @Override
    public void setList(List<Entity> List, LangAdapter.OnlangClickedListener listener) {
        langAdapter = new LangAdapter(getContext(), langList, listener);

        rvLang.setLayoutManager(new LinearLayoutManager(getContext()));
        rvLang.addItemDecoration(new DividerItemDecoration(rvLang.getContext(), DividerItemDecoration.VERTICAL));
        rvLang.setAdapter(langAdapter);
        langAdapter.notifyDataSetChanged();

    }

My code inside Fragment onClick inside Fragment(FragmentView)

 presenter.onLanguageAutoRenewClicked();

Inside Presenter this is the implementation

public void onLanguageAutoRenewClicked() {

// Retrofit call
onResponseSuccess() {

                   FragmentView.reloadData();
}

}

and from here inside my FragmentView I have reloadData

 @Override
    public void reloadData() {

               langAdapter.notifyDataSetChanged();

    }

I am calling a WS on click of button which is giving me the new list items which I am calling reloadData and on the fragment class I am setting notifyDataSetChanged but still I am not able to update the items in the adapter.

Body:
According to your comment:

list is updated but how to pass the updated list to adapter since we can not create the new adapter – Vish

I think your problem is the list that passed to the adapter. To call notify's methods, you should update the list that passed to the adapter.

You can implement your adapter like below with DiffUtil to increase the simplicity of the manipulation.

This code developed by Kotlin language. If you need it with Java, I can rewrite it for you :)

With DiffUtil you don't need to call notifyDataSetChanged() or other notify methods anymore.

class FooRvAdapter(
    private val dataList: ArrayList<Fee>
      ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    fun updateItems(newDataList: List<Fee>) {
        val diffCallback = FooRvAdapterDiffCallback(dataList, newDataList)
        val diffResult = DiffUtil.calculateDiff(diffCallback, false)
        dataList.clear()
        dataList.addAll(newDataList)
        diffResult.dispatchUpdatesTo(this@FooRvAdapter)
    }

     /*
      OnBind(),ViewHolder, etc.
      ...
     */

    inner class FooRvAdapterDiffCallback(
        private val oldList: List<Fee>,
        private val newList: List<Fee>
    ) : DiffUtil.Callback() {

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
            newList[newItemPosition].id == oldList[oldItemPosition].id

        override fun getOldListSize() = oldList.size

        override fun getNewListSize() = newList.size

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
            newList[newItemPosition] == oldList[oldItemPosition]
    }

    interface FooCallBack {
        fun onItemClick(data: Fee)
    }
}


问:
Regex comma separated sub string within a string
I need to get key value pair from string using regex.

String is something like

```<code>country=xxx,state=yyy,city=zzz,
</code>```

then this regex

```<code>([^,=]+?)(=)([^,=]+?),
</code>```

gives me 3 different key value pairs but if I have multiple comma separated values then only first is selected.

For e.g.

```<code>country=xxx,state=yyy,city=zzz,pqr,
</code>```

then for city pqr is dropped. I want to have both zzz,pqr for the city.

答:
Well then you can't put a comma in those to-be-avoided chars, can you?

```<code>([^,=]+)(=)([^=]+),
</code>```

Body:
I need to get key value pair from string using regex.

String is something like

country=xxx,state=yyy,city=zzz,

then this regex

([^,=]+?)(=)([^,=]+?),

gives me 3 different key value pairs but if I have multiple comma separated values then only first is selected.

For e.g.

country=xxx,state=yyy,city=zzz,pqr,

then for city pqr is dropped. I want to have both zzz,pqr for the city.

Body:
Well then you can't put a comma in those to-be-avoided chars, can you?

([^,=]+)(=)([^=]+),


问:
How to get local JSON (fetch)?
How to get local JSON (fetch)?

I do a service, then I call the class instance

This is not how it works:

Services.js

```<code>export default class ApiService {
    async GetPeople() {
        const request = await fetch('./data.json');
        if(!request.ok) {
            throw new Error('Что-то пошло не так', request.status)
        } else {
            return request.json()
        };
    };
};
</code>```

Userslist.js

```<code>import Service from '../../../Services';

const UsersListContainer = () => {

    const api = new Service();

    useEffect(() => {
        api.GetPeople()
        .then(data => console.log(data))
    }, [api])

    return (
        <UsersListView />
    );
};

export default UsersListContainer;
</code>```

答:
As Jai correctly said: You need to await the .json() method.
See: https://gist.github.com/msmfsd/fca50ab095b795eb39739e8c4357a808#gistcomment-2198304

Secondly I want to give you a recommendation:
export the ApiService as an singleton instance directly. Don't initialize the ApiService class inside your component and don't put the api as dependency in useEffect.

Reason: You ApiService class doesn't have any reason to create a instance anytime your UserListContainer gets mounted.

Title: How to get local JSON (fetch)?

Body:
How to get local JSON (fetch)?

I do a service, then I call the class instance

This is not how it works:

Services.js

export default class ApiService {
    async GetPeople() {
        const request = await fetch('./data.json');
        if(!request.ok) {
            throw new Error('Что-то пошло не так', request.status)
        } else {
            return request.json()
        };
    };
};

Userslist.js

import Service from '../../../Services';

const UsersListContainer = () => {

    const api = new Service();

    useEffect(() => {
        api.GetPeople()
        .then(data => console.log(data))
    }, [api])

    return (
        <UsersListView />
    );
};

export default UsersListContainer;