问:
Delete all documents in a collection with Springdata mongo Query
I want to implement a delete method which deletes all the documents in a collection. I am using mongo db with Spring Data.This could be done using db.myCollection.remove({}) in Mongo shell. But I want to write a method in my data access layer to do this.I am not using MongodbTemplate in my Dao class. I want to know how can I do this with Query.

```<code>Query query = new Query();
</code>```

Could anybody please tell me how can I do it.

答:
You can use MongoTemplate directly

mongoTemplate.remove(new Query(), collectionName);
```

Body:
I want to implement a delete method which deletes all the documents in a collection. I am using mongo db with Spring Data.This could be done using db.myCollection.remove({}) in Mongo shell. But I want to write a method in my data access layer to do this.I am not using MongodbTemplate in my Dao class. I want to know how can I do this with Query.

Query query = new Query();

Could anybody please tell me how can I do it.


来源: stackexchange

问:
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81
I am currently new to robot framework.I am currently using latest window version of chrome and chromedriver which is 80 but when i try to run the test it gives the message "SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81" in pycharm but currently beta version of 81 is only available. I have tried uninstalling everthing and reinstalling it again but nothing works can anyone help me with this.Thank you!

Screenshots below:

答:
Go to your Chrome settings -> About Chrome -> Check version
and download chromedriver from Below according to your Chrome version
https://chromedriver.chromium.org/downloads</p>

ContentLicense: CC BY-SA 4.0


问:
Multiple axios requests with vue.js and Airtable
I build a working code to retrieve data from fake Airtable database with axios. You can see the code below perfectly working. No problem to retrieve data when is on the main table. Yet as you can assume some fields are connected to other tables (named in Airtable: parent child data or fields). Is the case in my table when you have the field "ORGANIZZAZIONE" (Organization) that is connected to another table having the organization datails as for example: NOME (Name) and TIPOLOGIA (Activity).
As you can see in the code when I try to access to this data (ORGANIZZAZIONE) I have bad results. Probably I have to build an "axios.all" request but I can't find the right way.

```<code>enter code here
</code>```

           new Vue({
                el: '#app',
                data: {
                  saluti:'Saluti da Mauro',
                    items: []
                },
                mounted: function(){
                   this.loadItems();
                },
                methods: {
                    loadItems: function(){

                        // Init variables
                        var self = this
                        var app_id = "apppCqmyJHPmfDTLr";
                        var app_key = "key8S2tx7NINXaZzZ";
                        this.items = []
axios.get(
  "https://api.airtable.com/v0/"+app_id+"/DASHBOARD?api_key="+app_key,

                            {
                                headers: { Authorization: "Bearer "+app_key }
                            }
                        ).then(function(response){
                            self.items = response.data.records
                        }).catch(function(error){
                            console.log(error)
                        })
                    }
                }
            })
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <head>
      <title>Airtable example</title>
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    </head>
    <body>
      <h1>AIT</h1>
      <p>All work from <strong>Ryan Hayden</strong> | A basic introduction to the Airtable API.</p>
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

<div id="app">
            <h2>{{saluti}}</h2>
  <div class="container-fluid">

        <div class="card-body" v-for="item, index in items" :key:="items">
          <img src="https://www.artemedialab.it/wp-content/uploads/2019/04/immagini-sfondo-1-700x400.jpg" class="card-img-top" class="img-fluid" alt="MM" style="width: 18rem;">

              <div class="card text-BLACK bg-primary mb-3 text-right" style="width: 18rem;">
                <div class="card-header">

                    {{ index+1 }}
                </div>

                            <div class="card text-black bg-success mb-3" style="max-width: 18rem;">
                             <div class="card border-primary mb-1" style="max-width: 18rem;">
     <!-- lavorare su questo per approfondire la struttura su JSON
this.posts = response.data.data.map((post) => {
        return {id: post.id, title: post.attributes.title, body: post.attributes.body};
      }) -->

                    <p class="price"><strong>DATA INIZIO: </strong>{{ item['fields']['DATA INIZIO'] }}</p>
                     <p class="category"><strong>DETTAGLI ATTIVITA': </strong>{{ item['fields']["Attivita'"] }}</p>
                    <p class="category"><strong>PRIORITA': </strong>{{ item['fields']["PRIORITA'"] }}</p>
                               <p class="category"><strong>ORGANIZZAZIONE: </strong>{{ item['fields']['ORGANIZZAZIONE']}}</p>
                                <p class="category"><strong>ORGANIZZAZIONE / NOME: </strong>{{ item['fields']['ORGANIZZAZIONE']['Nome_Organizzazione']}}</p>
                               <p class="category"><strong>ORGANIZZAZIONE / TIPOLOGIA: </strong>{{ item['fields']['ORGANIZZAZIONE']['TIPOLOGIA']}}</p>
                    <img :src="item['fields']['Photo'][0]['thumbnails']['large']['url']" alt="" v-if="item['fields']['Photo']" width="150">

    </div>
    </div>
   </div>

    </div>

    <!--app-->

        <!-- Include Dependancy Scripts -->
        <script type="text/javascript" src="https://unpkg.com/vue"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>

    </body></code>```

答:
I got one blog regarding this issue. please check.
https://www.storyblok.com/tp/how-to-send-multiple-requests-using-axios</p>

Body:
I build a working code to retrieve data from fake Airtable database with axios. You can see the code below perfectly working. No problem to retrieve data when is on the main table. Yet as you can assume some fields are connected to other tables (named in Airtable: parent child data or fields). Is the case in my table when you have the field "ORGANIZZAZIONE" (Organization) that is connected to another table having the organization datails as for example: NOME (Name) and TIPOLOGIA (Activity).
As you can see in the code when I try to access to this data (ORGANIZZAZIONE) I have bad results. Probably I have to build an "axios.all" request but I can't find the right way.

enter code here

           new Vue({
                el: '#app',
                data: {
                  saluti:'Saluti da Mauro',
                    items: []
                },
                mounted: function(){
                   this.loadItems();
                },
                methods: {
                    loadItems: function(){

                        // Init variables
                        var self = this
                        var app_id = "apppCqmyJHPmfDTLr";
                        var app_key = "key8S2tx7NINXaZzZ";
                        this.items = []
axios.get(
  "https://api.airtable.com/v0/"+app_id+"/DASHBOARD?api_key="+app_key,

                            {
                                headers: { Authorization: "Bearer "+app_key }
                            }
                        ).then(function(response){
                            self.items = response.data.records
                        }).catch(function(error){
                            console.log(error)
                        })
                    }
                }
            })

      <title>Airtable example</title>
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

AIT

All work from Ryan Hayden | A basic introduction to the Airtable API.

      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

{{saluti}}

                    {{ index+1 }}

DATA INIZIO: {{ item['fields']['DATA INIZIO'] }}

DETTAGLI ATTIVITA': {{ item['fields']["Attivita'"] }}

PRIORITA': {{ item['fields']["PRIORITA'"] }}

ORGANIZZAZIONE: {{ item['fields']['ORGANIZZAZIONE']}}

ORGANIZZAZIONE / NOME: {{ item['fields']['ORGANIZZAZIONE']['Nome_Organizzazione']}}

ORGANIZZAZIONE / TIPOLOGIA: {{ item['fields']['ORGANIZZAZIONE']['TIPOLOGIA']}}


问:
Pass complex object between action methods ASP.Net MVC Core
I studied most of the similar questions but couldn't find the answer!
Let me declare that I can define a simple TempData like an string,int and get it in another action method successfully, but

I have 3 parameters/variable in ActionMethod1 which is named "ExternalLoginCallBack", and need to ask a "UserName" from user on client side and then save the total 4 parameters in ActionMethod2 which is named "CreateExternalUser".
This is what I have.
AskUserNameView_NoActionMethod.cshtml as below:

```<code>@model ExternalUserViewModel

<form asp-action="CreateExternalUser" asp-controller="Account" method="post">
        <label asp-for="UserName">Input your UserName Here: </label>
        <input asp-for="UserName" >
        <input  type="submit" value="ُSubmit"/>
</form>
</code>```

(Using TempData) Attemp-No.1:

```<code>public async Task<IActionResult> ActionMethod1

//some codes here

var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();
TempData["externalLoginInfo"] = externalLoginInfo;
TempData["email"] = email;
TempData["returnUrl"] = returnUrl;

return View("AskUserNameView_NoActionMethod");
</code>```

but instead of showing the AskUserNameView_NoActionMethod.cshtml it shows just a white page with no errors,no exception and nothing :

Attemp-No2: I removed  "ExternalLoginInfo" type and only two simple string as an object remained to pass to ActionMethod2:

```<code>public async Task<IActionResult> ActionMethod1

//some codes here

var externalUserViewModel= new ExternalUserViewModel()
{
Email = email,
ReturnUrl = returnUrl,
};

TempData["externalUserViewModel"] = externalUserViewModel;

return View("AskUserNameView_NoActionMethod");
</code>```

but again the white page above appeared. When I remove the complex TempData, my AskUserNameView_NoActionMethod.cshtml rendered successfully, and I can pass UserName which is entered by client side, to ActionMethod2. But without 3 other parameters which is needed to create a new External user !!

My ExternalUserViewModel is as below:

```<code> public class ExternalUserViewModel
{
    public ExternalLoginInfo ExternalLoginInfo { get; set; }
    public string Email { get; set; }

    public string UserName { get; set; }
    public string ReturnUrl { get; set; }
}
</code>```

and already added these codes to startup.cs:

```<code>services.AddControllersWithViews();
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();

app.UseSession();
</code>```

If TempData is not apllicable, I tried to pass my model with 3 parameters (Email,ReturnUrl,ExternalLoginInfo  ) to strongly typed AskUserNameView_NoActionMethod.cshtml, but again Username entered by client side,Email and returnedUrl passed to ActionMethod2 but externalLoginInfo  was null .

Summary: need an example to pass a complex data/object from actionmethod1 to actionmethod2 , without redirect to actionmethod2 !!

答:
You have two methods to achieve it.

As the TempData cannot store complex object here ,you can Serialize the object to json string and store it in TempData, then you can get the json string in CreateExternalUser action and Deserialize this json string to the correspond object as follow:

```<code>    public async Task<IActionResult> ActionMethod1()
    {

        //some codes here
        var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();
        TempData["externalLoginInfo"] = JsonConvert.SerializeObject(externalLoginInfo);
        TempData["email"] = email;
        TempData["returnUrl"] = returnUrl;

        return View("AskUserNameView_NoActionMethod");

    }
</code>```

Receive:

```<code>public async Task<IActionResult> CreateExternalUser(UserName  userName)
        {
            //some codes here
            var externalLoginInfo = JsonConvert.DeserializeObject<ExternalLoginInfo>(TempData["externalLoginInfo"].ToString());

           var email = TempData["email"] as string;
            var returnUrl = TempData["returnUrl"] as string;

            return View();
        }
</code>```

Another method is to create a custom method named TempDataExtensions to pass object from an action to another.

```<code>public static class TempDataExtensions
{
    public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
    {
        tempData[key] = JsonConvert.SerializeObject(value);
    }

    public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
    {
        object o;
        tempData.TryGetValue(key, out o);
        return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
    }
}
</code>```

Store object:

```<code>var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();
TempData.Put("externalLoginInfo", externalLoginInfo);
</code>```

Get object:

```<code>var externalLoginInfo = TempData.Get<ExternalLoginInfo>("externalLoginInfo");
</code>```

Body:
I studied most of the similar questions but couldn't find the answer!
Let me declare that I can define a simple TempData like an string,int and get it in another action method successfully, but

I have 3 parameters/variable in ActionMethod1 which is named "ExternalLoginCallBack", and need to ask a "UserName" from user on client side and then save the total 4 parameters in ActionMethod2 which is named "CreateExternalUser".
This is what I have.
AskUserNameView_NoActionMethod.cshtml as below:

@model ExternalUserViewModel

<form asp-action="CreateExternalUser" asp-controller="Account" method="post">
        Input your UserName Here:
        <input asp-for="UserName" >
        <input  type="submit" value="ُSubmit"/>
</form>

(Using TempData) Attemp-No.1:

public async Task<IActionResult> ActionMethod1

//some codes here

var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();
TempData["externalLoginInfo"] = externalLoginInfo;
TempData["email"] = email;
TempData["returnUrl"] = returnUrl;

return View("AskUserNameView_NoActionMethod");

but instead of showing the AskUserNameView_NoActionMethod.cshtml it shows just a white page with no errors,no exception and nothing :

Attemp-No2: I removed  "ExternalLoginInfo" type and only two simple string as an object remained to pass to ActionMethod2:

public async Task<IActionResult> ActionMethod1

//some codes here

var externalUserViewModel= new ExternalUserViewModel()
{
Email = email,
ReturnUrl = returnUrl,
};

TempData["externalUserViewModel"] = externalUserViewModel;

return View("AskUserNameView_NoActionMethod");

but again the white page above appeared. When I remove the complex TempData, my AskUserNameView_NoActionMethod.cshtml rendered successfully, and I can pass UserName which is entered by client side, to ActionMethod2. But without 3 other parameters which is needed to create a new External user !!

My ExternalUserViewModel is as below:

 public class ExternalUserViewModel
{
    public ExternalLoginInfo ExternalLoginInfo { get; set; }
    public string Email { get; set; }

    public string UserName { get; set; }
    public string ReturnUrl { get; set; }
}

and already added these codes to startup.cs:

services.AddControllersWithViews();
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();

app.UseSession();

If TempData is not apllicable, I tried to pass my model with 3 parameters (Email,ReturnUrl,ExternalLoginInfo  ) to strongly typed AskUserNameView_NoActionMethod.cshtml, but again Username entered by client side,Email and returnedUrl passed to ActionMethod2 but externalLoginInfo  was null .

Summary: need an example to pass a complex data/object from actionmethod1 to actionmethod2 , without redirect to actionmethod2 !!

Body:
You have two methods to achieve it.

As the TempData cannot store complex object here ,you can Serialize the object to json string and store it in TempData, then you can get the json string in CreateExternalUser action and Deserialize this json string to the correspond object as follow:

    public async Task<IActionResult> ActionMethod1()
    {

        //some codes here
        var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();
        TempData["externalLoginInfo"] = JsonConvert.SerializeObject(externalLoginInfo);
        TempData["email"] = email;
        TempData["returnUrl"] = returnUrl;

        return View("AskUserNameView_NoActionMethod");

    }

Receive:

public async Task<IActionResult> CreateExternalUser(UserName  userName)
        {
            //some codes here
            var externalLoginInfo = JsonConvert.DeserializeObject<ExternalLoginInfo>(TempData["externalLoginInfo"].ToString());

           var email = TempData["email"] as string;
            var returnUrl = TempData["returnUrl"] as string;

            return View();
        }

Another method is to create a custom method named TempDataExtensions to pass object from an action to another.

public static class TempDataExtensions
{
    public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
    {
        tempData[key] = JsonConvert.SerializeObject(value);
    }

    public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
    {
        object o;
        tempData.TryGetValue(key, out o);
        return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
    }
}

Store object:

var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();
TempData.Put("externalLoginInfo", externalLoginInfo);

Get object:

var externalLoginInfo = TempData.Get<ExternalLoginInfo>("externalLoginInfo");


问:
BeautifulSoup-tag returns none ,while there are elements in it
Trying to scrape the below website.Upon,extracting href from a-tags,it returns none.But,there are elements in those a tags.Here is the code:

```<code>from selenium import webdriver
import time
from bs4 import BeautifulSoup

driver = webdriver.Chrome(r"E:\chromedriver_win32\chromedriver.exe")
url= "https://www.adb.org/projects/tenders/sector/information-and-communication-technology-1066"
driver.get(url)

content = driver.page_source.encode('utf-8').strip()
soup = BeautifulSoup(content,"html.parser")
div_tags = soup.findAll("div",{"class":"item-title"})
for tags in div_tags:
    a_tag=tags.find('a')
    link=a_tag.get('href')
    print(link)
</code>```

div_tags-output printed:

```<code>[<div class="item-title">
<a href="/node/606921"><div class="item-title">Corporate Innovation Expert</div></a></div>, <div class="item-title">Corporate Innovation Expert</div>, <div class="item-title">
<a href="/node/605571"><div class="item-title">Communications Specialist</div></a></div>, <div class="item-title">Communications Specialist</div>, <div class="item-title">
<a href="/node/603231"><div class="item-title">Venture Partner Expert</div></a></div>, <div class="item-title">Venture Partner Expert</div>, <div class="item-title">
<a href="/node/457636"><div class="item-title">Partnerships & Communications Manager</div></a></div>, <div class="item-title">Partnerships & Communications Manager</div>, <div class="item-title">
<a href="/node/545151"><div class="item-title">Operations Associate</div></a></div>, <div class="item-title">Operations Associate</div>, <div class="item-title">
</code>```

答:
Here is the code:

```<code>from requests import get
import time
from bs4 import BeautifulSoup

response = get('https://www.adb.org/projects/tenders/sector/information-and-communication-technology-1066')
soup = BeautifulSoup(response.text, 'html.parser')

div_tags = soup.findAll("div",class_="item-title")
link={}
for tags in div_tags:
    a_tag=tags.find('a')
    try:
      link[a_tag.text]= "https://www.adb.org"+a_tag.get('href')
    except:
      continue
#print(link)# print all text and value as dict
for x, y in link.items():
  print(x, y) # x print text y print link
</code>```

If you want text and links as a dictionary, use print(link).
If you want text, use print(x) in for loop.
If you want links, use print(y) in for loop.

Run Online:https://repl.it/repls/ScaredCommonParallelcomputing

Body:
Trying to scrape the below website.Upon,extracting href from a-tags,it returns none.But,there are elements in those a tags.Here is the code:

from selenium import webdriver
import time
from bs4 import BeautifulSoup

driver = webdriver.Chrome(r"E:\chromedriver_win32\chromedriver.exe")
url= "https://www.adb.org/projects/tenders/sector/information-and-communication-technology-1066"
driver.get(url)

content = driver.page_source.encode('utf-8').strip()
soup = BeautifulSoup(content,"html.parser")
div_tags = soup.findAll("div",{"class":"item-title"})
for tags in div_tags:
    a_tag=tags.find('a')
    link=a_tag.get('href')
    print(link)

div_tags-output printed:

[

Corporate Innovation Expert

,
Corporate Innovation Expert
,

Communications Specialist

,
Communications Specialist
,

Venture Partner Expert

,
Venture Partner Expert
,

Partnerships & Communications Manager

,
Partnerships & Communications Manager
,

Operations Associate

,
Operations Associate
,

Body:
Here is the code:

from requests import get
import time
from bs4 import BeautifulSoup

response = get('https://www.adb.org/projects/tenders/sector/information-and-communication-technology-1066')
soup = BeautifulSoup(response.text, 'html.parser')

div_tags = soup.findAll("div",class_="item-title")
link={}
for tags in div_tags:
    a_tag=tags.find('a')
    try:
      link[a_tag.text]= "https://www.adb.org"+a_tag.get('href')
    except:
      continue
#print(link)# print all text and value as dict
for x, y in link.items():
  print(x, y) # x print text y print link

If you want text and links as a dictionary, use print(link).
If you want text, use print(x) in for loop.
If you want links, use print(y) in for loop.

Run Online:https://repl.it/repls/ScaredCommonParallelcomputing


问:
How to prevent the form data in html form wizard
I am using html form wizard for registration .If the form refreshes while registration it is going to first step again.I need to display same step .I have tried the below code.

```<code><!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<style>
* {
  box-sizing: border-box;
}

body {
  background-color: #f1f1f1;
}

#regForm {
  background-color: #ffffff;
  margin: 100px auto;
  font-family: Raleway;
  padding: 40px;
  width: 70%;
  min-width: 300px;
}

h1 {
  text-align: center;
}

input {
  padding: 10px;
  width: 100%;
  font-size: 17px;
  font-family: Raleway;
  border: 1px solid #aaaaaa;
}

/* Mark input boxes that gets an error on validation: */
input.invalid {
  background-color: #ffdddd;
}

/* Hide all steps by default: */
.tab {
  display: none;
}

button {
  background-color: #4CAF50;
  color: #ffffff;
  border: none;
  padding: 10px 20px;
  font-size: 17px;
  font-family: Raleway;
  cursor: pointer;
}

button:hover {
  opacity: 0.8;
}

#prevBtn {
  background-color: #bbbbbb;
}

/* Make circles that indicate the steps of the form: */
.step {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbbbbb;
  border: none;
  border-radius: 50%;
  display: inline-block;
  opacity: 0.5;
}

.step.active {
  opacity: 1;
}

/* Mark the steps that are finished and valid: */
.step.finish {
  background-color: #4CAF50;
}
</style>
<body>

<form id="regForm" action="/action_page.php">
  <h1>Register:</h1>
  <!-- One "tab" for each step in the form: -->
  <div class="tab">Name:
    <p><input placeholder="First name..." oninput="this.className = ''" name="fname"></p>
    <p><input placeholder="Last name..." oninput="this.className = ''" name="lname"></p>
  </div>
  <div class="tab">Contact Info:
    <p><input placeholder="E-mail..." oninput="this.className = ''" name="email"></p>
    <p><input placeholder="Phone..." oninput="this.className = ''" name="phone"></p>
  </div>
  <div class="tab">Birthday:
    <p><input placeholder="dd" oninput="this.className = ''" name="dd"></p>
    <p><input placeholder="mm" oninput="this.className = ''" name="nn"></p>
    <p><input placeholder="yyyy" oninput="this.className = ''" name="yyyy"></p>
  </div>
  <div class="tab">Login Info:
    <p><input placeholder="Username..." oninput="this.className = ''" name="uname"></p>
    <p><input placeholder="Password..." oninput="this.className = ''" name="pword" type="password"></p>
  </div>
  <div style="overflow:auto;">
    <div style="float:right;">
      <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
      <button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
    </div>
  </div>
  <!-- Circles which indicates the steps of the form: -->
  <div style="text-align:center;margin-top:40px;">
    <span class="step"></span>
    <span class="step"></span>
    <span class="step"></span>
    <span class="step"></span>
  </div>
</form>

<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
  //... and fix the Previous/Next buttons:
  if (n == 0) {
    document.getElementById("prevBtn").style.display = "none";
  } else {
    document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (x.length - 1)) {
    document.getElementById("nextBtn").innerHTML = "Submit";
  } else {
    document.getElementById("nextBtn").innerHTML = "Next";
  }
  //... and run a function that will display the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab");
  // Exit the function if any field in the current tab is invalid:
  if (n == 1 && !validateForm()) return false;
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form...
  if (currentTab >= x.length) {
    // ... the form gets submitted:
    document.getElementById("regForm").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);
}

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class on the current step:
  x[n].className += " active";
}
</script>

</body>
</html>
</code>```

I need to add 7-8 steps .If The form refreshes in 5th step user need to add data from the first step.
I am inserting data in final step in data base .It should display same step even after refreshing .

答: Save the data and step in the local storage and use them.</p>

Body:
I am using html form wizard for registration .If the form refreshes while registration it is going to first step again.I need to display same step .I have tried the below code.

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">

<form id="regForm" action="/action_page.php">

Register:

Name:

<input placeholder="First name..." oninput="this.className = ''" name="fname">

<input placeholder="Last name..." oninput="this.className = ''" name="lname">

Contact Info:

<input placeholder="E-mail..." oninput="this.className = ''" name="email">

<input placeholder="Phone..." oninput="this.className = ''" name="phone">

Birthday:

<input placeholder="dd" oninput="this.className = ''" name="dd">

<input placeholder="mm" oninput="this.className = ''" name="nn">

<input placeholder="yyyy" oninput="this.className = ''" name="yyyy">

Login Info:

<input placeholder="Username..." oninput="this.className = ''" name="uname">

<input placeholder="Password..." oninput="this.className = ''" name="pword" type="password">

      <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
      <button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>

</form>

I need to add 7-8 steps .If The form refreshes in 5th step user need to add data from the first step.
I am inserting data in final step in data base .It should display same step even after refreshing .


问:
How can i trim spaces in object.values?
my object.values(article.data) returns

```<code>[' This is ']
['is ']
['a']
['sentence ']
</code>```

how can i trim and remove the spaces so it becomes

```<code>['Thisis']
['is']
['a']
['sentence']
</code>```

答:
Presuming you want to update the object, you need to iterate over the object entries and assign the updated values to each of the object keys. Since your object values are arrays, you need to iterate over each of the values within those arrays, replacing all spaces in them with an empty string.

let obj = {
  'k1': [' This is '],
  'k2': ['is '],
  'k3': ['a'],
  'k4': ['sentence ']
}

for (let [key, value] of Object.entries(obj)) {
  obj[key] = value.map(v => v.replace(/\s+/g, ''));
}

console.log(obj);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: How can i trim spaces in object.values?

Body:
my object.values(article.data) returns

[' This is ']
['is ']
['a']
['sentence ']

how can i trim and remove the spaces so it becomes

['Thisis']
['is']
['a']
['sentence']

Body:
Presuming you want to update the object, you need to iterate over the object entries and assign the updated values to each of the object keys. Since your object values are arrays, you need to iterate over each of the values within those arrays, replacing all spaces in them with an empty string.

let obj = {
  'k1': [' This is '],
  'k2': ['is '],
  'k3': ['a'],
  'k4': ['sentence ']
}

for (let [key, value] of Object.entries(obj)) {
  obj[key] = value.map(v => v.replace(/\s+/g, ''));
}

console.log(obj);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Save values global in NodeRED
We are working with MQTT messages, process these messages and call a REST service to send the information to another system.

Now we need to save some values from the MQTT message to compare these values with other messages. Is it possible to create an array that is outside the workflow that can be accessed from other workflows? Currently we are saving the values to a file but this is not the way we want to do it.

答:
Try node-red-contrib-state it persists state across node-red restarts, and has a few other tools for state management.

mqtt is also good for saving state if you have access to an mqtt broker.

Title: Save values global in NodeRED


问:
Pasting a data on a new Google tab
I am new in programming (specifically Python Selenium), I have a question regarding pasting a data into an input box, it seems not working if I will paste data on another website, I will received an error. But if I use just one website (either of the two) in pasting the data it is working fine.

Here is my codes below.

```<code>from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\Users\Pashu\AppData\Local\Programs\Python\Python37\chromedriver.exe')

driver.get('https://tinyurl.com/')

inline_tinysite = driver.find_element_by_xpath('//*[@id="url"]')
inline_tinysite.send_keys("https://www.teamxtools.com/content/images/project-7/stack-324/exif/2dehands-velgen-volkswagen-golf-7.jpg")
submit = driver.find_element_by_xpath('/html/body/div[2]/div[2]/div[2]/div[2]/div[2]/form/input[3]')
submit.click()

driver.execute_script("window.open('https://cutt.ly/', 'new window')")
inline_cuttly = driver.find_element_by_xpath('//*[@id="link"]')
inline_cuttly.send_keys("https://www.teamxtools.com/content/images/project-7/stack-324/exif/2dehands-velgen-volkswagen-golf-7.jpg")
submit2 = driver.find_element_by_xpath('/html/body/div[1]/section[1]/div/div/div/div/div/button')
submit2.click()
#time.sleep(8)
</code>```

Here is the error message as text:

```<code>C:\Users\Pashu\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Pashu/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Helloworld.py
Traceback (most recent call last):
  File "C:/Users/Pashu/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Helloworld.py", line 14, in <module>
    inline_cuttly = driver.find_element_by_xpath('//*[@id="link"]')
  File "C:\Users\Pashu\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\Pashu\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\Pashu\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Pashu\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="link"]"}
  (Session info: chrome=81.0.4044.138)

Process finished with exit code 1
</code>```

答:
it was stuck on window 1, that is why element //*[@id="link"] is not found. I just added

```<code>driver.switch_to.window(driver.window_handles[1])
</code>```

for it to search on the second window.

Title: Pasting a data on a new Google tab

Body:
I am new in programming (specifically Python Selenium), I have a question regarding pasting a data into an input box, it seems not working if I will paste data on another website, I will received an error. But if I use just one website (either of the two) in pasting the data it is working fine.

Here is my codes below.

from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\Users\Pashu\AppData\Local\Programs\Python\Python37\chromedriver.exe')

driver.get('https://tinyurl.com/')

inline_tinysite = driver.find_element_by_xpath('//*[@id="url"]')
inline_tinysite.send_keys("https://www.teamxtools.com/content/images/project-7/stack-324/exif/2dehands-velgen-volkswagen-golf-7.jpg")
submit = driver.find_element_by_xpath('/html/body/div[2]/div[2]/div[2]/div[2]/div[2]/form/input[3]')
submit.click()

driver.execute_script("window.open('https://cutt.ly/', 'new window')")
inline_cuttly = driver.find_element_by_xpath('//*[@id="link"]')
inline_cuttly.send_keys("https://www.teamxtools.com/content/images/project-7/stack-324/exif/2dehands-velgen-volkswagen-golf-7.jpg")
submit2 = driver.find_element_by_xpath('/html/body/div[1]/section[1]/div/div/div/div/div/button')
submit2.click()
#time.sleep(8)

Here is the error message as text:

C:\Users\Pashu\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Pashu/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Helloworld.py
Traceback (most recent call last):
  File "C:/Users/Pashu/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Helloworld.py", line 14, in <module>
    inline_cuttly = driver.find_element_by_xpath('//*[@id="link"]')
  File "C:\Users\Pashu\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\Pashu\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\Pashu\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Pashu\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="link"]"}
  (Session info: chrome=81.0.4044.138)

Process finished with exit code 1

Body:
it was stuck on window 1, that is why element //*[@id="link"] is not found. I just added

driver.switch_to.window(driver.window_handles[1])

for it to search on the second window.


问:
Why can't an inherited protected constructor be made public?
Consider:

```<code>class A
{
protected:
    A(int) {}
    void f(int) {}

public:
    A() {}
};

class B : public A
{
public:
    using A::A;
    using A::f;
};

int main()
{
    B().f(1); // ok
    B(1); // error: 'A::A(int)' is protected within this context
}
</code>```

Why can't an inherited protected constructor be made public, while an inherited protected member function can?

答:
Actually, the inherited constructor can be made public, but not just the way you wrote it. You can define your B class as follows:

```<code>class B : public A {
public:
    B() {}

    B(int x) : A(x) {}  // instead of using A::A(int)
    using A::f;
};
</code>```

(see it on GodBolt)

Perhaps the standard committee thought that saying using A::A would be a bit ambiguous, since a constructor of the base class is not exactly the same thing as a constructor of the subclass.

Body:
Consider:

class A
{
protected:
    A(int) {}
    void f(int) {}

public:
    A() {}
};

class B : public A
{
public:
    using A::A;
    using A::f;
};

int main()
{
    B().f(1); // ok
    B(1); // error: 'A::A(int)' is protected within this context
}

Why can't an inherited protected constructor be made public, while an inherited protected member function can?

Body:
Actually, the inherited constructor can be made public, but not just the way you wrote it. You can define your B class as follows:

class B : public A {
public:
    B() {}

    B(int x) : A(x) {}  // instead of using A::A(int)
    using A::f;
};

(see it on GodBolt)

Perhaps the standard committee thought that saying using A::A would be a bit ambiguous, since a constructor of the base class is not exactly the same thing as a constructor of the subclass.


问:
uhttpd rewrite all routes to /
I am trying to set up a react app using react router behind a uhttpd server on an embedded device. Unfortunately I do not know how to forward all subroutes (eg. /foo/bar) back to /

In nginx this is possible using the try_files statement. Is there something similar using uhttpd?

答:
Hi I resolved this issue.

uhttpd have a option "error_page".

So we must set that option if we decide to use react.

e.g.

```<code>config uhttpd 'main'
    list listen_http '0.0.0.0:80'
    list listen_http '[::]:80'
    option home '/www'
    option error_page '/index.html'
</code>```

Title: uhttpd rewrite all routes to /

Body:
Hi I resolved this issue.

uhttpd have a option "error_page".

So we must set that option if we decide to use react.

e.g.

config uhttpd 'main'
    list listen_http '0.0.0.0:80'
    list listen_http '[::]:80'
    option home '/www'
    option error_page '/index.html'


问:
Why does Javascript drop keyUp events when the metaKey is pressed on Mac browsers?
On Mac browsers, javascript does not receive keyup events for most keys (other modifier keys seem to be an exception) when the metakey is down. Use this jsfiddle to demonstrate (focus the result area and try something like cmd + x, the x will not receive a keyup event):
http://jsfiddle.net/mUEaV/

I've reproduced this in stable releases for Chrome, FF, Safari and Opera. The same thing does not seem to happen with the control key in Windows 7.

Is the OS hijacking the keyup event? This seems especially strange since commands that use the metakey such as save, find, cut, copy, etcetera all activate on keydown not on keyup, and can be hijacked by the javascript just fine.

答:
You can create an artificial keyup event by waiting for a certain period after the last keydown event. The only caveat is people will have different repeat rates on their os.
https://jsfiddle.net/u7t43coz/10/

const metaKeyCodes = ["MetaLeft", "MetaRight"];
const shiftKeyCodes = ["ShiftLeft", "ShiftRight"];
const ctrlKeyCodes = ["ControlLeft", "ControlRight"];
const altKeyCodes = ["AltLeft", "AltRight"];
const modifierKeyCodes = [
  ...metaKeyCodes,
  ...shiftKeyCodes,
  ...ctrlKeyCodes,
  ...altKeyCodes
];

// record which keys are down
const downKeys = new Set()
const artificialKeyUpTimes = {}

function onKeydown(e) {
    downKeys.add(e.code);

    // do other keydown stuff here
    console.log("meta", e.metaKey, e.code, "down")

    // check if metaKey is down
    if (metaKeyCodes.some(k => downKeys.has(k))) {
      downKeys.forEach(dk => {
        // we want to exclude modifier keys has they dont repeat
        if (!modifierKeyCodes.includes(dk)) {
          // fire artificial keyup on timeout
          if (!artificialKeyUpTimes[dk])
            setTimeout(
              () => fireArtificialKeyUp(dk, e),
              500
            );
          artificialKeyUpTimes[dk] = Date.now();
        }
      });
    }
  }

 function fireArtificialKeyUp(code, e) {
    // if enough time has passed fire keyup
    if (Date.now() - artificialKeyUpTimes[code] > 100) {
      delete artificialKeyUpTimes[code];
      //if key is still down, fire keyup
      if (downKeys.has(code)) {
        const eCode = isNaN(code) ? { code: code } : { keyCode: code };
        document.dispatchEvent(
          new KeyboardEvent("keyup", { ...e, ...eCode })
        );
      }
    } else {
      setTimeout(() => fireArtificialKeyUp(code, e), 100);
    }
  }

  function onKeyup(e) {
    downKeys.delete(e.code);

    // do keyup stuff here
    console.log("meta", e.metaKey, e.code, "up")
  }

  document.addEventListener("keydown", onKeydown)
  document.addEventListener("keyup", onKeyup)
```

ContentLicense: CC BY-SA 3.0


问:
How to get a list of all months from current month to a month in the past using moment.js
I'm trying to generate a list of months starting from April 2020 to a month in the past ( October 2019 ) using moment.js.

const start = moment().startOf('month')
const startMonth = moment('10-01-2019', 'MM-DD-YYYY').format('MMMM YYYY')
const month = moment().startOf('month').format('MM')
for (let i = 0; i < month; i++) {
  const m = start.subtract(1, 'month').format('MMMM YYYY')
  if (m === startMonth) {
    break;
  }
  console.log(m)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script></code>```

I get only 5 months as a result. Could anyone please help?

答:
Using isSameOrBefore()

const start = moment().startOf('month')
const end = moment('11-11-2019', 'MM-DD-YYYY')

while (end.isSameOrBefore(start, 'month')) {
  console.log(start.format('MMMM YYYY'))
  start.subtract(1, 'month')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script></code>```

Exclude current month

const start = moment().startOf('month')
const end = moment('11-11-2019', 'MM-DD-YYYY')

while (end.isBefore(start, 'month')) {
  start.subtract(1, 'month')
  console.log(start.format('MMMM YYYY'))
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script></code>```

Body:
I'm trying to generate a list of months starting from April 2020 to a month in the past ( October 2019 ) using moment.js.

const start = moment().startOf('month')
const startMonth = moment('10-01-2019', 'MM-DD-YYYY').format('MMMM YYYY')
const month = moment().startOf('month').format('MM')
for (let i = 0; i < month; i++) {
  const m = start.subtract(1, 'month').format('MMMM YYYY')
  if (m === startMonth) {
    break;
  }
  console.log(m)
}

I get only 5 months as a result. Could anyone please help?

Body:
Using isSameOrBefore()

const start = moment().startOf('month')
const end = moment('11-11-2019', 'MM-DD-YYYY')

while (end.isSameOrBefore(start, 'month')) {
  console.log(start.format('MMMM YYYY'))
  start.subtract(1, 'month')
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

Exclude current month

const start = moment().startOf('month')
const end = moment('11-11-2019', 'MM-DD-YYYY')

while (end.isBefore(start, 'month')) {
  start.subtract(1, 'month')
  console.log(start.format('MMMM YYYY'))
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>


问:
Can Haskell programs be represented as Lisp S-expressions?
This would be useful for genetic programming, which usually use a Lisp subset as representation for programs.

I've found something called Liskell (Lisp syntax, Haskell inside) on the web, but the links are broken and I can't find the paper on it...

答:
Check out Lisk, which was designed to fix the author's gripes with Liskell.

In my spare time I’m working on a project called Lisk. Using the -pgmF option for GHC, you can provide GHC a program name that is called to preprocess the file before GHC compiles it. It also works in GHCi and imports. You use it like this:

```<code>{-# OPTIONS -F -pgmF lisk #-}
(module fibs
  (import system.environment)

  (:: main (io ()))
  (= main (>>= get-args (. print fib read head)))

  (:: test (-> :string (, :int :string)))
  (= test (, 1))

  (:: fib (-> :int :int))
  (= fib 0 0)
  (= fib 1 1)
  (= fib n (+ (fib (- n 1))
              (fib (- n 2)))))
</code>```

The source is here.

Also, if you don't actually care about Haskell and just want some of its features, you might want to check out Qi (or its successor, Shen), which has s-expression syntax with many modern functional-programming features similar to Haskell.

Body:
Check out Lisk, which was designed to fix the author's gripes with Liskell.

In my spare time I’m working on a project called Lisk. Using the -pgmF option for GHC, you can provide GHC a program name that is called to preprocess the file before GHC compiles it. It also works in GHCi and imports. You use it like this:

{-# OPTIONS -F -pgmF lisk #-}
(module fibs
  (import system.environment)

  (:: main (io ()))
  (= main (>>= get-args (. print fib read head)))

  (:: test (-> :string (, :int :string)))
  (= test (, 1))

  (:: fib (-> :int :int))
  (= fib 0 0)
  (= fib 1 1)
  (= fib n (+ (fib (- n 1))
              (fib (- n 2)))))

The source is here.

Also, if you don't actually care about Haskell and just want some of its features, you might want to check out Qi (or its successor, Shen), which has s-expression syntax with many modern functional-programming features similar to Haskell.


问:
Puzzled with the workings of these variable assignments?
Tried to figure out the working logic behind the results. I couldn't.

Could someone please help explain how Javascript works the output of each of the 4 situations and the reason behind it?

I think the 1st and 2nd are similar situations.

Thanks

var num = (1, 2, 3);    // num = 3 (last number returned, No error generated)
   console.log(num)

y = (1, 2, 3);          // y = 3  (last number returned, No error generated)
   console.log(y)

z = 1, 2, 3;            // z = 1  (first number returned, No error generated)
   console.log(z)

// Uncomment the following to run: (gives an error)

//var m = 1, 2, 3;        // Error: Unexpected number ```

答:
Your first three snippets are all basically the same. They demonstrate usage of the Comma Operator.

The Comma Operator a, b first evaluates a and throws away the result, then evaluates b and returns the result. It is left-associative, so a, b, c is the same as (a, b), c.

Observe:

const foo = () => { console.log("foo"); return 23; };
const bar = () => { console.log("bar"); return 42; };
const qux = () => { console.log("qux"); return 99; };

console.log((foo(), bar()));
// foo
// bar
// 42

console.log((foo(), bar(), qux()));
// foo
// bar
// qux
// 99```
</div>
</div>
</p>

<p>Note that I could have written the three functions like this, but of course it doesn't make much sense to use the Comma Operator while trying to explain it:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const foo = () => (console.log("foo"), 23);
const bar = () => (console.log("bar"), 42);
const qux = () => (console.log("qux"), 99);

console.log((foo(), bar(), qux()));
// foo
// bar
// qux
// 99</code>```

In your first snippet, you have a Variable Declaration statement, which declares a variable, evaluates the initializer, and binds the value of the initializer to the variable. The initializer in this case is 1, 2, 3, which is equivalent to (1, 2), 3. So, it will evaluate 1, throw away the result, evaluate 2 return the result 2 as the result of evaluating the sub-expression 1, 2 but then immediately throw it away, evaluate 3 and return the result 3 as the result of the evaluation.

Therefore, it binds the value 3 to the variable num.

The second snippet is exactly the same, except it is an Assignment Expression, not a Variable Declaration, i.e. in Strict Mode, it will assign to a variable named y that was previously declared with let or var and error out with a static error otherwise. In Loose Mode, it will assign to a variable named y that was previously declared with let or var, or to a property named y of the global implicit object otherwise.

The evaluation of the right-hand-side of the assignment is exactly the same as above.

Snippet #3 uses again the Comma Operator. The Comma Operator has higher precedence than the Assignment Operator (the way ECMAScript is specified, it does not contain a simple operator precedence table, rather, the precedence is implicit in the grammar, so you'll either have to read the entire grammar or believe me), so your snippet #3 is equivalent to

((z = 1), 2), 3;
```

<p>Again, it works just the same as snippets #1 and #2: first, the expression <code>z = 1</code> is evaluated (which has the side-effect of assigning <code>1</code> to <code>z</code>) and the result is thrown away, then the expression <code>2</code> is evaluated and the result is thrown away, then the expression <code>3</code> is evaluated, and the result is returned.</p>

<p>So, the result of the entire expression is <code>3</code>, but since that result is not assigned to anything, not returned, not printed, it is simply thrown away. All that is left is the side-effect that happened while evaluating the first expression, namely assigning <code>1</code> to <code>z</code>.</p>

<p>The last expression is different, because it does not demonstrate the use of the Comma Operator. It is, again, a Variable Declaration, just like snippet #1. A Variable Declaration basically is a list of comma-separated identifiers with optional initializers. The reason you get an error here, is that <code>2</code> is not a valid identifier for a variable.</p>

<p>Observe:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var n = 1, o, p;
// Declares variables `n`, `o`, `p`, initializes `n` to `1`.

console.log(n, o, p);
// 1 undefined undefined</code>```

Now, for comparison, your snippet #4 is ecactly the same:

var m = 1, 2, 3;
// Declares variables `m`, `2`, `3`, but `2` and `3` are not legal names.```
</div>
</div>
</p>

<p>The major difference between this snippet #4 and the other three is that the comma means <em>a completely different thing</em> here. In snippets #1 to #3, it is the <em>Comma Operator</em>, whereas in snippet #4, it is part of the Variable Declaration syntax.</p>

<p>There are other places where the comma can mean something different, for example parameter lists (<code>function foo(a, b, c)</code> or <code>(a, b, c) => bla</code>) or argument lists (<code>foo(1, 2, 3)</code>). In both cases, the comma is not the Comma Operator but part of the parameter list or argument list syntax to separate the parameters or arguments.</p>

<p>Observe:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(1, 2, 3);
// 1 2 3

console.log((1, 2, 3));
// 3</code>```

Body:
Your first three snippets are all basically the same. They demonstrate usage of the Comma Operator.

The Comma Operator a, b first evaluates a and throws away the result, then evaluates b and returns the result. It is left-associative, so a, b, c is the same as (a, b), c.

Observe:

const foo = () => { console.log("foo"); return 23; };
const bar = () => { console.log("bar"); return 42; };
const qux = () => { console.log("qux"); return 99; };

console.log((foo(), bar()));
// foo
// bar
// 42

console.log((foo(), bar(), qux()));
// foo
// bar
// qux
// 99

Note that I could have written the three functions like this, but of course it doesn't make much sense to use the Comma Operator while trying to explain it:

const foo = () => (console.log("foo"), 23);
const bar = () => (console.log("bar"), 42);
const qux = () => (console.log("qux"), 99);

console.log((foo(), bar(), qux()));
// foo
// bar
// qux
// 99

In your first snippet, you have a Variable Declaration statement, which declares a variable, evaluates the initializer, and binds the value of the initializer to the variable. The initializer in this case is 1, 2, 3, which is equivalent to (1, 2), 3. So, it will evaluate 1, throw away the result, evaluate 2 return the result 2 as the result of evaluating the sub-expression 1, 2 but then immediately throw it away, evaluate 3 and return the result 3 as the result of the evaluation.

Therefore, it binds the value 3 to the variable num.

The second snippet is exactly the same, except it is an Assignment Expression, not a Variable Declaration, i.e. in Strict Mode, it will assign to a variable named y that was previously declared with let or var and error out with a static error otherwise. In Loose Mode, it will assign to a variable named y that was previously declared with let or var, or to a property named y of the global implicit object otherwise.

The evaluation of the right-hand-side of the assignment is exactly the same as above.

Snippet #3 uses again the Comma Operator. The Comma Operator has higher precedence than the Assignment Operator (the way ECMAScript is specified, it does not contain a simple operator precedence table, rather, the precedence is implicit in the grammar, so you'll either have to read the entire grammar or believe me), so your snippet #3 is equivalent to

((z = 1), 2), 3;

Again, it works just the same as snippets #1 and #2: first, the expression z = 1 is evaluated (which has the side-effect of assigning 1 to z) and the result is thrown away, then the expression 2 is evaluated and the result is thrown away, then the expression 3 is evaluated, and the result is returned.

So, the result of the entire expression is 3, but since that result is not assigned to anything, not returned, not printed, it is simply thrown away. All that is left is the side-effect that happened while evaluating the first expression, namely assigning 1 to z.

The last expression is different, because it does not demonstrate the use of the Comma Operator. It is, again, a Variable Declaration, just like snippet #1. A Variable Declaration basically is a list of comma-separated identifiers with optional initializers. The reason you get an error here, is that 2 is not a valid identifier for a variable.

Observe:

var n = 1, o, p;
// Declares variables `n`, `o`, `p`, initializes `n` to `1`.

console.log(n, o, p);
// 1 undefined undefined

Now, for comparison, your snippet #4 is ecactly the same:

var m = 1, 2, 3;
// Declares variables `m`, `2`, `3`, but `2` and `3` are not legal names.

The major difference between this snippet #4 and the other three is that the comma means a completely different thing here. In snippets #1 to #3, it is the Comma Operator, whereas in snippet #4, it is part of the Variable Declaration syntax.

There are other places where the comma can mean something different, for example parameter lists (function foo(a, b, c) or (a, b, c) => bla) or argument lists (foo(1, 2, 3)). In both cases, the comma is not the Comma Operator but part of the parameter list or argument list syntax to separate the parameters or arguments.

Observe:

console.log(1, 2, 3);
// 1 2 3

console.log((1, 2, 3));
// 3


问:
What Django model field should I use for WYSIWYG data from React?
I am creating a blog application and want to use a text editor/ WYSIWYG editor for individual posts. Since I will be using React for the frontend, the data will be received through an API (using DRF for that). So in my model, what field should I create that will accept the WYSIWYG  data?

eg. model:

```<code>class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
</code>```

I want the content field to be accepting that data

答:
Presumably if your WYSIWYG editor is actually creating html files, and at this time not handling the inserted files (images), the TextField should be enough. It is additional issue if you enable pictures or other multimedia elements to be inserted while editing, but they would have to be dealt separately.

So, for general html files, produced by your WYSIWYG editor plain TextField should be enough.

Body:
I am creating a blog application and want to use a text editor/ WYSIWYG editor for individual posts. Since I will be using React for the frontend, the data will be received through an API (using DRF for that). So in my model, what field should I create that will accept the WYSIWYG  data?

eg. model:

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

I want the content field to be accepting that data


问:
JQuery - How to maintain (index) sequence with ability to delete dynamic elements in any order
My HTML has the following div(s) having one input with Add button :

```<code><form method="post" action="">
        <div class="row">
            <div class="col-lg-6">
                <div id="inputFormRow">
                    <div class="input-group input-group-sm mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">1</span>
                        </div>
                        <input type="text" name="title[]" class="form-control m-input"
                            placeholder="Enter title" autocomplete="off">
                    </div>
                </div>

                <div id="newRowGoesHere"></div>
                <button id="appendNewRow" type="button"
                    class="btn btn-sm btn-success">
                    <i class="fas fa-plus"></i> Add
                </button>
            </div>
        </div>
    </form>
</code>```

I am populating dynamic inputs using JQuery like below:

```<code>$(document)
        .ready(
                function() {
                    var x = 1;
                    console.log("ready!");

                    $("#appendNewRow")
                            .click(
                                    function() {
                                        x++;
                                        var html = '';
                                        html += '<div id="appendedRow">';
                                        html += '<div class="input-group input-group-sm mb-3">';
                                        html += '<div class="input-group-prepend">';
                                        html += '<span class="input-group-text">'
                                                + x + '</span></div>';

                                        html += '<input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">';
                                        html += '<div class="input-group-append">';
                                        html += '<button id="removeRow" type="button" class="btn btn-danger"><i class="far fa-trash-alt"></i></button>';
                                        html += '</div></div>';

                                        $('#newRowGoesHere').append(html);
                                    });

                    $(document).on('click', '#removeRow', function() {
                        $(this).closest('#appendedRow').remove();
                        x--;
                    });
                });
</code>```

I get index number prepended with increment nicely on each input but when I remove an input element, I loose the sequence.

For example, if I add 5 inputs and delete 2nd then if I add more then the counter starts from 5, like this (screenshot):

Expected sequence : 1,2,3,4,5 and not 1,3,4,5,5

Now I am clueless on how do I maintain the correct number sequence (prepended) irrespective of what element I delete.

I must capture the sequence number in my project. Where do I go from here? Any pointers will be greatly appreciated.

答:
You can use each to loop through all the div after any element is deleted and then reset your  to display correct count.Also you cannot have multiple id with same name so for this i have added a class="something" to every div before appending so that we can use that in each loop.

Demo Code :

$(document)
  .ready(
    function() {
      var x = 0;
      console.log("ready!");

      $("#appendNewRow")
        .click(
          function() {
            x++;
            var html = '';
            html += '
';
            html += '
';
            html += '
';
            html += '' +
              x + '
';

            html += '<input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">';
            html += '
';
            html += '<button id="removeRow" type="button" class="btn btn-danger removeRow">Del</button>';
            html += '

';

            $('#newRowGoesHere').append(html);
          });
      //remove
      $(document).on('click', '.removeRow', function() {
        $(this).closest('.abc').remove(); //find closest class
        x--;
        resetValues(); //call function
      });

      function resetValues() {
        counter = 1; //initialze to 1
        //looping through class div -> class abc
        $(".abc").each(function() {
          //getting span where count is display replace with new
          $(this).find('.input-group-text').text(counter);
          //replce id with new id
          $(this).attr('id', "appendedRow" + counter);
          counter++;
        })
      }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<form method="post" action="">
  <div class="row">
    <div class="col-lg-6">
      <div id="inputFormRow">
        <div class="input-group input-group-sm mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text">0</span>
          </div>
          <input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">
        </div>
      </div>

      <div id="newRowGoesHere"></div>
      <button id="appendNewRow" type="button" class="btn btn-sm btn-success">
                    <i class="fas fa-plus"></i> Add
                </button>
    </div>
  </div>
</form></code>```

Body:
My HTML has the following div(s) having one input with Add button :

<form method="post" action="">

                            1

                        <input type="text" name="title[]" class="form-control m-input"
                            placeholder="Enter title" autocomplete="off">

                <button id="appendNewRow" type="button"
                    class="btn btn-sm btn-success">
                     Add
                </button>

    </form>

I am populating dynamic inputs using JQuery like below:

$(document)
        .ready(
                function() {
                    var x = 1;
                    console.log("ready!");

                    $("#appendNewRow")
                            .click(
                                    function() {
                                        x++;
                                        var html = '';
                                        html += '
';
                                        html += '
';
                                        html += '
';
                                        html += ''
                                                + x + '
';

                                        html += '<input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">';
                                        html += '
';
                                        html += '<button id="removeRow" type="button" class="btn btn-danger"></button>';
                                        html += '

';

                                        $('#newRowGoesHere').append(html);
                                    });

                    $(document).on('click', '#removeRow', function() {
                        $(this).closest('#appendedRow').remove();
                        x--;
                    });
                });

I get index number prepended with increment nicely on each input but when I remove an input element, I loose the sequence.

For example, if I add 5 inputs and delete 2nd then if I add more then the counter starts from 5, like this (screenshot):

Expected sequence : 1,2,3,4,5 and not 1,3,4,5,5

Now I am clueless on how do I maintain the correct number sequence (prepended) irrespective of what element I delete.

I must capture the sequence number in my project. Where do I go from here? Any pointers will be greatly appreciated.

Body:
You can use each to loop through all the div after any element is deleted and then reset your <span> to display correct count.Also you cannot have multiple id with same name so for this i have added a class="something" to every div before appending so that we can use that in each loop.

Demo Code :

$(document)
  .ready(
    function() {
      var x = 0;
      console.log("ready!");

      $("#appendNewRow")
        .click(
          function() {
            x++;
            var html = '';
            html += '<div class="abc" id="appendedRow' + x + '">';
            html += '<div class="input-group input-group-sm mb-3">';
            html += '<div class="input-group-prepend">';
            html += '<span class="input-group-text">' +
              x + '</span></div>';

            html += '<input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">';
            html += '<div class="input-group-append">';
            html += '<button id="removeRow" type="button" class="btn btn-danger removeRow"><i class="far fa-trash-alt">Del</i></button>';
            html += '</div></div>';

            $('#newRowGoesHere').append(html);
          });
      //remove
      $(document).on('click', '.removeRow', function() {
        $(this).closest('.abc').remove(); //find closest class
        x--;
        resetValues(); //call function
      });

      function resetValues() {
        counter = 1; //initialze to 1
        //looping through class div -> class abc
        $(".abc").each(function() {
          //getting span where count is display replace with new
          $(this).find('.input-group-text').text(counter);
          //replce id with new id
          $(this).attr('id', "appendedRow" + counter);
          counter++;
        })
      }
    });

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<form method="post" action="">
  <div class="row">
    <div class="col-lg-6">
      <div id="inputFormRow">
        <div class="input-group input-group-sm mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text">0</span>
          </div>
          <input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">
        </div>
      </div>

      <div id="newRowGoesHere"></div>
      <button id="appendNewRow" type="button" class="btn btn-sm btn-success">
                    <i class="fas fa-plus"></i> Add
                </button>
    </div>
  </div>
</form>


问:
Customized location choices in Django/JS/Paypal Buttons Integration
Below I have my Payal Checkout setup. User can input any address they want but I want to limit the country, State/Province, and City choices they have with a dropdown menu.

Does anyone know how to do that? or any alternate options for this?

答:
You cannot limit a user's billing address, it is outside your control They are free to enter any billing address.

If you prompt for a shipping address using your own form before displaying the buttons, you can pass that shipping address to PayPal and use the application_context object's SET_PROVIDED_ADDRESS object to force the use of the shipping address you have collected and validated.

For example:

```<code>"application_context": {
  "shipping_preference": "SET_PROVIDED_ADDRESS"
},
"purchase_units": [{
  "shipping": {
    "address": {
      "address_line_1": "123 Sunny Lane",
      "admin_area_2": "Phoenix",
      "admin_area_1": "AZ",
      "postal_code": "85001",
      "country_code": "US",
    },
    "name": {
      "full_name":"John Doe",
    }
  },
  "amount": {
    "currency_code": "USD",
    "value": "123.45"
  },
}]
</code>```

PayPal doesn't recommend this integation, for two reasons:

1) If you collect an invalid address, the payment attempt will be rejected with an error (since you are forcing that address to be used), and checkout cannot proceed.

2) You are adding friction to the checkout process by forcing users to manually enter an address. Much of the benefit of the "PayPal" payment method, apart from security, is the ability to check out without having to type any payment or shipping information -- it's all all pre-saved in the buyer's account, allowing them to make a snap payment decision, thus increasing your site's sales "conversion" rate.

But well, there you go if you have this business need of controlling the addresses before the customer enters a checkout flow. This same v2/orders syntax applies to client-side JavaScript buttons, or a server-side API-based integration (interacting with the appropriate front-end for buttons)

Body:
You cannot limit a user's billing address, it is outside your control They are free to enter any billing address.

If you prompt for a shipping address using your own form before displaying the buttons, you can pass that shipping address to PayPal and use the application_context object's SET_PROVIDED_ADDRESS object to force the use of the shipping address you have collected and validated.

For example:

"application_context": {
  "shipping_preference": "SET_PROVIDED_ADDRESS"
},
"purchase_units": [{
  "shipping": {
    "address": {
      "address_line_1": "123 Sunny Lane",
      "admin_area_2": "Phoenix",
      "admin_area_1": "AZ",
      "postal_code": "85001",
      "country_code": "US",
    },
    "name": {
      "full_name":"John Doe",
    }
  },
  "amount": {
    "currency_code": "USD",
    "value": "123.45"
  },
}]

PayPal doesn't recommend this integation, for two reasons:

1) If you collect an invalid address, the payment attempt will be rejected with an error (since you are forcing that address to be used), and checkout cannot proceed.

2) You are adding friction to the checkout process by forcing users to manually enter an address. Much of the benefit of the "PayPal" payment method, apart from security, is the ability to check out without having to type any payment or shipping information -- it's all all pre-saved in the buyer's account, allowing them to make a snap payment decision, thus increasing your site's sales "conversion" rate.

But well, there you go if you have this business need of controlling the addresses before the customer enters a checkout flow. This same v2/orders syntax applies to client-side JavaScript buttons, or a server-side API-based integration (interacting with the appropriate front-end for buttons)


问:
Nginx + GraphQL Connection Refused

My Client (next.js) app running at port 3000

My Server (graphql) app running at port 4000

My website is https://example.com, nginx will pass proxy port 3000.

If the user access the site, the page is loaded successfully.

But behind the scene, In my webpage some api requests are sended to graphql server. (http://localhost:4000)

This api requests are failed.

I don't know why, but when I access http://example.com:4000/graphql the graphql playground (graphiql?) loaded successfully and I can send some query and result showed well. But request from webpage is failed.

nginx/sites-enabled/example.com

```<code>server {
        listen 80;
        listen [::]:80;
        server_name www.example.com example.com;
        return 301 https://example.com$request_uri;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
</code>```

client app's graphql part

```<code>export default function createApolloClient(initialState, ctx) {
  return new ApolloClient({
    ssrMode: Boolean(ctx),
    link: authLink.concat(new HttpLink({
      uri: 'http://localhost:4000/graphql', // Server URL (must be absolute)
      credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
      fetch,
    })),
    cache: new InMemoryCache({ fragmentMatcher }).restore(initialState),
    credentials: 'include',
  })
}
</code>```

** What I tried...**

I added below snippets to nginx conf (above listen [::]443 part) and restart the nginx service, but nothing changed.

```<code>   location /graphql {
        proxy_pass http://localhost:4000/graphql;
   }
</code>```

I think I miss something in nginx conf. How do I fix it?

答:
I resolved like below.

createApolloClient

```<code>... createApolloClient(initialState, ctx) {
  return new ApolloClient({
    ...
    link: createHttpLink({ uri: '/graphql' })
</code>```

nginx

```<code>  location /graphql {
        proxy_pass http://localhost:4000/graphql;
   }
</code>```

Title: Nginx + GraphQL Connection Refused

Body:
My Client (next.js) app running at port 3000

My Server (graphql) app running at port 4000

My website is https://example.com, nginx will pass proxy port 3000.

If the user access the site, the page is loaded successfully.

But behind the scene, In my webpage some api requests are sended to graphql server. (http://localhost:4000)

This api requests are failed.

I don't know why, but when I access http://example.com:4000/graphql the graphql playground (graphiql?) loaded successfully and I can send some query and result showed well. But request from webpage is failed.

nginx/sites-enabled/example.com

server {
        listen 80;
        listen [::]:80;
        server_name www.example.com example.com;
        return 301 https://example.com$request_uri;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

client app's graphql part

export default function createApolloClient(initialState, ctx) {
  return new ApolloClient({
    ssrMode: Boolean(ctx),
    link: authLink.concat(new HttpLink({
      uri: 'http://localhost:4000/graphql', // Server URL (must be absolute)
      credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
      fetch,
    })),
    cache: new InMemoryCache({ fragmentMatcher }).restore(initialState),
    credentials: 'include',
  })
}

** What I tried...**

I added below snippets to nginx conf (above listen [::]443 part) and restart the nginx service, but nothing changed.

   location /graphql {
        proxy_pass http://localhost:4000/graphql;
   }

I think I miss something in nginx conf. How do I fix it?

Body:
I resolved like below.

createApolloClient

... createApolloClient(initialState, ctx) {
  return new ApolloClient({
    ...
    link: createHttpLink({ uri: '/graphql' })

nginx

  location /graphql {
        proxy_pass http://localhost:4000/graphql;
   }


问:
How do I share custom typeDefs and enum in Apollo server?
Suppose I have two typeDefs, one is user and the other one is a product. In user typeDef, I have a mutation named logout, which when called returns a message. The other typeDef( product ) has a function called add product, which when called again returns a message. I added message typeDef individually in both the typeDefs, but that throws an error There can be only one type named \"Message\".\n\nField \"Message.message\" can only be defined once. I am adding screenshots as well for clarity. So How do I share the message typeDefs among both the typeDefs? I hope I have explained my problem.

答: I created one folder and inside that folder, I created message.js typeDefs. I included this file inside my root typeDefs. This approach solved my issues of sharing typeDef across typeDefs.</p>


问:
Insert server-side rendered HTML via Javascript
I have a table which changes frequently. I plan to fetch the new pre-rendered table from the server and switch it with the old table via Javascript.

Is this a terrible idea?

How would I go about it?

答:
This is not a terrible idea, but you can do better, the issue here is that you are sending an html output and not the actual data.

A better alternative would be to build an endpoint that gives you the actual data without the html, and then when you retrieve that data you update the views as needed, the advantages of this approach are:

You are only sending the data, and no unnecessary html, and so bundle size will be smaller, this will make the servers cost less, and front end will be able to interact with the data faster

sending an html means that you are tying this data to one type of a client, in this case this will be a browser, but what if later u decided to add mobiles, and other types of clients. When sending only data, later you can consume this endpoint from any client you want

sending only data will make it easier to make the client interact smarter with the data, and so optimising the user experience, for example if u notice that more data was added, and these data are at the end of the table, and u have table pagination, u can add these to the end of the table without disturbing the user. however if this was html you would need to replace the whole content, and the user will be disturbed.

finally, sending only data will make it easier to handle caching at both front-end and back-end, since you are doing caching on top of one layer (data) instead of two (data inside html)

Not everything i said here will apply to your use case, however i thought these are things u should consider. Other than that your approach will still work.


问:
Why is skew value calculated with excel sheet different from value calculated with pyspark/scipy
Calculating skew using scipy.stats

```<code>from scipy.stats import skew

val = [120.7, 120.5, 120.4, 120.2, 120.1]
skew(val)

0.13802317223314806
</code>```

Calculating skew using excel, arranged the values in each row in one column and used skew function

```<code>=SKEW(A1:A5)

0.2057527971
</code>```

Why is there a difference in skew value?
The same happens with pandas and pyspark. While calculating skew with pyspark it gives same result as scipy and when calculated with pandas it gives same result as excel

答:
This is likely the difference between a biased and unbiased calculation of the skewness. The scipy implementation of skew is biased by default. When you give an extra keyword bias=False you get the unbiased result:

```<code>from scipy.stats import skew

val = [120.7, 120.5, 120.4, 120.2, 120.1]
skew(val, bias=False)
>>0.20575279705565366
</code>```

The Excel implementation and pandas implementation are both unbiased by default. I haven't checked the pyspark version, but my guess is that it is biased by default.

Body:
Calculating skew using scipy.stats

from scipy.stats import skew

val = [120.7, 120.5, 120.4, 120.2, 120.1]
skew(val)

0.13802317223314806

Calculating skew using excel, arranged the values in each row in one column and used skew function

=SKEW(A1:A5)

0.2057527971

Why is there a difference in skew value?
The same happens with pandas and pyspark. While calculating skew with pyspark it gives same result as scipy and when calculated with pandas it gives same result as excel

Body:
This is likely the difference between a biased and unbiased calculation of the skewness. The scipy implementation of skew is biased by default. When you give an extra keyword bias=False you get the unbiased result:

from scipy.stats import skew

val = [120.7, 120.5, 120.4, 120.2, 120.1]
skew(val, bias=False)
>>0.20575279705565366

The Excel implementation and pandas implementation are both unbiased by default. I haven't checked the pyspark version, but my guess is that it is biased by default.


问:
How can I save a Turtle canvas as an image (.png or .jpg)
I've been working with the turtle module and want to use it as a starting point to work on a simple image recognition program that could recognize numbers/letters. I need to be able to save the turtle as an image I could manipulate - rescaling, rotating, etc. to try to regulate the images. I've been researching for hours and cannot seem to find anything that works. I have discovered how to save the Turtle output as a Tkinter canvas:

```<code>import turtle
t = turtle.Turtle()
# Draw something
canvas = t.getscreen().getcanvas()  # Saves a Tkinter canvas object
</code>```

This seems to work great. The next step is to save that as a .png or .jpg. However, the only thing I can find is how to save it as a postscript file:

```<code>canvas.postscript(file="turtle_img.ps")  # Saves as a .ps file
</code>```

From there, I have attempted to convert the .ps file into a .png or .jpeg file using PIL. Here is my code for that and the error that I get:

```<code>from PIL import Image
turtle_img = Image.open("turtle_img.ps")
turtle_img.save("turtle_img", "png")
# Also tried:   turtle_img.save("turtle_img, "jpeg")
</code>```

Running the line "turtle_img.save("turtle_img", "png") produces:

```<code>OSError: Unable to locate Ghostscript on paths
</code>```

I would love one of the following:
1. a way to convert a .ps into a .jpeg, .png, or even a bitmap
2. An alternate way of saving a Tkinter canvas that is easier to work with

EDIT: I wanted to clarify that I would be working with a large number of these and would like to automate the process in a script rather than use the command line for each image.

答:
You can directly save the canvas as a .png if you include the turtle in a tkinter canvas. This is very easy to do.

Grabbing the .png image can then be automated, or be done at the click of a button, or the pressing of a key - without manual intervention.

Here is an example that embeds a turtle in a tk.Canvas, draws a Sierpinski Gasket, and automatically saves the image generated on disk.

```<code>import tkinter as tk
from PIL import ImageGrab
import turtle

def dump_gui():
    """
    takes a png screenshot of a tkinter window, and saves it on in cwd
    """
    print('...dumping gui window to png')

    x0 = root.winfo_rootx()
    y0 = root.winfo_rooty()
    x1 = x0 + root.winfo_width()
    y1 = y0 + root.winfo_height()
    ImageGrab.grab().crop((x0, y0, x1, y1)).save("gui_image_grabbed.png")

def draw_sierpinski(length, depth):
    if depth == 0:
        for i in range(0, 3):
            t.fd(length)
            t.left(120)
    else:
        draw_sierpinski(length / 2, depth - 1)
        t.fd(length / 2)
        draw_sierpinski(length / 2, depth - 1)
        t.bk(length / 2)
        t.left(60)
        t.fd(length / 2)
        t.right(60)
        draw_sierpinski(length / 2, depth - 1)
        t.left(60)
        t.bk(length / 2)
        t.right(60)

root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()

t = turtle.RawTurtle(canvas)

t.penup()
t.goto(-200, -175)
t.pendown()
draw_sierpinski(400, 6)
t.hideturtle()

dump_gui()

root.mainloop()
</code>```

Body:
I've been working with the turtle module and want to use it as a starting point to work on a simple image recognition program that could recognize numbers/letters. I need to be able to save the turtle as an image I could manipulate - rescaling, rotating, etc. to try to regulate the images. I've been researching for hours and cannot seem to find anything that works. I have discovered how to save the Turtle output as a Tkinter canvas:

import turtle
t = turtle.Turtle()
# Draw something
canvas = t.getscreen().getcanvas()  # Saves a Tkinter canvas object

This seems to work great. The next step is to save that as a .png or .jpg. However, the only thing I can find is how to save it as a postscript file:

canvas.postscript(file="turtle_img.ps")  # Saves as a .ps file

From there, I have attempted to convert the .ps file into a .png or .jpeg file using PIL. Here is my code for that and the error that I get:

from PIL import Image
turtle_img = Image.open("turtle_img.ps")
turtle_img.save("turtle_img", "png")
# Also tried:   turtle_img.save("turtle_img, "jpeg")

Running the line "turtle_img.save("turtle_img", "png") produces:

OSError: Unable to locate Ghostscript on paths

I would love one of the following:
1. a way to convert a .ps into a .jpeg, .png, or even a bitmap
2. An alternate way of saving a Tkinter canvas that is easier to work with

EDIT: I wanted to clarify that I would be working with a large number of these and would like to automate the process in a script rather than use the command line for each image.

Body:
You can directly save the canvas as a .png if you include the turtle in a tkinter canvas. This is very easy to do.

Grabbing the .png image can then be automated, or be done at the click of a button, or the pressing of a key - without manual intervention.

Here is an example that embeds a turtle in a tk.Canvas, draws a Sierpinski Gasket, and automatically saves the image generated on disk.

import tkinter as tk
from PIL import ImageGrab
import turtle

def dump_gui():
    """
    takes a png screenshot of a tkinter window, and saves it on in cwd
    """
    print('...dumping gui window to png')

    x0 = root.winfo_rootx()
    y0 = root.winfo_rooty()
    x1 = x0 + root.winfo_width()
    y1 = y0 + root.winfo_height()
    ImageGrab.grab().crop((x0, y0, x1, y1)).save("gui_image_grabbed.png")

def draw_sierpinski(length, depth):
    if depth == 0:
        for i in range(0, 3):
            t.fd(length)
            t.left(120)
    else:
        draw_sierpinski(length / 2, depth - 1)
        t.fd(length / 2)
        draw_sierpinski(length / 2, depth - 1)
        t.bk(length / 2)
        t.left(60)
        t.fd(length / 2)
        t.right(60)
        draw_sierpinski(length / 2, depth - 1)
        t.left(60)
        t.bk(length / 2)
        t.right(60)

root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()

t = turtle.RawTurtle(canvas)

t.penup()
t.goto(-200, -175)
t.pendown()
draw_sierpinski(400, 6)
t.hideturtle()

dump_gui()

root.mainloop()


问:
Looping in a SQL QUERY from a huge database to do incremental data pull
I have a generic question about structuring a query in SQL.

I have a database for which I need to pull data for the last n days which turns out to be huge to fit in memory.

I have a query like

```<code> SELECT * FROM DB_A
  WHERE data >=n days
</code>```

The best way to fit the query into memory is to use a loop, such that I can pull the data say m days at time ( where m << n)

So how can I do that?

I am not getting any idea.

答:
If you are using the Oracle 12c or higher, you can directly use pagination by using OFFSET and FETCH as follows:

```<code>SELECT * FROM DB_A
  WHERE data >=n days
ORDER BY n
OFFSET m*x rows
fetch next m rows only;
</code>```

here, x is a number of iterations, starting with 0.

Let's say you want 5 rows at a time.

for the first iteration:

```<code>OFFSET 0 rows
fetch next 5 rows only;
</code>```

for the second iteration:

```<code>OFFSET 5 rows
fetch next 5 rows only;
</code>```

Continue till the end .....

Body:
I have a generic question about structuring a query in SQL.

I have a database for which I need to pull data for the last n days which turns out to be huge to fit in memory.

I have a query like

 SELECT * FROM DB_A
  WHERE data >=n days

The best way to fit the query into memory is to use a loop, such that I can pull the data say m days at time ( where m << n)

So how can I do that?

I am not getting any idea.

Body:
If you are using the Oracle 12c or higher, you can directly use pagination by using OFFSET and FETCH as follows:

SELECT * FROM DB_A
  WHERE data >=n days
ORDER BY n
OFFSET m*x rows
fetch next m rows only;

here, x is a number of iterations, starting with 0.

Let's say you want 5 rows at a time.

for the first iteration:

OFFSET 0 rows
fetch next 5 rows only;

for the second iteration:

OFFSET 5 rows
fetch next 5 rows only;

Continue till the end .....


问:
Accept/Reject Button in html
I am trying to accept or reject invitations through form elements in html.Here is the code :

```<code>             <form method="POST">
             <input type="submit" name="accept" id="accept" value="Accept">
             <input type="submit" name="decline" id="decline" value="Decline">
             </form>
</code>```

So whenever I try to accept or reject invitations ,the Accept or the Reject button should change to Accepted or Rejected.
I can make that happen using javascript onclick properties.But I am confused on how the response object should handle this in the post route in express js???What should my post route do?
When I click either accept or reject, the page should not reload and only the clicked button should change..

```<code>    response.send()
    response.redirect()
</code>```

My question is what method should my response object contain so that it achieves above(you can think of the 'add to cart' in shopping sites as example). How do I solve it?

答:
If you had only one submit, you could do like this:

```<code> <form name="myform" method="POST" onsubmit="onSubmit()";>
             <input type="submit" name="accept" id="accept" value="Accept">
  </form>

function onSubmit(){
 document.myform.accept.value = 'Accepted';

}
</code>```

However, in your case, there are two submits so you should use onClick of them

```<code>  <form name="myform" method="POST" onsubmit="onSubmit()";>
                 <input type="submit" name="accept" id="accept" value="Accept" onclick="acceptFunction()">
<input type="submit" name="reject" id="reject" value="Accept" onclick="rejectFunction()">
    </form>

function acceptFunction(){
 document.myform.accept.value  = "Accepted";
}
function rejectFunction(){
   document.myform.accept.value  = "Rejected";
}
</code>```

Title: Accept/Reject Button in html

Body:
I am trying to accept or reject invitations through form elements in html.Here is the code :

             <form method="POST">
             <input type="submit" name="accept" id="accept" value="Accept">
             <input type="submit" name="decline" id="decline" value="Decline">
             </form>

So whenever I try to accept or reject invitations ,the Accept or the Reject button should change to Accepted or Rejected.
I can make that happen using javascript onclick properties.But I am confused on how the response object should handle this in the post route in express js???What should my post route do?
When I click either accept or reject, the page should not reload and only the clicked button should change..

    response.send()
    response.redirect()

My question is what method should my response object contain so that it achieves above(you can think of the 'add to cart' in shopping sites as example). How do I solve it?

Body:
If you had only one submit, you could do like this:

 <form name="myform" method="POST" onsubmit="onSubmit()";>
             <input type="submit" name="accept" id="accept" value="Accept">
  </form>

function onSubmit(){
 document.myform.accept.value = 'Accepted';

}

However, in your case, there are two submits so you should use onClick of them

  <form name="myform" method="POST" onsubmit="onSubmit()";>
                 <input type="submit" name="accept" id="accept" value="Accept" onclick="acceptFunction()">
<input type="submit" name="reject" id="reject" value="Accept" onclick="rejectFunction()">
    </form>

function acceptFunction(){
 document.myform.accept.value  = "Accepted";
}
function rejectFunction(){
   document.myform.accept.value  = "Rejected";
}